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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.9.0-dev.11",
3
+ "version": "0.9.0-dev.12",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,16 +42,16 @@
42
42
  }
43
43
  },
44
44
  "scripts": {
45
- "typecheck": "tsc --noEmit",
45
+ "typecheck": "tsrs --build tsconfig.test.json",
46
46
  "test": "bun test"
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-dev.11",
51
- "@fabrika/auth-core": "0.9.0-dev.11",
52
- "@fabrika/db": "0.9.0-dev.11",
53
- "@fabrika/operations-contract": "0.9.0-dev.11",
54
- "@fabrika/platform-node": "0.9.0-dev.11",
50
+ "@fabrika/app": "0.9.0-dev.12",
51
+ "@fabrika/auth-core": "0.9.0-dev.12",
52
+ "@fabrika/db": "0.9.0-dev.12",
53
+ "@fabrika/operations-contract": "0.9.0-dev.12",
54
+ "@fabrika/platform-node": "0.9.0-dev.12",
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 { ContractArtifact } from '@fabrika/auth-core'
2
+ import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry } 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'
@@ -95,8 +95,8 @@ export const readApplicationTree = async (root: string): Promise<ApplicationTree
95
95
 
96
96
  /** The findings a module rule leaves until the contract is read: they depend on what it declares. */
97
97
  interface ContractDependent {
98
- /** Each `fetch` of an absolute URL, with its static prefix. */
99
- readonly fetches: { readonly target: string; readonly finding: Finding }[]
98
+ /** Each `fetch` of an absolute URL, with its static prefix and its labelled authority (`absoluteFetch`). */
99
+ readonly fetches: { readonly target: string; readonly labelled: string | undefined; readonly finding: Finding }[]
100
100
  /** Each `ctx.url` with a literal endpoint id. */
101
101
  readonly urls: { readonly endpoint: string; readonly finding: Finding }[]
102
102
  /** Each insert with literal `onConflict.columns`, checked against the migrations' unique indexes. */
@@ -146,9 +146,9 @@ const checkSourceModule = async (
146
146
  isGeneratedEntry,
147
147
  rawSql: rawSqlBindings(module.program),
148
148
  isServerModule: isServerModule(module.file),
149
- absoluteFetch: (node: AstNode, target: string) => {
149
+ absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => {
150
150
  const { message, allowed } = crossAppFetchMessage(target)
151
- for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, finding })
151
+ for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, labelled, finding })
152
152
  },
153
153
  appUrl: (node: AstNode, endpoint: string) => {
154
154
  const message = `ctx.url names '${endpoint}', which is no procedure of the contract`
@@ -189,7 +189,7 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
189
189
  /** What the module rules that wait for the contract compare against: its procedure ids and every declared origin. */
190
190
  interface CompiledReach {
191
191
  readonly procedures: ReadonlySet<string>
192
- readonly origins: readonly string[]
192
+ readonly egress: readonly EgressEntry[]
193
193
  }
194
194
 
195
195
  /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
@@ -209,24 +209,44 @@ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
209
209
  )
210
210
  return {
211
211
  procedures: new Set(procedures.map((row) => row.id)),
212
- origins: Object.values(artifact.declared ?? {}).flatMap((reach) => reach.egress ?? []),
212
+ egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
213
+ (reach.egress ?? []).flatMap((value) => {
214
+ const parsed = parseEgressEntry(value)
215
+ return parsed.ok ? [parsed.entry] : []
216
+ })
217
+ ),
213
218
  }
214
219
  }
215
220
 
216
221
  /**
217
222
  * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
218
- * not accepted), and every one stands when the contract does not compile. A `ctx.url` stands when the contract
219
- * compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
223
+ * not accepted, nor an interpolated label a pattern does not cover), and every one stands when the contract does not
224
+ * compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime guard on `fetch`
225
+ * still checks the site that runs.
220
226
  */
221
227
  const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
