@fabrika/check 0.9.0-dev.1 → 0.9.0-dev.11
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 -11
- package/src/check.ts +58 -9
- package/src/cli.ts +23 -4
- package/src/dialect.ts +29 -0
- package/src/endpoint-fixtures.ts +99 -13
- package/src/finding.ts +12 -3
- package/src/index.ts +4 -1
- package/src/layout.ts +16 -1
- package/src/migration-base.ts +85 -0
- package/src/reader/surface.ts +15 -0
- package/src/reader/value.ts +1 -1
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/framework.ts +2 -2
- package/src/rules/isolation.ts +5 -1
- package/src/rules/migration-history.ts +70 -0
- package/src/rules/migrations.ts +63 -0
- package/src/rules/modules.ts +3 -3
- package/src/rules/platform-migrations.ts +93 -0
- package/src/rules/runtime.ts +13 -7
- package/src/rules/structure.ts +26 -1
- package/src/rules/tests.ts +1 -1
- package/src/scaffold.ts +398 -71
- package/src/trust.ts +8 -4
- package/types/src/ast.d.ts +65 -0
- package/types/src/bun-plugin.d.ts +12 -0
- package/types/src/check.d.ts +22 -0
- package/types/src/cli.d.ts +2 -0
- package/types/src/contract.d.ts +58 -0
- package/types/src/dialect.d.ts +8 -0
- package/types/src/endpoint-fixtures.d.ts +54 -0
- package/types/src/finding.d.ts +39 -0
- package/types/src/graph.d.ts +68 -0
- package/types/src/index.d.ts +9 -0
- package/types/src/inputs.d.ts +9 -0
- package/types/src/jsonc.d.ts +2 -0
- package/types/src/layout.d.ts +76 -0
- package/types/src/limits.d.ts +15 -0
- package/types/src/lockfile.d.ts +19 -0
- package/types/src/migration-base.d.ts +9 -0
- package/types/src/packed.d.ts +15 -0
- package/types/src/reader/problems.d.ts +7 -0
- package/types/src/reader/schema.d.ts +18 -0
- package/types/src/reader/surface.d.ts +5 -0
- package/types/src/reader/tables.d.ts +6 -0
- package/types/src/reader/value.d.ts +113 -0
- package/types/src/references.d.ts +15 -0
- package/types/src/resolution.d.ts +20 -0
- package/types/src/rules/cloudflare.d.ts +9 -0
- package/types/src/rules/contract.d.ts +8 -0
- package/types/src/rules/crontab.d.ts +15 -0
- package/types/src/rules/framework.d.ts +19 -0
- package/types/src/rules/identity.d.ts +5 -0
- package/types/src/rules/isolation.d.ts +18 -0
- package/types/src/rules/json.d.ts +3 -0
- package/types/src/rules/literal.d.ts +63 -0
- package/types/src/rules/migration-history.d.ts +12 -0
- package/types/src/rules/migrations.d.ts +40 -0
- package/types/src/rules/modules.d.ts +12 -0
- package/types/src/rules/packages.d.ts +7 -0
- package/types/src/rules/platform-migrations.d.ts +13 -0
- package/types/src/rules/runtime.d.ts +34 -0
- package/types/src/rules/structure.d.ts +41 -0
- package/types/src/rules/tests.d.ts +22 -0
- package/types/src/rules/types.d.ts +4 -0
- package/types/src/scaffold-sample.d.ts +8 -0
- package/types/src/scaffold.d.ts +36 -0
- package/types/src/scope.d.ts +6 -0
- package/types/src/slice.d.ts +30 -0
- package/types/src/source-maps-cli.d.ts +4 -0
- package/types/src/source-maps.d.ts +32 -0
- package/types/src/toml.d.ts +30 -0
- package/types/src/trust.d.ts +15 -0
- package/types/src/version.d.ts +2 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The migrations `migration-edited` compares the tree with: those of the merge base of HEAD and the remote's default
|
|
2
|
+
// branch, read with git. Only the bin reads them; a caller with the files of a commit (Control, a deploy build) has no
|
|
3
|
+
// history to compare with, and the runner's checksum stays the real check.
|
|
4
|
+
|
|
5
|
+
import { MIGRATIONS_DIR } from './layout'
|
|
6
|
+
import type { MigrationBase } from './rules/migration-history'
|
|
7
|
+
|
|
8
|
+
/** What the default base is looked up as, in order, when the bin is given no `--base`. */
|
|
9
|
+
const DEFAULT_REFS = ['origin/main', 'origin/master']
|
|
10
|
+
|
|
11
|
+
interface GitResult {
|
|
12
|
+
readonly ok: boolean
|
|
13
|
+
readonly stdout: Uint8Array
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const git = async (root: string, args: readonly string[], stdin?: string): Promise<GitResult> => {
|
|
17
|
+
const input = stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin)
|
|
18
|
+
const child = Bun.spawn(['git', '-C', root, ...args], { stdin: input, stdout: 'pipe', stderr: 'ignore' })
|
|
19
|
+
const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).arrayBuffer()])
|
|
20
|
+
return { ok: code === 0, stdout: new Uint8Array(stdout) }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const text = (bytes: Uint8Array): string => new TextDecoder().decode(bytes).trim()
|
|
24
|
+
|
|
25
|
+
/** The remote's default branch: `origin/HEAD` where the clone recorded it, else the first of `DEFAULT_REFS` that exists. */
|
|
26
|
+
const defaultRef = async (root: string): Promise<string | null> => {
|
|
27
|
+
const head = await git(root, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD'])
|
|
28
|
+
if (head.ok && text(head.stdout) !== '') return text(head.stdout)
|
|
29
|
+
for (const ref of DEFAULT_REFS) {
|
|
30
|
+
if ((await git(root, ['rev-parse', '--verify', '-q', `${ref}^{commit}`])).ok) return ref
|
|
31
|
+
}
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Each regular file directly in `db/migrations/` at `commit`, by its blob id. */
|
|
36
|
+
const migrationBlobs = async (root: string, commit: string): Promise<Map<string, string> | null> => {
|
|
37
|
+
const listed = await git(root, ['ls-tree', '-z', commit, '--', MIGRATIONS_DIR])
|
|
38
|
+
if (!listed.ok) return null
|
|
39
|
+
const blobs = new Map<string, string>()
|
|
40
|
+
for (const entry of new TextDecoder().decode(listed.stdout).split('\0')) {
|
|
41
|
+
const match = /^(100644|100755) blob ([0-9a-f]+)\t(.+)$/.exec(entry)
|
|
42
|
+
if (match?.[2] !== undefined && match[3] !== undefined && match[3].endsWith('.sql')) blobs.set(match[3], match[2])
|
|
43
|
+
}
|
|
44
|
+
return blobs
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The blobs' texts, through one `git cat-file --batch`: each answer is `<id> blob <size>\n<bytes>\n`. */
|
|
48
|
+
const blobTexts = async (root: string, blobs: ReadonlyMap<string, string>): Promise<Map<string, string> | null> => {
|
|
49
|
+
if (blobs.size === 0) return new Map()
|
|
50
|
+
const ids = [...blobs.values()]
|
|
51
|
+
const batch = await git(root, ['cat-file', '--batch'], ids.map((id) => `${id}\n`).join(''))
|
|
52
|
+
if (!batch.ok) return null
|
|
53
|
+
const decoder = new TextDecoder()
|
|
54
|
+
const texts = new Map<string, string>()
|
|
55
|
+
let offset = 0
|
|
56
|
+
for (const id of ids) {
|
|
57
|
+
const end = batch.stdout.indexOf(10, offset)
|
|
58
|
+
const header = /^([0-9a-f]+) blob (\d+)$/.exec(decoder.decode(batch.stdout.subarray(offset, end)))
|
|
59
|
+
if (end < 0 || header?.[1] !== id || header[2] === undefined) return null
|
|
60
|
+
const size = Number(header[2])
|
|
61
|
+
texts.set(id, decoder.decode(batch.stdout.subarray(end + 1, end + 1 + size)))
|
|
62
|
+
offset = end + 1 + size + 1
|
|
63
|
+
}
|
|
64
|
+
return new Map([...blobs].map(([path, id]) => [path, texts.get(id) ?? '']))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
|
|
69
|
+
* the merge base so that migrations the default branch added since the branch forked are not read as deleted.
|
|
70
|
+
* `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
|
|
71
|
+
*/
|
|
72
|
+
export const readMigrationBase = async (root: string, ref?: string): Promise<MigrationBase | { readonly skipped: string } | null> => {
|
|
73
|
+
if (!(await git(root, ['rev-parse', '--is-inside-work-tree'])).ok) return null
|
|
74
|
+
const named = ref ?? (await defaultRef(root))
|
|
75
|
+
if (named === null) return { skipped: `no origin/HEAD, ${DEFAULT_REFS.join(' or ')} to compare the migrations with; pass --base <ref>` }
|
|
76
|
+
if (named.startsWith('-') || !(await git(root, ['rev-parse', '--verify', '-q', `${named}^{commit}`])).ok) {
|
|
77
|
+
return { skipped: `${named} names no commit` }
|
|
78
|
+
}
|
|
79
|
+
const mergeBase = await git(root, ['merge-base', 'HEAD', named])
|
|
80
|
+
if (!mergeBase.ok) return { skipped: `HEAD and ${named} share no commit this clone holds` }
|
|
81
|
+
const blobs = await migrationBlobs(root, text(mergeBase.stdout))
|
|
82
|
+
const files = blobs === null ? null : await blobTexts(root, blobs)
|
|
83
|
+
if (files === null) return { skipped: `the migrations of ${named} cannot be read` }
|
|
84
|
+
return { ref: named, files }
|
|
85
|
+
}
|
package/src/reader/surface.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
type ExportAccessDeclaration,
|
|
19
19
|
type FileKind,
|
|
20
20
|
type ImportDeclaration,
|
|
21
|
+
isPath,
|
|
21
22
|
type KitImportDeclaration,
|
|
22
23
|
kitImportsSection,
|
|
23
24
|
kitUnknownOptions,
|
|
@@ -31,6 +32,7 @@ import {
|
|
|
31
32
|
type SpaAccessDeclaration,
|
|
32
33
|
type Surface,
|
|
33
34
|
SURFACE_SECTIONS,
|
|
35
|
+
type TerminalDeclaration,
|
|
34
36
|
type TokenPurpose,
|
|
35
37
|
type TokenPurposes,
|
|
36
38
|
unknownOptions,
|
|
@@ -213,6 +215,7 @@ class SurfaceReader {
|
|
|
213
215
|
'mail',
|
|
214
216
|
'members',
|
|
215
217
|
'directory',
|
|
218
|
+
'terminal',
|
|
216
219
|
])
|
|
217
220
|
const locale = fields.get('locale')
|
|
218
221
|
const displayName = fields.get('displayName')
|
|
@@ -220,6 +223,7 @@ class SurfaceReader {
|
|
|
220
223
|
const members = fields.get('members')
|
|
221
224
|
const memberFields = members === undefined ? undefined : strictFields(members, 'the vocabulary members', ['manage', 'list'], [])
|
|
222
225
|
const directory = fields.get('directory')
|
|
226
|
+
const terminal = fields.get('terminal')
|
|
223
227
|
return {
|
|
224
228
|
app: text(fields.get('app'), value, 'app'),
|
|
225
229
|
...(locale === undefined ? {} : { locale: localeOf(locale, value) }),
|
|
@@ -229,6 +233,7 @@ class SurfaceReader {
|
|
|
229
233
|
? {}
|
|
230
234
|
: { members: { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') } }),
|
|
231
235
|
...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
|
|
236
|
+
...(terminal === undefined ? {} : { terminal: terminalOf(terminal) }),
|
|
232
237
|
dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
|
|
233
238
|
actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
|
|
234
239
|
roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
|
|
@@ -936,6 +941,16 @@ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
|
|
|
936
941
|
return directory
|
|
937
942
|
}
|
|
938
943
|
|
|
944
|
+
/** The vocabulary's `terminal: { identify: '/path' }`; `buildArtifact` checks the path itself. */
|
|
945
|
+
function terminalOf(value: LiteralValue): TerminalDeclaration {
|
|
946
|
+
const identify = strictFields(value, 'the vocabulary terminal', ['identify'], []).get('identify')
|
|
947
|
+
const path = text(identify, value, 'terminal.identify')
|
|
948
|
+
if (!isPath(path)) {
|
|
949
|
+
throw new Refused(identify?.at ?? value.at, `terminal.identify is '${path}'`, "terminal: { identify: '/identify' }")
|
|
950
|
+
}
|
|
951
|
+
return { identify: path }
|
|
952
|
+
}
|
|
953
|
+
|
|
939
954
|
function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
|
|
940
955
|
return value === undefined ? undefined : text(value, value, field)
|
|
941
956
|
}
|
package/src/reader/value.ts
CHANGED
|
@@ -83,7 +83,7 @@ type Role = { readonly callback: Kit } | { readonly procedures: Kit } | null
|
|
|
83
83
|
const callbackKit = (kind: BuilderKind): Kit => (kind === 'shell' ? 'shell' : kind === 'endpoints' ? 'endpoints' : 'surface')
|
|
84
84
|
|
|
85
85
|
/** The fields `defineVocabulary` copies from its argument, in its order. */
|
|
86
|
-
const VOCABULARY_SECTIONS = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail'] as const
|
|
86
|
+
const VOCABULARY_SECTIONS = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail', 'members', 'directory', 'terminal'] as const
|
|
87
87
|
|
|
88
88
|
const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
|
|
89
89
|
|
package/src/resolution.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isBuiltin } from 'node:module'
|
|
2
2
|
import { z } from 'zod/v4'
|
|
3
3
|
import { parseJsonc } from './jsonc'
|
|
4
|
-
import {
|
|
4
|
+
import { isRelativeSpecifier, isSkippedPath, joinRelative, resolveRelative } from './layout'
|
|
5
5
|
|
|
6
6
|
/** Pattern → targets. A target is a bare specifier, an absolute path, or `./<path from the root>` (`../…` above it). */
|
|
7
7
|
type MappingTable = ReadonlyMap<string, readonly string[]>
|
|
@@ -139,7 +139,7 @@ export const readImportMappings = (files: ReadonlyMap<string, string>): ImportMa
|
|
|
139
139
|
},
|
|
140
140
|
mayExist: (target) => {
|
|
141
141
|
const path = target.startsWith('/') ? undefined : joinRelative('package.json', target)
|
|
142
|
-
if (path === undefined || path
|
|
142
|
+
if (path === undefined || isSkippedPath(path)) return true
|
|
143
143
|
return resolveRelative((candidate) => files.has(candidate), 'package.json', `./${path}`).kind !== 'missing'
|
|
144
144
|
},
|
|
145
145
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
|
|
2
|
+
import type { ContractArtifact } from '@fabrika/auth-core'
|
|
3
|
+
import type { Finding } from '../finding'
|
|
4
|
+
import { CONTRACT_FILE } from '../layout'
|
|
5
|
+
|
|
6
|
+
const at = (rule: 'cloudflare-scan' | 'cloudflare-job-segment', message: string, allowed: string): Finding => ({
|
|
7
|
+
file: CONTRACT_FILE,
|
|
8
|
+
line: 1,
|
|
9
|
+
column: 1,
|
|
10
|
+
severity: 'refusal',
|
|
11
|
+
rule,
|
|
12
|
+
message,
|
|
13
|
+
allowed,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
/** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
|
|
17
|
+
const outsideCalls = (reach: { readonly egress?: readonly string[]; readonly connect: readonly string[] }): string[] => [
|
|
18
|
+
...(reach.egress ?? []).map((origin) => `egress ${origin}`),
|
|
19
|
+
...reach.connect.map((name) => `connect ${name}`),
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* What an application on Cloudflare cannot declare (ADR-0065): a file kind that scans, because no scanner runs there; a
|
|
24
|
+
* job longer than one segment, because the object runs it inside an alarm or a request. And a hint for a mutation that
|
|
25
|
+
* declares an outside call: the object runs one transaction at a time, and the mutation holds it while the call waits
|
|
26
|
+
* (backlog 216 item 7).
|
|
27
|
+
*/
|
|
28
|
+
export const checkCloudflareContract = (artifact: ContractArtifact): Finding[] => [
|
|
29
|
+
...Object.entries(artifact.fileKinds ?? {}).filter(([, kind]) => kind.scan === true).map(([name]) =>
|
|
30
|
+
at(
|
|
31
|
+
'cloudflare-scan',
|
|
32
|
+
`the file kind ${name} scans its files (scan: true), which an application on Cloudflare cannot: no scanner runs there`,
|
|
33
|
+
`c.files({ types, maxBytes }) without scan for ${name}, and no public procedure that takes its files`,
|
|
34
|
+
)
|
|
35
|
+
),
|
|
36
|
+
...Object.entries(artifact.jobs).filter(([, job]) => job.timeoutMs > CLOUDFLARE_MAX_JOB_SEGMENT_MS).map(([name, job]) =>
|
|
37
|
+
at(
|
|
38
|
+
'cloudflare-job-segment',
|
|
39
|
+
`the job ${name} runs up to ${job.timeoutMs} ms, and a job segment on Cloudflare runs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} ms`,
|
|
40
|
+
`limits.timeoutMs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} for ${name}: claim a bounded batch per run, and the next run takes the rest; a Workflow for one longer run is planned (backlog 230)`,
|
|
41
|
+
)
|
|
42
|
+
),
|
|
43
|
+
...artifact.endpoints.filter((endpoint) => endpoint.kind === 'mutation').flatMap((endpoint): Finding[] => {
|
|
44
|
+
const reach = artifact.declared?.[endpoint.id]
|
|
45
|
+
const calls = reach === undefined ? [] : outsideCalls(reach)
|
|
46
|
+
if (calls.length === 0) return []
|
|
47
|
+
return [{
|
|
48
|
+
file: CONTRACT_FILE,
|
|
49
|
+
line: 1,
|
|
50
|
+
column: 1,
|
|
51
|
+
severity: 'hint',
|
|
52
|
+
rule: 'cloudflare-held-call',
|
|
53
|
+
message: `${endpoint.id} is a mutation that declares ${
|
|
54
|
+
calls.join(', ')
|
|
55
|
+
}: on Cloudflare it waits for that call inside the object's transaction, which holds the whole environment`,
|
|
56
|
+
allowed: "record a row and ctx.kick('<job>'); the job declares the call and makes it outside ctx.transaction",
|
|
57
|
+
}]
|
|
58
|
+
}),
|
|
59
|
+
]
|
package/src/rules/framework.ts
CHANGED
|
@@ -79,7 +79,7 @@ export const trustedBindings = (file: string, program: AstNode, mappings: Import
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
/**
|
|
82
|
-
* The trusted binding a member chain starts from (`Database.
|
|
82
|
+
* The trusted binding a member chain starts from (`Database.fromEngine`, `db['Database'].fromEngine` → `Database`, `db`),
|
|
83
83
|
* when the name at `ancestors` denotes that declaration and no local that shadows it.
|
|
84
84
|
*/
|
|
85
85
|
const trustedRoot = (
|
|
@@ -135,7 +135,7 @@ const WRITERS = new Set([
|
|
|
135
135
|
|
|
136
136
|
/**
|
|
137
137
|
* A write to a member of a value from `@fabrika/*` or `zod`: an assignment, `delete`, `++`, or a writer call on it. A
|
|
138
|
-
* replaced `
|
|
138
|
+
* replaced `openPostgres` receives the database URL; a patched schema changes what the contract admits. A write
|
|
139
139
|
* through a prototype is `prototype-assignment`'s. A local that shadows such a name is not one.
|
|
140
140
|
*/
|
|
141
141
|
export const checkFrameworkWrite = (node: AstNode, ancestors: readonly AstNode[], bindings: TrustedBindings, report: Report): void => {
|
package/src/rules/isolation.ts
CHANGED
|
@@ -33,7 +33,11 @@ export const expectedGeneratedTests = async (
|
|
|
33
33
|
> => {
|
|
34
34
|
try {
|
|
35
35
|
const inputs = scaffoldInputs(files)
|
|
36
|
-
return {
|
|
36
|
+
return {
|
|
37
|
+
ok: true,
|
|
38
|
+
tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
|
|
39
|
+
missing: missingEndpointFixtures(inputs),
|
|
40
|
+
}
|
|
37
41
|
} catch (error) {
|
|
38
42
|
if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
|
|
39
43
|
if (error instanceof ContractError) {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// A migration that a shared branch already holds, edited, renamed or deleted in the tree being checked. Every runner
|
|
2
|
+
// keeps the SHA-256 of each applied file and refuses a deploy whose file changed after it ran (ADR-0017), and Control
|
|
3
|
+
// and the deploy see one commit, not its history: the checker is where the edit can be named before the push.
|
|
4
|
+
|
|
5
|
+
import type { Finding } from '../finding'
|
|
6
|
+
import { MIGRATIONS_DIR } from '../layout'
|
|
7
|
+
|
|
8
|
+
/** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
|
|
9
|
+
export interface MigrationBase {
|
|
10
|
+
/** How the commit is named to the author, such as `origin/main`. */
|
|
11
|
+
readonly ref: string
|
|
12
|
+
readonly files: ReadonlyMap<string, string>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const ALLOWED = 'the file as it is there, and the change as a new migration (bunx fabrika db new <slug>)'
|
|
16
|
+
|
|
17
|
+
const isMigration = (path: string): boolean => {
|
|
18
|
+
const name = path.slice(MIGRATIONS_DIR.length)
|
|
19
|
+
return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Lines without a trailing carriage return: a Windows checkout's line ends are not an edit of the committed file. */
|
|
23
|
+
const linesOf = (sql: string): string[] => sql.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
|
|
24
|
+
|
|
25
|
+
/** The first line where `current` leaves `base`, or its last line when it only lost lines at the end. */
|
|
26
|
+
const firstChangedLine = (base: readonly string[], current: readonly string[]): number | null => {
|
|
27
|
+
const length = Math.max(base.length, current.length)
|
|
28
|
+
for (let index = 0; index < length; index++) {
|
|
29
|
+
if (base[index] !== current[index]) return Math.min(index, current.length - 1) + 1
|
|
30
|
+
}
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
|
|
36
|
+
* removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
|
|
37
|
+
*/
|
|
38
|
+
export const checkMigrationHistory = (files: ReadonlyMap<string, string>, base: MigrationBase): Finding[] => {
|
|
39
|
+
const findings: Finding[] = []
|
|
40
|
+
for (const [path, committed] of base.files) {
|
|
41
|
+
if (!isMigration(path)) continue
|
|
42
|
+
const name = path.slice(MIGRATIONS_DIR.length)
|
|
43
|
+
const current = files.get(path)
|
|
44
|
+
if (current === undefined) {
|
|
45
|
+
findings.push({
|
|
46
|
+
file: path,
|
|
47
|
+
line: 1,
|
|
48
|
+
column: 1,
|
|
49
|
+
severity: 'refusal',
|
|
50
|
+
rule: 'migration-edited',
|
|
51
|
+
message:
|
|
52
|
+
`'${name}' is in ${base.ref} and was deleted or renamed: an environment that applied it keeps its changes, and a renamed file runs again there`,
|
|
53
|
+
allowed: ALLOWED,
|
|
54
|
+
})
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
const line = firstChangedLine(linesOf(committed), linesOf(current))
|
|
58
|
+
if (line === null) continue
|
|
59
|
+
findings.push({
|
|
60
|
+
file: path,
|
|
61
|
+
line,
|
|
62
|
+
column: 1,
|
|
63
|
+
severity: 'refusal',
|
|
64
|
+
rule: 'migration-edited',
|
|
65
|
+
message: `'${name}' differs from ${base.ref}: a deploy refuses a migration that changed after it was applied, even in a comment`,
|
|
66
|
+
allowed: ALLOWED,
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
return findings
|
|
70
|
+
}
|
package/src/rules/migrations.ts
CHANGED
|
@@ -2,11 +2,13 @@ import {
|
|
|
2
2
|
afterName,
|
|
3
3
|
closingParenthesis,
|
|
4
4
|
isPunct,
|
|
5
|
+
lexSqlite,
|
|
5
6
|
nameText,
|
|
6
7
|
objectNameAt,
|
|
7
8
|
skipWords,
|
|
8
9
|
splitAtCommas,
|
|
9
10
|
type SqlToken,
|
|
11
|
+
statementsOf,
|
|
10
12
|
topLevelStatements,
|
|
11
13
|
upperWord,
|
|
12
14
|
} from '@fabrika/platform-node/sql'
|
|
@@ -43,6 +45,67 @@ export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
|
|
|
43
45
|
return findings
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/** The default a SQLite timestamp column takes: the UTC ISO text every read of the table parses. */
|
|
49
|
+
const SQLITE_NOW_DEFAULT = "DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* On SQLite `DEFAULT CURRENT_TIMESTAMP` stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses as
|
|
53
|
+
* `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
|
|
54
|
+
*/
|
|
55
|
+
export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>): Finding[] => {
|
|
56
|
+
const findings: Finding[] = []
|
|
57
|
+
for (const [path, sql] of files) {
|
|
58
|
+
if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
|
|
59
|
+
for (const { tokens } of topLevelStatements(sql)) {
|
|
60
|
+
tokens.forEach((token, index) => {
|
|
61
|
+
if (upperWord(token) !== 'DEFAULT') return
|
|
62
|
+
const value = isPunct(tokens[index + 1], '(') ? tokens[index + 2] : tokens[index + 1]
|
|
63
|
+
if (value === undefined || upperWord(value) !== 'CURRENT_TIMESTAMP') return
|
|
64
|
+
findings.push({
|
|
65
|
+
file: path,
|
|
66
|
+
line: value.line,
|
|
67
|
+
column: 1,
|
|
68
|
+
severity: 'refusal',
|
|
69
|
+
rule: 'cloudflare-current-timestamp',
|
|
70
|
+
message: 'DEFAULT CURRENT_TIMESTAMP stores YYYY-MM-DD HH:MM:SS on SQLite, which every read of the table refuses as unexpected_row',
|
|
71
|
+
allowed: SQLITE_NOW_DEFAULT,
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return findings
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* On SQLite an application migration runs verbatim, with no name rule, so a view or a trigger over a framework table
|
|
81
|
+
* would reach what `ctx.sql`'s name rule keeps it from. Every `fabrika_*` name is refused (any case, quoted, bracketed,
|
|
82
|
+
* or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
|
|
83
|
+
*/
|
|
84
|
+
export const checkSqliteFrameworkNames = (files: ReadonlyMap<string, string>): Finding[] => {
|
|
85
|
+
const findings: Finding[] = []
|
|
86
|
+
for (const [path, sql] of files) {
|
|
87
|
+
if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
|
|
88
|
+
for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
|
|
89
|
+
tokens.forEach((token, index) => {
|
|
90
|
+
const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
|
|
91
|
+
const name = text?.toLowerCase()
|
|
92
|
+
if (name === undefined || !name.startsWith('fabrika_')) return
|
|
93
|
+
if (name === FILES_TABLE && token.kind !== 'string' && upperWord(tokens[index - 1]) === 'REFERENCES') return
|
|
94
|
+
findings.push({
|
|
95
|
+
file: path,
|
|
96
|
+
line: token.line,
|
|
97
|
+
column: 1,
|
|
98
|
+
severity: 'refusal',
|
|
99
|
+
rule: 'cloudflare-framework-name',
|
|
100
|
+
message: `'${text}' is the framework's: a migration on Cloudflare names no fabrika_* table, which ctx.sql could then reach through it`,
|
|
101
|
+
allowed: `the application's own tables, and REFERENCES ${FILES_TABLE} (id) for a file column`,
|
|
102
|
+
})
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return findings
|
|
107
|
+
}
|
|
108
|
+
|
|
46
109
|
/** A declared file column: `table.column` holds files of `kind`. */
|
|
47
110
|
export interface FileColumn {
|
|
48
111
|
readonly table: string
|
package/src/rules/modules.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Report } from '../finding'
|
|
2
|
-
import {
|
|
2
|
+
import { isRelativeSpecifier, isSkippedPath, isTestFile, joinRelative, resolveRelative } from '../layout'
|
|
3
3
|
import type { ModuleReference } from '../references'
|
|
4
4
|
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
5
5
|
|
|
@@ -94,7 +94,7 @@ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
|
|
|
94
94
|
* The test kits: the application's signs tokens with its own key and boots the application a second way; the
|
|
95
95
|
* database's reaches tables by name and seeds rows past the data layer. Production never loads either.
|
|
96
96
|
*/
|
|
97
|
-
const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing']
|
|
97
|
+
const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing', '@fabrika/db/testing-sqlite']
|
|
98
98
|
const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
|
|
99
99
|
|
|
100
100
|
export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))
|
|
@@ -114,7 +114,7 @@ const checkTestOnly = (reference: ModuleReference, target: string, report: Repor
|
|
|
114
114
|
/** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
|
|
115
115
|
const containmentProblem = (target: string | undefined): string | undefined => {
|
|
116
116
|
if (target === undefined) return 'resolves outside the application root, where the checker does not look'
|
|
117
|
-
if (target
|
|
117
|
+
if (isSkippedPath(target)) return 'resolves into a directory the checker skips'
|
|
118
118
|
return undefined
|
|
119
119
|
}
|
|
120
120
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// What the platform refuses of an application's migrations, found before the push instead of in a deploy's run log:
|
|
2
|
+
// the classifier Control runs on every snapshot, and on Cloudflare the backup's plan of the migrated schema, which every
|
|
3
|
+
// migration deploy takes first.
|
|
4
|
+
|
|
5
|
+
import { describeOpsDumpSchema, planOpsDump } from '@fabrika/auth-core'
|
|
6
|
+
import { withMigratedSqlite } from '@fabrika/db/codegen-sqlite'
|
|
7
|
+
import { FRAMEWORK_MIGRATION_BUNDLE } from '@fabrika/db/migrations'
|
|
8
|
+
import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
|
|
9
|
+
import { applicationDatabaseSchema, classifyMigrations } from '@fabrika/platform-node/sql'
|
|
10
|
+
import type { Finding } from '../finding'
|
|
11
|
+
import { MIGRATIONS_DIR } from '../layout'
|
|
12
|
+
|
|
13
|
+
interface MigrationText {
|
|
14
|
+
readonly path: string
|
|
15
|
+
readonly name: string
|
|
16
|
+
readonly sql: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The files of `db/migrations` itself, by name: the order the runner and Control read them in. */
|
|
20
|
+
const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
|
|
21
|
+
[...files].flatMap(([path, sql]) => {
|
|
22
|
+
const name = path.slice(MIGRATIONS_DIR.length)
|
|
23
|
+
return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/') ? [{ path, name, sql }] : []
|
|
24
|
+
}).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
|
|
28
|
+
* one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
|
|
29
|
+
* checked, applied or not: the checker does not know which an environment holds.
|
|
30
|
+
*/
|
|
31
|
+
export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
|
|
32
|
+
const texts = migrationTexts(files)
|
|
33
|
+
if (texts.length === 0) return []
|
|
34
|
+
const paths = new Map(texts.map((text) => [text.name, text.path]))
|
|
35
|
+
return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId)).files.flatMap((file) =>
|
|
36
|
+
file.refused.map((refusal): Finding => ({
|
|
37
|
+
file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
|
|
38
|
+
line: refusal.line,
|
|
39
|
+
column: 1,
|
|
40
|
+
severity: 'refusal',
|
|
41
|
+
rule: 'migration-refused',
|
|
42
|
+
message: `${refusal.reason} is not allowed: Control refuses the deploy that brings this migration`,
|
|
43
|
+
allowed: 'the statements, functions and objects the migration classifier admits (application-runtime reference, "Migrations")',
|
|
44
|
+
}))
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
|
|
50
|
+
* table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
|
|
51
|
+
* after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
|
|
52
|
+
*/
|
|
53
|
+
export const checkBackupPlan = async (files: ReadonlyMap<string, string>): Promise<Finding[]> => {
|
|
54
|
+
const texts = migrationTexts(files)
|
|
55
|
+
if (texts.length === 0) return []
|
|
56
|
+
let refused: { readonly table: string | null } | null
|
|
57
|
+
try {
|
|
58
|
+
refused = await withMigratedSqlite([
|
|
59
|
+
{ bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
|
|
60
|
+
{ bundle: 'app', migrations: texts.map(({ name, sql }) => ({ name, sql })) },
|
|
61
|
+
], (db) => {
|
|
62
|
+
const plan = planOpsDump(describeOpsDumpSchema((query, ...bindings) => db.query<Record<string, unknown>, string[]>(query).all(...bindings)))
|
|
63
|
+
return 'refused' in plan ? plan : null
|
|
64
|
+
})
|
|
65
|
+
} catch {
|
|
66
|
+
return []
|
|
67
|
+
}
|
|
68
|
+
if (refused === null) return []
|
|
69
|
+
const at = refused.table === null ? undefined : newestNaming(texts, refused.table)
|
|
70
|
+
const last = texts[texts.length - 1]
|
|
71
|
+
return [{
|
|
72
|
+
file: at?.path ?? last?.path ?? MIGRATIONS_DIR,
|
|
73
|
+
line: at?.line ?? 1,
|
|
74
|
+
column: 1,
|
|
75
|
+
severity: 'refusal',
|
|
76
|
+
rule: 'backup-schema',
|
|
77
|
+
message: refused.table === null
|
|
78
|
+
? 'the migrated schema cannot be backed up (a table name the data layer does not admit, or two tables of one name)'
|
|
79
|
+
: `table ${refused.table} cannot be backed up, and every migration deploy takes a backup first`,
|
|
80
|
+
allowed:
|
|
81
|
+
"a foreign key inside its table's cycle that is nullable, outside the primary key, referenced by no other key and named by no CHECK (ADR-0070 section 2); or no such key",
|
|
82
|
+
}]
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The newest migration that names `table`, and the first line there that does. */
|
|
86
|
+
const newestNaming = (texts: readonly MigrationText[], table: string): { path: string; line: number } | undefined => {
|
|
87
|
+
const word = new RegExp(`(^|[^A-Za-z0-9_$])["\`[]?${table.replace(/[$]/g, '\\$&')}["\`\\]]?($|[^A-Za-z0-9_$])`, 'i')
|
|
88
|
+
for (const text of [...texts].reverse()) {
|
|
89
|
+
const index = text.sql.split('\n').findIndex((line) => word.test(line))
|
|
90
|
+
if (index >= 0) return { path: text.path, line: index + 1 }
|
|
91
|
+
}
|
|
92
|
+
return undefined
|
|
93
|
+
}
|
package/src/rules/runtime.ts
CHANGED
|
@@ -482,9 +482,9 @@ const checkPrototypeWrite = (node: AstNode, context: SourceContext): void => {
|
|
|
482
482
|
|
|
483
483
|
const KEY_PREFIX = 'px_'
|
|
484
484
|
|
|
485
|
-
const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[],
|
|
485
|
+
const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], report: Report): void => {
|
|
486
486
|
if (texts.some((text) => text?.includes(KEY_PREFIX))) {
|
|
487
|
-
|
|
487
|
+
report(
|
|
488
488
|
node,
|
|
489
489
|
'key-literal',
|
|
490
490
|
`'${KEY_PREFIX}' in a literal: a key or a session cookie name in source`,
|
|
@@ -493,6 +493,15 @@ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[
|
|
|
493
493
|
}
|
|
494
494
|
}
|
|
495
495
|
|
|
496
|
+
/** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
|
|
497
|
+
export const checkKeyLiteralNode = (node: AstNode, report: Report): void => {
|
|
498
|
+
if (node.type === 'Literal') checkStringContent(node, [staticString(node)], report)
|
|
499
|
+
else if (node.type === 'TemplateElement') {
|
|
500
|
+
const { raw, cooked } = templateText(node)
|
|
501
|
+
checkStringContent(node, [raw, cooked], report)
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
496
505
|
const isTypeOnlyImport = (specifier: AstNode, parent: AstNode | undefined): boolean =>
|
|
497
506
|
stringField(specifier, 'importKind') === 'type' || (parent !== undefined && stringField(parent, 'importKind') === 'type')
|
|
498
507
|
|
|
@@ -536,11 +545,8 @@ export const checkRuntimeNode = (node: AstNode, ancestors: readonly AstNode[], c
|
|
|
536
545
|
return
|
|
537
546
|
}
|
|
538
547
|
case 'Literal':
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const { raw, cooked } = templateText(node)
|
|
542
|
-
return checkStringContent(node, [raw, cooked], context)
|
|
543
|
-
}
|
|
548
|
+
case 'TemplateElement':
|
|
549
|
+
return checkKeyLiteralNode(node, context.report)
|
|
544
550
|
case 'JSXAttribute': {
|
|
545
551
|
const name = child(node, 'name')
|
|
546
552
|
if (name?.type === 'JSXIdentifier' && stringField(name, 'name') === 'dangerouslySetInnerHTML') {
|
package/src/rules/structure.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { isBuiltin } from 'node:module'
|
|
2
2
|
import { type AstNode, child, identifierName, staticKey } from '../ast'
|
|
3
|
-
import { type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
|
|
3
|
+
import { type Finding, type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
|
|
4
4
|
import {
|
|
5
5
|
CONTRACT_FILE,
|
|
6
6
|
DATABASE_DIR,
|
|
7
7
|
isRelativeSpecifier,
|
|
8
8
|
isSourceFile,
|
|
9
9
|
isTestFile,
|
|
10
|
+
isToolModule,
|
|
10
11
|
resolveRelative,
|
|
11
12
|
SCHEMAS_DIR,
|
|
12
13
|
SCHEMAS_FILE,
|
|
@@ -221,6 +222,21 @@ const checkSliceReference = (place: StructurePlace, reference: ModuleReference,
|
|
|
221
222
|
)
|
|
222
223
|
}
|
|
223
224
|
|
|
225
|
+
/**
|
|
226
|
+
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
227
|
+
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
228
|
+
*/
|
|
229
|
+
export const checkToolPackages = (paths: readonly string[]): Finding[] =>
|
|
230
|
+
paths.filter((path) => isToolModule(path) && path.endsWith('/package.json')).map((path) => ({
|
|
231
|
+
file: path,
|
|
232
|
+
line: 1,
|
|
233
|
+
column: 1,
|
|
234
|
+
severity: 'refusal',
|
|
235
|
+
rule: 'tool-import',
|
|
236
|
+
message: `'${path}' makes a developer's tool a package, which the application could load by its name`,
|
|
237
|
+
allowed: "tools/ without a package.json: a tool's dependencies go in the root package.json",
|
|
238
|
+
}))
|
|
239
|
+
|
|
224
240
|
/** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
|
|
225
241
|
export const checkStructureReferences = (graph: StructureGraph, place: StructurePlace, report: Report): void => {
|
|
226
242
|
for (const reference of graph.referencesOf(place.file)) {
|
|
@@ -234,6 +250,15 @@ export const checkStructureReferences = (graph: StructureGraph, place: Structure
|
|
|
234
250
|
)
|
|
235
251
|
}
|
|
236
252
|
if (reference.typeOnly) continue
|
|
253
|
+
const tool = isToolModule(place.file) ? undefined : targets.files.find(isToolModule)
|
|
254
|
+
if (tool !== undefined) {
|
|
255
|
+
report(
|
|
256
|
+
reference.node,
|
|
257
|
+
'tool-import',
|
|
258
|
+
`'${reference.specifier}' loads ${tool}, a developer's tool, which nothing outside tools/ loads`,
|
|
259
|
+
'what the application and a tool share under src/ (pure code in src/shared/), imported by the tool',
|
|
260
|
+
)
|
|
261
|
+
}
|
|
237
262
|
if (place.file.startsWith(SPA_DIR) && !place.exempt) checkSpaReference(graph, reference, targets, report)
|
|
238
263
|
if (isSharedModule(place.file) && !place.exempt) checkSharedReference(reference, targets, report)
|
|
239
264
|
if (isLayerModule(place.file)) checkLayerReference(graph, place, reference, targets, report)
|
package/src/rules/tests.ts
CHANGED
|
@@ -33,7 +33,7 @@ const isAssertionCall = (node: AstNode): boolean => {
|
|
|
33
33
|
const path = memberPath(callee)
|
|
34
34
|
const [root] = path ?? []
|
|
35
35
|
const last = path?.[path.length - 1]
|
|
36
|
-
return root !== undefined && root !== 'expect' && (
|
|
36
|
+
return root !== undefined && root !== 'expect' && (root.startsWith('assert') || (last !== undefined && ASSERTION_NAME.test(last)))
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
/** Whether a test body runs an assertion; a nested function counts only where it is called or passed to a call. */
|