@fabrika/check 0.8.2 → 0.9.0-cloudflare.2

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.
Files changed (63) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +49 -12
  3. package/src/dialect.ts +29 -0
  4. package/src/endpoint-fixtures.ts +99 -13
  5. package/src/finding.ts +7 -3
  6. package/src/index.ts +2 -1
  7. package/src/layout.ts +8 -1
  8. package/src/reader/surface.ts +16 -1
  9. package/src/resolution.ts +2 -2
  10. package/src/rules/cloudflare.ts +58 -0
  11. package/src/rules/framework.ts +2 -2
  12. package/src/rules/isolation.ts +5 -1
  13. package/src/rules/migrations.ts +31 -0
  14. package/src/rules/modules.ts +9 -3
  15. package/src/rules/runtime.ts +7 -3
  16. package/src/scaffold.ts +265 -38
  17. package/types/src/ast.d.ts +65 -0
  18. package/types/src/bun-plugin.d.ts +12 -0
  19. package/types/src/check.d.ts +19 -0
  20. package/types/src/cli.d.ts +2 -0
  21. package/types/src/contract.d.ts +58 -0
  22. package/types/src/dialect.d.ts +8 -0
  23. package/types/src/endpoint-fixtures.d.ts +54 -0
  24. package/types/src/finding.d.ts +39 -0
  25. package/types/src/graph.d.ts +68 -0
  26. package/types/src/index.d.ts +7 -0
  27. package/types/src/inputs.d.ts +9 -0
  28. package/types/src/jsonc.d.ts +2 -0
  29. package/types/src/layout.d.ts +69 -0
  30. package/types/src/limits.d.ts +15 -0
  31. package/types/src/lockfile.d.ts +19 -0
  32. package/types/src/packed.d.ts +15 -0
  33. package/types/src/reader/problems.d.ts +7 -0
  34. package/types/src/reader/schema.d.ts +18 -0
  35. package/types/src/reader/surface.d.ts +5 -0
  36. package/types/src/reader/tables.d.ts +6 -0
  37. package/types/src/reader/value.d.ts +113 -0
  38. package/types/src/references.d.ts +15 -0
  39. package/types/src/resolution.d.ts +20 -0
  40. package/types/src/rules/cloudflare.d.ts +9 -0
  41. package/types/src/rules/contract.d.ts +8 -0
  42. package/types/src/rules/crontab.d.ts +15 -0
  43. package/types/src/rules/framework.d.ts +19 -0
  44. package/types/src/rules/identity.d.ts +5 -0
  45. package/types/src/rules/isolation.d.ts +18 -0
  46. package/types/src/rules/json.d.ts +3 -0
  47. package/types/src/rules/literal.d.ts +63 -0
  48. package/types/src/rules/migrations.d.ts +34 -0
  49. package/types/src/rules/modules.d.ts +12 -0
  50. package/types/src/rules/packages.d.ts +7 -0
  51. package/types/src/rules/runtime.d.ts +32 -0
  52. package/types/src/rules/structure.d.ts +36 -0
  53. package/types/src/rules/tests.d.ts +22 -0
  54. package/types/src/rules/types.d.ts +4 -0
  55. package/types/src/scaffold-sample.d.ts +8 -0
  56. package/types/src/scaffold.d.ts +34 -0
  57. package/types/src/scope.d.ts +6 -0
  58. package/types/src/slice.d.ts +30 -0
  59. package/types/src/source-maps-cli.d.ts +4 -0
  60. package/types/src/source-maps.d.ts +32 -0
  61. package/types/src/toml.d.ts +30 -0
  62. package/types/src/trust.d.ts +15 -0
  63. package/types/src/version.d.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.8.2",
3
+ "version": "0.9.0-cloudflare.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,27 +16,28 @@
16
16
  },
17
17
  "files": [
18
18
  "src",
19
- "!src/**/__tests__/**"
19
+ "!src/**/__tests__/**",
20
+ "types"
20
21
  ],
