@classic-homes/auth 1.47.0 → 1.50.0

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/README.md CHANGED
@@ -184,11 +184,33 @@ if (!accepted) {
184
184
  ```
185
185
 
186
186
  Set `sso.requireClientState: true` once the API echoing `client_state` is
187
- deployed to that environment. Until then (the default) every result is
188
- accepted, so log `result` to watch the rollout.
187
+ deployed to that environment (CHAPI does since the 2026-11 security release).
188
+ Until then (the default) every result is accepted, so log `result` to watch the
189
+ rollout.
189
190
 
190
191
  ### 5. MFA Challenge Verification
191
192
 
193
+ The MFA challenge page gets its token from the URL hash (`#mfaChallengeToken=…`),
194
+ either from the SSO callback or from your own password sign-in. Accept it only
195
+ when it is bound to this tab: `acceptMfaChallengeHash` checks the echoed
196
+ `client_state` (SSO; consumed) or compares the token with the one
197
+ `authService.login()` remembered when it returned the challenge (password).
198
+ A hash token matching neither came from a link someone else made.
199
+
200
+ ```typescript
201
+ import { acceptMfaChallengeHash } from '@classic-homes/auth/core';
202
+
203
+ const { accepted, token, via, result } = acceptMfaChallengeHash(window.location.hash);
204
+ window.history.replaceState({}, '', window.location.pathname); // drop the token from the URL
205
+ if (!accepted || !token) goto('/auth/login');
206
+ ```
207
+
208
+ It follows `sso.requireClientState` like `verifySsoClientState`. If you call
209
+ `authApi.login` directly (not `authService.login`), call
210
+ `rememberMfaChallengeToken(mfaToken)` yourself before navigating to the MFA
211
+ page; `authService.verifyMFAChallenge` clears it on success
212
+ (`clearMfaChallengeToken()` for a cancel).
213
+
192
214
  ```typescript
193
215
  import { authService } from '@classic-homes/auth/core';
194
216
 
@@ -206,6 +228,48 @@ async function handleMFAVerify(mfaToken: string, code: string, trustDevice: bool
206
228
  }
207
229
  ```
208
230
 
231
+ ### SSO account linking
232
+
233
+ `authService.linkAccount(provider, { callback? })` (`authApi.linkSSOAccount`)
234
+ sends the signed-in user to the IdP. CHAPI then redirects back to `callback`
235
+ with `?link=pending#sso_link_code=<code>` (or `?link=error&message=…`) and
236
+ **links nothing** until the same signed-in user posts that one-time code back.
237
+
238
+ `callback` defaults to the page the link started from
239
+ (`location.origin + location.pathname`), so the user lands where they clicked
240
+ "Link". Its origin must be on CHAPI's SSO allowlist (same rule as the authorize
241
+ endpoint's `callback`). Pass an absolute URL to return elsewhere, or
242
+ `callback: null` to send none (CHAPI then uses its own web `/account` page).
243
+ A callback with its own query (`/account?tab=linked-accounts`) is fine: CHAPI
244
+ adds `link`, and `readSsoLinkResult()` removes only `link`, `message` and
245
+ `sso_link_code`.
246
+
247
+ The authorization URL CHAPI returns is the identity provider's page, so it is
248
+ **not** checked against `allowedRedirectOrigins` (your app's origins). It must
249
+ be https, or, when `sso.idpOrigins` is set (e.g. `['https://auth.example.com']`),
250
+ on one of those origins, `sso.logoutOrigins`, the `authorizeUrl` origin or the
251
+ API origin.
252
+
253
+ On the callback page (any path):
254
+
255
+ ```typescript
256
+ import { authService, isApiError, readSsoLinkResult } from '@classic-homes/auth/core';
257
+
258
+ const link = readSsoLinkResult(); // reads and strips link/message/sso_link_code from the URL
259
+ if (link?.status === 'pending') {
260
+ try {
261
+ const { provider } = await authService.completeSSOLink(link.code);
262
+ toast.success(`Linked your ${provider} account`);
263
+ } catch (error) {
264
+ // 400: unknown, expired or already-used code, or the SSO account is linked to another user
265
+ // 403: started by a different account, or the IdP email is unverified / not this account's
266
+ toast.error(isApiError(error) ? error.message : 'Linking failed');
267
+ }
268
+ } else if (link?.status === 'error') {
269
+ toast.error(link.message ?? 'Linking failed');
270
+ }
271
+ ```
272
+
209
273
  ### 6. Protect Routes
210
274
 
211
275
  ```typescript
@@ -400,6 +464,13 @@ import {
400
464
  // API
401
465
  authApi,
402
466
 
467
+ // SSO / MFA binding and account linking
468
+ verifySsoClientState,
469
+ acceptMfaChallengeHash,
470
+ rememberMfaChallengeToken,
471
+ clearMfaChallengeToken,
472
+ readSsoLinkResult,
473
+
403
474
  // MFA Guards
404
475
  isMfaChallengeResponse,
405
476
  isLoginSuccessResponse,
@@ -491,6 +562,10 @@ interface AuthConfig {
491
562
  authorizeUrl?: string;
492
563
  /** Reject SSO callbacks whose client_state is missing or wrong (default false) */
493
564
  requireClientState?: boolean;
565
+ /** Origins the IdP's logout URL may be on */
566
+ logoutOrigins?: string[];
567
+ /** Origins linkSSOAccount may follow the IdP authorization URL to (unset: any https) */
568
+ idpOrigins?: string[];
494
569
  };
495
570
 
496
571
  /** Callback when auth errors occur */
@@ -0,0 +1,3 @@
1
+ export { authActions, authStore, currentUser, isAuthenticated } from './chunk-WARTLLDA.js';
2
+ import './chunk-AY7AKNQT.js';
3
+ import './chunk-SMPUGWF7.js';
@@ -1,4 +1,4 @@
1
- import { isInitialized, getConfig, getUserRoles, clearAccessSubject, getStorage, isTokenExpired, getFetch, isAccessProbeActive, isValidRedirectUrl, ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, parseRedactedHeader, reportAccess, requirementFromDenial, decodeJWT } from './chunk-TANYGU4O.js';
1
+ import { isInitialized, getConfig, getUserRoles, clearAccessSubject, getStorage, isTokenExpired, getFetch, isAccessProbeActive, isValidSSOAuthorizationUrl, isValidRedirectUrl, ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, parseRedactedHeader, reportAccess, requirementFromDenial, decodeJWT } from './chunk-SMPUGWF7.js';
2
2
 
3
3
  // src/core/sso-state.ts
4
4
  var SSO_CLIENT_STATE_PARAM = "client_state";
@@ -67,6 +67,52 @@ function verifySsoClientState(input) {
67
67
  const required = isInitialized() && getConfig().sso?.requireClientState === true;
68
68
  return { result, accepted: result === "ok" || !required };
69
69
  }
70
+ var MFA_CHALLENGE_TOKEN_PARAM = "mfaChallengeToken";
71
+ function mfaTokenKey() {
72
+ const prefix = isInitialized() ? getConfig().storageKey ?? "classic_auth" : "classic_auth";
73
+ return `${prefix}_mfa_challenge_token`;
74
+ }
75
+ function rememberMfaChallengeToken(token) {
76
+ const store = sessionStore();
77
+ if (!store || !token) return false;
78
+ try {
79
+ store.setItem(mfaTokenKey(), token);
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+ function clearMfaChallengeToken() {
86
+ const store = sessionStore();
87
+ if (!store) return;
88
+ try {
89
+ store.removeItem(mfaTokenKey());
90
+ } catch {
91
+ }
92
+ }
93
+ function rememberedMfaChallengeToken() {
94
+ const store = sessionStore();
95
+ if (!store) return null;
96
+ try {
97
+ return store.getItem(mfaTokenKey());
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+ function acceptMfaChallengeHash(input) {
103
+ const params = typeof input === "string" ? new URLSearchParams(input.replace(/^#/, "")) : input;
104
+ const token = params.get(MFA_CHALLENGE_TOKEN_PARAM);
105
+ const required = isInitialized() && getConfig().sso?.requireClientState === true;
106
+ if (!token) return { result: "missing", accepted: false, token: null, via: null };
107
+ const receivedState = params.get(SSO_CLIENT_STATE_PARAM);
108
+ if (receivedState !== null) {
109
+ const result2 = consumeSsoClientState(receivedState);
110
+ return { result: result2, accepted: result2 === "ok" || !required, token, via: "sso" };
111
+ }
112
+ const remembered = rememberedMfaChallengeToken();
113
+ const result = !remembered ? "missing" : timingSafeEqual(remembered, token) ? "ok" : "mismatch";
114
+ return { result, accepted: result === "ok" || !required, token, via: "password" };
115
+ }
70
116
 
71
117
  // src/core/errors.ts
72
118
  var RoleDeniedError = class _RoleDeniedError extends Error {
@@ -236,7 +282,7 @@ function writeStoredTokens(accessToken, refreshToken) {
236
282
  }
237
283
  async function syncSvelteStore(apply) {
238
284
  try {
239
- const { authStore } = await import('./auth.svelte-CPTJUC3O.js');
285
+ const { authStore } = await import('./auth.svelte-DSBVIXO5.js');
240
286
  apply(authStore);
241
287
  } catch {
242
288
  }
@@ -650,6 +696,24 @@ var api = {
650
696
  };
651
697
 
652
698
  // src/core/api.ts
699
+ function resolveLinkCallback(callback) {
700
+ if (callback === null) return void 0;
701
+ if (callback !== void 0) {
702
+ let parsed;
703
+ try {
704
+ parsed = new URL(callback);
705
+ } catch {
706
+ throw new Error("Invalid SSO link callback: must be an absolute URL");
707
+ }
708
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
709
+ throw new Error("Invalid SSO link callback: must be an http(s) URL");
710
+ }
711
+ return callback;
712
+ }
713
+ const origin = window.location?.origin;
714
+ if (!origin || origin === "null") return void 0;
715
+ return `${origin}${window.location.pathname ?? ""}`;
716
+ }
653
717
  async function fetchWithTimeout(url, init, read) {
654
718
  const config = getConfig();
655
719
  const fetchFn = config.fetch ?? fetch;
@@ -1069,14 +1133,24 @@ var authApi = {
1069
1133
  *
1070
1134
  * Initiates the SSO linking flow by making an authenticated API call.
1071
1135
  * The server returns an authorization URL to redirect the user to.
1136
+ * After the IdP, CHAPI returns the user to `callback` with
1137
+ * `?link=pending#sso_link_code=…` (or `?link=error&message=…`); nothing is
1138
+ * linked until that page calls `completeSSOLink(code)` (read the code with
1139
+ * `readSsoLinkResult()`).
1140
+ *
1141
+ * @param options.callback - Absolute URL to come back to; its origin must be
1142
+ * on CHAPI's SSO allowlist. Defaults to the current page
1143
+ * (`location.origin + location.pathname`). Pass `null` to send none
1144
+ * (CHAPI then uses its own web `/account` page).
1072
1145
  */
1073
- async linkSSOAccount(provider = "authentik") {
1146
+ async linkSSOAccount(provider = "authentik", options = {}) {
1074
1147
  if (typeof window === "undefined") return;
1075
1148
  const accessToken = getAccessToken();
1076
1149
  if (!accessToken) {
1077
1150
  throw new Error("Not authenticated");
1078
1151
  }
1079
1152
  const config = getConfig();
1153
+ const callback = resolveLinkCallback(options.callback);
1080
1154
  const result = await fetchWithTimeout(
1081
1155
  `${config.baseUrl}/auth/sso/link`,
1082
1156
  {
@@ -1085,7 +1159,7 @@ var authApi = {
1085
1159
  "Content-Type": "application/json",
1086
1160
  Authorization: `Bearer ${accessToken}`
1087
1161
  },
1088
- body: JSON.stringify({ provider })
1162
+ body: JSON.stringify(callback ? { provider, callback } : { provider })
1089
1163
  },
1090
1164
  async (response) => {
1091
1165
  if (!response.ok) {
@@ -1097,14 +1171,35 @@ var authApi = {
1097
1171
  );
1098
1172
  const authorizationUrl = extractData(result).authorizationUrl;
1099
1173
  if (authorizationUrl) {
1100
- if (!isValidRedirectUrl(authorizationUrl)) {
1174
+ if (!isValidSSOAuthorizationUrl(authorizationUrl)) {
1101
1175
  throw new Error(
1102
- "SSO link failed: authorization URL is not in the list of allowed redirect origins"
1176
+ "SSO link failed: authorization URL is not an allowed identity provider URL (see sso.idpOrigins)"
1103
1177
  );
1104
1178
  }
1105
1179
  window.location.href = authorizationUrl;
1106
1180
  }
1107
1181
  },
1182
+ /**
1183
+ * Finish linking an SSO account (`POST /auth/sso/link/complete`).
1184
+ *
1185
+ * After the IdP, CHAPI redirects to the link `callback` (the page that
1186
+ * started it) with `?link=pending#sso_link_code=…` and writes no link until the signed-in user who started it sends that
1187
+ * one-time code here. Throws `ApiError`: 400 for an unknown, expired or used
1188
+ * code (or an SSO account already linked to another user), 403 when the
1189
+ * link was started by a different account or the IdP email is unverified or
1190
+ * differs from the account email.
1191
+ */
1192
+ async completeSSOLink(code) {
1193
+ const response = await apiRequest(
1194
+ "/auth/sso/link/complete",
1195
+ {
1196
+ method: "POST",
1197
+ body: { code },
1198
+ authenticated: true
1199
+ }
1200
+ );
1201
+ return extractData(response);
1202
+ },
1108
1203
  // ============================================================================
1109
1204
  // Security Events
1110
1205
  // ============================================================================
@@ -1194,4 +1289,4 @@ var authApi = {
1194
1289
  }
1195
1290
  };
1196
1291
 
1197
- export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, api, apiRequest, authApi, bumpSessionGeneration, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, updateStoredTokens, verifySsoClientState };
1292
+ export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, MFA_CHALLENGE_TOKEN_PARAM, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, acceptMfaChallengeHash, api, apiRequest, authApi, bumpSessionGeneration, clearMfaChallengeToken, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, rememberMfaChallengeToken, updateStoredTokens, verifySsoClientState };
@@ -1,6 +1,6 @@
1
- import { authService } from './chunk-GAN4LIB2.js';
2
- import { authStore, currentUser, isAuthenticated, authActions } from './chunk-HWV4ZEZM.js';
3
- import { evaluateAccess, effectiveSubject, isAccessProbeActive, reportDecision, isInitialized, initAuth } from './chunk-TANYGU4O.js';
1
+ import { authService } from './chunk-YJUWI2VL.js';
2
+ import { authStore, currentUser, isAuthenticated, authActions } from './chunk-WARTLLDA.js';
3
+ import { evaluateAccess, effectiveSubject, isAccessProbeActive, reportDecision, isInitialized, initAuth } from './chunk-SMPUGWF7.js';
4
4
 
5
5
  // src/svelte/guards/auth-guard.ts
6
6
  function checkAuth(options = {}) {
@@ -140,6 +140,29 @@ function isValidSSOLogoutUrl(url) {
140
140
  }
141
141
  });
142
142
  }
143
+ function isValidSSOAuthorizationUrl(url) {
144
+ const cfg = getConfig();
145
+ let parsed;
146
+ try {
147
+ parsed = new URL(url);
148
+ } catch {
149
+ return false;
150
+ }
151
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
152
+ const idpOrigins = cfg.sso?.idpOrigins ?? [];
153
+ const listed = [...idpOrigins, ...cfg.sso?.logoutOrigins ?? [], cfg.baseUrl];
154
+ if (cfg.sso?.authorizeUrl) listed.push(cfg.sso.authorizeUrl);
155
+ const onListedOrigin = listed.some((origin) => {
156
+ try {
157
+ return new URL(origin).origin === parsed.origin;
158
+ } catch {
159
+ return false;
160
+ }
161
+ });
162
+ if (onListedOrigin) return true;
163
+ if (idpOrigins.length > 0) return false;
164
+ return parsed.protocol === "https:";
165
+ }
143
166
 
144
167
  // src/core/jwt.ts
145
168
  function decodeJWT(token) {
@@ -411,4 +434,4 @@ function hasAllRoles(user, roles) {
411
434
  return allowed;
412
435
  }
413
436
 
414
- export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, isValidRedirectUrl, isValidSSOLogoutUrl, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject };
437
+ export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, isValidRedirectUrl, isValidSSOAuthorizationUrl, isValidSSOLogoutUrl, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject };
@@ -1,5 +1,5 @@
1
- import { InvalidAuthResponseError, bumpSessionGeneration, authApi } from './chunk-4Q3R4TTI.js';
2
- import { onAccessSubjectChange, isInitialized, getConfig, isValidSSOLogoutUrl, hasRole, hasAnyRole, hasAllRoles, effectiveSubject, reportDecision, decodeJWT, getStorage, getDefaultStorage } from './chunk-TANYGU4O.js';
1
+ import { InvalidAuthResponseError, bumpSessionGeneration, authApi } from './chunk-AY7AKNQT.js';
2
+ import { onAccessSubjectChange, isInitialized, getConfig, isValidSSOLogoutUrl, hasRole, hasAnyRole, hasAllRoles, effectiveSubject, reportDecision, decodeJWT, getStorage, getDefaultStorage } from './chunk-SMPUGWF7.js';
3
3
 
4
4
  // src/svelte/stores/auth.svelte.ts
5
5
  var STORAGE_VERSION = 2;
@@ -1,5 +1,34 @@
1
- import { authApi, InvalidAuthResponseError, RoleDeniedError } from './chunk-4Q3R4TTI.js';
2
- import { getUserRoles } from './chunk-TANYGU4O.js';
1
+ import { authApi, rememberMfaChallengeToken, InvalidAuthResponseError, RoleDeniedError, clearMfaChallengeToken } from './chunk-AY7AKNQT.js';
2
+ import { getUserRoles } from './chunk-SMPUGWF7.js';
3
+
4
+ // src/core/sso-link.ts
5
+ var SSO_LINK_CODE_PARAM = "sso_link_code";
6
+ var SSO_LINK_STATUS_PARAM = "link";
7
+ function readSsoLinkResult(options = {}) {
8
+ const fromWindow = options.url === void 0;
9
+ if (fromWindow && typeof window === "undefined") return null;
10
+ const url = new URL(fromWindow ? window.location.href : String(options.url));
11
+ const hash = new URLSearchParams(url.hash.replace(/^#/, ""));
12
+ const code = hash.get(SSO_LINK_CODE_PARAM);
13
+ const status = url.searchParams.get(SSO_LINK_STATUS_PARAM);
14
+ const message = url.searchParams.get("message");
15
+ let result = null;
16
+ if (code) result = { status: "pending", code };
17
+ else if (status === "error") result = { status: "error", message };
18
+ if (result && fromWindow && options.clear !== false) clearLinkParams(url, hash);
19
+ return result;
20
+ }
21
+ function clearLinkParams(url, hash) {
22
+ url.searchParams.delete(SSO_LINK_STATUS_PARAM);
23
+ url.searchParams.delete("message");
24
+ hash.delete(SSO_LINK_CODE_PARAM);
25
+ const rest = hash.toString();
26
+ url.hash = rest ? `#${rest}` : "";
27
+ try {
28
+ window.history.replaceState(window.history.state, "", url.toString());
29
+ } catch {
30
+ }
31
+ }
3
32
 
4
33
  // src/core/guards.ts
5
34
  function isMfaChallengeResponse(response) {
@@ -19,7 +48,7 @@ function getAvailableMethods(response) {
19
48
  async function setStoreAuth(response) {
20
49
  let store;
21
50
  try {
22
- store = (await import('./auth.svelte-CPTJUC3O.js')).authStore;
51
+ store = (await import('./auth.svelte-DSBVIXO5.js')).authStore;
23
52
  } catch {
24
53
  return;
25
54
  }
@@ -38,6 +67,8 @@ var AuthService = class {
38
67
  async login(credentials, options) {
39
68
  const response = await authApi.login(credentials);
40
69
  if (isMfaChallengeResponse(response)) {
70
+ const mfaToken = getMfaToken(response);
71
+ if (mfaToken) rememberMfaChallengeToken(mfaToken);
41
72
  return response;
42
73
  }
43
74
  if (!isLoginSuccessResponse(response)) {
@@ -223,6 +254,7 @@ var AuthService = class {
223
254
  if (!isLoginSuccessResponse(response)) {
224
255
  throw new InvalidAuthResponseError();
225
256
  }
257
+ clearMfaChallengeToken();
226
258
  if (options?.allowedRoles?.length) {
227
259
  if (!holdsAnyRole(response.user, options.allowedRoles)) {
228
260
  throw new RoleDeniedError(
@@ -310,10 +342,20 @@ var AuthService = class {
310
342
  return await authApi.getSSOAccounts(customFetch);
311
343
  }
312
344
  /**
313
- * Link an SSO account (redirects to SSO provider).
345
+ * Link an SSO account (redirects to SSO provider). The IdP round trip
346
+ * returns to `options.callback`, by default the current page; finish there
347
+ * with `readSsoLinkResult()` + `completeSSOLink(code)`.
348
+ */
349
+ async linkAccount(provider = "authentik", options) {
350
+ await authApi.linkSSOAccount(provider, options);
351
+ }
352
+ /**
353
+ * Finish linking an SSO account with the one-time `sso_link_code` the
354
+ * link callback page received (see `readSsoLinkResult()`). Throws `ApiError`
355
+ * (400 unknown/used code, 403 different user or unverified/mismatched email).
314
356
  */
315
- async linkAccount(provider = "authentik") {
316
- await authApi.linkSSOAccount(provider);
357
+ async completeSSOLink(code) {
358
+ return await authApi.completeSSOLink(code);
317
359
  }
318
360
  /**
319
361
  * Unlink an SSO account.
@@ -400,4 +442,4 @@ function formatUserRoles(user, options = {}) {
400
442
  return formatted.join(separator);
401
443
  }
402
444
 
403
- export { AuthService, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse };
445
+ export { AuthService, SSO_LINK_CODE_PARAM, SSO_LINK_STATUS_PARAM, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse, readSsoLinkResult };
@@ -1,6 +1,6 @@
1
- import { e as LoginCredentials, f as LoginResponse, g as LogoutResponse, R as RegisterData, l as RegisterResponse, q as User, k as ProfileUpdateData, C as ChangePasswordData, o as Session, A as ApiKey, c as CreateApiKeyRequest, d as CreateApiKeyResponse, U as UpdateApiKeyRequest, j as MFAStatus, i as MFASetupResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, D as Device, r as UserPreferences, L as LinkedAccount, n as SecurityEvent, P as Pagination, s as UserRolesResponse } from '../types-DF5Ny2IA.js';
2
- export { a as AuthConfig, b as AuthState, m as ResetPasswordData, S as SSOConfig, p as StorageAdapter, t as createMemoryStorage, u as createSessionStorage, v as getConfig, w as getDefaultStorage, x as getFetch, y as getStorage, z as initAuth, B as isInitialized, E as resetConfig } from '../types-DF5Ny2IA.js';
3
- export { A as ApiError, a as AuthService, I as InvalidAuthResponseError, L as LoginOptions, M as MFAChallengeEmailError, b as MFAVerifyOptions, R as RoleDeniedError, S as SessionChangedError, c as authService, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, j as isApiError, k as isRoleDeniedError, l as isSessionChangedError } from '../user-utils-DYyljbJR.js';
1
+ import { o as SSOLinkResult, e as LoginCredentials, f as LoginResponse, g as LogoutResponse, R as RegisterData, l as RegisterResponse, s as User, k as ProfileUpdateData, C as ChangePasswordData, q as Session, A as ApiKey, c as CreateApiKeyRequest, d as CreateApiKeyResponse, U as UpdateApiKeyRequest, j as MFAStatus, i as MFASetupResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, D as Device, t as UserPreferences, L as LinkedAccount, n as SSOLinkCompleteResponse, p as SecurityEvent, P as Pagination, u as UserRolesResponse } from '../types-To6QJDLW.js';
2
+ export { a as AuthConfig, b as AuthState, m as ResetPasswordData, S as SSOConfig, r as StorageAdapter, v as createMemoryStorage, w as createSessionStorage, x as getConfig, y as getDefaultStorage, z as getFetch, B as getStorage, E as initAuth, F as isInitialized, G as resetConfig } from '../types-To6QJDLW.js';
3
+ export { A as ApiError, a as AuthService, I as InvalidAuthResponseError, L as LoginOptions, M as MFAChallengeEmailError, b as MFAVerifyOptions, R as RoleDeniedError, S as SessionChangedError, c as authService, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, j as isApiError, k as isRoleDeniedError, l as isSessionChangedError } from '../user-utils-_gHXq75w.js';
4
4
 
5
5
  /**
6
6
  * SSO client state
@@ -64,6 +64,86 @@ declare function consumeSsoClientState(received: string | null | undefined): Sso
64
64
  * ```
65
65
  */
66
66
  declare function verifySsoClientState(input: string | URLSearchParams | null | undefined): SsoClientStateVerification;
67
+ /** Hash-fragment parameter carrying the MFA challenge token. */
68
+ declare const MFA_CHALLENGE_TOKEN_PARAM = "mfaChallengeToken";
69
+ /**
70
+ * Remember the MFA challenge token a password sign-in received, for this tab,
71
+ * so the MFA challenge page can accept that token from its URL hash
72
+ * (`acceptMfaChallengeHash`). `authService.login()` calls this for you when
73
+ * the response is an MFA challenge. Returns `false` when sessionStorage is
74
+ * unavailable.
75
+ */
76
+ declare function rememberMfaChallengeToken(token: string): boolean;
77
+ /** Forget the remembered MFA challenge token (after verifying, or on cancel). */
78
+ declare function clearMfaChallengeToken(): void;
79
+ interface MfaChallengeHashVerification extends SsoClientStateVerification {
80
+ /** The `mfaChallengeToken` from the hash, or `null` when it has none. */
81
+ token: string | null;
82
+ /** Which binding was checked: the SSO `client_state`, or the password flow's remembered token. */
83
+ via: 'sso' | 'password' | null;
84
+ }
85
+ /**
86
+ * Decide whether the MFA challenge page may use the token in its URL hash.
87
+ *
88
+ * - SSO MFA redirect: the hash carries `client_state`, which must match the
89
+ * value this tab stored when it started SSO (consumed, single-use).
90
+ * - Password sign-in: no `client_state`; the token must equal the one this tab
91
+ * remembered when `login()` returned the challenge.
92
+ *
93
+ * A token that matches neither came from a link someone else made. The same
94
+ * `sso.requireClientState` policy as `verifySsoClientState` decides whether
95
+ * a failed binding is rejected (`accepted: false`). A hash without a token is
96
+ * never accepted.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * const params = new URLSearchParams(window.location.hash.slice(1));
101
+ * const { accepted, token } = acceptMfaChallengeHash(params);
102
+ * if (!accepted || !token) return goto('/login');
103
+ * ```
104
+ */
105
+ declare function acceptMfaChallengeHash(input: URLSearchParams | string): MfaChallengeHashVerification;
106
+
107
+ /**
108
+ * SSO account linking: the return trip to the link callback page.
109
+ *
110
+ * `linkSSOAccount()` sends the signed-in user to the IdP. CHAPI then redirects
111
+ * to the link `callback` (by default the page that started it; without one,
112
+ * CHAPI web's `/account`) with `?link=pending#sso_link_code=<code>` (or
113
+ * `?link=error&message=…`) and writes no link until the same user posts the
114
+ * one-time code to `POST /auth/sso/link/complete` (`completeSSOLink`).
115
+ *
116
+ * The code sits in the hash so it never reaches a server log or `Referer`;
117
+ * `readSsoLinkResult()` removes it from the address bar as it reads it, so a
118
+ * reload, a shared URL or the history entry can't replay it.
119
+ */
120
+
121
+ /** Hash-fragment parameter carrying the one-time link code. */
122
+ declare const SSO_LINK_CODE_PARAM = "sso_link_code";
123
+ /** Query parameter CHAPI sets on the link callback redirect (`pending` | `error`). */
124
+ declare const SSO_LINK_STATUS_PARAM = "link";
125
+ interface ReadSsoLinkResultOptions {
126
+ /** URL to read; defaults to `window.location.href`. */
127
+ url?: string | URL;
128
+ /**
129
+ * Remove `link`, `message` and `sso_link_code` from the address bar with
130
+ * `history.replaceState` (default `true`; only when reading the current page).
131
+ */
132
+ clear?: boolean;
133
+ }
134
+ /**
135
+ * Read (and by default clear) the outcome of an SSO account-link round trip,
136
+ * on whatever page the link callback pointed at. Returns `null` when the URL
137
+ * is not a link return.
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * const link = readSsoLinkResult();
142
+ * if (link?.status === 'pending') await authService.completeSSOLink(link.code);
143
+ * else if (link?.status === 'error') showError(link.message ?? 'Linking failed');
144
+ * ```
145
+ */
146
+ declare function readSsoLinkResult(options?: ReadSsoLinkResultOptions): SSOLinkResult | null;
67
147
 
68
148
  /**
69
149
  * HTTP Client
@@ -409,8 +489,30 @@ declare const authApi: {
409
489
  *
410
490
  * Initiates the SSO linking flow by making an authenticated API call.
411
491
  * The server returns an authorization URL to redirect the user to.
492
+ * After the IdP, CHAPI returns the user to `callback` with
493
+ * `?link=pending#sso_link_code=…` (or `?link=error&message=…`); nothing is
494
+ * linked until that page calls `completeSSOLink(code)` (read the code with
495
+ * `readSsoLinkResult()`).
496
+ *
497
+ * @param options.callback - Absolute URL to come back to; its origin must be
498
+ * on CHAPI's SSO allowlist. Defaults to the current page
499
+ * (`location.origin + location.pathname`). Pass `null` to send none
500
+ * (CHAPI then uses its own web `/account` page).
501
+ */
502
+ linkSSOAccount(provider?: string, options?: {
503
+ callback?: string | null;
504
+ }): Promise<void>;
505
+ /**
506
+ * Finish linking an SSO account (`POST /auth/sso/link/complete`).
507
+ *
508
+ * After the IdP, CHAPI redirects to the link `callback` (the page that
509
+ * started it) with `?link=pending#sso_link_code=…` and writes no link until the signed-in user who started it sends that
510
+ * one-time code here. Throws `ApiError`: 400 for an unknown, expired or used
511
+ * code (or an SSO account already linked to another user), 403 when the
512
+ * link was started by a different account or the IdP email is unverified or
513
+ * differs from the account email.
412
514
  */
413
- linkSSOAccount(provider?: string): Promise<void>;
515
+ completeSSOLink(code: string): Promise<SSOLinkCompleteResponse>;
414
516
  /**
415
517
  * Get security event history.
416
518
  */
@@ -869,4 +971,4 @@ declare function parseRedactedHeader(value: string | null | undefined): {
869
971
  omitted: number;
870
972
  };
871
973
 
872
- export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, type AccessCheckEvent, type AccessCheckSource, type AccessEvaluation, type AccessProbe, type AccessRequirement, type AccessSubject, ApiKey, type ApiRequestOptions, type ApiResponse, ChangePasswordData, CreateApiKeyRequest, CreateApiKeyResponse, Device, type JWTPayload, LinkedAccount, LoginCredentials, LoginResponse, LogoutResponse, MFAChallengeData, MFAChallengeEmailResponse, MFASetupResponse, MFAStatus, Pagination, ProfileUpdateData, ROLE_HIERARCHY, ROLE_NAMES, type RedactedField, type RefreshOutcome, type RefreshSessionOptions, RegisterData, RegisterResponse, type RoleName, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SecurityEvent, Session, type SsoClientStateResult, type SsoClientStateVerification, UpdateApiKeyRequest, User, UserPreferences, UserRolesResponse, api, apiRequest, authApi, clearAccessSubject, clearStoredAuth, computePrimaryRole, consumeSsoClientState, createSsoClientState, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, extractData, getAccessSubjectOverride, getAccessToken, getAvailableMethods, getEffectiveLevel, getMfaToken, getRefreshToken, getSessionToken, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initCrossTabSync, isAccessProbeActive, isLoginSuccessResponse, isMfaChallengeResponse, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, refreshSession, reportAccess, reportDecision, requirementFromDenial, setAccessProbe, setAccessSubject, updateStoredTokens, verifySsoClientState };
974
+ export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, type AccessCheckEvent, type AccessCheckSource, type AccessEvaluation, type AccessProbe, type AccessRequirement, type AccessSubject, ApiKey, type ApiRequestOptions, type ApiResponse, ChangePasswordData, CreateApiKeyRequest, CreateApiKeyResponse, Device, type JWTPayload, LinkedAccount, LoginCredentials, LoginResponse, LogoutResponse, MFAChallengeData, MFAChallengeEmailResponse, MFASetupResponse, MFAStatus, MFA_CHALLENGE_TOKEN_PARAM, type MfaChallengeHashVerification, Pagination, ProfileUpdateData, ROLE_HIERARCHY, ROLE_NAMES, type ReadSsoLinkResultOptions, type RedactedField, type RefreshOutcome, type RefreshSessionOptions, RegisterData, RegisterResponse, type RoleName, SSOLinkCompleteResponse, SSOLinkResult, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SSO_LINK_CODE_PARAM, SSO_LINK_STATUS_PARAM, SecurityEvent, Session, type SsoClientStateResult, type SsoClientStateVerification, UpdateApiKeyRequest, User, UserPreferences, UserRolesResponse, acceptMfaChallengeHash, api, apiRequest, authApi, clearAccessSubject, clearMfaChallengeToken, clearStoredAuth, computePrimaryRole, consumeSsoClientState, createSsoClientState, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, extractData, getAccessSubjectOverride, getAccessToken, getAvailableMethods, getEffectiveLevel, getMfaToken, getRefreshToken, getSessionToken, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initCrossTabSync, isAccessProbeActive, isLoginSuccessResponse, isMfaChallengeResponse, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, readSsoLinkResult, refreshSession, rememberMfaChallengeToken, reportAccess, reportDecision, requirementFromDenial, setAccessProbe, setAccessSubject, updateStoredTokens, verifySsoClientState };
@@ -1,3 +1,3 @@
1
- export { AuthService, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse } from '../chunk-GAN4LIB2.js';
2
- export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, api, apiRequest, authApi, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, updateStoredTokens, verifySsoClientState } from '../chunk-4Q3R4TTI.js';
3
- export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject } from '../chunk-TANYGU4O.js';
1
+ export { AuthService, SSO_LINK_CODE_PARAM, SSO_LINK_STATUS_PARAM, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse, readSsoLinkResult } from '../chunk-YJUWI2VL.js';
2
+ export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, MFA_CHALLENGE_TOKEN_PARAM, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, acceptMfaChallengeHash, api, apiRequest, authApi, clearMfaChallengeToken, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, rememberMfaChallengeToken, updateStoredTokens, verifySsoClientState } from '../chunk-AY7AKNQT.js';
3
+ export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject } from '../chunk-SMPUGWF7.js';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as ApiKey, a as AuthConfig, b as AuthState, C as ChangePasswordData, c as CreateApiKeyRequest, d as CreateApiKeyResponse, D as Device, L as LinkedAccount, e as LoginCredentials, f as LoginResponse, g as LogoutResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, i as MFASetupResponse, j as MFAStatus, P as Pagination, k as ProfileUpdateData, R as RegisterData, l as RegisterResponse, m as ResetPasswordData, S as SSOConfig, n as SecurityEvent, o as Session, p as StorageAdapter, U as UpdateApiKeyRequest, q as User, r as UserPreferences, s as UserRolesResponse, t as createMemoryStorage, u as createSessionStorage, v as getConfig, w as getDefaultStorage, x as getFetch, y as getStorage, z as initAuth, B as isInitialized, E as resetConfig } from './types-DF5Ny2IA.js';
2
- export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, AccessCheckEvent, AccessCheckSource, AccessEvaluation, AccessProbe, AccessRequirement, AccessSubject, ApiRequestOptions, ApiResponse, JWTPayload, ROLE_HIERARCHY, ROLE_NAMES, RedactedField, RefreshOutcome, RefreshSessionOptions, RoleName, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SsoClientStateResult, SsoClientStateVerification, api, apiRequest, authApi, clearAccessSubject, clearStoredAuth, computePrimaryRole, consumeSsoClientState, createSsoClientState, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, extractData, getAccessSubjectOverride, getAccessToken, getAvailableMethods, getEffectiveLevel, getMfaToken, getRefreshToken, getSessionToken, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initCrossTabSync, isAccessProbeActive, isLoginSuccessResponse, isMfaChallengeResponse, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, refreshSession, reportAccess, reportDecision, requirementFromDenial, setAccessProbe, setAccessSubject, updateStoredTokens, verifySsoClientState } from './core/index.js';
3
- export { A as ApiError, a as AuthService, I as InvalidAuthResponseError, L as LoginOptions, M as MFAChallengeEmailError, b as MFAVerifyOptions, R as RoleDeniedError, S as SessionChangedError, c as authService, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, j as isApiError, k as isRoleDeniedError, l as isSessionChangedError } from './user-utils-DYyljbJR.js';
1
+ export { A as ApiKey, a as AuthConfig, b as AuthState, C as ChangePasswordData, c as CreateApiKeyRequest, d as CreateApiKeyResponse, D as Device, L as LinkedAccount, e as LoginCredentials, f as LoginResponse, g as LogoutResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, i as MFASetupResponse, j as MFAStatus, P as Pagination, k as ProfileUpdateData, R as RegisterData, l as RegisterResponse, m as ResetPasswordData, S as SSOConfig, n as SSOLinkCompleteResponse, o as SSOLinkResult, p as SecurityEvent, q as Session, r as StorageAdapter, U as UpdateApiKeyRequest, s as User, t as UserPreferences, u as UserRolesResponse, v as createMemoryStorage, w as createSessionStorage, x as getConfig, y as getDefaultStorage, z as getFetch, B as getStorage, E as initAuth, F as isInitialized, G as resetConfig } from './types-To6QJDLW.js';
2
+ export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, AccessCheckEvent, AccessCheckSource, AccessEvaluation, AccessProbe, AccessRequirement, AccessSubject, ApiRequestOptions, ApiResponse, JWTPayload, MFA_CHALLENGE_TOKEN_PARAM, MfaChallengeHashVerification, ROLE_HIERARCHY, ROLE_NAMES, ReadSsoLinkResultOptions, RedactedField, RefreshOutcome, RefreshSessionOptions, RoleName, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SSO_LINK_CODE_PARAM, SSO_LINK_STATUS_PARAM, SsoClientStateResult, SsoClientStateVerification, acceptMfaChallengeHash, api, apiRequest, authApi, clearAccessSubject, clearMfaChallengeToken, clearStoredAuth, computePrimaryRole, consumeSsoClientState, createSsoClientState, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, extractData, getAccessSubjectOverride, getAccessToken, getAvailableMethods, getEffectiveLevel, getMfaToken, getRefreshToken, getSessionToken, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initCrossTabSync, isAccessProbeActive, isLoginSuccessResponse, isMfaChallengeResponse, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, readSsoLinkResult, refreshSession, rememberMfaChallengeToken, reportAccess, reportDecision, requirementFromDenial, setAccessProbe, setAccessSubject, updateStoredTokens, verifySsoClientState } from './core/index.js';
3
+ export { A as ApiError, a as AuthService, I as InvalidAuthResponseError, L as LoginOptions, M as MFAChallengeEmailError, b as MFAVerifyOptions, R as RoleDeniedError, S as SessionChangedError, c as authService, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, j as isApiError, k as isRoleDeniedError, l as isSessionChangedError } from './user-utils-_gHXq75w.js';
4
4
  export { AuthClient, AuthGuardOptions, AuthGuardResult, AuthHookOptions, CreateAuthClientOptions, NavFilterOptions, RoleRestrictedItem, authActions, authStore, canAccess, checkAuth, createAuthClient, createAuthGuard, createAuthHook, createNavFilter, currentUser, filterByAccess, filterNavSections, isAuthenticated, matchesRoute, protectedLoad, requireAuth, requirePermission, requireRole, routePatterns } from './svelte/index.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { canAccess, checkAuth, createAuthClient, createAuthGuard, createAuthHook, createNavFilter, filterByAccess, filterNavSections, matchesRoute, protectedLoad, requireAuth, requirePermission, requireRole, routePatterns } from './chunk-NRVZY2B3.js';
2
- export { AuthService, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse } from './chunk-GAN4LIB2.js';
3
- export { authActions, authStore, currentUser, isAuthenticated } from './chunk-HWV4ZEZM.js';
4
- export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, api, apiRequest, authApi, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, updateStoredTokens, verifySsoClientState } from './chunk-4Q3R4TTI.js';
5
- export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject } from './chunk-TANYGU4O.js';
1
+ export { canAccess, checkAuth, createAuthClient, createAuthGuard, createAuthHook, createNavFilter, filterByAccess, filterNavSections, matchesRoute, protectedLoad, requireAuth, requirePermission, requireRole, routePatterns } from './chunk-IZYOA3KJ.js';
2
+ export { AuthService, SSO_LINK_CODE_PARAM, SSO_LINK_STATUS_PARAM, authService, formatUserRoles, getAvailableMethods, getAvatarFallback, getDisplayName, getGreeting, getMfaToken, getUserEmail, getUserInitials, isLoginSuccessResponse, isMfaChallengeResponse, readSsoLinkResult } from './chunk-YJUWI2VL.js';
3
+ export { authActions, authStore, currentUser, isAuthenticated } from './chunk-WARTLLDA.js';
4
+ export { ApiError, InvalidAuthResponseError, MFAChallengeEmailError, MFA_CHALLENGE_TOKEN_PARAM, RoleDeniedError, SSO_CLIENT_STATE_PARAM, SSO_CLIENT_STATE_TTL_MS, SessionChangedError, acceptMfaChallengeHash, api, apiRequest, authApi, clearMfaChallengeToken, clearStoredAuth, consumeSsoClientState, createSsoClientState, extractData, getAccessToken, getRefreshToken, getSessionToken, initCrossTabSync, isApiError, isRoleDeniedError, isSessionChangedError, refreshSession, rememberMfaChallengeToken, updateStoredTokens, verifySsoClientState } from './chunk-AY7AKNQT.js';
5
+ export { ACCESS_DEBUG_HEADER, ACCESS_REDACTED_HEADER, ACCESS_REDACTED_TRUNCATED_HEADER, ROLE_HIERARCHY, ROLE_NAMES, clearAccessSubject, computePrimaryRole, createMemoryStorage, createSessionStorage, decodeJWT, effectiveSubject, evaluateAccess, extractClaims, getAccessSubjectOverride, getConfig, getDefaultStorage, getEffectiveLevel, getFetch, getStorage, getTokenExpiration, getTokenRemainingTime, getUserRoles, hasAllRoles, hasAnyRole, hasRole, initAuth, isAccessProbeActive, isInitialized, isTokenExpired, onAccessSubjectChange, parseRedactedHeader, reportAccess, reportDecision, requirementFromDenial, resetConfig, setAccessProbe, setAccessSubject } from './chunk-SMPUGWF7.js';
@@ -1,7 +1,7 @@
1
- import { b as AuthState, q as User, a as AuthConfig } from '../types-DF5Ny2IA.js';
2
- export { z as initAuth, B as isInitialized } from '../types-DF5Ny2IA.js';
3
- import { c as authService } from '../user-utils-DYyljbJR.js';
4
- export { I as InvalidAuthResponseError, R as RoleDeniedError, S as SessionChangedError, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, k as isRoleDeniedError, l as isSessionChangedError } from '../user-utils-DYyljbJR.js';
1
+ import { b as AuthState, s as User, a as AuthConfig } from '../types-To6QJDLW.js';
2
+ export { E as initAuth, F as isInitialized } from '../types-To6QJDLW.js';
3
+ import { c as authService } from '../user-utils-_gHXq75w.js';
4
+ export { I as InvalidAuthResponseError, R as RoleDeniedError, S as SessionChangedError, f as formatUserRoles, g as getAvatarFallback, d as getDisplayName, e as getGreeting, h as getUserEmail, i as getUserInitials, k as isRoleDeniedError, l as isSessionChangedError } from '../user-utils-_gHXq75w.js';
5
5
 
6
6
  /**
7
7
  * Auth Store
@@ -1,5 +1,5 @@
1
- export { canAccess, checkAuth, createAuthClient, createAuthGuard, createAuthHook, createNavFilter, filterByAccess, filterNavSections, matchesRoute, protectedLoad, requireAuth, requirePermission, requireRole, routePatterns } from '../chunk-NRVZY2B3.js';
2
- export { formatUserRoles, getAvatarFallback, getDisplayName, getGreeting, getUserEmail, getUserInitials } from '../chunk-GAN4LIB2.js';
3
- export { authActions, authStore, currentUser, isAuthenticated } from '../chunk-HWV4ZEZM.js';
4
- export { InvalidAuthResponseError, RoleDeniedError, SessionChangedError, isRoleDeniedError, isSessionChangedError } from '../chunk-4Q3R4TTI.js';
5
- export { initAuth, isInitialized } from '../chunk-TANYGU4O.js';
1
+ export { canAccess, checkAuth, createAuthClient, createAuthGuard, createAuthHook, createNavFilter, filterByAccess, filterNavSections, matchesRoute, protectedLoad, requireAuth, requirePermission, requireRole, routePatterns } from '../chunk-IZYOA3KJ.js';
2
+ export { formatUserRoles, getAvatarFallback, getDisplayName, getGreeting, getUserEmail, getUserInitials } from '../chunk-YJUWI2VL.js';
3
+ export { authActions, authStore, currentUser, isAuthenticated } from '../chunk-WARTLLDA.js';
4
+ export { InvalidAuthResponseError, RoleDeniedError, SessionChangedError, isRoleDeniedError, isSessionChangedError } from '../chunk-AY7AKNQT.js';
5
+ export { initAuth, isInitialized } from '../chunk-SMPUGWF7.js';
@@ -1,4 +1,4 @@
1
- import { q as User, D as Device, f as LoginResponse, n as SecurityEvent, o as Session, A as ApiKey, L as LinkedAccount, g as LogoutResponse, i as MFASetupResponse, j as MFAStatus, l as RegisterResponse, r as UserPreferences, p as StorageAdapter, b as AuthState, a as AuthConfig } from '../types-DF5Ny2IA.js';
1
+ import { s as User, D as Device, f as LoginResponse, p as SecurityEvent, q as Session, A as ApiKey, L as LinkedAccount, g as LogoutResponse, i as MFASetupResponse, j as MFAStatus, l as RegisterResponse, t as UserPreferences, r as StorageAdapter, b as AuthState, a as AuthConfig } from '../types-To6QJDLW.js';
2
2
 
3
3
  /**
4
4
  * User Fixtures
@@ -1,4 +1,4 @@
1
- import { hasRole, hasAnyRole, hasAllRoles, initAuth, resetConfig, getUserRoles, isTokenExpired, decodeJWT } from '../chunk-TANYGU4O.js';
1
+ import { hasRole, hasAnyRole, hasAllRoles, initAuth, resetConfig, getUserRoles, isTokenExpired, decodeJWT } from '../chunk-SMPUGWF7.js';
2
2
 
3
3
  // src/testing/fixtures/users.ts
4
4
  var mockUser = {
@@ -18,6 +18,15 @@ interface SSOConfig {
18
18
  * a logout URL anywhere else is dropped.
19
19
  */
20
20
  logoutOrigins?: string[];
21
+ /**
22
+ * Origins the identity provider's authorization page may be on (e.g.
23
+ * 'https://auth.example.com'), checked when `linkSSOAccount` follows the
24
+ * authorization URL CHAPI returns. When set, that URL must be on one of
25
+ * these, `logoutOrigins`, the `authorizeUrl` origin or the API origin.
26
+ * When unset, any https URL is accepted. Never checked against
27
+ * `allowedRedirectOrigins`, which lists the app's own origins.
28
+ */
29
+ idpOrigins?: string[];
21
30
  /**
22
31
  * Reject SSO callbacks whose `client_state` is missing or doesn't match the
23
32
  * one this tab sent to the authorize endpoint (see `verifySsoClientState`).
@@ -379,6 +388,24 @@ interface LinkedAccount {
379
388
  createdAt: string;
380
389
  lastUsedAt?: string | null;
381
390
  }
391
+ /** `POST /auth/sso/link/complete` result: the link is written. */
392
+ interface SSOLinkCompleteResponse {
393
+ linked: true;
394
+ provider: string;
395
+ }
396
+ /**
397
+ * Where an SSO account-link round trip left the callback page
398
+ * (`readSsoLinkResult()`):
399
+ * - `pending`: the IdP verified the identity; call `completeSSOLink(code)`
400
+ * - `error`: the IdP step failed; `message` is the server's reason
401
+ */
402
+ type SSOLinkResult = {
403
+ status: 'pending';
404
+ code: string;
405
+ } | {
406
+ status: 'error';
407
+ message: string | null;
408
+ };
382
409
  interface SecurityEvent {
383
410
  id: string;
384
411
  eventType: string;
@@ -413,4 +440,4 @@ interface ResetPasswordData {
413
440
  newPassword: string;
414
441
  }
415
442
 
416
- export { type ApiKey as A, isInitialized as B, type ChangePasswordData as C, type Device as D, resetConfig as E, type LinkedAccount as L, type MFAChallengeData as M, type Pagination as P, type RegisterData as R, type SSOConfig as S, type UpdateApiKeyRequest as U, type AuthConfig as a, type AuthState as b, type CreateApiKeyRequest as c, type CreateApiKeyResponse as d, type LoginCredentials as e, type LoginResponse as f, type LogoutResponse as g, type MFAChallengeEmailResponse as h, type MFASetupResponse as i, type MFAStatus as j, type ProfileUpdateData as k, type RegisterResponse as l, type ResetPasswordData as m, type SecurityEvent as n, type Session as o, type StorageAdapter as p, type User as q, type UserPreferences as r, type UserRolesResponse as s, createMemoryStorage as t, createSessionStorage as u, getConfig as v, getDefaultStorage as w, getFetch as x, getStorage as y, initAuth as z };
443
+ export { type ApiKey as A, getStorage as B, type ChangePasswordData as C, type Device as D, initAuth as E, isInitialized as F, resetConfig as G, type LinkedAccount as L, type MFAChallengeData as M, type Pagination as P, type RegisterData as R, type SSOConfig as S, type UpdateApiKeyRequest as U, type AuthConfig as a, type AuthState as b, type CreateApiKeyRequest as c, type CreateApiKeyResponse as d, type LoginCredentials as e, type LoginResponse as f, type LogoutResponse as g, type MFAChallengeEmailResponse as h, type MFASetupResponse as i, type MFAStatus as j, type ProfileUpdateData as k, type RegisterResponse as l, type ResetPasswordData as m, type SSOLinkCompleteResponse as n, type SSOLinkResult as o, type SecurityEvent as p, type Session as q, type StorageAdapter as r, type User as s, type UserPreferences as t, type UserRolesResponse as u, createMemoryStorage as v, createSessionStorage as w, getConfig as x, getDefaultStorage as y, getFetch as z };
@@ -1,4 +1,4 @@
1
- import { e as LoginCredentials, f as LoginResponse, g as LogoutResponse, R as RegisterData, l as RegisterResponse, q as User, k as ProfileUpdateData, o as Session, A as ApiKey, c as CreateApiKeyRequest, d as CreateApiKeyResponse, U as UpdateApiKeyRequest, j as MFAStatus, i as MFASetupResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, D as Device, r as UserPreferences, L as LinkedAccount, n as SecurityEvent, P as Pagination } from './types-DF5Ny2IA.js';
1
+ import { e as LoginCredentials, f as LoginResponse, g as LogoutResponse, R as RegisterData, l as RegisterResponse, s as User, k as ProfileUpdateData, q as Session, A as ApiKey, c as CreateApiKeyRequest, d as CreateApiKeyResponse, U as UpdateApiKeyRequest, j as MFAStatus, i as MFASetupResponse, M as MFAChallengeData, h as MFAChallengeEmailResponse, D as Device, t as UserPreferences, L as LinkedAccount, n as SSOLinkCompleteResponse, p as SecurityEvent, P as Pagination } from './types-To6QJDLW.js';
2
2
 
3
3
  /**
4
4
  * Auth Service
@@ -244,9 +244,19 @@ declare class AuthService {
244
244
  */
245
245
  getLinkedAccounts(customFetch?: typeof fetch): Promise<LinkedAccount[]>;
246
246
  /**
247
- * Link an SSO account (redirects to SSO provider).
247
+ * Link an SSO account (redirects to SSO provider). The IdP round trip
248
+ * returns to `options.callback`, by default the current page; finish there
249
+ * with `readSsoLinkResult()` + `completeSSOLink(code)`.
248
250
  */
249
- linkAccount(provider?: string): Promise<void>;
251
+ linkAccount(provider?: string, options?: {
252
+ callback?: string | null;
253
+ }): Promise<void>;
254
+ /**
255
+ * Finish linking an SSO account with the one-time `sso_link_code` the
256
+ * link callback page received (see `readSsoLinkResult()`). Throws `ApiError`
257
+ * (400 unknown/used code, 403 different user or unverified/mismatched email).
258
+ */
259
+ completeSSOLink(code: string): Promise<SSOLinkCompleteResponse>;
250
260
  /**
251
261
  * Unlink an SSO account.
252
262
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/auth",
3
- "version": "1.47.0",
3
+ "version": "1.50.0",
4
4
  "description": "Authentication services and Svelte bindings for Classic Theme apps",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,3 +0,0 @@
1
- export { authActions, authStore, currentUser, isAuthenticated } from './chunk-HWV4ZEZM.js';
2
- import './chunk-4Q3R4TTI.js';
3
- import './chunk-TANYGU4O.js';