@slotform/auth 0.0.0-stage → 0.1.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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/dist/ability/index.d.ts +31 -0
  4. package/dist/ability/index.d.ts.map +1 -0
  5. package/dist/ability/index.js +64 -0
  6. package/dist/ability/index.js.map +1 -0
  7. package/dist/access.d.ts +19 -0
  8. package/dist/access.d.ts.map +1 -0
  9. package/dist/access.js +33 -0
  10. package/dist/access.js.map +1 -0
  11. package/dist/callback-stubs.d.ts +15 -0
  12. package/dist/callback-stubs.d.ts.map +1 -0
  13. package/dist/callback-stubs.js +28 -0
  14. package/dist/callback-stubs.js.map +1 -0
  15. package/dist/client.d.ts +38 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +37 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/index.d.ts +190 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +451 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/infer.d.ts +31 -0
  24. package/dist/infer.d.ts.map +1 -0
  25. package/dist/infer.js +2 -0
  26. package/dist/infer.js.map +1 -0
  27. package/dist/schema/devices.d.ts +404 -0
  28. package/dist/schema/devices.d.ts.map +1 -0
  29. package/dist/schema/devices.js +45 -0
  30. package/dist/schema/devices.js.map +1 -0
  31. package/dist/schema/index.d.ts +679 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +94 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/oauth.d.ts +2062 -0
  36. package/dist/schema/oauth.d.ts.map +1 -0
  37. package/dist/schema/oauth.js +245 -0
  38. package/dist/schema/oauth.js.map +1 -0
  39. package/dist/schema/organization.d.ts +388 -0
  40. package/dist/schema/organization.d.ts.map +1 -0
  41. package/dist/schema/organization.js +75 -0
  42. package/dist/schema/organization.js.map +1 -0
  43. package/dist/schema/passkey.d.ts +215 -0
  44. package/dist/schema/passkey.d.ts.map +1 -0
  45. package/dist/schema/passkey.js +29 -0
  46. package/dist/schema/passkey.js.map +1 -0
  47. package/dist/schema/sets.d.ts +3715 -0
  48. package/dist/schema/sets.d.ts.map +1 -0
  49. package/dist/schema/sets.js +48 -0
  50. package/dist/schema/sets.js.map +1 -0
  51. package/dist/scope.d.ts +36 -0
  52. package/dist/scope.d.ts.map +1 -0
  53. package/dist/scope.js +59 -0
  54. package/dist/scope.js.map +1 -0
  55. package/dist/screens-fixtures.d.ts +148 -0
  56. package/dist/screens-fixtures.d.ts.map +1 -0
  57. package/dist/screens-fixtures.js +122 -0
  58. package/dist/screens-fixtures.js.map +1 -0
  59. package/dist/screens-session.d.ts +4 -0
  60. package/dist/screens-session.d.ts.map +1 -0
  61. package/dist/screens-session.js +24 -0
  62. package/dist/screens-session.js.map +1 -0
  63. package/dist/screens.d.ts +3 -0
  64. package/dist/screens.d.ts.map +1 -0
  65. package/dist/screens.js +8 -0
  66. package/dist/screens.js.map +1 -0
  67. package/dist/serve.d.ts +3 -0
  68. package/dist/serve.d.ts.map +1 -0
  69. package/dist/serve.js +44 -0
  70. package/dist/serve.js.map +1 -0
  71. package/dist/types.d.ts +152 -0
  72. package/dist/types.d.ts.map +1 -0
  73. package/dist/types.js +215 -0
  74. package/dist/types.js.map +1 -0
  75. package/dist/worker/callback-url.d.ts +6 -0
  76. package/dist/worker/callback-url.d.ts.map +1 -0
  77. package/dist/worker/callback-url.js +57 -0
  78. package/dist/worker/callback-url.js.map +1 -0
  79. package/dist/worker/cimd-transport.d.ts +2 -0
  80. package/dist/worker/cimd-transport.d.ts.map +1 -0
  81. package/dist/worker/cimd-transport.js +86 -0
  82. package/dist/worker/cimd-transport.js.map +1 -0
  83. package/dist/worker/devices.d.ts +6 -0
  84. package/dist/worker/devices.d.ts.map +1 -0
  85. package/dist/worker/devices.js +70 -0
  86. package/dist/worker/devices.js.map +1 -0
  87. package/dist/worker/email-key.d.ts +2 -0
  88. package/dist/worker/email-key.d.ts.map +1 -0
  89. package/dist/worker/email-key.js +20 -0
  90. package/dist/worker/email-key.js.map +1 -0
  91. package/dist/worker/index.d.ts +156 -0
  92. package/dist/worker/index.d.ts.map +1 -0
  93. package/dist/worker/index.js +507 -0
  94. package/dist/worker/index.js.map +1 -0
  95. package/dist/worker/listener.d.ts +12 -0
  96. package/dist/worker/listener.d.ts.map +1 -0
  97. package/dist/worker/listener.js +37 -0
  98. package/dist/worker/listener.js.map +1 -0
  99. package/dist/worker/oauth.d.ts +95 -0
  100. package/dist/worker/oauth.d.ts.map +1 -0
  101. package/dist/worker/oauth.js +456 -0
  102. package/dist/worker/oauth.js.map +1 -0
  103. package/dist/worker/outputs.d.ts +75 -0
  104. package/dist/worker/outputs.d.ts.map +1 -0
  105. package/dist/worker/outputs.js +7 -0
  106. package/dist/worker/outputs.js.map +1 -0
  107. package/dist/worker/procedures.d.ts +360 -0
  108. package/dist/worker/procedures.d.ts.map +1 -0
  109. package/dist/worker/procedures.js +464 -0
  110. package/dist/worker/procedures.js.map +1 -0
  111. package/dist/worker/rate-limit.d.ts +7 -0
  112. package/dist/worker/rate-limit.d.ts.map +1 -0
  113. package/dist/worker/rate-limit.js +49 -0
  114. package/dist/worker/rate-limit.js.map +1 -0
  115. package/dist/worker/reserved-slugs.d.ts +4 -0
  116. package/dist/worker/reserved-slugs.d.ts.map +1 -0
  117. package/dist/worker/reserved-slugs.js +30 -0
  118. package/dist/worker/reserved-slugs.js.map +1 -0
  119. package/dist/worker/session-ended.d.ts +6 -0
  120. package/dist/worker/session-ended.d.ts.map +1 -0
  121. package/dist/worker/session-ended.js +10 -0
  122. package/dist/worker/session-ended.js.map +1 -0
  123. package/dist/worker/sign-up-policy.d.ts +20 -0
  124. package/dist/worker/sign-up-policy.d.ts.map +1 -0
  125. package/dist/worker/sign-up-policy.js +65 -0
  126. package/dist/worker/sign-up-policy.js.map +1 -0
  127. package/dist/worker/tenancy.d.ts +23 -0
  128. package/dist/worker/tenancy.d.ts.map +1 -0
  129. package/dist/worker/tenancy.js +133 -0
  130. package/dist/worker/tenancy.js.map +1 -0
  131. package/guide/abilities.md +55 -0
  132. package/guide/add-a-role.md +33 -0
  133. package/guide/callbacks.md +97 -0
  134. package/guide/config.md +84 -0
  135. package/guide/devices.md +85 -0
  136. package/guide/mcp-oauth.md +97 -0
  137. package/guide/organizations.md +114 -0
  138. package/guide/protect-by-scope.md +29 -0
  139. package/guide/scopes.md +87 -0
  140. package/guide/sign-in.md +127 -0
  141. package/package.json +155 -3
  142. package/src/ability/index.ts +174 -0
  143. package/src/access.ts +45 -0
  144. package/src/callback-stubs.ts +45 -0
  145. package/src/client.ts +119 -0
  146. package/src/expo.tsx +275 -0
  147. package/src/index.ts +574 -0
  148. package/src/infer.ts +44 -0
  149. package/src/schema/devices.ts +54 -0
  150. package/src/schema/index.ts +128 -0
  151. package/src/schema/oauth.ts +320 -0
  152. package/src/schema/organization.ts +104 -0
  153. package/src/schema/passkey.ts +38 -0
  154. package/src/schema/sets.ts +73 -0
  155. package/src/scope.ts +135 -0
  156. package/src/screens-fixtures.ts +149 -0
  157. package/src/screens-session.ts +26 -0
  158. package/src/screens.ts +10 -0
  159. package/src/serve.ts +49 -0
  160. package/src/types.ts +313 -0
  161. package/src/worker/callback-url.ts +65 -0
  162. package/src/worker/cimd-transport.ts +115 -0
  163. package/src/worker/devices.ts +83 -0
  164. package/src/worker/email-key.ts +21 -0
  165. package/src/worker/index.ts +941 -0
  166. package/src/worker/listener.ts +55 -0
  167. package/src/worker/oauth.ts +709 -0
  168. package/src/worker/outputs.ts +102 -0
  169. package/src/worker/procedures.ts +758 -0
  170. package/src/worker/rate-limit.ts +64 -0
  171. package/src/worker/reserved-slugs.ts +39 -0
  172. package/src/worker/session-ended.ts +14 -0
  173. package/src/worker/sign-up-policy.ts +88 -0
  174. package/src/worker/tenancy.ts +229 -0
  175. package/templates/callbacks.ts +40 -0
