@sssb/kit 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/auth-tenancy.ts +157 -0
  4. package/src/adapters/configured-auth.ts +183 -0
  5. package/src/adapters/email-message.ts +30 -0
  6. package/src/adapters/fake/analytics.ts +1 -1
  7. package/src/adapters/fake/auth.ts +53 -3
  8. package/src/adapters/fake/data-dir.ts +32 -2
  9. package/src/adapters/fake/email.ts +2 -0
  10. package/src/adapters/fake/jobs.ts +5 -4
  11. package/src/adapters/fake/simulated-auth.ts +24 -0
  12. package/src/adapters/index.ts +3 -2
  13. package/src/adapters/real/accept-invite-form.tsx +32 -14
  14. package/src/adapters/real/analytics.ts +29 -2
  15. package/src/adapters/real/auth.ts +127 -23
  16. package/src/adapters/real/contract-postgres.ts +15 -11
  17. package/src/adapters/real/email.ts +2 -0
  18. package/src/adapters/real/index.ts +19 -3
  19. package/src/adapters/real/jobs-in-process.ts +32 -14
  20. package/src/adapters/real/jobs.ts +6 -3
  21. package/src/adapters/real/migrate-handler.ts +3 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/sign-in-form.tsx +29 -13
  25. package/src/authz/app-exemptions.ts +79 -9
  26. package/src/authz/authorize.ts +4 -1
  27. package/src/authz/route-scan.ts +626 -55
  28. package/src/components/auth/accept-invite-screen.tsx +5 -1
  29. package/src/components/auth/people-picker.tsx +20 -2
  30. package/src/components/profile-screen.tsx +27 -2
  31. package/src/core/abilities.ts +22 -6
  32. package/src/core/inbound-email.ts +41 -6
  33. package/src/core/jobs.ts +17 -0
  34. package/src/core/roles.ts +17 -2
  35. package/src/cutover/rows.json +4 -0
  36. package/src/db/jobs.ts +32 -11
  37. package/src/db/keyset.ts +8 -6
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/migrations/0017_job_requester.ts +20 -0
  40. package/src/db/migrations/index.ts +2 -0
  41. package/src/db/rls-coverage.ts +51 -17
  42. package/src/db/schedules.ts +9 -3
  43. package/src/db/schema.ts +2 -0
  44. package/src/demo-static/actor-drivers.ts +8 -2
  45. package/src/demo-static/contracts.ts +9 -0
  46. package/src/demo-static/email-html.ts +9 -0
  47. package/src/demo-static/rows.ts +2 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +98 -41
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +37 -6
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +10 -1
  56. package/src/server-lib/notify.ts +51 -9
  57. package/src/server-lib/scheduled-tick.ts +5 -1
  58. package/src/server-lib/webhook-dispatch.ts +3 -0
  59. package/src/service-auth/mailgun.ts +19 -4
  60. package/src/testing/conformance/auth-provider.ts +17 -5
  61. package/src/testing/conformance/authz.ts +6 -2
  62. package/src/testing/conformance/demo-presets.ts +4 -4
  63. package/src/testing/conformance/i18n.ts +99 -5
  64. package/src/testing/conformance/suite.ts +63 -3
