@fabrika/check 0.8.2 → 0.9.0-cloudflare.1

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 (61) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +23 -6
  3. package/src/dialect.ts +29 -0
  4. package/src/endpoint-fixtures.ts +29 -9
  5. package/src/finding.ts +7 -3
  6. package/src/index.ts +2 -1
  7. package/src/layout.ts +2 -0
  8. package/src/reader/surface.ts +15 -0
  9. package/src/rules/cloudflare.ts +58 -0
  10. package/src/rules/framework.ts +2 -2
  11. package/src/rules/isolation.ts +5 -1
  12. package/src/rules/migrations.ts +31 -0
  13. package/src/rules/modules.ts +1 -1
  14. package/src/scaffold.ts +133 -33
  15. package/types/src/ast.d.ts +65 -0
  16. package/types/src/bun-plugin.d.ts +12 -0
  17. package/types/src/check.d.ts +19 -0
  18. package/types/src/cli.d.ts +2 -0
  19. package/types/src/contract.d.ts +58 -0
  20. package/types/src/dialect.d.ts +8 -0
  21. package/types/src/endpoint-fixtures.d.ts +39 -0
  22. package/types/src/finding.d.ts +39 -0
  23. package/types/src/graph.d.ts +68 -0
  24. package/types/src/index.d.ts +7 -0
  25. package/types/src/inputs.d.ts +9 -0
  26. package/types/src/jsonc.d.ts +2 -0
  27. package/types/src/layout.d.ts +65 -0
  28. package/types/src/limits.d.ts +15 -0
  29. package/types/src/lockfile.d.ts +19 -0
  30. package/types/src/packed.d.ts +15 -0
  31. package/types/src/reader/problems.d.ts +7 -0
  32. package/types/src/reader/schema.d.ts +18 -0
  33. package/types/src/reader/surface.d.ts +5 -0
  34. package/types/src/reader/tables.d.ts +6 -0
  35. package/types/src/reader/value.d.ts +113 -0
  36. package/types/src/references.d.ts +15 -0
  37. package/types/src/resolution.d.ts +20 -0
  38. package/types/src/rules/cloudflare.d.ts +9 -0
  39. package/types/src/rules/contract.d.ts +8 -0
  40. package/types/src/rules/crontab.d.ts +15 -0
  41. package/types/src/rules/framework.d.ts +19 -0
  42. package/types/src/rules/identity.d.ts +5 -0
  43. package/types/src/rules/isolation.d.ts +18 -0
  44. package/types/src/rules/json.d.ts +3 -0
  45. package/types/src/rules/literal.d.ts +63 -0
  46. package/types/src/rules/migrations.d.ts +34 -0
  47. package/types/src/rules/modules.d.ts +12 -0
  48. package/types/src/rules/packages.d.ts +7 -0
  49. package/types/src/rules/runtime.d.ts +32 -0
  50. package/types/src/rules/structure.d.ts +36 -0
  51. package/types/src/rules/tests.d.ts +22 -0
  52. package/types/src/rules/types.d.ts +4 -0
  53. package/types/src/scaffold-sample.d.ts +8 -0
  54. package/types/src/scaffold.d.ts +34 -0
  55. package/types/src/scope.d.ts +6 -0
  56. package/types/src/slice.d.ts +30 -0
  57. package/types/src/source-maps-cli.d.ts +4 -0
  58. package/types/src/source-maps.d.ts +32 -0
  59. package/types/src/toml.d.ts +30 -0
  60. package/types/src/trust.d.ts +15 -0
  61. package/types/src/version.d.ts +2 -0
package/src/scaffold.ts CHANGED
@@ -13,8 +13,9 @@ import {
13
13
  tableActions,
14
14
  type TablePolicyArtifact,
15
15
  } from '@fabrika/auth-core'
16
- import { tablePolicies } from '@fabrika/db/tables'
16
+ import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
17
17
  import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
18
+ import { type ApplicationDialect, applicationDialect } from './dialect'
18
19
  import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
19
20
  import type { Finding } from './finding'
20
21
  import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
