@fabrika/check 0.9.0-dev.11 → 0.9.0-dev.13
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 +7 -7
- package/src/check.ts +40 -16
- package/src/contract.ts +1 -0
- package/src/finding.ts +1 -0
- package/src/reader/surface.ts +16 -3
- package/src/reader/value.ts +13 -1
- package/src/rules/migrations.ts +31 -0
- package/src/rules/platform-migrations.ts +4 -3
- package/src/rules/runtime.ts +27 -5
- package/src/scaffold.ts +9 -1
- package/types/src/contract.d.ts +1 -0
- package/types/src/finding.d.ts +2 -2
- package/types/src/rules/migrations.d.ts +5 -0
- package/types/src/rules/platform-migrations.d.ts +2 -2
- package/types/src/rules/runtime.d.ts +5 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/check",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.13",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,16 +42,16 @@
|
|
|
42
42
|
}
|
|
43
43
|
},
|
|
44
44
|
"scripts": {
|
|
45
|
-
"typecheck": "
|
|
45
|
+
"typecheck": "tsrs --build tsconfig.test.json",
|
|
46
46
|
"test": "bun test"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@babel/parser": "8.0.7",
|
|
50
|
-
"@fabrika/app": "0.9.0-dev.
|
|
51
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
52
|
-
"@fabrika/db": "0.9.0-dev.
|
|
53
|
-
"@fabrika/operations-contract": "0.9.0-dev.
|
|
54
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
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",
|
|
55
55
|
"zod": "^3.25.76"
|
|
56
56
|
}
|
|
57
57
|
}
|
package/src/check.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
|
|
2
|
-
import type
|
|
3
|
-
import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
2
|
+
import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry } 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'
|
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
checkFileColumnMigrations,
|
|
42
42
|
checkMigrationNames,
|
|
43
43
|
checkSqliteFrameworkNames,
|
|
44
|
+
checkSqliteViewTriggers,
|
|
44
45
|
type ConflictInsert,
|
|
45
46
|
type FileColumn,
|
|
46
47
|
} from './rules/migrations'
|
|
@@ -95,8 +96,8 @@ export const readApplicationTree = async (root: string): Promise<ApplicationTree
|
|
|
95
96
|
|
|
96
97
|
/** The findings a module rule leaves until the contract is read: they depend on what it declares. */
|
|
97
98
|
interface ContractDependent {
|
|
98
|
-
/** Each `fetch` of an absolute URL, with its static prefix. */
|
|
99
|
-
readonly fetches: { readonly target: string; readonly finding: Finding }[]
|
|
99
|
+
/** Each `fetch` of an absolute URL, with its static prefix and its labelled authority (`absoluteFetch`). */
|
|
100
|
+
readonly fetches: { readonly target: string; readonly labelled: string | undefined; readonly finding: Finding }[]
|
|
100
101
|
/** Each `ctx.url` with a literal endpoint id. */
|
|
101
102
|
readonly urls: { readonly endpoint: string; readonly finding: Finding }[]
|
|
102
103
|
/** Each insert with literal `onConflict.columns`, checked against the migrations' unique indexes. */
|
|
@@ -146,9 +147,9 @@ const checkSourceModule = async (
|
|
|
146
147
|
isGeneratedEntry,
|
|
147
148
|
rawSql: rawSqlBindings(module.program),
|
|
148
149
|
isServerModule: isServerModule(module.file),
|
|
149
|
-
absoluteFetch: (node: AstNode, target: string) => {
|
|
150
|
+
absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => {
|
|
150
151
|
const { message, allowed } = crossAppFetchMessage(target)
|
|
151
|
-
for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, finding })
|
|
152
|
+
for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, labelled, finding })
|
|
152
153
|
},
|
|
153
154
|
appUrl: (node: AstNode, endpoint: string) => {
|
|
154
155
|
const message = `ctx.url names '${endpoint}', which is no procedure of the contract`
|
|
@@ -189,7 +190,7 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
|
|
|
189
190
|
/** What the module rules that wait for the contract compare against: its procedure ids and every declared origin. */
|
|
190
191
|
interface CompiledReach {
|
|
191
192
|
readonly procedures: ReadonlySet<string>
|
|
192
|
-
readonly
|
|
193
|
+
readonly egress: readonly EgressEntry[]
|
|
193
194
|
}
|
|
194
195
|
|
|
195
196
|
/** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
|
|
@@ -209,24 +210,44 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
|
|
|
209
210
|
)
|
|
210
211
|
return {
|
|
211
212
|
procedures: new Set(procedures.map((row) => row.id)),
|
|
212
|
-
|
|
213
|
+
egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
|
|
214
|
+
(reach.egress ?? []).flatMap((value) => {
|
|
215
|
+
const parsed = parseEgressEntry(value)
|
|
216
|
+
return parsed.ok ? [parsed.entry] : []
|
|
217
|
+
})
|
|
218
|
+
),
|
|
213
219
|
}
|
|
214
220
|
}
|
|
215
221
|
|
|
216
222
|
/**
|
|
217
223
|
* A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
|
|
218
|
-
* not accepted
|
|
219
|
-
* compiles and names no such procedure. The runtime guard on `fetch`
|
|
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.
|
|
220
227
|
*/
|
|
221
228
|
const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
|
|
222
|
-
...dependent.fetches.filter((
|
|
223
|
-
finding
|
|
224
|
-
),
|
|
229
|
+
...dependent.fetches.filter((fetch) => reach === null || !isDeclaredFetch(fetch, reach.egress)).map(({ finding }) => finding),
|
|
225
230
|
...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
|
|
226
231
|
]
|
|
227
232
|
|
|
228
|
-
|
|
229
|
-
|
|
233
|
+
/** The static prefix names its whole authority, which an entry admits, or the labelled authority is a pattern's own. */
|
|
234
|
+
const isDeclaredFetch = (fetch: { readonly target: string; readonly labelled: string | undefined }, egress: readonly EgressEntry[]): boolean => {
|
|
235
|
+
const authority = /^https:\/\/[^/?#]+[/?#]/.exec(fetch.target)?.[0]
|
|
236
|
+
const url = authority === undefined ? null : urlOf(authority)
|
|
237
|
+
if (url !== null && egressAdmits(egress, url)) return true
|
|
238
|
+
// The interpolated label as a placeholder one, so the authority normalizes as the runtime's URL will; exact
|
|
239
|
+
// origins stay out, as no literal label is known.
|
|
240
|
+
const labelled = fetch.labelled === undefined ? null : urlOf(`https://${fetch.labelled.replace('*', 'label')}/`)
|
|
241
|
+
return labelled !== null && egressAdmits(egress.filter((entry) => entry.kind === 'pattern'), labelled)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const urlOf = (value: string): URL | null => {
|
|
245
|
+
try {
|
|
246
|
+
return new URL(value)
|
|
247
|
+
} catch {
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
}
|
|
230
251
|
|
|
231
252
|
/** Runs every rule over one application and returns the findings in file, line and column order. */
|
|
232
253
|
export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
|
|
@@ -297,11 +318,14 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
297
318
|
const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
|
|
298
319
|
const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
|
|
299
320
|
findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
|
|
300
|
-
if (artifact !== null)
|
|
321
|
+
if (artifact !== null) {
|
|
322
|
+
findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables)))
|
|
323
|
+
}
|
|
301
324
|
if (applicationDialect(tree.files) === 'sqlite') {
|
|
302
325
|
if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
|
|
303
326
|
findings.push(...checkCurrentTimestampDefaults(tree.files))
|
|
304
327
|
findings.push(...checkSqliteFrameworkNames(tree.files))
|
|
328
|
+
findings.push(...checkSqliteViewTriggers(tree.files))
|
|
305
329
|
findings.push(...(await checkBackupPlan(tree.files)))
|
|
306
330
|
}
|
|
307
331
|
if (declaredTables !== null) {
|
package/src/contract.ts
CHANGED
|
@@ -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'
|
package/src/finding.ts
CHANGED
package/src/reader/surface.ts
CHANGED
|
@@ -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
|
|
|
@@ -597,7 +608,7 @@ class SurfaceReader {
|
|
|
597
608
|
// ── Sections ────────────────────────────────────────────────────────────────────────────────
|
|
598
609
|
|
|
599
610
|
/**
|
|
600
|
-
* `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes` and `
|
|
611
|
+
* `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes`, `scan` and `inline` is unknown, as the kit
|
|
601
612
|
* records it, so `buildArtifact` refuses a file collection's `owner` in its own words.
|
|
602
613
|
*/
|
|
603
614
|
#files(value: LiteralValue, form: Form): FileKind {
|
|
@@ -606,11 +617,13 @@ class SurfaceReader {
|
|
|
606
617
|
const [kind] = args(at, 'c.files', 1, 1)
|
|
607
618
|
const options = builderOptions(kind, at, 'c.files')
|
|
608
619
|
const scan = options.get('scan')
|
|
620
|
+
const inline = options.get('inline')
|
|
609
621
|
return {
|
|
610
622
|
kind: 'file-kind',
|
|
611
623
|
types: texts(options.get('types'), at, 'types'),
|
|
612
624
|
maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
|
|
613
625
|
scan: scan === undefined ? undefined : boolean(scan, 'scan'),
|
|
626
|
+
inline: inline === undefined ? undefined : boolean(inline, 'inline'),
|
|
614
627
|
unknownOptions: optionKeys(options, 'fileKind'),
|
|
615
628
|
}
|
|
616
629
|
}
|
|
@@ -799,7 +812,7 @@ function plain(value: LiteralValue | undefined): unknown {
|
|
|
799
812
|
}
|
|
800
813
|
|
|
801
814
|
const DECLARED_ALLOWED =
|
|
802
|
-
"sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>']"
|
|
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>']"
|
|
803
816
|
|
|
804
817
|
/** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
|
|
805
818
|
const asSurface = (builder: BuilderValue): LiteralValue => ({
|
package/src/reader/value.ts
CHANGED
|
@@ -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 = [
|
|
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
|
|
package/src/rules/migrations.ts
CHANGED
|
@@ -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
|
|
@@ -24,15 +24,16 @@ 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. Control refuses a deploy whose new migration holds
|
|
28
28
|
* one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
|
|
29
29
|
* checked, applied or not: the checker does not know which an environment holds.
|
|
30
30
|
*/
|
|
31
|
-
export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
|
|
31
|
+
export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[]): Finding[] => {
|
|
32
32
|
const texts = migrationTexts(files)
|
|
33
33
|
if (texts.length === 0) return []
|
|
34
34
|
const paths = new Map(texts.map((text) => [text.name, text.path]))
|
|
35
|
-
|
|
35
|
+
const options = { accessTables: new Set(accessTables) }
|
|
36
|
+
return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId), options).files.flatMap((file) =>
|
|
36
37
|
file.refused.map((refusal): Finding => ({
|
|
37
38
|
file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
|
|
38
39
|
line: refusal.line,
|
package/src/rules/runtime.ts
CHANGED
|
@@ -28,8 +28,11 @@ export interface SourceContext {
|
|
|
28
28
|
readonly rawSql: ReadonlySet<string>
|
|
29
29
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
30
30
|
readonly isServerModule: boolean
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
|
|
33
|
+
* authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
|
|
34
|
+
*/
|
|
35
|
+
readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void
|
|
33
36
|
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
34
37
|
readonly appUrl: (node: AstNode, endpoint: string) => void
|
|
35
38
|
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|
|
@@ -130,10 +133,28 @@ const staticPrefix = (node: AstNode | undefined): string | undefined => {
|
|
|
130
133
|
const ABSOLUTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
|
|
131
134
|
const LOCAL_SCHEMES = /^(?:data|blob):/i
|
|
132
135
|
|
|
136
|
+
/**
|
|
137
|
+
* The authority of `https://${label}.<domain>…` with the interpolated label as `*` (`*.<domain>[:port]`), when the
|
|
138
|
+
* template's static text after it reaches the path, query or fragment; the runtime guard checks the label itself.
|
|
139
|
+
*/
|
|
140
|
+
const labelledAuthority = (node: AstNode | undefined): string | undefined => {
|
|
141
|
+
if (node === undefined) return undefined
|
|
142
|
+
if (node.type === 'NewExpression' && ['URL', 'Request'].includes(identifierName(child(node, 'callee')) ?? '')) {
|
|
143
|
+
return labelledAuthority(argumentAt(node, 0))
|
|
144
|
+
}
|
|
145
|
+
if (node.type !== 'TemplateLiteral') return undefined
|
|
146
|
+
const [head, next] = children(node, 'quasis')
|
|
147
|
+
if (!head || !next || templateText(head).cooked !== 'https://') return undefined
|
|
148
|
+
const rest = templateText(next).cooked ?? ''
|
|
149
|
+
const end = rest.search(/[/?#]/)
|
|
150
|
+
return rest.startsWith('.') && end > 1 ? `*${rest.slice(0, end)}` : undefined
|
|
151
|
+
}
|
|
152
|
+
|
|
133
153
|
const checkFetch = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
|
134
|
-
const
|
|
154
|
+
const argument = invokedArgument(node, path, 'fetch')
|
|
155
|
+
const target = staticPrefix(argument)
|
|
135
156
|
if (target === undefined || !ABSOLUTE_URL.test(target) || LOCAL_SCHEMES.test(target)) return
|
|
136
|
-
context.absoluteFetch(node, target)
|
|
157
|
+
context.absoluteFetch(node, target, labelledAuthority(argument))
|
|
137
158
|
}
|
|
138
159
|
|
|
139
160
|
/** `ctx.url('<endpoint id>', …)`, also on a `ctx` reached through a member (`args.ctx.url`). */
|
|
@@ -177,7 +198,8 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
|
|
|
177
198
|
/** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
|
|
178
199
|
export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
|
|
179
200
|
message: `fetch to the absolute origin '${target}' is a hand-written integration`,
|
|
180
|
-
allowed:
|
|
201
|
+
allowed:
|
|
202
|
+
"a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>' | 'https://*.<domain>'] on the site",
|
|
181
203
|
})
|
|
182
204
|
|
|
183
205
|
const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
package/src/scaffold.ts
CHANGED
|
@@ -251,7 +251,8 @@ const policyTestBody = (
|
|
|
251
251
|
dialect: ApplicationDialect,
|
|
252
252
|
): { readonly body: string; readonly cases: readonly string[] } | undefined => {
|
|
253
253
|
const policy = policies[table]
|
|
254
|
-
|
|
254
|
+
// A view's rows come from the tables it reads, so no probe seeds one; its parent's cases still run.
|
|
255
|
+
if (policy === undefined || policy.view === true) return undefined
|
|
255
256
|
const app = policy.scope.mode === 'app'
|
|
256
257
|
const dimension = grantDimension(policies, policy)
|
|
257
258
|
if (dimension === undefined && !app) return undefined
|
|
@@ -889,6 +890,13 @@ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }
|
|
|
889
890
|
for (const [field, table] of Object.entries(fields).sort(byKey)) {
|
|
890
891
|
if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
|
|
891
892
|
findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a row`, 'a top-level string field of the input'))
|
|
893
|
+
} else if (policies[table]?.view === true) {
|
|
894
|
+
findings.push(
|
|
895
|
+
at(
|
|
896
|
+
`${id}: ${field} names the view ${table}, whose rows the kit cannot seed: they come from the tables it reads`,
|
|
897
|
+
'a row field that names a table the view reads',
|
|
898
|
+
),
|
|
899
|
+
)
|
|
892
900
|
} else if (!rowPlace(policies, scope, table)) {
|
|
893
901
|
findings.push(at(...unplacedRow(policies, id, table, scope)))
|
|
894
902
|
}
|
package/types/src/contract.d.ts
CHANGED
|
@@ -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';
|
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"];
|
|
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"];
|
|
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", "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];
|
|
@@ -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;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { Finding } from '../finding';
|
|
2
2
|
/**
|
|
3
|
-
* Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
|
|
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
4
|
* one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
|
|
5
5
|
* checked, applied or not: the checker does not know which an environment holds.
|
|
6
6
|
*/
|
|
7
|
-
export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string) => Finding[];
|
|
7
|
+
export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[]) => Finding[];
|
|
8
8
|
/**
|
|
9
9
|
* On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
|
|
10
10
|
* table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
|
|
@@ -8,8 +8,11 @@ export interface SourceContext {
|
|
|
8
8
|
readonly rawSql: ReadonlySet<string>;
|
|
9
9
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
10
10
|
readonly isServerModule: boolean;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
|
|
13
|
+
* authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
|
|
14
|
+
*/
|
|
15
|
+
readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void;
|
|
13
16
|
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
14
17
|
readonly appUrl: (node: AstNode, endpoint: string) => void;
|
|
15
18
|
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|