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