@prunellejs/auth 0.1.1 → 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 +53 -23
- package/package.json +5 -4
- package/src/account.ts +101 -0
- package/src/crypto.ts +57 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +127 -24
- package/src/index.ts +320 -237
- package/src/links.ts +178 -0
- package/src/oauth-routes.ts +119 -52
- 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 +178 -120
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +158 -104
- package/src/sqlite-ext.ts +521 -0
- package/src/sqlite.ts +144 -71
- package/src/store-ext.ts +434 -0
- package/src/store.ts +120 -48
- package/src/totp-routes.ts +144 -0
- package/src/totp.ts +395 -0
- package/src/webauthn-crypto.ts +284 -0
package/src/routes.ts
CHANGED
|
@@ -1,31 +1,86 @@
|
|
|
1
1
|
// Auth HTTP routes: /session, /signup, /verify-email, /signin, /signout, /magic-link, /magic-link/verify.
|
|
2
2
|
|
|
3
|
-
import type { PluginRouteOptions, ServerPluginAPI } from 'prunelle/config'
|
|
4
3
|
import type { RequestContext } from 'prunelle/server'
|
|
5
|
-
import {
|
|
4
|
+
import type { AuthFormMessage, AuthFormMessages } from './form-messages'
|
|
5
|
+
import type { AuthLimits, AuthRouteRegistrar } from './http'
|
|
6
6
|
import type { CreateUserInput } from './index'
|
|
7
|
-
|
|
8
|
-
import type { AuthLimits } from './http'
|
|
7
|
+
import type { MailInBackground } from './links'
|
|
9
8
|
import type { SessionManager } from './session'
|
|
10
9
|
import type { AuthStore, AuthUser, PublicUser } from './store'
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
10
|
+
import type { TotpManager } from './totp'
|
|
11
|
+
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
12
|
+
import { hashPassword, verifyPassword } from './crypto'
|
|
13
|
+
import { fail, formPagePath, isValidEmail, linkConfirmPage, respondAuthError } from './http'
|
|
13
14
|
import { normalizeEmail, toPublicUser } from './store'
|
|
15
|
+
import { respondTwoFactorChallenge } from './totp'
|
|
14
16
|
|
|
15
17
|
const LINK_PAGES = {
|
|
16
18
|
'magic-link': { title: 'Sign in', button: 'Sign in' },
|
|
17
19
|
'verify-email': { title: 'Confirm your email address', button: 'Confirm' },
|
|
18
20
|
}
|
|
19
21
|
|
|
22
|
+
function isPasswordTooLong(password: string, max: number): boolean {
|
|
23
|
+
return password.length > max || Buffer.byteLength(password, 'utf8') > max
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// A form goes back to its page to say a link was sent: the redirect target is for after the link, and a guard would bounce an unverified visitor from it.
|
|
27
|
+
function respondVerificationAccepted(ctx: RequestContext, redirectTarget: string, sent: AuthFormMessage): Response {
|
|
28
|
+
if (wantsJson(ctx.request))
|
|
29
|
+
return ctx.json({ ok: true, verificationRequired: true, message: sent.text }, { status: 202 })
|
|
30
|
+
return ctx.redirect(formPagePath(ctx, 'notice', sent.code) ?? redirectTarget, 303)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// A second sign-up on an unverified address contests it: the mailbox owner cannot tell whose mailed link they click, so neither party's password or name is kept, and the link alone signs the owner in (#75).
|
|
34
|
+
async function reRegisterUnverified<TUser extends AuthUser>(
|
|
35
|
+
deps: AuthRoutesDeps<TUser>,
|
|
36
|
+
existing: TUser,
|
|
37
|
+
password: string,
|
|
38
|
+
linkOrigin: string | undefined,
|
|
39
|
+
redirectTarget: string,
|
|
40
|
+
): Promise<boolean> {
|
|
41
|
+
const { store, sessions, issueLink } = deps
|
|
42
|
+
// Same Argon2id cost as a first sign-up, so timing does not reveal a pending account.
|
|
43
|
+
await hashPassword(password)
|
|
44
|
+
const latest = await sessions.observeAsync(store.getUserById(existing.id))
|
|
45
|
+
if (!latest || latest.emailVerified)
|
|
46
|
+
return true
|
|
47
|
+
const prevHash = latest.passwordHash
|
|
48
|
+
const prevName = latest.name
|
|
49
|
+
await sessions.observeAsync(store.deleteUserSessions(existing.id))
|
|
50
|
+
await sessions.observeAsync(store.deleteUserOAuthAccounts(existing.id))
|
|
51
|
+
const patch = { passwordHash: undefined, name: undefined } as Partial<Omit<TUser, 'id' | 'createdAt'>>
|
|
52
|
+
const cleared = await sessions.observeAsync(store.updateUser(existing.id, patch))
|
|
53
|
+
const restore = async (): Promise<void> => {
|
|
54
|
+
const cur = await sessions.observeAsync(store.getUserById(existing.id))
|
|
55
|
+
if (!cur || cur.emailVerified || cur.updatedAt !== cleared?.updatedAt)
|
|
56
|
+
return
|
|
57
|
+
await sessions.observeAsync(store.updateUser(existing.id, { passwordHash: prevHash, name: prevName } as Partial<Omit<TUser, 'id' | 'createdAt'>>))
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
await issueLink('verify-email', existing.id, existing.email, linkOrigin, redirectTarget, { onFailure: restore })
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
try {
|
|
65
|
+
await restore()
|
|
66
|
+
}
|
|
67
|
+
catch (rollbackErr) {
|
|
68
|
+
console.error('[prunelle/auth] failed to roll back unverified signup update:', rollbackErr)
|
|
69
|
+
}
|
|
70
|
+
return false
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
20
74
|
export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
21
|
-
|
|
75
|
+
authRoute: AuthRouteRegistrar
|
|
76
|
+
limits: AuthLimits
|
|
22
77
|
store: AuthStore<TUser>
|
|
23
78
|
sessions: SessionManager<TUser>
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
basePath: string
|
|
27
|
-
authRouteOpts: PluginRouteOptions
|
|
79
|
+
totp: TotpManager
|
|
80
|
+
twoFactorRedirect: string
|
|
28
81
|
minPasswordLength: number
|
|
82
|
+
maxPasswordLength: number
|
|
83
|
+
messages: AuthFormMessages
|
|
29
84
|
defaultRedirect: string
|
|
30
85
|
requireEmailVerification: boolean
|
|
31
86
|
hasMailTransport: boolean
|
|
@@ -33,61 +88,96 @@ export interface AuthRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
|
33
88
|
createUser: (input: CreateUserInput<TUser>) => Promise<PublicUser<TUser>>
|
|
34
89
|
insertUser: (fields: Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>) => Promise<TUser>
|
|
35
90
|
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>
|
|
91
|
+
issueLink: (kind: 'magic-link' | 'verify-email', userId: string | undefined, email: string, origin: string | undefined, redirectTo: string | undefined, background?: MailInBackground) => Promise<string>
|
|
37
92
|
consumeLink: (kind: 'magic-link' | 'verify-email', rawToken: string) => Promise<{ email: string, user: TUser | undefined } | undefined>
|
|
38
93
|
sendMagicLink: (email: string, origin: string, redirectTo?: string) => Promise<string>
|
|
39
94
|
}
|
|
40
95
|
|
|
96
|
+
// A sign-up that waits for its mailed link: the answer is the same whether the address was new, unverified or taken, so it does not tell them apart.
|
|
97
|
+
async function signUpPendingVerification<TUser extends AuthUser>(
|
|
98
|
+
deps: AuthRoutesDeps<TUser>,
|
|
99
|
+
ctx: RequestContext,
|
|
100
|
+
input: { email: string, password: string, name: string | undefined, redirectTarget: string },
|
|
101
|
+
): Promise<Response> {
|
|
102
|
+
const { limits, store, sessions, messages, hasMailTransport, mailedLinkOrigin, createUser, issueLink } = deps
|
|
103
|
+
const { email, password, name, redirectTarget } = input
|
|
104
|
+
const linkOrigin = mailedLinkOrigin(ctx.url)
|
|
105
|
+
if (hasMailTransport && linkOrigin === undefined) {
|
|
106
|
+
console.error(`[prunelle/auth] refusing to mail a verification link for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
|
|
107
|
+
return fail(ctx, 500, 'Verification links are not configured')
|
|
108
|
+
}
|
|
109
|
+
const limited = limits.limitMail(ctx, email)
|
|
110
|
+
if (limited)
|
|
111
|
+
return limited
|
|
112
|
+
|
|
113
|
+
const existing = await sessions.observeAsync(store.getUserByEmail(email))
|
|
114
|
+
if (existing) {
|
|
115
|
+
if (!existing.emailVerified) {
|
|
116
|
+
const sent = await reRegisterUnverified(deps, existing, password, linkOrigin, redirectTarget)
|
|
117
|
+
if (!sent)
|
|
118
|
+
return fail(ctx, 500, 'Unable to send verification email')
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
// The same Argon2id cost as a new address, and no mail inside the request on either path, so timing does not reveal a verified account.
|
|
122
|
+
await hashPassword(password)
|
|
123
|
+
}
|
|
124
|
+
return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let user: PublicUser<TUser>
|
|
128
|
+
try {
|
|
129
|
+
user = await createUser({ email, password, name, emailVerified: false } as CreateUserInput<TUser>)
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
133
|
+
return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
|
|
134
|
+
throw err
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const deleteIfUnchanged = async (): Promise<void> => {
|
|
138
|
+
const cur = await sessions.observeAsync(store.getUserById(user.id))
|
|
139
|
+
if (!cur || cur.emailVerified || cur.updatedAt !== user.updatedAt)
|
|
140
|
+
return
|
|
141
|
+
await sessions.observeAsync(store.deleteUser(user.id))
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
// A mail outage deletes the account once the send fails, so it does not lock the address out.
|
|
145
|
+
await issueLink('verify-email', user.id, user.email, linkOrigin, redirectTarget, { onFailure: deleteIfUnchanged })
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
try {
|
|
149
|
+
await deleteIfUnchanged()
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
// Best-effort rollback so a store outage does not permanently lock out the email address.
|
|
153
|
+
}
|
|
154
|
+
return fail(ctx, 500, 'Unable to send verification email')
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return respondVerificationAccepted(ctx, redirectTarget, messages['signup.verification-sent'])
|
|
158
|
+
}
|
|
159
|
+
|
|
41
160
|
export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: AuthRoutesDeps<TUser>): void {
|
|
42
161
|
const {
|
|
43
|
-
|
|
162
|
+
authRoute,
|
|
163
|
+
limits,
|
|
44
164
|
store,
|
|
45
165
|
sessions,
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
basePath,
|
|
49
|
-
authRouteOpts,
|
|
166
|
+
totp,
|
|
167
|
+
twoFactorRedirect,
|
|
50
168
|
minPasswordLength,
|
|
169
|
+
maxPasswordLength,
|
|
170
|
+
messages,
|
|
51
171
|
defaultRedirect,
|
|
52
172
|
requireEmailVerification,
|
|
53
|
-
hasMailTransport,
|
|
54
173
|
mailedLinkOrigin,
|
|
55
174
|
createUser,
|
|
56
175
|
insertUser,
|
|
57
176
|
claimUnverified,
|
|
58
|
-
issueLink,
|
|
59
177
|
consumeLink,
|
|
60
178
|
sendMagicLink,
|
|
61
179
|
} = deps
|
|
62
180
|
|
|
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
181
|
// GET on a mailed link: the token stays unused until the page's button posts it, and the POST checks the redirect.
|
|
92
182
|
function confirmLinkRoute(kind: 'magic-link' | 'verify-email', path: string, limit: string): void {
|
|
93
183
|
authRoute('GET', path, { limit }, (ctx) => {
|
|
@@ -111,26 +201,18 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
111
201
|
if (!userRecord)
|
|
112
202
|
return fail(ctx, 400, invalid)
|
|
113
203
|
|
|
114
|
-
await
|
|
204
|
+
const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
|
|
205
|
+
if (twoFactorMethods.length > 0)
|
|
206
|
+
return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
|
|
207
|
+
|
|
115
208
|
const pub = toPublicUser(userRecord)
|
|
116
|
-
sessions.
|
|
209
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
117
210
|
if (wantsJson(ctx.request))
|
|
118
211
|
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
119
212
|
return ctx.redirect(redirectTarget, 303)
|
|
120
213
|
})
|
|
121
214
|
}
|
|
122
215
|
|
|
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
216
|
authRoute('GET', '/session', {}, async (ctx) => {
|
|
135
217
|
const resolved = await sessions.resolve(ctx)
|
|
136
218
|
return ctx.json({
|
|
@@ -139,71 +221,27 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
139
221
|
})
|
|
140
222
|
})
|
|
141
223
|
|
|
142
|
-
authRoute('POST', '/signup', { limit: 'signup',
|
|
224
|
+
authRoute('POST', '/signup', { limit: 'signup', readBody: true }, async (ctx, body) => {
|
|
143
225
|
const email = normalizeEmail(body.email ?? '')
|
|
144
226
|
const password = body.password ?? ''
|
|
145
227
|
const name = body.name?.trim() || undefined
|
|
146
228
|
const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
|
|
147
229
|
|
|
148
230
|
if (!isValidEmail(email))
|
|
149
|
-
return respondAuthError(ctx, 400, '
|
|
231
|
+
return respondAuthError(ctx, 400, messages['signup.invalid-email'])
|
|
150
232
|
if (password.length < minPasswordLength)
|
|
151
|
-
return respondAuthError(ctx, 400,
|
|
152
|
-
|
|
153
|
-
|
|
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
|
-
}
|
|
233
|
+
return respondAuthError(ctx, 400, messages['signup.password-too-short'])
|
|
234
|
+
if (isPasswordTooLong(password, maxPasswordLength))
|
|
235
|
+
return respondAuthError(ctx, 400, messages['signup.password-too-long'])
|
|
197
236
|
|
|
198
|
-
|
|
199
|
-
|
|
237
|
+
if (requireEmailVerification)
|
|
238
|
+
return signUpPendingVerification(deps, ctx, { email, password, name, redirectTarget })
|
|
200
239
|
|
|
201
240
|
if (await sessions.observeAsync(store.getUserByEmail(email)))
|
|
202
|
-
return respondAuthError(ctx, 409, '
|
|
241
|
+
return respondAuthError(ctx, 409, messages['signup.email-taken'])
|
|
203
242
|
|
|
204
243
|
const user = await createUser({ email, password, name } as CreateUserInput<TUser>)
|
|
205
|
-
await sessions.createSessionForUser(user.id, ctx)
|
|
206
|
-
sessions.setResolvedUser(ctx, user)
|
|
244
|
+
await sessions.createSessionForUser(user.id, ctx, user)
|
|
207
245
|
|
|
208
246
|
if (wantsJson(ctx.request))
|
|
209
247
|
return ctx.json({ ok: true, user }, { status: 201 })
|
|
@@ -214,25 +252,41 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
214
252
|
consumeLinkRoute('verify-email', '/verify-email', 'verify-email', 'Invalid or expired verification link', async ({ user }) => {
|
|
215
253
|
if (!user)
|
|
216
254
|
return undefined
|
|
255
|
+
if (!user.emailVerified) {
|
|
256
|
+
await sessions.observeAsync(store.deleteUserSessions(user.id))
|
|
257
|
+
await sessions.observeAsync(store.deleteUserOAuthAccounts(user.id))
|
|
258
|
+
}
|
|
217
259
|
return (await sessions.observeAsync(store.updateUser(user.id, { emailVerified: true } as Partial<Omit<TUser, 'id' | 'createdAt'>>))) ?? { ...user, emailVerified: true }
|
|
218
260
|
})
|
|
219
261
|
|
|
220
|
-
authRoute('POST', '/signin', { limit: 'signin',
|
|
262
|
+
authRoute('POST', '/signin', { limit: 'signin', readBody: true }, async (ctx, body) => {
|
|
221
263
|
const email = normalizeEmail(body.email ?? '')
|
|
222
264
|
const password = body.password ?? ''
|
|
223
265
|
const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
|
|
224
266
|
|
|
267
|
+
if (isPasswordTooLong(password, maxPasswordLength))
|
|
268
|
+
return respondAuthError(ctx, 400, messages['signin.password-too-long'])
|
|
269
|
+
|
|
270
|
+
const locked = limits.refuseLockedAccount(ctx, email)
|
|
271
|
+
if (locked)
|
|
272
|
+
return locked
|
|
273
|
+
|
|
225
274
|
const userRecord = email ? await sessions.observeAsync(store.getUserByEmail(email)) : undefined
|
|
226
275
|
const valid = await verifyPassword(password, userRecord?.passwordHash)
|
|
227
|
-
if (!userRecord || !valid)
|
|
228
|
-
|
|
276
|
+
if (!userRecord || !valid) {
|
|
277
|
+
limits.countFailedSignin(email)
|
|
278
|
+
return respondAuthError(ctx, 401, messages['signin.invalid-credentials'])
|
|
279
|
+
}
|
|
229
280
|
|
|
230
281
|
if (requireEmailVerification && !userRecord.emailVerified)
|
|
231
|
-
return respondAuthError(ctx, 403, '
|
|
282
|
+
return respondAuthError(ctx, 403, messages['signin.email-not-verified'])
|
|
283
|
+
|
|
284
|
+
const twoFactorMethods = await totp.getTwoFactorMethods(userRecord.id)
|
|
285
|
+
if (twoFactorMethods.length > 0)
|
|
286
|
+
return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirectTarget, twoFactorRedirect, twoFactorMethods)
|
|
232
287
|
|
|
233
|
-
await sessions.createSessionForUser(userRecord.id, ctx)
|
|
234
288
|
const pub = toPublicUser(userRecord)
|
|
235
|
-
sessions.
|
|
289
|
+
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
236
290
|
|
|
237
291
|
if (wantsJson(ctx.request))
|
|
238
292
|
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
@@ -240,13 +294,14 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
240
294
|
})
|
|
241
295
|
|
|
242
296
|
authRoute('POST', '/signout', {}, async (ctx) => {
|
|
297
|
+
totp.clearPendingCookie(ctx)
|
|
243
298
|
await sessions.signOut(ctx)
|
|
244
299
|
if (wantsJson(ctx.request))
|
|
245
300
|
return ctx.json({ ok: true })
|
|
246
301
|
return ctx.redirect(safeRedirect(ctx.url.searchParams.get('redirect'), defaultRedirect), 303)
|
|
247
302
|
})
|
|
248
303
|
|
|
249
|
-
authRoute('POST', '/magic-link', { limit: 'magic',
|
|
304
|
+
authRoute('POST', '/magic-link', { limit: 'magic', readBody: true }, async (ctx, body) => {
|
|
250
305
|
const email = normalizeEmail(body.email ?? '')
|
|
251
306
|
if (!isValidEmail(email))
|
|
252
307
|
return fail(ctx, 400, 'Please enter a valid email address')
|
|
@@ -256,6 +311,9 @@ export function registerAuthRoutes<TUser extends AuthUser = AuthUser>(deps: Auth
|
|
|
256
311
|
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
312
|
return fail(ctx, 500, 'Sign-in links are not configured')
|
|
258
313
|
}
|
|
314
|
+
const limited = limits.limitMail(ctx, email)
|
|
315
|
+
if (limited)
|
|
316
|
+
return limited
|
|
259
317
|
await sendMagicLink(email, linkOrigin, body.redirect ?? body.next)
|
|
260
318
|
return ctx.json({ ok: true, message: 'If that address can sign in, a link has been sent.' })
|
|
261
319
|
})
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// The session cookie's name and lifetime: `__Host-` prefixed over https, with opt-in migration from the plain name.
|
|
2
|
+
|
|
3
|
+
import type { RequestContext } from 'prunelle/server'
|
|
4
|
+
import { authCookie } from './http'
|
|
5
|
+
|
|
6
|
+
const HOST_PREFIX = '__Host-'
|
|
7
|
+
const SECURE_PREFIX = '__Secure-'
|
|
8
|
+
|
|
9
|
+
export interface SessionCookie {
|
|
10
|
+
/** The session token the request carries, under the https name (or plain name when `acceptLegacyCookie` is enabled). */
|
|
11
|
+
read: (ctx: RequestContext) => string | undefined
|
|
12
|
+
/** Sets the cookie to expire with the session, and drops the plain name when migrating a legacy cookie. */
|
|
13
|
+
set: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
|
|
14
|
+
/** Sets the cookie under its https name when the request carried the plain one. */
|
|
15
|
+
moveLegacy: (ctx: RequestContext, rawToken: string, expiresAt: number) => void
|
|
16
|
+
clear: (ctx: RequestContext) => void
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createSessionCookie(
|
|
20
|
+
cookieName: string,
|
|
21
|
+
isSecureCookie: (ctx: RequestContext) => boolean,
|
|
22
|
+
acceptLegacyCookie = false,
|
|
23
|
+
): SessionCookie {
|
|
24
|
+
// Contexts whose session came in under the plain name over https.
|
|
25
|
+
const legacy = new WeakSet<object>()
|
|
26
|
+
// A name that starts with `__` carries its own prefix rules and is used as given.
|
|
27
|
+
const hostName = cookieName.startsWith('__') ? undefined : `${HOST_PREFIX}${cookieName}`
|
|
28
|
+
const requiresSecure = cookieName.startsWith(HOST_PREFIX) || cookieName.startsWith(SECURE_PREFIX)
|
|
29
|
+
const currentName = (ctx: RequestContext): string => hostName !== undefined && isSecureCookie(ctx) ? hostName : cookieName
|
|
30
|
+
|
|
31
|
+
const set: SessionCookie['set'] = (ctx, rawToken, expiresAt) => {
|
|
32
|
+
const name = currentName(ctx)
|
|
33
|
+
ctx.cookies.set(name, rawToken, authCookie(requiresSecure || isSecureCookie(ctx), Math.max(0, Math.floor((expiresAt - Date.now()) / 1000))))
|
|
34
|
+
legacy.delete(ctx.locals)
|
|
35
|
+
if (name !== cookieName && acceptLegacyCookie)
|
|
36
|
+
ctx.cookies.delete(cookieName, { path: '/' })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
read(ctx) {
|
|
41
|
+
const name = currentName(ctx)
|
|
42
|
+
const token = ctx.cookies.get(name)
|
|
43
|
+
if (token !== undefined || name === cookieName || !acceptLegacyCookie)
|
|
44
|
+
return token
|
|
45
|
+
const old = ctx.cookies.get(cookieName)
|
|
46
|
+
if (old)
|
|
47
|
+
legacy.add(ctx.locals)
|
|
48
|
+
return old
|
|
49
|
+
},
|
|
50
|
+
set,
|
|
51
|
+
moveLegacy(ctx, rawToken, expiresAt) {
|
|
52
|
+
if (legacy.has(ctx.locals))
|
|
53
|
+
set(ctx, rawToken, expiresAt)
|
|
54
|
+
},
|
|
55
|
+
clear(ctx) {
|
|
56
|
+
if (hostName === undefined || !isSecureCookie(ctx) || acceptLegacyCookie)
|
|
57
|
+
ctx.cookies.delete(cookieName, requiresSecure ? { path: '/', secure: true } : { path: '/' })
|
|
58
|
+
if (hostName !== undefined && isSecureCookie(ctx))
|
|
59
|
+
ctx.cookies.delete(hostName, { path: '/', secure: true })
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
}
|