@fabrika/check 0.9.0-dev.3 → 0.9.0-dev.30
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 +12 -7
- package/src/ast.ts +69 -6
- package/src/bun-plugin.ts +4 -27
- package/src/check.ts +157 -44
- package/src/cli.ts +34 -8
- package/src/contract.ts +67 -11
- package/src/dialect.ts +29 -0
- package/src/finding.ts +21 -8
- package/src/graph.ts +49 -12
- package/src/index.ts +4 -12
- package/src/inputs.ts +4 -2
- package/src/layout.ts +41 -12
- package/src/limits.ts +15 -5
- package/src/migration-base.ts +85 -0
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +48 -7
- package/src/reader/value.ts +41 -8
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/compile.ts +32 -0
- package/src/rules/contract.ts +3 -2
- package/src/rules/framework.ts +2 -2
- package/src/rules/identity.ts +6 -9
- package/src/rules/literal.ts +42 -9
- package/src/rules/migration-history.ts +70 -0
- package/src/rules/migrations.ts +248 -9
- package/src/rules/modules.ts +9 -3
- package/src/rules/platform-migrations.ts +100 -0
- package/src/rules/runtime.ts +45 -14
- package/src/rules/structure.ts +172 -19
- package/src/rules/tests.ts +9 -60
- package/src/rules/types.ts +17 -16
- package/src/shell-modules.ts +53 -0
- package/src/slice.ts +6 -5
- package/src/source-maps.ts +2 -0
- package/src/trust.ts +8 -4
- package/src/vite-plugin.ts +65 -0
- package/types/src/ast.d.ts +6 -0
- package/types/src/check.d.ts +3 -0
- package/types/src/contract.d.ts +13 -1
- package/types/src/dialect.d.ts +8 -0
- package/types/src/finding.d.ts +7 -6
- package/types/src/graph.d.ts +12 -2
- package/types/src/index.d.ts +4 -3
- package/types/src/layout.d.ts +25 -10
- package/types/src/limits.d.ts +14 -4
- package/types/src/migration-base.d.ts +9 -0
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +3 -3
- package/types/src/rules/cloudflare.d.ts +9 -0
- package/types/src/rules/compile.d.ts +7 -0
- package/types/src/rules/framework.d.ts +1 -1
- package/types/src/rules/literal.d.ts +1 -1
- package/types/src/rules/migration-history.d.ts +12 -0
- package/types/src/rules/migrations.d.ts +28 -0
- package/types/src/rules/platform-migrations.d.ts +15 -0
- package/types/src/rules/runtime.d.ts +7 -2
- package/types/src/rules/structure.d.ts +18 -4
- package/types/src/rules/tests.d.ts +6 -14
- package/types/src/rules/types.d.ts +2 -0
- package/types/src/shell-modules.d.ts +7 -0
- package/types/src/slice.d.ts +8 -2
- package/types/src/vite-plugin.d.ts +27 -0
- package/src/endpoint-fixtures.ts +0 -221
- package/src/rules/crontab.ts +0 -147
- package/src/rules/isolation.ts +0 -79
- package/src/scaffold-sample.ts +0 -111
- package/src/scaffold.ts +0 -650
- package/types/src/endpoint-fixtures.d.ts +0 -36
- package/types/src/rules/crontab.d.ts +0 -15
- package/types/src/rules/isolation.d.ts +0 -18
- package/types/src/scaffold-sample.d.ts +0 -8
- package/types/src/scaffold.d.ts +0 -28
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.30",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,6 +35,11 @@
|
|
|
35
35
|
"types": "./types/src/bun-plugin.d.ts",
|
|
36
36
|
"default": "./src/bun-plugin.ts"
|
|
37
37
|
},
|
|
38
|
+
"./vite-plugin": {
|
|
39
|
+
"bun": "./src/vite-plugin.ts",
|
|
40
|
+
"types": "./types/src/vite-plugin.d.ts",
|
|
41
|
+
"default": "./src/vite-plugin.ts"
|
|
42
|
+
},
|
|
38
43
|
"./source-maps": {
|
|
39
44
|
"bun": "./src/source-maps.ts",
|
|
40
45
|
"types": "./types/src/source-maps.d.ts",
|
|
@@ -42,16 +47,16 @@
|
|
|
42
47
|
}
|
|
43
48
|
},
|
|
44
49
|
"scripts": {
|
|
45
|
-
"typecheck": "
|
|
50
|
+
"typecheck": "tsrs --build tsconfig.test.json",
|
|
46
51
|
"test": "bun test"
|
|
47
52
|
},
|
|
48
53
|
"dependencies": {
|
|
49
54
|
"@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.
|
|
55
|
+
"@fabrika/app": "0.9.0-dev.30",
|
|
56
|
+
"@fabrika/auth-core": "0.9.0-dev.30",
|
|
57
|
+
"@fabrika/db": "0.9.0-dev.30",
|
|
58
|
+
"@fabrika/operations-contract": "0.9.0-dev.30",
|
|
59
|
+
"@fabrika/platform-node": "0.9.0-dev.30",
|
|
55
60
|
"zod": "^3.25.76"
|
|
56
61
|
}
|
|
57
62
|
}
|
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
|
-
|
|
173
|
-
|
|
174
|
-
|
|
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[] = []
|
|
@@ -243,11 +287,30 @@ export const nodeDepth = (root: AstNode): number => {
|
|
|
243
287
|
return deepest
|
|
244
288
|
}
|
|
245
289
|
|
|
290
|
+
/** The number of syntax nodes in the tree below `root`, `root` included, counted without recursion. */
|
|
291
|
+
export const nodeCount = (root: AstNode): number => {
|
|
292
|
+
let count = 0
|
|
293
|
+
const pending: AstNode[] = [root]
|
|
294
|
+
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
|
|
295
|
+
count++
|
|
296
|
+
for (const [key, value] of Object.entries(node)) {
|
|
297
|
+
if (NON_CHILD_KEYS.has(key)) continue
|
|
298
|
+
if (isNode(value)) pending.push(value)
|
|
299
|
+
else if (Array.isArray(value)) {
|
|
300
|
+
for (const item of value) if (isNode(item)) pending.push(item)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return count
|
|
305
|
+
}
|
|
306
|
+
|
|
246
307
|
export const parseModule = (file: string, text: string): ParseResult => {
|
|
247
308
|
try {
|
|
248
|
-
|
|
309
|
+
// Nothing reads a comment from the node it is attached to; `ast.comments` lists them all.
|
|
310
|
+
const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file), attachComment: false })
|
|
249
311
|
const program: unknown = ast.program
|
|
250
312
|
if (!isNode(program)) return { ok: false, message: 'the parser returned no program', position: { line: 1, column: 1 } }
|
|
313
|
+
lineLocations(text, [program, ast.comments])
|
|
251
314
|
return { ok: true, module: { file, program, comments: readComments(ast.comments), bytes: utf8Bytes(text) } }
|
|
252
315
|
} catch (error) {
|
|
253
316
|
const message = error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : 'unparseable source'
|
package/src/bun-plugin.ts
CHANGED
|
@@ -1,20 +1,12 @@
|
|
|
1
1
|
// @fabrika/check/bun-plugin — a Bun build of the SPA that imports `fabrika.contract.ts` without its handlers. The
|
|
2
2
|
// typed client needs the contract's values (its paths and output schemas), never a handler or what only a handler
|
|
3
3
|
// imports. The plugin reads the shell graph as Control does, refuses the build when the reader refuses it, and loads
|
|
4
|
-
// each shell module as its slice; every other module loads as it is.
|
|
4
|
+
// each shell module as its slice; every other module loads as it is. `@fabrika/check/vite-plugin` is the same for Vite.
|
|
5
5
|
|
|
6
6
|
import type { BunPlugin, Loader } from 'bun'
|
|
7
|
-
import { readFileSync, realpathSync
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { CONTRACT_FILE, isSourceFile } from './layout'
|
|
11
|
-
import { shellSlice } from './slice'
|
|
12
|
-
|
|
13
|
-
const SOURCE_EXTENSION = String.raw`\.(?:[mc]?[jt]s|[jt]sx)$`
|
|
14
|
-
|
|
15
|
-
/** The application's own modules under `root`, outside `node_modules`: every extension the reader reads. */
|
|
16
|
-
const applicationModules = (root: string): RegExp =>
|
|
17
|
-
new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\/](?!(?:.*[\\/])?node_modules[\\/]).*${SOURCE_EXTENSION}`)
|
|
7
|
+
import { readFileSync, realpathSync } from 'node:fs'
|
|
8
|
+
import { resolve } from 'node:path'
|
|
9
|
+
import { applicationModules, shellModules } from './shell-modules'
|
|
18
10
|
|
|
19
11
|
export interface ShellSliceOptions {
|
|
20
12
|
/** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
|
|
@@ -41,21 +33,6 @@ export function shellSlicePlugin(options: ShellSliceOptions = {}): BunPlugin {
|
|
|
41
33
|
|
|
42
34
|
export default shellSlicePlugin()
|
|
43
35
|
|
|
44
|
-
const isFile = (path: string): boolean => statSync(path, { throwIfNoEntry: false })?.isFile() === true
|
|
45
|
-
|
|
46
|
-
/** The shell modules under `root`, by absolute path, as their slices; none without a `fabrika.contract.ts` there. */
|
|
47
|
-
function shellModules(root: string): ReadonlyMap<string, string> {
|
|
48
|
-
if (!isFile(join(root, CONTRACT_FILE))) return new Map()
|
|
49
|
-
const files = new Map<string, string>()
|
|
50
|
-
for (;;) {
|
|
51
|
-
const missing = contractReaderInputs(files, (path) => isFile(join(root, path)))
|
|
52
|
-
if (missing.length === 0) break
|
|
53
|
-
for (const path of missing) files.set(path, readFileSync(join(root, path), 'utf8'))
|
|
54
|
-
}
|
|
55
|
-
readContract(files)
|
|
56
|
-
return new Map([...files].filter(([path]) => isSourceFile(path)).map(([path, text]) => [join(root, path), shellSlice(path, text).text]))
|
|
57
|
-
}
|
|
58
|
-
|
|
59
36
|
function loaderOf(path: string): Loader {
|
|
60
37
|
if (path.endsWith('.tsx')) return 'tsx'
|
|
61
38
|
if (path.endsWith('.jsx')) return 'jsx'
|
package/src/check.ts
CHANGED
|
@@ -1,46 +1,70 @@
|
|
|
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, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
|
|
3
|
+
import { accessTables, type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
4
4
|
import { readdir, readFile } from 'node:fs/promises'
|
|
5
5
|
import { join } from 'node:path'
|
|
6
6
|
import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
|
|
7
7
|
import { contractModules, readContractModule } from './contract'
|
|
8
|
+
import { applicationDialect } from './dialect'
|
|
8
9
|
import { compareFindings, type Finding, reporter } from './finding'
|
|
9
10
|
import { ModuleGraph } from './graph'
|
|
10
11
|
import {
|
|
11
12
|
CONTRACT_FILE,
|
|
12
13
|
GENERATED_ENTRY_FILE,
|
|
13
14
|
isCheckedFile,
|
|
15
|
+
isGeneratedModule,
|
|
14
16
|
isIgnoredSegment,
|
|
15
17
|
isJsonFile,
|
|
16
18
|
isServerModule,
|
|
17
19
|
isSourceFile,
|
|
18
20
|
isTestFile,
|
|
21
|
+
isToolModule,
|
|
19
22
|
TABLES_FILE,
|
|
20
|
-
ZEROPS_FILES,
|
|
21
23
|
} from './layout'
|
|
22
24
|
import type { PackedSet } from './packed'
|
|
23
25
|
import { ReaderProblems } from './reader/problems'
|
|
24
26
|
import { readTablesValue } from './reader/tables'
|
|
25
27
|
import { type ModuleReference, moduleReferences } from './references'
|
|
26
28
|
import { type ImportMappings, readImportMappings } from './resolution'
|
|
29
|
+
import { checkCloudflareContract } from './rules/cloudflare'
|
|
30
|
+
import { checkContractCompiles } from './rules/compile'
|
|
27
31
|
import { checkContractRead } from './rules/contract'
|
|
28
|
-
import { checkCrontab, contractJobs } from './rules/crontab'
|
|
29
32
|
import { checkFrameworkWrite, trustedBindings } from './rules/framework'
|
|
30
33
|
import { checkClientIdentity } from './rules/identity'
|
|
31
|
-
import { checkGeneratedTests } from './rules/isolation'
|
|
32
34
|
import { checkJsonStrings } from './rules/json'
|
|
33
35
|
import { checkLiteralGraph } from './rules/literal'
|
|
34
|
-
import {
|
|
36
|
+
import { checkMigrationHistory, type MigrationBase } from './rules/migration-history'
|
|
37
|
+
import {
|
|
38
|
+
type AccessKey,
|
|
39
|
+
checkAccessViewKeys,
|
|
40
|
+
checkConflictIndexes,
|
|
41
|
+
checkCurrentTimestampDefaults,
|
|
42
|
+
checkFileColumnMigrations,
|
|
43
|
+
checkMigrationNames,
|
|
44
|
+
checkSqliteFrameworkNames,
|
|
45
|
+
checkSqliteViewTriggers,
|
|
46
|
+
type ConflictInsert,
|
|
47
|
+
type FileColumn,
|
|
48
|
+
} from './rules/migrations'
|
|
35
49
|
import { checkModuleReferences } from './rules/modules'
|
|
36
50
|
import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
51
|
+
import { checkBackupPlan, checkMigrationClassification } from './rules/platform-migrations'
|
|
52
|
+
import { checkKeyLiteralNode, checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
|
|
53
|
+
import { checkSingleSliceQueries, checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
|
|
54
|
+
import { checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
|
|
55
|
+
import { checkCapabilityNode, checkComments, checkTypeNode } from './rules/types'
|
|
41
56
|
import { moduleSlice, sliceFinding } from './slice'
|
|
42
57
|
import { BUNFIG_FILE, checkTrustedResolution } from './trust'
|
|
43
58
|
|
|
59
|
+
/** Every table that names an access view, with its key (ADR-0076). */
|
|
60
|
+
const accessKeys = (policies: TablePolicies): AccessKey[] =>
|
|
61
|
+
Object.entries(policies).flatMap(([table, policy]) => {
|
|
62
|
+
const views = Object.values(policy.access ?? {}).map((access) => access.view)
|
|
63
|
+
const scope = policy.scope
|
|
64
|
+
const key = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app' ? scope.key : undefined
|
|
65
|
+
return views.length === 0 || key === undefined ? [] : [{ table, key, views: [...new Set(views)].sort() }]
|
|
66
|
+
})
|
|
67
|
+
|
|
44
68
|
/** Every file column the table policies declare, with its kind. */
|
|
45
69
|
const fileColumns = (policies: TablePolicies): FileColumn[] =>
|
|
46
70
|
Object.entries(policies).flatMap(([table, policy]) => Object.entries(policy.files ?? {}).map(([column, kind]) => ({ table, column, kind })))
|
|
@@ -52,6 +76,8 @@ export interface CheckInput {
|
|
|
52
76
|
readonly files?: ReadonlyMap<string, string>
|
|
53
77
|
/** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
|
|
54
78
|
readonly packed?: PackedSet
|
|
79
|
+
/** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
|
|
80
|
+
readonly migrationBase?: MigrationBase
|
|
55
81
|
}
|
|
56
82
|
|
|
57
83
|
export interface ApplicationTree {
|
|
@@ -80,27 +106,56 @@ export const readApplicationTree = async (root: string): Promise<ApplicationTree
|
|
|
80
106
|
|
|
81
107
|
/** The findings a module rule leaves until the contract is read: they depend on what it declares. */
|
|
82
108
|
interface ContractDependent {
|
|
83
|
-
/** Each `fetch` of an absolute URL, with its static prefix. */
|
|
84
|
-
readonly fetches: { readonly target: string; readonly finding: Finding }[]
|
|
109
|
+
/** Each `fetch` of an absolute URL, with its static prefix and its labelled authority (`absoluteFetch`). */
|
|
110
|
+
readonly fetches: { readonly target: string; readonly labelled: string | undefined; readonly finding: Finding }[]
|
|
85
111
|
/** Each `ctx.url` with a literal endpoint id. */
|
|
86
112
|
readonly urls: { readonly endpoint: string; readonly finding: Finding }[]
|
|
87
113
|
/** Each insert with literal `onConflict.columns`, checked against the migrations' unique indexes. */
|
|
88
114
|
readonly inserts: ConflictInsert[]
|
|
89
115
|
}
|
|
90
116
|
|
|
91
|
-
|
|
117
|
+
/**
|
|
118
|
+
* Whether `type-assertion`, `any-type` and `suppression-comment` (how a module's own source is written) apply: not to
|
|
119
|
+
* a generated module, nor to a test file, which never ships and which `test-only-import` keeps out of shipped code.
|
|
120
|
+
*/
|
|
121
|
+
const isHeldToWriting = (file: string, generated: boolean): boolean => !generated && !isTestFile(file)
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A module under `tools/` runs on a developer's machine, never in the application: it is held to how its source is
|
|
125
|
+
* written (`type-assertion`, `any-type` and `suppression-comment` outside its tests; `capability-widening`), `key-literal`,
|
|
126
|
+
* a `declare module` of a trusted package and the rules of its tests. Every other module rule guards code that runs in the
|
|
127
|
+
* application.
|
|
128
|
+
*/
|
|
129
|
+
const checkToolModule = (module: ParsedModule, generated: boolean, findings: Finding[]): void => {
|
|
130
|
+
const report = reporter(module.file, findings)
|
|
131
|
+
const isTest = isTestFile(module.file)
|
|
132
|
+
const writing = isHeldToWriting(module.file, generated)
|
|
133
|
+
walk(module.program, (node, ancestors) => {
|
|
134
|
+
checkKeyLiteralNode(node, report)
|
|
135
|
+
if (writing) checkTypeNode(node, report)
|
|
136
|
+
checkCapabilityNode(node, report)
|
|
137
|
+
checkAmbientModule(node, report)
|
|
138
|
+
if (isTest) checkTestNode(node, ancestors, report)
|
|
139
|
+
checkMockModule(node, report)
|
|
140
|
+
})
|
|
141
|
+
if (writing) checkComments(module.comments, report)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A generated module (`isGeneratedModule`) is not held to `type-assertion`, `any-type`, `suppression-comment` and the hints; a test file not to the first three. */
|
|
145
|
+
const checkSourceModule = (
|
|
92
146
|
module: ParsedModule,
|
|
147
|
+
generated: boolean,
|
|
93
148
|
references: readonly ModuleReference[],
|
|
94
|
-
text: string,
|
|
95
149
|
mappings: ImportMappings,
|
|
96
150
|
files: ReadonlyMap<string, string>,
|
|
97
151
|
findings: Finding[],
|
|
98
152
|
dependent: ContractDependent,
|
|
99
|
-
):
|
|
153
|
+
): void => {
|
|
100
154
|
const exists = (path: string): boolean => files.has(path)
|
|
101
155
|
const report = reporter(module.file, findings)
|
|
102
156
|
const isGeneratedEntry = module.file === GENERATED_ENTRY_FILE
|
|
103
157
|
const isTest = isTestFile(module.file)
|
|
158
|
+
const writing = isHeldToWriting(module.file, generated)
|
|
104
159
|
const deferred = (at: AstNode, rule: 'cross-app-fetch' | 'url-endpoint' | 'on-conflict-index', message: string, allowed: string): Finding[] => {
|
|
105
160
|
const found: Finding[] = []
|
|
106
161
|
reporter(module.file, found)(at, rule, message, allowed)
|
|
@@ -111,9 +166,9 @@ const checkSourceModule = async (
|
|
|
111
166
|
isGeneratedEntry,
|
|
112
167
|
rawSql: rawSqlBindings(module.program),
|
|
113
168
|
isServerModule: isServerModule(module.file),
|
|
114
|
-
absoluteFetch: (node: AstNode, target: string) => {
|
|
169
|
+
absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => {
|
|
115
170
|
const { message, allowed } = crossAppFetchMessage(target)
|
|
116
|
-
for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, finding })
|
|
171
|
+
for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, labelled, finding })
|
|
117
172
|
},
|
|
118
173
|
appUrl: (node: AstNode, endpoint: string) => {
|
|
119
174
|
const message = `ctx.url names '${endpoint}', which is no procedure of the contract`
|
|
@@ -126,19 +181,19 @@ const checkSourceModule = async (
|
|
|
126
181
|
},
|
|
127
182
|
}
|
|
128
183
|
const trusted = trustedBindings(module.file, module.program, mappings)
|
|
129
|
-
const place = structurePlace(module.file, isGeneratedEntry)
|
|
184
|
+
const place = structurePlace(module.file, isGeneratedEntry, generated)
|
|
130
185
|
walk(module.program, (node, ancestors) => {
|
|
131
186
|
checkRuntimeNode(node, ancestors, context)
|
|
132
187
|
checkFrameworkWrite(node, ancestors, trusted, report)
|
|
133
|
-
checkTypeNode(node, report)
|
|
188
|
+
if (writing) checkTypeNode(node, report)
|
|
189
|
+
checkCapabilityNode(node, report)
|
|
134
190
|
checkAmbientModule(node, report)
|
|
135
191
|
if (isTest) checkTestNode(node, ancestors, report)
|
|
136
|
-
checkMockModule(node,
|
|
192
|
+
checkMockModule(node, report)
|
|
137
193
|
checkStructureNode(place, node, report)
|
|
138
194
|
})
|
|
139
|
-
checkComments(module.comments, report)
|
|
195
|
+
if (writing) checkComments(module.comments, report)
|
|
140
196
|
checkModuleReferences(module.file, references, mappings, exists, report, isGeneratedEntry, isTest)
|
|
141
|
-
await checkGeneratedTest(text, module.comments, report)
|
|
142
197
|
}
|
|
143
198
|
|
|
144
199
|
/** `module` as its shell slice (itself when it holds no colocated handler), and the `.handle(…)` forms it refused. */
|
|
@@ -154,41 +209,84 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
|
|
|
154
209
|
/** What the module rules that wait for the contract compare against: its procedure ids and every declared origin. */
|
|
155
210
|
interface CompiledReach {
|
|
156
211
|
readonly procedures: ReadonlySet<string>
|
|
157
|
-
readonly
|
|
212
|
+
readonly egress: readonly EgressEntry[]
|
|
213
|
+
/** Some cron job declares `egress: 'public'`. */
|
|
214
|
+
readonly publicEgress: boolean
|
|
158
215
|
}
|
|
159
216
|
|
|
160
|
-
/** The contract's
|
|
161
|
-
const
|
|
162
|
-
let artifact: ContractArtifact
|
|
217
|
+
/** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
|
|
218
|
+
const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
|
|
163
219
|
try {
|
|
164
|
-
|
|
220
|
+
return compileContract(contract, tables ?? {})
|
|
165
221
|
} catch (error) {
|
|
166
222
|
if (error instanceof ContractError) return null
|
|
167
223
|
throw error
|
|
168
224
|
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The contract's procedures and origins. */
|
|
228
|
+
const compiledReach = (artifact: ContractArtifact): CompiledReach => {
|
|
169
229
|
const procedures = artifact.endpoints.filter((row) =>
|
|
170
230
|
(row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
|
|
171
231
|
)
|
|
172
232
|
return {
|
|
173
233
|
procedures: new Set(procedures.map((row) => row.id)),
|
|
174
|
-
|
|
234
|
+
egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
|
|
235
|
+
(reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress).flatMap((value) => {
|
|
236
|
+
const parsed = parseEgressEntry(value)
|
|
237
|
+
return parsed.ok ? [parsed.entry] : []
|
|
238
|
+
})
|
|
239
|
+
),
|
|
240
|
+
publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
|
|
175
241
|
}
|
|
176
242
|
}
|
|
177
243
|
|
|
178
244
|
/**
|
|
179
245
|
* A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
|
|
180
|
-
* not accepted
|
|
181
|
-
*
|
|
246
|
+
* not accepted, nor an interpolated label a pattern does not cover) and, where a cron job declares `egress: 'public'`,
|
|
247
|
+
* when public egress would refuse it: another scheme, or a host its URL alone refuses (an IP address, a local or
|
|
248
|
+
* internal name, a port). A prefix that ends inside the host is then the runtime's to judge. Every one stands when the
|
|
249
|
+
* contract does not compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime
|
|
250
|
+
* guard on `fetch` still checks the site that runs.
|
|
182
251
|
*/
|
|
183
252
|
const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
|
|
184
|
-
...dependent.fetches.filter((
|
|
185
|
-
|
|
186
|
-
),
|
|
253
|
+
...dependent.fetches.filter((fetch) =>
|
|
254
|
+
reach === null || (!isDeclaredFetch(fetch, reach.egress) && !(reach.publicEgress && isPublicTarget(fetch.target)))
|
|
255
|
+
).map(({ finding }) => finding),
|
|
187
256
|
...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
|
|
188
257
|
]
|
|
189
258
|
|
|
190
|
-
|
|
191
|
-
|
|
259
|
+
/** The static prefix names its whole authority, which an entry admits, or the labelled authority is a pattern's own. */
|
|
260
|
+
const isDeclaredFetch = (fetch: { readonly target: string; readonly labelled: string | undefined }, egress: readonly EgressEntry[]): boolean => {
|
|
261
|
+
const authority = /^https:\/\/[^/?#]+[/?#]/.exec(fetch.target)?.[0]
|
|
262
|
+
const url = authority === undefined ? null : urlOf(authority)
|
|
263
|
+
if (url !== null && egressAdmits(egress, url)) return true
|
|
264
|
+
// The interpolated label as a placeholder one, so the authority normalizes as the runtime's URL will; exact
|
|
265
|
+
// origins stay out, as no literal label is known.
|
|
266
|
+
const labelled = fetch.labelled === undefined ? null : urlOf(`https://${fetch.labelled.replace('*', 'label')}/`)
|
|
267
|
+
return labelled !== null && egressAdmits(egress.filter((entry) => entry.kind === 'pattern'), labelled)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const urlOf = (value: string): URL | null => {
|
|
271
|
+
try {
|
|
272
|
+
return new URL(value)
|
|
273
|
+
} catch {
|
|
274
|
+
return null
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
|
|
279
|
+
const isPublicTarget = (target: string): boolean => {
|
|
280
|
+
const scheme = /^(https?):\/\//i.exec(target)
|
|
281
|
+
if (scheme === null) return false
|
|
282
|
+
const rest = target.slice(scheme[0].length)
|
|
283
|
+
if (!/[/?#]/.test(rest)) return true
|
|
284
|
+
try {
|
|
285
|
+
return publicEgressRefusal(new URL(target)) === null
|
|
286
|
+
} catch {
|
|
287
|
+
return false
|
|
288
|
+
}
|
|
289
|
+
}
|
|
192
290
|
|
|
193
291
|
/** Runs every rule over one application and returns the findings in file, line and column order. */
|
|
194
292
|
export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
|
|
@@ -196,6 +294,7 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
196
294
|
const findings: Finding[] = []
|
|
197
295
|
const modules = new Map<string, ParsedModule>()
|
|
198
296
|
const references = new Map<string, readonly ModuleReference[]>()
|
|
297
|
+
const generated = new Set<string>()
|
|
199
298
|
const dependent: ContractDependent = { fetches: [], urls: [], inserts: [] }
|
|
200
299
|
const checkedPaths = [...tree.files.keys()].filter(isCheckedFile).sort()
|
|
201
300
|
const mappings = readImportMappings(tree.files)
|
|
@@ -226,12 +325,16 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
226
325
|
modules.set(path, parsed.module)
|
|
227
326
|
const referencesOfModule = moduleReferences(parsed.module.program)
|
|
228
327
|
references.set(path, referencesOfModule)
|
|
229
|
-
|
|
328
|
+
const isGenerated = isGeneratedModule(path, parsed.module)
|
|
329
|
+
if (isGenerated) generated.add(path)
|
|
330
|
+
if (isToolModule(path)) checkToolModule(parsed.module, isGenerated, findings)
|
|
331
|
+
else checkSourceModule(parsed.module, isGenerated, referencesOfModule, mappings, tree.files, findings, dependent)
|
|
230
332
|
}
|
|
231
333
|
const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
|
|
232
334
|
for (const path of modules.keys()) {
|
|
233
|
-
checkStructureReferences(structure, structurePlace(path, path === GENERATED_ENTRY_FILE), reporter(path, findings))
|
|
335
|
+
checkStructureReferences(structure, structurePlace(path, path === GENERATED_ENTRY_FILE, generated.has(path)), reporter(path, findings))
|
|
234
336
|
}
|
|
337
|
+
findings.push(...checkSingleSliceQueries(structure, new Map([...modules].map(([path, module]) => [path, module.program]))))
|
|
235
338
|
|
|
236
339
|
// The contract rules read each module's shell slice: a colocated handler, and what only it uses, is application
|
|
237
340
|
// code, which the rules above checked in full.
|
|
@@ -250,22 +353,32 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
250
353
|
const contractRead = contract !== undefined && literal.length === 0 ? checkContractRead(graph) : []
|
|
251
354
|
findings.push(...contractRead)
|
|
252
355
|
for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
|
|
253
|
-
findings.push(...(
|
|
356
|
+
findings.push(...checkContractCompiles(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0))
|
|
254
357
|
findings.push(...checkMigrationNames(checkedPaths))
|
|
358
|
+
if (input.migrationBase !== undefined) findings.push(...checkMigrationHistory(tree.files, input.migrationBase))
|
|
359
|
+
findings.push(...checkToolPackages(checkedPaths))
|
|
255
360
|
const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
|
|
256
361
|
const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
|
|
257
|
-
|
|
362
|
+
const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
|
|
363
|
+
findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
|
|
364
|
+
const dialect = applicationDialect(tree.files)
|
|
365
|
+
if (artifact !== null) {
|
|
366
|
+
findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables), dialect))
|
|
367
|
+
}
|
|
368
|
+
if (dialect === 'sqlite') {
|
|
369
|
+
if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
|
|
370
|
+
findings.push(...checkCurrentTimestampDefaults(tree.files))
|
|
371
|
+
findings.push(...checkSqliteFrameworkNames(tree.files))
|
|
372
|
+
findings.push(...checkSqliteViewTriggers(tree.files))
|
|
373
|
+
findings.push(...(await checkBackupPlan(tree.files)))
|
|
374
|
+
}
|
|
258
375
|
if (declaredTables !== null) {
|
|
259
376
|
const policies = tablePolicies(declaredTables)
|
|
260
377
|
findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
|
|
261
378
|
findings.push(...checkConflictIndexes(tree.files, new Set(Object.keys(policies)), dependent.inserts))
|
|
379
|
+
findings.push(...checkAccessViewKeys(tree.files, accessKeys(policies)))
|
|
262
380
|
}
|
|
263
381
|
const bunfig = tree.files.get(BUNFIG_FILE)
|
|
264
382
|
if (bunfig !== undefined) findings.push(...checkTestSuiteConfig(bunfig))
|
|
265
|
-
const jobs = contract === undefined ? [] : contractJobs(contract, graph)
|
|
266
|
-
for (const name of ZEROPS_FILES) {
|
|
267
|
-
const text = tree.files.get(name)
|
|
268
|
-
if (text !== undefined) findings.push(...checkCrontab(name, text, jobs))
|
|
269
|
-
}
|
|
270
383
|
return findings.sort(compareFindings)
|
|
271
384
|
}
|
package/src/cli.ts
CHANGED
|
@@ -4,12 +4,14 @@ import { readFile } from 'node:fs/promises'
|
|
|
4
4
|
import { resolve } from 'node:path'
|
|
5
5
|
import { checkApplication } from './check'
|
|
6
6
|
import { type Finding, formatFinding } from './finding'
|
|
7
|
+
import { readMigrationBase } from './migration-base'
|
|
7
8
|
import { type PackedSet, readPackedSet } from './packed'
|
|
9
|
+
import type { MigrationBase } from './rules/migration-history'
|
|
8
10
|
|
|
9
11
|
const USAGE = `fabrika-check — the application checker
|
|
10
12
|
|
|
11
13
|
Usage:
|
|
12
|
-
fabrika-check [--packed <release-manifest.json>] [<root>]
|
|
14
|
+
fabrika-check [--hints] [--packed <release-manifest.json>] [--base <ref>] [<root>]
|
|
13
15
|
|
|
14
16
|
Checks the application in <root> (default: the current directory) and prints one line per finding:
|
|
15
17
|
<file>:<line>:<column> <rule> <message> (allowed form: <what to write instead>)
|
|
@@ -18,8 +20,12 @@ Checks the application in <root> (default: the current directory) and prints one
|
|
|
18
20
|
file: specifiers and overrides of its @fabrika/* packages, and their lockfile entries, when each tarball's bytes
|
|
19
21
|
match the sha512 the manifest records. Only a local or dogfood setup passes it; the platform build never does.
|
|
20
22
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
+
In a git work tree, every migration of db/migrations at the merge base of HEAD and the remote's default branch
|
|
24
|
+
(origin/HEAD, else origin/main or origin/master) must be in the tree unchanged: a deploy refuses a migration that
|
|
25
|
+
changed after it was applied. --base names another ref to compare with.
|
|
26
|
+
|
|
27
|
+
A refusal fails the check. A hint reports a step out of the application architecture and does not fail it. Without
|
|
28
|
+
--hints the checker prints how many there are; with it, it lists them under their own heading after the refusals.
|
|
23
29
|
|
|
24
30
|
Exit status: 0 with no refusals, 1 with a refusal, 2 on a usage or read error.
|
|
25
31
|
There is no suppression syntax; a finding is fixed in the code.
|
|
@@ -32,20 +38,27 @@ const count = (amount: number, noun: string): string => `${amount} ${noun}${amou
|
|
|
32
38
|
interface Arguments {
|
|
33
39
|
readonly root: string | undefined
|
|
34
40
|
readonly packed: string | undefined
|
|
41
|
+
readonly base: string | undefined
|
|
42
|
+
readonly hints: boolean
|
|
35
43
|
}
|
|
36
44
|
|
|
37
|
-
/** The root
|
|
45
|
+
/** The root, the `--packed` manifest, the `--base` ref and `--hints`, or the first argument the checker does not take. */
|
|
38
46
|
const parseArguments = (argv: readonly string[]): Arguments | { readonly unexpected: string } => {
|
|
39
47
|
let root: string | undefined
|
|
40
48
|
let packed: string | undefined
|
|
49
|
+
let base: string | undefined
|
|
50
|
+
let hints = false
|
|
41
51
|
for (let index = 0; index < argv.length; index++) {
|
|
42
52
|
const argument = argv[index] ?? ''
|
|
43
53
|
if (argument === '--packed' && packed === undefined && argv[index + 1] !== undefined) packed = argv[++index]
|
|
44
54
|
else if (argument.startsWith('--packed=') && packed === undefined) packed = argument.slice('--packed='.length)
|
|
55
|
+
else if (argument === '--base' && base === undefined && argv[index + 1] !== undefined) base = argv[++index]
|
|
56
|
+
else if (argument.startsWith('--base=') && base === undefined && argument.length > '--base='.length) base = argument.slice('--base='.length)
|
|
57
|
+
else if (argument === '--hints' && !hints) hints = true
|
|
45
58
|
else if (argument.startsWith('-') || root !== undefined) return { unexpected: argument }
|
|
46
59
|
else root = argument
|
|
47
60
|
}
|
|
48
|
-
return { root, packed }
|
|
61
|
+
return { root, packed, base, hints }
|
|
49
62
|
}
|
|
50
63
|
|
|
51
64
|
const main = async (argv: readonly string[]): Promise<number> => {
|
|
@@ -69,9 +82,18 @@ const main = async (argv: readonly string[]): Promise<number> => {
|
|
|
69
82
|
}
|
|
70
83
|
console.error(`fabrika-check: accepting the tarballs of the local pack ${packed.version}, which no deploy build does`)
|
|
71
84
|
}
|
|
85
|
+
const read = await readMigrationBase(root, parsed.base)
|
|
86
|
+
let migrationBase: MigrationBase | undefined
|
|
87
|
+
if (read !== null && !('skipped' in read)) migrationBase = read
|
|
88
|
+
else if (parsed.base !== undefined) {
|
|
89
|
+
console.error(
|
|
90
|
+
`fabrika-check: cannot compare the migrations with ${parsed.base}: ${read === null ? `${root} is in no git work tree` : read.skipped}`,
|
|
91
|
+
)
|
|
92
|
+
return 2
|
|
93
|
+
} else if (read !== null) console.error(`fabrika-check: migration-edited did not run: ${read.skipped}`)
|
|
72
94
|
let findings: Finding[]
|
|
73
95
|
try {
|
|
74
|
-
findings = await checkApplication({ root, packed })
|
|
96
|
+
findings = await checkApplication({ root, packed, migrationBase })
|
|
75
97
|
} catch (error) {
|
|
76
98
|
console.error(`fabrika-check: cannot read ${root}: ${error instanceof Error ? error.message : 'unknown error'}`)
|
|
77
99
|
return 2
|
|
@@ -79,8 +101,12 @@ const main = async (argv: readonly string[]): Promise<number> => {
|
|
|
79
101
|
const refusals = findings.filter((finding) => finding.severity === 'refusal')
|
|
80
102
|
const hints = findings.filter((finding) => finding.severity === 'hint')
|
|
81
103
|
for (const finding of refusals) console.log(formatFinding(finding))
|
|
82
|
-
if (hints
|
|
83
|
-
|
|
104
|
+
if (parsed.hints) {
|
|
105
|
+
if (hints.length > 0) console.log(HINTS_HEADING)
|
|
106
|
+
for (const finding of hints) console.log(formatFinding(finding))
|
|
107
|
+
} else if (hints.length > 0) {
|
|
108
|
+
console.log(`${count(hints.length, 'hint')} not listed (hints do not fail the check): fabrika-check --hints lists them`)
|
|
109
|
+
}
|
|
84
110
|
console.error(`fabrika-check: ${count(refusals.length, 'refusal')}, ${count(hints.length, 'hint')}`)
|
|
85
111
|
return refusals.length === 0 ? 0 : 1
|
|
86
112
|
}
|