@@ -0,0 +1,941 @@
1
+ import { expo } from "@better-auth/expo";
2
+ import { passkey } from "@better-auth/passkey";
3
+ import {
4
+ ORG_RULES_PATH,
5
+ type RateLimitBinding,
6
+ SCOPE_ROUTES_PATH,
7
+ } from "@slotform/api/procedure";
8
+ import type { RuntimePlugin } from "@slotform/cli/runtime";
9
+ import type { SQLiteColumn } from "@slotform/db/orm";
10
+ import type { BetterAuthPlugin } from "better-auth";
11
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
12
+ import { type BetterAuthOptions, betterAuth } from "better-auth/minimal";
13
+ import {
14
+ role as buildAcRole,
15
+ createAccessControl as createBetterAuthAccessControl,
16
+ } from "better-auth/plugins/access";
17
+ import { emailOTP } from "better-auth/plugins/email-otp";
18
+ import { magicLink } from "better-auth/plugins/magic-link";
19
+ import { organization } from "better-auth/plugins/organization";
20
+ import { defaultOrgRoles } from "../access.ts";
21
+ import type { SessionOf, SessionUser } from "../infer.ts";
22
+ import { tableSetsOf } from "../schema/sets.ts";
23
+ import {
24
+ type Membership,
25
+ organization as organizationScope,
26
+ type Scope,
27
+ } from "../scope.ts";
28
+ import type {
29
+ AuthCallbackPayloads,
30
+ AuthUser,
31
+ OtpType,
32
+ ResolvedSocialProvider,
33
+ SocialProviderName,
34
+ } from "../types.ts";
35
+ import {
36
+ AUTH_PREFIX,
37
+ CLIENT_IP_HEADER,
38
+ OAUTH_DISCOVERY_PREFIXES,
39
+ } from "../types.ts";
40
+ import { devicePlugins } from "./devices.ts";
41
+ import {
42
+ appUrlOf,
43
+ type BakedPasskey,
44
+ isDevMode,
45
+ passkeyFor,
46
+ } from "./listener.ts";
47
+ import {
48
+ createOAuth,
49
+ type GrantAdapter,
50
+ mcpPlugins,
51
+ type OAuth,
52
+ } from "./oauth.ts";
53
+ import {
54
+ type AuthProcedureFactory,
55
+ bySlugProcedure,
56
+ deviceProcedures,
57
+ emailOtpOauthProcedures,
58
+ emailOtpProcedures,
59
+ magicLinkOauthProcedures,
60
+ magicLinkProcedures,
61
+ OTP_LENGTH,
62
+ oauthProcedures,
63
+ organizationProcedures,
64
+ orgRulesProcedure,
65
+ type ScopeLookup,
66
+ sessionProcedures,
67
+ setActiveOauthProcedure,
68
+ } from "./procedures.ts";
69
+ import { type AuthRateLimiter, checkRateLimit } from "./rate-limit.ts";
70
+ import { refuseReservedSlug, reservedSlugCheck } from "./reserved-slugs.ts";
71
+ import { publishSessionEnded } from "./session-ended.ts";
72
+ import { type PolicyAdapter, signUpPolicy } from "./sign-up-policy.ts";
73
+ import { createTenancy, type Tenancy } from "./tenancy.ts";
74
+
75
+ // Routes `devices` takes off HTTP: docs/architecture/plugins/auth.md, "Devices".
76
+ const DEVICE_DISABLED_PATHS = [
77
+ "/api-key/create",
78
+ "/api-key/delete",
79
+ "/api-key/delete-all-expired-api-keys",
80
+ "/api-key/get",
81
+ "/api-key/list",
82
+ "/api-key/update",
83
+ "/api-key/verify",
84
+ ];
85
+
86
+ // The routes an authorization server serves that the app does not use: the
87
+ // session-minted JWT, and the consumer's own listing and revocation of grants
88
+ // that `consent` rows are reached through, never through a session.
89
+ const MCP_DISABLED_PATHS = [
90
+ "/token",
91
+ "/oauth2/get-consent",
92
+ "/oauth2/get-consents",
93
+ "/oauth2/update-consent",
94
+ "/oauth2/delete-consent",
95
+ ];
96
+
97
+ // Better Auth helpers re-exported: docs/architecture/plugins/auth.md, "Worker runtime".
98
+ export type { BetterAuthPlugin } from "better-auth";
99
+ export {
100
+ APIError,
101
+ createAuthEndpoint,
102
+ createAuthMiddleware,
103
+ getSessionFromCtx,
104
+ isAPIError,
105
+ } from "better-auth/api";
106
+ export { setSessionCookie } from "better-auth/cookies";
107
+ export { customSession } from "better-auth/plugins/custom-session";
108
+
109
+ export type { OtpType } from "../types.ts";
110
+ export type { OAuth, VerifiedAgent } from "./oauth.ts";
111
+ // The `auth.*` procedures' types name these, so a declaration emit of the
112
+ // consumer's generated `.slotform/worker.ts` names them through this subpath.
113
+ export type {
114
+ AcceptedInvitation,
115
+ ActiveOrganization,
116
+ CreatedDevice,
117
+ Device,
118
+ Invitation,
119
+ InvitationStatus,
120
+ OAuthClientPublic,
121
+ OAuthGrant,
122
+ OrganizationMember,
123
+ RejectedInvitation,
124
+ } from "./outputs.ts";
125
+ export type { AuthProcedureFactory, OAuthRedirect } from "./procedures.ts";
126
+ // The request context carries a `Tenancy` and an `AuthRateLimiter`, so a declaration
127
+ // emit of the consumer's generated `.slotform/procedure.ts` names them through this subpath.
128
+ export type { AuthRateLimiter } from "./rate-limit.ts";
129
+ export type { Tenancy } from "./tenancy.ts";
130
+
131
+ // Consumer-implemented hooks: docs/architecture/plugins/auth.md, "Callbacks".
132
+ export interface AuthCallbacks<TEnv = unknown> {
133
+ // Required while `emailOtp` is on: the runtime refuses to build without it.
134
+ sendOTP?(
135
+ payload: AuthCallbackPayloads<TEnv>["sendOTP"],
136
+ ): void | Promise<void>;
137
+ // Required while `magicLink` is on: the runtime refuses to build without it.
138
+ sendMagicLink?(
139
+ payload: AuthCallbackPayloads<TEnv>["sendMagicLink"],
140
+ ): void | Promise<void>;
141
+ sendInvitation?(
142
+ payload: AuthCallbackPayloads<TEnv>["sendInvitation"],
143
+ ): void | Promise<void>;
144
+ // Runs before better-auth deletes the row, and only when
145
+ // `user.deleteUser` is on. Throw to refuse the deletion (an `APIError`
146
+ // surfaces its own status; anything else is a 500). Revocation, storage
147
+ // cleanup, and PII scrubbing all belong here.
148
+ beforeDelete?(
149
+ payload: AuthCallbackPayloads<TEnv>["beforeDelete"],
150
+ ): void | Promise<void>;
151
+ // The passwordless-safe deletion path. When implemented, POST
152
+ // /delete-user emails `url` (a confirmation link) instead of deleting,
153
+ // and the deletion happens on the link's callback with no session
154
+ // freshness requirement. Without it, a passwordless consumer is pushed
155
+ // to `session.freshAge: 0`, which lets any stolen session cookie of any
156
+ // age delete the account in one request.
157
+ sendDeleteVerification?(
158
+ payload: AuthCallbackPayloads<TEnv>["sendDeleteVerification"],
159
+ ): void | Promise<void>;
160
+ // Replaces the OTP better-auth would generate. Return `undefined` to fall
161
+ // back to the default for that request, which is how a fixed review-account
162
+ // code coexists with real codes. Synchronous: better-auth reads the return
163
+ // value directly. Runs for every `OtpType` (sign-in, verification,
164
+ // forget-password, change-email), so key an override on `type` as well as
165
+ // the email; method syntax keeps payloads bivariant, so a handler that
166
+ // narrows `type` compiles but still receives all four at runtime.
167
+ generateOTP?(
168
+ payload: AuthCallbackPayloads<TEnv>["generateOTP"],
169
+ ): string | undefined;
170
+ // The consumer's own better-auth plugins, registered after the
171
+ // framework's: a sign-in flow the framework does not ship (endpoints,
172
+ // tables, hooks) is written here. A table a plugin declares lives in the
173
+ // consumer's schema under the model's name.
174
+ plugins?: BetterAuthPlugin[];
175
+ }
176
+
177
+ export interface AuthRuntimeInput {
178
+ secretVar: string;
179
+ appUrlVar: string;
180
+ callbacks?: AuthCallbacks;
181
+ sameSite?: "strict" | "lax" | "none";
182
+ trustedOrigins?: string[];
183
+ // Dev-server origins, applied only when the worker runs with SLOTFORM_DEV.
184
+ devTrustedOrigins?: string[];
185
+ cookies?: { prefix?: string; domain?: string };
186
+ session?: {
187
+ expiresIn?: number;
188
+ updateAge?: number;
189
+ freshAge?: number;
190
+ };
191
+ user?: {
192
+ deleteUser?: boolean;
193
+ };
194
+ // Codegen reduces the consumer's `{ ac, roles }` to plain records: the
195
+ // statements of `ac` and each role's grants.
196
+ organization?:
197
+ | boolean
198
+ | {
199
+ statements?: Record<string, readonly string[]>;
200
+ roles?: Record<string, Record<string, readonly string[]>>;
201
+ };
202
+ // Who may create an account; `open` when absent.
203
+ signUp?: "open" | "invite" | "first";
204
+ // On by default; `false` drops the email-OTP plugin (OAuth-only consumers).
205
+ emailOtp?: boolean;
206
+ // Off by default; on, adds the magic-link plugin and requires `sendMagicLink`.
207
+ magicLink?: boolean;
208
+ // Resolved provider → env-var references (var names, never secrets — the
209
+ // runtime reads credentials from `env` at request time).
210
+ socialProviders?: Partial<Record<SocialProviderName, ResolvedSocialProvider>>;
211
+ // Set by codegen for `expo`: docs/architecture/plugins/auth.md, "Native client".
212
+ expo?: boolean;
213
+ // Set by codegen for `mcp`: docs/architecture/plugins/auth.md, "MCP OAuth".
214
+ mcp?: boolean;
215
+ // Set by codegen when the consumer enables `devices`: device credentials,
216
+ // bearer keys that stand in for their member's session.
217
+ devices?: boolean;
218
+ // Set by codegen for `passkey`: docs/architecture/plugins/auth.md, "Passkeys".
219
+ passkey?: BakedPasskey;
220
+ // Wrangler rate-limiter binding names: docs/architecture/plugins/auth.md, "Rate limiting".
221
+ rateLimiter?: {
222
+ ip: { binding: string };
223
+ email: { binding: string };
224
+ agent?: { binding: string };
225
+ };
226
+ // Slugs an organization may not take: docs/architecture/plugins/auth.md, "Reserved slugs".
227
+ reservedSlugs?: readonly string[];
228
+ // The consumer's scopes module: docs/architecture/plugins/auth.md, "Scopes".
229
+ scopes?: Record<string, unknown>;
230
+ }
231
+
232
+ // Structural surface of the Better Auth instance: docs/architecture/plugins/auth.md, "Worker runtime".
233
+ export type AuthApi = {
234
+ getSession: (opts: { headers: Headers }) => Promise<{
235
+ user: Record<string, unknown>;
236
+ session: Record<string, unknown>;
237
+ } | null>;
238
+ };
239
+
240
+ type TenancyContext<TOptions> = TOptions extends { organization: infer O }
241
+ ? O extends undefined | false
242
+ ? object
243
+ : { tenancy: Tenancy }
244
+ : object;
245
+
246
+ // The OAuth capability exists only with `mcp` on.
247
+ type OAuthContext<TOptions> = TOptions extends { mcp: true }
248
+ ? { oauth: OAuth }
249
+ : object;
250
+
251
+ // `$Infer.Session` and `TOptions`: docs/architecture/plugins/auth.md, "Worker runtime".
252
+ export interface AuthInstance<
253
+ TOptions extends AuthRuntimeInput = AuthRuntimeInput,
254
+ > {
255
+ handler: (request: Request) => Promise<Response>;
256
+ api: AuthApi;
257
+ $Infer: {
258
+ Session: {
259
+ user: SessionUser;
260
+ session: SessionOf<TOptions>;
261
+ };
262
+ };
263
+ }
264
+
265
+ function appOrigin(url: unknown): string[] {
266
+ try {
267
+ return typeof url === "string" ? [new URL(url).origin] : [];
268
+ } catch {
269
+ // A URL var that does not parse names no origin; Better Auth refuses it as
270
+ // `baseURL` when the instance builds.
271
+ return [];
272
+ }
273
+ }
274
+
275
+ // The origins the instance trusts, which a sign-in link's redirect is held to:
276
+ // the baked list, plus the dev-server origins under SLOTFORM_DEV. The instance
277
+ // is built with the list alone: Better Auth trusts its own base URL besides,
278
+ // so a redirect check names that origin too.
279
+ function trustedOriginsOf(
280
+ options: Pick<AuthRuntimeInput, "trustedOrigins" | "devTrustedOrigins">,
281
+ env: Record<string, unknown>,
282
+ ): string[] {
283
+ return [
284
+ ...(options.trustedOrigins ?? []),
285
+ ...(isDevMode(env) ? (options.devTrustedOrigins ?? []) : []),
286
+ ];
287
+ }
288
+
289
+ // A callback an option on requires: the runtime refuses to build without it.
290
+ function missingCallback(callback: string, option: string, off: string): Error {
291
+ return new Error(
292
+ `auth: \`${option}\` is on but the callbacks file defines no \`${callback}\`. Implement \`${callback}\` in the auth callbacks file (\`auth.slots.callbackFile\`), or set \`${off}\`.`,
293
+ );
294
+ }
295
+
296
+ // The grants the roles table resolves: the consumer's, else better-auth's own.
297
+ function organizationRoles(options: AuthRuntimeInput): Record<string, unknown> {
298
+ return typeof options.organization === "object" && options.organization.roles
299
+ ? options.organization.roles
300
+ : defaultOrgRoles;
301
+ }
302
+
303
+ function buildAuth(
304
+ env: Record<string, unknown>,
305
+ db: unknown,
306
+ options: AuthRuntimeInput,
307
+ ) {
308
+ // The options schema refuses `mcp` and a closed `signUp` without
309
+ // `organization`, so the baked options never hold either alone.
310
+ const plugins: BetterAuthPlugin[] = [];
311
+ // The grant deletions of the organization hooks run without an endpoint
312
+ // context, so they reach the instance through this once it exists.
313
+ let authContext: Promise<{ adapter: GrantAdapter }> | undefined;
314
+ const mcpSetup = options.mcp
315
+ ? mcpPlugins({
316
+ appUrl: appUrlOf(env, options.appUrlVar),
317
+ db,
318
+ roles: organizationRoles(options),
319
+ membership: consumerMembership(options.scopes),
320
+ context: () => {
321
+ if (!authContext) throw new Error("auth: auth is not built");
322
+ return authContext;
323
+ },
324
+ })
325
+ : undefined;
326
+
327
+ const policy =
328
+ options.signUp === "invite" || options.signUp === "first"
329
+ ? signUpPolicy(
330
+ options.signUp,
331
+ // `GrantAdapter` and `PolicyAdapter` are two slices of Better Auth's one adapter.
332
+ async () => (await authContext)?.adapter as unknown as PolicyAdapter,
333
+ )
334
+ : undefined;
335
+ if (policy) plugins.push(policy.plugin);
336
+
337
+ if (options.emailOtp !== false) {
338
+ const sendOTP = options.callbacks?.sendOTP;
339
+ if (!sendOTP)
340
+ throw missingCallback("sendOTP", "emailOtp", "emailOtp: false");
341
+ // The fixture member's code under `slotform screens serve` (which sets
342
+ // `SLOTFORM_DEV`): the one address's code is fixed, every other's is its own.
343
+ const serveCode =
344
+ isDevMode(env) && typeof env.SLOTFORM_SERVE_CODE === "string"
345
+ ? env.SLOTFORM_SERVE_CODE
346
+ : undefined;
347
+ plugins.push(
348
+ emailOTP({
349
+ sendVerificationOTP: async ({ email, otp, type }) => {
350
+ await sendOTP({ email, code: otp, type, env });
351
+ },
352
+ // The key must be absent when the consumer has no callback:
353
+ // better-auth spreads these options over its defaults, so an
354
+ // explicit `generateOTP: undefined` overwrites the default
355
+ // generator and crashes every OTP send.
356
+ ...(options.callbacks?.generateOTP || serveCode
357
+ ? {
358
+ generateOTP: ({
359
+ email,
360
+ type,
361
+ }: {
362
+ email: string;
363
+ type: OtpType;
364
+ }) =>
365
+ email === env.SLOTFORM_SERVE_EMAIL
366
+ ? serveCode
367
+ : options.callbacks?.generateOTP?.({ email, type, env }),
368
+ }
369
+ : {}),
370
+ // Pinned, not options (the length is `OTP_LENGTH`, which `verifyOtp`'s input shares): the attempt cap is the actual brute-force
371
+ // gate (the verify path is only IP-limited), so it must never
372
+ // drift on a dependency bump.
373
+ otpLength: OTP_LENGTH,
374
+ expiresIn: 300,
375
+ allowedAttempts: 3,
376
+ }),
377
+ );
378
+ }
379
+
380
+ if (options.magicLink) {
381
+ const sendMagicLink = options.callbacks?.sendMagicLink;
382
+ if (!sendMagicLink)
383
+ throw missingCallback("sendMagicLink", "magicLink", "magicLink: false");
384
+ plugins.push(
385
+ magicLink({
386
+ sendMagicLink: async ({ email, url, token }) => {
387
+ await sendMagicLink({ email, url, token, env });
388
+ },
389
+ // Pinned, not options, as the OTP's are: a dependency bump never
390
+ // moves them. A token is spent on its first verification, so
391
+ // `allowedAttempts` is never passed.
392
+ expiresIn: 300,
393
+ disableSignUp: false,
394
+ storeToken: "hashed",
395
+ }),
396
+ );
397
+ }
398
+
399
+ if (options.organization) {
400
+ const sendInvitation = options.callbacks?.sendInvitation;
401
+ if (!sendInvitation)
402
+ throw missingCallback(
403
+ "sendInvitation",
404
+ "organization",
405
+ "organization: false",
406
+ );
407
+ const orgConfig =
408
+ typeof options.organization === "object" ? options.organization : {};
409
+ // better-auth's org plugin reads `.authorize()`/`.statements` off each
410
+ // `roles` entry directly (permission.mjs's `hasPermissionFn`), not the
411
+ // bare `{resource: actions[]}` records codegen bakes, so every role is
412
+ // rebuilt through better-auth's own access control. Its `ac` is read
413
+ // only under dynamic access control, which stays off.
414
+ const ac = orgConfig.statements
415
+ ? createBetterAuthAccessControl(orgConfig.statements)
416
+ : undefined;
417
+ const grantsByRole: Record<
418
+ string,
419
+ Record<string, readonly string[]>
420
+ > = orgConfig.roles ?? defaultOrgRoles;
421
+ const reserved = new Set(options.reservedSlugs ?? []);
422
+ plugins.push(
423
+ reservedSlugCheck(reserved),
424
+ organization({
425
+ // better-auth checks a slug is free, never that the app's own
426
+ // routes leave it free: both writes that set one refuse it here.
427
+ organizationHooks: {
428
+ beforeCreateOrganization: async ({ organization }) =>
429
+ refuseReservedSlug(reserved, organization.slug),
430
+ beforeUpdateOrganization: async ({ organization }) =>
431
+ refuseReservedSlug(reserved, organization.slug),
432
+ // With `mcp`, a member's grants end with their membership.
433
+ ...mcpSetup?.organizationHooks,
434
+ },
435
+ // biome-ignore lint/suspicious/noExplicitAny: AccessControl type is internal to better-auth.
436
+ ac: ac as any,
437
+ roles: Object.fromEntries(
438
+ Object.entries(grantsByRole).map(([name, grants]) => [
439
+ name,
440
+ buildAcRole(grants),
441
+ ]),
442
+ // biome-ignore lint/suspicious/noExplicitAny: roles shape is user-provided.
443
+ ) as any,
444
+ async sendInvitationEmail(data) {
445
+ await sendInvitation({
446
+ invitationId: data.id,
447
+ email: data.email,
448
+ role: data.role,
449
+ organization: {
450
+ id: data.organization.id,
451
+ name: data.organization.name,
452
+ slug: data.organization.slug,
453
+ },
454
+ inviter: {
455
+ id: data.inviter.user.id,
456
+ name: data.inviter.user.name,
457
+ email: data.inviter.user.email,
458
+ },
459
+ env,
460
+ });
461
+ },
462
+ }),
463
+ );
464
+ }
465
+
466
+ if (options.expo) {
467
+ plugins.push(expo());
468
+ }
469
+
470
+ if (options.passkey) {
471
+ plugins.push(passkey(passkeyFor(options.passkey, env)));
472
+ }
473
+
474
+ // jwt, the OAuth provider and CIMD, then the guards around them, before the
475
+ // consumer's own plugins.
476
+ if (mcpSetup) plugins.push(...mcpSetup.plugins);
477
+
478
+ if (options.devices) plugins.push(...devicePlugins());
479
+
480
+ plugins.push(...(options.callbacks?.plugins ?? []));
481
+
482
+ // Provider credentials are read from env: docs/architecture/plugins/auth.md, "Social providers".
483
+ const socialProviders: NonNullable<BetterAuthOptions["socialProviders"]> = {};
484
+ const google = options.socialProviders?.google;
485
+ if (google) {
486
+ socialProviders.google = {
487
+ clientId: env[google.clientIdVar] as string,
488
+ clientSecret: env[google.clientSecretVar] as string,
489
+ };
490
+ }
491
+ const apple = options.socialProviders?.apple;
492
+ if (apple) {
493
+ socialProviders.apple = {
494
+ clientId: env[apple.clientIdVar] as string,
495
+ clientSecret: env[apple.clientSecretVar] as string,
496
+ appBundleIdentifier: apple.appBundleIdentifier,
497
+ };
498
+ }
499
+ const socialProvidersOption =
500
+ Object.keys(socialProviders).length > 0 ? socialProviders : undefined;
501
+
502
+ // Dev origins and `sameSite`: docs/architecture/plugins/auth.md, "Origins and cookies".
503
+ const devOrigins = isDevMode(env) ? (options.devTrustedOrigins ?? []) : [];
504
+ const trustedOrigins = trustedOriginsOf(options, env);
505
+ const sameSite = devOrigins.length > 0 ? "none" : options.sameSite;
506
+
507
+ const instance = betterAuth({
508
+ baseURL: appUrlOf(env, options.appUrlVar),
509
+ secret: env[options.secretVar] as string,
510
+ trustedOrigins,
511
+ socialProviders: socialProvidersOption,
512
+ // biome-ignore lint/suspicious/noExplicitAny: drizzleAdapter DB type is opaque.
513
+ database: drizzleAdapter(db as any, {
514
+ provider: "sqlite",
515
+ // The Drizzle adapter's schema map: docs/architecture/plugins/auth.md, "Schema tables".
516
+ schema: Object.assign(
517
+ {},
518
+ (db as { _?: { fullSchema?: Record<string, unknown> } })._?.fullSchema,
519
+ ...tableSetsOf(options).map((set) => set.tables),
520
+ ),
521
+ }),
522
+ advanced: {
523
+ cookiePrefix: options.cookies?.prefix,
524
+ crossSubDomainCookies: options.cookies?.domain
525
+ ? { enabled: true, domain: options.cookies.domain }
526
+ : undefined,
527
+ defaultCookieAttributes: sameSite
528
+ ? {
529
+ sameSite,
530
+ secure: sameSite === "none",
531
+ }
532
+ : undefined,
533
+ // Without it session.ipAddress is wrong behind the CF edge.
534
+ ipAddress: { ipAddressHeaders: [CLIENT_IP_HEADER] },
535
+ },
536
+ session: {
537
+ expiresIn: options.session?.expiresIn,
538
+ updateAge: options.session?.updateAge,
539
+ freshAge: options.session?.freshAge,
540
+ // Signed session cache: docs/architecture/plugins/auth.md, "Worker runtime".
541
+ cookieCache: options.expo
542
+ ? { enabled: false }
543
+ : { enabled: true, maxAge: 300 },
544
+ },
545
+ user: options.user
546
+ ? {
547
+ deleteUser: options.user.deleteUser
548
+ ? {
549
+ enabled: true,
550
+ beforeDelete: async (user, request) => {
551
+ await options.callbacks?.beforeDelete?.({
552
+ // Better Auth's user row carries the fields `AuthUser` names.
553
+ user: user as AuthUser,
554
+ request,
555
+ env,
556
+ });
557
+ },
558
+ // Conditional spread, same reason as generateOTP: an
559
+ // undefined-valued key would make better-auth treat the
560
+ // email-verification path as configured.
561
+ ...(options.callbacks?.sendDeleteVerification
562
+ ? {
563
+ sendDeleteAccountVerification: async (data: {
564
+ user: unknown;
565
+ url: string;
566
+ token: string;
567
+ }) => {
568
+ await options.callbacks?.sendDeleteVerification?.({
569
+ user: data.user as AuthUser,
570
+ url: data.url,
571
+ token: data.token,
572
+ env,
573
+ });
574
+ },
575
+ }
576
+ : {}),
577
+ }
578
+ : undefined,
579
+ }
580
+ : undefined,
581
+ // Session deletions are announced; the sign-up policy runs first: docs/architecture/plugins/auth.md, "Session end".
582
+ databaseHooks: {
583
+ ...(policy ? { user: { create: { before: policy.beforeCreate } } } : {}),
584
+ session: {
585
+ delete: {
586
+ after: async (row) => publishSessionEnded(row),
587
+ },
588
+ },
589
+ },
590
+ plugins,
591
+ ...(options.mcp || options.devices
592
+ ? {
593
+ disabledPaths: [
594
+ ...(options.mcp ? MCP_DISABLED_PATHS : []),
595
+ ...(options.devices ? DEVICE_DISABLED_PATHS : []),
596
+ ],
597
+ }
598
+ : {}),
599
+ });
600
+ // The instance's inferred type holds `$context` as Better Auth's full
601
+ // context; the hooks need only its adapter.
602
+ authContext = instance.$context as unknown as Promise<{
603
+ adapter: GrantAdapter;
604
+ }>;
605
+ return instance;
606
+ }
607
+
608
+ // The scope descriptors a consumer's `src/shared/scopes.ts` exports, read off
609
+ // the module namespace codegen hands over. A descriptor exported under two
610
+ // names is one scope.
611
+ function consumerScopes(module: Record<string, unknown> | undefined): Scope[] {
612
+ const scopes = [...new Set(Object.values(module ?? {}))].filter(
613
+ (value): value is Scope =>
614
+ typeof value === "object" &&
615
+ value !== null &&
616
+ "name" in value &&
617
+ "table" in value &&
618
+ "parent" in value,
619
+ );
620
+ const names = new Set<string>();
621
+ for (const scope of scopes) {
622
+ if (names.has(scope.name)) {
623
+ throw new Error(
624
+ `auth: two scopes are named "${scope.name}"; scope names are unique.`,
625
+ );
626
+ }
627
+ names.add(scope.name);
628
+ }
629
+ return scopes;
630
+ }
631
+
632
+ // The membership predicate the same module exports, at most one.
633
+ function consumerMembership(
634
+ module: Record<string, unknown> | undefined,
635
+ ): Membership | null {
636
+ const declared = Object.entries(module ?? {}).filter(
637
+ (entry): entry is [string, Membership] =>
638
+ typeof entry[1] === "object" &&
639
+ entry[1] !== null &&
640
+ "kind" in entry[1] &&
641
+ entry[1].kind === "membership",
642
+ );
643
+ // A predicate exported under two names is one predicate.
644
+ const distinct = [...new Set(declared.map(([, membership]) => membership))];
645
+ if (distinct.length > 1) {
646
+ // One export name for each distinct predicate.
647
+ const names = distinct
648
+ .map((membership) => {
649
+ const [name] = declared.find(([, found]) => found === membership) ?? [];
650
+ return `"${name}"`;
651
+ })
652
+ .join(", ");
653
+ throw new Error(
654
+ `auth: the scopes module exports ${distinct.length} memberships (${names}); export one defineMembership.`,
655
+ );
656
+ }
657
+ return distinct[0] ?? null;
658
+ }
659
+
660
+ // The scopes a module exports that have a lookup: those whose `slug` is a
661
+ // column, keyed by name, plus the organization root.
662
+ type ScopeLookups<TOptions> = {
663
+ organization: ScopeLookup<typeof organizationScope>;
664
+ } & (TOptions extends { scopes: infer M }
665
+ ? {
666
+ [K in keyof M as M[K] extends Scope<infer N, unknown, SQLiteColumn>
667
+ ? N
668
+ : never]: M[K] extends Scope ? ScopeLookup<M[K]> : never;
669
+ }
670
+ : Record<never, never>);
671
+
672
+ // What a route set adds only while its option is on: organizations (`organization`
673
+ // truthy), email OTP (on unless `emailOtp: false`, as the runtime builds it)
674
+ // and magic links (`magicLink: true`).
675
+ type WithOrganization<TOptions, T> = TOptions extends { organization: infer O }
676
+ ? O extends undefined | false
677
+ ? Record<never, never>
678
+ : T
679
+ : Record<never, never>;
680
+ type WithEmailOtp<TOptions, T> = TOptions extends { emailOtp: false }
681
+ ? Record<never, never>
682
+ : T;
683
+ type WithMagicLink<TOptions, T> = TOptions extends { magicLink: true }
684
+ ? T
685
+ : Record<never, never>;
686
+
687
+ // With `mcp`, a call made inside an authorization takes the page's signed
688
+ // query and may answer the redirect that resumes it: these procedures replace
689
+ // their plain forms, and `auth.oauth` joins.
690
+ type WithMcp<TOptions, T> = TOptions extends { mcp: true }
691
+ ? T
692
+ : Record<never, never>;
693
+ type IfMcp<TOptions, Mcp, Plain> = TOptions extends { mcp: true } ? Mcp : Plain;
694
+ type Swap<Base, Over> = Omit<Base, keyof Over> & Over;
695
+
696
+ type SignInRoutes<TOptions> = WithEmailOtp<
697
+ TOptions,
698
+ {
699
+ signIn: IfMcp<
700
+ TOptions,
701
+ ReturnType<typeof emailOtpOauthProcedures>,
702
+ ReturnType<typeof emailOtpProcedures>
703
+ >;
704
+ }
705
+ > &
706
+ WithMagicLink<
707
+ TOptions,
708
+ {
709
+ signIn: IfMcp<
710
+ TOptions,
711
+ ReturnType<typeof magicLinkOauthProcedures>,
712
+ ReturnType<typeof magicLinkProcedures>
713
+ >;
714
+ }
715
+ >;
716
+
717
+ type OrganizationProcedures<TOptions> = IfMcp<
718
+ TOptions,
719
+ {
720
+ organization: Swap<
721
+ ReturnType<typeof organizationProcedures>["organization"],
722
+ { setActive: ReturnType<typeof setActiveOauthProcedure> }
723
+ >;
724
+ },
725
+ ReturnType<typeof organizationProcedures>
726
+ >;
727
+
728
+ type OrganizationRoutes<TOptions> = WithOrganization<
729
+ TOptions,
730
+ OrganizationProcedures<TOptions> & {
731
+ orgRules: ReturnType<typeof orgRulesProcedure>;
732
+ scope: {
733
+ [N in keyof ScopeLookups<TOptions>]: {
734
+ bySlug: ScopeLookups<TOptions>[N];
735
+ };
736
+ };
737
+ }
738
+ >;
739
+
740
+ type DeviceRoutes<TOptions> = TOptions extends { devices: true }
741
+ ? ReturnType<typeof deviceProcedures>
742
+ : Record<never, never>;
743
+
744
+ type OAuthRoutes<TOptions> = WithMcp<
745
+ TOptions,
746
+ ReturnType<typeof oauthProcedures>
747
+ >;
748
+
749
+ type AuthRoutes<TOptions> = {
750
+ auth: ReturnType<typeof sessionProcedures> &
751
+ SignInRoutes<TOptions> &
752
+ OrganizationRoutes<TOptions> &
753
+ OAuthRoutes<TOptions> &
754
+ DeviceRoutes<TOptions>;
755
+ };
756
+
757
+ export default function authRuntime<TOptions extends AuthRuntimeInput>(
758
+ options: TOptions,
759
+ ): RuntimePlugin<
760
+ "auth",
761
+ object,
762
+ {
763
+ auth: AuthInstance<TOptions>;
764
+ _rateLimiter?: AuthRateLimiter;
765
+ } & TenancyContext<TOptions> &
766
+ OAuthContext<TOptions>,
767
+ AuthRoutes<TOptions>
768
+ > {
769
+ const roles = organizationRoles(options);
770
+ // One instance per `env` of this runtime: Workers hand the same `env`
771
+ // object to every request of an isolate, so a `WeakMap` on it builds
772
+ // Better Auth once per isolate, with this runtime's options.
773
+ const instances = new WeakMap<object, ReturnType<typeof buildAuth>>();
774
+ const scopes = consumerScopes(options.scopes);
775
+ const membership = consumerMembership(options.scopes);
776
+
777
+ return {
778
+ name: "auth",
779
+ // `context()` reads `upstream.db`: docs/architecture/plugins/auth.md, "Worker runtime".
780
+ dependsOn: ["db"],
781
+ // Framework-owned procedures: docs/architecture/plugins/auth.md, "Procedures".
782
+ routes(procedure: unknown) {
783
+ // The worker passes the `api` plugin's `createProcedure<TContext>()` result;
784
+ // `RuntimePlugin` types the argument `unknown`. Its context carries
785
+ // the `tenancy` and the `api` endpoints of the plugins this plugin's
786
+ // context() provides when their options are on, and each group below
787
+ // reads only what its option provides.
788
+ const factory = procedure as AuthProcedureFactory;
789
+
790
+ const emailOtp = options.mcp
791
+ ? emailOtpOauthProcedures
792
+ : emailOtpProcedures;
793
+ const magicLink = options.mcp
794
+ ? magicLinkOauthProcedures
795
+ : magicLinkProcedures;
796
+ const signIn = {
797
+ ...(options.emailOtp === false ? {} : emailOtp(factory)),
798
+ ...(options.magicLink ? magicLink(factory) : {}),
799
+ };
800
+ // The conditional types `SignInRoutes<TOptions>` and
801
+ // `OrganizationRoutes<TOptions>` cannot be resolved inside the generic
802
+ // body; each fragment is built from the options that select it.
803
+ const signInRoutes = (
804
+ Object.keys(signIn).length > 0 ? { signIn } : {}
805
+ ) as SignInRoutes<TOptions>;
806
+ const organizationRoutes = (
807
+ options.organization
808
+ ? {
809
+ // With `mcp`, `setActive` is the one that takes the authorization's
810
+ // signed query.
811
+ ...(options.mcp
812
+ ? {
813
+ organization: {
814
+ ...organizationProcedures(factory).organization,
815
+ setActive: setActiveOauthProcedure(factory),
816
+ },
817
+ }
818
+ : organizationProcedures(factory)),
819
+ [ORG_RULES_PATH[1]]: orgRulesProcedure(factory, roles),
820
+ [SCOPE_ROUTES_PATH[1]]: Object.fromEntries(
821
+ [organizationScope, ...scopes]
822
+ .filter((scope) => scope.slug !== null)
823
+ .map((scope) => [
824
+ scope.name,
825
+ { bySlug: bySlugProcedure(factory, scope) },
826
+ ]),
827
+ ),
828
+ }
829
+ : {}
830
+ ) as OrganizationRoutes<TOptions>;
831
+
832
+ const oauthRoutes = (
833
+ options.mcp ? oauthProcedures(factory) : {}
834
+ ) as OAuthRoutes<TOptions>;
835
+
836
+ const deviceRoutes = (
837
+ options.devices ? deviceProcedures(factory) : {}
838
+ ) as DeviceRoutes<TOptions>;
839
+
840
+ return {
841
+ [ORG_RULES_PATH[0]]: {
842
+ ...sessionProcedures(factory),
843
+ ...signInRoutes,
844
+ ...organizationRoutes,
845
+ ...oauthRoutes,
846
+ ...deviceRoutes,
847
+ },
848
+ };
849
+ },
850
+ context(env, upstream) {
851
+ // `RuntimePlugin` types `env` and `upstream` as `unknown`; `dependsOn`
852
+ // makes `upstream.db` the drizzle client, and `env` is the worker's bindings.
853
+ const u = upstream as { db: unknown };
854
+ const e = env as Record<string, unknown>;
855
+
856
+ const rateLimiter: AuthRateLimiter = {};
857
+ // A rate-limiter binding is a Wrangler binding `Env` does not type.
858
+ const agentBinding = options.rateLimiter?.agent?.binding;
859
+ const agentLimiter =
860
+ agentBinding && !isDevMode(e)
861
+ ? (e[agentBinding] as RateLimitBinding | undefined)
862
+ : undefined;
863
+ const ipBinding = options.rateLimiter?.ip.binding;
864
+ if (ipBinding && e[ipBinding]) {
865
+ rateLimiter.ip = e[ipBinding] as RateLimitBinding;
866
+ }
867
+ const emailBinding = options.rateLimiter?.email.binding;
868
+ if (emailBinding && e[emailBinding]) {
869
+ rateLimiter.email = e[emailBinding] as RateLimitBinding;
870
+ }
871
+
872
+ let auth = instances.get(e);
873
+ if (!auth) {
874
+ auth = buildAuth(e, u.db, options);
875
+ instances.set(e, auth);
876
+ }
877
+ return {
878
+ // `buildAuth` returns whatever better-auth infers from the
879
+ // literal built inside `buildAuth`; it structurally satisfies
880
+ // `AuthApi` at runtime. This cast is the one place the
881
+ // hand-declared `AuthInstance<TOptions>` contract stands in for
882
+ // better-auth's own (differently-parameterized) inferred type; the
883
+ // cast in `createOAuth`'s `auth` below is the same.
884
+ auth: auth as unknown as AuthInstance<TOptions>,
885
+ ...(options.organization
886
+ ? { tenancy: createTenancy(u.db, roles, membership) }
887
+ : {}),
888
+ ...(options.mcp
889
+ ? {
890
+ oauth: createOAuth({
891
+ auth: auth as unknown as Parameters<
892
+ typeof createOAuth
893
+ >[0]["auth"],
894
+ db: u.db,
895
+ roles,
896
+ membership,
897
+ appUrl: appUrlOf(e, options.appUrlVar),
898
+ limiter: agentLimiter,
899
+ }),
900
+ }
901
+ : {}),
902
+ ...(rateLimiter.ip || rateLimiter.email
903
+ ? { _rateLimiter: rateLimiter }
904
+ : {}),
905
+ _trustedOrigins: [
906
+ ...trustedOriginsOf(options, e),
907
+ ...appOrigin(appUrlOf(e, options.appUrlVar)),
908
+ ],
909
+ } as {
910
+ auth: AuthInstance<TOptions>;
911
+ _rateLimiter?: AuthRateLimiter;
912
+ _trustedOrigins?: readonly string[];
913
+ } & TenancyContext<TOptions> &
914
+ OAuthContext<TOptions>;
915
+ },
916
+ async fetch(request, _env, upstream) {
917
+ const url = new URL(request.url);
918
+ // With `mcp`, the discovery documents are Better Auth's too, behind
919
+ // the same limiter.
920
+ const served =
921
+ url.pathname === AUTH_PREFIX ||
922
+ url.pathname.startsWith(`${AUTH_PREFIX}/`) ||
923
+ (options.mcp &&
924
+ OAUTH_DISCOVERY_PREFIXES.some(
925
+ (prefix) =>
926
+ url.pathname === prefix || url.pathname.startsWith(`${prefix}/`),
927
+ ));
928
+ if (!served) return null;
929
+ const u = upstream as {
930
+ auth: AuthInstance<TOptions>;
931
+ _rateLimiter?: AuthRateLimiter;
932
+ _devMode?: boolean;
933
+ };
934
+ if (!u._devMode) {
935
+ const denied = await checkRateLimit(request, url, u._rateLimiter);
936
+ if (denied) return denied;
937
+ }
938
+ return u.auth.handler(request);
939
+ },
940
+ };
941
+ }