| 1 | import { apiKey } from '@better-auth/api-key'; |
| 2 | import { tryGetCurrentAuthEndpointContext } |
| 3 | import { oauthProvider } |
| 4 | import { type Database, |
| 5 | import { ac, roles |
| 6 | import { |
| 7 | type BetterAuthOptions, |
| 8 | betterAuth, |
| 9 | type DBAdapter, |
| 10 | } from 'better-auth'; |
| 11 | import { drizzleAdapter } |
| 12 | import { |
| 13 | APIError, |
| 14 | createAuthMiddleware, |
| 15 | getSessionFromCtx, |
| 16 | } from 'better-auth/api'; |
| 17 | import { |
| 18 | deviceAuthorization, |
| 19 | jwt, |
| 20 | organization, |
| 21 | username, |
| 22 | } from 'better-auth/plugins'; |
| 23 | import { and, eq |
| 24 | |
| 25 | import { callbackMatches } |
| 26 | import { |
| 27 | findOauthApp, |
| 28 | keyOauthClientId, |
| 29 | oauthAppOrganization, |
| 30 | } from './github/oauth-apps.js'; |
| 31 | import { ACCESS_TOKEN_EXPIRES_IN } |
| 32 | import { KNOWN_SCOPES, NO_SCOPE |
| 33 | |
| 34 | export type AuthConfig |
| 35 | secret: string |
| 36 | baseURL: string |
| 37 | trustedOrigins?: string |
| 38 | /** 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`. */ |
| 39 | cookieDomain?: string |
| 40 | /** Set only when email verification is enabled (EMAIL_VERIFICATION_ENABLED); self-hosted instances without mail configured leave it unset. */ |
| 41 | sendVerificationEmail?: ( |
| 42 | email: string |
| 43 | name?: string |
| 44 | url: string |
| 45 | }) => |
| 46 | /** Set whenever mail is configured; password reset needs no verification flag. */ |
| 47 | sendResetPassword?: ( |
| 48 | email: string |
| 49 | name?: string |
| 50 | url: string |
| 51 | }) => |
| 52 | /** Set whenever mail is configured. Better Auth sends this to the address currently on the account, which is what makes a change reversible. */ |
| 53 | /** After an organization is gone: what it stored outside the database goes too, its OAuth apps' logos among it. */ |
| 54 | onOrganizationDeleted?: ( |
| 55 | organizationId: string |
| 56 | oauthClientIds: string |
| 57 | ) => |
| 58 | sendOrganizationInvitation?: ( |
| 59 | email: string |
| 60 | inviter: string |
| 61 | organization: string |
| 62 | role: string |
| 63 | url: string |
| 64 | }) => |
| 65 | sendChangeEmail?: ( |
| 66 | email: string |
| 67 | name?: string |
| 68 | newEmail: string |
| 69 | url: string |
| 70 | }) => |
| 71 | /** Origin of the web app, which owns the verify and reset forms. */ |
| 72 | webAppUrl?: string |
| 73 | /** Set when a GitHub OAuth app is configured: people sign in and up with it, and imports read with its token. */ |
| 74 | github?: { |
| 75 | }; |
| 76 | |
| 77 | /** better-auth defaults `callbackURL` to `/`, which resolves against the API. Point relative callbacks at the web app instead, where the forms live. */ |
| 78 | export function withWebCallback(url |
| 79 | if (!webAppUrl) |
| 80 | const parsed = |
| 81 | const callback = |
| 82 | if (!/^https?: |
| 83 | parsed.searchParams.set |
| 84 | } |
| 85 | return parsed.href |
| 86 | } |
| 87 | |
| 88 | /** Endpoints that take an address in the body and look a user up by it. */ |
| 89 | const EMAIL_LOOKUP_PATHS = [ |
| 90 | |
| 91 | /** 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. */ |
| 92 | function beforeAuthHooks(db: |
| 93 | return createAuthMiddleware(async |
| 94 | if (ctx.path |
| 95 | const body = |
| 96 | await assertNameFree(db |
| 97 | return; |
| 98 | } |
| 99 | |
| 100 | if (ctx.path |
| 101 | const body = |
| 102 | const next = |
| 103 | typeof body?.newEmail |
| 104 | ? body.newEmail. |
| 105 | : null; |
| 106 | if (!next) |
| 107 | |
| 108 | // Checked here as well as in the database hook, so a taken address is refused before a verification mail goes out. |
| 109 | const session = |
| 110 | await assertEmailAvailable(db |
| 111 | return; |
| 112 | } |
| 113 | |
| 114 | if (!EMAIL_LOOKUP_PATHS.includes |
| 115 | |
| 116 | const body = |
| 117 | const input = |
| 118 | if (!input) |
| 119 | |
| 120 | const [match] |
| 121 | .select({ email: |
| 122 | .from(schema.userEmail |
| 123 | .innerJoin(schema.user |
| 124 | .where( |
| 125 | and( |
| 126 | eq(schema.userEmail |
| 127 | eq(schema.userEmail |
| 128 | ), |
| 129 | ) |
| 130 | .limit(1); |
| 131 | |
| 132 | if (!match) |
| 133 | |
| 134 | return { context: |
| 135 | }); |
| 136 | } |
| 137 | |
| 138 | /** 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. */ |
| 139 | async function assertEmailAvailable |
| 140 | db: Database |
| 141 | email: string, |
| 142 | userId: string |
| 143 | ) { |
| 144 | const taken = |
| 145 | APIError.from('UNPROCESSABLE_ENTITY |
| 146 | message: 'That email address is already taken', |
| 147 | code: 'EMAIL_ALREADY_TAKEN', |
| 148 | }); |
| 149 | |
| 150 | const [[primaryOwner], |
| 151 | db |
| 152 | .select({ id: |
| 153 | .from(schema.user |
| 154 | .where(eq(sql |
| 155 | db |
| 156 | .select({ |
| 157 | id: schema.userEmail |
| 158 | userId: schema.userEmail |
| 159 | verified: schema.userEmail |
| 160 | }) |
| 161 | .from(schema.userEmail |
| 162 | .where(eq(schema |
| 163 | ]); |
| 164 | |
| 165 | if (primaryOwner && |
| 166 | if (!extraOwner) |
| 167 | if (extraOwner.userId |
| 168 | |
| 169 | if (!extraOwner.verified |
| 170 | throw APIError.from( |
| 171 | message: 'Confirm that address from the link sent to it first', |
| 172 | code: 'EMAIL_NOT_VERIFIED', |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | return extraOwner.id |
| 177 | } |
| 178 | |
| 179 | /** The web app's own top-level routes, and the API host's `/login` for GitHub's OAuth paths: an account under one of these names would have no profile to reach. */ |
| 180 | const RESERVED_NAMES = new |
| 181 | 'api', |
| 182 | 'auth', |
| 183 | 'changelog', |
| 184 | 'dashboard', |
| 185 | 'device', |
| 186 | 'login', |
| 187 | 'search', |
| 188 | 'settings', |
| 189 | ]); |
| 190 | |
| 191 | /** 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. */ |
| 192 | async function nameConflict( |
| 193 | db: Database |
| 194 | name: string, |
| 195 | taking: 'username |
| 196 | ) { |
| 197 | const lowered = |
| 198 | if (RESERVED_NAMES.has |
| 199 | |
| 200 | const [taken] |
| 201 | taking === 'username' |
| 202 | ? await db |
| 203 | .select({ id: |
| 204 | .from(schema.organization |
| 205 | .where(eq(sql |
| 206 | : await db |
| 207 | .select({ id: |
| 208 | .from(schema.user |
| 209 | .where(eq(sql |
| 210 | if (!taken) |
| 211 | |
| 212 | return taking === |
| 213 | ? 'An organization already uses that name' |
| 214 | : 'A user already has that name'; |
| 215 | } |
| 216 | |
| 217 | async function assertNameFree( |
| 218 | db: Database |
| 219 | name: unknown, |
| 220 | taking: 'username |
| 221 | ) { |
| 222 | if (typeof name |
| 223 | const conflict = |
| 224 | if (!conflict) |
| 225 | |
| 226 | throw APIError.from( |
| 227 | message: conflict, |
| 228 | code: 'NAME_ALREADY_TAKEN', |
| 229 | }); |
| 230 | } |
| 231 | |
| 232 | /** Better Auth's username availability check knows only users; an organization's slug or a route name is just as taken. */ |
| 233 | function afterAuthHooks(db: |
| 234 | return createAuthMiddleware(async |
| 235 | if (ctx.path |
| 236 | |
| 237 | const returned = |
| 238 | const body = |
| 239 | if (returned?.available |
| 240 | return; |
| 241 | } |
| 242 | if (await nameConflict |
| 243 | return ctx.json |
| 244 | } |
| 245 | }); |
| 246 | } |
| 247 | |
| 248 | /** A free username for someone signing up with GitHub. GitHub logins may hold hyphens and run 1 to 39 characters; Better Auth's username rules allow neither, and a hyphen is what keeps `ghost-importer` unclaimable. */ |
| 249 | export async function usernameForGitHubLogin |
| 250 | const base = |
| 251 | .toLowerCase() |
| 252 | .replaceAll('-', |
| 253 | .slice(0, 26 |
| 254 | .padEnd(3, ' |
| 255 | for (let suffix |
| 256 | const candidate = |
| 257 | const [user] |
| 258 | .select({ id: |
| 259 | .from(schema.user |
| 260 | .where(eq(sql |
| 261 | if (!user && |
| 262 | return candidate; |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | const isUsernameConflict = ( |
| 268 | error instanceof Error |
| 269 | (('constraint' in error |
| 270 | isUsernameConflict(error.cause |
| 271 | |
| 272 | /** Two GitHub sign-ups can both find the same name free before either is inserted; the one whose insert loses takes the next free name instead of failing. */ |
| 273 | export function retryGitHubUsernameConflicts( |
| 274 | db: Database |
| 275 | adapter: DBAdapter |
| 276 | ): DBAdapter { |
| 277 | const create: |
| 278 | try { |
| 279 | return await adapter |
| 280 | } catch (error) |
| 281 | const taken = |
| 282 | const signingUpWithGitHub = |
| 283 | tryGetCurrentAuthEndpointContext()?.path?.startsWith |
| 284 | if ( |
| 285 | args.model !== |
| 286 | typeof taken !== ' |
| 287 | !signingUpWithGitHub || |
| 288 | !isUsernameConflict(error) |
| 289 | ) { |
| 290 | throw error; |
| 291 | } |
| 292 | const username = |
| 293 | return create({ |
| 294 | ...args, |
| 295 | data: { ...args |
| 296 | }); |
| 297 | } |
| 298 | }; |
| 299 | return { ...adapter |
| 300 | } |
| 301 | |
| 302 | /** 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`. */ |
| 303 | async function claimEmailForAccount |
| 304 | db: Database |
| 305 | email: string, |
| 306 | userId: string |
| 307 | ) { |
| 308 | const extraId = |
| 309 | if (!extraId) |
| 310 | |
| 311 | await db.delete |
| 312 | } |
| 313 | |
| 314 | /** The only oauth-provider routes a browser reaches; everything else runs server-side through `auth.api`, behind GitHub's paths and Ghost's own API. */ |
| 315 | const BROWSER_OAUTH_PATHS = new |
| 316 | '/oauth2/authorize', |
| 317 | '/oauth2/consent', |
| 318 | '/oauth2/continue', |
| 319 | ]); |
| 320 | |
| 321 | export function createAuth(db |
| 322 | const consentPage = |
| 323 | const jwtPlugin = |
| 324 | const oauthPlugin = |
| 325 | loginPage: consentPage, |
| 326 | consentPage, |
| 327 | clientReference: () => |
| 328 | scopes: [...KNOWN_SCOPES |
| 329 | validateRedirectUri: (uri, |
| 330 | registered.some((callback |
| 331 | }); |
| 332 | return betterAuth({ |
| 333 | secret: config.secret |
| 334 | disabledPaths: [ |
| 335 | ...Object.values( |
| 336 | ...Object.values( |
| 337 | ] |
| 338 | .map((endpoint) |
| 339 | .filter((path) |
| 340 | baseURL: config.baseURL |
| 341 | trustedOrigins: config.trustedOrigins |
| 342 | advanced: { |
| 343 | ...(config.cookieDomain |
| 344 | ? { |
| 345 | crossSubDomainCookies: { |
| 346 | enabled: true, |
| 347 | domain: config.cookieDomain |
| 348 | }, |
| 349 | } |
| 350 | : undefined), |
| 351 | ...(process.env |
| 352 | ? { |
| 353 | ipAddress: { |
| 354 | ipAddressHeaders: ['X-Real-IP'], |
| 355 | }, |
| 356 | } |
| 357 | : undefined), |
| 358 | }, |
| 359 | |
| 360 | database: (options: |
| 361 | retryGitHubUsernameConflicts( |
| 362 | db, |
| 363 | drizzleAdapter(db, { |
| 364 | ), |
| 365 | socialProviders: config.github |
| 366 | ? { |
| 367 | github: { |
| 368 | ...config.github, |
| 369 | mapProfileToUser: async ( |
| 370 | const username = |
| 371 | return { username, |
| 372 | }, |
| 373 | }, |
| 374 | } |
| 375 | : undefined, |
| 376 | account: { |
| 377 | encryptOAuthTokens: true, |
| 378 | // A GitHub address rarely matches the account it is linked to, and signing in with GitHub must never take over an account by its email. |
| 379 | accountLinking: { |
| 380 | allowDifferentEmails: true, |
| 381 | disableImplicitLinking: true, |
| 382 | }, |
| 383 | }, |
| 384 | hooks: { before: beforeAuthHooks |
| 385 | databaseHooks: { |
| 386 | user: { |
| 387 | create: { |
| 388 | before: async ( |
| 389 | await assertNameFree(db |
| 390 | }, |
| 391 | }, |
| 392 | update: { |
| 393 | before: async ( |
| 394 | await assertNameFree(db |
| 395 | |
| 396 | const next = |
| 397 | typeof data.email |
| 398 | ? data.email. |
| 399 | : null; |
| 400 | if (!next) |
| 401 | |
| 402 | await claimEmailForAccount( |
| 403 | db, |
| 404 | next, |
| 405 | context?.context.session |
| 406 | (typeof data.id |
| 407 | ); |
| 408 | }, |
| 409 | }, |
| 410 | }, |
| 411 | }, |
| 412 | emailAndPassword: { |
| 413 | enabled: true, |
| 414 | requireEmailVerification: Boolean(config |
| 415 | sendResetPassword: config.sendResetPassword |
| 416 | ? async ({ |
| 417 | config.sendResetPassword!({ |
| 418 | email: user.email |
| 419 | name: user.name |
| 420 | url: withWebCallback(url |
| 421 | }) |
| 422 | : undefined, |
| 423 | }, |
| 424 | user: { |
| 425 | changeEmail: { |
| 426 | enabled: true, |
| 427 | // With no mail configured there is nobody to confirm with, and an unverified account would be stuck on its first address forever. |
| 428 | updateEmailWithoutVerification: !config.sendChangeEmail |
| 429 | sendChangeEmailConfirmation: config.sendChangeEmail |
| 430 | ? async ({ |
| 431 | config.sendChangeEmail!({ |
| 432 | email: user.email |
| 433 | name: user.name |
| 434 | newEmail, |
| 435 | url: withWebCallback(url |
| 436 | }) |
| 437 | : undefined, |
| 438 | }, |
| 439 | }, |
| 440 | emailVerification: config.sendVerificationEmail |
| 441 | ? { |
| 442 | sendOnSignUp: true, |
| 443 | autoSignInAfterVerification: true, |
| 444 | sendOnSignIn: true, |
| 445 | sendVerificationEmail: async ( |
| 446 | config.sendVerificationEmail!({ |
| 447 | email: user.email |
| 448 | name: user.name |
| 449 | url: withWebCallback(url |
| 450 | }), |
| 451 | } |
| 452 | : undefined, |
| 453 | plugins: [ |
| 454 | organization({ |
| 455 | ac, |
| 456 | roles, |
| 457 | creatorRole: 'owner', |
| 458 | defaultRole: 'member', |
| 459 | sendInvitationEmail: config.sendOrganizationInvitation |
| 460 | ? async ({ |
| 461 | config.sendOrganizationInvitation!({ |
| 462 | email, |
| 463 | role, |
| 464 | organization: organization.name |
| 465 | inviter: inviter.user |
| 466 | url: `${config. |
| 467 | }) |
| 468 | : undefined, |
| 469 | organizationHooks: { |
| 470 | beforeCreateOrganization: async ( |
| 471 | await assertNameFree(db |
| 472 | }, |
| 473 | beforeUpdateOrganization: async ( |
| 474 | await assertNameFree(db |
| 475 | }, |
| 476 | // Repository rows would cascade away while their stored history stayed behind; deleting a repository is what purges it (docs/0020). |
| 477 | beforeDeleteOrganization: async ( |
| 478 | const [repository] |
| 479 | .select({ id: |
| 480 | .from(schema.repository |
| 481 | .where(eq(schema |
| 482 | .limit(1); |
| 483 | if (!repository) |
| 484 | |
| 485 | throw APIError.from( |
| 486 | message: |
| 487 | 'Delete or transfer the organization’s repositories first', |
| 488 | code: 'ORGANIZATION_HAS_REPOSITORIES', |
| 489 | }); |
| 490 | }, |
| 491 | afterCreateOrganization: async ( |
| 492 | await db |
| 493 | .insert(schema.organizationSettings |
| 494 | .values({ organizationId: |
| 495 | .onConflictDoNothing(); |
| 496 | }, |
| 497 | // `referenceId` has no foreign key, so the organization's OAuth apps and the keys they minted go here. |
| 498 | afterDeleteOrganization: async ( |
| 499 | const apps = |
| 500 | .delete(schema.oauthClient |
| 501 | .where(eq(schema |
| 502 | .returning({ clientId: |
| 503 | const clientIds = |
| 504 | if (clientIds.length |
| 505 | await db |
| 506 | .delete(schema.apikey |
| 507 | .where(inArray(keyOauthClientId |
| 508 | } |
| 509 | await config.onOrganizationDeleted |
| 510 | }, |
| 511 | }, |
| 512 | dynamicAccessControl: { |
| 513 | enabled: true, |
| 514 | }, |
| 515 | teams: { |
| 516 | enabled: true, |
| 517 | allowRemovingAllTeams: true, |
| 518 | }, |
| 519 | }), |
| 520 | username({}), |
| 521 | apiKey({ |
| 522 | defaultPrefix: 'ghost_pat_', |
| 523 | // In days: OAuth apps with expiring user tokens get keys that last 8 hours. |
| 524 | keyExpiration: { minExpiresIn: ACCESS_TOKEN_EXPIRES_IN |
| 525 | // Device-flow keys record the OAuth app that minted them. |
| 526 | enableMetadata: true, |
| 527 | rateLimit: { |
| 528 | enabled: true, |
| 529 | maxRequests: 120, |
| 530 | timeWindow: 60000, |
| 531 | }, |
| 532 | }), |
| 533 | deviceAuthorization({ |
| 534 | verificationUri: `${config. |
| 535 | validateClient: async ( |
| 536 | (await findOauthApp(db |
| 537 | }), |
| 538 | jwtPlugin, |
| 539 | oauthPlugin, |
| 540 | ], |
| 541 | }); |
| 542 | } |
| 543 | |
| 544 | export type Auth |