@fabrika/check 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,95 @@
1
+ import { type AstNode, child, children, identifierName, memberPath, staticKey, staticString, stringField, walk } from './ast'
2
+
3
+ /**
4
+ * One way a module names another: a static import, a re-export, a dynamic `import()`, `require()` (also `module.require`
5
+ * and `import.meta.require`) or `import x = require()`.
6
+ */
7
+ export interface ModuleReference {
8
+ readonly specifier: string
9
+ readonly node: AstNode
10
+ /** The names taken from the module: imported or re-exported names, `default`, or `*` for the whole module. */
11
+ readonly names: readonly string[]
12
+ /** Erased at compile time: `import type`, or a declaration whose every specifier is `type`. */
13
+ readonly typeOnly: boolean
14
+ }
15
+
16
+ const specifierName = (specifier: AstNode, key: 'imported' | 'local'): string => {
17
+ if (specifier.type === 'ImportDefaultSpecifier') return 'default'
18
+ if (specifier.type === 'ImportNamespaceSpecifier') return '*'
19
+ const name = child(specifier, key)
20
+ return identifierName(name) ?? staticString(name) ?? ''
21
+ }
22
+
23
+ /** A declaration with a specifier list: `import { a, type b } from 'x'`, `export { a, type b } from 'x'`. */
24
+ const listReference = (node: AstNode, kindField: 'importKind' | 'exportKind', nameKey: 'imported' | 'local'): ModuleReference | undefined => {
25
+ const specifier = staticString(child(node, 'source'))
26
+ if (specifier === undefined) return undefined
27
+ const specifiers = children(node, 'specifiers').filter((item): item is AstNode => item !== null)
28
+ const values = specifiers.filter((item) => stringField(item, kindField) !== 'type')
29
+ const typeOnly = stringField(node, kindField) === 'type' || (specifiers.length > 0 && values.length === 0)
30
+ return { specifier, node, names: typeOnly ? [] : values.map((item) => specifierName(item, nameKey)), typeOnly }
31
+ }
32
+
33
+ /** What a direct load takes: `require('x').a` → `a`; `const { a } = await import('x')` → `a`; anything else the whole module. */
34
+ const loadedNames = (load: AstNode, ancestors: readonly AstNode[]): readonly string[] => {
35
+ let value = load
36
+ let depth = ancestors.length - 1
37
+ let parent = ancestors[depth]
38
+ if (parent?.type === 'AwaitExpression' && parent['argument'] === load) {
39
+ value = parent
40
+ depth--
41
+ parent = ancestors[depth]
42
+ }
43
+ if (parent?.type === 'MemberExpression' && parent['object'] === value) return [staticKey(parent, 'property') ?? '*']
44
+ const pattern = parent?.type === 'VariableDeclarator' && parent['init'] === value ? child(parent, 'id') : undefined
45
+ if (pattern?.type !== 'ObjectPattern') return ['*']
46
+ return children(pattern, 'properties').map((property) => (property?.type === 'Property' ? (staticKey(property, 'key') ?? '*') : '*'))
47
+ }
48
+
49
+ export const isRequire = (callee: AstNode | undefined): boolean => {
50
+ if (callee === undefined) return false
51
+ const path = memberPath(callee)
52
+ if (path?.length === 1) return path[0] === 'require'
53
+ return path?.length === 2 && (path[0] === 'module' || path[0] === 'import.meta') && path[1] === 'require'
54
+ }
55
+
56
+ const referenceOf = (node: AstNode, ancestors: readonly AstNode[]): ModuleReference | undefined => {
57
+ switch (node.type) {
58
+ case 'ImportDeclaration':
59
+ return listReference(node, 'importKind', 'imported')
60
+ case 'ExportNamedDeclaration':
61
+ return listReference(node, 'exportKind', 'local')
62
+ case 'ExportAllDeclaration': {
63
+ const specifier = staticString(child(node, 'source'))
64
+ const typeOnly = stringField(node, 'exportKind') === 'type'
65
+ return specifier === undefined ? undefined : { specifier, node, names: typeOnly ? [] : ['*'], typeOnly }
66
+ }
67
+ case 'ImportExpression': {
68
+ const specifier = staticString(child(node, 'source'))
69
+ return specifier === undefined ? undefined : { specifier, node, names: loadedNames(node, ancestors), typeOnly: false }
70
+ }
71
+ case 'CallExpression': {
72
+ if (!isRequire(child(node, 'callee'))) return undefined
73
+ const specifier = staticString(children(node, 'arguments')[0] ?? undefined)
74
+ return specifier === undefined ? undefined : { specifier, node, names: loadedNames(node, ancestors), typeOnly: false }
75
+ }
76
+ case 'TSImportEqualsDeclaration': {
77
+ const reference = child(node, 'moduleReference')
78
+ if (reference?.type !== 'TSExternalModuleReference') return undefined
79
+ const specifier = staticString(child(reference, 'expression'))
80
+ const typeOnly = stringField(node, 'importKind') === 'type'
81
+ return specifier === undefined ? undefined : { specifier, node, names: typeOnly ? [] : ['*'], typeOnly }
82
+ }
83
+ default:
84
+ return undefined
85
+ }
86
+ }
87
+
88
+ export const moduleReferences = (program: AstNode): readonly ModuleReference[] => {
89
+ const references: ModuleReference[] = []
90
+ walk(program, (node, ancestors) => {
91
+ const reference = referenceOf(node, ancestors)
92
+ if (reference !== undefined) references.push(reference)
93
+ })
94
+ return references
95
+ }
@@ -0,0 +1,178 @@
1
+ import { isBuiltin } from 'node:module'
2
+ import { z } from 'zod/v4'
3
+ import { parseJsonc } from './jsonc'
4
+ import { isIgnoredSegment, isRelativeSpecifier, joinRelative, resolveRelative } from './layout'
5
+
6
+ /** Pattern → targets. A target is a bare specifier, an absolute path, or `./<path from the root>` (`../…` above it). */
7
+ type MappingTable = ReadonlyMap<string, readonly string[]>
8
+
9
+ /**
10
+ * The application's own import mappings, as Bun applies them to one module: `compilerOptions.paths` of the nearest
11
+ * `tsconfig.json` (or `jsconfig.json`), with its local `extends`, then `imports` of the nearest `package.json`.
12
+ */
13
+ export interface ImportMappings {
14
+ readonly paths: (file: string) => MappingTable
15
+ readonly imports: (file: string) => MappingTable
16
+ /** Whether Bun may find a module at a target; one outside what the checker reads counts, so a rule still sees it. */
17
+ readonly mayExist: (target: string) => boolean
18
+ }
19
+
20
+ const packageJsonSchema = z.object({ imports: z.record(z.string(), z.unknown()).optional() })
21
+ const tsconfigSchema = z.object({
22
+ extends: z.union([z.string(), z.array(z.string())]).optional(),
23
+ compilerOptions: z.object({ baseUrl: z.string().optional(), paths: z.record(z.string(), z.array(z.string())).optional() }).optional(),
24
+ })
25
+
26
+ const TSCONFIG_NAMES = ['tsconfig.json', 'jsconfig.json'] as const
27
+ const EMPTY: MappingTable = new Map()
28
+
29
+ /** Every target string of an import-map value, through its condition objects and fallback arrays. */
30
+ const targetStrings = (value: unknown): string[] => {
31
+ if (typeof value === 'string') return [value]
32
+ if (Array.isArray(value)) return value.flatMap(targetStrings)
33
+ if (typeof value === 'object' && value !== null) return Object.values(value).flatMap(targetStrings)
34
+ return []
35
+ }
36
+
37
+ /** The directories a module's configuration is looked up in, nearest first: `src/a/b.ts` → `src/a`, `src`, the root. */
38
+ const directoriesAbove = (file: string): readonly string[] => {
39
+ const segments = file.split('/').slice(0, -1)
40
+ const directories: string[] = []
41
+ for (let length = segments.length; length >= 0; length--) directories.push(segments.slice(0, length).join('/'))
42
+ return directories
43
+ }
44
+
45
+ const inDirectory = (directory: string, name: string): string => (directory === '' ? name : `${directory}/${name}`)
46
+
47
+ /** A path written in `configFile`, as `./<path from the root>`; `../<path>` when it climbs above the root. */
48
+ const fromRoot = (configFile: string, path: string): string => {
49
+ const joined = joinRelative(configFile, path)
50
+ return joined === undefined ? `../${path}` : `./${joined}`
51
+ }
52
+
53
+ const packageImports = (manifestFile: string, text: string): MappingTable => {
54
+ const manifest = packageJsonSchema.safeParse(parseJsonc(text))
55
+ const entries = new Map<string, readonly string[]>()
56
+ for (const [pattern, value] of Object.entries(manifest.success ? (manifest.data.imports ?? {}) : {})) {
57
+ entries.set(pattern, targetStrings(value).map((target) => (isRelativeSpecifier(target) ? fromRoot(manifestFile, target) : target)))
58
+ }
59
+ return entries
60
+ }
61
+
62
+ interface Declared<T> {
63
+ readonly value: T
64
+ /** The configuration file that declares it; relative paths in it are relative to that file. */
65
+ readonly file: string
66
+ }
67
+
68
+ interface TsconfigOptions {
69
+ readonly paths?: Declared<Readonly<Record<string, readonly string[]>>>
70
+ readonly baseUrl?: Declared<string>
71
+ }
72
+
73
+ /** `paths` and `baseUrl` after `extends`: the extending file wins, and of an `extends` array the last entry. */
74
+ const tsconfigOptions = (file: string, files: ReadonlyMap<string, string>, seen: ReadonlySet<string>): TsconfigOptions => {
75
+ const config = tsconfigSchema.safeParse(parseJsonc(files.get(file) ?? ''))
76
+ if (!config.success) return {}
77
+ let inherited: TsconfigOptions = {}
78
+ const extended = config.data.extends
79
+ for (const target of typeof extended === 'string' ? [extended] : (extended ?? [])) {
80
+ // `checkTrustedResolution` refuses any other extends; the checker reads no file outside the application.
81
+ const base = isRelativeSpecifier(target) ? joinRelative(file, target) : undefined
82
+ const resolved = base === undefined ? undefined : [base, `${base}.json`].find((candidate) => files.has(candidate))
83
+ if (resolved === undefined || seen.has(resolved)) continue
84
+ const parent = tsconfigOptions(resolved, files, new Set([...seen, resolved]))
85
+ inherited = { paths: parent.paths ?? inherited.paths, baseUrl: parent.baseUrl ?? inherited.baseUrl }
86
+ }
87
+ const options = config.data.compilerOptions
88
+ return {
89
+ paths: options?.paths === undefined ? inherited.paths : { value: options.paths, file },
90
+ baseUrl: options?.baseUrl === undefined ? inherited.baseUrl : { value: options.baseUrl, file },
91
+ }
92
+ }
93
+
94
+ /** `paths` targets are relative to `baseUrl` when one is set, and otherwise to the file that declares `paths`. */
95
+ const tsconfigPaths = (file: string, files: ReadonlyMap<string, string>): MappingTable => {
96
+ const { paths, baseUrl } = tsconfigOptions(file, files, new Set([file]))
97
+ if (paths === undefined) return EMPTY
98
+ const baseDirectory = baseUrl === undefined ? undefined : joinRelative(baseUrl.file, baseUrl.value)
99
+ const resolve = (target: string): string => {
100
+ if (target.startsWith('/')) return target
101
+ if (baseUrl === undefined) return fromRoot(paths.file, target)
102
+ // A file in the baseUrl directory, which the target is relative to.
103
+ return baseDirectory === undefined ? `../${target}` : fromRoot(inDirectory(baseDirectory, 'tsconfig.json'), target)
104
+ }
105
+ const entries = new Map<string, readonly string[]>()
106
+ for (const [pattern, targets] of Object.entries(paths.value)) entries.set(pattern, targets.map(resolve))
107
+ return entries
108
+ }
109
+
110
+ const memoized = <T>(compute: (key: string) => T): (key: string) => T => {
111
+ const cache = new Map<string, T>()
112
+ return (key) => {
113
+ const cached = cache.get(key)
114
+ if (cached !== undefined) return cached
115
+ const value = compute(key)
116
+ cache.set(key, value)
117
+ return value
118
+ }
119
+ }
120
+
121
+ export const readImportMappings = (files: ReadonlyMap<string, string>): ImportMappings => {
122
+ const nearest = (file: string, names: readonly string[]): string | undefined => {
123
+ for (const directory of directoriesAbove(file)) {
124
+ const found = names.map((name) => inDirectory(directory, name)).find((path) => files.has(path))
125
+ if (found !== undefined) return found
126
+ }
127
+ return undefined
128
+ }
129
+ const pathsOf = memoized((config: string) => tsconfigPaths(config, files))
130
+ const importsOf = memoized((manifest: string) => packageImports(manifest, files.get(manifest) ?? ''))
131
+ return {
132
+ paths: (file) => {
133
+ const config = nearest(file, TSCONFIG_NAMES)
134
+ return config === undefined ? EMPTY : pathsOf(config)
135
+ },
136
+ imports: (file) => {
137
+ const manifest = nearest(file, ['package.json'])
138
+ return manifest === undefined ? EMPTY : importsOf(manifest)
139
+ },
140
+ mayExist: (target) => {
141
+ const path = target.startsWith('/') ? undefined : joinRelative('package.json', target)
142
+ if (path === undefined || path.split('/').some(isIgnoredSegment)) return true
143
+ return resolveRelative((candidate) => files.has(candidate), 'package.json', `./${path}`).kind !== 'missing'
144
+ },
145
+ }
146
+ }
147
+
148
+ /**
149
+ * The targets of the exact key, else of the most specific matching pattern: the longest prefix before its `*`, then the
150
+ * longest key (Node's and Bun's order for `imports`: `#x/*.ts` before `#x/*`).
151
+ */
152
+ const matchTable = (table: MappingTable, specifier: string): readonly string[] | undefined => {
153
+ const exact = specifier.includes('*') ? undefined : table.get(specifier)
154
+ if (exact !== undefined) return exact
155
+ let best: { readonly prefix: number; readonly key: number; readonly targets: readonly string[] } | undefined
156
+ for (const [pattern, targets] of table) {
157
+ const star = pattern.indexOf('*')
158
+ if (star === -1) continue
159
+ const prefix = pattern.slice(0, star)
160
+ const suffix = pattern.slice(star + 1)
161
+ if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix) || specifier.length < prefix.length + suffix.length) continue
162
+ if (best !== undefined && (best.prefix > prefix.length || (best.prefix === prefix.length && best.key >= pattern.length))) continue
163
+ const captured = specifier.slice(prefix.length, specifier.length - suffix.length)
164
+ best = { prefix: prefix.length, key: pattern.length, targets: targets.map((target) => target.replace('*', captured)) }
165
+ }
166
+ return best?.targets
167
+ }
168
+
169
+ /**
170
+ * What a bare specifier in `file` is mapped to, in Bun's order: a builtin is never mapped; then the first `paths`
171
+ * target that exists; when none does, the package scope's `imports`; `undefined` when nothing maps it, so it is loaded
172
+ * as a package. A relative target is `./<path from the root>` (`../…` above it).
173
+ */
174
+ export const mappedTargets = (mappings: ImportMappings, file: string, specifier: string): readonly string[] | undefined => {
175
+ if (isBuiltin(specifier)) return undefined
176
+ const path = matchTable(mappings.paths(file), specifier)?.find(mappings.mayExist)
177
+ return path === undefined ? matchTable(mappings.imports(file), specifier) : [path]
178
+ }
@@ -0,0 +1,78 @@
1
+ import { type ContractDeclaration, ContractError, describeContract, isProcedure, type ProcedureTreeDeclaration } from '@fabrika/app/contract'
2
+ import type { SchemaShape } from '@fabrika/auth-core'
3
+ import { type Position, positionOf } from '../ast'
4
+ import { readContractModule } from '../contract'
5
+ import type { Finding } from '../finding'
6
+ import type { ModuleGraph } from '../graph'
7
+ import { CONTRACT_EXPORT, CONTRACT_FILE } from '../layout'
8
+
9
+ const SCHEMA_SUBSET = 'a schema of the supported z subset (packages/check/CLAUDE.md)'
10
+ const ALLOWED_SUFFIX = /^(?<message>.*) \(allowed: (?<allowed>.*)\)$/s
11
+
12
+ /**
13
+ * What Control's static reader refuses, reported in the build: a form the reader cannot read into the contract, and a
14
+ * schema `describeContract` refuses. Runs only once the literal rule passes. Table policies are not read yet (A8b), so
15
+ * the checks `buildArtifact` makes against them run only where the tables are known.
16
+ */
17
+ export const checkContractRead = (graph: ModuleGraph): Finding[] => {
18
+ const read = readContractModule(graph)
19
+ if (!read.ok) {
20
+ return [...read.findings]
21
+ }
22
+ const module = graph.module(CONTRACT_FILE)
23
+ const binding = module === undefined ? undefined : graph.binding(module, CONTRACT_EXPORT)
24
+ const at = binding?.kind === 'const' && binding.init !== undefined ? positionOf(binding.init) : { line: 1, column: 1 }
25
+ try {
26
+ return memberAdmitsExternal(describeContract(read.contract), at)
27
+ } catch (error) {
28
+ if (!(error instanceof ContractError)) {
29
+ throw error
30
+ }
31
+ return error.problems.map((problem): Finding => {
32
+ const parts = ALLOWED_SUFFIX.exec(problem)?.groups
33
+ return {
34
+ file: CONTRACT_FILE,
35
+ ...at,
36
+ severity: 'refusal',
37
+ rule: 'contract',
38
+ message: parts?.['message'] ?? problem,
39
+ allowed: parts?.['allowed'] ?? SCHEMA_SUBSET,
40
+ }
41
+ })
42
+ }
43
+ }
44
+
45
+ /**
46
+ * `{ member: true }` admits a caller holding any permission of the application, so in a contract that declares an
47
+ * external role it admits the people from outside the organization who hold it (ADR-0051). A staff-only surface names
48
+ * an action that only internal roles grant. A hint: an endpoint for every member, externals included, is legitimate.
49
+ */
50
+ function memberAdmitsExternal(contract: ContractDeclaration<SchemaShape>, at: Position): Finding[] {
51
+ const external = Object.entries(contract.roles).filter(([, role]) => role.external === true).map(([name]) => name)
52
+ if (external.length === 0) {
53
+ return []
54
+ }
55
+ const roles = external.map((name) => `'${name}'`).join(', ')
56
+ const sites: string[] = []
57
+ for (const [name, mount] of Object.entries(contract.mounts)) {
58
+ // A machine-only mount admits services, and an external principal is always a user.
59
+ if (mount.kind === 'rpc' && mount.callers.includes('human')) sites.push(...memberProcedures(mount.procedures, name))
60
+ if (mount.kind === 'spa' && 'member' in mount.access) sites.push(name)
61
+ }
62
+ return sites.map((site): Finding => ({
63
+ file: CONTRACT_FILE,
64
+ ...at,
65
+ severity: 'hint',
66
+ rule: 'member-admits-external',
67
+ message: `'${site}' admits every member, and external role ${roles} makes a person from outside the organization one`,
68
+ allowed: 'a staff-only endpoint requires an action only internal roles grant: { action, over } or { action, app: true }',
69
+ }))
70
+ }
71
+
72
+ function memberProcedures(tree: ProcedureTreeDeclaration<SchemaShape>, path: string): string[] {
73
+ return Object.entries(tree).flatMap(([name, entry]) => {
74
+ const at = `${path}.${name}`
75
+ if (isProcedure(entry)) return 'member' in entry.access ? [at] : []
76
+ return memberProcedures(entry, at)
77
+ })
78
+ }
@@ -0,0 +1,147 @@
1
+ import { z } from 'zod/v4'
2
+ import { type AstNode, child, children, type ParsedModule, staticKey, walk } from '../ast'
3
+ import type { Finding } from '../finding'
4
+ import { type Located, type ModuleGraph, unwrapValue } from '../graph'
5
+
6
+ export interface ContractJob {
7
+ readonly name: string
8
+ /** `undefined` when the contract's schedule is not a static string. */
9
+ readonly schedule: string | undefined
10
+ }
11
+
12
+ /**
13
+ * Every `<name>: c.cron('<schedule>', { … })` in the contract, and every `<name>` there that names a const of the
14
+ * kit's `app.cron('<schedule>', { … })`; the schedule is resolved through literal consts.
15
+ */
16
+ export const contractJobs = (contract: ParsedModule, graph: ModuleGraph): readonly ContractJob[] => {
17
+ const jobs: ContractJob[] = []
18
+ const cronSchedule = (located: Located): string | undefined => {
19
+ const first = children(located.node, 'arguments')[0]
20
+ return first ? graph.resolveString({ module: located.module, node: first }) : undefined
21
+ }
22
+ walk(contract.program, (node, ancestors) => {
23
+ if (node.type === 'Property') {
24
+ const value = child(node, 'value')
25
+ const name = staticKey(node, 'key')
26
+ const resolved = value !== undefined && unwrapValue(value).type === 'Identifier'
27
+ ? graph.resolveValue({ module: contract, node: value })
28
+ : undefined
29
+ if (name !== undefined && resolved !== undefined && isCronCall(resolved.node)) jobs.push({ name, schedule: cronSchedule(resolved) })
30
+ return
31
+ }
32
+ if (!isCronCall(node)) return
33
+ const property = [...ancestors].reverse().find((ancestor) => {
34
+ const value = ancestor.type === 'Property' ? child(ancestor, 'value') : undefined
35
+ return value !== undefined && unwrapValue(value) === node
36
+ })
37
+ const name = property === undefined ? undefined : staticKey(property, 'key')
38
+ if (name !== undefined) jobs.push({ name, schedule: cronSchedule({ module: contract, node }) })
39
+ })
40
+ return jobs
41
+ }
42
+
43
+ const isCronCall = (node: AstNode): boolean => {
44
+ const callee = node.type === 'CallExpression' ? child(node, 'callee') : undefined
45
+ return callee?.type === 'MemberExpression' && staticKey(callee, 'property') === 'cron'
46
+ }
47
+
48
+ const crontabEntrySchema = z.object({
49
+ timing: z.string().optional(),
50
+ command: z.string().optional(),
51
+ allContainers: z.boolean().optional(),
52
+ })
53
+
54
+ const zeropsYamlSchema = z.object({
55
+ zerops: z.array(
56
+ z.object({
57
+ setup: z.string(),
58
+ run: z.object({ start: z.string().optional(), crontab: z.array(crontabEntrySchema).optional() }).optional(),
59
+ }),
60
+ ),
61
+ })
62
+
63
+ const JOB_COMMAND = /^fabrika job run (\S+)$/
64
+ /** A lone `&`, `nohup`, `setsid` or `disown` starts a process beside the server, outside every job rule. */
65
+ const BACKGROUND_PROCESS = /(?:^|[^&])&(?:[^&]|$)|\b(?:nohup|setsid|disown)\b/
66
+
67
+ /** The line of the first occurrence of `needle`, or 1. */
68
+ const lineOf = (text: string, needle: string, after = 0): number => {
69
+ const index = text.indexOf(needle, after)
70
+ return index === -1 ? 1 : text.slice(0, index).split('\n').length
71
+ }
72
+
73
+ /** Each setup that runs the application carries exactly the contract's jobs as crontab entries, and nothing else. */
74
+ export const checkCrontab = (file: string, text: string, jobs: readonly ContractJob[]): Finding[] => {
75
+ const findings: Finding[] = []
76
+ const finding = (line: number, message: string, allowed: string) =>
77
+ findings.push({ file, line, column: 1, severity: 'refusal', rule: 'crontab', message, allowed })
78
+ let document: unknown
79
+ try {
80
+ document = Bun.YAML.parse(text)
81
+ } catch {
82
+ finding(1, `${file} is not valid YAML`, 'a zerops.yaml that parses')
83
+ return findings
84
+ }
85
+ const parsed = zeropsYamlSchema.safeParse(document)
86
+ if (!parsed.success) {
87
+ const issue = parsed.error.issues[0]
88
+ finding(
89
+ 1,
90
+ `${file} does not have the zerops.yaml shape at '${issue?.path.join('.') ?? ''}'`,
91
+ 'zerops: [{ setup, run: { start, crontab: [{ timing, command, allContainers }] } }]',
92
+ )
93
+ return findings
94
+ }
95
+ const byName = new Map(jobs.map((job) => [job.name, job]))
96
+ for (const setup of parsed.data.zerops) {
97
+ const { run } = setup
98
+ if (run === undefined) continue
99
+ const setupLine = lineOf(text, `setup: ${setup.setup}`)
100
+ const crontabLine = lineOf(text, 'crontab:', text.indexOf(`setup: ${setup.setup}`))
101
+ if (run.start !== undefined && BACKGROUND_PROCESS.test(run.start)) {
102
+ finding(
103
+ lineOf(text, run.start),
104
+ `run.start of '${setup.setup}' starts a background process`,
105
+ 'one server process in run.start; background work is a job in the contract (c.cron)',
106
+ )
107
+ }
108
+ const scheduled = new Set<string>()
109
+ for (const entry of run.crontab ?? []) {
110
+ const line = entry.command === undefined ? crontabLine : lineOf(text, entry.command)
111
+ const name = JOB_COMMAND.exec(entry.command ?? '')?.[1]
112
+ const job = name === undefined ? undefined : byName.get(name)
113
+ if (job === undefined) {
114
+ finding(
115
+ line,
116
+ `crontab entry '${entry.command ?? ''}' is not a job of the contract`,
117
+ 'fabrika job run <name> for a c.cron job declared in fabrika.contract.ts',
118
+ )
119
+ continue
120
+ }
121
+ if (scheduled.has(job.name)) finding(line, `job '${job.name}' has a second crontab entry`, 'one crontab entry per job')
122
+ scheduled.add(job.name)
123
+ if (job.schedule === undefined) {
124
+ finding(line, `the contract's schedule of job '${job.name}' is not a static string`, `c.cron('<cron expression>', { … }) in fabrika.contract.ts`)
125
+ } else if (entry.timing !== job.schedule) {
126
+ finding(
127
+ line,
128
+ `crontab timing '${entry.timing ?? ''}' of job '${job.name}' differs from the contract's '${job.schedule}'`,
129
+ `timing: '${job.schedule}'`,
130
+ )
131
+ }
132
+ if (entry.allContainers !== false) {
133
+ finding(line, `crontab entry of job '${job.name}' does not set allContainers: false`, 'allContainers: false, written explicitly')
134
+ }
135
+ }
136
+ for (const job of jobs) {
137
+ if (!scheduled.has(job.name)) {
138
+ finding(
139
+ run.crontab === undefined ? setupLine : crontabLine,
140
+ `job '${job.name}' has no crontab entry in '${setup.setup}'`,
141
+ `{ timing: '${job.schedule ?? ''}', command: 'fabrika job run ${job.name}', allContainers: false }`,
142
+ )
143
+ }
144
+ }
145
+ }
146
+ return findings
147
+ }
@@ -0,0 +1,177 @@
1
+ import { type AstNode, child, children, identifierName, memberPath, staticString, stringField, unwrap, walk } from '../ast'
2
+ import type { Report } from '../finding'
3
+ import { isRequire } from '../references'
4
+ import { type ImportMappings, mappedTargets } from '../resolution'
5
+ import { declaringScope } from '../scope'
6
+ import { touchesPrototype } from './runtime'
7
+
8
+ const ALLOWED = 'framework objects are read-only: use them as they are'
9
+
10
+ /** The packages the platform trusts by name (`package-replacement`): their objects are the framework's. */
11
+ const isTrusted = (specifier: string): boolean => specifier.startsWith('@fabrika/') || specifier === 'zod' || specifier.startsWith('zod/')
12
+
13
+ /** One name bound to a trusted package's value, in the scope that declares it. */
14
+ interface TrustedBinding {
15
+ readonly specifier: string
16
+ readonly scope: AstNode | undefined
17
+ }
18
+
19
+ /** Local name → each declaration of it that holds a trusted package's value. */
20
+ export type TrustedBindings = ReadonlyMap<string, readonly TrustedBinding[]>
21
+
22
+ /** The trusted package a specifier loads, also through a package import map (`#data` → `@fabrika/db`). */
23
+ const trustedPackage = (specifier: string | undefined, mappings: ImportMappings, file: string): string | undefined => {
24
+ if (specifier === undefined) return undefined
25
+ const targets = mappedTargets(mappings, file, specifier) ?? [specifier]
26
+ return targets.find(isTrusted)
27
+ }
28
+
29
+ const loadedSpecifier = (init: AstNode | undefined): string | undefined => {
30
+ const value = init === undefined ? undefined : unwrap(init)
31
+ const load = value?.type === 'AwaitExpression' ? child(value, 'argument') : value
32
+ if (load?.type === 'ImportExpression') return staticString(child(load, 'source'))
33
+ if (load?.type === 'CallExpression' && isRequire(child(load, 'callee'))) return staticString(children(load, 'arguments')[0] ?? undefined)
34
+ return undefined
35
+ }
36
+
37
+ /** The names a declarator binds: `x`, or the values of `{ a, b: c }`. */
38
+ const boundNames = (pattern: AstNode | undefined): readonly string[] => {
39
+ const name = identifierName(pattern)
40
+ if (name !== undefined) return [name]
41
+ if (pattern?.type !== 'ObjectPattern') return []
42
+ return children(pattern, 'properties').flatMap((property) => {
43
+ const value = property?.type === 'Property' ? identifierName(child(property, 'value')) : undefined
44
+ return value === undefined ? [] : [value]
45
+ })
46
+ }
47
+
48
+ /** What a module binds to a trusted package's values: its imports, `import x = require()`, and direct loads into a `const`. */
49
+ export const trustedBindings = (file: string, program: AstNode, mappings: ImportMappings): TrustedBindings => {
50
+ const bindings = new Map<string, TrustedBinding[]>()
51
+ const bind = (name: string, specifier: string, scope: AstNode | undefined): void => {
52
+ bindings.set(name, [...(bindings.get(name) ?? []), { specifier, scope }])
53
+ }
54
+ walk(program, (node, ancestors) => {
55
+ if (node.type === 'ImportDeclaration' && stringField(node, 'importKind') !== 'type') {
56
+ const specifier = trustedPackage(staticString(child(node, 'source')), mappings, file)
57
+ if (specifier === undefined) return
58
+ for (const item of children(node, 'specifiers')) {
59
+ const local = item === null || stringField(item, 'importKind') === 'type' ? undefined : identifierName(child(item, 'local'))
60
+ if (local !== undefined) bind(local, specifier, program)
61
+ }
62
+ } else if (node.type === 'TSImportEqualsDeclaration' && stringField(node, 'importKind') !== 'type') {
63
+ const reference = child(node, 'moduleReference')
64
+ const specifier = trustedPackage(
65
+ reference?.type === 'TSExternalModuleReference' ? staticString(child(reference, 'expression')) : undefined,
66
+ mappings,
67
+ file,
68
+ )
69
+ const local = identifierName(child(node, 'id'))
70
+ if (specifier !== undefined && local !== undefined) bind(local, specifier, program)
71
+ } else if (node.type === 'VariableDeclarator') {
72
+ const specifier = trustedPackage(loadedSpecifier(child(node, 'init')), mappings, file)
73
+ if (specifier !== undefined) {
74
+ for (const name of boundNames(child(node, 'id'))) bind(name, specifier, declaringScope(name, ancestors))
75
+ }
76
+ }
77
+ })
78
+ return bindings
79
+ }
80
+
81
+ /**
82
+ * The trusted binding a member chain starts from (`Database.postgres`, `db['Database'].postgres` → `Database`, `db`),
83
+ * when the name at `ancestors` denotes that declaration and no local that shadows it.
84
+ */
85
+ const trustedRoot = (
86
+ target: AstNode | null | undefined,
87
+ ancestors: readonly AstNode[],
88
+ bindings: TrustedBindings,
89
+ ): { readonly name: string; readonly specifier: string } | undefined => {
90
+ let current = target === null || target === undefined ? undefined : unwrap(target)
91
+ while (current?.type === 'MemberExpression') {
92
+ const object = child(current, 'object')
93
+ current = object === undefined ? undefined : unwrap(object)
94
+ }
95
+ const name = identifierName(current)
96
+ const declarations = name === undefined ? undefined : bindings.get(name)
97
+ if (name === undefined || declarations === undefined) return undefined
98
+ const scope = declaringScope(name, ancestors)
99
+ const binding = declarations.find((declaration) => declaration.scope === scope)
100
+ return binding === undefined ? undefined : { name, specifier: binding.specifier }
101
+ }
102
+
103
+ /** The member expressions an assignment writes, also inside a destructuring pattern. */
104
+ const writtenMembers = (target: AstNode | undefined): readonly AstNode[] => {
105
+ if (target === undefined) return []
106
+ const node = unwrap(target)
107
+ switch (node.type) {
108
+ case 'MemberExpression':
109
+ return [node]
110
+ case 'ObjectPattern':
111
+ return children(node, 'properties').flatMap((property) =>
112
+ property === null ? [] : writtenMembers(child(property, property.type === 'RestElement' ? 'argument' : 'value'))
113
+ )
114
+ case 'ArrayPattern':
115
+ return children(node, 'elements').flatMap((element) => (element === null ? [] : writtenMembers(element)))
116
+ case 'AssignmentPattern':
117
+ return writtenMembers(child(node, 'left'))
118
+ case 'RestElement':
119
+ return writtenMembers(child(node, 'argument'))
120
+ default:
121
+ return []
122
+ }
123
+ }
124
+
125
+ const WRITERS = new Set([
126
+ 'Object.defineProperty',
127
+ 'Object.defineProperties',
128
+ 'Object.assign',
129
+ 'Object.setPrototypeOf',
130
+ 'Reflect.set',
131
+ 'Reflect.defineProperty',
132
+ 'Reflect.deleteProperty',
133
+ 'Reflect.setPrototypeOf',
134
+ ])
135
+
136
+ /**
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 `Database.postgres` receives the database URL; a patched schema changes what the contract admits. A write
139
+ * through a prototype is `prototype-assignment`'s. A local that shadows such a name is not one.
140
+ */
141
+ export const checkFrameworkWrite = (node: AstNode, ancestors: readonly AstNode[], bindings: TrustedBindings, report: Report): void => {
142
+ if (bindings.size === 0) return
143
+ const found = (at: AstNode, target: AstNode | null | undefined, how: string): void => {
144
+ if (touchesPrototype(target ?? undefined)) return
145
+ const root = trustedRoot(target, ancestors, bindings)
146
+ if (root === undefined) return
147
+ const written = target === null || target === undefined ? undefined : memberPath(target)
148
+ const name = written === undefined || written.length < 2 ? root.name : written.join('.')
149
+ report(at, 'framework-write', `${how} ${name}, a value from '${root.specifier}'`, ALLOWED)
150
+ }
151
+ switch (node.type) {
152
+ case 'AssignmentExpression':
153
+ for (const member of writtenMembers(child(node, 'left'))) found(node, member, 'assigns to')
154
+ return
155
+ case 'UpdateExpression':
156
+ for (const member of writtenMembers(child(node, 'argument'))) found(node, member, 'changes')
157
+ return
158
+ case 'UnaryExpression':
159
+ if (node['operator'] === 'delete') {
160
+ for (const member of writtenMembers(child(node, 'argument'))) found(node, member, 'deletes')
161
+ }
162
+ return
163
+ case 'CallExpression': {
164
+ const callee = child(node, 'callee')
165
+ const path = callee === undefined ? undefined : memberPath(callee)?.join('.')
166
+ if (path !== undefined && WRITERS.has(path)) {
167
+ const target = children(node, 'arguments')[0]
168
+ const key = children(node, 'arguments')[1]
169
+ const member = key !== null && key !== undefined && path !== 'Object.assign' ? staticString(key) : undefined
170
+ found(node, target, member === undefined ? `${path} writes to` : `${path} writes '${member}' of`)
171
+ }
172
+ return
173
+ }
174
+ default:
175
+ return
176
+ }
177
+ }