Skip to content
Permalink
ed832a1915
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
156 lines (130 sloc) 4.33 KB
import express from "express";
import fido2lib from "@dannymoerkerke/fido2-lib";
import base64url from "base64url";
import crypto from "crypto";
import cfg from "config";
import User from "../models/user.js";
const mode = process.env.NODE_ENV || "dev";
const config = cfg.get(mode);
const { Fido2Lib } = fido2lib;
const router = express.Router();
const fido = new Fido2Lib({
timeout: 60000,
rpName: "WebAuthnUX",
rpIcon: "https://whatpwacando.today/src/img/icons/icon-512x512.png",
challengeSize: 128,
attestation: "none",
cryptoParams: [-7, -257],
authenticatorAttachment: "platform",
authenticatorRequireResidentKey: false,
authenticatorUserVerification: "required",
});
router.post("/registration-options", async (req, res) => {
const { email, firstName, lastName } = req.body;
if (!email) {
console.log("Missing email");
return res.status(400).json({ error: "Missing email field" });
}
const userExists = await User.findOne({ email });
if (userExists) {
console.log("User already exists");
return res.status(400).json({ error: "User already exists" });
}
const userId = crypto.randomBytes(32);
// TODO: Create user in /register
const user = await User.create({
id: userId,
firstName,
lastName,
email,
});
user.save();
const registrationOptions = await fido.attestationOptions();
req.session.challenge = Buffer.from(registrationOptions.challenge);
req.session.userHandle = user.id;
registrationOptions.user.id = req.session.userHandle;
registrationOptions.challenge = Buffer.from(registrationOptions.challenge);
// iOS
registrationOptions.authenticatorSelection = {
authenticatorAttachment: "platform",
};
res.setHeader("Access-Control-Allow-Credentials", "true");
res.json(registrationOptions);
});
router.post("/register", async (req, res) => {
const { credential, email } = req.body;
const challenge = new Uint8Array(req.session.challenge.data).buffer;
const base64RawId = credential.rawId;
credential.rawId = new Uint8Array(Buffer.from(credential.rawId, "base64")).buffer;
credential.response.attestationObject = base64url.decode(
credential.response.attestationObject,
"base64"
);
credential.response.clientDataJSON = base64url.decode(
credential.response.clientDataJSON,
"base64"
);
const attestationExpectations = {
challenge,
origin: config.siteUrl,
factor: "either",
};
try {
const regResult = await fido.attestationResult(credential, attestationExpectations);
req.session.publicKey = regResult.authnrData.get("credentialPublicKeyPem");
req.session.prevCounter = regResult.authnrData.get("counter");
await User.findOneAndUpdate(
{
email: email,
},
{
credentialId: base64RawId,
}
);
res.json({ status: "ok" });
} catch (e) {
console.log("error", e);
res.status(500).json({ error: e });
}
});
router.post("/authentication-options", async (req, res) => {
const authnOptions = await fido.assertionOptions();
const { email } = req.body;
const user = await User.findOne({ email });
if (user) {
req.session.challenge = Buffer.from(authnOptions.challenge);
req.session.userHandle = user.id;
authnOptions.challenge = Buffer.from(authnOptions.challenge);
authnOptions.rawId = user.credentialId;
res.json(authnOptions);
} else {
res.status(404).json({ error: "User does not exist." });
}
});
router.post("/authenticate", async (req, res) => {
const { credential } = req.body;
credential.rawId = new Uint8Array(Buffer.from(credential.rawId, "base64")).buffer;
const challenge = new Uint8Array(req.session.challenge.data).buffer;
const { publicKey, prevCounter } = req.session;
if (publicKey === "undefined" || prevCounter === undefined) {
console.log("Not found");
res.status(404).json({ error: "Credential not found" });
} else {
const assertionExpectations = {
challenge,
origin: config.siteUrl,
factor: "either",
publicKey,
prevCounter,
userHandle: new Uint8Array(Buffer.from(req.session.userHandle, "base64")).buffer,
};
try {
await fido.assertionResult(credential, assertionExpectations);
res.json({ status: "ok" });
} catch (e) {
console.log(e);
res.status(500).json({ error: "Failed due internal server error" });
}
}
});
export default router;