21
22
  "exports": {
22
23
  ".": {
23
24
  "bun": "./src/index.ts",
24
- "types": "./src/index.ts",
25
+ "types": "./types/src/index.d.ts",
25
26
  "default": "./src/index.ts"
26
27
  },
27
28
  "./contract": {
28
29
  "bun": "./src/contract.ts",
29
- "types": "./src/contract.ts",
30
+ "types": "./types/src/contract.d.ts",
30
31
  "default": "./src/contract.ts"
31
32
  },
32
33
  "./bun-plugin": {
33
34
  "bun": "./src/bun-plugin.ts",
34
- "types": "./src/bun-plugin.ts",
35
+ "types": "./types/src/bun-plugin.d.ts",
35
36
  "default": "./src/bun-plugin.ts"
36
37
  },
37
38
  "./source-maps": {
38
39
  "bun": "./src/source-maps.ts",
39
- "types": "./src/source-maps.ts",
40
+ "types": "./types/src/source-maps.d.ts",
40
41
  "default": "./src/source-maps.ts"
41
42
  }
42
43
  },
@@ -46,11 +47,11 @@
46
47
  },
47
48
  "dependencies": {
48
49
  "@babel/parser": "8.0.7",
49
- "@fabrika/app": "0.8.2",
50
- "@fabrika/auth-core": "0.8.2",
51
- "@fabrika/db": "0.8.2",
52
- "@fabrika/operations-contract": "0.8.2",
53
- "@fabrika/platform-node": "0.8.2",
50
+ "@fabrika/app": "0.9.0-cloudflare.2",
51
+ "@fabrika/auth-core": "0.9.0-cloudflare.2",
52
+ "@fabrika/db": "0.9.0-cloudflare.2",
53
+ "@fabrika/operations-contract": "0.9.0-cloudflare.2",
54
+ "@fabrika/platform-node": "0.9.0-cloudflare.2",
54
55
  "zod": "^3.25.76"
55
56
  }
56
57
  }
package/src/check.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
- import type { ContractArtifact } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
3
3
  import { 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'
7
7
  import { contractModules, readContractModule } from './contract'
8
+ import { applicationDialect } from './dialect'
8
9
  import { compareFindings, type Finding, reporter } from './finding'
9
10
  import { ModuleGraph } from './graph'
10
11
  import {
@@ -24,6 +25,7 @@ import { ReaderProblems } from './reader/problems'
24
25
  import { readTablesValue } from './reader/tables'
25
26
  import { type ModuleReference, moduleReferences } from './references'
26
27
  import { type ImportMappings, readImportMappings } from './resolution'
28
+ import { checkCloudflareContract } from './rules/cloudflare'
27
29
  import { checkContractRead } from './rules/contract'
28
30
  import { checkCrontab, contractJobs } from './rules/crontab'
29
31
  import { checkFrameworkWrite, trustedBindings } from './rules/framework'
@@ -31,7 +33,14 @@ import { checkClientIdentity } from './rules/identity'
31
33
  import { checkGeneratedTests } from './rules/isolation'
32
34
  import { checkJsonStrings } from './rules/json'
33
35
  import { checkLiteralGraph } from './rules/literal'
34
- import { checkConflictIndexes, checkFileColumnMigrations, checkMigrationNames, type ConflictInsert, type FileColumn } from './rules/migrations'
36
+ import {
37
+ checkConflictIndexes,
38
+ checkCurrentTimestampDefaults,
39
+ checkFileColumnMigrations,
40
+ checkMigrationNames,
41
+ type ConflictInsert,
42
+ type FileColumn,
43
+ } from './rules/migrations'
35
44
  import { checkModuleReferences } from './rules/modules'
36
45
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
37
46
  import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
@@ -155,41 +164,64 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
155
164
  interface CompiledReach {
156
165
  readonly procedures: ReadonlySet<string>
157
166
  readonly origins: readonly string[]
167
+ /** Some cron job declares `egress: 'public'`. */
168
+ readonly publicEgress: boolean
158
169
  }
159
170
 
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
171
+ /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
172
+ const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
163
173
  try {
164
- artifact = compileContract(contract, tables ?? {})
174
+ return compileContract(contract, tables ?? {})
165
175
  } catch (error) {
166
176
  if (error instanceof ContractError) return null
167
177
  throw error
168
178
  }
179
+ }
180
+
181
+ /** The contract's procedures and origins. */
182
+ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
169
183
  const procedures = artifact.endpoints.filter((row) =>
170
184
  (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
185
  )
172
186
  return {
173
187
  procedures: new Set(procedures.map((row) => row.id)),
174
- origins: Object.values(artifact.declared ?? {}).flatMap((reach) => reach.egress ?? []),
188
+ origins: Object.values(artifact.declared ?? {}).flatMap((
189
+ reach,
190
+ ) => (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress)),
191
+ publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
175
192
  }
176
193
  }
177
194
 
178
195
  /**
179
196
  * 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
197
+ * not accepted) and, where a cron job declares `egress: 'public'`, when public egress would refuse it: another scheme,
198
+ * or a host its URL alone refuses (an IP address, a local or internal name, a port). A prefix that ends inside the host
199
+ * is then the runtime's to judge. Every one stands when the contract does not compile. A `ctx.url` stands when the contract
181
200
  * compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
182
201
  */
183
202
  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
- ),
203
+ ...dependent.fetches.filter(({ target }) =>
204
+ reach === null || (!reach.origins.some((origin) => isWithinOrigin(target, origin)) && !(reach.publicEgress && isPublicTarget(target)))
205
+ ).map(({ finding }) => finding),
187
206
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
188
207
  ]
