@capgo/capacitor-social-login 8.5.2 → 8.5.3

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/dist/plugin.js CHANGED
@@ -72,7 +72,13 @@ var capacitorCapacitorUpdater = (function (exports, core) {
72
72
  const OAUTH_POPUP_SESSION_KEY = 'social_login_oauth_popup';
73
73
  const OAUTH_RESULT_KEY_PREFIX = 'social_login_oauth_result_';
74
74
  const OAUTH_DELIVERED_KEY = 'social_login_oauth_delivered';
75
- const POPUP_WINDOW_NAMES = new Set(['OAuth2Login', 'XLogin', 'Google Sign In', 'Authorization']);
75
+ const POPUP_WINDOW_NAMES = new Set([
76
+ 'OAuth2Login',
77
+ 'XLogin',
78
+ 'Google Sign In',
79
+ 'Authorization',
80
+ 'TelegramLogin',
81
+ ]);
76
82
  function getOAuthResultKey(nonce) {
77
83
  return `${OAUTH_RESULT_KEY_PREFIX}${nonce}`;
78
84
  }
@@ -81,6 +87,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
81
87
  return `oauth2_${nonceOrState}`;
82
88
  if (provider === 'twitter')
83
89
  return `twitter_oauth_${nonceOrState}`;
90
+ if (provider === 'telegram')
91
+ return `telegram_oauth_${nonceOrState}`;
84
92
  return `google_oauth_${nonceOrState}`;
85
93
  }
86
94
  function markOAuthPopup(nonce) {
@@ -101,12 +109,14 @@ var capacitorCapacitorUpdater = (function (exports, core) {
101
109
  }
102
110
  }
103
111
  function hasOAuthRedirectParams() {
104
- const { search, hash } = window.location;
105
- return (search.includes('code=') ||
106
- search.includes('error=') ||
107
- hash.includes('access_token=') ||
108
- hash.includes('id_token=') ||
109
- hash.includes('error='));
112
+ const search = new URLSearchParams(window.location.search);
113
+ const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''));
114
+ return (search.has('code') ||
115
+ search.has('error') ||
116
+ (search.has('hash') && search.has('auth_date')) ||
117
+ hash.has('access_token') ||
118
+ hash.has('id_token') ||
119
+ hash.has('error'));
110
120
  }
111
121
  function isOAuthPopupContext() {
112
122
  if (typeof window === 'undefined')
@@ -1410,6 +1420,294 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1410
1420
  }
1411
1421
  }
1412
1422
 
