@miguelmorales13/nestkit 0.20.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.
@@ -1,13 +1,14 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
4
  var _chunkFH5UNWWWcjs = require('../../chunk-FH5UNWWW.cjs');
5
5
 
6
6
 
7
7
 
8
+
8
9
  var _chunkHDFPSA2Vcjs = require('../../chunk-HDFPSA2V.cjs');
9
- require('../../chunk-Q5Y33L7B.cjs');
10
10
  require('../../chunk-SDWHKPXI.cjs');
11
+ require('../../chunk-Q5Y33L7B.cjs');
11
12
  require('../../chunk-PNK5WMPP.cjs');
12
13
 
13
14
 
@@ -20,7 +21,7 @@ async function readJson(response, what) {
20
21
  let body;
21
22
  try {
22
23
  body = JSON.parse(text);
23
- } catch (e) {
24
+ } catch (e2) {
24
25
  throw new Error(`${what}: expected JSON, got ${response.status} ${text.slice(0, 200)}`);
25
26
  }
26
27
  if (!response.ok) {
@@ -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
- email,
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: _nullishCoalesce(data.email, () => ( "")),
88
+ email: data.email || void 0,
86
89
  name: data.name,
87
90
  avatarUrl: _optionalChain([picture, 'optionalAccess', _ => _.data, 'optionalAccess', _2 => _2.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: _nullishCoalesce(provider.clientId, () => ( "")),
97
+ [_nullishCoalesce(provider.clientIdParam, () => ( "client_id"))]: _nullishCoalesce(provider.clientId, () => ( "")),
95
98
  redirect_uri: _nullishCoalesce(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 exchangeCodeForToken(provider, code) {
106
+ async function exchangeCode(provider, code) {
107
+ const secret = typeof provider.clientSecret === "function" ? await provider.clientSecret() : _nullishCoalesce(provider.clientSecret, () => ( ""));
104
108
  const body = new URLSearchParams({
105
- client_id: _nullishCoalesce(provider.clientId, () => ( "")),
106
- client_secret: _nullishCoalesce(provider.clientSecret, () => ( "")),
109
+ [_nullishCoalesce(provider.clientIdParam, () => ( "client_id"))]: _nullishCoalesce(provider.clientId, () => ( "")),
110
+ client_secret: secret,
107
111
  redirect_uri: _nullishCoalesce(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
- const token = data.access_token;
123
- if (!token) throw new Error(`${provider.name} token exchange returned no access_token.`);
124
- return token;
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
+ var _crypto = require('crypto');
136
+ var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_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 = _nullishCoalesce(credentials.clientId, () => ( process.env.APPLE_CLIENT_ID));
141
+ const teamId = _nullishCoalesce(credentials.teamId, () => ( process.env.APPLE_TEAM_ID));
142
+ const keyId = _nullishCoalesce(credentials.keyId, () => ( process.env.APPLE_KEY_ID));
143
+ const privateKey = _optionalChain([(_nullishCoalesce(credentials.privateKey, () => ( process.env.APPLE_PRIVATE_KEY))), 'optionalAccess', _3 => _3.replace, 'call', _4 => _4(/\\n/g, "\n")]);
144
+ const keysUrl = _nullishCoalesce(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: _nullishCoalesce(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: _nullishCoalesce(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 _jsonwebtoken2.default.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: _nullishCoalesce(data.keys, () => ( [])) };
188
+ return cachedKeys.keys;
189
+ }
190
+ async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL) {
191
+ const decoded = _jsonwebtoken2.default.decode(idToken, { complete: true });
192
+ const kid = _optionalChain([decoded, 'optionalAccess', _5 => _5.header, 'access', _6 => _6.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 = _crypto.createPublicKey.call(void 0, { key, format: "jwk" }).export({ type: "spki", format: "pem" });
196
+ return _jsonwebtoken2.default.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 = [_optionalChain([user, 'access', _7 => _7.name, 'optionalAccess', _8 => _8.firstName]), _optionalChain([user, 'access', _9 => _9.name, 'optionalAccess', _10 => _10.lastName])].filter(Boolean).join(" ").trim();
204
+ return full || void 0;
205
+ } catch (e3) {
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: _nullishCoalesce(credentials.clientId, () => ( process.env.TIKTOK_CLIENT_KEY)),
215
+ clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.TIKTOK_CLIENT_SECRET)),
216
+ callbackUrl: _nullishCoalesce(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: _nullishCoalesce(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 (_optionalChain([error, 'optionalAccess', _11 => _11.code]) && error.code !== "ok") throw new Error(`TikTok user info: ${error.code} ${_nullishCoalesce(error.message, () => ( ""))}`);
230
+ const user = _optionalChain([data, 'access', _12 => _12.data, 'optionalAccess', _13 => _13.user]);
231
+ const openId = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _14 => _14.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: _optionalChain([user, 'optionalAccess', _15 => _15.display_name]),
236
+ avatarUrl: _optionalChain([user, 'optionalAccess', _16 => _16.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: _nullishCoalesce(credentials.clientId, () => ( process.env.GITHUB_CLIENT_ID)),
247
+ clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.GITHUB_CLIENT_SECRET)),
248
+ callbackUrl: _nullishCoalesce(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: _nullishCoalesce(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) ? _nullishCoalesce(emails.find((e) => e.primary && e.verified), () => ( emails.find((e) => e.verified))) : void 0;
264
+ return {
265
+ providerAccountId: String(user.id),
266
+ email: _optionalChain([primary, 'optionalAccess', _17 => _17.email]),
267
+ name: _nullishCoalesce(_nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(credentials.tenant, () => ( process.env.MICROSOFT_TENANT)), () => ( "common"));
277
+ return {
278
+ name: "microsoft",
279
+ clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.MICROSOFT_CLIENT_ID)),
280
+ clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.MICROSOFT_CLIENT_SECRET)),
281
+ callbackUrl: _nullishCoalesce(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: _nullishCoalesce(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 = _nullishCoalesce(me.mail, () => ( me.userPrincipalName));
291
+ return {
292
+ providerAccountId: String(me.id),
293
+ email: email && email.includes("@") ? email : void 0,
294
+ name: _nullishCoalesce(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: _nullishCoalesce(credentials.clientId, () => ( process.env.DISCORD_CLIENT_ID)),
305
+ clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.DISCORD_CLIENT_SECRET)),
306
+ callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.DISCORD_CALLBACK_URL)),
307
+ authorizeUrl: "https://discord.com/oauth2/authorize",
308
+ tokenUrl: "https://discord.com/api/oauth2/token",
309
+ scope: _nullishCoalesce(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: _nullishCoalesce(_nullishCoalesce(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: _nullishCoalesce(credentials.clientId, () => ( process.env.LINKEDIN_CLIENT_ID)),
332
+ clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.LINKEDIN_CLIENT_SECRET)),
333
+ callbackUrl: _nullishCoalesce(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: _nullishCoalesce(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,
@@ -139,16 +368,31 @@ function resolveOAuthOptions(options) {
139
368
  onErrorRedirect: _nullishCoalesce(options.onErrorRedirect, () => ( ((message) => `${webUrl}/login?error=${encodeURIComponent(message)}`))),
140
369
  onLinkRedirect: _nullishCoalesce(options.onLinkRedirect, () => ( ((provider, error) => error ? `${webUrl}/profile?error=${encodeURIComponent(error)}` : `${webUrl}/profile?linked=${provider}`))),
141
370
  cookie: {
142
- name: _nullishCoalesce(_optionalChain([options, 'access', _3 => _3.cookie, 'optionalAccess', _4 => _4.name]), () => ( "refresh_token")),
143
- path: _nullishCoalesce(_optionalChain([options, 'access', _5 => _5.cookie, 'optionalAccess', _6 => _6.path]), () => ( "/auth")),
144
- sameSite: _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.cookie, 'optionalAccess', _8 => _8.sameSite]), () => ( "lax")),
145
- secure: _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.cookie, 'optionalAccess', _10 => _10.secure]), () => ( process.env.NODE_ENV === "production"))
371
+ name: _nullishCoalesce(_optionalChain([options, 'access', _18 => _18.cookie, 'optionalAccess', _19 => _19.name]), () => ( "refresh_token")),
372
+ path: _nullishCoalesce(_optionalChain([options, 'access', _20 => _20.cookie, 'optionalAccess', _21 => _21.path]), () => ( "/auth")),
373
+ sameSite: _nullishCoalesce(_optionalChain([options, 'access', _22 => _22.cookie, 'optionalAccess', _23 => _23.sameSite]), () => ( "lax")),
374
+ secure: _nullishCoalesce(_optionalChain([options, 'access', _24 => _24.cookie, 'optionalAccess', _25 => _25.secure]), () => ( process.env.NODE_ENV === "production"))
146
375
  },
147
376
  magicLink: {
148
- ttlSeconds: _nullishCoalesce(_optionalChain([options, 'access', _11 => _11.magicLink, 'optionalAccess', _12 => _12.ttlSeconds]), () => ( 15 * 60)),
149
- allowSignUp: _nullishCoalesce(_optionalChain([options, 'access', _13 => _13.magicLink, 'optionalAccess', _14 => _14.allowSignUp]), () => ( true)),
150
- linkUrl: _nullishCoalesce(_optionalChain([options, 'access', _15 => _15.magicLink, 'optionalAccess', _16 => _16.linkUrl]), () => ( ((token) => `${webUrl}/magic-link#token=${encodeURIComponent(token)}`))),
151
- invalidLinkMessage: _nullishCoalesce(_optionalChain([options, 'access', _17 => _17.magicLink, 'optionalAccess', _18 => _18.invalidLinkMessage]), () => ( (() => "This sign-in link is invalid or has expired. Request a new one.")))
377
+ ttlSeconds: _nullishCoalesce(_optionalChain([options, 'access', _26 => _26.magicLink, 'optionalAccess', _27 => _27.ttlSeconds]), () => ( 15 * 60)),
378
+ allowSignUp: _nullishCoalesce(_optionalChain([options, 'access', _28 => _28.magicLink, 'optionalAccess', _29 => _29.allowSignUp]), () => ( true)),
379
+ linkUrl: _nullishCoalesce(_optionalChain([options, 'access', _30 => _30.magicLink, 'optionalAccess', _31 => _31.linkUrl]), () => ( ((token) => `${webUrl}/magic-link#token=${encodeURIComponent(token)}`))),
380
+ invalidLinkMessage: _nullishCoalesce(_optionalChain([options, 'access', _32 => _32.magicLink, 'optionalAccess', _33 => _33.invalidLinkMessage]), () => ( (() => "This sign-in link is invalid or has expired. Request a new one.")))
381
+ },
382
+ twoFactor: {
383
+ issuer: _nullishCoalesce(_optionalChain([options, 'access', _34 => _34.twoFactor, 'optionalAccess', _35 => _35.issuer]), () => ( host)),
384
+ challengeTtlSeconds: _nullishCoalesce(_optionalChain([options, 'access', _36 => _36.twoFactor, 'optionalAccess', _37 => _37.challengeTtlSeconds]), () => ( 5 * 60)),
385
+ backupCodes: _nullishCoalesce(_optionalChain([options, 'access', _38 => _38.twoFactor, 'optionalAccess', _39 => _39.backupCodes]), () => ( 10)),
386
+ onMfaRedirect: _nullishCoalesce(_optionalChain([options, 'access', _40 => _40.twoFactor, 'optionalAccess', _41 => _41.onMfaRedirect]), () => ( ((challenge) => `${webUrl}/two-factor#challenge=${encodeURIComponent(challenge)}`))),
387
+ invalidCodeMessage: _nullishCoalesce(_optionalChain([options, 'access', _42 => _42.twoFactor, 'optionalAccess', _43 => _43.invalidCodeMessage]), () => ( (() => "That code is not valid. Try the next one.")))
388
+ },
389
+ passkeys: {
390
+ rpId: _nullishCoalesce(_optionalChain([options, 'access', _44 => _44.passkeys, 'optionalAccess', _45 => _45.rpId]), () => ( host)),
391
+ rpName: _nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'access', _46 => _46.passkeys, 'optionalAccess', _47 => _47.rpName]), () => ( _optionalChain([options, 'access', _48 => _48.passkeys, 'optionalAccess', _49 => _49.rpId]))), () => ( host)),
392
+ origins: _nullishCoalesce(_optionalChain([options, 'access', _50 => _50.passkeys, 'optionalAccess', _51 => _51.origins]), () => ( [webUrl])),
393
+ challengeTtlSeconds: _nullishCoalesce(_optionalChain([options, 'access', _52 => _52.passkeys, 'optionalAccess', _53 => _53.challengeTtlSeconds]), () => ( 5 * 60)),
394
+ userVerification: _nullishCoalesce(_optionalChain([options, 'access', _54 => _54.passkeys, 'optionalAccess', _55 => _55.userVerification]), () => ( "required")),
395
+ invalidMessage: _nullishCoalesce(_optionalChain([options, 'access', _56 => _56.passkeys, 'optionalAccess', _57 => _57.invalidMessage]), () => ( (() => "The passkey could not be verified.")))
152
396
  },
153
397
  linkCookieName: _nullishCoalesce(options.linkCookieName, () => ( "link_intent")),
154
398
  stateCookieName: _nullishCoalesce(options.stateCookieName, () => ( "oauth_state")),
@@ -166,12 +410,114 @@ function resolveOAuthOptions(options) {
166
410
  missingEmailMessage: _nullishCoalesce(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 (e4) {
417
+ return url;
418
+ }
419
+ }
169
420
 
170
421
  // src/auth/oauth/oauth-auth.service.ts
171
422
  var _common = require('@nestjs/common');
172
- var _crypto = require('crypto');
173
- var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);
423
+
424
+
425
+
426
+ // src/auth/oauth/totp.ts
427
+
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(_crypto.randomBytes.call(void 0, 20));
461
+ }
462
+ function hotp(secret, counter, digits = 6) {
463
+ const buffer = Buffer.alloc(8);
464
+ buffer.writeBigUInt64BE(BigInt(counter));
465
+ const hmac = _crypto.createHmac.call(void 0, "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 = _nullishCoalesce(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(_nullishCoalesce(options.now, () => ( Date.now())), options.step);
482
+ const window = _nullishCoalesce(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 && _crypto.timingSafeEqual.call(void 0, 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(_nullishCoalesce(input.digits, () => ( 6))),
499
+ period: String(_nullishCoalesce(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 ??= Promise.resolve().then(() => _interopRequireWildcard(require("@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 _crypto.createHash.call(void 0, "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() {
@@ -202,7 +551,7 @@ var OAuthAuthService = class {
202
551
  */
203
552
  provider(name) {
204
553
  const found = this.options.providers.find((p) => p.name === name);
205
- if (!_optionalChain([found, 'optionalAccess', _19 => _19.clientId]) || !found.clientSecret) {
554
+ if (!_optionalChain([found, 'optionalAccess', _58 => _58.clientId]) || !found.clientSecret) {
206
555
  throw new (0, _common.ServiceUnavailableException)(this.options.unavailableMessage(name));
207
556
  }
208
557
  return found;
@@ -258,19 +607,29 @@ var OAuthAuthService = class {
258
607
  requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
259
608
  );
260
609
  return payload.typ === "state" && payload.provider === provider;
261
- } catch (e2) {
610
+ } catch (e5) {
262
611
  return false;
263
612
  }
264
613
  }
265
- /** Exchanges the callback's `code` for a normalised profile. */
266
- async profileFromCode(name, code) {
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 accessToken = await exchangeCodeForToken(provider, code);
269
- const profile = await provider.fetchProfile(accessToken);
270
- if (!profile.email) {
271
- throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.missingEmailMessage(name));
272
- }
273
- return { ...profile, email: normaliseEmail(profile.email) };
629
+ const tokens = await exchangeCode(provider, code);
630
+ const profile = await provider.fetchProfile(_nullishCoalesce(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
- let user = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _20 => _20.user]), () => ( null));
646
+ let user = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _59 => _59.user]), () => ( null));
287
647
  if (!user) {
648
+ if (!profile.email) {
649
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.missingEmailMessage(provider));
650
+ }
288
651
  const email = normaliseEmail(profile.email);
289
652
  user = await _asyncNullishCoalesce(await this.store.findUserByEmail(email), async () => ( await this.store.createUser({
290
653
  email,
@@ -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 or magic link —
370
- * ends here, so `singleSession` and the token pair behave identically
371
- * whichever door was used.
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(_optionalChain([record, 'optionalAccess', _60 => _60.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 (_optionalChain([existing, 'optionalAccess', _61 => _61.confirmedAt])) {
770
+ throw new (0, _chunkHDFPSA2Vcjs.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 (0, _chunkHDFPSA2Vcjs.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 = _jsonwebtoken2.default.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 (e6) {
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(_optionalChain([record, 'optionalAccess', _62 => _62.confirmedAt]));
821
+ }
822
+ issueMfaChallenge(userId) {
823
+ const ttl = this.options.twoFactor.challengeTtlSeconds;
824
+ const challenge = _jsonwebtoken2.default.sign(
825
+ { typ: "mfa", sub: userId, nonce: _crypto.randomUUID.call(void 0, ) },
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 (!_optionalChain([record, 'optionalAccess', _63 => _63.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 (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.twoFactor.invalidCodeMessage(), void 0, "TWO_FACTOR_INVALID");
850
+ }
851
+ requireTwoFactor() {
852
+ if (!this.twoFactor) throw new (0, _common.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 (0, _chunkHDFPSA2Vcjs.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: _nullishCoalesce(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 (e7) {
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: _optionalChain([name, 'optionalAccess', _64 => _64.trim, 'call', _65 => _65()]) || 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 (e8) {
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 (0, _chunkHDFPSA2Vcjs.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 _jsonwebtoken2.default.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 = _jsonwebtoken2.default.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 (e9) {
1062
+ throw this.invalidPasskey();
1063
+ }
1064
+ }
1065
+ invalidPasskey() {
1066
+ return new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.passkeys.invalidMessage(), void 0, "PASSKEY_INVALID");
1067
+ }
1068
+ requirePasskeys() {
1069
+ if (!this.passkeys) throw new (0, _common.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
  *
@@ -433,7 +1125,7 @@ var OAuthAuthService = class {
433
1125
  requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
434
1126
  );
435
1127
  return payload.typ === "link" && payload.sub ? payload.sub : null;
436
- } catch (e3) {
1128
+ } catch (e10) {
437
1129
  return null;
438
1130
  }
439
1131
  }
@@ -518,7 +1210,7 @@ var OAuthAuthService = class {
518
1210
  token,
519
1211
  requireSecret(this.options.refreshSecret, "JWT_REFRESH_SECRET")
520
1212
  );
521
- } catch (e4) {
1213
+ } catch (e11) {
522
1214
  throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid refresh token.");
523
1215
  }
524
1216
  }
@@ -531,11 +1223,34 @@ OAuthAuthService = exports.OAuthAuthService = _chunk2REOCMUDcjs.__decorateClass.
531
1223
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Optional.call(void 0, )),
532
1224
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Inject.call(void 0, MAGIC_LINK_STORE)),
533
1225
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Optional.call(void 0, )),
534
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Inject.call(void 0, MAGIC_LINK_SENDER))
1226
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Inject.call(void 0, MAGIC_LINK_SENDER)),
1227
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 5, _common.Optional.call(void 0, )),
1228
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 5, _common.Inject.call(void 0, TWO_FACTOR_STORE)),
1229
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 6, _common.Optional.call(void 0, )),
1230
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 6, _common.Inject.call(void 0, PASSKEY_STORE)),
1231
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 7, _common.Optional.call(void 0, )),
1232
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 7, _common.Inject.call(void 0, WEBAUTHN))
535
1233
  ], OAuthAuthService);
536
1234
  function normaliseEmail(email) {
537
1235
  return email.trim().toLowerCase();
538
1236
  }
1237
+ function makeBackupCode() {
1238
+ const raw = base32Encode(_crypto.randomBytes.call(void 0, 5)).toLowerCase();
1239
+ return `${raw.slice(0, 4)}-${raw.slice(4, 8)}`;
1240
+ }
1241
+ function hashBackupCode(code) {
1242
+ return _crypto.createHash.call(void 0, "sha256").update(code.replace(/[^a-z0-9]/gi, "").toUpperCase()).digest("hex");
1243
+ }
1244
+ function summarise(passkey) {
1245
+ return {
1246
+ id: passkey.id,
1247
+ name: _nullishCoalesce(passkey.name, () => ( null)),
1248
+ deviceType: passkey.deviceType,
1249
+ backedUp: passkey.backedUp,
1250
+ createdAt: passkey.createdAt,
1251
+ lastUsedAt: _nullishCoalesce(passkey.lastUsedAt, () => ( null))
1252
+ };
1253
+ }
539
1254
 
540
1255
  // src/auth/oauth/memory-magic-link.store.ts
541
1256
  var MemoryMagicLinkStore = class {
@@ -558,6 +1273,61 @@ 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 = _nullishCoalesce(_optionalChain([record, 'optionalAccess', _66 => _66.backupCodeHashes, 'access', _67 => _67.indexOf, 'call', _68 => _68(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
1332
  var _classvalidator = require('class-validator');
563
1333
  var MagicLinkRequestDto = class {
@@ -571,6 +1341,50 @@ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
571
1341
  _classvalidator.IsString.call(void 0, ),
572
1342
  _classvalidator.MinLength.call(void 0, 16)
573
1343
  ], MagicLinkVerifyDto.prototype, "token", 2);
1344
+ var TwoFactorCodeDto = class {
1345
+ };
1346
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1347
+ _classvalidator.IsString.call(void 0, ),
1348
+ _classvalidator.MinLength.call(void 0, 6)
1349
+ ], TwoFactorCodeDto.prototype, "code", 2);
1350
+ var MfaVerifyDto = class {
1351
+ };
1352
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1353
+ _classvalidator.IsString.call(void 0, ),
1354
+ _classvalidator.MinLength.call(void 0, 16)
1355
+ ], MfaVerifyDto.prototype, "challenge", 2);
1356
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1357
+ _classvalidator.IsString.call(void 0, ),
1358
+ _classvalidator.MinLength.call(void 0, 6)
1359
+ ], MfaVerifyDto.prototype, "code", 2);
1360
+ var PasskeyRegisterDto = class {
1361
+ };
1362
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1363
+ _classvalidator.IsString.call(void 0, ),
1364
+ _classvalidator.MinLength.call(void 0, 16)
1365
+ ], PasskeyRegisterDto.prototype, "token", 2);
1366
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1367
+ _classvalidator.IsObject.call(void 0, )
1368
+ ], PasskeyRegisterDto.prototype, "response", 2);
1369
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1370
+ _classvalidator.IsOptional.call(void 0, ),
1371
+ _classvalidator.IsString.call(void 0, )
1372
+ ], PasskeyRegisterDto.prototype, "name", 2);
1373
+ var PasskeyLoginOptionsDto = class {
1374
+ };
1375
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1376
+ _classvalidator.IsOptional.call(void 0, ),
1377
+ _classvalidator.IsEmail.call(void 0, )
1378
+ ], PasskeyLoginOptionsDto.prototype, "email", 2);
1379
+ var PasskeyLoginDto = class {
1380
+ };
1381
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1382
+ _classvalidator.IsString.call(void 0, ),
1383
+ _classvalidator.MinLength.call(void 0, 16)
1384
+ ], PasskeyLoginDto.prototype, "token", 2);
1385
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1386
+ _classvalidator.IsObject.call(void 0, )
1387
+ ], PasskeyLoginDto.prototype, "response", 2);
574
1388
 
575
1389
  // src/auth/oauth/oauth-callback.filter.ts
576
1390
 
@@ -587,7 +1401,7 @@ function setCookie(reply, name, value, options) {
587
1401
  else throw new Error("No cookie support on the reply: register @fastify/cookie or cookie-parser.");
588
1402
  }
589
1403
  function clearCookie(reply, name, options) {
590
- _optionalChain([reply, 'access', _21 => _21.clearCookie, 'optionalCall', _22 => _22(name, options)]);
1404
+ _optionalChain([reply, 'access', _69 => _69.clearCookie, 'optionalCall', _70 => _70(name, options)]);
591
1405
  }
592
1406
  function redirect(reply, url) {
593
1407
  const send = reply.redirect;
@@ -629,6 +1443,7 @@ OAuthCallbackFilter = exports.OAuthCallbackFilter = _chunk2REOCMUDcjs.__decorate
629
1443
 
630
1444
 
631
1445
 
1446
+
632
1447
  function createOAuthController(options = {}) {
633
1448
  const Guard = _nullishCoalesce(options.guard, () => ( _chunkFH5UNWWWcjs.JwtAuthGuard));
634
1449
  const userId = _nullishCoalesce(options.userId, () => ( ((user) => user.sub)));
@@ -639,14 +1454,14 @@ function createOAuthController(options = {}) {
639
1454
  this.auth = auth;
640
1455
  }
641
1456
  async refresh(request, reply) {
642
- const raw = _optionalChain([request, 'access', _23 => _23.cookies, 'optionalAccess', _24 => _24[this.auth.config.cookie.name]]);
1457
+ const raw = _optionalChain([request, 'access', _71 => _71.cookies, 'optionalAccess', _72 => _72[this.auth.config.cookie.name]]);
643
1458
  if (!raw) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("No refresh token.");
644
1459
  const { accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.refresh(raw);
645
1460
  this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
646
1461
  return { accessToken };
647
1462
  }
648
1463
  async logout(request, reply) {
649
- const raw = _optionalChain([request, 'access', _25 => _25.cookies, 'optionalAccess', _26 => _26[this.auth.config.cookie.name]]);
1464
+ const raw = _optionalChain([request, 'access', _73 => _73.cookies, 'optionalAccess', _74 => _74[this.auth.config.cookie.name]]);
650
1465
  if (raw) await this.auth.logout(raw);
651
1466
  clearCookie(reply, this.auth.config.cookie.name, { path: this.auth.config.cookie.path });
652
1467
  return { success: true };
@@ -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,37 +1487,80 @@ function createOAuthController(options = {}) {
670
1487
  return { ok: true };
671
1488
  }
672
1489
  async verifyMagicLink(body, reply) {
673
- const { user, accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.magicLinkLogin(
674
- body.token
675
- );
676
- this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
677
- return { accessToken, user };
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(_optionalChain([body, 'optionalAccess', _75 => _75.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 (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.magicLink.invalidLinkMessage());
681
- const { accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.magicLinkLogin(token);
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.cookieBase(),
1540
+ ...this.crossSiteAware(provider),
689
1541
  expires: expiresAt
690
1542
  });
691
1543
  redirect(reply, url);
692
1544
  }
693
- async callback(provider, code, state, request, reply) {
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, _nullishCoalesce(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 (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
695
- const stateCookie = _optionalChain([request, 'access', _27 => _27.cookies, 'optionalAccess', _28 => _28[this.auth.config.stateCookieName]]);
1555
+ const stateCookie = _optionalChain([request, 'access', _76 => _76.cookies, 'optionalAccess', _77 => _77[this.auth.config.stateCookieName]]);
696
1556
  clearCookie(reply, this.auth.config.stateCookieName, {
697
1557
  path: this.auth.config.cookie.path
698
1558
  });
699
1559
  if (!this.auth.verifyState(state, stateCookie, provider)) {
700
1560
  throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
701
1561
  }
702
- const profile = await this.auth.profileFromCode(provider, code);
703
- const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _29 => _29.cookies, 'optionalAccess', _30 => _30[this.auth.config.linkCookieName]]));
1562
+ const profile = await this.auth.profileFromCode(provider, code, params);
1563
+ const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _78 => _78.cookies, 'optionalAccess', _79 => _79[this.auth.config.linkCookieName]]));
704
1564
  if (linkUserId) {
705
1565
  clearCookie(reply, this.auth.config.linkCookieName, { path: this.auth.config.cookie.path });
706
1566
  try {
@@ -712,17 +1572,45 @@ function createOAuthController(options = {}) {
712
1572
  }
713
1573
  return;
714
1574
  }
715
- const { accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.login(
716
- provider,
717
- profile
718
- );
719
- this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
720
- redirect(reply, this.auth.config.onLoginRedirect(accessToken));
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 _optionalChain([config, 'optionalAccess', _80 => _80.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
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, )),
766
1654
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
767
1655
  ], OAuthControllerHost.prototype, "verifyMagicLink", 1);
1656
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1657
+ _common.Post.call(void 0, "2fa/verify"),
1658
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, )),
1659
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
1660
+ ], OAuthControllerHost.prototype, "verifyMfa", 1);
1661
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1662
+ _common.UseGuards.call(void 0, Guard),
1663
+ _common.Get.call(void 0, "2fa"),
1664
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
1665
+ ], OAuthControllerHost.prototype, "twoFactorStatus", 1);
1666
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1667
+ _common.UseGuards.call(void 0, Guard),
1668
+ _common.Post.call(void 0, "2fa/setup"),
1669
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
1670
+ ], OAuthControllerHost.prototype, "twoFactorSetup", 1);
1671
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1672
+ _common.UseGuards.call(void 0, Guard),
1673
+ _common.Post.call(void 0, "2fa/confirm"),
1674
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
1675
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Body.call(void 0, ))
1676
+ ], OAuthControllerHost.prototype, "twoFactorConfirm", 1);
1677
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1678
+ _common.UseGuards.call(void 0, Guard),
1679
+ _common.Post.call(void 0, "2fa/disable"),
1680
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
1681
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Body.call(void 0, ))
1682
+ ], OAuthControllerHost.prototype, "twoFactorDisable", 1);
1683
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1684
+ _common.UseGuards.call(void 0, Guard),
1685
+ _common.Post.call(void 0, "passkeys/register/options"),
1686
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
1687
+ ], OAuthControllerHost.prototype, "passkeyRegistrationOptions", 1);
1688
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1689
+ _common.UseGuards.call(void 0, Guard),
1690
+ _common.Post.call(void 0, "passkeys/register"),
1691
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
1692
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Body.call(void 0, ))
1693
+ ], OAuthControllerHost.prototype, "passkeyRegister", 1);
1694
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1695
+ _common.UseGuards.call(void 0, Guard),
1696
+ _common.Post.call(void 0, "passkeys/unlock/options"),
1697
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
1698
+ ], OAuthControllerHost.prototype, "passkeyUnlockOptions", 1);
1699
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1700
+ _common.UseGuards.call(void 0, Guard),
1701
+ _common.Post.call(void 0, "passkeys/unlock"),
1702
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
1703
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Body.call(void 0, ))
1704
+ ], OAuthControllerHost.prototype, "passkeyUnlock", 1);
1705
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1706
+ _common.UseGuards.call(void 0, Guard),
1707
+ _common.Get.call(void 0, "passkeys"),
1708
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, ))
1709
+ ], OAuthControllerHost.prototype, "listPasskeys", 1);
1710
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1711
+ _common.UseGuards.call(void 0, Guard),
1712
+ _common.Delete.call(void 0, "passkeys/:id"),
1713
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkFH5UNWWWcjs.CurrentUser.call(void 0, )),
1714
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Param.call(void 0, "id"))
1715
+ ], OAuthControllerHost.prototype, "deletePasskey", 1);
1716
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1717
+ _common.Post.call(void 0, "passkeys/login/options"),
1718
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, ))
1719
+ ], OAuthControllerHost.prototype, "passkeyLoginOptions", 1);
1720
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1721
+ _common.Post.call(void 0, "passkeys/login"),
1722
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, )),
1723
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
1724
+ ], OAuthControllerHost.prototype, "passkeyLogin", 1);
768
1725
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
769
1726
  _common.Get.call(void 0, "magic-link/callback"),