189
208
 
190
209
  const isWithinOrigin = (target: string, origin: string): boolean =>
191
210
  target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
192
211
 
212
+ /** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
213
+ const isPublicTarget = (target: string): boolean => {
214
+ const scheme = /^(https?):\/\//i.exec(target)
215
+ if (scheme === null) return false
216
+ const rest = target.slice(scheme[0].length)
217
+ if (!/[/?#]/.test(rest)) return true
218
+ try {
219
+ return publicEgressRefusal(new URL(target)) === null
220
+ } catch {
221
+ return false
222
+ }
223
+ }
224
+
193
225
  /** Runs every rule over one application and returns the findings in file, line and column order. */
194
226
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
195
227
  const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
@@ -254,7 +286,12 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
254
286
  findings.push(...checkMigrationNames(checkedPaths))
255
287
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
256
288
  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))
289
+ const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
290
+ findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
291
+ if (applicationDialect(tree.files) === 'sqlite') {
292
+ if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
293
+ findings.push(...checkCurrentTimestampDefaults(tree.files))
294
+ }
258
295
  if (declaredTables !== null) {
259
296
  const policies = tablePolicies(declaredTables)
260
297
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
package/src/dialect.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { child, identifierName, parseModule } from './ast'
2
+ import { ModuleGraph, unwrapValue } from './graph'
3
+ import { CONFIG_FILE } from './layout'
4
+
5
+ /** The database an application's data layer runs on: SQLite in its Durable Object on Cloudflare (ADR-0065), else Postgres. */
6
+ export type ApplicationDialect = 'postgres' | 'sqlite'
7
+
8
+ const CLOUDFLARE_PROVIDER = '@fabrika/provider-cloudflare'
9
+
10
+ /**
11
+ * Read statically from `fabrika.config.ts`: SQLite when its default export is a call of the `defineApp` that
12
+ * `@fabrika/provider-cloudflare` exports, the config every Cloudflare application writes. Postgres otherwise,
13
+ * including without a config or when the call's origin is not static.
14
+ */
15
+ export const applicationDialect = (files: ReadonlyMap<string, string>): ApplicationDialect => {
16
+ const text = files.get(CONFIG_FILE)
17
+ if (text === undefined) return 'postgres'
18
+ const parsed = parseModule(CONFIG_FILE, text)
19
+ if (!parsed.ok) return 'postgres'
20
+ const graph = new ModuleGraph(new Map([[CONFIG_FILE, parsed.module]]))
21
+ const exported = graph.exported(parsed.module, 'default')
22
+ if (exported.kind !== 'default') return 'postgres'
23
+ const call = unwrapValue(exported.expression)
24
+ if (call.type !== 'CallExpression') return 'postgres'
25
+ const callee = identifierName(child(call, 'callee'))
26
+ if (callee === undefined) return 'postgres'
27
+ const binding = graph.binding(parsed.module, callee)
28
+ return binding.kind === 'package' && binding.specifier === CLOUDFLARE_PROVIDER && binding.imported === 'defineApp' ? 'sqlite' : 'postgres'
29
+ }
@@ -4,10 +4,19 @@
4
4
  // that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
5
5
  // `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
6
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.
7
+ // table, which the kit seeds in each scope's object; `appRows` the rows of application tables an endpoint's own case
8
+ // reads (the guide a link holder downloads), by table, with their columns, which the kit seeds before each leak or own
9
+ // case asks and removes once it is over; `files` the file of the repository each generated case sends in a file field
10
+ // (a package a handler inspects), by input field, relative to the application's root; `refusals` the error types of the
11
+ // 400s an endpoint's handler answers its own object with when no fixture can meet its domain rule, which the kit then
12
+ // counts as the handler's answer; `pins` known values of text columns of the row an endpoint addresses (a skill's slug a
13
+ // package must name), the own scope's, which the kit writes there instead of a marker.
14
+ // Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
15
+ // `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
16
+ // ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
17
+ // `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`, `export const files = { '<endpoint
18
+ // id>': { <field>: '<path>' } }`, `export const refusals = { '<endpoint id>': ['<error type>'] }` and `export const pins
19
+ // = { '<endpoint id>': { <column>: '<value>' } }`, plain literals only.
11
20
  // Browser-safe.
12
21
 
13
22
  import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
@@ -22,14 +31,18 @@ export const MEMBERS_EXPORT = 'members'
22
31
  export const INVITATIONS_EXPORT = 'invitations'
23
32
  export const LINKS_EXPORT = 'links'
24
33
  export const ROWS_EXPORT = 'rows'
34
+ export const APP_ROWS_EXPORT = 'appRows'
35
+ export const FILES_EXPORT = 'files'
36
+ export const REFUSALS_EXPORT = 'refusals'
37
+ export const PINS_EXPORT = 'pins'
25
38
 
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
39
+ /** The exports that list strings by endpoint id: the input fields the kit fills with something it holds, and the refusals. */
40
+ const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT, REFUSALS_EXPORT] as const
28
41
  type FieldExport = (typeof FIELD_EXPORTS)[number]
