Spaces:
Running
Running
File size: 85,200 Bytes
5c05829 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 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 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 | import GoTrueAdminApi from './GoTrueAdminApi';
import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY } from './lib/constants';
import { AuthImplicitGrantRedirectError, AuthPKCEGrantCodeExchangeError, AuthInvalidCredentialsError, AuthSessionMissingError, AuthInvalidTokenResponseError, AuthUnknownError, isAuthApiError, isAuthError, isAuthRetryableFetchError, } from './lib/errors';
import { _request, _sessionResponse, _sessionResponsePassword, _userResponse, _ssoResponse, } from './lib/fetch';
import { decodeJWTPayload, Deferred, getItemAsync, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, generatePKCEVerifier, generatePKCEChallenge, supportsLocalStorage, parseParametersFromURL, } from './lib/helpers';
import { localStorageAdapter, memoryLocalStorageAdapter } from './lib/local-storage';
import { polyfillGlobalThis } from './lib/polyfills';
import { version } from './lib/version';
import { LockAcquireTimeoutError, navigatorLock } from './lib/locks';
polyfillGlobalThis(); // Make "globalThis" available
const DEFAULT_OPTIONS = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS,
flowType: 'implicit',
debug: false,
};
/** Current session will be checked for refresh at this interval. */
const AUTO_REFRESH_TICK_DURATION = 30 * 1000;
/**
* A token refresh will be attempted this many ticks before the current session expires. */
const AUTO_REFRESH_TICK_THRESHOLD = 3;
async function lockNoOp(name, acquireTimeout, fn) {
return await fn();
}
export default class GoTrueClient {
/**
* Create a new client for use in the browser.
*/
constructor(options) {
var _a, _b;
this.memoryStorage = null;
this.stateChangeEmitters = new Map();
this.autoRefreshTicker = null;
this.visibilityChangedCallback = null;
this.refreshingDeferred = null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the the auth state is known and it's save to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
this.initializePromise = null;
this.detectSessionInUrl = true;
this.lockAcquired = false;
this.pendingInLock = [];
/**
* Used to broadcast state change events to other tabs listening.
*/
this.broadcastChannel = null;
this.logger = console.log;
this.instanceID = GoTrueClient.nextInstanceID;
GoTrueClient.nextInstanceID += 1;
if (this.instanceID > 0 && isBrowser()) {
console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.');
}
const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
this.logDebugMessages = !!settings.debug;
if (typeof settings.debug === 'function') {
this.logger = settings.debug;
}
this.persistSession = settings.persistSession;
this.storageKey = settings.storageKey;
this.autoRefreshToken = settings.autoRefreshToken;
this.admin = new GoTrueAdminApi({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch,
});
this.url = settings.url;
this.headers = settings.headers;
this.fetch = resolveFetch(settings.fetch);
this.lock = settings.lock || lockNoOp;
this.detectSessionInUrl = settings.detectSessionInUrl;
this.flowType = settings.flowType;
if (settings.lock) {
this.lock = settings.lock;
}
else if (isBrowser() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) {
this.lock = navigatorLock;
}
else {
this.lock = lockNoOp;
}
this.mfa = {
verify: this._verify.bind(this),
enroll: this._enroll.bind(this),
unenroll: this._unenroll.bind(this),
challenge: this._challenge.bind(this),
listFactors: this._listFactors.bind(this),
challengeAndVerify: this._challengeAndVerify.bind(this),
getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
};
if (this.persistSession) {
if (settings.storage) {
this.storage = settings.storage;
}
else {
if (supportsLocalStorage()) {
this.storage = localStorageAdapter;
}
else {
this.memoryStorage = {};
this.storage = memoryLocalStorageAdapter(this.memoryStorage);
}
}
}
else {
this.memoryStorage = {};
this.storage = memoryLocalStorageAdapter(this.memoryStorage);
}
if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
try {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
}
catch (e) {
console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e);
}
(_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => {
this._debug('received broadcast notification from other tab or client', event);
await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages
});
}
this.initialize();
}
_debug(...args) {
if (this.logDebugMessages) {
this.logger(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args);
}
return this;
}
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
async initialize() {
if (this.initializePromise) {
return await this.initializePromise;
}
this.initializePromise = (async () => {
return await this._acquireLock(-1, async () => {
return await this._initialize();
});
})();
return await this.initializePromise;
}
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
async _initialize() {
try {
const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false;
this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow);
if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) {
const { data, error } = await this._getSessionFromURL(isPKCEFlow);
if (error) {
this._debug('#_initialize()', 'error detecting session from URL', error);
// hacky workaround to keep the existing session if there's an error returned from identity linking
// TODO: once error codes are ready, we should match against it instead of the message
if ((error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked' ||
(error === null || error === void 0 ? void 0 : error.message) === 'Identity is already linked to another user') {
return { error };
}
// failed login attempt via url,
// remove old session as in verifyOtp, signUp and signInWith*
await this._removeSession();
return { error };
}
const { session, redirectType } = data;
this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType);
await this._saveSession(session);
setTimeout(async () => {
if (redirectType === 'recovery') {
await this._notifyAllSubscribers('PASSWORD_RECOVERY', session);
}
else {
await this._notifyAllSubscribers('SIGNED_IN', session);
}
}, 0);
return { error: null };
}
// no login attempt via callback url try to recover session from storage
await this._recoverAndRefresh();
return { error: null };
}
catch (error) {
if (isAuthError(error)) {
return { error };
}
return {
error: new AuthUnknownError('Unexpected error during initialization', error),
};
}
finally {
await this._handleVisibilityChange();
this._debug('#_initialize()', 'end');
}
}
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
async signUp(credentials) {
var _a, _b, _c;
try {
await this._removeSession();
let res;
if ('email' in credentials) {
const { email, password, options } = credentials;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce') {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
}
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
body: {
email,
password,
data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
xform: _sessionResponse,
});
}
else if ('phone' in credentials) {
const { phone, password, options } = credentials;
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
phone,
password,
data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},
channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms',
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: _sessionResponse,
});
}
else {
throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
}
const { data, error } = res;
if (error || !data) {
return { data: { user: null, session: null }, error: error };
}
const session = data.session;
const user = data.user;
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers('SIGNED_IN', session);
}
return { data: { user, session }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
async signInWithPassword(credentials) {
try {
await this._removeSession();
let res;
if ('email' in credentials) {
const { email, password, options } = credentials;
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
email,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: _sessionResponsePassword,
});
}
else if ('phone' in credentials) {
const { phone, password, options } = credentials;
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
phone,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: _sessionResponsePassword,
});
}
else {
throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
}
const { data, error } = res;
if (error) {
return { data: { user: null, session: null }, error };
}
else if (!data || !data.session || !data.user) {
return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() };
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers('SIGNED_IN', data.session);
}
return {
data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)),
error,
};
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
async signInWithOAuth(credentials) {
var _a, _b, _c, _d;
await this._removeSession();
return await this._handleProviderSignIn(credentials.provider, {
redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect,
});
}
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
async exchangeCodeForSession(authCode) {
await this.initializePromise;
return this._acquireLock(-1, async () => {
return this._exchangeCodeForSession(authCode);
});
}
async _exchangeCodeForSession(authCode) {
const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/');
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, {
headers: this.headers,
body: {
auth_code: authCode,
code_verifier: codeVerifier,
},
xform: _sessionResponse,
});
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
if (error) {
return { data: { user: null, session: null, redirectType: null }, error };
}
else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null, redirectType: null },
error: new AuthInvalidTokenResponseError(),
};
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers('SIGNED_IN', data.session);
}
return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error };
}
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
async signInWithIdToken(credentials) {
await this._removeSession();
try {
const { options, provider, token, access_token, nonce } = credentials;
const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {
headers: this.headers,
body: {
provider,
id_token: token,
access_token,
nonce,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: _sessionResponse,
});
const { data, error } = res;
if (error) {
return { data: { user: null, session: null }, error };
}
else if (!data || !data.session || !data.user) {
return {
data: { user: null, session: null },
error: new AuthInvalidTokenResponseError(),
};
}
if (data.session) {
await this._saveSession(data.session);
await this._notifyAllSubscribers('SIGNED_IN', data.session);
}
return { data, error };
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
async signInWithOtp(credentials) {
var _a, _b, _c, _d, _e;
try {
await this._removeSession();
if ('email' in credentials) {
const { email, options } = credentials;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce') {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
}
const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
headers: this.headers,
body: {
email,
data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
});
return { data: { user: null, session: null }, error };
}
if ('phone' in credentials) {
const { phone, options } = credentials;
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
headers: this.headers,
body: {
phone,
data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {},
create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms',
},
});
return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error };
}
throw new AuthInvalidCredentialsError('You must provide either an email or phone number.');
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
async verifyOtp(params) {
var _a, _b;
try {
if (params.type !== 'email_change' && params.type !== 'phone_change') {
// we don't want to remove the authenticated session if the user is performing an email_change or phone_change verification
await this._removeSession();
}
let redirectTo = undefined;
let captchaToken = undefined;
if ('options' in params) {
redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo;
captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken;
}
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {
headers: this.headers,
body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }),
redirectTo,
xform: _sessionResponse,
});
if (error) {
throw error;
}
if (!data) {
throw new Error('An error occurred on token verification.');
}
const session = data.session;
const user = data.user;
if (session === null || session === void 0 ? void 0 : session.access_token) {
await this._saveSession(session);
await this._notifyAllSubscribers('SIGNED_IN', session);
}
return { data: { user, session }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
async signInWithSSO(params) {
var _a, _b, _c;
try {
await this._removeSession();
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce') {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
}
return await _request(this.fetch, 'POST', `${this.url}/sso`, {
body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken)
? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }
: null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
headers: this.headers,
xform: _ssoResponse,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
async reauthenticate() {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._reauthenticate();
});
}
async _reauthenticate() {
try {
return await this._useSession(async (result) => {
const { data: { session }, error: sessionError, } = result;
if (sessionError)
throw sessionError;
if (!session)
throw new AuthSessionMissingError();
const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {
headers: this.headers,
jwt: session.access_token,
});
return { data: { user: null, session: null }, error };
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
async resend(credentials) {
try {
if (credentials.type != 'email_change' && credentials.type != 'phone_change') {
await this._removeSession();
}
const endpoint = `${this.url}/resend`;
if ('email' in credentials) {
const { email, type, options } = credentials;
const { error } = await _request(this.fetch, 'POST', endpoint, {
headers: this.headers,
body: {
email,
type,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
});
return { data: { user: null, session: null }, error };
}
else if ('phone' in credentials) {
const { phone, type, options } = credentials;
const { data, error } = await _request(this.fetch, 'POST', endpoint, {
headers: this.headers,
body: {
phone,
type,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
});
return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error };
}
throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type');
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Returns the session, refreshing it if necessary.
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*/
async getSession() {
await this.initializePromise;
return this._acquireLock(-1, async () => {
return this._useSession(async (result) => {
return result;
});
});
}
/**
* Acquires a global lock based on the storage key.
*/
async _acquireLock(acquireTimeout, fn) {
this._debug('#_acquireLock', 'begin', acquireTimeout);
try {
if (this.lockAcquired) {
const last = this.pendingInLock.length
? this.pendingInLock[this.pendingInLock.length - 1]
: Promise.resolve();
const result = (async () => {
await last;
return await fn();
})();
this.pendingInLock.push((async () => {
try {
await result;
}
catch (e) {
// we just care if it finished
}
})());
return result;
}
return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {
this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey);
try {
this.lockAcquired = true;
const result = fn();
this.pendingInLock.push((async () => {
try {
await result;
}
catch (e) {
// we just care if it finished
}
})());
await result;
// keep draining the queue until there's nothing to wait on
while (this.pendingInLock.length) {
const waitOn = [...this.pendingInLock];
await Promise.all(waitOn);
this.pendingInLock.splice(0, waitOn.length);
}
return await result;
}
finally {
this._debug('#_acquireLock', 'lock released for storage key', this.storageKey);
this.lockAcquired = false;
}
});
}
finally {
this._debug('#_acquireLock', 'end');
}
}
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
async _useSession(fn) {
this._debug('#_useSession', 'begin');
try {
// the use of __loadSession here is the only correct use of the function!
const result = await this.__loadSession();
return await fn(result);
}
finally {
this._debug('#_useSession', 'end');
}
}
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
async __loadSession() {
this._debug('#__loadSession()', 'begin');
if (!this.lockAcquired) {
this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack);
}
try {
let currentSession = null;
const maybeSession = await getItemAsync(this.storage, this.storageKey);
this._debug('#getSession()', 'session from storage', maybeSession);
if (maybeSession !== null) {
if (this._isValidSession(maybeSession)) {
currentSession = maybeSession;
}
else {
this._debug('#getSession()', 'session from storage is not valid');
await this._removeSession();
}
}
if (!currentSession) {
return { data: { session: null }, error: null };
}
const hasExpired = currentSession.expires_at
? currentSession.expires_at <= Date.now() / 1000
: false;
this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at);
if (!hasExpired) {
return { data: { session: currentSession }, error: null };
}
const { session, error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { session: null }, error };
}
return { data: { session }, error: null };
}
finally {
this._debug('#__loadSession()', 'end');
}
}
/**
* Gets the current user details if there is an existing session.
* @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session.
*/
async getUser(jwt) {
if (jwt) {
return await this._getUser(jwt);
}
await this.initializePromise;
return this._acquireLock(-1, async () => {
return await this._getUser();
});
}
async _getUser(jwt) {
try {
if (jwt) {
return await _request(this.fetch, 'GET', `${this.url}/user`, {
headers: this.headers,
jwt: jwt,
xform: _userResponse,
});
}
return await this._useSession(async (result) => {
var _a, _b;
const { data, error } = result;
if (error) {
throw error;
}
return await _request(this.fetch, 'GET', `${this.url}/user`, {
headers: this.headers,
jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined,
xform: _userResponse,
});
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Updates user data for a logged in user.
*/
async updateUser(attributes, options = {}) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._updateUser(attributes, options);
});
}
async _updateUser(attributes, options = {}) {
try {
return await this._useSession(async (result) => {
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
throw sessionError;
}
if (!sessionData.session) {
throw new AuthSessionMissingError();
}
const session = sessionData.session;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce' && attributes.email != null) {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
}
const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {
headers: this.headers,
redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
jwt: session.access_token,
xform: _userResponse,
});
if (userError)
throw userError;
session.user = data.user;
await this._saveSession(session);
await this._notifyAllSubscribers('USER_UPDATED', session);
return { data: { user: session.user }, error: null };
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null }, error };
}
throw error;
}
}
/**
* Decodes a JWT (without performing any validation).
*/
_decodeJWT(jwt) {
return decodeJWTPayload(jwt);
}
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
async setSession(currentSession) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._setSession(currentSession);
});
}
async _setSession(currentSession) {
try {
if (!currentSession.access_token || !currentSession.refresh_token) {
throw new AuthSessionMissingError();
}
const timeNow = Date.now() / 1000;
let expiresAt = timeNow;
let hasExpired = true;
let session = null;
const payload = decodeJWTPayload(currentSession.access_token);
if (payload.exp) {
expiresAt = payload.exp;
hasExpired = expiresAt <= timeNow;
}
if (hasExpired) {
const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { user: null, session: null }, error: error };
}
if (!refreshedSession) {
return { data: { user: null, session: null }, error: null };
}
session = refreshedSession;
}
else {
const { data, error } = await this._getUser(currentSession.access_token);
if (error) {
throw error;
}
session = {
access_token: currentSession.access_token,
refresh_token: currentSession.refresh_token,
user: data.user,
token_type: 'bearer',
expires_in: expiresAt - timeNow,
expires_at: expiresAt,
};
await this._saveSession(session);
await this._notifyAllSubscribers('SIGNED_IN', session);
}
return { data: { user: session.user, session }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { session: null, user: null }, error };
}
throw error;
}
}
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
async refreshSession(currentSession) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._refreshSession(currentSession);
});
}
async _refreshSession(currentSession) {
try {
return await this._useSession(async (result) => {
var _a;
if (!currentSession) {
const { data, error } = result;
if (error) {
throw error;
}
currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined;
}
if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
throw new AuthSessionMissingError();
}
const { session, error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
return { data: { user: null, session: null }, error: error };
}
if (!session) {
return { data: { user: null, session: null }, error: null };
}
return { data: { user: session.user, session }, error: null };
});
}
catch (error) {
if (isAuthError(error)) {
return { data: { user: null, session: null }, error };
}
throw error;
}
}
/**
* Gets the session data from a URL string
*/
async _getSessionFromURL(isPKCEFlow) {
try {
if (!isBrowser())
throw new AuthImplicitGrantRedirectError('No browser detected.');
if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) {
throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.');
}
else if (this.flowType == 'pkce' && !isPKCEFlow) {
throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.');
}
const params = parseParametersFromURL(window.location.href);
if (isPKCEFlow) {
if (!params.code)
throw new AuthPKCEGrantCodeExchangeError('No code detected.');
const { data, error } = await this._exchangeCodeForSession(params.code);
if (error)
throw error;
const url = new URL(window.location.href);
url.searchParams.delete('code');
window.history.replaceState(window.history.state, '', url.toString());
return { data: { session: data.session, redirectType: null }, error: null };
}
if (params.error || params.error_description || params.error_code) {
throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', {
error: params.error || 'unspecified_error',
code: params.error_code || 'unspecified_code',
});
}
const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params;
if (!access_token || !expires_in || !refresh_token || !token_type) {
throw new AuthImplicitGrantRedirectError('No session defined in URL');
}
const timeNow = Math.round(Date.now() / 1000);
const expiresIn = parseInt(expires_in);
let expiresAt = timeNow + expiresIn;
if (expires_at) {
expiresAt = parseInt(expires_at);
}
const actuallyExpiresIn = expiresAt - timeNow;
if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION) {
console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`);
}
const issuedAt = expiresAt - expiresIn;
if (timeNow - issuedAt >= 120) {
console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow);
}
else if (timeNow - issuedAt < 0) {
console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew', issuedAt, expiresAt, timeNow);
}
const { data, error } = await this._getUser(access_token);
if (error)
throw error;
const session = {
provider_token,
provider_refresh_token,
access_token,
expires_in: expiresIn,
expires_at: expiresAt,
refresh_token,
token_type,
user: data.user,
};
// Remove tokens from URL
window.location.hash = '';
this._debug('#_getSessionFromURL()', 'clearing window.location.hash');
return { data: { session, redirectType: params.type }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { session: null, redirectType: null }, error };
}
throw error;
}
}
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*/
_isImplicitGrantFlow() {
const params = parseParametersFromURL(window.location.href);
return !!(isBrowser() && (params.access_token || params.error_description));
}
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
async _isPKCEFlow() {
const params = parseParametersFromURL(window.location.href);
const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
return !!(params.code && currentStorageContent);
}
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
async signOut(options = { scope: 'global' }) {
await this.initializePromise;
return await this._acquireLock(-1, async () => {
return await this._signOut(options);
});
}
async _signOut({ scope } = { scope: 'global' }) {
return await this._useSession(async (result) => {
var _a;
const { data, error: sessionError } = result;
if (sessionError) {
return { error: sessionError };
}
const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;
if (accessToken) {
const { error } = await this.admin.signOut(accessToken, scope);
if (error) {
// ignore 404s since user might not exist anymore
// ignore 401s since an invalid or expired JWT should sign out the current session
if (!(isAuthApiError(error) && (error.status === 404 || error.status === 401))) {
return { error };
}
}
}
if (scope !== 'others') {
await this._removeSession();
await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
await this._notifyAllSubscribers('SIGNED_OUT', null);
}
return { error: null };
});
}
/**
* Receive a notification every time an auth event happens.
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback) {
const id = uuid();
const subscription = {
id,
callback,
unsubscribe: () => {
this._debug('#unsubscribe()', 'state change callback with id removed', id);
this.stateChangeEmitters.delete(id);
},
};
this._debug('#onAuthStateChange()', 'registered callback with id', id);
this.stateChangeEmitters.set(id, subscription);
(async () => {
await this.initializePromise;
await this._acquireLock(-1, async () => {
this._emitInitialSession(id);
});
})();
return { data: { subscription } };
}
async _emitInitialSession(id) {
return await this._useSession(async (result) => {
var _a, _b;
try {
const { data: { session }, error, } = result;
if (error)
throw error;
await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session));
this._debug('INITIAL_SESSION', 'callback id', id, 'session', session);
}
catch (err) {
await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null));
this._debug('INITIAL_SESSION', 'callback id', id, 'error', err);
console.error(err);
}
});
}
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
async resetPasswordForEmail(email, options = {}) {
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce') {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, `${codeVerifier}/PASSWORD_RECOVERY`);
codeChallenge = await generatePKCEChallenge(codeVerifier);
codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
}
try {
return await _request(this.fetch, 'POST', `${this.url}/recover`, {
body: {
email,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
gotrue_meta_security: { captcha_token: options.captchaToken },
},
headers: this.headers,
redirectTo: options.redirectTo,
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Gets all the identities linked to a user.
*/
async getUserIdentities() {
var _a;
try {
const { data, error } = await this.getUser();
if (error)
throw error;
return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
async linkIdentity(credentials) {
var _a;
try {
const { data, error } = await this._useSession(async (result) => {
var _a, _b, _c, _d, _e;
const { data, error } = result;
if (error)
throw error;
const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
skipBrowserRedirect: true,
});
return await _request(this.fetch, 'GET', url, {
headers: this.headers,
jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined,
});
});
if (error)
throw error;
if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) {
window.location.assign(data === null || data === void 0 ? void 0 : data.url);
}
return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null };
}
catch (error) {
if (isAuthError(error)) {
return { data: { provider: credentials.provider, url: null }, error };
}
throw error;
}
}
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
async unlinkIdentity(identity) {
try {
return await this._useSession(async (result) => {
var _a, _b;
const { data, error } = result;
if (error) {
throw error;
}
return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, {
headers: this.headers,
jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined,
});
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
async _refreshAccessToken(refreshToken) {
const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`;
this._debug(debugName, 'begin');
try {
const startedAt = Date.now();
// will attempt to refresh the token with exponential backoff
return await retryable(async (attempt) => {
await sleep(attempt * 200); // 0, 200, 400, 800, ...
this._debug(debugName, 'refreshing attempt', attempt);
return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {
body: { refresh_token: refreshToken },
headers: this.headers,
xform: _sessionResponse,
});
}, (attempt, _, result) => result &&
result.error &&
isAuthRetryableFetchError(result.error) &&
// retryable only if the request can be sent before the backoff overflows the tick duration
Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION);
}
catch (error) {
this._debug(debugName, 'error', error);
if (isAuthError(error)) {
return { data: { session: null, user: null }, error };
}
throw error;
}
finally {
this._debug(debugName, 'end');
}
}
_isValidSession(maybeSession) {
const isValidSession = typeof maybeSession === 'object' &&
maybeSession !== null &&
'access_token' in maybeSession &&
'refresh_token' in maybeSession &&
'expires_at' in maybeSession;
return isValidSession;
}
async _handleProviderSignIn(provider, options) {
const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, {
redirectTo: options.redirectTo,
scopes: options.scopes,
queryParams: options.queryParams,
});
this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url);
// try to open on the browser
if (isBrowser() && !options.skipBrowserRedirect) {
window.location.assign(url);
}
return { data: { provider, url }, error: null };
}
/**
* Recovers the session from LocalStorage and refreshes
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
async _recoverAndRefresh() {
var _a;
const debugName = '#_recoverAndRefresh()';
this._debug(debugName, 'begin');
try {
const currentSession = await getItemAsync(this.storage, this.storageKey);
this._debug(debugName, 'session from storage', currentSession);
if (!this._isValidSession(currentSession)) {
this._debug(debugName, 'session is not valid');
if (currentSession !== null) {
await this._removeSession();
}
return;
}
const timeNow = Math.round(Date.now() / 1000);
const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN;
this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s`);
if (expiresWithMargin) {
if (this.autoRefreshToken && currentSession.refresh_token) {
const { error } = await this._callRefreshToken(currentSession.refresh_token);
if (error) {
console.error(error);
if (!isAuthRetryableFetchError(error)) {
this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error);
await this._removeSession();
}
}
}
}
else {
// no need to persist currentSession again, as we just loaded it from
// local storage; persisting it again may overwrite a value saved by
// another client with access to the same local storage
await this._notifyAllSubscribers('SIGNED_IN', currentSession);
}
}
catch (err) {
this._debug(debugName, 'error', err);
console.error(err);
return;
}
finally {
this._debug(debugName, 'end');
}
}
async _callRefreshToken(refreshToken) {
var _a, _b;
if (!refreshToken) {
throw new AuthSessionMissingError();
}
// refreshing is already in progress
if (this.refreshingDeferred) {
return this.refreshingDeferred.promise;
}
const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`;
this._debug(debugName, 'begin');
try {
this.refreshingDeferred = new Deferred();
const { data, error } = await this._refreshAccessToken(refreshToken);
if (error)
throw error;
if (!data.session)
throw new AuthSessionMissingError();
await this._saveSession(data.session);
await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session);
const result = { session: data.session, error: null };
this.refreshingDeferred.resolve(result);
return result;
}
catch (error) {
this._debug(debugName, 'error', error);
if (isAuthError(error)) {
const result = { session: null, error };
if (!isAuthRetryableFetchError(error)) {
await this._removeSession();
await this._notifyAllSubscribers('SIGNED_OUT', null);
}
(_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result);
return result;
}
(_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error);
throw error;
}
finally {
this.refreshingDeferred = null;
this._debug(debugName, 'end');
}
}
async _notifyAllSubscribers(event, session, broadcast = true) {
const debugName = `#_notifyAllSubscribers(${event})`;
this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`);
try {
if (this.broadcastChannel && broadcast) {
this.broadcastChannel.postMessage({ event, session });
}
const errors = [];
const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {
try {
await x.callback(event, session);
}
catch (e) {
errors.push(e);
}
});
await Promise.all(promises);
if (errors.length > 0) {
for (let i = 0; i < errors.length; i += 1) {
console.error(errors[i]);
}
throw errors[0];
}
}
finally {
this._debug(debugName, 'end');
}
}
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
async _saveSession(session) {
this._debug('#_saveSession()', session);
await setItemAsync(this.storage, this.storageKey, session);
}
async _removeSession() {
this._debug('#_removeSession()');
await removeItemAsync(this.storage, this.storageKey);
}
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
_removeVisibilityChangedCallback() {
this._debug('#_removeVisibilityChangedCallback()');
const callback = this.visibilityChangedCallback;
this.visibilityChangedCallback = null;
try {
if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) {
window.removeEventListener('visibilitychange', callback);
}
}
catch (e) {
console.error('removing visibilitychange callback failed', e);
}
}
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
async _startAutoRefresh() {
await this._stopAutoRefresh();
this._debug('#_startAutoRefresh()');
const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION);
this.autoRefreshTicker = ticker;
if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') {
// ticker is a NodeJS Timeout object that has an `unref` method
// https://nodejs.org/api/timers.html#timeoutunref
// When auto refresh is used in NodeJS (like for testing) the
// `setInterval` is preventing the process from being marked as
// finished and tests run endlessly. This can be prevented by calling
// `unref()` on the returned object.
ticker.unref();
// @ts-ignore
}
else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {
// similar like for NodeJS, but with the Deno API
// https://deno.land/api@latest?unstable&s=Deno.unrefTimer
// @ts-ignore
Deno.unrefTimer(ticker);
}
// run the tick immediately, but in the next pass of the event loop so that
// #_initialize can be allowed to complete without recursively waiting on
// itself
setTimeout(async () => {
await this.initializePromise;
await this._autoRefreshTokenTick();
}, 0);
}
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
async _stopAutoRefresh() {
this._debug('#_stopAutoRefresh()');
const ticker = this.autoRefreshTicker;
this.autoRefreshTicker = null;
if (ticker) {
clearInterval(ticker);
}
}
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
async startAutoRefresh() {
this._removeVisibilityChangedCallback();
await this._startAutoRefresh();
}
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
async stopAutoRefresh() {
this._removeVisibilityChangedCallback();
await this._stopAutoRefresh();
}
/**
* Runs the auto refresh token tick.
*/
async _autoRefreshTokenTick() {
this._debug('#_autoRefreshTokenTick()', 'begin');
try {
await this._acquireLock(0, async () => {
try {
const now = Date.now();
try {
return await this._useSession(async (result) => {
const { data: { session }, } = result;
if (!session || !session.refresh_token || !session.expires_at) {
this._debug('#_autoRefreshTokenTick()', 'no session');
return;
}
// session will expire in this many ticks (or has already expired if <= 0)
const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION);
this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);
if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {
await this._callRefreshToken(session.refresh_token);
}
});
}
catch (e) {
console.error('Auto refresh tick failed with error. This is likely a transient error.', e);
}
}
finally {
this._debug('#_autoRefreshTokenTick()', 'end');
}
});
}
catch (e) {
if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) {
this._debug('auto refresh token tick lock not available');
}
else {
throw e;
}
}
}
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
async _handleVisibilityChange() {
this._debug('#_handleVisibilityChange()');
if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
if (this.autoRefreshToken) {
// in non-browser environments the refresh token ticker runs always
this.startAutoRefresh();
}
return false;
}
try {
this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false);
window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback);
// now immediately call the visbility changed callback to setup with the
// current visbility state
await this._onVisibilityChanged(true); // initial call
}
catch (error) {
console.error('_handleVisibilityChange', error);
}
}
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
async _onVisibilityChanged(calledFromInitialize) {
const methodName = `#_onVisibilityChanged(${calledFromInitialize})`;
this._debug(methodName, 'visibilityState', document.visibilityState);
if (document.visibilityState === 'visible') {
if (this.autoRefreshToken) {
// in browser environments the refresh token ticker runs only on focused tabs
// which prevents race conditions
this._startAutoRefresh();
}
if (!calledFromInitialize) {
// called when the visibility has changed, i.e. the browser
// transitioned from hidden -> visible so we need to see if the session
// should be recovered immediately... but to do that we need to acquire
// the lock first asynchronously
await this.initializePromise;
await this._acquireLock(-1, async () => {
if (document.visibilityState !== 'visible') {
this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting');
// visibility has changed while waiting for the lock, abort
return;
}
// recover the session
await this._recoverAndRefresh();
});
}
}
else if (document.visibilityState === 'hidden') {
if (this.autoRefreshToken) {
this._stopAutoRefresh();
}
}
}
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
async _getUrlForProvider(url, provider, options) {
const urlParams = [`provider=${encodeURIComponent(provider)}`];
if (options === null || options === void 0 ? void 0 : options.redirectTo) {
urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`);
}
if (options === null || options === void 0 ? void 0 : options.scopes) {
urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`);
}
if (this.flowType === 'pkce') {
const codeVerifier = generatePKCEVerifier();
await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier);
const codeChallenge = await generatePKCEChallenge(codeVerifier);
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256';
this._debug('PKCE', 'code verifier', `${codeVerifier.substring(0, 5)}...`, 'code challenge', codeChallenge, 'method', codeChallengeMethod);
const flowParams = new URLSearchParams({
code_challenge: `${encodeURIComponent(codeChallenge)}`,
code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,
});
urlParams.push(flowParams.toString());
}
if (options === null || options === void 0 ? void 0 : options.queryParams) {
const query = new URLSearchParams(options.queryParams);
urlParams.push(query.toString());
}
if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) {
urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`);
}
return `${url}?${urlParams.join('&')}`;
}
async _unenroll(params) {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
});
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* {@see GoTrueMFAApi#enroll}
*/
async _enroll(params) {
try {
return await this._useSession(async (result) => {
var _a, _b;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, {
body: {
friendly_name: params.friendlyName,
factor_type: params.factorType,
issuer: params.issuer,
},
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
});
if (error) {
return { data: null, error };
}
if ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code) {
data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`;
}
return { data, error: null };
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
}
/**
* {@see GoTrueMFAApi#verify}
*/
async _verify(params) {
return this._acquireLock(-1, async () => {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, {
body: { code: params.code, challenge_id: params.challengeId },
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
});
if (error) {
return { data: null, error };
}
await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data));
await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data);
return { data, error };
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* {@see GoTrueMFAApi#challenge}
*/
async _challenge(params) {
return this._acquireLock(-1, async () => {
try {
return await this._useSession(async (result) => {
var _a;
const { data: sessionData, error: sessionError } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
return await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, {
headers: this.headers,
jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
});
});
}
catch (error) {
if (isAuthError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
async _challengeAndVerify(params) {
// both _challenge and _verify independently acquire the lock, so no need
// to acquire it here
const { data: challengeData, error: challengeError } = await this._challenge({
factorId: params.factorId,
});
if (challengeError) {
return { data: null, error: challengeError };
}
return await this._verify({
factorId: params.factorId,
challengeId: challengeData.id,
code: params.code,
});
}
/**
* {@see GoTrueMFAApi#listFactors}
*/
async _listFactors() {
// use #getUser instead of #_getUser as the former acquires a lock
const { data: { user }, error: userError, } = await this.getUser();
if (userError) {
return { data: null, error: userError };
}
const factors = (user === null || user === void 0 ? void 0 : user.factors) || [];
const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified');
return {
data: {
all: factors,
totp,
},
error: null,
};
}
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
async _getAuthenticatorAssuranceLevel() {
return this._acquireLock(-1, async () => {
return await this._useSession(async (result) => {
var _a, _b;
const { data: { session }, error: sessionError, } = result;
if (sessionError) {
return { data: null, error: sessionError };
}
if (!session) {
return {
data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },
error: null,
};
}
const payload = this._decodeJWT(session.access_token);
let currentLevel = null;
if (payload.aal) {
currentLevel = payload.aal;
}
let nextLevel = currentLevel;
const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : [];
if (verifiedFactors.length > 0) {
nextLevel = 'aal2';
}
const currentAuthenticationMethods = payload.amr || [];
return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };
});
});
}
}
GoTrueClient.nextInstanceID = 0;
//# sourceMappingURL=GoTrueClient.js.map |