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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | 6x 85x 85x 9x 9x 85x 9x 9x 9x 9x 3x 9x 3x 9x 10x 10x 10x 9x 6x 6x 6x 6x 5x 5x 6x 55x 9x 9x 9x 9x 9x 9x 9x 10x 10x 10x 10x 9x | import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { anonymous } from 'better-auth/plugins/anonymous';
import { jwt } from 'better-auth/plugins/jwt';
import { passkey } from '@better-auth/passkey';
import { oauthProvider } from '@better-auth/oauth-provider';
import { drizzle } from 'drizzle-orm/d1';
import { eq, count, notInArray } from 'drizzle-orm';
import { createProfile, onAccountKept } from './profiles.ts';
import * as schema from './schema.ts';
export interface Env {
DB: D1Database;
BLOBS: R2Bucket;
/** The Dashboard host, which is also the issuer origin: the issuer is `${AUTH_ORIGIN}/api/auth`. */
AUTH_ORIGIN: string;
BUILD_TIMESTAMP?: string;
BUILD_REVISION?: string;
SHOW_DONATE_LINK?: string;
PASSKEY_RP_ID: string;
/** JSON map of first-party client IDs to exact origins. */
OIDC_CLIENTS: string;
API_AUDIENCE: string;
BETTER_AUTH_SECRET: string;
DISCORD_CLIENT_ID?: string;
DISCORD_CLIENT_SECRET?: string;
GOOGLE_CLIENT_ID?: string;
GOOGLE_CLIENT_SECRET?: string;
}
const instances = new WeakMap<Env, ReturnType<typeof buildAuth>>();
export function createAuth(env: Env) {
let instance = instances.get(env);
if (!instance) {
instance = buildAuth(env);
instances.set(env, instance);
}
return instance;
}
function buildAuth(env: Env) {
const db = drizzle(env.DB, { schema });
const clients = JSON.parse(env.OIDC_CLIENTS) as Record<string, string>;
const socialProviders: Parameters<typeof betterAuth>[0]['socialProviders'] = {};
if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET)
socialProviders.discord = {
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
// The provider otherwise sends prompt=none, which Discord rejects until this app has been authorized.
prompt: 'consent',
};
if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET)
socialProviders.google = {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
// This provider omits prompt unless one is set, so the first grant can show consent.
};
const claims = async (user: { id: string; name?: string; isAnonymous?: unknown } | null | undefined) => {
Eif (user) await createProfile(db, user.id, user.isAnonymous === true);
const publicProfile = user
? await db.query.profile.findFirst({ where: eq(schema.profile.userId, user.id) })
: undefined;
return {
'https://be-music.app/passkeys': user
? (await db.select({ n: count() }).from(schema.passkey).where(eq(schema.passkey.userId, user.id)))[0].n
: 0,
'https://be-music.app/anonymous': user?.isAnonymous === true,
'https://be-music.app/linked-guests': user
? (await db.select().from(schema.identityLink).where(eq(schema.identityLink.toUserId, user.id))).map(
(row) => row.fromUserId,
)
: [],
...(user ? { name: publicProfile?.displayName ?? user.name } : {}),
};
};
return betterAuth({
baseURL: env.AUTH_ORIGIN,
basePath: '/api/auth',
secret: env.BETTER_AUTH_SECRET,
// Every ceremony takes place at the issuer origin. Never trust arbitrary subdomains or branch previews.
trustedOrigins: [env.AUTH_ORIGIN],
advanced: {
cookiePrefix: 'be-music-accounts',
},
database: drizzleAdapter(db, { provider: 'sqlite', schema }),
account: {
accountLinking: {
// A signed-in user may attach Discord or Google even when that provider's email differs from the
// account email, which is the usual case for guests and passkeys.
trustedProviders: ['discord', 'google'],
allowDifferentEmails: true,
},
},
databaseHooks: {
account: {
create: {
after: async (created) => {
Iif (created.providerId !== 'discord' && created.providerId !== 'google') return;
const [before] = await db
.select({ isAnonymous: schema.user.isAnonymous })
.from(schema.user)
.where(eq(schema.user.id, created.userId));
await db.update(schema.user).set({ isAnonymous: false }).where(eq(schema.user.id, created.userId));
// A guest who keeps the account this way is welcomed again, to name the account they now keep.
if (before?.isAnonymous === true) await onAccountKept(db, created.userId);
},
},
},
},
socialProviders,
disabledPaths: ['/token', '/update-user'],
plugins: [
anonymous({
onLinkAccount: async ({ anonymousUser, newUser }) => {
await db
.insert(schema.identityLink)
.values({ fromUserId: anonymousUser.user.id, toUserId: newUser.user.id })
.onConflictDoNothing();
// Carry previous guest merges through a later account link as well.
await db
.update(schema.identityLink)
.set({ toUserId: newUser.user.id })
.where(eq(schema.identityLink.toUserId, anonymousUser.user.id));
},
}),
passkey({ rpID: env.PASSKEY_RP_ID, rpName: 'Be-Music', origin: env.AUTH_ORIGIN }),
jwt({ jwt: { issuer: `${env.AUTH_ORIGIN}/api/auth` }, jwks: { keyPairConfig: { alg: 'RS256' } } }),
oauthProvider({
loginPage: '/login',
consentPage: '/consent',
scopes: ['openid', 'profile', 'be-music:api'],
grantTypes: ['authorization_code'],
allowDynamicClientRegistration: false,
clientPrivileges: () => false,
resourcePrivileges: () => false,
// Only explicitly provisioned public PKCE clients exist; all use the single first-party API resource.
enforcePerClientResources: true,
cachedTrustedClients: new Set(Object.keys(clients)),
customIdTokenClaims: ({ user }) => claims(user),
customAccessTokenClaims: ({ user }) => claims(user),
}),
],
});
}
/** Provision exact first-party callback URIs. This runs once per isolate before serving requests. */
const provisioned = new WeakSet<Env>();
export async function provisionClients(env: Env): Promise<void> {
if (provisioned.has(env)) return;
const db = drizzle(env.DB, { schema });
const clients = JSON.parse(env.OIDC_CLIENTS) as Record<string, string>;
Iif (Object.keys(clients).length === 0) throw new Error('At least one OIDC client is required');
await db
.update(schema.oauthClient)
.set({ disabled: true })
.where(notInArray(schema.oauthClient.clientId, Object.keys(clients)));
const resourceId = 'be-music-api';
await db
.insert(schema.oauthResource)
.values({
id: resourceId,
identifier: env.API_AUDIENCE,
name: 'Be-Music API',
allowedScopes: ['openid', 'profile', 'be-music:api'],
accessTokenTtl: 900,
})
.onConflictDoNothing();
for (const [clientId, origin] of Object.entries(clients)) {
Iif (new URL(origin).origin !== origin || !origin.startsWith('https://'))
throw new Error('Invalid OIDC client origin');
const value = {
id: clientId,
clientId,
disabled: false,
name: clientId,
redirectUris: [`${origin}/api/auth/callback`],
tokenEndpointAuthMethod: 'none',
applicationType: 'web',
grantTypes: ['authorization_code'],
responseTypes: ['code'],
scopes: ['openid', 'profile', 'be-music:api'],
requirePKCE: true,
skipConsent: true,
subjectType: 'public',
};
await db
.insert(schema.oauthClient)
.values(value)
.onConflictDoUpdate({ target: schema.oauthClient.clientId, set: value });
await db
.insert(schema.oauthClientResource)
.values({ id: `${clientId}-api`, clientId, resourceId: env.API_AUDIENCE })
.onConflictDoNothing();
}
provisioned.add(env);
}
|