770
1727
  _common.UseFilters.call(void 0, OAuthCallbackFilter),
@@ -780,11 +1737,18 @@ function createOAuthController(options = {}) {
780
1737
  _common.Get.call(void 0, ":provider/callback"),
781
1738
  _common.UseFilters.call(void 0, OAuthCallbackFilter),
782
1739
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
783
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Query.call(void 0, "code")),
784
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Query.call(void 0, "state")),
785
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Req.call(void 0, )),
786
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Res.call(void 0, ))
1740
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Query.call(void 0, )),
1741
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Req.call(void 0, )),
1742
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Res.call(void 0, ))
787
1743
  ], OAuthControllerHost.prototype, "callback", 1);
1744
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
1745
+ _common.Post.call(void 0, ":provider/callback"),
1746
+ _common.UseFilters.call(void 0, OAuthCallbackFilter),
1747
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
1748
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Body.call(void 0, )),
1749
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Req.call(void 0, )),
1750
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Res.call(void 0, ))
1751
+ ], OAuthControllerHost.prototype, "callbackByPost", 1);
788
1752
  OAuthControllerHost = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
789
1753
  _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "auth"))),
790
1754
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, OAuthAuthService))
@@ -834,4 +1798,31 @@ OAuthAuthModule = exports.OAuthAuthModule = _chunk2REOCMUDcjs.__decorateClass.ca
834
1798
 