29
42
  const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
30
43
 
31
44
  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"
45
+ "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'] }, export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }, export const appRows = { 'portal.guide': { guides: { active: true } } }, export const files = { 'api.skills.publish': { package: 'src/__tests__/fixtures/skill.zip' } }, export const refusals = { 'api.skills.publish': ['skill_frontmatter'] } and export const pins = { 'api.skills.publish': { slug: 'sample-skill' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
33
46
 
34
47
  type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
35
48
 
@@ -46,9 +59,35 @@ export interface EndpointFixtures {
46
59
  readonly links: Readonly<Record<string, readonly string[]>>
47
60
  /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
48
61
  readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
62
+ /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
63
+ readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>
64
+ /** The file each case sends in a file field, a path relative to the application's root, by input field, by endpoint id. */
65
+ readonly files: Readonly<Record<string, Readonly<Record<string, string>>>>
66
+ /** The error types of the 400s an endpoint's handler may answer its own object with, by endpoint id. */
67
+ readonly refusals: Readonly<Record<string, readonly string[]>>
68
+ /** The own scope's value of each pinned text column of the row the endpoint addresses, by endpoint id. */
69
+ readonly pins: Readonly<Record<string, Readonly<Record<string, string>>>>
49
70
  }
50
71
 
51
- export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
72
+ export const NO_FIXTURES: EndpointFixtures = {
73
+ inputs: {},
74
+ seeds: {},
75
+ members: {},
76
+ invitations: {},
77
+ links: {},
78
+ rows: {},
79
+ appRows: {},
80
+ files: {},
81
+ refusals: {},
82
+ pins: {},
83
+ }
84
+
85
+ /**
86
+ * Whether `path` may name a file fixture: relative to the application's root, `/`-separated, and each segment of
87
+ * letters, digits, `_`, `-` and `.` that starts with neither `.` nor `-`, so it never leaves the root, names no dotfile and
88
+ * reads the same as a URL path.
89
+ */
90
+ export const isFixtureFilePath = (path: string): boolean => /^[A-Za-z0-9_][A-Za-z0-9._-]*(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*$/.test(path)
52
91
 
53
92
  const finding = (at: AstNode | undefined, message: string): Finding => {
54
93
  const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
@@ -118,14 +157,15 @@ function byId(
118
157
  const entries: Record<string, Readonly<Record<string, Sample>>> = {}
119
158
  for (const [id, entry] of Object.entries(all)) {
120
159
  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'}`)] }
160
+ const of = name === SEEDS_EXPORT ? 'columns' : name === APP_ROWS_EXPORT ? 'tables' : 'input fields'
161
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${of}`)] }
122
162
  }
123
163
  entries[id] = entry
124
164
  }
125
165
  return { ok: true, value: entries }
126
166
  }
127
167
 
128
- /** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
168
+ /** `export const <members, invitations, links or refusals> = { '<endpoint id>': ['<field>', …] }`, read into lists. */
129
169
  function fieldsById(
130
170
  declarator: AstNode,
131
171
  name: FieldExport,
@@ -142,13 +182,23 @@ function fieldsById(
142
182
  const entries: Record<string, readonly string[]> = {}
143
183
  for (const [id, fields] of Object.entries(value.value)) {
144
184
  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`)] }
185
+ const of = name === REFUSALS_EXPORT ? 'error types' : 'input field names'
186
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of ${of}`)] }
146
187
  }
147
188
  entries[id] = fields.filter((field) => typeof field === 'string')
148
189
  }
149
190
  return { ok: true, value: entries }
150
191
  }
151
192
 
193
+ /** Each entry's string values, by endpoint id: what `rows`, `files` and `pins` hold once checked. */
194
+ const stringsById = (byIdValue: ById): Readonly<Record<string, Readonly<Record<string, string>>>> =>
195
+ Object.fromEntries(
196
+ Object.entries(byIdValue).map(([id, named]) => [
197
+ id,
198
+ Object.fromEntries(Object.entries(named).flatMap(([key, item]) => (typeof item === 'string' ? [[key, item]] : []))),
199
+ ]),
200
+ )
201
+
152
202
  /** The fixtures of `files`, by endpoint id; none without the file. */
153
203
  export function readEndpointFixtures(
154
204
  files: ReadonlyMap<string, string>,
@@ -173,7 +223,9 @@ export function readEndpointFixtures(
173
223
  const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
174
224
  if (
175
225
  statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
176
- || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
226
+ || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && name !== FILES_EXPORT
227
+ && name !== PINS_EXPORT && !isFieldExport(name))
228
+ || read.has(name)
177
229
  || (isFieldExport(name) && fields.has(name))
178
230
  ) {
179
231
  return {
@@ -181,7 +233,7 @@ export function readEndpointFixtures(
181
233
  findings: [
182
234
  finding(
183
235
  statement ?? undefined,
184
- `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
236
+ `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT}, ${APP_ROWS_EXPORT}, ${FILES_EXPORT}, ${REFUSALS_EXPORT} and ${PINS_EXPORT} = { … }, each at most once`,
185
237
  ),
