@fabrika/check 0.9.0-dev.12 → 0.9.0-dev.13

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.9.0-dev.12",
3
+ "version": "0.9.0-dev.13",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,11 +47,11 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-dev.12",
51
- "@fabrika/auth-core": "0.9.0-dev.12",
52
- "@fabrika/db": "0.9.0-dev.12",
53
- "@fabrika/operations-contract": "0.9.0-dev.12",
54
- "@fabrika/platform-node": "0.9.0-dev.12",
50
+ "@fabrika/app": "0.9.0-dev.13",
51
+ "@fabrika/auth-core": "0.9.0-dev.13",
52
+ "@fabrika/db": "0.9.0-dev.13",
53
+ "@fabrika/operations-contract": "0.9.0-dev.13",
54
+ "@fabrika/platform-node": "0.9.0-dev.13",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/check.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
2
  import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry } from '@fabrika/auth-core'
3
- import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
3
+ import { accessTables, type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
4
4
  import { readdir, readFile } from 'node:fs/promises'
5
5
  import { join } from 'node:path'
6
6
  import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
@@ -41,6 +41,7 @@ import {
41
41
  checkFileColumnMigrations,
42
42
  checkMigrationNames,
43
43
  checkSqliteFrameworkNames,
44
+ checkSqliteViewTriggers,
44
45
  type ConflictInsert,
45
46
  type FileColumn,
46
47
  } from './rules/migrations'
@@ -317,11 +318,14 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
317
318
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
318
319
  const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
319
320
  findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
320
- if (artifact !== null) findings.push(...checkMigrationClassification(tree.files, artifact.app))
321
+ if (artifact !== null) {
322
+ findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables)))
323
+ }
321
324
  if (applicationDialect(tree.files) === 'sqlite') {
322
325
  if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
323
326
  findings.push(...checkCurrentTimestampDefaults(tree.files))
324
327
  findings.push(...checkSqliteFrameworkNames(tree.files))
328
+ findings.push(...checkSqliteViewTriggers(tree.files))
325
329
  findings.push(...(await checkBackupPlan(tree.files)))
326
330
  }
327
331
  if (declaredTables !== null) {
package/src/contract.ts CHANGED
@@ -19,6 +19,7 @@ import { parseShellModule } from './slice'
19
19
  import { checkTrustedResolution } from './trust'
20
20
 
21
21
  export { ContractError } from '@fabrika/app/contract'
22
+ export { accessTables } from '@fabrika/db/tables'
22
23
  export { type Finding, formatFinding } from './finding'
23
24
  export { contractReaderInputs } from './inputs'
24
25
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
package/src/finding.ts CHANGED
@@ -48,6 +48,7 @@ export const REFUSAL_RULE_IDS = [
48
48
  'cloudflare-job-segment',
49
49
  'cloudflare-current-timestamp',
50
50
  'cloudflare-framework-name',
51
+ 'cloudflare-view-trigger',
51
52
  ] as const
52
53
 
53
54
  /** Rules that report a step out of the application architecture. */
@@ -216,7 +216,9 @@ class SurfaceReader {
216
216
  'members',
217
217
  'directory',
218
218
  'terminal',
219
+ 'relations',
219
220
  ])
221
+ const relations = fields.get('relations')
220
222
  const locale = fields.get('locale')
221
223
  const displayName = fields.get('displayName')
222
224
  const mail = fields.get('mail')
@@ -237,6 +239,13 @@ class SurfaceReader {
237
239
  dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
238
240
  actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
239
241
  roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
242
+ ...(relations === undefined
243
+ ? {}
244
+ : {
245
+ relations: this.#each(entries(relations, value, 'relations'), (name, relation) => ({
246
+ dimension: text(strictFields(relation, `relation '${name}'`, ['dimension'], []).get('dimension'), relation, 'dimension'),
247
+ })),
248
+ }),
240
249
  }
241
250
  }
242
251
 
@@ -283,16 +292,18 @@ class SurfaceReader {
283
292
  }
284
293
 
285
294
  #role(name: string, value: LiteralValue): RoleDef<string, string, string> {
286
- const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external'])
295
+ const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external', 'via'])
287
296
  const member = fields.get('member')
288
297
  const memberFields = member === undefined ? undefined : strictFields(member, `role '${name}' member`, ['scope', 'assignableBy'], [])
289
298
  const external = fields.get('external')
299
+ const via = fields.get('via')
290
300
  return {
291
301
  grants: texts(fields.get('grants'), value, 'grants'),
292
302
  member: memberFields === undefined
293
303
  ? undefined
294
304
  : { scope: text(memberFields.get('scope'), value, 'scope'), assignableBy: texts(memberFields.get('assignableBy'), value, 'assignableBy') },
295
305
  ...(external === undefined ? {} : { external: externalOf(external) }),
306
+ ...(via === undefined ? {} : { via: this.#each(entries(via, value, 'via'), (_, actions) => texts(actions, value, 'via')) }),
296
307
  }
297
308
  }
298
309
 
@@ -83,7 +83,19 @@ 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', 'members', 'directory', 'terminal'] as const
86
+ const VOCABULARY_SECTIONS = [
87
+ 'app',
88
+ 'dimensions',
89
+ 'actions',
90
+ 'roles',
91
+ 'relations',
92
+ 'locale',
93
+ 'displayName',
94
+ 'mail',
95
+ 'members',
96
+ 'directory',
97
+ 'terminal',
98
+ ] as const
87
99
 
88
100
  const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
89
101
 
@@ -106,6 +106,37 @@ export const checkSqliteFrameworkNames = (files: ReadonlyMap<string, string>): F
106
106
  return findings
107
107
  }
