forked from MasterKale/SimpleWebAuthn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
334 lines (287 loc) · 9.46 KB
/
index.ts
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
* An example Express server showing off a simple integration of @simplewebauthn/server.
*
* The webpages served from ./public use @simplewebauthn/browser.
*/
import https from 'https';
import http from 'http';
import fs from 'fs';
import express from 'express';
import session from 'express-session';
import memoryStore from 'memorystore';
import dotenv from 'dotenv';
dotenv.config();
import {
// Authentication
generateAuthenticationOptions,
// Registration
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from '@simplewebauthn/server';
import { isoBase64URL, isoUint8Array } from '@simplewebauthn/server/helpers';
import type {
GenerateAuthenticationOptionsOpts,
GenerateRegistrationOptionsOpts,
VerifiedAuthenticationResponse,
VerifiedRegistrationResponse,
VerifyAuthenticationResponseOpts,
VerifyRegistrationResponseOpts,
} from '@simplewebauthn/server';
import type {
AuthenticationResponseJSON,
AuthenticatorDevice,
RegistrationResponseJSON,
} from '@simplewebauthn/typescript-types';
import { LoggedInUser } from './example-server';
const app = express();
const MemoryStore = memoryStore(session);
const {
ENABLE_CONFORMANCE,
ENABLE_HTTPS,
RP_ID = 'localhost',
} = process.env;
app.use(express.static('./public/'));
app.use(express.json());
app.use(
session({
secret: 'secret123',
saveUninitialized: true,
resave: false,
cookie: {
maxAge: 86400000,
httpOnly: true, // Ensure to not expose session cookies to clientside scripts
},
store: new MemoryStore({
checkPeriod: 86_400_000, // prune expired entries every 24h
}),
}),
);
/**
* If the words "metadata statements" mean anything to you, you'll want to enable this route. It
* contains an example of a more complex deployment of SimpleWebAuthn with support enabled for the
* FIDO Metadata Service. This enables greater control over the types of authenticators that can
* interact with the Rely Party (a.k.a. "RP", a.k.a. "this server").
*/
if (ENABLE_CONFORMANCE === 'true') {
import('./fido-conformance').then(
({ fidoRouteSuffix, fidoConformanceRouter }) => {
app.use(fidoRouteSuffix, fidoConformanceRouter);
},
);
}
/**
* RP ID represents the "scope" of websites on which a authenticator should be usable. The Origin
* represents the expected URL from which registration or authentication occurs.
*/
export const rpID = RP_ID;
// This value is set at the bottom of page as part of server initialization (the empty string is
// to appease TypeScript until we determine the expected origin based on whether or not HTTPS
// support is enabled)
export let expectedOrigin = '';
/**
* 2FA and Passwordless WebAuthn flows expect you to be able to uniquely identify the user that
* performs registration or authentication. The user ID you specify here should be your internal,
* _unique_ ID for that user (uuid, etc...). Avoid using identifying information here, like email
* addresses, as it may be stored within the authenticator.
*
* Here, the example server assumes the following user has completed login:
*/
const loggedInUserId = 'internalUserId';
const inMemoryUserDeviceDB: { [loggedInUserId: string]: LoggedInUser } = {
[loggedInUserId]: {
id: loggedInUserId,
username: `user@${rpID}`,
devices: [],
},
};
/**
* Registration (a.k.a. "Registration")
*/
app.get('/generate-registration-options', async (req, res) => {
const user = inMemoryUserDeviceDB[loggedInUserId];
const {
/**
* The username can be a human-readable name, email, etc... as it is intended only for display.
*/
username,
devices,
} = user;
const opts: GenerateRegistrationOptionsOpts = {
rpName: 'SimpleWebAuthn Example',
rpID,
userID: loggedInUserId,
userName: username,
timeout: 60000,
attestationType: 'none',
/**
* Passing in a user's list of already-registered authenticator IDs here prevents users from
* registering the same device multiple times. The authenticator will simply throw an error in
* the browser if it's asked to perform registration when one of these ID's already resides
* on it.
*/
excludeCredentials: devices.map((dev) => ({
id: dev.credentialID,
type: 'public-key',
transports: dev.transports,
})),
authenticatorSelection: {
residentKey: 'discouraged',
/**
* Wondering why user verification isn't required? See here:
*
* https://passkeys.dev/docs/use-cases/bootstrapping/#a-note-about-user-verification
*/
userVerification: 'preferred',
},
/**
* Support the two most common algorithms: ES256, and RS256
*/
supportedAlgorithmIDs: [-7, -257],
};
const options = await generateRegistrationOptions(opts);
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
req.session.currentChallenge = options.challenge;
res.send(options);
});
app.post('/verify-registration', async (req, res) => {
const body: RegistrationResponseJSON = req.body;
const user = inMemoryUserDeviceDB[loggedInUserId];
const expectedChallenge = req.session.currentChallenge;
let verification: VerifiedRegistrationResponse;
try {
const opts: VerifyRegistrationResponseOpts = {
response: body,
expectedChallenge: `${expectedChallenge}`,
expectedOrigin,
expectedRPID: rpID,
requireUserVerification: false,
};
verification = await verifyRegistrationResponse(opts);
} catch (error) {
const _error = error as Error;
console.error(_error);
return res.status(400).send({ error: _error.message });
}
const { verified, registrationInfo } = verification;
if (verified && registrationInfo) {
const { credentialPublicKey, credentialID, counter } = registrationInfo;
const existingDevice = user.devices.find((device) =>
isoUint8Array.areEqual(device.credentialID, credentialID)
);
if (!existingDevice) {
/**
* Add the returned device to the user's list of devices
*/
const newDevice: AuthenticatorDevice = {
credentialPublicKey,
credentialID,
counter,
transports: body.response.transports,
};
user.devices.push(newDevice);
}
}
req.session.currentChallenge = undefined;
res.send({ verified });
});
/**
* Login (a.k.a. "Authentication")
*/
app.get('/generate-authentication-options', async (req, res) => {
// You need to know the user by this point
const user = inMemoryUserDeviceDB[loggedInUserId];
const opts: GenerateAuthenticationOptionsOpts = {
timeout: 60000,
allowCredentials: user.devices.map((dev) => ({
id: dev.credentialID,
type: 'public-key',
transports: dev.transports,
})),
/**
* Wondering why user verification isn't required? See here:
*
* https://passkeys.dev/docs/use-cases/bootstrapping/#a-note-about-user-verification
*/
userVerification: 'preferred',
rpID,
};
const options = await generateAuthenticationOptions(opts);
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
req.session.currentChallenge = options.challenge;
res.send(options);
});
app.post('/verify-authentication', async (req, res) => {
const body: AuthenticationResponseJSON = req.body;
const user = inMemoryUserDeviceDB[loggedInUserId];
const expectedChallenge = req.session.currentChallenge;
let dbAuthenticator;
const bodyCredIDBuffer = isoBase64URL.toBuffer(body.rawId);
// "Query the DB" here for an authenticator matching `credentialID`
for (const dev of user.devices) {
if (isoUint8Array.areEqual(dev.credentialID, bodyCredIDBuffer)) {
dbAuthenticator = dev;
break;
}
}
if (!dbAuthenticator) {
return res.status(400).send({
error: 'Authenticator is not registered with this site',
});
}
let verification: VerifiedAuthenticationResponse;
try {
const opts: VerifyAuthenticationResponseOpts = {
response: body,
expectedChallenge: `${expectedChallenge}`,
expectedOrigin,
expectedRPID: rpID,
authenticator: dbAuthenticator,
requireUserVerification: false,
};
verification = await verifyAuthenticationResponse(opts);
} catch (error) {
const _error = error as Error;
console.error(_error);
return res.status(400).send({ error: _error.message });
}
const { verified, authenticationInfo } = verification;
if (verified) {
// Update the authenticator's counter in the DB to the newest count in the authentication
dbAuthenticator.counter = authenticationInfo.newCounter;
}
req.session.currentChallenge = undefined;
res.send({ verified });
});
if (ENABLE_HTTPS) {
const host = '0.0.0.0';
const port = 443;
expectedOrigin = `https://${rpID}`;
https
.createServer(
{
/**
* See the README on how to generate this SSL cert and key pair using mkcert
*/
key: fs.readFileSync(`./${rpID}.key`),
cert: fs.readFileSync(`./${rpID}.crt`),
},
app,
)
.listen(port, host, () => {
console.log(`🚀 Server ready at ${expectedOrigin} (${host}:${port})`);
});
} else {
const host = '127.0.0.1';
const port = 8000;
expectedOrigin = `http://localhost:${port}`;
http.createServer(app).listen(port, host, () => {
console.log(`🚀 Server ready at ${expectedOrigin} (${host}:${port})`);
});
}