@edsis/angular 22.0.91 → 22.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, Injectable, inject, signal, computed, makeEnvironmentProviders, provideAppInitializer, Component, DestroyRef, Injector, viewChild, ElementRef, effect, afterNextRender, input } from '@angular/core';
2
+ import { InjectionToken, Injectable, inject, signal, computed, makeEnvironmentProviders, provideAppInitializer, Service, Component, DestroyRef, Injector, viewChild, ElementRef, effect, afterNextRender, input } from '@angular/core';
3
3
  import { HttpClient, HttpErrorResponse, HttpContextToken, HttpContext, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
4
4
  import { provideApiConfiguration } from '@edsis/sdk/shared';
5
5
  import { Router, RouterOutlet, ActivatedRoute, RouterLink } from '@angular/router';
6
6
  import { setNativeNotificationBadge, RuntimeContextService, NativeHostService } from '@edsis/angular/services/runtime';
7
7
  import { firstValueFrom, throwError, from, timeout, startWith, finalize } from 'rxjs';
8
8
  import { catchError, switchMap } from 'rxjs/operators';
9
- import { LayoutService, LayoutComponent, DesktopAppBarComponent, LayoutFluidComponent } from '@edsis/theme/layout';
10
9
  import { DOCUMENT, Location } from '@angular/common';
10
+ import { LayoutService, LayoutComponent, DesktopAppBarComponent, LayoutFluidComponent } from '@edsis/theme/layout';
11
11
  import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
12
12
  import { AuthSessionService, AuthMagicLinkService } from '@edsis/sdk/auth';
13
13
  import { AlertComponent, AlertDescriptionComponent } from '@edsis/component/alert';
@@ -26,6 +26,8 @@ const DEFAULT_LOGOUT_PATH = '/logout';
26
26
  const DEFAULT_VERIFY_PATH = '/verify';
27
27
  const DEFAULT_AUTHENTICATED_HOME_PATH = '/dashboard';
28
28
  const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 4000;
29
+ const GOOGLE_AUTH_GATEWAY_DEFAULT_START_ENDPOINT = '/v1/auth/google/start';
30
+ const GOOGLE_AUTH_GATEWAY_DEFAULT_HANDOFF_ENDPOINT = '/v1/auth/google/handoff';
29
31
  /**
30
32
  * Path route callback Google di dalam `authRoutes`; juga menjadi sumber
31
33
  * derivasi `redirectUri` (`${appUrl}/auth/google/callback`), sehingga URL yang
@@ -37,7 +39,6 @@ function resolveEdsisAuthConfig(config) {
37
39
  const loginPath = normalizePath(config.loginPath, DEFAULT_LOGIN_PATH);
38
40
  const apiUrl = normalizeAbsoluteUrl(config.apiUrl, 'apiUrl');
39
41
  const appUrl = normalizeAbsoluteUrl(config.appUrl, 'appUrl');
40
- const googleClientId = config.oauth?.google?.clientId.trim() ?? '';
41
42
  return {
42
43
  apiUrl,
43
44
  appUrl,
@@ -52,18 +53,76 @@ function resolveEdsisAuthConfig(config) {
52
53
  timeoutMs: config.healthCheck?.timeoutMs ?? DEFAULT_HEALTH_CHECK_TIMEOUT_MS,
53
54
  },
54
55
  oauth: {
55
- google: googleClientId
56
- ? {
57
- clientId: googleClientId,
58
- redirectUri: `${appUrl}/${GOOGLE_OAUTH_CALLBACK_ROUTE_PATH}`,
59
- }
60
- : null,
56
+ google: resolveGoogleOauth(config.oauth?.google, appUrl, apiUrl),
61
57
  nativeGoogle: config.oauth?.nativeGoogle && config.oauth.nativeGoogle.enabled !== false
62
58
  ? { apiUrl: normalizeSameOriginPath(config.oauth.nativeGoogle.apiUrl ?? '/api') }
63
59
  : null,
64
60
  },
65
61
  };
66
62
  }
63
+ function resolveGoogleOauth(config, appUrl, apiUrl) {
64
+ if (!config) {
65
+ return null;
66
+ }
67
+ const callbackUrl = `${appUrl}/${GOOGLE_OAUTH_CALLBACK_ROUTE_PATH}`;
68
+ if (config.mode === 'gateway') {
69
+ const mfeId = config.mfeId.trim();
70
+ if (mfeId.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(mfeId)) {
71
+ throw new Error('Edsis Google Auth Gateway requires a lower-kebab-case mfeId of at most 64 characters.');
72
+ }
73
+ const baseUrl = normalizeGatewayBaseUrl(config.gateway?.baseUrl ?? apiUrl, apiUrl);
74
+ const startEndpoint = normalizeGatewayEndpoint(config.gateway?.startEndpoint ?? GOOGLE_AUTH_GATEWAY_DEFAULT_START_ENDPOINT, 'startEndpoint');
75
+ const handoffEndpoint = normalizeGatewayEndpoint(config.gateway?.handoffEndpoint ?? GOOGLE_AUTH_GATEWAY_DEFAULT_HANDOFF_ENDPOINT, 'handoffEndpoint');
76
+ return {
77
+ mode: 'gateway',
78
+ mfeId,
79
+ returnUrl: callbackUrl,
80
+ gateway: {
81
+ baseUrl,
82
+ startUrl: joinGatewayUrl(baseUrl, startEndpoint),
83
+ handoffUrl: joinGatewayUrl(baseUrl, handoffEndpoint),
84
+ },
85
+ };
86
+ }
87
+ const clientId = config.clientId.trim();
88
+ return clientId
89
+ ? {
90
+ mode: 'direct',
91
+ clientId,
92
+ redirectUri: callbackUrl,
93
+ }
94
+ : null;
95
+ }
96
+ function normalizeGatewayBaseUrl(value, apiUrl) {
97
+ const baseUrl = normalizeAbsoluteUrl(value, 'Google Auth Gateway baseUrl');
98
+ const parsed = new URL(baseUrl);
99
+ const apiOrigin = new URL(apiUrl).origin;
100
+ const isLoopback = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
101
+ const hasAllowedProtocol = parsed.protocol === 'https:' || (parsed.protocol === 'http:' && isLoopback);
102
+ if (!hasAllowedProtocol || parsed.username || parsed.password || parsed.search || parsed.hash) {
103
+ throw new Error('Edsis Google Auth Gateway baseUrl must use HTTPS (HTTP is allowed only for loopback development) without credentials, query, or hash.');
104
+ }
105
+ if (parsed.origin !== apiOrigin) {
106
+ throw new Error('Edsis Google Auth Gateway baseUrl must use the same origin (scheme, host, and port) as apiUrl so the refresh-cookie session cannot split across origins.');
107
+ }
108
+ return baseUrl;
109
+ }
110
+ function normalizeGatewayEndpoint(value, label) {
111
+ const endpoint = value.trim();
112
+ const segments = endpoint.split('/').slice(1);
113
+ if (!endpoint.startsWith('/') ||
114
+ endpoint.startsWith('//') ||
115
+ endpoint.includes('?') ||
116
+ endpoint.includes('#') ||
117
+ segments.length === 0 ||
118
+ segments.some((segment) => !/^[A-Za-z0-9._~-]+$/u.test(segment) || segment === '.' || segment === '..')) {
119
+ throw new Error(`Edsis Google Auth Gateway ${label} must be a root-relative path.`);
120
+ }
121
+ return endpoint;
122
+ }
123
+ function joinGatewayUrl(baseUrl, endpoint) {
124
+ return `${baseUrl}/${endpoint.replace(/^\/+/, '')}`;
125
+ }
67
126
  function normalizeSameOriginPath(value) {
68
127
  const normalizedValue = value.trim().replace(/\/+$/u, '');
69
128
  if (!normalizedValue.startsWith('/') ||
@@ -116,10 +175,13 @@ const DEFAULT_EDSIS_AUTH_MESSAGES = {
116
175
  },
117
176
  google: {
118
177
  title: 'Menyelesaikan Google Sign-In.',
119
- intro: 'Kode otorisasi dari Google ditukar menjadi sesi oleh backend, sesi refresh cookie dibentuk, lalu access token disimpan secara lokal untuk aplikasi.',
178
+ intro: 'Kode otorisasi dari Google ditukar menjadi sesi oleh backend, sesi refresh cookie dibentuk, lalu access token hanya disimpan di memori aplikasi.',
120
179
  badge: 'GOOGLE',
121
180
  signInAria: 'Login dengan Google',
122
181
  googleRedirecting: 'Mengarahkan ke Google...',
182
+ gatewayStartFailed: 'Gagal memulai login melalui Auth Gateway. Silakan coba lagi.',
183
+ gatewayHandoffInProgress: 'Menyelesaikan sesi Google melalui Auth Gateway...',
184
+ gatewaySessionMissing: 'Sesi keamanan Auth Gateway tidak ditemukan atau sudah kedaluwarsa. Silakan ulangi login dari awal.',
123
185
  nativeSignInInProgress: 'Menyelesaikan login Google di perangkat...',
124
186
  nativeSignInUnavailable: 'Google Sign-In native tidak tersedia pada perangkat ini. Perbarui aplikasi atau hubungi administrator.',
125
187
  nativeSignInFailed: 'Login Google pada perangkat gagal diproses.',
@@ -241,9 +303,11 @@ class AuthService {
241
303
  }
242
304
  get sessionApiUrl() {
243
305
  const nativeApiUrl = this.config.oauth.nativeGoogle?.apiUrl;
244
- return this.runtime?.isTabletShell() === true && nativeApiUrl
245
- ? nativeApiUrl.replace(/\/+$/u, '')
246
- : this.apiUrl;
306
+ if (this.runtime?.isTabletShell() === true && nativeApiUrl) {
307
+ return nativeApiUrl.replace(/\/+$/u, '');
308
+ }
309
+ const google = this.config.oauth.google;
310
+ return google?.mode === 'gateway' ? google.gateway.baseUrl : this.apiUrl;
247
311
  }
248
312
  /** Restores an existing cookie session. A missing/expired cookie is normal. */
249
313
  initialize() {
@@ -628,6 +692,104 @@ const guestOnlyGuard = async () => {
628
692
  return router.parseUrl(authConfig.authenticatedHomePath);
629
693
  };
630
694
 
695
+ const GOOGLE_GATEWAY_SESSION_STORAGE_KEY = 'auth-google-gateway-session';
696
+ const GOOGLE_GATEWAY_SESSION_VERSION = 1;
697
+ const PKCE_RANDOM_BYTE_LENGTH = 32;
698
+ const PKCE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/u;
699
+ /** RFC 7636 verifier with 256 bits of entropy and no persisted token material. */
700
+ function createGooglePkceVerifier(windowRef) {
701
+ const randomBytes = windowRef.crypto.getRandomValues(new Uint8Array(PKCE_RANDOM_BYTE_LENGTH));
702
+ return encodeBase64Url(windowRef, randomBytes);
703
+ }
704
+ /** RFC 7636 S256 challenge for the verifier retained in the one-time session. */
705
+ async function createGooglePkceChallenge(windowRef, codeVerifier) {
706
+ if (!PKCE_VERIFIER_PATTERN.test(codeVerifier)) {
707
+ throw new Error('Google Auth Gateway PKCE verifier must contain 43-128 RFC 7636 characters.');
708
+ }
709
+ const digest = await windowRef.crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
710
+ return encodeBase64Url(windowRef, new Uint8Array(digest));
711
+ }
712
+ /** Stores only the verifier and short-lived correlation metadata. */
713
+ function storeGoogleGatewaySession(documentRef, session) {
714
+ try {
715
+ const storage = documentRef.defaultView?.sessionStorage;
716
+ if (!storage) {
717
+ throw new Error('sessionStorage is unavailable.');
718
+ }
719
+ storage.setItem(GOOGLE_GATEWAY_SESSION_STORAGE_KEY, JSON.stringify(session));
720
+ }
721
+ catch {
722
+ throw new Error('Google Auth Gateway cannot retain its one-time PKCE session.');
723
+ }
724
+ }
725
+ function clearGoogleGatewaySession(documentRef) {
726
+ try {
727
+ documentRef.defaultView?.sessionStorage?.removeItem(GOOGLE_GATEWAY_SESSION_STORAGE_KEY);
728
+ }
729
+ catch {
730
+ // Storage-disabled browsers are treated as having no resumable PKCE session.
731
+ }
732
+ }
733
+ /**
734
+ * Consumes the PKCE session exactly once. Malformed, expired, or cross-MFE
735
+ * records fail closed after removal so they cannot be replayed.
736
+ */
737
+ function consumeGoogleGatewaySession(documentRef, expected) {
738
+ let storage = null;
739
+ let serialized = null;
740
+ try {
741
+ storage = documentRef.defaultView?.sessionStorage ?? null;
742
+ serialized = storage?.getItem(GOOGLE_GATEWAY_SESSION_STORAGE_KEY) ?? null;
743
+ }
744
+ catch {
745
+ return null;
746
+ }
747
+ finally {
748
+ try {
749
+ storage?.removeItem(GOOGLE_GATEWAY_SESSION_STORAGE_KEY);
750
+ }
751
+ catch {
752
+ // Best-effort removal; the callback still fails closed below.
753
+ }
754
+ }
755
+ if (!serialized) {
756
+ return null;
757
+ }
758
+ try {
759
+ const value = JSON.parse(serialized);
760
+ if (!isGoogleGatewaySession(value)) {
761
+ return null;
762
+ }
763
+ const now = expected.now ?? Date.now();
764
+ if (value.mfeId !== expected.mfeId ||
765
+ value.returnUrl !== expected.returnUrl ||
766
+ value.expiresAt <= now) {
767
+ return null;
768
+ }
769
+ return value;
770
+ }
771
+ catch {
772
+ return null;
773
+ }
774
+ }
775
+ function isGoogleGatewaySession(value) {
776
+ if (!value || typeof value !== 'object') {
777
+ return false;
778
+ }
779
+ const record = value;
780
+ return (record['version'] === GOOGLE_GATEWAY_SESSION_VERSION &&
781
+ typeof record['mfeId'] === 'string' &&
782
+ typeof record['returnUrl'] === 'string' &&
783
+ typeof record['codeVerifier'] === 'string' &&
784
+ PKCE_VERIFIER_PATTERN.test(record['codeVerifier']) &&
785
+ typeof record['expiresAt'] === 'number' &&
786
+ Number.isSafeInteger(record['expiresAt']));
787
+ }
788
+ function encodeBase64Url(windowRef, bytes) {
789
+ const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('');
790
+ return windowRef.btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/gu, '');
791
+ }
792
+
631
793
  const GOOGLE_OAUTH_STATE_STORAGE_KEY = 'auth-google-state';
632
794
  const GOOGLE_OAUTH_AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
633
795
  const GOOGLE_OAUTH_SCOPE = 'openid email profile';
@@ -660,6 +822,122 @@ function consumeGoogleOauthState(documentRef) {
660
822
  return state;
661
823
  }
662
824
 
825
+ const MAX_GATEWAY_SESSION_LIFETIME_SECONDS = 600;
826
+ /** HTTP client for the central Google Auth Gateway mode. */
827
+ class GoogleGatewayAuthService {
828
+ config = inject(EDSIS_AUTH_CONFIG);
829
+ documentRef = inject(DOCUMENT);
830
+ http = inject(HttpClient);
831
+ async start() {
832
+ const gateway = this.requireGatewayConfig();
833
+ const windowRef = this.requireWindow();
834
+ clearGoogleGatewaySession(this.documentRef);
835
+ const codeVerifier = createGooglePkceVerifier(windowRef);
836
+ const codeChallenge = await createGooglePkceChallenge(windowRef, codeVerifier);
837
+ const response = await firstValueFrom(this.http.post(gateway.gateway.startUrl, {
838
+ mfeId: gateway.mfeId,
839
+ returnUrl: gateway.returnUrl,
840
+ codeChallenge,
841
+ codeChallengeMethod: 'S256',
842
+ }, { context: skipAuthContext() }));
843
+ const start = parseStartResponse(response);
844
+ storeGoogleGatewaySession(this.documentRef, {
845
+ version: 1,
846
+ mfeId: gateway.mfeId,
847
+ returnUrl: gateway.returnUrl,
848
+ codeVerifier,
849
+ expiresAt: Date.now() + start.expiresInSeconds * 1000,
850
+ });
851
+ return start.authorizationUrl;
852
+ }
853
+ consumeSession() {
854
+ const gateway = this.requireGatewayConfig();
855
+ return consumeGoogleGatewaySession(this.documentRef, {
856
+ mfeId: gateway.mfeId,
857
+ returnUrl: gateway.returnUrl,
858
+ });
859
+ }
860
+ exchangeHandoff(handoffCode, session) {
861
+ const gateway = this.requireGatewayConfig();
862
+ const normalizedHandoffCode = handoffCode.trim();
863
+ if (!normalizedHandoffCode) {
864
+ throw new Error('Google Auth Gateway callback is missing its handoff code.');
865
+ }
866
+ if (session.mfeId !== gateway.mfeId ||
867
+ session.returnUrl !== gateway.returnUrl ||
868
+ session.expiresAt <= Date.now()) {
869
+ throw new Error('Google Auth Gateway session is invalid or expired for this MFE.');
870
+ }
871
+ return firstValueFrom(this.http.post(gateway.gateway.handoffUrl, {
872
+ mfeId: gateway.mfeId,
873
+ returnUrl: gateway.returnUrl,
874
+ handoffCode: normalizedHandoffCode,
875
+ codeVerifier: session.codeVerifier,
876
+ }, {
877
+ context: skipAuthContext(),
878
+ withCredentials: true,
879
+ }));
880
+ }
881
+ requireGatewayConfig() {
882
+ const google = this.config.oauth.google;
883
+ if (google?.mode !== 'gateway') {
884
+ throw new Error('Google Auth Gateway mode is not configured.');
885
+ }
886
+ return google;
887
+ }
888
+ requireWindow() {
889
+ const windowRef = this.documentRef.defaultView;
890
+ if (!windowRef) {
891
+ throw new Error('Google Auth Gateway requires a browser window.');
892
+ }
893
+ return windowRef;
894
+ }
895
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.7", ngImport: i0, type: GoogleGatewayAuthService, deps: [], target: i0.ɵɵFactoryTarget.Service });
896
+ static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.0.7", ngImport: i0, type: GoogleGatewayAuthService });
897
+ }
898
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.7", ngImport: i0, type: GoogleGatewayAuthService, decorators: [{
899
+ type: Service
900
+ }] });
901
+ function parseStartResponse(response) {
902
+ if (!response || typeof response !== 'object') {
903
+ throw new Error('Google Auth Gateway returned an invalid start response.');
904
+ }
905
+ const envelope = response;
906
+ const data = envelope['data'];
907
+ if (!data || typeof data !== 'object') {
908
+ throw new Error('Google Auth Gateway start response is missing data.');
909
+ }
910
+ const record = data;
911
+ const authorizationUrl = record['authorizationUrl'];
912
+ const expiresInSeconds = record['expiresInSeconds'];
913
+ if (typeof authorizationUrl !== 'string' || !isTrustedGoogleAuthorizationUrl(authorizationUrl)) {
914
+ throw new Error('Google Auth Gateway returned an invalid authorization URL.');
915
+ }
916
+ if (typeof expiresInSeconds !== 'number' ||
917
+ !Number.isSafeInteger(expiresInSeconds) ||
918
+ expiresInSeconds <= 0 ||
919
+ expiresInSeconds > MAX_GATEWAY_SESSION_LIFETIME_SECONDS) {
920
+ throw new Error('Google Auth Gateway returned an invalid session lifetime.');
921
+ }
922
+ return { authorizationUrl, expiresInSeconds };
923
+ }
924
+ function isTrustedGoogleAuthorizationUrl(value) {
925
+ try {
926
+ const authorizationUrl = new URL(value);
927
+ const trustedUrl = new URL(GOOGLE_OAUTH_AUTHORIZE_URL);
928
+ return (authorizationUrl.origin === trustedUrl.origin &&
929
+ authorizationUrl.pathname === trustedUrl.pathname &&
930
+ !authorizationUrl.username &&
931
+ !authorizationUrl.password);
932
+ }
933
+ catch {
934
+ return false;
935
+ }
936
+ }
937
+ function skipAuthContext() {
938
+ return new HttpContext().set(EDSIS_SKIP_AUTH, true);
939
+ }
940
+
663
941
  class AuthShellPage {
664
942
  runtimeContext = inject(RuntimeContextService, { optional: true });
665
943
  nativeHost = inject(NativeHostService, { optional: true });
@@ -820,6 +1098,7 @@ class AuthGoogleCallbackPage {
820
1098
  authSessionService = inject(AuthSessionService);
821
1099
  authService = inject(AuthService);
822
1100
  authConfig = inject(EDSIS_AUTH_CONFIG);
1101
+ googleGateway = inject(GoogleGatewayAuthService);
823
1102
  messages = inject(EDSIS_AUTH_MESSAGES);
824
1103
  loginPath = this.authConfig.loginPath;
825
1104
  authenticatedHomePath = this.authConfig.authenticatedHomePath;
@@ -844,14 +1123,41 @@ class AuthGoogleCallbackPage {
844
1123
  const oauthError = queryParams.get('error')?.trim() ?? '';
845
1124
  const code = queryParams.get('code')?.trim() ?? '';
846
1125
  const returnedState = queryParams.get('state')?.trim() ?? '';
847
- // State dikonsumsi (dibaca + dihapus) sebelum bercabang supaya bersih di
848
- // semua cabang, termasuk cabang error dari Google.
849
- const storedState = consumeGoogleOauthState(this.documentRef);
1126
+ const handoffCode = queryParams.get('handoffCode')?.trim() ?? '';
1127
+ const googleOauth = this.authConfig.oauth.google;
850
1128
  this.clearCallbackParamsFromAddressBar();
1129
+ if (!googleOauth) {
1130
+ consumeGoogleOauthState(this.documentRef);
1131
+ clearGoogleGatewaySession(this.documentRef);
1132
+ this.fail(this.messages.google.googleCallbackError);
1133
+ return;
1134
+ }
1135
+ if (googleOauth.mode === 'gateway') {
1136
+ consumeGoogleOauthState(this.documentRef);
1137
+ // Konsumsi verifier sebelum bercabang; callback error dan replay tidak
1138
+ // boleh menyisakan sesi PKCE yang dapat dipakai kembali.
1139
+ const gatewaySession = this.googleGateway.consumeSession();
1140
+ if (oauthError) {
1141
+ this.fail(this.callbackErrorMessage(oauthError));
1142
+ return;
1143
+ }
1144
+ if (!gatewaySession) {
1145
+ this.fail(this.messages.google.gatewaySessionMissing);
1146
+ return;
1147
+ }
1148
+ if (!handoffCode) {
1149
+ this.fail(this.messages.google.googleCallbackError);
1150
+ return;
1151
+ }
1152
+ void this.exchangeGatewayHandoff(handoffCode, gatewaySession);
1153
+ return;
1154
+ }
1155
+ clearGoogleGatewaySession(this.documentRef);
1156
+ // Direct-mode state dikonsumsi (dibaca + dihapus) sebelum bercabang supaya
1157
+ // bersih di semua cabang, termasuk error dari Google.
1158
+ const storedState = consumeGoogleOauthState(this.documentRef);
851
1159
  if (oauthError) {
852
- this.fail(oauthError === 'access_denied'
853
- ? this.messages.google.googleAccessDenied
854
- : this.messages.google.googleCallbackError);
1160
+ this.fail(this.callbackErrorMessage(oauthError));
855
1161
  return;
856
1162
  }
857
1163
  if (!returnedState || !storedState || returnedState !== storedState) {
@@ -862,14 +1168,14 @@ class AuthGoogleCallbackPage {
862
1168
  this.fail(this.messages.google.googleCallbackError);
863
1169
  return;
864
1170
  }
865
- this.exchange(code);
1171
+ this.exchangeDirectCode(code);
866
1172
  }
867
1173
  clearCallbackParamsFromAddressBar() {
868
1174
  this.location.replaceState(`/${GOOGLE_OAUTH_CALLBACK_ROUTE_PATH}`);
869
1175
  }
870
- exchange(code) {
1176
+ exchangeDirectCode(code) {
871
1177
  const googleOauth = this.authConfig.oauth.google;
872
- if (!googleOauth) {
1178
+ if (!googleOauth || googleOauth.mode !== 'direct') {
873
1179
  this.fail(this.messages.google.googleCallbackError);
874
1180
  return;
875
1181
  }
@@ -884,21 +1190,38 @@ class AuthGoogleCallbackPage {
884
1190
  })
885
1191
  .pipe(takeUntilDestroyed(this.destroyRef))
886
1192
  .subscribe({
887
- next: (response) => {
888
- this.authService.acceptTokenResponse(response);
889
- if (!this.authService.isAuthenticated()) {
890
- this.fail(this.messages.google.missingAccessToken);
891
- return;
892
- }
893
- this.state.set('success');
894
- this.message.set(getResponseMessage(response, this.messages.google.successRedirect));
895
- void this.router.navigateByUrl(this.authenticatedHomePath, { replaceUrl: true });
896
- },
1193
+ next: (response) => this.complete(response),
897
1194
  error: (error) => {
898
1195
  this.fail(getBackendErrorMessage(error, this.messages.google.googleCallbackError));
899
1196
  },
900
1197
  });
901
1198
  }
1199
+ async exchangeGatewayHandoff(handoffCode, session) {
1200
+ this.state.set('pending');
1201
+ this.message.set(this.messages.google.gatewayHandoffInProgress);
1202
+ try {
1203
+ const response = await this.googleGateway.exchangeHandoff(handoffCode, session);
1204
+ this.complete(response);
1205
+ }
1206
+ catch (error) {
1207
+ this.fail(getBackendErrorMessage(error, this.messages.google.googleCallbackError));
1208
+ }
1209
+ }
1210
+ complete(response) {
1211
+ this.authService.acceptTokenResponse(response);
1212
+ if (!this.authService.isAuthenticated()) {
1213
+ this.fail(this.messages.google.missingAccessToken);
1214
+ return;
1215
+ }
1216
+ this.state.set('success');
1217
+ this.message.set(getResponseMessage(response, this.messages.google.successRedirect));
1218
+ void this.router.navigateByUrl(this.authenticatedHomePath, { replaceUrl: true });
1219
+ }
1220
+ callbackErrorMessage(error) {
1221
+ return error === 'access_denied'
1222
+ ? this.messages.google.googleAccessDenied
1223
+ : this.messages.google.googleCallbackError;
1224
+ }
902
1225
  fail(message) {
903
1226
  this.state.set('error');
904
1227
  this.message.set(message);
@@ -1067,6 +1390,7 @@ class AuthLoginPage {
1067
1390
  injector = inject(Injector);
1068
1391
  authMagicLinkService = inject(AuthMagicLinkService);
1069
1392
  authConfig = inject(EDSIS_AUTH_CONFIG);
1393
+ googleGateway = inject(GoogleGatewayAuthService);
1070
1394
  nativeGoogle = inject(NativeGoogleAuthService, { optional: true });
1071
1395
  router = inject(Router, { optional: true });
1072
1396
  messages = inject(EDSIS_AUTH_MESSAGES);
@@ -1193,7 +1517,12 @@ class AuthLoginPage {
1193
1517
  const windowRef = this.documentRef.defaultView;
1194
1518
  if (!googleOauth || !windowRef)
1195
1519
  return;
1520
+ if (googleOauth.mode === 'gateway') {
1521
+ void this.signInWithGatewayGoogle();
1522
+ return;
1523
+ }
1196
1524
  this.isGoogleRedirecting.set(true);
1525
+ this.googleErrorMessage.set(null);
1197
1526
  const state = createGoogleOauthState(windowRef);
1198
1527
  storeGoogleOauthState(this.documentRef, state);
1199
1528
  this.redirectTo(buildGoogleAuthorizeUrl({
@@ -1202,6 +1531,18 @@ class AuthLoginPage {
1202
1531
  state,
1203
1532
  }));
1204
1533
  }
1534
+ async signInWithGatewayGoogle() {
1535
+ this.isGoogleRedirecting.set(true);
1536
+ this.googleErrorMessage.set(null);
1537
+ try {
1538
+ const authorizationUrl = await this.googleGateway.start();
1539
+ this.redirectTo(authorizationUrl);
1540
+ }
1541
+ catch (error) {
1542
+ this.googleErrorMessage.set(getBackendErrorMessage(error, this.messages.google.gatewayStartFailed));
1543
+ this.isGoogleRedirecting.set(false);
1544
+ }
1545
+ }
1205
1546
  async signInWithNativeGoogle() {
1206
1547
  if (!this.nativeGoogle)
1207
1548
  return;
@@ -2242,5 +2583,5 @@ const authRoutes = [
2242
2583
  * Generated bundle index. Do not edit.
2243
2584
  */
2244
2585
 
2245
- export { AuthGoogleCallbackPage, AuthLoginPage, AuthLogoutPage, AuthService, AuthShellPage, AuthVerifyPage, DEFAULT_EDSIS_AUTH_MESSAGES, EDSIS_AUTH_CONFIG, EDSIS_AUTH_MESSAGES, EDSIS_NATIVE_GOOGLE_AUTH_ADAPTER, EDSIS_SKIP_AUTH, GOOGLE_OAUTH_AUTHORIZE_URL, GOOGLE_OAUTH_CALLBACK_ROUTE_PATH, GOOGLE_OAUTH_STATE_STORAGE_KEY, NativeGoogleAuthService, TauriNativeGoogleAuthAdapter, authRoutes, authenticatedGuard, buildGoogleAuthorizeUrl, consumeGoogleOauthState, createGoogleOauthState, edsisAuthInterceptor, guestOnlyGuard, homeRedirectGuard, isNativeGoogleSignInResult, mergeEdsisAuthMessages, provideEdsisAuth, resolveEdsisAuthConfig, setAuthNotificationBadge, storeGoogleOauthState };
2586
+ export { AuthGoogleCallbackPage, AuthLoginPage, AuthLogoutPage, AuthService, AuthShellPage, AuthVerifyPage, DEFAULT_EDSIS_AUTH_MESSAGES, EDSIS_AUTH_CONFIG, EDSIS_AUTH_MESSAGES, EDSIS_NATIVE_GOOGLE_AUTH_ADAPTER, EDSIS_SKIP_AUTH, GOOGLE_AUTH_GATEWAY_DEFAULT_HANDOFF_ENDPOINT, GOOGLE_AUTH_GATEWAY_DEFAULT_START_ENDPOINT, GOOGLE_GATEWAY_SESSION_STORAGE_KEY, GOOGLE_GATEWAY_SESSION_VERSION, GOOGLE_OAUTH_AUTHORIZE_URL, GOOGLE_OAUTH_CALLBACK_ROUTE_PATH, GOOGLE_OAUTH_STATE_STORAGE_KEY, GoogleGatewayAuthService, NativeGoogleAuthService, TauriNativeGoogleAuthAdapter, authRoutes, authenticatedGuard, buildGoogleAuthorizeUrl, clearGoogleGatewaySession, consumeGoogleGatewaySession, consumeGoogleOauthState, createGoogleOauthState, createGooglePkceChallenge, createGooglePkceVerifier, edsisAuthInterceptor, guestOnlyGuard, homeRedirectGuard, isNativeGoogleSignInResult, mergeEdsisAuthMessages, provideEdsisAuth, resolveEdsisAuthConfig, setAuthNotificationBadge, storeGoogleGatewaySession, storeGoogleOauthState };
2246
2587
  //# sourceMappingURL=edsis-angular-module-auth.mjs.map