835
1799
 
836
1800
 
837
- exports.MAGIC_LINK_PROVIDER = MAGIC_LINK_PROVIDER; exports.MAGIC_LINK_SENDER = MAGIC_LINK_SENDER; exports.MAGIC_LINK_STORE = MAGIC_LINK_STORE; exports.MagicLinkRequestDto = MagicLinkRequestDto; exports.MagicLinkVerifyDto = MagicLinkVerifyDto; exports.MemoryMagicLinkStore = MemoryMagicLinkStore; exports.OAUTH_AUTH_OPTIONS = OAUTH_AUTH_OPTIONS; exports.OAUTH_STORE = OAUTH_STORE; exports.OAuthAuthModule = OAuthAuthModule; exports.OAuthAuthService = OAuthAuthService; exports.OAuthCallbackFilter = OAuthCallbackFilter; exports.REFRESH_TOKEN_STORE = REFRESH_TOKEN_STORE; exports.buildAuthorizeUrl = buildAuthorizeUrl; exports.createOAuthController = createOAuthController; exports.exchangeCodeForToken = exchangeCodeForToken; exports.facebookProvider = facebookProvider; exports.googleProvider = googleProvider; exports.resolveOAuthOptions = resolveOAuthOptions;
1801
+
1802
+
1803
+
1804
+
1805
+
1806
+
1807
+
1808
+
1809
+
1810
+
1811
+
1812
+
1813
+
1814
+
1815
+
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+ exports.MAGIC_LINK_PROVIDER = MAGIC_LINK_PROVIDER; exports.MAGIC_LINK_SENDER = MAGIC_LINK_SENDER; exports.MAGIC_LINK_STORE = MAGIC_LINK_STORE; exports.MagicLinkRequestDto = MagicLinkRequestDto; exports.MagicLinkVerifyDto = MagicLinkVerifyDto; exports.MemoryMagicLinkStore = MemoryMagicLinkStore; exports.MemoryPasskeyStore = MemoryPasskeyStore; exports.MemoryTwoFactorStore = MemoryTwoFactorStore; exports.MfaVerifyDto = MfaVerifyDto; exports.OAUTH_AUTH_OPTIONS = OAUTH_AUTH_OPTIONS; exports.OAUTH_STORE = OAUTH_STORE; exports.OAuthAuthModule = OAuthAuthModule; exports.OAuthAuthService = OAuthAuthService; exports.OAuthCallbackFilter = OAuthCallbackFilter; exports.PASSKEY_STORE = PASSKEY_STORE; exports.PasskeyLoginDto = PasskeyLoginDto; exports.PasskeyLoginOptionsDto = PasskeyLoginOptionsDto; exports.PasskeyRegisterDto = PasskeyRegisterDto; exports.REFRESH_TOKEN_STORE = REFRESH_TOKEN_STORE; exports.TWO_FACTOR_STORE = TWO_FACTOR_STORE; exports.TwoFactorCodeDto = TwoFactorCodeDto; exports.WEBAUTHN = WEBAUTHN; exports.appleProvider = appleProvider; exports.base32Decode = base32Decode; exports.base32Encode = base32Encode; exports.buildAuthorizeUrl = buildAuthorizeUrl; exports.createOAuthController = createOAuthController; exports.discordProvider = discordProvider; exports.exchangeCode = exchangeCode; exports.exchangeCodeForToken = exchangeCodeForToken; exports.facebookProvider = facebookProvider; exports.generateTotpSecret = generateTotpSecret; exports.githubProvider = githubProvider; exports.googleProvider = googleProvider; exports.isMfaChallenge = isMfaChallenge; exports.linkedinProvider = linkedinProvider; exports.loadWebAuthn = loadWebAuthn; exports.microsoftProvider = microsoftProvider; exports.mintClientSecret = mintClientSecret; exports.otpauthUri = otpauthUri; exports.resolveOAuthOptions = resolveOAuthOptions; exports.tiktokProvider = tiktokProvider; exports.totp = totp; exports.verifyAppleIdToken = verifyAppleIdToken; exports.verifyTotp = verifyTotp;