| 1 | import { apiKey } from '@better-auth/api-key'; |
| 2 | import { type Database, |
| 3 | import { betterAuth } |
| 4 | import { drizzleAdapter } |
| 5 | import { |
| 6 | APIError, |
| 7 | createAuthMiddleware, |
| 8 | getSessionFromCtx, |
| 9 | } from 'better-auth/api'; |
| 10 | import { organization, username |
| 11 | import { and, eq |
| 12 | |
| 13 | import { ac, roles |
| 14 | |
| 15 | export type AuthConfig |
| 16 | secret: string |
| 17 | baseURL: string |
| 18 | trustedOrigins?: string |
| 19 | /** Registrable domain to pin session cookies to, e.g. `.example.com`, when the web app and the API sit on sibling subdomains. Unset in local development, where both share `localhost`. */ |
| 20 | cookieDomain?: string |
| 21 | /** Set only when email verification is enabled (EMAIL_VERIFICATION_ENABLED); self-hosted instances without mail configured leave it unset. */ |
| 22 | sendVerificationEmail?: ( |
| 23 | email: string |
| 24 | name?: string |
| 25 | url: string |
| 26 | }) => |
| 27 | /** Set whenever mail is configured; password reset needs no verification flag. */ |
| 28 | sendResetPassword?: ( |
| 29 | email: string |
| 30 | name?: string |
| 31 | url: string |
| 32 | }) => |
| 33 | /** Set whenever mail is configured. Better Auth sends this to the address currently on the account, which is what makes a change reversible. */ |
| 34 | /** After an organization is gone: what it stored outside the database goes too. */ |
| 35 | onOrganizationDeleted?: ( |
| 36 | sendOrganizationInvitation?: ( |
| 37 | email: string |
| 38 | inviter: string |
| 39 | organization: string |
| 40 | role: string |
| 41 | url: string |
| 42 | }) => |
| 43 | sendChangeEmail?: ( |
| 44 | email: string |
| 45 | name?: string |
| 46 | newEmail: string |
| 47 | url: string |
| 48 | }) => |
| 49 | /** Origin of the web app, which owns the verify and reset forms. */ |
| 50 | webAppUrl?: string |
| 51 | /** Set only when GitHub imports are configured. GitHub is linked to an existing account for its token, never used to sign up. */ |
| 52 | github?: { |
| 53 | }; |
| 54 | |
| 55 | /** better-auth defaults `callbackURL` to `/`, which resolves against the API. Point relative callbacks at the web app instead, where the forms live. */ |
| 56 | export function withWebCallback(url |
| 57 | if (!webAppUrl) |
| 58 | const parsed = |
| 59 | const callback = |
| 60 | if (!/^https?: |
| 61 | parsed.searchParams.set |
| 62 | } |
| 63 | return parsed.href |
| 64 | } |
| 65 | |
| 66 | /** Endpoints that take an address in the body and look a user up by it. */ |
| 67 | const EMAIL_LOOKUP_PATHS = [ |
| 68 | |
| 69 | /** Swaps an account's verified extra address for the `user.email` Better Auth knows (unverified ones must not let anyone sign in as the owner), and makes the organization slug check refuse a name a user or a route holds. */ |
| 70 | function beforeAuthHooks(db: |
| 71 | return createAuthMiddleware(async |
| 72 | if (ctx.path |
| 73 | const body = |
| 74 | await assertNameFree(db |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | if (ctx.path |
| 79 | const body = |
| 80 | const next = |
| 81 | typeof body?.newEmail |
| 82 | ? body.newEmail. |
| 83 | : null; |
| 84 | if (!next) |
| 85 | |
| 86 | // Checked here as well as in the database hook, so a taken address is refused before a verification mail goes out. |
| 87 | const session = |
| 88 | await assertEmailAvailable(db |
| 89 | return; |
| 90 | } |
| 91 | |
| 92 | if (!EMAIL_LOOKUP_PATHS.includes |
| 93 | |
| 94 | const body = |
| 95 | const input = |
| 96 | if (!input) |
| 97 | |
| 98 | const [match] |
| 99 | .select({ email: |
| 100 | .from(schema.userEmail |
| 101 | .innerJoin(schema.user |
| 102 | .where( |
| 103 | and( |
| 104 | eq(schema.userEmail |
| 105 | eq(schema.userEmail |
| 106 | ), |
| 107 | ) |
| 108 | .limit(1); |
| 109 | |
| 110 | if (!match) |
| 111 | |
| 112 | return { context: |
| 113 | }); |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Claims an address for an account before it is written to `user.email`. |
| 118 | * |
| 119 | * Better Auth checks uniqueness against `user.email` alone, so without this a change-email could take an address another account verified as an extra. Claiming the account's own extra drops that row instead. |
| 120 | */ |
| 121 | async function assertEmailAvailable |
| 122 | db: Database |
| 123 | email: string, |
| 124 | userId: string |
| 125 | ) { |
| 126 | const taken = |
| 127 | APIError.from('UNPROCESSABLE_ENTITY |
| 128 | message: 'That email address is already taken', |
| 129 | code: 'EMAIL_ALREADY_TAKEN', |
| 130 | }); |
| 131 | |
| 132 | const [[primaryOwner], |
| 133 | db |
| 134 | .select({ id: |
| 135 | .from(schema.user |
| 136 | .where(eq(sql |
| 137 | db |
| 138 | .select({ |
| 139 | id: schema.userEmail |
| 140 | userId: schema.userEmail |
| 141 | verified: schema.userEmail |
| 142 | }) |
| 143 | .from(schema.userEmail |
| 144 | .where(eq(schema |
| 145 | ]); |
| 146 | |
| 147 | if (primaryOwner && |
| 148 | if (!extraOwner) |
| 149 | if (extraOwner.userId |
| 150 | |
| 151 | if (!extraOwner.verified |
| 152 | throw APIError.from( |
| 153 | message: 'Confirm that address from the link sent to it first', |
| 154 | code: 'EMAIL_NOT_VERIFIED', |
| 155 | }); |
| 156 | } |
| 157 | |
| 158 | return extraOwner.id |
| 159 | } |
| 160 | |
| 161 | /** The web app's own top-level routes: an account under one of these names would have no profile to reach. */ |
| 162 | const RESERVED_NAMES = new |
| 163 | 'api', |
| 164 | 'auth', |
| 165 | 'dashboard', |
| 166 | 'search', |
| 167 | 'settings', |
| 168 | ]); |
| 169 | |
| 170 | /** Why `name` cannot be taken as a username or an organization slug, or null when it can. `/name/repo` resolves a name to a user or an organization, so the two must never share one. Case is ignored, as both are matched lowercase. */ |
| 171 | async function nameConflict( |
| 172 | db: Database |
| 173 | name: string, |
| 174 | taking: 'username |
| 175 | ) { |
| 176 | const lowered = |
| 177 | if (RESERVED_NAMES.has |
| 178 | |
| 179 | const [taken] |
| 180 | taking === 'username' |
| 181 | ? await db |
| 182 | .select({ id: |
| 183 | .from(schema.organization |
| 184 | .where(eq(sql |
| 185 | : await db |
| 186 | .select({ id: |
| 187 | .from(schema.user |
| 188 | .where(eq(sql |
| 189 | if (!taken) |
| 190 | |
| 191 | return taking === |
| 192 | ? 'An organization already uses that name' |
| 193 | : 'A user already has that name'; |
| 194 | } |
| 195 | |
| 196 | async function assertNameFree( |
| 197 | db: Database |
| 198 | name: unknown, |
| 199 | taking: 'username |
| 200 | ) { |
| 201 | if (typeof name |
| 202 | const conflict = |
| 203 | if (!conflict) |
| 204 | |
| 205 | throw APIError.from( |
| 206 | message: conflict, |
| 207 | code: 'NAME_ALREADY_TAKEN', |
| 208 | }); |
| 209 | } |
| 210 | |
| 211 | /** Better Auth's username availability check knows only users; an organization's slug or a route name is just as taken. */ |
| 212 | function afterAuthHooks(db: |
| 213 | return createAuthMiddleware(async |
| 214 | if (ctx.path |
| 215 | |
| 216 | const returned = |
| 217 | const body = |
| 218 | if (returned?.available |
| 219 | return; |
| 220 | } |
| 221 | if (await nameConflict |
| 222 | return ctx.json |
| 223 | } |
| 224 | }); |
| 225 | } |
| 226 | |
| 227 | /** Same check, then the write: the account's own extra row is dropped so the address is not held twice once it lands on `user.email`. */ |
| 228 | async function claimEmailForAccount |
| 229 | db: Database |
| 230 | email: string, |
| 231 | userId: string |
| 232 | ) { |
| 233 | const extraId = |
| 234 | if (!extraId) |
| 235 | |
| 236 | await db.delete |
| 237 | } |
| 238 | |
| 239 | export function createAuth(db |
| 240 | return betterAuth({ |
| 241 | secret: config.secret |
| 242 | baseURL: config.baseURL |
| 243 | trustedOrigins: config.trustedOrigins |
| 244 | advanced: { |
| 245 | ...(config.cookieDomain |
| 246 | ? { |
| 247 | crossSubDomainCookies: { |
| 248 | enabled: true, |
| 249 | domain: config.cookieDomain |
| 250 | }, |
| 251 | } |
| 252 | : undefined), |
| 253 | ...(process.env |
| 254 | ? { |
| 255 | ipAddress: { |
| 256 | ipAddressHeaders: ['X-Real-IP'], |
| 257 | }, |
| 258 | } |
| 259 | : undefined), |
| 260 | }, |
| 261 | |
| 262 | database: drizzleAdapter(db |
| 263 | provider: 'pg', |
| 264 | }), |
| 265 | socialProviders: config.github |
| 266 | ? { github: { |
| 267 | : undefined, |
| 268 | account: { |
| 269 | encryptOAuthTokens: true, |
| 270 | // GitHub is only ever linked by a signed-in user, whose GitHub address rarely matches; signing in with GitHub never attaches to an account by email. |
| 271 | accountLinking: { allowDifferentEmails: true |
| 272 | }, |
| 273 | hooks: { before: beforeAuthHooks |
| 274 | databaseHooks: { |
| 275 | user: { |
| 276 | create: { |
| 277 | before: async ( |
| 278 | await assertNameFree(db |
| 279 | }, |
| 280 | }, |
| 281 | update: { |
| 282 | before: async ( |
| 283 | await assertNameFree(db |
| 284 | |
| 285 | const next = |
| 286 | typeof data.email |
| 287 | ? data.email. |
| 288 | : null; |
| 289 | if (!next) |
| 290 | |
| 291 | await claimEmailForAccount( |
| 292 | db, |
| 293 | next, |
| 294 | context?.context.session |
| 295 | (typeof data.id |
| 296 | ); |
| 297 | }, |
| 298 | }, |
| 299 | }, |
| 300 | }, |
| 301 | emailAndPassword: { |
| 302 | enabled: true, |
| 303 | requireEmailVerification: Boolean(config |
| 304 | sendResetPassword: config.sendResetPassword |
| 305 | ? async ({ |
| 306 | config.sendResetPassword!({ |
| 307 | email: user.email |
| 308 | name: user.name |
| 309 | url: withWebCallback(url |
| 310 | }) |
| 311 | : undefined, |
| 312 | }, |
| 313 | user: { |
| 314 | changeEmail: { |
| 315 | enabled: true, |
| 316 | // With no mail configured there is nobody to confirm with, and an unverified account would be stuck on its first address forever. |
| 317 | updateEmailWithoutVerification: !config.sendChangeEmail |
| 318 | sendChangeEmailConfirmation: config.sendChangeEmail |
| 319 | ? async ({ |
| 320 | config.sendChangeEmail!({ |
| 321 | email: user.email |
| 322 | name: user.name |
| 323 | newEmail, |
| 324 | url: withWebCallback(url |
| 325 | }) |
| 326 | : undefined, |
| 327 | }, |
| 328 | }, |
| 329 | emailVerification: config.sendVerificationEmail |
| 330 | ? { |
| 331 | sendOnSignUp: true, |
| 332 | autoSignInAfterVerification: true, |
| 333 | sendOnSignIn: true, |
| 334 | sendVerificationEmail: async ( |
| 335 | config.sendVerificationEmail!({ |
| 336 | email: user.email |
| 337 | name: user.name |
| 338 | url: withWebCallback(url |
| 339 | }), |
| 340 | } |
| 341 | : undefined, |
| 342 | plugins: [ |
| 343 | organization({ |
| 344 | ac, |
| 345 | roles, |
| 346 | creatorRole: 'owner', |
| 347 | defaultRole: 'member', |
| 348 | sendInvitationEmail: config.sendOrganizationInvitation |
| 349 | ? async ({ |
| 350 | config.sendOrganizationInvitation!({ |
| 351 | email, |
| 352 | role, |
| 353 | organization: organization.name |
| 354 | inviter: inviter.user |
| 355 | url: `${config. |
| 356 | }) |
| 357 | : undefined, |
| 358 | organizationHooks: { |
| 359 | beforeCreateOrganization: async ( |
| 360 | await assertNameFree(db |
| 361 | }, |
| 362 | beforeUpdateOrganization: async ( |
| 363 | await assertNameFree(db |
| 364 | }, |
| 365 | // Repository rows would cascade away while their stored history stayed behind; deleting a repository is what purges it (docs/0020). |
| 366 | beforeDeleteOrganization: async ( |
| 367 | const [repository] |
| 368 | .select({ id: |
| 369 | .from(schema.repository |
| 370 | .where(eq(schema |
| 371 | .limit(1); |
| 372 | if (!repository) |
| 373 | |
| 374 | throw APIError.from( |
| 375 | message: |
| 376 | 'Delete or transfer the organization’s repositories first', |
| 377 | code: 'ORGANIZATION_HAS_REPOSITORIES', |
| 378 | }); |
| 379 | }, |
| 380 | afterCreateOrganization: async ( |
| 381 | await db |
| 382 | .insert(schema.organizationSettings |
| 383 | .values({ organizationId: |
| 384 | .onConflictDoNothing(); |
| 385 | }, |
| 386 | afterDeleteOrganization: async ( |
| 387 | await config.onOrganizationDeleted |
| 388 | }, |
| 389 | }, |
| 390 | dynamicAccessControl: { |
| 391 | enabled: true, |
| 392 | }, |
| 393 | teams: { |
| 394 | enabled: true, |
| 395 | allowRemovingAllTeams: true, |
| 396 | }, |
| 397 | }), |
| 398 | username({}), |
| 399 | apiKey({ |
| 400 | defaultPrefix: 'ghost_pat_', |
| 401 | rateLimit: { |
| 402 | enabled: true, |
| 403 | maxRequests: 120, |
| 404 | timeWindow: 60000, // |
| 405 | }, |
| 406 | }), |
| 407 | ], |
| 408 | }); |
| 409 | } |
| 410 | |
| 411 | export type Auth |