-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
324 lines (290 loc) · 9.81 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
/* eslint-disable @typescript-eslint/no-var-requires */
/**
* An example Express server showing off a simple integration of @simplewebauthn/server.
*
* The webpages served from ./public use @simplewebauthn/browser.
*/
import type {
GenerateAuthenticationOptionsOpts,
GenerateRegistrationOptionsOpts,
VerifiedAuthenticationResponse,
VerifiedRegistrationResponse,
VerifyAuthenticationResponseOpts,
VerifyRegistrationResponseOpts,
} from '@simplewebauthn/server';
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from '@simplewebauthn/server';
import { LoggedInUser } from './example-server';
import base64url from 'base64url';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import fs from 'fs';
import http from 'http';
import https from 'https';
import { isoUint8Array } from '@simplewebauthn/server/helpers';
import memoryStore from 'memorystore';
import session from 'express-session';
dotenv.config();
const app = express();
const MemoryStore = memoryStore(session);
const { ENABLE_CONFORMANCE, ENABLE_HTTPS, RP_ID = 'localhost' } = process.env; // Change RP_ID according to environment
app.use(cors());
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 const expectedOrigin = 'http://localhost:3000'; //// Change expectedOrigin according to environment
/**
* 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: `CREDEBL@${rpID}`,
devices: [],
},
};
/**
* Registration (a.k.a. "Registration")
*/
app.get('/generate-registration-options', async (req, res) => {
const user = inMemoryUserDeviceDB[loggedInUserId];
let userName = req.query.userName;
if (typeof userName !== 'string') {
throw new Error("Username is not string")
}
let {
/**
* The username can be a human-readable name, email, etc... as it is intended only for display.
*/
devices,
} = user;
devices = [];
const opts: GenerateRegistrationOptionsOpts = {
rpName: 'SimpleWebAuthn Example',
rpID,
userID: userName,
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',
},
/**
* 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 = (await options).challenge;
res.send(options);
});
app.post('/verify-registration', async (req, res) => {
const { challangeId, ...rest } = req?.body;
const body = rest;
const user = inMemoryUserDeviceDB[loggedInUserId];
const expectedChallenge = challangeId;
let verification: VerifiedRegistrationResponse;
try {
const opts: VerifyRegistrationResponseOpts = {
response: body,
expectedChallenge: `${expectedChallenge}`,
expectedOrigin,
requireUserVerification: true,
};
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;
let newDevice: any = {};
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
*/
newDevice = {
credentialPublicKey,
credentialID,
counter,
transports: body.response.transports,
};
user.devices.push(newDevice);
}
}
req.session.currentChallenge = undefined;
const pubKey = Buffer.from(newDevice.credentialPublicKey).toString('base64');
const credID = Buffer.from(newDevice.credentialID).toString('base64');
newDevice = {
credentialPublicKey: pubKey,
credentialID: credID,
counter: newDevice.counter,
transports: body.response.transports,
};
res.send({ verified, newDevice });
});
/**
* Login (a.k.a. "Authentication")
*/
app.post('/generate-authentication-options', async (req, res) => {
let allowCredential = [];
for (const credentialId of req.body) {
let credentialID = new Uint8Array(Buffer.from(credentialId as any, 'base64'));;
allowCredential.push({
id: credentialID,
type: 'public-key',
transports: [],
})
}
const opts: GenerateAuthenticationOptionsOpts = {
timeout: 60000,
allowCredentials: [],
userVerification: 'required',
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 = (await options).challenge;
res.send(options);
});
app.post('/verify-authentication', async (req, res) => {
const { challangeId, ...rest } = JSON.parse(req?.body?.verifyAuthenticationDetails);
const body = rest;
const expectedChallenge = challangeId;
let dbAuthenticator = {
credentialPublicKey: new Uint8Array(),
credentialID: new Uint8Array(),
counter: 0,
transports: [],
};
req?.body?.devices.map((cred: any) => {
const bodyCredIDBuffer = base64url.toBuffer(body.rawId);
const credId = new Uint8Array(Buffer.from(cred.credentialId, 'base64'));
const result = isoUint8Array.areEqual(credId, bodyCredIDBuffer);
const pubKey = new Uint8Array(Buffer.from(cred?.devices?.credentialPublicKey, 'base64'),
);
if (result) {
dbAuthenticator = {
counter: cred?.devices?.counter,
transports: cred?.devices?.transports,
credentialID: credId,
credentialPublicKey: pubKey
}
}
})
let verification: VerifiedAuthenticationResponse;
try {
const opts: VerifyAuthenticationResponseOpts = {
response: body,
expectedChallenge: `${expectedChallenge}`,
expectedOrigin,
expectedRPID: rpID,
authenticator: dbAuthenticator,
requireUserVerification: true,
};
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;
const 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 = '0.0.0.0';
const port = 8000;
const expectedOrigin = `http://localhost:${port}`;
http.createServer(app).listen(port, host, () => {
console.log(`🚀 Server ready at ${expectedOrigin} (${host}:${port})`);
});
}