@xk2800/nextjs-template 0.7.1-beta.14 → 0.7.1-beta.16
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/components/auth/oneTap.tsx +9 -1
- package/components/dashboard/deleteAccountCard.tsx +31 -4
- package/dist/api/feedback.js +498 -63
- package/dist/api/feedback.js.map +1 -1
- package/dist/api/feedback.mjs +1 -1
- package/dist/api/marketing.js +498 -63
- package/dist/api/marketing.js.map +1 -1
- package/dist/api/marketing.mjs +2 -2
- package/dist/auth/helpers.js +496 -61
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/helpers.mjs +2 -2
- package/dist/auth/index.d.mts +142 -10
- package/dist/auth/index.d.ts +142 -10
- package/dist/auth/index.js +496 -61
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/index.mjs +1 -1
- package/dist/{chunk-6Z3WUSDJ.mjs → chunk-A2K3FVDH.mjs} +3 -3
- package/dist/{chunk-6Z3WUSDJ.mjs.map → chunk-A2K3FVDH.mjs.map} +1 -1
- package/dist/chunk-WJMWCE2I.mjs +897 -0
- package/dist/chunk-WJMWCE2I.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/chunk-7QVIOQ47.mjs +0 -462
- package/dist/chunk-7QVIOQ47.mjs.map +0 -1
package/dist/api/marketing.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { unexpectedErrorMessage } from '../chunk-6MDQRT6U.mjs';
|
|
2
2
|
import { MARKETING_SEGMENT_ID, setSubscribed } from '../chunk-C6RGN6QA.mjs';
|
|
3
|
-
import { hasRole } from '../chunk-
|
|
4
|
-
import { auth } from '../chunk-
|
|
3
|
+
import { hasRole } from '../chunk-A2K3FVDH.mjs';
|
|
4
|
+
import { auth } from '../chunk-WJMWCE2I.mjs';
|
|
5
5
|
import '../chunk-7F2POZM6.mjs';
|
|
6
6
|
import '../chunk-6OAHCEDJ.mjs';
|
|
7
7
|
import '../chunk-P2G23JMY.mjs';
|
package/dist/auth/helpers.js
CHANGED
|
@@ -15,8 +15,9 @@ var pg = require('pg');
|
|
|
15
15
|
var pgCore = require('drizzle-orm/pg-core');
|
|
16
16
|
var zod = require('zod');
|
|
17
17
|
var plugins = require('better-auth/plugins');
|
|
18
|
-
var passkey = require('@better-auth/passkey');
|
|
19
18
|
var api = require('better-auth/api');
|
|
19
|
+
var crypto = require('better-auth/crypto');
|
|
20
|
+
var passkey = require('@better-auth/passkey');
|
|
20
21
|
var uaParserJs = require('ua-parser-js');
|
|
21
22
|
var geoip = require('geoip-lite');
|
|
22
23
|
var headers = require('next/headers');
|
|
@@ -509,6 +510,410 @@ if (config.DB_DRIVER === "pg") {
|
|
|
509
510
|
} else {
|
|
510
511
|
console.log("Database connection not established, unknown DB_DRIVER:", config.DB_DRIVER);
|
|
511
512
|
}
|
|
513
|
+
|
|
514
|
+
// node_modules/@better-auth/utils/dist/base32.mjs
|
|
515
|
+
function getAlphabet(hex2) {
|
|
516
|
+
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
517
|
+
}
|
|
518
|
+
function createDecodeMap(alphabet) {
|
|
519
|
+
const decodeMap = /* @__PURE__ */ new Map();
|
|
520
|
+
for (let i = 0; i < alphabet.length; i++) {
|
|
521
|
+
decodeMap.set(alphabet[i], i);
|
|
522
|
+
}
|
|
523
|
+
return decodeMap;
|
|
524
|
+
}
|
|
525
|
+
function base32Encode(data, alphabet, padding) {
|
|
526
|
+
let result = "";
|
|
527
|
+
let buffer = 0;
|
|
528
|
+
let shift = 0;
|
|
529
|
+
for (const byte of data) {
|
|
530
|
+
buffer = buffer << 8 | byte;
|
|
531
|
+
shift += 8;
|
|
532
|
+
while (shift >= 5) {
|
|
533
|
+
shift -= 5;
|
|
534
|
+
result += alphabet[buffer >> shift & 31];
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (shift > 0) {
|
|
538
|
+
result += alphabet[buffer << 5 - shift & 31];
|
|
539
|
+
}
|
|
540
|
+
if (padding) {
|
|
541
|
+
const padCount = (8 - result.length % 8) % 8;
|
|
542
|
+
result += "=".repeat(padCount);
|
|
543
|
+
}
|
|
544
|
+
return result;
|
|
545
|
+
}
|
|
546
|
+
function base32Decode(data, alphabet) {
|
|
547
|
+
const decodeMap = createDecodeMap(alphabet);
|
|
548
|
+
const result = [];
|
|
549
|
+
let buffer = 0;
|
|
550
|
+
let bitsCollected = 0;
|
|
551
|
+
for (const char of data) {
|
|
552
|
+
if (char === "=")
|
|
553
|
+
break;
|
|
554
|
+
const value = decodeMap.get(char);
|
|
555
|
+
if (value === void 0) {
|
|
556
|
+
throw new Error(`Invalid Base32 character: ${char}`);
|
|
557
|
+
}
|
|
558
|
+
buffer = buffer << 5 | value;
|
|
559
|
+
bitsCollected += 5;
|
|
560
|
+
while (bitsCollected >= 8) {
|
|
561
|
+
bitsCollected -= 8;
|
|
562
|
+
result.push(buffer >> bitsCollected & 255);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return Uint8Array.from(result);
|
|
566
|
+
}
|
|
567
|
+
var base32 = {
|
|
568
|
+
/**
|
|
569
|
+
* Encodes data into a Base32 string.
|
|
570
|
+
* @param data - The data to encode (ArrayBuffer, TypedArray, or string).
|
|
571
|
+
* @param options - Encoding options.
|
|
572
|
+
* @returns The Base32 encoded string.
|
|
573
|
+
*/
|
|
574
|
+
encode(data, options = {}) {
|
|
575
|
+
var _a;
|
|
576
|
+
const alphabet = getAlphabet();
|
|
577
|
+
const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
578
|
+
return base32Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
|
|
579
|
+
},
|
|
580
|
+
/**
|
|
581
|
+
* Decodes a Base32 string into a Uint8Array.
|
|
582
|
+
* @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
|
|
583
|
+
* @returns The decoded Uint8Array.
|
|
584
|
+
*/
|
|
585
|
+
decode(data) {
|
|
586
|
+
if (typeof data !== "string") {
|
|
587
|
+
data = new TextDecoder().decode(data);
|
|
588
|
+
}
|
|
589
|
+
const alphabet = getAlphabet();
|
|
590
|
+
return base32Decode(data, alphabet);
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
// node_modules/@better-auth/utils/dist/hex.mjs
|
|
595
|
+
var hexadecimal = "0123456789abcdef";
|
|
596
|
+
var hex = {
|
|
597
|
+
encode: (data) => {
|
|
598
|
+
if (typeof data === "string") {
|
|
599
|
+
data = new TextEncoder().encode(data);
|
|
600
|
+
}
|
|
601
|
+
if (data.byteLength === 0) {
|
|
602
|
+
return "";
|
|
603
|
+
}
|
|
604
|
+
const buffer = new Uint8Array(data);
|
|
605
|
+
let result = "";
|
|
606
|
+
for (const byte of buffer) {
|
|
607
|
+
result += byte.toString(16).padStart(2, "0");
|
|
608
|
+
}
|
|
609
|
+
return result;
|
|
610
|
+
},
|
|
611
|
+
decode: (data) => {
|
|
612
|
+
if (!data) {
|
|
613
|
+
return "";
|
|
614
|
+
}
|
|
615
|
+
if (typeof data === "string") {
|
|
616
|
+
if (data.length % 2 !== 0) {
|
|
617
|
+
throw new Error("Invalid hexadecimal string");
|
|
618
|
+
}
|
|
619
|
+
if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {
|
|
620
|
+
throw new Error("Invalid hexadecimal string");
|
|
621
|
+
}
|
|
622
|
+
const result = new Uint8Array(data.length / 2);
|
|
623
|
+
for (let i = 0; i < data.length; i += 2) {
|
|
624
|
+
result[i / 2] = parseInt(data.slice(i, i + 2), 16);
|
|
625
|
+
}
|
|
626
|
+
return new TextDecoder().decode(result);
|
|
627
|
+
}
|
|
628
|
+
return new TextDecoder().decode(data);
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// node_modules/@better-auth/utils/dist/base64.mjs
|
|
633
|
+
function getAlphabet2(urlSafe) {
|
|
634
|
+
return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
635
|
+
}
|
|
636
|
+
function base64Encode(data, alphabet, padding) {
|
|
637
|
+
let result = "";
|
|
638
|
+
let buffer = 0;
|
|
639
|
+
let shift = 0;
|
|
640
|
+
for (const byte of data) {
|
|
641
|
+
buffer = buffer << 8 | byte;
|
|
642
|
+
shift += 8;
|
|
643
|
+
while (shift >= 6) {
|
|
644
|
+
shift -= 6;
|
|
645
|
+
result += alphabet[buffer >> shift & 63];
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (shift > 0) {
|
|
649
|
+
result += alphabet[buffer << 6 - shift & 63];
|
|
650
|
+
}
|
|
651
|
+
if (padding) {
|
|
652
|
+
const padCount = (4 - result.length % 4) % 4;
|
|
653
|
+
result += "=".repeat(padCount);
|
|
654
|
+
}
|
|
655
|
+
return result;
|
|
656
|
+
}
|
|
657
|
+
function base64Decode(data, alphabet) {
|
|
658
|
+
const decodeMap = /* @__PURE__ */ new Map();
|
|
659
|
+
for (let i = 0; i < alphabet.length; i++) {
|
|
660
|
+
decodeMap.set(alphabet[i], i);
|
|
661
|
+
}
|
|
662
|
+
const result = [];
|
|
663
|
+
let buffer = 0;
|
|
664
|
+
let bitsCollected = 0;
|
|
665
|
+
for (const char of data) {
|
|
666
|
+
if (char === "=")
|
|
667
|
+
break;
|
|
668
|
+
const value = decodeMap.get(char);
|
|
669
|
+
if (value === void 0) {
|
|
670
|
+
throw new Error(`Invalid Base64 character: ${char}`);
|
|
671
|
+
}
|
|
672
|
+
buffer = buffer << 6 | value;
|
|
673
|
+
bitsCollected += 6;
|
|
674
|
+
if (bitsCollected >= 8) {
|
|
675
|
+
bitsCollected -= 8;
|
|
676
|
+
result.push(buffer >> bitsCollected & 255);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return Uint8Array.from(result);
|
|
680
|
+
}
|
|
681
|
+
var base64 = {
|
|
682
|
+
encode(data, options = {}) {
|
|
683
|
+
var _a;
|
|
684
|
+
const alphabet = getAlphabet2(false);
|
|
685
|
+
const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
686
|
+
return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
|
|
687
|
+
},
|
|
688
|
+
decode(data) {
|
|
689
|
+
if (typeof data !== "string") {
|
|
690
|
+
data = new TextDecoder().decode(data);
|
|
691
|
+
}
|
|
692
|
+
const urlSafe = data.includes("-") || data.includes("_");
|
|
693
|
+
const alphabet = getAlphabet2(urlSafe);
|
|
694
|
+
return base64Decode(data, alphabet);
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
var base64Url = {
|
|
698
|
+
encode(data, options = {}) {
|
|
699
|
+
var _a;
|
|
700
|
+
const alphabet = getAlphabet2(true);
|
|
701
|
+
const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
702
|
+
return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
|
|
703
|
+
},
|
|
704
|
+
decode(data) {
|
|
705
|
+
const urlSafe = data.includes("-") || data.includes("_");
|
|
706
|
+
const alphabet = getAlphabet2(urlSafe);
|
|
707
|
+
return base64Decode(data, alphabet);
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
|
|
711
|
+
// node_modules/@better-auth/utils/dist/index.mjs
|
|
712
|
+
function getWebcryptoSubtle() {
|
|
713
|
+
const cr = typeof globalThis !== "undefined" && globalThis.crypto;
|
|
714
|
+
if (cr && typeof cr.subtle === "object" && cr.subtle != null)
|
|
715
|
+
return cr.subtle;
|
|
716
|
+
throw new Error("crypto.subtle must be defined");
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// node_modules/@better-auth/utils/dist/hmac.mjs
|
|
720
|
+
var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
|
|
721
|
+
const hmac = {
|
|
722
|
+
importKey: async (key, keyUsage) => {
|
|
723
|
+
return getWebcryptoSubtle().importKey(
|
|
724
|
+
"raw",
|
|
725
|
+
typeof key === "string" ? new TextEncoder().encode(key) : key,
|
|
726
|
+
{ name: "HMAC", hash: { name: algorithm } },
|
|
727
|
+
false,
|
|
728
|
+
[keyUsage]
|
|
729
|
+
);
|
|
730
|
+
},
|
|
731
|
+
sign: async (hmacKey, data) => {
|
|
732
|
+
if (typeof hmacKey === "string") {
|
|
733
|
+
hmacKey = await hmac.importKey(hmacKey, "sign");
|
|
734
|
+
}
|
|
735
|
+
const signature = await getWebcryptoSubtle().sign(
|
|
736
|
+
"HMAC",
|
|
737
|
+
hmacKey,
|
|
738
|
+
typeof data === "string" ? new TextEncoder().encode(data) : data
|
|
739
|
+
);
|
|
740
|
+
if (encoding === "hex") {
|
|
741
|
+
return hex.encode(signature);
|
|
742
|
+
}
|
|
743
|
+
if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
|
|
744
|
+
return base64Url.encode(signature, {
|
|
745
|
+
padding: encoding !== "base64urlnopad"
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
return signature;
|
|
749
|
+
},
|
|
750
|
+
verify: async (hmacKey, data, signature) => {
|
|
751
|
+
if (typeof hmacKey === "string") {
|
|
752
|
+
hmacKey = await hmac.importKey(hmacKey, "verify");
|
|
753
|
+
}
|
|
754
|
+
if (encoding === "hex") {
|
|
755
|
+
signature = hex.decode(signature);
|
|
756
|
+
}
|
|
757
|
+
if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
|
|
758
|
+
signature = await base64.decode(signature);
|
|
759
|
+
}
|
|
760
|
+
return getWebcryptoSubtle().verify(
|
|
761
|
+
"HMAC",
|
|
762
|
+
hmacKey,
|
|
763
|
+
typeof signature === "string" ? new TextEncoder().encode(signature) : signature,
|
|
764
|
+
typeof data === "string" ? new TextEncoder().encode(data) : data
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
return hmac;
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
// node_modules/@better-auth/utils/dist/otp.mjs
|
|
772
|
+
var defaultPeriod = 30;
|
|
773
|
+
var defaultDigits = 6;
|
|
774
|
+
function constantTimeEqualOTP(input, expected) {
|
|
775
|
+
let difference = input.length ^ expected.length;
|
|
776
|
+
for (let i = 0; i < expected.length; i++) {
|
|
777
|
+
difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
|
|
778
|
+
}
|
|
779
|
+
return difference === 0;
|
|
780
|
+
}
|
|
781
|
+
async function generateHOTP(secret, {
|
|
782
|
+
counter,
|
|
783
|
+
digits,
|
|
784
|
+
hash = "SHA-1"
|
|
785
|
+
}) {
|
|
786
|
+
const _digits = digits != null ? digits : defaultDigits;
|
|
787
|
+
if (_digits < 1 || _digits > 8) {
|
|
788
|
+
throw new TypeError("Digits must be between 1 and 8");
|
|
789
|
+
}
|
|
790
|
+
const buffer = new ArrayBuffer(8);
|
|
791
|
+
new DataView(buffer).setBigUint64(0, BigInt(counter), false);
|
|
792
|
+
const bytes = new Uint8Array(buffer);
|
|
793
|
+
const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));
|
|
794
|
+
const offset = hmacResult[hmacResult.length - 1] & 15;
|
|
795
|
+
const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;
|
|
796
|
+
const otp = truncated % 10 ** _digits;
|
|
797
|
+
return otp.toString().padStart(_digits, "0");
|
|
798
|
+
}
|
|
799
|
+
async function generateTOTP(secret, options) {
|
|
800
|
+
var _a, _b;
|
|
801
|
+
const digits = (_a = options == null ? void 0 : options.digits) != null ? _a : defaultDigits;
|
|
802
|
+
const period = (_b = options == null ? void 0 : options.period) != null ? _b : defaultPeriod;
|
|
803
|
+
const milliseconds = period * 1e3;
|
|
804
|
+
const counter = Math.floor(Date.now() / milliseconds);
|
|
805
|
+
return await generateHOTP(secret, { counter, digits, hash: options == null ? void 0 : options.hash });
|
|
806
|
+
}
|
|
807
|
+
async function verifyTOTP(otp, {
|
|
808
|
+
window = 1,
|
|
809
|
+
digits = defaultDigits,
|
|
810
|
+
secret,
|
|
811
|
+
period = defaultPeriod
|
|
812
|
+
}) {
|
|
813
|
+
const milliseconds = period * 1e3;
|
|
814
|
+
const counter = Math.floor(Date.now() / milliseconds);
|
|
815
|
+
let matched = false;
|
|
816
|
+
for (let i = -window; i <= window; i++) {
|
|
817
|
+
const generatedOTP = await generateHOTP(secret, {
|
|
818
|
+
counter: counter + i,
|
|
819
|
+
digits
|
|
820
|
+
});
|
|
821
|
+
matched = constantTimeEqualOTP(otp, generatedOTP) || matched;
|
|
822
|
+
}
|
|
823
|
+
return matched;
|
|
824
|
+
}
|
|
825
|
+
function generateQRCode({
|
|
826
|
+
issuer,
|
|
827
|
+
account,
|
|
828
|
+
secret,
|
|
829
|
+
digits = defaultDigits,
|
|
830
|
+
period = defaultPeriod
|
|
831
|
+
}) {
|
|
832
|
+
const encodedIssuer = encodeURIComponent(issuer);
|
|
833
|
+
const encodedAccountName = encodeURIComponent(account);
|
|
834
|
+
const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;
|
|
835
|
+
const params = new URLSearchParams({
|
|
836
|
+
secret: base32.encode(secret, {
|
|
837
|
+
padding: false
|
|
838
|
+
}),
|
|
839
|
+
issuer
|
|
840
|
+
});
|
|
841
|
+
if (digits !== void 0) {
|
|
842
|
+
params.set("digits", digits.toString());
|
|
843
|
+
}
|
|
844
|
+
if (period !== void 0) {
|
|
845
|
+
params.set("period", period.toString());
|
|
846
|
+
}
|
|
847
|
+
return `${baseURI}?${params.toString()}`;
|
|
848
|
+
}
|
|
849
|
+
var createOTP = (secret, opts) => {
|
|
850
|
+
var _a, _b;
|
|
851
|
+
const digits = (_a = void 0 ) != null ? _a : defaultDigits;
|
|
852
|
+
const period = (_b = void 0 ) != null ? _b : defaultPeriod;
|
|
853
|
+
return {
|
|
854
|
+
hotp: (counter) => generateHOTP(secret, { counter, digits }),
|
|
855
|
+
totp: () => generateTOTP(secret, { digits, period }),
|
|
856
|
+
verify: (otp, options) => verifyTOTP(otp, __spreadValues({ secret, digits, period }, options)),
|
|
857
|
+
url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })
|
|
858
|
+
};
|
|
859
|
+
};
|
|
860
|
+
|
|
861
|
+
// lib/two-factor.ts
|
|
862
|
+
var CHALLENGED_PATHS = ["/callback/:id", "/one-tap/callback"];
|
|
863
|
+
var CODE_REQUIRED_PATHS = ["/two-factor/disable", "/two-factor/generate-backup-codes"];
|
|
864
|
+
function twoFactorPlugins(baseURL, { issuer, passwordless = false, challengeAfterOAuth = false }) {
|
|
865
|
+
const plugin = plugins.twoFactor({ issuer, allowPasswordless: passwordless });
|
|
866
|
+
if (challengeAfterOAuth) {
|
|
867
|
+
const [challenge] = plugin.hooks.after;
|
|
868
|
+
plugin.hooks.after = [__spreadProps(__spreadValues({}, challenge), {
|
|
869
|
+
matcher: (ctx) => {
|
|
870
|
+
var _a;
|
|
871
|
+
return challenge.matcher(ctx) || CHALLENGED_PATHS.includes((_a = ctx.path) != null ? _a : "");
|
|
872
|
+
}
|
|
873
|
+
})];
|
|
874
|
+
}
|
|
875
|
+
const extras = {
|
|
876
|
+
id: "two-factor-extras",
|
|
877
|
+
hooks: {
|
|
878
|
+
// allowPasswordless lets disable / regenerate-backup-codes run on a session alone,
|
|
879
|
+
// so anyone at an unlocked, signed-in browser could switch 2FA off. Require a
|
|
880
|
+
// current authenticator code instead of the password the user doesn't have.
|
|
881
|
+
before: passwordless ? [{
|
|
882
|
+
matcher: (ctx) => {
|
|
883
|
+
var _a;
|
|
884
|
+
return CODE_REQUIRED_PATHS.includes((_a = ctx.path) != null ? _a : "");
|
|
885
|
+
},
|
|
886
|
+
handler: api.createAuthMiddleware(async (ctx) => {
|
|
887
|
+
var _a;
|
|
888
|
+
const session = await api.getSessionFromCtx(ctx);
|
|
889
|
+
if (!session) return;
|
|
890
|
+
const code = (_a = ctx.body) == null ? void 0 : _a.code;
|
|
891
|
+
const row = await ctx.context.adapter.findOne({
|
|
892
|
+
model: "twoFactor",
|
|
893
|
+
where: [{ field: "userId", value: session.user.id }]
|
|
894
|
+
});
|
|
895
|
+
const valid = typeof code === "string" && !!row && await createOTP(await crypto.symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code);
|
|
896
|
+
if (!valid) throw new api.APIError("UNAUTHORIZED", { message: "Enter the current code from your authenticator app" });
|
|
897
|
+
})
|
|
898
|
+
}] : [],
|
|
899
|
+
// The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's
|
|
900
|
+
// caller handles. The Google callback is a browser redirect, so turn it into a
|
|
901
|
+
// redirect to /login/2fa, keeping where the user was headed (same-origin only).
|
|
902
|
+
after: challengeAfterOAuth ? [{
|
|
903
|
+
matcher: (ctx) => ctx.path === "/callback/:id",
|
|
904
|
+
handler: api.createAuthMiddleware(async (ctx) => {
|
|
905
|
+
var _a, _b;
|
|
906
|
+
const returned = ctx.context.returned;
|
|
907
|
+
if (!(returned == null ? void 0 : returned.twoFactorRedirect)) return;
|
|
908
|
+
const target = new URL((_b = (_a = ctx.context.responseHeaders) == null ? void 0 : _a.get("location")) != null ? _b : "/dashboard", baseURL);
|
|
909
|
+
const callbackUrl = target.origin === new URL(baseURL).origin ? target.pathname + target.search : "/dashboard";
|
|
910
|
+
throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`);
|
|
911
|
+
})
|
|
912
|
+
}] : []
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
return [plugin, extras];
|
|
916
|
+
}
|
|
512
917
|
async function logActivity({
|
|
513
918
|
userId,
|
|
514
919
|
action,
|
|
@@ -771,7 +1176,52 @@ async function notifyPasskeyChange(ctx, action) {
|
|
|
771
1176
|
console.error("Failed to send passkey-change notification", error);
|
|
772
1177
|
}
|
|
773
1178
|
}
|
|
1179
|
+
async function packageSessionCreated(...[session, context]) {
|
|
1180
|
+
var _a, _b, _c, _d;
|
|
1181
|
+
const impersonatedBy = session.impersonatedBy;
|
|
1182
|
+
if (impersonatedBy) {
|
|
1183
|
+
const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
|
|
1184
|
+
await logActivity({
|
|
1185
|
+
userId: impersonatedBy,
|
|
1186
|
+
action: "impersonation_started",
|
|
1187
|
+
description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
|
|
1188
|
+
metadata: { impersonatedUserId: session.userId }
|
|
1189
|
+
});
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
try {
|
|
1193
|
+
await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
|
|
1194
|
+
} catch (error) {
|
|
1195
|
+
console.error("Failed to update lastLoginAt", error);
|
|
1196
|
+
}
|
|
1197
|
+
try {
|
|
1198
|
+
const headers2 = context == null ? void 0 : context.headers;
|
|
1199
|
+
const ipAddress = getClientIp(headers2);
|
|
1200
|
+
const userAgent = (_c = headers2 == null ? void 0 : headers2.get("user-agent")) != null ? _c : null;
|
|
1201
|
+
const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers2 == null ? void 0 : headers2.get("referer")) || null;
|
|
1202
|
+
const device = parseUserAgent(userAgent);
|
|
1203
|
+
const geo = lookupGeoLocation(ipAddress);
|
|
1204
|
+
const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
|
|
1205
|
+
const isFirstSession = Number(count) <= 1;
|
|
1206
|
+
await logActivity({
|
|
1207
|
+
userId: session.userId,
|
|
1208
|
+
action: "login",
|
|
1209
|
+
description: isFirstSession ? "New account registered and signed in" : "User logged in",
|
|
1210
|
+
ipAddress,
|
|
1211
|
+
userAgent,
|
|
1212
|
+
referrerUrl,
|
|
1213
|
+
os: device.os,
|
|
1214
|
+
browser: device.browser,
|
|
1215
|
+
deviceType: device.deviceType,
|
|
1216
|
+
country: geo.country,
|
|
1217
|
+
city: geo.city
|
|
1218
|
+
});
|
|
1219
|
+
} catch (error) {
|
|
1220
|
+
console.error("Failed to log login activity", error);
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
774
1223
|
function createAuth(overrides = {}) {
|
|
1224
|
+
var _a, _b, _c, _d, _e, _f;
|
|
775
1225
|
const socialProviders = __spreadValues(__spreadValues({}, config.AUTH_ENABLE_GOOGLE ? {
|
|
776
1226
|
google: {
|
|
777
1227
|
clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
|
|
@@ -786,6 +1236,18 @@ function createAuth(overrides = {}) {
|
|
|
786
1236
|
);
|
|
787
1237
|
}
|
|
788
1238
|
const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
|
|
1239
|
+
const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
|
|
1240
|
+
issuer: config.APP_NAME,
|
|
1241
|
+
passwordless: (_a = overrides.twoFactor) == null ? void 0 : _a.passwordless,
|
|
1242
|
+
challengeAfterOAuth: (_b = overrides.twoFactor) == null ? void 0 : _b.challengeAfterOAuth
|
|
1243
|
+
});
|
|
1244
|
+
const appHooks = {
|
|
1245
|
+
id: "app-hooks",
|
|
1246
|
+
hooks: {
|
|
1247
|
+
before: ((_c = overrides.hooks) == null ? void 0 : _c.before) ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],
|
|
1248
|
+
after: ((_d = overrides.hooks) == null ? void 0 : _d.after) ? [{ matcher: () => true, handler: overrides.hooks.after }] : []
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
789
1251
|
return betterAuth.betterAuth({
|
|
790
1252
|
database: drizzle.drizzleAdapter(db, {
|
|
791
1253
|
provider: "pg",
|
|
@@ -865,63 +1327,30 @@ function createAuth(overrides = {}) {
|
|
|
865
1327
|
// no password, so better-auth instead requires a session younger than
|
|
866
1328
|
// `freshAge` (default 1 day). Every user-owned table cascades on delete.
|
|
867
1329
|
// Impersonation and last-admin guards live in hooks.before below.
|
|
868
|
-
deleteUser: { enabled: true }
|
|
1330
|
+
deleteUser: { enabled: (_e = overrides.deleteUser) != null ? _e : true }
|
|
869
1331
|
},
|
|
870
1332
|
// Advanced options
|
|
871
|
-
advanced: {
|
|
1333
|
+
advanced: __spreadProps(__spreadValues({}, overrides.advanced), {
|
|
872
1334
|
database: {
|
|
873
1335
|
generateId: () => cuid2.createId()
|
|
874
1336
|
}
|
|
875
|
-
},
|
|
876
|
-
|
|
877
|
-
// use that as the "last logged in" signal rather than session updates,
|
|
878
|
-
// which also fire on cookie-cache refresh / expiry extension.
|
|
1337
|
+
}),
|
|
1338
|
+
rateLimit: overrides.rateLimit,
|
|
879
1339
|
databaseHooks: {
|
|
1340
|
+
user: {
|
|
1341
|
+
create: {
|
|
1342
|
+
async after(user, context) {
|
|
1343
|
+
var _a2, _b2, _c2, _d2;
|
|
1344
|
+
await ((_d2 = (_c2 = (_b2 = (_a2 = overrides.databaseHooks) == null ? void 0 : _a2.user) == null ? void 0 : _b2.create) == null ? void 0 : _c2.after) == null ? void 0 : _d2.call(_c2, user, context));
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
},
|
|
880
1348
|
session: {
|
|
881
1349
|
create: {
|
|
882
1350
|
async after(session, context) {
|
|
883
|
-
var
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
|
|
887
|
-
await logActivity({
|
|
888
|
-
userId: impersonatedBy,
|
|
889
|
-
action: "impersonation_started",
|
|
890
|
-
description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
|
|
891
|
-
metadata: { impersonatedUserId: session.userId }
|
|
892
|
-
});
|
|
893
|
-
return;
|
|
894
|
-
}
|
|
895
|
-
try {
|
|
896
|
-
await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
|
|
897
|
-
} catch (error) {
|
|
898
|
-
console.error("Failed to update lastLoginAt", error);
|
|
899
|
-
}
|
|
900
|
-
try {
|
|
901
|
-
const headers2 = context == null ? void 0 : context.headers;
|
|
902
|
-
const ipAddress = getClientIp(headers2);
|
|
903
|
-
const userAgent = (_c = headers2 == null ? void 0 : headers2.get("user-agent")) != null ? _c : null;
|
|
904
|
-
const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers2 == null ? void 0 : headers2.get("referer")) || null;
|
|
905
|
-
const device = parseUserAgent(userAgent);
|
|
906
|
-
const geo = lookupGeoLocation(ipAddress);
|
|
907
|
-
const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
|
|
908
|
-
const isFirstSession = Number(count) <= 1;
|
|
909
|
-
await logActivity({
|
|
910
|
-
userId: session.userId,
|
|
911
|
-
action: "login",
|
|
912
|
-
description: isFirstSession ? "New account registered and signed in" : "User logged in",
|
|
913
|
-
ipAddress,
|
|
914
|
-
userAgent,
|
|
915
|
-
referrerUrl,
|
|
916
|
-
os: device.os,
|
|
917
|
-
browser: device.browser,
|
|
918
|
-
deviceType: device.deviceType,
|
|
919
|
-
country: geo.country,
|
|
920
|
-
city: geo.city
|
|
921
|
-
});
|
|
922
|
-
} catch (error) {
|
|
923
|
-
console.error("Failed to log login activity", error);
|
|
924
|
-
}
|
|
1351
|
+
var _a2, _b2, _c2, _d2;
|
|
1352
|
+
await packageSessionCreated(session, context);
|
|
1353
|
+
await ((_d2 = (_c2 = (_b2 = (_a2 = overrides.databaseHooks) == null ? void 0 : _a2.session) == null ? void 0 : _b2.create) == null ? void 0 : _c2.after) == null ? void 0 : _d2.call(_c2, session, context));
|
|
925
1354
|
}
|
|
926
1355
|
}
|
|
927
1356
|
}
|
|
@@ -935,9 +1364,9 @@ function createAuth(overrides = {}) {
|
|
|
935
1364
|
// available together.
|
|
936
1365
|
hooks: {
|
|
937
1366
|
before: api.createAuthMiddleware(async (ctx) => {
|
|
938
|
-
var
|
|
1367
|
+
var _a2, _b2, _c2, _d2;
|
|
939
1368
|
if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
|
|
940
|
-
const fingerprint = (
|
|
1369
|
+
const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
|
|
941
1370
|
const ip = getClientIp(ctx.headers);
|
|
942
1371
|
const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
|
|
943
1372
|
if (throttled) {
|
|
@@ -947,7 +1376,7 @@ function createAuth(overrides = {}) {
|
|
|
947
1376
|
}
|
|
948
1377
|
}
|
|
949
1378
|
if (ctx.path === "/sign-in/social") {
|
|
950
|
-
if (((
|
|
1379
|
+
if (((_b2 = ctx.body) == null ? void 0 : _b2.provider) === "google") {
|
|
951
1380
|
const flags = await getEffectiveAuthFlags();
|
|
952
1381
|
if (!flags.google) {
|
|
953
1382
|
throw new api.APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
|
|
@@ -969,6 +1398,9 @@ function createAuth(overrides = {}) {
|
|
|
969
1398
|
}
|
|
970
1399
|
return;
|
|
971
1400
|
}
|
|
1401
|
+
if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
|
|
1402
|
+
throw new api.APIError("FORBIDDEN", { message: "Impersonation is turned off." });
|
|
1403
|
+
}
|
|
972
1404
|
if (ctx.path === "/delete-user") {
|
|
973
1405
|
const current2 = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
|
|
974
1406
|
if (!current2) return;
|
|
@@ -990,13 +1422,13 @@ function createAuth(overrides = {}) {
|
|
|
990
1422
|
await logActivity({
|
|
991
1423
|
userId: current.session.impersonatedBy,
|
|
992
1424
|
action: "impersonation_stopped",
|
|
993
|
-
description: `Admin stopped impersonating ${(
|
|
1425
|
+
description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
|
|
994
1426
|
metadata: { impersonatedUserId: current.session.userId }
|
|
995
1427
|
});
|
|
996
1428
|
}
|
|
997
1429
|
}),
|
|
998
1430
|
after: api.createAuthMiddleware(async (ctx) => {
|
|
999
|
-
var
|
|
1431
|
+
var _a2, _b2, _c2, _d2;
|
|
1000
1432
|
if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
|
|
1001
1433
|
if (ctx.context.returned instanceof api.APIError) return;
|
|
1002
1434
|
await notifyPasskeyChange(
|
|
@@ -1006,15 +1438,15 @@ function createAuth(overrides = {}) {
|
|
|
1006
1438
|
return;
|
|
1007
1439
|
}
|
|
1008
1440
|
if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
|
|
1009
|
-
const fingerprint = (
|
|
1441
|
+
const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
|
|
1010
1442
|
const ip = getClientIp(ctx.headers);
|
|
1011
1443
|
const ipKey = ip ? `ip:${ip}` : null;
|
|
1012
1444
|
if (!fingerprint && !ipKey) return;
|
|
1013
1445
|
const failed = ctx.context.returned instanceof api.APIError;
|
|
1014
|
-
const rawEmail = (
|
|
1446
|
+
const rawEmail = (_b2 = ctx.body) == null ? void 0 : _b2.email;
|
|
1015
1447
|
const meta = {
|
|
1016
1448
|
ipAddress: ip,
|
|
1017
|
-
userAgent: (
|
|
1449
|
+
userAgent: (_d2 = (_c2 = ctx.headers) == null ? void 0 : _c2.get("user-agent")) != null ? _d2 : null,
|
|
1018
1450
|
email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
|
|
1019
1451
|
};
|
|
1020
1452
|
const keys = [fingerprint, ipKey].filter((k) => !!k);
|
|
@@ -1062,9 +1494,10 @@ function createAuth(overrides = {}) {
|
|
|
1062
1494
|
}
|
|
1063
1495
|
}
|
|
1064
1496
|
}),
|
|
1065
|
-
// TOTP second factor + encrypted backup codes
|
|
1066
|
-
//
|
|
1067
|
-
|
|
1497
|
+
// TOTP second factor + encrypted backup codes (see lib/two-factor.ts).
|
|
1498
|
+
// Listed individually, not spread: see the note on the spread below.
|
|
1499
|
+
twoFactorPlugin,
|
|
1500
|
+
twoFactorExtras,
|
|
1068
1501
|
// WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
|
|
1069
1502
|
// passwordless sign-in method. rpID must be the bare host and origin
|
|
1070
1503
|
// the full URL — both derived from baseURL above.
|
|
@@ -1076,7 +1509,9 @@ function createAuth(overrides = {}) {
|
|
|
1076
1509
|
// checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
|
|
1077
1510
|
// Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
|
|
1078
1511
|
// array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
|
|
1079
|
-
...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : []
|
|
1512
|
+
...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : [],
|
|
1513
|
+
appHooks,
|
|
1514
|
+
...(_f = overrides.plugins) != null ? _f : []
|
|
1080
1515
|
]
|
|
1081
1516
|
});
|
|
1082
1517
|
}
|