@fabrika/check 0.5.5 → 0.7.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.5.5",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -46,11 +46,11 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@babel/parser": "8.0.7",
49
- "@fabrika/app": "0.5.5",
50
- "@fabrika/auth-core": "0.5.5",
51
- "@fabrika/db": "0.5.5",
52
- "@fabrika/operations-contract": "0.5.5",
53
- "@fabrika/platform-node": "0.5.5",
49
+ "@fabrika/app": "0.7.0",
50
+ "@fabrika/auth-core": "0.7.0",
51
+ "@fabrika/db": "0.7.0",
52
+ "@fabrika/operations-contract": "0.7.0",
53
+ "@fabrika/platform-node": "0.7.0",
54
54
  "zod": "^3.25.76"
55
55
  }
56
56
  }
package/src/check.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
+ import type { ContractArtifact } from '@fabrika/auth-core'
3
+ import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
1
4
  import { readdir, readFile } from 'node:fs/promises'
2
5
  import { join } from 'node:path'
3
- import { type ParsedModule, parseModule, walk } from './ast'
6
+ import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
4
7
  import { contractModules, readContractModule } from './contract'
5
8
  import { compareFindings, type Finding, reporter } from './finding'
6
9
  import { ModuleGraph } from './graph'
@@ -17,6 +20,8 @@ import {
17
20
  ZEROPS_FILES,
18
21
  } from './layout'
19
22
  import type { PackedSet } from './packed'
23
+ import { ReaderProblems } from './reader/problems'
24
+ import { readTablesValue } from './reader/tables'
20
25
  import { type ModuleReference, moduleReferences } from './references'
21
26
  import { type ImportMappings, readImportMappings } from './resolution'
22
27
  import { checkContractRead } from './rules/contract'
@@ -26,16 +31,20 @@ import { checkClientIdentity } from './rules/identity'
26
31
  import { checkGeneratedTests } from './rules/isolation'
27
32
  import { checkJsonStrings } from './rules/json'
28
33
  import { checkLiteralGraph } from './rules/literal'
29
- import { checkMigrationNames, checkScanMigrations } from './rules/migrations'
34
+ import { checkConflictIndexes, checkFileColumnMigrations, checkMigrationNames, type ConflictInsert, type FileColumn } from './rules/migrations'
30
35
  import { checkModuleReferences } from './rules/modules'
31
36
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
32
- import { checkRuntimeNode, rawSqlBindings } from './rules/runtime'
37
+ import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
33
38
  import { checkStructureNode, checkStructureReferences, structurePlace } from './rules/structure'
34
39
  import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
35
40
  import { checkComments, checkTypeNode } from './rules/types'
36
41
  import { moduleSlice, sliceFinding } from './slice'
37
42
  import { BUNFIG_FILE, checkTrustedResolution } from './trust'
38
43
 
44
+ /** Every file column the table policies declare, with its kind. */
45
+ const fileColumns = (policies: TablePolicies): FileColumn[] =>
46
+ Object.entries(policies).flatMap(([table, policy]) => Object.entries(policy.files ?? {}).map(([column, kind]) => ({ table, column, kind })))
47
+
39
48
  export interface CheckInput {
40
49
  /** The application's root directory. */
41
50
  readonly root: string
@@ -69,6 +78,16 @@ export const readApplicationTree = async (root: string): Promise<ApplicationTree
69
78
  return { files, links }
70
79
  }
71
80
 
81
+ /** The findings a module rule leaves until the contract is read: they depend on what it declares. */
82
+ interface ContractDependent {
83
+ /** Each `fetch` of an absolute URL, with its static prefix. */
84
+ readonly fetches: { readonly target: string; readonly finding: Finding }[]
85
+ /** Each `ctx.url` with a literal endpoint id. */
86
+ readonly urls: { readonly endpoint: string; readonly finding: Finding }[]
87
+ /** Each insert with literal `onConflict.columns`, checked against the migrations' unique indexes. */
88
+ readonly inserts: ConflictInsert[]
89
+ }
90
+
72
91
  const checkSourceModule = async (
73
92
  module: ParsedModule,
74
93
  references: readonly ModuleReference[],
@@ -76,12 +95,36 @@ const checkSourceModule = async (
76
95
  mappings: ImportMappings,
77
96
  files: ReadonlyMap<string, string>,
78
97
  findings: Finding[],
98
+ dependent: ContractDependent,
79
99
  ): Promise<void> => {
80
100
  const exists = (path: string): boolean => files.has(path)
81
101
  const report = reporter(module.file, findings)
82
102
  const isGeneratedEntry = module.file === GENERATED_ENTRY_FILE
83
103
  const isTest = isTestFile(module.file)
84
- const context = { report, isGeneratedEntry, rawSql: rawSqlBindings(module.program), isServerModule: isServerModule(module.file) }
104
+ const deferred = (at: AstNode, rule: 'cross-app-fetch' | 'url-endpoint' | 'on-conflict-index', message: string, allowed: string): Finding[] => {
105
+ const found: Finding[] = []
106
+ reporter(module.file, found)(at, rule, message, allowed)
107
+ return found
108
+ }
109
+ const context = {
110
+ report,
111
+ isGeneratedEntry,
112
+ rawSql: rawSqlBindings(module.program),
113
+ isServerModule: isServerModule(module.file),
114
+ absoluteFetch: (node: AstNode, target: string) => {
115
+ const { message, allowed } = crossAppFetchMessage(target)
116
+ for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, finding })
117
+ },
118
+ appUrl: (node: AstNode, endpoint: string) => {
119
+ const message = `ctx.url names '${endpoint}', which is no procedure of the contract`
120
+ for (const finding of deferred(node, 'url-endpoint', message, URL_ENDPOINT_ALLOWED)) dependent.urls.push({ endpoint, finding })
121
+ },
122
+ conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => {
123
+ const message = `${table}.insert names onConflict columns (${columns.join(', ')}) that no unique index of a migration covers`
124
+ const allowed = `a migration with create unique index ${table}_${columns.join('_')} on ${table} (${columns.join(', ')}), or the columns of one`
125
+ for (const finding of deferred(node, 'on-conflict-index', message, allowed)) dependent.inserts.push({ table, columns, finding })
126
+ },
127
+ }
85
128
  const trusted = trustedBindings(module.file, module.program, mappings)
