summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorMatthew Miller <matthew@millerti.me>2023-08-18 11:16:52 -0700
committerMatthew Miller <matthew@millerti.me>2023-08-18 11:16:52 -0700
commit872893e3c4930c293cd8b701395429e24088ce1e (patch)
tree5b5cc3ed1e41e7d4cc3eaf01af312e290d959f23
parente30aa4f9f563186c3f7dd3c4601b91a884f45da7 (diff)
Run `deno fmt` on example project
-rw-r--r--example/README.md6
-rw-r--r--example/example-server.d.ts4
-rw-r--r--example/fido-conformance.ts136
-rw-r--r--example/index.ts96
4 files changed, 142 insertions, 100 deletions
diff --git a/example/README.md b/example/README.md
index 4439d78..573c275 100644
--- a/example/README.md
+++ b/example/README.md
@@ -1,5 +1,7 @@
# SimpleWebAuthn Example Project
-A fully-functional reference implementation of **@simplewebauthn/server** and **@simplewebauthn/browser**.
+A fully-functional reference implementation of **@simplewebauthn/server** and
+**@simplewebauthn/browser**.
-You can find an in-depth guide to the Example Project here: https://simplewebauthn.dev/docs/advanced/example-project
+You can find an in-depth guide to the Example Project here:
+https://simplewebauthn.dev/docs/advanced/example-project
diff --git a/example/example-server.d.ts b/example/example-server.d.ts
index 2e56445..fc72b24 100644
--- a/example/example-server.d.ts
+++ b/example/example-server.d.ts
@@ -1,4 +1,4 @@
-import type { AuthenticatorDevice } from '@simplewebauthn/typescript-types';
+import type { AuthenticatorDevice } from "@simplewebauthn/typescript-types";
/**
* You'll need a database to store a few things:
@@ -37,7 +37,7 @@ interface LoggedInUser {
devices: AuthenticatorDevice[];
}
-declare module 'express-session' {
+declare module "express-session" {
interface SessionData {
/**
* A simple way of storing a user's current challenge being signed by registration or authentication.
diff --git a/example/fido-conformance.ts b/example/fido-conformance.ts
index 53b1beb..a536f46 100644
--- a/example/fido-conformance.ts
+++ b/example/fido-conformance.ts
@@ -1,24 +1,24 @@
-import fs from 'fs';
-import express from 'express';
-import fetch from 'node-fetch';
+import fs from "fs";
+import express from "express";
+import fetch from "node-fetch";
import {
- generateRegistrationOptions,
- verifyRegistrationResponse,
generateAuthenticationOptions,
- verifyAuthenticationResponse,
+ generateRegistrationOptions,
MetadataService,
MetadataStatement,
SettingsService,
-} from '@simplewebauthn/server';
-import { isoBase64URL, isoUint8Array } from '@simplewebauthn/server/helpers';
+ verifyAuthenticationResponse,
+ verifyRegistrationResponse,
+} from "@simplewebauthn/server";
+import { isoBase64URL, isoUint8Array } from "@simplewebauthn/server/helpers";
import {
- RegistrationResponseJSON,
AuthenticationResponseJSON,
-} from '@simplewebauthn/typescript-types';
+ RegistrationResponseJSON,
+} from "@simplewebauthn/typescript-types";
-import { rpID, expectedOrigin } from './index';
-import { LoggedInUser } from './example-server';
+import { expectedOrigin, rpID } from "./index";
+import { LoggedInUser } from "./example-server";
interface LoggedInFIDOUser extends LoggedInUser {
currentAuthenticationUserVerification?: UserVerificationRequirement;
@@ -28,9 +28,9 @@ interface LoggedInFIDOUser extends LoggedInUser {
* Create paths specifically for testing with the FIDO Conformance Tools
*/
export const fidoConformanceRouter = express.Router();
-export const fidoRouteSuffix = '/fido';
+export const fidoRouteSuffix = "/fido";
-const rpName = 'FIDO Conformance Test';
+const rpName = "FIDO Conformance Test";
/**
* Load JSON metadata statements provided by the Conformance Tools
@@ -41,11 +41,14 @@ const statements: MetadataStatement[] = [];
try {
// Update this to whatever folder you extracted the statements to
- const conformanceMetadataPath = './fido-conformance-mds';
+ const conformanceMetadataPath = "./fido-conformance-mds";
const conformanceMetadataFilenames = fs.readdirSync(conformanceMetadataPath);
for (const statementPath of conformanceMetadataFilenames) {
- if (statementPath.endsWith('.json')) {
- const contents = fs.readFileSync(`${conformanceMetadataPath}/${statementPath}`, 'utf-8');
+ if (statementPath.endsWith(".json")) {
+ const contents = fs.readFileSync(
+ `${conformanceMetadataPath}/${statementPath}`,
+ "utf-8",
+ );
statements.push(JSON.parse(contents));
}
}
@@ -58,24 +61,24 @@ try {
*
* (Grabbed this URL from the POST made on https://mds3.fido.tools/ when you submit your site's URL)
*/
-fetch('https://mds3.fido.tools/getEndpoints', {
- method: 'POST',
+fetch("https://mds3.fido.tools/getEndpoints", {
+ method: "POST",
body: JSON.stringify({ endpoint: `${expectedOrigin}${fidoRouteSuffix}` }),
- headers: { 'Content-Type': 'application/json' },
+ headers: { "Content-Type": "application/json" },
})
- .then(resp => resp.json())
- .then(json => {
+ .then((resp) => resp.json())
+ .then((json) => {
const mdsServers: string[] = json.result;
return MetadataService.initialize({
statements,
mdsServers,
- verificationMode: 'strict',
+ verificationMode: "strict",
});
})
.catch(console.error)
.finally(() => {
- console.log('🔐 FIDO Conformance routes ready');
+ console.log("🔐 FIDO Conformance routes ready");
});
const inMemoryUserDeviceDB: { [username: string]: LoggedInFIDOUser } = {
@@ -98,14 +101,32 @@ const inMemoryUserDeviceDB: { [username: string]: LoggedInFIDOUser } = {
// A cheap way of remembering who's "logged in" between the request for options and the response
let loggedInUsername: string | undefined = undefined;
-const supportedAlgorithmIDs = [-7, -8, -35, -36, -37, -38, -39, -257, -258, -259, -65535];
+const supportedAlgorithmIDs = [
+ -7,
+ -8,
+ -35,
+ -36,
+ -37,
+ -38,
+ -39,
+ -257,
+ -258,
+ -259,
+ -65535,
+];
/**
* [FIDO2] Server Tests > MakeCredential Request
*/
-fidoConformanceRouter.post('/attestation/options', (req, res) => {
+fidoConformanceRouter.post("/attestation/options", (req, res) => {
const { body } = req;
- const { username, displayName, authenticatorSelection, attestation, extensions } = body;
+ const {
+ username,
+ displayName,
+ authenticatorSelection,
+ attestation,
+ extensions,
+ } = body;
loggedInUsername = username;
@@ -132,10 +153,10 @@ fidoConformanceRouter.post('/attestation/options', (req, res) => {
attestationType: attestation,
authenticatorSelection,
extensions,
- excludeCredentials: devices.map(dev => ({
+ excludeCredentials: devices.map((dev) => ({
id: dev.credentialID,
- type: 'public-key',
- transports: ['usb', 'ble', 'nfc', 'internal'],
+ type: "public-key",
+ transports: ["usb", "ble", "nfc", "internal"],
})),
supportedAlgorithmIDs,
});
@@ -147,15 +168,15 @@ fidoConformanceRouter.post('/attestation/options', (req, res) => {
return res.send({
...opts,
- status: 'ok',
- errorMessage: '',
+ status: "ok",
+ errorMessage: "",
});
});
/**
* [FIDO2] Server Tests > MakeCredential Response
*/
-fidoConformanceRouter.post('/attestation/result', async (req, res) => {
+fidoConformanceRouter.post("/attestation/result", async (req, res) => {
const body: RegistrationResponseJSON = req.body;
const user = inMemoryUserDeviceDB[`${loggedInUsername}`];
@@ -182,7 +203,9 @@ fidoConformanceRouter.post('/attestation/result', async (req, res) => {
if (verified && registrationInfo) {
const { credentialPublicKey, credentialID, counter } = registrationInfo;
- const existingDevice = user.devices.find(device => device.credentialID === credentialID);
+ const existingDevice = user.devices.find((device) =>
+ device.credentialID === credentialID
+ );
if (!existingDevice) {
/**
@@ -197,15 +220,15 @@ fidoConformanceRouter.post('/attestation/result', async (req, res) => {
}
return res.send({
- status: verified ? 'ok' : '',
- errorMessage: '',
+ status: verified ? "ok" : "",
+ errorMessage: "",
});
});
/**
* [FIDO2] Server Tests > GetAuthentication Request
*/
-fidoConformanceRouter.post('/assertion/options', (req, res) => {
+fidoConformanceRouter.post("/assertion/options", (req, res) => {
const { body } = req;
const { username, userVerification, extensions } = body;
@@ -218,10 +241,10 @@ fidoConformanceRouter.post('/assertion/options', (req, res) => {
const opts = generateAuthenticationOptions({
extensions,
userVerification,
- allowCredentials: devices.map(dev => ({
+ allowCredentials: devices.map((dev) => ({
id: dev.credentialID,
- type: 'public-key',
- transports: ['usb', 'ble', 'nfc', 'internal'],
+ type: "public-key",
+ transports: ["usb", "ble", "nfc", "internal"],
})),
});
@@ -230,12 +253,12 @@ fidoConformanceRouter.post('/assertion/options', (req, res) => {
return res.send({
...opts,
- status: 'ok',
- errorMessage: '',
+ status: "ok",
+ errorMessage: "",
});
});
-fidoConformanceRouter.post('/assertion/result', async (req, res) => {
+fidoConformanceRouter.post("/assertion/result", async (req, res) => {
const body: AuthenticationResponseJSON = req.body;
const { id } = body;
@@ -252,7 +275,9 @@ fidoConformanceRouter.post('/assertion/result', async (req, res) => {
}
const credIDBuffer = isoBase64URL.toBuffer(id);
- const existingDevice = user.devices.find(device => isoUint8Array.areEqual(device.credentialID, credIDBuffer));
+ const existingDevice = user.devices.find((device) =>
+ isoUint8Array.areEqual(device.credentialID, credIDBuffer)
+ );
if (!existingDevice) {
const msg = `Could not find device matching ${id}`;
@@ -284,8 +309,8 @@ fidoConformanceRouter.post('/assertion/result', async (req, res) => {
}
return res.send({
- status: verified ? 'ok' : '',
- errorMessage: '',
+ status: verified ? "ok" : "",
+ errorMessage: "",
});
});
@@ -293,7 +318,7 @@ fidoConformanceRouter.post('/assertion/result', async (req, res) => {
* A catch-all for future test routes we might need to support but haven't yet defined (helps with
* discovering which routes, what methods, and what data need to be defined)
*/
-fidoConformanceRouter.all('*', (req, res, next) => {
+fidoConformanceRouter.all("*", (req, res, next) => {
console.log(req.url);
console.log(req.method);
console.log(req.body);
@@ -329,8 +354,17 @@ X2S5Ht8+e+EQnezLJBJXtnkRWY+Zt491wgt/AwSs5PHHMv5QgjELOuMxQBc=
`;
// Set above root cert for use by MetadataService
-SettingsService.setRootCertificates({ identifier: 'mds', certificates: [MDS3ROOT] });
+SettingsService.setRootCertificates({
+ identifier: "mds",
+ certificates: [MDS3ROOT],
+});
// Reset preset root certificates
-SettingsService.setRootCertificates({ identifier: 'apple', certificates: [] });
-SettingsService.setRootCertificates({ identifier: 'android-key', certificates: [] });
-SettingsService.setRootCertificates({ identifier: 'android-safetynet', certificates: [] });
+SettingsService.setRootCertificates({ identifier: "apple", certificates: [] });
+SettingsService.setRootCertificates({
+ identifier: "android-key",
+ certificates: [],
+});
+SettingsService.setRootCertificates({
+ identifier: "android-safetynet",
+ certificates: [],
+});
diff --git a/example/index.ts b/example/index.ts
index e8ce33a..1610205 100644
--- a/example/index.ts
+++ b/example/index.ts
@@ -4,42 +4,42 @@
* The webpages served from ./public use @simplewebauthn/browser.
*/
-import https from 'https';
-import http from 'http';
-import fs from 'fs';
+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';
+import express from "express";
+import session from "express-session";
+import memoryStore from "memorystore";
+import dotenv from "dotenv";
dotenv.config();
import {
- // Registration
- generateRegistrationOptions,
- verifyRegistrationResponse,
// Authentication
generateAuthenticationOptions,
+ // Registration
+ generateRegistrationOptions,
verifyAuthenticationResponse,
-} from '@simplewebauthn/server';
-import { isoBase64URL, isoUint8Array } from '@simplewebauthn/server/helpers';
+ verifyRegistrationResponse,
+} from "@simplewebauthn/server";
+import { isoBase64URL, isoUint8Array } from "@simplewebauthn/server/helpers";
import type {
- GenerateRegistrationOptionsOpts,
GenerateAuthenticationOptionsOpts,
- VerifyRegistrationResponseOpts,
- VerifyAuthenticationResponseOpts,
- VerifiedRegistrationResponse,
+ GenerateRegistrationOptionsOpts,
VerifiedAuthenticationResponse,
-} from '@simplewebauthn/server';
+ VerifiedRegistrationResponse,
+ VerifyAuthenticationResponseOpts,
+ VerifyRegistrationResponseOpts,
+} from "@simplewebauthn/server";
import type {
- RegistrationResponseJSON,
AuthenticationResponseJSON,
AuthenticatorDevice,
-} from '@simplewebauthn/typescript-types';
+ RegistrationResponseJSON,
+} from "@simplewebauthn/typescript-types";
-import { LoggedInUser } from './example-server';
+import { LoggedInUser } from "./example-server";
const app = express();
const MemoryStore = memoryStore(session);
@@ -47,14 +47,14 @@ const MemoryStore = memoryStore(session);
const {
ENABLE_CONFORMANCE,
ENABLE_HTTPS,
- RP_ID = 'localhost',
+ RP_ID = "localhost",
} = process.env;
-app.use(express.static('./public/'));
+app.use(express.static("./public/"));
app.use(express.json());
app.use(
session({
- secret: 'secret123',
+ secret: "secret123",
saveUninitialized: true,
resave: false,
cookie: {
@@ -73,10 +73,12 @@ app.use(
* 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);
- });
+if (ENABLE_CONFORMANCE === "true") {
+ import("./fido-conformance").then(
+ ({ fidoRouteSuffix, fidoConformanceRouter }) => {
+ app.use(fidoRouteSuffix, fidoConformanceRouter);
+ },
+ );
}
/**
@@ -87,7 +89,7 @@ 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 = '';
+export let expectedOrigin = "";
/**
* 2FA and Passwordless WebAuthn flows expect you to be able to uniquely identify the user that
@@ -97,7 +99,7 @@ export let expectedOrigin = '';
*
* Here, the example server assumes the following user has completed login:
*/
-const loggedInUserId = 'internalUserId';
+const loggedInUserId = "internalUserId";
const inMemoryUserDeviceDB: { [loggedInUserId: string]: LoggedInUser } = {
[loggedInUserId]: {
@@ -110,7 +112,7 @@ const inMemoryUserDeviceDB: { [loggedInUserId: string]: LoggedInUser } = {
/**
* Registration (a.k.a. "Registration")
*/
-app.get('/generate-registration-options', (req, res) => {
+app.get("/generate-registration-options", (req, res) => {
const user = inMemoryUserDeviceDB[loggedInUserId];
const {
@@ -122,25 +124,25 @@ app.get('/generate-registration-options', (req, res) => {
} = user;
const opts: GenerateRegistrationOptionsOpts = {
- rpName: 'SimpleWebAuthn Example',
+ rpName: "SimpleWebAuthn Example",
rpID,
userID: loggedInUserId,
userName: username,
timeout: 60000,
- attestationType: 'none',
+ 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 => ({
+ excludeCredentials: devices.map((dev) => ({
id: dev.credentialID,
- type: 'public-key',
+ type: "public-key",
transports: dev.transports,
})),
authenticatorSelection: {
- residentKey: 'discouraged',
+ residentKey: "discouraged",
},
/**
* Support the two most common algorithms: ES256, and RS256
@@ -159,7 +161,7 @@ app.get('/generate-registration-options', (req, res) => {
res.send(options);
});
-app.post('/verify-registration', async (req, res) => {
+app.post("/verify-registration", async (req, res) => {
const body: RegistrationResponseJSON = req.body;
const user = inMemoryUserDeviceDB[loggedInUserId];
@@ -187,7 +189,9 @@ app.post('/verify-registration', async (req, res) => {
if (verified && registrationInfo) {
const { credentialPublicKey, credentialID, counter } = registrationInfo;
- const existingDevice = user.devices.find(device => isoUint8Array.areEqual(device.credentialID, credentialID));
+ const existingDevice = user.devices.find((device) =>
+ isoUint8Array.areEqual(device.credentialID, credentialID)
+ );
if (!existingDevice) {
/**
@@ -211,18 +215,18 @@ app.post('/verify-registration', async (req, res) => {
/**
* Login (a.k.a. "Authentication")
*/
-app.get('/generate-authentication-options', (req, res) => {
+app.get("/generate-authentication-options", (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 => ({
+ allowCredentials: user.devices.map((dev) => ({
id: dev.credentialID,
- type: 'public-key',
+ type: "public-key",
transports: dev.transports,
})),
- userVerification: 'required',
+ userVerification: "required",
rpID,
};
@@ -237,7 +241,7 @@ app.get('/generate-authentication-options', (req, res) => {
res.send(options);
});
-app.post('/verify-authentication', async (req, res) => {
+app.post("/verify-authentication", async (req, res) => {
const body: AuthenticationResponseJSON = req.body;
const user = inMemoryUserDeviceDB[loggedInUserId];
@@ -255,7 +259,9 @@ app.post('/verify-authentication', async (req, res) => {
}
if (!dbAuthenticator) {
- return res.status(400).send({ error: 'Authenticator is not registered with this site' });
+ return res.status(400).send({
+ error: "Authenticator is not registered with this site",
+ });
}
let verification: VerifiedAuthenticationResponse;
@@ -288,7 +294,7 @@ app.post('/verify-authentication', async (req, res) => {
});
if (ENABLE_HTTPS) {
- const host = '0.0.0.0';
+ const host = "0.0.0.0";
const port = 443;
expectedOrigin = `https://${rpID}`;
@@ -307,7 +313,7 @@ if (ENABLE_HTTPS) {
console.log(`🚀 Server ready at ${expectedOrigin} (${host}:${port})`);
});
} else {
- const host = '127.0.0.1';
+ const host = "127.0.0.1";
const port = 8000;
expectedOrigin = `http://localhost:${port}`;