summaryrefslogtreecommitdiffhomepage
path: root/example/fido-conformance.js
blob: 37cd90e9d967528c2eeaa883e75c7a11c72205e4 (plain)
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
/* eslint-disable @typescript-eslint/no-var-requires */
const fs = require('fs');
const express = require('express');
const { v4: uuidv4 } = require('uuid');

const {
  generateAttestationOptions,
  verifyAttestationResponse,
  generateAssertionOptions,
  verifyAssertionResponse,
  MetadataService,
} = require('@simplewebauthn/server');

/**
 * Load JSON metadata statements provided by the Conformance Tools
 *
 * FIDO2 > TESTS CONFIGURATION > DOWNLOAD SERVER METADATA (button)
 */
// Update this to whatever folder you extracted the statements to
const conformanceMetadataPath = './fido-conformance-mds-v1.3.4';
const conformanceMetadataFilenames = fs.readdirSync(conformanceMetadataPath);
const statements = [];
for (const statementPath of conformanceMetadataFilenames) {
  if (statementPath.endsWith('.json')) {
    const contents = fs.readFileSync(`${conformanceMetadataPath}/${statementPath}`, 'utf-8');
    statements.push(JSON.parse(contents));
  }
}
// Initialize the metadata service with the prepared statements
MetadataService.initialize(statements);

const inMemoryUserDeviceDB = {
  // [username]: string: {
  //   id: loggedInUserId,
  //   username: 'user@yourdomain.com',
  //   devices: [
  //     /**
  //      * {
  //      *   credentialID: string,
  //      *   publicKey: string,
  //      *   counter: number,
  //      * }
  //      */
  //   ],
  //   currentChallenge: undefined,
  // },
};

/**
 * Create paths specifically for testing with the FIDO Conformance Tools
 */
const fidoComplianceRouter = express.Router();

let loggedInUsername = undefined;
const serviceName = 'FIDO Conformance Test';
const rpID = 'dev.dontneeda.pw';
const origin = 'https://dev.dontneeda.pw';

/**
 * [FIDO2] Server Tests > MakeCredential Request
 */
fidoComplianceRouter.post('/attestation/options', (req, res) => {
  const { body } = req;
  const { username, displayName, authenticatorSelection, attestation, extensions } = body;

  loggedInUsername = username;

  let user = inMemoryUserDeviceDB[username];
  if (!user) {
    const newUser = {
      id: username,
      username,
      devices: [],
    };

    inMemoryUserDeviceDB[username] = newUser;
    user = newUser;
  }

  const { devices } = user;

  const challenge = uuidv4();
  user.currentChallenge = challenge;

  const opts = generateAttestationOptions({
    serviceName,
    rpID,
    challenge,
    userID: username,
    userName: username,
    userDisplayName: displayName,
    attestationType: attestation,
    authenticatorSelection,
    extensions,
    excludedCredentialIDs: devices.map(dev => dev.credentialID),
  });

  return res.send({
    ...opts,
    status: 'ok',
    errorMessage: '',
  });
});

/**
 * [FIDO2] Server Tests > MakeCredential Response
 */
fidoComplianceRouter.post('/attestation/result', (req, res) => {
  const { body } = req;

  const user = inMemoryUserDeviceDB[loggedInUsername];

  const expectedChallenge = user.currentChallenge;

  let verification;
  try {
    verification = verifyAttestationResponse({
      credential: body,
      expectedChallenge: Buffer.from(expectedChallenge, 'base64'),
      expectedOrigin: origin,
    });
  } catch (error) {
    console.error(error.message);
    return res.status(400).send({ errorMessage: error.message });
  }

  const { verified, authenticatorInfo } = verification;

  if (verified) {
    const { base64PublicKey, base64CredentialID, counter } = authenticatorInfo;

    const existingDevice = user.devices.find(device => device.credentialID === base64CredentialID);

    if (!existingDevice) {
      /**
       * Add the returned device to the user's list of devices
       */
      user.devices.push({
        publicKey: base64PublicKey,
        credentialID: base64CredentialID,
        counter,
      });
    }
  }

  return res.send({
    status: verified ? 'ok' : '',
    errorMessage: '',
  });
});

/**
 * [FIDO2] Server Tests > GetAssertion Request
 */
fidoComplianceRouter.post('/assertion/options', (req, res) => {
  const { body } = req;
  const { username, userVerification, extensions } = body;

  loggedInUsername = username;

  let user = inMemoryUserDeviceDB[username];

  const { devices } = user;

  const challenge = uuidv4();
  user.currentChallenge = challenge;

  const opts = generateAssertionOptions({
    challenge,
    extensions,
    userVerification,
    allowedCredentialIDs: devices.map(dev => dev.credentialID),
  });

  return res.send({
    ...opts,
    status: 'ok',
    errorMessage: '',
  });
});

fidoComplianceRouter.post('/assertion/result', (req, res) => {
  const { body } = req;
  const { id } = body;

  const user = inMemoryUserDeviceDB[loggedInUsername];
  const expectedChallenge = user.currentChallenge;
  const existingDevice = user.devices.find(device => device.credentialID === id);

  if (!existingDevice) {
    throw new Error('Assertion device is not registered to user');
  }

  let verification;
  try {
    verification = verifyAssertionResponse({
      credential: body,
      expectedChallenge: Buffer.from(expectedChallenge, 'base64'),
      expectedOrigin: origin,
      expectedRPID: rpID,
      authenticator: existingDevice,
    });
  } catch (error) {
    console.error(error.message);
    return res.status(400).send({ errorMessage: error.message });
  }

  const { verified, authenticatorInfo } = verification;

  if (verified) {
    const { base64CredentialID, counter } = authenticatorInfo;
    const existingDevice = user.devices.find(device => device.credentialID === base64CredentialID);
    existingDevice.counter = counter;
  }

  return res.send({
    status: verified ? 'ok' : '',
    errorMessage: '',
  });
});

fidoComplianceRouter.all('*', (req, res, next) => {
  console.log(req.url);
  console.log(req.method);
  console.log(req.body);

  next();
});

module.exports = fidoComplianceRouter;