@sssb/kit 0.0.0 → 0.3.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +212 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +313 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +248 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +93 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,1516 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript'
4
+
5
+ /**
6
+ * The analyser behind the authorization scan (each app's, ./app-exemptions.ts `scanApp`, and the kit's own over its
7
+ * fixture, `authorized-mutations.test.ts`), split out so the scan's POLICY (which roots, which exemptions:
8
+ * ./route-policy.ts and an app's own) is input rather than something this module knows. It reads route
9
+ * files with the TypeScript compiler's parser and binder, never a regex over their text, and judges EACH
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.
12
+ *
13
+ * WHAT "REACHES" MEANS. A call counts for a handler when it sits on that handler's own path:
14
+ *
15
+ * - in the handler's body, before any statement control cannot get past: `return`, `throw`, `break`,
16
+ * `continue`; an `if`, `try`, `switch` or labeled block every way through which does; a `while (true)` or
17
+ * `for (;;)` nothing breaks out of; a `do` whose body never falls through;
18
+ * - 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;
20
+ * nothing else is evaluated;
21
+ * - in a function literal passed as an argument (`withPortErrors(async () => { … })`), which the call is
22
+ * ASSUMED to invoke and to carry its failure in the call's own result. That is the wrapper idiom every route
23
+ * uses, and the one trust this module extends: it cannot read an imported wrapper to see whether it really
24
+ * 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;
26
+ * - in a function declared in the SAME module and called (or passed as an argument) from the handler's
27
+ * path, followed to any depth. A function that is only defined, or that the file reassigns or declares twice,
28
+ * is not followed;
29
+ * - where its denial reaches the handler's OUTCOME, the promise Next awaits. `authorize` throws synchronously, so a
30
+ * denial goes up through every synchronous frame, and is lost in three places:
31
+ * - an async boundary nobody awaits. In an `async` function a throw only rejects the function's promise, and a
32
+ * function handed to a call may run later (`.then`, a timer, an async wrapper). So a call into an `async`
33
+ * function, or one a function is handed to, carries the denial only when its result is `await`ed or returned
34
+ * on the spot (`settledBy`: `return`, an arrow's expression body; through parentheses, a type assertion, a
35
+ * ternary arm, the right of `&&`, `||`, `??` or a comma, or the left of `||` or `??`). A statement of its own,
36
+ * `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;
41
+ * - a `try` whose `catch` can do anything but rethrow (fall through, `return`, `break` or `continue` out of
42
+ * itself), or whose `finally` can leave in the throw's place. A promise the `try` returns (`return p`) is not
43
+ * caught; `return await p` throws inside it.
44
+ * (The rule is syntactic: a sync function counts as throwing in place, and an `authorize` named by
45
+ * `ScanOptions.authorizeModules` must throw synchronously too, as SSSB's does.)
46
+ *
47
+ * For a handler that is a wrapper's result (`export const POST = withX(fn)`), the wrapper call itself and
48
+ * its other arguments run once, when the module loads; only the functions handed to it run per request, so
49
+ * only those are the handler's path. The wrapper, being what Next calls, is trusted to carry their failure, unless
50
+ * its code is in this file, or it sits inside a wrapper whose code is.
51
+ *
52
+ * What is NOT followed, and so does not count: a call into another module (an imported helper that calls
53
+ * `authorize` inside it), a method on an object, a getter, a class body, a generator (calling one runs none of its
54
+ * body), and a parameter or destructuring default (it runs only when the value is missing). Each of those fails the
55
+ * handler.
56
+ *
57
+ * WHAT COUNTS AS `authorize`: a call to the `authorize` imported from one of `ScanOptions.authorizeModules`
58
+ * (SSSB's `@sssb/kit/authz/authorize` by default), under any local name or through a namespace import, by a
59
+ * value import (not `import type`, not a JSDoc `@import`). A local function that happens to be named
60
+ * `authorize` is followed like any other, so it counts only if it calls the real one.
61
+ *
62
+ * WHAT COUNTS AS A GATE'S NAME: the same rule, by binding (`gateName`). `withWebhookSecret`, `auth.updateProfile`,
63
+ * `isSimulated` count only when the name (the head of a dotted one) is a value import kept under the name it is
64
+ * exported by, from any module; a namespace member reads under its own name. A local look-alike
65
+ * (`const isSimulated = true`) or an alias (`import { identity as withWebhookSecret }`) is not the gate.
66
+ *
67
+ * A handler the module cannot resolve at all (a destructured export, a `let`, a reassigned function, an
68
+ * unresolvable re-export, a file that does not parse, a module that is not an ES module) is REFUSED with
69
+ * the reason, and a refusal is a failure.
70
+ */
71
+
72
+ /** The verbs that mutate. GET, HEAD and OPTIONS are never judged. */
73
+ const MUTATING_VERBS: readonly string[] = ['POST', 'PUT', 'PATCH', 'DELETE']
74
+
75
+ // Next.js routes route.ts/tsx/js/jsx/mjs. All of them, or the scan is bypassable by filename.
76
+ const ROUTE_FILE = /^route\.(?:mjs|[jt]sx?)$/
77
+
78
+ /** The extensions one extensionless module specifier can land on, in TypeScript's resolution or the bundler's. */
79
+ const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']
80
+
81
+ /**
82
+ * Every file the module TypeScript resolved to could have been, by the bundler's rules: `impl` with any source
83
+ * extension, `impl/index` with any, and `impl/package.json` (whose `main` the bundler may follow). For a resolved
84
+ * `impl/index.ts`, the module is `impl`.
85
+ */
86
+ function moduleCandidates(resolvedFile: string): string[] {
87
+ const stem = resolvedFile.replace(/\.[cm]?[jt]sx?$/, '')
88
+ const base = path.basename(stem) === 'index' ? path.dirname(stem) : stem
89
+ return [
90
+ ...SOURCE_EXTENSIONS.map((ext) => base + ext),
91
+ ...SOURCE_EXTENSIONS.map((ext) => path.join(base, `index${ext}`)),
92
+ path.join(base, 'package.json'),
93
+ ].filter((file) => existsSync(file))
94
+ }
95
+
96
+ export interface ScanRoot {
97
+ /** Human label: disambiguates identical route paths across roots. */
98
+ label: string
99
+ /** Where the walk starts. */
100
+ dir: string
101
+ /** Where exemption paths are measured from. A file outside it gets a `../` path no exemption can match. */
102
+ exemptDir: string
103
+ /**
104
+ * The tsconfig whose module resolution (its `paths`, its `moduleResolution`) re-exports and imported
105
+ * handlers are followed with. Without one, relative specifiers and packages resolve, aliases do not.
106
+ */
107
+ tsconfig?: string | undefined
108
+ }
109
+
110
+ /**
111
+ * What an exemption's gate requires of ONE handler. Each kind is checked per verb, and every name in it
112
+ * must be a value import in the route's module (see the header):
113
+ *
114
+ * - `wrapped-by`: the handler IS a call to one of `callees` (`export const POST = withWebhookSecret(…)`).
115
+ * For a guard that wraps the handler, reaching it is not enough: the guard has to be what Next calls.
116
+ * - `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.
121
+ */
122
+ export type Gate =
123
+ | { kind: 'wrapped-by'; callees: readonly string[] }
124
+ | { kind: 'calls'; callees: readonly string[] }
125
+ | { kind: 'opens-with-simulated-404' }
126
+
127
+ /** What the analyser found on one handler's path. */
128
+ export interface HandlerFacts {
129
+ /** A call to `authorize` imported from one of the scan's authorize modules is on the handler's path. */
130
+ reachesAuthorize: boolean
131
+ /** Gate name (`gateName`) of the call the handler IS (`export const POST = withX(…)` → `withX`), or null. */
132
+ wrappedBy: string | null
133
+ /** Gate name (`gateName`) of every call on the handler's path that has one (`auth.updateProfile`). */
134
+ calls: ReadonlySet<string>
135
+ /** The handler opens with the inert `if (!isSimulated)` gate and no parameter runs code (`opensWithSimulated404`). */
136
+ opensWithSimulated404: boolean
137
+ }
138
+
139
+ /** One exported mutating handler: its facts, or why it could not be read (a refusal is a failure). */
140
+ export type Handler =
141
+ { verb: string; facts: HandlerFacts; refusal?: never } | { verb: string; refusal: string; facts?: never }
142
+
143
+ export interface ScannedRoute {
144
+ root: string
145
+ /** Path relative to the root's `exemptDir`, `/`-separated. */
146
+ rel: string
147
+ file: string
148
+ /** One entry per exported mutating verb. Empty for a route that mutates nothing. */
149
+ handlers: Handler[]
150
+ }
151
+
152
+ export interface ScanOptions {
153
+ /** Module specifiers whose `authorize` export is the choke point. Default: SSSB's. */
154
+ authorizeModules?: readonly string[]
155
+ }
156
+
157
+ /** Every route file under every root, each with its exported mutating handlers analysed. */
158
+ export function scanRoutes(roots: readonly ScanRoot[], options: ScanOptions = {}): ScannedRoute[] {
159
+ const authorizeModules = options.authorizeModules ?? ['@sssb/kit/authz/authorize']
160
+ return roots.flatMap((root) => {
161
+ const scanner = new RootScanner(root, authorizeModules)
162
+ return routeFiles(root.dir).map((file) => ({
163
+ root: root.label,
164
+ rel: path.relative(root.exemptDir, file).split(path.sep).join('/'),
165
+ file,
166
+ handlers: scanner.handlers(file),
167
+ }))
168
+ })
169
+ }
170
+
171
+ function routeFiles(dir: string): string[] {
172
+ const out: string[] = []
173
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
174
+ 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)
177
+ }
178
+ return out.sort()
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------------------------------------
182
+ // Policy: exemptions and the gates they rest on.
183
+ // ---------------------------------------------------------------------------------------------------------
184
+
185
+ export interface Exemption {
186
+ reason: string
187
+ /** The gate the reason rests on. Checked on every exempted handler, per verb, in every root. */
188
+ mustMatch: Gate
189
+ }
190
+
191
+ export interface ScanPolicy {
192
+ /** Exemptions by path prefix, relative to a root's `exemptDir`. */
193
+ exemptPrefixes: Readonly<Record<string, Exemption>>
194
+ /** Exemptions by exact path. An exact entry wins over a prefix. */
195
+ exemptFiles: Readonly<Record<string, Exemption>>
196
+ /** Gates a non-exempt handler under a prefix must pass IN ADDITION to reaching `authorize`. */
197
+ requiredAlongside: Readonly<Record<string, Exemption>>
198
+ /** Appended to the "does not reach authorize" failure. */
199
+ hint?: string | undefined
200
+ }
201
+
202
+ export function exemptionFor(policy: ScanPolicy, rel: string): Exemption | undefined {
203
+ const exact = policy.exemptFiles[rel]
204
+ if (exact) return exact
205
+ const prefix = Object.keys(policy.exemptPrefixes).find((p) => rel.startsWith(p))
206
+ return prefix === undefined ? undefined : policy.exemptPrefixes[prefix]
207
+ }
208
+
209
+ function requiredFor(policy: ScanPolicy, rel: string): Exemption | undefined {
210
+ const prefix = Object.keys(policy.requiredAlongside).find((p) => rel.startsWith(p))
211
+ return prefix === undefined ? undefined : policy.requiredAlongside[prefix]
212
+ }
213
+
214
+ export function gateHolds(gate: Gate, facts: HandlerFacts): boolean {
215
+ switch (gate.kind) {
216
+ case 'wrapped-by':
217
+ return facts.wrappedBy !== null && gate.callees.includes(facts.wrappedBy)
218
+ case 'calls':
219
+ return gate.callees.some((callee) => facts.calls.has(callee))
220
+ case 'opens-with-simulated-404':
221
+ return facts.opensWithSimulated404
222
+ }
223
+ }
224
+
225
+ export function describeGate(gate: Gate): string {
226
+ const names = (callees: readonly string[]) => callees.map((c) => `${c}(…)`).join(' or ')
227
+ switch (gate.kind) {
228
+ case 'wrapped-by':
229
+ return `the handler is itself a call to an imported ${names(gate.callees)}, as in \`export const POST = ${gate.callees[0]}(…)\``
230
+ case 'calls':
231
+ return `the handler reaches a call to an imported ${names(gate.callees)} on its own path`
232
+ case 'opens-with-simulated-404':
233
+ return (
234
+ 'the handler takes no parameter that runs code (a default) and opens with ' +
235
+ '`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)'
237
+ )
238
+ }
239
+ }
240
+
241
+ /** Why `handler` fails the scan, or undefined if it passes. */
242
+ export function judge(route: ScannedRoute, handler: Handler, policy: ScanPolicy): string | undefined {
243
+ const where = `${route.root}: ${route.rel} ${handler.verb}`
244
+ if (handler.refusal !== undefined) {
245
+ return `${where} cannot be checked: ${handler.refusal}. The scan fails a handler it cannot follow rather than pass it.`
246
+ }
247
+ // An exemption is an alternative to authorize(...), never a ban on it: a handler under an exempted path that
248
+ // does not pass the gate is judged like any other, so one that authorizes passes.
249
+ const exemption = exemptionFor(policy, route.rel)
250
+ if (exemption && gateHolds(exemption.mustMatch, handler.facts)) return undefined
251
+ const required = requiredFor(policy, route.rel)
252
+ if (required && !gateHolds(required.mustMatch, handler.facts)) {
253
+ return `${where} must also satisfy: ${describeGate(required.mustMatch)}. ${required.reason}`
254
+ }
255
+ if (!handler.facts.reachesAuthorize && exemption) {
256
+ return (
257
+ `${where} sits under an exemption that holds only when ${describeGate(exemption.mustMatch)}, and this ` +
258
+ `handler does not: the exemption's justification does not hold here. Add the gate to THIS handler, or call ` +
259
+ `authorize(...). (A string, a comment, a look-alike, or the gate on another verb does not count.)`
260
+ )
261
+ }
262
+ if (!handler.facts.reachesAuthorize) {
263
+ return (
264
+ `${where} exports a mutating handler that does not reach authorize(...) on its own path, and the route is ` +
265
+ `not in the exemption map. A call in a string, a comment, another handler, a dead branch, an uncalled ` +
266
+ `function or another module does not count, nor does one whose denial cannot reach the handler: in an ` +
267
+ `async function or a callback whose promise the handler neither awaits nor returns, in a callback handed ` +
268
+ `to a function of this file, or in a try whose catch does not rethrow. Call authorize(...) in this handler ` +
269
+ `(or in a function in this file that it calls, awaiting it if it is async), or, only if it is genuinely ` +
270
+ `not a per-actor product mutation, add a justified exemption.` +
271
+ (policy.hint ? ` ${policy.hint}` : '')
272
+ )
273
+ }
274
+ return undefined
275
+ }
276
+
277
+ // ---------------------------------------------------------------------------------------------------------
278
+ // Analysis.
279
+ // ---------------------------------------------------------------------------------------------------------
280
+
281
+ interface Source {
282
+ fileName: string
283
+ sf: ts.SourceFile
284
+ checker: ts.TypeChecker
285
+ /** Symbols the file assigns to (`POST = …`, `check = …`, `x++`): never trusted as a handler or helper. */
286
+ reassigned: ReadonlySet<ts.Symbol>
287
+ }
288
+
289
+ /** What an exported name is bound to. */
290
+ type Binding =
291
+ | { kind: 'decl'; src: Source; decl: ts.Declaration }
292
+ | { kind: 'module'; src: Source; specifier: string; name: string }
293
+ | { kind: 'refused'; reason: string }
294
+
295
+ /** A handler resolved to code: a function Next calls, or a call whose result Next calls. */
296
+ type HandlerNode = { src: Source; fn: ts.FunctionLikeDeclaration } | { src: Source; call: ts.CallExpression }
297
+
298
+ type Refusal = { reason: string }
299
+
300
+ // Parse and bind one file at a time: no lib, no import resolution. Every question asked of the checker is
301
+ // about a binding in the file itself; following an import is this module's job, done explicitly below.
302
+ const ANALYSIS_OPTIONS: ts.CompilerOptions = {
303
+ noResolve: true,
304
+ noLib: true,
305
+ types: [],
306
+ allowJs: true,
307
+ jsx: ts.JsxEmit.Preserve,
308
+ target: ts.ScriptTarget.ESNext,
309
+ module: ts.ModuleKind.ESNext,
310
+ noEmit: true,
311
+ }
312
+
313
+ const DEFAULT_RESOLUTION: ts.CompilerOptions = {
314
+ module: ts.ModuleKind.ESNext,
315
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
316
+ allowJs: true,
317
+ }
318
+
319
+ class RootScanner {
320
+ private readonly sources = new Map<string, Source | string>()
321
+ private readonly resolution: ts.CompilerOptions
322
+ private readonly authorizeModules: readonly string[]
323
+
324
+ constructor(root: ScanRoot, authorizeModules: readonly string[]) {
325
+ this.authorizeModules = authorizeModules
326
+ this.resolution = root.tsconfig ? readCompilerOptions(root.tsconfig) : DEFAULT_RESOLUTION
327
+ }
328
+
329
+ handlers(file: string): Handler[] {
330
+ const src = this.load(file)
331
+ if (typeof src === 'string') return [{ verb: '*', refusal: src }]
332
+ return this.mutatingExports(src, new Set()).map(([verb, binding]) => {
333
+ const node = this.handlerOf(binding, new Set())
334
+ return 'reason' in node ? { verb, refusal: node.reason } : { verb, facts: this.facts(node) }
335
+ })
336
+ }
337
+
338
+ private load(fileName: string): Source | string {
339
+ const cached = this.sources.get(fileName)
340
+ if (cached !== undefined) return cached
341
+ const program = ts.createProgram({ rootNames: [fileName], options: ANALYSIS_OPTIONS })
342
+ const sf = program.getSourceFile(fileName)
343
+ let result: Source | string
344
+ if (!sf) result = 'the file could not be read'
345
+ else if (program.getSyntacticDiagnostics(sf).length > 0) {
346
+ const [first] = program.getSyntacticDiagnostics(sf)
347
+ result = `the file does not parse (${ts.flattenDiagnosticMessageText(first?.messageText, ' ')})`
348
+ } else {
349
+ const checker = program.getTypeChecker()
350
+ // `export =` makes TypeScript call the file a module, but it compiles to `module.exports =`, and Next
351
+ // serves the handlers on it: it is CommonJS for this purpose.
352
+ const exportEquals = sf.statements.some((s) => ts.isExportAssignment(s) && s.isExportEquals)
353
+ if (!ts.isExternalModule(sf) || exportEquals || usesCommonJsExports(sf, checker)) {
354
+ result =
355
+ 'the file is not an ES module, or uses `export =`, `module.exports` or `exports`, which the scan ' +
356
+ 'does not read (route modules are ES modules)'
357
+ } else result = { fileName, sf, checker, reassigned: reassignedSymbols(sf, checker) }
358
+ }
359
+ this.sources.set(fileName, result)
360
+ return result
361
+ }
362
+
363
+ private resolve(from: Source, specifier: string): Source | string {
364
+ const resolved = ts.resolveModuleName(specifier, from.fileName, this.resolution, ts.sys).resolvedModule
365
+ if (!resolved) return `'${specifier}' does not resolve from ${from.fileName}`
366
+ if (/\.d\.[cm]?ts$/.test(resolved.resolvedFileName)) {
367
+ return `'${specifier}' resolves to a declaration file (${resolved.resolvedFileName}), which has no handler body to read`
368
+ }
369
+ // TypeScript and Next's bundler do not pick the same file from every layout: TypeScript prefers `impl.ts`
370
+ // where the bundler may load `impl.js` beside it, skips `impl.mjs` for an extensionless specifier and reads
371
+ // `impl/index.ts` instead, and follows a package.json's `types` where the bundler follows `main`. With more
372
+ // than one candidate for the one module, the scan cannot know which file is served, so it reads none.
373
+ const candidates = moduleCandidates(resolved.resolvedFileName)
374
+ if (candidates.length > 1) {
375
+ const names = candidates.map((file) => path.relative(path.dirname(from.fileName), file)).join(', ')
376
+ return `'${specifier}' could load any of ${names}, and the scan cannot tell which Next serves`
377
+ }
378
+ const loaded = this.load(resolved.resolvedFileName)
379
+ return typeof loaded === 'string' ? `'${specifier}' (${resolved.resolvedFileName}): ${loaded}` : loaded
380
+ }
381
+
382
+ /** `[verb, binding]` for every mutating verb the module exports, through `export *` as well. */
383
+ private mutatingExports(src: Source, seen: Set<string>): Array<[string, Binding]> {
384
+ const { named, stars } = exportsOf(src)
385
+ const out = [...named].filter(([name]) => MUTATING_VERBS.includes(name))
386
+ if (seen.has(src.fileName)) return out
387
+ seen.add(src.fileName)
388
+ for (const specifier of stars) {
389
+ const target = this.resolve(src, specifier)
390
+ if (typeof target === 'string') {
391
+ const reason = `\`export * from '${specifier}'\` cannot be followed (${target}), so which verbs it exports is unknown`
392
+ out.push(['*', { kind: 'refused', reason }])
393
+ continue
394
+ }
395
+ for (const [verb, binding] of this.mutatingExports(target, seen)) {
396
+ if (!out.some(([known]) => known === verb)) out.push([verb, binding])
397
+ }
398
+ }
399
+ return out
400
+ }
401
+
402
+ /** The binding a module exports under `name`, through `export *` as well. */
403
+ private exportNamed(src: Source, name: string, seen: Set<string>): Binding | undefined {
404
+ const { named, stars } = exportsOf(src)
405
+ const direct = named.get(name)
406
+ if (direct) return direct
407
+ if (seen.has(src.fileName)) return undefined
408
+ seen.add(src.fileName)
409
+ for (const specifier of stars) {
410
+ const target = this.resolve(src, specifier)
411
+ if (typeof target === 'string') return { kind: 'refused', reason: target }
412
+ const found = this.exportNamed(target, name, seen)
413
+ if (found) return found
414
+ }
415
+ return undefined
416
+ }
417
+
418
+ private handlerOf(binding: Binding, seen: Set<unknown>): HandlerNode | Refusal {
419
+ if (binding.kind === 'refused') return { reason: binding.reason }
420
+ if (binding.kind === 'module') {
421
+ const target = this.resolve(binding.src, binding.specifier)
422
+ if (typeof target === 'string') return { reason: `the handler is re-exported from ${target}` }
423
+ const key = `${target.fileName}\0${binding.name}`
424
+ if (seen.has(key)) return { reason: `the re-export of \`${binding.name}\` leads back to itself` }
425
+ seen.add(key)
426
+ const next = this.exportNamed(target, binding.name, new Set())
427
+ if (!next) return { reason: `'${binding.specifier}' has no export named \`${binding.name}\`` }
428
+ return this.handlerOf(next, seen)
429
+ }
430
+ const { src, decl } = binding
431
+ if (seen.has(decl)) return { reason: 'the handler is defined in terms of itself' }
432
+ seen.add(decl)
433
+ if (ts.isFunctionDeclaration(decl)) {
434
+ if (!decl.body) return { reason: 'the handler is a declaration with no body' }
435
+ if (isReassigned(src, decl)) {
436
+ return {
437
+ reason: 'the handler is a function the file reassigns, so the declaration is not what Next calls',
438
+ }
439
+ }
440
+ if (isRedeclared(decl)) {
441
+ return {
442
+ reason:
443
+ 'the handler is declared more than once in its scope, and the last declaration is the one that ' +
444
+ 'runs; declare it once',
445
+ }
446
+ }
447
+ return { src, fn: decl }
448
+ }
449
+ if (ts.isVariableDeclaration(decl)) {
450
+ if (!isConst(decl)) {
451
+ return {
452
+ reason:
453
+ 'the handler is a `let` or `var`, which can be reassigned after the binding the scan reads; ' +
454
+ 'declare it `const` or as a function',
455
+ }
456
+ }
457
+ if (!decl.initializer) return { reason: 'the handler has no initializer' }
458
+ return this.handlerFromExpression(src, decl.initializer, seen)
459
+ }
460
+ if (ts.isExportAssignment(decl) && !decl.isExportEquals)
461
+ return this.handlerFromExpression(src, decl.expression, seen)
462
+ return { reason: `the handler is a ${ts.SyntaxKind[decl.kind]}, not a function` }
463
+ }
464
+
465
+ private handlerFromExpression(src: Source, expression: ts.Expression, seen: Set<unknown>): HandlerNode | Refusal {
466
+ const e = unwrap(expression)
467
+ if (isFunctionLiteral(e)) return { src, fn: e }
468
+ if (ts.isCallExpression(e)) return { src, call: e }
469
+ if (ts.isIdentifier(e)) {
470
+ const decl = declarationOf(src, e)
471
+ if (!decl) return { reason: `\`${e.text}\` is not declared in this file` }
472
+ return this.handlerOf(bindingOfDeclaration(src, decl), seen)
473
+ }
474
+ return {
475
+ reason:
476
+ `the handler is a ${ts.SyntaxKind[e.kind]}, which the scan cannot follow; export a function, ` +
477
+ 'or a call that wraps one',
478
+ }
479
+ }
480
+
481
+ private facts(node: HandlerNode): HandlerFacts {
482
+ const reach = new Reach(node.src, this.authorizeModules)
483
+ if ('fn' in node) {
484
+ reach.invoke(node.fn)
485
+ return {
486
+ reachesAuthorize: reach.authorize,
487
+ wrappedBy: null,
488
+ calls: reach.calls,
489
+ opensWithSimulated404: opensWithSimulated404(node.src, node.fn),
490
+ }
491
+ }
492
+ reach.wrapped(node.call)
493
+ return {
494
+ reachesAuthorize: reach.authorize,
495
+ wrappedBy: gateName(node.src, node.call.expression) ?? null,
496
+ calls: reach.calls,
497
+ opensWithSimulated404: false,
498
+ }
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Where a failure at one point of the walk goes: whether a throw there, or a rejection of the promise the current
504
+ * function returns, reaches the handler's outcome (what Next awaits). A handler's own body reaches it both ways.
505
+ */
506
+ interface Outcome {
507
+ /** A throw here reaches the handler's outcome. In an async function, that is a rejection of its promise. */
508
+ thrown: boolean
509
+ /** A promise the current function returns reaches the handler's outcome, so a rejection of it does. */
510
+ returned: boolean
511
+ }
512
+
513
+ const HANDLER_OUTCOME: Outcome = { thrown: true, returned: true }
514
+ const LOST: Outcome = { thrown: false, returned: false }
515
+
516
+ /** Walks one handler's path, collecting the calls on it. One instance per handler, never shared. */
517
+ class Reach {
518
+ readonly calls = new Set<string>()
519
+ authorize = false
520
+ /** Each function walked, per outcome it was walked under: a cycle stops, a second path that reaches does not. */
521
+ private readonly invoked = new Map<ts.Node, Set<string>>()
522
+
523
+ private readonly src: Source
524
+ private readonly authorizeModules: readonly string[]
525
+
526
+ constructor(src: Source, authorizeModules: readonly string[]) {
527
+ this.src = src
528
+ this.authorizeModules = authorizeModules
529
+ }
530
+
531
+ /** Walks `fn`'s body, where `outcome` says what reaches the handler's outcome from inside it. */
532
+ invoke(fn: ts.FunctionLikeDeclaration, outcome: Outcome = HANDLER_OUTCOME): void {
533
+ const key = `${outcome.thrown}/${outcome.returned}`
534
+ const seen = this.invoked.get(fn) ?? new Set<string>()
535
+ if (seen.has(key)) return
536
+ seen.add(key)
537
+ this.invoked.set(fn, seen)
538
+ // Calling a generator runs none of its body; it only makes an iterator.
539
+ if (fn.asteriskToken) return
540
+ // Parameter defaults are not visited: one runs only when its argument is missing, which for a handler
541
+ // depends on what Next passes, and for a helper on the caller. Not counting them fails closed.
542
+ if (!fn.body) return
543
+ if (ts.isBlock(fn.body)) this.statements(fn.body.statements, outcome)
544
+ else this.visit(fn.body, outcome)
545
+ }
546
+
547
+ /**
548
+ * A handler that is a call's result. The call and its non-function arguments ran when the module loaded;
549
+ * per request, only the functions handed to it run (a nested wrapper's, too: `withA(withB(fn))`). The wrapper
550
+ * is what Next calls, and is trusted to carry their failure to Next (see the header). A wrapper declared in
551
+ * this file is not: the scan can read it, but does not follow a function through its parameter, so what it
552
+ * is handed counts for nothing, and so does what a wrapper inside it is handed.
553
+ */
554
+ wrapped(call: ts.CallExpression, outcome: Outcome = HANDLER_OUTCOME): void {
555
+ const own = this.isSameFile(call.expression) ? LOST : outcome
556
+ for (const argument of call.arguments) {
557
+ const a = unwrap(argument)
558
+ if (isFunctionLiteral(a)) this.invoke(a, own)
559
+ else if (ts.isCallExpression(a)) this.wrapped(a, own)
560
+ else {
561
+ const local = this.localFunction(a)
562
+ if (local) this.invoke(local, own)
563
+ }
564
+ }
565
+ }
566
+
567
+ /**
568
+ * A callee whose code is in this file, which the scan could read but does not follow through a parameter, so it
569
+ * is never trusted the way an imported wrapper is. Its head (through `o.run`, `o['run']`, `new C`, `mk()`,
570
+ * `await`, either arm of a ternary, either side of `&&`, `||`, `??` or a comma) is a function, class or object
571
+ * literal, an array literal holding one, or a name declared here as a function or class, as a variable or
572
+ * destructured name whose initializer is any of those, or as anything the file assigns to. A parameter, an
573
+ * import, a global, and a local holding anything else (`const client = await connect()`) are not: their code
574
+ * is out of the scan's sight either way.
575
+ */
576
+ private isSameFile(callee: ts.Expression, seen: Set<ts.Node> = new Set()): boolean {
577
+ let e = unwrap(callee)
578
+ while (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) e = unwrap(e.expression)
579
+ if (isFunctionLiteral(e) || ts.isClassExpression(e) || ts.isObjectLiteralExpression(e)) return true
580
+ if (ts.isArrayLiteralExpression(e)) {
581
+ return e.elements.some((element) => !ts.isOmittedExpression(element) && this.isSameFile(element, seen))
582
+ }
583
+ if (ts.isCallExpression(e) || ts.isNewExpression(e) || ts.isAwaitExpression(e) || ts.isSpreadElement(e)) {
584
+ return this.isSameFile(e.expression, seen)
585
+ }
586
+ if (ts.isConditionalExpression(e))
587
+ return this.isSameFile(e.whenTrue, seen) || this.isSameFile(e.whenFalse, seen)
588
+ if (ts.isBinaryExpression(e)) return this.isSameFile(e.left, seen) || this.isSameFile(e.right, seen)
589
+ if (!ts.isIdentifier(e)) return false
590
+ const symbol = this.src.checker.getSymbolAtLocation(e)
591
+ if (symbol !== undefined && this.src.reassigned.has(symbol)) return true
592
+ const decl = declarationOf(this.src, e)
593
+ if (decl === undefined) return false
594
+ if (ts.isFunctionDeclaration(decl) || ts.isClassDeclaration(decl)) return true
595
+ const variable = variableOf(decl)
596
+ if (variable?.initializer === undefined) return false
597
+ // A name defined in terms of itself (`const a = b(); const b = a()`) fails closed.
598
+ if (seen.has(variable)) return true
599
+ seen.add(variable)
600
+ return this.isSameFile(variable.initializer, seen)
601
+ }
602
+
603
+ /**
604
+ * Whether a method's receiver is an object whose code is in this file (an object or class literal, a `new` of a
605
+ * same-file class, a class, or a variable or destructured name holding one), so that its `forEach` is its own
606
+ * and not an array's. A call's or an `await`'s result is taken for data, as an array is.
607
+ */
608
+ private isSameFileObject(receiver: ts.Expression, seen: Set<ts.Node> = new Set()): boolean {
609
+ let e = unwrap(receiver)
610
+ while (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) e = unwrap(e.expression)
611
+ if (ts.isObjectLiteralExpression(e) || ts.isClassExpression(e)) return true
612
+ if (ts.isNewExpression(e)) return this.isSameFile(e.expression)
613
+ if (ts.isConditionalExpression(e)) {
614
+ return this.isSameFileObject(e.whenTrue, seen) || this.isSameFileObject(e.whenFalse, seen)
615
+ }
616
+ if (ts.isBinaryExpression(e)) return this.isSameFileObject(e.left, seen) || this.isSameFileObject(e.right, seen)
617
+ if (!ts.isIdentifier(e)) return false
618
+ const decl = declarationOf(this.src, e)
619
+ if (decl === undefined) return false
620
+ if (ts.isClassDeclaration(decl)) return true
621
+ const variable = variableOf(decl)
622
+ if (variable?.initializer === undefined || seen.has(variable)) return false
623
+ seen.add(variable)
624
+ return this.isSameFileObject(variable.initializer, seen)
625
+ }
626
+
627
+ /**
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.
633
+ */
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
+ }
640
+ if (name === undefined || !ARRAY_ITERATION.has(name)) return undefined
641
+ const receiver = unwrap((callee as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression)
642
+ let head = receiver
643
+ for (;;) {
644
+ if (ts.isPropertyAccessExpression(head) || ts.isElementAccessExpression(head))
645
+ head = unwrap(head.expression)
646
+ else if (ts.isCallExpression(head)) head = unwrap(head.expression)
647
+ else break
648
+ }
649
+ if (ts.isIdentifier(head) && valueImportOf(declarationOf(this.src, head)) !== undefined) return undefined
650
+ if (this.isSameFileObject(receiver)) return undefined
651
+ return { name, lazy: !EAGER_ITERATION.has(name) && isIterator(receiver) }
652
+ }
653
+
654
+ private visit(node: ts.Node, outcome: Outcome): void {
655
+ // A function or class body runs only when called; a type never runs.
656
+ if (ts.isFunctionLike(node) || ts.isClassLike(node) || ts.isTypeNode(node)) return
657
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) return this.call(node, outcome)
658
+ // The initializer runs; a default inside a destructuring pattern runs only when the value is missing.
659
+ if (ts.isVariableDeclaration(node)) return node.initializer && this.visit(node.initializer, outcome)
660
+ // A condition always runs; only the branch it rules out is dead.
661
+ if (ts.isConditionalExpression(node)) {
662
+ const condition = constantTruth(this.src, node.condition)
663
+ this.visit(node.condition, outcome)
664
+ if (condition !== false) this.visit(node.whenTrue, outcome)
665
+ if (condition !== true) this.visit(node.whenFalse, outcome)
666
+ return
667
+ }
668
+ if (ts.isBinaryExpression(node) && isShortCircuit(node.operatorToken.kind)) {
669
+ this.visit(node.left, outcome)
670
+ if (!rightIsDead(this.src, node)) this.visit(node.right, outcome)
671
+ return
672
+ }
673
+ ts.forEachChild(node, (child) => this.visit(child, outcome))
674
+ }
675
+
676
+ private call(node: ts.CallExpression | ts.NewExpression, outcome: Outcome): void {
677
+ const callee = unwrap(node.expression)
678
+ const name = gateName(this.src, callee)
679
+ if (name) this.calls.add(name)
680
+ // `authorize` throws synchronously, so its denial reaches the outcome wherever a throw here does.
681
+ if (outcome.thrown && this.isAuthorize(callee)) this.authorize = true
682
+ // The promise this call returns reaches the outcome only when it is awaited or returned on the spot.
683
+ const settled = settledBy(node)
684
+ const result = settled === 'await' ? outcome.thrown : settled === 'return' ? outcome.returned : false
685
+ // Called directly, a sync function throws into this point; an async one only rejects its promise.
686
+ const direct = (fn: ts.FunctionLikeDeclaration): Outcome =>
687
+ isAsync(fn) ? { thrown: result, returned: result } : { thrown: outcome.thrown, returned: result }
688
+ if (isFunctionLiteral(callee)) this.invoke(callee, direct(callee))
689
+ else {
690
+ this.visit(callee, outcome)
691
+ const local = this.localFunction(callee)
692
+ if (local) this.invoke(local, direct(local))
693
+ }
694
+ // A function handed to a call is assumed to be invoked, and its failure to come out of the call's own result:
695
+ // the callee is not read, and may run it now or later (`.then`, a timer, an async wrapper). Two exceptions.
696
+ // An array's iteration method drops an async function's promise, awaited or not, and runs a sync one in
697
+ // place, so it throws through the call; a lazy one on an iterator runs nothing. A callee whose code is in
698
+ // this file is not followed through its parameter, so what it is handed counts for nothing.
699
+ 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
705
+ }
706
+ for (const argument of node.arguments ?? []) {
707
+ const a = unwrap(argument)
708
+ if (isFunctionLiteral(a)) this.invoke(a, handed(a))
709
+ else {
710
+ this.visit(a, outcome)
711
+ const local = this.localFunction(a)
712
+ if (local) this.invoke(local, handed(local))
713
+ }
714
+ }
715
+ }
716
+
717
+ private localFunction(e: ts.Expression): ts.FunctionLikeDeclaration | undefined {
718
+ if (!ts.isIdentifier(e)) return undefined
719
+ const decl = declarationOf(this.src, e)
720
+ if (!decl) return undefined
721
+ if (ts.isFunctionDeclaration(decl)) {
722
+ return decl.body && !isReassigned(this.src, decl) && !isRedeclared(decl) ? decl : undefined
723
+ }
724
+ if (ts.isVariableDeclaration(decl) && isConst(decl) && decl.initializer) {
725
+ const init = unwrap(decl.initializer)
726
+ if (isFunctionLiteral(init)) return init
727
+ }
728
+ return undefined
729
+ }
730
+
731
+ private isAuthorize(callee: ts.Expression): boolean {
732
+ if (ts.isIdentifier(callee)) {
733
+ const imported = valueImportOf(declarationOf(this.src, callee))
734
+ return (
735
+ imported?.kind === 'named' &&
736
+ imported.name === 'authorize' &&
737
+ this.authorizeModules.includes(imported.module)
738
+ )
739
+ }
740
+ if (
741
+ ts.isPropertyAccessExpression(callee) &&
742
+ callee.name.text === 'authorize' &&
743
+ ts.isIdentifier(callee.expression)
744
+ ) {
745
+ const imported = valueImportOf(declarationOf(this.src, callee.expression))
746
+ return imported?.kind === 'namespace' && this.authorizeModules.includes(imported.module)
747
+ }
748
+ return false
749
+ }
750
+
751
+ private statements(list: readonly ts.Statement[], outcome: Outcome): void {
752
+ for (const statement of list) {
753
+ this.statement(statement, outcome)
754
+ if (alwaysExits(this.src, statement)) return
755
+ }
756
+ }
757
+
758
+ private statement(s: ts.Statement, outcome: Outcome): void {
759
+ if (ts.isExpressionStatement(s)) this.visit(s.expression, outcome)
760
+ else if (ts.isVariableStatement(s)) this.visit(s.declarationList, outcome)
761
+ else if (ts.isReturnStatement(s) || ts.isThrowStatement(s)) {
762
+ if (s.expression) this.visit(s.expression, outcome)
763
+ } else if (ts.isIfStatement(s)) {
764
+ const condition = constantTruth(this.src, s.expression)
765
+ this.visit(s.expression, outcome)
766
+ if (condition !== false) this.statement(s.thenStatement, outcome)
767
+ if (condition !== true && s.elseStatement) this.statement(s.elseStatement, outcome)
768
+ } else if (ts.isBlock(s)) this.statements(s.statements, outcome)
769
+ else if (ts.isTryStatement(s)) {
770
+ // A throw in the `try` goes on only if the `catch` rethrows on every path: it neither falls through, nor
771
+ // returns, nor jumps out of itself (`break`, `continue`). A throw in either, or a promise either returns,
772
+ // goes on only if the `finally` has no way to leave in its place. A promise the `try` returns (`return p`,
773
+ // not `return await p`, which throws inside it) is not caught by the `catch`.
774
+ const finallyMayLeave = s.finallyBlock !== undefined && leavesBlock(s.finallyBlock, true)
775
+ const catchSwallows =
776
+ s.catchClause !== undefined &&
777
+ (!alwaysExits(this.src, s.catchClause.block) || leavesBlock(s.catchClause.block, true))
778
+ const thrown = outcome.thrown && !finallyMayLeave
779
+ 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 })
782
+ if (s.finallyBlock) this.statements(s.finallyBlock.statements, outcome)
783
+ } else if (ts.isWhileStatement(s)) {
784
+ const condition = constantTruth(this.src, s.expression)
785
+ this.visit(s.expression, outcome)
786
+ if (condition !== false) this.statement(s.statement, outcome)
787
+ } else if (ts.isDoStatement(s)) {
788
+ this.statement(s.statement, outcome)
789
+ // The condition runs only when the body falls through or continues; a body that always returns
790
+ // never reaches it.
791
+ if (reachesLoopEnd(this.src, s)) this.visit(s.expression, outcome)
792
+ } else if (ts.isForStatement(s)) {
793
+ if (s.initializer) this.visit(s.initializer, outcome)
794
+ const condition = s.condition ? constantTruth(this.src, s.condition) : true
795
+ if (s.condition) this.visit(s.condition, outcome)
796
+ if (condition !== false) {
797
+ this.statement(s.statement, outcome)
798
+ if (s.incrementor && reachesLoopEnd(this.src, s)) this.visit(s.incrementor, outcome)
799
+ }
800
+ } else if (ts.isForOfStatement(s) || ts.isForInStatement(s)) {
801
+ this.visit(s.expression, outcome)
802
+ this.statement(s.statement, outcome)
803
+ } else if (ts.isSwitchStatement(s)) {
804
+ this.visit(s.expression, outcome)
805
+ for (const clause of s.caseBlock.clauses) {
806
+ if (ts.isCaseClause(clause)) this.visit(clause.expression, outcome)
807
+ this.statements(clause.statements, outcome)
808
+ }
809
+ } else if (ts.isLabeledStatement(s)) this.statement(s.statement, outcome)
810
+ // Anything else (a function or class declaration, an import, an enum) runs nothing on this path that
811
+ // the scan credits: fail closed.
812
+ }
813
+ }
814
+
815
+ function isAsync(fn: ts.FunctionLikeDeclaration): boolean {
816
+ return hasModifier(fn, ts.SyntaxKind.AsyncKeyword)
817
+ }
818
+
819
+ /** Iteration methods that call their function argument before they return, on an array, and on an iterator that has them. */
820
+ const EAGER_ITERATION: ReadonlySet<string> = new Set([
821
+ 'every',
822
+ 'find',
823
+ 'findIndex',
824
+ 'findLast',
825
+ 'findLastIndex',
826
+ 'forEach',
827
+ 'reduce',
828
+ 'reduceRight',
829
+ 'some',
830
+ ])
831
+
832
+ /** Every array iteration method: on an array all run in place; on an iterator `filter`, `flatMap`, `map` are lazy. */
833
+ const ARRAY_ITERATION: ReadonlySet<string> = new Set([...EAGER_ITERATION, 'filter', 'flatMap', 'map'])
834
+
835
+ /** A receiver that is visibly an iterator: `xs.values()`, `xs.keys()`, `xs.entries()` or `Iterator.from(…)`. */
836
+ function isIterator(receiver: ts.Expression): boolean {
837
+ const e = unwrap(receiver)
838
+ if (!ts.isCallExpression(e) || !ts.isPropertyAccessExpression(e.expression)) return false
839
+ const name = e.expression.name.text
840
+ if (name === 'values' || name === 'keys' || name === 'entries') return true
841
+ const target = unwrap(e.expression.expression)
842
+ return name === 'from' && ts.isIdentifier(target) && target.text === 'Iterator'
843
+ }
844
+
845
+ /** The variable declaration a declared name belongs to, through destructuring; undefined for a parameter. */
846
+ function variableOf(decl: ts.Declaration): ts.VariableDeclaration | undefined {
847
+ let node: ts.Node = decl
848
+ while (ts.isBindingElement(node) || ts.isObjectBindingPattern(node) || ts.isArrayBindingPattern(node)) {
849
+ node = node.parent
850
+ }
851
+ return ts.isVariableDeclaration(node) ? node : undefined
852
+ }
853
+
854
+ /**
855
+ * Whether `block` has a way out of itself other than falling off its end or throwing: a `break` or `continue` whose
856
+ * target is outside it, and with `returns`, a `return`. Nested functions are not looked into.
857
+ */
858
+ function leavesBlock(block: ts.Block, returns: boolean): boolean {
859
+ let found = false
860
+ const walk = (node: ts.Node, labels: readonly string[], loops: number, switches: number): void => {
861
+ if (found || ts.isFunctionLike(node) || ts.isClassLike(node)) return
862
+ if (ts.isReturnStatement(node)) {
863
+ if (returns) found = true
864
+ } else if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
865
+ if (node.label) found = !labels.includes(node.label.text)
866
+ else found = ts.isBreakStatement(node) ? loops + switches === 0 : loops === 0
867
+ if (found) return
868
+ }
869
+ const inner = ts.isLabeledStatement(node) ? [...labels, node.label.text] : labels
870
+ const loop = ts.isIterationStatement(node, false) ? 1 : 0
871
+ const swtch = ts.isSwitchStatement(node) ? 1 : 0
872
+ ts.forEachChild(node, (child) => walk(child, inner, loops + loop, switches + swtch))
873
+ }
874
+ walk(block, [], 0, 0)
875
+ return found
876
+ }
877
+
878
+ /**
879
+ * What happens to the value of `call` on the spot: it is `await`ed, or returned from the function it sits in (by
880
+ * `return`, or as an arrow's expression body). On the way it may pass through parentheses, a type assertion
881
+ * (`as`, `satisfies`, `!`, `<T>`), a ternary's arm, the right of `&&`, `||`, `??` or a comma, or the left of `||` or
882
+ * `??` (a promise is truthy and never nullish, so it is their value), which hand it on. Anything else (a statement
883
+ * of its own, `void`, a variable, an argument, a `.then`) leaves its promise floating, as far as the scan can see.
884
+ */
885
+ function settledBy(call: ts.Expression): 'await' | 'return' | undefined {
886
+ let node: ts.Node = call
887
+ for (;;) {
888
+ const parent: ts.Node = node.parent
889
+ const operator = ts.isBinaryExpression(parent) ? parent.operatorToken.kind : undefined
890
+ if (
891
+ ts.isParenthesizedExpression(parent) ||
892
+ ts.isAsExpression(parent) ||
893
+ ts.isSatisfiesExpression(parent) ||
894
+ ts.isNonNullExpression(parent) ||
895
+ ts.isTypeAssertionExpression(parent) ||
896
+ (ts.isConditionalExpression(parent) && parent.condition !== node) ||
897
+ (ts.isBinaryExpression(parent) &&
898
+ parent.right === node &&
899
+ operator !== undefined &&
900
+ (isShortCircuit(operator) || operator === ts.SyntaxKind.CommaToken)) ||
901
+ (ts.isBinaryExpression(parent) &&
902
+ parent.left === node &&
903
+ (operator === ts.SyntaxKind.BarBarToken || operator === ts.SyntaxKind.QuestionQuestionToken))
904
+ ) {
905
+ node = parent
906
+ continue
907
+ }
908
+ if (ts.isAwaitExpression(parent)) return 'await'
909
+ if (ts.isReturnStatement(parent)) return 'return'
910
+ if (ts.isArrowFunction(parent) && parent.body === node) return 'return'
911
+ return undefined
912
+ }
913
+ }
914
+
915
+ // ---------------------------------------------------------------------------------------------------------
916
+ // Helpers over the syntax tree.
917
+ // ---------------------------------------------------------------------------------------------------------
918
+
919
+ function exportsOf(src: Source): { named: Map<string, Binding>; stars: string[] } {
920
+ const named = new Map<string, Binding>()
921
+ const stars: string[] = []
922
+ for (const statement of src.sf.statements) {
923
+ if (ts.isExportDeclaration(statement)) {
924
+ if (statement.isTypeOnly) continue
925
+ const specifier =
926
+ statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)
927
+ ? statement.moduleSpecifier.text
928
+ : undefined
929
+ const clause = statement.exportClause
930
+ if (!clause) {
931
+ if (specifier !== undefined) stars.push(specifier)
932
+ } else if (ts.isNamespaceExport(clause)) {
933
+ named.set(exportNameText(clause.name), {
934
+ kind: 'refused',
935
+ reason: 'a namespace re-export (`export * as …`) is not a handler',
936
+ })
937
+ } else {
938
+ for (const element of clause.elements) {
939
+ if (element.isTypeOnly) continue
940
+ const exported = exportNameText(element.name)
941
+ if (specifier !== undefined) {
942
+ named.set(exported, {
943
+ kind: 'module',
944
+ src,
945
+ specifier,
946
+ name: exportNameText(element.propertyName ?? element.name),
947
+ })
948
+ } else {
949
+ const decl = preferBody(src.checker.getExportSpecifierLocalTargetSymbol(element)?.declarations)
950
+ named.set(
951
+ exported,
952
+ decl
953
+ ? bindingOfDeclaration(src, decl)
954
+ : { kind: 'refused', reason: `\`${exported}\` is not declared in this file` },
955
+ )
956
+ }
957
+ }
958
+ }
959
+ continue
960
+ }
961
+ if (ts.isExportAssignment(statement)) {
962
+ // `export default <expression>`. (`export =` is CommonJS: the file was refused when it loaded.)
963
+ if (!statement.isExportEquals) named.set('default', { kind: 'decl', src, decl: statement })
964
+ continue
965
+ }
966
+ if (!hasModifier(statement, ts.SyntaxKind.ExportKeyword)) continue
967
+ const isDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword)
968
+ if (ts.isFunctionDeclaration(statement) && (statement.name || isDefault)) {
969
+ const name = isDefault ? 'default' : statement.name!.text
970
+ // An overload signature has no body; the implementation is the handler.
971
+ if (statement.body || !named.has(name)) named.set(name, { kind: 'decl', src, decl: statement })
972
+ } else if (isDefault) {
973
+ if (ts.isClassDeclaration(statement)) named.set('default', { kind: 'decl', src, decl: statement })
974
+ } else if (ts.isVariableStatement(statement)) {
975
+ for (const decl of statement.declarationList.declarations) {
976
+ if (ts.isIdentifier(decl.name)) named.set(decl.name.text, { kind: 'decl', src, decl })
977
+ else {
978
+ for (const name of boundNames(decl.name)) {
979
+ named.set(name, {
980
+ kind: 'refused',
981
+ reason: `\`${name}\` is destructured out of another value, which the scan cannot follow`,
982
+ })
983
+ }
984
+ }
985
+ }
986
+ } else if (ts.isImportEqualsDeclaration(statement)) {
987
+ named.set(statement.name.text, { kind: 'refused', reason: '`export import … =` is not followed' })
988
+ } else if (
989
+ (ts.isClassDeclaration(statement) ||
990
+ ts.isEnumDeclaration(statement) ||
991
+ ts.isModuleDeclaration(statement)) &&
992
+ statement.name &&
993
+ ts.isIdentifier(statement.name)
994
+ ) {
995
+ named.set(statement.name.text, { kind: 'decl', src, decl: statement })
996
+ }
997
+ }
998
+ return { named, stars }
999
+ }
1000
+
1001
+ function bindingOfDeclaration(src: Source, decl: ts.Declaration): Binding {
1002
+ if (ts.isImportSpecifier(decl) || ts.isImportClause(decl) || ts.isNamespaceImport(decl)) {
1003
+ const imported = valueImportOf(decl)
1004
+ if (!imported) return { kind: 'refused', reason: 'the handler is a type-only import' }
1005
+ if (imported.kind === 'namespace') return { kind: 'refused', reason: 'a namespace import is not a handler' }
1006
+ return { kind: 'module', src, specifier: imported.module, name: imported.name }
1007
+ }
1008
+ return { kind: 'decl', src, decl }
1009
+ }
1010
+
1011
+ type ValueImport = { kind: 'named'; module: string; name: string } | { kind: 'namespace'; module: string }
1012
+
1013
+ /**
1014
+ * What a declaration imports, when it is a VALUE import of an `import` statement: not `import type`, not
1015
+ * `import { type x }`, not a JSDoc `@import` (whose parent chain is a comment's, not an import's).
1016
+ */
1017
+ function valueImportOf(decl: ts.Declaration | undefined): ValueImport | undefined {
1018
+ if (!decl) return undefined
1019
+ let clause: ts.ImportClause
1020
+ if (ts.isImportSpecifier(decl)) {
1021
+ if (decl.isTypeOnly) return undefined
1022
+ clause = decl.parent.parent
1023
+ } else if (ts.isNamespaceImport(decl)) clause = decl.parent
1024
+ else if (ts.isImportClause(decl)) clause = decl
1025
+ else return undefined
1026
+ const statement = clause.parent
1027
+ if (clause.isTypeOnly || !ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {
1028
+ return undefined
1029
+ }
1030
+ const from = statement.moduleSpecifier.text
1031
+ if (ts.isImportSpecifier(decl)) {
1032
+ return { kind: 'named', module: from, name: exportNameText(decl.propertyName ?? decl.name) }
1033
+ }
1034
+ if (ts.isNamespaceImport(decl)) return { kind: 'namespace', module: from }
1035
+ return { kind: 'named', module: from, name: 'default' }
1036
+ }
1037
+
1038
+ /**
1039
+ * The dotted name a gate is matched against (`auth.updateProfile`), or undefined when the name's head is not a
1040
+ * value import that keeps the name it is exported under. A named import counts under its exported name only, so
1041
+ * `import { identity as withWebhookSecret }` is not the guard. A namespace import's head is dropped, so
1042
+ * `respond.withWebhookSecret` reads as `withWebhookSecret`. A default import has no exported name to check and
1043
+ * counts under its local one.
1044
+ *
1045
+ * WHICH module exports the name is not checked: an app may re-export SSSB's `isSimulated` from its own module, and
1046
+ * the wrappers are the app's. So a module that exports a fake under the real name passes. The scan catches a
1047
+ * route that lost its gate; it does not stand against one written to fool it (ADR-0012).
1048
+ */
1049
+ function gateName(src: Source, callee: ts.Expression): string | undefined {
1050
+ const members: string[] = []
1051
+ let head = unwrap(callee)
1052
+ while (ts.isPropertyAccessExpression(head)) {
1053
+ if (!ts.isIdentifier(head.name)) return undefined
1054
+ members.unshift(head.name.text)
1055
+ head = unwrap(head.expression)
1056
+ }
1057
+ if (!ts.isIdentifier(head)) return undefined
1058
+ const imported = valueImportOf(declarationOf(src, head))
1059
+ if (!imported) return undefined
1060
+ if (imported.kind === 'namespace') return members.length > 0 ? members.join('.') : undefined
1061
+ if (imported.name !== 'default' && imported.name !== head.text) return undefined
1062
+ return [head.text, ...members].join('.')
1063
+ }
1064
+
1065
+ function boundNames(pattern: ts.BindingName): string[] {
1066
+ if (ts.isIdentifier(pattern)) return [pattern.text]
1067
+ return pattern.elements.flatMap((element) => (ts.isOmittedExpression(element) ? [] : boundNames(element.name)))
1068
+ }
1069
+
1070
+ function exportNameText(name: ts.ModuleExportName): string {
1071
+ return name.text
1072
+ }
1073
+
1074
+ function hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {
1075
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === kind)
1076
+ }
1077
+
1078
+ /** An overloaded function has a declaration per signature; the one with a body is the function. */
1079
+ function preferBody(declarations: readonly ts.Declaration[] | undefined): ts.Declaration | undefined {
1080
+ return declarations?.find((d) => ts.isFunctionDeclaration(d) && d.body !== undefined) ?? declarations?.[0]
1081
+ }
1082
+
1083
+ function declarationOf(src: Source, id: ts.Identifier): ts.Declaration | undefined {
1084
+ return preferBody(src.checker.getSymbolAtLocation(id)?.declarations)
1085
+ }
1086
+
1087
+ function isConst(decl: ts.VariableDeclaration): boolean {
1088
+ return (ts.getCombinedNodeFlags(decl) & ts.NodeFlags.Const) !== 0
1089
+ }
1090
+
1091
+ /**
1092
+ * A function declared twice in one scope, or also declared as a `var` (`function check() {…} function check() {}`,
1093
+ * `var check = …`): TypeScript rejects both, but nothing typechecks a route.js, and at run time the LAST one is what
1094
+ * the name holds. An overload signature has no body and is not a second declaration.
1095
+ */
1096
+ function isRedeclared(decl: ts.FunctionDeclaration): boolean {
1097
+ // Read from the syntax, not the binder: in a JS file the binder gives `function check` and `var check` separate
1098
+ // symbols, and an exported function its own export symbol, so neither shows as a second declaration there.
1099
+ // The scope is the block that holds the declaration: a module is strict code, where a function declared in a
1100
+ // block belongs to that block. A `var` anywhere inside it (outside nested functions) hoists past it and is the
1101
+ // same name.
1102
+ const name = decl.name?.text
1103
+ if (name === undefined) return false
1104
+ const scope: ts.Node = decl.parent
1105
+ let count = 0
1106
+ const walk = (node: ts.Node): void => {
1107
+ if (node !== scope && (ts.isFunctionLike(node) || ts.isClassLike(node))) {
1108
+ // A nested function's NAME belongs to this scope; nothing inside it does.
1109
+ if (ts.isFunctionDeclaration(node) && node.body !== undefined && node.name?.text === name) count++
1110
+ return
1111
+ }
1112
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) count++
1113
+ ts.forEachChild(node, walk)
1114
+ }
1115
+ walk(scope)
1116
+ return count > 1
1117
+ }
1118
+
1119
+ function isReassigned(src: Source, decl: ts.FunctionDeclaration): boolean {
1120
+ const symbol = decl.name ? src.checker.getSymbolAtLocation(decl.name) : undefined
1121
+ return symbol !== undefined && src.reassigned.has(symbol)
1122
+ }
1123
+
1124
+ /**
1125
+ * Every symbol the file writes to by name: an assignment or compound assignment, including each name in a
1126
+ * destructuring target (`[POST] = …`, `({ open: POST } = …)`), a `for (x of …)`/`for (x in …)` target, and `++`/`--`.
1127
+ */
1128
+ function reassignedSymbols(sf: ts.SourceFile, checker: ts.TypeChecker): Set<ts.Symbol> {
1129
+ const out = new Set<ts.Symbol>()
1130
+ const mark = (target: ts.Expression): void => {
1131
+ const e = unwrap(target)
1132
+ if (ts.isIdentifier(e)) {
1133
+ const symbol = checker.getSymbolAtLocation(e)
1134
+ if (symbol) out.add(symbol)
1135
+ } else if (ts.isArrayLiteralExpression(e)) {
1136
+ for (const element of e.elements) mark(ts.isSpreadElement(element) ? element.expression : element)
1137
+ } else if (ts.isObjectLiteralExpression(e)) {
1138
+ for (const property of e.properties) {
1139
+ if (ts.isPropertyAssignment(property)) mark(property.initializer)
1140
+ else if (ts.isShorthandPropertyAssignment(property)) {
1141
+ // The name's own symbol is the object property; the variable written is this one.
1142
+ const symbol = checker.getShorthandAssignmentValueSymbol(property)
1143
+ if (symbol) out.add(symbol)
1144
+ } else if (ts.isSpreadAssignment(property)) mark(property.expression)
1145
+ }
1146
+ }
1147
+ // A default inside a target (`[POST = x] = …`) is an assignment expression itself; the walk marks it.
1148
+ }
1149
+ const walk = (node: ts.Node): void => {
1150
+ if (
1151
+ ts.isBinaryExpression(node) &&
1152
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1153
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
1154
+ ) {
1155
+ mark(node.left)
1156
+ } else if (
1157
+ (ts.isForOfStatement(node) || ts.isForInStatement(node)) &&
1158
+ !ts.isVariableDeclarationList(node.initializer)
1159
+ ) {
1160
+ mark(node.initializer)
1161
+ } else if (
1162
+ (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
1163
+ (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)
1164
+ ) {
1165
+ mark(node.operand)
1166
+ }
1167
+ ts.forEachChild(node, walk)
1168
+ }
1169
+ walk(sf)
1170
+ return out
1171
+ }
1172
+
1173
+ function isFunctionLiteral(node: ts.Node): node is ts.ArrowFunction | ts.FunctionExpression {
1174
+ return ts.isArrowFunction(node) || ts.isFunctionExpression(node)
1175
+ }
1176
+
1177
+ /** Strips parentheses and type-only wrappers (`as`, `satisfies`, `!`, `<T>x`). */
1178
+ function unwrap(e: ts.Expression): ts.Expression {
1179
+ while (
1180
+ ts.isParenthesizedExpression(e) ||
1181
+ ts.isAsExpression(e) ||
1182
+ ts.isSatisfiesExpression(e) ||
1183
+ ts.isNonNullExpression(e) ||
1184
+ ts.isTypeAssertionExpression(e)
1185
+ ) {
1186
+ e = e.expression
1187
+ }
1188
+ return e
1189
+ }
1190
+
1191
+ /** `auth.updateProfile` for that callee; undefined for anything that is not a plain dotted name. */
1192
+ function dottedName(e: ts.Expression): string | undefined {
1193
+ const node = unwrap(e)
1194
+ if (ts.isIdentifier(node)) return node.text
1195
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {
1196
+ const head = dottedName(node.expression)
1197
+ return head === undefined ? undefined : `${head}.${node.name.text}`
1198
+ }
1199
+ return undefined
1200
+ }
1201
+
1202
+ /** The `const` initializer an identifier is bound to, followed a few names deep; undefined if it is not one. */
1203
+ function constInitializer(src: Source, e: ts.Expression, depth: number): ts.Expression | undefined {
1204
+ if (!ts.isIdentifier(e) || depth >= 4) return undefined
1205
+ const decl = declarationOf(src, e)
1206
+ if (decl && ts.isVariableDeclaration(decl) && isConst(decl) && decl.initializer && ts.isIdentifier(decl.name)) {
1207
+ return decl.initializer
1208
+ }
1209
+ return undefined
1210
+ }
1211
+
1212
+ /**
1213
+ * The truthiness of a condition the scan can decide without running anything, or undefined. Literals,
1214
+ * `!`, `void`, and a `const` bound to one of those (to a depth of a few names); nothing else.
1215
+ */
1216
+ function constantTruth(src: Source, expression: ts.Expression, depth = 0): boolean | undefined {
1217
+ const e = unwrap(expression)
1218
+ switch (e.kind) {
1219
+ case ts.SyntaxKind.TrueKeyword:
1220
+ return true
1221
+ case ts.SyntaxKind.FalseKeyword:
1222
+ case ts.SyntaxKind.NullKeyword:
1223
+ return false
1224
+ case ts.SyntaxKind.VoidExpression:
1225
+ return false
1226
+ }
1227
+ if (ts.isNumericLiteral(e)) return Number(e.text) !== 0
1228
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) return e.text !== ''
1229
+ if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.ExclamationToken) {
1230
+ const inner = constantTruth(src, e.operand, depth)
1231
+ return inner === undefined ? undefined : !inner
1232
+ }
1233
+ if (ts.isIdentifier(e)) {
1234
+ if (e.text === 'undefined' && !declarationOf(src, e)) return false
1235
+ const init = constInitializer(src, e, depth)
1236
+ return init === undefined ? undefined : constantTruth(src, init, depth + 1)
1237
+ }
1238
+ return undefined
1239
+ }
1240
+
1241
+ /** Whether the value is a constant known not to be null or undefined (so `??` never reaches its right side). */
1242
+ function constantlyNonNullish(src: Source, expression: ts.Expression, depth = 0): boolean {
1243
+ const e = unwrap(expression)
1244
+ if (e.kind === ts.SyntaxKind.NullKeyword || e.kind === ts.SyntaxKind.VoidExpression) return false
1245
+ if (ts.isIdentifier(e)) {
1246
+ const init = constInitializer(src, e, depth)
1247
+ return init !== undefined && constantlyNonNullish(src, init, depth + 1)
1248
+ }
1249
+ return constantTruth(src, e) !== undefined
1250
+ }
1251
+
1252
+ function isShortCircuit(kind: ts.SyntaxKind): boolean {
1253
+ return (
1254
+ kind === ts.SyntaxKind.AmpersandAmpersandToken ||
1255
+ kind === ts.SyntaxKind.BarBarToken ||
1256
+ kind === ts.SyntaxKind.QuestionQuestionToken
1257
+ )
1258
+ }
1259
+
1260
+ /** For `a && b`, `a || b` and `a ?? b`: whether a constant left side means `b` never runs. */
1261
+ function rightIsDead(src: Source, node: ts.BinaryExpression): boolean {
1262
+ const kind = node.operatorToken.kind
1263
+ if (kind === ts.SyntaxKind.QuestionQuestionToken) return constantlyNonNullish(src, node.left)
1264
+ const left = constantTruth(src, node.left)
1265
+ if (left === undefined) return false
1266
+ return kind === ts.SyntaxKind.AmpersandAmpersandToken ? left === false : left === true
1267
+ }
1268
+
1269
+ /**
1270
+ * Whether control never falls through `s` to the statement after it. `labels` are the labels `s` carries
1271
+ * (`a: b: { … }` carries both), so a `break` naming any of them counts as falling through.
1272
+ */
1273
+ function alwaysExits(src: Source, s: ts.Statement, labels: readonly string[] = []): boolean {
1274
+ if (ts.isReturnStatement(s) || ts.isThrowStatement(s) || ts.isBreakStatement(s) || ts.isContinueStatement(s)) {
1275
+ return true
1276
+ }
1277
+ // A labeled block, `if` or `try` falls through after all when a `break` names its label.
1278
+ const named = (exits: boolean) => exits && (labels.length === 0 || !breaksOut(s, labels, false, false))
1279
+ if (ts.isBlock(s)) return named(s.statements.some((inner) => alwaysExits(src, inner)))
1280
+ if (ts.isIfStatement(s)) {
1281
+ const condition = constantTruth(src, s.expression)
1282
+ if (condition === true) return named(alwaysExits(src, s.thenStatement))
1283
+ if (condition === false) return named(s.elseStatement !== undefined && alwaysExits(src, s.elseStatement))
1284
+ return named(
1285
+ s.elseStatement !== undefined && alwaysExits(src, s.thenStatement) && alwaysExits(src, s.elseStatement),
1286
+ )
1287
+ }
1288
+ if (ts.isTryStatement(s)) {
1289
+ if (s.finallyBlock && alwaysExits(src, s.finallyBlock)) return named(true)
1290
+ return named(alwaysExits(src, s.tryBlock) && (!s.catchClause || alwaysExits(src, s.catchClause.block)))
1291
+ }
1292
+ if (ts.isLabeledStatement(s)) return alwaysExits(src, s.statement, [...labels, s.label.text])
1293
+ // A loop that only a `break` can leave: `while (true)`, `for (;;)`, `for (; true;)`.
1294
+ if (ts.isWhileStatement(s) || ts.isForStatement(s)) {
1295
+ const condition = ts.isWhileStatement(s) ? s.expression : s.condition
1296
+ const forever = condition === undefined || constantTruth(src, condition) === true
1297
+ return forever && !breaksOut(s.statement, labels, true, false)
1298
+ }
1299
+ if (ts.isDoStatement(s)) {
1300
+ if (alwaysExits(src, s.statement) && !breaksOut(s.statement, labels, true, true)) return true
1301
+ return constantTruth(src, s.expression) === true && !breaksOut(s.statement, labels, true, false)
1302
+ }
1303
+ // A switch with a default that nothing breaks out of: control leaves only through the last clause's end.
1304
+ if (ts.isSwitchStatement(s)) {
1305
+ const clauses = s.caseBlock.clauses
1306
+ const last = clauses[clauses.length - 1]
1307
+ return (
1308
+ clauses.some(ts.isDefaultClause) &&
1309
+ last !== undefined &&
1310
+ last.statements.some((inner) => alwaysExits(src, inner)) &&
1311
+ !breaksOut(s.caseBlock, labels, true, false)
1312
+ )
1313
+ }
1314
+ return false
1315
+ }
1316
+
1317
+ /** The labels a statement carries: those of the labeled statements directly around it. */
1318
+ function labelsOf(s: ts.Statement): string[] {
1319
+ const labels: string[] = []
1320
+ for (let parent = s.parent; ts.isLabeledStatement(parent); parent = parent.parent) labels.push(parent.label.text)
1321
+ return labels
1322
+ }
1323
+
1324
+ /**
1325
+ * Whether a `do` or `for` loop's body can reach the end of an iteration, where the `do` condition or the `for`
1326
+ * incrementor runs: it falls through, or a `continue` aims at this loop. A body that always returns never does.
1327
+ */
1328
+ function reachesLoopEnd(src: Source, loop: ts.DoStatement | ts.ForStatement): boolean {
1329
+ return !alwaysExits(src, loop.statement) || breaksOut(loop.statement, labelsOf(loop), false, true)
1330
+ }
1331
+
1332
+ /**
1333
+ * Whether `body` holds a jump that lands just after the statement it belongs to: a `break` naming one of
1334
+ * `labels`; with `unlabeled`, a bare `break` not inside a nested loop or switch; with `continues`, a bare
1335
+ * `continue` not inside a nested loop, or one naming one of `labels` (a loop's continue goes to its end, then on).
1336
+ */
1337
+ function breaksOut(body: ts.Node, labels: readonly string[], unlabeled: boolean, continues: boolean): boolean {
1338
+ let found = false
1339
+ const walk = (node: ts.Node, loops: number, switches: number): void => {
1340
+ if (found || ts.isFunctionLike(node) || ts.isClassLike(node)) return
1341
+ if (ts.isBreakStatement(node)) {
1342
+ if (node.label ? labels.includes(node.label.text) : unlabeled && loops + switches === 0) found = true
1343
+ return
1344
+ }
1345
+ if (ts.isContinueStatement(node)) {
1346
+ if (continues && (node.label ? labels.includes(node.label.text) : loops === 0)) found = true
1347
+ return
1348
+ }
1349
+ const loop = ts.isIterationStatement(node, false) ? 1 : 0
1350
+ const swtch = ts.isSwitchStatement(node) ? 1 : 0
1351
+ ts.forEachChild(node, (child) => walk(child, loops + loop, switches + swtch))
1352
+ }
1353
+ walk(body, 0, 0)
1354
+ return found
1355
+ }
1356
+
1357
+ /**
1358
+ * The handler's first statement is `if (!isSimulated) <branch>` with `isSimulated` imported under that name, the
1359
+ * branch does nothing but return or throw a response built from literals, and nothing runs before it (no
1360
+ * parameter default or destructuring), so in real mode the handler does nothing at all.
1361
+ */
1362
+ function opensWithSimulated404(src: Source, fn: ts.FunctionLikeDeclaration): boolean {
1363
+ if (!fn.body || !ts.isBlock(fn.body)) return false
1364
+ if (!fn.parameters.every(runsNothing)) return false
1365
+ const [first] = fn.body.statements
1366
+ if (!first || !ts.isIfStatement(first)) return false
1367
+ const condition = unwrap(first.expression)
1368
+ if (!ts.isPrefixUnaryExpression(condition) || condition.operator !== ts.SyntaxKind.ExclamationToken) return false
1369
+ if (gateName(src, condition.operand) !== 'isSimulated') return false
1370
+ return isInertExit(src, first.thenStatement)
1371
+ }
1372
+
1373
+ /**
1374
+ * A parameter that runs no code when the handler is called: no default anywhere in it, and no computed key in a
1375
+ * destructuring pattern. Next's own `(request, { params })` is fine; `{ params = wipe() }` is not.
1376
+ */
1377
+ function runsNothing(p: ts.ParameterDeclaration | ts.BindingElement): boolean {
1378
+ if (p.initializer !== undefined) return false
1379
+ if (ts.isBindingElement(p) && p.propertyName !== undefined && ts.isComputedPropertyName(p.propertyName))
1380
+ return false
1381
+ if (ts.isIdentifier(p.name)) return true
1382
+ return p.name.elements.every((element) => ts.isOmittedExpression(element) || runsNothing(element))
1383
+ }
1384
+
1385
+ const RESPONSE_CONSTRUCTORS = ['Response', 'NextResponse']
1386
+ /** A global constructor that may be thrown from the gate: an `Error`, which does nothing when built. */
1387
+ const GLOBAL_ERROR = /^(?:[A-Z][A-Za-z]*)?Error$/
1388
+ const RESPONSE_FACTORIES = ['Response.json', 'Response.redirect', 'NextResponse.json', 'NextResponse.redirect']
1389
+
1390
+ /** `return <response>` or `throw new X(…)`, alone or alone in a block, built from literals only. */
1391
+ function isInertExit(src: Source, s: ts.Statement): boolean {
1392
+ if (ts.isBlock(s)) return s.statements.length === 1 && isInertExit(src, s.statements[0]!)
1393
+ if (ts.isReturnStatement(s)) {
1394
+ const e = s.expression && unwrap(s.expression)
1395
+ if (!e || !(ts.isNewExpression(e) || ts.isCallExpression(e))) return false
1396
+ const name = globalOrGateName(src, e.expression)
1397
+ const allowed = ts.isNewExpression(e) ? RESPONSE_CONSTRUCTORS : RESPONSE_FACTORIES
1398
+ return name !== undefined && allowed.includes(name) && (e.arguments ?? []).every((a) => isLiteralValue(src, a))
1399
+ }
1400
+ 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.
1403
+ const e = unwrap(s.expression)
1404
+ if (!ts.isNewExpression(e)) return false
1405
+ const name = globalOrGateName(src, e.expression)
1406
+ const global = isGlobal(src, e.expression)
1407
+ return (
1408
+ name !== undefined &&
1409
+ (!global || GLOBAL_ERROR.test(name)) &&
1410
+ (e.arguments ?? []).every((a) => isLiteralValue(src, a))
1411
+ )
1412
+ }
1413
+ return false
1414
+ }
1415
+
1416
+ /** The callee's head is declared nowhere in the file. */
1417
+ function isGlobal(src: Source, callee: ts.Expression): boolean {
1418
+ let head = unwrap(callee)
1419
+ while (ts.isPropertyAccessExpression(head)) head = unwrap(head.expression)
1420
+ return ts.isIdentifier(head) && declarationOf(src, head) === undefined
1421
+ }
1422
+
1423
+ /** A callee's dotted name when its head is a global (declared nowhere in the file), or its gate name if imported. */
1424
+ function globalOrGateName(src: Source, callee: ts.Expression): string | undefined {
1425
+ let head = unwrap(callee)
1426
+ while (ts.isPropertyAccessExpression(head)) head = unwrap(head.expression)
1427
+ if (!ts.isIdentifier(head)) return undefined
1428
+ return declarationOf(src, head) === undefined ? dottedName(callee) : gateName(src, callee)
1429
+ }
1430
+
1431
+ /**
1432
+ * A value whose construction runs no code: a literal, `undefined`, a signed number, an array or object literal
1433
+ * of those (plain properties only, no spread, computed key, method or accessor), or `JSON.stringify` of one. An
1434
+ * identifier or a property read is not one: it can be an object whose `toJSON` or getter runs on use.
1435
+ */
1436
+ function isLiteralValue(src: Source, expression: ts.Expression): boolean {
1437
+ const e = unwrap(expression)
1438
+ switch (e.kind) {
1439
+ case ts.SyntaxKind.StringLiteral:
1440
+ case ts.SyntaxKind.NumericLiteral:
1441
+ case ts.SyntaxKind.BigIntLiteral:
1442
+ case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
1443
+ case ts.SyntaxKind.TrueKeyword:
1444
+ case ts.SyntaxKind.FalseKeyword:
1445
+ case ts.SyntaxKind.NullKeyword:
1446
+ return true
1447
+ }
1448
+ if (ts.isIdentifier(e)) return e.text === 'undefined' && declarationOf(src, e) === undefined
1449
+ if (ts.isPrefixUnaryExpression(e)) {
1450
+ return (
1451
+ (e.operator === ts.SyntaxKind.MinusToken || e.operator === ts.SyntaxKind.PlusToken) &&
1452
+ ts.isNumericLiteral(unwrap(e.operand))
1453
+ )
1454
+ }
1455
+ if (ts.isArrayLiteralExpression(e)) {
1456
+ return e.elements.every((element) => ts.isOmittedExpression(element) || isLiteralValue(src, element))
1457
+ }
1458
+ if (ts.isObjectLiteralExpression(e)) {
1459
+ return e.properties.every(
1460
+ (p) =>
1461
+ ts.isPropertyAssignment(p) && !ts.isComputedPropertyName(p.name) && isLiteralValue(src, p.initializer),
1462
+ )
1463
+ }
1464
+ if (ts.isCallExpression(e)) {
1465
+ return (
1466
+ globalOrGateName(src, e.expression) === 'JSON.stringify' &&
1467
+ e.arguments.every((argument) => isLiteralValue(src, argument))
1468
+ )
1469
+ }
1470
+ return false
1471
+ }
1472
+
1473
+ /** The file reads `module.exports`, `module['exports']` or a free `exports`: CommonJS, whatever else it has. */
1474
+ function usesCommonJsExports(sf: ts.SourceFile, checker: ts.TypeChecker): boolean {
1475
+ let found = false
1476
+ const free = (node: ts.Node, name: string) =>
1477
+ ts.isIdentifier(node) && node.text === name && !checker.getSymbolAtLocation(node)?.declarations?.length
1478
+ const walk = (node: ts.Node): void => {
1479
+ if (found) return
1480
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
1481
+ const member = ts.isPropertyAccessExpression(node)
1482
+ ? node.name.text
1483
+ : ts.isStringLiteralLike(node.argumentExpression)
1484
+ ? node.argumentExpression.text
1485
+ : undefined
1486
+ if ((free(node.expression, 'module') && member === 'exports') || free(node.expression, 'exports')) {
1487
+ found = true
1488
+ return
1489
+ }
1490
+ }
1491
+ if (ts.isCallExpression(node) && node.arguments.some((a) => free(a, 'exports'))) {
1492
+ found = true
1493
+ return
1494
+ }
1495
+ ts.forEachChild(node, walk)
1496
+ }
1497
+ walk(sf)
1498
+ return found
1499
+ }
1500
+
1501
+ function readCompilerOptions(tsconfig: string): ts.CompilerOptions {
1502
+ const parsed = ts.getParsedCommandLineOfConfigFile(
1503
+ tsconfig,
1504
+ {},
1505
+ {
1506
+ ...ts.sys,
1507
+ // Only the options are wanted; listing the project's files would walk the whole app for nothing.
1508
+ readDirectory: () => [],
1509
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
1510
+ throw new Error(`${tsconfig}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, ' ')}`)
1511
+ },
1512
+ },
1513
+ )
1514
+ if (!parsed) throw new Error(`${tsconfig}: could not be read`)
1515
+ return parsed.options
1516
+ }