1423
+ class TelegramSocialLogin extends BaseSocialLogin {
1424
+ constructor() {
1425
+ super(...arguments);
1426
+ this.botId = null;
1427
+ this.redirectUrl = null;
1428
+ this.origin = null;
1429
+ this.requestAccess = 'write';
1430
+ this.languageCode = null;
1431
+ this.TOKENS_KEY = 'capgo_social_login_telegram_session_v1';
1432
+ this.STATE_PREFIX = 'capgo_social_login_telegram_state_';
1433
+ this.SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h session window based on Telegram auth_date
1434
+ }
1435
+ initialize(botId, requestAccess, redirectUrl, origin, languageCode) {
1436
+ this.botId = botId;
1437
+ this.requestAccess = requestAccess !== null && requestAccess !== void 0 ? requestAccess : 'write';
1438
+ this.redirectUrl = redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : null;
1439
+ this.origin = origin !== null && origin !== void 0 ? origin : null;
1440
+ this.languageCode = languageCode !== null && languageCode !== void 0 ? languageCode : null;
1441
+ }
1442
+ async login(options) {
1443
+ var _a, _b, _c, _d, _e;
1444
+ if (!this.botId) {
1445
+ throw new Error('Telegram botId is not configured. Call initialize() first.');
1446
+ }
1447
+ const redirectUri = (_b = (_a = options.redirectUrl) !== null && _a !== void 0 ? _a : this.redirectUrl) !== null && _b !== void 0 ? _b : window.location.origin + window.location.pathname;
1448
+ const state = (_c = options.state) !== null && _c !== void 0 ? _c : this.generateState();
1449
+ const requestAccess = (_d = options.requestAccess) !== null && _d !== void 0 ? _d : this.requestAccess;
1450
+ const origin = (_e = this.origin) !== null && _e !== void 0 ? _e : this.getOriginFromRedirect(redirectUri);
1451
+ if (!this.isHttpOrigin(origin)) {
1452
+ throw new Error('Telegram origin must be a valid http(s) URL registered with BotFather. Pass origin when redirectUrl is not http(s).');
1453
+ }
1454
+ const returnTo = this.appendStateToRedirect(redirectUri, state);
1455
+ this.persistPendingLogin(state, {
1456
+ redirectUri,
1457
+ requestAccess,
1458
+ });
1459
+ localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, JSON.stringify({ provider: 'telegram', state }));
1460
+ const authUrl = this.buildAuthUrl(origin, requestAccess, returnTo);
1461
+ const popup = this.openPopup(authUrl);
1462
+ return new Promise((resolve, reject) => {
1463
+ if (!popup) {
1464
+ this.clearPendingTelegramState(state);
1465
+ reject(new Error('Unable to open login window. Please allow popups.'));
1466
+ return;
1467
+ }
1468
+ let settled = false;
1469
+ let timeoutHandle = 0;
1470
+ let popupClosedInterval = 0;
1471
+ let removeOAuthListener = null;
1472
+ const cleanup = (shouldClose = false) => {
1473
+ clearTimeout(timeoutHandle);
1474
+ clearInterval(popupClosedInterval);
1475
+ if (removeOAuthListener) {
1476
+ removeOAuthListener();
1477
+ removeOAuthListener = null;
1478
+ }
1479
+ this.clearPendingTelegramState(state);
1480
+ if (shouldClose) {
1481
+ try {
1482
+ popup.close();
1483
+ }
1484
+ catch (_a) {
1485
+ // ignore if already closed
1486
+ }
1487
+ }
1488
+ };
1489
+ const settle = (shouldClose, action) => {
1490
+ if (settled)
1491
+ return;
1492
+ settled = true;
1493
+ cleanup(shouldClose);
1494
+ action();
1495
+ };
1496
+ removeOAuthListener = listenForOAuthResult('telegram', state, {
1497
+ onResponse: (data) => {
1498
+ if ((data === null || data === void 0 ? void 0 : data.provider) && data.provider !== 'telegram') {
1499
+ return;
1500
+ }
1501
+ const _a = data, { provider: _ignoredProvider, type: _ignoredType, _ts: _ignoredTs } = _a, payload = __rest(_a, ["provider", "type", "_ts"]);
1502
+ settle(true, () => {
1503
+ resolve({
1504
+ provider: 'telegram',
1505
+ result: payload,
1506
+ });
1507
+ });
1508
+ },
1509
+ onError: (error, code) => {
1510
+ const message = error || 'Telegram login was cancelled.';
1511
+ settle(true, () => {
1512
+ reject(code === 'USER_CANCELLED' ? createUserCancelledError(message) : inferUserCancelledError(message));
1513
+ });
1514
+ },
1515
+ });
1516
+ timeoutHandle = window.setTimeout(() => {
1517
+ settle(true, () => {
1518
+ reject(new Error('Telegram login timed out.'));
1519
+ });
1520
+ }, 300000);
1521
+ popupClosedInterval = window.setInterval(() => {
1522
+ try {
1523
+ if (popup.closed) {
1524
+ settle(false, () => {
1525
+ reject(createUserCancelledError('Telegram login window was closed.'));
1526
+ });
1527
+ }
1528
+ }
1529
+ catch (_a) {
1530
+ clearInterval(popupClosedInterval);
1531
+ }
1532
+ }, 1000);
1533
+ });
1534
+ }
1535
+ async logout() {
1536
+ localStorage.removeItem(this.TOKENS_KEY);
1537
+ }
1538
+ async isLoggedIn() {
1539
+ const session = this.getStoredSession();
1540
+ if (!session) {
1541
+ return { isLoggedIn: false };
1542
+ }
1543
+ const isValid = session.expiresAt > Date.now();
1544
+ if (!isValid) {
1545
+ localStorage.removeItem(this.TOKENS_KEY);
1546
+ }
1547
+ return { isLoggedIn: isValid };
1548
+ }
1549
+ async getAuthorizationCode() {
1550
+ throw new Error('getAuthorizationCode is not available for Telegram.');
1551
+ }
1552
+ async refresh() {
1553
+ throw new Error('Telegram refresh is not supported. Call login() again.');
1554
+ }
1555
+ async handleOAuthRedirect(url, expectedState) {
1556
+ var _a;
1557
+ const params = url.searchParams;
1558
+ const stateFromUrl = params.get('state');
1559
+ if (!stateFromUrl) {
1560
+ return null;
1561
+ }
1562
+ if (expectedState && expectedState !== stateFromUrl) {
1563
+ return { error: 'Telegram login session expired or state mismatch.' };
1564
+ }
1565
+ const pending = this.consumePendingLogin(stateFromUrl);
1566
+ if (!pending) {
1567
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1568
+ return { error: 'Telegram login session expired or state mismatch.' };
1569
+ }
1570
+ const error = params.get('error');
1571
+ if (error) {
1572
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1573
+ return { error: params.get('error_description') || error };
1574
+ }
1575
+ const id = params.get('id');
1576
+ const authDateRaw = params.get('auth_date');
1577
+ const hash = params.get('hash');
1578
+ if (!id || !authDateRaw || !hash) {
1579
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1580
+ return { error: 'Telegram login payload is incomplete.' };
1581
+ }
1582
+ const profile = {
1583
+ id,
1584
+ firstName: (_a = params.get('first_name')) !== null && _a !== void 0 ? _a : '',
1585
+ lastName: params.get('last_name'),
1586
+ username: params.get('username'),
1587
+ photoUrl: params.get('photo_url'),
1588
+ };
1589
+ const authDate = Number(authDateRaw);
1590
+ if (!Number.isInteger(authDate)) {
1591
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1592
+ return { error: 'Telegram auth_date is invalid.' };
1593
+ }
1594
+ const result = {
1595
+ profile,
1596
+ authDate,
1597
+ hash,
1598
+ requestAccess: pending.requestAccess,
1599
+ };
1600
+ this.persistSession({
1601
+ expiresAt: authDate * 1000 + this.SESSION_TTL_MS,
1602
+ });
1603
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1604
+ return {
1605
+ provider: 'telegram',
1606
+ result,
1607
+ };
1608
+ }
1609
+ buildAuthUrl(origin, requestAccess, returnTo) {
1610
+ var _a;
1611
+ const params = new URLSearchParams({
1612
+ bot_id: (_a = this.botId) !== null && _a !== void 0 ? _a : '',
1613
+ origin,
1614
+ request_access: requestAccess,
1615
+ return_to: returnTo,
1616
+ embed: '1',
1617
+ mobile: '1',
1618
+ });
1619
+ if (this.languageCode) {
1620
+ params.set('lang', this.languageCode);
1621
+ }
1622
+ return `https://oauth.telegram.org/auth?${params.toString()}`;
1623
+ }
1624
+ openPopup(authUrl) {
1625
+ const width = 500;
1626
+ const height = 650;
1627
+ const left = window.screenX + (window.outerWidth - width) / 2;
1628
+ const top = window.screenY + (window.outerHeight - height) / 2;
1629
+ return window.open(authUrl, 'TelegramLogin', `width=${width},height=${height},left=${left},top=${top},popup=1`);
1630
+ }
1631
+ appendStateToRedirect(redirectUri, state) {
1632
+ try {
1633
+ const redirect = new URL(redirectUri);
1634
+ redirect.searchParams.set('state', state);
1635
+ return redirect.toString();
1636
+ }
1637
+ catch (_a) {
1638
+ return redirectUri;
1639
+ }
1640
+ }
1641
+ isHttpOrigin(value) {
1642
+ if (!value) {
1643
+ return false;
1644
+ }
1645
+ try {
1646
+ const url = new URL(value);
1647
+ return url.protocol === 'http:' || url.protocol === 'https:';
1648
+ }
1649
+ catch (_a) {
1650
+ return false;
1651
+ }
1652
+ }
1653
+ getOriginFromRedirect(redirectUri) {
1654
+ return this.isHttpOrigin(redirectUri) ? new URL(redirectUri).origin : undefined;
1655
+ }
1656
+ persistSession(session) {
1657
+ localStorage.setItem(this.TOKENS_KEY, JSON.stringify(session));
1658
+ }
1659
+ getStoredSession() {
1660
+ const raw = localStorage.getItem(this.TOKENS_KEY);
1661
+ if (!raw) {
1662
+ return null;
1663
+ }
1664
+ try {
1665
+ return JSON.parse(raw);
1666
+ }
1667
+ catch (err) {
1668
+ console.warn('Failed to parse stored Telegram session', err);
1669
+ return null;
1670
+ }
1671
+ }
1672
+ persistPendingLogin(state, payload) {
1673
+ localStorage.setItem(`${this.STATE_PREFIX}${state}`, JSON.stringify(payload));
1674
+ }
1675
+ consumePendingLogin(state) {
1676
+ const key = `${this.STATE_PREFIX}${state}`;
1677
+ const raw = localStorage.getItem(key);
1678
+ localStorage.removeItem(key);
1679
+ if (!raw) {
1680
+ return null;
1681
+ }
1682
+ try {
1683
+ return JSON.parse(raw);
1684
+ }
1685
+ catch (err) {
1686
+ console.warn('Failed to parse pending Telegram login payload', err);
1687
+ return null;
1688
+ }
1689
+ }
1690
+ clearPendingTelegramState(state) {
1691
+ try {
1692
+ localStorage.removeItem(`${this.STATE_PREFIX}${state}`);
1693
+ const raw = localStorage.getItem(BaseSocialLogin.OAUTH_STATE_KEY);
1694
+ if (!raw) {
1695
+ return;
1696
+ }
1697
+ const parsed = JSON.parse(raw);
1698
+ if (parsed.provider === 'telegram' && parsed.state === state) {
1699
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
1700
+ }
1701
+ }
1702
+ catch (_a) {
1703
+ // ignore storage errors
1704
+ }
1705
+ }
1706
+ generateState() {
1707
+ return [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('');
1708
+ }
1709
+ }
1710
+
1413
1711
  class TwitterSocialLogin extends BaseSocialLogin {
1414
1712
  constructor() {
1415
1713
  super(...arguments);
@@ -1801,11 +2099,15 @@ var capacitorCapacitorUpdater = (function (exports, core) {
1801
2099
  const googleProvider = new GoogleSocialLogin();
1802
2100
  const oauth2Provider = new OAuth2SocialLogin();
1803
2101
  const twitterProvider = new TwitterSocialLogin();
2102
+ const telegramProvider = new TelegramSocialLogin();
1804
2103
  let result = null;
1805
2104
  switch (provider) {
1806
2105
  case 'twitter':
1807
2106
  result = await twitterProvider.handleOAuthRedirect(url, state);
1808
2107
  break;
2108
+ case 'telegram':
2109
+ result = await telegramProvider.handleOAuthRedirect(url, state);
2110
+ break;
1809
2111
  case 'oauth2':
1810
2112
  result = await oauth2Provider.handleOAuthRedirect(url, state);
1811
2113
  break;
@@ -2448,6 +2750,7 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2448
2750
  this.appleProvider = new AppleSocialLogin();
2449
2751
  this.facebookProvider = new FacebookSocialLogin();
2450
2752
  this.twitterProvider = new TwitterSocialLogin();
2753
+ this.telegramProvider = new TelegramSocialLogin();
2451
2754
  this.oauth2Provider = new OAuth2SocialLogin();
2452
2755
  // Auto-finish OAuth redirects only when running inside a popup window.
2453
2756
  // For redirect-based flows (full page navigation), the app should call `handleRedirectCallback()` explicitly.
@@ -2487,6 +2790,9 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2487
2790
  case 'twitter':
2488
2791
  result = await this.twitterProvider.handleOAuthRedirect(url, state);
2489
2792
  break;
2793
+ case 'telegram':
2794
+ result = await this.telegramProvider.handleOAuthRedirect(url, state);
2795
+ break;
2490
2796
  case 'oauth2':
2491
2797
  result = await this.oauth2Provider.handleOAuthRedirect(url, state);
2492
2798
  break;
@@ -2527,7 +2833,7 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2527
2833
  }
2528
2834
  }
2529
2835
  async initialize(options) {
2530
- var _a, _b, _c, _d;
2836
+ var _a, _b, _c, _d, _e;
2531
2837
  const initPromises = [];
2532
2838
  if ((_a = options.google) === null || _a === void 0 ? void 0 : _a.webClientId) {
2533
2839
  initPromises.push(this.googleProvider.initialize(options.google.webClientId, options.google.mode, options.google.hostedDomain, options.google.redirectUrl));
@@ -2541,6 +2847,9 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2541
2847
  if ((_d = options.twitter) === null || _d === void 0 ? void 0 : _d.clientId) {
2542
2848
  initPromises.push(this.twitterProvider.initialize(options.twitter.clientId, options.twitter.redirectUrl, options.twitter.defaultScopes, options.twitter.forceLogin, options.twitter.audience));
2543
2849
  }
2850
+ if ((_e = options.telegram) === null || _e === void 0 ? void 0 : _e.botId) {
2851
+ this.telegramProvider.initialize(options.telegram.botId, options.telegram.requestAccess, options.telegram.redirectUrl, options.telegram.origin, options.telegram.languageCode);
2852
+ }
2544
2853
  if (options.oauth2 && Object.keys(options.oauth2).length > 0) {
2545
2854
  initPromises.push(this.oauth2Provider.initializeProviders(options.oauth2));
2546
2855
  }
@@ -2556,6 +2865,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2556
2865
  return this.facebookProvider.login(options.options);
2557
2866
  case 'twitter':
2558
2867
  return this.twitterProvider.login(options.options);
2868
+ case 'telegram':
2869
+ return this.telegramProvider.login(options.options);
2559
2870
  case 'oauth2':
2560
2871
  return this.oauth2Provider.login(options.options);
2561
2872
  default:
@@ -2572,6 +2883,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2572
2883
  return this.facebookProvider.logout();
2573
2884
  case 'twitter':
2574
2885
  return this.twitterProvider.logout();
2886
+ case 'telegram':
2887
+ return this.telegramProvider.logout();
2575
2888
  case 'oauth2':
2576
2889
  if (!options.providerId) {
2577
2890
  throw new Error('providerId is required for oauth2 logout');
@@ -2591,6 +2904,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2591
2904
  return this.facebookProvider.isLoggedIn();
2592
2905
  case 'twitter':
2593
2906
  return this.twitterProvider.isLoggedIn();
2907
+ case 'telegram':
2908
+ return this.telegramProvider.isLoggedIn();
2594
2909
  case 'oauth2':
2595
2910
  if (!options.providerId) {
2596
2911
  throw new Error('providerId is required for oauth2 isLoggedIn');
@@ -2629,6 +2944,8 @@ var capacitorCapacitorUpdater = (function (exports, core) {
2629
2944
  return this.facebookProvider.refresh(options.options);
2630
2945
  case 'twitter':
2631
2946
  return this.twitterProvider.refresh();
2947
+ case 'telegram':
2948
+ return this.telegramProvider.refresh();
2632
2949
  case 'oauth2': {
2633
2950
  const oauth2Options = options.options;
2634
2951
  if (!(oauth2Options === null || oauth2Options === void 0 ? void 0 : oauth2Options.providerId)) {