@fabrika/check 0.9.0-cloudflare.1 → 0.9.0-cloudflare.3
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 +6 -6
- package/src/check.ts +28 -6
- package/src/endpoint-fixtures.ts +76 -10
- package/src/finding.ts +2 -1
- package/src/layout.ts +6 -1
- package/src/reader/surface.ts +1 -1
- package/src/reader/value.ts +1 -1
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +16 -15
- package/src/rules/migrations.ts +32 -0
- package/src/rules/modules.ts +8 -2
- package/src/rules/runtime.ts +7 -3
- package/src/rules/tests.ts +1 -1
- package/src/scaffold.ts +139 -12
- package/types/src/endpoint-fixtures.d.ts +15 -0
- package/types/src/finding.d.ts +2 -2
- package/types/src/layout.d.ts +4 -0
- package/types/src/rules/cloudflare.d.ts +5 -5
- package/types/src/rules/migrations.d.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/check",
|
|
3
|
-
"version": "0.9.0-cloudflare.
|
|
3
|
+
"version": "0.9.0-cloudflare.3",
|
|
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-cloudflare.
|
|
51
|
-
"@fabrika/auth-core": "0.9.0-cloudflare.
|
|
52
|
-
"@fabrika/db": "0.9.0-cloudflare.
|
|
53
|
-
"@fabrika/operations-contract": "0.9.0-cloudflare.
|
|
54
|
-
"@fabrika/platform-node": "0.9.0-cloudflare.
|
|
50
|
+
"@fabrika/app": "0.9.0-cloudflare.3",
|
|
51
|
+
"@fabrika/auth-core": "0.9.0-cloudflare.3",
|
|
52
|
+
"@fabrika/db": "0.9.0-cloudflare.3",
|
|
53
|
+
"@fabrika/operations-contract": "0.9.0-cloudflare.3",
|
|
54
|
+
"@fabrika/platform-node": "0.9.0-cloudflare.3",
|
|
55
55
|
"zod": "^3.25.76"
|
|
56
56
|
}
|
|
57
57
|
}
|
package/src/check.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
|
|
2
|
-
import type
|
|
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'
|
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
checkCurrentTimestampDefaults,
|
|
39
39
|
checkFileColumnMigrations,
|
|
40
40
|
checkMigrationNames,
|
|
41
|
+
checkSqliteFrameworkNames,
|
|
41
42
|
type ConflictInsert,
|
|
42
43
|
type FileColumn,
|
|
43
44
|
} from './rules/migrations'
|
|
@@ -164,6 +165,8 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
|
|
|
164
165
|
interface CompiledReach {
|
|
165
166
|
readonly procedures: ReadonlySet<string>
|
|
166
167
|
readonly origins: readonly string[]
|
|
168
|
+
/** Some cron job declares `egress: 'public'`. */
|
|
169
|
+
readonly publicEgress: boolean
|
|
167
170
|
}
|
|
168
171
|
|
|
169
172
|
/** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
|
|
@@ -183,25 +186,43 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
|
|
|
183
186
|
)
|
|
184
187
|
return {
|
|
185
188
|
procedures: new Set(procedures.map((row) => row.id)),
|
|
186
|
-
origins: Object.values(artifact.declared ?? {}).flatMap((
|
|
189
|
+
origins: Object.values(artifact.declared ?? {}).flatMap((
|
|
190
|
+
reach,
|
|
191
|
+
) => (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress)),
|
|
192
|
+
publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
|
|
187
193
|
}
|
|
188
194
|
}
|
|
189
195
|
|
|
190
196
|
/**
|
|
191
197
|
* A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
|
|
192
|
-
* not accepted)
|
|
198
|
+
* not accepted) and, where a cron job declares `egress: 'public'`, when public egress would refuse it: another scheme,
|
|
199
|
+
* or a host its URL alone refuses (an IP address, a local or internal name, a port). A prefix that ends inside the host
|
|
200
|
+
* is then the runtime's to judge. Every one stands when the contract does not compile. A `ctx.url` stands when the contract
|
|
193
201
|
* compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
|
|
194
202
|
*/
|
|
195
203
|
const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
|
|
196
|
-
...dependent.fetches.filter(({ target }) =>
|
|
197
|
-
|
|
198
|
-
),
|
|
204
|
+
...dependent.fetches.filter(({ target }) =>
|
|
205
|
+
reach === null || (!reach.origins.some((origin) => isWithinOrigin(target, origin)) && !(reach.publicEgress && isPublicTarget(target)))
|
|
206
|
+
).map(({ finding }) => finding),
|
|
199
207
|
...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
|
|
200
208
|
]
|
|
201
209
|
|
|
202
210
|
const isWithinOrigin = (target: string, origin: string): boolean =>
|
|
203
211
|
target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
|
|
204
212
|
|
|
213
|
+
/** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
|
|
214
|
+
const isPublicTarget = (target: string): boolean => {
|
|
215
|
+
const scheme = /^(https?):\/\//i.exec(target)
|
|
216
|
+
if (scheme === null) return false
|
|
217
|
+
const rest = target.slice(scheme[0].length)
|
|
218
|
+
if (!/[/?#]/.test(rest)) return true
|
|
219
|
+
try {
|
|
220
|
+
return publicEgressRefusal(new URL(target)) === null
|
|
221
|
+
} catch {
|
|
222
|
+
return false
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
205
226
|
/** Runs every rule over one application and returns the findings in file, line and column order. */
|
|
206
227
|
export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
|
|
207
228
|
const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
|
|
@@ -271,6 +292,7 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
271
292
|
if (applicationDialect(tree.files) === 'sqlite') {
|
|
272
293
|
if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
|
|
273
294
|
findings.push(...checkCurrentTimestampDefaults(tree.files))
|
|
295
|
+
findings.push(...checkSqliteFrameworkNames(tree.files))
|
|
274
296
|
}
|
|
275
297
|
if (declaredTables !== null) {
|
|
276
298
|
const policies = tablePolicies(declaredTables)
|
package/src/endpoint-fixtures.ts
CHANGED
|
@@ -6,11 +6,17 @@
|
|
|
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
7
|
// table, which the kit seeds in each scope's object; `appRows` the rows of application tables an endpoint's own case
|
|
8
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
|
|
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.
|
|
10
14
|
// Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
|
|
11
15
|
// `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
|
|
12
16
|
// ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
|
|
13
|
-
// `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`,
|
|
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.
|
|
14
20
|
// Browser-safe.
|
|
15
21
|
|
|
16
22
|
import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
|
|
@@ -26,14 +32,17 @@ export const INVITATIONS_EXPORT = 'invitations'
|
|
|
26
32
|
export const LINKS_EXPORT = 'links'
|
|
27
33
|
export const ROWS_EXPORT = 'rows'
|
|
28
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'
|
|
29
38
|
|
|
30
|
-
/** The exports that list
|
|
31
|
-
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
|
|
32
41
|
type FieldExport = (typeof FIELD_EXPORTS)[number]
|
|
33
42
|
const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
|
|
34
43
|
|
|
35
44
|
const ALLOWED =
|
|
36
|
-
"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' } }
|
|
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"
|
|
37
46
|
|
|
38
47
|
type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
|
|
39
48
|
|
|
@@ -52,9 +61,33 @@ export interface EndpointFixtures {
|
|
|
52
61
|
readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
|
|
53
62
|
/** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
|
|
54
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>>>>
|
|
55
70
|
}
|
|
56
71
|
|
|
57
|
-
export const NO_FIXTURES: EndpointFixtures = {
|
|
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)
|
|
58
91
|
|
|
59
92
|
const finding = (at: AstNode | undefined, message: string): Finding => {
|
|
60
93
|
const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
|
|
@@ -132,7 +165,7 @@ function byId(
|
|
|
132
165
|
return { ok: true, value: entries }
|
|
133
166
|
}
|
|
134
167
|
|
|
135
|
-
/** `export const <members, invitations or
|
|
168
|
+
/** `export const <members, invitations, links or refusals> = { '<endpoint id>': ['<field>', …] }`, read into lists. */
|
|
136
169
|
function fieldsById(
|
|
137
170
|
declarator: AstNode,
|
|
138
171
|
name: FieldExport,
|
|
@@ -149,13 +182,23 @@ function fieldsById(
|
|
|
149
182
|
const entries: Record<string, readonly string[]> = {}
|
|
150
183
|
for (const [id, fields] of Object.entries(value.value)) {
|
|
151
184
|
if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
|
|
152
|
-
|
|
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}`)] }
|
|
153
187
|
}
|
|
154
188
|
entries[id] = fields.filter((field) => typeof field === 'string')
|
|
155
189
|
}
|
|
156
190
|
return { ok: true, value: entries }
|
|
157
191
|
}
|
|
158
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
|
+
|
|
159
202
|
/** The fixtures of `files`, by endpoint id; none without the file. */
|
|
160
203
|
export function readEndpointFixtures(
|
|
161
204
|
files: ReadonlyMap<string, string>,
|
|
@@ -180,7 +223,8 @@ export function readEndpointFixtures(
|
|
|
180
223
|
const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
|
|
181
224
|
if (
|
|
182
225
|
statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
|
|
183
|
-
|| (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT &&
|
|
226
|
+
|| (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && name !== FILES_EXPORT
|
|
227
|
+
&& name !== PINS_EXPORT && !isFieldExport(name))
|
|
184
228
|
|| read.has(name)
|
|
185
229
|
|| (isFieldExport(name) && fields.has(name))
|
|
186
230
|
) {
|
|
@@ -189,7 +233,7 @@ export function readEndpointFixtures(
|
|
|
189
233
|
findings: [
|
|
190
234
|
finding(
|
|
191
235
|
statement ?? undefined,
|
|
192
|
-
`the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT} and ${
|
|
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`,
|
|
193
237
|
),
|
|
194
238
|
],
|
|
195
239
|
}
|
|
@@ -208,6 +252,20 @@ export function readEndpointFixtures(
|
|
|
208
252
|
return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
|
|
209
253
|
}
|
|
210
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
|
+
}
|
|
211
269
|
if (name === APP_ROWS_EXPORT) {
|
|
212
270
|
const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
|
|
213
271
|
if (named !== undefined) {
|
|
@@ -224,6 +282,7 @@ export function readEndpointFixtures(
|
|
|
224
282
|
members: fields.get(MEMBERS_EXPORT) ?? {},
|
|
225
283
|
invitations: fields.get(INVITATIONS_EXPORT) ?? {},
|
|
226
284
|
links: fields.get(LINKS_EXPORT) ?? {},
|
|
285
|
+
refusals: fields.get(REFUSALS_EXPORT) ?? {},
|
|
227
286
|
rows: Object.fromEntries(
|
|
228
287
|
Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
|
|
229
288
|
id,
|
|
@@ -236,6 +295,13 @@ export function readEndpointFixtures(
|
|
|
236
295
|
Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
|
|
237
296
|
]),
|
|
238
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
|
+
),
|
|
239
305
|
},
|
|
240
306
|
}
|
|
241
307
|
}
|
package/src/finding.ts
CHANGED
|
@@ -40,9 +40,10 @@ export const REFUSAL_RULE_IDS = [
|
|
|
40
40
|
'layer-import',
|
|
41
41
|
'generated-test-import',
|
|
42
42
|
'shared-import',
|
|
43
|
-
'cloudflare-sql',
|
|
44
43
|
'cloudflare-scan',
|
|
44
|
+
'cloudflare-job-segment',
|
|
45
45
|
'cloudflare-current-timestamp',
|
|
46
|
+
'cloudflare-framework-name',
|
|
46
47
|
] as const
|
|
47
48
|
|
|
48
49
|
/** Rules that report a step out of the application architecture. */
|
package/src/layout.ts
CHANGED
|
@@ -8,6 +8,8 @@ export const TABLES_FILE = 'src/db/tables.ts'
|
|
|
8
8
|
/** The named export of the tables module that holds `defineTables(…)(…)`. */
|
|
9
9
|
export const TABLES_EXPORT = 'tables'
|
|
10
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/'
|
|
11
13
|
export const MIGRATIONS_DIR = 'db/migrations/'
|
|
12
14
|
/** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
|
|
13
15
|
export const POLICY_TESTS_DIR = 'src/db/__tests__/'
|
|
@@ -42,6 +44,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
|
|
|
42
44
|
/** Build output, installed packages and tool state are not application source and are never read. */
|
|
43
45
|
export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
|
|
44
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
|
+
|
|
45
50
|
export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
|
|
46
51
|
|
|
47
52
|
export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
|
|
@@ -55,7 +60,7 @@ export const isJsonFile = (path: string): boolean => path.endsWith('.json')
|
|
|
55
60
|
export const isCheckedFile = (path: string): boolean => {
|
|
56
61
|
// The registry configuration and the lockfile decide what a trusted package name installs.
|
|
57
62
|
if (path === '.npmrc' || path === 'bun.lock') return true
|
|
58
|
-
if (path
|
|
63
|
+
if (isSkippedPath(path)) return false
|
|
59
64
|
return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
|
|
60
65
|
|| path === 'bunfig.toml'
|
|
61
66
|
}
|
package/src/reader/surface.ts
CHANGED
|
@@ -799,7 +799,7 @@ function plain(value: LiteralValue | undefined): unknown {
|
|
|
799
799
|
}
|
|
800
800
|
|
|
801
801
|
const DECLARED_ALLOWED =
|
|
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>']"
|
|
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)"
|
|
803
803
|
|
|
804
804
|
/** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
|
|
805
805
|
const asSurface = (builder: BuilderValue): LiteralValue => ({
|
package/src/reader/value.ts
CHANGED
|
@@ -83,7 +83,7 @@ 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'] as const
|
|
86
|
+
const VOCABULARY_SECTIONS = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail', 'members', 'directory', 'terminal'] as const
|
|
87
87
|
|
|
88
88
|
const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
|
|
89
89
|
|
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 {
|
|
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
|
|
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
|
}
|
package/src/rules/cloudflare.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
|
|
2
|
+
import { type ContractArtifact, type DeclaredEgress, PUBLIC_EGRESS } from '@fabrika/auth-core'
|
|
2
3
|
import type { Finding } from '../finding'
|
|
3
4
|
import { CONTRACT_FILE } from '../layout'
|
|
4
5
|
|
|
5
|
-
const at = (rule: 'cloudflare-
|
|
6
|
+
const at = (rule: 'cloudflare-scan' | 'cloudflare-job-segment', message: string, allowed: string): Finding => ({
|
|
6
7
|
file: CONTRACT_FILE,
|
|
7
8
|
line: 1,
|
|
8
9
|
column: 1,
|
|
@@ -13,25 +14,18 @@ const at = (rule: 'cloudflare-sql' | 'cloudflare-scan', message: string, allowed
|
|
|
13
14
|
})
|
|
14
15
|
|
|
15
16
|
/** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
|
|
16
|
-
const outsideCalls = (reach: { readonly egress?:
|
|
17
|
-
...(reach.egress ?? []).map((origin) => `egress ${origin}`),
|
|
17
|
+
const outsideCalls = (reach: { readonly egress?: DeclaredEgress; readonly connect: readonly string[] }): string[] => [
|
|
18
|
+
...(reach.egress === PUBLIC_EGRESS ? [`egress '${PUBLIC_EGRESS}'`] : (reach.egress ?? []).map((origin) => `egress ${origin}`)),
|
|
18
19
|
...reach.connect.map((name) => `connect ${name}`),
|
|
19
20
|
]
|
|
20
21
|
|
|
21
22
|
/**
|
|
22
|
-
* What an application on Cloudflare cannot declare (ADR-0065):
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
23
|
+
* What an application on Cloudflare cannot declare (ADR-0065): a file kind that scans, because no scanner runs there; a
|
|
24
|
+
* job longer than one segment, because the object runs it inside an alarm or a request. And a hint for a mutation that
|
|
25
|
+
* declares an outside call: the object runs one transaction at a time, and the mutation holds it while the call waits
|
|
26
|
+
* (backlog 216 item 7).
|
|
26
27
|
*/
|
|
27
28
|
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
29
|
...Object.entries(artifact.fileKinds ?? {}).filter(([, kind]) => kind.scan === true).map(([name]) =>
|
|
36
30
|
at(
|
|
37
31
|
'cloudflare-scan',
|
|
@@ -39,6 +33,13 @@ export const checkCloudflareContract = (artifact: ContractArtifact): Finding[] =
|
|
|
39
33
|
`c.files({ types, maxBytes }) without scan for ${name}, and no public procedure that takes its files`,
|
|
40
34
|
)
|
|
41
35
|
),
|
|
36
|
+
...Object.entries(artifact.jobs).filter(([, job]) => job.timeoutMs > CLOUDFLARE_MAX_JOB_SEGMENT_MS).map(([name, job]) =>
|
|
37
|
+
at(
|
|
38
|
+
'cloudflare-job-segment',
|
|
39
|
+
`the job ${name} runs up to ${job.timeoutMs} ms, and a job segment on Cloudflare runs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} ms`,
|
|
40
|
+
`limits.timeoutMs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} for ${name}: claim a bounded batch per run, and the next run takes the rest; a Workflow for one longer run is planned (backlog 230)`,
|
|
41
|
+
)
|
|
42
|
+
),
|
|
42
43
|
...artifact.endpoints.filter((endpoint) => endpoint.kind === 'mutation').flatMap((endpoint): Finding[] => {
|
|
43
44
|
const reach = artifact.declared?.[endpoint.id]
|
|
44
45
|
const calls = reach === undefined ? [] : outsideCalls(reach)
|
package/src/rules/migrations.ts
CHANGED
|
@@ -2,11 +2,13 @@ import {
|
|
|
2
2
|
afterName,
|
|
3
3
|
closingParenthesis,
|
|
4
4
|
isPunct,
|
|
5
|
+
lexSqlite,
|
|
5
6
|
nameText,
|
|
6
7
|
objectNameAt,
|
|
7
8
|
skipWords,
|
|
8
9
|
splitAtCommas,
|
|
9
10
|
type SqlToken,
|
|
11
|
+
statementsOf,
|
|
10
12
|
topLevelStatements,
|
|
11
13
|
upperWord,
|
|
12
14
|
} from '@fabrika/platform-node/sql'
|
|
@@ -74,6 +76,36 @@ export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>
|
|
|
74
76
|
return findings
|
|
75
77
|
}
|
|
76
78
|
|
|
79
|
+
/**
|
|
80
|
+
* On SQLite an application migration runs verbatim, with no name rule, so a view or a trigger over a framework table
|
|
81
|
+
* would reach what `ctx.sql`'s name rule keeps it from. Every `fabrika_*` name is refused (any case, quoted, bracketed,
|
|
82
|
+
* or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
|
|
83
|
+
*/
|
|
84
|
+
export const checkSqliteFrameworkNames = (files: ReadonlyMap<string, string>): Finding[] => {
|
|
85
|
+
const findings: Finding[] = []
|
|
86
|
+
for (const [path, sql] of files) {
|
|
87
|
+
if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
|
|
88
|
+
for (const { tokens } of statementsOf(lexSqlite(sql).tokens)) {
|
|
89
|
+
tokens.forEach((token, index) => {
|
|
90
|
+
const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
|
|
91
|
+
const name = text?.toLowerCase()
|
|
92
|
+
if (name === undefined || !name.startsWith('fabrika_')) return
|
|
93
|
+
if (name === FILES_TABLE && token.kind !== 'string' && upperWord(tokens[index - 1]) === 'REFERENCES') return
|
|
94
|
+
findings.push({
|
|
95
|
+
file: path,
|
|
96
|
+
line: token.line,
|
|
97
|
+
column: 1,
|
|
98
|
+
severity: 'refusal',
|
|
99
|
+
rule: 'cloudflare-framework-name',
|
|
100
|
+
message: `'${text}' is the framework's: a migration on Cloudflare names no fabrika_* table, which ctx.sql could then reach through it`,
|
|
101
|
+
allowed: `the application's own tables, and REFERENCES ${FILES_TABLE} (id) for a file column`,
|
|
102
|
+
})
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return findings
|
|
107
|
+
}
|
|
108
|
+
|
|
77
109
|
/** A declared file column: `table.column` holds files of `kind`. */
|
|
78
110
|
export interface FileColumn {
|
|
79
111
|
readonly table: string
|
package/src/rules/modules.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Report } from '../finding'
|
|
2
|
-
import {
|
|
2
|
+
import { isRelativeSpecifier, isSkippedPath, isTestFile, joinRelative, resolveRelative } from '../layout'
|
|
3
3
|
import type { ModuleReference } from '../references'
|
|
4
4
|
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
5
5
|
|
|
@@ -15,6 +15,11 @@ const NETWORK: Forbidden = {
|
|
|
15
15
|
what: 'a raw network module',
|
|
16
16
|
allowed: 'endpoints declared in the contract; another application through a connector import',
|
|
17
17
|
}
|
|
18
|
+
/** `Bun.fetch`: Bun's own `fetch`, which the egress guard on the global one does not wrap. */
|
|
19
|
+
const BUN_FETCH: Forbidden = {
|
|
20
|
+
what: "Bun's own fetch, past the egress guard",
|
|
21
|
+
allowed: "the global fetch, under the site's egress: ['<origin>'] or a cron job's egress: 'public'",
|
|
22
|
+
}
|
|
18
23
|
const PROCESSES: Forbidden = { what: 'a process-spawning module', allowed: 'a job declared in the contract (c.cron)' }
|
|
19
24
|
|
|
20
25
|
const FORBIDDEN_PACKAGES: ReadonlyMap<string, Forbidden> = new Map([
|
|
@@ -78,6 +83,7 @@ export const FORBIDDEN_BUN_MEMBERS: ReadonlyMap<string, Forbidden> = new Map([
|
|
|
78
83
|
...['sql', 'SQL'].map((name): [string, Forbidden] => [name, DATABASE]),
|
|
79
84
|
...['S3Client', 's3'].map((name): [string, Forbidden] => [name, STORAGE]),
|
|
80
85
|
...['serve', 'connect', 'listen', 'udpSocket'].map((name): [string, Forbidden] => [name, NETWORK]),
|
|
86
|
+
['fetch', BUN_FETCH],
|
|
81
87
|
...['spawn', 'spawnSync', '$'].map((name): [string, Forbidden] => [name, PROCESSES]),
|
|
82
88
|
])
|
|
83
89
|
|
|
@@ -114,7 +120,7 @@ const checkTestOnly = (reference: ModuleReference, target: string, report: Repor
|
|
|
114
120
|
/** A path from the root that a mapping or an import lands on, judged by where the checker reads. */
|
|
115
121
|
const containmentProblem = (target: string | undefined): string | undefined => {
|
|
116
122
|
if (target === undefined) return 'resolves outside the application root, where the checker does not look'
|
|
117
|
-
if (target
|
|
123
|
+
if (isSkippedPath(target)) return 'resolves into a directory the checker skips'
|
|
118
124
|
return undefined
|
|
119
125
|
}
|
|
120
126
|
|
package/src/rules/runtime.ts
CHANGED
|
@@ -36,8 +36,11 @@ export interface SourceContext {
|
|
|
36
36
|
readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/**
|
|
40
|
+
* The global objects, `Bun`, and `WebSocket`, a socket the egress guard on `fetch` does not see: a server module reaches
|
|
41
|
+
* the platform and the outside through the framework only.
|
|
42
|
+
*/
|
|
43
|
+
const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun', 'WebSocket'])
|
|
41
44
|
|
|
42
45
|
/**
|
|
43
46
|
* The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
|
|
@@ -177,7 +180,8 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
|
|
|
177
180
|
/** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
|
|
178
181
|
export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
|
|
179
182
|
message: `fetch to the absolute origin '${target}' is a hand-written integration`,
|
|
180
|
-
allowed:
|
|
183
|
+
allowed:
|
|
184
|
+
"a same-origin path to a declared endpoint, another application through a connector import, egress: ['<origin>'] on the site, or a public host of http(s) under a cron job's egress: 'public'",
|
|
181
185
|
})
|
|
182
186
|
|
|
183
187
|
const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
package/src/rules/tests.ts
CHANGED
|
@@ -33,7 +33,7 @@ const isAssertionCall = (node: AstNode): boolean => {
|
|
|
33
33
|
const path = memberPath(callee)
|
|
34
34
|
const [root] = path ?? []
|
|
35
35
|
const last = path?.[path.length - 1]
|
|
36
|
-
return root !== undefined && root !== 'expect' && (
|
|
36
|
+
return root !== undefined && root !== 'expect' && (root.startsWith('assert') || (last !== undefined && ASSERTION_NAME.test(last)))
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
/** Whether a test body runs an assertion; a nested function counts only where it is called or passed to a call. */
|
package/src/scaffold.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// one file per application, from the contract: they run the application's own `serve(…)` and handlers. The checker
|
|
4
4
|
// regenerates both to find a missing, edited, stale or orphaned file. Browser-safe: no file API.
|
|
5
5
|
|
|
6
|
-
import { GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
|
|
6
|
+
import { GENERATED_FILE_PREFIX, GENERATED_INVITATION, GENERATED_LINK, GENERATED_MEMBER, GENERATED_ROW_PREFIX } from '@fabrika/app/contract'
|
|
7
7
|
import {
|
|
8
8
|
type ContractArtifact,
|
|
9
9
|
endpointDirectory,
|
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
import { type ApplicationRowRefusal, applicationRowRefusalText, applicationRowsPlan, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
17
17
|
import { ContractSourceError, readContractSource, readTablesDefinition } from './contract'
|
|
18
18
|
import { type ApplicationDialect, applicationDialect } from './dialect'
|
|
19
|
-
import { type EndpointFixtures, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
|
|
19
|
+
import { type EndpointFixtures, isFixtureFilePath, isSampleObject, NO_FIXTURES, readEndpointFixtures } from './endpoint-fixtures'
|
|
20
20
|
import type { Finding } from './finding'
|
|
21
21
|
import { CONTRACT_FILE, ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR } from './layout'
|
|
22
22
|
|
|
@@ -295,7 +295,9 @@ const isLinkProcedure = (row: EndpointRow): boolean =>
|
|
|
295
295
|
* The input an endpoint's cases send: the author's fixture, else a sample of its schema; `undefined` when neither
|
|
296
296
|
* exists. Each field its `members`, `invitations` or `links` name holds `GENERATED_MEMBER`, `GENERATED_INVITATION` or
|
|
297
297
|
* `GENERATED_LINK`, which the kit replaces with a real member, an open invitation or a link it issued; each field its
|
|
298
|
-
* `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded
|
|
298
|
+
* `rows` name holds `GENERATED_ROW_PREFIX` and the table, which the kit replaces with the key of a row it seeded; each file
|
|
299
|
+
* field its `files` name holds its kind's marker (in a list, for a list of files), even where the sample left an optional
|
|
300
|
+
* one out, which the kit sends as the named file.
|
|
299
301
|
*/
|
|
300
302
|
const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<string, Sample>> | undefined => {
|
|
301
303
|
const fixture = fixtures.inputs[row.id]
|
|
@@ -309,10 +311,83 @@ const inputOf = (row: EndpointRow, fixtures: EndpointFixtures): Readonly<Record<
|
|
|
309
311
|
...generated(fixtures.invitations[row.id], GENERATED_INVITATION),
|
|
310
312
|
...generated(fixtures.links[row.id], GENERATED_LINK),
|
|
311
313
|
...Object.entries(fixtures.rows[row.id] ?? {}).map(([field, table]) => [field, `${GENERATED_ROW_PREFIX}${table}`]),
|
|
314
|
+
...Object.keys(fixtures.files[row.id] ?? {}).flatMap((field) => {
|
|
315
|
+
const file = fileFieldOf(row.input, field)
|
|
316
|
+
if (file === undefined) return []
|
|
317
|
+
const marker = `${GENERATED_FILE_PREFIX}${file.kind}`
|
|
318
|
+
return [[field, file.list ? [marker] : marker]]
|
|
319
|
+
}),
|
|
312
320
|
]),
|
|
313
321
|
}
|
|
314
322
|
}
|
|
315
323
|
|
|
324
|
+
/** The file kind of a top-level file field of `input` (a file, an optional or nullable one, or a list of them), or `undefined`. */
|
|
325
|
+
const fileFieldOf = (input: SchemaShape | null, field: string): { readonly kind: string; readonly list: boolean } | undefined => {
|
|
326
|
+
const kindOf = (shape: SchemaShape | undefined): string | undefined =>
|
|
327
|
+
shape?.type === 'file' ? shape.kind : shape?.type === 'optional' || shape?.type === 'nullable' ? kindOf(shape.inner) : undefined
|
|
328
|
+
const shape = input?.type === 'object' ? input.fields[field] : undefined
|
|
329
|
+
const unwrapped = shape?.type === 'optional' || shape?.type === 'nullable' ? shape.inner : shape
|
|
330
|
+
if (unwrapped?.type === 'array') {
|
|
331
|
+
const kind = kindOf(unwrapped.items)
|
|
332
|
+
return kind === undefined ? undefined : { kind, list: true }
|
|
333
|
+
}
|
|
334
|
+
const kind = kindOf(shape)
|
|
335
|
+
return kind === undefined ? undefined : { kind, list: false }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The ids of the endpoints with endpoint access cases. */
|
|
339
|
+
const testedEndpoints = (artifact: ContractArtifact): ReadonlySet<string> =>
|
|
340
|
+
new Set(artifact.endpoints.filter((row) => isAccessTested(row) || isLinkProcedure(row)).map((row) => row.id))
|
|
341
|
+
|
|
342
|
+
/** How a generated endpoint access test reaches the application's root, where a file fixture's path starts. */
|
|
343
|
+
const ROOT_FROM_ENDPOINT_TEST = '../'.repeat(ENDPOINT_ACCESS_TEST.split('/').length - 1)
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* The options of the generated test's kit: the file fixtures of the tested endpoints, each a URL beside the test. Empty
|
|
347
|
+
* without any, so a test without file fixtures stays as it was.
|
|
348
|
+
*/
|
|
349
|
+
const kitOptions = (fixtures: EndpointFixtures, tested: ReadonlySet<string>): string => {
|
|
350
|
+
const files = Object.entries(fixtures.files).sort(byKey).flatMap(([id, fields]) => {
|
|
351
|
+
const valid = Object.entries(fields).sort(byKey).filter(([, path]) => isFixtureFilePath(path))
|
|
352
|
+
if (!tested.has(id) || valid.length === 0) return []
|
|
353
|
+
const rendered = valid.map(([field, path]) => `${renderKey(field)}: new URL(${quote(`${ROOT_FROM_ENDPOINT_TEST}${path}`)}, import.meta.url)`)
|
|
354
|
+
return [`${quote(id)}: { ${rendered.join(', ')} }`]
|
|
355
|
+
})
|
|
356
|
+
const refusals = Object.entries(fixtures.refusals).sort(byKey).flatMap(([id, types]) => {
|
|
357
|
+
const valid = types.filter(isDeclarableRefusal)
|
|
358
|
+
return tested.has(id) && valid.length > 0 ? [`${quote(id)}: [${valid.map(quote).join(', ')}]`] : []
|
|
359
|
+
})
|
|
360
|
+
const pins = Object.entries(fixtures.pins).sort(byKey).flatMap(([id, columns]) => {
|
|
361
|
+
const entries = Object.entries(columns).sort(byKey)
|
|
362
|
+
return tested.has(id) && entries.length > 0
|
|
363
|
+
? [`${quote(id)}: { ${entries.map(([column, value]) => `${renderKey(column)}: ${quote(value)}`).join(', ')} }`]
|
|
364
|
+
: []
|
|
365
|
+
})
|
|
366
|
+
const options = [
|
|
367
|
+
...(files.length === 0 ? [] : [`files: { ${files.join(', ')} }`]),
|
|
368
|
+
...(refusals.length === 0 ? [] : [`refusals: { ${refusals.join(', ')} }`]),
|
|
369
|
+
...(pins.length === 0 ? [] : [`pins: { ${pins.join(', ')} }`]),
|
|
370
|
+
]
|
|
371
|
+
return options.length === 0 ? '' : `, { ${options.join(', ')} }`
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** A refusal the fixtures may declare: a handler's own error type, never the input schema's (`validation`). */
|
|
375
|
+
const isDeclarableRefusal = (type: string): boolean => type !== '' && type !== 'validation'
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The own case of an endpoint: 200, or, where its fixtures declare the refusals its handler may answer its own object
|
|
379
|
+
* with, also the 400 the kit hands back only for one of them.
|
|
380
|
+
*/
|
|
381
|
+
const ownCase = (row: EndpointRow, fixtures: EndpointFixtures, name: string, args: string): Case => {
|
|
382
|
+
const declared = (fixtures.refusals[row.id] ?? []).filter(isDeclarableRefusal)
|
|
383
|
+
return declared.length === 0
|
|
384
|
+
? ownScopeCase(name, `expect(await kit.own(${args})).toEqual({ status: 200 })`)
|
|
385
|
+
: ownScopeCase(`${name} (200, or a refusal its fixtures declare)`, `expect([200, 400]).toContain((await kit.own(${args})).status)`)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** An object key as `renderSample` writes one: bare when it is an identifier, else quoted. */
|
|
389
|
+
const renderKey = (key: string): string => (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : quote(key))
|
|
390
|
+
|
|
316
391
|
/** Whether the endpoint's handler gets `ctx.links`: on or in a dimension a link mount's `issuedBy` names its action for. */
|
|
317
392
|
const issuesLinks = (artifact: ContractArtifact, row: EndpointRow): boolean => {
|
|
318
393
|
if (row.requirement?.kind !== 'action') return false
|
|
@@ -426,12 +501,7 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
|
|
|
426
501
|
}
|
|
427
502
|
if (linked) {
|
|
428
503
|
if (own) {
|
|
429
|
-
cases.push(
|
|
430
|
-
ownScopeCase(
|
|
431
|
-
`${row.id}: the holder of a link to a ${access.dimension} reaches it`,
|
|
432
|
-
`expect(await kit.own(${seededArgs})).toEqual({ status: 200 })`,
|
|
433
|
-
),
|
|
434
|
-
)
|
|
504
|
+
cases.push(ownCase(row, fixtures, `${row.id}: the holder of a link to a ${access.dimension} reaches it`, seededArgs))
|
|
435
505
|
}
|
|
436
506
|
return cases
|
|
437
507
|
}
|
|
@@ -440,9 +510,11 @@ const endpointCases = (row: EndpointRow, artifact: ContractArtifact, policies: P
|
|
|
440
510
|
if (!unscoped) cases.push(...leaked())
|
|
441
511
|
if (own) {
|
|
442
512
|
cases.push(
|
|
443
|
-
|
|
513
|
+
ownCase(
|
|
514
|
+
row,
|
|
515
|
+
fixtures,
|
|
444
516
|
`${row.id}: a caller with only ${ownGrants(row, artifact, action, access.dimension)} reaches its own ${access.dimension}`,
|
|
445
|
-
|
|
517
|
+
seededArgs,
|
|
446
518
|
),
|
|
447
519
|
)
|
|
448
520
|
}
|
|
@@ -531,7 +603,7 @@ const endpointTestBody = (
|
|
|
531
603
|
'',
|
|
532
604
|
`if (${database.name} !== null) {`,
|
|
533
605
|
`\tafterAll(() => ${database.name}.close())`,
|
|
534
|
-
`\tconst kit = endpointAccessKit(app, tables, ${database.name})`,
|
|
606
|
+
`\tconst kit = endpointAccessKit(app, tables, ${database.name}${kitOptions(fixtures, testedEndpoints(artifact))})`,
|
|
535
607
|
'',
|
|
536
608
|
describeBlock('endpoints: a caller of one scope reaches nothing of another', cases),
|
|
537
609
|
'}',
|
|
@@ -737,8 +809,63 @@ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }
|
|
|
737
809
|
findings.push(at(`${id}: ${applicationRowRefusalText(refusal)}`, appRowAllowed(refusal)))
|
|
738
810
|
}
|
|
739
811
|
}
|
|
812
|
+
for (const [id, fields] of Object.entries(fixtures.files).sort(byKey)) {
|
|
813
|
+
const row = tested.find((candidate) => candidate.id === id)
|
|
814
|
+
if (row === undefined) {
|
|
815
|
+
findings.push(
|
|
816
|
+
at(
|
|
817
|
+
`${id} is no tested endpoint, whose cases could send a file`,
|
|
818
|
+
"export const files = { '<endpoint id>': { <file field>: '<path from the application root>' } }, for a tested endpoint with a file input",
|
|
819
|
+
),
|
|
820
|
+
)
|
|
821
|
+
continue
|
|
822
|
+
}
|
|
823
|
+
for (const [field, path] of Object.entries(fields).sort(byKey)) {
|
|
824
|
+
if (fileFieldOf(row.input, field) === undefined) {
|
|
825
|
+
findings.push(at(`${id}: ${field} is no file field of its input, so no case sends a file there`, 'a top-level file field of the input'))
|
|
826
|
+
} else if (!isFixtureFilePath(path)) {
|
|
827
|
+
findings.push(
|
|
828
|
+
at(
|
|
829
|
+
`${id}: the file of ${field}, '${path}', is no path inside the application`,
|
|
830
|
+
"a path from the application's root, '/'-separated, without '..', a leading '/' or '.', or characters other than letters, digits, '_', '-' and '.'",
|
|
831
|
+
),
|
|
832
|
+
)
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
for (const [id, types] of Object.entries(fixtures.refusals).sort(byKey)) {
|
|
837
|
+
if (!tested.some((row) => row.id === id)) {
|
|
838
|
+
findings.push(
|
|
839
|
+
at(
|
|
840
|
+
`${id} is no tested endpoint, whose handler a case runs`,
|
|
841
|
+
"export const refusals = { '<endpoint id>': ['<error type>'] }, for a tested endpoint",
|
|
842
|
+
),
|
|
843
|
+
)
|
|
844
|
+
continue
|
|
845
|
+
}
|
|
846
|
+
for (const type of types) {
|
|
847
|
+
if (!isDeclarableRefusal(type)) {
|
|
848
|
+
findings.push(
|
|
849
|
+
at(
|
|
850
|
+
`${id}: '${type}' is no refusal of its handler; an input the schema refuses (validation) is the fixture's mistake`,
|
|
851
|
+
"the error type of a 400 the handler throws (new HttpError(400, '<type>', …))",
|
|
852
|
+
),
|
|
853
|
+
)
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
740
857
|
const seeded = (row: EndpointRow): boolean =>
|
|
741
858
|
row.requirement?.kind === 'action' && (row.requirement.access.form === 'on' || row.requirement.access.form === 'in')
|
|
859
|
+
for (const id of Object.keys(fixtures.pins).sort()) {
|
|
860
|
+
if (!tested.some((row) => row.id === id && (seeded(row) || isLinkProcedure(row)))) {
|
|
861
|
+
findings.push(
|
|
862
|
+
at(
|
|
863
|
+
`${id} is no endpoint with an on or in access form, whose row a pin sets`,
|
|
864
|
+
"export const pins = { '<endpoint id>': { <text column>: '<value>' } }",
|
|
865
|
+
),
|
|
866
|
+
)
|
|
867
|
+
}
|
|
868
|
+
}
|
|
742
869
|
for (const id of Object.keys(fixtures.seeds).sort()) {
|
|
743
870
|
if (!tested.some((row) => row.id === id && seeded(row))) {
|
|
744
871
|
findings.push(
|
|
@@ -7,6 +7,9 @@ export declare const INVITATIONS_EXPORT = "invitations";
|
|
|
7
7
|
export declare const LINKS_EXPORT = "links";
|
|
8
8
|
export declare const ROWS_EXPORT = "rows";
|
|
9
9
|
export declare const APP_ROWS_EXPORT = "appRows";
|
|
10
|
+
export declare const FILES_EXPORT = "files";
|
|
11
|
+
export declare const REFUSALS_EXPORT = "refusals";
|
|
12
|
+
export declare const PINS_EXPORT = "pins";
|
|
10
13
|
type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>;
|
|
11
14
|
export interface EndpointFixtures {
|
|
12
15
|
/** The input each endpoint's cases send, by endpoint id. */
|
|
@@ -23,8 +26,20 @@ export interface EndpointFixtures {
|
|
|
23
26
|
readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
24
27
|
/** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
|
|
25
28
|
readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>;
|
|
29
|
+
/** The file each case sends in a file field, a path relative to the application's root, by input field, by endpoint id. */
|
|
30
|
+
readonly files: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
31
|
+
/** The error types of the 400s an endpoint's handler may answer its own object with, by endpoint id. */
|
|
32
|
+
readonly refusals: Readonly<Record<string, readonly string[]>>;
|
|
33
|
+
/** The own scope's value of each pinned text column of the row the endpoint addresses, by endpoint id. */
|
|
34
|
+
readonly pins: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
26
35
|
}
|
|
27
36
|
export declare const NO_FIXTURES: EndpointFixtures;
|
|
37
|
+
/**
|
|
38
|
+
* Whether `path` may name a file fixture: relative to the application's root, `/`-separated, and each segment of
|
|
39
|
+
* letters, digits, `_`, `-` and `.` that starts with neither `.` nor `-`, so it never leaves the root, names no dotfile and
|
|
40
|
+
* reads the same as a URL path.
|
|
41
|
+
*/
|
|
42
|
+
export declare const isFixtureFilePath: (path: string) => boolean;
|
|
28
43
|
export declare function isSampleObject(value: Sample): value is {
|
|
29
44
|
readonly [key: string]: Sample;
|
|
30
45
|
};
|
package/types/src/finding.d.ts
CHANGED
|
@@ -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", "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", "cloudflare-
|
|
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", "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", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
|
|
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", "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", "cloudflare-
|
|
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", "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", "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"];
|
|
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];
|
package/types/src/layout.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export declare const TABLES_FILE = "src/db/tables.ts";
|
|
|
8
8
|
/** The named export of the tables module that holds `defineTables(…)(…)`. */
|
|
9
9
|
export declare const TABLES_EXPORT = "tables";
|
|
10
10
|
export declare 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 declare const STAGED_ASSETS_DIR = "fabrika/assets/";
|
|
11
13
|
export declare const MIGRATIONS_DIR = "db/migrations/";
|
|
12
14
|
/** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
|
|
13
15
|
export declare const POLICY_TESTS_DIR = "src/db/__tests__/";
|
|
@@ -36,6 +38,8 @@ export declare const SPA_DIR = "web/";
|
|
|
36
38
|
export declare const SERVER_DIR = "src/";
|
|
37
39
|
/** Build output, installed packages and tool state are not application source and are never read. */
|
|
38
40
|
export declare const isIgnoredSegment: (segment: string) => boolean;
|
|
41
|
+
/** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
|
|
42
|
+
export declare const isSkippedPath: (path: string) => boolean;
|
|
39
43
|
export declare const isSourceFile: (path: string) => boolean;
|
|
40
44
|
export declare const isTestFile: (path: string) => boolean;
|
|
41
45
|
/** A module that runs in the application's server process: under `src/`, not a test. */
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ContractArtifact } from '@fabrika/auth-core';
|
|
2
2
|
import type { Finding } from '../finding';
|
|
3
3
|
/**
|
|
4
|
-
* What an application on Cloudflare cannot declare (ADR-0065):
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* What an application on Cloudflare cannot declare (ADR-0065): a file kind that scans, because no scanner runs there; a
|
|
5
|
+
* job longer than one segment, because the object runs it inside an alarm or a request. And a hint for a mutation that
|
|
6
|
+
* declares an outside call: the object runs one transaction at a time, and the mutation holds it while the call waits
|
|
7
|
+
* (backlog 216 item 7).
|
|
8
8
|
*/
|
|
9
9
|
export declare const checkCloudflareContract: (artifact: ContractArtifact) => Finding[];
|
|
@@ -6,6 +6,12 @@ export declare const checkMigrationNames: (paths: readonly string[]) => Finding[
|
|
|
6
6
|
* `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
|
|
7
7
|
*/
|
|
8
8
|
export declare const checkCurrentTimestampDefaults: (files: ReadonlyMap<string, string>) => Finding[];
|
|
9
|
+
/**
|
|
10
|
+
* On SQLite an application migration runs verbatim, with no name rule, so a view or a trigger over a framework table
|
|
11
|
+
* would reach what `ctx.sql`'s name rule keeps it from. Every `fabrika_*` name is refused (any case, quoted, bracketed,
|
|
12
|
+
* or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
|
|
13
|
+
*/
|
|
14
|
+
export declare const checkSqliteFrameworkNames: (files: ReadonlyMap<string, string>) => Finding[];
|
|
9
15
|
/** A declared file column: `table.column` holds files of `kind`. */
|
|
10
16
|
export interface FileColumn {
|
|
11
17
|
readonly table: string;
|