@@ -33,13 +34,40 @@ export interface GeneratedTest {
33
34
 
34
35
  type Policies = Readonly<Record<string, TablePolicyArtifact>>
35
36
 
37
+ /** The test database kit of each dialect, and the name a generated test gives the database it opens. */
38
+ const TEST_KITS: Readonly<Record<ApplicationDialect, { readonly module: string; readonly name: string }>> = {
39
+ postgres: { module: '@fabrika/db/testing', name: 'postgres' },
40
+ sqlite: { module: '@fabrika/db/testing-sqlite', name: 'database' },
41
+ }
42
+
43
+ /** The lines of a generated test that open its database: the kit's import and the call, against `migrations`. */
44
+ const testDatabaseLines = (
45
+ dialect: ApplicationDialect,
46
+ migrations: string,
47
+ ): { readonly kit: string; readonly open: string; readonly name: string } => {
48
+ const { module, name } = TEST_KITS[dialect]
49
+ return {
50
+ kit: `import { testDatabase } from '${module}'`,
51
+ open: `const ${name} = await testDatabase({ migrations: new URL('${migrations}', import.meta.url), label })`,
52
+ name,
53
+ }
54
+ }
55
+
36
56
  interface Case {
37
57
  readonly name: string
38
58
  readonly lines: readonly string[]
59
+ /** A leak or an own case: it runs the handler for the caller's own scope, which application rows can serve. */
60
+ readonly ownScope?: true
39
61
  }
40
62
 
41
63
  const testCase = (name: string, ...lines: readonly string[]): Case => ({ name, lines })
42
64
 
65
+ /** A case that runs the handler for the caller's own scope: a leak or an own case. */
66
+ const ownScopeCase = (name: string, line: string): Case => ({ name, lines: [line], ownScope: true })
67
+
68
+ /** Orders entries by their key, as every fixture is reported and seeded. */
69
+ const byKey = ([left]: readonly [string, unknown], [right]: readonly [string, unknown]): number => (left < right ? -1 : left > right ? 1 : 0)
70
+
43
71
  const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
44
72
 
45
73
  const renderCase = (item: Case): string =>
@@ -209,6 +237,7 @@ const policyTestBody = (
209
237
  policies: Policies,
210
238
  table: string,
211
239
  scopedSites: boolean,
240
+ dialect: ApplicationDialect,
212
241
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
213
242
  const policy = policies[table]
214
243
  if (policy === undefined) return undefined
@@ -225,6 +254,7 @@ const policyTestBody = (
225
254
  ? `policy of ${table}: only a global holder of its actions reaches a row`
226
255
  : `policy of ${table}: a caller of one ${dimension} reaches no row of another`
227
256
  const kitOf = app ? 'appPolicyIsolationKit' : 'policyIsolationKit'
257
+ const database = testDatabaseLines(dialect, '../../../db/migrations/')
228
258
  const blocks = [describeBlock(title, isolation)]
229
259
  if (hidden.length > 0) blocks.push(describeBlock(`policy of ${table}: a column with its own read action is never returned`, hidden))
230
260
  const body = [
@@ -233,16 +263,16 @@ const policyTestBody = (
233
263
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a policy change.',
234
264
  '',
235
265
  `import { ${['afterAll', 'describe', 'expect', kitOf, 'test'].sort().join(', ')} } from '@fabrika/app/testing/isolation'`,
236
- "import { testDatabase } from '@fabrika/db/testing'",
266
+ database.kit,
237
267
  "import { contract } from '../../../fabrika.contract'",
238
268
  "import { tables } from '../tables'",
239
269
  '',
240
270
  `const label = ${quote(`${table}${POLICY_TEST_SUFFIX}`)}`,
241
- "const postgres = await testDatabase({ migrations: new URL('../../../db/migrations/', import.meta.url), label })",
271
+ database.open,
242
272
  '',
243
- 'if (postgres !== null) {',
244
- '\tafterAll(() => postgres.close())',
245
- `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, postgres)`,
273
+ `if (${database.name} !== null) {`,
274
+ `\tafterAll(() => ${database.name}.close())`,
275
+ `\tconst kit = ${kitOf}(contract, tables, ${quote(table)}, ${database.name})`,
246
276
  '',
247
277
  blocks.join('\n\n'),
248
278
  '}',
@@ -313,6 +343,17 @@ const ownerRead = (policies: Policies, dimension: string): string | undefined =>
313
343
  Object.values(policies).find((policy) => policy.scope.mode === 'dimension' && policy.scope.dimension === dimension)?.actions.read ?? null,
314
344
  )[0]
315
345
 
346
+ /**
347
+ * Whether an endpoint gets the `own` case: `on` an object a table owns, as a link procedure or with an action other
348
+ * than the owner's read action (a caller holding only that one reaches every object, which proves nothing).
349
+ */
350
+ const hasOwnCase = (row: EndpointRow, policies: Policies): boolean => {
351
+ if (row.requirement?.kind !== 'action') return false
352
+ const { access, action } = row.requirement
353
+ const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
354
+ return read !== undefined && (isLinkProcedure(row) || read !== action)
355
+ }
356
+
316
357
  /**
317
358
  * What the `own` case's caller holds: the endpoint's action, plus what IAM requires of a link's issuer (the actions the
318
359
  * link grants) and of a member manager (an assigning role and the assigned role's actions).
@@ -341,21 +382,27 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
341
382
  const seed = fixtures.seeds[row.id]
342
383
  const args = `${quote(row.id)}, ${renderSample(input)}`
343
384
  const seeded = seed === undefined ? args : `${args}, ${renderSample(seed)}`
385
+ // The application rows reach every case that runs the handler on the caller's own object: its leak cases and its own
386
+ // case. Only an endpoint with them gets the fourth argument, so every other generated file stays as it was.
387
+ const appRows = fixtures.appRows[row.id]
388
+ const rowsTail = appRows === undefined ? '' : `, ${renderSample(appRows)}`
389
+ const unseededArgs = appRows === undefined ? args : `${args}, {}${rowsTail}`
390
+ const seededArgs = seed === undefined ? unseededArgs : `${seeded}${rowsTail}`
344
391
  const declared = artifact.declared?.[row.id]
345
392
  const unscoped = declared !== undefined && Object.keys(declared.unscoped).length > 0
346
- const read = access.form === 'on' ? ownerRead(policies, access.dimension) : undefined
347
- const own = read !== undefined && (linked || read !== action)
393
+ const own = hasOwnCase(row, policies)
348
394
  const cases: Case[] = []
349
- // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks.
395
+ // The unseeded probe always runs: a seed meets a precondition, and must not also set aside the state that leaks. The
396
+ // application rows reach it too: they are rows of the whole application, which the handler needs to answer at all.
350
397
  const leaked = (): Case[] => [
351
- testCase(
398
+ ownScopeCase(
352
399
  `${row.id}: the answer to one scope holds nothing of the scope answered before it`,
353
- `expect(await kit.leaked(${args})).toEqual({ answered: true, leaked: [] })`,
400
+ `expect(await kit.leaked(${unseededArgs})).toEqual({ answered: true, leaked: [] })`,
354
401
  ),
355
402
  ...(seed === undefined ? [] : [
356
- testCase(
403
+ ownScopeCase(
357
404
  `${row.id}: with its seed, the answer to one scope holds nothing of the scope answered before it`,
358
- `expect(await kit.leaked(${seeded})).toEqual({ answered: true, leaked: [] })`,
405
+ `expect(await kit.leaked(${seededArgs})).toEqual({ answered: true, leaked: [] })`,
359
406
  ),
360
407
  ]),
361
408
  ]
@@ -380,7 +427,10 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
380
427
  if (linked) {
381
428
  if (own) {
382
429
  cases.push(
383
- testCase(`${row.id}: the holder of a link to a ${access.dimension} reaches it`, `expect(await kit.own(${seeded})).toEqual({ status: 200 })`),
430
+ ownScopeCase(
431
+ `${row.id}: the holder of a link to a ${access.dimension} reaches it`,
432
+ `expect(await kit.own(${seededArgs})).toEqual({ status: 200 })`,
433
+ ),
384
434
  )
385
435
  }
386
436
  return cases
@@ -390,9 +440,9 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
390
440
  if (!unscoped) cases.push(...leaked())
391
441
  if (own) {
392
442
  cases.push(
393
- testCase(
443
+ ownScopeCase(
394
444
  `${row.id}: a caller with only ${ownGrants(row, artifact, action, access.dimension)} reaches its own ${access.dimension}`,
395
- `expect(await kit.own(${seeded})).toEqual({ status: 200 })`,
445
+ `expect(await kit.own(${seededArgs})).toEqual({ status: 200 })`,
396
446
  ),
397
447
  )
398
448
  }
@@ -452,6 +502,7 @@ const endpointTestBody = (
452
502
  artifact: ContractArtifact,
453
503
  policies: Policies,
454
504
  fixtures: EndpointFixtures,
505
+ dialect: ApplicationDialect,
455
506
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
456
507
  const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
457
508
  row,
@@ -461,6 +512,7 @@ const endpointTestBody = (
461
512
  ...publicCases(row, artifact, fixtures),
462
513
  ])
463
514
  if (cases.length === 0) return undefined
515
+ const database = testDatabaseLines(dialect, '../../db/migrations/')
464
516
  const body = [
465
517
  '// The endpoint access tests of this application, written by fabrika db test-scaffold from fabrika.contract.ts and',
466
518
  '// src/db/tables.ts. They run src/app.ts itself: callers of two scopes that share no value ask every endpoint with an',
@@ -470,16 +522,16 @@ const endpointTestBody = (
470
522
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
471
523
  '',
472
524
  "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
473
- "import { testDatabase } from '@fabrika/db/testing'",
525
+ database.kit,
474
526
  "import app from '../app'",
475
527
  "import { tables } from '../db/tables'",
476
528
  '',
477
529
  "const label = 'endpoint-access.test.ts'",
478
- "const postgres = await testDatabase({ migrations: new URL('../../db/migrations/', import.meta.url), label })",
530
+ database.open,
479
531
  '',
480
- 'if (postgres !== null) {',
481
- '\tafterAll(() => postgres.close())',
482
- '\tconst kit = endpointAccessKit(app, tables, postgres)',
532
+ `if (${database.name} !== null) {`,
533
+ `\tafterAll(() => ${database.name}.close())`,
534
+ `\tconst kit = endpointAccessKit(app, tables, ${database.name})`,
483
535
  '',
484
536
  describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
485
537
  '}',
@@ -495,29 +547,64 @@ const generated = async ({ body, cases }: { readonly body: string; readonly case
495
547
 
496
548
  /**
497
549
  * Every test the scaffold writes for these policies and, when the application has a contract, its artifact; by path.
498
- * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from.
550
+ * Endpoint access tests exist only for an application on `@fabrika/db`, which has policies to seed rows from. They
551
+ * open the test database of the application's dialect.
499
552
  */
500
553
  export const generatedTests = async (
501
554
  policies: Policies,
502
555
  artifact: ContractArtifact | null,
503
556
  fixtures: EndpointFixtures = NO_FIXTURES,
557
+ dialect: ApplicationDialect = 'postgres',
504
558
  ): Promise<ReadonlyMap<string, GeneratedTest>> => {
505
559
  const files = new Map<string, GeneratedTest>()
506
560
  // The kit's scoped sites are `over` the vocabulary's first dimension: without one, no scoped site exists.
507
561
  const scopedSites = artifact !== null && Object.keys(artifact.dimensions).length > 0
508
562
  for (const table of Object.keys(policies).sort()) {
509
- const test = policyTestBody(policies, table, scopedSites)
563
+ const test = policyTestBody(policies, table, scopedSites, dialect)
510
564
  if (test !== undefined) files.set(policyTestPath(table), await generated(test))
511
565
  }
512
- const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures)
566
+ const endpoints = artifact === null || files.size === 0 ? undefined : endpointTestBody(artifact, policies, fixtures, dialect)
513
567
  if (endpoints !== undefined) files.set(ENDPOINT_ACCESS_TEST, await generated(endpoints))
514
568
  return files
515
569
  }
516
570
 
517
571
  export interface ScaffoldInputs {
572
+ /** What `src/db/tables.ts` defines, its column list included; `null` without the file. */
573
+ readonly tables: Tables<unknown, unknown> | null
518
574
  readonly policies: Policies
519
575
  readonly artifact: ContractArtifact | null
520
576
  readonly fixtures: EndpointFixtures
577
+ readonly dialect: ApplicationDialect
578
+ }
579
+
580
+ /**
581
+ * Whether an endpoint's generated cases run its handler for the caller's own scope, which application rows can serve: a
582
+ * leak or an own case, read off the cases `endpointCases` writes. An input it lacks a fixture for does not matter here.
583
+ */
584
+ const runsOnOwnScope = (row: EndpointRow, artifact: ContractArtifact, policies: Policies, fixtures: EndpointFixtures): boolean => {
585
+ const withInput = { ...fixtures, inputs: { ...fixtures.inputs, [row.id]: fixtures.inputs[row.id] ?? {} } }
586
+ return endpointCases(row, artifact, policies, withInput).some((item) => item.ownScope === true)
587
+ }
588
+
589
+ /** The allowed form of an `appRows` entry `applicationRowsPlan` refuses; the message is the kit's own words. */
590
+ const appRowAllowed = (refusal: ApplicationRowRefusal): string => {
591
+ switch (refusal.kind) {
592
+ case 'table':
593
+ return refusal.mode === null
594
+ ? 'the name of a table with scope: { app } in src/db/tables.ts'
595
+ : "rows, for a row in the endpoint's object; seeds, for the state of the object's own row"
596
+ case 'column':
597
+ return `a column of ${refusal.table} in src/db/schema.generated.ts`
598
+ case 'stamped':
599
+ case 'file':
600
+ return "the row's other columns"
601
+ case 'value':
602
+ return 'a string, a number, a boolean or null'
603
+ case 'partial-key':
604
+ return `all of ${refusal.key.columns.join(', ')}, or none, which the kit then fills`
605
+ case 'cycle':
606
+ return 'a value for one of the foreign keys (null, where it may be), which the kit then does not fill'
607
+ }
521
608
  }
522
609
 
523
610
  /** What the scaffold reads from an application's files; throws `ContractSourceError` or `ContractError` as the reader does. */
@@ -528,15 +615,15 @@ export const scaffoldInputs = (files: ReadonlyMap<string, string>): ScaffoldInpu
528
615
  if (!fixtures.ok) throw new ContractSourceError(fixtures.findings)
529
616
  // Endpoint tests seed rows from the policies, so without src/db/tables.ts there is nothing to compile them against.
530
617
  const artifact = files.has(CONTRACT_FILE) && tables !== null ? readContractSource(files, tables) : null
531
- return { policies, artifact, fixtures: fixtures.fixtures }
618
+ return { tables, policies, artifact, fixtures: fixtures.fixtures, dialect: applicationDialect(files) }
532
619
  }
533
620
 
534
621
  /**
535
622
  * What stops the endpoint access tests from covering every endpoint: one whose input the scaffold cannot sample and
536
623
  * the author gave no fixture, and a fixture of no tested endpoint. Each is an `endpoint-fixture` finding.
537
624
  */
538
- export const missingEndpointFixtures = ({ policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
539
- if (artifact === null || Object.keys(policies).length === 0) return []
625
+ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }: ScaffoldInputs): readonly Finding[] => {
626
+ if (artifact === null || tables === null || Object.keys(policies).length === 0) return []
540
627
  const at = (message: string, allowed: string): Finding => ({
541
628
  file: ENDPOINT_FIXTURES_FILE,
542
629
  line: 1,
@@ -560,7 +647,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
560
647
  )
561
648
  }
562
649
  }
563
- for (const [id, fields] of Object.entries(fixtures.members).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
650
+ for (const [id, fields] of Object.entries(fixtures.members).sort(byKey)) {
564
651
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate))
565
652
  const directory = row === undefined ? null : endpointDirectory(artifact, row)
566
653
  if (row === undefined || directory === null) {
@@ -579,8 +666,6 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
579
666
  }
580
667
  }
581
668
  }
