@fabrika/check 0.9.0-dev.12 → 0.9.0-dev.14

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-dev.12",
3
+ "version": "0.9.0-dev.14",
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-dev.12",
51
- "@fabrika/auth-core": "0.9.0-dev.12",
52
- "@fabrika/db": "0.9.0-dev.12",
53
- "@fabrika/operations-contract": "0.9.0-dev.12",
54
- "@fabrika/platform-node": "0.9.0-dev.12",
50
+ "@fabrika/app": "0.9.0-dev.14",
51
+ "@fabrika/auth-core": "0.9.0-dev.14",
52
+ "@fabrika/db": "0.9.0-dev.14",
53
+ "@fabrika/operations-contract": "0.9.0-dev.14",
54
+ "@fabrika/platform-node": "0.9.0-dev.14",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/ast.ts CHANGED
@@ -167,17 +167,61 @@ export const isValueReference = (node: AstNode, parent: AstNode | undefined): bo
167
167
  }
168
168
  }
169
169
 
170
+ /**
171
+ * A node's line and column (from 1), as the parser counts them, for a tree `parseModule` returns: its `loc` is the
172
+ * start of its line (`lineLocations`). A tree parsed any other way has no such `loc` and reads as 1:1.
173
+ */
170
174
  export const positionOf = (node: AstNode): Position => {
171
175
  const loc = node['loc']
172
- if (isRecord(loc)) {
173
- const start = loc['start']
174
- if (isRecord(start) && typeof start['line'] === 'number' && typeof start['column'] === 'number') {
175
- return { line: start['line'], column: start['column'] + 1 }
176
- }
176
+ const start = node['start']
177
+ if (isRecord(loc) && typeof loc['line'] === 'number' && typeof loc['offset'] === 'number' && typeof start === 'number') {
178
+ return { line: loc['line'], column: start - loc['offset'] + 1 }
177
179
  }
178
180
  return { line: 1, column: 1 }
179
181
  }
180
182
 
183
+ /** Where a line starts: a line break is the parser's (`\r\n`, `\n`, `\r`, U+2028, U+2029). */
184
+ interface LineStart {
185
+ readonly line: number
186
+ readonly offset: number
187
+ }
188
+
189
+ const LINE_BREAK = /\r\n|[\n\r\u2028\u2029]/g
190
+
191
+ const isMutableNode = (value: unknown): value is Record<string, unknown> =>
192
+ typeof value === 'object' && value !== null && !Array.isArray(value) && 'type' in value && typeof value.type === 'string'
193
+
194
+ /**
195
+ * Replaces the parser's location of every node below `roots` (an object and two positions per node) with the start of
196
+ * the node's line, one object per line, which `positionOf` reads with the node's offset. The syntax trees of a
197
+ * contract are most of the memory its reader holds, and these locations were the largest part of them.
198
+ */
199
+ function lineLocations(text: string, roots: readonly unknown[]): void {
200
+ const lines: LineStart[] = [{ line: 1, offset: 0 }]
201
+ for (const match of text.matchAll(LINE_BREAK)) lines.push({ line: lines.length + 1, offset: match.index + match[0].length })
202
+ const lineAt = (offset: number): LineStart | undefined => {
203
+ let low = 0
204
+ let high = lines.length - 1
205
+ while (low < high) {
206
+ const middle = (low + high + 1) >> 1
207
+ if ((lines[middle]?.offset ?? 0) <= offset) low = middle
208
+ else high = middle - 1
209
+ }
210
+ return lines[low]
211
+ }
212
+ const pending: unknown[] = [...roots]
213
+ while (pending.length > 0) {
214
+ const value = pending.pop()
215
+ if (Array.isArray(value)) {
216
+ for (const item of value) pending.push(item)
217
+ } else if (isMutableNode(value)) {
218
+ const start = value['start']
219
+ value['loc'] = typeof start === 'number' ? lineAt(start) : undefined
220
+ for (const [key, child] of Object.entries(value)) if (!NON_CHILD_KEYS.has(key) && typeof child === 'object') pending.push(child)
221
+ }
222
+ }
223
+ }
224
+
181
225
  /** Visits every node below `root`, depth first, with the chain of its ancestors (nearest last); `'skip'` prunes a subtree. */
182
226
  export const walk = (root: AstNode, visit: (node: AstNode, ancestors: readonly AstNode[]) => 'skip' | undefined | void): void => {
183
227
  const ancestors: AstNode[] = []
@@ -245,9 +289,11 @@ export const nodeDepth = (root: AstNode): number => {
245
289
 
246
290
  export const parseModule = (file: string, text: string): ParseResult => {
247
291
  try {
248
- const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file) })
292
+ // Nothing reads a comment from the node it is attached to; `ast.comments` lists them all.
293
+ const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file), attachComment: false })
249
294
  const program: unknown = ast.program
250
295
  if (!isNode(program)) return { ok: false, message: 'the parser returned no program', position: { line: 1, column: 1 } }
296
+ lineLocations(text, [program, ast.comments])
251
297
  return { ok: true, module: { file, program, comments: readComments(ast.comments), bytes: utf8Bytes(text) } }
