@prunellejs/auth 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,193 @@
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 { 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
+ limitIp: (ctx: RequestContext, scope: string) => Response | undefined
30
+ isSecureCookie: (ctx: RequestContext) => boolean
31
+ claimUnverified: (user: TUser) => Promise<TUser>
32
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
33
+ createSessionForUser: (userId: string, ctx: RequestContext) => Promise<unknown>
34
+ setResolvedUser: (ctx: RequestContext, user: PublicUser<TUser>) => void
35
+ observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
36
+ }
37
+
38
+ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAuthRouteDeps<TUser>): void {
39
+ const { route, store, providers, secret, site, basePath, stateCookieName, defaultRedirect, limitIp, observeAsync } = deps
40
+ const callbackUrlFor = (ctx: RequestContext, provider: OAuthProvider): string =>
41
+ `${site ?? ctx.url.origin}${basePath}/oauth/${encodeURIComponent(provider.id)}/callback`
42
+
43
+ const noStoreRoute = (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>): void => {
44
+ route(method, path, async ctx => withNoStore(await handler(ctx)))
45
+ }
46
+
47
+ noStoreRoute('GET', `${basePath}/oauth/:provider`, (ctx) => {
48
+ const limited = limitIp(ctx, 'oauth-start')
49
+ if (limited)
50
+ return limited
51
+
52
+ const provider = providers.get(ctx.params.provider ?? '')
53
+ if (!provider)
54
+ return fail(ctx, 404, 'Unknown OAuth provider')
55
+
56
+ const state = randomToken(24)
57
+ const verifier = provider.pkce !== false ? randomToken(32) : undefined
58
+ const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
59
+
60
+ const cookieVal = signPayload(secret, {
61
+ provider: provider.id,
62
+ state,
63
+ verifier,
64
+ redirect: redirectTarget,
65
+ exp: Date.now() + 10 * 60 * 1000,
66
+ } satisfies OAuthStateCookie)
67
+
68
+ ctx.cookies.set(stateCookieName, cookieVal, {
69
+ path: '/',
70
+ httpOnly: true,
71
+ sameSite: 'lax',
72
+ secure: deps.isSecureCookie(ctx),
73
+ maxAge: 600,
74
+ })
75
+
76
+ const callbackUrl = callbackUrlFor(ctx, provider)
77
+ const authUrl = new URL(provider.authorizeUrl)
78
+ authUrl.searchParams.set('client_id', provider.clientId)
79
+ authUrl.searchParams.set('redirect_uri', callbackUrl)
80
+ authUrl.searchParams.set('response_type', 'code')
81
+ authUrl.searchParams.set('scope', provider.scopes.join(' '))
82
+ authUrl.searchParams.set('state', state)
83
+ if (verifier !== undefined) {
84
+ authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
85
+ authUrl.searchParams.set('code_challenge_method', 'S256')
86
+ }
87
+ return ctx.redirect(authUrl.toString(), 302)
88
+ })
89
+
90
+ noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
91
+ const limited = limitIp(ctx, 'oauth-cb')
92
+ if (limited)
93
+ return limited
94
+
95
+ const provider = providers.get(ctx.params.provider ?? '')
96
+ if (!provider)
97
+ return fail(ctx, 404, 'Unknown OAuth provider')
98
+
99
+ const code = ctx.url.searchParams.get('code')
100
+ const returnedState = ctx.url.searchParams.get('state')
101
+ const rawCookie = ctx.cookies.get(stateCookieName)
102
+ ctx.cookies.delete(stateCookieName, { path: '/' })
103
+
104
+ if (!code || !returnedState || !rawCookie)
105
+ return fail(ctx, 400, 'Invalid OAuth callback parameters')
106
+
107
+ const saved = verifyPayload<OAuthStateCookie>(secret, rawCookie)
108
+ if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
109
+ return fail(ctx, 400, 'Invalid or expired OAuth state')
110
+
111
+ const callbackUrl = callbackUrlFor(ctx, provider)
112
+ const tokenBody = new URLSearchParams({
113
+ grant_type: 'authorization_code',
114
+ code,
115
+ redirect_uri: callbackUrl,
116
+ client_id: provider.clientId,
117
+ client_secret: provider.clientSecret,
118
+ })
119
+ if (saved.verifier !== undefined)
120
+ tokenBody.set('code_verifier', saved.verifier)
121
+
122
+ let tokenData: { access_token?: string }
123
+ try {
124
+ const tokenRes = await fetch(provider.tokenUrl, {
125
+ method: 'POST',
126
+ headers: {
127
+ 'content-type': 'application/x-www-form-urlencoded',
128
+ 'accept': 'application/json',
129
+ },
130
+ body: tokenBody.toString(),
131
+ signal: AbortSignal.timeout(OAUTH_FETCH_TIMEOUT_MS),
132
+ })
133
+ if (!tokenRes.ok)
134
+ return fail(ctx, 502, 'OAuth token exchange failed')
135
+ tokenData = await tokenRes.json() as { access_token?: string }
136
+ }
137
+ catch {
138
+ return fail(ctx, 502, 'OAuth token exchange failed')
139
+ }
140
+
141
+ if (!tokenData?.access_token)
142
+ return fail(ctx, 502, 'OAuth provider did not return an access token')
143
+
144
+ let profile: OAuthProfile
145
+ try {
146
+ profile = await provider.fetchProfile(tokenData.access_token)
147
+ }
148
+ catch {
149
+ return fail(ctx, 502, 'OAuth profile fetch failed')
150
+ }
151
+ if (!profile?.id || !profile.email)
152
+ return fail(ctx, 502, 'OAuth profile fetch failed')
153
+
154
+ const existingLink = await observeAsync(store.getOAuthAccount(provider.id, profile.id))
155
+ let userRecord: TUser | undefined
156
+
157
+ if (existingLink) {
158
+ userRecord = await observeAsync(store.getUserById(existingLink.userId))
159
+ }
160
+ else {
161
+ const byEmail = await observeAsync(store.getUserByEmail(profile.email))
162
+ if (byEmail && profile.emailVerified) {
163
+ userRecord = byEmail.emailVerified ? byEmail : await deps.claimUnverified(byEmail)
164
+ }
165
+ else if (!byEmail) {
166
+ userRecord = await deps.insertUser({
167
+ email: profile.email,
168
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
169
+ ...(profile.avatarUrl !== undefined ? { avatarUrl: profile.avatarUrl } : {}),
170
+ emailVerified: profile.emailVerified,
171
+ } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
172
+ }
173
+ else {
174
+ return fail(ctx, 409, 'An account with this email already exists; verify email to link')
175
+ }
176
+ if (userRecord) {
177
+ await observeAsync(store.linkOAuthAccount({
178
+ provider: provider.id,
179
+ providerAccountId: profile.id,
180
+ userId: userRecord.id,
181
+ createdAt: Date.now(),
182
+ }))
183
+ }
184
+ }
185
+
186
+ if (!userRecord)
187
+ return fail(ctx, 500, 'Unable to resolve user account')
188
+
189
+ await deps.createSessionForUser(userRecord.id, ctx)
190
+ deps.setResolvedUser(ctx, toPublicUser(userRecord))
191
+ return ctx.redirect(safeRedirect(saved.redirect, defaultRedirect), 302)
192
+ })
193
+ }
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
+ }
package/src/routes.ts ADDED
@@ -0,0 +1,269 @@
1
+ // Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
2
+
3
+ import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import { safeRedirect, wantsJson } from 'prunelle/server'
6
+ import type { CreateUserInput } from './index'
7
+
8
+ import type { AuthLimits } from './http'
9
+ import type { SessionManager } from './session'
10
+ import type { AuthStore, AuthUser, PublicUser } from './store'
11
+ import { verifyPassword } from './crypto'
12
+ import { fail, isValidEmail, linkConfirmPage, parseBody, respondAuthError, withNoStore } from './http'
13
+ import { normalizeEmail, toPublicUser } from './store'
14
+
15
+ const LINK_PAGES = {
16
+ 'magic-link': { title: 'Sign in', button: 'Sign in' },
17
+ 'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
18
+ }
19
+
20
+ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
21
+ api: ServerPluginAPI
22
+ store: AuthStore<TUser>
23
+ sessions: SessionManager<TUser>
24
+ limitIp: AuthLimits['limitIp']
25
+ limitEmail: AuthLimits['limitEmail']
26
+ basePath: string
27
+ authRouteOpts: PluginRouteOptions
28
+ minPasswordLength: number
29
+ defaultRedirect: string
30
+ requireEmailVerification: boolean
31
+ hasMailTransport: boolean
32
+ mailedLinkOrigin: (url: URL) => string | undefined
33
+ createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
34
+ insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
35
+ claimUnverified: (user: TUser) => Promise<TUser>
36
+ issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined) => Promise<string>
37
+ consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
38
+ sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
39
+ }
40
+
41
+ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
42
+ const {
43
+ api,
44
+ store,
45
+ sessions,
46
+ limitEmail,
47
+ limitIp,
48
+ basePath,
49
+ authRouteOpts,
50
+ minPasswordLength,
51
+ defaultRedirect,
52
+ requireEmailVerification,
53
+ hasMailTransport,
54
+ mailedLinkOrigin,
55
+ createUser,
56
+ insertUser,
57
+ claimUnverified,
58
+ issueLink,
59
+ consumeLink,
60
+ sendMagicLink,
61
+ } = deps
62
+
63
+ function authRoute(
64
+ method: 'GET' | 'POST',
65
+ path: string,
66
+ routeCfg: { limit?: string, emailLimit?: string, readBody?: boolean },
67
+ handler: (ctx: RequestContext, body: Record<string, string>) => Response | Promise<Response>,
68
+ ): void {
69
+ api.route(method, `${basePath}${path}`, async (ctx) => {
70
+ if (routeCfg.limit !== undefined) {
71
+ const limited = limitIp(ctx, routeCfg.limit)
72
+ if (limited)
73
+ return withNoStore(limited)
74
+ }
75
+ let body: Record<string, string> = {}
76
+ if (routeCfg.readBody) {
77
+ const parsed = await parseBody(ctx)
78
+ if (parsed instanceof Response)
79
+ return withNoStore(parsed)
80
+ body = parsed
81
+ }
82
+ if (routeCfg.emailLimit !== undefined) {
83
+ const limited = limitEmail(ctx, routeCfg.emailLimit, body.email)
84
+ if (limited)
85
+ return withNoStore(limited)
86
+ }
87
+ return withNoStore(await handler(ctx, body))
88
+ }, method === 'POST' ? authRouteOpts : undefined)
89
+ }
90
+
91
+ // GET on a mailed link: the token stays unused until the page's button posts it, and the POST checks the redirect.
92
+ function confirmLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string): void {
93
+ authRoute('GET', path, { limit }, (ctx) => {
94
+ const token = ctx.url.searchParams.get('token') ?? ''
95
+ if (!token)
96
+ return fail(ctx, 400, 'Missing token')
97
+ return linkConfirmPage(LINK_PAGES[kind], { token, redirect: ctx.url.searchParams.get('redirect') ?? '' })
98
+ })
99
+ }
100
+
101
+ // POST from the confirm page (form) or a client (JSON): consumes the token, then `signIn` picks the user to open a session for.
102
+ function consumeLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string, invalid: string, signIn: (consumed: { email: string, user: TUser | undefined }) => Promise<TUser | undefined>): void {
103
+ authRoute('POST', path, { limit, readBody: true }, async (ctx, body) => {
104
+ const rawToken = body.token ?? ctx.url.searchParams.get('token') ?? ''
105
+ const redirectTarget = safeRedirect(body.redirect ?? body.next ?? ctx.url.searchParams.get('redirect'), defaultRedirect)
106
+ if (!rawToken)
107
+ return fail(ctx, 400, 'Missing token')
108
+
109
+ const consumed = await consumeLink(kind, rawToken)
110
+ const userRecord = consumed && await signIn(consumed)
111
+ if (!userRecord)
112
+ return fail(ctx, 400, invalid)
113
+
114
+ await sessions.createSessionForUser(userRecord.id, ctx)
115
+ const pub = toPublicUser(userRecord)
116
+ sessions.setResolvedUser(ctx, pub)
117
+ if (wantsJson(ctx.request))
118
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
119
+ return ctx.redirect(redirectTarget, 303)
120
+ })
121
+ }
122
+
123
+ function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string): Response {
124
+ if (wantsJson(ctx.request)) {
125
+ return ctx.json({
126
+ ok: true,
127
+ verificationRequired: true,
128
+ message: 'If that address can be registered, a verification link has been sent.',
129
+ }, { status: 202 })
130
+ }
131
+ return ctx.redirect(redirectTarget, 303)
132
+ }
133
+
134
+ authRoute('GET', '/session', {}, async (ctx) => {
135
+ const resolved = await sessions.resolve(ctx)
136
+ return ctx.json({
137
+ user: resolved?.user ?? null,
138
+ session: resolved ? { id: resolved.session.id, expiresAt: resolved.session.expiresAt } : null,
139
+ })
140
+ })
141
+
142
+ authRoute('POST', '/signup', { limit: 'signup', emailLimit: 'signup', readBody: true }, async (ctx, body) => {
143
+ const email = normalizeEmail(body.email ?? '')
144
+ const password = body.password ?? ''
145
+ const name = body.name?.trim() || undefined
146
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
147
+
148
+ if (!isValidEmail(email))
149
+ return respondAuthError(ctx, 400, 'Please enter a valid email address')
150
+ if (password.length < minPasswordLength)
151
+ return respondAuthError(ctx, 400, `Password must be at least ${minPasswordLength} characters`)
152
+
153
+ if (requireEmailVerification) {
154
+ const linkOrigin = mailedLinkOrigin(ctx.url)
155
+ if (hasMailTransport && linkOrigin === undefined) {
156
+ console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
157
+ return fail(ctx, 500, 'Verification links are not configured')
158
+ }
159
+
160
+ const existing = await sessions.observeAsync(store.getUserByEmail(email))
161
+ if (existing) {
162
+ // Equalize timing with Argon2id hashing and avoid revealing whether the email is already registered.
163
+ await verifyPassword(password, undefined)
164
+ if (!existing.emailVerified) {
165
+ try {
166
+ await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget)
167
+ }
168
+ catch {
169
+ return fail(ctx, 500, 'Unable to send verification email')
170
+ }
171
+ }
172
+ return respondVerificationAccepted(ctx, redirectTarget)
173
+ }
174
+
175
+ let user: PublicUser<TUser>
176
+ try {
177
+ user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
178
+ }
179
+ catch (err) {
180
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
181
+ return respondVerificationAccepted(ctx, redirectTarget)
182
+ throw err
183
+ }
184
+
185
+ try {
186
+ await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget)
187
+ }
188
+ catch {
189
+ try {
190
+ await sessions.observeAsync(store.deleteUser(user.id))
191
+ }
192
+ catch {
193
+ // Best-effort rollback so a mail outage does not permanently lock out the email address.
194
+ }
195
+ return fail(ctx, 500, 'Unable to send verification email')
196
+ }
197
+
198
+ return respondVerificationAccepted(ctx, redirectTarget)
199
+ }
200
+
201
+ if (await sessions.observeAsync(store.getUserByEmail(email)))
202
+ return respondAuthError(ctx, 409, 'An account with this email already exists')
203
+
204
+ const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
205
+ await sessions.createSessionForUser(user.id, ctx)
206
+ sessions.setResolvedUser(ctx, user)
207
+
208
+ if (wantsJson(ctx.request))
209
+ return ctx.json({ ok: true, user }, { status: 201 })
210
+ return ctx.redirect(redirectTarget, 303)
211
+ })
212
+
213
+ confirmLinkRoute('verify-email', '/verify-email', 'verify-email')
214
+ consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
215
+ if (!user)
216
+ return undefined
217
+ return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
218
+ })
219
+
220
+ authRoute('POST', '/signin', { limit: 'signin', emailLimit: 'signin', readBody: true }, async (ctx, body) => {
221
+ const email = normalizeEmail(body.email ?? '')
222
+ const password = body.password ?? ''
223
+ const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
224
+
225
+ const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
226
+ const valid = await verifyPassword(password, userRecord?.passwordHash)
227
+ if (!userRecord || !valid)
228
+ return respondAuthError(ctx, 401, 'Invalid email or password')
229
+
230
+ if (requireEmailVerification && !userRecord.emailVerified)
231
+ return respondAuthError(ctx, 403, 'Email not verified')
232
+
233
+ await sessions.createSessionForUser(userRecord.id, ctx)
234
+ const pub = toPublicUser(userRecord)
235
+ sessions.setResolvedUser(ctx, pub)
236
+
237
+ if (wantsJson(ctx.request))
238
+ return ctx.json({ ok: true, user: pub }, { status: 200 })
239
+ return ctx.redirect(redirectTarget, 303)
240
+ })
241
+
242
+ authRoute('POST', '/signout', {}, async (ctx) => {
243
+ await sessions.signOut(ctx)
244
+ if (wantsJson(ctx.request))
245
+ return ctx.json({ ok: true })
246
+ return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
247
+ })
248
+
249
+ authRoute('POST', '/magic-link', { limit: 'magic', emailLimit: 'magic', readBody: true }, async (ctx, body) => {
250
+ const email = normalizeEmail(body.email ?? '')
251
+ if (!isValidEmail(email))
252
+ return fail(ctx, 400, 'Please enter a valid email address')
253
+
254
+ const linkOrigin = mailedLinkOrigin(ctx.url)
255
+ if (linkOrigin === undefined) {
256
+ console.error(`[prunelle/auth] refusing to mail a sign-in link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
257
+ return fail(ctx, 500, 'Sign-in links are not configured')
258
+ }
259
+ await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
260
+ return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
261
+ })
262
+
263
+ confirmLinkRoute('magic-link', '/magic-link/verify', 'magic-verify')
264
+ consumeLinkRoute('magic-link', '/magic-link/verify', 'magic-verify', 'Invalid or expired sign-in link', async ({ email, user }) => {
265
+ if (!user)
266
+ return insertUser({ email, emailVerified: true } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
267
+ return user.emailVerified ? user : claimUnverified(user)
268
+ })
269
+ }