@fabrika/check 0.9.0-dev.13 → 0.9.0-dev.15
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 +6 -6
- package/src/ast.ts +69 -6
- package/src/check.ts +41 -8
- package/src/contract.ts +41 -6
- package/src/finding.ts +1 -0
- package/src/inputs.ts +4 -2
- package/src/layout.ts +4 -1
- package/src/limits.ts +13 -3
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +3 -2
- package/src/reader/value.ts +5 -5
- package/src/rules/cloudflare.ts +3 -3
- package/src/rules/literal.ts +3 -1
- package/src/rules/migrations.ts +155 -10
- package/src/rules/modules.ts +6 -0
- package/src/rules/platform-migrations.ts +10 -4
- package/src/rules/runtime.ts +6 -3
- package/src/rules/structure.ts +7 -6
- package/types/src/ast.d.ts +6 -0
- package/types/src/finding.d.ts +2 -2
- package/types/src/layout.d.ts +4 -1
- package/types/src/limits.d.ts +12 -2
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +2 -2
- package/types/src/rules/cloudflare.d.ts +1 -1
- package/types/src/rules/migrations.d.ts +12 -0
- package/types/src/rules/platform-migrations.d.ts +4 -2
package/src/rules/cloudflare.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
|
|
2
|
-
import type
|
|
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?:
|
|
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
|
|
package/src/rules/literal.ts
CHANGED
|
@@ -29,6 +29,8 @@ export type BuilderKind =
|
|
|
29
29
|
/** The only imported names a literal module may use: the builders the platform reads without executing them. */
|
|
30
30
|
export const BUILDER_IMPORTS: Readonly<Record<string, Readonly<Record<string, BuilderKind>>>> = {
|
|
31
31
|
'zod/v4': { z: 'zod', '*': 'zod' },
|
|
32
|
+
// The same subset, each schema held as data; the reader reads both alike.
|
|
33
|
+
'@fabrika/app/schema': { z: 'zod', '*': 'zod' },
|
|
32
34
|
'@fabrika/app/contract': {
|
|
33
35
|
defineContract: 'contract',
|
|
34
36
|
defineVocabulary: 'vocabulary',
|
|
@@ -164,7 +166,7 @@ const ALLOWED_SCHEMA = 'a schema of the supported z subset (packages/check/CLAUD
|
|
|
164
166
|
const ALLOWED_CALLBACK =
|
|
165
167
|
'a function only as a builder callback: defineContract(…, (c) => ({ … })), app.contract((c) => ({ … })), app.group(…, (r) => ({ … })), procedures: (l) => ({ … }) of a link or an export, and the handler of .handle(…)'
|
|
166
168
|
const ALLOWED_IMPORT =
|
|
167
|
-
'z from zod/v4, defineContract, defineVocabulary or defineApp from @fabrika/app/contract, defineTables from @fabrika/db/tables, or a literal const of the application'
|
|
169
|
+
'z from zod/v4 or @fabrika/app/schema, defineContract, defineVocabulary or defineApp from @fabrika/app/contract, defineTables from @fabrika/db/tables, or a literal const of the application'
|
|
168
170
|
|
|
169
171
|
export type Link = { readonly kind: 'member'; readonly name: string | undefined; readonly node: AstNode } | {
|
|
170
172
|
readonly kind: 'call'
|
package/src/rules/migrations.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
370
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
-
|
|
425
|
-
|
|
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
|
}
|
package/src/rules/modules.ts
CHANGED
|
@@ -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
|
|
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 = (
|
|
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}`,
|
package/src/rules/runtime.ts
CHANGED
|
@@ -39,8 +39,11 @@ export interface SourceContext {
|
|
|
39
39
|
readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
/**
|
|
43
|
-
|
|
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,
|
|
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 => {
|
package/src/rules/structure.ts
CHANGED
|
@@ -129,12 +129,13 @@ const runtimeClosure = (graph: StructureGraph, start: Targets, descend: (path: s
|
|
|
129
129
|
const isDataPackage = (specifier: string): boolean => specifier === '@fabrika/db' || specifier.startsWith('@fabrika/db/')
|
|
130
130
|
|
|
131
131
|
/** The framework modules logic and queries may import; the rest of `@fabrika/*` is the framework's own composition. */
|
|
132
|
-
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/db'])
|
|
132
|
+
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/app/schema', '@fabrika/db'])
|
|
133
133
|
|
|
134
134
|
/** The framework modules an SPA loads: the typed client, its React hooks, the component kit and its challenge widget. */
|
|
135
135
|
const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
136
136
|
'@fabrika/app/client',
|
|
137
137
|
'@fabrika/app/react',
|
|
138
|
+
'@fabrika/app/schema',
|
|
138
139
|
'@fabrika/ui',
|
|
139
140
|
'@fabrika/ui/challenge',
|
|
140
141
|
'@fabrika/ui/styles.css',
|
|
@@ -142,7 +143,7 @@ const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
|
142
143
|
])
|
|
143
144
|
|
|
144
145
|
const SPA_ALLOWED =
|
|
145
|
-
'@fabrika/app/client, @fabrika/app/react, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
146
|
+
'@fabrika/app/client, @fabrika/app/react, @fabrika/app/schema, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
146
147
|
|
|
147
148
|
const isSchemaModule = (path: string): boolean => path === SCHEMAS_FILE || path.startsWith(SCHEMAS_DIR)
|
|
148
149
|
|
|
@@ -169,18 +170,18 @@ const checkSpaReference = (graph: StructureGraph, reference: ModuleReference, ta
|
|
|
169
170
|
if (server !== undefined) report(reference.node, 'spa-server-import', viaMessage(reference, server, 'server code', 'the SPA'), SPA_ALLOWED)
|
|
170
171
|
}
|
|
171
172
|
|
|
172
|
-
/** The
|
|
173
|
-
const
|
|
173
|
+
/** The packages shared code loads, zod's schemas either way; everything else it needs is in other modules of `src/shared/`. */
|
|
174
|
+
const SHARED_PACKAGES: ReadonlySet<string> = new Set(['zod/v4', '@fabrika/app/schema'])
|
|
174
175
|
|
|
175
176
|
/** A shared module runs in the SPA and in every slice, so it loads nothing either side lacks. */
|
|
176
177
|
const checkSharedReference = (reference: ModuleReference, targets: Targets, report: Report): void => {
|
|
177
|
-
const outside = targets.packages.find((specifier) => specifier
|
|
178
|
+
const outside = targets.packages.find((specifier) => !SHARED_PACKAGES.has(specifier)) ?? targets.files.find((path) => !isSharedModule(path))
|
|
178
179
|
if (outside === undefined) return
|
|
179
180
|
report(
|
|
180
181
|
reference.node,
|
|
181
182
|
'shared-import',
|
|
182
183
|
viaMessage(reference, outside, 'outside src/shared/', 'shared code'),
|
|
183
|
-
'zod/v4 and other modules under src/shared/; a type-only import of anything else',
|
|
184
|
+
'zod/v4, @fabrika/app/schema and other modules under src/shared/; a type-only import of anything else',
|
|
184
185
|
)
|
|
185
186
|
}
|
|
186
187
|
|
package/types/src/ast.d.ts
CHANGED
|
@@ -54,12 +54,18 @@ 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;
|
|
60
64
|
export declare const utf8Bytes: (text: string) => number;
|
|
61
65
|
/** The nesting depth of the tree below `root`, measured without recursion, so a deep tree cannot exhaust the stack. */
|
|
62
66
|
export declare const nodeDepth: (root: AstNode) => number;
|
|
67
|
+
/** The number of syntax nodes in the tree below `root`, `root` included, counted without recursion. */
|
|
68
|
+
export declare const nodeCount: (root: AstNode) => number;
|
|
63
69
|
export declare const parseModule: (file: string, text: string) => ParseResult;
|
|
64
70
|
/** The sources of a module's import and re-export declarations; `rules/literal.ts` decides which of them are allowed. */
|
|
65
71
|
export declare const importedSpecifiers: (module: ParsedModule) => string[];
|
package/types/src/finding.d.ts
CHANGED
|
@@ -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];
|
package/types/src/layout.d.ts
CHANGED
|
@@ -25,7 +25,10 @@ export declare const APP_KIT_FILE = "src/app-kit.ts";
|
|
|
25
25
|
/** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
|
|
26
26
|
export declare const SCHEMAS_FILE = "src/schemas.ts";
|
|
27
27
|
export declare const SCHEMAS_DIR = "src/schemas/";
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* Pure code the SPA and every slice may import: it loads nothing but `zod/v4`, `@fabrika/app/schema` and other modules of
|
|
30
|
+
* its own directory.
|
|
31
|
+
*/
|
|
29
32
|
export declare const SHARED_DIR = "src/shared/";
|
|
30
33
|
/** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
|
|
31
34
|
export declare const DATABASE_DIR = "src/db/";
|
package/types/src/limits.d.ts
CHANGED
|
@@ -4,12 +4,22 @@
|
|
|
4
4
|
* step runs.
|
|
5
5
|
*/
|
|
6
6
|
export declare const CONTRACT_LIMITS: {
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. Control reads them in a Cloudflare
|
|
9
|
+
* Worker, whose isolate has 128 MB; handler bodies are sliced out before the parse, so they cost bytes, not nodes.
|
|
10
|
+
*/
|
|
8
11
|
readonly sourceBytes: number;
|
|
12
|
+
/** UTF-8 bytes of one module: its own parse is the peak while it is read, and a dense one needs up to 340 times it. */
|
|
13
|
+
readonly moduleBytes: number;
|
|
14
|
+
/**
|
|
15
|
+
* Syntax nodes the reader holds over each graph (the contract's, the tables'), top-level type declarations left out.
|
|
16
|
+
* At this, `sourceBytes` and `schemaNodes` together, Control's read needs a 95 MB heap of its 128 MB isolate.
|
|
17
|
+
*/
|
|
18
|
+
readonly astNodes: 400000;
|
|
9
19
|
/** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
|
|
10
20
|
readonly astDepth: 128;
|
|
11
21
|
/** Schema nodes once every shared schema is expanded where the contract uses it, over the whole contract. */
|
|
12
|
-
readonly schemaNodes:
|
|
22
|
+
readonly schemaNodes: 60000;
|
|
13
23
|
/** Nesting of one schema: objects, arrays, unions and wrappers. */
|
|
14
24
|
readonly schemaDepth: 32;
|
|
15
25
|
};
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
+
import { DataSchema } from '@fabrika/app/schema';
|
|
1
2
|
import { z } from 'zod/v4';
|
|
2
3
|
import type { LiteralValue } from './value';
|
|
4
|
+
/** A schema the reader holds: one it read from a chain, or a framework schema (`signedToken()`, `file()`). */
|
|
5
|
+
export type ReadSchema = DataSchema | z.ZodType;
|
|
3
6
|
export type SchemaStep = {
|
|
4
7
|
readonly factory: string;
|
|
5
8
|
readonly iso: boolean;
|
|
6
9
|
} | {
|
|
7
10
|
readonly method: string;
|
|
8
|
-
readonly receiver:
|
|
11
|
+
readonly receiver: ReadSchema | undefined;
|
|
9
12
|
};
|
|
10
13
|
export type BuiltSchema = {
|
|
11
14
|
readonly ok: true;
|
|
12
|
-
readonly schema:
|
|
15
|
+
readonly schema: DataSchema;
|
|
13
16
|
} | {
|
|
14
17
|
readonly ok: false;
|
|
15
18
|
readonly message: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { z } from 'zod/v4';
|
|
2
1
|
import { type AstNode, type ParsedModule } from '../ast';
|
|
3
2
|
import type { Located, ModuleGraph } from '../graph';
|
|
4
3
|
import type { ReaderProblems } from './problems';
|
|
4
|
+
import { type ReadSchema } from './schema';
|
|
5
5
|
/**
|
|
6
6
|
* The builder kit a call belongs to: `c` of `defineContract` and `l` of its link's `procedures`; `app`, the kit
|
|
7
7
|
* `defineApp` returned; `c` of `app.contract` (`shell`) and `r` of a group, a link or an export (`endpoints`).
|
|
@@ -42,7 +42,7 @@ export type LiteralValue = {
|
|
|
42
42
|
/** `nodes` counts the schema with every shared part expanded, as the artifact will hold it; `depth` its nesting. */
|
|
43
43
|
| {
|
|
44
44
|
readonly kind: 'schema';
|
|
45
|
-
readonly schema:
|
|
45
|
+
readonly schema: ReadSchema;
|
|
46
46
|
readonly nodes: number;
|
|
47
47
|
readonly depth: number;
|
|
48
48
|
/** The chain that built it, factory first (`iso` for `z.iso.*`), across a const and the methods applied to it. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
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
|
|
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
|