86
129
  const place = structurePlace(module.file, isGeneratedEntry)
87
130
  walk(module.program, (node, ancestors) => {
@@ -106,12 +149,54 @@ const shellModule = (module: ParsedModule, text: string): { readonly module: Par
106
149
  return { module: parsed?.ok === true ? parsed.module : module, refusals }
107
150
  }
108
151
 
152
+ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<mount>.<group>.<procedure>', { input?, query? })"
153
+
154
+ /** What the module rules that wait for the contract compare against: its procedure ids and every declared origin. */
155
+ interface CompiledReach {
156
+ readonly procedures: ReadonlySet<string>
157
+ readonly origins: readonly string[]
158
+ }
159
+
160
+ /** The contract's procedures and origins, or `null` when it does not compile, which its own rule reports. */
161
+ const compiledReach = (contract: AnyContract, tables: Tables<unknown, unknown> | null): CompiledReach | null => {
162
+ let artifact: ContractArtifact
163
+ try {
164
+ artifact = compileContract(contract, tables ?? {})
165
+ } catch (error) {
166
+ if (error instanceof ContractError) return null
167
+ throw error
168
+ }
169
+ const procedures = artifact.endpoints.filter((row) =>
170
+ (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
+ )
172
+ return {
173
+ procedures: new Set(procedures.map((row) => row.id)),
174
+ origins: Object.values(artifact.declared ?? {}).flatMap((reach) => reach.egress ?? []),
175
+ }
176
+ }
177
+
178
+ /**
179
+ * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
180
+ * not accepted), and every one stands when the contract does not compile. A `ctx.url` stands when the contract
181
+ * compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
182
+ */
183
+ const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
184
+ ...dependent.fetches.filter(({ target }) => reach === null || !reach.origins.some((origin) => isWithinOrigin(target, origin))).map(({ finding }) =>
185
+ finding
186
+ ),
187
+ ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
188
+ ]
189
+
190
+ const isWithinOrigin = (target: string, origin: string): boolean =>
191
+ target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
192
+
109
193
  /** Runs every rule over one application and returns the findings in file, line and column order. */
110
194
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
111
195
  const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
112
196
  const findings: Finding[] = []
113
197
  const modules = new Map<string, ParsedModule>()
114
198
  const references = new Map<string, readonly ModuleReference[]>()
199
+ const dependent: ContractDependent = { fetches: [], urls: [], inserts: [] }
115
200
  const checkedPaths = [...tree.files.keys()].filter(isCheckedFile).sort()
116
201
  const mappings = readImportMappings(tree.files)
117
202
  const trust = checkTrustedResolution(tree.files)
@@ -141,7 +226,7 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
141
226
  modules.set(path, parsed.module)
142
227
  const referencesOfModule = moduleReferences(parsed.module.program)
143
228
  references.set(path, referencesOfModule)
144
- await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings)
229
+ await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
145
230
  }
146
231
  const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