222
- ...dependent.fetches.filter(({ target }) => reach === null || !reach.origins.some((origin) => isWithinOrigin(target, origin))).map(({ finding }) =>
223
- finding
224
- ),
228
+ ...dependent.fetches.filter((fetch) => reach === null || !isDeclaredFetch(fetch, reach.egress)).map(({ finding }) => finding),
225
229
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
226
230
  ]
227
231
 
228
- const isWithinOrigin = (target: string, origin: string): boolean =>
229
- target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
232
+ /** The static prefix names its whole authority, which an entry admits, or the labelled authority is a pattern's own. */
233
+ const isDeclaredFetch = (fetch: { readonly target: string; readonly labelled: string | undefined }, egress: readonly EgressEntry[]): boolean => {
234
+ const authority = /^https:\/\/[^/?#]+[/?#]/.exec(fetch.target)?.[0]
235
+ const url = authority === undefined ? null : urlOf(authority)
236
+ if (url !== null && egressAdmits(egress, url)) return true
237
+ // The interpolated label as a placeholder one, so the authority normalizes as the runtime's URL will; exact
238
+ // origins stay out, as no literal label is known.
239
+ const labelled = fetch.labelled === undefined ? null : urlOf(`https://${fetch.labelled.replace('*', 'label')}/`)
240
+ return labelled !== null && egressAdmits(egress.filter((entry) => entry.kind === 'pattern'), labelled)
241
+ }
242
+
243
+ const urlOf = (value: string): URL | null => {
244
+ try {
245
+ return new URL(value)
246
+ } catch {
247
+ return null
248
+ }
249
+ }
230
250
 
231
251
  /** Runs every rule over one application and returns the findings in file, line and column order. */
232
252
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
@@ -597,7 +597,7 @@ class SurfaceReader {
597
597
  // ── Sections ────────────────────────────────────────────────────────────────────────────────
598
598
 
599
599
  /**
600
- * `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes` and `scan` is unknown, as the kit
600
+ * `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes`, `scan` and `inline` is unknown, as the kit
601
601
  * records it, so `buildArtifact` refuses a file collection's `owner` in its own words.
602
602
  */
603
603
  #files(value: LiteralValue, form: Form): FileKind {
@@ -606,11 +606,13 @@ class SurfaceReader {
606
606
  const [kind] = args(at, 'c.files', 1, 1)
607
607
  const options = builderOptions(kind, at, 'c.files')
608
608
  const scan = options.get('scan')
609
+ const inline = options.get('inline')
609
610
  return {
610
611
  kind: 'file-kind',
611
612
  types: texts(options.get('types'), at, 'types'),
612
613
  maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
613
614
  scan: scan === undefined ? undefined : boolean(scan, 'scan'),
615
+ inline: inline === undefined ? undefined : boolean(inline, 'inline'),
614
616
  unknownOptions: optionKeys(options, 'fileKind'),
615
617
  }
616
618
  }
@@ -799,7 +801,7 @@ function plain(value: LiteralValue | undefined): unknown {
799
801
  }
800
802
 
801
803
  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>']"
804
+ "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>' | 'https://*.<domain>']"
803
805
 
804
806
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
805
807
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -28,8 +28,11 @@ export interface SourceContext {
28
28
  readonly rawSql: ReadonlySet<string>
29
29
  /** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
30
30
  readonly isServerModule: boolean
31
- /** A `fetch` of an absolute URL: refused once the contract shows that no site declares its origin in `egress`. */
32
- readonly absoluteFetch: (node: AstNode, target: string) => void
31
+ /**
32
+ * A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
33
+ * authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
34
+ */
35
+ readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void
33
36
  /** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
34
37
  readonly appUrl: (node: AstNode, endpoint: string) => void
35
38
  /** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
@@ -130,10 +133,28 @@ const staticPrefix = (node: AstNode | undefined): string | undefined => {
130
133
  const ABSOLUTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
131
134
  const LOCAL_SCHEMES = /^(?:data|blob):/i
132
135
 
136
+ /**
137
+ * The authority of `https://${label}.<domain>…` with the interpolated label as `*` (`*.<domain>[:port]`), when the
138
+ * template's static text after it reaches the path, query or fragment; the runtime guard checks the label itself.
139
+ */
140
+ const labelledAuthority = (node: AstNode | undefined): string | undefined => {
141
+ if (node === undefined) return undefined
142
+ if (node.type === 'NewExpression' && ['URL', 'Request'].includes(identifierName(child(node, 'callee')) ?? '')) {
143
+ return labelledAuthority(argumentAt(node, 0))
144
+ }
145
+ if (node.type !== 'TemplateLiteral') return undefined
146
+ const [head, next] = children(node, 'quasis')
147
+ if (!head || !next || templateText(head).cooked !== 'https://') return undefined
148
+ const rest = templateText(next).cooked ?? ''
149
+ const end = rest.search(/[/?#]/)
150
+ return rest.startsWith('.') && end > 1 ? `*${rest.slice(0, end)}` : undefined
151
+ }
152
+
133
153
  const checkFetch = (node: AstNode, path: readonly string[], context: SourceContext): void => {
134
- const target = staticPrefix(invokedArgument(node, path, 'fetch'))
154
+ const argument = invokedArgument(node, path, 'fetch')
155
+ const target = staticPrefix(argument)
135
156
  if (target === undefined || !ABSOLUTE_URL.test(target) || LOCAL_SCHEMES.test(target)) return
136
- context.absoluteFetch(node, target)
157
+ context.absoluteFetch(node, target, labelledAuthority(argument))
137
158
  }
138
159
 
139
160
  /** `ctx.url('<endpoint id>', …)`, also on a `ctx` reached through a member (`args.ctx.url`). */
@@ -177,7 +198,8 @@ const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
177
198
  /** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
178
199
  export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
179
200
  message: `fetch to the absolute origin '${target}' is a hand-written integration`,
180
- allowed: "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>'] on the site",
201
+ allowed:
202
+ "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>' | 'https://*.<domain>'] on the site",
181
203
  })
182
204
 
183
205
  const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
package/src/scaffold.ts CHANGED
@@ -251,7 +251,8 @@ const policyTestBody = (
251
251
  dialect: ApplicationDialect,
252
252
  ): { readonly body: string; readonly cases: readonly string[] } | undefined => {
253
253
  const policy = policies[table]
254
- if (policy === undefined) return undefined
254
+ // A view's rows come from the tables it reads, so no probe seeds one; its parent's cases still run.
255
+ if (policy === undefined || policy.view === true) return undefined
255
256
  const app = policy.scope.mode === 'app'
256
257
  const dimension = grantDimension(policies, policy)
257
258
  if (dimension === undefined && !app) return undefined
@@ -889,6 +890,13 @@ export const missingEndpointFixtures = ({ tables, policies, artifact, fixtures }
889
890
  for (const [field, table] of Object.entries(fields).sort(byKey)) {
890
891
  if (row.input?.type !== 'object' || !admitsString(row.input.fields[field])) {
891
892
  findings.push(at(`${id}: ${field} is no string field of its input, so it cannot name a row`, 'a top-level string field of the input'))
893
+ } else if (policies[table]?.view === true) {
894
+ findings.push(
895
+ at(
896
+ `${id}: ${field} names the view ${table}, whose rows the kit cannot seed: they come from the tables it reads`,
897
+ 'a row field that names a table the view reads',
898
+ ),
899
+ )
892
900
  } else if (!rowPlace(policies, scope, table)) {
893
901
  findings.push(at(...unplacedRow(policies, id, table, scope)))
894
902
  }
@@ -8,8 +8,11 @@ export interface SourceContext {
8
8
  readonly rawSql: ReadonlySet<string>;
9
9
  /** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
10
10
  readonly isServerModule: boolean;
11
- /** A `fetch` of an absolute URL: refused once the contract shows that no site declares its origin in `egress`. */
12
- readonly absoluteFetch: (node: AstNode, target: string) => void;
11
+ /**
12
+ * A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
13
+ * authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
14
+ */
15
+ readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void;
13
16
  /** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
14
17
  readonly appUrl: (node: AstNode, endpoint: string) => void;
15
18
  /** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */