-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
281 lines (239 loc) · 8.23 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
/* 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 fs from "fs";
import http from "http";
import https from "https";
import base64url from "base64url";
import dotenv from "dotenv";
import express from "express";
dotenv.config();
import type {
GenerateAuthenticationOptionsOpts,
GenerateRegistrationOptionsOpts,
} from "@simplewebauthn/server";
import {
// Authentication
generateAuthenticationOptions,
generateRegistrationOptions,
} from "@simplewebauthn/server";
import { LoggedInUser } from "./example-server";
import cors from "cors";
import {
googleOAuthVerifyToMintHandler,
googleOAuthVerifyToFetchPKPsHandler,
} from "./routes/auth/google";
import { getAuthStatusHandler } from "./routes/auth/status";
import limiter from "./routes/middlewares/limiter";
import { storeConditionHandler } from "./routes/storeCondition";
import apiKeyGateAndTracking from "./routes/middlewares/apiKeyGateAndTracking";
import {
webAuthnVerifyRegistrationHandler,
webAuthnGenerateRegistrationOptionsHandler,
webAuthnVerifyToFetchPKPsHandler,
} from "./routes/auth/webAuthn";
import {
discordOAuthVerifyToFetchPKPsHandler,
discordOAuthVerifyToMintHandler,
} from "./routes/auth/discord";
import {
walletVerifyToMintHandler,
walletVerifyToFetchPKPsHandler,
} from "./routes/auth/wallet";
import {
fetchPKPsHandler,
mintNextAndAddAuthMethodsHandler,
} from "./routes/auth/mintAndFetch";
import config from "./config";
import {
stytchOtpVerifyToFetchPKPsHandler,
stytchOtpVerifyToMintHandler,
} from "./routes/auth/stytchOtp";
import {
otpVerifyToFetchPKPsHandler,
otpVerifyToMintHandler,
} from "./routes/auth/otp";
import { mintClaimedKeyId } from "./routes/auth/claim";
import { registerPayerHandler } from "./routes/delegate/register";
import { addPayeeHandler } from "./routes/delegate/user";
const app = express();
const { ENABLE_CONFORMANCE, ENABLE_HTTPS, RP_ID = "localhost" } = process.env;
app.use(express.static("./public/"));
app.use(express.json());
app.use(cors());
app.use(limiter);
app.use(apiKeyGateAndTracking);
/**
* 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;
/**
* 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: `user@${rpID}`,
devices: [],
/**
* A simple way of storing a user's current challenge being signed by registration or authentication.
* It should be expired after `timeout` milliseconds (optional argument for `generate` methods,
* defaults to 60000ms)
*/
currentChallenge: undefined,
},
};
/**
* Registration (a.k.a. "Registration")
*/
app.get("/generate-registration-options", (req, res) => {
const user = inMemoryUserDeviceDB[loggedInUserId];
const {
/**
* The username can be a human-readable name, email, etc... as it is intended only for display.
*/
username,
devices,
} = user;
const opts: GenerateRegistrationOptionsOpts = {
rpName: "SimpleWebAuthn Example",
rpID,
userID: loggedInUserId,
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,
})),
/**
* The optional authenticatorSelection property allows for specifying more constraints around
* the types of authenticators that users to can use for registration
*/
authenticatorSelection: {
userVerification: "required",
residentKey: "required",
},
/**
* Support the two most common algorithms: ES256, and RS256
*/
supportedAlgorithmIDs: [-7],
};
const options = generateRegistrationOptions(opts);
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
inMemoryUserDeviceDB[loggedInUserId].currentChallenge = options.challenge;
res.send(options);
});
/**
* Login (a.k.a. "Authentication")
*/
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) => ({
id: dev.credentialID,
type: "public-key",
transports: dev.transports,
})),
userVerification: "required",
rpID,
};
const options = generateAuthenticationOptions(opts);
/**
* The server needs to temporarily remember this value for verification, so don't lose it until
* after you verify an authenticator response.
*/
inMemoryUserDeviceDB[loggedInUserId].currentChallenge = options.challenge;
res.send(options);
});
// --- Store condition
app.post("/store-condition", storeConditionHandler);
// --- Mint PKP for authorized account
app.post("/mint-next-and-add-auth-methods", mintNextAndAddAuthMethodsHandler);
// --- Fetch PKPs tied to authorized account
app.post("/fetch-pkps-by-auth-method", fetchPKPsHandler);
// --- Poll minting progress
app.get("/auth/status/:requestId", getAuthStatusHandler);
// -- Payment Delegation
app.post("/register-payer", registerPayerHandler);
app.post("/add-users", addPayeeHandler);
// *** Deprecated ***
app.post("/auth/google", googleOAuthVerifyToMintHandler);
app.post("/auth/discord", discordOAuthVerifyToMintHandler);
app.post("/auth/wallet", walletVerifyToMintHandler);
app.post("/auth/otp", otpVerifyToMintHandler);
app.post("/auth/stytch-otp", stytchOtpVerifyToMintHandler);
app.post("/auth/google/userinfo", googleOAuthVerifyToFetchPKPsHandler);
app.post("/auth/discord/userinfo", discordOAuthVerifyToFetchPKPsHandler);
app.post("/auth/wallet/userinfo", walletVerifyToFetchPKPsHandler);
app.post("/auth/otp/userinfo", otpVerifyToFetchPKPsHandler);
app.post("/auth/stytch-otp/userinfo", stytchOtpVerifyToFetchPKPsHandler);
app.post("/auth/webauthn/userinfo", webAuthnVerifyToFetchPKPsHandler);
app.post(
"/auth/webauthn/verify-registration",
webAuthnVerifyRegistrationHandler,
);
app.get(
"/auth/webauthn/generate-registration-options",
webAuthnGenerateRegistrationOptionsHandler,
);
app.post("/auth/claim", mintClaimedKeyId);
if (ENABLE_HTTPS) {
const host = "0.0.0.0";
const port = 443;
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(`🚀 1: Server ready at ${host}:${port}`);
});
} else {
const host = "127.0.0.1";
const port = config.port;
http.createServer(app).listen(port, () => {
console.log(`🚀 2: Server ready at ${host}:${port} 🌶️ NETWORK: ${process.env.NETWORK} | RPC: ${process.env.LIT_TXSENDER_RPC_URL} |`);
});
}