252
298
  } catch (error) {
253
299
  const message = error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : 'unparseable source'
package/src/check.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
- import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry } from '@fabrika/auth-core'
3
- import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
2
+ import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
3
+ import { accessTables, 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'
6
6
  import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
@@ -36,11 +36,14 @@ import { checkJsonStrings } from './rules/json'
36
36
  import { checkLiteralGraph } from './rules/literal'
37
37
  import { checkMigrationHistory, type MigrationBase } from './rules/migration-history'
38
38
  import {
39
+ type AccessKey,
40
+ checkAccessViewKeys,
39
41
  checkConflictIndexes,
40
42
  checkCurrentTimestampDefaults,
41
43
  checkFileColumnMigrations,
42
44
  checkMigrationNames,
43
45
  checkSqliteFrameworkNames,
46
+ checkSqliteViewTriggers,
44
47
  type ConflictInsert,
45
48
  type FileColumn,
46
49
  } from './rules/migrations'
@@ -54,6 +57,15 @@ import { checkComments, checkTypeNode } from './rules/types'
54
57
  import { moduleSlice, sliceFinding } from './slice'
55
58
  import { BUNFIG_FILE, checkTrustedResolution } from './trust'
56
59
 
60
+ /** Every table that names an access view, with its key (ADR-0076). */
61
+ const accessKeys = (policies: TablePolicies): AccessKey[] =>
62
+ Object.entries(policies).flatMap(([table, policy]) => {
63
+ const views = Object.values(policy.access ?? {}).map((access) => access.view)
64
+ const scope = policy.scope
65
+ const key = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app' ? scope.key : undefined
66
+ return views.length === 0 || key === undefined ? [] : [{ table, key, views: [...new Set(views)].sort() }]
67
+ })
68
+
57
69
  /** Every file column the table policies declare, with its kind. */
58
70
  const fileColumns = (policies: TablePolicies): FileColumn[] =>
59
71
  Object.entries(policies).flatMap(([table, policy]) => Object.entries(policy.files ?? {}).map(([column, kind]) => ({ table, column, kind })))
@@ -190,6 +202,8 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
190
202
  interface CompiledReach {
191
203
  readonly procedures: ReadonlySet<string>
192
204
  readonly egress: readonly EgressEntry[]
205
+ /** Some cron job declares `egress: 'public'`. */
206
+ readonly publicEgress: boolean
193
207
  }
194
208
 
195
209
  /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
@@ -210,22 +224,27 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
210
224
  return {
211
225
  procedures: new Set(procedures.map((row) => row.id)),
212
226
  egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
213
- (reach.egress ?? []).flatMap((value) => {
227
+ (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress).flatMap((value) => {
214
228
  const parsed = parseEgressEntry(value)
215
229
  return parsed.ok ? [parsed.entry] : []
216
230
  })
217
231
  ),
232
+ publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
218
233
  }
219
234
  }
220
235
 
221
236
  /**
222
237
  * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
223
- * not accepted, nor an interpolated label a pattern does not cover), and every one stands when the contract does not
224
- * compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime guard on `fetch`
225
- * still checks the site that runs.
238
+ * not accepted, nor an interpolated label a pattern does not cover) and, where a cron job declares `egress: 'public'`,
239
+ * when public egress would refuse it: another scheme, or a host its URL alone refuses (an IP address, a local or
240
+ * internal name, a port). A prefix that ends inside the host is then the runtime's to judge. Every one stands when the
241
+ * contract does not compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime
242
+ * guard on `fetch` still checks the site that runs.
226
243
  */
227
244
  const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
228
- ...dependent.fetches.filter((fetch) => reach === null || !isDeclaredFetch(fetch, reach.egress)).map(({ finding }) => finding),
245
+ ...dependent.fetches.filter((fetch) =>
246
+ reach === null || (!isDeclaredFetch(fetch, reach.egress) && !(reach.publicEgress && isPublicTarget(fetch.target)))
247
+ ).map(({ finding }) => finding),
229
248
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
230
249
  ]
231
250
 
@@ -248,6 +267,19 @@ const urlOf = (value: string): URL | null => {
248
267
  }
249
268
  }
250
269
 
270
+ /** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
271
+ const isPublicTarget = (target: string): boolean => {
272
+ const scheme = /^(https?):\/\//i.exec(target)
273
+ if (scheme === null) return false
274
+ const rest = target.slice(scheme[0].length)
275
+ if (!/[/?#]/.test(rest)) return true
276
+ try {
277
+ return publicEgressRefusal(new URL(target)) === null
278
+ } catch {
279
+ return false
280
+ }
281
+ }
282
+
251
283
  /** Runs every rule over one application and returns the findings in file, line and column order. */
252
284
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
253
285
  const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
@@ -317,17 +349,22 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
317
349
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
318
350
  const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
319
351
  findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
