@fabrika/check 0.9.0-dev.13 → 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.13",
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.13",
51
- "@fabrika/auth-core": "0.9.0-dev.13",
52
- "@fabrika/db": "0.9.0-dev.13",
53
- "@fabrika/operations-contract": "0.9.0-dev.13",
54
- "@fabrika/platform-node": "0.9.0-dev.13",
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,5 +1,5 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
- import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
3
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'
@@ -36,6 +36,8 @@ 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,
@@ -55,6 +57,15 @@ import { checkComments, checkTypeNode } from './rules/types'
55
57
  import { moduleSlice, sliceFinding } from './slice'
56
58
  import { BUNFIG_FILE, checkTrustedResolution } from './trust'
57
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
+
58
69
  /** Every file column the table policies declare, with its kind. */
59
70
  const fileColumns = (policies: TablePolicies): FileColumn[] =>
60
71
  Object.entries(policies).flatMap(([table, policy]) => Object.entries(policy.files ?? {}).map(([column, kind]) => ({ table, column, kind })))
@@ -191,6 +202,8 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
191
202
  interface CompiledReach {
192
203
  readonly procedures: ReadonlySet<string>
193
204
  readonly egress: readonly EgressEntry[]
205
+ /** Some cron job declares `egress: 'public'`. */
206
+ readonly publicEgress: boolean
194
207
  }
195
208
 
196
209
  /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
@@ -211,22 +224,27 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
211
224
  return {
212
225
  procedures: new Set(procedures.map((row) => row.id)),
213
226
  egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
214
- (reach.egress ?? []).flatMap((value) => {
227
+ (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress).flatMap((value) => {
215
228
  const parsed = parseEgressEntry(value)
216
229
  return parsed.ok ? [parsed.entry] : []
217
230
  })
218
231
  ),
232
+ publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
219
233
  }
220
234
  }
221
235
 
222
236
  /**
223
237
  * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
224
- * not accepted, nor an interpolated label a pattern does not cover), and every one stands when the contract does not
225
- * compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime guard on `fetch`
226
- * 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.
227
243
  */
228
244
  const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
229
- ...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),
230
248
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
231
249
  ]
232
250
 
@@ -249,6 +267,19 @@ const urlOf = (value: string): URL | null => {
249
267
  }
250
268
  }
251
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
+
252
283
  /** Runs every rule over one application and returns the findings in file, line and column order. */
253
284
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
254
285
  const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
@@ -318,10 +349,11 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
318
349
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
319
350
  const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
320
351
  findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
352
+ const dialect = applicationDialect(tree.files)
321
353
  if (artifact !== null) {
322
- findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables)))
354
+ findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables), dialect))
323
355
  }
324
- if (applicationDialect(tree.files) === 'sqlite') {
356
+ if (dialect === 'sqlite') {
325
357
  if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
326
358
  findings.push(...checkCurrentTimestampDefaults(tree.files))
327
359
  findings.push(...checkSqliteFrameworkNames(tree.files))
@@ -332,6 +364,7 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
332
364
  const policies = tablePolicies(declaredTables)
333
365
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
334
366
  findings.push(...checkConflictIndexes(tree.files, new Set(Object.keys(policies)), dependent.inserts))
367
+ findings.push(...checkAccessViewKeys(tree.files, accessKeys(policies)))
335
368
  }
336
369
  const bunfig = tree.files.get(BUNFIG_FILE)
337
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'
@@ -229,7 +229,7 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
229
229
  if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
230
230
  return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
231
231
  }
232
- modules.set(path, parsed.module)
232
+ modules.set(path, withoutTypeDeclarations(parsed.module))
233
233
  for (const specifier of importedSpecifiers(parsed.module)) {
234
234
  const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
235
235
  if (resolution?.kind === 'file') {
@@ -242,6 +242,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
242
242
  return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
243
243
  }
244
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
+
245
257
  function missingFile(file: string): Finding {
246
258
  return {
247
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',
@@ -812,7 +812,7 @@ function plain(value: LiteralValue | undefined): unknown {
812
812
  }
813
813
 
814
814
  const DECLARED_ALLOWED =
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>']"
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)"
816
816
 
817
817
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
818
818
  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 } 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]
@@ -357,6 +357,108 @@ export const checkConflictIndexes = (
357
357
  return checked.filter((insert) => !present.has(`${insert.table}(${keyOf(insert.columns)})`)).map((insert) => insert.finding)
358
358
  }
359
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
+
360
462
  interface UniqueIndex {
361
463
  readonly name: string | undefined
362
464
  readonly table: string
@@ -366,23 +468,28 @@ interface UniqueIndex {
366
468
  function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]): void {
367
469
  const verb = upperWord(tokens[0])
368
470
  const object = upperWord(tokens[1])
369
- if (verb === 'CREATE' && object === 'TABLE') {
370
- 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')
371
475
  const table = objectNameAt(tokens, at)?.name
372
476
  const open = afterName(tokens, at)
373
477
  const close = open === undefined ? undefined : closingParenthesis(tokens, open)
374
478
  if (table === undefined || open === undefined || close === undefined) return
479
+ keep((index) => index.table !== table)
375
480
  for (const element of splitAtCommas(tokens.slice(open + 1, close))) {
376
481
  readUniqueElement(table, element, unique)
377
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))
378
486
  } else if (verb === 'ALTER' && object === 'TABLE') {
379
487
  const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
380
488
  const table = objectNameAt(tokens, at)?.name
381
489
  const end = afterName(tokens, at)
382
490
  if (table === undefined || end === undefined) return
383
491
  for (const action of splitAtCommas(tokens.slice(end))) {
384
- if (upperWord(action[0]) !== 'ADD') continue
385
- readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
492
+ alterUnique(table, action, unique, keep)
386
493
  }
387
494
  } else if (verb === 'CREATE' && object === 'UNIQUE' && upperWord(tokens[2]) === 'INDEX') {
388
495
  const rest = tokens.slice(3)
@@ -406,7 +513,41 @@ function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]):
406
513
  }
407
514
  }
408
515
 
409
- /** 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
+ */
410
551
  function readUniqueElement(table: string, element: readonly SqlToken[], unique: UniqueIndex[]): void {
411
552
  const head = upperWord(element[0])
412
553
  if (head !== undefined && TABLE_CONSTRAINTS.has(head)) {
@@ -416,12 +557,16 @@ function readUniqueElement(table: string, element: readonly SqlToken[], unique:
416
557
  const list = open === undefined ? undefined : columnList(constraint, open)
417
558
  const columns = list?.columns.filter((column) => column !== undefined) ?? []
418
559
  if (list !== undefined && columns.length > 0 && columns.length === list.columns.length) {
419
- 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 })
420
562
  }
421
563
  return
422
564
  }
423
565
  const column = nameText(element[0])
424
- if (column !== undefined && depthZeroWords(element.slice(1)).some((word) => word === 'UNIQUE' || word === 'PRIMARY')) {
425
- 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] })
426
571
  }
427
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,21 @@ 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, against the application's access tables. 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, accessTables: readonly 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
- const options = { accessTables: new Set(accessTables) }
41
+ const options = { accessTables: new Set(accessTables), dialect }
36
42
  return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId), options).files.flatMap((file) =>
37
43
  file.refused.map((refusal): Finding => ({
38
44
  file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
@@ -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;
@@ -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", "cloudflare-view-trigger"];
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", "cloudflare-view-trigger", "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
@@ -43,3 +43,15 @@ export interface ConflictInsert {
43
43
  * checked: another receiver of `insert` is no table of the data layer.
44
44
  */
45
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, against the application's access tables. 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, accessTables: readonly 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