1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
import { and, eq, lt } from "drizzle-orm";
import {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
} from "@simplewebauthn/server";
import type {
RegistrationResponseJSON,
AuthenticationResponseJSON,
} from "@simplewebauthn/server";
import { db } from "../db";
import { webauthnChallenges, userPasskeys } from "../db/schema";
import { config } from "./config";
const CHALLENGE_TTL_MS = 5 * 60 * 1000;
function newSessionKey(): string {
const bytes = crypto.getRandomValues(new Uint8Array(24));
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
async function gcExpiredChallenges(): Promise<void> {
try {
await db
.delete(webauthnChallenges)
.where(lt(webauthnChallenges.expiresAt, new Date()));
} catch {
}
}
export async function startRegistration(opts: {
userId: string;
userName: string;
userDisplayName?: string;
excludeCredentialIds?: string[];
}) {
await gcExpiredChallenges();
const options = await generateRegistrationOptions({
rpName: config.webauthnRpName,
rpID: config.webauthnRpId,
userName: opts.userName,
userDisplayName: opts.userDisplayName || opts.userName,
userID: new TextEncoder().encode(opts.userId),
attestationType: "none",
excludeCredentials: (opts.excludeCredentialIds || []).map((id) => ({
id,
})),
authenticatorSelection: {
residentKey: "preferred",
userVerification: "preferred",
},
});
const sessionKey = newSessionKey();
await db.insert(webauthnChallenges).values({
userId: opts.userId,
sessionKey,
challenge: options.challenge,
kind: "register",
expiresAt: new Date(Date.now() + CHALLENGE_TTL_MS),
});
return { options, sessionKey };
}
export async function finishRegistration(opts: {
sessionKey: string;
response: RegistrationResponseJSON;
}): Promise<
| { ok: true; credentialId: string; publicKey: string; counter: number }
| { ok: false; error: string }
> {
try {
const [chal] = await db
.select()
.from(webauthnChallenges)
.where(
and(
eq(webauthnChallenges.sessionKey, opts.sessionKey),
eq(webauthnChallenges.kind, "register")
)
)
.limit(1);
if (!chal) return { ok: false, error: "Challenge not found or expired" };
if (new Date(chal.expiresAt) < new Date()) {
return { ok: false, error: "Challenge expired" };
}
const verification = await verifyRegistrationResponse({
response: opts.response,
expectedChallenge: chal.challenge,
expectedOrigin: config.webauthnOrigin,
expectedRPID: config.webauthnRpId,
requireUserVerification: false,
});
await db
.delete(webauthnChallenges)
.where(eq(webauthnChallenges.sessionKey, opts.sessionKey));
if (!verification.verified || !verification.registrationInfo) {
return { ok: false, error: "Registration did not verify" };
}
const { credential } = verification.registrationInfo;
return {
ok: true,
credentialId: credential.id,
publicKey: Buffer.from(credential.publicKey).toString("base64url"),
counter: credential.counter,
};
} catch (err) {
console.error("[webauthn] finishRegistration:", err);
return { ok: false, error: "Verification failed" };
}
}
export async function startAuthentication(opts: {
userId?: string;
allowCredentialIds?: string[];
}) {
await gcExpiredChallenges();
const options = await generateAuthenticationOptions({
rpID: config.webauthnRpId,
allowCredentials: (opts.allowCredentialIds || []).map((id) => ({ id })),
userVerification: "preferred",
});
const sessionKey = newSessionKey();
await db.insert(webauthnChallenges).values({
userId: opts.userId || null,
sessionKey,
challenge: options.challenge,
kind: "authenticate",
expiresAt: new Date(Date.now() + CHALLENGE_TTL_MS),
});
return { options, sessionKey };
}
export async function finishAuthentication(opts: {
sessionKey: string;
response: AuthenticationResponseJSON;
}): Promise<
| {
ok: true;
userId: string;
credentialId: string;
newCounter: number;
}
| { ok: false; error: string }
> {
try {
const [chal] = await db
.select()
.from(webauthnChallenges)
.where(
and(
eq(webauthnChallenges.sessionKey, opts.sessionKey),
eq(webauthnChallenges.kind, "authenticate")
)
)
.limit(1);
if (!chal) return { ok: false, error: "Challenge not found or expired" };
if (new Date(chal.expiresAt) < new Date()) {
return { ok: false, error: "Challenge expired" };
}
const credentialId = opts.response.id;
const [pk] = await db
.select()
.from(userPasskeys)
.where(eq(userPasskeys.credentialId, credentialId))
.limit(1);
if (!pk) {
return { ok: false, error: "Unknown credential" };
}
const verification = await verifyAuthenticationResponse({
response: opts.response,
expectedChallenge: chal.challenge,
expectedOrigin: config.webauthnOrigin,
expectedRPID: config.webauthnRpId,
credential: {
id: pk.credentialId,
publicKey: new Uint8Array(Buffer.from(pk.publicKey, "base64url")),
counter: pk.counter,
},
requireUserVerification: false,
});
await db
.delete(webauthnChallenges)
.where(eq(webauthnChallenges.sessionKey, opts.sessionKey));
if (!verification.verified) {
return { ok: false, error: "Authentication did not verify" };
}
const newCounter = verification.authenticationInfo.newCounter;
await db
.update(userPasskeys)
.set({ counter: newCounter, lastUsedAt: new Date() })
.where(eq(userPasskeys.id, pk.id));
return {
ok: true,
userId: pk.userId,
credentialId: pk.credentialId,
newCounter,
};
} catch (err) {
console.error("[webauthn] finishAuthentication:", err);
return { ok: false, error: "Verification failed" };
}
}
|