186
238
  ],
187
239
  }
@@ -200,6 +252,26 @@ export function readEndpointFixtures(
200
252
  return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
201
253
  }
202
254
  }
255
+ if (name === FILES_EXPORT) {
256
+ const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((path) => typeof path !== 'string'))
257
+ if (named !== undefined) {
258
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the files of ${named[0]} name each field's file as a path string`)] }
259
+ }
260
+ }
261
+ if (name === PINS_EXPORT) {
262
+ const named = Object.entries(value.value).find(([, columns]) =>
263
+ Object.values(columns).some((pinned) => typeof pinned !== 'string' || pinned === '')
264
+ )
265
+ if (named !== undefined) {
266
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the pins of ${named[0]} give each column a non-empty string`)] }
267
+ }
268
+ }
269
+ if (name === APP_ROWS_EXPORT) {
270
+ const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
271
+ if (named !== undefined) {
272
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the appRows of ${named[0]} give each table's row as an object of columns`)] }
273
+ }
274
+ }
203
275
  read.set(name, value.value)
204
276
  }
205
277
  return {
@@ -210,12 +282,26 @@ export function readEndpointFixtures(
210
282
  members: fields.get(MEMBERS_EXPORT) ?? {},
211
283
  invitations: fields.get(INVITATIONS_EXPORT) ?? {},
212
284
  links: fields.get(LINKS_EXPORT) ?? {},
285
+ refusals: fields.get(REFUSALS_EXPORT) ?? {},
213
286
  rows: Object.fromEntries(
214
287
  Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
215
288
  id,
216
289
  Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
217
290
  ]),
218
291
  ),