108
108
 
109
+ /**
110
+ * A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
111
+ * takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
112
+ */
113
+ export const checkSqliteViewTriggers = (files: ReadonlyMap<string, string>): Finding[] => {
114
+ const findings: Finding[] = []
115
+ for (const [path, sql] of files) {
116
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
117
+ for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
118
+ if (upperWord(tokens[0]) !== 'CREATE') continue
119
+ const at = skipWords(tokens, skipWords(tokens, 1, 'TEMP'), 'TEMPORARY')
120
+ if (upperWord(tokens[at]) !== 'TRIGGER') continue
121
+ for (let index = at + 1; index < tokens.length && upperWord(tokens[index]) !== 'ON'; index++) {
122
+ const token = tokens[index]
123
+ if (token === undefined || upperWord(token) !== 'INSTEAD' || upperWord(tokens[index + 1]) !== 'OF') continue
124
+ findings.push({
125
+ file: path,
126
+ line: token.line,
127
+ column: 1,
128
+ severity: 'refusal',
129
+ rule: 'cloudflare-view-trigger',
130
+ message: 'an INSTEAD OF trigger makes a view writable, and a view is read-only (ADR-0072)',
131
+ allowed: 'a view without triggers, written through its source tables',
132
+ })
133
+ break
134
+ }
135
+ }
136
+ }
137
+ return findings
138
+ }
139
+
109
140
  /** A declared file column: `table.column` holds files of `kind`. */
110
141
  export interface FileColumn {
111
142
  readonly table: string
@@ -24,15 +24,16 @@ const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
24
24
  }).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
25
25
 
26
26
  /**
27
- * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
27
+ * Every statement Control's classifier refuses, at its file and line, against the application's access tables. Control refuses a deploy whose new migration holds
28
28
  * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
29
29
  * checked, applied or not: the checker does not know which an environment holds.
30
30
  */
31
- export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
31
+ export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[]): Finding[] => {
32
32
  const texts = migrationTexts(files)
33
33
  if (texts.length === 0) return []
34
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) =>
35
+ const options = { accessTables: new Set(accessTables) }
36
+ return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId), options).files.flatMap((file) =>
36
37
  file.refused.map((refusal): Finding => ({
37
38
  file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
38
39
  line: refusal.line,
@@ -5,6 +5,7 @@ import { type ParsedModule } from './ast';
5
5
  import { type Finding } from './finding';
6
6
  import { ModuleGraph } from './graph';
7
7
  export { ContractError } from '@fabrika/app/contract';
8
+ export { accessTables } from '@fabrika/db/tables';
8
9
  export { type Finding, formatFinding } from './finding';
9
10
  export { contractReaderInputs } from './inputs';
10
11
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout';
@@ -1,6 +1,6 @@
1
1
  import type { AstNode, Position } from './ast';
2
2
  /** Rules whose finding fails the check: the framework's forms and platform integrity. */
3
- export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
3
+ export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "cloudflare-view-trigger"];
4
4
  /** Rules that report a step out of the application architecture. */
5
5
  export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
6
6
  /**
@@ -9,7 +9,7 @@ export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cr
9
9
  * Cloudflare mutation that waits for an outside call inside the object's transaction.
10
10
  */
11
11
  export declare const HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
12
- export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
12
+ export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "cloudflare-view-trigger", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
13
13
  export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number];
14
14
  export type HintRuleId = (typeof HINT_RULE_IDS)[number];
15
15
  export type RuleId = (typeof RULE_IDS)[number];
@@ -12,6 +12,11 @@ export declare const checkCurrentTimestampDefaults: (files: ReadonlyMap<string,
12
12
  * or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
13
13
  */
14
14
  export declare const checkSqliteFrameworkNames: (files: ReadonlyMap<string, string>) => Finding[];
15
+ /**
16
+ * A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
17
+ * takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
18
+ */
19
+ export declare const checkSqliteViewTriggers: (files: ReadonlyMap<string, string>) => Finding[];
15
20
  /** A declared file column: `table.column` holds files of `kind`. */
16
21
  export interface FileColumn {
17
22
  readonly table: string;
@@ -1,10 +1,10 @@
1
1
  import type { Finding } from '../finding';
2
2
  /**
3
- * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
3
+ * Every statement Control's classifier refuses, at its file and line, against the application's access tables. Control refuses a deploy whose new migration holds
4
4
  * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
5
5
  * checked, applied or not: the checker does not know which an environment holds.
6
6
  */
7
- export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string) => Finding[];
7
+ export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[]) => Finding[];
8
8
  /**
9
9
  * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
10
10
  * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration