@meshmakers/shared-auth 3.5.780 → 3.5.800
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/fesm2022/meshmakers-shared-auth-dash0.mjs +29 -58
- package/fesm2022/meshmakers-shared-auth-dash0.mjs.map +1 -1
- package/fesm2022/meshmakers-shared-auth-login-ui.mjs +230 -127
- package/fesm2022/meshmakers-shared-auth-login-ui.mjs.map +1 -1
- package/fesm2022/meshmakers-shared-auth.mjs +1063 -2021
- package/fesm2022/meshmakers-shared-auth.mjs.map +1 -1
- package/package.json +1 -1
- package/types/meshmakers-shared-auth-dash0.d.ts +15 -16
- package/types/meshmakers-shared-auth-login-ui.d.ts +51 -44
- package/types/meshmakers-shared-auth.d.ts +489 -500
|
@@ -1,1814 +1,897 @@
|
|
|
1
|
-
import * as i0 from
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { catchError,
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Minimal JWT payload access for the claims this library routes on: `tenant_id` and
|
|
10
|
-
* `allowed_tenants`.
|
|
11
|
-
*
|
|
12
|
-
* Decoding only, no signature validation. The token was issued to this client by identity and
|
|
13
|
-
* is used for client-side decisions the backend enforces again on every request.
|
|
14
|
-
*/
|
|
1
|
+
import * as i0 from "@angular/core";
|
|
2
|
+
import { ChangeDetectionStrategy, Component, Injectable, InjectionToken, computed, effect, inject, makeEnvironmentProviders, signal, viewChild } from "@angular/core";
|
|
3
|
+
import { OAuthService, OAuthStorage, provideOAuthClient } from "angular-oauth2-oidc";
|
|
4
|
+
import { HttpBackend, HttpClient, HttpErrorResponse, HttpParams } from "@angular/common/http";
|
|
5
|
+
import { catchError, firstValueFrom, from, switchMap, throwError, timeout } from "rxjs";
|
|
6
|
+
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
|
|
15
7
|
function decodeJwtPayload(token) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
|
|
27
|
-
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
28
|
-
return JSON.parse(atob(padded));
|
|
29
|
-
}
|
|
30
|
-
catch {
|
|
31
|
-
return null;
|
|
32
|
-
}
|
|
8
|
+
if (!token) return null;
|
|
9
|
+
try {
|
|
10
|
+
const parts = token.split(".");
|
|
11
|
+
if (parts.length !== 3) return null;
|
|
12
|
+
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
13
|
+
const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
|
|
14
|
+
return JSON.parse(atob(padded));
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
33
18
|
}
|
|
34
|
-
/** The `tenant_id` claim: the tenant the token was issued for, or null. */
|
|
35
19
|
function tenantIdFromToken(token) {
|
|
36
|
-
|
|
37
|
-
|
|
20
|
+
const tenantId = decodeJwtPayload(token)?.["tenant_id"];
|
|
21
|
+
return typeof tenantId === "string" && tenantId.length > 0 ? tenantId : null;
|
|
38
22
|
}
|
|
39
|
-
/** The `allowed_tenants` claim as a list. A single-valued claim arrives as a plain string. */
|
|
40
23
|
function allowedTenantsFromToken(token) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (typeof allowed === 'string') {
|
|
46
|
-
return [allowed];
|
|
47
|
-
}
|
|
48
|
-
return [];
|
|
24
|
+
const allowed = decodeJwtPayload(token)?.["allowed_tenants"];
|
|
25
|
+
if (Array.isArray(allowed)) return allowed.filter((tenantId) => typeof tenantId === "string");
|
|
26
|
+
if (typeof allowed === "string") return [allowed];
|
|
27
|
+
return [];
|
|
49
28
|
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Known OAuth storage keys used by angular-oauth2-oidc.
|
|
53
|
-
* Used by clearAllTenants() to identify and remove OAuth-related entries
|
|
54
|
-
* across all tenants without affecting other localStorage data.
|
|
55
|
-
*/
|
|
56
29
|
const OAUTH_STORAGE_KEYS = [
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
30
|
+
"access_token",
|
|
31
|
+
"refresh_token",
|
|
32
|
+
"id_token",
|
|
33
|
+
"id_token_claims_obj",
|
|
34
|
+
"id_token_header",
|
|
35
|
+
"expires_at",
|
|
36
|
+
"access_token_stored_at",
|
|
37
|
+
"id_token_expires_at",
|
|
38
|
+
"id_token_stored_at",
|
|
39
|
+
"nonce",
|
|
40
|
+
"PKCE_verifier",
|
|
41
|
+
"session_state",
|
|
42
|
+
"granted_scopes",
|
|
43
|
+
"requested_route"
|
|
71
44
|
];
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
*
|
|
77
|
-
* Without this, two tabs starting login simultaneously would overwrite
|
|
78
|
-
* each other's nonce in shared localStorage, causing "invalid_nonce_in_state"
|
|
79
|
-
* errors when the first tab's callback tries to validate.
|
|
80
|
-
*/
|
|
81
|
-
const SESSION_SCOPED_KEYS = new Set([
|
|
82
|
-
'nonce',
|
|
83
|
-
'PKCE_verifier',
|
|
84
|
-
'requested_route',
|
|
45
|
+
const SESSION_SCOPED_KEYS = /* @__PURE__ */ new Set([
|
|
46
|
+
"nonce",
|
|
47
|
+
"PKCE_verifier",
|
|
48
|
+
"requested_route"
|
|
85
49
|
]);
|
|
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
|
-
adoptUnprefixedSession(tenantId) {
|
|
167
|
-
const prefix = `${tenantId}__`;
|
|
168
|
-
const slotKeys = OAUTH_STORAGE_KEYS.filter(key => !SESSION_SCOPED_KEYS.has(key));
|
|
169
|
-
let unprefixedAccessToken;
|
|
170
|
-
try {
|
|
171
|
-
if (slotKeys.some(key => localStorage.getItem(prefix + key) !== null)) {
|
|
172
|
-
return false;
|
|
173
|
-
}
|
|
174
|
-
unprefixedAccessToken = localStorage.getItem('access_token');
|
|
175
|
-
}
|
|
176
|
-
catch {
|
|
177
|
-
return false;
|
|
178
|
-
}
|
|
179
|
-
const issuedFor = tenantIdFromToken(unprefixedAccessToken);
|
|
180
|
-
if (!issuedFor || issuedFor.toLowerCase() !== tenantId.toLowerCase()) {
|
|
181
|
-
return false;
|
|
182
|
-
}
|
|
183
|
-
for (const key of slotKeys) {
|
|
184
|
-
const value = localStorage.getItem(key);
|
|
185
|
-
if (value === null) {
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
localStorage.setItem(prefix + key, value);
|
|
189
|
-
localStorage.removeItem(key);
|
|
190
|
-
}
|
|
191
|
-
return true;
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Restores the tenant ID from sessionStorage.
|
|
195
|
-
* Call this on app startup when the tenant cannot be determined from the URL
|
|
196
|
-
* (e.g., after an OAuth redirect to the root path).
|
|
197
|
-
*
|
|
198
|
-
* @returns The restored tenant ID, or null if none was persisted.
|
|
199
|
-
*/
|
|
200
|
-
restoreTenantId() {
|
|
201
|
-
try {
|
|
202
|
-
const stored = sessionStorage.getItem(STORAGE_TENANT_KEY);
|
|
203
|
-
if (stored) {
|
|
204
|
-
this.tenantId = stored;
|
|
205
|
-
return stored;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
catch {
|
|
209
|
-
// sessionStorage may be unavailable
|
|
210
|
-
}
|
|
211
|
-
return null;
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Returns the prefixed key for the given base key.
|
|
215
|
-
* When tenantId is null, returns the base key unchanged.
|
|
216
|
-
*/
|
|
217
|
-
prefixKey(key) {
|
|
218
|
-
if (this.tenantId) {
|
|
219
|
-
return `${this.tenantId}__${key}`;
|
|
220
|
-
}
|
|
221
|
-
return key;
|
|
222
|
-
}
|
|
223
|
-
getItem(key) {
|
|
224
|
-
const prefixed = this.prefixKey(key);
|
|
225
|
-
if (SESSION_SCOPED_KEYS.has(key)) {
|
|
226
|
-
return sessionStorage.getItem(prefixed);
|
|
227
|
-
}
|
|
228
|
-
return localStorage.getItem(prefixed);
|
|
229
|
-
}
|
|
230
|
-
removeItem(key) {
|
|
231
|
-
const prefixed = this.prefixKey(key);
|
|
232
|
-
if (SESSION_SCOPED_KEYS.has(key)) {
|
|
233
|
-
sessionStorage.removeItem(prefixed);
|
|
234
|
-
}
|
|
235
|
-
else {
|
|
236
|
-
localStorage.removeItem(prefixed);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
setItem(key, data) {
|
|
240
|
-
const prefixed = this.prefixKey(key);
|
|
241
|
-
if (SESSION_SCOPED_KEYS.has(key)) {
|
|
242
|
-
sessionStorage.setItem(prefixed, data);
|
|
243
|
-
}
|
|
244
|
-
else {
|
|
245
|
-
localStorage.setItem(prefixed, data);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Clears all OAuth-related keys for ALL tenants from both
|
|
250
|
-
* localStorage and sessionStorage, while leaving non-OAuth data intact.
|
|
251
|
-
*
|
|
252
|
-
* Used during full logout to ensure no stale tokens remain for any tenant.
|
|
253
|
-
*/
|
|
254
|
-
clearAllTenants() {
|
|
255
|
-
this.clearOAuthKeysFromStorage(localStorage);
|
|
256
|
-
this.clearOAuthKeysFromStorage(sessionStorage);
|
|
257
|
-
}
|
|
258
|
-
clearOAuthKeysFromStorage(storage) {
|
|
259
|
-
const keysToRemove = [];
|
|
260
|
-
for (let i = 0; i < storage.length; i++) {
|
|
261
|
-
const storageKey = storage.key(i);
|
|
262
|
-
if (!storageKey)
|
|
263
|
-
continue;
|
|
264
|
-
for (const oauthKey of OAUTH_STORAGE_KEYS) {
|
|
265
|
-
if (storageKey === oauthKey || storageKey.endsWith('__' + oauthKey)) {
|
|
266
|
-
keysToRemove.push(storageKey);
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
for (const key of keysToRemove) {
|
|
272
|
-
storage.removeItem(key);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/**
|
|
278
|
-
* Optional DI token. Apps that provide it get their sink driven by `AuthorizeService`; apps that do not
|
|
279
|
-
* see no behaviour change at all. See `provideDash0SessionIdentity()` in `@meshmakers/shared-auth/dash0`.
|
|
280
|
-
*/
|
|
281
|
-
const SESSION_IDENTITY_SINK = new InjectionToken('SESSION_IDENTITY_SINK');
|
|
282
|
-
/** True when both identities describe the same user on the same tenant. */
|
|
50
|
+
const STORAGE_TENANT_KEY = "octo_storage_tenant";
|
|
51
|
+
var TenantAwareOAuthStorage = class extends OAuthStorage {
|
|
52
|
+
tenantId = null;
|
|
53
|
+
setTenantId(tenantId) {
|
|
54
|
+
this.tenantId = tenantId;
|
|
55
|
+
try {
|
|
56
|
+
if (tenantId) sessionStorage.setItem(STORAGE_TENANT_KEY, tenantId);
|
|
57
|
+
else sessionStorage.removeItem(STORAGE_TENANT_KEY);
|
|
58
|
+
} catch {}
|
|
59
|
+
}
|
|
60
|
+
getTenantId() {
|
|
61
|
+
return this.tenantId;
|
|
62
|
+
}
|
|
63
|
+
adoptUnprefixedSession(tenantId) {
|
|
64
|
+
const prefix = `${tenantId}__`;
|
|
65
|
+
const slotKeys = OAUTH_STORAGE_KEYS.filter((key) => !SESSION_SCOPED_KEYS.has(key));
|
|
66
|
+
let unprefixedAccessToken;
|
|
67
|
+
try {
|
|
68
|
+
if (slotKeys.some((key) => localStorage.getItem(prefix + key) !== null)) return false;
|
|
69
|
+
unprefixedAccessToken = localStorage.getItem("access_token");
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
const issuedFor = tenantIdFromToken(unprefixedAccessToken);
|
|
74
|
+
if (!issuedFor || issuedFor.toLowerCase() !== tenantId.toLowerCase()) return false;
|
|
75
|
+
for (const key of slotKeys) {
|
|
76
|
+
const value = localStorage.getItem(key);
|
|
77
|
+
if (value === null) continue;
|
|
78
|
+
localStorage.setItem(prefix + key, value);
|
|
79
|
+
localStorage.removeItem(key);
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
restoreTenantId() {
|
|
84
|
+
try {
|
|
85
|
+
const stored = sessionStorage.getItem(STORAGE_TENANT_KEY);
|
|
86
|
+
if (stored) {
|
|
87
|
+
this.tenantId = stored;
|
|
88
|
+
return stored;
|
|
89
|
+
}
|
|
90
|
+
} catch {}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
prefixKey(key) {
|
|
94
|
+
if (this.tenantId) return `${this.tenantId}__${key}`;
|
|
95
|
+
return key;
|
|
96
|
+
}
|
|
97
|
+
getItem(key) {
|
|
98
|
+
const prefixed = this.prefixKey(key);
|
|
99
|
+
if (SESSION_SCOPED_KEYS.has(key)) return sessionStorage.getItem(prefixed);
|
|
100
|
+
return localStorage.getItem(prefixed);
|
|
101
|
+
}
|
|
102
|
+
removeItem(key) {
|
|
103
|
+
const prefixed = this.prefixKey(key);
|
|
104
|
+
if (SESSION_SCOPED_KEYS.has(key)) sessionStorage.removeItem(prefixed);
|
|
105
|
+
else localStorage.removeItem(prefixed);
|
|
106
|
+
}
|
|
107
|
+
setItem(key, data) {
|
|
108
|
+
const prefixed = this.prefixKey(key);
|
|
109
|
+
if (SESSION_SCOPED_KEYS.has(key)) sessionStorage.setItem(prefixed, data);
|
|
110
|
+
else localStorage.setItem(prefixed, data);
|
|
111
|
+
}
|
|
112
|
+
clearAllTenants() {
|
|
113
|
+
this.clearOAuthKeysFromStorage(localStorage);
|
|
114
|
+
this.clearOAuthKeysFromStorage(sessionStorage);
|
|
115
|
+
}
|
|
116
|
+
clearOAuthKeysFromStorage(storage) {
|
|
117
|
+
const keysToRemove = [];
|
|
118
|
+
for (let i = 0; i < storage.length; i++) {
|
|
119
|
+
const storageKey = storage.key(i);
|
|
120
|
+
if (!storageKey) continue;
|
|
121
|
+
for (const oauthKey of OAUTH_STORAGE_KEYS) if (storageKey === oauthKey || storageKey.endsWith("__" + oauthKey)) {
|
|
122
|
+
keysToRemove.push(storageKey);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const key of keysToRemove) storage.removeItem(key);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
const SESSION_IDENTITY_SINK = new InjectionToken("SESSION_IDENTITY_SINK");
|
|
283
130
|
function sameSessionIdentity(a, b) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
if (a === null || b === null) {
|
|
288
|
-
return false;
|
|
289
|
-
}
|
|
290
|
-
return a.userId === b.userId && a.name === b.name && a.email === b.email && a.tenantId === b.tenantId;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
class AuthorizeOptions {
|
|
294
|
-
wellKnownServiceUris;
|
|
295
|
-
// Url of the Identity Provider
|
|
296
|
-
issuer;
|
|
297
|
-
// URL of the SPA to redirect the user to after login
|
|
298
|
-
redirectUri;
|
|
299
|
-
postLogoutRedirectUri;
|
|
300
|
-
// The SPA's id. The SPA is registered with this id at the auth-server
|
|
301
|
-
clientId;
|
|
302
|
-
// set the scope for the permissions the client should request
|
|
303
|
-
// The first three are defined by OIDC. The 4th is a use case-specific one
|
|
304
|
-
scope;
|
|
305
|
-
showDebugInformation;
|
|
306
|
-
sessionChecksEnabled;
|
|
307
|
-
// Default tenant ID for single-tenant apps. When set, login() uses this tenant
|
|
308
|
-
// if no tenantId is explicitly provided (sends acr_values=tenant:{defaultTenantId}).
|
|
309
|
-
defaultTenantId;
|
|
310
|
-
// Discovery scope for an app host that serves one tenant subtree (AB#5311/5312).
|
|
311
|
-
// A login() without a tenant — and without defaultTenantId — then sends
|
|
312
|
-
// acr_values=tenant_scope:{discoveryScopeTenantId}: identity still resolves the
|
|
313
|
-
// tenant itself (single-session shortcut or its email-first tenant discovery),
|
|
314
|
-
// but offers only the tenants strictly below the scope. Typically the app's
|
|
315
|
-
// rootTenantId. Ignored when a tenant is named, explicitly or by default.
|
|
316
|
-
discoveryScopeTenantId;
|
|
317
|
-
// Retry policy for loadDiscoveryDocumentAndTryLogin() — covers the brief
|
|
318
|
-
// window during which the Identity service is unreachable after a redeploy
|
|
319
|
-
// or rolling restart. Defaults: 6 attempts, 1500ms initial, 30000ms cap.
|
|
320
|
-
discoveryDocumentRetry;
|
|
321
|
-
}
|
|
322
|
-
class AuthorizeService {
|
|
323
|
-
oauthService = inject(OAuthService);
|
|
324
|
-
// =============================================================================
|
|
325
|
-
// INTERNAL STATE (Writable Signals)
|
|
326
|
-
// =============================================================================
|
|
327
|
-
_isAuthenticated = signal(false, /* @ts-ignore */
|
|
328
|
-
...(ngDevMode ? [{ debugName: "_isAuthenticated" }] : /* istanbul ignore next */ []));
|
|
329
|
-
_issuer = signal(null, /* @ts-ignore */
|
|
330
|
-
...(ngDevMode ? [{ debugName: "_issuer" }] : /* istanbul ignore next */ []));
|
|
331
|
-
_accessToken = signal(null, /* @ts-ignore */
|
|
332
|
-
...(ngDevMode ? [{ debugName: "_accessToken" }] : /* istanbul ignore next */ []));
|
|
333
|
-
_user = signal(null, /* @ts-ignore */
|
|
334
|
-
...(ngDevMode ? [{ debugName: "_user" }] : /* istanbul ignore next */ []));
|
|
335
|
-
_userInitials = signal(null, /* @ts-ignore */
|
|
336
|
-
...(ngDevMode ? [{ debugName: "_userInitials" }] : /* istanbul ignore next */ []));
|
|
337
|
-
_isInitialized = signal(false, /* @ts-ignore */
|
|
338
|
-
...(ngDevMode ? [{ debugName: "_isInitialized" }] : /* istanbul ignore next */ []));
|
|
339
|
-
_isInitializing = signal(false, /* @ts-ignore */
|
|
340
|
-
...(ngDevMode ? [{ debugName: "_isInitializing" }] : /* istanbul ignore next */ []));
|
|
341
|
-
_sessionLoading = signal(false, /* @ts-ignore */
|
|
342
|
-
...(ngDevMode ? [{ debugName: "_sessionLoading" }] : /* istanbul ignore next */ []));
|
|
343
|
-
_allowedTenants = signal([], /* @ts-ignore */
|
|
344
|
-
...(ngDevMode ? [{ debugName: "_allowedTenants" }] : /* istanbul ignore next */ []));
|
|
345
|
-
_tokenTenantId = signal(null, /* @ts-ignore */
|
|
346
|
-
...(ngDevMode ? [{ debugName: "_tokenTenantId" }] : /* istanbul ignore next */ []));
|
|
347
|
-
_discoveryDocumentError = signal(null, /* @ts-ignore */
|
|
348
|
-
...(ngDevMode ? [{ debugName: "_discoveryDocumentError" }] : /* istanbul ignore next */ []));
|
|
349
|
-
_discoveryDocumentRetryAttempt = signal(0, /* @ts-ignore */
|
|
350
|
-
...(ngDevMode ? [{ debugName: "_discoveryDocumentRetryAttempt" }] : /* istanbul ignore next */ []));
|
|
351
|
-
static TENANT_REAUTH_KEY = 'octo_tenant_reauth';
|
|
352
|
-
/** RFC 8693 token exchange, used to switch tenants without a redirect. */
|
|
353
|
-
static TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
|
354
|
-
static ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
|
|
355
|
-
static TENANT_SWITCH_ATTEMPTED_KEY = 'octo_tenant_switch_attempted';
|
|
356
|
-
/** Set when the user explicitly retried the sign-in from the tenant-mismatch screen (AB#6731). */
|
|
357
|
-
static TENANT_SIGNIN_RETRIED_KEY = 'octo_tenant_signin_retried';
|
|
358
|
-
static DEFAULT_DISCOVERY_RETRY = {
|
|
359
|
-
attempts: 6,
|
|
360
|
-
initialDelayMs: 1500,
|
|
361
|
-
maxDelayMs: 30000
|
|
362
|
-
};
|
|
363
|
-
tenantStorage = new TenantAwareOAuthStorage();
|
|
364
|
-
_loginInProgress = false;
|
|
365
|
-
authorizeOptions = null;
|
|
366
|
-
lastAuthConfig = null;
|
|
367
|
-
// =============================================================================
|
|
368
|
-
// PUBLIC API (Readonly Signals) - NEW API
|
|
369
|
-
// =============================================================================
|
|
370
|
-
/**
|
|
371
|
-
* Signal indicating whether the user is currently authenticated.
|
|
372
|
-
*/
|
|
373
|
-
isAuthenticated = this._isAuthenticated.asReadonly();
|
|
374
|
-
/**
|
|
375
|
-
* Signal containing the issuer URL.
|
|
376
|
-
*/
|
|
377
|
-
issuer = this._issuer.asReadonly();
|
|
378
|
-
/**
|
|
379
|
-
* Signal containing the current access token.
|
|
380
|
-
*/
|
|
381
|
-
accessToken = this._accessToken.asReadonly();
|
|
382
|
-
/**
|
|
383
|
-
* Signal containing the current user information.
|
|
384
|
-
*/
|
|
385
|
-
user = this._user.asReadonly();
|
|
386
|
-
/**
|
|
387
|
-
* Computed signal containing the user's initials (e.g., "JD" for John Doe).
|
|
388
|
-
*/
|
|
389
|
-
userInitials = this._userInitials.asReadonly();
|
|
390
|
-
/**
|
|
391
|
-
* Signal indicating whether the session is currently loading.
|
|
392
|
-
*/
|
|
393
|
-
sessionLoading = this._sessionLoading.asReadonly();
|
|
394
|
-
/**
|
|
395
|
-
* Signal containing the list of tenants the user is allowed to access.
|
|
396
|
-
* Parsed from the allowed_tenants claims in the access token.
|
|
397
|
-
*/
|
|
398
|
-
allowedTenants = this._allowedTenants.asReadonly();
|
|
399
|
-
/**
|
|
400
|
-
* Signal containing the tenant_id claim from the current access token.
|
|
401
|
-
* Used to detect tenant mismatch when navigating between tenants.
|
|
402
|
-
*/
|
|
403
|
-
tokenTenantId = this._tokenTenantId.asReadonly();
|
|
404
|
-
/**
|
|
405
|
-
* Computed signal containing the user's roles.
|
|
406
|
-
*/
|
|
407
|
-
roles = computed(() => this._user()?.role ?? [], /* @ts-ignore */
|
|
408
|
-
...(ngDevMode ? [{ debugName: "roles" }] : /* istanbul ignore next */ []));
|
|
409
|
-
/**
|
|
410
|
-
* Signal carrying the last error from loadDiscoveryDocumentAndTryLogin().
|
|
411
|
-
* Non-null means the Identity service was unreachable across the full retry
|
|
412
|
-
* budget; host apps can render a recovery screen and call retryDiscoveryDocument().
|
|
413
|
-
*/
|
|
414
|
-
discoveryDocumentError = this._discoveryDocumentError.asReadonly();
|
|
415
|
-
/**
|
|
416
|
-
* Signal containing the current discovery-document retry attempt (1-based while
|
|
417
|
-
* retrying, 0 when idle). Useful for showing "Reconnecting (attempt N)…" UI.
|
|
418
|
-
*/
|
|
419
|
-
discoveryDocumentRetryAttempt = this._discoveryDocumentRetryAttempt.asReadonly();
|
|
420
|
-
/**
|
|
421
|
-
* Computed signal for the user's display name.
|
|
422
|
-
* Uses given_name + family_name if available, otherwise derives from the username.
|
|
423
|
-
*/
|
|
424
|
-
displayName = computed(() => {
|
|
425
|
-
const user = this._user();
|
|
426
|
-
if (!user)
|
|
427
|
-
return null;
|
|
428
|
-
if (user.given_name && user.family_name) {
|
|
429
|
-
return user.given_name + ' ' + user.family_name;
|
|
430
|
-
}
|
|
431
|
-
return this.deriveDisplayNameFromUsername(user.name);
|
|
432
|
-
}, /* @ts-ignore */
|
|
433
|
-
...(ngDevMode ? [{ debugName: "displayName" }] : /* istanbul ignore next */ []));
|
|
434
|
-
constructor() {
|
|
435
|
-
console.debug('AuthorizeService::created');
|
|
436
|
-
this.setUpSessionIdentity(inject(SESSION_IDENTITY_SINK, { optional: true }));
|
|
437
|
-
this.oauthService.discoveryDocumentLoaded$.subscribe((_) => {
|
|
438
|
-
console.debug('discoveryDocumentLoaded$');
|
|
439
|
-
});
|
|
440
|
-
this.oauthService.events.subscribe((e) => {
|
|
441
|
-
console.debug('oauth/oidc event', e);
|
|
442
|
-
});
|
|
443
|
-
this.oauthService.events
|
|
444
|
-
.pipe((source) => source)
|
|
445
|
-
.subscribe((e) => {
|
|
446
|
-
if (e.type === 'session_terminated') {
|
|
447
|
-
console.debug('Your session has been terminated!');
|
|
448
|
-
this._accessToken.set(null);
|
|
449
|
-
this._user.set(null);
|
|
450
|
-
this._isAuthenticated.set(false);
|
|
451
|
-
this._tokenTenantId.set(null);
|
|
452
|
-
// Reload the page to trigger the auth flow and redirect to login
|
|
453
|
-
this.reloadPage();
|
|
454
|
-
}
|
|
455
|
-
if (e.type === 'token_refresh_error') {
|
|
456
|
-
console.warn('AuthorizeService: Token refresh failed — clearing local session and reloading');
|
|
457
|
-
this._accessToken.set(null);
|
|
458
|
-
this._user.set(null);
|
|
459
|
-
this._isAuthenticated.set(false);
|
|
460
|
-
this._tokenTenantId.set(null);
|
|
461
|
-
this._allowedTenants.set([]);
|
|
462
|
-
// Do NOT call oauthService.logOut() here — it destroys the server-side
|
|
463
|
-
// session at the Identity Server's end_session_endpoint. If the refresh
|
|
464
|
-
// token is invalid (e.g., after an IDS restart), the user still has a
|
|
465
|
-
// valid IDS session cookie and can silently re-authenticate. Calling
|
|
466
|
-
// logOut() would force a full re-login with credentials.
|
|
467
|
-
// Instead, clear local tokens and reload — the guard will trigger
|
|
468
|
-
// login() which obtains a fresh authorization code via the existing session.
|
|
469
|
-
this.tenantStorage.clearAllTenants();
|
|
470
|
-
this.reloadPage();
|
|
471
|
-
}
|
|
472
|
-
});
|
|
473
|
-
this.oauthService.events.subscribe(async (e) => {
|
|
474
|
-
if (e.type === 'token_received') {
|
|
475
|
-
this._loginInProgress = false;
|
|
476
|
-
await this.loadUserAsync();
|
|
477
|
-
}
|
|
478
|
-
});
|
|
479
|
-
this.oauthService.events.subscribe(async (e) => {
|
|
480
|
-
if (e.type === 'session_unchanged') {
|
|
481
|
-
if (this._user() == null) {
|
|
482
|
-
await this.loadUserAsync();
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
this.oauthService.events.subscribe((e) => {
|
|
487
|
-
if (e.type === 'logout') {
|
|
488
|
-
console.debug('AuthorizeService: Logout event received');
|
|
489
|
-
this._accessToken.set(null);
|
|
490
|
-
this._user.set(null);
|
|
491
|
-
this._isAuthenticated.set(false);
|
|
492
|
-
this._tokenTenantId.set(null);
|
|
493
|
-
this._allowedTenants.set([]);
|
|
494
|
-
// Do NOT call reloadPage() here — oauthService.logOut() already
|
|
495
|
-
// redirects to the Identity Server's end_session_endpoint.
|
|
496
|
-
// Calling reload() would race with that redirect and cause the
|
|
497
|
-
// page to reload before the server-side session is terminated,
|
|
498
|
-
// leaving the user still logged in.
|
|
499
|
-
}
|
|
500
|
-
});
|
|
501
|
-
// Listen for storage events from other tabs (e.g., SLO logout callback)
|
|
502
|
-
// This enables immediate cross-tab logout detection
|
|
503
|
-
window.addEventListener('storage', (event) => {
|
|
504
|
-
console.debug('AuthorizeService: Storage event received', event.key, event.newValue);
|
|
505
|
-
// Check if the current tenant's access_token was removed (logout in another tab)
|
|
506
|
-
// With per-tenant storage, the key is prefixed (e.g., "maco__access_token")
|
|
507
|
-
// Note: OAuth library may set to empty string or null when clearing
|
|
508
|
-
const expectedKey = this.tenantStorage.prefixKey('access_token');
|
|
509
|
-
if (event.key === expectedKey && (event.newValue === null || event.newValue === '') && this._isAuthenticated()) {
|
|
510
|
-
console.debug('AuthorizeService: Access token removed in another tab - logging out and reloading');
|
|
511
|
-
this._accessToken.set(null);
|
|
512
|
-
this._user.set(null);
|
|
513
|
-
this._isAuthenticated.set(false);
|
|
514
|
-
this._tokenTenantId.set(null);
|
|
515
|
-
// Reload the page to trigger the auth flow and redirect to login
|
|
516
|
-
this.reloadPage();
|
|
517
|
-
}
|
|
518
|
-
});
|
|
519
|
-
// Also listen for BroadcastChannel messages for cross-tab logout
|
|
520
|
-
// This is more reliable than storage events for iframe-based SLO
|
|
521
|
-
if (typeof BroadcastChannel !== 'undefined') {
|
|
522
|
-
console.debug("AuthorizeService: Setting up BroadcastChannel listener for 'octo-auth-logout'");
|
|
523
|
-
const logoutChannel = new BroadcastChannel('octo-auth-logout');
|
|
524
|
-
logoutChannel.onmessage = (event) => {
|
|
525
|
-
console.debug('AuthorizeService: BroadcastChannel message received', event.data);
|
|
526
|
-
if (event.data?.type === 'logout' && this._isAuthenticated()) {
|
|
527
|
-
console.debug('AuthorizeService: Logout broadcast received - reloading');
|
|
528
|
-
this._accessToken.set(null);
|
|
529
|
-
this._user.set(null);
|
|
530
|
-
this._isAuthenticated.set(false);
|
|
531
|
-
this._tokenTenantId.set(null);
|
|
532
|
-
this.reloadPage();
|
|
533
|
-
}
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
else {
|
|
537
|
-
console.warn('AuthorizeService: BroadcastChannel not supported in this browser');
|
|
538
|
-
}
|
|
539
|
-
// When the tab returns from the background and we previously failed to load
|
|
540
|
-
// the discovery document (e.g. because the Identity service was redeploying),
|
|
541
|
-
// try to recover automatically. Without this the loading icon would sit
|
|
542
|
-
// forever until the user manually reloads.
|
|
543
|
-
if (typeof document !== 'undefined') {
|
|
544
|
-
document.addEventListener('visibilitychange', () => {
|
|
545
|
-
if (document.visibilityState !== 'visible') {
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
if (this._discoveryDocumentError() && !this._isInitializing() && this.authorizeOptions) {
|
|
549
|
-
console.debug('AuthorizeService: visibilitychange → retrying after discovery-document failure');
|
|
550
|
-
// Re-run initialize() with the last options. We intentionally swallow
|
|
551
|
-
// the error here — initialize() already records it in the signal.
|
|
552
|
-
void this.initialize(this.authorizeOptions).catch(() => undefined);
|
|
553
|
-
}
|
|
554
|
-
});
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Public hook to retry loading the discovery document after a failure.
|
|
559
|
-
* No-op while initialization is in progress.
|
|
560
|
-
*/
|
|
561
|
-
async retryDiscoveryDocument() {
|
|
562
|
-
if (this._isInitializing() || !this.authorizeOptions) {
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
await this.initialize(this.authorizeOptions);
|
|
566
|
-
}
|
|
567
|
-
/**
|
|
568
|
-
* Checks if the current user has the specified role.
|
|
569
|
-
*/
|
|
570
|
-
isInRole(role) {
|
|
571
|
-
return this._user()?.role?.includes(role) ?? false;
|
|
572
|
-
}
|
|
573
|
-
/**
|
|
574
|
-
* Gets the configured service URIs that should receive the authorization token.
|
|
575
|
-
*/
|
|
576
|
-
getServiceUris() {
|
|
577
|
-
return this.authorizeOptions?.wellKnownServiceUris ?? null;
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Sets the tenant ID for per-tenant token storage isolation.
|
|
581
|
-
* Call it BEFORE initialize() so tokens are stored/retrieved under the correct tenant prefix
|
|
582
|
-
* in localStorage.
|
|
583
|
-
*
|
|
584
|
-
* When set, all OAuth storage keys are prefixed with `{tenantId}__`
|
|
585
|
-
* (e.g., `maco__access_token`), preventing token collisions between tenants.
|
|
586
|
-
* The tenant ID is also persisted in sessionStorage so it survives OAuth redirects.
|
|
587
|
-
*
|
|
588
|
-
* It may also be called AFTER initialize(), once the app has learned the tenant from the
|
|
589
|
-
* token: a sign-in that started without a tenant — identity resolved it through tenant
|
|
590
|
-
* discovery — leaves its session in the unprefixed slot, and that session is then moved into
|
|
591
|
-
* the tenant's slot (see {@link TenantAwareOAuthStorage.adoptUnprefixedSession}). Without
|
|
592
|
-
* the move, the next reload on a tenant URL finds an empty slot and re-authenticates silently.
|
|
593
|
-
*
|
|
594
|
-
* @param tenantId The tenant ID to use for storage key prefixing, or null for unprefixed mode.
|
|
595
|
-
*/
|
|
596
|
-
setStorageTenantId(tenantId) {
|
|
597
|
-
if (tenantId && this.tenantStorage.adoptUnprefixedSession(tenantId)) {
|
|
598
|
-
console.debug(`AuthorizeService::setStorageTenantId — adopted the unprefixed session for "${tenantId}"`);
|
|
599
|
-
}
|
|
600
|
-
this.tenantStorage.setTenantId(tenantId);
|
|
601
|
-
console.debug(`AuthorizeService::setStorageTenantId("${tenantId}")`);
|
|
602
|
-
}
|
|
603
|
-
/**
|
|
604
|
-
* Returns the current storage tenant ID.
|
|
605
|
-
* Used by the interceptor to inject acr_values into token endpoint requests.
|
|
606
|
-
*/
|
|
607
|
-
getStorageTenantId() {
|
|
608
|
-
return this.tenantStorage.getTenantId();
|
|
609
|
-
}
|
|
610
|
-
/**
|
|
611
|
-
* Restores the storage tenant ID from sessionStorage.
|
|
612
|
-
* Use this when the tenant ID cannot be determined from the URL
|
|
613
|
-
* (e.g., after an OAuth redirect to the root path).
|
|
614
|
-
*
|
|
615
|
-
* @returns The restored tenant ID, or null if none was persisted.
|
|
616
|
-
*/
|
|
617
|
-
restoreStorageTenantId() {
|
|
618
|
-
const tenantId = this.tenantStorage.restoreTenantId();
|
|
619
|
-
if (tenantId) {
|
|
620
|
-
console.debug(`AuthorizeService::restoreStorageTenantId("${tenantId}")`);
|
|
621
|
-
}
|
|
622
|
-
return tenantId;
|
|
623
|
-
}
|
|
624
|
-
/**
|
|
625
|
-
* Gets the current access token synchronously.
|
|
626
|
-
* Use this for functional interceptors that need immediate access to the token.
|
|
627
|
-
*
|
|
628
|
-
* @returns The current access token or null if not authenticated
|
|
629
|
-
*/
|
|
630
|
-
getAccessTokenSync() {
|
|
631
|
-
return this._accessToken();
|
|
632
|
-
}
|
|
633
|
-
/**
|
|
634
|
-
* Checks if the user is allowed to access the specified tenant.
|
|
635
|
-
* Returns true if no allowed_tenants claims are present (backwards compatibility).
|
|
636
|
-
*/
|
|
637
|
-
isTenantAllowed(tenantId) {
|
|
638
|
-
const allowed = this._allowedTenants();
|
|
639
|
-
if (allowed.length === 0) {
|
|
640
|
-
return true; // No claims = backwards compatible (old tokens)
|
|
641
|
-
}
|
|
642
|
-
return allowed.some(t => t.toLowerCase() === tenantId.toLowerCase());
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Initiates the login flow.
|
|
646
|
-
* Multiple guards (canActivateChild, canMatch) may call this concurrently
|
|
647
|
-
* during route resolution. Only the first call proceeds — subsequent calls
|
|
648
|
-
* are skipped to prevent generating a new nonce that overwrites the first
|
|
649
|
-
* one, which would cause an "invalid_nonce_in_state" error after the
|
|
650
|
-
* identity server redirects back.
|
|
651
|
-
*
|
|
652
|
-
* @param tenantId Optional tenant ID. When provided, includes acr_values=tenant:{tenantId}
|
|
653
|
-
* so the identity server redirects to the correct tenant's login page. Without one
|
|
654
|
-
* (and without a defaultTenantId) identity resolves the tenant itself; a configured
|
|
655
|
-
* discoveryScopeTenantId then travels as acr_values=tenant_scope:{scope} and limits
|
|
656
|
-
* that resolution to the scope's subtree (AB#5311).
|
|
657
|
-
*/
|
|
658
|
-
login(tenantId) {
|
|
659
|
-
if (this._loginInProgress) {
|
|
660
|
-
console.debug('AuthorizeService::login skipped (already in progress)');
|
|
661
|
-
return;
|
|
662
|
-
}
|
|
663
|
-
this._loginInProgress = true;
|
|
664
|
-
const effectiveTenantId = tenantId ?? this.authorizeOptions?.defaultTenantId;
|
|
665
|
-
if (effectiveTenantId) {
|
|
666
|
-
this.oauthService.initImplicitFlow('', { acr_values: `tenant:${effectiveTenantId}` });
|
|
667
|
-
return;
|
|
668
|
-
}
|
|
669
|
-
const scopeTenantId = this.authorizeOptions?.discoveryScopeTenantId;
|
|
670
|
-
if (scopeTenantId) {
|
|
671
|
-
this.oauthService.initImplicitFlow('', { acr_values: `tenant_scope:${scopeTenantId}` });
|
|
672
|
-
}
|
|
673
|
-
else {
|
|
674
|
-
this.oauthService.initImplicitFlow();
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
/**
|
|
678
|
-
* Forces re-authentication for a different tenant by clearing the local
|
|
679
|
-
* OAuth session and reloading the page. On reload, the guard will see
|
|
680
|
-
* isAuthenticated=false and call login(tenantId) with the correct acr_values.
|
|
681
|
-
*
|
|
682
|
-
* This is used when the current token's tenant_id does not match the
|
|
683
|
-
* route's tenantId (e.g., navigating from octosystem to meshtest).
|
|
684
|
-
*/
|
|
685
|
-
/**
|
|
686
|
-
* Returns true if the switch was initiated, false if skipped (loop prevention).
|
|
687
|
-
*/
|
|
688
|
-
switchTenant(targetTenantId, targetUrl) {
|
|
689
|
-
console.debug(`AuthorizeService::switchTenant to "${targetTenantId}" at "${targetUrl}"`);
|
|
690
|
-
// Prevent infinite redirect loop: if we already attempted a switch to this
|
|
691
|
-
// exact tenant and ended up here again, the Identity Server did not issue
|
|
692
|
-
// a token for the target tenant. Do NOT attempt again.
|
|
693
|
-
try {
|
|
694
|
-
const previousAttempt = sessionStorage.getItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
695
|
-
if (previousAttempt && previousAttempt.toLowerCase() === targetTenantId.toLowerCase()) {
|
|
696
|
-
console.warn(`AuthorizeService::switchTenant — already attempted switch to "${targetTenantId}", skipping to prevent loop`);
|
|
697
|
-
return false;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
catch {
|
|
701
|
-
// sessionStorage may be unavailable
|
|
702
|
-
}
|
|
703
|
-
// Store target tenant so login() uses the correct acr_values after reload
|
|
704
|
-
try {
|
|
705
|
-
sessionStorage.setItem(AuthorizeService.TENANT_REAUTH_KEY, targetTenantId);
|
|
706
|
-
sessionStorage.setItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY, targetTenantId);
|
|
707
|
-
}
|
|
708
|
-
catch {
|
|
709
|
-
// sessionStorage may be unavailable
|
|
710
|
-
}
|
|
711
|
-
// Stop automatic refresh and session checks to prevent the OAuth library
|
|
712
|
-
// from firing additional authorize requests during the page reload window.
|
|
713
|
-
// This prevents race conditions where a session check or silent refresh
|
|
714
|
-
// could overwrite the nonce/PKCE verifier of the new tenant's auth flow.
|
|
715
|
-
this.oauthService.stopAutomaticRefresh();
|
|
716
|
-
// With per-tenant storage (TenantAwareOAuthStorage), we do NOT clear
|
|
717
|
-
// tokens from localStorage. Each tenant's tokens are stored under
|
|
718
|
-
// prefixed keys (e.g., "maco__access_token") and are isolated from
|
|
719
|
-
// each other. After page reload, the storage tenant will be set to
|
|
720
|
-
// the target tenant, and cached tokens (if valid) can be reused.
|
|
721
|
-
// Clear our signals
|
|
722
|
-
this._accessToken.set(null);
|
|
723
|
-
this._user.set(null);
|
|
724
|
-
this._isAuthenticated.set(false);
|
|
725
|
-
this._tokenTenantId.set(null);
|
|
726
|
-
// Full page navigation to the target URL — triggers fresh auth flow
|
|
727
|
-
this.navigateTo(targetUrl);
|
|
728
|
-
return true;
|
|
729
|
-
}
|
|
730
|
-
/**
|
|
731
|
-
* User-initiated retry from the tenant-mismatch screen (AB#6731): clears the loop-protection
|
|
732
|
-
* flag once and starts a fresh authorization-code flow for the target tenant. The retry is
|
|
733
|
-
* remembered, so a second mismatch is reported as "not a member" instead of offering another
|
|
734
|
-
* sign-in. Returns false (and does nothing) when this tenant was already retried.
|
|
735
|
-
*/
|
|
736
|
-
retryTenantSignIn(targetTenantId, targetUrl) {
|
|
737
|
-
if (this.isTenantSignInRetried(targetTenantId)) {
|
|
738
|
-
return false;
|
|
739
|
-
}
|
|
740
|
-
try {
|
|
741
|
-
sessionStorage.setItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY, targetTenantId);
|
|
742
|
-
sessionStorage.removeItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
743
|
-
}
|
|
744
|
-
catch {
|
|
745
|
-
// sessionStorage may be unavailable
|
|
746
|
-
}
|
|
747
|
-
return this.switchTenant(targetTenantId, targetUrl);
|
|
748
|
-
}
|
|
749
|
-
/** True when the user already retried the sign-in for this tenant from the mismatch screen. */
|
|
750
|
-
isTenantSignInRetried(targetTenantId) {
|
|
751
|
-
try {
|
|
752
|
-
const retried = sessionStorage.getItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY);
|
|
753
|
-
return !!retried && retried.toLowerCase() === targetTenantId.toLowerCase();
|
|
754
|
-
}
|
|
755
|
-
catch {
|
|
756
|
-
return false;
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* Switches to another tenant in place, without a redirect, by exchanging the current access
|
|
761
|
-
* token for one issued in the target tenant (RFC 8693).
|
|
762
|
-
*
|
|
763
|
-
* Preferred over {@link switchTenant}, which reloads the page and runs a full authorization
|
|
764
|
-
* code flow — a visible round trip through the identity server, and a fresh login mask whenever
|
|
765
|
-
* the tenant's session cookie has expired. The exchange re-resolves the user's roles in the
|
|
766
|
-
* target tenant server-side, so no privilege from the source tenant leaks across.
|
|
767
|
-
*
|
|
768
|
-
* @returns true when the switch completed and the session now belongs to the target tenant;
|
|
769
|
-
* false when it was not possible, in which case the caller should fall back to
|
|
770
|
-
* {@link switchTenant}. Never throws.
|
|
771
|
-
*/
|
|
772
|
-
async switchTenantByExchange(targetTenantId) {
|
|
773
|
-
const subjectToken = this.oauthService.getAccessToken();
|
|
774
|
-
const tokenEndpoint = this.oauthService.tokenEndpoint;
|
|
775
|
-
const clientId = this.lastAuthConfig?.clientId;
|
|
776
|
-
if (!subjectToken || !tokenEndpoint || !clientId) {
|
|
777
|
-
console.debug('AuthorizeService::switchTenantByExchange — no token or endpoint yet, falling back');
|
|
778
|
-
return false;
|
|
779
|
-
}
|
|
780
|
-
const currentTenantId = this._tokenTenantId();
|
|
781
|
-
if (currentTenantId && currentTenantId.toLowerCase() === targetTenantId.toLowerCase()) {
|
|
782
|
-
return true;
|
|
783
|
-
}
|
|
784
|
-
// The server-side gate would refuse anyway; skip the round trip and let the caller redirect,
|
|
785
|
-
// which at least gives the user a login mask to act on.
|
|
786
|
-
const allowedTenants = this._allowedTenants();
|
|
787
|
-
if (allowedTenants.length > 0 &&
|
|
788
|
-
!allowedTenants.some(t => t.toLowerCase() === targetTenantId.toLowerCase())) {
|
|
789
|
-
console.debug(`AuthorizeService::switchTenantByExchange — "${targetTenantId}" not in allowed_tenants, falling back`);
|
|
790
|
-
return false;
|
|
791
|
-
}
|
|
792
|
-
try {
|
|
793
|
-
const body = new URLSearchParams({
|
|
794
|
-
grant_type: AuthorizeService.TOKEN_EXCHANGE_GRANT,
|
|
795
|
-
client_id: clientId,
|
|
796
|
-
subject_token: subjectToken,
|
|
797
|
-
subject_token_type: AuthorizeService.ACCESS_TOKEN_TYPE,
|
|
798
|
-
acr_values: `tenant:${targetTenantId}`
|
|
799
|
-
});
|
|
800
|
-
const scope = this.lastAuthConfig?.scope;
|
|
801
|
-
if (scope) {
|
|
802
|
-
body.set('scope', scope);
|
|
803
|
-
}
|
|
804
|
-
// Deliberately fetch() rather than HttpClient: authorizeInterceptor rewrites token-endpoint
|
|
805
|
-
// requests to carry the STORAGE tenant's acr_values, which would override the target here.
|
|
806
|
-
const response = await fetch(tokenEndpoint, {
|
|
807
|
-
method: 'POST',
|
|
808
|
-
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
809
|
-
body: body.toString()
|
|
810
|
-
});
|
|
811
|
-
if (!response.ok) {
|
|
812
|
-
console.warn(`AuthorizeService::switchTenantByExchange — exchange to "${targetTenantId}" failed (HTTP ${response.status}), falling back`);
|
|
813
|
-
return false;
|
|
814
|
-
}
|
|
815
|
-
const tokens = await response.json();
|
|
816
|
-
if (!tokens.access_token) {
|
|
817
|
-
console.warn('AuthorizeService::switchTenantByExchange — exchange returned no access token, falling back');
|
|
818
|
-
return false;
|
|
819
|
-
}
|
|
820
|
-
// The exchange yields no id_token, so the profile comes from the userinfo endpoint.
|
|
821
|
-
const claims = await this.fetchUserInfoClaims(tokens.access_token);
|
|
822
|
-
if (!claims) {
|
|
823
|
-
console.warn('AuthorizeService::switchTenantByExchange — could not load the profile, falling back');
|
|
824
|
-
return false;
|
|
825
|
-
}
|
|
826
|
-
this.storeExchangedTokens(targetTenantId, tokens, claims);
|
|
827
|
-
this.applyExchangedSession(targetTenantId, tokens.access_token, claims);
|
|
828
|
-
console.debug(`AuthorizeService::switchTenantByExchange — now on "${this._tokenTenantId()}"`);
|
|
829
|
-
return true;
|
|
830
|
-
}
|
|
831
|
-
catch (error) {
|
|
832
|
-
console.warn('AuthorizeService::switchTenantByExchange — exchange threw, falling back', error);
|
|
833
|
-
return false;
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
/** Reads the profile of an exchanged token; it carries no id_token of its own. */
|
|
837
|
-
async fetchUserInfoClaims(accessToken) {
|
|
838
|
-
const userinfoEndpoint = this.oauthService.userinfoEndpoint;
|
|
839
|
-
if (!userinfoEndpoint) {
|
|
840
|
-
return null;
|
|
841
|
-
}
|
|
842
|
-
const response = await fetch(userinfoEndpoint, {
|
|
843
|
-
headers: { Authorization: `Bearer ${accessToken}` }
|
|
844
|
-
});
|
|
845
|
-
if (!response.ok) {
|
|
846
|
-
return null;
|
|
847
|
-
}
|
|
848
|
-
return await response.json();
|
|
849
|
-
}
|
|
850
|
-
/**
|
|
851
|
-
* Writes the exchanged tokens into the TARGET tenant's storage slots, so the OAuth library and
|
|
852
|
-
* a later reload both find a complete session there.
|
|
853
|
-
*/
|
|
854
|
-
storeExchangedTokens(targetTenantId, tokens, claims) {
|
|
855
|
-
this.tenantStorage.setTenantId(targetTenantId);
|
|
856
|
-
const storedAt = Date.now();
|
|
857
|
-
this.tenantStorage.setItem('access_token', tokens.access_token);
|
|
858
|
-
this.tenantStorage.setItem('access_token_stored_at', String(storedAt));
|
|
859
|
-
if (tokens.expires_in) {
|
|
860
|
-
this.tenantStorage.setItem('expires_at', String(storedAt + tokens.expires_in * 1000));
|
|
861
|
-
}
|
|
862
|
-
if (tokens.refresh_token) {
|
|
863
|
-
this.tenantStorage.setItem('refresh_token', tokens.refresh_token);
|
|
864
|
-
}
|
|
865
|
-
if (tokens.scope) {
|
|
866
|
-
this.tenantStorage.setItem('granted_scopes', JSON.stringify(tokens.scope.split(' ')));
|
|
867
|
-
}
|
|
868
|
-
// Stands in for the id_token claims the library would normally read here.
|
|
869
|
-
this.tenantStorage.setItem('id_token_claims_obj', JSON.stringify(claims));
|
|
870
|
-
}
|
|
871
|
-
/** Mirrors what loadUserAsync() publishes, for a session that arrived without an id_token. */
|
|
872
|
-
applyExchangedSession(targetTenantId, accessToken, claims) {
|
|
873
|
-
const user = claims;
|
|
874
|
-
if (user.given_name && user.family_name) {
|
|
875
|
-
this._userInitials.set(user.given_name.charAt(0).toUpperCase() + user.family_name.charAt(0).toUpperCase());
|
|
876
|
-
}
|
|
877
|
-
else {
|
|
878
|
-
const derived = this.deriveDisplayNameFromUsername(user.name ?? targetTenantId);
|
|
879
|
-
this._userInitials.set(this.deriveInitials(derived));
|
|
880
|
-
}
|
|
881
|
-
this._user.set(user);
|
|
882
|
-
this._accessToken.set(accessToken);
|
|
883
|
-
this._isAuthenticated.set(true);
|
|
884
|
-
this._sessionLoading.set(false);
|
|
885
|
-
this._allowedTenants.set(allowedTenantsFromToken(accessToken));
|
|
886
|
-
this._tokenTenantId.set(tenantIdFromToken(accessToken));
|
|
887
|
-
// No redirect happened, so nothing downstream should still believe a switch is in flight.
|
|
888
|
-
this.clearPendingTenantSwitch();
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* Returns the pending tenant switch target (if any) WITHOUT clearing it.
|
|
892
|
-
* The key persists across the OAuth redirect cycle (guard → IDS → callback → guard)
|
|
893
|
-
* and is only cleared after a successful token exchange in loadUserAsync().
|
|
894
|
-
*
|
|
895
|
-
* Previously this method removed the key immediately, but that caused a race condition:
|
|
896
|
-
* the guard consumed it before the IDS redirect, and after the callback redirect the
|
|
897
|
-
* key was gone — causing the guard to fall back to the route tenant (wrong tenant).
|
|
898
|
-
*/
|
|
899
|
-
consumePendingTenantSwitch() {
|
|
900
|
-
try {
|
|
901
|
-
return sessionStorage.getItem(AuthorizeService.TENANT_REAUTH_KEY);
|
|
902
|
-
}
|
|
903
|
-
catch {
|
|
904
|
-
return null;
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
/**
|
|
908
|
-
* Clears the pending tenant switch key. Called after a successful token exchange
|
|
909
|
-
* when the token's tenant_id matches the target, completing the switch cycle.
|
|
910
|
-
*/
|
|
911
|
-
clearPendingTenantSwitch() {
|
|
912
|
-
try {
|
|
913
|
-
sessionStorage.removeItem(AuthorizeService.TENANT_REAUTH_KEY);
|
|
914
|
-
}
|
|
915
|
-
catch {
|
|
916
|
-
// sessionStorage may be unavailable
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
/**
|
|
920
|
-
* Returns the tenant for which a switch was already attempted (if any) and clears it.
|
|
921
|
-
* Used by the guard to prevent infinite redirect loops: if the Identity Server
|
|
922
|
-
* issues a token for the wrong tenant even after a switch, we skip the second attempt.
|
|
923
|
-
*/
|
|
924
|
-
consumeSwitchAttempted() {
|
|
925
|
-
try {
|
|
926
|
-
const tenantId = sessionStorage.getItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
927
|
-
sessionStorage.removeItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
928
|
-
// A consistent token/route tenant ends the whole switch cycle, including an explicit retry.
|
|
929
|
-
sessionStorage.removeItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY);
|
|
930
|
-
return tenantId;
|
|
931
|
-
}
|
|
932
|
-
catch {
|
|
933
|
-
return null;
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Logs out the current user by redirecting to the Identity Server's
|
|
938
|
-
* OIDC end_session_endpoint for proper Single Logout (SLO).
|
|
939
|
-
*
|
|
940
|
-
* We cannot rely on oauthService.logOut() for the redirect because it calls
|
|
941
|
-
* clearStorage() which may clear internal state before the redirect happens.
|
|
942
|
-
* Instead, we capture the logoutUrl and id_token first, then clear state,
|
|
943
|
-
* then manually redirect to the end_session_endpoint.
|
|
944
|
-
*/
|
|
945
|
-
logout() {
|
|
946
|
-
// Capture the current tenant BEFORE clearing storage so the host app
|
|
947
|
-
// can return the user to the same tenant after the IdS end_session
|
|
948
|
-
// round-trip. The post_logout_redirect_uri registered with the IdS is
|
|
949
|
-
// typically `${origin}/` and therefore drops the tenant path segment,
|
|
950
|
-
// so without this hint the next login would fall through to whatever
|
|
951
|
-
// default-tenant redirect the host application has wired up.
|
|
952
|
-
const currentTenant = this.tenantStorage.getTenantId();
|
|
953
|
-
if (currentTenant) {
|
|
954
|
-
try {
|
|
955
|
-
sessionStorage.setItem('octo_post_logout_tenant', currentTenant);
|
|
956
|
-
}
|
|
957
|
-
catch {
|
|
958
|
-
// sessionStorage may be unavailable
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
// Read the end_session_endpoint (stored as logoutUrl on the service) and id_token BEFORE clearing storage
|
|
962
|
-
const endSessionEndpoint = this.oauthService.logoutUrl;
|
|
963
|
-
const idToken = this.oauthService.getIdToken();
|
|
964
|
-
const postLogoutRedirectUri = this.lastAuthConfig?.postLogoutRedirectUri;
|
|
965
|
-
// Clear local OAuth state (tokens, discovery doc, etc.)
|
|
966
|
-
this.oauthService.logOut(true); // true = noRedirectToLogoutUrl (we redirect manually)
|
|
967
|
-
// Clear OAuth tokens for ALL tenants, not just the current one.
|
|
968
|
-
// With per-tenant storage, oauthService.logOut() only clears the current
|
|
969
|
-
// tenant's prefixed keys. We need to ensure no stale tokens remain for
|
|
970
|
-
// any tenant after a full logout.
|
|
971
|
-
this.tenantStorage.clearAllTenants();
|
|
972
|
-
if (endSessionEndpoint) {
|
|
973
|
-
// Build the end_session URL with id_token_hint and post_logout_redirect_uri
|
|
974
|
-
const params = new URLSearchParams();
|
|
975
|
-
if (idToken) {
|
|
976
|
-
params.set('id_token_hint', idToken);
|
|
977
|
-
}
|
|
978
|
-
if (postLogoutRedirectUri) {
|
|
979
|
-
params.set('post_logout_redirect_uri', postLogoutRedirectUri);
|
|
980
|
-
}
|
|
981
|
-
this.navigateTo(`${endSessionEndpoint}?${params.toString()}`);
|
|
982
|
-
}
|
|
983
|
-
else {
|
|
984
|
-
// Fallback: no end_session_endpoint available, just reload
|
|
985
|
-
this.reloadPage();
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
/**
|
|
989
|
-
* Updates the redirect URIs without performing a full re-initialization.
|
|
990
|
-
* Use this when the OAuth session is already established and only the
|
|
991
|
-
* redirect targets need to change (e.g., when switching tenants).
|
|
992
|
-
*/
|
|
993
|
-
updateRedirectUris(redirectUri, postLogoutRedirectUri) {
|
|
994
|
-
if (this.authorizeOptions) {
|
|
995
|
-
this.authorizeOptions.redirectUri = redirectUri;
|
|
996
|
-
this.authorizeOptions.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
997
|
-
}
|
|
998
|
-
if (this.lastAuthConfig) {
|
|
999
|
-
this.lastAuthConfig.redirectUri = redirectUri;
|
|
1000
|
-
this.lastAuthConfig.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
1001
|
-
}
|
|
1002
|
-
// Update the redirect URIs directly on the OAuthService without calling
|
|
1003
|
-
// configure(), because configure() does Object.assign(this, new AuthConfig(), config)
|
|
1004
|
-
// which resets ALL properties — including logoutUrl, tokenEndpoint, and other
|
|
1005
|
-
// discovery document endpoints — back to their AuthConfig defaults (empty).
|
|
1006
|
-
this.oauthService.redirectUri = redirectUri;
|
|
1007
|
-
this.oauthService.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
1008
|
-
console.debug('AuthorizeService::updateRedirectUris::done');
|
|
1009
|
-
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Refreshes the access token and updates the allowed tenants signal.
|
|
1012
|
-
* Call this after actions that change the user's tenant access (e.g., provisioning).
|
|
1013
|
-
*/
|
|
1014
|
-
async refreshAccessToken() {
|
|
1015
|
-
console.debug('AuthorizeService::refreshAccessToken::started');
|
|
1016
|
-
await this.oauthService.refreshToken();
|
|
1017
|
-
await this.loadUserAsync();
|
|
1018
|
-
console.debug('AuthorizeService::refreshAccessToken::done');
|
|
1019
|
-
}
|
|
1020
|
-
/**
|
|
1021
|
-
* Initializes the authorization service with the specified options.
|
|
1022
|
-
*/
|
|
1023
|
-
async initialize(authorizeOptions) {
|
|
1024
|
-
console.debug('AuthorizeService::initialize::started');
|
|
1025
|
-
await this.uninitialize();
|
|
1026
|
-
if (this._isInitializing()) {
|
|
1027
|
-
return;
|
|
1028
|
-
}
|
|
1029
|
-
if (this._isInitialized()) {
|
|
1030
|
-
console.debug('AuthorizeService::initialize::alreadyInitialized');
|
|
1031
|
-
return;
|
|
1032
|
-
}
|
|
1033
|
-
this._isInitializing.set(true);
|
|
1034
|
-
try {
|
|
1035
|
-
const config = {
|
|
1036
|
-
responseType: 'code',
|
|
1037
|
-
issuer: authorizeOptions.issuer,
|
|
1038
|
-
redirectUri: authorizeOptions.redirectUri,
|
|
1039
|
-
postLogoutRedirectUri: authorizeOptions.postLogoutRedirectUri,
|
|
1040
|
-
clientId: authorizeOptions.clientId,
|
|
1041
|
-
scope: authorizeOptions.scope,
|
|
1042
|
-
showDebugInformation: authorizeOptions.showDebugInformation,
|
|
1043
|
-
sessionChecksEnabled: authorizeOptions.sessionChecksEnabled,
|
|
1044
|
-
sessionCheckIntervall: 60 * 1000,
|
|
1045
|
-
preserveRequestedRoute: true
|
|
1046
|
-
};
|
|
1047
|
-
this.authorizeOptions = authorizeOptions;
|
|
1048
|
-
this.lastAuthConfig = config;
|
|
1049
|
-
this.oauthService.setStorage(this.tenantStorage);
|
|
1050
|
-
this.oauthService.configure(config);
|
|
1051
|
-
console.debug('AuthorizeService::initialize::loadingDiscoveryDocumentAndTryLogin');
|
|
1052
|
-
await this.loadDiscoveryDocumentAndTryLoginWithRetry(authorizeOptions.discoveryDocumentRetry ?? AuthorizeService.DEFAULT_DISCOVERY_RETRY);
|
|
1053
|
-
console.debug('AuthorizeService::initialize::setupAutomaticSilentRefresh');
|
|
1054
|
-
this.oauthService.setupAutomaticSilentRefresh();
|
|
1055
|
-
this._issuer.set(authorizeOptions.issuer ?? null);
|
|
1056
|
-
if (this.oauthService.hasValidIdToken()) {
|
|
1057
|
-
// if the idToken is still valid, we can use the session
|
|
1058
|
-
console.debug('AuthorizeService::initialize::hasValidIdToken');
|
|
1059
|
-
this._sessionLoading.set(true);
|
|
1060
|
-
await this.oauthService.refreshToken();
|
|
1061
|
-
}
|
|
1062
|
-
this._isInitialized.set(true);
|
|
1063
|
-
console.debug('AuthorizeService::initialize::done');
|
|
1064
|
-
}
|
|
1065
|
-
finally {
|
|
1066
|
-
this._isInitializing.set(false);
|
|
1067
|
-
}
|
|
1068
|
-
console.debug('AuthorizeService::initialize::completed');
|
|
1069
|
-
}
|
|
1070
|
-
/**
|
|
1071
|
-
* Wraps oauthService.loadDiscoveryDocumentAndTryLogin() with bounded
|
|
1072
|
-
* exponential-backoff retries so a brief outage of the Identity service
|
|
1073
|
-
* (cold start after redeploy, rolling restart, transient ingress 5xx)
|
|
1074
|
-
* does not leave the SPA stuck on the loading icon.
|
|
1075
|
-
*
|
|
1076
|
-
* The CORS-error symptom seen on test-2 — "No 'Access-Control-Allow-Origin'
|
|
1077
|
-
* header" against /.well-known/openid-configuration — is exactly such a
|
|
1078
|
-
* transient failure: the ingress synthesises a default error page that
|
|
1079
|
-
* does not carry the CORS headers, so the browser reports a CORS violation
|
|
1080
|
-
* rather than the actual HTTP status. Retrying after the backend comes
|
|
1081
|
-
* back resolves it without user interaction.
|
|
1082
|
-
*
|
|
1083
|
-
* Throws the last error if every attempt fails. The error is also stored
|
|
1084
|
-
* in the discoveryDocumentError signal so callers can render a recovery UI.
|
|
1085
|
-
*/
|
|
1086
|
-
async loadDiscoveryDocumentAndTryLoginWithRetry(retry) {
|
|
1087
|
-
const attempts = Math.max(1, retry.attempts);
|
|
1088
|
-
const initialDelayMs = Math.max(0, retry.initialDelayMs);
|
|
1089
|
-
const maxDelayMs = Math.max(initialDelayMs, retry.maxDelayMs);
|
|
1090
|
-
let lastError = null;
|
|
1091
|
-
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
1092
|
-
this._discoveryDocumentRetryAttempt.set(attempt);
|
|
1093
|
-
try {
|
|
1094
|
-
await this.oauthService.loadDiscoveryDocumentAndTryLogin();
|
|
1095
|
-
this._discoveryDocumentError.set(null);
|
|
1096
|
-
this._discoveryDocumentRetryAttempt.set(0);
|
|
1097
|
-
if (attempt > 1) {
|
|
1098
|
-
console.info(`AuthorizeService: discovery document loaded on retry attempt ${attempt}/${attempts}`);
|
|
1099
|
-
}
|
|
1100
|
-
return;
|
|
1101
|
-
}
|
|
1102
|
-
catch (err) {
|
|
1103
|
-
lastError = err;
|
|
1104
|
-
if (attempt === attempts) {
|
|
1105
|
-
break;
|
|
1106
|
-
}
|
|
1107
|
-
const delayMs = Math.min(initialDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
|
|
1108
|
-
console.warn(`AuthorizeService: discovery document load failed (attempt ${attempt}/${attempts}); retrying in ${delayMs}ms`, err);
|
|
1109
|
-
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
const error = lastError instanceof Error
|
|
1113
|
-
? lastError
|
|
1114
|
-
: new Error('Failed to load OIDC discovery document');
|
|
1115
|
-
this._discoveryDocumentError.set(error);
|
|
1116
|
-
this._discoveryDocumentRetryAttempt.set(0);
|
|
1117
|
-
console.error(`AuthorizeService: discovery document load failed after ${attempts} attempt(s)`, error);
|
|
1118
|
-
throw error;
|
|
1119
|
-
}
|
|
1120
|
-
/**
|
|
1121
|
-
* Uninitializes the authorization service.
|
|
1122
|
-
*/
|
|
1123
|
-
async uninitialize() {
|
|
1124
|
-
console.debug('AuthorizeService::uninitialize::started');
|
|
1125
|
-
if (this._isInitializing()) {
|
|
1126
|
-
return;
|
|
1127
|
-
}
|
|
1128
|
-
if (!this._isInitialized()) {
|
|
1129
|
-
console.debug('AuthorizeService::uninitialize::alreadyUninitialized');
|
|
1130
|
-
return;
|
|
1131
|
-
}
|
|
1132
|
-
try {
|
|
1133
|
-
this._isInitializing.set(true);
|
|
1134
|
-
this.oauthService.stopAutomaticRefresh();
|
|
1135
|
-
this.authorizeOptions = null;
|
|
1136
|
-
this.lastAuthConfig = null;
|
|
1137
|
-
// Note: Do NOT clear auth signals (_accessToken, _isAuthenticated, etc.) here.
|
|
1138
|
-
// The access token and user info are globally valid (not per-tenant) and remain
|
|
1139
|
-
// valid during re-initialization. Clearing them creates a window where the HTTP
|
|
1140
|
-
// interceptor sends requests without a Bearer token, causing 401 errors.
|
|
1141
|
-
// Signals are already properly cleared on logout/session_terminated events.
|
|
1142
|
-
this._isInitialized.set(false);
|
|
1143
|
-
console.debug('AuthorizeService::uninitialize::done');
|
|
1144
|
-
}
|
|
1145
|
-
finally {
|
|
1146
|
-
this._isInitializing.set(false);
|
|
1147
|
-
}
|
|
1148
|
-
console.debug('AuthorizeService::uninitialize::completed');
|
|
1149
|
-
}
|
|
1150
|
-
/**
|
|
1151
|
-
* Drives the optional {@link SessionIdentitySink} from one place (AB#7327): the identity is derived from
|
|
1152
|
-
* `_user` + `_tokenTenantId`, so every path that sets them (login, token refresh, in-place tenant switch,
|
|
1153
|
-
* redirect fallback) and every path that clears them (logout, session_terminated, token_refresh_error,
|
|
1154
|
-
* cross-tab logout, reset before a redirect switch) is covered without touching each one. Nothing is
|
|
1155
|
-
* registered when the app provides no sink. A sink that throws never affects authentication.
|
|
1156
|
-
*/
|
|
1157
|
-
setUpSessionIdentity(sink) {
|
|
1158
|
-
if (!sink) {
|
|
1159
|
-
return;
|
|
1160
|
-
}
|
|
1161
|
-
const identity = computed(() => {
|
|
1162
|
-
const user = this._user();
|
|
1163
|
-
if (!user?.sub) {
|
|
1164
|
-
return null;
|
|
1165
|
-
}
|
|
1166
|
-
return {
|
|
1167
|
-
userId: user.sub,
|
|
1168
|
-
name: user.name || null,
|
|
1169
|
-
email: user.email || null,
|
|
1170
|
-
tenantId: this._tokenTenantId()
|
|
1171
|
-
};
|
|
1172
|
-
}, { ...(ngDevMode ? { debugName: "identity" } : /* istanbul ignore next */ {}), equal: sameSessionIdentity });
|
|
1173
|
-
let published = false;
|
|
1174
|
-
effect(() => {
|
|
1175
|
-
const current = identity();
|
|
1176
|
-
if (current === null && !published) {
|
|
1177
|
-
return; // anonymous start: nothing was published, nothing to clear
|
|
1178
|
-
}
|
|
1179
|
-
published = current !== null;
|
|
1180
|
-
try {
|
|
1181
|
-
if (current === null) {
|
|
1182
|
-
sink.clear();
|
|
1183
|
-
}
|
|
1184
|
-
else {
|
|
1185
|
-
sink.set(current);
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
catch (error) {
|
|
1189
|
-
// Fixed text + error type only: the message or the identity may carry name or e-mail.
|
|
1190
|
-
console.warn(`AuthorizeService: session identity sink failed on ${current === null ? 'clear' : 'set'} (${error instanceof Error ? error.name : typeof error}) — ignored`);
|
|
1191
|
-
}
|
|
1192
|
-
});
|
|
1193
|
-
}
|
|
1194
|
-
async loadUserAsync() {
|
|
1195
|
-
const claims = this.oauthService.getIdentityClaims();
|
|
1196
|
-
if (!claims) {
|
|
1197
|
-
console.error('claims were null when loading identity claims');
|
|
1198
|
-
return;
|
|
1199
|
-
}
|
|
1200
|
-
// Capture auth state BEFORE setting _isAuthenticated to true,
|
|
1201
|
-
// so we can distinguish initial login from token refresh below.
|
|
1202
|
-
const previouslyAuthenticated = this._isAuthenticated();
|
|
1203
|
-
const user = claims;
|
|
1204
|
-
if (user.given_name && user.family_name) {
|
|
1205
|
-
this._userInitials.set(user.given_name.charAt(0).toUpperCase() + user.family_name.charAt(0).toUpperCase());
|
|
1206
|
-
}
|
|
1207
|
-
else {
|
|
1208
|
-
const derived = this.deriveDisplayNameFromUsername(user.name);
|
|
1209
|
-
this._userInitials.set(this.deriveInitials(derived));
|
|
1210
|
-
}
|
|
1211
|
-
const accessToken = this.oauthService.getAccessToken();
|
|
1212
|
-
this._user.set(user);
|
|
1213
|
-
this._accessToken.set(accessToken);
|
|
1214
|
-
this._isAuthenticated.set(true);
|
|
1215
|
-
this._sessionLoading.set(false);
|
|
1216
|
-
// Parse allowed_tenants from the access token
|
|
1217
|
-
this._allowedTenants.set(allowedTenantsFromToken(accessToken));
|
|
1218
|
-
const tokenTenantId = tenantIdFromToken(accessToken);
|
|
1219
|
-
this._tokenTenantId.set(tokenTenantId);
|
|
1220
|
-
// Detect tenant mismatch after silent refresh: if we were already authenticated
|
|
1221
|
-
// (i.e., this is a token refresh, not an initial login) and the new token's tenant_id
|
|
1222
|
-
// doesn't match the expected tenant from storage, trigger re-authentication.
|
|
1223
|
-
// This handles the case where the Identity Server returns a token for the wrong tenant
|
|
1224
|
-
// (e.g., after a service restart when the in-memory token-to-tenant cache is lost).
|
|
1225
|
-
const expectedTenantId = this.tenantStorage.getTenantId();
|
|
1226
|
-
if (previouslyAuthenticated && tokenTenantId && expectedTenantId &&
|
|
1227
|
-
tokenTenantId.toLowerCase() !== expectedTenantId.toLowerCase()) {
|
|
1228
|
-
console.warn(`AuthorizeService::loadUserAsync: Tenant mismatch after silent refresh — ` +
|
|
1229
|
-
`token="${tokenTenantId}", expected="${expectedTenantId}". Triggering re-authentication.`);
|
|
1230
|
-
this.switchTenant(expectedTenantId, window.location.href);
|
|
1231
|
-
return;
|
|
1232
|
-
}
|
|
1233
|
-
// Clear the pending tenant switch key now that we have a valid token.
|
|
1234
|
-
// This completes the switch cycle and prevents the guard from re-using
|
|
1235
|
-
// the pending tenant on subsequent route activations.
|
|
1236
|
-
this.clearPendingTenantSwitch();
|
|
1237
|
-
console.debug(`AuthorizeService::loadUserAsync::done (tokenTenantId="${tokenTenantId}", allowedTenants=${JSON.stringify(this._allowedTenants())})`);
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Decodes the JWT access token payload and extracts allowed_tenants claims.
|
|
1241
|
-
* The claim can be a single string or an array of strings.
|
|
1242
|
-
*/
|
|
1243
|
-
deriveDisplayNameFromUsername(username) {
|
|
1244
|
-
let name = username;
|
|
1245
|
-
// Strip xt_{tenantId}_ prefix
|
|
1246
|
-
const xtMatch = name.match(/^xt_[^_]+_(.+)$/);
|
|
1247
|
-
if (xtMatch) {
|
|
1248
|
-
name = xtMatch[1];
|
|
1249
|
-
}
|
|
1250
|
-
// Extract local part of email
|
|
1251
|
-
const atIndex = name.indexOf('@');
|
|
1252
|
-
if (atIndex > 0) {
|
|
1253
|
-
name = name.substring(0, atIndex);
|
|
1254
|
-
}
|
|
1255
|
-
// Split by dots and capitalize
|
|
1256
|
-
const parts = name.split('.').filter(p => p.length > 0);
|
|
1257
|
-
return parts.map(p => p.charAt(0).toUpperCase() + p.slice(1)).join(' ');
|
|
1258
|
-
}
|
|
1259
|
-
deriveInitials(displayName) {
|
|
1260
|
-
const words = displayName.split(' ').filter(w => w.length > 0);
|
|
1261
|
-
if (words.length >= 2) {
|
|
1262
|
-
return words[0].charAt(0).toUpperCase() + words[1].charAt(0).toUpperCase();
|
|
1263
|
-
}
|
|
1264
|
-
if (words.length === 1 && words[0].length >= 2) {
|
|
1265
|
-
return words[0].charAt(0).toUpperCase() + words[0].charAt(1).toLowerCase();
|
|
1266
|
-
}
|
|
1267
|
-
return '??';
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Reloads the page. This method is protected to allow mocking in tests.
|
|
1271
|
-
* @internal
|
|
1272
|
-
*/
|
|
1273
|
-
reloadPage() {
|
|
1274
|
-
window.location.reload();
|
|
1275
|
-
}
|
|
1276
|
-
/**
|
|
1277
|
-
* Navigates to the given URL via full page navigation.
|
|
1278
|
-
* This method is protected to allow mocking in tests.
|
|
1279
|
-
* @internal
|
|
1280
|
-
*/
|
|
1281
|
-
navigateTo(url) {
|
|
1282
|
-
window.location.href = url;
|
|
1283
|
-
}
|
|
1284
|
-
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: AuthorizeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1285
|
-
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: AuthorizeService });
|
|
131
|
+
if (a === b) return true;
|
|
132
|
+
if (a === null || b === null) return false;
|
|
133
|
+
return a.userId === b.userId && a.name === b.name && a.email === b.email && a.tenantId === b.tenantId;
|
|
1286
134
|
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
135
|
+
var AuthorizeOptions = class {
|
|
136
|
+
wellKnownServiceUris;
|
|
137
|
+
issuer;
|
|
138
|
+
redirectUri;
|
|
139
|
+
postLogoutRedirectUri;
|
|
140
|
+
clientId;
|
|
141
|
+
scope;
|
|
142
|
+
showDebugInformation;
|
|
143
|
+
sessionChecksEnabled;
|
|
144
|
+
defaultTenantId;
|
|
145
|
+
discoveryScopeTenantId;
|
|
146
|
+
discoveryDocumentRetry;
|
|
147
|
+
};
|
|
148
|
+
var AuthorizeService = class AuthorizeService {
|
|
149
|
+
oauthService = inject(OAuthService);
|
|
150
|
+
_isAuthenticated = signal(false, ...ngDevMode ? [{ debugName: "_isAuthenticated" }] : /* istanbul ignore next */ []);
|
|
151
|
+
_issuer = signal(null, ...ngDevMode ? [{ debugName: "_issuer" }] : /* istanbul ignore next */ []);
|
|
152
|
+
_accessToken = signal(null, ...ngDevMode ? [{ debugName: "_accessToken" }] : /* istanbul ignore next */ []);
|
|
153
|
+
_user = signal(null, ...ngDevMode ? [{ debugName: "_user" }] : /* istanbul ignore next */ []);
|
|
154
|
+
_userInitials = signal(null, ...ngDevMode ? [{ debugName: "_userInitials" }] : /* istanbul ignore next */ []);
|
|
155
|
+
_isInitialized = signal(false, ...ngDevMode ? [{ debugName: "_isInitialized" }] : /* istanbul ignore next */ []);
|
|
156
|
+
_isInitializing = signal(false, ...ngDevMode ? [{ debugName: "_isInitializing" }] : /* istanbul ignore next */ []);
|
|
157
|
+
_sessionLoading = signal(false, ...ngDevMode ? [{ debugName: "_sessionLoading" }] : /* istanbul ignore next */ []);
|
|
158
|
+
_allowedTenants = signal([], ...ngDevMode ? [{ debugName: "_allowedTenants" }] : /* istanbul ignore next */ []);
|
|
159
|
+
_tokenTenantId = signal(null, ...ngDevMode ? [{ debugName: "_tokenTenantId" }] : /* istanbul ignore next */ []);
|
|
160
|
+
_discoveryDocumentError = signal(null, ...ngDevMode ? [{ debugName: "_discoveryDocumentError" }] : /* istanbul ignore next */ []);
|
|
161
|
+
_discoveryDocumentRetryAttempt = signal(0, ...ngDevMode ? [{ debugName: "_discoveryDocumentRetryAttempt" }] : /* istanbul ignore next */ []);
|
|
162
|
+
static TENANT_REAUTH_KEY = "octo_tenant_reauth";
|
|
163
|
+
static TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
164
|
+
static ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
|
|
165
|
+
static TENANT_SWITCH_ATTEMPTED_KEY = "octo_tenant_switch_attempted";
|
|
166
|
+
static TENANT_SIGNIN_RETRIED_KEY = "octo_tenant_signin_retried";
|
|
167
|
+
static DEFAULT_DISCOVERY_RETRY = {
|
|
168
|
+
attempts: 6,
|
|
169
|
+
initialDelayMs: 1500,
|
|
170
|
+
maxDelayMs: 3e4
|
|
171
|
+
};
|
|
172
|
+
tenantStorage = new TenantAwareOAuthStorage();
|
|
173
|
+
_loginInProgress = false;
|
|
174
|
+
authorizeOptions = null;
|
|
175
|
+
lastAuthConfig = null;
|
|
176
|
+
isAuthenticated = this._isAuthenticated.asReadonly();
|
|
177
|
+
issuer = this._issuer.asReadonly();
|
|
178
|
+
accessToken = this._accessToken.asReadonly();
|
|
179
|
+
user = this._user.asReadonly();
|
|
180
|
+
userInitials = this._userInitials.asReadonly();
|
|
181
|
+
sessionLoading = this._sessionLoading.asReadonly();
|
|
182
|
+
allowedTenants = this._allowedTenants.asReadonly();
|
|
183
|
+
tokenTenantId = this._tokenTenantId.asReadonly();
|
|
184
|
+
roles = computed(() => this._user()?.role ?? [], ...ngDevMode ? [{ debugName: "roles" }] : /* istanbul ignore next */ []);
|
|
185
|
+
discoveryDocumentError = this._discoveryDocumentError.asReadonly();
|
|
186
|
+
discoveryDocumentRetryAttempt = this._discoveryDocumentRetryAttempt.asReadonly();
|
|
187
|
+
displayName = computed(() => {
|
|
188
|
+
const user = this._user();
|
|
189
|
+
if (!user) return null;
|
|
190
|
+
if (user.given_name && user.family_name) return user.given_name + " " + user.family_name;
|
|
191
|
+
return this.deriveDisplayNameFromUsername(user.name);
|
|
192
|
+
}, ...ngDevMode ? [{ debugName: "displayName" }] : /* istanbul ignore next */ []);
|
|
193
|
+
constructor() {
|
|
194
|
+
console.debug("AuthorizeService::created");
|
|
195
|
+
this.setUpSessionIdentity(inject(SESSION_IDENTITY_SINK, { optional: true }));
|
|
196
|
+
this.oauthService.discoveryDocumentLoaded$.subscribe((_) => {
|
|
197
|
+
console.debug("discoveryDocumentLoaded$");
|
|
198
|
+
});
|
|
199
|
+
this.oauthService.events.subscribe((e) => {
|
|
200
|
+
console.debug("oauth/oidc event", e);
|
|
201
|
+
});
|
|
202
|
+
this.oauthService.events.pipe((source) => source).subscribe((e) => {
|
|
203
|
+
if (e.type === "session_terminated") {
|
|
204
|
+
console.debug("Your session has been terminated!");
|
|
205
|
+
this._accessToken.set(null);
|
|
206
|
+
this._user.set(null);
|
|
207
|
+
this._isAuthenticated.set(false);
|
|
208
|
+
this._tokenTenantId.set(null);
|
|
209
|
+
this.reloadPage();
|
|
210
|
+
}
|
|
211
|
+
if (e.type === "token_refresh_error") {
|
|
212
|
+
console.warn("AuthorizeService: Token refresh failed — clearing local session and reloading");
|
|
213
|
+
this._accessToken.set(null);
|
|
214
|
+
this._user.set(null);
|
|
215
|
+
this._isAuthenticated.set(false);
|
|
216
|
+
this._tokenTenantId.set(null);
|
|
217
|
+
this._allowedTenants.set([]);
|
|
218
|
+
this.tenantStorage.clearAllTenants();
|
|
219
|
+
this.reloadPage();
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
this.oauthService.events.subscribe(async (e) => {
|
|
223
|
+
if (e.type === "token_received") {
|
|
224
|
+
this._loginInProgress = false;
|
|
225
|
+
await this.loadUserAsync();
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
this.oauthService.events.subscribe(async (e) => {
|
|
229
|
+
if (e.type === "session_unchanged") {
|
|
230
|
+
if (this._user() == null) await this.loadUserAsync();
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
this.oauthService.events.subscribe((e) => {
|
|
234
|
+
if (e.type === "logout") {
|
|
235
|
+
console.debug("AuthorizeService: Logout event received");
|
|
236
|
+
this._accessToken.set(null);
|
|
237
|
+
this._user.set(null);
|
|
238
|
+
this._isAuthenticated.set(false);
|
|
239
|
+
this._tokenTenantId.set(null);
|
|
240
|
+
this._allowedTenants.set([]);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
window.addEventListener("storage", (event) => {
|
|
244
|
+
console.debug("AuthorizeService: Storage event received", event.key, event.newValue);
|
|
245
|
+
const expectedKey = this.tenantStorage.prefixKey("access_token");
|
|
246
|
+
if (event.key === expectedKey && (event.newValue === null || event.newValue === "") && this._isAuthenticated()) {
|
|
247
|
+
console.debug("AuthorizeService: Access token removed in another tab - logging out and reloading");
|
|
248
|
+
this._accessToken.set(null);
|
|
249
|
+
this._user.set(null);
|
|
250
|
+
this._isAuthenticated.set(false);
|
|
251
|
+
this._tokenTenantId.set(null);
|
|
252
|
+
this.reloadPage();
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
if (typeof BroadcastChannel !== "undefined") {
|
|
256
|
+
console.debug("AuthorizeService: Setting up BroadcastChannel listener for 'octo-auth-logout'");
|
|
257
|
+
const logoutChannel = new BroadcastChannel("octo-auth-logout");
|
|
258
|
+
logoutChannel.onmessage = (event) => {
|
|
259
|
+
console.debug("AuthorizeService: BroadcastChannel message received", event.data);
|
|
260
|
+
if (event.data?.type === "logout" && this._isAuthenticated()) {
|
|
261
|
+
console.debug("AuthorizeService: Logout broadcast received - reloading");
|
|
262
|
+
this._accessToken.set(null);
|
|
263
|
+
this._user.set(null);
|
|
264
|
+
this._isAuthenticated.set(false);
|
|
265
|
+
this._tokenTenantId.set(null);
|
|
266
|
+
this.reloadPage();
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
} else console.warn("AuthorizeService: BroadcastChannel not supported in this browser");
|
|
270
|
+
if (typeof document !== "undefined") document.addEventListener("visibilitychange", () => {
|
|
271
|
+
if (document.visibilityState !== "visible") return;
|
|
272
|
+
if (this._discoveryDocumentError() && !this._isInitializing() && this.authorizeOptions) {
|
|
273
|
+
console.debug("AuthorizeService: visibilitychange → retrying after discovery-document failure");
|
|
274
|
+
this.initialize(this.authorizeOptions).catch(() => void 0);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
async retryDiscoveryDocument() {
|
|
279
|
+
if (this._isInitializing() || !this.authorizeOptions) return;
|
|
280
|
+
await this.initialize(this.authorizeOptions);
|
|
281
|
+
}
|
|
282
|
+
isInRole(role) {
|
|
283
|
+
return this._user()?.role?.includes(role) ?? false;
|
|
284
|
+
}
|
|
285
|
+
getServiceUris() {
|
|
286
|
+
return this.authorizeOptions?.wellKnownServiceUris ?? null;
|
|
287
|
+
}
|
|
288
|
+
setStorageTenantId(tenantId) {
|
|
289
|
+
if (tenantId && this.tenantStorage.adoptUnprefixedSession(tenantId)) console.debug(`AuthorizeService::setStorageTenantId — adopted the unprefixed session for "${tenantId}"`);
|
|
290
|
+
this.tenantStorage.setTenantId(tenantId);
|
|
291
|
+
console.debug(`AuthorizeService::setStorageTenantId("${tenantId}")`);
|
|
292
|
+
}
|
|
293
|
+
getStorageTenantId() {
|
|
294
|
+
return this.tenantStorage.getTenantId();
|
|
295
|
+
}
|
|
296
|
+
restoreStorageTenantId() {
|
|
297
|
+
const tenantId = this.tenantStorage.restoreTenantId();
|
|
298
|
+
if (tenantId) console.debug(`AuthorizeService::restoreStorageTenantId("${tenantId}")`);
|
|
299
|
+
return tenantId;
|
|
300
|
+
}
|
|
301
|
+
getAccessTokenSync() {
|
|
302
|
+
return this._accessToken();
|
|
303
|
+
}
|
|
304
|
+
isTenantAllowed(tenantId) {
|
|
305
|
+
const allowed = this._allowedTenants();
|
|
306
|
+
if (allowed.length === 0) return true;
|
|
307
|
+
return allowed.some((t) => t.toLowerCase() === tenantId.toLowerCase());
|
|
308
|
+
}
|
|
309
|
+
login(tenantId) {
|
|
310
|
+
if (this._loginInProgress) {
|
|
311
|
+
console.debug("AuthorizeService::login skipped (already in progress)");
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
this._loginInProgress = true;
|
|
315
|
+
const effectiveTenantId = tenantId ?? this.authorizeOptions?.defaultTenantId;
|
|
316
|
+
if (effectiveTenantId) {
|
|
317
|
+
this.oauthService.initImplicitFlow("", { acr_values: `tenant:${effectiveTenantId}` });
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const scopeTenantId = this.authorizeOptions?.discoveryScopeTenantId;
|
|
321
|
+
if (scopeTenantId) this.oauthService.initImplicitFlow("", { acr_values: `tenant_scope:${scopeTenantId}` });
|
|
322
|
+
else this.oauthService.initImplicitFlow();
|
|
323
|
+
}
|
|
324
|
+
switchTenant(targetTenantId, targetUrl) {
|
|
325
|
+
console.debug(`AuthorizeService::switchTenant to "${targetTenantId}" at "${targetUrl}"`);
|
|
326
|
+
try {
|
|
327
|
+
const previousAttempt = sessionStorage.getItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
328
|
+
if (previousAttempt && previousAttempt.toLowerCase() === targetTenantId.toLowerCase()) {
|
|
329
|
+
console.warn(`AuthorizeService::switchTenant — already attempted switch to "${targetTenantId}", skipping to prevent loop`);
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
} catch {}
|
|
333
|
+
try {
|
|
334
|
+
sessionStorage.setItem(AuthorizeService.TENANT_REAUTH_KEY, targetTenantId);
|
|
335
|
+
sessionStorage.setItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY, targetTenantId);
|
|
336
|
+
} catch {}
|
|
337
|
+
this.oauthService.stopAutomaticRefresh();
|
|
338
|
+
this._accessToken.set(null);
|
|
339
|
+
this._user.set(null);
|
|
340
|
+
this._isAuthenticated.set(false);
|
|
341
|
+
this._tokenTenantId.set(null);
|
|
342
|
+
this.navigateTo(targetUrl);
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
retryTenantSignIn(targetTenantId, targetUrl) {
|
|
346
|
+
if (this.isTenantSignInRetried(targetTenantId)) return false;
|
|
347
|
+
try {
|
|
348
|
+
sessionStorage.setItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY, targetTenantId);
|
|
349
|
+
sessionStorage.removeItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
350
|
+
} catch {}
|
|
351
|
+
return this.switchTenant(targetTenantId, targetUrl);
|
|
352
|
+
}
|
|
353
|
+
isTenantSignInRetried(targetTenantId) {
|
|
354
|
+
try {
|
|
355
|
+
const retried = sessionStorage.getItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY);
|
|
356
|
+
return !!retried && retried.toLowerCase() === targetTenantId.toLowerCase();
|
|
357
|
+
} catch {
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
async switchTenantByExchange(targetTenantId) {
|
|
362
|
+
const subjectToken = this.oauthService.getAccessToken();
|
|
363
|
+
const tokenEndpoint = this.oauthService.tokenEndpoint;
|
|
364
|
+
const clientId = this.lastAuthConfig?.clientId;
|
|
365
|
+
if (!subjectToken || !tokenEndpoint || !clientId) {
|
|
366
|
+
console.debug("AuthorizeService::switchTenantByExchange — no token or endpoint yet, falling back");
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
const currentTenantId = this._tokenTenantId();
|
|
370
|
+
if (currentTenantId && currentTenantId.toLowerCase() === targetTenantId.toLowerCase()) return true;
|
|
371
|
+
const allowedTenants = this._allowedTenants();
|
|
372
|
+
if (allowedTenants.length > 0 && !allowedTenants.some((t) => t.toLowerCase() === targetTenantId.toLowerCase())) {
|
|
373
|
+
console.debug(`AuthorizeService::switchTenantByExchange — "${targetTenantId}" not in allowed_tenants, falling back`);
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
const body = new URLSearchParams({
|
|
378
|
+
grant_type: AuthorizeService.TOKEN_EXCHANGE_GRANT,
|
|
379
|
+
client_id: clientId,
|
|
380
|
+
subject_token: subjectToken,
|
|
381
|
+
subject_token_type: AuthorizeService.ACCESS_TOKEN_TYPE,
|
|
382
|
+
acr_values: `tenant:${targetTenantId}`
|
|
383
|
+
});
|
|
384
|
+
const scope = this.lastAuthConfig?.scope;
|
|
385
|
+
if (scope) body.set("scope", scope);
|
|
386
|
+
const response = await fetch(tokenEndpoint, {
|
|
387
|
+
method: "POST",
|
|
388
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
389
|
+
body: body.toString()
|
|
390
|
+
});
|
|
391
|
+
if (!response.ok) {
|
|
392
|
+
console.warn(`AuthorizeService::switchTenantByExchange — exchange to "${targetTenantId}" failed (HTTP ${response.status}), falling back`);
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
const tokens = await response.json();
|
|
396
|
+
if (!tokens.access_token) {
|
|
397
|
+
console.warn("AuthorizeService::switchTenantByExchange — exchange returned no access token, falling back");
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
const claims = await this.fetchUserInfoClaims(tokens.access_token);
|
|
401
|
+
if (!claims) {
|
|
402
|
+
console.warn("AuthorizeService::switchTenantByExchange — could not load the profile, falling back");
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
this.storeExchangedTokens(targetTenantId, tokens, claims);
|
|
406
|
+
this.applyExchangedSession(targetTenantId, tokens.access_token, claims);
|
|
407
|
+
console.debug(`AuthorizeService::switchTenantByExchange — now on "${this._tokenTenantId()}"`);
|
|
408
|
+
return true;
|
|
409
|
+
} catch (error) {
|
|
410
|
+
console.warn("AuthorizeService::switchTenantByExchange — exchange threw, falling back", error);
|
|
411
|
+
return false;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
async fetchUserInfoClaims(accessToken) {
|
|
415
|
+
const userinfoEndpoint = this.oauthService.userinfoEndpoint;
|
|
416
|
+
if (!userinfoEndpoint) return null;
|
|
417
|
+
const response = await fetch(userinfoEndpoint, { headers: { Authorization: `Bearer ${accessToken}` } });
|
|
418
|
+
if (!response.ok) return null;
|
|
419
|
+
return await response.json();
|
|
420
|
+
}
|
|
421
|
+
storeExchangedTokens(targetTenantId, tokens, claims) {
|
|
422
|
+
this.tenantStorage.setTenantId(targetTenantId);
|
|
423
|
+
const storedAt = Date.now();
|
|
424
|
+
this.tenantStorage.setItem("access_token", tokens.access_token);
|
|
425
|
+
this.tenantStorage.setItem("access_token_stored_at", String(storedAt));
|
|
426
|
+
if (tokens.expires_in) this.tenantStorage.setItem("expires_at", String(storedAt + tokens.expires_in * 1e3));
|
|
427
|
+
if (tokens.refresh_token) this.tenantStorage.setItem("refresh_token", tokens.refresh_token);
|
|
428
|
+
if (tokens.scope) this.tenantStorage.setItem("granted_scopes", JSON.stringify(tokens.scope.split(" ")));
|
|
429
|
+
this.tenantStorage.setItem("id_token_claims_obj", JSON.stringify(claims));
|
|
430
|
+
}
|
|
431
|
+
applyExchangedSession(targetTenantId, accessToken, claims) {
|
|
432
|
+
const user = claims;
|
|
433
|
+
if (user.given_name && user.family_name) this._userInitials.set(user.given_name.charAt(0).toUpperCase() + user.family_name.charAt(0).toUpperCase());
|
|
434
|
+
else {
|
|
435
|
+
const derived = this.deriveDisplayNameFromUsername(user.name ?? targetTenantId);
|
|
436
|
+
this._userInitials.set(this.deriveInitials(derived));
|
|
437
|
+
}
|
|
438
|
+
this._user.set(user);
|
|
439
|
+
this._accessToken.set(accessToken);
|
|
440
|
+
this._isAuthenticated.set(true);
|
|
441
|
+
this._sessionLoading.set(false);
|
|
442
|
+
this._allowedTenants.set(allowedTenantsFromToken(accessToken));
|
|
443
|
+
this._tokenTenantId.set(tenantIdFromToken(accessToken));
|
|
444
|
+
this.clearPendingTenantSwitch();
|
|
445
|
+
}
|
|
446
|
+
consumePendingTenantSwitch() {
|
|
447
|
+
try {
|
|
448
|
+
return sessionStorage.getItem(AuthorizeService.TENANT_REAUTH_KEY);
|
|
449
|
+
} catch {
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
clearPendingTenantSwitch() {
|
|
454
|
+
try {
|
|
455
|
+
sessionStorage.removeItem(AuthorizeService.TENANT_REAUTH_KEY);
|
|
456
|
+
} catch {}
|
|
457
|
+
}
|
|
458
|
+
consumeSwitchAttempted() {
|
|
459
|
+
try {
|
|
460
|
+
const tenantId = sessionStorage.getItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
461
|
+
sessionStorage.removeItem(AuthorizeService.TENANT_SWITCH_ATTEMPTED_KEY);
|
|
462
|
+
sessionStorage.removeItem(AuthorizeService.TENANT_SIGNIN_RETRIED_KEY);
|
|
463
|
+
return tenantId;
|
|
464
|
+
} catch {
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
logout() {
|
|
469
|
+
const currentTenant = this.tenantStorage.getTenantId();
|
|
470
|
+
if (currentTenant) try {
|
|
471
|
+
sessionStorage.setItem("octo_post_logout_tenant", currentTenant);
|
|
472
|
+
} catch {}
|
|
473
|
+
const endSessionEndpoint = this.oauthService.logoutUrl;
|
|
474
|
+
const idToken = this.oauthService.getIdToken();
|
|
475
|
+
const postLogoutRedirectUri = this.lastAuthConfig?.postLogoutRedirectUri;
|
|
476
|
+
this.oauthService.logOut(true);
|
|
477
|
+
this.tenantStorage.clearAllTenants();
|
|
478
|
+
if (endSessionEndpoint) {
|
|
479
|
+
const params = new URLSearchParams();
|
|
480
|
+
if (idToken) params.set("id_token_hint", idToken);
|
|
481
|
+
if (postLogoutRedirectUri) params.set("post_logout_redirect_uri", postLogoutRedirectUri);
|
|
482
|
+
this.navigateTo(`${endSessionEndpoint}?${params.toString()}`);
|
|
483
|
+
} else this.reloadPage();
|
|
484
|
+
}
|
|
485
|
+
updateRedirectUris(redirectUri, postLogoutRedirectUri) {
|
|
486
|
+
if (this.authorizeOptions) {
|
|
487
|
+
this.authorizeOptions.redirectUri = redirectUri;
|
|
488
|
+
this.authorizeOptions.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
489
|
+
}
|
|
490
|
+
if (this.lastAuthConfig) {
|
|
491
|
+
this.lastAuthConfig.redirectUri = redirectUri;
|
|
492
|
+
this.lastAuthConfig.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
493
|
+
}
|
|
494
|
+
this.oauthService.redirectUri = redirectUri;
|
|
495
|
+
this.oauthService.postLogoutRedirectUri = postLogoutRedirectUri;
|
|
496
|
+
console.debug("AuthorizeService::updateRedirectUris::done");
|
|
497
|
+
}
|
|
498
|
+
async refreshAccessToken() {
|
|
499
|
+
console.debug("AuthorizeService::refreshAccessToken::started");
|
|
500
|
+
await this.oauthService.refreshToken();
|
|
501
|
+
await this.loadUserAsync();
|
|
502
|
+
console.debug("AuthorizeService::refreshAccessToken::done");
|
|
503
|
+
}
|
|
504
|
+
async initialize(authorizeOptions) {
|
|
505
|
+
console.debug("AuthorizeService::initialize::started");
|
|
506
|
+
await this.uninitialize();
|
|
507
|
+
if (this._isInitializing()) return;
|
|
508
|
+
if (this._isInitialized()) {
|
|
509
|
+
console.debug("AuthorizeService::initialize::alreadyInitialized");
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
this._isInitializing.set(true);
|
|
513
|
+
try {
|
|
514
|
+
const config = {
|
|
515
|
+
responseType: "code",
|
|
516
|
+
issuer: authorizeOptions.issuer,
|
|
517
|
+
redirectUri: authorizeOptions.redirectUri,
|
|
518
|
+
postLogoutRedirectUri: authorizeOptions.postLogoutRedirectUri,
|
|
519
|
+
clientId: authorizeOptions.clientId,
|
|
520
|
+
scope: authorizeOptions.scope,
|
|
521
|
+
showDebugInformation: authorizeOptions.showDebugInformation,
|
|
522
|
+
sessionChecksEnabled: authorizeOptions.sessionChecksEnabled,
|
|
523
|
+
sessionCheckIntervall: 6e4,
|
|
524
|
+
preserveRequestedRoute: true
|
|
525
|
+
};
|
|
526
|
+
this.authorizeOptions = authorizeOptions;
|
|
527
|
+
this.lastAuthConfig = config;
|
|
528
|
+
this.oauthService.setStorage(this.tenantStorage);
|
|
529
|
+
this.oauthService.configure(config);
|
|
530
|
+
console.debug("AuthorizeService::initialize::loadingDiscoveryDocumentAndTryLogin");
|
|
531
|
+
await this.loadDiscoveryDocumentAndTryLoginWithRetry(authorizeOptions.discoveryDocumentRetry ?? AuthorizeService.DEFAULT_DISCOVERY_RETRY);
|
|
532
|
+
console.debug("AuthorizeService::initialize::setupAutomaticSilentRefresh");
|
|
533
|
+
this.oauthService.setupAutomaticSilentRefresh();
|
|
534
|
+
this._issuer.set(authorizeOptions.issuer ?? null);
|
|
535
|
+
if (this.oauthService.hasValidIdToken()) {
|
|
536
|
+
console.debug("AuthorizeService::initialize::hasValidIdToken");
|
|
537
|
+
this._sessionLoading.set(true);
|
|
538
|
+
await this.oauthService.refreshToken();
|
|
539
|
+
}
|
|
540
|
+
this._isInitialized.set(true);
|
|
541
|
+
console.debug("AuthorizeService::initialize::done");
|
|
542
|
+
} finally {
|
|
543
|
+
this._isInitializing.set(false);
|
|
544
|
+
}
|
|
545
|
+
console.debug("AuthorizeService::initialize::completed");
|
|
546
|
+
}
|
|
547
|
+
async loadDiscoveryDocumentAndTryLoginWithRetry(retry) {
|
|
548
|
+
const attempts = Math.max(1, retry.attempts);
|
|
549
|
+
const initialDelayMs = Math.max(0, retry.initialDelayMs);
|
|
550
|
+
const maxDelayMs = Math.max(initialDelayMs, retry.maxDelayMs);
|
|
551
|
+
let lastError = null;
|
|
552
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
553
|
+
this._discoveryDocumentRetryAttempt.set(attempt);
|
|
554
|
+
try {
|
|
555
|
+
await this.oauthService.loadDiscoveryDocumentAndTryLogin();
|
|
556
|
+
this._discoveryDocumentError.set(null);
|
|
557
|
+
this._discoveryDocumentRetryAttempt.set(0);
|
|
558
|
+
if (attempt > 1) console.info(`AuthorizeService: discovery document loaded on retry attempt ${attempt}/${attempts}`);
|
|
559
|
+
return;
|
|
560
|
+
} catch (err) {
|
|
561
|
+
lastError = err;
|
|
562
|
+
if (attempt === attempts) break;
|
|
563
|
+
const delayMs = Math.min(initialDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
|
|
564
|
+
console.warn(`AuthorizeService: discovery document load failed (attempt ${attempt}/${attempts}); retrying in ${delayMs}ms`, err);
|
|
565
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
const error = lastError instanceof Error ? lastError : /* @__PURE__ */ new Error("Failed to load OIDC discovery document");
|
|
569
|
+
this._discoveryDocumentError.set(error);
|
|
570
|
+
this._discoveryDocumentRetryAttempt.set(0);
|
|
571
|
+
console.error(`AuthorizeService: discovery document load failed after ${attempts} attempt(s)`, error);
|
|
572
|
+
throw error;
|
|
573
|
+
}
|
|
574
|
+
async uninitialize() {
|
|
575
|
+
console.debug("AuthorizeService::uninitialize::started");
|
|
576
|
+
if (this._isInitializing()) return;
|
|
577
|
+
if (!this._isInitialized()) {
|
|
578
|
+
console.debug("AuthorizeService::uninitialize::alreadyUninitialized");
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
this._isInitializing.set(true);
|
|
583
|
+
this.oauthService.stopAutomaticRefresh();
|
|
584
|
+
this.authorizeOptions = null;
|
|
585
|
+
this.lastAuthConfig = null;
|
|
586
|
+
this._isInitialized.set(false);
|
|
587
|
+
console.debug("AuthorizeService::uninitialize::done");
|
|
588
|
+
} finally {
|
|
589
|
+
this._isInitializing.set(false);
|
|
590
|
+
}
|
|
591
|
+
console.debug("AuthorizeService::uninitialize::completed");
|
|
592
|
+
}
|
|
593
|
+
setUpSessionIdentity(sink) {
|
|
594
|
+
if (!sink) return;
|
|
595
|
+
const identity = computed(() => {
|
|
596
|
+
const user = this._user();
|
|
597
|
+
if (!user?.sub) return null;
|
|
598
|
+
return {
|
|
599
|
+
userId: user.sub,
|
|
600
|
+
name: user.name || null,
|
|
601
|
+
email: user.email || null,
|
|
602
|
+
tenantId: this._tokenTenantId()
|
|
603
|
+
};
|
|
604
|
+
}, {
|
|
605
|
+
...ngDevMode ? { debugName: "identity" } : /* istanbul ignore next */ {},
|
|
606
|
+
equal: sameSessionIdentity
|
|
607
|
+
});
|
|
608
|
+
let published = false;
|
|
609
|
+
effect(() => {
|
|
610
|
+
const current = identity();
|
|
611
|
+
if (current === null && !published) return;
|
|
612
|
+
published = current !== null;
|
|
613
|
+
try {
|
|
614
|
+
if (current === null) sink.clear();
|
|
615
|
+
else sink.set(current);
|
|
616
|
+
} catch (error) {
|
|
617
|
+
console.warn(`AuthorizeService: session identity sink failed on ${current === null ? "clear" : "set"} (${error instanceof Error ? error.name : typeof error}) — ignored`);
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
async loadUserAsync() {
|
|
622
|
+
const claims = this.oauthService.getIdentityClaims();
|
|
623
|
+
if (!claims) {
|
|
624
|
+
console.error("claims were null when loading identity claims");
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const previouslyAuthenticated = this._isAuthenticated();
|
|
628
|
+
const user = claims;
|
|
629
|
+
if (user.given_name && user.family_name) this._userInitials.set(user.given_name.charAt(0).toUpperCase() + user.family_name.charAt(0).toUpperCase());
|
|
630
|
+
else {
|
|
631
|
+
const derived = this.deriveDisplayNameFromUsername(user.name);
|
|
632
|
+
this._userInitials.set(this.deriveInitials(derived));
|
|
633
|
+
}
|
|
634
|
+
const accessToken = this.oauthService.getAccessToken();
|
|
635
|
+
this._user.set(user);
|
|
636
|
+
this._accessToken.set(accessToken);
|
|
637
|
+
this._isAuthenticated.set(true);
|
|
638
|
+
this._sessionLoading.set(false);
|
|
639
|
+
this._allowedTenants.set(allowedTenantsFromToken(accessToken));
|
|
640
|
+
const tokenTenantId = tenantIdFromToken(accessToken);
|
|
641
|
+
this._tokenTenantId.set(tokenTenantId);
|
|
642
|
+
const expectedTenantId = this.tenantStorage.getTenantId();
|
|
643
|
+
if (previouslyAuthenticated && tokenTenantId && expectedTenantId && tokenTenantId.toLowerCase() !== expectedTenantId.toLowerCase()) {
|
|
644
|
+
console.warn(`AuthorizeService::loadUserAsync: Tenant mismatch after silent refresh — token="${tokenTenantId}", expected="${expectedTenantId}". Triggering re-authentication.`);
|
|
645
|
+
this.switchTenant(expectedTenantId, window.location.href);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
this.clearPendingTenantSwitch();
|
|
649
|
+
console.debug(`AuthorizeService::loadUserAsync::done (tokenTenantId="${tokenTenantId}", allowedTenants=${JSON.stringify(this._allowedTenants())})`);
|
|
650
|
+
}
|
|
651
|
+
deriveDisplayNameFromUsername(username) {
|
|
652
|
+
let name = username;
|
|
653
|
+
const xtMatch = name.match(/^xt_[^_]+_(.+)$/);
|
|
654
|
+
if (xtMatch) name = xtMatch[1];
|
|
655
|
+
const atIndex = name.indexOf("@");
|
|
656
|
+
if (atIndex > 0) name = name.substring(0, atIndex);
|
|
657
|
+
return name.split(".").filter((p) => p.length > 0).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(" ");
|
|
658
|
+
}
|
|
659
|
+
deriveInitials(displayName) {
|
|
660
|
+
const words = displayName.split(" ").filter((w) => w.length > 0);
|
|
661
|
+
if (words.length >= 2) return words[0].charAt(0).toUpperCase() + words[1].charAt(0).toUpperCase();
|
|
662
|
+
if (words.length === 1 && words[0].length >= 2) return words[0].charAt(0).toUpperCase() + words[0].charAt(1).toLowerCase();
|
|
663
|
+
return "??";
|
|
664
|
+
}
|
|
665
|
+
reloadPage() {
|
|
666
|
+
window.location.reload();
|
|
667
|
+
}
|
|
668
|
+
navigateTo(url) {
|
|
669
|
+
window.location.href = url;
|
|
670
|
+
}
|
|
671
|
+
static ɵfac = i0.ɵɵngDeclareFactory({
|
|
672
|
+
minVersion: "12.0.0",
|
|
673
|
+
version: "22.3.0",
|
|
674
|
+
ngImport: i0,
|
|
675
|
+
type: AuthorizeService,
|
|
676
|
+
deps: [],
|
|
677
|
+
target: i0.ɵɵFactoryTarget.Injectable
|
|
678
|
+
});
|
|
679
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({
|
|
680
|
+
minVersion: "12.0.0",
|
|
681
|
+
version: "22.3.0",
|
|
682
|
+
ngImport: i0,
|
|
683
|
+
type: AuthorizeService
|
|
684
|
+
});
|
|
685
|
+
};
|
|
686
|
+
i0.ɵɵngDeclareClassMetadata({
|
|
687
|
+
minVersion: "12.0.0",
|
|
688
|
+
version: "22.3.0",
|
|
689
|
+
ngImport: i0,
|
|
690
|
+
type: AuthorizeService,
|
|
691
|
+
decorators: [{ type: Injectable }],
|
|
692
|
+
ctorParameters: () => []
|
|
693
|
+
});
|
|
1291
694
|
var Roles;
|
|
1292
|
-
(function
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
/**
|
|
1308
|
-
* Trigger secret sweeps (Verify / Encrypt / CleanupUnreadable) and delete a pre-sweep dump early
|
|
1309
|
-
* (SECRET value type AB#5528, handover §6). Seeded by `System.Identity.Bootstrap`
|
|
1310
|
-
* (`CommonConstants.SecretManagementRole`); the secrets overview itself needs `AdminPanelManagement`.
|
|
1311
|
-
*/
|
|
1312
|
-
Roles["SecretManagement"] = "SecretManagement";
|
|
1313
|
-
Roles["BotManagement"] = "BotManagement";
|
|
1314
|
-
Roles["UserManagement"] = "UserManagement";
|
|
1315
|
-
Roles["CommunicationManagement"] = "CommunicationManagement";
|
|
1316
|
-
Roles["TenantManagement"] = "TenantManagement";
|
|
1317
|
-
Roles["Development"] = "Development";
|
|
1318
|
-
Roles["StreamDataAdmin"] = "StreamDataAdmin";
|
|
1319
|
-
Roles["StreamDataWriter"] = "StreamDataWriter";
|
|
1320
|
-
Roles["StreamDataReader"] = "StreamDataReader";
|
|
695
|
+
(function(Roles) {
|
|
696
|
+
Roles["ReportingManagement"] = "ReportingManagement";
|
|
697
|
+
Roles["ReportingViewer"] = "ReportingViewer";
|
|
698
|
+
Roles["FileManagement"] = "FileManagement";
|
|
699
|
+
Roles["FileViewer"] = "FileViewer";
|
|
700
|
+
Roles["AdminPanelManagement"] = "AdminPanelManagement";
|
|
701
|
+
Roles["SecretManagement"] = "SecretManagement";
|
|
702
|
+
Roles["BotManagement"] = "BotManagement";
|
|
703
|
+
Roles["UserManagement"] = "UserManagement";
|
|
704
|
+
Roles["CommunicationManagement"] = "CommunicationManagement";
|
|
705
|
+
Roles["TenantManagement"] = "TenantManagement";
|
|
706
|
+
Roles["Development"] = "Development";
|
|
707
|
+
Roles["StreamDataAdmin"] = "StreamDataAdmin";
|
|
708
|
+
Roles["StreamDataWriter"] = "StreamDataWriter";
|
|
709
|
+
Roles["StreamDataReader"] = "StreamDataReader";
|
|
1321
710
|
})(Roles || (Roles = {}));
|
|
1322
|
-
|
|
1323
|
-
// =============================================================================
|
|
1324
|
-
// URL MATCHING UTILITIES
|
|
1325
|
-
// =============================================================================
|
|
1326
|
-
/**
|
|
1327
|
-
* Checks if the request URL is from the same origin as the application.
|
|
1328
|
-
*/
|
|
1329
711
|
function isSameOriginUrl(req) {
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
// It's a protocol relative url with the same origin.
|
|
1335
|
-
// For example: //www.example.com/api/Products
|
|
1336
|
-
if (req.url.startsWith(`//${window.location.host}/`)) {
|
|
1337
|
-
return true;
|
|
1338
|
-
}
|
|
1339
|
-
// It's a relative url like /api/Products
|
|
1340
|
-
if (/^\/[^/].*/.test(req.url)) {
|
|
1341
|
-
return true;
|
|
1342
|
-
}
|
|
1343
|
-
// It's an absolute or protocol relative url that doesn't have the same origin.
|
|
1344
|
-
return false;
|
|
712
|
+
if (req.url.startsWith(`${window.location.origin}/`)) return true;
|
|
713
|
+
if (req.url.startsWith(`//${window.location.host}/`)) return true;
|
|
714
|
+
if (/^\/[^/].*/.test(req.url)) return true;
|
|
715
|
+
return false;
|
|
1345
716
|
}
|
|
1346
|
-
/**
|
|
1347
|
-
* Checks if the request URL matches any of the known service URIs.
|
|
1348
|
-
*/
|
|
1349
717
|
function isKnownServiceUri(req, serviceUris) {
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
continue;
|
|
1357
|
-
}
|
|
1358
|
-
// A bare prefix test would also accept a host that merely begins with a configured
|
|
1359
|
-
// one — `https://api.example.com.attacker.test` — and hand it the operator's bearer.
|
|
1360
|
-
// The match must therefore end on a path, query or fragment boundary.
|
|
1361
|
-
const remainder = req.url.slice(serviceUri.length);
|
|
1362
|
-
if (serviceUri.endsWith('/') || remainder === '' || '/?#'.includes(remainder.charAt(0))) {
|
|
1363
|
-
return true;
|
|
1364
|
-
}
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
return false;
|
|
718
|
+
if (serviceUris != null) for (const serviceUri of serviceUris) {
|
|
719
|
+
if (!serviceUri || serviceUri === "/" || !req.url.startsWith(serviceUri)) continue;
|
|
720
|
+
const remainder = req.url.slice(serviceUri.length);
|
|
721
|
+
if (serviceUri.endsWith("/") || remainder === "" || "/?#".includes(remainder.charAt(0))) return true;
|
|
722
|
+
}
|
|
723
|
+
return false;
|
|
1368
724
|
}
|
|
1369
|
-
/**
|
|
1370
|
-
* Checks if the request targets the OIDC token endpoint.
|
|
1371
|
-
*
|
|
1372
|
-
* The comparison runs on the path alone, because a guard keyed on the raw URL fails
|
|
1373
|
-
* silently rather than loudly: a query string, fragment or trailing slash would make the
|
|
1374
|
-
* refresh post to that endpoint through this same chain, and the single-flight promise
|
|
1375
|
-
* would wait on itself. It never settles, its `finally` never runs, and since every request
|
|
1376
|
-
* of that service shares it, each later 401 would await a promise that cannot resolve.
|
|
1377
|
-
*/
|
|
1378
725
|
function isTokenEndpointUrl(url) {
|
|
1379
|
-
|
|
1380
|
-
return path.endsWith('/connect/token');
|
|
726
|
+
return url.split("#")[0].split("?")[0].replace(/\/+$/, "").endsWith("/connect/token");
|
|
1381
727
|
}
|
|
1382
|
-
/**
|
|
1383
|
-
* Checks if the request targets a service's detailed health report (`<service>/health`).
|
|
1384
|
-
*
|
|
1385
|
-
* Since AB#6739 that report needs a Bearer token, so the interceptor attaches one like to any
|
|
1386
|
-
* other service call. It is deliberately kept out of the 401 recovery below: the report is polled
|
|
1387
|
-
* by the cockpit and the service-health widgets, and a service that keeps refusing the token
|
|
1388
|
-
* (a mis-configured issuer, say) would otherwise spend one refresh grant per poll — and a failed refresh clears the session,
|
|
1389
|
-
* which a health tile must never cause. The 401 reaches the caller, which shows the service as
|
|
1390
|
-
* "unknown"; a genuinely expired token is refreshed by the next ordinary API call.
|
|
1391
|
-
*
|
|
1392
|
-
* Path-only comparison, like `isTokenEndpointUrl`: a query string, fragment or trailing slash
|
|
1393
|
-
* must not change the decision.
|
|
1394
|
-
*/
|
|
1395
728
|
function isHealthReportUrl(url) {
|
|
1396
|
-
|
|
1397
|
-
return path.endsWith('/health');
|
|
729
|
+
return url.split("#")[0].split("?")[0].replace(/\/+$/, "").endsWith("/health");
|
|
1398
730
|
}
|
|
1399
|
-
|
|
1400
|
-
* The one denial code a refresh can repair. Adapter-owned and stable: the server deliberately
|
|
1401
|
-
* does not make a client key on the framework's English `error_description`, which a dependency
|
|
1402
|
-
* bump may reword.
|
|
1403
|
-
*/
|
|
1404
|
-
const REFRESHABLE_DENIAL_CODE = 'token_expired';
|
|
1405
|
-
/**
|
|
1406
|
-
* Answers whether refreshing the access token could possibly change this `401`.
|
|
1407
|
-
*
|
|
1408
|
-
* A server that follows RFC 6750 §3 names the reason it refused. Only an expired token gets a
|
|
1409
|
-
* different answer from a newer one — a wrong issuer, a wrong audience or an unknown signing key
|
|
1410
|
-
* describe something every token of this session shares, so refreshing spends one grant per user
|
|
1411
|
-
* action and lands in exactly the same place, indefinitely.
|
|
1412
|
-
*
|
|
1413
|
-
* A response that names no reason keeps the old behaviour and is refreshed, and so does a standard
|
|
1414
|
-
* challenge that carries no `error_code`. That is deliberate rather than a gap: every ASP.NET
|
|
1415
|
-
* service in the platform answers `Bearer error="invalid_token"` with a framework-worded
|
|
1416
|
-
* description and no such parameter, and RFC 6750 defines no code that separates an expired token
|
|
1417
|
-
* from a rejected one — so treating a bare challenge as unrepairable would silently drop the
|
|
1418
|
-
* recovery for every sibling service. The adapter closes the ambiguous case from its own side by
|
|
1419
|
-
* naming `token_not_evaluated` when it holds a token it never evaluated.
|
|
1420
|
-
*/
|
|
731
|
+
const REFRESHABLE_DENIAL_CODE = "token_expired";
|
|
1421
732
|
function mayRefreshRepair(error) {
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
const code = /error_code=(?:"([^"]*)"|([^\s,]+))/.exec(challenge);
|
|
1428
|
-
const value = code?.[1] ?? code?.[2];
|
|
1429
|
-
return value === undefined || value === REFRESHABLE_DENIAL_CODE;
|
|
733
|
+
const challenge = error.headers?.get("WWW-Authenticate");
|
|
734
|
+
if (!challenge) return true;
|
|
735
|
+
const code = /error_code=(?:"([^"]*)"|([^\s,]+))/.exec(challenge);
|
|
736
|
+
const value = code?.[1] ?? code?.[2];
|
|
737
|
+
return value === void 0 || value === REFRESHABLE_DENIAL_CODE;
|
|
1430
738
|
}
|
|
1431
|
-
|
|
1432
|
-
// SINGLE-FLIGHT TOKEN REFRESH
|
|
1433
|
-
// =============================================================================
|
|
1434
|
-
/**
|
|
1435
|
-
* Parallel 401s share one refresh instead of spending one grant each.
|
|
1436
|
-
*
|
|
1437
|
-
* Keyed by the service rather than held in a module variable: `AuthorizeService` is provided
|
|
1438
|
-
* per injector, so an app still gets exactly one in-flight refresh page-wide, while two
|
|
1439
|
-
* injectors in one process no longer await each other's promise and each test gets a clean
|
|
1440
|
-
* slate — a module variable is unreachable from a `beforeEach` unless it is exported.
|
|
1441
|
-
*
|
|
1442
|
-
* Do not restate the single-flight rationale as "concurrent grants would end the session":
|
|
1443
|
-
* that holds only for a client whose `RefreshTokenUsage` is `OneTimeOnly`, and ours are not —
|
|
1444
|
-
* Duende defaults the property to `ReUse` and nothing in octo-identity-services overrides it
|
|
1445
|
-
* (the CK attribute carries no default and reaches Duende through AutoMapper's by-name
|
|
1446
|
-
* convention, which is why grepping the C# for its name finds nothing).
|
|
1447
|
-
*/
|
|
1448
|
-
const refreshInFlight = new WeakMap();
|
|
739
|
+
const refreshInFlight = /* @__PURE__ */ new WeakMap();
|
|
1449
740
|
function refreshAccessTokenOnce(authorizeService) {
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
}
|
|
1459
|
-
return pending;
|
|
741
|
+
let pending = refreshInFlight.get(authorizeService);
|
|
742
|
+
if (!pending) {
|
|
743
|
+
pending = Promise.resolve().then(() => authorizeService.refreshAccessToken()).finally(() => {
|
|
744
|
+
refreshInFlight.delete(authorizeService);
|
|
745
|
+
});
|
|
746
|
+
refreshInFlight.set(authorizeService, pending);
|
|
747
|
+
}
|
|
748
|
+
return pending;
|
|
1460
749
|
}
|
|
1461
|
-
// =============================================================================
|
|
1462
|
-
// FUNCTIONAL INTERCEPTOR (RECOMMENDED)
|
|
1463
|
-
// =============================================================================
|
|
1464
|
-
/**
|
|
1465
|
-
* Functional HTTP interceptor that adds Bearer token to authorized requests
|
|
1466
|
-
* and injects tenant context (acr_values) into token endpoint requests.
|
|
1467
|
-
*
|
|
1468
|
-
* Adds the Authorization header to requests that are either:
|
|
1469
|
-
* - Same-origin requests (relative URLs or same host)
|
|
1470
|
-
* - Requests to known service URIs configured in AuthorizeOptions
|
|
1471
|
-
*
|
|
1472
|
-
* For token endpoint POST requests (`/connect/token`), appends
|
|
1473
|
-
* `acr_values=tenant:{tenantId}` to the form body so the Identity Server
|
|
1474
|
-
* can resolve the correct tenant during refresh token exchanges.
|
|
1475
|
-
*
|
|
1476
|
-
* When a request that carried a token comes back `401`, the access token is refreshed
|
|
1477
|
-
* and the request retried once with the new bearer. If the token has already been replaced
|
|
1478
|
-
* by then — a slower request reporting its `401` after someone else's refresh finished —
|
|
1479
|
-
* the retry goes out with that token and no second refresh is started. A refresh that fails
|
|
1480
|
-
* or yields no new token rethrows the original `401`, so hosts can still classify it.
|
|
1481
|
-
*
|
|
1482
|
-
* @example
|
|
1483
|
-
* ```typescript
|
|
1484
|
-
* // app.config.ts
|
|
1485
|
-
* import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
|
1486
|
-
* import { authorizeInterceptor } from '@meshmakers/shared-auth';
|
|
1487
|
-
*
|
|
1488
|
-
* export const appConfig: ApplicationConfig = {
|
|
1489
|
-
* providers: [
|
|
1490
|
-
* provideHttpClient(withInterceptors([authorizeInterceptor])),
|
|
1491
|
-
* provideMmSharedAuth(),
|
|
1492
|
-
* ]
|
|
1493
|
-
* };
|
|
1494
|
-
* ```
|
|
1495
|
-
*/
|
|
1496
750
|
const authorizeInterceptor = (req, next) => {
|
|
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
|
-
// deadlock this avoids — nor the health report (see isHealthReportUrl).
|
|
1533
|
-
if (!tokenAttached || isTokenEndpointUrl(req.url) || isHealthReportUrl(req.url)) {
|
|
1534
|
-
return next(req);
|
|
1535
|
-
}
|
|
1536
|
-
const authorizedReq = req;
|
|
1537
|
-
// `next()` hands off to the rest of the chain, so a retried request does not re-enter this
|
|
1538
|
-
// interceptor — at most one retry by construction, without any bookkeeping.
|
|
1539
|
-
const retryWith = (bearer) => next(authorizedReq.clone({ setHeaders: { Authorization: `Bearer ${bearer}` } }));
|
|
1540
|
-
return next(authorizedReq).pipe(catchError((error) => {
|
|
1541
|
-
if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
|
|
1542
|
-
return throwError(() => error);
|
|
1543
|
-
}
|
|
1544
|
-
// Checked before the retry below as well: a token the server refuses for its issuer or
|
|
1545
|
-
// audience is refused again once refreshed, so neither path is worth an HTTP call.
|
|
1546
|
-
if (!mayRefreshRepair(error)) {
|
|
1547
|
-
console.warn('[AuthInterceptor] The server refused this token for a reason a refresh cannot repair:', error.headers?.get('WWW-Authenticate'));
|
|
1548
|
-
return throwError(() => error);
|
|
1549
|
-
}
|
|
1550
|
-
// Single-flight only covers the window while a refresh runs. A slower request that
|
|
1551
|
-
// went out with the same stale token reports its 401 after that window closed, and
|
|
1552
|
-
// its failure is already explained by the token that has since been replaced —
|
|
1553
|
-
// refreshing again would spend a second grant to learn the same thing.
|
|
1554
|
-
const currentToken = authorizeService.getAccessTokenSync();
|
|
1555
|
-
if (currentToken && currentToken !== token) {
|
|
1556
|
-
return retryWith(currentToken);
|
|
1557
|
-
}
|
|
1558
|
-
// Surface the original 401, not the refresh error: consuming apps classify the status
|
|
1559
|
-
// code to pick their message, and AuthorizeService already reacts to
|
|
1560
|
-
// `token_refresh_error` by clearing the session. The mapping is bound to the refresh
|
|
1561
|
-
// promise rather than placed in the pipe, because as an operator it only holds while it
|
|
1562
|
-
// sits above the switchMap below — and a 403 from the retried request must reach the
|
|
1563
|
-
// host as 403, not as the remembered 401.
|
|
1564
|
-
const refresh = refreshAccessTokenOnce(authorizeService).catch((refreshError) => {
|
|
1565
|
-
console.warn('[AuthInterceptor] Token refresh threw; surfacing the original 401.', refreshError);
|
|
1566
|
-
return Promise.reject(error);
|
|
1567
|
-
});
|
|
1568
|
-
return from(refresh).pipe(switchMap(() => {
|
|
1569
|
-
const refreshedToken = authorizeService.getAccessTokenSync();
|
|
1570
|
-
if (!refreshedToken || refreshedToken === token) {
|
|
1571
|
-
// Distinct from the throw above, and from each other: all three end in the same
|
|
1572
|
-
// 401 for the host, so the log is the only place they stay tellable apart.
|
|
1573
|
-
console.warn(refreshedToken
|
|
1574
|
-
? '[AuthInterceptor] Token refresh returned the same access token; surfacing the original 401.'
|
|
1575
|
-
: '[AuthInterceptor] Token refresh returned no access token; surfacing the original 401.');
|
|
1576
|
-
return throwError(() => error);
|
|
1577
|
-
}
|
|
1578
|
-
return retryWith(refreshedToken);
|
|
1579
|
-
}));
|
|
1580
|
-
}));
|
|
751
|
+
const authorizeService = inject(AuthorizeService);
|
|
752
|
+
const token = authorizeService.getAccessTokenSync();
|
|
753
|
+
const serviceUris = authorizeService.getServiceUris();
|
|
754
|
+
const tokenAttached = !!token && (isSameOriginUrl(req) || isKnownServiceUri(req, serviceUris));
|
|
755
|
+
if (tokenAttached) req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
|
|
756
|
+
if (req.method === "POST" && isTokenEndpointUrl(req.url) && req.body instanceof HttpParams) {
|
|
757
|
+
if (req.body.get("grant_type") === "refresh_token") {
|
|
758
|
+
const tenantId = authorizeService.getStorageTenantId() ?? authorizeService.tokenTenantId();
|
|
759
|
+
if (tenantId) req = req.clone({ body: req.body.set("acr_values", `tenant:${tenantId}`) });
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (!tokenAttached || isTokenEndpointUrl(req.url) || isHealthReportUrl(req.url)) return next(req);
|
|
763
|
+
const authorizedReq = req;
|
|
764
|
+
const retryWith = (bearer) => next(authorizedReq.clone({ setHeaders: { Authorization: `Bearer ${bearer}` } }));
|
|
765
|
+
return next(authorizedReq).pipe(catchError((error) => {
|
|
766
|
+
if (!(error instanceof HttpErrorResponse) || error.status !== 401) return throwError(() => error);
|
|
767
|
+
if (!mayRefreshRepair(error)) {
|
|
768
|
+
console.warn("[AuthInterceptor] The server refused this token for a reason a refresh cannot repair:", error.headers?.get("WWW-Authenticate"));
|
|
769
|
+
return throwError(() => error);
|
|
770
|
+
}
|
|
771
|
+
const currentToken = authorizeService.getAccessTokenSync();
|
|
772
|
+
if (currentToken && currentToken !== token) return retryWith(currentToken);
|
|
773
|
+
const refresh = refreshAccessTokenOnce(authorizeService).catch((refreshError) => {
|
|
774
|
+
console.warn("[AuthInterceptor] Token refresh threw; surfacing the original 401.", refreshError);
|
|
775
|
+
return Promise.reject(error);
|
|
776
|
+
});
|
|
777
|
+
return from(refresh).pipe(switchMap(() => {
|
|
778
|
+
const refreshedToken = authorizeService.getAccessTokenSync();
|
|
779
|
+
if (!refreshedToken || refreshedToken === token) {
|
|
780
|
+
console.warn(refreshedToken ? "[AuthInterceptor] Token refresh returned the same access token; surfacing the original 401." : "[AuthInterceptor] Token refresh returned no access token; surfacing the original 401.");
|
|
781
|
+
return throwError(() => error);
|
|
782
|
+
}
|
|
783
|
+
return retryWith(refreshedToken);
|
|
784
|
+
}));
|
|
785
|
+
}));
|
|
1581
786
|
};
|
|
1582
|
-
|
|
1583
|
-
/**
|
|
1584
|
-
* Classifies an HTTP failure as an authorization refusal, or `null` when it is anything else.
|
|
1585
|
-
*
|
|
1586
|
-
* Hosts phrase the outcome themselves - one app wants an i18n key, another a translated string,
|
|
1587
|
-
* and the public landing pages deliberately merge both cases because an anonymous visitor cannot
|
|
1588
|
-
* act on the difference. What they share is reading `status`, and six copies of that read is how
|
|
1589
|
-
* the six drift apart.
|
|
1590
|
-
*
|
|
1591
|
-
* Takes `unknown` because that is how the error arrives: through a rejected promise, a `catch`
|
|
1592
|
-
* block, or a rethrow that may have stripped the `HttpErrorResponse` prototype along the way.
|
|
1593
|
-
* The status is therefore read structurally and must be a `number` - a body that merely carries
|
|
1594
|
-
* `"403"` is not a refusal.
|
|
1595
|
-
*
|
|
1596
|
-
* @example
|
|
1597
|
-
* ```typescript
|
|
1598
|
-
* switch (authorizationRefusal(error)) {
|
|
1599
|
-
* case 'forbidden': return this.translate.instant('pipeline.forbidden');
|
|
1600
|
-
* case 'unauthorized': return this.translate.instant('pipeline.unauthorized');
|
|
1601
|
-
* default: return null;
|
|
1602
|
-
* }
|
|
1603
|
-
* ```
|
|
1604
|
-
*/
|
|
1605
787
|
function authorizationRefusal(error) {
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
if (status === 403) {
|
|
1611
|
-
return 'forbidden';
|
|
1612
|
-
}
|
|
1613
|
-
return null;
|
|
788
|
+
const status = error?.status;
|
|
789
|
+
if (status === 401) return "unauthorized";
|
|
790
|
+
if (status === 403) return "forbidden";
|
|
791
|
+
return null;
|
|
1614
792
|
}
|
|
1615
|
-
|
|
1616
|
-
/**
|
|
1617
|
-
* Path segment of the blocking route a host registers as `/:tenantId/tenant-mismatch`. The guard
|
|
1618
|
-
* redirects there when the token still belongs to another tenant than the route after the switch
|
|
1619
|
-
* attempt (AB#6731); render {@link TenantMismatchComponent} on it.
|
|
1620
|
-
*/
|
|
1621
|
-
const TENANT_MISMATCH_PATH = 'tenant-mismatch';
|
|
1622
|
-
/**
|
|
1623
|
-
* Walks up the route tree to find the tenantId parameter.
|
|
1624
|
-
*/
|
|
793
|
+
const TENANT_MISMATCH_PATH = "tenant-mismatch";
|
|
1625
794
|
function findRouteTenantId(route) {
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
current = current.parent;
|
|
1632
|
-
}
|
|
1633
|
-
return undefined;
|
|
795
|
+
let current = route;
|
|
796
|
+
while (current) {
|
|
797
|
+
if (current.params?.["tenantId"]) return current.params["tenantId"];
|
|
798
|
+
current = current.parent;
|
|
799
|
+
}
|
|
1634
800
|
}
|
|
1635
801
|
function mismatchTree(router, routeTenantId) {
|
|
1636
|
-
|
|
802
|
+
return router.createUrlTree([
|
|
803
|
+
"/",
|
|
804
|
+
routeTenantId,
|
|
805
|
+
TENANT_MISMATCH_PATH
|
|
806
|
+
]);
|
|
1637
807
|
}
|
|
1638
|
-
/**
|
|
1639
|
-
* Handles authorization check for route activation.
|
|
1640
|
-
* Redirects to login if not authenticated, or to home if user lacks required roles.
|
|
1641
|
-
* Forces re-authentication when the token's tenant_id does not match the route's tenantId.
|
|
1642
|
-
*
|
|
1643
|
-
* @param route - The activated route snapshot containing route data
|
|
1644
|
-
* @returns true if authorized, false otherwise
|
|
1645
|
-
*
|
|
1646
|
-
* @example
|
|
1647
|
-
* ```typescript
|
|
1648
|
-
* // Route without role requirements
|
|
1649
|
-
* { path: 'dashboard', component: DashboardComponent, canActivate: [authorizeGuard] }
|
|
1650
|
-
*
|
|
1651
|
-
* // Route with role requirements
|
|
1652
|
-
* { path: 'admin', component: AdminComponent, canActivate: [authorizeGuard], data: { roles: ['AdminPanelManagement'] } }
|
|
1653
|
-
* ```
|
|
1654
|
-
*/
|
|
1655
808
|
const authorizeGuard = async (route, state) => {
|
|
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
|
-
// block with an explanation instead of letting the page issue requests that fail.
|
|
1689
|
-
const tokenAfter = authorizeService.tokenTenantId();
|
|
1690
|
-
if (tokenAfter && tokenAfter.toLowerCase() !== routeTenantId.toLowerCase()) {
|
|
1691
|
-
return mismatchTree(router, routeTenantId);
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1694
|
-
else {
|
|
1695
|
-
// No mismatch — clear any leftover switch-attempted flag
|
|
1696
|
-
authorizeService.consumeSwitchAttempted();
|
|
1697
|
-
}
|
|
1698
|
-
// Use roles signal directly (synchronous)
|
|
1699
|
-
const userRoles = authorizeService.roles();
|
|
1700
|
-
const requiredRoles = route.data['roles'];
|
|
1701
|
-
if (requiredRoles === undefined || requiredRoles === null) {
|
|
1702
|
-
if (typeof ngDevMode === 'undefined' || ngDevMode) {
|
|
1703
|
-
console.warn(`[AuthGuard] Route "${route.routeConfig?.path}" has no required roles defined — access granted to any authenticated user.`);
|
|
1704
|
-
}
|
|
1705
|
-
return true;
|
|
1706
|
-
}
|
|
1707
|
-
// Empty roles array (roles: []) means intentionally open to any authenticated user
|
|
1708
|
-
if (requiredRoles.length === 0) {
|
|
1709
|
-
return true;
|
|
1710
|
-
}
|
|
1711
|
-
if (!requiredRoles.some(role => userRoles.includes(role))) {
|
|
1712
|
-
// Navigate to the current tenant's home, not root ''.
|
|
1713
|
-
// Navigating to '' would redirect to a default tenant (e.g., octosystem),
|
|
1714
|
-
// causing a tenant mismatch → switchTenant → redirect loop.
|
|
1715
|
-
const tenantHome = routeTenantId ? `/${routeTenantId}` : '';
|
|
1716
|
-
await router.navigate([tenantHome]);
|
|
1717
|
-
return false;
|
|
1718
|
-
}
|
|
1719
|
-
return true;
|
|
809
|
+
const authorizeService = inject(AuthorizeService);
|
|
810
|
+
const router = inject(Router);
|
|
811
|
+
if (!authorizeService.isAuthenticated()) {
|
|
812
|
+
const tenantId = authorizeService.consumePendingTenantSwitch() ?? findRouteTenantId(route);
|
|
813
|
+
authorizeService.login(tenantId);
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
const tokenTenantId = authorizeService.tokenTenantId();
|
|
817
|
+
const routeTenantId = findRouteTenantId(route);
|
|
818
|
+
if (tokenTenantId && routeTenantId && routeTenantId.toLowerCase() !== tokenTenantId.toLowerCase()) {
|
|
819
|
+
console.debug(`[AuthGuard] Tenant mismatch: token="${tokenTenantId}", route="${routeTenantId}" — attempting tenant switch`);
|
|
820
|
+
if (await authorizeService.switchTenantByExchange(routeTenantId)) authorizeService.consumeSwitchAttempted();
|
|
821
|
+
else {
|
|
822
|
+
const targetUrl = window.location.origin + state.url;
|
|
823
|
+
if (authorizeService.switchTenant(routeTenantId, targetUrl)) return false;
|
|
824
|
+
}
|
|
825
|
+
const tokenAfter = authorizeService.tokenTenantId();
|
|
826
|
+
if (tokenAfter && tokenAfter.toLowerCase() !== routeTenantId.toLowerCase()) return mismatchTree(router, routeTenantId);
|
|
827
|
+
} else authorizeService.consumeSwitchAttempted();
|
|
828
|
+
const userRoles = authorizeService.roles();
|
|
829
|
+
const requiredRoles = route.data["roles"];
|
|
830
|
+
if (requiredRoles === void 0 || requiredRoles === null) {
|
|
831
|
+
if (typeof ngDevMode === "undefined" || ngDevMode) console.warn(`[AuthGuard] Route "${route.routeConfig?.path}" has no required roles defined — access granted to any authenticated user.`);
|
|
832
|
+
return true;
|
|
833
|
+
}
|
|
834
|
+
if (requiredRoles.length === 0) return true;
|
|
835
|
+
if (!requiredRoles.some((role) => userRoles.includes(role))) {
|
|
836
|
+
const tenantHome = routeTenantId ? `/${routeTenantId}` : "";
|
|
837
|
+
await router.navigate([tenantHome]);
|
|
838
|
+
return false;
|
|
839
|
+
}
|
|
840
|
+
return true;
|
|
1720
841
|
};
|
|
1721
|
-
/**
|
|
1722
|
-
* Guard for child routes. Delegates to authorizeGuard.
|
|
1723
|
-
*
|
|
1724
|
-
* @example
|
|
1725
|
-
* ```typescript
|
|
1726
|
-
* {
|
|
1727
|
-
* path: 'parent',
|
|
1728
|
-
* canActivateChild: [authorizeChildGuard],
|
|
1729
|
-
* children: [
|
|
1730
|
-
* { path: 'child', component: ChildComponent, data: { roles: ['RequiredRole'] } }
|
|
1731
|
-
* ]
|
|
1732
|
-
* }
|
|
1733
|
-
* ```
|
|
1734
|
-
*/
|
|
1735
842
|
const authorizeChildGuard = authorizeGuard;
|
|
1736
|
-
/**
|
|
1737
|
-
* Guard for lazy-loaded routes. Checks if user is authenticated.
|
|
1738
|
-
* Replaces the deprecated canLoad guard.
|
|
1739
|
-
*
|
|
1740
|
-
* @example
|
|
1741
|
-
* ```typescript
|
|
1742
|
-
* {
|
|
1743
|
-
* path: 'lazy',
|
|
1744
|
-
* loadChildren: () => import('./lazy/lazy.routes'),
|
|
1745
|
-
* canMatch: [authorizeMatchGuard]
|
|
1746
|
-
* }
|
|
1747
|
-
* ```
|
|
1748
|
-
*/
|
|
1749
843
|
const authorizeMatchGuard = (_route, segments) => {
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
return false;
|
|
1758
|
-
}
|
|
1759
|
-
return true;
|
|
844
|
+
const authorizeService = inject(AuthorizeService);
|
|
845
|
+
if (!authorizeService.isAuthenticated()) {
|
|
846
|
+
const tenantId = segments.length > 0 ? segments[0].path : void 0;
|
|
847
|
+
authorizeService.login(tenantId);
|
|
848
|
+
return false;
|
|
849
|
+
}
|
|
850
|
+
return true;
|
|
1760
851
|
};
|
|
1761
|
-
/**
|
|
1762
|
-
* Guard that always allows deactivation.
|
|
1763
|
-
* Use this as a placeholder or override in specific routes.
|
|
1764
|
-
*
|
|
1765
|
-
* @example
|
|
1766
|
-
* ```typescript
|
|
1767
|
-
* { path: 'form', component: FormComponent, canDeactivate: [authorizeDeactivateGuard] }
|
|
1768
|
-
* ```
|
|
1769
|
-
*/
|
|
1770
852
|
const authorizeDeactivateGuard = () => true;
|
|
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
|
-
|
|
853
|
+
var TenantMismatchComponent = class TenantMismatchComponent {
|
|
854
|
+
authorizeService = inject(AuthorizeService);
|
|
855
|
+
route = inject(ActivatedRoute);
|
|
856
|
+
routeTenantId = computed(() => this.route.snapshot.paramMap.get("tenantId") ?? "", ...ngDevMode ? [{ debugName: "routeTenantId" }] : /* istanbul ignore next */ []);
|
|
857
|
+
tokenTenantId = this.authorizeService.tokenTenantId;
|
|
858
|
+
signInButton = viewChild("signInButton", ...ngDevMode ? [{ debugName: "signInButton" }] : /* istanbul ignore next */ []);
|
|
859
|
+
signedInAs = computed(() => {
|
|
860
|
+
const current = this.tokenTenantId();
|
|
861
|
+
return current ? `You are signed in to ${current}.` : "You are signed in to a different tenant.";
|
|
862
|
+
}, ...ngDevMode ? [{ debugName: "signedInAs" }] : /* istanbul ignore next */ []);
|
|
863
|
+
retried = computed(() => this.authorizeService.isTenantSignInRetried(this.routeTenantId()), ...ngDevMode ? [{ debugName: "retried" }] : /* istanbul ignore next */ []);
|
|
864
|
+
otherTenants = computed(() => this.authorizeService.allowedTenants().filter((t) => t.toLowerCase() !== (this.tokenTenantId() ?? "").toLowerCase()), ...ngDevMode ? [{ debugName: "otherTenants" }] : /* istanbul ignore next */ []);
|
|
865
|
+
constructor() {
|
|
866
|
+
effect(() => this.signInButton()?.nativeElement.focus());
|
|
867
|
+
}
|
|
868
|
+
signIn() {
|
|
869
|
+
const tenantId = this.routeTenantId();
|
|
870
|
+
this.authorizeService.retryTenantSignIn(tenantId, `${window.location.origin}/${tenantId}`);
|
|
871
|
+
}
|
|
872
|
+
static ɵfac = i0.ɵɵngDeclareFactory({
|
|
873
|
+
minVersion: "12.0.0",
|
|
874
|
+
version: "22.3.0",
|
|
875
|
+
ngImport: i0,
|
|
876
|
+
type: TenantMismatchComponent,
|
|
877
|
+
deps: [],
|
|
878
|
+
target: i0.ɵɵFactoryTarget.Component
|
|
879
|
+
});
|
|
880
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({
|
|
881
|
+
minVersion: "17.0.0",
|
|
882
|
+
version: "22.3.0",
|
|
883
|
+
type: TenantMismatchComponent,
|
|
884
|
+
isStandalone: true,
|
|
885
|
+
selector: "mm-tenant-mismatch",
|
|
886
|
+
viewQueries: [{
|
|
887
|
+
propertyName: "signInButton",
|
|
888
|
+
first: true,
|
|
889
|
+
predicate: ["signInButton"],
|
|
890
|
+
descendants: true,
|
|
891
|
+
isSignal: true
|
|
892
|
+
}],
|
|
893
|
+
ngImport: i0,
|
|
894
|
+
template: `
|
|
1812
895
|
<div class="mm-tenant-mismatch">
|
|
1813
896
|
<section class="mm-tenant-mismatch__panel" aria-labelledby="mm-tenant-mismatch-title">
|
|
1814
897
|
<span class="mm-tenant-mismatch__chip">Access denied</span>
|
|
@@ -1843,11 +926,44 @@ class TenantMismatchComponent {
|
|
|
1843
926
|
}
|
|
1844
927
|
</section>
|
|
1845
928
|
</div>
|
|
1846
|
-
`,
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
929
|
+
`,
|
|
930
|
+
isInline: true,
|
|
931
|
+
styles: [":host{display:flex;flex:1;width:100%}.mm-tenant-mismatch{display:grid;place-items:center;flex:1;padding:2rem 1rem;background:var(--kendo-color-app-surface);color:var(--kendo-color-on-app-surface)}.mm-tenant-mismatch__panel{display:grid;justify-items:start;gap:.75rem;width:min(480px,100%);padding:1.5rem;background:var(--kendo-color-surface);border:1px solid var(--kendo-color-border);border-radius:var(--kendo-border-radius-md, 4px)}h1{margin:0;font-size:1.25rem;font-weight:600}.mm-tenant-mismatch__chip{display:inline-flex;align-items:center;height:20px;padding:0 7px;border-radius:2px;font-size:.71875rem;font-weight:500;color:var(--kendo-color-error);background:color-mix(in srgb,var(--kendo-color-error) 15%,transparent)}.mm-tenant-mismatch__hint{color:var(--kendo-color-subtle)}p{margin:0}code{font-family:var(--kendo-font-family-monospace, monospace)}.mm-tenant-mismatch__tenants{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}.mm-tenant-mismatch__link{color:var(--kendo-color-primary)}\n"],
|
|
932
|
+
dependencies: [{
|
|
933
|
+
kind: "directive",
|
|
934
|
+
type: RouterLink,
|
|
935
|
+
selector: "[routerLink]",
|
|
936
|
+
inputs: [
|
|
937
|
+
"target",
|
|
938
|
+
"queryParams",
|
|
939
|
+
"fragment",
|
|
940
|
+
"queryParamsHandling",
|
|
941
|
+
"state",
|
|
942
|
+
"info",
|
|
943
|
+
"relativeTo",
|
|
944
|
+
"preserveFragment",
|
|
945
|
+
"skipLocationChange",
|
|
946
|
+
"replaceUrl",
|
|
947
|
+
"browserUrl",
|
|
948
|
+
"scroll",
|
|
949
|
+
"routerLink"
|
|
950
|
+
]
|
|
951
|
+
}],
|
|
952
|
+
changeDetection: i0.ChangeDetectionStrategy.OnPush
|
|
953
|
+
});
|
|
954
|
+
};
|
|
955
|
+
i0.ɵɵngDeclareClassMetadata({
|
|
956
|
+
minVersion: "12.0.0",
|
|
957
|
+
version: "22.3.0",
|
|
958
|
+
ngImport: i0,
|
|
959
|
+
type: TenantMismatchComponent,
|
|
960
|
+
decorators: [{
|
|
961
|
+
type: Component,
|
|
962
|
+
args: [{
|
|
963
|
+
selector: "mm-tenant-mismatch",
|
|
964
|
+
imports: [RouterLink],
|
|
965
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
966
|
+
template: `
|
|
1851
967
|
<div class="mm-tenant-mismatch">
|
|
1852
968
|
<section class="mm-tenant-mismatch__panel" aria-labelledby="mm-tenant-mismatch-title">
|
|
1853
969
|
<span class="mm-tenant-mismatch__chip">Access denied</span>
|
|
@@ -1882,267 +998,193 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImpor
|
|
|
1882
998
|
}
|
|
1883
999
|
</section>
|
|
1884
1000
|
</div>
|
|
1885
|
-
`,
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1001
|
+
`,
|
|
1002
|
+
styles: [":host{display:flex;flex:1;width:100%}.mm-tenant-mismatch{display:grid;place-items:center;flex:1;padding:2rem 1rem;background:var(--kendo-color-app-surface);color:var(--kendo-color-on-app-surface)}.mm-tenant-mismatch__panel{display:grid;justify-items:start;gap:.75rem;width:min(480px,100%);padding:1.5rem;background:var(--kendo-color-surface);border:1px solid var(--kendo-color-border);border-radius:var(--kendo-border-radius-md, 4px)}h1{margin:0;font-size:1.25rem;font-weight:600}.mm-tenant-mismatch__chip{display:inline-flex;align-items:center;height:20px;padding:0 7px;border-radius:2px;font-size:.71875rem;font-weight:500;color:var(--kendo-color-error);background:color-mix(in srgb,var(--kendo-color-error) 15%,transparent)}.mm-tenant-mismatch__hint{color:var(--kendo-color-subtle)}p{margin:0}code{font-family:var(--kendo-font-family-monospace, monospace)}.mm-tenant-mismatch__tenants{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center}.mm-tenant-mismatch__link{color:var(--kendo-color-primary)}\n"]
|
|
1003
|
+
}]
|
|
1004
|
+
}],
|
|
1005
|
+
ctorParameters: () => [],
|
|
1006
|
+
propDecorators: { signInButton: [{
|
|
1007
|
+
type: i0.ViewChild,
|
|
1008
|
+
args: ["signInButton", { isSignal: true }]
|
|
1009
|
+
}] }
|
|
1010
|
+
});
|
|
1895
1011
|
function topologyLeaves(result) {
|
|
1896
|
-
|
|
1012
|
+
return result.topologyKnown ? result.tenants.filter((t) => !t.hasChildren) : [];
|
|
1897
1013
|
}
|
|
1898
|
-
/** Direct children of the scope (depth 1). Empty when unknown. */
|
|
1899
1014
|
function topologyDirectChildren(result) {
|
|
1900
|
-
|
|
1015
|
+
return result.topologyKnown ? result.tenants.filter((t) => t.depth === 1) : [];
|
|
1901
1016
|
}
|
|
1902
|
-
/** All tenant ids of the result. Empty when unknown. */
|
|
1903
1017
|
function topologyTenantIds(result) {
|
|
1904
|
-
|
|
1018
|
+
return result.topologyKnown ? result.tenants.map((t) => t.tenantId) : [];
|
|
1905
1019
|
}
|
|
1906
|
-
/** Test helper for app specs: a known topology. */
|
|
1907
1020
|
function knownTopology(scope, nodes, scopeHasChildren = nodes.length > 0) {
|
|
1908
|
-
|
|
1021
|
+
return {
|
|
1022
|
+
topologyKnown: true,
|
|
1023
|
+
scope,
|
|
1024
|
+
scopeHasChildren,
|
|
1025
|
+
tenants: nodes.map((n) => ({ ...n }))
|
|
1026
|
+
};
|
|
1909
1027
|
}
|
|
1910
|
-
/** Test helper for app specs: an unknown topology with the given reason. */
|
|
1911
1028
|
function unknownTopology(reason) {
|
|
1912
|
-
|
|
1029
|
+
return {
|
|
1030
|
+
topologyKnown: false,
|
|
1031
|
+
reason,
|
|
1032
|
+
tenants: [],
|
|
1033
|
+
scopeHasChildren: null
|
|
1034
|
+
};
|
|
1913
1035
|
}
|
|
1914
|
-
|
|
1915
|
-
/** What identity accepts as a tenant id: at most 64 ASCII letters, digits, `-` or `_`. */
|
|
1916
1036
|
const TENANT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
1917
|
-
const REQUEST_TIMEOUT_MS =
|
|
1918
|
-
const LOG_PREFIX =
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
const status = error instanceof HttpErrorResponse ? error.status : 0;
|
|
2028
|
-
// A 2xx that the HttpClient could not parse as JSON: html means an old identity, anything else is malformed.
|
|
2029
|
-
if (error instanceof HttpErrorResponse && status >= 200 && status < 300) {
|
|
2030
|
-
return this.unknown(isNonJsonContentType(error.headers.get('Content-Type')) ? 'identity-too-old' : 'invalid-response', scope, status);
|
|
2031
|
-
}
|
|
2032
|
-
return this.unknown(reasonForStatus(status), scope, status);
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
unknown(reason, scope, status) {
|
|
2036
|
-
console.debug(`${LOG_PREFIX}: topology of scope "${scope}" is unknown (${reason}${status ? `, HTTP ${status}` : ''})`);
|
|
2037
|
-
return unknownTopology(reason);
|
|
2038
|
-
}
|
|
2039
|
-
isCacheable(result) {
|
|
2040
|
-
return result.topologyKnown || result.reason === 'identity-too-old';
|
|
2041
|
-
}
|
|
2042
|
-
cacheKey(scope, token) {
|
|
2043
|
-
const tenant = (tenantIdFromToken(token) ?? '').toLowerCase();
|
|
2044
|
-
const allowed = [...new Set(allowedTenantsFromToken(token).map((t) => t.toLowerCase()))].sort();
|
|
2045
|
-
return JSON.stringify([scope.toLowerCase(), tenant, allowed]);
|
|
2046
|
-
}
|
|
2047
|
-
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: TenantTopologyService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
2048
|
-
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: TenantTopologyService, providedIn: 'root' });
|
|
2049
|
-
}
|
|
2050
|
-
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.5", ngImport: i0, type: TenantTopologyService, decorators: [{
|
|
2051
|
-
type: Injectable,
|
|
2052
|
-
args: [{ providedIn: 'root' }]
|
|
2053
|
-
}], ctorParameters: () => [] });
|
|
2054
|
-
/** True when a content type is present and is not JSON (`application/json`, `application/problem+json`, ...). */
|
|
1037
|
+
const REQUEST_TIMEOUT_MS = 1e4;
|
|
1038
|
+
const LOG_PREFIX = "TenantTopologyService";
|
|
1039
|
+
var TenantTopologyService = class TenantTopologyService {
|
|
1040
|
+
authorizeService = inject(AuthorizeService);
|
|
1041
|
+
http = new HttpClient(inject(HttpBackend));
|
|
1042
|
+
cache = /* @__PURE__ */ new Map();
|
|
1043
|
+
inFlight = /* @__PURE__ */ new Map();
|
|
1044
|
+
generation = 0;
|
|
1045
|
+
constructor() {
|
|
1046
|
+
let wasAuthenticated = false;
|
|
1047
|
+
effect(() => {
|
|
1048
|
+
const authenticated = this.authorizeService.isAuthenticated();
|
|
1049
|
+
if (wasAuthenticated && !authenticated) this.clearCache();
|
|
1050
|
+
wasAuthenticated = authenticated;
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
load(scope, options) {
|
|
1054
|
+
try {
|
|
1055
|
+
return this.loadCore(scope, options?.refresh === true);
|
|
1056
|
+
} catch {
|
|
1057
|
+
return Promise.resolve(unknownTopology("not-configured"));
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
clearCache() {
|
|
1061
|
+
this.generation++;
|
|
1062
|
+
this.cache.clear();
|
|
1063
|
+
this.inFlight.clear();
|
|
1064
|
+
}
|
|
1065
|
+
loadCore(scope, refresh) {
|
|
1066
|
+
const issuer = (this.authorizeService.issuer() ?? "").trim().replace(/\/+$/, "");
|
|
1067
|
+
const token = this.authorizeService.getAccessTokenSync();
|
|
1068
|
+
if (!/^https?:\/\/[^\s/?#]+/i.test(issuer) || !token) return Promise.resolve(unknownTopology("not-configured"));
|
|
1069
|
+
if (typeof scope !== "string" || !TENANT_ID_PATTERN.test(scope)) return Promise.resolve(unknownTopology("not-configured"));
|
|
1070
|
+
const key = this.cacheKey(scope, token);
|
|
1071
|
+
if (refresh) this.cache.delete(key);
|
|
1072
|
+
else {
|
|
1073
|
+
const cached = this.cache.get(key);
|
|
1074
|
+
if (cached) return Promise.resolve(cached);
|
|
1075
|
+
const pending = this.inFlight.get(key);
|
|
1076
|
+
if (pending) return pending;
|
|
1077
|
+
}
|
|
1078
|
+
const generation = this.generation;
|
|
1079
|
+
const request = this.fetch(issuer, scope, token).then((result) => {
|
|
1080
|
+
if (this.inFlight.get(key) === request) this.inFlight.delete(key);
|
|
1081
|
+
if (generation === this.generation && this.isCacheable(result)) this.cache.set(key, result);
|
|
1082
|
+
return result;
|
|
1083
|
+
});
|
|
1084
|
+
this.inFlight.set(key, request);
|
|
1085
|
+
return request;
|
|
1086
|
+
}
|
|
1087
|
+
async fetch(issuer, scope, token) {
|
|
1088
|
+
try {
|
|
1089
|
+
const response = await firstValueFrom(this.http.get(`${issuer}/api/tenant-topology`, {
|
|
1090
|
+
params: { scope },
|
|
1091
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1092
|
+
observe: "response"
|
|
1093
|
+
}).pipe(timeout(REQUEST_TIMEOUT_MS)));
|
|
1094
|
+
if (isNonJsonContentType(response.headers.get("Content-Type"))) return this.unknown("identity-too-old", scope, response.status);
|
|
1095
|
+
const parsed = parseResponse(response.body, scope);
|
|
1096
|
+
if (!parsed) return this.unknown("invalid-response", scope);
|
|
1097
|
+
return parsed;
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
const status = error instanceof HttpErrorResponse ? error.status : 0;
|
|
1100
|
+
if (error instanceof HttpErrorResponse && status >= 200 && status < 300) return this.unknown(isNonJsonContentType(error.headers.get("Content-Type")) ? "identity-too-old" : "invalid-response", scope, status);
|
|
1101
|
+
return this.unknown(reasonForStatus(status), scope, status);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
unknown(reason, scope, status) {
|
|
1105
|
+
console.debug(`${LOG_PREFIX}: topology of scope "${scope}" is unknown (${reason}${status ? `, HTTP ${status}` : ""})`);
|
|
1106
|
+
return unknownTopology(reason);
|
|
1107
|
+
}
|
|
1108
|
+
isCacheable(result) {
|
|
1109
|
+
return result.topologyKnown || result.reason === "identity-too-old";
|
|
1110
|
+
}
|
|
1111
|
+
cacheKey(scope, token) {
|
|
1112
|
+
const tenant = (tenantIdFromToken(token) ?? "").toLowerCase();
|
|
1113
|
+
const allowed = [...new Set(allowedTenantsFromToken(token).map((t) => t.toLowerCase()))].sort();
|
|
1114
|
+
return JSON.stringify([
|
|
1115
|
+
scope.toLowerCase(),
|
|
1116
|
+
tenant,
|
|
1117
|
+
allowed
|
|
1118
|
+
]);
|
|
1119
|
+
}
|
|
1120
|
+
static ɵfac = i0.ɵɵngDeclareFactory({
|
|
1121
|
+
minVersion: "12.0.0",
|
|
1122
|
+
version: "22.3.0",
|
|
1123
|
+
ngImport: i0,
|
|
1124
|
+
type: TenantTopologyService,
|
|
1125
|
+
deps: [],
|
|
1126
|
+
target: i0.ɵɵFactoryTarget.Injectable
|
|
1127
|
+
});
|
|
1128
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({
|
|
1129
|
+
minVersion: "12.0.0",
|
|
1130
|
+
version: "22.3.0",
|
|
1131
|
+
ngImport: i0,
|
|
1132
|
+
type: TenantTopologyService,
|
|
1133
|
+
providedIn: "root"
|
|
1134
|
+
});
|
|
1135
|
+
};
|
|
1136
|
+
i0.ɵɵngDeclareClassMetadata({
|
|
1137
|
+
minVersion: "12.0.0",
|
|
1138
|
+
version: "22.3.0",
|
|
1139
|
+
ngImport: i0,
|
|
1140
|
+
type: TenantTopologyService,
|
|
1141
|
+
decorators: [{
|
|
1142
|
+
type: Injectable,
|
|
1143
|
+
args: [{ providedIn: "root" }]
|
|
1144
|
+
}],
|
|
1145
|
+
ctorParameters: () => []
|
|
1146
|
+
});
|
|
2055
1147
|
function isNonJsonContentType(contentType) {
|
|
2056
|
-
|
|
2057
|
-
|
|
1148
|
+
const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
1149
|
+
return type !== "" && type !== "application/json" && !type.endsWith("+json");
|
|
2058
1150
|
}
|
|
2059
1151
|
function reasonForStatus(status) {
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
return 'rate-limited';
|
|
2070
|
-
case 503:
|
|
2071
|
-
return 'hierarchy-unreadable';
|
|
2072
|
-
default:
|
|
2073
|
-
// 0 (transport error, CORS, timeout), 502, 504 and other 5xx are transient; any other
|
|
2074
|
-
// status is not part of the contract.
|
|
2075
|
-
return status === 0 || status >= 500 ? 'network' : 'invalid-response';
|
|
2076
|
-
}
|
|
1152
|
+
switch (status) {
|
|
1153
|
+
case 400: return "not-configured";
|
|
1154
|
+
case 401:
|
|
1155
|
+
case 403: return "unauthorized";
|
|
1156
|
+
case 404: return "identity-too-old";
|
|
1157
|
+
case 429: return "rate-limited";
|
|
1158
|
+
case 503: return "hierarchy-unreadable";
|
|
1159
|
+
default: return status === 0 || status >= 500 ? "network" : "invalid-response";
|
|
1160
|
+
}
|
|
2077
1161
|
}
|
|
2078
|
-
/** Validates the body against the contract and copies exactly the known fields; null when it does not fit. */
|
|
2079
1162
|
function parseResponse(body, requestedScope) {
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
typeof hasChildren !== 'boolean') {
|
|
2102
|
-
return null;
|
|
2103
|
-
}
|
|
2104
|
-
nodes.push({ tenantId, depth, hasChildren });
|
|
2105
|
-
}
|
|
2106
|
-
return { topologyKnown: true, scope, scopeHasChildren, tenants: nodes };
|
|
1163
|
+
if (typeof body !== "object" || body === null) return null;
|
|
1164
|
+
const { scope, scopeHasChildren, tenants } = body;
|
|
1165
|
+
if (typeof scope !== "string" || scope.toLowerCase() !== requestedScope.toLowerCase()) return null;
|
|
1166
|
+
if (typeof scopeHasChildren !== "boolean" || !Array.isArray(tenants)) return null;
|
|
1167
|
+
const nodes = [];
|
|
1168
|
+
for (const entry of tenants) {
|
|
1169
|
+
if (typeof entry !== "object" || entry === null) return null;
|
|
1170
|
+
const { tenantId, depth, hasChildren } = entry;
|
|
1171
|
+
if (typeof tenantId !== "string" || tenantId.length === 0 || typeof depth !== "number" || !Number.isInteger(depth) || depth < 1 || typeof hasChildren !== "boolean") return null;
|
|
1172
|
+
nodes.push({
|
|
1173
|
+
tenantId,
|
|
1174
|
+
depth,
|
|
1175
|
+
hasChildren
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
return {
|
|
1179
|
+
topologyKnown: true,
|
|
1180
|
+
scope,
|
|
1181
|
+
scopeHasChildren,
|
|
1182
|
+
tenants: nodes
|
|
1183
|
+
};
|
|
2107
1184
|
}
|
|
2108
|
-
|
|
2109
|
-
/*
|
|
2110
|
-
* Public API Surface of shared-auth
|
|
2111
|
-
*/
|
|
2112
|
-
// UI Components (Kendo) - available via '@meshmakers/shared-auth/login-ui'
|
|
2113
|
-
// import { LoginAppBarSectionComponent } from '@meshmakers/shared-auth/login-ui';
|
|
2114
|
-
/**
|
|
2115
|
-
* Provides all shared-auth dependencies.
|
|
2116
|
-
*
|
|
2117
|
-
* @example
|
|
2118
|
-
* ```typescript
|
|
2119
|
-
* // app.config.ts
|
|
2120
|
-
* import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
|
2121
|
-
* import { provideMmSharedAuth, authorizeInterceptor } from '@meshmakers/shared-auth';
|
|
2122
|
-
*
|
|
2123
|
-
* export const appConfig: ApplicationConfig = {
|
|
2124
|
-
* providers: [
|
|
2125
|
-
* provideHttpClient(withInterceptors([authorizeInterceptor])),
|
|
2126
|
-
* provideMmSharedAuth(),
|
|
2127
|
-
* // ... other providers
|
|
2128
|
-
* ]
|
|
2129
|
-
* };
|
|
2130
|
-
* ```
|
|
2131
|
-
*
|
|
2132
|
-
* @remarks
|
|
2133
|
-
* Functional guards and interceptors don't need to be provided - they use inject() internally.
|
|
2134
|
-
* For the functional interceptor, use `provideHttpClient(withInterceptors([authorizeInterceptor]))`.
|
|
2135
|
-
*/
|
|
2136
1185
|
function provideMmSharedAuth() {
|
|
2137
|
-
|
|
2138
|
-
provideOAuthClient(),
|
|
2139
|
-
AuthorizeService
|
|
2140
|
-
]);
|
|
1186
|
+
return makeEnvironmentProviders([provideOAuthClient(), AuthorizeService]);
|
|
2141
1187
|
}
|
|
2142
|
-
|
|
2143
|
-
/**
|
|
2144
|
-
* Generated bundle index. Do not edit.
|
|
2145
|
-
*/
|
|
2146
|
-
|
|
2147
1188
|
export { AuthorizeOptions, AuthorizeService, Roles, SESSION_IDENTITY_SINK, TENANT_MISMATCH_PATH, TenantAwareOAuthStorage, TenantMismatchComponent, TenantTopologyService, allowedTenantsFromToken, authorizationRefusal, authorizeChildGuard, authorizeDeactivateGuard, authorizeGuard, authorizeInterceptor, authorizeMatchGuard, decodeJwtPayload, knownTopology, provideMmSharedAuth, tenantIdFromToken, topologyDirectChildren, topologyLeaves, topologyTenantIds, unknownTopology };
|
|
2148
|
-
|
|
1189
|
+
|
|
1190
|
+
//# sourceMappingURL=meshmakers-shared-auth.mjs.map
|