| 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 | sendChangeEmail?: ( |
| 35 | email: string |
| 36 | name?: string |
| 37 | newEmail: string |
| 38 | url: string |
| 39 | }) => |
| 40 | /** Origin of the web app, which owns the verify and reset forms. */ |
| 41 | webAppUrl?: string |
| 42 | }; |
| 43 | |
| 44 | /** better-auth defaults `callbackURL` to `/`, which resolves against the API. Point relative callbacks at the web app instead, where the forms live. */ |
| 45 | export function withWebCallback(url |
| 46 | if (!webAppUrl) |
| 47 | const parsed = |
| 48 | const callback = |
| 49 | if (!/^https?: |
| 50 | parsed.searchParams.set |
| 51 | } |
| 52 | return parsed.href |
| 53 | } |
| 54 | |
| 55 | /** Endpoints that take an address in the body and look a user up by it. */ |
| 56 | const EMAIL_LOOKUP_PATHS = [ |
| 57 | |
| 58 | /** |
| 59 | * Resolves one of an account's extra addresses to the one Better Auth knows. |
| 60 | * |
| 61 | * Better Auth knows only `user.email`, so extras are swapped in before its endpoint runs. Only verified rows resolve - otherwise adding an address would be enough to sign in as its owner. |
| 62 | */ |
| 63 | function resolvePrimaryEmail(db: |
| 64 | return createAuthMiddleware(async |
| 65 | if (ctx.path |
| 66 | const body = |
| 67 | const next = |
| 68 | typeof body?.newEmail |
| 69 | ? body.newEmail. |
| 70 | : null; |
| 71 | if (!next) |
| 72 | |
| 73 | // Checked here as well as in the database hook, so a taken address is refused before a verification mail goes out. |
| 74 | const session = |
| 75 | await assertEmailAvailable(db |
| 76 | return; |
| 77 | } |
| 78 | |
| 79 | if (!EMAIL_LOOKUP_PATHS.includes |
| 80 | |
| 81 | const body = |
| 82 | const input = |
| 83 | if (!input) |
| 84 | |
| 85 | const [match] |
| 86 | .select({ email: |
| 87 | .from(schema.userEmail |
| 88 | .innerJoin(schema.user |
| 89 | .where( |
| 90 | and( |
| 91 | eq(schema.userEmail |
| 92 | eq(schema.userEmail |
| 93 | ), |
| 94 | ) |
| 95 | .limit(1); |
| 96 | |
| 97 | if (!match) |
| 98 | |
| 99 | return { context: |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Claims an address for an account before it is written to `user.email`. |
| 105 | * |
| 106 | * 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. |
| 107 | */ |
| 108 | async function assertEmailAvailable |
| 109 | db: Database |
| 110 | email: string, |
| 111 | userId: string |
| 112 | ) { |
| 113 | const taken = |
| 114 | APIError.from('UNPROCESSABLE_ENTITY |
| 115 | message: 'That email address is already taken', |
| 116 | code: 'EMAIL_ALREADY_TAKEN', |
| 117 | }); |
| 118 | |
| 119 | const [[primaryOwner], |
| 120 | db |
| 121 | .select({ id: |
| 122 | .from(schema.user |
| 123 | .where(eq(sql |
| 124 | db |
| 125 | .select({ |
| 126 | id: schema.userEmail |
| 127 | userId: schema.userEmail |
| 128 | verified: schema.userEmail |
| 129 | }) |
| 130 | .from(schema.userEmail |
| 131 | .where(eq(schema |
| 132 | ]); |
| 133 | |
| 134 | if (primaryOwner && |
| 135 | if (!extraOwner) |
| 136 | if (extraOwner.userId |
| 137 | |
| 138 | if (!extraOwner.verified |
| 139 | throw APIError.from( |
| 140 | message: 'Confirm that address from the link sent to it first', |
| 141 | code: 'EMAIL_NOT_VERIFIED', |
| 142 | }); |
| 143 | } |
| 144 | |
| 145 | return extraOwner.id |
| 146 | } |
| 147 | |
| 148 | /** 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`. */ |
| 149 | async function claimEmailForAccount |
| 150 | db: Database |
| 151 | email: string, |
| 152 | userId: string |
| 153 | ) { |
| 154 | const extraId = |
| 155 | if (!extraId) |
| 156 | |
| 157 | await db.delete |
| 158 | } |
| 159 | |
| 160 | export function createAuth(db |
| 161 | return betterAuth({ |
| 162 | secret: config.secret |
| 163 | baseURL: config.baseURL |
| 164 | trustedOrigins: config.trustedOrigins |
| 165 | advanced: config.cookieDomain |
| 166 | ? { |
| 167 | crossSubDomainCookies: { |
| 168 | enabled: true, |
| 169 | domain: config.cookieDomain |
| 170 | }, |
| 171 | } |
| 172 | : undefined, |
| 173 | database: drizzleAdapter(db |
| 174 | provider: 'pg', |
| 175 | }), |
| 176 | hooks: { before: resolvePrimaryEmail |
| 177 | databaseHooks: { |
| 178 | user: { |
| 179 | update: { |
| 180 | before: async ( |
| 181 | const next = |
| 182 | typeof data.email |
| 183 | ? data.email. |
| 184 | : null; |
| 185 | if (!next) |
| 186 | |
| 187 | await claimEmailForAccount( |
| 188 | db, |
| 189 | next, |
| 190 | context?.context.session |
| 191 | (typeof data.id |
| 192 | ); |
| 193 | }, |
| 194 | }, |
| 195 | }, |
| 196 | }, |
| 197 | emailAndPassword: { |
| 198 | enabled: true, |
| 199 | requireEmailVerification: Boolean(config |
| 200 | sendResetPassword: config.sendResetPassword |
| 201 | ? async ({ |
| 202 | config.sendResetPassword!({ |
| 203 | email: user.email |
| 204 | name: user.name |
| 205 | url: withWebCallback(url |
| 206 | }) |
| 207 | : undefined, |
| 208 | }, |
| 209 | user: { |
| 210 | changeEmail: { |
| 211 | enabled: true, |
| 212 | // With no mail configured there is nobody to confirm with, and an unverified account would be stuck on its first address forever. |
| 213 | updateEmailWithoutVerification: !config.sendChangeEmail |
| 214 | sendChangeEmailConfirmation: config.sendChangeEmail |
| 215 | ? async ({ |
| 216 | config.sendChangeEmail!({ |
| 217 | email: user.email |
| 218 | name: user.name |
| 219 | newEmail, |
| 220 | url: withWebCallback(url |
| 221 | }) |
| 222 | : undefined, |
| 223 | }, |
| 224 | }, |
| 225 | emailVerification: config.sendVerificationEmail |
| 226 | ? { |
| 227 | sendOnSignUp: true, |
| 228 | autoSignInAfterVerification: true, |
| 229 | sendVerificationEmail: async ( |
| 230 | config.sendVerificationEmail!({ |
| 231 | email: user.email |
| 232 | name: user.name |
| 233 | url: withWebCallback(url |
| 234 | }), |
| 235 | } |
| 236 | : undefined, |
| 237 | plugins: [ |
| 238 | organization({ |
| 239 | ac, |
| 240 | roles, |
| 241 | creatorRole: 'owner', |
| 242 | defaultRole: 'read', |
| 243 | dynamicAccessControl: { |
| 244 | enabled: true, |
| 245 | }, |
| 246 | teams: { |
| 247 | enabled: true, |
| 248 | allowRemovingAllTeams: true, |
| 249 | }, |
| 250 | }), |
| 251 | username({}), |
| 252 | apiKey({ |
| 253 | defaultPrefix: 'ghost_pat_', |
| 254 | rateLimit: { |
| 255 | enabled: true, |
| 256 | maxRequests: 120, |
| 257 | timeWindow: 60000, // |
| 258 | }, |
| 259 | }), |
| 260 | ], |
| 261 | }); |
| 262 | } |
| 263 | |
| 264 | export type Auth |