582
- const sortedById = (fields: Readonly<Record<string, readonly string[]>>) =>
583
- Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
584
669
  const holders = [
585
670
  {
586
671
  fields: fixtures.invitations,
@@ -598,7 +683,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
598
683
  },
599
684
  ]
600
685
  for (const holder of holders) {
601
- for (const [id, fields] of sortedById(holder.fields)) {
686
+ for (const [id, fields] of Object.entries(holder.fields).sort(byKey)) {
602
687
  const row = tested.find((candidate) => candidate.id === id && !isLinkProcedure(candidate) && holder.admits(candidate))
603
688
  if (row === undefined) {
604
689
  findings.push(at(holder.refusal(id), holder.allowed))
@@ -611,7 +696,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
611
696
  }
612
697
  }
613
698
  }
614
- for (const [id, fields] of Object.entries(fixtures.rows).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
699
+ for (const [id, fields] of Object.entries(fixtures.rows).sort(byKey)) {
615
700
  const row = tested.find((candidate) => candidate.id === id)
616
701
  const access = row?.requirement?.kind === 'action' ? row.requirement.access : undefined
617
702
  const owned = access?.form === 'on' && ownerRead(policies, access.dimension) !== undefined
@@ -624,7 +709,7 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
624
709
  )
625
710
  continue
626
711
  }
627
- for (const [field, table] of Object.entries(fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
712
+ for (const [field, table] of Object.entries(fields).sort(byKey)) {
628
713
  if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
629
714
  findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a row`, 'a top-level string field of the input'))
630
715
  } else if (!liesDirectlyIn(policies, table, access.dimension)) {
@@ -637,6 +722,21 @@ export const missingEndpointFixtures = ({ policies, artifact, fixtures }: Scaffo
637
722
  }
638
723
  }
639
724
  }
725
+ for (const [id, rows] of Object.entries(fixtures.appRows).sort(byKey)) {
726
+ if (!tested.some((row) => row.id === id && runsOnOwnScope(row, artifact, policies, fixtures))) {
727
+ findings.push(
728
+ at(
729
+ `${id} is no endpoint with a leak or an own case, whose handler could read an application row the kit seeds`,
730
+ "export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }, for an endpoint on, in or over a scope",
731
+ ),
732
+ )
733
+ continue
734
+ }
735
+ // The rule the kit seeds by, read from the policies and the column list: one rule, so the two cannot drift.
736
+ for (const refusal of applicationRowsPlan(tables, rows).refusals) {
737
+ findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
738
+ }
739
+ }
640
740
  const seeded = (row: EndpointRow): boolean =>
641
741
  row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
642
742
  for (const id of Object.keys(fixtures.seeds).sort()) {
@@ -0,0 +1,65 @@
1
+ /** An ESTree node as `@babel/parser` returns it with the `estree` plugin, read structurally. */
2
+ export interface AstNode {
3
+ readonly type: string;
4
+ readonly [key: string]: unknown;
5
+ }
6
+ export interface Position {
7
+ readonly line: number;
8
+ readonly column: number;
9
+ }
10
+ export interface Comment {
11
+ readonly text: string;
12
+ readonly position: Position;
13
+ }
14
+ export interface ParsedModule {
15
+ readonly file: string;
16
+ readonly program: AstNode;
17
+ readonly comments: readonly Comment[];
18
+ /** The UTF-8 size of the source text. */
19
+ readonly bytes: number;
20
+ }
21
+ export type ParseResult = {
22
+ readonly ok: true;
23
+ readonly module: ParsedModule;
24
+ } | {
25
+ readonly ok: false;
26
+ readonly message: string;
27
+ readonly position: Position;
28
+ };
29
+ export declare const isNode: (value: unknown) => value is AstNode;
30
+ /** Whether the source wraps a node in parentheses, which the parser records beside the node rather than as one. */
31
+ export declare const isParenthesized: (node: AstNode) => boolean;
32
+ export declare const child: (node: AstNode, key: string) => AstNode | undefined;
33
+ /** The nodes of an array property; holes (`[a, , b]`) come back as `null`. */
34
+ export declare const children: (node: AstNode, key: string) => readonly (AstNode | null)[];
35
+ export declare const stringField: (node: AstNode, key: string) => string | undefined;
36
+ /** The name of an `Identifier`, or `undefined` for any other node. */
37
+ export declare const identifierName: (node: AstNode | undefined) => string | undefined;
38
+ /** The text of a node whose value is a fixed string: a string `Literal`, or a template with no `${…}`. */
39
+ export declare const staticString: (node: AstNode | undefined) => string | undefined;
40
+ /** A `TemplateElement`'s source text and its decoded value (`undefined` for an invalid escape in a tagged template). */
41
+ export declare const templateText: (element: AstNode) => {
42
+ readonly raw: string;
43
+ readonly cooked: string | undefined;
44
+ };
45
+ /** A property or member key read statically: `a.b`, `a['b']`, ``a[`b`]``, `{ b: … }`, `{ 'b': … }`. */
46
+ export declare const staticKey: (node: AstNode, keyField: "property" | "key") => string | undefined;
47
+ /** The static property names at the end of a member chain, whatever its root: `load().db.sql.raw` → `['db', 'sql', 'raw']`. */
48
+ export declare const memberSuffix: (node: AstNode) => readonly string[];
49
+ /** `as const` and `<const>x` fix a literal's type; they assert nothing. */
50
+ export declare const isConstAssertion: (node: AstNode) => boolean;
51
+ /** Strips the wrappers that do not change which value an expression denotes. */
52
+ export declare const unwrap: (node: AstNode) => AstNode;
53
+ /** `a.b.c` as `['a', 'b', 'c']`; `undefined` when a link is computed or the root is not an identifier. */
54
+ export declare const memberPath: (node: AstNode) => readonly string[] | undefined;
55
+ /** Whether an `Identifier` denotes a runtime value here, rather than a property name, a key, a label or a type. */
56
+ export declare const isValueReference: (node: AstNode, parent: AstNode | undefined) => boolean;
57
+ export declare const positionOf: (node: AstNode) => Position;
58
+ /** Visits every node below `root`, depth first, with the chain of its ancestors (nearest last); `'skip'` prunes a subtree. */
59
+ export declare const walk: (root: AstNode, visit: (node: AstNode, ancestors: readonly AstNode[]) => "skip" | undefined | void) => void;
60
+ export declare const utf8Bytes: (text: string) => number;
61
+ /** The nesting depth of the tree below `root`, measured without recursion, so a deep tree cannot exhaust the stack. */
62
+ export declare const nodeDepth: (root: AstNode) => number;
63
+ export declare const parseModule: (file: string, text: string) => ParseResult;
64
+ /** The sources of a module's import and re-export declarations; `rules/literal.ts` decides which of them are allowed. */
65
+ export declare const importedSpecifiers: (module: ParsedModule) => string[];
@@ -0,0 +1,12 @@
1
+ import type { BunPlugin } from 'bun';
2
+ export interface ShellSliceOptions {
3
+ /** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
4
+ readonly root?: string;
5
+ }
6
+ /**
7
+ * Loads every module of the application's shell graph as its slice: no `.handle(…)`, and no import only a handler
8
+ * used. The build fails with the reader's findings when the static reader refuses the shell.
9
+ */
10
+ export declare function shellSlicePlugin(options?: ShellSliceOptions): BunPlugin;
11
+ declare const _default: BunPlugin;
12
+ export default _default;
@@ -0,0 +1,19 @@
1
+ import { type Finding } from './finding';
2
+ import type { PackedSet } from './packed';
3
+ export interface CheckInput {
4
+ /** The application's root directory. */
5
+ readonly root: string;
6
+ /** The application's files keyed by path relative to `root` with `/` separators; read from disk under `root` when omitted. */
7
+ readonly files?: ReadonlyMap<string, string>;
8
+ /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
9
+ readonly packed?: PackedSet;
10
+ }
11
+ export interface ApplicationTree {
12
+ readonly files: ReadonlyMap<string, string>;
13
+ /** Symbolic links outside the skipped directories; the checker does not follow them. */
14
+ readonly links: readonly string[];
15
+ }
16
+ /** Every file the checker reads, by relative path, and the symbolic links it refuses to follow. */
17
+ export declare const readApplicationTree: (root: string) => Promise<ApplicationTree>;
18
+ /** Runs every rule over one application and returns the findings in file, line and column order. */
19
+ export declare const checkApplication: (input: CheckInput) => Promise<Finding[]>;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,58 @@
1
+ import { type AnyContract } from '@fabrika/app/contract';
2
+ import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core';
3
+ import { type TablePolicies, type Tables } from '@fabrika/db/tables';
4
+ import { type ParsedModule } from './ast';
5
+ import { type Finding } from './finding';
6
+ import { ModuleGraph } from './graph';
7
+ export { ContractError } from '@fabrika/app/contract';
8
+ export { type Finding, formatFinding } from './finding';
9
+ export { contractReaderInputs } from './inputs';
10
+ export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout';
11
+ export { CONTRACT_LIMITS } from './limits';
12
+ export { lockedRegistryVersion, LOCKFILE } from './lockfile';
13
+ export { CHECKER_VERSION } from './version';
14
+ /** Every form the reader refuses, each with its file, line, column and the allowed form. */
15
+ export declare class ContractSourceError extends Error {
16
+ readonly name = "ContractSourceError";
17
+ readonly findings: readonly Finding[];
18
+ constructor(findings: readonly Finding[]);
19
+ }
20
+ /**
21
+ * The contract artifact of an application, read from the text of its files (path relative to the application root →
22
+ * text): `fabrika.contract.ts`, every module it imports and the configuration that applies to them (`readContract`),
23
+ * and `src/db/tables.ts` with the modules it imports (`readTablesDefinition`). `tables`, when given, replaces what
24
+ * `src/db/tables.ts` declares: its parsed policies, or the artifact form of each policy.
25
+ *
26
+ * Throws `ContractSourceError` for a form the reader refuses, and `ContractError` with the same problems
27
+ * `compileContract` reports for a contract that does not compile.
28
+ */
29
+ export declare function readContractSource(files: ReadonlyMap<string, string>, tables?: Tables<unknown, unknown> | Readonly<Record<string, TablePolicyArtifact>>): ContractArtifact;
30
+ /**
31
+ * The table policies of `src/db/tables.ts` in their artifact form (`readTablesDefinition`); none when `files` has no
32
+ * such file. Throws `ContractSourceError`.
33
+ */
34
+ export declare function readTablesSource(files: ReadonlyMap<string, string>): TablePolicies;
35
+ /**
36
+ * The table policies of `src/db/tables.ts`, read from source and parsed by `@fabrika/db`'s own policy parse, as
37
+ * `defineTables` returns them; `null` when `files` has no such file. `files` carries its imports (the generated
38
+ * `src/db/schema.generated.ts`) and the configuration `readContract` names. Throws `ContractSourceError`.
39
+ */
40
+ export declare function readTablesDefinition(files: ReadonlyMap<string, string>): Tables<unknown, unknown> | null;
41
+ /**
42
+ * The contract `defineContract` returns in the evaluated module, read from source; throws `ContractSourceError`.
43
+ * Besides the contract's modules, `files` carries every `package.json`, `tsconfig.json`, `jsconfig.json` and
44
+ * `bunfig.toml` that applies to them (the root and each directory of a contract module): one of them can redirect the
45
+ * packages the reader trusts by name, and the reader cannot tell a missing file from an absent one.
46
+ */
47
+ export declare function readContract(files: ReadonlyMap<string, string>): AnyContract;
48
+ export type ContractRead = {
49
+ readonly ok: true;
50
+ readonly contract: AnyContract;
51
+ } | {
52
+ readonly ok: false;
53
+ readonly findings: readonly Finding[];
54
+ };
55
+ /** Reads the `contract` export of a graph whose contract modules already pass the literal rule. */
56
+ export declare function readContractModule(graph: ModuleGraph): ContractRead;
57
+ /** The contract module and every module its value imports reach. */
58
+ export declare function contractModules(graph: ModuleGraph, entry: ParsedModule): ParsedModule[];
@@ -0,0 +1,8 @@
1
+ /** The database an application's data layer runs on: SQLite in its Durable Object on Cloudflare (ADR-0065), else Postgres. */
2
+ export type ApplicationDialect = 'postgres' | 'sqlite';
3
+ /**
4
+ * Read statically from `fabrika.config.ts`: SQLite when its default export is a call of the `defineApp` that
5
+ * `@fabrika/provider-cloudflare` exports, the config every Cloudflare application writes. Postgres otherwise,
6
+ * including without a config or when the call's origin is not static.
7
+ */
8
+ export declare const applicationDialect: (files: ReadonlyMap<string, string>) => ApplicationDialect;
@@ -0,0 +1,39 @@
1
+ import type { Finding } from './finding';
2
+ import type { Sample } from './scaffold-sample';
3
+ export declare const FIXTURES_EXPORT = "fixtures";
4
+ export declare const SEEDS_EXPORT = "seeds";
5
+ export declare const MEMBERS_EXPORT = "members";
6
+ export declare const INVITATIONS_EXPORT = "invitations";
7
+ export declare const LINKS_EXPORT = "links";
8
+ export declare const ROWS_EXPORT = "rows";
9
+ export declare const APP_ROWS_EXPORT = "appRows";
10
+ type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>;
11
+ export interface EndpointFixtures {
12
+ /** The input each endpoint's cases send, by endpoint id. */
13
+ readonly inputs: ById;
14
+ /** The columns of the row each endpoint addresses, as both scopes' rows are seeded, by endpoint id. */
15
+ readonly seeds: ById;
16
+ /** The input fields that name a member of the endpoint's member directory, by endpoint id. */
17
+ readonly members: Readonly<Record<string, readonly string[]>>;
18
+ /** The input fields that name an invitation the endpoint cancels, by endpoint id. */
19
+ readonly invitations: Readonly<Record<string, readonly string[]>>;
20
+ /** The input fields that name a share link the endpoint revokes, by endpoint id. */
21
+ readonly links: Readonly<Record<string, readonly string[]>>;
22
+ /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
23
+ readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>;
24
+ /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
25
+ readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>;
26
+ }
27
+ export declare const NO_FIXTURES: EndpointFixtures;
28
+ export declare function isSampleObject(value: Sample): value is {
29
+ readonly [key: string]: Sample;
30
+ };
31
+ /** The fixtures of `files`, by endpoint id; none without the file. */
32
+ export declare function readEndpointFixtures(files: ReadonlyMap<string, string>): {
33
+ readonly ok: true;
34
+ readonly fixtures: EndpointFixtures;
35
+ } | {
36
+ readonly ok: false;
37
+ readonly findings: readonly Finding[];
38
+ };
39
+ export {};
@@ -0,0 +1,39 @@
1
+ import type { AstNode, Position } from './ast';
2
+ /** Rules whose finding fails the check: the framework's forms and platform integrity. */
3
+ export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "cloudflare-sql", "cloudflare-scan", "cloudflare-current-timestamp"];
4
+ /** Rules that report a step out of the application architecture. */
5
+ export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
6
+ /**
7
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
8
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
9
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
10
+ */
11
+ export declare const HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
12
+ export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "cloudflare-sql", "cloudflare-scan", "cloudflare-current-timestamp", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
13
+ export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number];
14
+ export type HintRuleId = (typeof HINT_RULE_IDS)[number];
15
+ export type RuleId = (typeof RULE_IDS)[number];
16
+ export type Severity = 'refusal' | 'hint';
17
+ interface FindingFields {
18
+ /** Relative to the application root, with `/` separators. */
19
+ readonly file: string;
20
+ readonly line: number;
21
+ readonly column: number;
22
+ readonly message: string;
23
+ /** What to write instead; every finding names it, because the reader is often an agent with no other feedback. */
24
+ readonly allowed: string;
25
+ }
26
+ /** A finding's severity is its rule's: a refusal rule never reports a hint, nor the reverse. */
27
+ export type Finding = (FindingFields & {
28
+ readonly severity: 'refusal';
29
+ readonly rule: RefusalRuleId;
30
+ }) | (FindingFields & {
31
+ readonly severity: 'hint';
32
+ readonly rule: HintRuleId;
33
+ });
34
+ export declare const isHintRule: (rule: RuleId) => rule is HintRuleId;
35
+ export type Report = (at: AstNode | Position, rule: RuleId, message: string, allowed: string) => void;
36
+ export declare const reporter: (file: string, findings: Finding[]) => Report;
37
+ export declare const formatFinding: (finding: Finding) => string;
38
+ export declare const compareFindings: (left: Finding, right: Finding) => number;
39
+ export {};