147
232
  for (const path of modules.keys()) {
@@ -168,9 +253,12 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
168
253
  findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
169
254
  findings.push(...checkMigrationNames(checkedPaths))
170
255
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
171
- if (read?.ok === true) {
172
- const scanning = Object.entries(read.contract.surface.files ?? {}).filter(([, collection]) => collection.scan === true).map(([name]) => name)
173
- findings.push(...checkScanMigrations(tree.files, scanning))
256
+ const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
257
+ findings.push(...contractDependentFindings(dependent, read?.ok === true ? compiledReach(read.contract, declaredTables) : null))
258
+ if (declaredTables !== null) {
259
+ const policies = tablePolicies(declaredTables)
260
+ findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
261
+ findings.push(...checkConflictIndexes(tree.files, new Set(Object.keys(policies)), dependent.inserts))
174
262
  }
175
263
  const bunfig = tree.files.get(BUNFIG_FILE)
176
264
  if (bunfig !== undefined) findings.push(...checkTestSuiteConfig(bunfig))
package/src/contract.ts CHANGED
@@ -23,6 +23,7 @@ export { type Finding, formatFinding } from './finding'
23
23
  export { contractReaderInputs } from './inputs'
24
24
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
25
25
  export { CONTRACT_LIMITS } from './limits'
26
+ export { lockedRegistryVersion, LOCKFILE } from './lockfile'
26
27
  export { CHECKER_VERSION } from './version'
27
28
 
28
29
  /** Every form the reader refuses, each with its file, line, column and the allowed form. */
@@ -40,8 +41,7 @@ export class ContractSourceError extends Error {
40
41
  * The contract artifact of an application, read from the text of its files (path relative to the application root →
41
42
  * text): `fabrika.contract.ts`, every module it imports and the configuration that applies to them (`readContract`),
42
43
  * 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.
44
+ * `src/db/tables.ts` declares: its parsed policies, or the artifact form of each policy.
45
45
  *
46
46
  * Throws `ContractSourceError` for a form the reader refuses, and `ContractError` with the same problems
47
47
  * `compileContract` reports for a contract that does not compile.
package/src/finding.ts CHANGED
@@ -20,13 +20,15 @@ export const REFUSAL_RULE_IDS = [
20
20
  'env-read',
21
21
  'public-env',
22
22
  'cross-app-fetch',
23
+ 'url-endpoint',
24
+ 'on-conflict-index',
23
25
  'key-literal',
24
26
  'client-identity',
25
27
  'sensitive-log',
26
28
  'unsafe-html',
27
29
  'dynamic-code',
28
30
  'migration-name',
29
- 'file-scan-migration',
31
+ 'file-column-migration',
30
32
  'crontab',
31
33
  'package-replacement',
32
34
  'skipped-test',
@@ -0,0 +1,47 @@
1
+ // An application's `bun.lock`: the checker refuses an entry of a trusted package that does not come from the npm
2
+ // registry, and Control reads from it the framework release the application pins (ADR-0062). Worker-safe.
3
+
4
+ import { parseJsonc } from './jsonc'
5
+
6
+ export const LOCKFILE = 'bun.lock'
7
+
8
+ /** An exact version, as `bun install` records one resolved from the registry. */
9
+ export const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
10
+
11
+ /** One `packages` entry: `[<name>@<version>, <registry>, <metadata>, <integrity>]`; a tarball has no registry. */
12
+ export interface LockfileEntry {
13
+ /** What follows `<name>@` in the resolution, or empty when the resolution names another package. */
14
+ readonly version: string
15
+ readonly registry: unknown
16
+ readonly integrity: unknown
17
+ }
18
+
19
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => typeof value === 'object' && value !== null && !Array.isArray(value)
20
+
21
+ /** The `packages` of a `bun.lock` by key; null when the text is not a lockfile bun writes. */
22
+ export function lockfilePackages(text: string): Readonly<Record<string, unknown>> | null {
23
+ const lockfile = parseJsonc(text)
24
+ const packages = isRecord(lockfile) ? lockfile['packages'] : undefined
25
+ return isRecord(packages) ? packages : null
26
+ }
27
+
28
+ export function lockfileEntry(name: string, entry: unknown): LockfileEntry {
29
+ const resolution = Array.isArray(entry) ? entry[0] : undefined
30
+ return {
31
+ version: typeof resolution === 'string' && resolution.startsWith(`${name}@`) ? resolution.slice(name.length + 1) : '',
32
+ registry: Array.isArray(entry) ? entry[1] : undefined,
33
+ integrity: Array.isArray(entry) ? entry.at(-1) : undefined,
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The registry version the lockfile resolves the package `name` to for the application itself: its top-level entry,
39
+ * not one nested under another package. Null when the text is not a lockfile, holds no such entry, or resolves it from
40
+ * anywhere but the npm registry.
41
+ */
42
+ export function lockedRegistryVersion(text: string, name: string): string | null {
43
+ const packages = lockfilePackages(text)
44
+ if (packages === null) return null
45
+ const entry = lockfileEntry(name, packages[name])
46
+ return entry.registry === '' && EXACT_VERSION.test(entry.version) ? entry.version : null
47
+ }
package/src/packed.ts CHANGED
@@ -23,10 +23,13 @@ export interface PackedSet {
23
23
  readonly tarballs: ReadonlyMap<string, string>
24
24
  }
25
25
 
26
+ /** An npm package name, scoped or not: a pack holds `agent-canvas` beside the `@fabrika/*` set. */
27
+ const PACKAGE_NAME = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/
28
+
26
29
  const releaseManifestSchema = z.object({
27
30
  version: z.string().min(1),
28
31
  packages: z.array(z.object({
29
- name: z.string().startsWith('@fabrika/'),
32
+ name: z.string().regex(PACKAGE_NAME),
30
33
  filename: z.string().regex(/^[A-Za-z0-9._-]+\.tgz$/),
31
34
  integrity: z.string().startsWith('sha512-'),
32
35
  })),