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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.9.0-cloudflare.3",
3
+ "version": "0.9.0-dev.10",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,11 +47,11 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-cloudflare.3",
51
- "@fabrika/auth-core": "0.9.0-cloudflare.3",
52
- "@fabrika/db": "0.9.0-cloudflare.3",
53
- "@fabrika/operations-contract": "0.9.0-cloudflare.3",
54
- "@fabrika/platform-node": "0.9.0-cloudflare.3",
50
+ "@fabrika/app": "0.9.0-dev.10",
51
+ "@fabrika/auth-core": "0.9.0-dev.10",
52
+ "@fabrika/db": "0.9.0-dev.10",
53
+ "@fabrika/operations-contract": "0.9.0-dev.10",
54
+ "@fabrika/platform-node": "0.9.0-dev.10",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/check.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
- import { type ContractArtifact, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
2
+ import type { ContractArtifact } from '@fabrika/auth-core'
3
3
  import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
4
4
  import { readdir, readFile } from 'node:fs/promises'
5
5
  import { join } from 'node:path'
@@ -17,6 +17,7 @@ import {
17
17
  isServerModule,
18
18
  isSourceFile,
19
19
  isTestFile,
20
+ isToolModule,
20
21
  TABLES_FILE,
21
22
  ZEROPS_FILES,
22
23
  } from './layout'
@@ -33,6 +34,7 @@ import { checkClientIdentity } from './rules/identity'
33
34
  import { checkGeneratedTests } from './rules/isolation'
34
35
  import { checkJsonStrings } from './rules/json'
35
36
  import { checkLiteralGraph } from './rules/literal'
37
+ import { checkMigrationHistory, type MigrationBase } from './rules/migration-history'
36
38
  import {
37
39
  checkConflictIndexes,
38
40
  checkCurrentTimestampDefaults,
@@ -44,8 +46,9 @@ import {
44
46
  } from './rules/migrations'
45
47
  import { checkModuleReferences } from './rules/modules'
46
48
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
47
- import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
48
- import { checkStructureNode, checkStructureReferences, structurePlace } from './rules/structure'
49
+ import { checkBackupPlan, checkMigrationClassification } from './rules/platform-migrations'
50
+ import { checkKeyLiteralNode, checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
51
+ import { checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
49
52
  import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
50
53
  import { checkComments, checkTypeNode } from './rules/types'
51
54
  import { moduleSlice, sliceFinding } from './slice'
@@ -62,6 +65,8 @@ export interface CheckInput {
62
65
  readonly files?: ReadonlyMap<string, string>
63
66
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
64
67
  readonly packed?: PackedSet
68
+ /** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
69
+ readonly migrationBase?: MigrationBase
65
70
  }
66
71
 
67
72
  export interface ApplicationTree {
@@ -98,6 +103,26 @@ interface ContractDependent {
98
103
  readonly inserts: ConflictInsert[]
99
104
  }
100
105
 
106
+ /**
107
+ * A module under `tools/` runs on a developer's machine, never in the application: it is held to how its source is
108
+ * written (`type-assertion`, `any-type`, `capability-widening`, `suppression-comment`), `key-literal`, a `declare
109
+ * module` of a trusted package and the rules of its tests. Every other module rule guards code that runs in the
110
+ * application. `generated-test-import` reaches it through `checkStructureReferences`, as every module.
111
+ */
112
+ const checkToolModule = async (module: ParsedModule, text: string, files: ReadonlyMap<string, string>, findings: Finding[]): Promise<void> => {
113
+ const report = reporter(module.file, findings)
114
+ const isTest = isTestFile(module.file)
115
+ walk(module.program, (node, ancestors) => {
116
+ checkKeyLiteralNode(node, report)
117
+ checkTypeNode(node, report)
118
+ checkAmbientModule(node, report)
119
+ if (isTest) checkTestNode(node, ancestors, report)
120
+ checkMockModule(node, module.file, files, report)
121
+ })
122
+ checkComments(module.comments, report)
123
+ await checkGeneratedTest(text, module.comments, report)
124
+ }
125
+
101
126
  const checkSourceModule = async (
102
127
  module: ParsedModule,
103
128
  references: readonly ModuleReference[],
@@ -165,8 +190,6 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
165
190
  interface CompiledReach {
166
191
  readonly procedures: ReadonlySet<string>
167
192
  readonly origins: readonly string[]
168
- /** Some cron job declares `egress: 'public'`. */
169
- readonly publicEgress: boolean
170
193
  }
171
194
 
172
195
  /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
@@ -186,43 +209,25 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
186
209
  )
187
210
  return {
188
211
  procedures: new Set(procedures.map((row) => row.id)),
189
- origins: Object.values(artifact.declared ?? {}).flatMap((
190
- reach,
191
- ) => (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress)),
192
- publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
212
+ origins: Object.values(artifact.declared ?? {}).flatMap((reach) => reach.egress ?? []),
193
213
  }
194
214
  }
195
215
 
196
216
  /**
197
217
  * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
198
- * not accepted) and, where a cron job declares `egress: 'public'`, when public egress would refuse it: another scheme,
199
- * or a host its URL alone refuses (an IP address, a local or internal name, a port). A prefix that ends inside the host
200
- * is then the runtime's to judge. Every one stands when the contract does not compile. A `ctx.url` stands when the contract
218
+ * not accepted), and every one stands when the contract does not compile. A `ctx.url` stands when the contract
201
219
  * compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
202
220
  */
203
221
  const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
204
- ...dependent.fetches.filter(({ target }) =>
205
- reach === null || (!reach.origins.some((origin) => isWithinOrigin(target, origin)) && !(reach.publicEgress && isPublicTarget(target)))
206
- ).map(({ finding }) => finding),
222
+ ...dependent.fetches.filter(({ target }) => reach === null || !reach.origins.some((origin) => isWithinOrigin(target, origin))).map(({ finding }) =>
223
+ finding
224
+ ),
207
225
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
208
226
  ]
209
227
 
210
228
  const isWithinOrigin = (target: string, origin: string): boolean =>
211
229
  target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
212
230
 
213
- /** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
214
- const isPublicTarget = (target: string): boolean => {
215
- const scheme = /^(https?):\/\//i.exec(target)
216
- if (scheme === null) return false
217
- const rest = target.slice(scheme[0].length)
218
- if (!/[/?#]/.test(rest)) return true
219
- try {
220
- return publicEgressRefusal(new URL(target)) === null
221
- } catch {
222
- return false
223
- }
224
- }
225
-
226
231
  /** Runs every rule over one application and returns the findings in file, line and column order. */
227
232
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
228
233
  const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
@@ -259,7 +264,8 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
259
264
  modules.set(path, parsed.module)
260
265
  const referencesOfModule = moduleReferences(parsed.module.program)
261
266
  references.set(path, referencesOfModule)
262
- await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
267
+ if (isToolModule(path)) await checkToolModule(parsed.module, text, tree.files, findings)
268
+ else await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
263
269
  }
264
270
  const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
265
271
  for (const path of modules.keys()) {
@@ -285,14 +291,18 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
285
291
  for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
286
292
  findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
287
293
  findings.push(...checkMigrationNames(checkedPaths))
294
+ if (input.migrationBase !== undefined) findings.push(...checkMigrationHistory(tree.files, input.migrationBase))
295
+ findings.push(...checkToolPackages(checkedPaths))
288
296
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
289
297
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
290
298
  const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
291
299
  findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
300
+ if (artifact !== null) findings.push(...checkMigrationClassification(tree.files, artifact.app))
292
301
  if (applicationDialect(tree.files) === 'sqlite') {
293
302
  if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
294
303
  findings.push(...checkCurrentTimestampDefaults(tree.files))
295
304
  findings.push(...checkSqliteFrameworkNames(tree.files))
305
+ findings.push(...(await checkBackupPlan(tree.files)))
296
306
  }
297
307
  if (declaredTables !== null) {
298
308
  const policies = tablePolicies(declaredTables)
package/src/cli.ts CHANGED
@@ -4,12 +4,14 @@ import { readFile } from 'node:fs/promises'
4
4
  import { resolve } from 'node:path'
5
5
  import { checkApplication } from './check'
6
6
  import { type Finding, formatFinding } from './finding'
7
+ import { readMigrationBase } from './migration-base'
7
8
  import { type PackedSet, readPackedSet } from './packed'
9
+ import type { MigrationBase } from './rules/migration-history'
8
10
 
9
11
  const USAGE = `fabrika-check — the application checker
10
12
 
11
13
  Usage:
12
- fabrika-check [--packed <release-manifest.json>] [<root>]
14
+ fabrika-check [--packed <release-manifest.json>] [--base <ref>] [<root>]
13
15
 
14
16
  Checks the application in <root> (default: the current directory) and prints one line per finding:
15
17
  <file>:<line>:<column> <rule> <message> (allowed form: <what to write instead>)
@@ -18,6 +20,10 @@ Checks the application in <root> (default: the current directory) and prints one
18
20
  file: specifiers and overrides of its @fabrika/* packages, and their lockfile entries, when each tarball's bytes
19
21
  match the sha512 the manifest records. Only a local or dogfood setup passes it; the platform build never does.
20
22
 
23
+ In a git work tree, every migration of db/migrations at the merge base of HEAD and the remote's default branch
24
+ (origin/HEAD, else origin/main or origin/master) must be in the tree unchanged: a deploy refuses a migration that
25
+ changed after it was applied. --base names another ref to compare with.
26
+
21
27
  A refusal fails the check. A hint, printed under its own heading after the refusals, reports a step out of the
22
28
  application architecture and does not fail it.
23
29
 
@@ -32,20 +38,24 @@ const count = (amount: number, noun: string): string => `${amount} ${noun}${amou
32
38
  interface Arguments {
33
39
  readonly root: string | undefined
34
40
  readonly packed: string | undefined
41
+ readonly base: string | undefined
35
42
  }
36
43
 
37
- /** The root and the `--packed` manifest, or the first argument the checker does not take. */
44
+ /** The root, the `--packed` manifest and the `--base` ref, or the first argument the checker does not take. */
38
45
  const parseArguments = (argv: readonly string[]): Arguments | { readonly unexpected: string } => {
39
46
  let root: string | undefined
40
47
  let packed: string | undefined
48
+ let base: string | undefined
41
49
  for (let index = 0; index < argv.length; index++) {
42
50
  const argument = argv[index] ?? ''
43
51
  if (argument === '--packed' && packed === undefined && argv[index + 1] !== undefined) packed = argv[++index]
44
52
  else if (argument.startsWith('--packed=') && packed === undefined) packed = argument.slice('--packed='.length)
53
+ else if (argument === '--base' && base === undefined && argv[index + 1] !== undefined) base = argv[++index]
54
+ else if (argument.startsWith('--base=') && base === undefined && argument.length > '--base='.length) base = argument.slice('--base='.length)
45
55
  else if (argument.startsWith('-') || root !== undefined) return { unexpected: argument }
46
56
  else root = argument
47
57
  }
48
- return { root, packed }
58
+ return { root, packed, base }
49
59
  }
50
60
 
51
61
  const main = async (argv: readonly string[]): Promise<number> => {
@@ -69,9 +79,18 @@ const main = async (argv: readonly string[]): Promise<number> => {
69
79
  }
70
80
  console.error(`fabrika-check: accepting the tarballs of the local pack ${packed.version}, which no deploy build does`)
71
81
  }
82
+ const read = await readMigrationBase(root, parsed.base)
83
+ let migrationBase: MigrationBase | undefined
84
+ if (read !== null && !('skipped' in read)) migrationBase = read
85
+ else if (parsed.base !== undefined) {
86
+ console.error(
87
+ `fabrika-check: cannot compare the migrations with ${parsed.base}: ${read === null ? `${root} is in no git work tree` : read.skipped}`,
88
+ )
89
+ return 2
90
+ } else if (read !== null) console.error(`fabrika-check: migration-edited did not run: ${read.skipped}`)
72
91
  let findings: Finding[]
73
92
  try {
74
- findings = await checkApplication({ root, packed })
93
+ findings = await checkApplication({ root, packed, migrationBase })
75
94
  } catch (error) {
76
95
  console.error(`fabrika-check: cannot read ${root}: ${error instanceof Error ? error.message : 'unknown error'}`)
77
96
  return 2
package/src/finding.ts CHANGED
@@ -28,6 +28,9 @@ export const REFUSAL_RULE_IDS = [
28
28
  'unsafe-html',
29
29
  'dynamic-code',
30
30
  'migration-name',
31
+ 'migration-refused',
32
+ 'backup-schema',
33
+ 'migration-edited',
31
34
  'file-column-migration',
32
35
  'crontab',
33
36
  'package-replacement',
@@ -40,6 +43,7 @@ export const REFUSAL_RULE_IDS = [
40
43
  'layer-import',
41
44
  'generated-test-import',
42
45
  'shared-import',
46
+ 'tool-import',
43
47
  'cloudflare-scan',
44
48
  'cloudflare-job-segment',
45
49
  'cloudflare-current-timestamp',
package/src/index.ts CHANGED
@@ -2,7 +2,9 @@ export { type ApplicationTree, checkApplication, type CheckInput, readApplicatio
2
2
  export { type ApplicationDialect, applicationDialect } from './dialect'
3
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding'
4
4
  export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
5
+ export { readMigrationBase } from './migration-base'
5
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
7
+ export type { MigrationBase } from './rules/migration-history'
6
8
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
7
9
  export {
8
10
  ENDPOINT_ACCESS_TEST,
package/src/layout.ts CHANGED
@@ -37,6 +37,11 @@ export const SLICE_QUERIES_FILE = 'queries.ts'
37
37
  export const SPA_DIR = 'web/'
38
38
  /** The server half of an application: its modules run in the application's process. */
39
39
  export const SERVER_DIR = 'src/'
40
+ /**
41
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
42
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
43
+ */
44
+ export const TOOLS_DIR = 'tools/'
40
45
 
41
46
  const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
42
47
  const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
@@ -54,6 +59,9 @@ export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
54
59
  /** A module that runs in the application's server process: under `src/`, not a test. */
55
60
  export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
56
61
 
62
+ /** A module under `tools/`, tests included. */
63
+ export const isToolModule = (path: string): boolean => path.startsWith(TOOLS_DIR)
64
+
57
65
  export const isJsonFile = (path: string): boolean => path.endsWith('.json')
58
66
 
59
67
  /** Whether the checker reads this file at all. */
@@ -0,0 +1,85 @@
1
+ // The migrations `migration-edited` compares the tree with: those of the merge base of HEAD and the remote's default
2
+ // branch, read with git. Only the bin reads them; a caller with the files of a commit (Control, a deploy build) has no
3
+ // history to compare with, and the runner's checksum stays the real check.
4
+
5
+ import { MIGRATIONS_DIR } from './layout'
6
+ import type { MigrationBase } from './rules/migration-history'
7
+
8
+ /** What the default base is looked up as, in order, when the bin is given no `--base`. */
9
+ const DEFAULT_REFS = ['origin/main', 'origin/master']
10
+
11
+ interface GitResult {
12
+ readonly ok: boolean
13
+ readonly stdout: Uint8Array
14
+ }
15
+
16
+ const git = async (root: string, args: readonly string[], stdin?: string): Promise<GitResult> => {
17
+ const input = stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin)
18
+ const child = Bun.spawn(['git', '-C', root, ...args], { stdin: input, stdout: 'pipe', stderr: 'ignore' })
19
+ const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).arrayBuffer()])
20
+ return { ok: code === 0, stdout: new Uint8Array(stdout) }
21
+ }
22
+
23
+ const text = (bytes: Uint8Array): string => new TextDecoder().decode(bytes).trim()
24
+
25
+ /** The remote's default branch: `origin/HEAD` where the clone recorded it, else the first of `DEFAULT_REFS` that exists. */
26
+ const defaultRef = async (root: string): Promise<string | null> => {
27
+ const head = await git(root, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD'])
28
+ if (head.ok && text(head.stdout) !== '') return text(head.stdout)
29
+ for (const ref of DEFAULT_REFS) {
30
+ if ((await git(root, ['rev-parse', '--verify', '-q', `${ref}^{commit}`])).ok) return ref
31
+ }
32
+ return null
33
+ }
34
+
35
+ /** Each regular file directly in `db/migrations/` at `commit`, by its blob id. */
36
+ const migrationBlobs = async (root: string, commit: string): Promise<Map<string, string> | null> => {
37
+ const listed = await git(root, ['ls-tree', '-z', commit, '--', MIGRATIONS_DIR])
38
+ if (!listed.ok) return null
39
+ const blobs = new Map<string, string>()
40
+ for (const entry of new TextDecoder().decode(listed.stdout).split('\0')) {
41
+ const match = /^(100644|100755) blob ([0-9a-f]+)\t(.+)$/.exec(entry)
42
+ if (match?.[2] !== undefined && match[3] !== undefined && match[3].endsWith('.sql')) blobs.set(match[3], match[2])
43
+ }
44
+ return blobs
45
+ }
46
+
47
+ /** The blobs' texts, through one `git cat-file --batch`: each answer is `<id> blob <size>\n<bytes>\n`. */
48
+ const blobTexts = async (root: string, blobs: ReadonlyMap<string, string>): Promise<Map<string, string> | null> => {
49
+ if (blobs.size === 0) return new Map()
50
+ const ids = [...blobs.values()]
51
+ const batch = await git(root, ['cat-file', '--batch'], ids.map((id) => `${id}\n`).join(''))
52
+ if (!batch.ok) return null
53
+ const decoder = new TextDecoder()
54
+ const texts = new Map<string, string>()
55
+ let offset = 0
56
+ for (const id of ids) {
57
+ const end = batch.stdout.indexOf(10, offset)
58
+ const header = /^([0-9a-f]+) blob (\d+)$/.exec(decoder.decode(batch.stdout.subarray(offset, end)))
59
+ if (end < 0 || header?.[1] !== id || header[2] === undefined) return null
60
+ const size = Number(header[2])
61
+ texts.set(id, decoder.decode(batch.stdout.subarray(end + 1, end + 1 + size)))
62
+ offset = end + 1 + size + 1
63
+ }
64
+ return new Map([...blobs].map(([path, id]) => [path, texts.get(id) ?? '']))
65
+ }
66
+
67
+ /**
68
+ * The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
69
+ * the merge base so that migrations the default branch added since the branch forked are not read as deleted.
70
+ * `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
71
+ */
72
+ export const readMigrationBase = async (root: string, ref?: string): Promise<MigrationBase | { readonly skipped: string } | null> => {
73
+ if (!(await git(root, ['rev-parse', '--is-inside-work-tree'])).ok) return null
74
+ const named = ref ?? (await defaultRef(root))
75
+ if (named === null) return { skipped: `no origin/HEAD, ${DEFAULT_REFS.join(' or ')} to compare the migrations with; pass --base <ref>` }
76
+ if (named.startsWith('-') || !(await git(root, ['rev-parse', '--verify', '-q', `${named}^{commit}`])).ok) {
77
+ return { skipped: `${named} names no commit` }
78
+ }
79
+ const mergeBase = await git(root, ['merge-base', 'HEAD', named])
80
+ if (!mergeBase.ok) return { skipped: `HEAD and ${named} share no commit this clone holds` }
81
+ const blobs = await migrationBlobs(root, text(mergeBase.stdout))
82
+ const files = blobs === null ? null : await blobTexts(root, blobs)
83
+ if (files === null) return { skipped: `the migrations of ${named} cannot be read` }
84
+ return { ref: named, files }
85
+ }
@@ -799,7 +799,7 @@ function plain(value: LiteralValue | undefined): unknown {
799
799
  }
800
800
 
801
801
  const DECLARED_ALLOWED =
802
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>'] | 'public' (a cron job)"
802
+ "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>']"
803
803
 
804
804
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
805
805
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -1,5 +1,5 @@
1
1
  import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
2
- import { type ContractArtifact, type DeclaredEgress, PUBLIC_EGRESS } from '@fabrika/auth-core'
2
+ import type { ContractArtifact } from '@fabrika/auth-core'
3
3
  import type { Finding } from '../finding'
4
4
  import { CONTRACT_FILE } from '../layout'
5
5
 
@@ -14,8 +14,8 @@ const at = (rule: 'cloudflare-scan' | 'cloudflare-job-segment', message: string,
14
14
  })
15
15
 
16
16
  /** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
17
- const outsideCalls = (reach: { readonly egress?: DeclaredEgress; readonly connect: readonly string[] }): string[] => [
18
- ...(reach.egress === PUBLIC_EGRESS ? [`egress '${PUBLIC_EGRESS}'`] : (reach.egress ?? []).map((origin) => `egress ${origin}`)),
17
+ const outsideCalls = (reach: { readonly egress?: readonly string[]; readonly connect: readonly string[] }): string[] => [
18
+ ...(reach.egress ?? []).map((origin) => `egress ${origin}`),
19
19
  ...reach.connect.map((name) => `connect ${name}`),
20
20
  ]
21
21
 
@@ -0,0 +1,70 @@
1
+ // A migration that a shared branch already holds, edited, renamed or deleted in the tree being checked. Every runner
2
+ // keeps the SHA-256 of each applied file and refuses a deploy whose file changed after it ran (ADR-0017), and Control
3
+ // and the deploy see one commit, not its history: the checker is where the edit can be named before the push.
4
+
5
+ import type { Finding } from '../finding'
6
+ import { MIGRATIONS_DIR } from '../layout'
7
+
8
+ /** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
9
+ export interface MigrationBase {
10
+ /** How the commit is named to the author, such as `origin/main`. */
11
+ readonly ref: string
12
+ readonly files: ReadonlyMap<string, string>
13
+ }
14
+
15
+ const ALLOWED = 'the file as it is there, and the change as a new migration (bunx fabrika db new <slug>)'
16
+
17
+ const isMigration = (path: string): boolean => {
18
+ const name = path.slice(MIGRATIONS_DIR.length)
19
+ return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/')
20
+ }
21
+
22
+ /** Lines without a trailing carriage return: a Windows checkout's line ends are not an edit of the committed file. */
23
+ const linesOf = (sql: string): string[] => sql.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
24
+
25
+ /** The first line where `current` leaves `base`, or its last line when it only lost lines at the end. */
26
+ const firstChangedLine = (base: readonly string[], current: readonly string[]): number | null => {
27
+ const length = Math.max(base.length, current.length)
28
+ for (let index = 0; index < length; index++) {
29
+ if (base[index] !== current[index]) return Math.min(index, current.length - 1) + 1
30
+ }
31
+ return null
32
+ }
33
+
34
+ /**
35
+ * Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
36
+ * removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
37
+ */
38
+ export const checkMigrationHistory = (files: ReadonlyMap<string, string>, base: MigrationBase): Finding[] => {
39
+ const findings: Finding[] = []
40
+ for (const [path, committed] of base.files) {
41
+ if (!isMigration(path)) continue
42
+ const name = path.slice(MIGRATIONS_DIR.length)
43
+ const current = files.get(path)
44
+ if (current === undefined) {
45
+ findings.push({
46
+ file: path,
47
+ line: 1,
48
+ column: 1,
49
+ severity: 'refusal',
50
+ rule: 'migration-edited',
51
+ message:
52
+ `'${name}' is in ${base.ref} and was deleted or renamed: an environment that applied it keeps its changes, and a renamed file runs again there`,
53
+ allowed: ALLOWED,
54
+ })
55
+ continue
56
+ }
57
+ const line = firstChangedLine(linesOf(committed), linesOf(current))
58
+ if (line === null) continue
59
+ findings.push({
60
+ file: path,
61
+ line,
62
+ column: 1,
63
+ severity: 'refusal',
64
+ rule: 'migration-edited',
65
+ message: `'${name}' differs from ${base.ref}: a deploy refuses a migration that changed after it was applied, even in a comment`,
66
+ allowed: ALLOWED,
67
+ })
68
+ }
69
+ return findings
70
+ }
@@ -15,11 +15,6 @@ const NETWORK: Forbidden = {
15
15
  what: 'a raw network module',
16
16
  allowed: 'endpoints declared in the contract; another application through a connector import',
17
17
  }
18
- /** `Bun.fetch`: Bun's own `fetch`, which the egress guard on the global one does not wrap. */
19
- const BUN_FETCH: Forbidden = {
20
- what: "Bun's own fetch, past the egress guard",
21
- allowed: "the global fetch, under the site's egress: ['<origin>'] or a cron job's egress: 'public'",
22
- }
23
18
  const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
24
19
 
25
20
  const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
@@ -83,7 +78,6 @@ export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
83
78
  ...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
84
79
  ...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
85
80
  ...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
86
- ['fetch', BUN_FETCH],
87
81
  ...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
88
82
  ])
89
83
 
@@ -0,0 +1,93 @@
1
+ // What the platform refuses of an application's migrations, found before the push instead of in a deploy's run log:
2
+ // the classifier Control runs on every snapshot, and on Cloudflare the backup's plan of the migrated schema, which every
3
+ // migration deploy takes first.
4
+
5
+ import { describeOpsDumpSchema, planOpsDump } from '@fabrika/auth-core'
6
+ import { withMigratedSqlite } from '@fabrika/db/codegen-sqlite'
7
+ import { FRAMEWORK_MIGRATION_BUNDLE } from '@fabrika/db/migrations'
8
+ import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
9
+ import { applicationDatabaseSchema, classifyMigrations } from '@fabrika/platform-node/sql'
10
+ import type { Finding } from '../finding'
11
+ import { MIGRATIONS_DIR } from '../layout'
12
+
13
+ interface MigrationText {
14
+ readonly path: string
15
+ readonly name: string
16
+ readonly sql: string
17
+ }
18
+
19
+ /** The files of `db/migrations` itself, by name: the order the runner and Control read them in. */
20
+ const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
21
+ [...files].flatMap(([path, sql]) => {
22
+ const name = path.slice(MIGRATIONS_DIR.length)
23
+ return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/') ? [{ path, name, sql }] : []
24
+ }).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
25
+
26
+ /**
27
+ * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
28
+ * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
29
+ * checked, applied or not: the checker does not know which an environment holds.
30
+ */
31
+ export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
32
+ const texts = migrationTexts(files)
33
+ if (texts.length === 0) return []
34
+ const paths = new Map(texts.map((text) => [text.name, text.path]))
35
+ return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId)).files.flatMap((file) =>
36
+ file.refused.map((refusal): Finding => ({
37
+ file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
38
+ line: refusal.line,
39
+ column: 1,
40
+ severity: 'refusal',
41
+ rule: 'migration-refused',
42
+ message: `${refusal.reason} is not allowed: Control refuses the deploy that brings this migration`,
43
+ allowed: 'the statements, functions and objects the migration classifier admits (application-runtime reference, "Migrations")',
44
+ }))
45
+ )
46
+ }
47
+
48
+ /**
49
+ * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
50
+ * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
51
+ * after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
52
+ */
53
+ export const checkBackupPlan = async (files: ReadonlyMap<string, string>): Promise<Finding[]> => {
54
+ const texts = migrationTexts(files)
55
+ if (texts.length === 0) return []
56
+ let refused: { readonly table: string | null } | null
57
+ try {
58
+ refused = await withMigratedSqlite([
59
+ { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
60
+ { bundle: 'app', migrations: texts.map(({ name, sql }) => ({ name, sql })) },
61
+ ], (db) => {
62
+ const plan = planOpsDump(describeOpsDumpSchema((query, ...bindings) => db.query<Record<string, unknown>, string[]>(query).all(...bindings)))
63
+ return 'refused' in plan ? plan : null
64
+ })
65
+ } catch {
66
+ return []
67
+ }
68
+ if (refused === null) return []
69
+ const at = refused.table === null ? undefined : newestNaming(texts, refused.table)
70
+ const last = texts[texts.length - 1]
71
+ return [{
72
+ file: at?.path ?? last?.path ?? MIGRATIONS_DIR,
73
+ line: at?.line ?? 1,
74
+ column: 1,
75
+ severity: 'refusal',
76
+ rule: 'backup-schema',
77
+ message: refused.table === null
78
+ ? 'the migrated schema cannot be backed up (a table name the data layer does not admit, or two tables of one name)'
79
+ : `table ${refused.table} cannot be backed up, and every migration deploy takes a backup first`,
80
+ allowed:
81
+ "a foreign key inside its table's cycle that is nullable, outside the primary key, referenced by no other key and named by no CHECK (ADR-0070 section 2); or no such key",
82
+ }]
83
+ }
84
+
85
+ /** The newest migration that names `table`, and the first line there that does. */
86
+ const newestNaming = (texts: readonly MigrationText[], table: string): { path: string; line: number } | undefined => {
87
+ const word = new RegExp(`(^|[^A-Za-z0-9_$])["\`[]?${table.replace(/[$]/g, '\\$&')}["\`\\]]?($|[^A-Za-z0-9_$])`, 'i')
88
+ for (const text of [...texts].reverse()) {
89
+ const index = text.sql.split('\n').findIndex((line) => word.test(line))
90
+ if (index >= 0) return { path: text.path, line: index + 1 }
91
+ }
92
+ return undefined
93
+ }
@@ -36,11 +36,8 @@ export interface SourceContext {
36
36
  readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
37
37
  }
38
38
 
39
- /**
40
- * The global objects, `Bun`, and `WebSocket`, a socket the egress guard on `fetch` does not see: a server module reaches
41
- * the platform and the outside through the framework only.
42
- */
43
- const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun', 'WebSocket'])
39
+ /** The global objects and `Bun`: a server module reaches the platform through the framework only. */
40
+ const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun'])
44
41
 
45
42
  /**
46
43
  * The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
@@ -180,8 +177,7 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
180
177
  /** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
181
178
  export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
182
179
  message: `fetch to the absolute origin '${target}' is a hand-written integration`,
183
- allowed:
184
- "a same-origin path to a declared endpoint, another application through a connector import, egress: ['<origin>'] on the site, or a public host of http(s) under a cron job's egress: 'public'",
180
+ allowed: "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>'] on the site",
185
181
  })
186
182
 
187
183
  const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
@@ -486,9 +482,9 @@ const checkPrototypeWrite = (node: AstNode, context: SourceContext): void => {
486
482
 
487
483
  const KEY_PREFIX = 'px_'
488
484
 
489
- const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], context: SourceContext): void => {
485
+ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], report: Report): void => {
490
486
  if (texts.some((text) => text?.includes(KEY_PREFIX))) {
491
- context.report(
487
+ report(
492
488
  node,
493
489
  'key-literal',
494
490
  `'${KEY_PREFIX}' in a literal: a key or a session cookie name in source`,
@@ -497,6 +493,15 @@ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[
497
493
  }
498
494
  }
499
495
 
496
+ /** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
497
+ export const checkKeyLiteralNode = (node: AstNode, report: Report): void => {
498
+ if (node.type === 'Literal') checkStringContent(node, [staticString(node)], report)
499
+ else if (node.type === 'TemplateElement') {
500
+ const { raw, cooked } = templateText(node)
501
+ checkStringContent(node, [raw, cooked], report)
502
+ }
503
+ }
504
+
500
505
  const isTypeOnlyImport = (specifier: AstNode, parent: AstNode | undefined): boolean =>
501
506
  stringField(specifier, 'importKind') === 'type' || (parent !== undefined && stringField(parent, 'importKind') === 'type')
502
507
 
@@ -540,11 +545,8 @@ export const checkRuntimeNode = (node: AstNode, ancestors: readonly AstNode[], c
540
545
  return
541
546
  }
542
547
  case 'Literal':
543
- return checkStringContent(node, [staticString(node)], context)
544
- case 'TemplateElement': {
545
- const { raw, cooked } = templateText(node)
546
- return checkStringContent(node, [raw, cooked], context)
547
- }
548
+ case 'TemplateElement':
549
+ return checkKeyLiteralNode(node, context.report)
548
550
  case 'JSXAttribute': {
549
551
  const name = child(node, 'name')
550
552
  if (name?.type === 'JSXIdentifier' && stringField(name, 'name') === 'dangerouslySetInnerHTML') {
@@ -1,12 +1,13 @@
1
1
  import { isBuiltin } from 'node:module'
2
2
  import { type AstNode, child, identifierName, staticKey } from '../ast'
3
- import { type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
3
+ import { type Finding, type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
4
4
  import {
5
5
  CONTRACT_FILE,
6
6
  DATABASE_DIR,
7
7
  isRelativeSpecifier,
8
8
  isSourceFile,
9
9
  isTestFile,
10
+ isToolModule,
10
11
  resolveRelative,
11
12
  SCHEMAS_DIR,
12
13
  SCHEMAS_FILE,
@@ -221,6 +222,21 @@ const checkSliceReference = (place: StructurePlace, reference: ModuleReference,
221
222
  )
222
223
  }
223
224
 
225
+ /**
226
+ * A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
227
+ * load by its name, past `tool-import`, which judges the files an import resolves to.
228
+ */
229
+ export const checkToolPackages = (paths: readonly string[]): Finding[] =>
230
+ paths.filter((path) => isToolModule(path) && path.endsWith('/package.json')).map((path) => ({
231
+ file: path,
232
+ line: 1,
233
+ column: 1,
234
+ severity: 'refusal',
235
+ rule: 'tool-import',
236
+ message: `'${path}' makes a developer's tool a package, which the application could load by its name`,
237
+ allowed: "tools/ without a package.json: a tool's dependencies go in the root package.json",
238
+ }))
239
+
224
240
  /** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
225
241
  export const checkStructureReferences = (graph: StructureGraph, place: StructurePlace, report: Report): void => {
226
242
  for (const reference of graph.referencesOf(place.file)) {
@@ -234,6 +250,15 @@ export const checkStructureReferences = (graph: StructureGraph, place: Structure
234
250
  )
235
251
  }
236
252
  if (reference.typeOnly) continue
253
+ const tool = isToolModule(place.file) ? undefined : targets.files.find(isToolModule)
254
+ if (tool !== undefined) {
255
+ report(
256
+ reference.node,
257
+ 'tool-import',
258
+ `'${reference.specifier}' loads ${tool}, a developer's tool, which nothing outside tools/ loads`,
259
+ 'what the application and a tool share under src/ (pure code in src/shared/), imported by the tool',
260
+ )
261
+ }
237
262
  if (place.file.startsWith(SPA_DIR) && !place.exempt) checkSpaReference(graph, reference, targets, report)
238
263
  if (isSharedModule(place.file) && !place.exempt) checkSharedReference(reference, targets, report)
239
264
  if (isLayerModule(place.file)) checkLayerReference(graph, place, reference, targets, report)
package/src/scaffold.ts CHANGED
@@ -3,7 +3,14 @@
3
3
  // one file per application, from the contract: they run the application's own `serve(…)` and handlers. The checker
4
4
  // regenerates both to find a missing, edited, stale or orphaned file. Browser-safe: no file API.
5
5
 
6
- import { GENERATED_FILE_PREFIX, GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
6
+ import {
7
+ deniedCaseRuledOutBy,
8
+ GENERATED_FILE_PREFIX,
9
+ GENERATED_INVITATION,
10
+ GENERATED_LINK,
11
+ GENERATED_MEMBER,
12
+ GENERATED_ROW_PREFIX,
13
+ } from '@fabrika/app/contract'
7
14
  import {
8
15
  type ContractArtifact,
9
16
  endpointDirectory,
@@ -30,6 +37,8 @@ export const policyTestPath = (table: string): string => `${POLICY_TESTS_DIR}${t
30
37
  export interface GeneratedTest {
31
38
  readonly text: string
32
39
  readonly cases: readonly string[]
40
+ /** What the test cannot check, one line each, which `fabrika db test-scaffold` prints: a ruled-out capability case. */
41
+ readonly notes: readonly string[]
33
42
  }
