| 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 | }; |
| 52 | |
| 53 | /** better-auth defaults `callbackURL` to `/`, which resolves against the API. Point relative callbacks at the web app instead, where the forms live. */ |
| 54 | export function withWebCallback(url |
| 55 | if (!webAppUrl) |
| 56 | const parsed = |
| 57 | const callback = |
| 58 | if (!/^https?: |
| 59 | parsed.searchParams.set |
| 60 | } |
| 61 | return parsed.href |
| 62 | } |
| 63 | |
| 64 | /** Endpoints that take an address in the body and look a user up by it. */ |
| 65 | const EMAIL_LOOKUP_PATHS = [ |
| 66 | |
| 67 | /** 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. */ |
| 68 | function beforeAuthHooks(db: |
| 69 | return createAuthMiddleware(async |
| 70 | if (ctx.path |
| 71 | const body = |
| 72 | await assertNameFree(db |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | if (ctx.path |
| 77 | const body = |
| 78 | const next = |
| 79 | typeof body?.newEmail |
| 80 | ? body.newEmail. |
| 81 | : null; |
| 82 | if (!next) |
| 83 | |
| 84 | // Checked here as well as in the database hook, so a taken address is refused before a verification mail goes out. |
| 85 | const session = |
| 86 | await assertEmailAvailable(db |
| 87 | return; |
| 88 | } |
| 89 | |
| 90 | if (!EMAIL_LOOKUP_PATHS.includes |
| 91 | |
| 92 | const body = |
| 93 | const input = |
| 94 | if (!input) |
| 95 | |
| 96 | const [match] |
| 97 | .select({ email: |
| 98 | .from(schema.userEmail |
| 99 | .innerJoin(schema.user |
| 100 | .where( |
| 101 | and( |
| 102 | eq(schema.userEmail |
| 103 | eq(schema.userEmail |
| 104 | ), |
| 105 | ) |
| 106 | .limit(1); |
| 107 | |
| 108 | if (!match) |
| 109 | |
| 110 | return { context: |
| 111 | }); |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Claims an address for an account before it is written to `user.email`. |
| 116 | * |
| 117 | * 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. |
| 118 | */ |
| 119 | async function assertEmailAvailable |
| 120 | db: Database |
| 121 | email: string, |
| 122 | userId: string |
| 123 | ) { |
| 124 | const taken = |
| 125 | APIError.from('UNPROCESSABLE_ENTITY |
| 126 | message: 'That email address is already taken', |
| 127 | code: 'EMAIL_ALREADY_TAKEN', |
| 128 | }); |
| 129 | |
| 130 | const [[primaryOwner], |
| 131 | db |
| 132 | .select({ id: |
| 133 | .from(schema.user |
| 134 | .where(eq(sql |
| 135 | db |
| 136 | .select({ |
| 137 | id: schema.userEmail |
| 138 | userId: schema.userEmail |
| 139 | verified: schema.userEmail |
| 140 | }) |
| 141 | .from(schema.userEmail |
| 142 | .where(eq(schema |
| 143 | ]); |
| 144 | |
| 145 | if (primaryOwner && |
| 146 | if (!extraOwner) |
| 147 | if (extraOwner.userId |
| 148 | |
| 149 | if (!extraOwner.verified |
| 150 | throw APIError.from( |
| 151 | message: 'Confirm that address from the link sent to it first', |
| 152 | code: 'EMAIL_NOT_VERIFIED', |
| 153 | }); |
| 154 | } |
| 155 | |
| 156 | return extraOwner.id |
| 157 | } |
| 158 | |
| 159 | /** The web app's own top-level routes: an account under one of these names would have no profile to reach. */ |
| 160 | const RESERVED_NAMES = new |
| 161 | 'api', |
| 162 | 'auth', |
| 163 | 'dashboard', |
| 164 | 'search', |
| 165 | 'settings', |
| 166 | ]); |
| 167 | |
| 168 | /** 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. */ |
| 169 | async function nameConflict( |
| 170 | db: Database |
| 171 | name: string, |
| 172 | taking: 'username |
| 173 | ) { |
| 174 | const lowered = |
| 175 | if (RESERVED_NAMES.has |
| 176 | |
| 177 | const [taken] |
| 178 | taking === 'username' |
| 179 | ? await db |
| 180 | .select({ id: |
| 181 | .from(schema.organization |
| 182 | .where(eq(sql |
| 183 | : await db |
| 184 | .select({ id: |
| 185 | .from(schema.user |
| 186 | .where(eq(sql |
| 187 | if (!taken) |
| 188 | |
| 189 | return taking === |
| 190 | ? 'An organization already uses that name' |
| 191 | : 'A user already has that name'; |
| 192 | } |
| 193 | |
| 194 | async function assertNameFree( |
| 195 | db: Database |
| 196 | name: unknown, |
| 197 | taking: 'username |
| 198 | ) { |
| 199 | if (typeof name |
| 200 | const conflict = |
| 201 | if (!conflict) |
| 202 | |
| 203 | throw APIError.from( |
| 204 | message: conflict, |
| 205 | code: 'NAME_ALREADY_TAKEN', |
| 206 | }); |
| 207 | } |
| 208 | |
| 209 | /** Better Auth's username availability check knows only users; an organization's slug or a route name is just as taken. */ |
| 210 | function afterAuthHooks(db: |
| 211 | return createAuthMiddleware(async |
| 212 | if (ctx.path |
| 213 | |
| 214 | const returned = |
| 215 | const body = |
| 216 | if (returned?.available |
| 217 | return; |
| 218 | } |
| 219 | if (await nameConflict |
| 220 | return ctx.json |
| 221 | } |
| 222 | }); |
| 223 | } |
| 224 | |
| 225 | /** 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`. */ |
| 226 | async function claimEmailForAccount |
| 227 | db: Database |
| 228 | email: string, |
| 229 | userId: string |
| 230 | ) { |
| 231 | const extraId = |
| 232 | if (!extraId) |
| 233 | |
| 234 | await db.delete |
| 235 | } |
| 236 | |
| 237 | export function createAuth(db |
| 238 | return betterAuth({ |
| 239 | secret: config.secret |
| 240 | baseURL: config.baseURL |
| 241 | trustedOrigins: config.trustedOrigins |
| 242 | advanced: config.cookieDomain |
| 243 | ? { |
| 244 | crossSubDomainCookies: { |
| 245 | enabled: true, |
| 246 | domain: config.cookieDomain |
| 247 | }, |
| 248 | } |
| 249 | : undefined, |
| 250 | database: drizzleAdapter(db |
| 251 | provider: 'pg', |
| 252 | }), |
| 253 | hooks: { before: beforeAuthHooks |
| 254 | databaseHooks: { |
| 255 | user: { |
| 256 | create: { |
| 257 | before: async ( |
| 258 | await assertNameFree(db |
| 259 | }, |
| 260 | }, |
| 261 | update: { |
| 262 | before: async ( |
| 263 | await assertNameFree(db |
| 264 | |
| 265 | const next = |
| 266 | typeof data.email |
| 267 | ? data.email. |
| 268 | : null; |
| 269 | if (!next) |
| 270 | |
| 271 | await claimEmailForAccount( |
| 272 | db, |
| 273 | next, |
| 274 | context?.context.session |
| 275 | (typeof data.id |
| 276 | ); |
| 277 | }, |
| 278 | }, |
| 279 | }, |
| 280 | }, |
| 281 | emailAndPassword: { |
| 282 | enabled: true, |
| 283 | requireEmailVerification: Boolean(config |
| 284 | sendResetPassword: config.sendResetPassword |
| 285 | ? async ({ |
| 286 | config.sendResetPassword!({ |
| 287 | email: user.email |
| 288 | name: user.name |
| 289 | url: withWebCallback(url |
| 290 | }) |
| 291 | : undefined, |
| 292 | }, |
| 293 | user: { |
| 294 | changeEmail: { |
| 295 | enabled: true, |
| 296 | // With no mail configured there is nobody to confirm with, and an unverified account would be stuck on its first address forever. |
| 297 | updateEmailWithoutVerification: !config.sendChangeEmail |
| 298 | sendChangeEmailConfirmation: config.sendChangeEmail |
| 299 | ? async ({ |
| 300 | config.sendChangeEmail!({ |
| 301 | email: user.email |
| 302 | name: user.name |
| 303 | newEmail, |
| 304 | url: withWebCallback(url |
| 305 | }) |
| 306 | : undefined, |
| 307 | }, |
| 308 | }, |
| 309 | emailVerification: config.sendVerificationEmail |
| 310 | ? { |
| 311 | sendOnSignUp: true, |
| 312 | autoSignInAfterVerification: true, |
| 313 | sendOnSignIn: true, |
| 314 | sendVerificationEmail: async ( |
| 315 | config.sendVerificationEmail!({ |
| 316 | email: user.email |
| 317 | name: user.name |
| 318 | url: withWebCallback(url |
| 319 | }), |
| 320 | } |
| 321 | : undefined, |
| 322 | plugins: [ |
| 323 | organization({ |
| 324 | ac, |
| 325 | roles, |
| 326 | creatorRole: 'owner', |
| 327 | defaultRole: 'member', |
| 328 | sendInvitationEmail: config.sendOrganizationInvitation |
| 329 | ? async ({ |
| 330 | config.sendOrganizationInvitation!({ |
| 331 | email, |
| 332 | role, |
| 333 | organization: organization.name |
| 334 | inviter: inviter.user |
| 335 | url: `${config. |
| 336 | }) |
| 337 | : undefined, |
| 338 | organizationHooks: { |
| 339 | beforeCreateOrganization: async ( |
| 340 | await assertNameFree(db |
| 341 | }, |
| 342 | beforeUpdateOrganization: async ( |
| 343 | await assertNameFree(db |
| 344 | }, |
| 345 | // Repository rows would cascade away while their stored history stayed behind; deleting a repository is what purges it (docs/0020). |
| 346 | beforeDeleteOrganization: async ( |
| 347 | const [repository] |
| 348 | .select({ id: |
| 349 | .from(schema.repository |
| 350 | .where(eq(schema |
| 351 | .limit(1); |
| 352 | if (!repository) |
| 353 | |
| 354 | throw APIError.from( |
| 355 | message: |
| 356 | 'Delete or transfer the organization’s repositories first', |
| 357 | code: 'ORGANIZATION_HAS_REPOSITORIES', |
| 358 | }); |
| 359 | }, |
| 360 | afterCreateOrganization: async ( |
| 361 | await db |
| 362 | .insert(schema.organizationSettings |
| 363 | .values({ organizationId: |
| 364 | .onConflictDoNothing(); |
| 365 | }, |
| 366 | afterDeleteOrganization: async ( |
| 367 | await config.onOrganizationDeleted |
| 368 | }, |
| 369 | }, |
| 370 | dynamicAccessControl: { |
| 371 | enabled: true, |
| 372 | }, |
| 373 | teams: { |
| 374 | enabled: true, |
| 375 | allowRemovingAllTeams: true, |
| 376 | }, |
| 377 | }), |
| 378 | username({}), |
| 379 | apiKey({ |
| 380 | defaultPrefix: 'ghost_pat_', |
| 381 | rateLimit: { |
| 382 | enabled: true, |
| 383 | maxRequests: 120, |
| 384 | timeWindow: 60000, // |
| 385 | }, |
| 386 | }), |
| 387 | ], |
| 388 | }); |
| 389 | } |
| 390 | |
| 391 | export type Auth |