@prunellejs/auth 0.6.0 → 0.7.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.
- package/LICENSE +21 -0
- package/llms.txt +17 -11
- package/package.json +2 -2
- package/src/account.ts +101 -0
- package/src/form-messages.ts +58 -0
- package/src/http.ts +75 -29
- package/src/index.ts +124 -55
- package/src/links.ts +67 -39
- package/src/oauth-routes.ts +29 -24
- package/src/org-routes.ts +15 -5
- package/src/orgs.ts +17 -0
- package/src/passkey-client.ts +8 -4
- package/src/passkey-routes.ts +12 -2
- package/src/passkeys.ts +11 -14
- package/src/routes.ts +125 -92
- package/src/session-cookie.ts +62 -0
- package/src/session.ts +46 -42
- package/src/sqlite-ext.ts +6 -1
- package/src/sqlite.ts +97 -38
- package/src/store-ext.ts +9 -0
- package/src/store.ts +48 -19
- package/src/totp-routes.ts +11 -5
- package/src/totp.ts +99 -42
package/src/oauth-routes.ts
CHANGED
|
@@ -4,10 +4,12 @@ import type { RequestContext } from 'prunelle/server'
|
|
|
4
4
|
import { safeEqual, safeRedirect } from 'prunelle/server'
|
|
5
5
|
import type { OAuthProfile, OAuthProvider } from './oauth'
|
|
6
6
|
import type { AuthStore, AuthUser, PublicUser } from './store'
|
|
7
|
+
import type { TotpManager } from './totp'
|
|
7
8
|
import { pkceChallenge, randomToken, signPayload, verifyPayload } from './crypto'
|
|
8
|
-
import { fail, withNoStore } from './http'
|
|
9
|
+
import { authCookie, fail, withNoStore } from './http'
|
|
9
10
|
import { OAUTH_FETCH_TIMEOUT_MS } from './oauth'
|
|
10
11
|
import { normalizeEmail, toPublicUser } from './store'
|
|
12
|
+
import { respondTwoFactorChallenge } from './totp'
|
|
11
13
|
|
|
12
14
|
interface OAuthStateCookie {
|
|
13
15
|
provider: string
|
|
@@ -21,7 +23,8 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
|
|
|
21
23
|
route: (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>) => void
|
|
22
24
|
store: AuthStore<TUser>
|
|
23
25
|
providers: ReadonlyMap<string, OAuthProvider>
|
|
24
|
-
secret
|
|
26
|
+
/** The app's signing secret, resolved at first use. */
|
|
27
|
+
secret: () => string
|
|
25
28
|
site: string | undefined
|
|
26
29
|
basePath: string
|
|
27
30
|
stateCookieName: string
|
|
@@ -34,10 +37,24 @@ export interface OAuthRouteDeps<TUser extends AuthUser = AuthUser> {
|
|
|
34
37
|
isSecureCookie: (ctx: RequestContext) => boolean
|
|
35
38
|
claimUnverified: (user: TUser) => Promise<TUser>
|
|
36
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
|
|
37
44
|
createSessionForUser: (userId: string, ctx: RequestContext, knownUser?: PublicUser<TUser>) => Promise<unknown>
|
|
38
45
|
observeAsync: <T>(value: T | Promise<T>) => T | Promise<T>
|
|
39
46
|
}
|
|
40
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
|
+
|
|
41
58
|
async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
|
|
42
59
|
deps: OAuthRouteDeps<TUser>,
|
|
43
60
|
ctx: RequestContext,
|
|
@@ -49,12 +66,7 @@ async function handleUnverifiedOAuthSignup<TUser extends AuthUser>(
|
|
|
49
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`)
|
|
50
67
|
return fail(ctx, 500, 'Verification links are not configured')
|
|
51
68
|
}
|
|
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>)
|
|
69
|
+
const created = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: false } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
58
70
|
try {
|
|
59
71
|
await deps.issueLink('verify-email', created.id, created.email, linkOrigin, redirectTarget)
|
|
60
72
|
}
|
|
@@ -108,12 +120,7 @@ async function resolveOAuthUser<TUser extends AuthUser>(
|
|
|
108
120
|
else if (!byEmail) {
|
|
109
121
|
if (requireEmailVerification && !profile.emailVerified)
|
|
110
122
|
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>)
|
|
123
|
+
userRecord = await deps.insertUser({ ...profileFields(deps, profile), email: profile.email, emailVerified: profile.emailVerified } as Pick<AuthUser, 'email' | 'emailVerified'> & Partial<TUser>)
|
|
117
124
|
}
|
|
118
125
|
else {
|
|
119
126
|
return fail(ctx, 409, 'An account with this email already exists; verify email to link')
|
|
@@ -150,7 +157,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
150
157
|
const verifier = provider.pkce !== false ? randomToken(32) : undefined
|
|
151
158
|
const redirectTarget = safeRedirect(ctx.url.searchParams.get('redirect') ?? ctx.url.searchParams.get('next'), defaultRedirect)
|
|
152
159
|
|
|
153
|
-
const cookieVal = signPayload(secret, {
|
|
160
|
+
const cookieVal = signPayload(secret(), {
|
|
154
161
|
provider: provider.id,
|
|
155
162
|
state,
|
|
156
163
|
verifier,
|
|
@@ -158,13 +165,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
158
165
|
exp: Date.now() + 10 * 60 * 1000,
|
|
159
166
|
} satisfies OAuthStateCookie)
|
|
160
167
|
|
|
161
|
-
ctx.cookies.set(stateCookieName, cookieVal,
|
|
162
|
-
path: '/',
|
|
163
|
-
httpOnly: true,
|
|
164
|
-
sameSite: 'lax',
|
|
165
|
-
secure: deps.isSecureCookie(ctx),
|
|
166
|
-
maxAge: 600,
|
|
167
|
-
})
|
|
168
|
+
ctx.cookies.set(stateCookieName, cookieVal, authCookie(deps.isSecureCookie(ctx), 600))
|
|
168
169
|
|
|
169
170
|
const callbackUrl = callbackUrlFor(ctx, provider)
|
|
170
171
|
const authUrl = new URL(provider.authorizeUrl)
|
|
@@ -177,7 +178,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
177
178
|
authUrl.searchParams.set('code_challenge', pkceChallenge(verifier))
|
|
178
179
|
authUrl.searchParams.set('code_challenge_method', 'S256')
|
|
179
180
|
}
|
|
180
|
-
return ctx.redirect(authUrl.toString(), 302)
|
|
181
|
+
return ctx.redirect(authUrl.toString(), 302, { external: true })
|
|
181
182
|
})
|
|
182
183
|
|
|
183
184
|
noStoreRoute('GET', `${basePath}/oauth/:provider/callback`, async (ctx) => {
|
|
@@ -197,7 +198,7 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
197
198
|
if (!code || !returnedState || !rawCookie)
|
|
198
199
|
return fail(ctx, 400, 'Invalid OAuth callback parameters')
|
|
199
200
|
|
|
200
|
-
const saved = verifyPayload<OAuthStateCookie>(secret, rawCookie)
|
|
201
|
+
const saved = verifyPayload<OAuthStateCookie>(secret(), rawCookie)
|
|
201
202
|
if (!saved || saved.exp <= Date.now() || saved.provider !== provider.id || !safeEqual(saved.state, returnedState))
|
|
202
203
|
return fail(ctx, 400, 'Invalid or expired OAuth state')
|
|
203
204
|
|
|
@@ -249,6 +250,10 @@ export function registerOAuthRoutes<TUser extends AuthUser = AuthUser>(deps: OAu
|
|
|
249
250
|
if (resolved instanceof Response)
|
|
250
251
|
return resolved
|
|
251
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
|
+
|
|
252
257
|
await deps.createSessionForUser(resolved.id, ctx, toPublicUser(resolved))
|
|
253
258
|
return ctx.redirect(redirectTarget, 302)
|
|
254
259
|
})
|
package/src/org-routes.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
// HTTP routes for organizations: create, invite, accept invitation, update member role, remove/leave member.
|
|
2
2
|
|
|
3
3
|
import type { RequestContext } from 'prunelle/server'
|
|
4
|
-
import type { AuthRouteRegistrar } from './http'
|
|
4
|
+
import type { AuthLimits, AuthRouteRegistrar } from './http'
|
|
5
5
|
import type { OrgError, OrgManager } from './orgs'
|
|
6
6
|
import type { SessionManager } from './session'
|
|
7
7
|
import type { AuthUser, Organization } from './store'
|
|
8
8
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
9
|
-
import { fail, linkConfirmPage } from './http'
|
|
9
|
+
import { fail, isValidEmail, linkConfirmPage } from './http'
|
|
10
|
+
import { normalizeEmail } from './store'
|
|
10
11
|
|
|
11
12
|
export interface OrgRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
12
13
|
authRoute: AuthRouteRegistrar
|
|
14
|
+
limits: AuthLimits
|
|
13
15
|
sessions: SessionManager<TUser>
|
|
14
16
|
orgs: OrgManager
|
|
15
17
|
defaultRedirect: string
|
|
@@ -107,7 +109,7 @@ function registerOrgMemberRoutes<TUser extends AuthUser>(
|
|
|
107
109
|
}
|
|
108
110
|
|
|
109
111
|
export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRoutesDeps<TUser>): void {
|
|
110
|
-
const { authRoute, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin } = deps
|
|
112
|
+
const { authRoute, limits, sessions, orgs, defaultRedirect, hasMailTransport, mailedLinkOrigin } = deps
|
|
111
113
|
|
|
112
114
|
async function resolveOrgParam(body: Record<string, string>): Promise<Organization | undefined> {
|
|
113
115
|
const ref = (body.orgId ?? body.org ?? body.slug ?? '').trim()
|
|
@@ -132,7 +134,7 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
|
|
|
132
134
|
}
|
|
133
135
|
})
|
|
134
136
|
|
|
135
|
-
authRoute('POST', '/orgs/invite', { limit: 'orgs-invite',
|
|
137
|
+
authRoute('POST', '/orgs/invite', { limit: 'orgs-invite', readBody: true }, async (ctx, body) => {
|
|
136
138
|
const resolved = await sessions.resolve(ctx)
|
|
137
139
|
if (!resolved)
|
|
138
140
|
return fail(ctx, 401, 'Authentication required')
|
|
@@ -149,16 +151,24 @@ export function registerOrgRoutes<TUser extends AuthUser = AuthUser>(deps: OrgRo
|
|
|
149
151
|
if (role === 'owner' && caller.role !== 'owner')
|
|
150
152
|
return fail(ctx, 403, 'Only organization owners can invite another owner')
|
|
151
153
|
|
|
154
|
+
const email = normalizeEmail(body.email ?? '')
|
|
155
|
+
if (!isValidEmail(email))
|
|
156
|
+
return fail(ctx, 400, 'prunelle: please enter a valid email address')
|
|
157
|
+
|
|
152
158
|
const linkOrigin = mailedLinkOrigin(ctx.url)
|
|
153
159
|
if (hasMailTransport && linkOrigin === undefined) {
|
|
154
160
|
console.error(`[prunelle/auth] refusing to mail an organization invite for host ${ctx.url.host}: set the auth \`site\` option to the public origin`)
|
|
155
161
|
return fail(ctx, 500, 'Invitation links are not configured')
|
|
156
162
|
}
|
|
157
163
|
|
|
164
|
+
const limited = limits.limitMail(ctx, email)
|
|
165
|
+
if (limited)
|
|
166
|
+
return limited
|
|
167
|
+
|
|
158
168
|
const redirectTarget = safeRedirect(body.redirect ?? body.next, defaultRedirect)
|
|
159
169
|
try {
|
|
160
170
|
const { invitation } = await orgs.inviteToOrg(org.id, {
|
|
161
|
-
email
|
|
171
|
+
email,
|
|
162
172
|
role,
|
|
163
173
|
invitedBy: resolved.user.id,
|
|
164
174
|
origin: linkOrigin,
|
package/src/orgs.ts
CHANGED
|
@@ -22,6 +22,23 @@ function orgError(status: number, message: string): OrgError {
|
|
|
22
22
|
return err
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
// The orgs a user's deletion takes with it, those they are the only member of; throws 409 when they are the last owner of an org others still belong to.
|
|
26
|
+
export async function orgsDeletedWithUser<TUser extends AuthUser>(store: AuthStore<TUser>, userId: string): Promise<string[]> {
|
|
27
|
+
if (!store.listUserOrgMemberships || !store.listOrgMembers)
|
|
28
|
+
return []
|
|
29
|
+
const deleted: string[] = []
|
|
30
|
+
for (const { org, role } of await store.listUserOrgMemberships(userId)) {
|
|
31
|
+
if (role !== 'owner')
|
|
32
|
+
continue
|
|
33
|
+
const members = await store.listOrgMembers(org.id)
|
|
34
|
+
if (members.length === 1)
|
|
35
|
+
deleted.push(org.id)
|
|
36
|
+
else if (members.filter(m => m.role === 'owner').length === 1)
|
|
37
|
+
throw orgError(409, `prunelle: this account is the last owner of "${org.name}": make another member owner, or delete the organization, before deleting the account`)
|
|
38
|
+
}
|
|
39
|
+
return deleted
|
|
40
|
+
}
|
|
41
|
+
|
|
25
42
|
export function slugifyOrgName(name: string): string {
|
|
26
43
|
return name
|
|
27
44
|
.normalize('NFKD')
|
package/src/passkey-client.ts
CHANGED
|
@@ -130,14 +130,18 @@ export async function registerPasskey(options: RegisterPasskeyOptions = {}): Pro
|
|
|
130
130
|
})
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
export type PasskeySignInResult =
|
|
134
|
+
| { ok: true, user: Record<string, unknown>, twoFactorRequired?: false | undefined }
|
|
135
|
+
| { ok: true, twoFactorRequired: true, methods: Array<'totp' | 'passkey'>, userId: string, user?: undefined }
|
|
136
|
+
|
|
137
|
+
async function runAssertion<T = { ok: true, user: Record<string, unknown> }>(
|
|
134
138
|
fetchImpl: typeof globalThis.fetch,
|
|
135
139
|
optionsUrl: string,
|
|
136
140
|
verifyUrl: string,
|
|
137
141
|
startBody: Record<string, unknown>,
|
|
138
142
|
extraVerify: Record<string, unknown>,
|
|
139
143
|
mediation?: CredentialMediationRequirement,
|
|
140
|
-
): Promise<
|
|
144
|
+
): Promise<T> {
|
|
141
145
|
if (!isPasskeySupported())
|
|
142
146
|
throw new Error('Passkeys are not supported in this browser')
|
|
143
147
|
|
|
@@ -181,10 +185,10 @@ async function runAssertion(
|
|
|
181
185
|
})
|
|
182
186
|
}
|
|
183
187
|
|
|
184
|
-
export async function signInWithPasskey(options: SignInWithPasskeyOptions = {}): Promise<
|
|
188
|
+
export async function signInWithPasskey(options: SignInWithPasskeyOptions = {}): Promise<PasskeySignInResult> {
|
|
185
189
|
const base = (options.basePath ?? '/auth').replace(/\/$/, '')
|
|
186
190
|
const fetchImpl = options.fetch ?? globalThis.fetch
|
|
187
|
-
return runAssertion(
|
|
191
|
+
return runAssertion<PasskeySignInResult>(
|
|
188
192
|
fetchImpl,
|
|
189
193
|
`${base}/passkeys/login/options`,
|
|
190
194
|
`${base}/passkeys/login/verify`,
|
package/src/passkey-routes.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { TotpManager } from './totp'
|
|
|
9
9
|
import { safeRedirect, wantsJson } from 'prunelle/server'
|
|
10
10
|
import { fail, parseJsonBody } from './http'
|
|
11
11
|
import { toPublicUser } from './store'
|
|
12
|
+
import { respondTwoFactorChallenge } from './totp'
|
|
12
13
|
|
|
13
14
|
export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
14
15
|
authRoute: AuthRouteRegistrar
|
|
@@ -16,6 +17,7 @@ export interface PasskeyRoutesDeps<TUser extends AuthUser = AuthUser> {
|
|
|
16
17
|
sessions: SessionManager<TUser>
|
|
17
18
|
passkeys: PasskeyManager
|
|
18
19
|
totp: TotpManager
|
|
20
|
+
twoFactorRedirect: string
|
|
19
21
|
defaultRedirect: string
|
|
20
22
|
requireEmailVerification: boolean
|
|
21
23
|
}
|
|
@@ -67,7 +69,7 @@ function asAssertionInput(body: Record<string, unknown>): AssertionVerifyInput |
|
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: PasskeyRoutesDeps<TUser>): void {
|
|
70
|
-
const { authRoute, store, sessions, passkeys, totp, defaultRedirect, requireEmailVerification } = deps
|
|
72
|
+
const { authRoute, store, sessions, passkeys, totp, twoFactorRedirect, defaultRedirect, requireEmailVerification } = deps
|
|
71
73
|
|
|
72
74
|
authRoute('POST', '/passkeys/register/options', { limit: 'passkey-reg' }, async (ctx) => {
|
|
73
75
|
const resolved = await sessions.resolve(ctx)
|
|
@@ -130,9 +132,13 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
130
132
|
if (requireEmailVerification && !userRecord.emailVerified)
|
|
131
133
|
return fail(ctx, 403, 'Email not verified')
|
|
132
134
|
|
|
135
|
+
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
|
|
136
|
+
const twoFactorMethods = (await totp.getTwoFactorMethods(userRecord.id)).filter(m => m !== 'passkey')
|
|
137
|
+
if (twoFactorMethods.length > 0)
|
|
138
|
+
return respondTwoFactorChallenge(totp, ctx, userRecord.id, redirect, twoFactorRedirect, twoFactorMethods)
|
|
139
|
+
|
|
133
140
|
const pub = toPublicUser(userRecord)
|
|
134
141
|
await sessions.createSessionForUser(userRecord.id, ctx, pub)
|
|
135
|
-
const redirect = safeRedirect(typeof raw.redirect === 'string' ? raw.redirect : (typeof raw.next === 'string' ? raw.next : undefined), defaultRedirect)
|
|
136
142
|
if (wantsJson(ctx.request))
|
|
137
143
|
return ctx.json({ ok: true, user: pub }, { status: 200 })
|
|
138
144
|
return ctx.redirect(redirect, 303)
|
|
@@ -146,6 +152,8 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
146
152
|
const pending = totp.readPendingCookie(ctx)
|
|
147
153
|
if (!pending)
|
|
148
154
|
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
155
|
+
if (!pending.methods.includes('passkey'))
|
|
156
|
+
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
149
157
|
try {
|
|
150
158
|
const options = await passkeys.createAssertionOptions(ctx, '2fa', { userId: pending.userId })
|
|
151
159
|
return ctx.json({ ok: true, options }, { status: 200 })
|
|
@@ -159,6 +167,8 @@ export function registerPasskeyRoutes<TUser extends AuthUser = AuthUser>(deps: P
|
|
|
159
167
|
const pending = totp.readPendingCookie(ctx)
|
|
160
168
|
if (!pending)
|
|
161
169
|
return fail(ctx, 401, 'Two-factor session expired or invalid')
|
|
170
|
+
if (!pending.methods.includes('passkey'))
|
|
171
|
+
return fail(ctx, 403, 'Passkey cannot be used as second factor for this sign-in')
|
|
162
172
|
const raw = await parseJsonBody(ctx)
|
|
163
173
|
if (raw instanceof Response)
|
|
164
174
|
return raw
|
package/src/passkeys.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { SessionManager } from './session'
|
|
|
5
5
|
import type { AuthStore, AuthUser, PasskeyRecord, PasskeySummary } from './store'
|
|
6
6
|
import { safeEqual } from 'prunelle/server'
|
|
7
7
|
import { fromBase64Url, randomToken, sha256Bytes, signPayload, toBase64Url, verifyPayload } from './crypto'
|
|
8
|
+
import { authCookie } from './http'
|
|
8
9
|
import { toPasskeySummary } from './store'
|
|
9
10
|
import { COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_ALG_RS256, coseKeyToJwk, decodeCbor, parseAuthenticatorData, verifyWebAuthnSignature } from './webauthn-crypto'
|
|
10
11
|
|
|
@@ -20,7 +21,7 @@ export interface PasskeyOptions {
|
|
|
20
21
|
rpName?: string | undefined
|
|
21
22
|
/** Expected WebAuthn origin (defaults to `site` or request origin). */
|
|
22
23
|
origin?: string | undefined
|
|
23
|
-
/** Authenticator user verification requirement (default: `'preferred'`). */
|
|
24
|
+
/** Authenticator user verification requirement (default: `'required'` for registration and passwordless login, `'preferred'` for 2FA). */
|
|
24
25
|
userVerification?: PasskeyUserVerification | undefined
|
|
25
26
|
}
|
|
26
27
|
|
|
@@ -72,7 +73,8 @@ export interface AssertionVerifyInput {
|
|
|
72
73
|
export interface PasskeyManagerDeps<TUser extends AuthUser = AuthUser> {
|
|
73
74
|
store: AuthStore<TUser>
|
|
74
75
|
sessions: SessionManager<TUser>
|
|
75
|
-
secret
|
|
76
|
+
/** The app's signing secret, resolved at first use. */
|
|
77
|
+
secret: () => string
|
|
76
78
|
challengeCookieName: string
|
|
77
79
|
getSite: () => string | undefined
|
|
78
80
|
options?: PasskeyOptions | undefined
|
|
@@ -260,7 +262,8 @@ async function performAssertionVerify<TUser extends AuthUser>(
|
|
|
260
262
|
|
|
261
263
|
export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: PasskeyManagerDeps<TUser>): PasskeyManager {
|
|
262
264
|
const { store, sessions, secret, challengeCookieName, getSite, options, isSecureCookie } = deps
|
|
263
|
-
const
|
|
265
|
+
const userVerificationFor = (purpose: 'register' | 'login' | '2fa'): PasskeyUserVerification =>
|
|
266
|
+
options?.userVerification ?? (purpose === '2fa' ? 'preferred' : 'required')
|
|
264
267
|
const activeChallenges = new Map<string, number>()
|
|
265
268
|
|
|
266
269
|
function resolveExpectedOrigin(ctx: RequestContext): string {
|
|
@@ -291,13 +294,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
291
294
|
...(userId !== undefined ? { userId } : {}),
|
|
292
295
|
exp,
|
|
293
296
|
}
|
|
294
|
-
ctx.cookies.set(challengeCookieName, signPayload(secret, payload),
|
|
295
|
-
path: '/',
|
|
296
|
-
httpOnly: true,
|
|
297
|
-
sameSite: 'lax',
|
|
298
|
-
secure: isSecureCookie(ctx),
|
|
299
|
-
maxAge: Math.floor(CHALLENGE_TTL_MS / 1000),
|
|
300
|
-
})
|
|
297
|
+
ctx.cookies.set(challengeCookieName, signPayload(secret(), payload), authCookie(isSecureCookie(ctx), Math.floor(CHALLENGE_TTL_MS / 1000)))
|
|
301
298
|
return challenge
|
|
302
299
|
}
|
|
303
300
|
|
|
@@ -306,7 +303,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
306
303
|
ctx.cookies.delete(challengeCookieName, { path: '/' })
|
|
307
304
|
if (!raw)
|
|
308
305
|
throw passkeyError(400, 'Missing passkey challenge')
|
|
309
|
-
const payload = verifyPayload<ChallengeCookiePayload>(secret, raw)
|
|
306
|
+
const payload = verifyPayload<ChallengeCookiePayload>(secret(), raw)
|
|
310
307
|
const now = Date.now()
|
|
311
308
|
if (!payload || payload.exp <= now || payload.purpose !== purpose)
|
|
312
309
|
throw passkeyError(400, 'Invalid or expired passkey challenge')
|
|
@@ -324,7 +321,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
324
321
|
expectedChallenge: consumeChallenge(ctx, purpose, expectedUserId),
|
|
325
322
|
expectedOrigin: resolveExpectedOrigin(ctx),
|
|
326
323
|
expectedRpId: resolveRpId(ctx),
|
|
327
|
-
userVerification,
|
|
324
|
+
userVerification: userVerificationFor(purpose),
|
|
328
325
|
}
|
|
329
326
|
}
|
|
330
327
|
|
|
@@ -354,7 +351,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
354
351
|
attestation: 'none',
|
|
355
352
|
authenticatorSelection: {
|
|
356
353
|
residentKey: 'preferred',
|
|
357
|
-
userVerification,
|
|
354
|
+
userVerification: userVerificationFor('register'),
|
|
358
355
|
},
|
|
359
356
|
excludeCredentials: existing.map(p => ({
|
|
360
357
|
type: 'public-key',
|
|
@@ -402,7 +399,7 @@ export function createPasskeyManager<TUser extends AuthUser = AuthUser>(deps: Pa
|
|
|
402
399
|
challenge,
|
|
403
400
|
timeout: CHALLENGE_TTL_MS,
|
|
404
401
|
rpId,
|
|
405
|
-
userVerification,
|
|
402
|
+
userVerification: userVerificationFor(purpose),
|
|
406
403
|
...(allowCredentials !== undefined ? { allowCredentials } : {}),
|
|
407
404
|
}
|
|
408
405
|
},
|