292
+ appRows: Object.fromEntries(
293
+ Object.entries(read.get(APP_ROWS_EXPORT) ?? {}).map(([id, tables]) => [
294
+ id,
295
+ Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
296
+ ]),
297
+ ),
298
+ pins: stringsById(read.get(PINS_EXPORT) ?? {}),
299
+ files: Object.fromEntries(
300
+ Object.entries(read.get(FILES_EXPORT) ?? {}).map(([id, named]) => [
301
+ id,
302
+ Object.fromEntries(Object.entries(named).flatMap(([field, path]) => (typeof path === 'string' ? [[field, path]] : []))),
303
+ ]),
304
+ ),
219
305
  },
220
306
  }
221
307
  }
package/src/finding.ts CHANGED
@@ -40,16 +40,20 @@ export const REFUSAL_RULE_IDS = [
40
40
  'layer-import',
41
41
  'generated-test-import',
42
42
  'shared-import',
43
+ 'cloudflare-sql',
44
+ 'cloudflare-scan',
45
+ 'cloudflare-current-timestamp',
43
46
  ] as const
44
47
 
45
48
  /** Rules that report a step out of the application architecture. */
46
49
  export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
47
50
 
48
51
  /**
49
- * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, and a
50
- * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization.
52
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
53
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
54
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
55
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
56
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
57
 
54
58
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
59
 
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { type ApplicationTree, checkApplication, type CheckInput, readApplicationTree } from './check'
2
+ export { type ApplicationDialect, applicationDialect } from './dialect'
2
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding'
3
- export { CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
4
+ export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
4
5
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
5
6
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
6
7
  export {
package/src/layout.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  /** Where an application keeps what the checker reads. Paths are relative to the application root. */
2
2
  export const CONTRACT_FILE = 'fabrika.contract.ts'
3
+ /** The provider-authored application config, whose `defineApp` names the provider. */
4
+ export const CONFIG_FILE = 'fabrika.config.ts'
3
5
  /** The named export of the contract module that holds `defineContract(…)`. */
4
6
  export const CONTRACT_EXPORT = 'contract'
5
7
  export const TABLES_FILE = 'src/db/tables.ts'
6
8
  /** The named export of the tables module that holds `defineTables(…)(…)`. */
7
9
  export const TABLES_EXPORT = 'tables'
8
10
  export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
11
+ /** Where a Cloudflare deploy stages the SPA mounts' built files (`@fabrika/provider-cloudflare`): build output, never source. */
12
+ export const STAGED_ASSETS_DIR = 'fabrika/assets/'
9
13
  export const MIGRATIONS_DIR = 'db/migrations/'
10
14
  /** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
11
15
  export const POLICY_TESTS_DIR = 'src/db/__tests__/'
@@ -40,6 +44,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
40
44
  /** Build output, installed packages and tool state are not application source and are never read. */
41
45
  export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
42
46
 
