@bagelink/auth 1.21.44 → 1.21.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +4 -1
- package/dist/index.cjs +35 -8
- package/dist/index.mjs +35 -8
- package/dist/useAuth.d.ts +4 -0
- package/package.json +1 -1
- package/src/api.ts +10 -1
- package/src/sessionExpiry.test.ts +114 -0
- package/src/useAuth.ts +40 -3
package/dist/api.d.ts
CHANGED
|
@@ -2,13 +2,16 @@ import { AxiosInstance } from 'axios';
|
|
|
2
2
|
import { RegisterRequest, UpdateAccountRequest, ChangePasswordRequest, ForgotPasswordRequest, ResetPasswordRequest, SendVerificationRequest, VerifyEmailRequest, AuthenticationAccount, PasswordLoginRequest, EmailTokenSendRequest, EmailTokenVerifyRequest, OTPSendRequest, OTPVerifyRequest, SMSSendRequest, SMSVerifyRequest, GenerateTokenRequest, RedeemTokenRequest, SSOLoginRequest, LoginResponse, RegisterResponse, LogoutResponse, GetMeResponse, UpdateMeResponse, DeleteMeResponse, ChangePasswordResponse, ForgotPasswordResponse, ResetPasswordResponse, VerifyResetTokenResponse, SendVerificationResponse, VerifyEmailResponse, RefreshSessionResponse, GetSessionsResponse, DeleteSessionResponse, DeleteAllSessionsResponse, CleanupSessionsResponse, GetMethodsResponse, GetAuthStatusResponse, SendEmailTokenResponse, VerifyEmailTokenResponse, SendOTPResponse, VerifyOTPResponse, SendSMSResponse, VerifySMSResponse, GenerateLoginTokenResponse, RedeemLoginTokenResponse, LegacySSOLoginResponse, SSOProvider, SSOInitiateRequest, SSOCallbackRequest, SSOLinkRequest, InitiateSSOResponse, CallbackSSOResponse, LinkSSOResponse, UnlinkSSOResponse, GetTenantsResponse, GetTenantResponse, CreateTenantResponse, UpdateTenantResponse, DeleteTenantResponse, GetTenantMembersResponse, AddTenantMemberResponse, UpdateTenantMemberResponse, DeleteTenantMemberResponse, GetTenantRolesResponse, CreateInvitationResponse, GetInvitationResponse, AcceptInvitationResponse, CreateTenantRequest, UpdateTenantRequest, AddMemberRequest, UpdateMemberRequest, CreateInvitationRequest, AcceptInvitationRequest } from './types';
|
|
3
3
|
export declare class AuthApi {
|
|
4
4
|
private onApiError?;
|
|
5
|
+
private onUnauthorized?;
|
|
5
6
|
private api;
|
|
6
7
|
private currentTenantId;
|
|
7
8
|
private externalAxiosInstances;
|
|
8
9
|
private sessionToken;
|
|
9
10
|
/** Keep replacement sessions in memory; the server owns the HttpOnly cookie. */
|
|
10
11
|
setSessionToken(token: string | null): void;
|
|
11
|
-
constructor(baseURL?: string, onApiError?: ((error: unknown) => void) | undefined);
|
|
12
|
+
constructor(baseURL?: string, onApiError?: ((error: unknown) => void) | undefined, onUnauthorized?: (() => void) | undefined);
|
|
13
|
+
/** @internal test hook: the auth transport, so tests can stub its responses. */
|
|
14
|
+
get axiosForTest(): AxiosInstance;
|
|
12
15
|
private observeErrors;
|
|
13
16
|
/**
|
|
14
17
|
* Register an external axios instance so that tenant headers
|
package/dist/index.cjs
CHANGED
|
@@ -61,12 +61,13 @@ function queryParams() {
|
|
|
61
61
|
return result;
|
|
62
62
|
}
|
|
63
63
|
class AuthApi {
|
|
64
|
-
constructor(baseURL = "", onApiError) {
|
|
64
|
+
constructor(baseURL = "", onApiError, onUnauthorized) {
|
|
65
65
|
__publicField(this, "api");
|
|
66
66
|
__publicField(this, "currentTenantId", null);
|
|
67
67
|
__publicField(this, "externalAxiosInstances", /* @__PURE__ */ new Set());
|
|
68
68
|
__publicField(this, "sessionToken", null);
|
|
69
69
|
this.onApiError = onApiError;
|
|
70
|
+
this.onUnauthorized = onUnauthorized;
|
|
70
71
|
this.api = createAxiosInstance(baseURL);
|
|
71
72
|
this.setupInterceptors();
|
|
72
73
|
this.observeErrors(this.api);
|
|
@@ -79,10 +80,16 @@ class AuthApi {
|
|
|
79
80
|
else delete instance.defaults.headers.common.Authorization;
|
|
80
81
|
}
|
|
81
82
|
}
|
|
83
|
+
/** @internal test hook: the auth transport, so tests can stub its responses. */
|
|
84
|
+
get axiosForTest() {
|
|
85
|
+
return this.api;
|
|
86
|
+
}
|
|
82
87
|
observeErrors(instance) {
|
|
83
88
|
instance.interceptors.response.use((response) => response, (error) => {
|
|
84
|
-
var _a;
|
|
85
|
-
(_a =
|
|
89
|
+
var _a, _b, _c;
|
|
90
|
+
const status = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status;
|
|
91
|
+
if (status === 401) (_b = this.onUnauthorized) == null ? void 0 : _b.call(this);
|
|
92
|
+
(_c = this.onApiError) == null ? void 0 : _c.call(this, error);
|
|
86
93
|
return Promise.reject(error);
|
|
87
94
|
});
|
|
88
95
|
}
|
|
@@ -1157,13 +1164,20 @@ function getRedirectConfig() {
|
|
|
1157
1164
|
function isAuthPublicPath() {
|
|
1158
1165
|
var _a;
|
|
1159
1166
|
const route = (_a = autoRedirectRouter == null ? void 0 : autoRedirectRouter.currentRoute) == null ? void 0 : _a.value;
|
|
1160
|
-
return routeIsAuthPublic(route, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1167
|
+
if (route) return routeIsAuthPublic(route, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1168
|
+
return routeIsAuthPublic(null, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1161
1169
|
}
|
|
1162
1170
|
function createAuth(params) {
|
|
1163
1171
|
if (authApi === null) {
|
|
1164
|
-
authApi = new AuthApi(
|
|
1165
|
-
|
|
1166
|
-
|
|
1172
|
+
authApi = new AuthApi(
|
|
1173
|
+
params.baseURL,
|
|
1174
|
+
(error) => {
|
|
1175
|
+
useAuth().handleApiError(error);
|
|
1176
|
+
},
|
|
1177
|
+
() => {
|
|
1178
|
+
useAuth().handleUnauthorized();
|
|
1179
|
+
}
|
|
1180
|
+
);
|
|
1167
1181
|
}
|
|
1168
1182
|
if (eventEmitter === null) {
|
|
1169
1183
|
eventEmitter = new EventEmitter();
|
|
@@ -1347,12 +1361,22 @@ function useAuth() {
|
|
|
1347
1361
|
const logoutPromise = api.logout();
|
|
1348
1362
|
await logoutPromise.catch(() => {
|
|
1349
1363
|
});
|
|
1364
|
+
clearSession();
|
|
1365
|
+
emitter.emit(AuthState.LOGOUT);
|
|
1366
|
+
}
|
|
1367
|
+
function clearSession() {
|
|
1350
1368
|
api.setSessionToken(null);
|
|
1351
1369
|
pendingMfa.value = null;
|
|
1352
1370
|
accountInfo.value = null;
|
|
1353
1371
|
tenants.value = [];
|
|
1354
1372
|
currentTenant.value = null;
|
|
1355
1373
|
api.setTenantId(null);
|
|
1374
|
+
resetInitialAuth();
|
|
1375
|
+
}
|
|
1376
|
+
function handleUnauthorized() {
|
|
1377
|
+
if (isAuthPublicPath()) return;
|
|
1378
|
+
if (!getIsLoggedIn()) return;
|
|
1379
|
+
clearSession();
|
|
1356
1380
|
emitter.emit(AuthState.LOGOUT);
|
|
1357
1381
|
}
|
|
1358
1382
|
function captureMfa(response) {
|
|
@@ -1674,6 +1698,7 @@ function useAuth() {
|
|
|
1674
1698
|
requiresMfa,
|
|
1675
1699
|
beginMfa,
|
|
1676
1700
|
handleApiError,
|
|
1701
|
+
handleUnauthorized,
|
|
1677
1702
|
authDestinationRoute,
|
|
1678
1703
|
// Full account info (for advanced use cases)
|
|
1679
1704
|
accountInfo,
|
|
@@ -1749,7 +1774,9 @@ function useAuth() {
|
|
|
1749
1774
|
getInvitation,
|
|
1750
1775
|
acceptInvitation,
|
|
1751
1776
|
// Axios integration
|
|
1752
|
-
registerAxios: (instance) => api.registerAxios(instance)
|
|
1777
|
+
registerAxios: (instance) => api.registerAxios(instance),
|
|
1778
|
+
/** @internal test hook */
|
|
1779
|
+
api
|
|
1753
1780
|
};
|
|
1754
1781
|
}
|
|
1755
1782
|
const useAuth$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
package/dist/index.mjs
CHANGED
|
@@ -59,12 +59,13 @@ function queryParams() {
|
|
|
59
59
|
return result;
|
|
60
60
|
}
|
|
61
61
|
class AuthApi {
|
|
62
|
-
constructor(baseURL = "", onApiError) {
|
|
62
|
+
constructor(baseURL = "", onApiError, onUnauthorized) {
|
|
63
63
|
__publicField(this, "api");
|
|
64
64
|
__publicField(this, "currentTenantId", null);
|
|
65
65
|
__publicField(this, "externalAxiosInstances", /* @__PURE__ */ new Set());
|
|
66
66
|
__publicField(this, "sessionToken", null);
|
|
67
67
|
this.onApiError = onApiError;
|
|
68
|
+
this.onUnauthorized = onUnauthorized;
|
|
68
69
|
this.api = createAxiosInstance(baseURL);
|
|
69
70
|
this.setupInterceptors();
|
|
70
71
|
this.observeErrors(this.api);
|
|
@@ -77,10 +78,16 @@ class AuthApi {
|
|
|
77
78
|
else delete instance.defaults.headers.common.Authorization;
|
|
78
79
|
}
|
|
79
80
|
}
|
|
81
|
+
/** @internal test hook: the auth transport, so tests can stub its responses. */
|
|
82
|
+
get axiosForTest() {
|
|
83
|
+
return this.api;
|
|
84
|
+
}
|
|
80
85
|
observeErrors(instance) {
|
|
81
86
|
instance.interceptors.response.use((response) => response, (error) => {
|
|
82
|
-
var _a;
|
|
83
|
-
(_a =
|
|
87
|
+
var _a, _b, _c;
|
|
88
|
+
const status = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status;
|
|
89
|
+
if (status === 401) (_b = this.onUnauthorized) == null ? void 0 : _b.call(this);
|
|
90
|
+
(_c = this.onApiError) == null ? void 0 : _c.call(this, error);
|
|
84
91
|
return Promise.reject(error);
|
|
85
92
|
});
|
|
86
93
|
}
|
|
@@ -1155,13 +1162,20 @@ function getRedirectConfig() {
|
|
|
1155
1162
|
function isAuthPublicPath() {
|
|
1156
1163
|
var _a;
|
|
1157
1164
|
const route = (_a = autoRedirectRouter == null ? void 0 : autoRedirectRouter.currentRoute) == null ? void 0 : _a.value;
|
|
1158
|
-
return routeIsAuthPublic(route, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1165
|
+
if (route) return routeIsAuthPublic(route, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1166
|
+
return routeIsAuthPublic(null, (redirectConfig == null ? void 0 : redirectConfig.noAuthRoutes) ?? []);
|
|
1159
1167
|
}
|
|
1160
1168
|
function createAuth(params) {
|
|
1161
1169
|
if (authApi === null) {
|
|
1162
|
-
authApi = new AuthApi(
|
|
1163
|
-
|
|
1164
|
-
|
|
1170
|
+
authApi = new AuthApi(
|
|
1171
|
+
params.baseURL,
|
|
1172
|
+
(error) => {
|
|
1173
|
+
useAuth().handleApiError(error);
|
|
1174
|
+
},
|
|
1175
|
+
() => {
|
|
1176
|
+
useAuth().handleUnauthorized();
|
|
1177
|
+
}
|
|
1178
|
+
);
|
|
1165
1179
|
}
|
|
1166
1180
|
if (eventEmitter === null) {
|
|
1167
1181
|
eventEmitter = new EventEmitter();
|
|
@@ -1345,12 +1359,22 @@ function useAuth() {
|
|
|
1345
1359
|
const logoutPromise = api.logout();
|
|
1346
1360
|
await logoutPromise.catch(() => {
|
|
1347
1361
|
});
|
|
1362
|
+
clearSession();
|
|
1363
|
+
emitter.emit(AuthState.LOGOUT);
|
|
1364
|
+
}
|
|
1365
|
+
function clearSession() {
|
|
1348
1366
|
api.setSessionToken(null);
|
|
1349
1367
|
pendingMfa.value = null;
|
|
1350
1368
|
accountInfo.value = null;
|
|
1351
1369
|
tenants.value = [];
|
|
1352
1370
|
currentTenant.value = null;
|
|
1353
1371
|
api.setTenantId(null);
|
|
1372
|
+
resetInitialAuth();
|
|
1373
|
+
}
|
|
1374
|
+
function handleUnauthorized() {
|
|
1375
|
+
if (isAuthPublicPath()) return;
|
|
1376
|
+
if (!getIsLoggedIn()) return;
|
|
1377
|
+
clearSession();
|
|
1354
1378
|
emitter.emit(AuthState.LOGOUT);
|
|
1355
1379
|
}
|
|
1356
1380
|
function captureMfa(response) {
|
|
@@ -1672,6 +1696,7 @@ function useAuth() {
|
|
|
1672
1696
|
requiresMfa,
|
|
1673
1697
|
beginMfa,
|
|
1674
1698
|
handleApiError,
|
|
1699
|
+
handleUnauthorized,
|
|
1675
1700
|
authDestinationRoute,
|
|
1676
1701
|
// Full account info (for advanced use cases)
|
|
1677
1702
|
accountInfo,
|
|
@@ -1747,7 +1772,9 @@ function useAuth() {
|
|
|
1747
1772
|
getInvitation,
|
|
1748
1773
|
acceptInvitation,
|
|
1749
1774
|
// Axios integration
|
|
1750
|
-
registerAxios: (instance) => api.registerAxios(instance)
|
|
1775
|
+
registerAxios: (instance) => api.registerAxios(instance),
|
|
1776
|
+
/** @internal test hook */
|
|
1777
|
+
api
|
|
1751
1778
|
};
|
|
1752
1779
|
}
|
|
1753
1780
|
const useAuth$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
package/dist/useAuth.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { App, ObjectPlugin } from 'vue';
|
|
2
2
|
import { AccountInfo, User, NewUser, UpdatePasswordForm, UpdateAccountRequest, AuthEventMap, SSOProvider, SSOInitiateRequest, SSOCallbackRequest, SSOLinkRequest, TenantInfo, CreateTenantRequest, UpdateTenantRequest, AddMemberRequest, UpdateMemberRequest, CreateInvitationRequest, AcceptInvitationRequest, OTPSendRequest, OTPVerifyRequest, SMSSendRequest, SMSVerifyRequest, EmailTokenSendRequest, EmailTokenVerifyRequest, GenerateTokenRequest, GenerateTokenResponse, AuthenticationResponse, AuthState } from './types';
|
|
3
3
|
import { RedirectConfig, NormalizedRedirectConfig } from './types/redirect';
|
|
4
|
+
import { AuthApi } from './api';
|
|
4
5
|
import { MfaFlowApi, PendingMfaMetadata } from './mfa';
|
|
5
6
|
interface InitParams {
|
|
6
7
|
baseURL: string;
|
|
@@ -131,6 +132,7 @@ export declare function useAuth(): {
|
|
|
131
132
|
requiresMfa: () => Promise<boolean>;
|
|
132
133
|
beginMfa: (flowApi?: MfaFlowApi, force?: boolean) => Promise<PendingMfaMetadata | null>;
|
|
133
134
|
handleApiError: (error: unknown) => boolean;
|
|
135
|
+
handleUnauthorized: () => void;
|
|
134
136
|
authDestinationRoute: (destination: string) => string | {
|
|
135
137
|
name: string;
|
|
136
138
|
query: {
|
|
@@ -322,5 +324,7 @@ export declare function useAuth(): {
|
|
|
322
324
|
}>;
|
|
323
325
|
acceptInvitation: (token: string, data?: AcceptInvitationRequest) => Promise<void>;
|
|
324
326
|
registerAxios: (instance: any) => void;
|
|
327
|
+
/** @internal test hook */
|
|
328
|
+
api: AuthApi;
|
|
325
329
|
};
|
|
326
330
|
export {};
|
package/package.json
CHANGED
package/src/api.ts
CHANGED
|
@@ -91,14 +91,23 @@ export class AuthApi {
|
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
constructor(baseURL: string = '', private onApiError?: (error: unknown) => void) {
|
|
94
|
+
constructor(baseURL: string = '', private onApiError?: (error: unknown) => void, private onUnauthorized?: () => void) {
|
|
95
95
|
this.api = createAxiosInstance(baseURL)
|
|
96
96
|
this.setupInterceptors()
|
|
97
97
|
this.observeErrors(this.api)
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
+
/** @internal test hook: the auth transport, so tests can stub its responses. */
|
|
101
|
+
get axiosForTest(): AxiosInstance {
|
|
102
|
+
return this.api
|
|
103
|
+
}
|
|
104
|
+
|
|
100
105
|
private observeErrors(instance: AxiosInstance) {
|
|
101
106
|
instance.interceptors.response.use(response => response, (error: unknown) => {
|
|
107
|
+
const status = (error as { response?: { status?: number } } | null)?.response?.status
|
|
108
|
+
// A dead session is a logout, not just a failed request. The auth
|
|
109
|
+
// layer owns that decision; callers still see the rejected promise.
|
|
110
|
+
if (status === 401) this.onUnauthorized?.()
|
|
102
111
|
this.onApiError?.(error)
|
|
103
112
|
return Promise.reject(error)
|
|
104
113
|
})
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import axios, { AxiosError, type AxiosInstance, type InternalAxiosRequestConfig } from 'axios'
|
|
3
|
+
import { AuthState } from './types'
|
|
4
|
+
import { createAuth, ensureInitialAuth, resetInitialAuth, useAuth } from './useAuth'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A revoked session must end the client session the moment any authenticated
|
|
8
|
+
* call answers 401: the cached user is cleared, LOGOUT fires (app shells listen
|
|
9
|
+
* for it and redirect to login), and the cached boot check is dropped so the
|
|
10
|
+
* next navigation re-probes instead of trusting a stale logged-in result.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const LOGGED_IN = {
|
|
14
|
+
id: 'user-1',
|
|
15
|
+
account_type: 'identity',
|
|
16
|
+
authentication_methods: [{ type: 'password', identifier: 'a@b.co' }],
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function respondWith(instance: AxiosInstance, status: number, data: unknown = LOGGED_IN) {
|
|
20
|
+
instance.defaults.adapter = async (config) => {
|
|
21
|
+
const response = {
|
|
22
|
+
status,
|
|
23
|
+
statusText: status === 200 ? 'OK' : 'Unauthorized',
|
|
24
|
+
data: status < 400 ? data : { detail: 'Not authenticated' },
|
|
25
|
+
headers: {},
|
|
26
|
+
config: config as InternalAxiosRequestConfig,
|
|
27
|
+
}
|
|
28
|
+
if (status >= 400) {
|
|
29
|
+
throw new AxiosError('Request failed', 'ERR_BAD_REQUEST', config as InternalAxiosRequestConfig, null, response)
|
|
30
|
+
}
|
|
31
|
+
return response
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function route(name: string, path: string) {
|
|
36
|
+
return { name, path, fullPath: path, query: {}, params: {}, meta: {}, matched: [] }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('dead session on 401', () => {
|
|
40
|
+
const router = {
|
|
41
|
+
currentRoute: { value: route('People', '/people') },
|
|
42
|
+
beforeEach: vi.fn(),
|
|
43
|
+
replace: vi.fn(),
|
|
44
|
+
push: vi.fn(),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
vi.stubGlobal('window', { location: { search: '', pathname: '/people' } })
|
|
49
|
+
resetInitialAuth()
|
|
50
|
+
createAuth({
|
|
51
|
+
baseURL: 'http://localhost',
|
|
52
|
+
redirect: { loginRoute: 'auth-login', noAuthRoutes: ['auth-login'], autoRedirect: false },
|
|
53
|
+
}).use(router)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
afterEach(() => {
|
|
57
|
+
resetInitialAuth()
|
|
58
|
+
vi.unstubAllGlobals()
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('ends the session when an authenticated request is rejected with 401', async () => {
|
|
62
|
+
const auth = useAuth()
|
|
63
|
+
// Establish a live session, exactly as the boot probe does.
|
|
64
|
+
respondWith(auth.api.axiosForTest, 200)
|
|
65
|
+
expect(await ensureInitialAuth()).toBe(true)
|
|
66
|
+
expect(auth.user.value).not.toBeNull()
|
|
67
|
+
|
|
68
|
+
const transport = axios.create({ baseURL: 'http://localhost' })
|
|
69
|
+
auth.registerAxios(transport)
|
|
70
|
+
respondWith(transport, 401)
|
|
71
|
+
|
|
72
|
+
const onLogout = vi.fn()
|
|
73
|
+
createAuth({ baseURL: 'http://localhost' }).on(AuthState.LOGOUT, onLogout)
|
|
74
|
+
|
|
75
|
+
await expect(transport.get('/people')).rejects.toThrow()
|
|
76
|
+
|
|
77
|
+
expect(auth.user.value).toBeNull()
|
|
78
|
+
expect(onLogout).toHaveBeenCalledOnce()
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('does not log out on a 401 from a public auth screen', async () => {
|
|
82
|
+
router.currentRoute.value = route('auth-login', '/login')
|
|
83
|
+
const auth = useAuth()
|
|
84
|
+
respondWith(auth.api.axiosForTest, 200)
|
|
85
|
+
expect(await ensureInitialAuth()).toBe(true)
|
|
86
|
+
|
|
87
|
+
const transport = axios.create({ baseURL: 'http://localhost' })
|
|
88
|
+
auth.registerAxios(transport)
|
|
89
|
+
respondWith(transport, 401)
|
|
90
|
+
|
|
91
|
+
const onLogout = vi.fn()
|
|
92
|
+
createAuth({ baseURL: 'http://localhost' }).on(AuthState.LOGOUT, onLogout)
|
|
93
|
+
|
|
94
|
+
await expect(transport.get('/authentication/me')).rejects.toThrow()
|
|
95
|
+
|
|
96
|
+
expect(auth.user.value).not.toBeNull()
|
|
97
|
+
expect(onLogout).not.toHaveBeenCalled()
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it('re-probes the session on the next boot after a mid-session logout', async () => {
|
|
101
|
+
const auth = useAuth()
|
|
102
|
+
respondWith(auth.api.axiosForTest, 200)
|
|
103
|
+
expect(await ensureInitialAuth()).toBe(true)
|
|
104
|
+
|
|
105
|
+
await auth.logout()
|
|
106
|
+
|
|
107
|
+
// The cached boot result must be gone: the next check hits the server,
|
|
108
|
+
// which now says the session is dead.
|
|
109
|
+
respondWith(auth.api.axiosForTest, 401)
|
|
110
|
+
const probe = vi.spyOn(auth.api, 'getCurrentUser')
|
|
111
|
+
expect(await ensureInitialAuth()).toBe(false)
|
|
112
|
+
expect(probe).toHaveBeenCalledOnce()
|
|
113
|
+
})
|
|
114
|
+
})
|
package/src/useAuth.ts
CHANGED
|
@@ -124,13 +124,20 @@ export function getRedirectConfig(): NormalizedRedirectConfig {
|
|
|
124
124
|
/** True on login/signup/callback screens, where a logged-out 401 is expected. */
|
|
125
125
|
export function isAuthPublicPath(): boolean {
|
|
126
126
|
const route = autoRedirectRouter?.currentRoute?.value as { name?: unknown, path?: string } | undefined
|
|
127
|
-
return routeIsAuthPublic(route, redirectConfig?.noAuthRoutes ?? [])
|
|
127
|
+
if (route) return routeIsAuthPublic(route, redirectConfig?.noAuthRoutes ?? [])
|
|
128
|
+
// Router not connected yet: fall back to the address bar so a 401 during
|
|
129
|
+
// boot still ends a dead session instead of being swallowed.
|
|
130
|
+
return routeIsAuthPublic(null, redirectConfig?.noAuthRoutes ?? [])
|
|
128
131
|
}
|
|
129
132
|
|
|
130
133
|
// Initialize auth
|
|
131
134
|
export function createAuth(params: InitParams): AuthInstance {
|
|
132
135
|
if (authApi === null) {
|
|
133
|
-
authApi = new AuthApi(
|
|
136
|
+
authApi = new AuthApi(
|
|
137
|
+
params.baseURL,
|
|
138
|
+
error => { useAuth().handleApiError(error) },
|
|
139
|
+
() => { useAuth().handleUnauthorized() },
|
|
140
|
+
)
|
|
134
141
|
}
|
|
135
142
|
|
|
136
143
|
if (eventEmitter === null) {
|
|
@@ -364,13 +371,40 @@ export function useAuth() {
|
|
|
364
371
|
// Ignore logout errors
|
|
365
372
|
})
|
|
366
373
|
// Clear local state regardless of API result
|
|
374
|
+
clearSession()
|
|
375
|
+
// Emit logout event
|
|
376
|
+
emitter.emit(AuthState.LOGOUT)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Drop everything that says "logged in". Also invalidates the cached boot
|
|
381
|
+
* probe, so the next navigation re-checks the session instead of trusting
|
|
382
|
+
* a result from before it died.
|
|
383
|
+
*/
|
|
384
|
+
function clearSession() {
|
|
367
385
|
api.setSessionToken(null)
|
|
368
386
|
pendingMfa.value = null
|
|
369
387
|
accountInfo.value = null
|
|
370
388
|
tenants.value = []
|
|
371
389
|
currentTenant.value = null
|
|
372
390
|
api.setTenantId(null)
|
|
373
|
-
|
|
391
|
+
resetInitialAuth()
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* An authenticated call came back 401: the server no longer recognises the
|
|
396
|
+
* session. Treat it as a logout so app shells redirect to login. A 401 on a
|
|
397
|
+
* public auth screen (login, callback) is the normal logged-out state, and
|
|
398
|
+
* one while already logged out has nothing to end.
|
|
399
|
+
*/
|
|
400
|
+
function handleUnauthorized() {
|
|
401
|
+
// A 401 on a public auth screen is the normal logged-out state.
|
|
402
|
+
if (isAuthPublicPath()) return
|
|
403
|
+
// Only end a session that was actually established. A cold boot whose
|
|
404
|
+
// first /me is 401 is just "logged out" — clearing here would wipe the
|
|
405
|
+
// check still in flight and the guard would never resolve.
|
|
406
|
+
if (!getIsLoggedIn()) return
|
|
407
|
+
clearSession()
|
|
374
408
|
emitter.emit(AuthState.LOGOUT)
|
|
375
409
|
}
|
|
376
410
|
|
|
@@ -826,6 +860,7 @@ export function useAuth() {
|
|
|
826
860
|
requiresMfa,
|
|
827
861
|
beginMfa,
|
|
828
862
|
handleApiError,
|
|
863
|
+
handleUnauthorized,
|
|
829
864
|
authDestinationRoute,
|
|
830
865
|
|
|
831
866
|
// Full account info (for advanced use cases)
|
|
@@ -921,5 +956,7 @@ export function useAuth() {
|
|
|
921
956
|
|
|
922
957
|
// Axios integration
|
|
923
958
|
registerAxios: (instance: any) => api.registerAxios(instance),
|
|
959
|
+
/** @internal test hook */
|
|
960
|
+
api,
|
|
924
961
|
}
|
|
925
962
|
}
|