320
- if (artifact !== null) findings.push(...checkMigrationClassification(tree.files, artifact.app))
321
- if (applicationDialect(tree.files) === 'sqlite') {
352
+ const dialect = applicationDialect(tree.files)
353
+ if (artifact !== null) {
354
+ findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables), dialect))
355
+ }
356
+ if (dialect === 'sqlite') {
322
357
  if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
323
358
  findings.push(...checkCurrentTimestampDefaults(tree.files))
324
359
  findings.push(...checkSqliteFrameworkNames(tree.files))
360
+ findings.push(...checkSqliteViewTriggers(tree.files))
325
361
  findings.push(...(await checkBackupPlan(tree.files)))
326
362
  }
327
363
  if (declaredTables !== null) {
328
364
  const policies = tablePolicies(declaredTables)
329
365
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
330
366
  findings.push(...checkConflictIndexes(tree.files, new Set(Object.keys(policies)), dependent.inserts))
367
+ findings.push(...checkAccessViewKeys(tree.files, accessKeys(policies)))
331
368
  }
332
369
  const bunfig = tree.files.get(BUNFIG_FILE)
333
370
  if (bunfig !== undefined) findings.push(...checkTestSuiteConfig(bunfig))
package/src/contract.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { type AnyContract, compileContract } from '@fabrika/app/contract'
6
6
  import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core'
7
7
  import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
8
- import { importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
8
+ import { child, children, importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
9
9
  import { type Finding, formatFinding } from './finding'
10
10
  import { ModuleGraph } from './graph'
11
11
  import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
@@ -19,6 +19,7 @@ import { parseShellModule } from './slice'
19
19
  import { checkTrustedResolution } from './trust'
20
20
 
21
21
  export { ContractError } from '@fabrika/app/contract'
22
+ export { accessTables } from '@fabrika/db/tables'
22
23
  export { type Finding, formatFinding } from './finding'
23
24
  export { contractReaderInputs } from './inputs'
24
25
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
@@ -228,7 +229,7 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
228
229
  if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
229
230
  return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
230
231
  }
231
- modules.set(path, parsed.module)
232
+ modules.set(path, withoutTypeDeclarations(parsed.module))
232
233
  for (const specifier of importedSpecifiers(parsed.module)) {
233
234
  const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
234
235
  if (resolution?.kind === 'file') {
@@ -241,6 +242,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
241
242
  return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
242
243
  }
243
244
 
245
+ /** Top-level type declarations: the module index binds no name to them, and the literal rule passes over them. */
246
+ const TYPE_DECLARATIONS = new Set(['TSTypeAliasDeclaration', 'TSInterfaceDeclaration'])
247
+
248
+ /** The module without its top-level type declarations, which the reader would otherwise hold until it is done. */
249
+ function withoutTypeDeclarations(module: ParsedModule): ParsedModule {
250
+ const body = children(module.program, 'body').filter((statement) => {
251
+ const declaration = statement?.type === 'ExportNamedDeclaration' ? child(statement, 'declaration') : statement
252
+ return declaration === null || declaration === undefined || !TYPE_DECLARATIONS.has(declaration.type)
253
+ })
254
+ return { ...module, program: { ...module.program, body } }
255
+ }
256
+
244
257
  function missingFile(file: string): Finding {
245
258
  return {
246
259
  file,
package/src/finding.ts CHANGED
@@ -22,6 +22,7 @@ export const REFUSAL_RULE_IDS = [
22
22
  'cross-app-fetch',
23
23
  'url-endpoint',
24
24
  'on-conflict-index',
25
+ 'access-view-key',
25
26
  'key-literal',
26
27
  'client-identity',
27
28
  'sensitive-log',
@@ -48,6 +49,7 @@ export const REFUSAL_RULE_IDS = [
48
49
  'cloudflare-job-segment',
49
50
  'cloudflare-current-timestamp',
50
51
  'cloudflare-framework-name',
52
+ 'cloudflare-view-trigger',
51
53
  ] as const
52
54
 
53
55
  /** Rules that report a step out of the application architecture. */
@@ -216,7 +216,9 @@ class SurfaceReader {
216
216
  'members',
217
217
  'directory',
218
218
  'terminal',
219
+ 'relations',
219
220
  ])
221
+ const relations = fields.get('relations')
220
222
  const locale = fields.get('locale')
221
223
  const displayName = fields.get('displayName')
222
224
  const mail = fields.get('mail')
@@ -237,6 +239,13 @@ class SurfaceReader {
237
239
  dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
238
240
  actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
239
241
  roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
242
+ ...(relations === undefined
243
+ ? {}
244
+ : {
245
+ relations: this.#each(entries(relations, value, 'relations'), (name, relation) => ({
246
+ dimension: text(strictFields(relation, `relation '${name}'`, ['dimension'], []).get('dimension'), relation, 'dimension'),
247
+ })),
248
+ }),
240
249
  }
241
250
  }
242
251
 
@@ -283,16 +292,18 @@ class SurfaceReader {
283
292
  }
284
293
 
285
294
  #role(name: string, value: LiteralValue): RoleDef<string, string, string> {
