@miguelmorales13/nestkit 0.19.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -7
- package/dist/auth/oauth/index.cjs +1059 -68
- package/dist/auth/oauth/index.d.ts +20 -7
- package/dist/auth/oauth/index.js +1049 -58
- package/dist/auth/oauth/magic-link.dto.d.ts +20 -0
- package/dist/auth/oauth/memory-security.stores.d.ts +19 -0
- package/dist/auth/oauth/oauth-auth.service.d.ts +168 -14
- package/dist/auth/oauth/oauth-provider.d.ts +54 -5
- package/dist/auth/oauth/oauth.options.d.ts +57 -1
- package/dist/auth/oauth/oauth.ports.d.ts +58 -0
- package/dist/auth/oauth/providers/apple.d.ts +58 -0
- package/dist/auth/oauth/providers/discord.d.ts +7 -0
- package/dist/auth/oauth/providers/github.d.ts +8 -0
- package/dist/auth/oauth/providers/linkedin.d.ts +7 -0
- package/dist/auth/oauth/providers/microsoft.d.ts +17 -0
- package/dist/auth/oauth/providers/tiktok.d.ts +17 -0
- package/dist/auth/oauth/totp.d.ts +33 -0
- package/dist/auth/oauth/webauthn.port.d.ts +17 -0
- package/dist/index.cjs +5 -5
- package/dist/index.js +7 -7
- package/dist/invoicing/adapters/facturama.invoicing.d.ts +1 -0
- package/dist/invoicing/index.cjs +7 -2
- package/dist/invoicing/index.js +7 -2
- package/dist/invoicing/invoicing.port.d.ts +10 -0
- package/package.json +7 -2
package/dist/auth/oauth/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
JwtAuthGuard
|
|
4
4
|
} from "../../chunk-TUNDBBQF.js";
|
|
5
5
|
import {
|
|
6
|
+
NotFoundAppException,
|
|
6
7
|
UnauthorizedAppException,
|
|
7
8
|
ValidationAppException
|
|
8
9
|
} from "../../chunk-ZFIDAX7K.js";
|
|
@@ -55,7 +56,9 @@ function googleProvider(credentials = {}) {
|
|
|
55
56
|
if (!email) throw new Error("Google did not return an email.");
|
|
56
57
|
return {
|
|
57
58
|
providerAccountId: String(data.sub),
|
|
58
|
-
|
|
59
|
+
// Google says whether it verified the address; an unverified one
|
|
60
|
+
// (rare, but possible with Workspace accounts) must not link.
|
|
61
|
+
email: data.email_verified === false ? void 0 : email,
|
|
59
62
|
name: data.name,
|
|
60
63
|
avatarUrl: data.picture
|
|
61
64
|
};
|
|
@@ -82,7 +85,7 @@ function facebookProvider(credentials = {}) {
|
|
|
82
85
|
const picture = data.picture;
|
|
83
86
|
return {
|
|
84
87
|
providerAccountId: String(data.id),
|
|
85
|
-
email: data.email
|
|
88
|
+
email: data.email || void 0,
|
|
86
89
|
name: data.name,
|
|
87
90
|
avatarUrl: picture?.data?.url
|
|
88
91
|
};
|
|
@@ -91,7 +94,7 @@ function facebookProvider(credentials = {}) {
|
|
|
91
94
|
}
|
|
92
95
|
function buildAuthorizeUrl(provider, state) {
|
|
93
96
|
const params = new URLSearchParams({
|
|
94
|
-
client_id: provider.clientId ?? "",
|
|
97
|
+
[provider.clientIdParam ?? "client_id"]: provider.clientId ?? "",
|
|
95
98
|
redirect_uri: provider.callbackUrl ?? "",
|
|
96
99
|
response_type: "code",
|
|
97
100
|
scope: provider.scope,
|
|
@@ -100,10 +103,11 @@ function buildAuthorizeUrl(provider, state) {
|
|
|
100
103
|
});
|
|
101
104
|
return `${provider.authorizeUrl}?${params.toString()}`;
|
|
102
105
|
}
|
|
103
|
-
async function
|
|
106
|
+
async function exchangeCode(provider, code) {
|
|
107
|
+
const secret = typeof provider.clientSecret === "function" ? await provider.clientSecret() : provider.clientSecret ?? "";
|
|
104
108
|
const body = new URLSearchParams({
|
|
105
|
-
client_id: provider.clientId ?? "",
|
|
106
|
-
client_secret:
|
|
109
|
+
[provider.clientIdParam ?? "client_id"]: provider.clientId ?? "",
|
|
110
|
+
client_secret: secret,
|
|
107
111
|
redirect_uri: provider.callbackUrl ?? "",
|
|
108
112
|
grant_type: "authorization_code",
|
|
109
113
|
code
|
|
@@ -119,9 +123,230 @@ async function exchangeCodeForToken(provider, code) {
|
|
|
119
123
|
}),
|
|
120
124
|
`${provider.name} token exchange`
|
|
121
125
|
);
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
126
|
+
return data;
|
|
127
|
+
}
|
|
128
|
+
async function exchangeCodeForToken(provider, code) {
|
|
129
|
+
const tokens = await exchangeCode(provider, code);
|
|
130
|
+
if (!tokens.access_token) throw new Error(`${provider.name} token exchange returned no access_token.`);
|
|
131
|
+
return tokens.access_token;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/auth/oauth/providers/apple.ts
|
|
135
|
+
import { createPublicKey } from "crypto";
|
|
136
|
+
import jwt from "jsonwebtoken";
|
|
137
|
+
var ISSUER = "https://appleid.apple.com";
|
|
138
|
+
var KEYS_URL = "https://appleid.apple.com/auth/keys";
|
|
139
|
+
function appleProvider(credentials = {}) {
|
|
140
|
+
const clientId = credentials.clientId ?? process.env.APPLE_CLIENT_ID;
|
|
141
|
+
const teamId = credentials.teamId ?? process.env.APPLE_TEAM_ID;
|
|
142
|
+
const keyId = credentials.keyId ?? process.env.APPLE_KEY_ID;
|
|
143
|
+
const privateKey = (credentials.privateKey ?? process.env.APPLE_PRIVATE_KEY)?.replace(/\\n/g, "\n");
|
|
144
|
+
const keysUrl = credentials.keysUrl ?? KEYS_URL;
|
|
145
|
+
const configured = Boolean(clientId && teamId && keyId && privateKey);
|
|
146
|
+
return {
|
|
147
|
+
name: "apple",
|
|
148
|
+
clientId,
|
|
149
|
+
// Only offered as configured when every piece exists: `provider()` tests
|
|
150
|
+
// `clientSecret` for truthiness, and a function that would throw later
|
|
151
|
+
// must not count.
|
|
152
|
+
clientSecret: configured ? () => mintClientSecret(clientId, teamId, keyId, privateKey) : void 0,
|
|
153
|
+
callbackUrl: credentials.callbackUrl ?? process.env.APPLE_CALLBACK_URL,
|
|
154
|
+
authorizeUrl: "https://appleid.apple.com/auth/authorize",
|
|
155
|
+
tokenUrl: "https://appleid.apple.com/auth/token",
|
|
156
|
+
scope: credentials.scope ?? "name email",
|
|
157
|
+
authorizeParams: { response_mode: "form_post" },
|
|
158
|
+
callbackMethod: "POST",
|
|
159
|
+
async fetchProfile(_accessToken, tokens, callback) {
|
|
160
|
+
if (!tokens.id_token) throw new Error("Apple token exchange returned no id_token.");
|
|
161
|
+
const claims = await verifyAppleIdToken(tokens.id_token, clientId, keysUrl);
|
|
162
|
+
const verified = claims.email_verified === true || claims.email_verified === "true";
|
|
163
|
+
return {
|
|
164
|
+
providerAccountId: claims.sub,
|
|
165
|
+
email: verified && claims.email ? claims.email : void 0,
|
|
166
|
+
name: nameFromCallback(callback)
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function mintClientSecret(clientId, teamId, keyId, privateKey) {
|
|
172
|
+
return jwt.sign({}, privateKey, {
|
|
173
|
+
algorithm: "ES256",
|
|
174
|
+
keyid: keyId,
|
|
175
|
+
issuer: teamId,
|
|
176
|
+
subject: clientId,
|
|
177
|
+
audience: ISSUER,
|
|
178
|
+
expiresIn: "180d"
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
var cachedKeys;
|
|
182
|
+
var KEYS_TTL_MS = 60 * 60 * 1e3;
|
|
183
|
+
async function appleKeys(keysUrl, kid) {
|
|
184
|
+
const fresh = cachedKeys && Date.now() - cachedKeys.fetchedAt < KEYS_TTL_MS;
|
|
185
|
+
if (fresh && cachedKeys.keys.some((k) => k.kid === kid)) return cachedKeys.keys;
|
|
186
|
+
const data = await readJson(await fetch(keysUrl), "Apple keys");
|
|
187
|
+
cachedKeys = { fetchedAt: Date.now(), keys: data.keys ?? [] };
|
|
188
|
+
return cachedKeys.keys;
|
|
189
|
+
}
|
|
190
|
+
async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL) {
|
|
191
|
+
const decoded = jwt.decode(idToken, { complete: true });
|
|
192
|
+
const kid = decoded?.header.kid;
|
|
193
|
+
const key = (await appleKeys(keysUrl, kid)).find((k) => k.kid === kid);
|
|
194
|
+
if (!key) throw new Error("Apple id_token is signed with a key Apple does not publish.");
|
|
195
|
+
const pem = createPublicKey({ key, format: "jwk" }).export({ type: "spki", format: "pem" });
|
|
196
|
+
return jwt.verify(idToken, pem, { algorithms: ["RS256"], audience: clientId, issuer: ISSUER });
|
|
197
|
+
}
|
|
198
|
+
function nameFromCallback(callback) {
|
|
199
|
+
const raw = callback.user;
|
|
200
|
+
if (!raw) return void 0;
|
|
201
|
+
try {
|
|
202
|
+
const user = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
203
|
+
const full = [user.name?.firstName, user.name?.lastName].filter(Boolean).join(" ").trim();
|
|
204
|
+
return full || void 0;
|
|
205
|
+
} catch {
|
|
206
|
+
return void 0;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/auth/oauth/providers/tiktok.ts
|
|
211
|
+
function tiktokProvider(credentials = {}) {
|
|
212
|
+
return {
|
|
213
|
+
name: "tiktok",
|
|
214
|
+
clientId: credentials.clientId ?? process.env.TIKTOK_CLIENT_KEY,
|
|
215
|
+
clientSecret: credentials.clientSecret ?? process.env.TIKTOK_CLIENT_SECRET,
|
|
216
|
+
callbackUrl: credentials.callbackUrl ?? process.env.TIKTOK_CALLBACK_URL,
|
|
217
|
+
authorizeUrl: "https://www.tiktok.com/v2/auth/authorize/",
|
|
218
|
+
tokenUrl: "https://open.tiktokapis.com/v2/oauth/token/",
|
|
219
|
+
scope: credentials.scope ?? "user.info.basic",
|
|
220
|
+
clientIdParam: "client_key",
|
|
221
|
+
async fetchProfile(accessToken, tokens) {
|
|
222
|
+
const url = new URL("https://open.tiktokapis.com/v2/user/info/");
|
|
223
|
+
url.searchParams.set("fields", "open_id,display_name,avatar_url");
|
|
224
|
+
const data = await readJson(
|
|
225
|
+
await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
226
|
+
"TikTok user info"
|
|
227
|
+
);
|
|
228
|
+
const error = data.error;
|
|
229
|
+
if (error?.code && error.code !== "ok") throw new Error(`TikTok user info: ${error.code} ${error.message ?? ""}`);
|
|
230
|
+
const user = data.data?.user;
|
|
231
|
+
const openId = user?.open_id ?? tokens.open_id;
|
|
232
|
+
if (!openId) throw new Error("TikTok did not return an open_id.");
|
|
233
|
+
return {
|
|
234
|
+
providerAccountId: openId,
|
|
235
|
+
name: user?.display_name,
|
|
236
|
+
avatarUrl: user?.avatar_url
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// src/auth/oauth/providers/github.ts
|
|
243
|
+
function githubProvider(credentials = {}) {
|
|
244
|
+
return {
|
|
245
|
+
name: "github",
|
|
246
|
+
clientId: credentials.clientId ?? process.env.GITHUB_CLIENT_ID,
|
|
247
|
+
clientSecret: credentials.clientSecret ?? process.env.GITHUB_CLIENT_SECRET,
|
|
248
|
+
callbackUrl: credentials.callbackUrl ?? process.env.GITHUB_CALLBACK_URL,
|
|
249
|
+
authorizeUrl: "https://github.com/login/oauth/authorize",
|
|
250
|
+
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
251
|
+
scope: credentials.scope ?? "read:user user:email",
|
|
252
|
+
async fetchProfile(accessToken) {
|
|
253
|
+
const headers = {
|
|
254
|
+
Authorization: `Bearer ${accessToken}`,
|
|
255
|
+
Accept: "application/vnd.github+json",
|
|
256
|
+
"User-Agent": "nestkit"
|
|
257
|
+
};
|
|
258
|
+
const user = await readJson(await fetch("https://api.github.com/user", { headers }), "GitHub user");
|
|
259
|
+
const emails = await readJson(
|
|
260
|
+
await fetch("https://api.github.com/user/emails", { headers }),
|
|
261
|
+
"GitHub emails"
|
|
262
|
+
);
|
|
263
|
+
const primary = Array.isArray(emails) ? emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified) : void 0;
|
|
264
|
+
return {
|
|
265
|
+
providerAccountId: String(user.id),
|
|
266
|
+
email: primary?.email,
|
|
267
|
+
name: user.name ?? user.login ?? void 0,
|
|
268
|
+
avatarUrl: user.avatar_url
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// src/auth/oauth/providers/microsoft.ts
|
|
275
|
+
function microsoftProvider(credentials = {}) {
|
|
276
|
+
const tenant = credentials.tenant ?? process.env.MICROSOFT_TENANT ?? "common";
|
|
277
|
+
return {
|
|
278
|
+
name: "microsoft",
|
|
279
|
+
clientId: credentials.clientId ?? process.env.MICROSOFT_CLIENT_ID,
|
|
280
|
+
clientSecret: credentials.clientSecret ?? process.env.MICROSOFT_CLIENT_SECRET,
|
|
281
|
+
callbackUrl: credentials.callbackUrl ?? process.env.MICROSOFT_CALLBACK_URL,
|
|
282
|
+
authorizeUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/authorize`,
|
|
283
|
+
tokenUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`,
|
|
284
|
+
scope: credentials.scope ?? "openid profile email User.Read",
|
|
285
|
+
async fetchProfile(accessToken) {
|
|
286
|
+
const me = await readJson(
|
|
287
|
+
await fetch("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
288
|
+
"Microsoft Graph me"
|
|
289
|
+
);
|
|
290
|
+
const email = me.mail ?? me.userPrincipalName;
|
|
291
|
+
return {
|
|
292
|
+
providerAccountId: String(me.id),
|
|
293
|
+
email: email && email.includes("@") ? email : void 0,
|
|
294
|
+
name: me.displayName ?? void 0
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/auth/oauth/providers/discord.ts
|
|
301
|
+
function discordProvider(credentials = {}) {
|
|
302
|
+
return {
|
|
303
|
+
name: "discord",
|
|
304
|
+
clientId: credentials.clientId ?? process.env.DISCORD_CLIENT_ID,
|
|
305
|
+
clientSecret: credentials.clientSecret ?? process.env.DISCORD_CLIENT_SECRET,
|
|
306
|
+
callbackUrl: credentials.callbackUrl ?? process.env.DISCORD_CALLBACK_URL,
|
|
307
|
+
authorizeUrl: "https://discord.com/oauth2/authorize",
|
|
308
|
+
tokenUrl: "https://discord.com/api/oauth2/token",
|
|
309
|
+
scope: credentials.scope ?? "identify email",
|
|
310
|
+
async fetchProfile(accessToken) {
|
|
311
|
+
const user = await readJson(
|
|
312
|
+
await fetch("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
313
|
+
"Discord user"
|
|
314
|
+
);
|
|
315
|
+
const id = String(user.id);
|
|
316
|
+
const avatar = user.avatar;
|
|
317
|
+
return {
|
|
318
|
+
providerAccountId: id,
|
|
319
|
+
email: user.verified === true && typeof user.email === "string" ? user.email : void 0,
|
|
320
|
+
name: user.global_name ?? user.username ?? void 0,
|
|
321
|
+
avatarUrl: avatar ? `https://cdn.discordapp.com/avatars/${id}/${avatar}.png` : void 0
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// src/auth/oauth/providers/linkedin.ts
|
|
328
|
+
function linkedinProvider(credentials = {}) {
|
|
329
|
+
return {
|
|
330
|
+
name: "linkedin",
|
|
331
|
+
clientId: credentials.clientId ?? process.env.LINKEDIN_CLIENT_ID,
|
|
332
|
+
clientSecret: credentials.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET,
|
|
333
|
+
callbackUrl: credentials.callbackUrl ?? process.env.LINKEDIN_CALLBACK_URL,
|
|
334
|
+
authorizeUrl: "https://www.linkedin.com/oauth/v2/authorization",
|
|
335
|
+
tokenUrl: "https://www.linkedin.com/oauth/v2/accessToken",
|
|
336
|
+
scope: credentials.scope ?? "openid profile email",
|
|
337
|
+
async fetchProfile(accessToken) {
|
|
338
|
+
const claims = await readJson(
|
|
339
|
+
await fetch("https://api.linkedin.com/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
340
|
+
"LinkedIn userinfo"
|
|
341
|
+
);
|
|
342
|
+
return {
|
|
343
|
+
providerAccountId: String(claims.sub),
|
|
344
|
+
email: claims.email_verified === false ? void 0 : claims.email,
|
|
345
|
+
name: claims.name,
|
|
346
|
+
avatarUrl: claims.picture
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
};
|
|
125
350
|
}
|
|
126
351
|
|
|
127
352
|
// src/auth/oauth/oauth.options.ts
|
|
@@ -130,8 +355,12 @@ var OAUTH_STORE = /* @__PURE__ */ Symbol("OAUTH_STORE");
|
|
|
130
355
|
var REFRESH_TOKEN_STORE = /* @__PURE__ */ Symbol("REFRESH_TOKEN_STORE");
|
|
131
356
|
var MAGIC_LINK_STORE = /* @__PURE__ */ Symbol("MAGIC_LINK_STORE");
|
|
132
357
|
var MAGIC_LINK_SENDER = /* @__PURE__ */ Symbol("MAGIC_LINK_SENDER");
|
|
358
|
+
var TWO_FACTOR_STORE = /* @__PURE__ */ Symbol("TWO_FACTOR_STORE");
|
|
359
|
+
var PASSKEY_STORE = /* @__PURE__ */ Symbol("PASSKEY_STORE");
|
|
360
|
+
var WEBAUTHN = /* @__PURE__ */ Symbol("WEBAUTHN");
|
|
133
361
|
function resolveOAuthOptions(options) {
|
|
134
362
|
const webUrl = options.webUrl.replace(/\/$/, "");
|
|
363
|
+
const host = safeHost(webUrl);
|
|
135
364
|
return {
|
|
136
365
|
providers: options.providers,
|
|
137
366
|
webUrl,
|
|
@@ -150,6 +379,21 @@ function resolveOAuthOptions(options) {
|
|
|
150
379
|
linkUrl: options.magicLink?.linkUrl ?? ((token) => `${webUrl}/magic-link#token=${encodeURIComponent(token)}`),
|
|
151
380
|
invalidLinkMessage: options.magicLink?.invalidLinkMessage ?? (() => "This sign-in link is invalid or has expired. Request a new one.")
|
|
152
381
|
},
|
|
382
|
+
twoFactor: {
|
|
383
|
+
issuer: options.twoFactor?.issuer ?? host,
|
|
384
|
+
challengeTtlSeconds: options.twoFactor?.challengeTtlSeconds ?? 5 * 60,
|
|
385
|
+
backupCodes: options.twoFactor?.backupCodes ?? 10,
|
|
386
|
+
onMfaRedirect: options.twoFactor?.onMfaRedirect ?? ((challenge) => `${webUrl}/two-factor#challenge=${encodeURIComponent(challenge)}`),
|
|
387
|
+
invalidCodeMessage: options.twoFactor?.invalidCodeMessage ?? (() => "That code is not valid. Try the next one.")
|
|
388
|
+
},
|
|
389
|
+
passkeys: {
|
|
390
|
+
rpId: options.passkeys?.rpId ?? host,
|
|
391
|
+
rpName: options.passkeys?.rpName ?? options.passkeys?.rpId ?? host,
|
|
392
|
+
origins: options.passkeys?.origins ?? [webUrl],
|
|
393
|
+
challengeTtlSeconds: options.passkeys?.challengeTtlSeconds ?? 5 * 60,
|
|
394
|
+
userVerification: options.passkeys?.userVerification ?? "required",
|
|
395
|
+
invalidMessage: options.passkeys?.invalidMessage ?? (() => "The passkey could not be verified.")
|
|
396
|
+
},
|
|
153
397
|
linkCookieName: options.linkCookieName ?? "link_intent",
|
|
154
398
|
stateCookieName: options.stateCookieName ?? "oauth_state",
|
|
155
399
|
accessTtlSeconds: options.accessTtlSeconds ?? 15 * 60,
|
|
@@ -166,12 +410,114 @@ function resolveOAuthOptions(options) {
|
|
|
166
410
|
missingEmailMessage: options.missingEmailMessage ?? ((provider) => `${provider} did not share your email address, so we cannot create your account.`)
|
|
167
411
|
};
|
|
168
412
|
}
|
|
413
|
+
function safeHost(url) {
|
|
414
|
+
try {
|
|
415
|
+
return new URL(url).hostname;
|
|
416
|
+
} catch {
|
|
417
|
+
return url;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
169
420
|
|
|
170
421
|
// src/auth/oauth/oauth-auth.service.ts
|
|
171
422
|
import { Inject, Injectable, Optional, ServiceUnavailableException } from "@nestjs/common";
|
|
172
|
-
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "crypto";
|
|
173
|
-
import
|
|
423
|
+
import { createHash, randomBytes as randomBytes2, randomUUID, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
424
|
+
import jwt2 from "jsonwebtoken";
|
|
425
|
+
|
|
426
|
+
// src/auth/oauth/totp.ts
|
|
427
|
+
import { createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
428
|
+
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
429
|
+
function base32Encode(bytes) {
|
|
430
|
+
let bits = 0;
|
|
431
|
+
let value = 0;
|
|
432
|
+
let out = "";
|
|
433
|
+
for (const byte of bytes) {
|
|
434
|
+
value = value << 8 | byte;
|
|
435
|
+
bits += 8;
|
|
436
|
+
while (bits >= 5) {
|
|
437
|
+
out += ALPHABET[value >>> bits - 5 & 31];
|
|
438
|
+
bits -= 5;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (bits > 0) out += ALPHABET[value << 5 - bits & 31];
|
|
442
|
+
return out;
|
|
443
|
+
}
|
|
444
|
+
function base32Decode(text) {
|
|
445
|
+
const clean = text.toUpperCase().replace(/[^A-Z2-7]/g, "");
|
|
446
|
+
const out = [];
|
|
447
|
+
let bits = 0;
|
|
448
|
+
let value = 0;
|
|
449
|
+
for (const char of clean) {
|
|
450
|
+
value = value << 5 | ALPHABET.indexOf(char);
|
|
451
|
+
bits += 5;
|
|
452
|
+
if (bits >= 8) {
|
|
453
|
+
out.push(value >>> bits - 8 & 255);
|
|
454
|
+
bits -= 8;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return Uint8Array.from(out);
|
|
458
|
+
}
|
|
459
|
+
function generateTotpSecret() {
|
|
460
|
+
return base32Encode(randomBytes(20));
|
|
461
|
+
}
|
|
462
|
+
function hotp(secret, counter, digits = 6) {
|
|
463
|
+
const buffer = Buffer.alloc(8);
|
|
464
|
+
buffer.writeBigUInt64BE(BigInt(counter));
|
|
465
|
+
const hmac = createHmac("sha1", secret).update(buffer).digest();
|
|
466
|
+
const offset = hmac[hmac.length - 1] & 15;
|
|
467
|
+
const binary = (hmac[offset] & 127) << 24 | (hmac[offset + 1] & 255) << 16 | (hmac[offset + 2] & 255) << 8 | hmac[offset + 3] & 255;
|
|
468
|
+
return String(binary % 10 ** digits).padStart(digits, "0");
|
|
469
|
+
}
|
|
470
|
+
function totpStep(now, step = 30) {
|
|
471
|
+
return Math.floor(now / 1e3 / step);
|
|
472
|
+
}
|
|
473
|
+
function totp(secretBase32, now = Date.now(), options = {}) {
|
|
474
|
+
return hotp(base32Decode(secretBase32), totpStep(now, options.step), options.digits);
|
|
475
|
+
}
|
|
476
|
+
function verifyTotp(secretBase32, code, options = {}) {
|
|
477
|
+
const digits = options.digits ?? 6;
|
|
478
|
+
const typed = code.replace(/\s+/g, "");
|
|
479
|
+
if (!/^\d+$/.test(typed) || typed.length !== digits) return null;
|
|
480
|
+
const secret = base32Decode(secretBase32);
|
|
481
|
+
const current = totpStep(options.now ?? Date.now(), options.step);
|
|
482
|
+
const window = options.window ?? 1;
|
|
483
|
+
const typedBuffer = Buffer.from(typed);
|
|
484
|
+
for (let delta = -window; delta <= window; delta += 1) {
|
|
485
|
+
const candidate = Buffer.from(hotp(secret, current + delta, digits));
|
|
486
|
+
if (candidate.length === typedBuffer.length && timingSafeEqual(candidate, typedBuffer)) {
|
|
487
|
+
return current + delta;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
function otpauthUri(input) {
|
|
493
|
+
const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;
|
|
494
|
+
const params = new URLSearchParams({
|
|
495
|
+
secret: input.secret,
|
|
496
|
+
issuer: input.issuer,
|
|
497
|
+
algorithm: "SHA1",
|
|
498
|
+
digits: String(input.digits ?? 6),
|
|
499
|
+
period: String(input.step ?? 30)
|
|
500
|
+
});
|
|
501
|
+
return `otpauth://totp/${label}?${params.toString()}`;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// src/auth/oauth/webauthn.port.ts
|
|
505
|
+
var loaded;
|
|
506
|
+
function loadWebAuthn() {
|
|
507
|
+
loaded ??= import("@simplewebauthn/server").then((m) => ({
|
|
508
|
+
generateRegistrationOptions: m.generateRegistrationOptions,
|
|
509
|
+
verifyRegistrationResponse: m.verifyRegistrationResponse,
|
|
510
|
+
generateAuthenticationOptions: m.generateAuthenticationOptions,
|
|
511
|
+
verifyAuthenticationResponse: m.verifyAuthenticationResponse
|
|
512
|
+
}));
|
|
513
|
+
return loaded;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// src/auth/oauth/oauth-auth.service.ts
|
|
174
517
|
var MAGIC_LINK_PROVIDER = "email";
|
|
518
|
+
function isMfaChallenge(result) {
|
|
519
|
+
return "mfaRequired" in result && result.mfaRequired === true;
|
|
520
|
+
}
|
|
175
521
|
function hashToken(token) {
|
|
176
522
|
return createHash("sha256").update(token).digest("hex");
|
|
177
523
|
}
|
|
@@ -181,11 +527,14 @@ function requireSecret(explicit, envName) {
|
|
|
181
527
|
return value;
|
|
182
528
|
}
|
|
183
529
|
var OAuthAuthService = class {
|
|
184
|
-
constructor(options, store, sessions, magicLinks, magicLinkSender) {
|
|
530
|
+
constructor(options, store, sessions, magicLinks, magicLinkSender, twoFactor, passkeys, webauthnImpl) {
|
|
185
531
|
this.store = store;
|
|
186
532
|
this.sessions = sessions;
|
|
187
533
|
this.magicLinks = magicLinks;
|
|
188
534
|
this.magicLinkSender = magicLinkSender;
|
|
535
|
+
this.twoFactor = twoFactor;
|
|
536
|
+
this.passkeys = passkeys;
|
|
537
|
+
this.webauthnImpl = webauthnImpl;
|
|
189
538
|
this.options = resolveOAuthOptions(options);
|
|
190
539
|
}
|
|
191
540
|
get config() {
|
|
@@ -225,7 +574,7 @@ var OAuthAuthService = class {
|
|
|
225
574
|
authorizeUrl(name) {
|
|
226
575
|
const provider = this.provider(name);
|
|
227
576
|
const ttl = this.options.stateTtlSeconds;
|
|
228
|
-
const state =
|
|
577
|
+
const state = jwt2.sign(
|
|
229
578
|
// `nonce` makes two authorize requests within the same second produce
|
|
230
579
|
// different tokens; `typ` keeps this from being swapped with the link
|
|
231
580
|
// token, which is signed with the same secret.
|
|
@@ -251,9 +600,9 @@ var OAuthAuthService = class {
|
|
|
251
600
|
if (!received || !fromCookie) return false;
|
|
252
601
|
const a = Buffer.from(received);
|
|
253
602
|
const b = Buffer.from(fromCookie);
|
|
254
|
-
if (a.length !== b.length || !
|
|
603
|
+
if (a.length !== b.length || !timingSafeEqual2(a, b)) return false;
|
|
255
604
|
try {
|
|
256
|
-
const payload =
|
|
605
|
+
const payload = jwt2.verify(
|
|
257
606
|
received,
|
|
258
607
|
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
|
|
259
608
|
);
|
|
@@ -262,15 +611,25 @@ var OAuthAuthService = class {
|
|
|
262
611
|
return false;
|
|
263
612
|
}
|
|
264
613
|
}
|
|
265
|
-
/**
|
|
266
|
-
|
|
614
|
+
/**
|
|
615
|
+
* Exchanges the callback's `code` for a normalised profile.
|
|
616
|
+
*
|
|
617
|
+
* `callback` is whatever came back alongside the code — the query string,
|
|
618
|
+
* or the form body for a POST callback. Apple is why it is passed through:
|
|
619
|
+
* the person's name arrives there, on the first authorisation only.
|
|
620
|
+
*
|
|
621
|
+
* A profile with no email is returned as is, not rejected: whether that is
|
|
622
|
+
* a problem depends on what happens next. Linking an already-signed-in
|
|
623
|
+
* user needs none, and neither does signing in to an account linked
|
|
624
|
+
* earlier. `login` is where the absence stops things, and only when it
|
|
625
|
+
* would have to create an account from it.
|
|
626
|
+
*/
|
|
627
|
+
async profileFromCode(name, code, callback = {}) {
|
|
267
628
|
const provider = this.provider(name);
|
|
268
|
-
const
|
|
269
|
-
const profile = await provider.fetchProfile(
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
}
|
|
273
|
-
return { ...profile, email: normaliseEmail(profile.email) };
|
|
629
|
+
const tokens = await exchangeCode(provider, code);
|
|
630
|
+
const profile = await provider.fetchProfile(tokens.access_token ?? "", tokens, callback);
|
|
631
|
+
const email = profile.email ? normaliseEmail(profile.email) : void 0;
|
|
632
|
+
return { ...profile, email };
|
|
274
633
|
}
|
|
275
634
|
/**
|
|
276
635
|
* Signs someone in, creating the account the first time.
|
|
@@ -278,13 +637,17 @@ var OAuthAuthService = class {
|
|
|
278
637
|
* The provider is a parameter because the flow is identical for all of
|
|
279
638
|
* them: find the linked account, and failing that link by email to whoever
|
|
280
639
|
* is already registered. That email link is what makes signing in with
|
|
281
|
-
* Facebook today and Google tomorrow land on one account instead of two
|
|
640
|
+
* Facebook today and Google tomorrow land on one account instead of two —
|
|
641
|
+
* and why the email must be one the provider verified (see `OAuthProfile`).
|
|
282
642
|
*/
|
|
283
643
|
async login(providerName, profile) {
|
|
284
644
|
const provider = this.provider(providerName).name;
|
|
285
645
|
const existing = await this.store.findAccount(provider, profile.providerAccountId);
|
|
286
646
|
let user = existing?.user ?? null;
|
|
287
647
|
if (!user) {
|
|
648
|
+
if (!profile.email) {
|
|
649
|
+
throw new UnauthorizedAppException(this.options.missingEmailMessage(provider));
|
|
650
|
+
}
|
|
288
651
|
const email = normaliseEmail(profile.email);
|
|
289
652
|
user = await this.store.findUserByEmail(email) ?? await this.store.createUser({
|
|
290
653
|
email,
|
|
@@ -327,7 +690,7 @@ var OAuthAuthService = class {
|
|
|
327
690
|
if (!this.options.magicLink.allowSignUp && !await this.store.findUserByEmail(email)) {
|
|
328
691
|
return;
|
|
329
692
|
}
|
|
330
|
-
const token =
|
|
693
|
+
const token = randomBytes2(32).toString("base64url");
|
|
331
694
|
const expiresAt = new Date(Date.now() + this.options.magicLink.ttlSeconds * 1e3);
|
|
332
695
|
await store.create(hashToken(token), email, expiresAt);
|
|
333
696
|
await sender.send({ email, url: this.options.magicLink.linkUrl(token), expiresAt });
|
|
@@ -366,17 +729,346 @@ var OAuthAuthService = class {
|
|
|
366
729
|
return { store: this.magicLinks, sender: this.magicLinkSender };
|
|
367
730
|
}
|
|
368
731
|
/**
|
|
369
|
-
* The one place a session is opened. Every sign-in — OAuth
|
|
370
|
-
* ends here, so `singleSession
|
|
371
|
-
*
|
|
732
|
+
* The one place a session is opened. Every sign-in — OAuth, magic link,
|
|
733
|
+
* passkey, a second factor just passed — ends here, so `singleSession`,
|
|
734
|
+
* the token pair and the second-factor rule behave identically whichever
|
|
735
|
+
* door was used.
|
|
736
|
+
*
|
|
737
|
+
* `strong` says the door already verified the person beyond a shared
|
|
738
|
+
* secret: a passkey (the device checked their face or finger) or the
|
|
739
|
+
* second factor itself. Anything else, for an account with 2FA confirmed,
|
|
740
|
+
* gets a challenge instead of a session.
|
|
372
741
|
*/
|
|
373
|
-
async establishSession(user) {
|
|
742
|
+
async establishSession(user, options = {}) {
|
|
743
|
+
if (!options.strong && await this.hasSecondFactor(user.id)) {
|
|
744
|
+
return this.issueMfaChallenge(user.id);
|
|
745
|
+
}
|
|
374
746
|
if (this.options.singleSession) {
|
|
375
747
|
await this.sessions.revokeAllForUser(user.id);
|
|
376
748
|
}
|
|
377
749
|
const tokens = await this.issueTokenPair(user);
|
|
378
750
|
return { user: this.present(user), ...tokens };
|
|
379
751
|
}
|
|
752
|
+
// ---------------------------------------------------------------------
|
|
753
|
+
// Second factor (TOTP)
|
|
754
|
+
// ---------------------------------------------------------------------
|
|
755
|
+
async twoFactorStatus(userId) {
|
|
756
|
+
const record = await this.requireTwoFactor().get(userId);
|
|
757
|
+
const enabled = Boolean(record?.confirmedAt);
|
|
758
|
+
return { enabled, backupCodesLeft: enabled ? record.backupCodeHashes.length : 0 };
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Starts enrolment: a fresh secret, parked unconfirmed, and the URI the
|
|
762
|
+
* QR code encodes. Nothing changes for sign-in until `twoFactorConfirm`
|
|
763
|
+
* sees a code from the app — a person who scans and closes the tab must
|
|
764
|
+
* not be locked out of an account whose second factor they never finished.
|
|
765
|
+
*/
|
|
766
|
+
async twoFactorSetup(userId) {
|
|
767
|
+
const store = this.requireTwoFactor();
|
|
768
|
+
const existing = await store.get(userId);
|
|
769
|
+
if (existing?.confirmedAt) {
|
|
770
|
+
throw new ValidationAppException("Two-factor authentication is already enabled.", void 0, "TWO_FACTOR_ALREADY_ENABLED");
|
|
771
|
+
}
|
|
772
|
+
const user = await this.store.findUserById(userId);
|
|
773
|
+
if (!user) throw new UnauthorizedAppException("User not found.");
|
|
774
|
+
const secret = generateTotpSecret();
|
|
775
|
+
await store.set(userId, { secret, confirmedAt: null, backupCodeHashes: [], lastStep: null });
|
|
776
|
+
return {
|
|
777
|
+
secret,
|
|
778
|
+
otpauthUri: otpauthUri({ issuer: this.options.twoFactor.issuer, account: user.email, secret })
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
/** Turns the pending secret on, once a code proves the app has it. Hands out the backup codes — the only time they are readable. */
|
|
782
|
+
async twoFactorConfirm(userId, code) {
|
|
783
|
+
const store = this.requireTwoFactor();
|
|
784
|
+
const record = await store.get(userId);
|
|
785
|
+
if (!record || record.confirmedAt) throw this.invalidCode();
|
|
786
|
+
const step = verifyTotp(record.secret, code);
|
|
787
|
+
if (step === null || !await store.claimStep(userId, step)) throw this.invalidCode();
|
|
788
|
+
const backupCodes = Array.from({ length: this.options.twoFactor.backupCodes }, () => makeBackupCode());
|
|
789
|
+
await store.set(userId, {
|
|
790
|
+
...record,
|
|
791
|
+
confirmedAt: /* @__PURE__ */ new Date(),
|
|
792
|
+
lastStep: step,
|
|
793
|
+
backupCodeHashes: backupCodes.map(hashBackupCode)
|
|
794
|
+
});
|
|
795
|
+
return { backupCodes };
|
|
796
|
+
}
|
|
797
|
+
/** Off, but only for whoever can still produce a code or a backup code. */
|
|
798
|
+
async twoFactorDisable(userId, code) {
|
|
799
|
+
await this.checkSecondFactor(userId, code);
|
|
800
|
+
await this.requireTwoFactor().delete(userId);
|
|
801
|
+
}
|
|
802
|
+
/** Completes a sign-in that stopped at {@link MfaChallenge}. */
|
|
803
|
+
async verifyMfa(challenge, code) {
|
|
804
|
+
let userId;
|
|
805
|
+
try {
|
|
806
|
+
const payload = jwt2.verify(challenge, requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"));
|
|
807
|
+
if (payload.typ !== "mfa" || !payload.sub) throw new Error("wrong typ");
|
|
808
|
+
userId = payload.sub;
|
|
809
|
+
} catch {
|
|
810
|
+
throw this.invalidCode();
|
|
811
|
+
}
|
|
812
|
+
await this.checkSecondFactor(userId, code);
|
|
813
|
+
const user = await this.store.findUserById(userId);
|
|
814
|
+
if (!user) throw this.invalidCode();
|
|
815
|
+
return await this.establishSession(user, { strong: true });
|
|
816
|
+
}
|
|
817
|
+
async hasSecondFactor(userId) {
|
|
818
|
+
if (!this.twoFactor) return false;
|
|
819
|
+
const record = await this.twoFactor.get(userId);
|
|
820
|
+
return Boolean(record?.confirmedAt);
|
|
821
|
+
}
|
|
822
|
+
issueMfaChallenge(userId) {
|
|
823
|
+
const ttl = this.options.twoFactor.challengeTtlSeconds;
|
|
824
|
+
const challenge = jwt2.sign(
|
|
825
|
+
{ typ: "mfa", sub: userId, nonce: randomUUID() },
|
|
826
|
+
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
|
|
827
|
+
{ expiresIn: ttl }
|
|
828
|
+
);
|
|
829
|
+
return { mfaRequired: true, challenge, expiresAt: new Date(Date.now() + ttl * 1e3) };
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* A TOTP code, or failing that a backup code. Each accepted once: the step
|
|
833
|
+
* is claimed and the backup code consumed atomically, so a code seen over
|
|
834
|
+
* a shoulder is spent by whoever typed it first.
|
|
835
|
+
*/
|
|
836
|
+
async checkSecondFactor(userId, code) {
|
|
837
|
+
const store = this.requireTwoFactor();
|
|
838
|
+
const record = await store.get(userId);
|
|
839
|
+
if (!record?.confirmedAt) throw this.invalidCode();
|
|
840
|
+
const step = verifyTotp(record.secret, code);
|
|
841
|
+
if (step !== null) {
|
|
842
|
+
if (!await store.claimStep(userId, step)) throw this.invalidCode();
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
if (await store.consumeBackupCode(userId, hashBackupCode(code))) return;
|
|
846
|
+
throw this.invalidCode();
|
|
847
|
+
}
|
|
848
|
+
invalidCode() {
|
|
849
|
+
return new UnauthorizedAppException(this.options.twoFactor.invalidCodeMessage(), void 0, "TWO_FACTOR_INVALID");
|
|
850
|
+
}
|
|
851
|
+
requireTwoFactor() {
|
|
852
|
+
if (!this.twoFactor) throw new ServiceUnavailableException(this.options.unavailableMessage("two-factor"));
|
|
853
|
+
return this.twoFactor;
|
|
854
|
+
}
|
|
855
|
+
// ---------------------------------------------------------------------
|
|
856
|
+
// Passkeys (WebAuthn)
|
|
857
|
+
// ---------------------------------------------------------------------
|
|
858
|
+
/**
|
|
859
|
+
* Options for `navigator.credentials.create()`, and the token that ties
|
|
860
|
+
* the answer back to this challenge.
|
|
861
|
+
*
|
|
862
|
+
* `residentKey: 'required'` is not negotiable. A discoverable credential
|
|
863
|
+
* is what iCloud Keychain stores and syncs reliably — a non-discoverable
|
|
864
|
+
* one made iOS answer "no passkeys for this site" on the next open — and
|
|
865
|
+
* it is the only kind the browser can offer in the username field's
|
|
866
|
+
* autofill, which is the sign-in experience passkeys exist for.
|
|
867
|
+
*/
|
|
868
|
+
async passkeyRegistrationOptions(userId) {
|
|
869
|
+
const store = this.requirePasskeys();
|
|
870
|
+
const user = await this.store.findUserById(userId);
|
|
871
|
+
if (!user) throw new UnauthorizedAppException("User not found.");
|
|
872
|
+
const webauthn = await this.webauthn();
|
|
873
|
+
const { rpId, rpName, userVerification, challengeTtlSeconds } = this.options.passkeys;
|
|
874
|
+
const existing = await store.listByUser(userId);
|
|
875
|
+
const options = await webauthn.generateRegistrationOptions({
|
|
876
|
+
rpName,
|
|
877
|
+
rpID: rpId,
|
|
878
|
+
userName: user.email,
|
|
879
|
+
userDisplayName: user.name ?? user.email,
|
|
880
|
+
userID: new Uint8Array(Buffer.from(userId)),
|
|
881
|
+
attestationType: "none",
|
|
882
|
+
timeout: challengeTtlSeconds * 1e3,
|
|
883
|
+
excludeCredentials: existing.map((p) => ({ id: p.id, transports: p.transports })),
|
|
884
|
+
authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification }
|
|
885
|
+
});
|
|
886
|
+
return { options, token: this.signChallenge("webauthn-register", options.challenge, userId) };
|
|
887
|
+
}
|
|
888
|
+
/** Verifies the authenticator's answer and keeps the public key. */
|
|
889
|
+
async passkeyRegister(userId, token, response, name) {
|
|
890
|
+
const store = this.requirePasskeys();
|
|
891
|
+
const challenge = this.readChallenge("webauthn-register", token, userId);
|
|
892
|
+
const webauthn = await this.webauthn();
|
|
893
|
+
const { rpId, origins, userVerification } = this.options.passkeys;
|
|
894
|
+
let verification;
|
|
895
|
+
try {
|
|
896
|
+
verification = await webauthn.verifyRegistrationResponse({
|
|
897
|
+
response,
|
|
898
|
+
expectedChallenge: challenge,
|
|
899
|
+
expectedOrigin: origins,
|
|
900
|
+
expectedRPID: rpId,
|
|
901
|
+
requireUserVerification: userVerification === "required"
|
|
902
|
+
});
|
|
903
|
+
} catch {
|
|
904
|
+
throw this.invalidPasskey();
|
|
905
|
+
}
|
|
906
|
+
if (!verification.verified) throw this.invalidPasskey();
|
|
907
|
+
const { credential, credentialDeviceType, credentialBackedUp } = verification.registrationInfo;
|
|
908
|
+
const passkey = {
|
|
909
|
+
id: credential.id,
|
|
910
|
+
userId,
|
|
911
|
+
publicKey: Buffer.from(credential.publicKey).toString("base64url"),
|
|
912
|
+
counter: credential.counter,
|
|
913
|
+
transports: credential.transports,
|
|
914
|
+
deviceType: credentialDeviceType,
|
|
915
|
+
backedUp: credentialBackedUp,
|
|
916
|
+
name: name?.trim() || null,
|
|
917
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
918
|
+
lastUsedAt: null
|
|
919
|
+
};
|
|
920
|
+
await store.create(passkey);
|
|
921
|
+
return summarise(passkey);
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Options for `navigator.credentials.get()`.
|
|
925
|
+
*
|
|
926
|
+
* With no email — the usual case — `allowCredentials` is empty and the
|
|
927
|
+
* browser offers whatever discoverable passkeys it holds for this site,
|
|
928
|
+
* including in the username field's autofill (`mediation: 'conditional'`
|
|
929
|
+
* on the client). With one, the known credentials are listed, which some
|
|
930
|
+
* platforms use to go straight to the biometric prompt. An unknown email
|
|
931
|
+
* gets the same empty list as no email, so nothing reveals which is which.
|
|
932
|
+
*/
|
|
933
|
+
async passkeyAuthenticationOptions(email) {
|
|
934
|
+
const store = this.requirePasskeys();
|
|
935
|
+
const webauthn = await this.webauthn();
|
|
936
|
+
const { rpId, userVerification, challengeTtlSeconds } = this.options.passkeys;
|
|
937
|
+
let allowCredentials = [];
|
|
938
|
+
if (email) {
|
|
939
|
+
const user = await this.store.findUserByEmail(normaliseEmail(email));
|
|
940
|
+
if (user) {
|
|
941
|
+
allowCredentials = (await store.listByUser(user.id)).map((p) => ({ id: p.id, transports: p.transports }));
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
const options = await webauthn.generateAuthenticationOptions({
|
|
945
|
+
rpID: rpId,
|
|
946
|
+
userVerification,
|
|
947
|
+
timeout: challengeTtlSeconds * 1e3,
|
|
948
|
+
allowCredentials
|
|
949
|
+
});
|
|
950
|
+
return { options, token: this.signChallenge("webauthn-login", options.challenge) };
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Signs in with the authenticator's answer. The credential id in the
|
|
954
|
+
* answer says who; the signature over the challenge proves it.
|
|
955
|
+
*
|
|
956
|
+
* The counter is persisted only when it moved. Synced passkeys report 0
|
|
957
|
+
* forever, and a store that insists on "greater than before" would refuse
|
|
958
|
+
* every one of them — which is how a passkey sign-in "randomly" breaks on
|
|
959
|
+
* iPhones. The library already rejects a counter that went backwards on
|
|
960
|
+
* hardware that does count, which is the actual clone signal.
|
|
961
|
+
*/
|
|
962
|
+
async passkeyLogin(token, response) {
|
|
963
|
+
const challenge = this.readChallenge("webauthn-login", token);
|
|
964
|
+
const passkey = await this.verifyPasskeyAnswer(challenge, response);
|
|
965
|
+
const user = await this.store.findUserById(passkey.userId);
|
|
966
|
+
if (!user) throw this.invalidPasskey();
|
|
967
|
+
return await this.establishSession(user, { strong: true });
|
|
968
|
+
}
|
|
969
|
+
/** The verification both sign-in and unlock share: the credential named in the answer, checked against the challenge, counter touched. */
|
|
970
|
+
async verifyPasskeyAnswer(challenge, response) {
|
|
971
|
+
const store = this.requirePasskeys();
|
|
972
|
+
const passkey = await store.findById(response.id);
|
|
973
|
+
if (!passkey) throw this.invalidPasskey();
|
|
974
|
+
const webauthn = await this.webauthn();
|
|
975
|
+
const { rpId, origins, userVerification } = this.options.passkeys;
|
|
976
|
+
let verification;
|
|
977
|
+
try {
|
|
978
|
+
verification = await webauthn.verifyAuthenticationResponse({
|
|
979
|
+
response,
|
|
980
|
+
expectedChallenge: challenge,
|
|
981
|
+
expectedOrigin: origins,
|
|
982
|
+
expectedRPID: rpId,
|
|
983
|
+
requireUserVerification: userVerification === "required",
|
|
984
|
+
credential: {
|
|
985
|
+
id: passkey.id,
|
|
986
|
+
publicKey: new Uint8Array(Buffer.from(passkey.publicKey, "base64url")),
|
|
987
|
+
counter: passkey.counter,
|
|
988
|
+
transports: passkey.transports
|
|
989
|
+
}
|
|
990
|
+
});
|
|
991
|
+
} catch {
|
|
992
|
+
throw this.invalidPasskey();
|
|
993
|
+
}
|
|
994
|
+
if (!verification.verified) throw this.invalidPasskey();
|
|
995
|
+
const { newCounter } = verification.authenticationInfo;
|
|
996
|
+
await store.touch(passkey.id, newCounter > passkey.counter ? newCounter : passkey.counter, /* @__PURE__ */ new Date());
|
|
997
|
+
return passkey;
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Options to re-verify the signed-in person — a lock screen over a session
|
|
1001
|
+
* that never expires, opened with Face ID when the app comes back.
|
|
1002
|
+
*
|
|
1003
|
+
* Not `passkeyAuthenticationOptions`: the user is known, so their own
|
|
1004
|
+
* credentials are listed (some platforms then go straight to the biometric
|
|
1005
|
+
* prompt), and the token is bound to them so an unlock answer can never be
|
|
1006
|
+
* replayed as somebody else's.
|
|
1007
|
+
*/
|
|
1008
|
+
async passkeyUnlockOptions(userId) {
|
|
1009
|
+
const store = this.requirePasskeys();
|
|
1010
|
+
const webauthn = await this.webauthn();
|
|
1011
|
+
const { rpId, userVerification, challengeTtlSeconds } = this.options.passkeys;
|
|
1012
|
+
const options = await webauthn.generateAuthenticationOptions({
|
|
1013
|
+
rpID: rpId,
|
|
1014
|
+
userVerification,
|
|
1015
|
+
timeout: challengeTtlSeconds * 1e3,
|
|
1016
|
+
allowCredentials: (await store.listByUser(userId)).map((p) => ({ id: p.id, transports: p.transports }))
|
|
1017
|
+
});
|
|
1018
|
+
return { options, token: this.signChallenge("webauthn-unlock", options.challenge, userId) };
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Verifies an unlock answer. Opens no session and rotates no token: the
|
|
1022
|
+
* session the person already has stays exactly as it was, and the answer
|
|
1023
|
+
* is only accepted for a passkey that belongs to them.
|
|
1024
|
+
*/
|
|
1025
|
+
async passkeyUnlock(userId, token, response) {
|
|
1026
|
+
const challenge = this.readChallenge("webauthn-unlock", token, userId);
|
|
1027
|
+
const passkey = await this.verifyPasskeyAnswer(challenge, response);
|
|
1028
|
+
if (passkey.userId !== userId) throw this.invalidPasskey();
|
|
1029
|
+
return { ok: true, passkeyId: passkey.id };
|
|
1030
|
+
}
|
|
1031
|
+
async listPasskeys(userId) {
|
|
1032
|
+
return (await this.requirePasskeys().listByUser(userId)).map(summarise);
|
|
1033
|
+
}
|
|
1034
|
+
async deletePasskey(userId, id) {
|
|
1035
|
+
if (!await this.requirePasskeys().delete(id, userId)) {
|
|
1036
|
+
throw new NotFoundAppException("Passkey not found.", void 0, "PASSKEY_NOT_FOUND");
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
webauthn() {
|
|
1040
|
+
return this.webauthnImpl ? Promise.resolve(this.webauthnImpl) : loadWebAuthn();
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* The challenge travels signed, not stored: no table, no cleanup, and it
|
|
1044
|
+
* expires by itself — the same reasoning as the OAuth `state`. `typ` keeps
|
|
1045
|
+
* a registration token from passing as a sign-in one, and `sub` ties a
|
|
1046
|
+
* registration to the account that asked for it.
|
|
1047
|
+
*/
|
|
1048
|
+
signChallenge(typ, challenge, userId) {
|
|
1049
|
+
return jwt2.sign(
|
|
1050
|
+
{ typ, challenge, ...userId ? { sub: userId } : {} },
|
|
1051
|
+
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
|
|
1052
|
+
{ expiresIn: this.options.passkeys.challengeTtlSeconds }
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
readChallenge(typ, token, userId) {
|
|
1056
|
+
try {
|
|
1057
|
+
const payload = jwt2.verify(token, requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"));
|
|
1058
|
+
if (payload.typ !== typ || !payload.challenge) throw new Error("wrong typ");
|
|
1059
|
+
if (userId !== void 0 && payload.sub !== userId) throw new Error("wrong user");
|
|
1060
|
+
return payload.challenge;
|
|
1061
|
+
} catch {
|
|
1062
|
+
throw this.invalidPasskey();
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
invalidPasskey() {
|
|
1066
|
+
return new UnauthorizedAppException(this.options.passkeys.invalidMessage(), void 0, "PASSKEY_INVALID");
|
|
1067
|
+
}
|
|
1068
|
+
requirePasskeys() {
|
|
1069
|
+
if (!this.passkeys) throw new ServiceUnavailableException(this.options.unavailableMessage("passkeys"));
|
|
1070
|
+
return this.passkeys;
|
|
1071
|
+
}
|
|
380
1072
|
/**
|
|
381
1073
|
* Rotates a refresh token: the old one is spent, a new pair comes back.
|
|
382
1074
|
*
|
|
@@ -412,7 +1104,7 @@ var OAuthAuthService = class {
|
|
|
412
1104
|
*/
|
|
413
1105
|
issueLinkToken(userId) {
|
|
414
1106
|
const ttl = this.options.linkTtlSeconds;
|
|
415
|
-
const token =
|
|
1107
|
+
const token = jwt2.sign(
|
|
416
1108
|
{ sub: userId, typ: "link" },
|
|
417
1109
|
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
|
|
418
1110
|
{ expiresIn: ttl }
|
|
@@ -428,7 +1120,7 @@ var OAuthAuthService = class {
|
|
|
428
1120
|
readLinkToken(token) {
|
|
429
1121
|
if (!token) return null;
|
|
430
1122
|
try {
|
|
431
|
-
const payload =
|
|
1123
|
+
const payload = jwt2.verify(
|
|
432
1124
|
token,
|
|
433
1125
|
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
|
|
434
1126
|
);
|
|
@@ -494,12 +1186,12 @@ var OAuthAuthService = class {
|
|
|
494
1186
|
return this.options.mapUser ? this.options.mapUser(user) : user;
|
|
495
1187
|
}
|
|
496
1188
|
async issueTokenPair(user) {
|
|
497
|
-
const accessToken =
|
|
1189
|
+
const accessToken = jwt2.sign(
|
|
498
1190
|
{ sub: user.id, email: user.email },
|
|
499
1191
|
requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
|
|
500
1192
|
{ expiresIn: this.options.accessTtlSeconds }
|
|
501
1193
|
);
|
|
502
|
-
const refreshToken =
|
|
1194
|
+
const refreshToken = jwt2.sign(
|
|
503
1195
|
// The jti keeps two tokens minted for the same user in the same second
|
|
504
1196
|
// from coming out byte-identical — a JWT is deterministic given the
|
|
505
1197
|
// same payload and secret, and identical tokens collide on the unique
|
|
@@ -514,7 +1206,7 @@ var OAuthAuthService = class {
|
|
|
514
1206
|
}
|
|
515
1207
|
verifyRefresh(token) {
|
|
516
1208
|
try {
|
|
517
|
-
return
|
|
1209
|
+
return jwt2.verify(
|
|
518
1210
|
token,
|
|
519
1211
|
requireSecret(this.options.refreshSecret, "JWT_REFRESH_SECRET")
|
|
520
1212
|
);
|
|
@@ -531,11 +1223,34 @@ OAuthAuthService = __decorateClass([
|
|
|
531
1223
|
__decorateParam(3, Optional()),
|
|
532
1224
|
__decorateParam(3, Inject(MAGIC_LINK_STORE)),
|
|
533
1225
|
__decorateParam(4, Optional()),
|
|
534
|
-
__decorateParam(4, Inject(MAGIC_LINK_SENDER))
|
|
1226
|
+
__decorateParam(4, Inject(MAGIC_LINK_SENDER)),
|
|
1227
|
+
__decorateParam(5, Optional()),
|
|
1228
|
+
__decorateParam(5, Inject(TWO_FACTOR_STORE)),
|
|
1229
|
+
__decorateParam(6, Optional()),
|
|
1230
|
+
__decorateParam(6, Inject(PASSKEY_STORE)),
|
|
1231
|
+
__decorateParam(7, Optional()),
|
|
1232
|
+
__decorateParam(7, Inject(WEBAUTHN))
|
|
535
1233
|
], OAuthAuthService);
|
|
536
1234
|
function normaliseEmail(email) {
|
|
537
1235
|
return email.trim().toLowerCase();
|
|
538
1236
|
}
|
|
1237
|
+
function makeBackupCode() {
|
|
1238
|
+
const raw = base32Encode(randomBytes2(5)).toLowerCase();
|
|
1239
|
+
return `${raw.slice(0, 4)}-${raw.slice(4, 8)}`;
|
|
1240
|
+
}
|
|
1241
|
+
function hashBackupCode(code) {
|
|
1242
|
+
return createHash("sha256").update(code.replace(/[^a-z0-9]/gi, "").toUpperCase()).digest("hex");
|
|
1243
|
+
}
|
|
1244
|
+
function summarise(passkey) {
|
|
1245
|
+
return {
|
|
1246
|
+
id: passkey.id,
|
|
1247
|
+
name: passkey.name ?? null,
|
|
1248
|
+
deviceType: passkey.deviceType,
|
|
1249
|
+
backedUp: passkey.backedUp,
|
|
1250
|
+
createdAt: passkey.createdAt,
|
|
1251
|
+
lastUsedAt: passkey.lastUsedAt ?? null
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
539
1254
|
|
|
540
1255
|
// src/auth/oauth/memory-magic-link.store.ts
|
|
541
1256
|
var MemoryMagicLinkStore = class {
|
|
@@ -558,8 +1273,63 @@ var MemoryMagicLinkStore = class {
|
|
|
558
1273
|
}
|
|
559
1274
|
};
|
|
560
1275
|
|
|
1276
|
+
// src/auth/oauth/memory-security.stores.ts
|
|
1277
|
+
var MemoryTwoFactorStore = class {
|
|
1278
|
+
constructor() {
|
|
1279
|
+
this.records = /* @__PURE__ */ new Map();
|
|
1280
|
+
}
|
|
1281
|
+
async get(userId) {
|
|
1282
|
+
const record = this.records.get(userId);
|
|
1283
|
+
return record ? { ...record, backupCodeHashes: [...record.backupCodeHashes] } : null;
|
|
1284
|
+
}
|
|
1285
|
+
async set(userId, record) {
|
|
1286
|
+
this.records.set(userId, { ...record, backupCodeHashes: [...record.backupCodeHashes] });
|
|
1287
|
+
}
|
|
1288
|
+
async delete(userId) {
|
|
1289
|
+
this.records.delete(userId);
|
|
1290
|
+
}
|
|
1291
|
+
async claimStep(userId, step) {
|
|
1292
|
+
const record = this.records.get(userId);
|
|
1293
|
+
if (!record || record.lastStep !== null && step <= record.lastStep) return false;
|
|
1294
|
+
record.lastStep = step;
|
|
1295
|
+
return true;
|
|
1296
|
+
}
|
|
1297
|
+
async consumeBackupCode(userId, hash) {
|
|
1298
|
+
const record = this.records.get(userId);
|
|
1299
|
+
const index = record?.backupCodeHashes.indexOf(hash) ?? -1;
|
|
1300
|
+
if (!record || index === -1) return false;
|
|
1301
|
+
record.backupCodeHashes.splice(index, 1);
|
|
1302
|
+
return true;
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
var MemoryPasskeyStore = class {
|
|
1306
|
+
constructor() {
|
|
1307
|
+
this.passkeys = /* @__PURE__ */ new Map();
|
|
1308
|
+
}
|
|
1309
|
+
async listByUser(userId) {
|
|
1310
|
+
return [...this.passkeys.values()].filter((p) => p.userId === userId).map((p) => ({ ...p }));
|
|
1311
|
+
}
|
|
1312
|
+
async findById(id) {
|
|
1313
|
+
const found = this.passkeys.get(id);
|
|
1314
|
+
return found ? { ...found } : null;
|
|
1315
|
+
}
|
|
1316
|
+
async create(passkey) {
|
|
1317
|
+
this.passkeys.set(passkey.id, { ...passkey });
|
|
1318
|
+
}
|
|
1319
|
+
async touch(id, counter, lastUsedAt) {
|
|
1320
|
+
const found = this.passkeys.get(id);
|
|
1321
|
+
if (found) Object.assign(found, { counter, lastUsedAt });
|
|
1322
|
+
}
|
|
1323
|
+
async delete(id, userId) {
|
|
1324
|
+
const found = this.passkeys.get(id);
|
|
1325
|
+
if (!found || found.userId !== userId) return false;
|
|
1326
|
+
this.passkeys.delete(id);
|
|
1327
|
+
return true;
|
|
1328
|
+
}
|
|
1329
|
+
};
|
|
1330
|
+
|
|
561
1331
|
// src/auth/oauth/magic-link.dto.ts
|
|
562
|
-
import { IsEmail, IsString, MinLength } from "class-validator";
|
|
1332
|
+
import { IsEmail, IsObject, IsOptional, IsString, MinLength } from "class-validator";
|
|
563
1333
|
var MagicLinkRequestDto = class {
|
|
564
1334
|
};
|
|
565
1335
|
__decorateClass([
|
|
@@ -571,6 +1341,50 @@ __decorateClass([
|
|
|
571
1341
|
IsString(),
|
|
572
1342
|
MinLength(16)
|
|
573
1343
|
], MagicLinkVerifyDto.prototype, "token", 2);
|
|
1344
|
+
var TwoFactorCodeDto = class {
|
|
1345
|
+
};
|
|
1346
|
+
__decorateClass([
|
|
1347
|
+
IsString(),
|
|
1348
|
+
MinLength(6)
|
|
1349
|
+
], TwoFactorCodeDto.prototype, "code", 2);
|
|
1350
|
+
var MfaVerifyDto = class {
|
|
1351
|
+
};
|
|
1352
|
+
__decorateClass([
|
|
1353
|
+
IsString(),
|
|
1354
|
+
MinLength(16)
|
|
1355
|
+
], MfaVerifyDto.prototype, "challenge", 2);
|
|
1356
|
+
__decorateClass([
|
|
1357
|
+
IsString(),
|
|
1358
|
+
MinLength(6)
|
|
1359
|
+
], MfaVerifyDto.prototype, "code", 2);
|
|
1360
|
+
var PasskeyRegisterDto = class {
|
|
1361
|
+
};
|
|
1362
|
+
__decorateClass([
|
|
1363
|
+
IsString(),
|
|
1364
|
+
MinLength(16)
|
|
1365
|
+
], PasskeyRegisterDto.prototype, "token", 2);
|
|
1366
|
+
__decorateClass([
|
|
1367
|
+
IsObject()
|
|
1368
|
+
], PasskeyRegisterDto.prototype, "response", 2);
|
|
1369
|
+
__decorateClass([
|
|
1370
|
+
IsOptional(),
|
|
1371
|
+
IsString()
|
|
1372
|
+
], PasskeyRegisterDto.prototype, "name", 2);
|
|
1373
|
+
var PasskeyLoginOptionsDto = class {
|
|
1374
|
+
};
|
|
1375
|
+
__decorateClass([
|
|
1376
|
+
IsOptional(),
|
|
1377
|
+
IsEmail()
|
|
1378
|
+
], PasskeyLoginOptionsDto.prototype, "email", 2);
|
|
1379
|
+
var PasskeyLoginDto = class {
|
|
1380
|
+
};
|
|
1381
|
+
__decorateClass([
|
|
1382
|
+
IsString(),
|
|
1383
|
+
MinLength(16)
|
|
1384
|
+
], PasskeyLoginDto.prototype, "token", 2);
|
|
1385
|
+
__decorateClass([
|
|
1386
|
+
IsObject()
|
|
1387
|
+
], PasskeyLoginDto.prototype, "response", 2);
|
|
574
1388
|
|
|
575
1389
|
// src/auth/oauth/oauth-callback.filter.ts
|
|
576
1390
|
import {
|
|
@@ -619,6 +1433,7 @@ OAuthCallbackFilter = __decorateClass([
|
|
|
619
1433
|
import {
|
|
620
1434
|
Body,
|
|
621
1435
|
Controller,
|
|
1436
|
+
Delete,
|
|
622
1437
|
Get,
|
|
623
1438
|
Inject as Inject3,
|
|
624
1439
|
Param,
|
|
@@ -659,8 +1474,10 @@ function createOAuthController(options = {}) {
|
|
|
659
1474
|
}
|
|
660
1475
|
linkIntent(user, reply) {
|
|
661
1476
|
const { token, expiresAt } = this.auth.issueLinkToken(userId(user));
|
|
1477
|
+
const anyPost = this.auth.config.providers.some((p) => p.callbackMethod === "POST");
|
|
662
1478
|
setCookie(reply, this.auth.config.linkCookieName, token, {
|
|
663
1479
|
...this.cookieBase(),
|
|
1480
|
+
...anyPost ? { sameSite: "none", secure: true } : {},
|
|
664
1481
|
expires: expiresAt
|
|
665
1482
|
});
|
|
666
1483
|
return { ok: true };
|
|
@@ -670,27 +1487,70 @@ function createOAuthController(options = {}) {
|
|
|
670
1487
|
return { ok: true };
|
|
671
1488
|
}
|
|
672
1489
|
async verifyMagicLink(body, reply) {
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
this.
|
|
677
|
-
|
|
1490
|
+
return this.answerSignIn(await this.auth.magicLinkLogin(body.token), reply);
|
|
1491
|
+
}
|
|
1492
|
+
async verifyMfa(body, reply) {
|
|
1493
|
+
return this.answerSignIn(await this.auth.verifyMfa(body.challenge, body.code), reply);
|
|
1494
|
+
}
|
|
1495
|
+
twoFactorStatus(user) {
|
|
1496
|
+
return this.auth.twoFactorStatus(userId(user));
|
|
1497
|
+
}
|
|
1498
|
+
twoFactorSetup(user) {
|
|
1499
|
+
return this.auth.twoFactorSetup(userId(user));
|
|
1500
|
+
}
|
|
1501
|
+
twoFactorConfirm(user, body) {
|
|
1502
|
+
return this.auth.twoFactorConfirm(userId(user), body.code);
|
|
1503
|
+
}
|
|
1504
|
+
async twoFactorDisable(user, body) {
|
|
1505
|
+
await this.auth.twoFactorDisable(userId(user), body.code);
|
|
1506
|
+
return { ok: true };
|
|
1507
|
+
}
|
|
1508
|
+
passkeyRegistrationOptions(user) {
|
|
1509
|
+
return this.auth.passkeyRegistrationOptions(userId(user));
|
|
1510
|
+
}
|
|
1511
|
+
passkeyRegister(user, body) {
|
|
1512
|
+
return this.auth.passkeyRegister(userId(user), body.token, body.response, body.name);
|
|
1513
|
+
}
|
|
1514
|
+
passkeyUnlockOptions(user) {
|
|
1515
|
+
return this.auth.passkeyUnlockOptions(userId(user));
|
|
1516
|
+
}
|
|
1517
|
+
passkeyUnlock(user, body) {
|
|
1518
|
+
return this.auth.passkeyUnlock(userId(user), body.token, body.response);
|
|
1519
|
+
}
|
|
1520
|
+
listPasskeys(user) {
|
|
1521
|
+
return this.auth.listPasskeys(userId(user));
|
|
1522
|
+
}
|
|
1523
|
+
async deletePasskey(user, id) {
|
|
1524
|
+
await this.auth.deletePasskey(userId(user), id);
|
|
1525
|
+
return { ok: true };
|
|
1526
|
+
}
|
|
1527
|
+
passkeyLoginOptions(body) {
|
|
1528
|
+
return this.auth.passkeyAuthenticationOptions(body?.email);
|
|
1529
|
+
}
|
|
1530
|
+
async passkeyLogin(body, reply) {
|
|
1531
|
+
return this.answerSignIn(await this.auth.passkeyLogin(body.token, body.response), reply);
|
|
678
1532
|
}
|
|
679
1533
|
async magicLinkCallback(token, reply) {
|
|
680
1534
|
if (!token) throw new UnauthorizedAppException(this.auth.config.magicLink.invalidLinkMessage());
|
|
681
|
-
|
|
682
|
-
this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
|
|
683
|
-
redirect(reply, this.auth.config.onLoginRedirect(accessToken));
|
|
1535
|
+
this.redirectSignIn(await this.auth.magicLinkLogin(token), reply);
|
|
684
1536
|
}
|
|
685
1537
|
start(provider, reply) {
|
|
686
1538
|
const { url, state, expiresAt } = this.auth.authorizeUrl(provider);
|
|
687
1539
|
setCookie(reply, this.auth.config.stateCookieName, state, {
|
|
688
|
-
...this.
|
|
1540
|
+
...this.crossSiteAware(provider),
|
|
689
1541
|
expires: expiresAt
|
|
690
1542
|
});
|
|
691
1543
|
redirect(reply, url);
|
|
692
1544
|
}
|
|
693
|
-
|
|
1545
|
+
callback(provider, query, request, reply) {
|
|
1546
|
+
return this.completeCallback(provider, query, request, reply);
|
|
1547
|
+
}
|
|
1548
|
+
callbackByPost(provider, body, request, reply) {
|
|
1549
|
+
return this.completeCallback(provider, body ?? {}, request, reply);
|
|
1550
|
+
}
|
|
1551
|
+
async completeCallback(provider, params, request, reply) {
|
|
1552
|
+
const code = typeof params.code === "string" ? params.code : void 0;
|
|
1553
|
+
const state = typeof params.state === "string" ? params.state : void 0;
|
|
694
1554
|
if (!code) throw new UnauthorizedAppException(this.auth.config.genericErrorMessage());
|
|
695
1555
|
const stateCookie = request.cookies?.[this.auth.config.stateCookieName];
|
|
696
1556
|
clearCookie(reply, this.auth.config.stateCookieName, {
|
|
@@ -699,7 +1559,7 @@ function createOAuthController(options = {}) {
|
|
|
699
1559
|
if (!this.auth.verifyState(state, stateCookie, provider)) {
|
|
700
1560
|
throw new UnauthorizedAppException(this.auth.config.genericErrorMessage());
|
|
701
1561
|
}
|
|
702
|
-
const profile = await this.auth.profileFromCode(provider, code);
|
|
1562
|
+
const profile = await this.auth.profileFromCode(provider, code, params);
|
|
703
1563
|
const linkUserId = this.auth.readLinkToken(request.cookies?.[this.auth.config.linkCookieName]);
|
|
704
1564
|
if (linkUserId) {
|
|
705
1565
|
clearCookie(reply, this.auth.config.linkCookieName, { path: this.auth.config.cookie.path });
|
|
@@ -712,17 +1572,45 @@ function createOAuthController(options = {}) {
|
|
|
712
1572
|
}
|
|
713
1573
|
return;
|
|
714
1574
|
}
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
1575
|
+
this.redirectSignIn(await this.auth.login(provider, profile), reply);
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* A sign-in either opened a session — refresh token to the cookie,
|
|
1579
|
+
* access token to the body — or stopped at the second factor, in which
|
|
1580
|
+
* case the client gets the challenge and no cookie at all.
|
|
1581
|
+
*/
|
|
1582
|
+
answerSignIn(result, reply) {
|
|
1583
|
+
if (isMfaChallenge(result)) {
|
|
1584
|
+
return { mfaRequired: true, challenge: result.challenge, expiresAt: result.expiresAt };
|
|
1585
|
+
}
|
|
1586
|
+
this.writeRefreshCookie(reply, result.refreshToken, result.refreshTokenExpiresAt);
|
|
1587
|
+
return { accessToken: result.accessToken, user: result.user };
|
|
1588
|
+
}
|
|
1589
|
+
/** The redirect flavour of {@link answerSignIn}, for the browser-navigation flows. */
|
|
1590
|
+
redirectSignIn(result, reply) {
|
|
1591
|
+
if (isMfaChallenge(result)) {
|
|
1592
|
+
redirect(reply, this.auth.config.twoFactor.onMfaRedirect(result.challenge));
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
this.writeRefreshCookie(reply, result.refreshToken, result.refreshTokenExpiresAt);
|
|
1596
|
+
redirect(reply, this.auth.config.onLoginRedirect(result.accessToken));
|
|
721
1597
|
}
|
|
722
1598
|
cookieBase() {
|
|
723
1599
|
const { secure, sameSite, path } = this.auth.config.cookie;
|
|
724
1600
|
return { httpOnly: true, secure, sameSite, path };
|
|
725
1601
|
}
|
|
1602
|
+
/**
|
|
1603
|
+
* `SameSite=None` for a provider that POSTs its callback: the browser
|
|
1604
|
+
* sends no `Lax` cookie on a cross-site POST, so the `state` written on
|
|
1605
|
+
* the way out would never come back and every Apple sign-in would be
|
|
1606
|
+
* refused as forged. `None` requires `Secure`, which Apple's https-only
|
|
1607
|
+
* callback satisfies anyway.
|
|
1608
|
+
*/
|
|
1609
|
+
crossSiteAware(provider) {
|
|
1610
|
+
const base = this.cookieBase();
|
|
1611
|
+
const config = this.auth.config.providers.find((p) => p.name === provider);
|
|
1612
|
+
return config?.callbackMethod === "POST" ? { ...base, sameSite: "none", secure: true } : base;
|
|
1613
|
+
}
|
|
726
1614
|
writeRefreshCookie(reply, token, expiresAt) {
|
|
727
1615
|
setCookie(reply, this.auth.config.cookie.name, token, {
|
|
728
1616
|
...this.cookieBase(),
|
|
@@ -765,6 +1653,75 @@ function createOAuthController(options = {}) {
|
|
|
765
1653
|
__decorateParam(0, Body()),
|
|
766
1654
|
__decorateParam(1, Res({ passthrough: true }))
|
|
767
1655
|
], OAuthControllerHost.prototype, "verifyMagicLink", 1);
|
|
1656
|
+
__decorateClass([
|
|
1657
|
+
Post("2fa/verify"),
|
|
1658
|
+
__decorateParam(0, Body()),
|
|
1659
|
+
__decorateParam(1, Res({ passthrough: true }))
|
|
1660
|
+
], OAuthControllerHost.prototype, "verifyMfa", 1);
|
|
1661
|
+
__decorateClass([
|
|
1662
|
+
UseGuards(Guard),
|
|
1663
|
+
Get("2fa"),
|
|
1664
|
+
__decorateParam(0, CurrentUser())
|
|
1665
|
+
], OAuthControllerHost.prototype, "twoFactorStatus", 1);
|
|
1666
|
+
__decorateClass([
|
|
1667
|
+
UseGuards(Guard),
|
|
1668
|
+
Post("2fa/setup"),
|
|
1669
|
+
__decorateParam(0, CurrentUser())
|
|
1670
|
+
], OAuthControllerHost.prototype, "twoFactorSetup", 1);
|
|
1671
|
+
__decorateClass([
|
|
1672
|
+
UseGuards(Guard),
|
|
1673
|
+
Post("2fa/confirm"),
|
|
1674
|
+
__decorateParam(0, CurrentUser()),
|
|
1675
|
+
__decorateParam(1, Body())
|
|
1676
|
+
], OAuthControllerHost.prototype, "twoFactorConfirm", 1);
|
|
1677
|
+
__decorateClass([
|
|
1678
|
+
UseGuards(Guard),
|
|
1679
|
+
Post("2fa/disable"),
|
|
1680
|
+
__decorateParam(0, CurrentUser()),
|
|
1681
|
+
__decorateParam(1, Body())
|
|
1682
|
+
], OAuthControllerHost.prototype, "twoFactorDisable", 1);
|
|
1683
|
+
__decorateClass([
|
|
1684
|
+
UseGuards(Guard),
|
|
1685
|
+
Post("passkeys/register/options"),
|
|
1686
|
+
__decorateParam(0, CurrentUser())
|
|
1687
|
+
], OAuthControllerHost.prototype, "passkeyRegistrationOptions", 1);
|
|
1688
|
+
__decorateClass([
|
|
1689
|
+
UseGuards(Guard),
|
|
1690
|
+
Post("passkeys/register"),
|
|
1691
|
+
__decorateParam(0, CurrentUser()),
|
|
1692
|
+
__decorateParam(1, Body())
|
|
1693
|
+
], OAuthControllerHost.prototype, "passkeyRegister", 1);
|
|
1694
|
+
__decorateClass([
|
|
1695
|
+
UseGuards(Guard),
|
|
1696
|
+
Post("passkeys/unlock/options"),
|
|
1697
|
+
__decorateParam(0, CurrentUser())
|
|
1698
|
+
], OAuthControllerHost.prototype, "passkeyUnlockOptions", 1);
|
|
1699
|
+
__decorateClass([
|
|
1700
|
+
UseGuards(Guard),
|
|
1701
|
+
Post("passkeys/unlock"),
|
|
1702
|
+
__decorateParam(0, CurrentUser()),
|
|
1703
|
+
__decorateParam(1, Body())
|
|
1704
|
+
], OAuthControllerHost.prototype, "passkeyUnlock", 1);
|
|
1705
|
+
__decorateClass([
|
|
1706
|
+
UseGuards(Guard),
|
|
1707
|
+
Get("passkeys"),
|
|
1708
|
+
__decorateParam(0, CurrentUser())
|
|
1709
|
+
], OAuthControllerHost.prototype, "listPasskeys", 1);
|
|
1710
|
+
__decorateClass([
|
|
1711
|
+
UseGuards(Guard),
|
|
1712
|
+
Delete("passkeys/:id"),
|
|
1713
|
+
__decorateParam(0, CurrentUser()),
|
|
1714
|
+
__decorateParam(1, Param("id"))
|
|
1715
|
+
], OAuthControllerHost.prototype, "deletePasskey", 1);
|
|
1716
|
+
__decorateClass([
|
|
1717
|
+
Post("passkeys/login/options"),
|
|
1718
|
+
__decorateParam(0, Body())
|
|
1719
|
+
], OAuthControllerHost.prototype, "passkeyLoginOptions", 1);
|
|
1720
|
+
__decorateClass([
|
|
1721
|
+
Post("passkeys/login"),
|
|
1722
|
+
__decorateParam(0, Body()),
|
|
1723
|
+
__decorateParam(1, Res({ passthrough: true }))
|
|
1724
|
+
], OAuthControllerHost.prototype, "passkeyLogin", 1);
|
|
768
1725
|
__decorateClass([
|
|
769
1726
|
Get("magic-link/callback"),
|
|
770
1727
|
UseFilters(OAuthCallbackFilter),
|
|
@@ -780,11 +1737,18 @@ function createOAuthController(options = {}) {
|
|
|
780
1737
|
Get(":provider/callback"),
|
|
781
1738
|
UseFilters(OAuthCallbackFilter),
|
|
782
1739
|
__decorateParam(0, Param("provider")),
|
|
783
|
-
__decorateParam(1, Query(
|
|
784
|
-
__decorateParam(2,
|
|
785
|
-
__decorateParam(3,
|
|
786
|
-
__decorateParam(4, Res())
|
|
1740
|
+
__decorateParam(1, Query()),
|
|
1741
|
+
__decorateParam(2, Req()),
|
|
1742
|
+
__decorateParam(3, Res())
|
|
787
1743
|
], OAuthControllerHost.prototype, "callback", 1);
|
|
1744
|
+
__decorateClass([
|
|
1745
|
+
Post(":provider/callback"),
|
|
1746
|
+
UseFilters(OAuthCallbackFilter),
|
|
1747
|
+
__decorateParam(0, Param("provider")),
|
|
1748
|
+
__decorateParam(1, Body()),
|
|
1749
|
+
__decorateParam(2, Req()),
|
|
1750
|
+
__decorateParam(3, Res())
|
|
1751
|
+
], OAuthControllerHost.prototype, "callbackByPost", 1);
|
|
788
1752
|
OAuthControllerHost = __decorateClass([
|
|
789
1753
|
Controller(options.path ?? "auth"),
|
|
790
1754
|
__decorateParam(0, Inject3(OAuthAuthService))
|
|
@@ -822,16 +1786,43 @@ export {
|
|
|
822
1786
|
MagicLinkRequestDto,
|
|
823
1787
|
MagicLinkVerifyDto,
|
|
824
1788
|
MemoryMagicLinkStore,
|
|
1789
|
+
MemoryPasskeyStore,
|
|
1790
|
+
MemoryTwoFactorStore,
|
|
1791
|
+
MfaVerifyDto,
|
|
825
1792
|
OAUTH_AUTH_OPTIONS,
|
|
826
1793
|
OAUTH_STORE,
|
|
827
1794
|
OAuthAuthModule,
|
|
828
1795
|
OAuthAuthService,
|
|
829
1796
|
OAuthCallbackFilter,
|
|
1797
|
+
PASSKEY_STORE,
|
|
1798
|
+
PasskeyLoginDto,
|
|
1799
|
+
PasskeyLoginOptionsDto,
|
|
1800
|
+
PasskeyRegisterDto,
|
|
830
1801
|
REFRESH_TOKEN_STORE,
|
|
1802
|
+
TWO_FACTOR_STORE,
|
|
1803
|
+
TwoFactorCodeDto,
|
|
1804
|
+
WEBAUTHN,
|
|
1805
|
+
appleProvider,
|
|
1806
|
+
base32Decode,
|
|
1807
|
+
base32Encode,
|
|
831
1808
|
buildAuthorizeUrl,
|
|
832
1809
|
createOAuthController,
|
|
1810
|
+
discordProvider,
|
|
1811
|
+
exchangeCode,
|
|
833
1812
|
exchangeCodeForToken,
|
|
834
1813
|
facebookProvider,
|
|
1814
|
+
generateTotpSecret,
|
|
1815
|
+
githubProvider,
|
|
835
1816
|
googleProvider,
|
|
836
|
-
|
|
1817
|
+
isMfaChallenge,
|
|
1818
|
+
linkedinProvider,
|
|
1819
|
+
loadWebAuthn,
|
|
1820
|
+
microsoftProvider,
|
|
1821
|
+
mintClientSecret,
|
|
1822
|
+
otpauthUri,
|
|
1823
|
+
resolveOAuthOptions,
|
|
1824
|
+
tiktokProvider,
|
|
1825
|
+
totp,
|
|
1826
|
+
verifyAppleIdToken,
|
|
1827
|
+
verifyTotp
|
|
837
1828
|
};
|