@fabrika/check 0.0.0-stage → 0.4.0
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 +48 -5
- package/src/ast.ts +268 -0
- package/src/bun-plugin.ts +63 -0
- package/src/check.ts +183 -0
- package/src/cli.ts +88 -0
- package/src/contract.ts +254 -0
- package/src/endpoint-fixtures.ts +221 -0
- package/src/finding.ts +88 -0
- package/src/graph.ts +206 -0
- package/src/index.ts +15 -0
- package/src/inputs.ts +88 -0
- package/src/jsonc.ts +63 -0
- package/src/layout.ts +115 -0
- package/src/limits.ts +15 -0
- package/src/packed.ts +66 -0
- package/src/reader/problems.ts +11 -0
- package/src/reader/schema.ts +551 -0
- package/src/reader/surface.ts +1087 -0
- package/src/reader/tables.ts +116 -0
- package/src/reader/value.ts +644 -0
- package/src/references.ts +95 -0
- package/src/resolution.ts +178 -0
- package/src/rules/contract.ts +78 -0
- package/src/rules/crontab.ts +147 -0
- package/src/rules/framework.ts +177 -0
- package/src/rules/identity.ts +80 -0
- package/src/rules/isolation.ts +79 -0
- package/src/rules/json.ts +28 -0
- package/src/rules/literal.ts +736 -0
- package/src/rules/migrations.ts +87 -0
- package/src/rules/modules.ts +226 -0
- package/src/rules/packages.ts +168 -0
- package/src/rules/runtime.ts +507 -0
- package/src/rules/structure.ts +299 -0
- package/src/rules/tests.ts +208 -0
- package/src/rules/types.ts +62 -0
- package/src/scaffold-sample.ts +108 -0
- package/src/scaffold.ts +605 -0
- package/src/scope.ts +108 -0
- package/src/slice.ts +339 -0
- package/src/toml.ts +159 -0
- package/src/trust.ts +189 -0
- package/src/version.ts +4 -0
- package/README.md +0 -3
package/src/contract.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// @fabrika/check/contract — the static contract reader. It reads `fabrika.contract.ts` and the schema modules it imports
|
|
2
|
+
// from their text, as Control has them at a commit, and executes no application code. Browser- and Worker-safe: no
|
|
3
|
+
// Node or Bun API, so a Worker can bundle it.
|
|
4
|
+
|
|
5
|
+
import { type AnyContract, compileContract } from '@fabrika/app/contract'
|
|
6
|
+
import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core'
|
|
7
|
+
import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
8
|
+
import { importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
|
|
9
|
+
import { type Finding, formatFinding } from './finding'
|
|
10
|
+
import { ModuleGraph } from './graph'
|
|
11
|
+
import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
|
|
12
|
+
import { CONTRACT_LIMITS } from './limits'
|
|
13
|
+
import { ReaderProblems } from './reader/problems'
|
|
14
|
+
import { readContractValue } from './reader/surface'
|
|
15
|
+
import { readTablesValue } from './reader/tables'
|
|
16
|
+
import { ValueReader } from './reader/value'
|
|
17
|
+
import { checkLiteralGraph } from './rules/literal'
|
|
18
|
+
import { parseShellModule } from './slice'
|
|
19
|
+
import { checkTrustedResolution } from './trust'
|
|
20
|
+
|
|
21
|
+
export { ContractError } from '@fabrika/app/contract'
|
|
22
|
+
export { type Finding, formatFinding } from './finding'
|
|
23
|
+
export { contractReaderInputs } from './inputs'
|
|
24
|
+
export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
|
|
25
|
+
export { CONTRACT_LIMITS } from './limits'
|
|
26
|
+
export { CHECKER_VERSION } from './version'
|
|
27
|
+
|
|
28
|
+
/** Every form the reader refuses, each with its file, line, column and the allowed form. */
|
|
29
|
+
export class ContractSourceError extends Error {
|
|
30
|
+
override readonly name = 'ContractSourceError'
|
|
31
|
+
readonly findings: readonly Finding[]
|
|
32
|
+
|
|
33
|
+
constructor(findings: readonly Finding[]) {
|
|
34
|
+
super(`the contract cannot be read from source:\n${findings.map(formatFinding).join('\n')}`)
|
|
35
|
+
this.findings = findings
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The contract artifact of an application, read from the text of its files (path relative to the application root →
|
|
41
|
+
* text): `fabrika.contract.ts`, every module it imports and the configuration that applies to them (`readContract`),
|
|
42
|
+
* and `src/db/tables.ts` with the modules it imports (`readTablesDefinition`). `tables`, when given, replaces what
|
|
43
|
+
* `src/db/tables.ts` declares: its parsed policies, or the artifact form of each policy, which names no inbox's
|
|
44
|
+
* columns, so a form's fields are not checked against them.
|
|
45
|
+
*
|
|
46
|
+
* Throws `ContractSourceError` for a form the reader refuses, and `ContractError` with the same problems
|
|
47
|
+
* `compileContract` reports for a contract that does not compile.
|
|
48
|
+
*/
|
|
49
|
+
export function readContractSource(
|
|
50
|
+
files: ReadonlyMap<string, string>,
|
|
51
|
+
tables?: Tables<unknown, unknown> | Readonly<Record<string, TablePolicyArtifact>>,
|
|
52
|
+
): ContractArtifact {
|
|
53
|
+
const contract = readContract(files)
|
|
54
|
+
return compileContract(contract, tables ?? readTablesDefinition(files) ?? {})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The table policies of `src/db/tables.ts` in their artifact form (`readTablesDefinition`); none when `files` has no
|
|
59
|
+
* such file. Throws `ContractSourceError`.
|
|
60
|
+
*/
|
|
61
|
+
export function readTablesSource(files: ReadonlyMap<string, string>): TablePolicies {
|
|
62
|
+
const tables = readTablesDefinition(files)
|
|
63
|
+
return tables === null ? {} : tablePolicies(tables)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The table policies of `src/db/tables.ts`, read from source and parsed by `@fabrika/db`'s own policy parse, as
|
|
68
|
+
* `defineTables` returns them; `null` when `files` has no such file. `files` carries its imports (the generated
|
|
69
|
+
* `src/db/schema.generated.ts`) and the configuration `readContract` names. Throws `ContractSourceError`.
|
|
70
|
+
*/
|
|
71
|
+
export function readTablesDefinition(files: ReadonlyMap<string, string>): Tables<unknown, unknown> | null {
|
|
72
|
+
if (!files.has(TABLES_FILE)) {
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
const trust = checkTrustedResolution(files)
|
|
76
|
+
if (trust.length > 0) {
|
|
77
|
+
throw new ContractSourceError(trust)
|
|
78
|
+
}
|
|
79
|
+
const parsed = parseSourceGraph(files, TABLES_FILE)
|
|
80
|
+
if (!parsed.ok) {
|
|
81
|
+
throw new ContractSourceError(parsed.findings)
|
|
82
|
+
}
|
|
83
|
+
const literal = checkLiteralGraph([TABLES_FILE], parsed.graph)
|
|
84
|
+
const module = parsed.graph.module(TABLES_FILE)
|
|
85
|
+
const budget = module === undefined ? [] : sourceBudget(contractModules(parsed.graph, module), TABLES_FILE)
|
|
86
|
+
if (literal.length > 0 || budget.length > 0) {
|
|
87
|
+
throw new ContractSourceError([...literal, ...budget])
|
|
88
|
+
}
|
|
89
|
+
if (module === undefined) {
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
const problems = new ReaderProblems()
|
|
93
|
+
const tables = readTablesValue(parsed.graph, module, problems)
|
|
94
|
+
if (tables === null || problems.findings.length > 0) {
|
|
95
|
+
throw new ContractSourceError(problems.findings)
|
|
96
|
+
}
|
|
97
|
+
return tables
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The contract `defineContract` returns in the evaluated module, read from source; throws `ContractSourceError`.
|
|
102
|
+
* Besides the contract's modules, `files` carries every `package.json`, `tsconfig.json`, `jsconfig.json` and
|
|
103
|
+
* `bunfig.toml` that applies to them (the root and each directory of a contract module): one of them can redirect the
|
|
104
|
+
* packages the reader trusts by name, and the reader cannot tell a missing file from an absent one.
|
|
105
|
+
*/
|
|
106
|
+
export function readContract(files: ReadonlyMap<string, string>): AnyContract {
|
|
107
|
+
const trust = checkTrustedResolution(files)
|
|
108
|
+
if (trust.length > 0) {
|
|
109
|
+
throw new ContractSourceError(trust)
|
|
110
|
+
}
|
|
111
|
+
const parsed = parseSourceGraph(files, CONTRACT_FILE)
|
|
112
|
+
if (!parsed.ok) {
|
|
113
|
+
throw new ContractSourceError(parsed.findings)
|
|
114
|
+
}
|
|
115
|
+
const literal = checkLiteralGraph([CONTRACT_FILE], parsed.graph)
|
|
116
|
+
if (literal.length > 0) {
|
|
117
|
+
throw new ContractSourceError(literal)
|
|
118
|
+
}
|
|
119
|
+
const read = readContractModule(parsed.graph)
|
|
120
|
+
if (!read.ok) {
|
|
121
|
+
throw new ContractSourceError(read.findings)
|
|
122
|
+
}
|
|
123
|
+
return read.contract
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type ContractRead = { readonly ok: true; readonly contract: AnyContract } | { readonly ok: false; readonly findings: readonly Finding[] }
|
|
127
|
+
|
|
128
|
+
/** Reads the `contract` export of a graph whose contract modules already pass the literal rule. */
|
|
129
|
+
export function readContractModule(graph: ModuleGraph): ContractRead {
|
|
130
|
+
const problems = new ReaderProblems()
|
|
131
|
+
const module = graph.module(CONTRACT_FILE)
|
|
132
|
+
if (module === undefined) {
|
|
133
|
+
return { ok: false, findings: [missingFile(CONTRACT_FILE)] }
|
|
134
|
+
}
|
|
135
|
+
const budget = sourceBudget(contractModules(graph, module))
|
|
136
|
+
if (budget.length > 0) {
|
|
137
|
+
return { ok: false, findings: budget }
|
|
138
|
+
}
|
|
139
|
+
const value = new ValueReader(graph, problems).exported(module, CONTRACT_EXPORT, module.program)
|
|
140
|
+
const contract = value === null ? null : readContractValue(value, problems)
|
|
141
|
+
return contract === null || problems.findings.length > 0 ? { ok: false, findings: problems.findings } : { ok: true, contract }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The contract module and every module its value imports reach. */
|
|
145
|
+
export function contractModules(graph: ModuleGraph, entry: ParsedModule): ParsedModule[] {
|
|
146
|
+
const reached = new Map<string, ParsedModule>()
|
|
147
|
+
const queue = [entry]
|
|
148
|
+
for (let module = queue.shift(); module !== undefined; module = queue.shift()) {
|
|
149
|
+
if (reached.has(module.file)) {
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
reached.set(module.file, module)
|
|
153
|
+
for (const imported of graph.index(module).imports.values()) {
|
|
154
|
+
const target = graph.resolve(module.file, imported.specifier)
|
|
155
|
+
if (target !== undefined) {
|
|
156
|
+
queue.push(target)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return [...reached.values()]
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The source and syntax-depth limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
|
|
164
|
+
function sourceBudget(modules: readonly ParsedModule[], entry = CONTRACT_FILE): Finding[] {
|
|
165
|
+
const findings: Finding[] = []
|
|
166
|
+
const bytes = modules.reduce((total, module) => total + module.bytes, 0)
|
|
167
|
+
if (bytes > CONTRACT_LIMITS.sourceBytes) {
|
|
168
|
+
findings.push(overBudget(entry, `${entry} and its modules are ${bytes} bytes, over ${CONTRACT_LIMITS.sourceBytes}`))
|
|
169
|
+
}
|
|
170
|
+
for (const module of modules) {
|
|
171
|
+
if (nodeDepth(module.program) > CONTRACT_LIMITS.astDepth) {
|
|
172
|
+
findings.push(overBudget(module.file, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`))
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return findings
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function overBudget(file: string, message: string): Finding {
|
|
179
|
+
return {
|
|
180
|
+
file,
|
|
181
|
+
line: 1,
|
|
182
|
+
column: 1,
|
|
183
|
+
severity: 'refusal',
|
|
184
|
+
rule: 'contract',
|
|
185
|
+
message,
|
|
186
|
+
allowed: 'a contract within CONTRACT_LIMITS (packages/check/CLAUDE.md)',
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
type ParsedGraph = { readonly ok: true; readonly graph: ModuleGraph } | { readonly ok: false; readonly findings: readonly Finding[] }
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Parses `entry` (`fabrika.contract.ts` or `src/db/tables.ts`) and the modules its imports reach among `files`, and
|
|
194
|
+
* nothing else; each module as its shell slice, so an import only a handler uses is never followed. Every candidate of an import is parsed, so that `rules/literal.ts` sees an ambiguous or directory
|
|
195
|
+
* import; the size limit holds before a module is parsed and the depth limit right after, before any recursive rule
|
|
196
|
+
* walks it.
|
|
197
|
+
*/
|
|
198
|
+
function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): ParsedGraph {
|
|
199
|
+
const modules = new Map<string, ParsedModule>()
|
|
200
|
+
const findings: Finding[] = []
|
|
201
|
+
if (!files.has(entry)) {
|
|
202
|
+
return { ok: false, findings: [missingFile(entry)] }
|
|
203
|
+
}
|
|
204
|
+
let bytes = 0
|
|
205
|
+
const queue = [entry]
|
|
206
|
+
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
|
207
|
+
const text = files.get(path)
|
|
208
|
+
if (modules.has(path) || text === undefined || !isSourceFile(path)) {
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
bytes += utf8Bytes(text)
|
|
212
|
+
if (bytes > CONTRACT_LIMITS.sourceBytes) {
|
|
213
|
+
return { ok: false, findings: [overBudget(path, `${entry} and its modules are over ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
|
|
214
|
+
}
|
|
215
|
+
const { parsed, refusals } = parseShellModule(path, text)
|
|
216
|
+
findings.push(...refusals)
|
|
217
|
+
if (!parsed.ok) {
|
|
218
|
+
findings.push({
|
|
219
|
+
file: path,
|
|
220
|
+
...parsed.position,
|
|
221
|
+
severity: 'refusal',
|
|
222
|
+
rule: 'parse-error',
|
|
223
|
+
message: parsed.message,
|
|
224
|
+
allowed: 'source the TypeScript parser accepts',
|
|
225
|
+
})
|
|
226
|
+
continue
|
|
227
|
+
}
|
|
228
|
+
if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
|
|
229
|
+
return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
|
|
230
|
+
}
|
|
231
|
+
modules.set(path, parsed.module)
|
|
232
|
+
for (const specifier of importedSpecifiers(parsed.module)) {
|
|
233
|
+
const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
|
|
234
|
+
if (resolution?.kind === 'file') {
|
|
235
|
+
queue.push(resolution.path)
|
|
236
|
+
} else if (resolution?.kind === 'ambiguous' || resolution?.kind === 'directory') {
|
|
237
|
+
queue.push(...resolution.paths)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function missingFile(file: string): Finding {
|
|
245
|
+
return {
|
|
246
|
+
file,
|
|
247
|
+
line: 1,
|
|
248
|
+
column: 1,
|
|
249
|
+
severity: 'refusal',
|
|
250
|
+
rule: 'contract',
|
|
251
|
+
message: `the application has no ${file}`,
|
|
252
|
+
allowed: `${file} with export const ${CONTRACT_EXPORT} = defineContract(…)`,
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// `src/__tests__/endpoint-access.fixtures.ts`: what an application's author gives the endpoint access tests. `fixtures`
|
|
2
|
+
// are the inputs the scaffold cannot sample (a `regex`); `seeds` are the state of the row an endpoint addresses, which
|
|
3
|
+
// its precondition needs (`deals.reopen` reopens only a won deal: `{ stage: 'won' }`); `members` are the input fields
|
|
4
|
+
// that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
|
|
5
|
+
// `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
|
|
6
|
+
// kit fills with one it holds; `rows` the fields that name a row lying in the endpoint's object (a note's comment), by
|
|
7
|
+
// table, which the kit seeds in each scope's object. Read from source, never executed, within the reader's budget:
|
|
8
|
+
// `export const fixtures = { '<endpoint id>': { … } }`, `export const seeds = { '<endpoint id>': { <column>: <value> } }`,
|
|
9
|
+
// `export const members = { '<endpoint id>': ['<field>'] }` (`invitations`, `links` alike) and
|
|
10
|
+
// `export const rows = { '<endpoint id>': { <field>: '<table>' } }`, plain literals only.
|
|
11
|
+
// Browser-safe.
|
|
12
|
+
|
|
13
|
+
import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
|
|
14
|
+
import type { Finding } from './finding'
|
|
15
|
+
import { ENDPOINT_FIXTURES_FILE } from './layout'
|
|
16
|
+
import { CONTRACT_LIMITS } from './limits'
|
|
17
|
+
import type { Sample } from './scaffold-sample'
|
|
18
|
+
|
|
19
|
+
export const FIXTURES_EXPORT = 'fixtures'
|
|
20
|
+
export const SEEDS_EXPORT = 'seeds'
|
|
21
|
+
export const MEMBERS_EXPORT = 'members'
|
|
22
|
+
export const INVITATIONS_EXPORT = 'invitations'
|
|
23
|
+
export const LINKS_EXPORT = 'links'
|
|
24
|
+
export const ROWS_EXPORT = 'rows'
|
|
25
|
+
|
|
26
|
+
/** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
|
|
27
|
+
const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
|
|
28
|
+
type FieldExport = (typeof FIELD_EXPORTS)[number]
|
|
29
|
+
const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
|
|
30
|
+
|
|
31
|
+
const ALLOWED =
|
|
32
|
+
"export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] } and export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
|
|
33
|
+
|
|
34
|
+
type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
|
|
35
|
+
|
|
36
|
+
export interface EndpointFixtures {
|
|
37
|
+
/** The input each endpoint's cases send, by endpoint id. */
|
|
38
|
+
readonly inputs: ById
|
|
39
|
+
/** The columns of the row each endpoint addresses, as both scopes' rows are seeded, by endpoint id. */
|
|
40
|
+
readonly seeds: ById
|
|
41
|
+
/** The input fields that name a member of the endpoint's member directory, by endpoint id. */
|
|
42
|
+
readonly members: Readonly<Record<string, readonly string[]>>
|
|
43
|
+
/** The input fields that name an invitation the endpoint cancels, by endpoint id. */
|
|
44
|
+
readonly invitations: Readonly<Record<string, readonly string[]>>
|
|
45
|
+
/** The input fields that name a share link the endpoint revokes, by endpoint id. */
|
|
46
|
+
readonly links: Readonly<Record<string, readonly string[]>>
|
|
47
|
+
/** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
|
|
48
|
+
readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
|
|
52
|
+
|
|
53
|
+
const finding = (at: AstNode | undefined, message: string): Finding => {
|
|
54
|
+
const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
|
|
55
|
+
return { file: ENDPOINT_FIXTURES_FILE, line, column, severity: 'refusal', rule: 'endpoint-fixture', message, allowed: ALLOWED }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isSampleObject(value: Sample): value is { readonly [key: string]: Sample } {
|
|
59
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A plain literal value, or the node that is not one. */
|
|
63
|
+
function literal(
|
|
64
|
+
node: AstNode | undefined,
|
|
65
|
+
): { readonly ok: true; readonly value: Sample } | { readonly ok: false; readonly at: AstNode | undefined } {
|
|
66
|
+
if (node === undefined) return { ok: false, at: node }
|
|
67
|
+
if (node.type === 'Literal') {
|
|
68
|
+
const value = node['value']
|
|
69
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
|
|
70
|
+
return { ok: true, value }
|
|
71
|
+
}
|
|
72
|
+
return { ok: false, at: node }
|
|
73
|
+
}
|
|
74
|
+
if (node.type === 'TemplateLiteral') {
|
|
75
|
+
const text = staticString(node)
|
|
76
|
+
return text === undefined ? { ok: false, at: node } : { ok: true, value: text }
|
|
77
|
+
}
|
|
78
|
+
if (node.type === 'UnaryExpression' && node['operator'] === '-') {
|
|
79
|
+
const inner = literal(child(node, 'argument'))
|
|
80
|
+
return inner.ok && typeof inner.value === 'number' ? { ok: true, value: -inner.value } : { ok: false, at: node }
|
|
81
|
+
}
|
|
82
|
+
if (node.type === 'ArrayExpression') {
|
|
83
|
+
const items: Sample[] = []
|
|
84
|
+
for (const element of children(node, 'elements')) {
|
|
85
|
+
const item = literal(element ?? undefined)
|
|
86
|
+
if (!item.ok) return item
|
|
87
|
+
items.push(item.value)
|
|
88
|
+
}
|
|
89
|
+
return { ok: true, value: items }
|
|
90
|
+
}
|
|
91
|
+
if (node.type === 'ObjectExpression') {
|
|
92
|
+
const entries: [string, Sample][] = []
|
|
93
|
+
for (const property of children(node, 'properties')) {
|
|
94
|
+
if (property?.type !== 'Property' || property['computed'] === true || property['method'] === true) return { ok: false, at: property ?? node }
|
|
95
|
+
const key = staticKey(property, 'key')
|
|
96
|
+
if (key === undefined || key === '__proto__') return { ok: false, at: property }
|
|
97
|
+
const value = literal(child(property, 'value'))
|
|
98
|
+
if (!value.ok) return value
|
|
99
|
+
entries.push([key, value.value])
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, value: Object.fromEntries(entries) }
|
|
102
|
+
}
|
|
103
|
+
return { ok: false, at: node }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** One `export const <name> = { '<endpoint id>': { … } }`, read into an object of objects. */
|
|
107
|
+
function byId(
|
|
108
|
+
declarator: AstNode,
|
|
109
|
+
name: string,
|
|
110
|
+
): { readonly ok: true; readonly value: ById } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
111
|
+
const init = child(declarator, 'init')
|
|
112
|
+
const value = literal(init)
|
|
113
|
+
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
114
|
+
const all = value.value
|
|
115
|
+
if (!isSampleObject(all)) {
|
|
116
|
+
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
117
|
+
}
|
|
118
|
+
const entries: Record<string, Readonly<Record<string, Sample>>> = {}
|
|
119
|
+
for (const [id, entry] of Object.entries(all)) {
|
|
120
|
+
if (!isSampleObject(entry)) {
|
|
121
|
+
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${name === SEEDS_EXPORT ? 'columns' : 'input fields'}`)] }
|
|
122
|
+
}
|
|
123
|
+
entries[id] = entry
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, value: entries }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
|
|
129
|
+
function fieldsById(
|
|
130
|
+
declarator: AstNode,
|
|
131
|
+
name: FieldExport,
|
|
132
|
+
): { readonly ok: true; readonly value: Readonly<Record<string, readonly string[]>> } | {
|
|
133
|
+
readonly ok: false
|
|
134
|
+
readonly findings: readonly Finding[]
|
|
135
|
+
} {
|
|
136
|
+
const init = child(declarator, 'init')
|
|
137
|
+
const value = literal(init)
|
|
138
|
+
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
139
|
+
if (!isSampleObject(value.value)) {
|
|
140
|
+
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
141
|
+
}
|
|
142
|
+
const entries: Record<string, readonly string[]> = {}
|
|
143
|
+
for (const [id, fields] of Object.entries(value.value)) {
|
|
144
|
+
if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
|
|
145
|
+
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of input field names`)] }
|
|
146
|
+
}
|
|
147
|
+
entries[id] = fields.filter((field) => typeof field === 'string')
|
|
148
|
+
}
|
|
149
|
+
return { ok: true, value: entries }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The fixtures of `files`, by endpoint id; none without the file. */
|
|
153
|
+
export function readEndpointFixtures(
|
|
154
|
+
files: ReadonlyMap<string, string>,
|
|
155
|
+
): { readonly ok: true; readonly fixtures: EndpointFixtures } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
156
|
+
const text = files.get(ENDPOINT_FIXTURES_FILE)
|
|
157
|
+
if (text === undefined) return { ok: true, fixtures: NO_FIXTURES }
|
|
158
|
+
if (new TextEncoder().encode(text).byteLength > CONTRACT_LIMITS.sourceBytes) {
|
|
159
|
+
return { ok: false, findings: [finding(undefined, `the fixtures exceed ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
|
|
160
|
+
}
|
|
161
|
+
const parsed = parseModule(ENDPOINT_FIXTURES_FILE, text)
|
|
162
|
+
if (!parsed.ok) return { ok: false, findings: [finding(undefined, parsed.message)] }
|
|
163
|
+
const program = parsed.module.program
|
|
164
|
+
if (nodeDepth(program) > CONTRACT_LIMITS.astDepth) {
|
|
165
|
+
return { ok: false, findings: [finding(undefined, `the fixtures nest deeper than ${CONTRACT_LIMITS.astDepth}`)] }
|
|
166
|
+
}
|
|
167
|
+
const read = new Map<string, ById>()
|
|
168
|
+
const fields = new Map<FieldExport, Readonly<Record<string, readonly string[]>>>()
|
|
169
|
+
for (const statement of children(program, 'body')) {
|
|
170
|
+
const declaration = statement === null ? undefined : child(statement, 'declaration')
|
|
171
|
+
const declarators = declaration?.type === 'VariableDeclaration' && declaration['kind'] === 'const' ? children(declaration, 'declarations') : []
|
|
172
|
+
const declarator = declarators.length === 1 ? declarators[0] : undefined
|
|
173
|
+
const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
|
|
174
|
+
if (
|
|
175
|
+
statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
|
|
176
|
+
|| (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
|
|
177
|
+
|| (isFieldExport(name) && fields.has(name))
|
|
178
|
+
) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
findings: [
|
|
182
|
+
finding(
|
|
183
|
+
statement ?? undefined,
|
|
184
|
+
`the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
|
|
185
|
+
),
|
|
186
|
+
],
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (isFieldExport(name)) {
|
|
190
|
+
const listed = fieldsById(declarator, name)
|
|
191
|
+
if (!listed.ok) return listed
|
|
192
|
+
fields.set(name, listed.value)
|
|
193
|
+
continue
|
|
194
|
+
}
|
|
195
|
+
const value = byId(declarator, name)
|
|
196
|
+
if (!value.ok) return value
|
|
197
|
+
if (name === ROWS_EXPORT) {
|
|
198
|
+
const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((table) => typeof table !== 'string'))
|
|
199
|
+
if (named !== undefined) {
|
|
200
|
+
return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
read.set(name, value.value)
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
ok: true,
|
|
207
|
+
fixtures: {
|
|
208
|
+
inputs: read.get(FIXTURES_EXPORT) ?? {},
|
|
209
|
+
seeds: read.get(SEEDS_EXPORT) ?? {},
|
|
210
|
+
members: fields.get(MEMBERS_EXPORT) ?? {},
|
|
211
|
+
invitations: fields.get(INVITATIONS_EXPORT) ?? {},
|
|
212
|
+
links: fields.get(LINKS_EXPORT) ?? {},
|
|
213
|
+
rows: Object.fromEntries(
|
|
214
|
+
Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
|
|
215
|
+
id,
|
|
216
|
+
Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
|
|
217
|
+
]),
|
|
218
|
+
),
|
|
219
|
+
},
|
|
220
|
+
}
|
|
221
|
+
}
|
package/src/finding.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { AstNode, Position } from './ast'
|
|
2
|
+
import { positionOf } from './ast'
|
|
3
|
+
|
|
4
|
+
/** Rules whose finding fails the check: the framework's forms and platform integrity. */
|
|
5
|
+
export const REFUSAL_RULE_IDS = [
|
|
6
|
+
'parse-error',
|
|
7
|
+
'literal',
|
|
8
|
+
'contract',
|
|
9
|
+
'forbidden-import',
|
|
10
|
+
'test-only-import',
|
|
11
|
+
'unchecked-import',
|
|
12
|
+
'forbidden-global',
|
|
13
|
+
'raw-sql',
|
|
14
|
+
'type-assertion',
|
|
15
|
+
'any-type',
|
|
16
|
+
'suppression-comment',
|
|
17
|
+
'capability-widening',
|
|
18
|
+
'prototype-assignment',
|
|
19
|
+
'framework-write',
|
|
20
|
+
'env-read',
|
|
21
|
+
'public-env',
|
|
22
|
+
'cross-app-fetch',
|
|
23
|
+
'key-literal',
|
|
24
|
+
'client-identity',
|
|
25
|
+
'sensitive-log',
|
|
26
|
+
'unsafe-html',
|
|
27
|
+
'dynamic-code',
|
|
28
|
+
'migration-name',
|
|
29
|
+
'file-scan-migration',
|
|
30
|
+
'crontab',
|
|
31
|
+
'package-replacement',
|
|
32
|
+
'skipped-test',
|
|
33
|
+
'test-without-assertion',
|
|
34
|
+
'generated-test-hash',
|
|
35
|
+
'mock-module',
|
|
36
|
+
'endpoint-fixture',
|
|
37
|
+
'spa-server-import',
|
|
38
|
+
'layer-import',
|
|
39
|
+
'generated-test-import',
|
|
40
|
+
'shared-import',
|
|
41
|
+
] as const
|
|
42
|
+
|
|
43
|
+
/** Rules that report a step out of the application architecture. */
|
|
44
|
+
export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, and a
|
|
48
|
+
* `{ member: true }` endpoint of a contract whose external role admits people from outside the organization.
|
|
49
|
+
*/
|
|
50
|
+
export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
|
|
51
|
+
|
|
52
|
+
export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
|
|
53
|
+
|
|
54
|
+
export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number]
|
|
55
|
+
export type HintRuleId = (typeof HINT_RULE_IDS)[number]
|
|
56
|
+
export type RuleId = (typeof RULE_IDS)[number]
|
|
57
|
+
export type Severity = 'refusal' | 'hint'
|
|
58
|
+
|
|
59
|
+
interface FindingFields {
|
|
60
|
+
/** Relative to the application root, with `/` separators. */
|
|
61
|
+
readonly file: string
|
|
62
|
+
readonly line: number
|
|
63
|
+
readonly column: number
|
|
64
|
+
readonly message: string
|
|
65
|
+
/** What to write instead; every finding names it, because the reader is often an agent with no other feedback. */
|
|
66
|
+
readonly allowed: string
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A finding's severity is its rule's: a refusal rule never reports a hint, nor the reverse. */
|
|
70
|
+
export type Finding =
|
|
71
|
+
| (FindingFields & { readonly severity: 'refusal'; readonly rule: RefusalRuleId })
|
|
72
|
+
| (FindingFields & { readonly severity: 'hint'; readonly rule: HintRuleId })
|
|
73
|
+
|
|
74
|
+
export const isHintRule = (rule: RuleId): rule is HintRuleId => HINT_RULE_IDS.some((hint) => hint === rule)
|
|
75
|
+
|
|
76
|
+
export type Report = (at: AstNode | Position, rule: RuleId, message: string, allowed: string) => void
|
|
77
|
+
|
|
78
|
+
export const reporter = (file: string, findings: Finding[]): Report => (at, rule, message, allowed) => {
|
|
79
|
+
const { line, column } = 'type' in at ? positionOf(at) : at
|
|
80
|
+
if (isHintRule(rule)) findings.push({ file, line, column, severity: 'hint', rule, message, allowed })
|
|
81
|
+
else findings.push({ file, line, column, severity: 'refusal', rule, message, allowed })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const formatFinding = (finding: Finding): string =>
|
|
85
|
+
`${finding.file}:${finding.line}:${finding.column} ${finding.rule} ${finding.message} (allowed form: ${finding.allowed})`
|
|
86
|
+
|
|
87
|
+
export const compareFindings = (left: Finding, right: Finding): number =>
|
|
88
|
+
left.file.localeCompare(right.file) || left.line - right.line || left.column - right.column || left.rule.localeCompare(right.rule)
|