@fabrika/check 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,507 @@
1
+ import {
2
+ type AstNode,
3
+ child,
4
+ children,
5
+ identifierName,
6
+ isValueReference,
7
+ memberPath,
8
+ memberSuffix,
9
+ staticKey,
10
+ staticString,
11
+ stringField,
12
+ templateText,
13
+ unwrap,
14
+ walk,
15
+ } from '../ast'
16
+ import type { Report } from '../finding'
17
+ import { unwrapValue } from '../graph'
18
+ import { isRequire } from '../references'
19
+ import { declaringScope } from '../scope'
20
+ import { FORBIDDEN_BUN_MEMBERS } from './modules'
21
+ import { handledProcedure } from './structure'
22
+
23
+ export interface SourceContext {
24
+ readonly report: Report
25
+ /** The generated entrypoint is the one module that reads the framework's variables. */
26
+ readonly isGeneratedEntry: boolean
27
+ /** The names the module binds to an imported `sql` (`rawSqlBindings`): a parameter of that name is not one of them. */
28
+ readonly rawSql: ReadonlySet<string>
29
+ /** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
30
+ readonly isServerModule: boolean
31
+ }
32
+
33
+ /** The global objects and `Bun`: a server module reaches the platform through the framework only. */
34
+ const SERVER_REFUSED_GLOBALS = new Set(['globalThis', 'global', 'self', 'window', 'Bun'])
35
+
36
+ /**
37
+ * The local names a module binds to a value named `sql` it loads: `import { sql as q } from 'kysely'` and
38
+ * `const { sql } = await import('bun')`. The raw-sql rule refuses a driver's tag by this origin, so a query function
39
+ * may take the declared `ctx.sql` tag as a parameter of any name.
40
+ */
41
+ export const rawSqlBindings = (program: AstNode): ReadonlySet<string> => {
42
+ const names = new Set<string>()
43
+ walk(program, (node) => {
44
+ if (node.type === 'ImportDeclaration' && stringField(node, 'importKind') !== 'type') {
45
+ for (const item of children(node, 'specifiers')) {
46
+ const imported = item === null ? undefined : child(item, 'imported')
47
+ const local = item === null || stringField(item, 'importKind') === 'type' ? undefined : identifierName(child(item, 'local'))
48
+ if (local !== undefined && (identifierName(imported) ?? staticString(imported)) === 'sql') names.add(local)
49
+ }
50
+ } else if (node.type === 'VariableDeclarator' && isLoad(child(node, 'init'))) {
51
+ const pattern = child(node, 'id')
52
+ for (const property of pattern?.type === 'ObjectPattern' ? children(pattern, 'properties') : []) {
53
+ const local = property?.type === 'Property' && staticKey(property, 'key') === 'sql' ? identifierName(child(property, 'value')) : undefined
54
+ if (local !== undefined) names.add(local)
55
+ }
56
+ }
57
+ })
58
+ return names
59
+ }
60
+
61
+ /** `import(x)`, `await import(x)` or `require(x)`. */
62
+ const isLoad = (init: AstNode | undefined): boolean => {
63
+ const value = init === undefined ? undefined : unwrap(init)
64
+ const load = value?.type === 'AwaitExpression' ? child(value, 'argument') : value
65
+ return load !== undefined && loadedSpecifier(load) !== undefined
66
+ }
67
+
68
+ const GLOBAL_OBJECTS = new Set(['globalThis', 'window', 'self'])
69
+ /** Kysely's raw helpers (`sql.raw`, `sql.lit`, …) and Bun's `sql.unsafe`. */
70
+ const RAW_SQL_HELPERS = new Set(['raw', 'lit', 'ref', 'id', 'table', 'val', 'join', 'unsafe'])
71
+ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
72
+ const ALLOWED_QUERY = 'a query through the scoped data layer of @fabrika/db'
73
+ const ALLOWED_MARKUP = 'text content, or elements rendered by React'
74
+ const ALLOWED_CODE = 'a function written in the source'
75
+
76
+ /** `globalThis.Bun.serve` and `Bun.serve` name the same global. */
77
+ const globalPath = (node: AstNode): readonly string[] | undefined => {
78
+ const path = memberPath(node)
79
+ if (path === undefined) return undefined
80
+ let start = 0
81
+ while (start < path.length - 1 && GLOBAL_OBJECTS.has(path[start] ?? '')) start++
82
+ return path.slice(start)
83
+ }
84
+
85
+ const pathIs = (path: readonly string[] | undefined, ...expected: string[]): boolean =>
86
+ path !== undefined && path.length === expected.length && expected.every((segment, index) => path[index] === segment)
87
+
88
+ const argumentAt = (node: AstNode, position: number): AstNode | undefined => {
89
+ const argument = children(node, 'arguments')[position]
90
+ return argument === null || argument === undefined ? undefined : unwrap(argument)
91
+ }
92
+
93
+ /** The argument a direct call receives, also through `f.call(this, x)` and `f.apply(this, [x])`. */
94
+ const invokedArgument = (node: AstNode, path: readonly string[], name: string): AstNode | undefined => {
95
+ if (pathIs(path, name)) return argumentAt(node, 0)
96
+ if (pathIs(path, name, 'call')) return argumentAt(node, 1)
97
+ const list = pathIs(path, name, 'apply') ? argumentAt(node, 1) : undefined
98
+ const first = list?.type === 'ArrayExpression' ? children(list, 'elements')[0] : undefined
99
+ return first === null || first === undefined ? undefined : unwrap(first)
100
+ }
101
+
102
+ /** The text a string expression starts with, as far as it is static: literals, templates and `+` concatenation. */
103
+ const staticPrefix = (node: AstNode | undefined): string | undefined => {
104
+ if (node === undefined) return undefined
105
+ const whole = staticString(node)
106
+ if (whole !== undefined) return whole
107
+ if (node.type === 'TemplateLiteral') {
108
+ const head = children(node, 'quasis')[0]
109
+ return head ? templateText(head).cooked : undefined
110
+ }
111
+ if (node.type === 'BinaryExpression' && node['operator'] === '+') {
112
+ const left = child(node, 'left')
113
+ const leftText = left === undefined ? undefined : staticString(unwrap(left))
114
+ const right = child(node, 'right')
115
+ if (leftText !== undefined) return leftText + (staticPrefix(right === undefined ? undefined : unwrap(right)) ?? '')
116
+ return staticPrefix(left === undefined ? undefined : unwrap(left))
117
+ }
118
+ if (node.type === 'NewExpression' && ['URL', 'Request'].includes(identifierName(child(node, 'callee')) ?? '')) {
119
+ return staticPrefix(argumentAt(node, 0))
120
+ }
121
+ return undefined
122
+ }
123
+
124
+ const ABSOLUTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
125
+ const LOCAL_SCHEMES = /^(?:data|blob):/i
126
+
127
+ const checkFetch = (node: AstNode, path: readonly string[], context: SourceContext): void => {
128
+ const target = staticPrefix(invokedArgument(node, path, 'fetch'))
129
+ if (target === undefined || !ABSOLUTE_URL.test(target) || LOCAL_SCHEMES.test(target)) return
130
+ context.report(
131
+ node,
132
+ 'cross-app-fetch',
133
+ `fetch to the absolute origin '${target}' is a hand-written integration`,
134
+ 'a same-origin path to a declared endpoint, or another application through a connector import',
135
+ )
136
+ }
137
+
138
+ const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
139
+ const isConstructor = pathIs(path, 'Function') || pathIs(path, 'Function', 'call') || pathIs(path, 'Function', 'apply')
140
+ if (isConstructor && (node.type === 'CallExpression' || node.type === 'NewExpression')) {
141
+ context.report(node, 'dynamic-code', 'the Function constructor compiles a string into code', ALLOWED_CODE)
142
+ return
143
+ }
144
+ if (node.type !== 'CallExpression' || !(pathIs(path, 'setTimeout') || pathIs(path, 'setInterval'))) return
145
+ const callback = argumentAt(node, 0)
146
+ if (callback !== undefined && callback.type !== 'NewExpression' && staticPrefix(callback) !== undefined) {
147
+ context.report(node, 'dynamic-code', `${path[0]} with a string evaluates it as code`, 'a function callback')
148
+ }
149
+ }
150
+
151
+ const SENSITIVE_NAMES = new Set(['err', 'error', 'e', 'ex', 'exception', 'cause', 'req', 'request', 'headers', 'env'])
152
+ const SENSITIVE_MEMBERS = new Set(['error', 'cause', 'request', 'headers', 'env'])
153
+ const SENSITIVE_CONSTRUCTORS = /^(?:\w*Error|Request|Headers)$/
154
+
155
+ const catchParameters = (ancestors: readonly AstNode[]): ReadonlySet<string> => {
156
+ const names = new Set<string>()
157
+ for (const ancestor of ancestors) {
158
+ const name = ancestor.type === 'CatchClause' ? identifierName(child(ancestor, 'param')) : undefined
159
+ if (name !== undefined) names.add(name)
160
+ }
161
+ return names
162
+ }
163
+
164
+ /** The parts of an expression whose value is logged as is: a conditional's branches, a template's substitutions, … */
165
+ const loggedParts = (value: AstNode): readonly AstNode[] => {
166
+ const parts = (key: string) => children(value, key).filter((item): item is AstNode => item !== null)
167
+ const single = (key: string) => {
168
+ const inner = child(value, key)
169
+ return inner === undefined ? [] : [inner]
170
+ }
171
+ switch (value.type) {
172
+ case 'ObjectExpression':
173
+ return parts('properties').flatMap((property) => {
174
+ const inner = child(property, property.type === 'SpreadElement' ? 'argument' : 'value')
175
+ return inner === undefined ? [] : [inner]
176
+ })
177
+ case 'ArrayExpression':
178
+ return parts('elements')
179
+ case 'CallExpression':
180
+ case 'NewExpression':
181
+ return parts('arguments')
182
+ case 'TemplateLiteral':
183
+ return parts('expressions')
184
+ case 'ConditionalExpression':
185
+ return [...single('consequent'), ...single('alternate')]
186
+ case 'LogicalExpression':
187
+ return [...single('left'), ...single('right')]
188
+ case 'SpreadElement':
189
+ case 'AwaitExpression':
190
+ return single('argument')
191
+ default:
192
+ return []
193
+ }
194
+ }
195
+
196
+ /** The first part of a logged value that is an error object, a request, headers or the environment. */
197
+ const sensitiveArgument = (node: AstNode, caught: ReadonlySet<string>): AstNode | undefined => {
198
+ const value = unwrap(node)
199
+ const name = identifierName(value)
200
+ if (name !== undefined) return SENSITIVE_NAMES.has(name) || caught.has(name) ? value : undefined
201
+ if (value.type === 'MemberExpression') {
202
+ const property = staticKey(value, 'property')
203
+ return property !== undefined && SENSITIVE_MEMBERS.has(property) ? value : undefined
204
+ }
205
+ if (value.type === 'NewExpression' && SENSITIVE_CONSTRUCTORS.test(identifierName(child(value, 'callee')) ?? '')) return value
206
+ for (const part of loggedParts(value)) {
207
+ const found = sensitiveArgument(part, caught)
208
+ if (found !== undefined) return found
209
+ }
210
+ return undefined
211
+ }
212
+
213
+ const checkConsole = (node: AstNode, path: readonly string[], ancestors: readonly AstNode[], context: SourceContext): void => {
214
+ if (path.length !== 2 || path[0] !== 'console') return
215
+ const caught = catchParameters(ancestors)
216
+ for (const argument of children(node, 'arguments')) {
217
+ const found = argument === null ? undefined : sensitiveArgument(argument, caught)
218
+ if (found === undefined) continue
219
+ context.report(
220
+ found,
221
+ 'sensitive-log',
222
+ `console.${path[1]} of an error object, request, headers or environment can carry a secret`,
223
+ 'a short message, or a chosen field such as error.message',
224
+ )
225
+ return
226
+ }
227
+ }
228
+
229
+ const PROTOTYPE_KEYS = new Set(['prototype', '__proto__'])
230
+ const PROTOTYPE_READERS = ['Object.getPrototypeOf', 'Reflect.getPrototypeOf']
231
+ const PROTOTYPE_WRITERS = ['Object.setPrototypeOf', 'Reflect.setPrototypeOf']
232
+ const PROPERTY_WRITERS = ['Object.defineProperty', 'Object.defineProperties', 'Object.assign', 'Reflect.defineProperty', 'Reflect.set']
233
+ const ALLOWED_PROTOTYPE = 'no patching of prototypes; the framework checks capabilities at runtime'
234
+
235
+ /** Whether an expression reaches a prototype: through `.prototype`, `.__proto__` or `Object.getPrototypeOf(…)`. */
236
+ export const touchesPrototype = (node: AstNode | undefined): boolean => {
237
+ let current = node === undefined ? undefined : unwrap(node)
238
+ while (current?.type === 'MemberExpression') {
239
+ const key = staticKey(current, 'property')
240
+ if (key !== undefined && PROTOTYPE_KEYS.has(key)) return true
241
+ const object = child(current, 'object')
242
+ current = object === undefined ? undefined : unwrap(object)
243
+ }
244
+ const callee = current?.type === 'CallExpression' ? child(current, 'callee') : undefined
245
+ return callee !== undefined && PROTOTYPE_READERS.includes(memberPath(callee)?.join('.') ?? '')
246
+ }
247
+
248
+ const checkPrototypeCall = (node: AstNode, path: readonly string[], context: SourceContext): void => {
249
+ const name = path.join('.')
250
+ if (PROTOTYPE_WRITERS.includes(name)) {
251
+ context.report(node, 'prototype-assignment', `${name} replaces an object's prototype`, ALLOWED_PROTOTYPE)
252
+ } else if (PROPERTY_WRITERS.includes(name) && touchesPrototype(argumentAt(node, 0))) {
253
+ context.report(node, 'prototype-assignment', `${name} writes to a prototype`, ALLOWED_PROTOTYPE)
254
+ }
255
+ }
256
+
257
+ const ALLOWED_LOAD = 'a static import, or import() and require() of a string literal'
258
+
259
+ /** The specifier of a direct load: `import(x)`, `require(x)`, `module.require(x)`, `import.meta.require(x)`. */
260
+ const loadedSpecifier = (node: AstNode): { readonly what: string; readonly specifier: AstNode | null | undefined } | undefined => {
261
+ if (node.type === 'ImportExpression') return { what: 'import()', specifier: child(node, 'source') }
262
+ if (node.type === 'CallExpression' && isRequire(child(node, 'callee'))) return { what: 'require()', specifier: children(node, 'arguments')[0] }
263
+ return undefined
264
+ }
265
+
266
+ /** A load of a computed specifier: the checker cannot say which module it reaches, nor run its rules there. */
267
+ const checkComputedLoad = (node: AstNode, context: SourceContext): void => {
268
+ const load = loadedSpecifier(node)
269
+ if (load === undefined || staticString(load.specifier ?? undefined) !== undefined) return
270
+ context.report(node, 'unchecked-import', `${load.what} of a computed specifier loads a module the checker cannot name`, ALLOWED_LOAD)
271
+ }
272
+
273
+ const LOADER_METHODS = new Set(['call', 'apply', 'bind'])
274
+
275
+ /** A loader invoked indirectly, `require.call(…)` or `Reflect.apply(require, …)`: references.ts reads direct calls only. */
276
+ const checkIndirectLoad = (node: AstNode, path: readonly string[] | undefined, context: SourceContext): void => {
277
+ const callee = child(node, 'callee')
278
+ const object = callee?.type === 'MemberExpression' ? child(callee, 'object') : undefined
279
+ const method = callee?.type === 'MemberExpression' ? staticKey(callee, 'property') : undefined
280
+ const loader = method !== undefined && LOADER_METHODS.has(method) && isRequire(object) ? object : undefined
281
+ const applied = pathIs(path, 'Reflect', 'apply') && isRequire(argumentAt(node, 0)) ? argumentAt(node, 0) : undefined
282
+ const reached = loader ?? applied
283
+ if (reached === undefined) return
284
+ const name = `${memberPath(reached)?.join('.') ?? 'require'}${loader === undefined ? ' through Reflect.apply' : `.${method}`}`
285
+ context.report(node, 'unchecked-import', `${name} loads a module the checker does not follow`, ALLOWED_LOAD)
286
+ }
287
+
288
+ /** They turn a specifier into a module file, or reach the loaded modules: what a load by path or URL starts from. */
289
+ const RESOLVERS = new Set(['import.meta.resolve', 'import.meta.resolveSync', 'require.resolve', 'require.cache', 'Bun.resolve', 'Bun.resolveSync'])
290
+
291
+ const checkCall = (node: AstNode, ancestors: readonly AstNode[], context: SourceContext): void => {
292
+ checkComputedLoad(node, context)
293
+ const callee = child(node, 'callee')
294
+ const path = callee === undefined ? undefined : globalPath(callee)
295
+ if (node.type === 'CallExpression') checkIndirectLoad(node, path, context)
296
+ if (path === undefined) return
297
+ checkDynamicCode(node, path, context)
298
+ if (node.type !== 'CallExpression') return
299
+ checkFetch(node, path, context)
300
+ checkConsole(node, path, ancestors, context)
301
+ checkPrototypeCall(node, path, context)
302
+ const [name] = path
303
+ if (path.length === 1 && name !== undefined && context.rawSql.has(name)) {
304
+ context.report(node, 'raw-sql', `${name}(…) builds raw SQL`, ALLOWED_QUERY)
305
+ }
306
+ }
307
+
308
+ const checkMember = (node: AstNode, ancestors: readonly AstNode[], context: SourceContext): void => {
309
+ const parent = ancestors[ancestors.length - 1]
310
+ const path = globalPath(node)
311
+ const property = staticKey(node, 'property')
312
+ const name = path?.join('.') ?? ''
313
+ if (RESOLVERS.has(name)) context.report(node, 'unchecked-import', `${name} names a module by its file, past what the checker reads`, ALLOWED_LOAD)
314
+ if (name === 'process.getBuiltinModule') {
315
+ context.report(
316
+ node,
317
+ 'unchecked-import',
318
+ 'process.getBuiltinModule loads a built-in module past the import rules (createRequire among them)',
319
+ ALLOWED_LOAD,
320
+ )
321
+ }
322
+ const bunMember = path?.length === 2 && path[0] === 'Bun' ? FORBIDDEN_BUN_MEMBERS.get(path[1] ?? '') : undefined
323
+ // In a server module the root itself is refused (`checkIdentifier`), once.
324
+ const root = memberPath(node)?.[0] ?? ''
325
+ const rootRefused = context.isServerModule && SERVER_REFUSED_GLOBALS.has(root) && declaringScope(root, ancestors) === undefined
326
+ if (bunMember !== undefined && !rootRefused) context.report(node, 'forbidden-global', `Bun.${path?.[1]} is ${bunMember.what}`, bunMember.allowed)
327
+ if (pathIs(path, 'eval') && (memberPath(node)?.length ?? 0) > 1) context.report(node, 'dynamic-code', 'eval runs a string as code', ALLOWED_CODE)
328
+ if (!context.isGeneratedEntry && (pathIs(path, 'process', 'env') || pathIs(path, 'Bun', 'env'))) {
329
+ context.report(node, 'env-read', `${path?.join('.')} is read outside the generated entrypoint`, ALLOWED_ENV)
330
+ }
331
+ if (!context.isGeneratedEntry && pathIs(path, 'import.meta', 'env')) {
332
+ const name = parent?.type === 'MemberExpression' && parent['object'] === node ? staticKey(parent, 'property') : undefined
333
+ if (name === undefined || !name.startsWith('FABRIKA_PUBLIC_')) {
334
+ context.report(
335
+ node,
336
+ 'public-env',
337
+ `import.meta.env${name === undefined ? '' : `.${name}`} is not a public variable`,
338
+ 'import.meta.env.FABRIKA_PUBLIC_<NAME>',
339
+ )
340
+ }
341
+ }
342
+ const fullPath = memberPath(node)
343
+ const suffix = fullPath ?? memberSuffix(node)
344
+ const helper = suffix[suffix.length - 1] ?? ''
345
+ const receiver = suffix[suffix.length - 2] ?? ''
346
+ // `<x>.sql.raw` by name; a bare `sql.raw` (or an alias's `q.raw`) by the origin of its root.
347
+ const rawHelper = fullPath?.length === 2 ? context.rawSql.has(receiver) : receiver === 'sql'
348
+ if (suffix.length >= 2 && RAW_SQL_HELPERS.has(helper) && rawHelper) {
349
+ context.report(node, 'raw-sql', `${receiver}.${helper} builds raw SQL`, ALLOWED_QUERY)
350
+ }
351
+ if (property === 'innerHTML' || property === 'outerHTML' || property === 'insertAdjacentHTML') {
352
+ context.report(node, 'unsafe-html', `${property} injects markup that runs as the signed-in user`, ALLOWED_MARKUP)
353
+ }
354
+ }
355
+
356
+ /** The site's options: the object literal its builder takes last (`r.query({ … })`, also `{ … } satisfies T` or `as const`). */
357
+ const procedureOptions = (procedure: AstNode): AstNode | undefined => {
358
+ const last = children(procedure, 'arguments').at(-1)
359
+ const options = last === null || last === undefined ? undefined : unwrapValue(last)
360
+ return options?.type === 'ObjectExpression' ? options : undefined
361
+ }
362
+
363
+ /** Whether the options declare `sql`; a spread may hold it, so it counts as declaring. */
364
+ const declaresSql = (options: AstNode): boolean =>
365
+ children(options, 'properties').some((property) => property === null || property.type === 'SpreadElement' || staticKey(property, 'key') === 'sql')
366
+
367
+ /**
368
+ * `ctx.sql` (or a job's `tx.sql`) in a `.handle(…)` whose options declare no `sql`: the runtime builds no `ctx.sql`
369
+ * there. A hint, not the boundary: a destructured `ctx` or a helper escapes it, and the runtime refuses anyway.
370
+ */
371
+ const checkUndeclaredSql = (node: AstNode, ancestors: readonly AstNode[], context: SourceContext): void => {
372
+ const handle = identifierName(child(node, 'object'))
373
+ if (staticKey(node, 'property') !== 'sql' || (handle !== 'ctx' && handle !== 'tx')) return
374
+ for (let index = ancestors.length - 1; index >= 0; index--) {
375
+ const site = handledProcedure(ancestors[index] ?? node)
376
+ if (site === undefined) continue
377
+ const options = procedureOptions(site.procedure)
378
+ if (options === undefined || declaresSql(options)) return
379
+ const holder = ancestors[index - 1]
380
+ const name = holder?.type === 'Property' ? staticKey(holder, 'key') : undefined
381
+ const where = name === undefined ? `this ${site.builder}` : `'${name}'`
382
+ const reads = site.builder === 'query' || site.builder === 'export'
383
+ context.report(
384
+ node,
385
+ 'sql-undeclared',
386
+ `${handle}.sql in the handler of ${where}, whose options declare no sql`,
387
+ reads ? `sql: 'read' in the options of ${where}` : `sql: 'read' in the options of ${where}, or sql: 'write' to write`,
388
+ )
389
+ return
390
+ }
391
+ }
392
+
393
+ /** Inside an ambient `declare`, which types a name and runs nothing. */
394
+ const isAmbient = (ancestors: readonly AstNode[]): boolean => ancestors.some((ancestor) => ancestor['declare'] === true)
395
+
396
+ const checkIdentifier = (node: AstNode, ancestors: readonly AstNode[], context: SourceContext): void => {
397
+ const parent = ancestors[ancestors.length - 1]
398
+ if (!isValueReference(node, parent)) return
399
+ const name = stringField(node, 'name')
400
+ const isMemberObject = parent?.type === 'MemberExpression' && parent['object'] === node
401
+ if (name === 'eval') context.report(node, 'dynamic-code', 'eval runs a string as code', ALLOWED_CODE)
402
+ const isTypeofCheck = parent?.type === 'UnaryExpression' && parent['operator'] === 'typeof'
403
+ const isRefusedName = context.isServerModule && name !== undefined && SERVER_REFUSED_GLOBALS.has(name) && !isTypeofCheck
404
+ // A name the module binds itself (a declaration, a parameter, an import) is its own value, not the global.
405
+ if (isRefusedName && declaringScope(name, ancestors) === undefined && !isAmbient(ancestors)) {
406
+ context.report(node, 'forbidden-global', `${name} is not used in a server module`, 'what the framework hands the handler through ctx or deps')
407
+ return
408
+ }
409
+ if (name === 'Bun' && !isMemberObject) {
410
+ context.report(node, 'forbidden-global', 'Bun used as a value hides which global is reached', 'Bun.<member> written out')
411
+ }
412
+ if (name === 'process' && !isMemberObject && !context.isGeneratedEntry && !isTypeofCheck) {
413
+ context.report(node, 'env-read', 'process used as a value hides a read of process.env', ALLOWED_ENV)
414
+ }
415
+ }
416
+
417
+ /** `const { env } = import.meta` reads the whole environment without naming a variable. */
418
+ const checkDestructuredEnv = (node: AstNode, context: SourceContext): void => {
419
+ const pattern = child(node, 'id')
420
+ const init = child(node, 'init')
421
+ if (pattern?.type !== 'ObjectPattern' || init?.type !== 'MetaProperty' || context.isGeneratedEntry) return
422
+ if (children(pattern, 'properties').some((property) => property !== null && staticKey(property, 'key') === 'env')) {
423
+ context.report(node, 'public-env', 'env destructured from import.meta', 'import.meta.env.FABRIKA_PUBLIC_<NAME>')
424
+ }
425
+ }
426
+
427
+ const checkPrototypeWrite = (node: AstNode, context: SourceContext): void => {
428
+ const target = node.type === 'AssignmentExpression' ? child(node, 'left') : child(node, 'argument')
429
+ const isWrite = node.type !== 'UnaryExpression' || node['operator'] === 'delete'
430
+ if (isWrite && target !== undefined && touchesPrototype(target)) {
431
+ context.report(node, 'prototype-assignment', 'a write to a prototype patches every instance', ALLOWED_PROTOTYPE)
432
+ }
433
+ }
434
+
435
+ const KEY_PREFIX = 'px_'
436
+
437
+ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], context: SourceContext): void => {
438
+ if (texts.some((text) => text?.includes(KEY_PREFIX))) {
439
+ context.report(
440
+ node,
441
+ 'key-literal',
442
+ `'${KEY_PREFIX}' in a literal: a key or a session cookie name in source`,
443
+ 'the credential the framework supplies; keys never appear in code',
444
+ )
445
+ }
446
+ }
447
+
448
+ const isTypeOnlyImport = (specifier: AstNode, parent: AstNode | undefined): boolean =>
449
+ stringField(specifier, 'importKind') === 'type' || (parent !== undefined && stringField(parent, 'importKind') === 'type')
450
+
451
+ const DANGEROUSLY_SET = 'dangerouslySetInnerHTML injects markup that runs as the signed-in user'
452
+
453
+ /** The rules that read one node at a time, for every source file. */
454
+ export const checkRuntimeNode = (node: AstNode, ancestors: readonly AstNode[], context: SourceContext): void => {
455
+ const parent = ancestors[ancestors.length - 1]
456
+ switch (node.type) {
457
+ case 'CallExpression':
458
+ case 'NewExpression':
459
+ return checkCall(node, ancestors, context)
460
+ case 'ImportExpression':
461
+ return checkComputedLoad(node, context)
462
+ case 'MemberExpression':
463
+ checkUndeclaredSql(node, ancestors, context)
464
+ return checkMember(node, ancestors, context)
465
+ case 'Identifier':
466
+ return checkIdentifier(node, ancestors, context)
467
+ case 'VariableDeclarator':
468
+ return checkDestructuredEnv(node, context)
469
+ case 'AssignmentExpression':
470
+ case 'UpdateExpression':
471
+ case 'UnaryExpression':
472
+ return checkPrototypeWrite(node, context)
473
+ case 'TaggedTemplateExpression': {
474
+ const tag = child(node, 'tag')
475
+ const path = tag === undefined ? undefined : memberPath(tag)
476
+ const suffix = tag === undefined ? [] : (path ?? memberSuffix(tag))
477
+ const [root] = suffix
478
+ // A member `.sql` tag by name; a bare tag by its origin, so a parameter that holds the declared ctx.sql is not one.
479
+ const raw = path?.length === 1 ? root !== undefined && context.rawSql.has(root) : suffix[suffix.length - 1] === 'sql'
480
+ if (raw) context.report(node, 'raw-sql', 'an sql`…` template is raw SQL', ALLOWED_QUERY)
481
+ return
482
+ }
483
+ case 'ImportSpecifier': {
484
+ const imported = child(node, 'imported')
485
+ if ((identifierName(imported) ?? staticString(imported)) === 'sql' && !isTypeOnlyImport(node, parent)) {
486
+ context.report(node, 'raw-sql', 'the sql tag imported', ALLOWED_QUERY)
487
+ }
488
+ return
489
+ }
490
+ case 'Literal':
491
+ return checkStringContent(node, [staticString(node)], context)
492
+ case 'TemplateElement': {
493
+ const { raw, cooked } = templateText(node)
494
+ return checkStringContent(node, [raw, cooked], context)
495
+ }
496
+ case 'JSXAttribute': {
497
+ const name = child(node, 'name')
498
+ if (name?.type === 'JSXIdentifier' && stringField(name, 'name') === 'dangerouslySetInnerHTML') {
499
+ context.report(node, 'unsafe-html', DANGEROUSLY_SET, ALLOWED_MARKUP)
500
+ }
501
+ return
502
+ }
503
+ case 'Property':
504
+ if (staticKey(node, 'key') === 'dangerouslySetInnerHTML') context.report(node, 'unsafe-html', DANGEROUSLY_SET, ALLOWED_MARKUP)
505
+ return
506
+ }
507
+ }