-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.ts
203 lines (183 loc) · 6.07 KB
/
example.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
/*eslint-env node */
import * as fs from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import mod_fastify, { FastifyPluginAsync } from 'fastify';
import fastify_static from '@fastify/static';
import * as schemas from '../test/example/schemas.mjs';
import {
ISecretSessionData,
make_secret_session_data,
verify_secret_session_data
} from '../test/example/session.mjs';
import makeWebAuthn from '../index.js';
import {
User,
Credential,
CredentialCreationResponse,
CredentialAssertionResponse,
CredentialDescriptor
} from './webauthn';
const readFile = fs.promises.readFile;
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const users = new Map<string, User>();
class ErrorWithStatus extends Error {
constructor(message : string, public statusCode : number) {
super(message);
}
}
const test_dir = join(__dirname, '..', 'test');
const keys_dir = join(test_dir, 'keys');
const fastify = mod_fastify({
logger: true,
https: {
key: await readFile(join(keys_dir, 'server.key')),
cert: await readFile(join(keys_dir, 'server.crt'))
}
});
fastify.register(fastify_static, {
root: join(test_dir, 'fixtures'),
index: ['example.html']
});
const webAuthn = await makeWebAuthn({
RPDisplayName: 'WebAuthnJS',
RPID: 'localhost',
RPOrigins: [`https://localhost:${port}`],
/*Timeouts: {
Login: {
Enforce: true,
Timeout: 60 * 1000,
TimeoutUVD: 60 * 1000
},
Registration: {
Enforce: true,
Timeout: 60 * 1000,
TimeoutUVD: 60 * 1000
}
}*/
});
interface IUserRoute {
Params: { username : string }
}
const register : FastifyPluginAsync = async function (fastify) {
fastify.get<IUserRoute>('/:username', {
schema: schemas.register.get
}, async request => {
let user = users.get(request.params.username);
if (!user) {
user = {
id: `user${users.size}`,
name: request.params.username,
displayName: request.params.username.split('@')[0],
iconURL: '',
credentials: []
};
users.set(request.params.username, user);
}
const excludeCredentials = user.credentials.map((c) : CredentialDescriptor => ({
type: 'public-key',
id: c.id
}));
const { options, sessionData } = await webAuthn.beginRegistration(
user,
cco => {
cco.excludeCredentials = excludeCredentials;
return cco;
});
return {
options,
session_data: await make_secret_session_data(
request.params.username, 'registration', sessionData)
};
});
interface ICreateRoute extends IUserRoute {
Body: {
ccr : CredentialCreationResponse,
session_data : ISecretSessionData
}
}
fastify.put<ICreateRoute>('/:username', {
schema: schemas.register.put
}, async (request, reply) => {
const user = users.get(request.params.username);
if (!user) {
throw new ErrorWithStatus('no user', 404);
}
const session_data = await verify_secret_session_data(
request.params.username, 'registration', request.body.session_data);
let credential : Credential;
try {
credential = await webAuthn.finishRegistration(
user, session_data, request.body.ccr);
} catch (ex : any) { // eslint-disable-line @typescript-eslint/no-explicit-any
ex.statusCode = 400;
throw ex;
}
for (const u of users.values()) {
if (u.credentials.find(c => c.id === credential.id)) {
throw new ErrorWithStatus('credential in use', 409);
}
}
user.credentials.push(credential);
reply.code(204);
});
}
const login : FastifyPluginAsync = async function (fastify) {
fastify.get<IUserRoute>('/:username', {
schema: schemas.login.get
}, async request => {
const user = users.get(request.params.username);
if (!user) {
throw new ErrorWithStatus('no user', 404);
}
const { options, sessionData } = await webAuthn.beginLogin(user);
return {
options,
session_data: await make_secret_session_data(
request.params.username, 'login', sessionData)
};
});
interface IAssertRoute extends IUserRoute {
Body: {
car : CredentialAssertionResponse,
session_data : ISecretSessionData
}
}
fastify.post<IAssertRoute>('/:username', {
schema: schemas.login.post
}, async (request, reply) => {
const user = users.get(request.params.username);
if (!user) {
throw new ErrorWithStatus('no user', 404);
}
const session_data = await verify_secret_session_data(
request.params.username, 'login', request.body.session_data);
let credential : Credential;
try {
credential = await webAuthn.finishLogin(
user, session_data, request.body.car);
} catch (ex : any) { // eslint-disable-line @typescript-eslint/no-explicit-any
ex.statusCode = 400;
throw ex;
}
if (credential.authenticator.cloneWarning) {
throw new ErrorWithStatus('credential appears to be cloned', 403);
}
const user_cred = user.credentials.find(c => c.id === credential.id);
if (!user_cred) {
// Should have been checked already in Go by webAuthn.finishLogin
throw new ErrorWithStatus('no credential', 500);
}
user_cred.authenticator.signCount = credential.authenticator.signCount;
reply.code(204);
});
}
fastify.register(register, {
prefix: '/register/'
});
fastify.register(login, {
prefix: '/login/'
});
await fastify.listen({ port });
console.log(`Please visit https://localhost:${port}`);