All files / app-leaderboard/src legacy-auth.ts

91.42% Statements 32/35
78.94% Branches 30/38
90% Functions 9/10
91.42% Lines 32/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160                              464x                     413x 413x 407x 407x   413x 413x 407x 407x   413x     14x                     460x 146x   314x       314x               475x 472x   3x 4x                                       410x 410x   413x 413x 410x 410x                   407x 407x 407x 407x     407x     407x                                                                       77x                  
import { passkey } from '@better-auth/passkey';
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { anonymous } from 'better-auth/plugins/anonymous';
import { drizzle } from 'drizzle-orm/d1';
import * as schema from './db/schema.ts';
import type { Env } from './env.ts';
import { createProfile } from './profiles.ts';
import { reassignScores } from './scores/reassign.ts';
 
/**
 * Whether a request carries a Better Auth session cookie (`better-auth.session_token`, `__Secure-` prefixed over HTTPS).
 * Without one `getSession` can only answer null, so callers skip building the auth instance and asking it.
 */
export function hasSessionCookie(headers: Headers): boolean {
  return headers.get('cookie')?.includes('session_token=') ?? false;
}
 
/**
 * Better Auth for a request's bindings and origin (docs/leaderboard.md section 3), built once per bindings object and
 * origin and reused while the isolate lives: setting it up and its context per request cost every request. The
 * bindings come from the request (`c.env`), so the cache is keyed by that object and never outlives it. Discord and
 * Google sign-in are enabled only when their secrets are configured, so local runs and tests work with anonymous
 * sessions alone.
 */
export function createAuth(env: Env, origin: string): Auth {
  let byOrigin = AUTH_BY_ENV.get(env);
  if (byOrigin === undefined) {
    byOrigin = new Map();
    AUTH_BY_ENV.set(env, byOrigin);
  }
  let auth = byOrigin.get(origin);
  if (auth === undefined) {
    auth = buildAuth(env, origin);
    byOrigin.set(origin, auth);
  }
  return auth;
}
 
const AUTH_BY_ENV = new WeakMap<Env, Map<string, Auth>>();
 
/**
 * The signed-in session of a request (null without one), and the cookies Better Auth set while reading it: the
 * refreshed five-minute cookie cache, or a session whose expiry it extended. Passing those on with the response keeps
 * the cache warm, so later requests read the session from the cookie instead of D1.
 */
export async function loadSession(
  env: Env,
  request: Request,
): Promise<{ session: Awaited<ReturnType<Auth['api']['getSession']>>; setCookies: string[] }> {
  if (!hasSessionCookie(request.headers)) {
    return { session: null, setCookies: [] };
  }
  const result = await createAuth(env, new URL(request.url).origin).api.getSession({
    headers: request.headers,
    returnHeaders: true,
  });
  return { session: result.response, setCookies: result.headers?.getSetCookie() ?? [] };
}
 
/**
 * Adds the cookies {@link loadSession} collected to a response, unless it is publicly cacheable (a replay, a card):
 * a shared cache must not keep one player's cookie, and a response with one would not be cached at all.
 */
export function passOnSetCookies(response: Response, setCookies: readonly string[]): void {
  if (setCookies.length === 0 || /\bpublic\b/.test(response.headers.get('cache-control') ?? '')) {
    return;
  }
  for (const cookie of setCookies) {
    response.headers.append('set-cookie', cookie);
  }
}
 
/** How Better Auth is reached and where its cookies go, for a request's bindings and origin. */
export interface AuthSettings {
  baseURL: string;
  /** Origins allowed to call Better Auth and to run passkey ceremonies; the base URL's origin comes first. */
  trustedOrigins: string[];
  cookieDomain: string | undefined;
  cookiePrefix: string | undefined;
  rpID: string;
}
 
/**
 * Better Auth's settings from the bindings (docs/services.md section 3). With `AUTH_ORIGIN` set, every service reaches
 * one Better Auth at that origin and shares its cookies on `COOKIE_DOMAIN`; without it (local runs, tests), the
 * request's own origin serves as before.
 */
export function authSettings(env: Env, requestOrigin: string): AuthSettings {
  const baseURL = env.AUTH_ORIGIN?.trim() || requestOrigin;
  const extra = (env.TRUSTED_ORIGINS ?? '')
    .split(',')
    .map((origin) => origin.trim())
    .filter((origin) => origin.length > 0);
  const trustedOrigins = [...new Set([new URL(baseURL).origin, ...extra])];
  return {
    baseURL,
    trustedOrigins,
    cookieDomain: env.COOKIE_DOMAIN?.trim() || undefined,
    cookiePrefix: env.COOKIE_PREFIX?.trim() || undefined,
    rpID: env.PASSKEY_RP_ID?.trim() || new URL(baseURL).hostname,
  };
}
 
function buildAuth(env: Env, origin: string) {
  const settings = authSettings(env, origin);
  const db = drizzle(env.DB, { schema });
  const socialProviders: Parameters<typeof betterAuth>[0]['socialProviders'] = {};
  Iif (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
    socialProviders.discord = { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET };
  }
  Iif (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) {
    socialProviders.google = { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET };
  }
  return betterAuth({
    baseURL: settings.baseURL,
    basePath: '/api/auth',
    secret: env.BETTER_AUTH_SECRET,
    trustedOrigins: settings.trustedOrigins,
    advanced: {
      ...(settings.cookiePrefix ? { cookiePrefix: settings.cookiePrefix } : {}),
      ...(settings.cookieDomain ? { crossSubDomainCookies: { enabled: true, domain: settings.cookieDomain } } : {}),
    },
    database: drizzleAdapter(db, {
      provider: 'sqlite',
      schema: {
        user: schema.user,
        session: schema.session,
        account: schema.account,
        verification: schema.verification,
        passkey: schema.passkey,
      },
    }),
    socialProviders,
    // Keep the session in a signed cookie for 5 minutes, so pages and the API read it without a D1 round trip. A
    // signed-out or revoked session lingers that long at most; nothing here trusts more than its user id.
    session: { cookieCache: { enabled: true, maxAge: 5 * 60 } },
    plugins: [
      anonymous({
        // Runs before the anonymous user is deleted, so its plays move instead of cascading away.
        onLinkAccount: async ({ anonymousUser, newUser }) => {
          await reassignScores(db, anonymousUser.user.id, newUser.user.id);
        },
      }),
      passkey({ rpID: settings.rpID, rpName: 'Be-Music', origin: settings.trustedOrigins }),
    ],
    databaseHooks: {
      user: {
        create: {
          after: async (created) => {
            await createProfile(db, created.id, (created as { isAnonymous?: boolean | null }).isAnonymous === true);
          },
        },
      },
    },
  });
}
 
export type Auth = ReturnType<typeof buildAuth>;