286
- const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external'])
295
+ const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external', 'via'])
287
296
  const member = fields.get('member')
288
297
  const memberFields = member === undefined ? undefined : strictFields(member, `role '${name}' member`, ['scope', 'assignableBy'], [])
289
298
  const external = fields.get('external')
299
+ const via = fields.get('via')
290
300
  return {
291
301
  grants: texts(fields.get('grants'), value, 'grants'),
292
302
  member: memberFields === undefined
293
303
  ? undefined
294
304
  : { scope: text(memberFields.get('scope'), value, 'scope'), assignableBy: texts(memberFields.get('assignableBy'), value, 'assignableBy') },
295
305
  ...(external === undefined ? {} : { external: externalOf(external) }),
306
+ ...(via === undefined ? {} : { via: this.#each(entries(via, value, 'via'), (_, actions) => texts(actions, value, 'via')) }),
296
307
  }
297
308
  }
298
309
 
@@ -801,7 +812,7 @@ function plain(value: LiteralValue | undefined): unknown {
801
812
  }
802
813
 
803
814
  const DECLARED_ALLOWED =
804
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>']"
815
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>'] | 'public' (a cron job)"
805
816
 
806
817
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
807
818
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -83,7 +83,19 @@ type Role = { readonly callback: Kit } | { readonly procedures: Kit } | null
83
83
  const callbackKit = (kind: BuilderKind): Kit => (kind === 'shell' ? 'shell' : kind === 'endpoints' ? 'endpoints' : 'surface')
84
84
 
85
85
  /** The fields `defineVocabulary` copies from its argument, in its order. */
86
- const VOCABULARY_SECTIONS = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail', 'members', 'directory', 'terminal'] as const
86
+ const VOCABULARY_SECTIONS = [
87
+ 'app',
88
+ 'dimensions',
89
+ 'actions',
90
+ 'roles',
91
+ 'relations',
92
+ 'locale',
93
+ 'displayName',
94
+ 'mail',
95
+ 'members',
96
+ 'directory',
97
+ 'terminal',
98
+ ] as const
87
99
 
88
100
  const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
89
101
 
@@ -1,5 +1,5 @@
1
1
  import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
2
- import type { ContractArtifact } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, type DeclaredEgress, PUBLIC_EGRESS } 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?: readonly string[]; readonly connect: readonly string[] }): string[] => [
18
- ...(reach.egress ?? []).map((origin) => `egress ${origin}`),
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}`)),
19
19
  ...reach.connect.map((name) => `connect ${name}`),
20
20
  ]
21
21
 
@@ -13,7 +13,7 @@ import {
13
13
  upperWord,
14
14
  } from '@fabrika/platform-node/sql'
15
15
  import type { Finding } from '../finding'
16
- import { MIGRATIONS_DIR } from '../layout'
16
+ import { MIGRATIONS_DIR, TABLES_FILE } from '../layout'
17
17
 
18
18
  const MIGRATION_NAME = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_[a-z0-9]+(?:_[a-z0-9]+)*\.sql$/
19
19
  const ALLOWED = 'db/migrations/YYYYMMDDHHMMSS_slug.sql with a lowercase snake_case slug, as fabrika db new <slug> writes it'
@@ -56,7 +56,7 @@ export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>
56
56
  const findings: Finding[] = []
57
57
  for (const [path, sql] of files) {
58
58
  if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
59
- for (const { tokens } of topLevelStatements(sql)) {
59
+ for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
60
60
  tokens.forEach((token, index) => {
61
61
  if (upperWord(token) !== 'DEFAULT') return
62
62
  const value = isPunct(tokens[index + 1], '(') ? tokens[index + 2] : tokens[index + 1]
@@ -106,6 +106,37 @@ export const checkSqliteFrameworkNames = (files: ReadonlyMap<string, string>): F
106
106
  return findings
107
107
  }
108
108
 
109
+ /**
110
+ * A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
111
+ * takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
112
+ */
113
+ export const checkSqliteViewTriggers = (files: ReadonlyMap<string, string>): Finding[] => {
114
+ const findings: Finding[] = []
115
+ for (const [path, sql] of files) {
116
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
117
+ for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
118
+ if (upperWord(tokens[0]) !== 'CREATE') continue
119
+ const at = skipWords(tokens, skipWords(tokens, 1, 'TEMP'), 'TEMPORARY')
120
+ if (upperWord(tokens[at]) !== 'TRIGGER') continue
121
+ for (let index = at + 1; index < tokens.length && upperWord(tokens[index]) !== 'ON'; index++) {
122
+ const token = tokens[index]
123
+ if (token === undefined || upperWord(token) !== 'INSTEAD' || upperWord(tokens[index + 1]) !== 'OF') continue
124
+ findings.push({
125
+ file: path,
126
+ line: token.line,
127
+ column: 1,
128
+ severity: 'refusal',
129
+ rule: 'cloudflare-view-trigger',
130
+ message: 'an INSTEAD OF trigger makes a view writable, and a view is read-only (ADR-0072)',
131
+ allowed: 'a view without triggers, written through its source tables',
132
+ })
133
+ break
134
+ }
135
+ }
136
+ }
137
+ return findings
138
+ }
139
+
109
140
  /** A declared file column: `table.column` holds files of `kind`. */
110
141
  export interface FileColumn {
111
142
  readonly table: string
@@ -326,6 +357,108 @@ export const checkConflictIndexes = (
326
357
  return checked.filter((insert) => !present.has(`${insert.table}(${keyOf(insert.columns)})`)).map((insert) => insert.finding)
327
358
  }
328
359
 
360
+ /** A table that names an access view under `key` (ADR-0076). */
361
+ export interface AccessKey {
362
+ readonly table: string
363
+ readonly key: string
364
+ readonly views: readonly string[]
365
+ }
366
+
367
+ /**
368
+ * A table that names an access view needs its key unique on its own, or the view's `row` names several rows at once
369
+ * (ADR-0076 section 1). A view as the target keeps its key unique by its SQL; any other name no migration creates as a
370
+ * table is refused, so a statement the reader does not follow fails closed.
371
+ */
372
+ export const checkAccessViewKeys = (files: ReadonlyMap<string, string>, keys: readonly AccessKey[]): Finding[] => {
373
+ if (keys.length === 0) {
374
+ return []
375
+ }
376
+ const unique: UniqueIndex[] = []
377
+ const created = new Map<string, { readonly path: string; readonly line: number }>()
378
+ const views = new Set<string>()
379
+ const migrations = [...files.entries()]
380
+ .filter(([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'))
381
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
382
+ for (const [path, sql] of migrations) {
383
+ for (const statement of topLevelStatements(sql)) {
384
+ readUniqueIndexes(statement.tokens, unique)
385
+ const table = createdTable(statement.tokens)
386
+ if (table !== undefined) created.set(table, { path, line: statement.line })
387
+ const view = createdView(statement.tokens)
388
+ if (view !== undefined) views.add(view)
389
+ for (const dropped of droppedTables(statement.tokens)) created.delete(dropped)
390
+ const renamed = renamedTable(statement.tokens)
391
+ const at = renamed === undefined ? undefined : created.get(renamed.from)
392
+ if (renamed !== undefined && at !== undefined) {
393
+ created.delete(renamed.from)
394
+ created.set(renamed.to, at)
395
+ }
396
+ }
397
+ }
398
+ const findings: Finding[] = []
399
+ for (const { table, key, views: named } of keys) {
400
+ const at = created.get(table)
401
+ if (at === undefined && views.has(table)) continue
402
+ if (at !== undefined && unique.some((index) => index.table === table && index.columns.length === 1 && index.columns[0] === key)) continue
403
+ findings.push({
404
+ file: at?.path ?? TABLES_FILE,
405
+ line: at?.line ?? 1,
406
+ column: 1,
407
+ severity: 'refusal',
408
+ rule: 'access-view-key',
409
+ message: at === undefined
410
+ ? `${table} names the access view ${named.join(', ')}, and no migration creates ${table} as a table or a view`
411
+ : `${table} names the access view ${named.join(', ')}, and no migration makes its key ${key} unique on its own`,
412
+ allowed: `${key} as the primary key of ${table}, or create unique index ${table}_${key} on ${table} (${key})`,
413
+ })
414
+ }
415
+ return findings
416
+ }
417
+
418
+ /** The table a `CREATE [UNLOGGED | TEMP | TEMPORARY] TABLE` statement creates. */
419
+ function createdTable(tokens: readonly SqlToken[]): string | undefined {
420
+ if (upperWord(tokens[0]) !== 'CREATE') return undefined
421
+ const at = skipOne(tokens, 1, 'UNLOGGED', 'TEMP', 'TEMPORARY')
422
+ if (upperWord(tokens[at]) !== 'TABLE') return undefined
423
+ return objectNameAt(tokens, skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS'))?.name
424
+ }
425
+
426
+ /** The view a `CREATE [OR REPLACE] [TEMP] [MATERIALIZED] VIEW` statement creates. */
427
+ function createdView(tokens: readonly SqlToken[]): string | undefined {
428
+ if (upperWord(tokens[0]) !== 'CREATE') return undefined
429
+ const at = skipOne(tokens, skipOne(tokens, skipWords(tokens, 1, 'OR', 'REPLACE'), 'TEMP', 'TEMPORARY'), 'MATERIALIZED')
430
+ if (upperWord(tokens[at]) !== 'VIEW') return undefined
431
+ return objectNameAt(tokens, skipWords(tokens, at + 1, 'IF', 'NOT', 'EXISTS'))?.name
432
+ }
433
+
434
+ /** Past one of `words` at `at`, when the token there is one of them. */
435
+ function skipOne(tokens: readonly SqlToken[], at: number, ...words: readonly string[]): number {
436
+ const word = upperWord(tokens[at])
437
+ return word !== undefined && words.includes(word) ? at + 1 : at
438
+ }
439
+
440
+ /** The tables a `DROP TABLE` statement drops. */
441
+ function droppedTables(tokens: readonly SqlToken[]): string[] {
442
+ if (upperWord(tokens[0]) !== 'DROP' || upperWord(tokens[1]) !== 'TABLE') return []
443
+ const at = skipWords(tokens, 2, 'IF', 'EXISTS')
444
+ return splitAtCommas(tokens.slice(at)).flatMap((part) => objectNameAt(part, 0)?.name ?? [])
445
+ }
446
+
447
+ /** `ALTER TABLE from RENAME TO to`. */
448
+ function renamedTable(tokens: readonly SqlToken[]): { readonly from: string; readonly to: string } | undefined {
449
+ if (upperWord(tokens[0]) !== 'ALTER' || upperWord(tokens[1]) !== 'TABLE') return undefined
450
+ const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
451
+ const from = objectNameAt(tokens, at)?.name
452
+ const end = afterName(tokens, at)
453
+ if (from === undefined || end === undefined || upperWord(tokens[end]) !== 'RENAME' || upperWord(tokens[end + 1]) !== 'TO') return undefined
454
+ const to = objectNameAt(tokens, end + 2)?.name
455
+ return to === undefined ? undefined : { from, to }
456
+ }
457
+
458
+ function defaultConstraintName(table: string, primary: boolean, columns: readonly string[]): string {
459
+ return primary ? `${table}_pkey` : `${table}_${columns.join('_')}_key`
460
+ }
461
+
329
462
  interface UniqueIndex {
330
463
  readonly name: string | undefined
331
464
  readonly table: string
@@ -335,23 +468,28 @@ interface UniqueIndex {
335
468
  function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]): void {
336
469
  const verb = upperWord(tokens[0])
337
470
  const object = upperWord(tokens[1])
338
- if (verb === 'CREATE' && object === 'TABLE') {
339
- const at = skipWords(tokens, 2, 'IF', 'NOT', 'EXISTS')
471
+ const keep = (kept: (index: UniqueIndex) => boolean) => unique.splice(0, unique.length, ...unique.filter(kept))
472
+ const tableAt = verb === 'CREATE' ? skipOne(tokens, 1, 'UNLOGGED', 'TEMP', 'TEMPORARY') : 1
473
+ if (verb === 'CREATE' && upperWord(tokens[tableAt]) === 'TABLE') {
474
+ const at = skipWords(tokens, tableAt + 1, 'IF', 'NOT', 'EXISTS')
340
475
  const table = objectNameAt(tokens, at)?.name
341
476
  const open = afterName(tokens, at)
342
477
  const close = open === undefined ? undefined : closingParenthesis(tokens, open)
343
478
  if (table === undefined || open === undefined || close === undefined) return
479
+ keep((index) => index.table !== table)
344
480
  for (const element of splitAtCommas(tokens.slice(open + 1, close))) {
345
481
  readUniqueElement(table, element, unique)
346
482
  }
483
+ } else if (verb === 'DROP' && object === 'TABLE') {
484
+ const dropped = new Set(splitAtCommas(tokens.slice(skipWords(tokens, 2, 'IF', 'EXISTS'))).map((part) => objectNameAt(part, 0)?.name))
485
+ keep((index) => !dropped.has(index.table))
347
486
  } else if (verb === 'ALTER' && object === 'TABLE') {
348
487
  const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
349
488
  const table = objectNameAt(tokens, at)?.name
350
489
  const end = afterName(tokens, at)
351
490
  if (table === undefined || end === undefined) return
352
491
  for (const action of splitAtCommas(tokens.slice(end))) {
353
- if (upperWord(action[0]) !== 'ADD') continue
354
- readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
492
+ alterUnique(table, action, unique, keep)
355
493
  }
356
494
  } else if (verb === 'CREATE' && object === 'UNIQUE' && upperWord(tokens[2]) === 'INDEX') {
357
495
  const rest = tokens.slice(3)
@@ -375,7 +513,41 @@ function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]):
375
513
  }
376
514
  }
377
515
 
378
- /** A column with `UNIQUE` or `PRIMARY KEY`, or a `UNIQUE (…)` or `PRIMARY KEY (…)` table constraint. */
516
+ /**
517
+ * One action of `ALTER TABLE table`: `ADD` a unique column or constraint, `DROP CONSTRAINT` one by name, `DROP COLUMN`,
518
+ * or `RENAME` the table or a column, which the unique keys follow.
519
+ */
520
+ function alterUnique(table: string, action: readonly SqlToken[], unique: UniqueIndex[], keep: (kept: (index: UniqueIndex) => boolean) => void): void {
521
+ const verb = upperWord(action[0])
522
+ if (verb === 'ADD') {
523
+ readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
524
+ } else if (verb === 'DROP' && upperWord(action[1]) === 'CONSTRAINT') {
525
+ const name = objectNameAt(action, skipWords(action, 2, 'IF', 'EXISTS'))?.name
526
+ keep((index) => index.table !== table || index.name !== name)
527
+ } else if (verb === 'DROP') {
528
+ const column = objectNameAt(action, skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'EXISTS'))?.name
529
+ keep((index) => index.table !== table || column === undefined || !index.columns.includes(column))
530
+ } else if (verb === 'RENAME' && upperWord(action[1]) === 'TO') {
531
+ const to = objectNameAt(action, 2)?.name
532
+ if (to !== undefined) unique.splice(0, unique.length, ...unique.map((index) => (index.table === table ? { ...index, table: to } : index)))
533
+ } else if (verb === 'RENAME') {
534
+ const at = skipWords(action, 1, 'COLUMN')
535
+ const from = objectNameAt(action, at)?.name
536
+ const after = afterName(action, at)
537
+ const to = after === undefined || upperWord(action[after]) !== 'TO' ? undefined : objectNameAt(action, after + 1)?.name
538
+ if (from === undefined || to === undefined) return
539
+ unique.splice(
540
+ 0,
541
+ unique.length,
542
+ ...unique.map((index) => index.table === table ? { ...index, columns: index.columns.map((column) => (column === from ? to : column)) } : index),
543
+ )
544
+ }
545
+ }
546
+
547
+ /**
548
+ * A column with `UNIQUE` or `PRIMARY KEY`, or a `UNIQUE (…)` or `PRIMARY KEY (…)` table constraint, named as declared or
549
+ * as Postgres names it by default (`<table>_pkey`, `<table>_<columns>_key`), so a later `DROP CONSTRAINT` finds it.
550
+ */
379
551
  function readUniqueElement(table: string, element: readonly SqlToken[], unique: UniqueIndex[]): void {
380
552
  const head = upperWord(element[0])
381
553
  if (head !== undefined && TABLE_CONSTRAINTS.has(head)) {
@@ -385,12 +557,16 @@ function readUniqueElement(table: string, element: readonly SqlToken[], unique:
385
557
  const list = open === undefined ? undefined : columnList(constraint, open)
386
558
  const columns = list?.columns.filter((column) => column !== undefined) ?? []
387
559
  if (list !== undefined && columns.length > 0 && columns.length === list.columns.length) {
388
- unique.push({ name: undefined, table, columns })
560
+ const declared = head === 'CONSTRAINT' ? nameText(element[1]) : undefined
561
+ unique.push({ name: declared ?? defaultConstraintName(table, kind === 'PRIMARY', columns), table, columns })
389
562
  }
390
563
  return
391
564
  }
392
565
  const column = nameText(element[0])
393
- if (column !== undefined && depthZeroWords(element.slice(1)).some((word) => word === 'UNIQUE' || word === 'PRIMARY')) {
394
- unique.push({ name: undefined, table, columns: [column] })
566
+ const words = depthZeroWords(element.slice(1))
567
+ if (column !== undefined && words.some((word) => word === 'UNIQUE' || word === 'PRIMARY')) {
568
+ const named = element.findIndex((token) => upperWord(token) === 'CONSTRAINT')
569
+ const declared = named < 0 ? undefined : nameText(element[named + 1])
570
+ unique.push({ name: declared ?? defaultConstraintName(table, words.includes('PRIMARY'), [column]), table, columns: [column] })
395
571
  }
396
572
  }
@@ -15,6 +15,11 @@ 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
+ }
18
23
  const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
19
24
 
20
25
  const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
@@ -78,6 +83,7 @@ export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
78
83
  ...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
79
84
  ...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
80
85
  ...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
86
+ ['fetch', BUN_FETCH],
81
87
  ...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
82
88
  ])
83
89
 
@@ -6,7 +6,7 @@ import { describeOpsDumpSchema, planOpsDump } from '@fabrika/auth-core'
6
6
  import { withMigratedSqlite } from '@fabrika/db/codegen-sqlite'
7
7
  import { FRAMEWORK_MIGRATION_BUNDLE } from '@fabrika/db/migrations'
8
8
  import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
9
- import { applicationDatabaseSchema, classifyMigrations } from '@fabrika/platform-node/sql'
9
+ import { applicationDatabaseSchema, classifyMigrations, type MigrationDialect } from '@fabrika/platform-node/sql'
10
10
  import type { Finding } from '../finding'
11
11
  import { MIGRATIONS_DIR } from '../layout'
12
12
 
@@ -24,15 +24,22 @@ const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
24
24
  }).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
25
25
 
26
26
  /**
27
- * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
27
+ * Every statement Control's classifier refuses, at its file and line, against the application's access tables and in its
28
+ * dialect. Control refuses a deploy whose new migration holds
28
29
  * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
29
30
  * checked, applied or not: the checker does not know which an environment holds.
30
31
  */
31
- export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
32
+ export const checkMigrationClassification = (
33
+ files: ReadonlyMap<string, string>,
34
+ appId: string,
35
+ accessTables: readonly string[],
36
+ dialect: MigrationDialect,
37
+ ): Finding[] => {
32
38
  const texts = migrationTexts(files)
33
39
  if (texts.length === 0) return []
34
40
  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) =>
41
+ const options = { accessTables: new Set(accessTables), dialect }
42
+ return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId), options).files.flatMap((file) =>
36
43
  file.refused.map((refusal): Finding => ({
37
44
  file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
38
45
  line: refusal.line,
@@ -39,8 +39,11 @@ export interface SourceContext {
39
39
  readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
40
40
  }
41
41
 
42
- /** The global objects and `Bun`: a server module reaches the platform through the framework only. */
43
- const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun'])
42
+ /**
43
+ * The global objects, `Bun`, and `WebSocket`, a socket the egress guard on `fetch` does not see: a server module reaches
44
+ * the platform and the outside through the framework only.
45
+ */
46
+ const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun', 'WebSocket'])
44
47
 
45
48
  /**
46
49
  * The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
@@ -199,7 +202,7 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
199
202
  export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
200
203
  message: `fetch to the absolute origin '${target}' is a hand-written integration`,
201
204
  allowed:
202
- "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>' | 'https://*.<domain>'] on the site",
205
+ "a same-origin path to a declared endpoint, another application through a connector import, egress: ['<origin>' | 'https://*.<domain>'] on the site, or a public host of http(s) under a cron job's egress: 'public'",
203
206
  })
204
207
 
205
208
  const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
@@ -54,6 +54,10 @@ export declare const unwrap: (node: AstNode) => AstNode;
54
54
  export declare const memberPath: (node: AstNode) => readonly string[] | undefined;
55
55
  /** Whether an `Identifier` denotes a runtime value here, rather than a property name, a key, a label or a type. */
56
56
  export declare const isValueReference: (node: AstNode, parent: AstNode | undefined) => boolean;
57
+ /**
58
+ * A node's line and column (from 1), as the parser counts them, for a tree `parseModule` returns: its `loc` is the
59
+ * start of its line (`lineLocations`). A tree parsed any other way has no such `loc` and reads as 1:1.
60
+ */
57
61
  export declare const positionOf: (node: AstNode) => Position;
58
62
  /** Visits every node below `root`, depth first, with the chain of its ancestors (nearest last); `'skip'` prunes a subtree. */
59
63
  export declare const walk: (root: AstNode, visit: (node: AstNode, ancestors: readonly AstNode[]) => "skip" | undefined | void) => void;
@@ -5,6 +5,7 @@ import { type ParsedModule } from './ast';
5
5
  import { type Finding } from './finding';
6
6
  import { ModuleGraph } from './graph';
7
7
  export { ContractError } from '@fabrika/app/contract';
8
+ export { accessTables } from '@fabrika/db/tables';
8
9
  export { type Finding, formatFinding } from './finding';
9
10
  export { contractReaderInputs } from './inputs';
10
11
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout';
@@ -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", "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"];
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", "access-view-key", "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", "cloudflare-view-trigger"];
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", "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"];
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", "access-view-key", "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", "cloudflare-view-trigger", "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];
@@ -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
@@ -12,6 +12,11 @@ export declare const checkCurrentTimestampDefaults: (files: ReadonlyMap<string,
12
12
  * or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
13
13
  */
14
14
  export declare const checkSqliteFrameworkNames: (files: ReadonlyMap<string, string>) => Finding[];
15
+ /**
16
+ * A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
17
+ * takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
18
+ */
19
+ export declare const checkSqliteViewTriggers: (files: ReadonlyMap<string, string>) => Finding[];
15
20
  /** A declared file column: `table.column` holds files of `kind`. */
16
21
  export interface FileColumn {
17
22
  readonly table: string;
@@ -38,3 +43,15 @@ export interface ConflictInsert {
38
43
  * checked: another receiver of `insert` is no table of the data layer.
39
44
  */
40
45
  export declare const checkConflictIndexes: (files: ReadonlyMap<string, string>, tables: ReadonlySet<string>, inserts: readonly ConflictInsert[]) => Finding[];
46
+ /** A table that names an access view under `key` (ADR-0076). */
47
+ export interface AccessKey {
48
+ readonly table: string;
49
+ readonly key: string;
50
+ readonly views: readonly string[];
51
+ }
52
+ /**
53
+ * A table that names an access view needs its key unique on its own, or the view's `row` names several rows at once
54
+ * (ADR-0076 section 1). A view as the target keeps its key unique by its SQL; any other name no migration creates as a
55
+ * table is refused, so a statement the reader does not follow fails closed.
56
+ */
57
+ export declare const checkAccessViewKeys: (files: ReadonlyMap<string, string>, keys: readonly AccessKey[]) => Finding[];
@@ -1,10 +1,12 @@
1
+ import { type MigrationDialect } from '@fabrika/platform-node/sql';
1
2
  import type { Finding } from '../finding';
2
3
  /**
3
- * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
4
+ * Every statement Control's classifier refuses, at its file and line, against the application's access tables and in its
5
+ * dialect. Control refuses a deploy whose new migration holds
4
6
  * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
5
7
  * checked, applied or not: the checker does not know which an environment holds.
6
8
  */
7
- export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string) => Finding[];
9
+ export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[], dialect: MigrationDialect) => Finding[];
8
10
  /**
9
11
  * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
10
12
  * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration