@prunellejs/auth 0.0.0-stage → 0.7.2
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/LICENSE +21 -0
- package/llms.txt +95 -0
- package/package.json +27 -4
- package/src/account.ts +101 -0
- package/src/crypto.ts +130 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +214 -0
- package/src/index.ts +635 -0
- package/src/links.ts +178 -0
- package/src/oauth-routes.ts +260 -0
- package/src/oauth.ts +155 -0
- package/src/org-routes.ts +226 -0
- package/src/orgs.ts +403 -0
- package/src/passkey-client.ts +211 -0
- package/src/passkey-routes.ts +220 -0
- package/src/passkeys.ts +422 -0
- package/src/routes.ts +327 -0
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +384 -0
- package/src/sqlite-ext.ts +521 -0
- package/src/sqlite.ts +410 -0
- package/src/store-ext.ts +434 -0
- package/src/store.ts +339 -0
- package/src/totp-routes.ts +144 -0
- package/src/totp.ts +395 -0
- package/src/webauthn-crypto.ts +284 -0
- package/README.md +0 -3
package/src/links.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
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 LINK_PATHS = { 'magic-link': 'magic-link/verify', 'verify-email': 'verify-email' } as const
|
|
11
|
+
const LINK_MAILS = {
|
|
12
|
+
'magic-link': { subject: 'Your sign-in link', text: 'Sign in using this one-time link', html: 'Click to sign in', label: 'Sign in' },
|
|
13
|
+
'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' },
|
|
14
|
+
} as const
|
|
15
|
+
|
|
16
|
+
// Binds a verify-email token to the user's current passwordHash so any password update invalidates prior verification links.
|
|
17
|
+
function verifyBinding(user: { id: string, passwordHash?: string | undefined }): string {
|
|
18
|
+
return sha256Hex(`verify:${user.id}:${user.passwordHash ?? ''}`).slice(0, 32)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function buildMailDeliverer(
|
|
22
|
+
sendMail: AuthOptions['sendMail'],
|
|
23
|
+
mailer: AuthOptions['mailer'],
|
|
24
|
+
): ((mail: AuthMailPayload) => void | Promise<void>) | undefined {
|
|
25
|
+
if (sendMail)
|
|
26
|
+
return sendMail
|
|
27
|
+
if (!mailer)
|
|
28
|
+
return undefined
|
|
29
|
+
return async (mail) => {
|
|
30
|
+
await mailer.send({ to: mail.to, subject: mail.subject, text: mail.text, html: mail.html })
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type MailDeliverer = (mail: AuthMailPayload) => void | Promise<void>
|
|
35
|
+
|
|
36
|
+
/** A mail sent after the response, so a taken and a new address take the same time to answer; `onFailure` undoes what the sign-up did when it cannot be sent. */
|
|
37
|
+
export interface MailInBackground {
|
|
38
|
+
onFailure: () => void | Promise<void>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface LinkServiceDeps<TUser extends AuthUser = AuthUser> {
|
|
42
|
+
store: AuthStore<TUser>
|
|
43
|
+
sessions: SessionManager<TUser>
|
|
44
|
+
basePath: string
|
|
45
|
+
defaultRedirect: string
|
|
46
|
+
tokenTtlMs: number
|
|
47
|
+
deliverMail: ((mail: AuthMailPayload) => void | Promise<void>) | undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createLinkService<TUser extends AuthUser = AuthUser>(deps: LinkServiceDeps<TUser>) {
|
|
51
|
+
const { store, sessions, basePath, defaultRedirect, tokenTtlMs, deliverMail } = deps
|
|
52
|
+
const pendingDeliveries = new Set<Promise<void>>()
|
|
53
|
+
|
|
54
|
+
async function issueLink(
|
|
55
|
+
kind: 'magic-link' | 'verify-email',
|
|
56
|
+
userId: string | undefined,
|
|
57
|
+
email: string,
|
|
58
|
+
origin: string | undefined,
|
|
59
|
+
redirectTo: string | undefined,
|
|
60
|
+
background?: MailInBackground,
|
|
61
|
+
): Promise<string> {
|
|
62
|
+
const normalized = normalizeEmail(email)
|
|
63
|
+
const boundUser = kind === 'verify-email' && userId !== undefined ? await sessions.observeAsync(store.getUserById(userId)) : undefined
|
|
64
|
+
const rawToken = boundUser ? `${randomToken(32)}.${verifyBinding(boundUser)}` : randomToken(32)
|
|
65
|
+
const tokenHash = sha256Hex(rawToken)
|
|
66
|
+
await sessions.observeAsync(store.createToken({
|
|
67
|
+
tokenHash,
|
|
68
|
+
...(userId !== undefined ? { userId } : {}),
|
|
69
|
+
email: normalized,
|
|
70
|
+
kind,
|
|
71
|
+
expiresAt: Date.now() + tokenTtlMs,
|
|
72
|
+
}))
|
|
73
|
+
|
|
74
|
+
const next = safeRedirect(redirectTo, defaultRedirect)
|
|
75
|
+
const path = `${basePath}/${LINK_PATHS[kind]}?token=${encodeURIComponent(rawToken)}&redirect=${encodeURIComponent(next)}`
|
|
76
|
+
const url = origin !== undefined ? `${origin.replace(/\/$/, '')}${path}` : path
|
|
77
|
+
|
|
78
|
+
if (deliverMail && origin !== undefined) {
|
|
79
|
+
const delivery = deliverLink(deliverMail, kind, normalized, url, tokenHash)
|
|
80
|
+
if (background === undefined) {
|
|
81
|
+
await delivery
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
const tracked = delivery.catch(err => failBackgroundMail(err, background)).finally(() => { pendingDeliveries.delete(tracked) })
|
|
85
|
+
pendingDeliveries.add(tracked)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return url
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Mails the link; a mail that cannot be sent takes its token back, so a link that never arrived cannot be used.
|
|
92
|
+
async function deliverLink(send: MailDeliverer, kind: 'magic-link' | 'verify-email', to: string, url: string, tokenHash: string): Promise<void> {
|
|
93
|
+
const mail = LINK_MAILS[kind]
|
|
94
|
+
try {
|
|
95
|
+
await send({
|
|
96
|
+
to,
|
|
97
|
+
subject: mail.subject,
|
|
98
|
+
text: `${mail.text}: ${url}`,
|
|
99
|
+
html: `<p>${mail.html}: <a href="${url}">${mail.label}</a></p>`,
|
|
100
|
+
url,
|
|
101
|
+
kind,
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
try {
|
|
106
|
+
await sessions.observeAsync(store.consumeToken(tokenHash, kind))
|
|
107
|
+
}
|
|
108
|
+
catch (cleanupErr) {
|
|
109
|
+
console.error('[prunelle/auth] failed to clean up token after mail error:', cleanupErr)
|
|
110
|
+
}
|
|
111
|
+
throw err
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function failBackgroundMail(err: unknown, background: MailInBackground): Promise<void> {
|
|
116
|
+
console.error('[prunelle/auth] could not send a verification mail:', err)
|
|
117
|
+
try {
|
|
118
|
+
await background.onFailure()
|
|
119
|
+
}
|
|
120
|
+
catch (rollbackErr) {
|
|
121
|
+
console.error('[prunelle/auth] failed to roll back after a mail error:', rollbackErr)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function sendVerificationEmail(email: string, origin: string, redirectTo?: string): Promise<string> {
|
|
126
|
+
const normalized = normalizeEmail(email)
|
|
127
|
+
const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
|
|
128
|
+
return issueLink('verify-email', existing?.id, normalized, origin, redirectTo)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function sendMagicLink(email: string, origin: string, redirectTo?: string): Promise<string> {
|
|
132
|
+
const normalized = normalizeEmail(email)
|
|
133
|
+
const existing = await sessions.observeAsync(store.getUserByEmail(normalized))
|
|
134
|
+
return issueLink('magic-link', existing?.id, normalized, origin, redirectTo)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function consumeLink(kind: 'magic-link' | 'verify-email', rawToken: string): Promise<{ email: string, user: TUser | undefined } | undefined> {
|
|
138
|
+
const consumed = await sessions.observeAsync(store.consumeToken(sha256Hex(rawToken), kind))
|
|
139
|
+
if (!consumed)
|
|
140
|
+
return undefined
|
|
141
|
+
const user = consumed.userId
|
|
142
|
+
? await sessions.observeAsync(store.getUserById(consumed.userId))
|
|
143
|
+
: await sessions.observeAsync(store.getUserByEmail(consumed.email))
|
|
144
|
+
if (kind === 'verify-email') {
|
|
145
|
+
const dot = rawToken.lastIndexOf('.')
|
|
146
|
+
if (!user || dot <= 0 || !safeEqual(rawToken.slice(dot + 1), verifyBinding(user)))
|
|
147
|
+
return undefined
|
|
148
|
+
}
|
|
149
|
+
return { email: consumed.email, user }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function drain(timeoutMs = 5_000): Promise<void> {
|
|
153
|
+
if (pendingDeliveries.size === 0)
|
|
154
|
+
return
|
|
155
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
156
|
+
try {
|
|
157
|
+
await Promise.race([
|
|
158
|
+
Promise.allSettled([...pendingDeliveries]),
|
|
159
|
+
new Promise<void>((resolve) => {
|
|
160
|
+
timer = setTimeout(resolve, timeoutMs)
|
|
161
|
+
timer.unref?.()
|
|
162
|
+
}),
|
|
163
|
+
])
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
if (timer !== undefined)
|
|
167
|
+
clearTimeout(timer)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
issueLink,
|
|
173
|
+
sendVerificationEmail,
|
|
174
|
+
sendMagicLink,
|
|
175
|
+
consumeLink,
|
|
176
|
+
drain,
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
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 type { TotpManager } from './totp'
|
|
8
|
+
import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
|
|
9
|
+
import { authCookie, fail, withNoStore } from './http'
|
|
10
|
+
import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
|
|
11
|
+
import { normalizeEmail, toPublicUser } from './store'
|
|
12
|
+
import { respondTwoFactorChallenge } from './totp'
|
|
13
|
+
|
|
14
|
+
interface OAuthStateCookie {
|
|
15
|
+
provider: string
|
|
16
|
+
state: string
|
|
17
|
+
verifier?: string | undefined
|
|
18
|
+
redirect: string
|
|
19
|
+
exp: number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
|
|
23
|
+
route: (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>) => void
|
|
24
|
+
store: AuthStore<TUser>
|
|
25
|
+
providers: ReadonlyMap<string, OAuthProvider>
|
|
26
|
+
/** The app's signing secret, resolved at first use. */
|
|
27
|
+
secret: () => string
|
|
28
|
+
site: string | undefined
|
|
29
|
+
basePath: string
|
|
30
|
+
stateCookieName: string
|
|
31
|
+
defaultRedirect: string
|
|
32
|
+
requireEmailVerification: boolean
|
|
33
|
+
hasMailTransport: boolean
|
|
34
|
+
mailedLinkOrigin: (url: URL) => string | undefined
|
|
35
|
+
issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
|
|
36
|
+
limitIp: (ctx: RequestContext, scope: string) => Response | undefined
|
|
37
|
+
isSecureCookie: (ctx: RequestContext) => boolean
|
|
38
|
+
claimUnverified: (user: TUser) => Promise<TUser>
|
|
39
|
+
insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
|
|
40
|
+
/** Keep the provider's name and avatar URL on a new account. */
|
|
41
|
+
storeProfile: boolean
|
|
42
|
+
totp: Pick<TotpManager, 'getTwoFactorMethods' | 'issuePendingCookie'>
|
|
43
|
+
twoFactorRedirect: string
|
|
44
|
+
createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
|
|
45
|
+
observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The provider's name and avatar belong to the account only when the app asked to keep them.
|
|
49
|
+
function profileFields(deps: Pick<OAuthRouteDeps, 'storeProfile'>, profile: OAuthProfile): { name?: string, avatarUrl?: string } {
|
|
50
|
+
if (!deps.storeProfile)
|
|
51
|
+
return {}
|
|
52
|
+
return {
|
|
53
|
+
...(profile.name !== undefined ? { name: profile.name } : {}),
|
|
54
|
+
...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
|
|
59
|
+
deps: OAuthRouteDeps<TUser>,
|
|
60
|
+
ctx: RequestContext,
|
|
61
|
+
profile: OAuthProfile,
|
|
62
|
+
redirectTarget: string,
|
|
63
|
+
): Promise<Response> {
|
|
64
|
+
const linkOrigin = deps.mailedLinkOrigin(ctx.url)
|
|
65
|
+
if (deps.hasMailTransport && linkOrigin === undefined) {
|
|
66
|
+
console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
|
|
67
|
+
return fail(ctx, 500, 'Verification links are not configured')
|
|
68
|
+
}
|
|
69
|
+
const created = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: false } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
70
|
+
try {
|
|
71
|
+
await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
try {
|
|
75
|
+
await deps.observeAsync(deps.store.deleteUser(created.id))
|
|
76
|
+
}
|
|
77
|
+
catch (rollbackErr) {
|
|
78
|
+
console.error('[prunelle/auth] failed to roll back unverified OAuth user:', rollbackErr)
|
|
79
|
+
}
|
|
80
|
+
return fail(ctx, 500, 'Unable to send verification email')
|
|
81
|
+
}
|
|
82
|
+
return ctx.redirect(redirectTarget, 302)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function resolveOAuthUser<TUser extends AuthUser>(
|
|
86
|
+
deps: OAuthRouteDeps<TUser>,
|
|
87
|
+
ctx: RequestContext,
|
|
88
|
+
provider: OAuthProvider,
|
|
89
|
+
profile: OAuthProfile,
|
|
90
|
+
redirectTarget: string,
|
|
91
|
+
): Promise<TUser | Response> {
|
|
92
|
+
const { store, observeAsync, requireEmailVerification } = deps
|
|
93
|
+
const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
|
|
94
|
+
|
|
95
|
+
if (existingLink) {
|
|
96
|
+
let userRecord = await observeAsync(store.getUserById(existingLink.userId))
|
|
97
|
+
if (!userRecord)
|
|
98
|
+
return fail(ctx, 500, 'Unable to resolve user account')
|
|
99
|
+
if (requireEmailVerification && !userRecord.emailVerified) {
|
|
100
|
+
if (profile.emailVerified && normalizeEmail(profile.email) === userRecord.email) {
|
|
101
|
+
userRecord = await deps.claimUnverified(userRecord)
|
|
102
|
+
await observeAsync(store.linkOAuthAccount({
|
|
103
|
+
provider: provider.id,
|
|
104
|
+
providerAccountId: profile.id,
|
|
105
|
+
userId: userRecord.id,
|
|
106
|
+
createdAt: Date.now(),
|
|
107
|
+
}))
|
|
108
|
+
return userRecord
|
|
109
|
+
}
|
|
110
|
+
return fail(ctx, 403, 'Email not verified')
|
|
111
|
+
}
|
|
112
|
+
return userRecord
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const byEmail = await observeAsync(store.getUserByEmail(profile.email))
|
|
116
|
+
let userRecord: TUser | undefined
|
|
117
|
+
if (byEmail && profile.emailVerified) {
|
|
118
|
+
userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
|
|
119
|
+
}
|
|
120
|
+
else if (!byEmail) {
|
|
121
|
+
if (requireEmailVerification && !profile.emailVerified)
|
|
122
|
+
return handleUnverifiedOAuthSignup(deps, ctx, profile, redirectTarget)
|
|
123
|
+
userRecord = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: profile.emailVerified } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
return fail(ctx, 409, 'An account with this email already exists; verify email to link')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
await observeAsync(store.linkOAuthAccount({
|
|
130
|
+
provider: provider.id,
|
|
131
|
+
providerAccountId: profile.id,
|
|
132
|
+
userId: userRecord.id,
|
|
133
|
+
createdAt: Date.now(),
|
|
134
|
+
}))
|
|
135
|
+
return userRecord
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
|
|
139
|
+
const { route, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp } = deps
|
|
140
|
+
const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
|
|
141
|
+
`${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
|
|
142
|
+
|
|
143
|
+
const noStoreRoute = (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>): void => {
|
|
144
|
+
route(method, path, async ctx => withNoStore(await handler(ctx)))
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
noStoreRoute('GET', `${basePath}/oauth/:provider`, (ctx) => {
|
|
148
|
+
const limited = limitIp(ctx, 'oauth-start')
|
|
149
|
+
if (limited)
|
|
150
|
+
return limited
|
|
151
|
+
|
|
152
|
+
const provider = providers.get(ctx.params.provider ?? '')
|
|
153
|
+
if (!provider)
|
|
154
|
+
return fail(ctx, 404, 'Unknown OAuth provider')
|
|
155
|
+
|
|
156
|
+
const state = randomToken(24)
|
|
157
|
+
const verifier = provider.pkce !== false ? randomToken(32) : undefined
|
|
158
|
+
const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
|
|
159
|
+
|
|
160
|
+
const cookieVal = signPayload(secret(), {
|
|
161
|
+
provider: provider.id,
|
|
162
|
+
state,
|
|
163
|
+
verifier,
|
|
164
|
+
redirect: redirectTarget,
|
|
165
|
+
exp: Date.now() + 10 * 60 * 1000,
|
|
166
|
+
} satisfies OAuthStateCookie)
|
|
167
|
+
|
|
168
|
+
ctx.cookies.set(stateCookieName, cookieVal, authCookie(deps.isSecureCookie(ctx), 600))
|
|
169
|
+
|
|
170
|
+
const callbackUrl = callbackUrlFor(ctx, provider)
|
|
171
|
+
const authUrl = new URL(provider.authorizeUrl)
|
|
172
|
+
authUrl.searchParams.set('client_id', provider.clientId)
|
|
173
|
+
authUrl.searchParams.set('redirect_uri', callbackUrl)
|
|
174
|
+
authUrl.searchParams.set('response_type', 'code')
|
|
175
|
+
authUrl.searchParams.set('scope', provider.scopes.join(' '))
|
|
176
|
+
authUrl.searchParams.set('state', state)
|
|
177
|
+
if (verifier !== undefined) {
|
|
178
|
+
authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
|
|
179
|
+
authUrl.searchParams.set('code_challenge_method', 'S256')
|
|
180
|
+
}
|
|
181
|
+
return ctx.redirect(authUrl.toString(), 302, { external: true })
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
|
|
185
|
+
const limited = limitIp(ctx, 'oauth-cb')
|
|
186
|
+
if (limited)
|
|
187
|
+
return limited
|
|
188
|
+
|
|
189
|
+
const provider = providers.get(ctx.params.provider ?? '')
|
|
190
|
+
if (!provider)
|
|
191
|
+
return fail(ctx, 404, 'Unknown OAuth provider')
|
|
192
|
+
|
|
193
|
+
const code = ctx.url.searchParams.get('code')
|
|
194
|
+
const returnedState = ctx.url.searchParams.get('state')
|
|
195
|
+
const rawCookie = ctx.cookies.get(stateCookieName)
|
|
196
|
+
ctx.cookies.delete(stateCookieName, { path: '/' })
|
|
197
|
+
|
|
198
|
+
if (!code || !returnedState || !rawCookie)
|
|
199
|
+
return fail(ctx, 400, 'Invalid OAuth callback parameters')
|
|
200
|
+
|
|
201
|
+
const saved = verifyPayload<OAuthStateCookie>(secret(), rawCookie)
|
|
202
|
+
if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
|
|
203
|
+
return fail(ctx, 400, 'Invalid or expired OAuth state')
|
|
204
|
+
|
|
205
|
+
const callbackUrl = callbackUrlFor(ctx, provider)
|
|
206
|
+
const tokenBody = new URLSearchParams({
|
|
207
|
+
grant_type: 'authorization_code',
|
|
208
|
+
code,
|
|
209
|
+
redirect_uri: callbackUrl,
|
|
210
|
+
client_id: provider.clientId,
|
|
211
|
+
client_secret: provider.clientSecret,
|
|
212
|
+
})
|
|
213
|
+
if (saved.verifier !== undefined)
|
|
214
|
+
tokenBody.set('code_verifier', saved.verifier)
|
|
215
|
+
|
|
216
|
+
let tokenData: { access_token?: string }
|
|
217
|
+
try {
|
|
218
|
+
const tokenRes = await fetch(provider.tokenUrl, {
|
|
219
|
+
method: 'POST',
|
|
220
|
+
headers: {
|
|
221
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
222
|
+
'accept': 'application/json',
|
|
223
|
+
},
|
|
224
|
+
body: tokenBody.toString(),
|
|
225
|
+
signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
|
|
226
|
+
})
|
|
227
|
+
if (!tokenRes.ok)
|
|
228
|
+
return fail(ctx, 502, 'OAuth token exchange failed')
|
|
229
|
+
tokenData = await tokenRes.json() as { access_token?: string }
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return fail(ctx, 502, 'OAuth token exchange failed')
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (!tokenData?.access_token)
|
|
236
|
+
return fail(ctx, 502, 'OAuth provider did not return an access token')
|
|
237
|
+
|
|
238
|
+
let profile: OAuthProfile
|
|
239
|
+
try {
|
|
240
|
+
profile = await provider.fetchProfile(tokenData.access_token)
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return fail(ctx, 502, 'OAuth profile fetch failed')
|
|
244
|
+
}
|
|
245
|
+
if (!profile?.id || !profile.email)
|
|
246
|
+
return fail(ctx, 502, 'OAuth profile fetch failed')
|
|
247
|
+
|
|
248
|
+
const redirectTarget = safeRedirect(saved.redirect, defaultRedirect)
|
|
249
|
+
const resolved = await resolveOAuthUser(deps, ctx, provider, profile, redirectTarget)
|
|
250
|
+
if (resolved instanceof Response)
|
|
251
|
+
return resolved
|
|
252
|
+
|
|
253
|
+
const twoFactorMethods = await deps.totp.getTwoFactorMethods(resolved.id)
|
|
254
|
+
if (twoFactorMethods.length > 0)
|
|
255
|
+
return respondTwoFactorChallenge(deps.totp, ctx, resolved.id, redirectTarget, deps.twoFactorRedirect, twoFactorMethods, 302)
|
|
256
|
+
|
|
257
|
+
await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
|
|
258
|
+
return ctx.redirect(redirectTarget, 302)
|
|
259
|
+
})
|
|
260
|
+
}
|
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
|
+
}
|