47
+ /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
48
+ export const isSkippedPath = (path: string): boolean => path.split('/').some(isIgnoredSegment) || path.startsWith(STAGED_ASSETS_DIR)
49
+
43
50
  export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
44
51
 
45
52
  export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
@@ -53,7 +60,7 @@ export const isJsonFile = (path: string): boolean => path.endsWith('.json')
53
60
  export const isCheckedFile = (path: string): boolean => {
54
61
  // The registry configuration and the lockfile decide what a trusted package name installs.
55
62
  if (path === '.npmrc' || path === 'bun.lock') return true
56
- if (path.split('/').some(isIgnoredSegment)) return false
63
+ if (isSkippedPath(path)) return false
57
64
  return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
58
65
  || path === 'bunfig.toml'
59
66
  }
@@ -18,6 +18,7 @@ import {
18
18
  type ExportAccessDeclaration,
19
19
  type FileKind,
20
20
  type ImportDeclaration,
21
+ isPath,
21
22
  type KitImportDeclaration,
22
23
  kitImportsSection,
23
24
  kitUnknownOptions,
@@ -31,6 +32,7 @@ import {
31
32
  type SpaAccessDeclaration,
32
33
  type Surface,
33
34
  SURFACE_SECTIONS,
35
+ type TerminalDeclaration,
34
36
  type TokenPurpose,
35
37
  type TokenPurposes,
36
38
  unknownOptions,
@@ -213,6 +215,7 @@ class SurfaceReader {
213
215
  'mail',
214
216
  'members',
215
217
  'directory',
218
+ 'terminal',
216
219
  ])
217
220
  const locale = fields.get('locale')
218
221
  const displayName = fields.get('displayName')
@@ -220,6 +223,7 @@ class SurfaceReader {
220
223
  const members = fields.get('members')
221
224
  const memberFields = members === undefined ? undefined : strictFields(members, 'the vocabulary members', ['manage', 'list'], [])
222
225
  const directory = fields.get('directory')
226
+ const terminal = fields.get('terminal')
223
227
  return {
224
228
  app: text(fields.get('app'), value, 'app'),
225
229
  ...(locale === undefined ? {} : { locale: localeOf(locale, value) }),
@@ -229,6 +233,7 @@ class SurfaceReader {
229
233
  ? {}
230
234
  : { members: { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') } }),
231
235
  ...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
236
+ ...(terminal === undefined ? {} : { terminal: terminalOf(terminal) }),
232
237
  dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
233
238
  actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
234
239
  roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
@@ -794,7 +799,7 @@ function plain(value: LiteralValue | undefined): unknown {
794
799
  }
795
800
 
796
801
  const DECLARED_ALLOWED =
797
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>']"
802
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>'] | 'public' (a cron job)"
798
803
 
799
804
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
800
805
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -936,6 +941,16 @@ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
936
941
  return directory
937
942
  }
938
943
 
944
+ /** The vocabulary's `terminal: { identify: '/path' }`; `buildArtifact` checks the path itself. */
945
+ function terminalOf(value: LiteralValue): TerminalDeclaration {
946
+ const identify = strictFields(value, 'the vocabulary terminal', ['identify'], []).get('identify')
947
+ const path = text(identify, value, 'terminal.identify')
948
+ if (!isPath(path)) {
949
+ throw new Refused(identify?.at ?? value.at, `terminal.identify is '${path}'`, "terminal: { identify: '/identify' }")
950
+ }
951
+ return { identify: path }
952
+ }
953
+
939
954
  function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
940
955
  return value === undefined ? undefined : text(value, value, field)
941
956
  }
package/src/resolution.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isBuiltin } from 'node:module'
2
2
  import { z } from 'zod/v4'
3
3
  import { parseJsonc } from './jsonc'
4
- import { isIgnoredSegment, isRelativeSpecifier, joinRelative, resolveRelative } from './layout'
4
+ import { isRelativeSpecifier, isSkippedPath, joinRelative, resolveRelative } from './layout'
5
5
 
6
6
  /** Pattern → targets. A target is a bare specifier, an absolute path, or `./<path from the root>` (`../…` above it). */
7
7
  type MappingTable = ReadonlyMap<string, readonly string[]>
@@ -139,7 +139,7 @@ export const readImportMappings = (files: ReadonlyMap<string, string>): ImportMa
139
139
  },
140
140
  mayExist: (target) => {
141
141
  const path = target.startsWith('/') ? undefined : joinRelative('package.json', target)
142
- if (path === undefined || path.split('/').some(isIgnoredSegment)) return true
142
+ if (path === undefined || isSkippedPath(path)) return true
143
143
  return resolveRelative((candidate) => files.has(candidate), 'package.json', `./${path}`).kind !== 'missing'
144
144
  },
145
145
  }
@@ -0,0 +1,58 @@
1
+ import { type ContractArtifact, type DeclaredEgress, PUBLIC_EGRESS } from '@fabrika/auth-core'
2
+ import type { Finding } from '../finding'
3
+ import { CONTRACT_FILE } from '../layout'
4
+
5
+ const at = (rule: 'cloudflare-sql' | 'cloudflare-scan', message: string, allowed: string): Finding => ({
6
+ file: CONTRACT_FILE,
7
+ line: 1,
8
+ column: 1,
9
+ severity: 'refusal',
10
+ rule,
11
+ message,
12
+ allowed,
13
+ })
14
+
15
+ /** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
16
+ const outsideCalls = (reach: { readonly egress?: DeclaredEgress; readonly connect: readonly string[] }): string[] => [
17
+ ...(reach.egress === PUBLIC_EGRESS ? [`egress '${PUBLIC_EGRESS}'`] : (reach.egress ?? []).map((origin) => `egress ${origin}`)),
18
+ ...reach.connect.map((name) => `connect ${name}`),
19
+ ]
20
+
21
+ /**
22
+ * What an application on Cloudflare cannot declare (ADR-0065): raw SQL, because a Durable Object's SQLite has no role
23
+ * under it and the classifier reads Postgres's lexical rules; a file kind that scans, because no scanner runs there.
24
+ * And a hint for a mutation that declares an outside call: the object runs one transaction at a time, and the mutation
25
+ * holds it while the call waits (backlog 216 item 7).
26
+ */
27
+ export const checkCloudflareContract = (artifact: ContractArtifact): Finding[] => [
28
+ ...Object.entries(artifact.declared ?? {}).filter(([, reach]) => reach.sql !== null).map(([site]) =>
29
+ at(
30
+ 'cloudflare-sql',
31
+ `${site} declares sql, which an application on Cloudflare cannot run: its SQLite database has no role to bound raw SQL`,
32
+ 'ctx.db and its stores, without sql in the site options',
33
+ )
34
+ ),
35
+ ...Object.entries(artifact.fileKinds ?? {}).filter(([, kind]) => kind.scan === true).map(([name]) =>
36
+ at(
37
+ 'cloudflare-scan',
38
+ `the file kind ${name} scans its files (scan: true), which an application on Cloudflare cannot: no scanner runs there`,
39
+ `c.files({ types, maxBytes }) without scan for ${name}, and no public procedure that takes its files`,
40
+ )
41
+ ),
42
+ ...artifact.endpoints.filter((endpoint) => endpoint.kind === 'mutation').flatMap((endpoint): Finding[] => {
43
+ const reach = artifact.declared?.[endpoint.id]
44
+ const calls = reach === undefined ? [] : outsideCalls(reach)
45
+ if (calls.length === 0) return []
46
+ return [{
47
+ file: CONTRACT_FILE,
48
+ line: 1,
49
+ column: 1,
50
+ severity: 'hint',
51
+ rule: 'cloudflare-held-call',
52
+ message: `${endpoint.id} is a mutation that declares ${
53
+ calls.join(', ')
54
+ }: on Cloudflare it waits for that call inside the object's transaction, which holds the whole environment`,
55
+ allowed: "record a row and ctx.kick('<job>'); the job declares the call and makes it outside ctx.transaction",
56
+ }]
57
+ }),
58
+ ]