34
43
 
35
44
  type Policies = Readonly<Record<string, TablePolicyArtifact>>
@@ -529,25 +538,47 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
529
538
 
530
539
  /**
531
540
  * An endpoint of several capabilities: one denied case per capability, each refused while every other one passes. An
532
- * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403 (`over`).
541
+ * object of another scope is 404 (`on`), a value of another scope 403 (`in`), and a caller without the action 403
542
+ * (`over`). An `over` capability whose action another one needs in a related dimension has none (`deniedCaseRuledOutBy`);
543
+ * `notes` says so for each, in the generated test and in `fabrika db test-scaffold`'s output.
533
544
  */
534
- const capabilityCases = (row: EndpointRow, fixtures: EndpointFixtures): readonly Case[] => {
535
- if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) return []
545
+ const capabilityCases = (
546
+ row: EndpointRow,
547
+ artifact: ContractArtifact,
548
+ fixtures: EndpointFixtures,
549
+ ): { readonly cases: readonly Case[]; readonly notes: readonly string[] } => {
550
+ if (row.requirement?.kind !== 'capabilities' || !row.callers.some((caller) => caller === 'human' || caller === 'machine')) {
551
+ return { cases: [], notes: [] }
552
+ }
536
553
  const input = inputOf(row, fixtures)
537
- if (input === undefined) return []
554
+ if (input === undefined) return { cases: [], notes: [] }
538
555
  const seed = fixtures.seeds[row.id]
539
- return Object.entries(row.requirement.capabilities).map(([name, { action, access }]) => {
556
+ const { capabilities } = row.requirement
557
+ const cases: Case[] = []
558
+ const notes: string[] = []
559
+ for (const [name, { action, access }] of Object.entries(capabilities)) {
540
560
  const args = `${quote(row.id)}, ${quote(name)}, ${renderSample(input)}${seed === undefined ? '' : `, ${renderSample(seed)}`}`
541
561
  const call = `await kit.capability(${args})`
542
562
  if (access.form === 'over') {
543
- return testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`)
563
+ const ruledOutBy = deniedCaseRuledOutBy(capabilities, name, artifact.dimensions)
564
+ if (ruledOutBy === undefined) {
565
+ cases.push(testCase(`${row.id}: a caller without ${action} (capability ${name}) is 403`, `expect(${call}).toEqual({ status: 403 })`))
566
+ } else {
567
+ notes.push(
568
+ `${row.id}: capability ${name} has no denied case: ${ruledOutBy} needs ${action} in a related dimension, so every caller that passes it is answered the list`,
569
+ )
570
+ }
571
+ continue
544
572
  }
545
573
  const status = access.form === 'on' ? 404 : 403
546
- return testCase(
547
- `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
548
- `expect(${call}).toEqual({ status: ${status} })`,
574
+ cases.push(
575
+ testCase(
576
+ `${row.id}: the ${access.dimension} of another scope as capability ${name} is ${status}`,
577
+ `expect(${call}).toEqual({ status: ${status} })`,
578
+ ),
549
579
  )
550
- })
580
+ }
581
+ return { cases, notes }
551
582
  }
552
583
 
553
584
  /**
@@ -569,20 +600,24 @@ const publicCases = (row: EndpointRow, artifact: ContractArtifact, fixtures: End
569
600
  ]
570
601
  }
571
602
 
603
+ /** The endpoints of the artifact by id, the order of their cases. */
604
+ const sortedEndpoints = (artifact: ContractArtifact): readonly EndpointRow[] =>
605
+ [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
606
+
572
607
  /** The endpoint access test of the application, or `undefined` when no endpoint has an access form to test. */
573
608
  const endpointTestBody = (
574
609
  artifact: ContractArtifact,
575
610
  policies: Policies,
576
611
  fixtures: EndpointFixtures,
577
612
  dialect: ApplicationDialect,
578
- ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
579
- const cases = [...artifact.endpoints].sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).flatMap((
580
- row,
581
- ) => [
582
- ...endpointCases(row, artifact, policies, fixtures),
583
- ...capabilityCases(row, fixtures),
584
- ...publicCases(row, artifact, fixtures),
585
- ])
613
+ ): { readonly body: string; readonly cases: readonly string[]; readonly notes: readonly string[] } | undefined => {
614
+ const cases: Case[] = []
615
+ const notes: string[] = []
616
+ for (const row of sortedEndpoints(artifact)) {
617
+ const capability = capabilityCases(row, artifact, fixtures)
618
+ cases.push(...endpointCases(row, artifact, policies, fixtures), ...capability.cases, ...publicCases(row, artifact, fixtures))
619
+ notes.push(...capability.notes)
620
+ }
586
621
  if (cases.length === 0) return undefined
587
622
  const database = testDatabaseLines(dialect, '../../db/migrations/')
588
623
  const body = [
@@ -592,6 +627,7 @@ const endpointTestBody = (
592
627
  '// issuer, asks for its own object. A handler bug that needs other data or another order is beyond them; the state a',
593
628
  '// precondition needs is a seed in endpoint-access.fixtures.ts.',
594
629
  '// Do not edit: @fabrika/check compares this file with what the scaffold writes; rerun it after a contract change.',
630
+ ...notes.map((note) => `// Not checked: ${note}.`),
595
631
  '',
596
632
  "import { afterAll, describe, endpointAccessKit, expect, test } from '@fabrika/app/testing/isolation'",
597
633
  database.kit,
@@ -609,13 +645,12 @@ const endpointTestBody = (
609
645
  '}',
610
646
  '',
611
647
  ].join('\n')
612
- return { body, cases: cases.map((item) => item.name) }
648
+ return { body, cases: cases.map((item) => item.name), notes }
613
649
  }
614
650
 
615
- const generated = async ({ body, cases }: { readonly body: string; readonly cases: readonly string[] }): Promise<GeneratedTest> => ({
616
- text: `${await generatedTestHeader(body)}\n${body}`,
617
- cases,
618
- })
651
+ const generated = async (
652
+ { body, cases, notes = [] }: { readonly body: string; readonly cases: readonly string[]; readonly notes?: readonly string[] },
653
+ ): Promise<GeneratedTest> => ({ text: `${await generatedTestHeader(body)}\n${body}`, cases, notes })
619
654
 
620
655
  /**
621
656
  * Every test the scaffold writes for these policies and, when the application has a contract, its artifact; by path.
package/src/trust.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type { Finding } from './finding'
6
6
  import { parseJsonc } from './jsonc'
7
- import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, joinRelative } from './layout'
7
+ import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, isToolModule, joinRelative } from './layout'
8
8
  import { isKey, parseToml } from './toml'
9
9
 
10
10
  /** Packages whose exports the reader trusts by name, and the packages they rely on. */
@@ -141,11 +141,15 @@ function checkTsconfig(path: string, text: string, files: ReadonlyMap<string, st
141
141
  }
142
142
  }
143
143
 
144
- /** A test preload must be a checked application file: a skipped or generated one runs unchecked during the build. */
144
+ /**
145
+ * A test preload must be a checked application file: a skipped or generated one runs unchecked during the build, and a
146
+ * developer's tool is not checked as application code.
147
+ */
145
148
  const isCheckedTestPreload = (target: string): boolean => {
146
149
  if (!target.startsWith('./')) return false
147
150
  const segments = target.slice(2).split('/')
148
- return segments[0] !== 'fabrika' && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
151
+ return segments[0] !== 'fabrika' && !isToolModule(target.slice(2))
152
+ && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
149
153
  && isSourceFile(target)
150
154
  }
151
155
 
@@ -180,7 +184,7 @@ function checkBunfig(text: string, report: (needle: string, message: string, all
180
184
  report(
181
185
  at(entry.line),
182
186
  'a test preload outside the checked application files runs unchecked in the platform build',
183
- "'./<path>' of a source file the checker reads, outside fabrika/, dist/, node_modules/ and dot directories",
187
+ "'./<path>' of a source file the checker reads, outside fabrika/, tools/, dist/, node_modules/ and dot directories",
184
188
  )
185
189
  }
186
190
  }
@@ -1,5 +1,6 @@
1
1
  import { type Finding } from './finding';
2
2
  import type { PackedSet } from './packed';
3
+ import { type MigrationBase } from './rules/migration-history';
3
4
  export interface CheckInput {
4
5
  /** The application's root directory. */
5
6
  readonly root: string;
@@ -7,6 +8,8 @@ export interface CheckInput {
7
8
  readonly files?: ReadonlyMap<string, string>;
8
9
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
9
10
  readonly packed?: PackedSet;
11
+ /** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
12
+ readonly migrationBase?: MigrationBase;
10
13
  }
11
14
  export interface ApplicationTree {
12
15
  readonly files: ReadonlyMap<string, string>;
@@ -1,6 +1,6 @@
1
1
  import type { AstNode, Position } from './ast';
2
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-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
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", "migration-refused", "backup-schema", "migration-edited", "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", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
4
4
  /** Rules that report a step out of the application architecture. */
5
5
  export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
6
6
  /**
@@ -9,7 +9,7 @@ export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cr
9
9
  * Cloudflare mutation that waits for an outside call inside the object's transaction.
10
10
  */
11
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-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "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", "migration-refused", "backup-schema", "migration-edited", "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", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
13
13
  export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number];
14
14
  export type HintRuleId = (typeof HINT_RULE_IDS)[number];
15
15
  export type RuleId = (typeof RULE_IDS)[number];
@@ -2,6 +2,8 @@ export { type ApplicationTree, checkApplication, type CheckInput, readApplicatio
2
2
  export { type ApplicationDialect, applicationDialect } from './dialect';
3
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding';
4
4
  export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout';
5
+ export { readMigrationBase } from './migration-base';
5
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed';
7
+ export type { MigrationBase } from './rules/migration-history';
6
8
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests';
7
9
  export { ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, type GeneratedTest, generatedTests, missingEndpointFixtures, POLICY_TESTS_DIR, policyTestPath, scaffoldInputs, } from './scaffold';
@@ -36,6 +36,11 @@ export declare const SLICE_QUERIES_FILE = "queries.ts";
36
36
  export declare const SPA_DIR = "web/";
37
37
  /** The server half of an application: its modules run in the application's process. */
38
38
  export declare const SERVER_DIR = "src/";
39
+ /**
40
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
41
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
42
+ */
43
+ export declare const TOOLS_DIR = "tools/";
39
44
  /** Build output, installed packages and tool state are not application source and are never read. */
40
45
  export declare const isIgnoredSegment: (segment: string) => boolean;
41
46
  /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
@@ -44,6 +49,8 @@ export declare const isSourceFile: (path: string) => boolean;
44
49
  export declare const isTestFile: (path: string) => boolean;
45
50
  /** A module that runs in the application's server process: under `src/`, not a test. */
46
51
  export declare const isServerModule: (path: string) => boolean;
52
+ /** A module under `tools/`, tests included. */
53
+ export declare const isToolModule: (path: string) => boolean;
47
54
  export declare const isJsonFile: (path: string) => boolean;
48
55
  /** Whether the checker reads this file at all. */
49
56
  export declare const isCheckedFile: (path: string) => boolean;
@@ -0,0 +1,9 @@
1
+ import type { MigrationBase } from './rules/migration-history';
2
+ /**
3
+ * The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
4
+ * the merge base so that migrations the default branch added since the branch forked are not read as deleted.
5
+ * `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
6
+ */
7
+ export declare const readMigrationBase: (root: string, ref?: string) => Promise<MigrationBase | {
8
+ readonly skipped: string;
9
+ } | null>;
@@ -1,4 +1,4 @@
1
- import { type ContractArtifact } from '@fabrika/auth-core';
1
+ import type { ContractArtifact } from '@fabrika/auth-core';
2
2
  import type { Finding } from '../finding';
3
3
  /**
4
4
  * What an application on Cloudflare cannot declare (ADR-0065): a file kind that scans, because no scanner runs there; a
@@ -0,0 +1,12 @@
1
+ import type { Finding } from '../finding';
2
+ /** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
3
+ export interface MigrationBase {
4
+ /** How the commit is named to the author, such as `origin/main`. */
5
+ readonly ref: string;
6
+ readonly files: ReadonlyMap<string, string>;
7
+ }
8
+ /**
9
+ * Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
10
+ * removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
11
+ */
12
+ export declare const checkMigrationHistory: (files: ReadonlyMap<string, string>, base: MigrationBase) => Finding[];
@@ -0,0 +1,13 @@
1
+ import type { Finding } from '../finding';
2
+ /**
3
+ * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
4
+ * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
5
+ * checked, applied or not: the checker does not know which an environment holds.
6
+ */
7
+ export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string) => Finding[];
8
+ /**
9
+ * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
10
+ * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
11
+ * after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
12
+ */
13
+ export declare const checkBackupPlan: (files: ReadonlyMap<string, string>) => Promise<Finding[]>;
@@ -28,5 +28,7 @@ export declare const crossAppFetchMessage: (target: string) => {
28
28
  };
29
29
  /** Whether an expression reaches a prototype: through `.prototype`, `.__proto__` or `Object.getPrototypeOf(…)`. */
30
30
  export declare const touchesPrototype: (node: AstNode | undefined) => boolean;
31
+ /** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
32
+ export declare const checkKeyLiteralNode: (node: AstNode, report: Report) => void;
31
33
  /** The rules that read one node at a time, for every source file. */
32
34
  export declare const checkRuntimeNode: (node: AstNode, ancestors: readonly AstNode[], context: SourceContext) => void;
@@ -1,5 +1,5 @@
1
1
  import { type AstNode } from '../ast';
2
- import { type Report } from '../finding';
2
+ import { type Finding, type Report } from '../finding';
3
3
  import type { ModuleReference } from '../references';
4
4
  import { type ImportMappings } from '../resolution';
5
5
  /** The rules of the application architecture (docs/reference/application-architecture.md): four refusals and the hints. */
@@ -20,6 +20,11 @@ export interface StructureGraph {
20
20
  readonly mappings: ImportMappings;
21
21
  readonly referencesOf: (path: string) => readonly ModuleReference[];
22
22
  }
23
+ /**
24
+ * A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
25
+ * load by its name, past `tool-import`, which judges the files an import resolves to.
26
+ */
27
+ export declare const checkToolPackages: (paths: readonly string[]) => Finding[];
23
28
  /** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
24
29
  export declare const checkStructureReferences: (graph: StructureGraph, place: StructurePlace, report: Report) => void;
25
30
  /** A `<x>.<builder>(…).handle(…)` call: the builder's name, its call (whose arguments hold the options) and `.handle`. */
@@ -9,6 +9,8 @@ export declare const policyTestPath: (table: string) => string;
9
9
  export interface GeneratedTest {
10
10
  readonly text: string;
11
11
  readonly cases: readonly string[];
12
+ /** What the test cannot check, one line each, which `fabrika db test-scaffold` prints: a ruled-out capability case. */
13
+ readonly notes: readonly string[];
12
14
  }
13
15
  type Policies = Readonly<Record<string, TablePolicyArtifact>>;
14
16
  /**