@prunellejs/auth 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/links.ts ADDED
@@ -0,0 +1,150 @@
1
+ // One-time emailed link issuance & verification (magic links and email verification) with signup mail-delay equalization.
2
+
3
+ import type { AuthMailPayload, AuthOptions } from './index'
4
+ import type { SessionManager } from './session'
5
+ import type { AuthStore, AuthUser } from './store'
6
+ import { safeEqual, safeRedirect } from 'prunelle/server'
7
+ import { randomToken, sha256Hex } from './crypto'
8
+ import { normalizeEmail } from './store'
9
+
10
+ const MAIL_DELAY_MIN_MS = 5
11
+ const MAIL_DELAY_MAX_MS = 2000
12
+ const LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
13
+ const LINK_MAILS = {
14
+ 'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
15
+ 'verify-email': { subject: 'Verify your email address', text: 'Confirm your email address using this one-time link', html: 'Click to verify your email address', label: 'Verify email' },
16
+ } as const
17
+
18
+ // Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
19
+ function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
20
+ return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
21
+ }
22
+
23
+ export function buildMailDeliverer(
24
+ sendMail: AuthOptions['sendMail'],
25
+ mailer: AuthOptions['mailer'],
26
+ ): ((mail: AuthMailPayload) => void | Promise<void>) | undefined {
27
+ if (sendMail)
28
+ return sendMail
29
+ if (!mailer)
30
+ return undefined
31
+ return async (mail) => {
32
+ await mailer.send({ to: mail.to, subject: mail.subject, text: mail.text, html: mail.html })
33
+ }
34
+ }
35
+
36
+ function createMailDelayTracker(): { observe: (ms: number) => void, pad: () => Promise<void> } {
37
+ let ewmaMs: number | undefined
38
+ return {
39
+ observe(ms: number) {
40
+ const clamped = Math.min(MAIL_DELAY_MAX_MS, Math.max(0, ms))
41
+ ewmaMs = ewmaMs === undefined ? clamped : ewmaMs * 0.7 + clamped * 0.3
42
+ },
43
+ async pad() {
44
+ if (ewmaMs === undefined || ewmaMs < MAIL_DELAY_MIN_MS)
45
+ return
46
+ const jittered = Math.min(MAIL_DELAY_MAX_MS, Math.round(ewmaMs * (0.85 + Math.random() * 0.3)))
47
+ if (jittered >= MAIL_DELAY_MIN_MS)
48
+ await Bun.sleep(jittered)
49
+ },
50
+ }
51
+ }
52
+
53
+ export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
54
+ store: AuthStore<TUser>
55
+ sessions: SessionManager<TUser>
56
+ basePath: string
57
+ defaultRedirect: string
58
+ tokenTtlMs: number
59
+ deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
60
+ }
61
+
62
+ export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
63
+ const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
64
+ const mailDelay = createMailDelayTracker()
65
+
66
+ async function issueLink(
67
+ kind: 'magic-link' | 'verify-email',
68
+ userId: string | undefined,
69
+ email: string,
70
+ origin: string | undefined,
71
+ redirectTo: string | undefined,
72
+ ): Promise<string> {
73
+ const normalized = normalizeEmail(email)
74
+ const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
75
+ const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
76
+ const tokenHash = sha256Hex(rawToken)
77
+ await sessions.observeAsync(store.createToken({
78
+ tokenHash,
79
+ ...(userId !== undefined ? { userId } : {}),
80
+ email: normalized,
81
+ kind,
82
+ expiresAt: Date.now() + tokenTtlMs,
83
+ }))
84
+
85
+ const next = safeRedirect(redirectTo, defaultRedirect)
86
+ const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
87
+ const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
88
+
89
+ if (deliverMail && origin !== undefined) {
90
+ const mail = LINK_MAILS[kind]
91
+ const startedAt = performance.now()
92
+ try {
93
+ await deliverMail({
94
+ to: normalized,
95
+ subject: mail.subject,
96
+ text: `${mail.text}: ${url}`,
97
+ html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
98
+ url,
99
+ kind,
100
+ })
101
+ mailDelay.observe(performance.now() - startedAt)
102
+ }
103
+ catch (err) {
104
+ try {
105
+ await sessions.observeAsync(store.consumeToken(tokenHash, kind))
106
+ }
107
+ catch (cleanupErr) {
108
+ console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
109
+ }
110
+ throw err
111
+ }
112
+ }
113
+ return url
114
+ }
115
+
116
+ async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
117
+ const normalized = normalizeEmail(email)
118
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
119
+ return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
120
+ }
121
+
122
+ async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
123
+ const normalized = normalizeEmail(email)
124
+ const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
125
+ return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
126
+ }
127
+
128
+ async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
129
+ const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
130
+ if (!consumed)
131
+ return undefined
132
+ const user = consumed.userId
133
+ ? await sessions.observeAsync(store.getUserById(consumed.userId))
134
+ : await sessions.observeAsync(store.getUserByEmail(consumed.email))
135
+ if (kind === 'verify-email') {
136
+ const dot = rawToken.lastIndexOf('.')
137
+ if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
138
+ return undefined
139
+ }
140
+ return { email: consumed.email, user }
141
+ }
142
+
143
+ return {
144
+ issueLink,
145
+ sendVerificationEmail,
146
+ sendMagicLink,
147
+ consumeLink,
148
+ equalizeSignupMailDelay: () => deliverMail ? mailDelay.pad() : Promise.resolve(),
149
+ }
150
+ }
@@ -0,0 +1,255 @@
1
+ // OAuth 2.0 authorization-code + PKCE routes: provider redirect and callback with a signed, short-lived state cookie.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+ import { safeEqual, safeRedirect } from 'prunelle/server'
5
+ import type { OAuthProfile, OAuthProvider } from './oauth'
6
+ import type { AuthStore, AuthUser, PublicUser } from './store'
7
+ import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
8
+ import { fail, withNoStore } from './http'
9
+ import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
10
+ import { normalizeEmail, toPublicUser } from './store'
11
+
12
+ interface OAuthStateCookie {
13
+ provider: string
14
+ state: string
15
+ verifier?: string | undefined
16
+ redirect: string
17
+ exp: number
18
+ }
19
+
20
+ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
21
+ route: (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>) => void
22
+ store: AuthStore<TUser>
23
+ providers: ReadonlyMap<string, OAuthProvider>
24
+ secret: string
25
+ site: string | undefined
26
+ basePath: string
27
+ stateCookieName: string
28
+ defaultRedirect: string
29
+ requireEmailVerification: boolean
30
+ hasMailTransport: boolean
31
+ mailedLinkOrigin: (url: URL) => string | undefined
32
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
33
+ limitIp: (ctx: RequestContext, scope: string) => Response | undefined
34
+ isSecureCookie: (ctx: RequestContext) => boolean
35
+ claimUnverified: (user: TUser) => Promise<TUser>
36
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
37
+ createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
38
+ observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
39
+ }
40
+
41
+ async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
42
+ deps: OAuthRouteDeps<TUser>,
43
+ ctx: RequestContext,
44
+ profile: OAuthProfile,
45
+ redirectTarget: string,
46
+ ): Promise<Response> {
47
+ const linkOrigin = deps.mailedLinkOrigin(ctx.url)
48
+ if (deps.hasMailTransport && linkOrigin === undefined) {
49
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
50
+ return fail(ctx, 500, 'Verification links are not configured')
51
+ }
52
+ const created = await deps.insertUser({
53
+ email: profile.email,
54
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
55
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
56
+ emailVerified: false,
57
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
58
+ try {
59
+ await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
60
+ }
61
+ catch {
62
+ try {
63
+ await deps.observeAsync(deps.store.deleteUser(created.id))
64
+ }
65
+ catch (rollbackErr) {
66
+ console.error('[prunelle/auth] failed to roll back unverified OAuth user:', rollbackErr)
67
+ }
68
+ return fail(ctx, 500, 'Unable to send verification email')
69
+ }
70
+ return ctx.redirect(redirectTarget, 302)
71
+ }
72
+
73
+ async function resolveOAuthUser<TUser extends AuthUser>(
74
+ deps: OAuthRouteDeps<TUser>,
75
+ ctx: RequestContext,
76
+ provider: OAuthProvider,
77
+ profile: OAuthProfile,
78
+ redirectTarget: string,
79
+ ): Promise<TUser | Response> {
80
+ const { store, observeAsync, requireEmailVerification } = deps
81
+ const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
82
+
83
+ if (existingLink) {
84
+ let userRecord = await observeAsync(store.getUserById(existingLink.userId))
85
+ if (!userRecord)
86
+ return fail(ctx, 500, 'Unable to resolve user account')
87
+ if (requireEmailVerification && !userRecord.emailVerified) {
88
+ if (profile.emailVerified && normalizeEmail(profile.email) === userRecord.email) {
89
+ userRecord = await deps.claimUnverified(userRecord)
90
+ await observeAsync(store.linkOAuthAccount({
91
+ provider: provider.id,
92
+ providerAccountId: profile.id,
93
+ userId: userRecord.id,
94
+ createdAt: Date.now(),
95
+ }))
96
+ return userRecord
97
+ }
98
+ return fail(ctx, 403, 'Email not verified')
99
+ }
100
+ return userRecord
101
+ }
102
+
103
+ const byEmail = await observeAsync(store.getUserByEmail(profile.email))
104
+ let userRecord: TUser | undefined
105
+ if (byEmail && profile.emailVerified) {
106
+ userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
107
+ }
108
+ else if (!byEmail) {
109
+ if (requireEmailVerification && !profile.emailVerified)
110
+ return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
111
+ userRecord = await deps.insertUser({
112
+ email: profile.email,
113
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
114
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
115
+ emailVerified: profile.emailVerified,
116
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
117
+ }
118
+ else {
119
+ return fail(ctx, 409, 'An account with this email already exists; verify email to link')
120
+ }
121
+
122
+ await observeAsync(store.linkOAuthAccount({
123
+ provider: provider.id,
124
+ providerAccountId: profile.id,
125
+ userId: userRecord.id,
126
+ createdAt: Date.now(),
127
+ }))
128
+ return userRecord
129
+ }
130
+
131
+ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
132
+ const { route, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp } = deps
133
+ const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
134
+ `${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
135
+
136
+ const noStoreRoute = (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>): void => {
137
+ route(method, path, async ctx => withNoStore(await handler(ctx)))
138
+ }
139
+
140
+ noStoreRoute('GET', `${basePath}/oauth/:provider`, (ctx) => {
141
+ const limited = limitIp(ctx, 'oauth-start')
142
+ if (limited)
143
+ return limited
144
+
145
+ const provider = providers.get(ctx.params.provider ?? '')
146
+ if (!provider)
147
+ return fail(ctx, 404, 'Unknown OAuth provider')
148
+
149
+ const state = randomToken(24)
150
+ const verifier = provider.pkce !== false ? randomToken(32) : undefined
151
+ const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
152
+
153
+ const cookieVal = signPayload(secret, {
154
+ provider: provider.id,
155
+ state,
156
+ verifier,
157
+ redirect: redirectTarget,
158
+ exp: Date.now() + 10 * 60 * 1000,
159
+ } satisfies OAuthStateCookie)
160
+
161
+ ctx.cookies.set(stateCookieName, cookieVal, {
162
+ path: '/',
163
+ httpOnly: true,
164
+ sameSite: 'lax',
165
+ secure: deps.isSecureCookie(ctx),
166
+ maxAge: 600,
167
+ })
168
+
169
+ const callbackUrl = callbackUrlFor(ctx, provider)
170
+ const authUrl = new URL(provider.authorizeUrl)
171
+ authUrl.searchParams.set('client_id', provider.clientId)
172
+ authUrl.searchParams.set('redirect_uri', callbackUrl)
173
+ authUrl.searchParams.set('response_type', 'code')
174
+ authUrl.searchParams.set('scope', provider.scopes.join(' '))
175
+ authUrl.searchParams.set('state', state)
176
+ if (verifier !== undefined) {
177
+ authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
178
+ authUrl.searchParams.set('code_challenge_method', 'S256')
179
+ }
180
+ return ctx.redirect(authUrl.toString(), 302)
181
+ })
182
+
183
+ noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
184
+ const limited = limitIp(ctx, 'oauth-cb')
185
+ if (limited)
186
+ return limited
187
+
188
+ const provider = providers.get(ctx.params.provider ?? '')
189
+ if (!provider)
190
+ return fail(ctx, 404, 'Unknown OAuth provider')
191
+
192
+ const code = ctx.url.searchParams.get('code')
193
+ const returnedState = ctx.url.searchParams.get('state')
194
+ const rawCookie = ctx.cookies.get(stateCookieName)
195
+ ctx.cookies.delete(stateCookieName, { path: '/' })
196
+
197
+ if (!code || !returnedState || !rawCookie)
198
+ return fail(ctx, 400, 'Invalid OAuth callback parameters')
199
+
200
+ const saved = verifyPayload<OAuthStateCookie>(secret, rawCookie)
201
+ if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
202
+ return fail(ctx, 400, 'Invalid or expired OAuth state')
203
+
204
+ const callbackUrl = callbackUrlFor(ctx, provider)
205
+ const tokenBody = new URLSearchParams({
206
+ grant_type: 'authorization_code',
207
+ code,
208
+ redirect_uri: callbackUrl,
209
+ client_id: provider.clientId,
210
+ client_secret: provider.clientSecret,
211
+ })
212
+ if (saved.verifier !== undefined)
213
+ tokenBody.set('code_verifier', saved.verifier)
214
+
215
+ let tokenData: { access_token?: string }
216
+ try {
217
+ const tokenRes = await fetch(provider.tokenUrl, {
218
+ method: 'POST',
219
+ headers: {
220
+ 'content-type': 'application/x-www-form-urlencoded',
221
+ 'accept': 'application/json',
222
+ },
223
+ body: tokenBody.toString(),
224
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
225
+ })
226
+ if (!tokenRes.ok)
227
+ return fail(ctx, 502, 'OAuth token exchange failed')
228
+ tokenData = await tokenRes.json() as { access_token?: string }
229
+ }
230
+ catch {
231
+ return fail(ctx, 502, 'OAuth token exchange failed')
232
+ }
233
+
234
+ if (!tokenData?.access_token)
235
+ return fail(ctx, 502, 'OAuth provider did not return an access token')
236
+
237
+ let profile: OAuthProfile
238
+ try {
239
+ profile = await provider.fetchProfile(tokenData.access_token)
240
+ }
241
+ catch {
242
+ return fail(ctx, 502, 'OAuth profile fetch failed')
243
+ }
244
+ if (!profile?.id || !profile.email)
245
+ return fail(ctx, 502, 'OAuth profile fetch failed')
246
+
247
+ const redirectTarget = safeRedirect(saved.redirect, defaultRedirect)
248
+ const resolved = await resolveOAuthUser(deps, ctx, provider, profile, redirectTarget)
249
+ if (resolved instanceof Response)
250
+ return resolved
251
+
252
+ await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
253
+ return ctx.redirect(redirectTarget, 302)
254
+ })
255
+ }
package/src/oauth.ts ADDED
@@ -0,0 +1,155 @@
1
+ // Zero-dependency OAuth 2.0 + PKCE (S256) provider definitions for @prunellejs/auth.
2
+
3
+ export const OAUTH_FETCH_TIMEOUT_MS = 10_000
4
+
5
+ export interface OAuthProfile {
6
+ id: string
7
+ email: string
8
+ emailVerified: boolean
9
+ name?: string | undefined
10
+ avatarUrl?: string | undefined
11
+ }
12
+
13
+ export interface OAuthProvider {
14
+ id: string
15
+ clientId: string
16
+ clientSecret: string
17
+ authorizeUrl: string
18
+ tokenUrl: string
19
+ scopes: string[]
20
+ pkce?: boolean | undefined
21
+ fetchProfile: (accessToken: string) => Promise<OAuthProfile>
22
+ }
23
+
24
+ export interface OAuthPresetConfig {
25
+ clientId: string
26
+ clientSecret: string
27
+ scopes?: string[] | undefined
28
+ }
29
+
30
+ export function oauthProvider(def: OAuthProvider): OAuthProvider {
31
+ return def
32
+ }
33
+
34
+ interface GitHubEmail {
35
+ email: string
36
+ primary: boolean
37
+ verified: boolean
38
+ }
39
+
40
+ export function github(config: OAuthPresetConfig): OAuthProvider {
41
+ return {
42
+ id: 'github',
43
+ clientId: config.clientId,
44
+ clientSecret: config.clientSecret,
45
+ authorizeUrl: 'https://github.com/login/oauth/authorize',
46
+ tokenUrl: 'https://github.com/login/oauth/access_token',
47
+ scopes: config.scopes ?? ['read:user', 'user:email'],
48
+ pkce: false,
49
+ async fetchProfile(accessToken) {
50
+ const headers = { 'authorization': `Bearer ${accessToken}`, 'accept': 'application/vnd.github+json', 'user-agent': 'prunelle-auth' }
51
+ const userRes = await fetch('https://api.github.com/user', {
52
+ headers,
53
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
54
+ })
55
+ if (!userRes.ok)
56
+ throw new Error(`github profile fetch failed: ${userRes.status}`)
57
+ const user = await userRes.json() as { id: number, email?: string | null, name?: string | null, login?: string, avatar_url?: string }
58
+ let email = user.email ?? ''
59
+ let emailVerified = false
60
+
61
+ // Always query /user/emails: /user does not indicate whether a public email is verified.
62
+ const emailRes = await fetch('https://api.github.com/user/emails', {
63
+ headers,
64
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
65
+ })
66
+ if (emailRes.ok) {
67
+ const raw = await emailRes.json() as unknown
68
+ const emails = Array.isArray(raw) ? raw as GitHubEmail[] : []
69
+ const matched = email ? emails.find(e => e.email.toLowerCase() === email.toLowerCase()) : undefined
70
+ if (matched?.verified) {
71
+ email = matched.email
72
+ emailVerified = true
73
+ }
74
+ else {
75
+ const best = emails.find(e => e.primary && e.verified) ?? emails.find(e => e.verified) ?? matched ?? emails[0]
76
+ if (best) {
77
+ email = best.email
78
+ emailVerified = Boolean(best.verified)
79
+ }
80
+ }
81
+ }
82
+
83
+ if (!email)
84
+ throw new Error('github profile did not return an email address')
85
+ return {
86
+ id: String(user.id),
87
+ email,
88
+ emailVerified,
89
+ name: user.name ?? user.login,
90
+ avatarUrl: user.avatar_url,
91
+ }
92
+ },
93
+ }
94
+ }
95
+
96
+ export function discord(config: OAuthPresetConfig): OAuthProvider {
97
+ return {
98
+ id: 'discord',
99
+ clientId: config.clientId,
100
+ clientSecret: config.clientSecret,
101
+ authorizeUrl: 'https://discord.com/oauth2/authorize',
102
+ tokenUrl: 'https://discord.com/api/oauth2/token',
103
+ scopes: config.scopes ?? ['identify', 'email'],
104
+ pkce: true,
105
+ async fetchProfile(accessToken) {
106
+ const res = await fetch('https://discord.com/api/users/@me', {
107
+ headers: { authorization: `Bearer ${accessToken}` },
108
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
109
+ })
110
+ if (!res.ok)
111
+ throw new Error(`discord profile fetch failed: ${res.status}`)
112
+ const u = await res.json() as { id: string, email?: string, verified?: boolean, global_name?: string, username: string, avatar?: string | null }
113
+ if (!u.email)
114
+ throw new Error('discord profile did not return an email address')
115
+ const avatarUrl = u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png` : undefined
116
+ return {
117
+ id: u.id,
118
+ email: u.email,
119
+ emailVerified: Boolean(u.verified),
120
+ name: u.global_name ?? u.username,
121
+ avatarUrl,
122
+ }
123
+ },
124
+ }
125
+ }
126
+
127
+ export function google(config: OAuthPresetConfig): OAuthProvider {
128
+ return {
129
+ id: 'google',
130
+ clientId: config.clientId,
131
+ clientSecret: config.clientSecret,
132
+ authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
133
+ tokenUrl: 'https://oauth2.googleapis.com/token',
134
+ scopes: config.scopes ?? ['openid', 'email', 'profile'],
135
+ pkce: true,
136
+ async fetchProfile(accessToken) {
137
+ const res = await fetch('https://openidconnect.googleapis.com/v1/userinfo', {
138
+ headers: { authorization: `Bearer ${accessToken}` },
139
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
140
+ })
141
+ if (!res.ok)
142
+ throw new Error(`google profile fetch failed: ${res.status}`)
143
+ const u = await res.json() as { sub: string, email?: string, email_verified?: boolean, name?: string, picture?: string }
144
+ if (!u.email)
145
+ throw new Error('google profile did not return an email address')
146
+ return {
147
+ id: u.sub,
148
+ email: u.email,
149
+ emailVerified: Boolean(u.email_verified),
150
+ name: u.name,
151
+ avatarUrl: u.picture,
152
+ }
153
+ },
154
+ }
155
+ }