@@ -1,4 +1,4 @@
1
- import { existsSync, readdirSync } from 'node:fs'
1
+ import { type Dirent, existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import ts from 'typescript'
4
4
 
@@ -8,7 +8,9 @@ import ts from 'typescript'
8
8
  * ./route-policy.ts and an app's own) is input rather than something this module knows. It reads route
9
9
  * files with the TypeScript compiler's parser and binder, never a regex over their text, and judges EACH
10
10
  * exported mutating handler on its own: a string, a comment, a call in another handler or a call in
11
- * statically dead code proves nothing about the handler in front of it.
11
+ * statically dead code proves nothing about the handler in front of it. Server Actions (`scanServerActions`) are
12
+ * judged by the same rules as a POST, each export of a `'use server'` file and each function whose body opens with
13
+ * `'use server'`; no exemption applies to one. The walks follow a symbolic link to a directory, as Next does.
12
14
  *
13
15
  * WHAT "REACHES" MEANS. A call counts for a handler when it sits on that handler's own path:
14
16
  *
@@ -16,13 +18,21 @@ import ts from 'typescript'
16
18
  * `continue`; an `if`, `try`, `switch` or labeled block every way through which does; a `while (true)` or
17
19
  * `for (;;)` nothing breaks out of; a `do` whose body never falls through;
18
20
  * - not in a branch a constant condition rules out: `if (false)`, `false && …`, `true ? … : here`,
19
- * `'x' ?? …`, or a `const` bound to such a literal. Constants are literals, `!`, `void` and parentheses;
21
+ * `'x' ?? …`, an optional call on a receiver a constant makes nullish (`hook?.(…)` with `const hook = null`), or a
22
+ * `const` bound to such a literal. Constants are literals, `!`, `void` and parentheses;
20
23
  * nothing else is evaluated;
21
24
  * - in a function literal passed as an argument (`withPortErrors(async () => { … })`), which the call is
22
25
  * ASSUMED to invoke and to carry its failure in the call's own result. That is the wrapper idiom every route
23
26
  * uses, and the one trust this module extends: it cannot read an imported wrapper to see whether it really
24
27
  * calls its argument. It extends none to a callee whose code is in this file (`isSameFile`): a function is not
25
- * followed through a parameter, so what such a callee is handed counts for nothing;
28
+ * followed through a parameter, so what such a callee is handed counts for nothing. Nor to a callee known never to
29
+ * hand a function's failure back (`neverCarriesFailure`): a timer or microtask (`setTimeout`, `setInterval`,
30
+ * `setImmediate`, `queueMicrotask`, `process.nextTick`; bare, as a member of `globalThis`, `self` or `window`, or
31
+ * imported from Node's `timers`), Next's `after` (and `unstable_after`), which runs its callback after the response,
32
+ * `Promise.resolve`, which never calls a function, a `.catch`, `.finally` or listener method (`.on`, `.once`,
33
+ * `addEventListener`, …) on any receiver, and the second argument of `.then`, which runs only on a rejection. A function
34
+ * handed to a callee whose result is RETURNED counts only where a throw at the call would also reach the outcome
35
+ * (not inside a `try` whose `catch` swallows): the callee may run it synchronously, a tracing span does;
26
36
  * - in a function declared in the SAME module and called (or passed as an argument) from the handler's
27
37
  * path, followed to any depth. A function that is only defined, or that the file reassigns or declares twice,
28
38
  * is not followed;
@@ -34,10 +44,15 @@ import ts from 'typescript'
34
44
  * on the spot (`settledBy`: `return`, an arrow's expression body; through parentheses, a type assertion, a
35
45
  * ternary arm, the right of `&&`, `||`, `??` or a comma, or the left of `||` or `??`). A statement of its own,
36
46
  * `void`, a variable awaited later, a `.then` or `.catch` chain, an argument, all leave the promise floating;
37
- * - an array iteration method (`forEach`, `map`, …, by name, on a receiver that is neither an import nor an
38
- * object whose code is in this file). It drops an `async` function's promise, awaited or not, and runs a sync
39
- * one in place, so its throw goes up through the call; but a `map`, `filter` or `flatMap` on a receiver that is
40
- * visibly an iterator (`xs.values()`, `Iterator.from(…)`) runs nothing until consumed;
47
+ * - an array iteration method (`forEach`, `map`, …, by name on any receiver but an object whose code is in this
48
+ * file, and `Array.from`'s mapper). It drops an `async` function's promise, awaited or not, and runs a sync one
49
+ * in place, so its throw goes up through the call; but a `map`, `filter` or `flatMap` on a receiver that is
50
+ * visibly an iterator (`xs.values()`, `Iterator.from(…)`) runs nothing until consumed, and on a receiver whose
51
+ * head is an import (`R.forEach`, `parse(req).ids.map`), where the name may be a library's, a sync callback
52
+ * counts only when the call's result is settled, as for any imported callee. The one way an async callback's
53
+ * failure comes back is `Promise.all(xs.map(async …))` awaited or returned: Promise.all rejects with the first
54
+ * rejection. `allSettled` never rejects, and `any` and `race` settle on another promise, so they do not count.
55
+ * (`Array.fromAsync` awaits what its mapper returns, so it is trusted like any imported callee);
41
56
  * - a `try` whose `catch` can do anything but rethrow (fall through, `return`, `break` or `continue` out of
42
57
  * itself), or whose `finally` can leave in the throw's place. A promise the `try` returns (`return p`) is not
43
58
  * caught; `return await p` throws inside it.
@@ -59,7 +74,11 @@ import ts from 'typescript'
59
74
  * value import (not `import type`, not a JSDoc `@import`). A local function that happens to be named
60
75
  * `authorize` is followed like any other, so it counts only if it calls the real one.
61
76
  *
62
- * WHAT COUNTS AS A GATE'S NAME: the same rule, by binding (`gateName`). `withWebhookSecret`, `auth.updateProfile`,
77
+ * WHAT COUNTS AS A GATE'S NAME: the same rule, by binding (`gateName`). A gate's call counts wherever it RUNS on the
78
+ * handler's path, whatever a `try` around it does with its failure (a `calls` gate says what the route's mutation is,
79
+ * so what matters is that it runs). One in a function that never runs, or runs only later and not for the handler (a
80
+ * same-file callee the scan does not follow, a lazy iterator, a timer, a listener, a `.catch` handler, an `after`
81
+ * callback), does not count. `withWebhookSecret`, `auth.updateProfile`,
63
82
  * `isSimulated` count only when the name (the head of a dotted one) is a value import kept under the name it is
64
83
  * exported by, from any module; a namespace member reads under its own name. A local look-alike
65
84
  * (`const isSimulated = true`) or an alias (`import { identity as withWebhookSecret }`) is not the gate.
@@ -67,6 +86,13 @@ import ts from 'typescript'
67
86
  * A handler the module cannot resolve at all (a destructured export, a `let`, a reassigned function, an
68
87
  * unresolvable re-export, a file that does not parse, a module that is not an ES module) is REFUSED with
69
88
  * the reason, and a refusal is a failure.
89
+ *
90
+ * WHAT IT DOES NOT PROVE. "Reaches" is MAY-reach: some path through the handler passes an `authorize` whose denial
91
+ * stops it. It does not prove that EVERY path does, nor that the call comes before the mutation. A handler that
92
+ * returns early on an attacker's input before authorizing, authorizes only inside an `if`, mutates first and
93
+ * authorizes after, or authorizes in a loop over a list that may be empty, passes. Only a branch a constant rules
94
+ * out is dead to it; a condition it cannot evaluate is taken both ways. The rule an author keeps by hand is
95
+ * stronger: authorize before anything else the handler does, on every path.
70
96
  */
71
97
 
72
98
  /** The verbs that mutate. GET, HEAD and OPTIONS are never judged. */
@@ -114,10 +140,12 @@ export interface ScanRoot {
114
140
  * - `wrapped-by`: the handler IS a call to one of `callees` (`export const POST = withWebhookSecret(…)`).
115
141
  * For a guard that wraps the handler, reaching it is not enough: the guard has to be what Next calls.
116
142
  * - `calls`: the handler reaches a call to one of `callees` (dotted names, `auth.updateProfile`).
117
- * - `opens-with-simulated-404`: the handler's FIRST statement is `if (!isSimulated)` and its branch does
118
- * nothing but return or throw a response built from literals (`return new Response(null, { status: 404 })`,
119
- * `return Response.json(…)`, `throw new NotFoundError(…)`), and no parameter runs code before it (a default),
120
- * so the real-mode path does nothing.
143
+ * - `opens-with-simulated-404`: the handler's FIRST statement (after a directive prologue) is `if (!isSimulated)`
144
+ * and its branch does nothing but return or throw a response built from literals (`return new Response(null,
145
+ * { status: 404 })`, `return Response.json(…)`, `throw new NotFoundError(…)` with the error imported from
146
+ * `@sssb/kit/ports/errors`, or a global `…Error`), no parameter runs code before it (a default), and the file
147
+ * assigns to none of the globals that branch builds (`Response`, `JSON`, an `…Error`), so the real-mode path
148
+ * does nothing.
121
149
  */
122
150
  export type Gate =
123
151
  | { kind: 'wrapped-by'; callees: readonly string[] }
@@ -159,25 +187,279 @@ export function scanRoutes(roots: readonly ScanRoot[], options: ScanOptions = {}
159
187
  const authorizeModules = options.authorizeModules ?? ['@sssb/kit/authz/authorize']
160
188
  return roots.flatMap((root) => {
161
189
  const scanner = new RootScanner(root, authorizeModules)
162
- return routeFiles(root.dir).map((file) => ({
190
+ const unreadable = new Map<string, string>()
191
+ const routes: ScannedRoute[] = routeFiles(root.dir, unreadable).map((file) => ({
163
192
  root: root.label,
164
193
  rel: path.relative(root.exemptDir, file).split(path.sep).join('/'),
165
194
  file,
166
195
  handlers: scanner.handlers(file),
167
196
  }))
197
+ for (const [dir, code] of unreadable) {
198
+ routes.push({
199
+ root: root.label,
200
+ rel: path.relative(root.exemptDir, dir).split(path.sep).join('/'),
201
+ file: dir,
202
+ handlers: [{ verb: '*', refusal: unreadableRefusal(code) }],
203
+ })
204
+ }
205
+ return routes
168
206
  })
169
207
  }
170
208
 
171
- function routeFiles(dir: string): string[] {
209
+ function routeFiles(dir: string, unreadable: Map<string, string>): string[] {
210
+ return walkFiles(
211
+ dir,
212
+ (name) => ROUTE_FILE.test(name),
213
+ () => true,
214
+ new Set(),
215
+ new Map(),
216
+ unreadable,
217
+ )
218
+ }
219
+
220
+ /** The refusal for a directory the walk could not read: a failure, since a route or an action may be in it. */
221
+ function unreadableRefusal(code: string): string {
222
+ return `the directory could not be read (${code}), so a route or Server Action in it would go unchecked`
223
+ }
224
+
225
+ /**
226
+ * Files under `dir` named `route.<something>` that the scan does not read as a route (`route.mts`, `route.api.ts`):
227
+ * Next serves `route.<ext>` for every extension its `pageExtensions` names, which the scan does not read, so such a
228
+ * file may be a route nobody checked. A colocated test artefact (`route.test.ts`, `route.integration.test.ts`,
229
+ * `route.spec.tsx`, `route.stories.tsx`, `route.bench.ts`, `route.test-d.ts`, a `.snap`) and a declaration file are
230
+ * not routes.
231
+ */
232
+ export function unreadRouteFiles(dir: string): string[] {
233
+ const named = (name: string) =>
234
+ /^route\./.test(name) &&
235
+ !ROUTE_FILE.test(name) &&
236
+ !/^route\.(?:[\w-]+\.)*(?:test|spec|stories|bench|test-d)\.[cm]?[jt]sx?$/.test(name) &&
237
+ !/\.d\.[cm]?ts$/.test(name) &&
238
+ !name.endsWith('.snap')
239
+ return walkFiles(dir, named, () => true)
240
+ }
241
+
242
+ /**
243
+ * Every file under `dir` whose name `accept`s, descending into each directory `descend` allows. A symbolic link to
244
+ * a directory is followed as Next's own walk follows it (a `Dirent` reports the link, not a directory, so a walk
245
+ * that asked only `isDirectory()` skipped every route behind one), and a link back to a directory the walk is
246
+ * already inside is not, so a cycle ends. A file's path is the one the walk reached it by, link included: that is
247
+ * the path Next serves it at.
248
+ */
249
+ function walkFiles(
250
+ dir: string,
251
+ accept: (name: string) => boolean,
252
+ descend: (name: string) => boolean,
253
+ ancestors: ReadonlySet<string> = new Set(),
254
+ walked: Map<string, { base: string; files: string[] }> = new Map(),
255
+ unreadable: Map<string, string> = new Map(),
256
+ ): string[] {
257
+ // A directory the walk cannot read (EACCES, or removed mid-walk: ENOENT) may hold a route: it is recorded in
258
+ // `unreadable` with the error's code, for the caller to report as a failure, never skipped in silence.
259
+ let real: string
260
+ let listed: Dirent[]
261
+ try {
262
+ real = realpathSync(dir)
263
+ if (ancestors.has(real)) return []
264
+ listed = readdirSync(dir, { withFileTypes: true })
265
+ } catch (error) {
266
+ unreadable.set(dir, (error as NodeJS.ErrnoException).code ?? 'unknown error')
267
+ return []
268
+ }
269
+ const inside = new Set(ancestors).add(real)
172
270
  const out: string[] = []
173
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
271
+ // Sorted, so what the walk finds never depends on the filesystem's entry order.
272
+ const entries = listed.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
273
+ for (const entry of entries) {
174
274
  const full = path.join(dir, entry.name)
175
- if (entry.isDirectory()) out.push(...routeFiles(full))
176
- else if (ROUTE_FILE.test(entry.name)) out.push(full)
275
+ const linked = entry.isSymbolicLink() && isDirectoryTarget(full)
276
+ if (entry.isDirectory() || linked) {
277
+ if (!descend(entry.name)) continue
278
+ // A directory reached through a link that was already walked is not walked again (two links per level would
279
+ // make the walk exponential in the depth), but every file found there is reported again at THIS path too:
280
+ // Next serves it at both, and an exemption is judged by path.
281
+ const target = linked ? realpathOrUndefined(full) : undefined
282
+ const prior = target === undefined || inside.has(target) ? undefined : walked.get(target)
283
+ if (prior) {
284
+ out.push(...prior.files.map((file) => path.join(full, path.relative(prior.base, file))))
285
+ continue
286
+ }
287
+ const files = walkFiles(full, accept, descend, inside, walked, unreadable)
288
+ const walkedReal = realpathOrUndefined(full)
289
+ if (walkedReal !== undefined) walked.set(walkedReal, { base: full, files })
290
+ out.push(...files)
291
+ } else if (accept(entry.name)) out.push(full)
177
292
  }
178
293
  return out.sort()
179
294
  }
180
295
 
296
+ /** A path's real path, or undefined when it cannot be resolved (the walk reports such a directory itself). */
297
+ function realpathOrUndefined(file: string): string | undefined {
298
+ try {
299
+ return realpathSync(file)
300
+ } catch {
301
+ return undefined
302
+ }
303
+ }
304
+
305
+ /** Whether a symbolic link leads to a directory; false for a dangling one. */
306
+ function isDirectoryTarget(link: string): boolean {
307
+ try {
308
+ return statSync(link).isDirectory()
309
+ } catch {
310
+ return false
311
+ }
312
+ }
313
+
314
+ /** A source file Next could compile into the app, by extension. Declaration files hold no code. */
315
+ function isSourceFile(name: string): boolean {
316
+ return /\.(?:[cm]?[jt]sx?)$/.test(name) && !/\.d\.[cm]?ts$/.test(name)
317
+ }
318
+
319
+ /** Whether `statements` opens with a `'use server'` directive (a string-literal statement in the prologue). */
320
+ function hasUseServer(statements: readonly ts.Statement[]): boolean {
321
+ for (const statement of statements) {
322
+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) return false
323
+ if (statement.expression.text === 'use server') return true
324
+ }
325
+ return false
326
+ }
327
+
328
+ /** Whether the file declares any Server Action: a file-level `'use server'`, or one opening a function's body. */
329
+ function declaresServerActions(file: string): boolean {
330
+ let text: string
331
+ try {
332
+ text = readFileSync(file, 'utf8')
333
+ } catch {
334
+ // A dangling link (an editor's lockfile, `.#page.tsx -> user@host.pid`): nothing there to serve or to read.
335
+ return false
336
+ }
337
+ if (!text.includes('use server')) return false
338
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ESNext, false)
339
+ let found = hasUseServer(sf.statements)
340
+ const visit = (node: ts.Node): void => {
341
+ if (found) return
342
+ if (ts.isFunctionLike(node) && 'body' in node && node.body && ts.isBlock(node.body)) {
343
+ if (hasUseServer(node.body.statements)) found = true
344
+ }
345
+ ts.forEachChild(node, visit)
346
+ }
347
+ if (!found) visit(sf)
348
+ return found
349
+ }
350
+
351
+ export interface ScannedAction {
352
+ root: string
353
+ /** Path relative to the root's `dir`, `/`-separated. */
354
+ rel: string
355
+ file: string
356
+ /** The action's name: its export name, or `<function name or "inline"> (line N)` for an inline one. */
357
+ name: string
358
+ handler: Handler
359
+ }
360
+
361
+ /**
362
+ * Every Server Action under `root.dir`, each analysed as a mutating handler (verb `action`). A Server Action is
363
+ * a POST endpoint Next exposes for the function, so it must reach `authorize` by the same rules as a route's
364
+ * POST, and no exemption applies to one (the exemption map names route paths). Two kinds: every export of a file
365
+ * that opens with `'use server'`, and every function whose own body opens with it. `node_modules` is not walked.
366
+ */
367
+ export function scanServerActions(root: ScanRoot, options: ScanOptions = {}): ScannedAction[] {
368
+ const authorizeModules = options.authorizeModules ?? ['@sssb/kit/authz/authorize']
369
+ const scanner = new RootScanner(root, authorizeModules)
370
+ const unreadable = new Map<string, string>()
371
+ const files = walkFiles(
372
+ root.dir,
373
+ isSourceFile,
374
+ (name) => name !== 'node_modules',
375
+ new Set(),
376
+ new Map(),
377
+ unreadable,
378
+ ).filter(declaresServerActions)
379
+ const actions: ScannedAction[] = files.flatMap((file) =>
380
+ scanner.actions(file).map(({ name, handler }) => ({
381
+ root: root.label,
382
+ rel: path.relative(root.dir, file).split(path.sep).join('/'),
383
+ file,
384
+ name,
385
+ handler,
386
+ })),
387
+ )
388
+ for (const [dir, code] of unreadable) {
389
+ actions.push({
390
+ root: root.label,
391
+ rel: path.relative(root.dir, dir).split(path.sep).join('/'),
392
+ file: dir,
393
+ name: '*',
394
+ handler: { verb: 'action', refusal: unreadableRefusal(code) },
395
+ })
396
+ }
397
+ return actions
398
+ }
399
+
400
+ /**
401
+ * Build and test output a generated workspace's `.gitignore` names, at any depth. A bundler can keep a `'use server'`
402
+ * directive as the first statement of what it writes there, which is not the app's source: judging it would make the
403
+ * check's verdict depend on whether a build had run.
404
+ */
405
+ const BUILD_OUTPUT_DIRS: ReadonlySet<string> = new Set([
406
+ 'build',
407
+ 'cdk.out',
408
+ 'coverage',
409
+ 'dist',
410
+ 'dist-demo',
411
+ 'out',
412
+ 'playwright-report',
413
+ 'storybook-static',
414
+ 'test-results',
415
+ ])
416
+
417
+ /**
418
+ * Files in `appDir` but outside its `src` (and outside `node_modules`, dot-directories such as a build's `.next`, and
419
+ * BUILD_OUTPUT_DIRS) that declare Server Actions. The scan judges actions only under `src`, so one elsewhere would go
420
+ * unchecked. A directory it cannot read goes in `unreadable`, with its error code.
421
+ */
422
+ export function serverActionFilesOutsideSrc(appDir: string, unreadable: Map<string, string> = new Map()): string[] {
423
+ const keep = (name: string) => name !== 'node_modules' && !name.startsWith('.') && !BUILD_OUTPUT_DIRS.has(name)
424
+ if (!existsSync(appDir)) return []
425
+ let entries: Dirent[]
426
+ try {
427
+ entries = readdirSync(appDir, { withFileTypes: true })
428
+ } catch (error) {
429
+ unreadable.set(appDir, (error as NodeJS.ErrnoException).code ?? 'unknown error')
430
+ return []
431
+ }
432
+ return entries
433
+ .flatMap((entry) => {
434
+ const full = path.join(appDir, entry.name)
435
+ if (entry.name === 'src' || !keep(entry.name)) return []
436
+ if (entry.isDirectory() || (entry.isSymbolicLink() && isDirectoryTarget(full))) {
437
+ return walkFiles(full, isSourceFile, keep, new Set(), new Map(), unreadable)
438
+ }
439
+ return isSourceFile(entry.name) ? [full] : []
440
+ })
441
+ .filter(declaresServerActions)
442
+ .sort()
443
+ }
444
+
445
+ /** Why a Server Action fails the scan, or undefined if it passes. No exemption applies to one. */
446
+ export function judgeServerAction(action: ScannedAction): string | undefined {
447
+ const where = `${action.root}: ${action.rel} Server Action \`${action.name}\``
448
+ if (action.handler.refusal !== undefined) {
449
+ return `${where} cannot be checked: ${action.handler.refusal}. The scan fails a handler it cannot follow rather than pass it.`
450
+ }
451
+ if (action.handler.facts.reachesAuthorize) return undefined
452
+ return (
453
+ `${where} does not reach authorize(...) on its own path. A Server Action is a POST endpoint Next exposes ` +
454
+ `for the function, whoever renders the form that calls it, so it is judged as a route's POST is, and no ` +
455
+ `exemption applies to it. A call in a dead branch, an uncalled function or another module does not count, nor ` +
456
+ `does one whose denial cannot reach the action: in an async function or a callback whose promise it neither ` +
457
+ `awaits nor returns, or in a try whose catch does not rethrow (the useActionState shape, ` +
458
+ `\`try { authorize(...); … } catch (e) { return { error } }\`, swallows the denial). Call authorize(...) first, ` +
459
+ `before any try (or in a function in this file that it calls, awaiting it if it is async).`
460
+ )
461
+ }
462
+
181
463
  // ---------------------------------------------------------------------------------------------------------
182
464
  // Policy: exemptions and the gates they rest on.
183
465
  // ---------------------------------------------------------------------------------------------------------
@@ -233,7 +515,10 @@ export function describeGate(gate: Gate): string {
233
515
  return (
234
516
  'the handler takes no parameter that runs code (a default) and opens with ' +
235
517
  '`if (!isSimulated) return new Response(null, { status: 404 })` (an imported ' +
236
- '`isSimulated`, and a branch that only returns or throws a response built from inert values)'
518
+ '`isSimulated`, and a branch that only returns or throws a response built from inert values: ' +
519
+ '`new Response(…)` or `Response.json(…)` with literal arguments, or `throw new NotFoundError(…)` imported ' +
520
+ "from @sssb/kit/ports/errors. Next's `notFound()` (next/navigation) and an options object held in a " +
521
+ 'variable, `new Response(null, NOT_FOUND)`, are refused: the scan cannot see that either runs nothing)'
237
522
  )
238
523
  }
239
524
  }
@@ -335,6 +620,46 @@ class RootScanner {
335
620
  })
336
621
  }
337
622
 
623
+ /** Every Server Action `file` declares, with its facts or why it could not be read. */
624
+ actions(file: string): Array<{ name: string; handler: Handler }> {
625
+ const src = this.load(file)
626
+ if (typeof src === 'string') return [{ name: '*', handler: { verb: 'action', refusal: src } }]
627
+ const out: Array<{ name: string; handler: Handler }> = []
628
+ if (hasUseServer(src.sf.statements)) {
629
+ const { named, stars } = exportsOf(src)
630
+ for (const [name, binding] of named) {
631
+ const node = this.handlerOf(binding, new Set())
632
+ out.push({
633
+ name,
634
+ handler:
635
+ 'reason' in node
636
+ ? { verb: 'action', refusal: node.reason }
637
+ : { verb: 'action', facts: this.facts(node) },
638
+ })
639
+ }
640
+ for (const specifier of stars) {
641
+ const refusal = `\`export * from '${specifier}'\` in a 'use server' file is not followed; export each action by name`
642
+ out.push({ name: '*', handler: { verb: 'action', refusal } })
643
+ }
644
+ }
645
+ const visit = (node: ts.Node): void => {
646
+ if (ts.isFunctionLike(node) && 'body' in node && node.body && ts.isBlock(node.body)) {
647
+ if (hasUseServer(node.body.statements)) {
648
+ const fn = node as ts.FunctionLikeDeclaration
649
+ const line = src.sf.getLineAndCharacterOfPosition(fn.getStart(src.sf)).line + 1
650
+ const label = fn.name && ts.isIdentifier(fn.name) ? fn.name.text : 'inline'
651
+ out.push({
652
+ name: `${label} (line ${line})`,
653
+ handler: { verb: 'action', facts: this.facts({ src, fn }) },
654
+ })
655
+ }
656
+ }
657
+ ts.forEachChild(node, visit)
658
+ }
659
+ visit(src.sf)
660
+ return out
661
+ }
662
+
338
663
  private load(fileName: string): Source | string {
339
664
  const cached = this.sources.get(fileName)
340
665
  if (cached !== undefined) return cached
@@ -508,10 +833,21 @@ interface Outcome {
508
833
  thrown: boolean
509
834
  /** A promise the current function returns reaches the handler's outcome, so a rejection of it does. */
510
835
  returned: boolean
836
+ /**
837
+ * Code here runs when the handler does (as far as the scan can tell), whether or not its failure reaches the
838
+ * outcome. A gate's call counts where this holds: a `calls` gate says what the route's mutation IS, so what
839
+ * matters is that it runs, not where its failure goes. False in a function never invoked, or run later by
840
+ * something that is not the handler (a same-file callee not followed, a lazy iterator, a timer, a listener, a
841
+ * `.catch` handler).
842
+ */
843
+ runs: boolean
511
844
  }
512
845
 
513
- const HANDLER_OUTCOME: Outcome = { thrown: true, returned: true }
514
- const LOST: Outcome = { thrown: false, returned: false }
846
+ const HANDLER_OUTCOME: Outcome = { thrown: true, returned: true, runs: true }
847
+ /** Never runs on the handler's path. */
848
+ const NEVER: Outcome = { thrown: false, returned: false, runs: false }
849
+ /** Runs, but its failure does not reach the handler's outcome (the outcome `outer` carries over its `runs`). */
850
+ const dropped = (outer: Outcome): Outcome => ({ thrown: false, returned: false, runs: outer.runs })
515
851
 
516
852
  /** Walks one handler's path, collecting the calls on it. One instance per handler, never shared. */
517
853
  class Reach {
@@ -530,7 +866,7 @@ class Reach {
530
866
 
531
867
  /** Walks `fn`'s body, where `outcome` says what reaches the handler's outcome from inside it. */
532
868
  invoke(fn: ts.FunctionLikeDeclaration, outcome: Outcome = HANDLER_OUTCOME): void {
533
- const key = `${outcome.thrown}/${outcome.returned}`
869
+ const key = `${outcome.thrown}/${outcome.returned}/${outcome.runs}`
534
870
  const seen = this.invoked.get(fn) ?? new Set<string>()
535
871
  if (seen.has(key)) return
536
872
  seen.add(key)
@@ -552,7 +888,7 @@ class Reach {
552
888
  * is handed counts for nothing, and so does what a wrapper inside it is handed.
553
889
  */
554
890
  wrapped(call: ts.CallExpression, outcome: Outcome = HANDLER_OUTCOME): void {
555
- const own = this.isSameFile(call.expression) ? LOST : outcome
891
+ const own = this.isSameFile(call.expression) ? NEVER : outcome
556
892
  for (const argument of call.arguments) {
557
893
  const a = unwrap(argument)
558
894
  if (isFunctionLiteral(a)) this.invoke(a, own)
@@ -625,18 +961,17 @@ class Reach {
625
961
  }
626
962
 
627
963
  /**
628
- * `xs.forEach`, `xs['map']` and the like, by name: an array iteration method, unless the receiver's head is an
629
- * import, where the same name is often a library's (Ramda's curried `R.map`, `Effect.map`), deferred or lazy, or
630
- * an object whose code is in this file, whose `forEach` is its own. `lazy` is a `map`, `filter` or `flatMap` on
631
- * a receiver that is visibly an iterator (`xs.values()`, `.keys()`, `.entries()`, `Iterator.from(…)`), which
632
- * runs nothing until something consumes it.
964
+ * `xs.forEach`, `xs['map']` and the like, by name, whatever the receiver: an array iteration method, unless the
965
+ * receiver is an object whose code is in this file, whose `forEach` is its own (and, being same-file, is not
966
+ * followed through its parameter at all). `imported` is a receiver whose head is an import (`parse(req).ids`,
967
+ * `R`), where the same name may be a library's, deferred or lazy: an async callback is dropped either way, and a
968
+ * sync one is trusted only as far as an imported callee is. `lazy` is a `map`, `filter` or `flatMap` on a
969
+ * receiver that is visibly an iterator (`xs.values()`, `.keys()`, `.entries()`, `Iterator.from(…)`), which runs
970
+ * nothing until something consumes it. `Array.from(xs, fn)` maps like an eager method.
633
971
  */
634
- private iterationMethod(callee: ts.Expression): { name: string; lazy: boolean } | undefined {
635
- let name: string | undefined
636
- if (ts.isPropertyAccessExpression(callee)) name = callee.name.text
637
- else if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
638
- name = callee.argumentExpression.text
639
- }
972
+ private iterationMethod(callee: ts.Expression): { name: string; lazy: boolean; imported: boolean } | undefined {
973
+ if (isGlobalMember(this.src, callee, 'Array', 'from')) return { name: 'from', lazy: false, imported: false }
974
+ const name = memberName(callee)
640
975
  if (name === undefined || !ARRAY_ITERATION.has(name)) return undefined
641
976
  const receiver = unwrap((callee as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression)
642
977
  let head = receiver
@@ -646,9 +981,9 @@ class Reach {
646
981
  else if (ts.isCallExpression(head)) head = unwrap(head.expression)
647
982
  else break
648
983
  }
649
- if (ts.isIdentifier(head) && valueImportOf(declarationOf(this.src, head)) !== undefined) return undefined
984
+ const imported = ts.isIdentifier(head) && valueImportOf(declarationOf(this.src, head)) !== undefined
650
985
  if (this.isSameFileObject(receiver)) return undefined
651
- return { name, lazy: !EAGER_ITERATION.has(name) && isIterator(receiver) }
986
+ return { name, lazy: !EAGER_ITERATION.has(name) && isIterator(this.src, receiver), imported }
652
987
  }
653
988
 
654
989
  private visit(node: ts.Node, outcome: Outcome): void {
@@ -674,17 +1009,33 @@ class Reach {
674
1009
  }
675
1010
 
676
1011
  private call(node: ts.CallExpression | ts.NewExpression, outcome: Outcome): void {
1012
+ // `hook?.(…)`, `x?.y(…)` on a receiver a constant makes null or undefined: the chain stops there, and neither
1013
+ // the call nor its arguments run.
1014
+ if (shortCircuitsOnConstant(this.src, node)) return
677
1015
  const callee = unwrap(node.expression)
1016
+ // A gate's call counts wherever it RUNS on the handler's path, whatever a `try` around it does with its
1017
+ // failure; one in a function that never runs (a same-file no-op, a lazy iterator, a timer, a `.catch`
1018
+ // handler) does not.
678
1019
  const name = gateName(this.src, callee)
679
- if (name) this.calls.add(name)
1020
+ if (name && outcome.runs) this.calls.add(name)
680
1021
  // `authorize` throws synchronously, so its denial reaches the outcome wherever a throw here does.
681
1022
  if (outcome.thrown && this.isAuthorize(callee)) this.authorize = true
682
1023
  // The promise this call returns reaches the outcome only when it is awaited or returned on the spot.
683
1024
  const settled = settledBy(node)
684
1025
  const result = settled === 'await' ? outcome.thrown : settled === 'return' ? outcome.returned : false
1026
+ // A function handed to an imported callee may run synchronously inside it (a tracing span, an
1027
+ // AsyncLocalStorage.run), so its denial may come out as a throw from the call rather than as a rejection of
1028
+ // what the call returns. A returned call carries it only where a throw at the call also reaches the outcome:
1029
+ // not inside a `try` whose `catch` swallows, where `return wrap(() => authorize(…))` passed before.
1030
+ // An async function literal cannot throw synchronously out of the call (its denial rejects its promise), so the
1031
+ // condition applies only to a sync one.
1032
+ const handedResult = (fn: ts.FunctionLikeDeclaration): boolean =>
1033
+ settled === 'return' && !isAsync(fn) ? result && outcome.thrown : result
685
1034
  // Called directly, a sync function throws into this point; an async one only rejects its promise.
686
1035
  const direct = (fn: ts.FunctionLikeDeclaration): Outcome =>
687
- isAsync(fn) ? { thrown: result, returned: result } : { thrown: outcome.thrown, returned: result }
1036
+ isAsync(fn)
1037
+ ? { thrown: result, returned: result, runs: outcome.runs }
1038
+ : { thrown: outcome.thrown, returned: result, runs: outcome.runs }
688
1039
  if (isFunctionLiteral(callee)) this.invoke(callee, direct(callee))
689
1040
  else {
690
1041
  this.visit(callee, outcome)
@@ -697,21 +1048,46 @@ class Reach {
697
1048
  // place, so it throws through the call; a lazy one on an iterator runs nothing. A callee whose code is in
698
1049
  // this file is not followed through its parameter, so what it is handed counts for nothing.
699
1050
  const method = this.iterationMethod(callee)
700
- const handed = (fn: ts.FunctionLikeDeclaration): Outcome => {
701
- if (method !== undefined)
702
- return isAsync(fn) || method.lazy ? LOST : { thrown: outcome.thrown, returned: false }
703
- if (this.isSameFile(callee)) return LOST
704
- return result ? HANDLER_OUTCOME : LOST
1051
+ const allOf = method?.name === 'map' && !method.lazy ? promiseAllOf(this.src, node) : undefined
1052
+ const handed = (fn: ts.FunctionLikeDeclaration, index: number): Outcome => {
1053
+ if (method !== undefined) {
1054
+ // Only the callback is called: argument 0 (Array.from's mapper is argument 1). Another function
1055
+ // argument is a `thisArg`, which is never invoked.
1056
+ if (index !== (method.name === 'from' ? 1 : 0)) return NEVER
1057
+ if (method.lazy) return NEVER
1058
+ // `await Promise.all(xs.map(cb))`: the array map returns is what Promise.all settles, and it rejects
1059
+ // with the first rejection, so what each callback RETURNS reaches the Promise.all call's own result:
1060
+ // an async callback's promise, or the promise a sync one returns (`xs.map((x) => db.withTenant(…))`).
1061
+ // A sync callback's throw still goes up through map. Only Promise.all: allSettled never rejects, and
1062
+ // any and race settle on another promise's outcome.
1063
+ if (allOf !== undefined) {
1064
+ const settledAll = settledBy(allOf)
1065
+ const reaches =
1066
+ settledAll === 'await' ? outcome.thrown : settledAll === 'return' && outcome.returned
1067
+ if (isAsync(fn)) return { thrown: reaches, returned: reaches, runs: outcome.runs }
1068
+ return { thrown: outcome.thrown, returned: reaches, runs: outcome.runs }
1069
+ }
1070
+ if (isAsync(fn)) return dropped(outcome)
1071
+ // A sync callback runs in place on an array. On a receiver whose head is an import, the same name may
1072
+ // be a library's (a curried `R.forEach`, a query builder's `map`) that runs it later or not at all,
1073
+ // so it is trusted no further than any imported callee: only when the call's result is settled.
1074
+ if (method.imported && !handedResult(fn)) return dropped(outcome)
1075
+ return { thrown: outcome.thrown, returned: false, runs: outcome.runs }
1076
+ }
1077
+ // `.then(onFulfilled, onRejected)`: the second runs only on a rejection, as a `.catch` handler does.
1078
+ if (index === 1 && memberName(callee) === 'then') return NEVER
1079
+ if (this.isSameFile(callee) || neverCarriesFailure(this.src, callee)) return NEVER
1080
+ return handedResult(fn) ? { ...HANDLER_OUTCOME, runs: outcome.runs } : dropped(outcome)
705
1081
  }
706
- for (const argument of node.arguments ?? []) {
1082
+ node.arguments?.forEach((argument, index) => {
707
1083
  const a = unwrap(argument)
708
- if (isFunctionLiteral(a)) this.invoke(a, handed(a))
1084
+ if (isFunctionLiteral(a)) this.invoke(a, handed(a, index))
709
1085
  else {
710
1086
  this.visit(a, outcome)
711
1087
  const local = this.localFunction(a)
712
- if (local) this.invoke(local, handed(local))
1088
+ if (local) this.invoke(local, handed(local, index))
713
1089
  }
714
- }
1090
+ })
715
1091
  }
716
1092
 
717
1093
  private localFunction(e: ts.Expression): ts.FunctionLikeDeclaration | undefined {
@@ -777,8 +1153,9 @@ class Reach {
777
1153
  (!alwaysExits(this.src, s.catchClause.block) || leavesBlock(s.catchClause.block, true))
778
1154
  const thrown = outcome.thrown && !finallyMayLeave
779
1155
  const returned = outcome.returned && !finallyMayLeave
780
- this.statements(s.tryBlock.statements, { thrown: thrown && !catchSwallows, returned })
781
- if (s.catchClause) this.statements(s.catchClause.block.statements, { thrown, returned })
1156
+ const runs = outcome.runs
1157
+ this.statements(s.tryBlock.statements, { thrown: thrown && !catchSwallows, returned, runs })
1158
+ if (s.catchClause) this.statements(s.catchClause.block.statements, { thrown, returned, runs })
782
1159
  if (s.finallyBlock) this.statements(s.finallyBlock.statements, outcome)
783
1160
  } else if (ts.isWhileStatement(s)) {
784
1161
  const condition = constantTruth(this.src, s.expression)
@@ -827,21 +1204,127 @@ const EAGER_ITERATION: ReadonlySet<string> = new Set([
827
1204
  'reduce',
828
1205
  'reduceRight',
829
1206
  'some',
1207
+ // A comparator: called in place, and an async one's promise is read as a number (NaN), never awaited.
1208
+ 'sort',
1209
+ 'toSorted',
830
1210
  ])
831
1211
 
832
1212
  /** Every array iteration method: on an array all run in place; on an iterator `filter`, `flatMap`, `map` are lazy. */
833
1213
  const ARRAY_ITERATION: ReadonlySet<string> = new Set([...EAGER_ITERATION, 'filter', 'flatMap', 'map'])
834
1214
 
835
1215
  /** A receiver that is visibly an iterator: `xs.values()`, `xs.keys()`, `xs.entries()` or `Iterator.from(…)`. */
836
- function isIterator(receiver: ts.Expression): boolean {
1216
+ function isIterator(src: Source, receiver: ts.Expression): boolean {
837
1217
  const e = unwrap(receiver)
838
1218
  if (!ts.isCallExpression(e) || !ts.isPropertyAccessExpression(e.expression)) return false
839
1219
  const name = e.expression.name.text
840
- if (name === 'values' || name === 'keys' || name === 'entries') return true
841
1220
  const target = unwrap(e.expression.expression)
1221
+ // `Object.entries(m)` and its siblings return arrays, not iterators.
1222
+ if (ts.isIdentifier(target) && target.text === 'Object' && declarationOf(src, target) === undefined) return false
1223
+ if (name === 'values' || name === 'keys' || name === 'entries') return true
842
1224
  return name === 'from' && ts.isIdentifier(target) && target.text === 'Iterator'
843
1225
  }
844
1226
 
1227
+ /** The member a callee names, `x.name` or `x['name']`; undefined for any other callee. */
1228
+ function memberName(callee: ts.Expression): string | undefined {
1229
+ if (ts.isPropertyAccessExpression(callee)) return callee.name.text
1230
+ if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
1231
+ return callee.argumentExpression.text
1232
+ }
1233
+ return undefined
1234
+ }
1235
+
1236
+ /** `Global.member` (or `Global['member']`), where `Global` is not declared or imported in this file. */
1237
+ function isGlobalMember(src: Source, callee: ts.Expression, global: string, member: string): boolean {
1238
+ if (memberName(callee) !== member) return false
1239
+ const target = unwrap((callee as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression)
1240
+ return ts.isIdentifier(target) && target.text === global && declarationOf(src, target) === undefined
1241
+ }
1242
+
1243
+ /** Globals that take a function and never hand its failure back: they run it later, or not at all. */
1244
+ const DETACHING_GLOBALS: ReadonlySet<string> = new Set([
1245
+ 'queueMicrotask',
1246
+ 'requestAnimationFrame',
1247
+ 'requestIdleCallback',
1248
+ 'setImmediate',
1249
+ 'setInterval',
1250
+ 'setTimeout',
1251
+ ])
1252
+
1253
+ /**
1254
+ * Methods, by name on any receiver, whose function argument's failure never comes out of the call's result: a
1255
+ * `.catch` handler runs only if the promise rejects, a `.finally` one after it has settled, and a listener when
1256
+ * an event fires.
1257
+ */
1258
+ const DETACHING_METHODS: ReadonlySet<string> = new Set([
1259
+ 'addEventListener',
1260
+ 'addListener',
1261
+ 'catch',
1262
+ 'finally',
1263
+ 'on',
1264
+ 'once',
1265
+ 'prependListener',
1266
+ 'prependOnceListener',
1267
+ ])
1268
+
1269
+ /**
1270
+ * A callee known not to carry the failure of a function handed to it out of its own result, awaited or not: a
1271
+ * timer or microtask (`setTimeout`, `queueMicrotask`, `process.nextTick`), `Promise.resolve`, which never calls a
1272
+ * function it is given, or a `.catch`, `.finally` or listener method (DETACHING_METHODS). Every other callee that
1273
+ * is neither same-file nor an iteration method is trusted when its result is settled (see the header).
1274
+ */
1275
+ function neverCarriesFailure(src: Source, callee: ts.Expression): boolean {
1276
+ if (ts.isIdentifier(callee)) {
1277
+ const decl = declarationOf(src, callee)
1278
+ if (decl === undefined) return DETACHING_GLOBALS.has(callee.text)
1279
+ const imported = valueImportOf(decl)
1280
+ if (imported?.kind !== 'named') return false
1281
+ // Next's `after` runs its callback once the response has been sent; Node's timers module exports the timers.
1282
+ if (imported.module === 'next/server') return imported.name === 'after' || imported.name === 'unstable_after'
1283
+ return TIMER_MODULES.has(imported.module) && DETACHING_GLOBALS.has(imported.name)
1284
+ }
1285
+ const name = memberName(callee)
1286
+ if (name !== undefined && DETACHING_METHODS.has(name)) return true
1287
+ // `globalThis.setTimeout`, `self.queueMicrotask`, `window.setTimeout`, and `timers.setTimeout` through a namespace
1288
+ // import of Node's timers module.
1289
+ if (name !== undefined && DETACHING_GLOBALS.has(name)) {
1290
+ const target = unwrap((callee as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression)
1291
+ if (ts.isIdentifier(target)) {
1292
+ const decl = declarationOf(src, target)
1293
+ if (decl === undefined) return GLOBAL_OBJECTS.has(target.text)
1294
+ const imported = valueImportOf(decl)
1295
+ if (imported?.kind === 'namespace' && TIMER_MODULES.has(imported.module)) return true
1296
+ }
1297
+ }
1298
+ return isGlobalMember(src, callee, 'process', 'nextTick') || isGlobalMember(src, callee, 'Promise', 'resolve')
1299
+ }
1300
+
1301
+ /** Node's modules that export the timer functions under their global names. */
1302
+ const TIMER_MODULES: ReadonlySet<string> = new Set(['timers', 'node:timers'])
1303
+
1304
+ /** The names the global object goes by. */
1305
+ const GLOBAL_OBJECTS: ReadonlySet<string> = new Set(['globalThis', 'self', 'window'])
1306
+
1307
+ /**
1308
+ * The `Promise.all(…)` call `node` is the first argument of (through parentheses and type assertions), when
1309
+ * `Promise` is the global; undefined otherwise.
1310
+ */
1311
+ function promiseAllOf(src: Source, node: ts.CallExpression | ts.NewExpression): ts.CallExpression | undefined {
1312
+ let child: ts.Node = node
1313
+ let parent: ts.Node = node.parent
1314
+ while (
1315
+ ts.isParenthesizedExpression(parent) ||
1316
+ ts.isAsExpression(parent) ||
1317
+ ts.isSatisfiesExpression(parent) ||
1318
+ ts.isNonNullExpression(parent) ||
1319
+ ts.isTypeAssertionExpression(parent)
1320
+ ) {
1321
+ child = parent
1322
+ parent = parent.parent
1323
+ }
1324
+ if (!ts.isCallExpression(parent) || parent.arguments[0] !== child) return undefined
1325
+ return isGlobalMember(src, unwrap(parent.expression), 'Promise', 'all') ? parent : undefined
1326
+ }
1327
+
845
1328
  /** The variable declaration a declared name belongs to, through destructuring; undefined for a parameter. */
846
1329
  function variableOf(decl: ts.Declaration): ts.VariableDeclaration | undefined {
847
1330
  let node: ts.Node = decl
@@ -1249,6 +1732,26 @@ function constantlyNonNullish(src: Source, expression: ts.Expression, depth = 0)
1249
1732
  return constantTruth(src, e) !== undefined
1250
1733
  }
1251
1734
 
1735
+ /** Whether the value is a constant known to be null or undefined: `null`, `void …`, `undefined`, or a const of one. */
1736
+ function constantlyNullish(src: Source, expression: ts.Expression, depth = 0): boolean {
1737
+ const e = unwrap(expression)
1738
+ if (e.kind === ts.SyntaxKind.NullKeyword || e.kind === ts.SyntaxKind.VoidExpression) return true
1739
+ if (!ts.isIdentifier(e)) return false
1740
+ if (e.text === 'undefined' && !declarationOf(src, e)) return true
1741
+ const init = constInitializer(src, e, depth)
1742
+ return init !== undefined && constantlyNullish(src, init, depth + 1)
1743
+ }
1744
+
1745
+ /** A call in an optional chain (`a?.(…)`, `a?.b(…)`, `a?.b.c(…)`) whose optional link's receiver is constantly nullish. */
1746
+ function shortCircuitsOnConstant(src: Source, node: ts.CallExpression | ts.NewExpression): boolean {
1747
+ let link: ts.Expression = node
1748
+ while (ts.isCallExpression(link) || ts.isPropertyAccessExpression(link) || ts.isElementAccessExpression(link)) {
1749
+ if (link.questionDotToken && constantlyNullish(src, link.expression)) return true
1750
+ link = unwrap(link.expression)
1751
+ }
1752
+ return false
1753
+ }
1754
+
1252
1755
  function isShortCircuit(kind: ts.SyntaxKind): boolean {
1253
1756
  return (
1254
1757
  kind === ts.SyntaxKind.AmpersandAmpersandToken ||
@@ -1362,7 +1865,9 @@ function breaksOut(body: ts.Node, labels: readonly string[], unlabeled: boolean,
1362
1865
  function opensWithSimulated404(src: Source, fn: ts.FunctionLikeDeclaration): boolean {
1363
1866
  if (!fn.body || !ts.isBlock(fn.body)) return false
1364
1867
  if (!fn.parameters.every(runsNothing)) return false
1365
- const [first] = fn.body.statements
1868
+ if (assignsGateGlobal(src.sf)) return false
1869
+ // A directive prologue (`'use strict'`) runs nothing, so the gate may follow it.
1870
+ const first = fn.body.statements.find((s) => !(ts.isExpressionStatement(s) && ts.isStringLiteral(s.expression)))
1366
1871
  if (!first || !ts.isIfStatement(first)) return false
1367
1872
  const condition = unwrap(first.expression)
1368
1873
  if (!ts.isPrefixUnaryExpression(condition) || condition.operator !== ts.SyntaxKind.ExclamationToken) return false
@@ -1398,21 +1903,87 @@ function isInertExit(src: Source, s: ts.Statement): boolean {
1398
1903
  return name !== undefined && allowed.includes(name) && (e.arguments ?? []).every((a) => isLiteralValue(src, a))
1399
1904
  }
1400
1905
  if (ts.isThrowStatement(s)) {
1401
- // An imported constructor falls under the gate-name trust (gateName); a global must be an Error, since
1402
- // other globals (a WebSocket) do I/O when built.
1906
+ // A constructor runs code when built, so only one known to do nothing may be thrown: a global Error, or one
1907
+ // of SSSB's port errors imported from ERRORS_MODULE. Any other import (`throw new PurgeTenant('all')`) may
1908
+ // do anything, and other globals (a WebSocket) do I/O.
1403
1909
  const e = unwrap(s.expression)
1404
1910
  if (!ts.isNewExpression(e)) return false
1405
1911
  const name = globalOrGateName(src, e.expression)
1406
1912
  const global = isGlobal(src, e.expression)
1407
1913
  return (
1408
1914
  name !== undefined &&
1409
- (!global || GLOBAL_ERROR.test(name)) &&
1915
+ (global ? GLOBAL_ERROR.test(name) : importedFrom(src, e.expression) === ERRORS_MODULE) &&
1410
1916
  (e.arguments ?? []).every((a) => isLiteralValue(src, a))
1411
1917
  )
1412
1918
  }
1413
1919
  return false
1414
1920
  }
1415
1921
 
1922
+ /** The module whose errors (`NotFoundError` and the rest) the simulated-mode gate may throw. */
1923
+ const ERRORS_MODULE = '@sssb/kit/ports/errors'
1924
+
1925
+ /** The module a callee's head is a value import from, or undefined. */
1926
+ function importedFrom(src: Source, callee: ts.Expression): string | undefined {
1927
+ let head = unwrap(callee)
1928
+ while (ts.isPropertyAccessExpression(head)) head = unwrap(head.expression)
1929
+ return ts.isIdentifier(head) ? valueImportOf(declarationOf(src, head))?.module : undefined
1930
+ }
1931
+
1932
+ /**
1933
+ * Whether the file assigns to a global the gate's inert exit relies on (`Response`, `NextResponse`, `JSON`, an
1934
+ * `…Error`, or `globalThis`), or to a property of one (`Response.json = …`): an assignment replaces what the exit
1935
+ * builds with code of the file's own. Undeclared names only; a declared one is not the global anyway.
1936
+ */
1937
+ function assignsGateGlobal(sf: ts.SourceFile): boolean {
1938
+ let found = false
1939
+ const relied = (name: string) =>
1940
+ name === 'Response' ||
1941
+ name === 'NextResponse' ||
1942
+ name === 'JSON' ||
1943
+ name === 'globalThis' ||
1944
+ GLOBAL_ERROR.test(name)
1945
+ const visit = (node: ts.Node): void => {
1946
+ if (found) return
1947
+ if (
1948
+ ts.isBinaryExpression(node) &&
1949
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1950
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
1951
+ ) {
1952
+ let head = unwrap(node.left)
1953
+ while (ts.isPropertyAccessExpression(head) || ts.isElementAccessExpression(head))
1954
+ head = unwrap(head.expression)
1955
+ if (ts.isIdentifier(head) && relied(head.text) && !hasLocalDeclaration(sf, head.text)) found = true
1956
+ }
1957
+ ts.forEachChild(node, visit)
1958
+ }
1959
+ visit(sf)
1960
+ return found
1961
+ }
1962
+
1963
+ /** Whether `name` is declared anywhere in the file (a variable, function, class, parameter or import). */
1964
+ function hasLocalDeclaration(sf: ts.SourceFile, name: string): boolean {
1965
+ let found = false
1966
+ const visit = (node: ts.Node): void => {
1967
+ if (found) return
1968
+ const declared =
1969
+ (ts.isVariableDeclaration(node) ||
1970
+ ts.isFunctionDeclaration(node) ||
1971
+ ts.isClassDeclaration(node) ||
1972
+ ts.isParameter(node) ||
1973
+ ts.isImportSpecifier(node) ||
1974
+ ts.isImportClause(node) ||
1975
+ ts.isNamespaceImport(node) ||
1976
+ ts.isBindingElement(node)) &&
1977
+ node.name !== undefined &&
1978
+ ts.isIdentifier(node.name) &&
1979
+ node.name.text === name
1980
+ if (declared) found = true
1981
+ else ts.forEachChild(node, visit)
1982
+ }
1983
+ visit(sf)
1984
+ return found
1985
+ }
1986
+
1416
1987
  /** The callee's head is declared nowhere in the file. */
1417
1988
  function isGlobal(src: Source, callee: ts.Expression): boolean {
1418
1989
  let head = unwrap(callee)