@sneat/auth-ui 0.27.20 → 0.27.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,25 @@
1
1
  import { DOCUMENT } from '@angular/common';
2
- import { Component, ElementRef, inject, ChangeDetectionStrategy, input } from '@angular/core';
2
+ import { ChangeDetectionStrategy, Component, DestroyRef, ElementRef, inject, input, signal, } from '@angular/core';
3
+ import { ErrorLogger } from '@sneat/core';
3
4
  import { SneatAuthWithTelegramService, } from './sneat-auth-with-telegram.service';
4
5
  import { TelegramLoginConfig, resolveTelegramBotID, } from './telegram-login-config';
6
+ import { loadTelegramLoginScript, telegramLoginApi, } from './telegram-login-js';
5
7
  import * as i0 from "@angular/core";
6
8
  let authWithTelegramService;
9
+ /** Server nonces live 10 minutes; refresh well inside that. */
10
+ const OIDC_NONCE_REFRESH_MS = 8 * 60 * 1000;
11
+ /**
12
+ * Telegram login button. Bots with OpenID login configured server-side use
13
+ * Telegram's OpenID popup (telegram-login.js); others keep the legacy Login
14
+ * Widget (telegram-widget.js), e.g. the local dev bot.
15
+ */
7
16
  export class LoginWithTelegramComponent {
8
17
  // TODO: Article about Telegram login
9
18
  constructor() {
10
19
  this.el = inject(ElementRef);
11
20
  this.document = inject(DOCUMENT);
21
+ this.destroyRef = inject(DestroyRef);
22
+ this.errorLogger = inject(ErrorLogger);
12
23
  this.authWithTelegram = inject(SneatAuthWithTelegramService);
13
24
  this.telegramLoginConfig = inject(TelegramLoginConfig, {
14
25
  optional: true,
@@ -23,69 +34,106 @@ export class LoginWithTelegramComponent {
23
34
  ...(ngDevMode ? [{ debugName: "requestAccess" }] : /* istanbul ignore next */ []));
24
35
  this.userPic = input(true, /* @ts-ignore */
25
36
  ...(ngDevMode ? [{ debugName: "userPic" }] : /* istanbul ignore next */ []));
37
+ /** Set once the OpenID popup can be offered: Client ID plus a live nonce. */
38
+ this.oidc = signal(undefined, /* @ts-ignore */
39
+ ...(ngDevMode ? [{ debugName: "oidc" }] : /* istanbul ignore next */ []));
26
40
  const authWithTelegram = this.authWithTelegram;
27
41
  authWithTelegramService = authWithTelegram;
28
42
  }
29
43
  ngOnInit() {
30
44
  const botID = this.botID();
31
- if (botID) {
32
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
33
- // @ts-ignore
34
- window.onTelegramAuth = (tgAuthData) => {
35
- // https://core.telegram.org/widgets/login#receiving-authorization-data
36
- // After a successful authorization, the widget returns data
37
- // by calling the callback function data-onauth with the JSON-object containing
38
- // id, first_name, last_name, username, photo_url, auth_date and hash fields.
39
- authWithTelegramService.loginWithTelegram(botID, tgAuthData, this.isUserAuthenticated());
40
- };
41
- const script = this.document.createElement('script');
42
- script.src = 'https://telegram.org/js/telegram-widget.js?22';
43
- script.setAttribute('data-telegram-login', botID);
44
- script.setAttribute('data-request-access', this.requestAccess());
45
- script.setAttribute('data-size', this.size());
46
- if (!this.userPic()) {
47
- script.setAttribute('data-userpic', 'false');
45
+ if (!botID) {
46
+ return;
47
+ }
48
+ this.authWithTelegram.getTelegramOIDCNonce(botID).subscribe({
49
+ next: (cfg) => this.startOIDC(botID, cfg),
50
+ // The server answers 400 for a bot without OpenID login configured.
51
+ error: () => this.startLegacyWidget(botID),
52
+ });
53
+ }
54
+ loginWithOIDC(cfg) {
55
+ const api = telegramLoginApi(this.document.defaultView ?? window);
56
+ if (!api) {
57
+ this.errorLogger.logErrorHandler('Telegram login library not loaded')(new Error('window.Telegram.Login is undefined'));
58
+ return;
59
+ }
60
+ const botID = this.botID();
61
+ // Called straight from the click handler: the library opens its popup
62
+ // synchronously, which keeps the browser's popup blocker out of the way.
63
+ api.auth({
64
+ client_id: Number(cfg.clientID),
65
+ nonce: cfg.nonce,
66
+ request_access: this.requestAccess() === 'write' ? ['write'] : [],
67
+ }, (result) => {
68
+ if (result.id_token) {
69
+ this.authWithTelegram.loginWithTelegramOIDC(botID, result.id_token, this.isUserAuthenticated());
70
+ this.refreshNonce(botID);
48
71
  }
49
- // https://core.telegram.org/widgets/login#receiving-authorization-data
72
+ // result.error (e.g. the user closed the popup) needs no action:
73
+ // the button stays, and the user can try again.
74
+ });
75
+ }
76
+ startOIDC(botID, cfg) {
77
+ loadTelegramLoginScript(this.document).then(() => {
78
+ this.oidc.set(cfg);
79
+ const timer = setInterval(() => this.refreshNonce(botID), OIDC_NONCE_REFRESH_MS);
80
+ this.destroyRef.onDestroy(() => clearInterval(timer));
81
+ }, this.errorLogger.logErrorHandler('Failed to load Telegram login library'));
82
+ }
83
+ refreshNonce(botID) {
84
+ this.authWithTelegram.getTelegramOIDCNonce(botID).subscribe({
85
+ next: (cfg) => this.oidc.set(cfg),
86
+ error: this.errorLogger.logErrorHandler('Failed to refresh Telegram login nonce'),
87
+ });
88
+ }
89
+ startLegacyWidget(botID) {
90
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
91
+ // @ts-ignore
92
+ window.onTelegramAuth = (tgAuthData) => {
93
+ // https://core.telegram.org/widgets/login-legacy
50
94
  // After a successful authorization, the widget returns data
51
95
  // by calling the callback function data-onauth with the JSON-object containing
52
96
  // id, first_name, last_name, username, photo_url, auth_date and hash fields.
53
- script.setAttribute('data-onauth', 'onTelegramAuth(user)');
54
- this.el.nativeElement.appendChild(script);
97
+ authWithTelegramService.loginWithTelegram(botID, tgAuthData, this.isUserAuthenticated());
98
+ };
99
+ const script = this.document.createElement('script');
100
+ script.src = 'https://telegram.org/js/telegram-widget.js?22';
101
+ script.setAttribute('data-telegram-login', botID);
102
+ script.setAttribute('data-request-access', this.requestAccess());
103
+ script.setAttribute('data-size', this.size());
104
+ if (!this.userPic()) {
105
+ script.setAttribute('data-userpic', 'false');
55
106
  }
107
+ script.setAttribute('data-onauth', 'onTelegramAuth(user)');
108
+ this.el.nativeElement.appendChild(script);
56
109
  }
57
110
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: LoginWithTelegramComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
58
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.1.3", type: LoginWithTelegramComponent, isStandalone: true, selector: "sneat-login-with-telegram", inputs: { isUserAuthenticated: { classPropertyName: "isUserAuthenticated", publicName: "isUserAuthenticated", isSignal: true, isRequired: false, transformFunction: null }, botID: { classPropertyName: "botID", publicName: "botID", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null }, requestAccess: { classPropertyName: "requestAccess", publicName: "requestAccess", isSignal: true, isRequired: false, transformFunction: null }, userPic: { classPropertyName: "userPic", publicName: "userPic", isSignal: true, isRequired: false, transformFunction: null } }, providers: [SneatAuthWithTelegramService], ngImport: i0, template: `
59
- <!--
60
- <script
61
- async
62
- src="https://telegram.org/js/telegram-widget.js?22"
63
- data-telegram-login="SneatBot"
64
- data-size="large"
65
- data-onauth="onTelegramAuth(user)"
66
- data-request-access="write"
67
- ></script>
68
- -->
69
- `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
111
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.3", type: LoginWithTelegramComponent, isStandalone: true, selector: "sneat-login-with-telegram", inputs: { isUserAuthenticated: { classPropertyName: "isUserAuthenticated", publicName: "isUserAuthenticated", isSignal: true, isRequired: false, transformFunction: null }, botID: { classPropertyName: "botID", publicName: "botID", isSignal: true, isRequired: false, transformFunction: null }, size: { classPropertyName: "size", publicName: "size", isSignal: true, isRequired: false, transformFunction: null }, requestAccess: { classPropertyName: "requestAccess", publicName: "requestAccess", isSignal: true, isRequired: false, transformFunction: null }, userPic: { classPropertyName: "userPic", publicName: "userPic", isSignal: true, isRequired: false, transformFunction: null } }, providers: [SneatAuthWithTelegramService], ngImport: i0, template: `
112
+ @if (oidc(); as cfg) {
113
+ <button
114
+ type="button"
115
+ class="tg-oidc-login"
116
+ [attr.data-size]="size()"
117
+ (click)="loginWithOIDC(cfg)"
118
+ >
119
+ Log in with Telegram
120
+ </button>
121
+ }
122
+ `, isInline: true, styles: [".tg-oidc-login{background:#54a9eb;color:#fff;border:0;border-radius:20px;font-weight:500;cursor:pointer;font-size:16px;padding:10px 21px}.tg-oidc-login[data-size=medium]{font-size:14px;padding:8px 16px}.tg-oidc-login[data-size=small]{font-size:13px;padding:6px 12px}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
70
123
  }
71
124
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: LoginWithTelegramComponent, decorators: [{
72
125
  type: Component,
73
- args: [{
74
- providers: [SneatAuthWithTelegramService],
75
- selector: 'sneat-login-with-telegram',
76
- changeDetection: ChangeDetectionStrategy.OnPush,
77
- template: `
78
- <!--
79
- <script
80
- async
81
- src="https://telegram.org/js/telegram-widget.js?22"
82
- data-telegram-login="SneatBot"
83
- data-size="large"
84
- data-onauth="onTelegramAuth(user)"
85
- data-request-access="write"
86
- ></script>
87
- -->
88
- `,
89
- }]
126
+ args: [{ providers: [SneatAuthWithTelegramService], selector: 'sneat-login-with-telegram', changeDetection: ChangeDetectionStrategy.OnPush, template: `
127
+ @if (oidc(); as cfg) {
128
+ <button
129
+ type="button"
130
+ class="tg-oidc-login"
131
+ [attr.data-size]="size()"
132
+ (click)="loginWithOIDC(cfg)"
133
+ >
134
+ Log in with Telegram
135
+ </button>
136
+ }
137
+ `, styles: [".tg-oidc-login{background:#54a9eb;color:#fff;border:0;border-radius:20px;font-weight:500;cursor:pointer;font-size:16px;padding:10px 21px}.tg-oidc-login[data-size=medium]{font-size:14px;padding:8px 16px}.tg-oidc-login[data-size=small]{font-size:13px;padding:6px 12px}\n"] }]
90
138
  }], ctorParameters: () => [], propDecorators: { isUserAuthenticated: [{ type: i0.Input, args: [{ isSignal: true, alias: "isUserAuthenticated", required: false }] }], botID: [{ type: i0.Input, args: [{ isSignal: true, alias: "botID", required: false }] }], size: [{ type: i0.Input, args: [{ isSignal: true, alias: "size", required: false }] }], requestAccess: [{ type: i0.Input, args: [{ isSignal: true, alias: "requestAccess", required: false }] }], userPic: [{ type: i0.Input, args: [{ isSignal: true, alias: "userPic", required: false }] }] } });
91
139
  //# sourceMappingURL=login-with-telegram.component.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"login-with-telegram.component.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/pages/login-page/login-with-telegram.component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAU,MAAM,EAAE,uBAAuB,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtG,OAAO,EAEL,4BAA4B,GAC7B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;;AAEjC,IAAI,uBAAqD,CAAC;AAmB1D,MAAM,OAAO,0BAA0B;IAQrC,qCAAqC;IACrC;QARiB,OAAE,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;QACxB,aAAQ,GAAG,MAAM,CAAW,QAAQ,CAAC,CAAC;QAC9C,qBAAgB,GAAG,MAAM,CAAC,4BAA4B,CAAC,CAAC;QAChD,wBAAmB,GAAG,MAAM,CAAC,mBAAmB,EAAE;YACjE,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QASa,wBAAmB,GAAG,KAAK,CAAC,KAAK;gGAAC,CAAC;QAEnC,UAAK,GAAG,KAAK,CAAS,oBAAoB,CAAC,IAAI,CAAC,mBAAmB,EAAE,QAAQ,CAAC,QAAQ,CAAC;kFAAC,CAAC;QAEzF,SAAI,GAAG,KAAK,CAA+B,OAAO;iFAAC,CAAC;QACpD,kBAAa,GAAG,KAAK,CAAmB,OAAO;0FAAC,CAAC;QACjD,YAAO,GAAG,KAAK,CAAC,IAAI;oFAAC,CAAC;QAXpC,MAAM,gBA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WT;;2FAEU,0BAA0B;kBAjBtC,SAAS;mBAAC;oBACT,SAAS,EAAE,CAAC,4BAA4B,CAAC;oBACzC,QAAQ,EAAE,2BAA2B;oBACrC,eAAe,EAAE,uBAAuB,CAAC,MAAM;oBAC/C,QAAQ,EAAE;;;;;;;;;;;GAWT;iBACF","sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport { Component, ElementRef, OnInit, inject, ChangeDetectionStrategy, input } from '@angular/core';\nimport {\n ITelegramAuthData,\n SneatAuthWithTelegramService,\n} from './sneat-auth-with-telegram.service';\nimport {\n TelegramLoginConfig,\n resolveTelegramBotID,\n} from './telegram-login-config';\n\nlet authWithTelegramService: SneatAuthWithTelegramService;\n\n@Component({\n providers: [SneatAuthWithTelegramService],\n selector: 'sneat-login-with-telegram',\n changeDetection: ChangeDetectionStrategy.OnPush,\n template: `\n <!--\n\t\t\t\t<script\n\t\t\t\t\tasync\n\t\t\t\t\tsrc=\"https://telegram.org/js/telegram-widget.js?22\"\n\t\t\t\t\tdata-telegram-login=\"SneatBot\"\n\t\t\t\t\tdata-size=\"large\"\n\t\t\t\t\tdata-onauth=\"onTelegramAuth(user)\"\n\t\t\t\t\tdata-request-access=\"write\"\n\t\t\t\t></script>\n\t\t\t\t-->\n `,\n})\nexport class LoginWithTelegramComponent implements OnInit {\n private readonly el = inject(ElementRef);\n private readonly document = inject<Document>(DOCUMENT);\n readonly authWithTelegram = inject(SneatAuthWithTelegramService);\n private readonly telegramLoginConfig = inject(TelegramLoginConfig, {\n optional: true,\n });\n\n // TODO: Article about Telegram login\n constructor() {\n const authWithTelegram = this.authWithTelegram;\n\n authWithTelegramService = authWithTelegram;\n }\n\n public readonly isUserAuthenticated = input(false);\n\n public readonly botID = input<string>(resolveTelegramBotID(this.telegramLoginConfig, location.hostname));\n\n public readonly size = input<'small' | 'medium' | 'large'>('large');\n public readonly requestAccess = input<'write' | 'read'>('write');\n public readonly userPic = input(true);\n\n ngOnInit() {\n const botID = this.botID();\n if (botID) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n window.onTelegramAuth = (tgAuthData: ITelegramAuthData) => {\n // https://core.telegram.org/widgets/login#receiving-authorization-data\n // After a successful authorization, the widget returns data\n // by calling the callback function data-onauth with the JSON-object containing\n // id, first_name, last_name, username, photo_url, auth_date and hash fields.\n authWithTelegramService.loginWithTelegram(\n botID,\n tgAuthData,\n this.isUserAuthenticated(),\n );\n };\n\n const script = this.document.createElement('script');\n\n script.src = 'https://telegram.org/js/telegram-widget.js?22';\n script.setAttribute('data-telegram-login', botID);\n script.setAttribute('data-request-access', this.requestAccess());\n script.setAttribute('data-size', this.size());\n if (!this.userPic()) {\n script.setAttribute('data-userpic', 'false');\n }\n // https://core.telegram.org/widgets/login#receiving-authorization-data\n // After a successful authorization, the widget returns data\n // by calling the callback function data-onauth with the JSON-object containing\n // id, first_name, last_name, username, photo_url, auth_date and hash fields.\n script.setAttribute('data-onauth', 'onTelegramAuth(user)');\n this.el.nativeElement.appendChild(script);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"login-with-telegram.component.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/pages/login-page/login-with-telegram.component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,UAAU,EACV,UAAU,EAEV,MAAM,EACN,KAAK,EACL,MAAM,GACP,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAgB,MAAM,aAAa,CAAC;AACxD,OAAO,EAGL,4BAA4B,GAC7B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;;AAE7B,IAAI,uBAAqD,CAAC;AAE1D,+DAA+D;AAC/D,MAAM,qBAAqB,GA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AAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;YACpB,MAAM,CAAC,YAAY,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAC/C,CAAC;QACD,MAAM,CAAC,YAAY,CAAC,aAAa,EAAE,sBAAsB,CAAC,CAAC;QAC3D,IAAI,CAAC,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;8GAtHU,0BAA0B;kGAA1B,0BAA0B,ivBAtC1B,CAAC,4BAA4B,CAAC,0BAG/B;;;;;;;;;;;GAWT;;2FAwBU,0BAA0B;kBAvCtC,SAAS;gCACG,CAAC,4BAA4B,CAAC,YAC/B,2BAA2B,mBACpB,uBAAuB,CAAC,MAAM,YACrC;;;;;;;;;;;GAWT","sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport {\n ChangeDetectionStrategy,\n Component,\n DestroyRef,\n ElementRef,\n OnInit,\n inject,\n input,\n signal,\n} from '@angular/core';\nimport { ErrorLogger, IErrorLogger } from '@sneat/core';\nimport {\n ITelegramAuthData,\n ITelegramOIDCNonce,\n SneatAuthWithTelegramService,\n} from './sneat-auth-with-telegram.service';\nimport {\n TelegramLoginConfig,\n resolveTelegramBotID,\n} from './telegram-login-config';\nimport {\n ITelegramLoginResult,\n loadTelegramLoginScript,\n telegramLoginApi,\n} from './telegram-login-js';\n\nlet authWithTelegramService: SneatAuthWithTelegramService;\n\n/** Server nonces live 10 minutes; refresh well inside that. */\nconst OIDC_NONCE_REFRESH_MS = 8 * 60 * 1000;\n\n/**\n * Telegram login button. Bots with OpenID login configured server-side use\n * Telegram's OpenID popup (telegram-login.js); others keep the legacy Login\n * Widget (telegram-widget.js), e.g. the local dev bot.\n */\n@Component({\n providers: [SneatAuthWithTelegramService],\n selector: 'sneat-login-with-telegram',\n changeDetection: ChangeDetectionStrategy.OnPush,\n template: `\n @if (oidc(); as cfg) {\n <button\n type=\"button\"\n class=\"tg-oidc-login\"\n [attr.data-size]=\"size()\"\n (click)=\"loginWithOIDC(cfg)\"\n >\n Log in with Telegram\n </button>\n }\n `,\n styles: [\n `\n .tg-oidc-login {\n background: #54a9eb;\n color: #fff;\n border: 0;\n border-radius: 20px;\n font-weight: 500;\n cursor: pointer;\n font-size: 16px;\n padding: 10px 21px;\n }\n .tg-oidc-login[data-size='medium'] {\n font-size: 14px;\n padding: 8px 16px;\n }\n .tg-oidc-login[data-size='small'] {\n font-size: 13px;\n padding: 6px 12px;\n }\n `,\n ],\n})\nexport class LoginWithTelegramComponent implements OnInit {\n private readonly el = inject(ElementRef);\n private readonly document = inject<Document>(DOCUMENT);\n private readonly destroyRef = inject(DestroyRef);\n private readonly errorLogger = inject<IErrorLogger>(ErrorLogger);\n readonly authWithTelegram = inject(SneatAuthWithTelegramService);\n private readonly telegramLoginConfig = inject(TelegramLoginConfig, {\n optional: true,\n });\n\n // TODO: Article about Telegram login\n constructor() {\n const authWithTelegram = this.authWithTelegram;\n\n authWithTelegramService = authWithTelegram;\n }\n\n public readonly isUserAuthenticated = input(false);\n\n public readonly botID = input<string>(resolveTelegramBotID(this.telegramLoginConfig, location.hostname));\n\n public readonly size = input<'small' | 'medium' | 'large'>('large');\n public readonly requestAccess = input<'write' | 'read'>('write');\n public readonly userPic = input(true);\n\n /** Set once the OpenID popup can be offered: Client ID plus a live nonce. */\n protected readonly oidc = signal<ITelegramOIDCNonce | undefined>(undefined);\n\n ngOnInit() {\n const botID = this.botID();\n if (!botID) {\n return;\n }\n this.authWithTelegram.getTelegramOIDCNonce(botID).subscribe({\n next: (cfg) => this.startOIDC(botID, cfg),\n // The server answers 400 for a bot without OpenID login configured.\n error: () => this.startLegacyWidget(botID),\n });\n }\n\n protected loginWithOIDC(cfg: ITelegramOIDCNonce): void {\n const api = telegramLoginApi(this.document.defaultView ?? window);\n if (!api) {\n this.errorLogger.logErrorHandler('Telegram login library not loaded')(\n new Error('window.Telegram.Login is undefined'),\n );\n return;\n }\n const botID = this.botID();\n // Called straight from the click handler: the library opens its popup\n // synchronously, which keeps the browser's popup blocker out of the way.\n api.auth(\n {\n client_id: Number(cfg.clientID),\n nonce: cfg.nonce,\n request_access: this.requestAccess() === 'write' ? ['write'] : [],\n },\n (result: ITelegramLoginResult) => {\n if (result.id_token) {\n this.authWithTelegram.loginWithTelegramOIDC(\n botID,\n result.id_token,\n this.isUserAuthenticated(),\n );\n this.refreshNonce(botID);\n }\n // result.error (e.g. the user closed the popup) needs no action:\n // the button stays, and the user can try again.\n },\n );\n }\n\n private startOIDC(botID: string, cfg: ITelegramOIDCNonce): void {\n loadTelegramLoginScript(this.document).then(() => {\n this.oidc.set(cfg);\n const timer = setInterval(\n () => this.refreshNonce(botID),\n OIDC_NONCE_REFRESH_MS,\n );\n this.destroyRef.onDestroy(() => clearInterval(timer));\n }, this.errorLogger.logErrorHandler('Failed to load Telegram login library'));\n }\n\n private refreshNonce(botID: string): void {\n this.authWithTelegram.getTelegramOIDCNonce(botID).subscribe({\n next: (cfg) => this.oidc.set(cfg),\n error: this.errorLogger.logErrorHandler(\n 'Failed to refresh Telegram login nonce',\n ),\n });\n }\n\n private startLegacyWidget(botID: string): void {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n window.onTelegramAuth = (tgAuthData: ITelegramAuthData) => {\n // https://core.telegram.org/widgets/login-legacy\n // After a successful authorization, the widget returns data\n // by calling the callback function data-onauth with the JSON-object containing\n // id, first_name, last_name, username, photo_url, auth_date and hash fields.\n authWithTelegramService.loginWithTelegram(\n botID,\n tgAuthData,\n this.isUserAuthenticated(),\n );\n };\n\n const script = this.document.createElement('script');\n\n script.src = 'https://telegram.org/js/telegram-widget.js?22';\n script.setAttribute('data-telegram-login', botID);\n script.setAttribute('data-request-access', this.requestAccess());\n script.setAttribute('data-size', this.size());\n if (!this.userPic()) {\n script.setAttribute('data-userpic', 'false');\n }\n script.setAttribute('data-onauth', 'onTelegramAuth(user)');\n this.el.nativeElement.appendChild(script);\n }\n}\n"]}
@@ -9,11 +9,26 @@ export class SneatAuthWithTelegramService {
9
9
  this.apiService = inject(SneatApiService);
10
10
  this.authService = inject(SneatAuthStateService);
11
11
  }
12
+ /** Legacy Login Widget: posts the widget's signed payload. */
12
13
  loginWithTelegram(botID, tgAuthData, isUserAuthenticated) {
13
- const postRequest = isUserAuthenticated
14
- ? (endpoint, body) => this.apiService.post(endpoint, body)
15
- : (endpoint, body) => this.apiService.postAsAnonymous(endpoint, body);
16
- postRequest('auth/login-from-telegram-widget?botID=' + botID, tgAuthData).subscribe({
14
+ this.signIn('auth/login-from-telegram-widget?botID=' + botID, tgAuthData, isUserAuthenticated);
15
+ }
16
+ /**
17
+ * Asks the server for the bot's OpenID Client ID and a fresh nonce. Fails
18
+ * with 400 for a bot that has no OpenID login configured server-side.
19
+ */
20
+ getTelegramOIDCNonce(botID) {
21
+ return this.apiService.postAsAnonymous('auth/telegram-oidc-nonce?botID=' + botID, {});
22
+ }
23
+ /** OpenID login: posts the id_token Telegram's popup returned. */
24
+ loginWithTelegramOIDC(botID, idToken, isUserAuthenticated) {
25
+ this.signIn('auth/login-from-telegram-oidc?botID=' + botID, { id_token: idToken }, isUserAuthenticated);
26
+ }
27
+ signIn(endpoint, body, isUserAuthenticated) {
28
+ const request = isUserAuthenticated
29
+ ? this.apiService.post(endpoint, body)
30
+ : this.apiService.postAsAnonymous(endpoint, body);
31
+ request.subscribe({
17
32
  next: (response) => {
18
33
  this.authService
19
34
  .signInWithToken(response.token)
@@ -1 +1 @@
1
- {"version":3,"file":"sneat-auth-with-telegram.service.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/pages/login-page/sneat-auth-with-telegram.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAgB,MAAM,aAAa,CAAC;;AAkBxD,MAAM,OAAO,4BAA4B;IADzC;QAEmB,gBAAW,GAAG,MAAM,CAAe,WAAW,CAAC,CAAC;QAChD,eAAU,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;QACrC,gBAAW,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;KA+B9D;IA7BQ,iBAAiB,CACtB,KAAa,EACb,UAA6B,EAC7B,mBAA4B;QAE5B,MAAM,WAAW,GAGY,mBAAmB;YAC9C,CAAC,CAAC,CAAC,QAAgB,EAAE,IAAa,EAAE,EAAE,CAClC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAY,QAAQ,EAAE,IAAI,CAAC;YACnD,CAAC,CAAC,CAAC,QAAgB,EAAE,IAAa,EAAE,EAAE,CAClC,IAAI,CAAC,UAAU,CAAC,eAAe,CAAY,QAAQ,EAAE,IAAI,CAAC,CAAC;QACjE,WAAW,CACT,wCAAwC,GAAG,KAAK,EAChD,UAAU,CACX,CAAC,SAAS,CAAC;YACV,IAAI,EAAE,CAAC,QAAQ,EAAE,EAAE;gBACjB,IAAI,CAAC,WAAW;qBACb,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC;qBAC/B,KAAK,CACJ,IAAI,CAAC,WAAW,CAAC,eAAe,CAC9B,qCAAqC,CACtC,CACF,CAAC;YACN,CAAC;YACD,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,6BAA6B,CAAC;SACvE,CAAC,CAAC;IACL,CAAC;8GAjCU,4BAA4B;kHAA5B,4BAA4B;;2FAA5B,4BAA4B;kBADxC,UAAU","sourcesContent":["import { Injectable, inject } from '@angular/core';\nimport { SneatApiService } from '@sneat/api';\nimport { SneatAuthStateService } from '@sneat/auth-core';\nimport { ErrorLogger, IErrorLogger } from '@sneat/core';\nimport { Observable } from 'rxjs';\n\nexport interface ITelegramAuthData {\n id: number;\n first_name: string;\n last_name: string;\n username?: string;\n photo_url?: string;\n auth_date: number;\n hash: string;\n}\n\ninterface IResponse {\n token: string;\n}\n\n@Injectable()\nexport class SneatAuthWithTelegramService {\n private readonly errorLogger = inject<IErrorLogger>(ErrorLogger);\n private readonly apiService = inject(SneatApiService);\n private readonly authService = inject(SneatAuthStateService);\n\n public loginWithTelegram(\n botID: string,\n tgAuthData: ITelegramAuthData,\n isUserAuthenticated: boolean,\n ): void {\n const postRequest: (\n endpoint: string,\n body: unknown,\n ) => Observable<IResponse> = isUserAuthenticated\n ? (endpoint: string, body: unknown) =>\n this.apiService.post<IResponse>(endpoint, body)\n : (endpoint: string, body: unknown) =>\n this.apiService.postAsAnonymous<IResponse>(endpoint, body);\n postRequest(\n 'auth/login-from-telegram-widget?botID=' + botID,\n tgAuthData,\n ).subscribe({\n next: (response) => {\n this.authService\n .signInWithToken(response.token)\n .catch(\n this.errorLogger.logErrorHandler(\n 'Failed to sign-in with custom token',\n ),\n );\n },\n error: this.errorLogger.logErrorHandler('signInWithTelegram() error:'),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"sneat-auth-with-telegram.service.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/pages/login-page/sneat-auth-with-telegram.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAgB,MAAM,aAAa,CAAC;;AAwBxD,MAAM,OAAO,4BAA4B;IADzC;QAEmB,gBAAW,GAAG,MAAM,CAAe,WAAW,CAAC,CAAC;QAChD,eAAU,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;QACrC,gBAAW,GAAG,MAAM,CAAC,qBAAqB,CAAC,CAAC;KA4D9D;IA1DC,8DAA8D;IACvD,iBAAiB,CACtB,KAAa,EACb,UAA6B,EAC7B,mBAA4B;QAE5B,IAAI,CAAC,MAAM,CACT,wCAAwC,GAAG,KAAK,EAChD,UAAU,EACV,mBAAmB,CACpB,CAAC;IACJ,CAAC;IAED;;;OAGG;IACI,oBAAoB,CAAC,KAAa;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,CACpC,iCAAiC,GAAG,KAAK,EACzC,EAAE,CACH,CAAC;IACJ,CAAC;IAED,kEAAkE;IAC3D,qBAAqB,CAC1B,KAAa,EACb,OAAe,EACf,mBAA4B;QAE5B,IAAI,CAAC,MAAM,CACT,sCAAsC,GAAG,KAAK,EAC9C,EAAE,QAAQ,EAAE,OAAO,EAAE,EACrB,mBAAmB,CACpB,CAAC;IACJ,CAAC;IAEO,MAAM,CACZ,QAAgB,EAChB,IAAa,EACb,mBAA4B;QAE5B,MAAM,OAAO,GAAG,mBAAmB;YACjC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAY,QAAQ,EAAE,IAAI,CAAC;YACjD,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,eAAe,CAAY,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC/D,OAAO,CAAC,SAAS,CAAC;YAChB,IAAI,EAAE,CAAC,QAAQ,EAAE,EAAE;gBACjB,IAAI,CAAC,WAAW;qBACb,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC;qBAC/B,KAAK,CACJ,IAAI,CAAC,WAAW,CAAC,eAAe,CAC9B,qCAAqC,CACtC,CACF,CAAC;YACN,CAAC;YACD,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,6BAA6B,CAAC;SACvE,CAAC,CAAC;IACL,CAAC;8GA9DU,4BAA4B;kHAA5B,4BAA4B;;2FAA5B,4BAA4B;kBADxC,UAAU","sourcesContent":["import { Injectable, inject } from '@angular/core';\nimport { SneatApiService } from '@sneat/api';\nimport { SneatAuthStateService } from '@sneat/auth-core';\nimport { ErrorLogger, IErrorLogger } from '@sneat/core';\nimport { Observable } from 'rxjs';\n\nexport interface ITelegramAuthData {\n id: number;\n first_name: string;\n last_name: string;\n username?: string;\n photo_url?: string;\n auth_date: number;\n hash: string;\n}\n\n/** What the server hands the page before it opens Telegram's OpenID popup. */\nexport interface ITelegramOIDCNonce {\n clientID: string;\n nonce: string;\n}\n\ninterface IResponse {\n token: string;\n}\n\n@Injectable()\nexport class SneatAuthWithTelegramService {\n private readonly errorLogger = inject<IErrorLogger>(ErrorLogger);\n private readonly apiService = inject(SneatApiService);\n private readonly authService = inject(SneatAuthStateService);\n\n /** Legacy Login Widget: posts the widget's signed payload. */\n public loginWithTelegram(\n botID: string,\n tgAuthData: ITelegramAuthData,\n isUserAuthenticated: boolean,\n ): void {\n this.signIn(\n 'auth/login-from-telegram-widget?botID=' + botID,\n tgAuthData,\n isUserAuthenticated,\n );\n }\n\n /**\n * Asks the server for the bot's OpenID Client ID and a fresh nonce. Fails\n * with 400 for a bot that has no OpenID login configured server-side.\n */\n public getTelegramOIDCNonce(botID: string): Observable<ITelegramOIDCNonce> {\n return this.apiService.postAsAnonymous<ITelegramOIDCNonce>(\n 'auth/telegram-oidc-nonce?botID=' + botID,\n {},\n );\n }\n\n /** OpenID login: posts the id_token Telegram's popup returned. */\n public loginWithTelegramOIDC(\n botID: string,\n idToken: string,\n isUserAuthenticated: boolean,\n ): void {\n this.signIn(\n 'auth/login-from-telegram-oidc?botID=' + botID,\n { id_token: idToken },\n isUserAuthenticated,\n );\n }\n\n private signIn(\n endpoint: string,\n body: unknown,\n isUserAuthenticated: boolean,\n ): void {\n const request = isUserAuthenticated\n ? this.apiService.post<IResponse>(endpoint, body)\n : this.apiService.postAsAnonymous<IResponse>(endpoint, body);\n request.subscribe({\n next: (response) => {\n this.authService\n .signInWithToken(response.token)\n .catch(\n this.errorLogger.logErrorHandler(\n 'Failed to sign-in with custom token',\n ),\n );\n },\n error: this.errorLogger.logErrorHandler('signInWithTelegram() error:'),\n });\n }\n}\n"]}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Telegram's OpenID login library for websites.
3
+ * https://core.telegram.org/bots/telegram-login
4
+ */
5
+ export const TELEGRAM_LOGIN_JS_URL = 'https://oauth.telegram.org/js/telegram-login.js?6';
6
+ export function telegramLoginApi(win) {
7
+ return win
8
+ .Telegram?.Login;
9
+ }
10
+ /** Loads telegram-login.js once per document; resolves once it has loaded. */
11
+ export function loadTelegramLoginScript(doc) {
12
+ const existing = doc.querySelector(`script[src="${TELEGRAM_LOGIN_JS_URL}"]`);
13
+ if (existing?.dataset['loaded'] === 'true') {
14
+ return Promise.resolve();
15
+ }
16
+ return new Promise((resolve, reject) => {
17
+ const script = existing ?? doc.createElement('script');
18
+ script.addEventListener('load', () => {
19
+ script.dataset['loaded'] = 'true';
20
+ resolve();
21
+ }, { once: true });
22
+ script.addEventListener('error', () => reject(new Error('Failed to load ' + TELEGRAM_LOGIN_JS_URL)), { once: true });
23
+ if (!existing) {
24
+ script.async = true;
25
+ script.src = TELEGRAM_LOGIN_JS_URL;
26
+ doc.head.appendChild(script);
27
+ }
28
+ });
29
+ }
30
+ //# sourceMappingURL=telegram-login-js.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telegram-login-js.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/pages/login-page/telegram-login-js.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,mDAAmD,CAAC;AA6BtD,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,OAAQ,GAA+D;SACpE,QAAQ,EAAE,KAAK,CAAC;AACrB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,uBAAuB,CAAC,GAAa;IACnD,MAAM,QAAQ,GAAG,GAAG,CAAC,aAAa,CAChC,eAAe,qBAAqB,IAAI,CACzC,CAAC;IACF,IAAI,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,KAAK,MAAM,EAAE,CAAC;QAC3C,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACD,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC3C,MAAM,MAAM,GAAG,QAAQ,IAAI,GAAG,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QACvD,MAAM,CAAC,gBAAgB,CACrB,MAAM,EACN,GAAG,EAAE;YACH,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;YAClC,OAAO,EAAE,CAAC;QACZ,CAAC,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAC;QACF,MAAM,CAAC,gBAAgB,CACrB,OAAO,EACP,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,GAAG,qBAAqB,CAAC,CAAC,EAClE,EAAE,IAAI,EAAE,IAAI,EAAE,CACf,CAAC;QACF,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC;YACpB,MAAM,CAAC,GAAG,GAAG,qBAAqB,CAAC;YACnC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Telegram's OpenID login library for websites.\n * https://core.telegram.org/bots/telegram-login\n */\nexport const TELEGRAM_LOGIN_JS_URL =\n 'https://oauth.telegram.org/js/telegram-login.js?6';\n\nexport interface ITelegramLoginOptions {\n /** The bot's Client ID from @BotFather (Login Widget section). */\n client_id: number;\n /** Server-issued nonce; Telegram echoes it into the id_token. */\n nonce?: string;\n /**\n * `['write']` asks permission for the bot to message the user. Because no\n * `scope` is passed, the library also requests `profile`, whose `id` claim\n * carries the numeric Telegram user ID the server signs in with.\n */\n request_access?: string[];\n lang?: string;\n}\n\nexport interface ITelegramLoginResult {\n id_token?: string;\n user?: Record<string, unknown>;\n error?: string;\n}\n\ninterface ITelegramLoginApi {\n auth(\n options: ITelegramLoginOptions,\n callback: (result: ITelegramLoginResult) => void,\n ): void;\n}\n\nexport function telegramLoginApi(win: Window): ITelegramLoginApi | undefined {\n return (win as unknown as { Telegram?: { Login?: ITelegramLoginApi } })\n .Telegram?.Login;\n}\n\n/** Loads telegram-login.js once per document; resolves once it has loaded. */\nexport function loadTelegramLoginScript(doc: Document): Promise<void> {\n const existing = doc.querySelector<HTMLScriptElement>(\n `script[src=\"${TELEGRAM_LOGIN_JS_URL}\"]`,\n );\n if (existing?.dataset['loaded'] === 'true') {\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const script = existing ?? doc.createElement('script');\n script.addEventListener(\n 'load',\n () => {\n script.dataset['loaded'] = 'true';\n resolve();\n },\n { once: true },\n );\n script.addEventListener(\n 'error',\n () => reject(new Error('Failed to load ' + TELEGRAM_LOGIN_JS_URL)),\n { once: true },\n );\n if (!existing) {\n script.async = true;\n script.src = TELEGRAM_LOGIN_JS_URL;\n doc.head.appendChild(script);\n }\n });\n}\n"]}
@@ -1,9 +1,16 @@
1
1
  import { OnInit } from '@angular/core';
2
- import { SneatAuthWithTelegramService } from './sneat-auth-with-telegram.service';
2
+ import { ITelegramOIDCNonce, SneatAuthWithTelegramService } from './sneat-auth-with-telegram.service';
3
3
  import * as i0 from "@angular/core";
4
+ /**
5
+ * Telegram login button. Bots with OpenID login configured server-side use
6
+ * Telegram's OpenID popup (telegram-login.js); others keep the legacy Login
7
+ * Widget (telegram-widget.js), e.g. the local dev bot.
8
+ */
4
9
  export declare class LoginWithTelegramComponent implements OnInit {
5
10
  private readonly el;
6
11
  private readonly document;
12
+ private readonly destroyRef;
13
+ private readonly errorLogger;
7
14
  readonly authWithTelegram: SneatAuthWithTelegramService;
8
15
  private readonly telegramLoginConfig;
9
16
  constructor();
@@ -12,7 +19,13 @@ export declare class LoginWithTelegramComponent implements OnInit {
12
19
  readonly size: import("@angular/core").InputSignal<"medium" | "small" | "large">;
13
20
  readonly requestAccess: import("@angular/core").InputSignal<"write" | "read">;
14
21
  readonly userPic: import("@angular/core").InputSignal<boolean>;
22
+ /** Set once the OpenID popup can be offered: Client ID plus a live nonce. */
23
+ protected readonly oidc: import("@angular/core").WritableSignal<ITelegramOIDCNonce | undefined>;
15
24
  ngOnInit(): void;
25
+ protected loginWithOIDC(cfg: ITelegramOIDCNonce): void;
26
+ private startOIDC;
27
+ private refreshNonce;
28
+ private startLegacyWidget;
16
29
  static ɵfac: i0.ɵɵFactoryDeclaration<LoginWithTelegramComponent, never>;
17
30
  static ɵcmp: i0.ɵɵComponentDeclaration<LoginWithTelegramComponent, "sneat-login-with-telegram", never, { "isUserAuthenticated": { "alias": "isUserAuthenticated"; "required": false; "isSignal": true; }; "botID": { "alias": "botID"; "required": false; "isSignal": true; }; "size": { "alias": "size"; "required": false; "isSignal": true; }; "requestAccess": { "alias": "requestAccess"; "required": false; "isSignal": true; }; "userPic": { "alias": "userPic"; "required": false; "isSignal": true; }; }, {}, never, never, true, never>;
18
31
  }
@@ -1,3 +1,4 @@
1
+ import { Observable } from 'rxjs';
1
2
  import * as i0 from "@angular/core";
2
3
  export interface ITelegramAuthData {
3
4
  id: number;
@@ -8,11 +9,25 @@ export interface ITelegramAuthData {
8
9
  auth_date: number;
9
10
  hash: string;
10
11
  }
12
+ /** What the server hands the page before it opens Telegram's OpenID popup. */
13
+ export interface ITelegramOIDCNonce {
14
+ clientID: string;
15
+ nonce: string;
16
+ }
11
17
  export declare class SneatAuthWithTelegramService {
12
18
  private readonly errorLogger;
13
19
  private readonly apiService;
14
20
  private readonly authService;
21
+ /** Legacy Login Widget: posts the widget's signed payload. */
15
22
  loginWithTelegram(botID: string, tgAuthData: ITelegramAuthData, isUserAuthenticated: boolean): void;
23
+ /**
24
+ * Asks the server for the bot's OpenID Client ID and a fresh nonce. Fails
25
+ * with 400 for a bot that has no OpenID login configured server-side.
26
+ */
27
+ getTelegramOIDCNonce(botID: string): Observable<ITelegramOIDCNonce>;
28
+ /** OpenID login: posts the id_token Telegram's popup returned. */
29
+ loginWithTelegramOIDC(botID: string, idToken: string, isUserAuthenticated: boolean): void;
30
+ private signIn;
16
31
  static ɵfac: i0.ɵɵFactoryDeclaration<SneatAuthWithTelegramService, never>;
17
32
  static ɵprov: i0.ɵɵInjectableDeclaration<SneatAuthWithTelegramService>;
18
33
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Telegram's OpenID login library for websites.
3
+ * https://core.telegram.org/bots/telegram-login
4
+ */
5
+ export declare const TELEGRAM_LOGIN_JS_URL = "https://oauth.telegram.org/js/telegram-login.js?6";
6
+ export interface ITelegramLoginOptions {
7
+ /** The bot's Client ID from @BotFather (Login Widget section). */
8
+ client_id: number;
9
+ /** Server-issued nonce; Telegram echoes it into the id_token. */
10
+ nonce?: string;
11
+ /**
12
+ * `['write']` asks permission for the bot to message the user. Because no
13
+ * `scope` is passed, the library also requests `profile`, whose `id` claim
14
+ * carries the numeric Telegram user ID the server signs in with.
15
+ */
16
+ request_access?: string[];
17
+ lang?: string;
18
+ }
19
+ export interface ITelegramLoginResult {
20
+ id_token?: string;
21
+ user?: Record<string, unknown>;
22
+ error?: string;
23
+ }
24
+ interface ITelegramLoginApi {
25
+ auth(options: ITelegramLoginOptions, callback: (result: ITelegramLoginResult) => void): void;
26
+ }
27
+ export declare function telegramLoginApi(win: Window): ITelegramLoginApi | undefined;
28
+ /** Loads telegram-login.js once per document; resolves once it has loaded. */
29
+ export declare function loadTelegramLoginScript(doc: Document): Promise<void>;
30
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sneat/auth-ui",
3
- "version": "0.27.20",
3
+ "version": "0.27.22",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },