@bagelink/auth 1.20.78 → 1.20.80
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 +3 -1
- package/dist/index.cjs +105 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +105 -7
- package/dist/mfa.d.ts +44 -0
- package/dist/useAuth.d.ts +28 -4
- package/package.json +1 -1
- package/src/api.ts +10 -1
- package/src/index.ts +1 -0
- package/src/mfa.test.ts +40 -0
- package/src/mfa.ts +76 -0
- package/src/router.test.ts +41 -1
- package/src/router.ts +11 -0
- package/src/useAuth.ts +56 -7
package/dist/api.d.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
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
|
+
private onApiError?;
|
|
4
5
|
private api;
|
|
5
6
|
private currentTenantId;
|
|
6
7
|
private externalAxiosInstances;
|
|
7
8
|
private sessionToken;
|
|
8
9
|
/** Keep replacement sessions in memory; the server owns the HttpOnly cookie. */
|
|
9
10
|
setSessionToken(token: string | null): void;
|
|
10
|
-
constructor(baseURL?: string);
|
|
11
|
+
constructor(baseURL?: string, onApiError?: ((error: unknown) => void) | undefined);
|
|
12
|
+
private observeErrors;
|
|
11
13
|
/**
|
|
12
14
|
* Register an external axios instance so that tenant headers
|
|
13
15
|
* are automatically applied to it when setTenantId() is called.
|
package/dist/index.cjs
CHANGED
|
@@ -61,13 +61,15 @@ function queryParams() {
|
|
|
61
61
|
return result;
|
|
62
62
|
}
|
|
63
63
|
class AuthApi {
|
|
64
|
-
constructor(baseURL = "") {
|
|
64
|
+
constructor(baseURL = "", onApiError) {
|
|
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
|
+
this.onApiError = onApiError;
|
|
69
70
|
this.api = createAxiosInstance(baseURL);
|
|
70
71
|
this.setupInterceptors();
|
|
72
|
+
this.observeErrors(this.api);
|
|
71
73
|
}
|
|
72
74
|
/** Keep replacement sessions in memory; the server owns the HttpOnly cookie. */
|
|
73
75
|
setSessionToken(token) {
|
|
@@ -77,11 +79,19 @@ class AuthApi {
|
|
|
77
79
|
else delete instance.defaults.headers.common.Authorization;
|
|
78
80
|
}
|
|
79
81
|
}
|
|
82
|
+
observeErrors(instance) {
|
|
83
|
+
instance.interceptors.response.use((response) => response, (error) => {
|
|
84
|
+
var _a;
|
|
85
|
+
(_a = this.onApiError) == null ? void 0 : _a.call(this, error);
|
|
86
|
+
return Promise.reject(error);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
80
89
|
/**
|
|
81
90
|
* Register an external axios instance so that tenant headers
|
|
82
91
|
* are automatically applied to it when setTenantId() is called.
|
|
83
92
|
*/
|
|
84
93
|
registerAxios(instance) {
|
|
94
|
+
if (!this.externalAxiosInstances.has(instance)) this.observeErrors(instance);
|
|
85
95
|
this.externalAxiosInstances.add(instance);
|
|
86
96
|
if (this.sessionToken) instance.defaults.headers.common.Authorization = `Bearer ${this.sessionToken}`;
|
|
87
97
|
if (this.currentTenantId !== null) {
|
|
@@ -459,6 +469,38 @@ const providers = {
|
|
|
459
469
|
okta: { name: "Okta", icon: "sun", color: "#FFB600" },
|
|
460
470
|
facebook: { name: "Facebook", icon: "facebook", color: "#1877F3" }
|
|
461
471
|
};
|
|
472
|
+
function serverStep(value) {
|
|
473
|
+
if (value === void 0) return void 0;
|
|
474
|
+
if (value === "enroll_phone" || value === "verify_factor" || value === "ready") return value;
|
|
475
|
+
throw new Error("Unsupported MFA next step");
|
|
476
|
+
}
|
|
477
|
+
function mfaNextStep(status) {
|
|
478
|
+
const step = serverStep(status.next_step);
|
|
479
|
+
if (step) return step;
|
|
480
|
+
if (status.phone_enrollment_required) return "enroll_phone";
|
|
481
|
+
return (status.require_mfa || status.enabled) && !status.session_verified ? "verify_factor" : "ready";
|
|
482
|
+
}
|
|
483
|
+
function mfaChallengeStep(challenge) {
|
|
484
|
+
return serverStep(challenge.next_step) ?? (challenge.phone_enrollment_required ? "enroll_phone" : "verify_factor");
|
|
485
|
+
}
|
|
486
|
+
function pendingMfaMetadata(response) {
|
|
487
|
+
const metadata = response.metadata;
|
|
488
|
+
const token = (metadata == null ? void 0 : metadata.challenge_token) ?? (metadata == null ? void 0 : metadata.token);
|
|
489
|
+
if (!response.requires_verification || typeof token !== "string" || !token) return null;
|
|
490
|
+
const next = serverStep(metadata == null ? void 0 : metadata.next_step);
|
|
491
|
+
const methods = metadata == null ? void 0 : metadata.methods;
|
|
492
|
+
return {
|
|
493
|
+
challenge_token: token,
|
|
494
|
+
next_step: next ?? ((metadata == null ? void 0 : metadata.phone_enrollment_required) === true ? "enroll_phone" : "verify_factor"),
|
|
495
|
+
methods: Array.isArray(methods) ? methods.filter((method) => ["sms", "email", "totp"].includes(method)) : []
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function isMfaRequiredError(error) {
|
|
499
|
+
var _a, _b, _c;
|
|
500
|
+
const response = error == null ? void 0 : error.response;
|
|
501
|
+
const code = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.code) ?? ((_c = (_b = response == null ? void 0 : response.data) == null ? void 0 : _b.detail) == null ? void 0 : _c.code);
|
|
502
|
+
return (response == null ? void 0 : response.status) === 403 && (code === "mfa_required" || code === "mfa_enrollment_required");
|
|
503
|
+
}
|
|
462
504
|
function getRedirectUrl(router2, config) {
|
|
463
505
|
const redirect2 = router2.currentRoute.value.query[config.queryKey];
|
|
464
506
|
return redirect2 || config.fallback;
|
|
@@ -1037,6 +1079,7 @@ let redirectConfig = null;
|
|
|
1037
1079
|
let autoRedirectRouter = null;
|
|
1038
1080
|
let cachedAuthGuard = null;
|
|
1039
1081
|
let tenancyEnabled = false;
|
|
1082
|
+
let mfaApi;
|
|
1040
1083
|
const pendingMfa = vue.ref(null);
|
|
1041
1084
|
const accountInfo = vue.ref(null);
|
|
1042
1085
|
const tenants = vue.ref([]);
|
|
@@ -1059,7 +1102,9 @@ function getRedirectConfig() {
|
|
|
1059
1102
|
}
|
|
1060
1103
|
function createAuth(params) {
|
|
1061
1104
|
if (authApi === null) {
|
|
1062
|
-
authApi = new AuthApi(params.baseURL)
|
|
1105
|
+
authApi = new AuthApi(params.baseURL, (error) => {
|
|
1106
|
+
useAuth().handleApiError(error);
|
|
1107
|
+
});
|
|
1063
1108
|
}
|
|
1064
1109
|
if (eventEmitter === null) {
|
|
1065
1110
|
eventEmitter = new EventEmitter();
|
|
@@ -1068,6 +1113,7 @@ function createAuth(params) {
|
|
|
1068
1113
|
redirectConfig = normalizeRedirectConfig(params.redirect);
|
|
1069
1114
|
}
|
|
1070
1115
|
tenancyEnabled = params.tenancy ?? false;
|
|
1116
|
+
mfaApi = params.mfa;
|
|
1071
1117
|
if (redirectConfig == null ? void 0 : redirectConfig.autoRedirect) {
|
|
1072
1118
|
setupAutoRedirect();
|
|
1073
1119
|
}
|
|
@@ -1246,15 +1292,42 @@ function useAuth() {
|
|
|
1246
1292
|
emitter.emit(AuthState.LOGOUT);
|
|
1247
1293
|
}
|
|
1248
1294
|
function captureMfa(response) {
|
|
1249
|
-
const metadata = response
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
pendingMfa.value = { ...response, metadata: { ...metadata, challenge_token: token } };
|
|
1295
|
+
const metadata = pendingMfaMetadata(response);
|
|
1296
|
+
if (metadata) {
|
|
1297
|
+
pendingMfa.value = { ...response, metadata };
|
|
1253
1298
|
return true;
|
|
1254
1299
|
}
|
|
1255
1300
|
pendingMfa.value = null;
|
|
1256
1301
|
return false;
|
|
1257
1302
|
}
|
|
1303
|
+
async function requiresMfa() {
|
|
1304
|
+
if (pendingMfa.value) return true;
|
|
1305
|
+
if (!mfaApi) return false;
|
|
1306
|
+
return mfaNextStep(await mfaApi.status()) !== "ready";
|
|
1307
|
+
}
|
|
1308
|
+
async function beginMfa(flowApi = mfaApi, force = false) {
|
|
1309
|
+
if (pendingMfa.value) return pendingMfa.value.metadata;
|
|
1310
|
+
if (!flowApi) throw new Error("MFA API is not configured");
|
|
1311
|
+
const status = await flowApi.status();
|
|
1312
|
+
if (!force && mfaNextStep(status) === "ready") return null;
|
|
1313
|
+
if (force && status.session_verified && mfaNextStep(status) === "ready") return null;
|
|
1314
|
+
const challenge = await flowApi.stepUp.start();
|
|
1315
|
+
const metadata = pendingMfaMetadata({ requires_verification: true, metadata: { ...challenge } });
|
|
1316
|
+
if (!metadata) throw new Error("Invalid MFA challenge");
|
|
1317
|
+
pendingMfa.value = { success: false, requires_verification: true, metadata };
|
|
1318
|
+
return metadata;
|
|
1319
|
+
}
|
|
1320
|
+
function handleApiError(error) {
|
|
1321
|
+
if (!mfaApi || !isMfaRequiredError(error) || !autoRedirectRouter) return false;
|
|
1322
|
+
const current = autoRedirectRouter.currentRoute.value;
|
|
1323
|
+
if (current.name !== "auth-mfa") {
|
|
1324
|
+
void autoRedirectRouter.replace({ name: "auth-mfa", query: { redirect: current.fullPath } });
|
|
1325
|
+
}
|
|
1326
|
+
return true;
|
|
1327
|
+
}
|
|
1328
|
+
function authDestinationRoute(destination) {
|
|
1329
|
+
return pendingMfa.value && pendingMfa.value.metadata.next_step !== "ready" ? { name: "auth-mfa", query: { redirect: destination } } : destination;
|
|
1330
|
+
}
|
|
1258
1331
|
async function completeMfa(response) {
|
|
1259
1332
|
if (!response.success || response.requires_verification) throw new Error("MFA verification failed");
|
|
1260
1333
|
if (!response.session_token) throw new Error("MFA response missing replacement session");
|
|
@@ -1432,7 +1505,7 @@ function useAuth() {
|
|
|
1432
1505
|
await api.acceptInvitation(token, data);
|
|
1433
1506
|
await checkAuth();
|
|
1434
1507
|
}
|
|
1435
|
-
async function signup(newUser) {
|
|
1508
|
+
async function signup(newUser, options = {}) {
|
|
1436
1509
|
const hasPassword = newUser.password !== void 0 && newUser.password.length > 0;
|
|
1437
1510
|
if (hasPassword && newUser.password !== newUser.confirmPassword) {
|
|
1438
1511
|
throw new Error("Passwords do not match");
|
|
@@ -1444,6 +1517,13 @@ function useAuth() {
|
|
|
1444
1517
|
phone_number: newUser.phone_number,
|
|
1445
1518
|
password: newUser.password
|
|
1446
1519
|
});
|
|
1520
|
+
if (!data.success && !data.requires_verification) throw new Error(data.message || "Registration failed");
|
|
1521
|
+
if (captureMfa(data)) return data;
|
|
1522
|
+
if (options.login && newUser.password) {
|
|
1523
|
+
const response = await login({ email: newUser.email, password: newUser.password });
|
|
1524
|
+
emitter.emit(AuthState.SIGNUP);
|
|
1525
|
+
return response;
|
|
1526
|
+
}
|
|
1447
1527
|
if (data.success === true && data.requires_verification !== true) {
|
|
1448
1528
|
await checkAuth();
|
|
1449
1529
|
}
|
|
@@ -1527,6 +1607,10 @@ function useAuth() {
|
|
|
1527
1607
|
user,
|
|
1528
1608
|
pendingMfa,
|
|
1529
1609
|
completeMfa,
|
|
1610
|
+
requiresMfa,
|
|
1611
|
+
beginMfa,
|
|
1612
|
+
handleApiError,
|
|
1613
|
+
authDestinationRoute,
|
|
1530
1614
|
// Full account info (for advanced use cases)
|
|
1531
1615
|
accountInfo,
|
|
1532
1616
|
// SSO Providers (ready to use!)
|
|
@@ -1617,6 +1701,7 @@ function resetAuthState() {
|
|
|
1617
1701
|
}
|
|
1618
1702
|
function authGuard() {
|
|
1619
1703
|
return async function guard(to, _from) {
|
|
1704
|
+
var _a;
|
|
1620
1705
|
const auth = useAuth();
|
|
1621
1706
|
const config = getRedirectConfig();
|
|
1622
1707
|
const requiresAuth = to.meta[config.authMetaKey];
|
|
@@ -1627,6 +1712,15 @@ function authGuard() {
|
|
|
1627
1712
|
await ensureInitialAuth();
|
|
1628
1713
|
}
|
|
1629
1714
|
const isAuthenticated = !!auth.user.value;
|
|
1715
|
+
if (to.name !== "auth-mfa" && (requiresAuth || requiresNoAuth) && (isAuthenticated || ((_a = auth.pendingMfa) == null ? void 0 : _a.value))) {
|
|
1716
|
+
try {
|
|
1717
|
+
if (await auth.requiresMfa()) {
|
|
1718
|
+
return { name: "auth-mfa", query: { redirect: requiresNoAuth ? config.authenticatedRedirect : to.fullPath } };
|
|
1719
|
+
}
|
|
1720
|
+
} catch {
|
|
1721
|
+
return { name: "auth-mfa", query: { redirect: to.fullPath } };
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1630
1724
|
if (isAuthenticated && requiresNoAuth) {
|
|
1631
1725
|
return config.authenticatedRedirect;
|
|
1632
1726
|
}
|
|
@@ -1701,9 +1795,13 @@ exports.getRedirectConfig = getRedirectConfig;
|
|
|
1701
1795
|
exports.getRedirectUrl = getRedirectUrl;
|
|
1702
1796
|
exports.getSSOProvider = getSSOProvider;
|
|
1703
1797
|
exports.handleSsoPopup = handleSsoPopup;
|
|
1798
|
+
exports.isMfaRequiredError = isMfaRequiredError;
|
|
1704
1799
|
exports.isSupportedProvider = isSupportedProvider;
|
|
1705
1800
|
exports.isValidRedirect = isValidRedirect;
|
|
1801
|
+
exports.mfaChallengeStep = mfaChallengeStep;
|
|
1802
|
+
exports.mfaNextStep = mfaNextStep;
|
|
1706
1803
|
exports.normalizeRedirectConfig = normalizeRedirectConfig;
|
|
1804
|
+
exports.pendingMfaMetadata = pendingMfaMetadata;
|
|
1707
1805
|
exports.performRedirect = performRedirect;
|
|
1708
1806
|
exports.providers = providers;
|
|
1709
1807
|
exports.resetAuthState = resetAuthState;
|
package/dist/index.d.ts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -59,13 +59,15 @@ function queryParams() {
|
|
|
59
59
|
return result;
|
|
60
60
|
}
|
|
61
61
|
class AuthApi {
|
|
62
|
-
constructor(baseURL = "") {
|
|
62
|
+
constructor(baseURL = "", onApiError) {
|
|
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
|
+
this.onApiError = onApiError;
|
|
67
68
|
this.api = createAxiosInstance(baseURL);
|
|
68
69
|
this.setupInterceptors();
|
|
70
|
+
this.observeErrors(this.api);
|
|
69
71
|
}
|
|
70
72
|
/** Keep replacement sessions in memory; the server owns the HttpOnly cookie. */
|
|
71
73
|
setSessionToken(token) {
|
|
@@ -75,11 +77,19 @@ class AuthApi {
|
|
|
75
77
|
else delete instance.defaults.headers.common.Authorization;
|
|
76
78
|
}
|
|
77
79
|
}
|
|
80
|
+
observeErrors(instance) {
|
|
81
|
+
instance.interceptors.response.use((response) => response, (error) => {
|
|
82
|
+
var _a;
|
|
83
|
+
(_a = this.onApiError) == null ? void 0 : _a.call(this, error);
|
|
84
|
+
return Promise.reject(error);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
78
87
|
/**
|
|
79
88
|
* Register an external axios instance so that tenant headers
|
|
80
89
|
* are automatically applied to it when setTenantId() is called.
|
|
81
90
|
*/
|
|
82
91
|
registerAxios(instance) {
|
|
92
|
+
if (!this.externalAxiosInstances.has(instance)) this.observeErrors(instance);
|
|
83
93
|
this.externalAxiosInstances.add(instance);
|
|
84
94
|
if (this.sessionToken) instance.defaults.headers.common.Authorization = `Bearer ${this.sessionToken}`;
|
|
85
95
|
if (this.currentTenantId !== null) {
|
|
@@ -457,6 +467,38 @@ const providers = {
|
|
|
457
467
|
okta: { name: "Okta", icon: "sun", color: "#FFB600" },
|
|
458
468
|
facebook: { name: "Facebook", icon: "facebook", color: "#1877F3" }
|
|
459
469
|
};
|
|
470
|
+
function serverStep(value) {
|
|
471
|
+
if (value === void 0) return void 0;
|
|
472
|
+
if (value === "enroll_phone" || value === "verify_factor" || value === "ready") return value;
|
|
473
|
+
throw new Error("Unsupported MFA next step");
|
|
474
|
+
}
|
|
475
|
+
function mfaNextStep(status) {
|
|
476
|
+
const step = serverStep(status.next_step);
|
|
477
|
+
if (step) return step;
|
|
478
|
+
if (status.phone_enrollment_required) return "enroll_phone";
|
|
479
|
+
return (status.require_mfa || status.enabled) && !status.session_verified ? "verify_factor" : "ready";
|
|
480
|
+
}
|
|
481
|
+
function mfaChallengeStep(challenge) {
|
|
482
|
+
return serverStep(challenge.next_step) ?? (challenge.phone_enrollment_required ? "enroll_phone" : "verify_factor");
|
|
483
|
+
}
|
|
484
|
+
function pendingMfaMetadata(response) {
|
|
485
|
+
const metadata = response.metadata;
|
|
486
|
+
const token = (metadata == null ? void 0 : metadata.challenge_token) ?? (metadata == null ? void 0 : metadata.token);
|
|
487
|
+
if (!response.requires_verification || typeof token !== "string" || !token) return null;
|
|
488
|
+
const next = serverStep(metadata == null ? void 0 : metadata.next_step);
|
|
489
|
+
const methods = metadata == null ? void 0 : metadata.methods;
|
|
490
|
+
return {
|
|
491
|
+
challenge_token: token,
|
|
492
|
+
next_step: next ?? ((metadata == null ? void 0 : metadata.phone_enrollment_required) === true ? "enroll_phone" : "verify_factor"),
|
|
493
|
+
methods: Array.isArray(methods) ? methods.filter((method) => ["sms", "email", "totp"].includes(method)) : []
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function isMfaRequiredError(error) {
|
|
497
|
+
var _a, _b, _c;
|
|
498
|
+
const response = error == null ? void 0 : error.response;
|
|
499
|
+
const code = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.code) ?? ((_c = (_b = response == null ? void 0 : response.data) == null ? void 0 : _b.detail) == null ? void 0 : _c.code);
|
|
500
|
+
return (response == null ? void 0 : response.status) === 403 && (code === "mfa_required" || code === "mfa_enrollment_required");
|
|
501
|
+
}
|
|
460
502
|
function getRedirectUrl(router2, config) {
|
|
461
503
|
const redirect2 = router2.currentRoute.value.query[config.queryKey];
|
|
462
504
|
return redirect2 || config.fallback;
|
|
@@ -1035,6 +1077,7 @@ let redirectConfig = null;
|
|
|
1035
1077
|
let autoRedirectRouter = null;
|
|
1036
1078
|
let cachedAuthGuard = null;
|
|
1037
1079
|
let tenancyEnabled = false;
|
|
1080
|
+
let mfaApi;
|
|
1038
1081
|
const pendingMfa = ref(null);
|
|
1039
1082
|
const accountInfo = ref(null);
|
|
1040
1083
|
const tenants = ref([]);
|
|
@@ -1057,7 +1100,9 @@ function getRedirectConfig() {
|
|
|
1057
1100
|
}
|
|
1058
1101
|
function createAuth(params) {
|
|
1059
1102
|
if (authApi === null) {
|
|
1060
|
-
authApi = new AuthApi(params.baseURL)
|
|
1103
|
+
authApi = new AuthApi(params.baseURL, (error) => {
|
|
1104
|
+
useAuth().handleApiError(error);
|
|
1105
|
+
});
|
|
1061
1106
|
}
|
|
1062
1107
|
if (eventEmitter === null) {
|
|
1063
1108
|
eventEmitter = new EventEmitter();
|
|
@@ -1066,6 +1111,7 @@ function createAuth(params) {
|
|
|
1066
1111
|
redirectConfig = normalizeRedirectConfig(params.redirect);
|
|
1067
1112
|
}
|
|
1068
1113
|
tenancyEnabled = params.tenancy ?? false;
|
|
1114
|
+
mfaApi = params.mfa;
|
|
1069
1115
|
if (redirectConfig == null ? void 0 : redirectConfig.autoRedirect) {
|
|
1070
1116
|
setupAutoRedirect();
|
|
1071
1117
|
}
|
|
@@ -1244,15 +1290,42 @@ function useAuth() {
|
|
|
1244
1290
|
emitter.emit(AuthState.LOGOUT);
|
|
1245
1291
|
}
|
|
1246
1292
|
function captureMfa(response) {
|
|
1247
|
-
const metadata = response
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
pendingMfa.value = { ...response, metadata: { ...metadata, challenge_token: token } };
|
|
1293
|
+
const metadata = pendingMfaMetadata(response);
|
|
1294
|
+
if (metadata) {
|
|
1295
|
+
pendingMfa.value = { ...response, metadata };
|
|
1251
1296
|
return true;
|
|
1252
1297
|
}
|
|
1253
1298
|
pendingMfa.value = null;
|
|
1254
1299
|
return false;
|
|
1255
1300
|
}
|
|
1301
|
+
async function requiresMfa() {
|
|
1302
|
+
if (pendingMfa.value) return true;
|
|
1303
|
+
if (!mfaApi) return false;
|
|
1304
|
+
return mfaNextStep(await mfaApi.status()) !== "ready";
|
|
1305
|
+
}
|
|
1306
|
+
async function beginMfa(flowApi = mfaApi, force = false) {
|
|
1307
|
+
if (pendingMfa.value) return pendingMfa.value.metadata;
|
|
1308
|
+
if (!flowApi) throw new Error("MFA API is not configured");
|
|
1309
|
+
const status = await flowApi.status();
|
|
1310
|
+
if (!force && mfaNextStep(status) === "ready") return null;
|
|
1311
|
+
if (force && status.session_verified && mfaNextStep(status) === "ready") return null;
|
|
1312
|
+
const challenge = await flowApi.stepUp.start();
|
|
1313
|
+
const metadata = pendingMfaMetadata({ requires_verification: true, metadata: { ...challenge } });
|
|
1314
|
+
if (!metadata) throw new Error("Invalid MFA challenge");
|
|
1315
|
+
pendingMfa.value = { success: false, requires_verification: true, metadata };
|
|
1316
|
+
return metadata;
|
|
1317
|
+
}
|
|
1318
|
+
function handleApiError(error) {
|
|
1319
|
+
if (!mfaApi || !isMfaRequiredError(error) || !autoRedirectRouter) return false;
|
|
1320
|
+
const current = autoRedirectRouter.currentRoute.value;
|
|
1321
|
+
if (current.name !== "auth-mfa") {
|
|
1322
|
+
void autoRedirectRouter.replace({ name: "auth-mfa", query: { redirect: current.fullPath } });
|
|
1323
|
+
}
|
|
1324
|
+
return true;
|
|
1325
|
+
}
|
|
1326
|
+
function authDestinationRoute(destination) {
|
|
1327
|
+
return pendingMfa.value && pendingMfa.value.metadata.next_step !== "ready" ? { name: "auth-mfa", query: { redirect: destination } } : destination;
|
|
1328
|
+
}
|
|
1256
1329
|
async function completeMfa(response) {
|
|
1257
1330
|
if (!response.success || response.requires_verification) throw new Error("MFA verification failed");
|
|
1258
1331
|
if (!response.session_token) throw new Error("MFA response missing replacement session");
|
|
@@ -1430,7 +1503,7 @@ function useAuth() {
|
|
|
1430
1503
|
await api.acceptInvitation(token, data);
|
|
1431
1504
|
await checkAuth();
|
|
1432
1505
|
}
|
|
1433
|
-
async function signup(newUser) {
|
|
1506
|
+
async function signup(newUser, options = {}) {
|
|
1434
1507
|
const hasPassword = newUser.password !== void 0 && newUser.password.length > 0;
|
|
1435
1508
|
if (hasPassword && newUser.password !== newUser.confirmPassword) {
|
|
1436
1509
|
throw new Error("Passwords do not match");
|
|
@@ -1442,6 +1515,13 @@ function useAuth() {
|
|
|
1442
1515
|
phone_number: newUser.phone_number,
|
|
1443
1516
|
password: newUser.password
|
|
1444
1517
|
});
|
|
1518
|
+
if (!data.success && !data.requires_verification) throw new Error(data.message || "Registration failed");
|
|
1519
|
+
if (captureMfa(data)) return data;
|
|
1520
|
+
if (options.login && newUser.password) {
|
|
1521
|
+
const response = await login({ email: newUser.email, password: newUser.password });
|
|
1522
|
+
emitter.emit(AuthState.SIGNUP);
|
|
1523
|
+
return response;
|
|
1524
|
+
}
|
|
1445
1525
|
if (data.success === true && data.requires_verification !== true) {
|
|
1446
1526
|
await checkAuth();
|
|
1447
1527
|
}
|
|
@@ -1525,6 +1605,10 @@ function useAuth() {
|
|
|
1525
1605
|
user,
|
|
1526
1606
|
pendingMfa,
|
|
1527
1607
|
completeMfa,
|
|
1608
|
+
requiresMfa,
|
|
1609
|
+
beginMfa,
|
|
1610
|
+
handleApiError,
|
|
1611
|
+
authDestinationRoute,
|
|
1528
1612
|
// Full account info (for advanced use cases)
|
|
1529
1613
|
accountInfo,
|
|
1530
1614
|
// SSO Providers (ready to use!)
|
|
@@ -1615,6 +1699,7 @@ function resetAuthState() {
|
|
|
1615
1699
|
}
|
|
1616
1700
|
function authGuard() {
|
|
1617
1701
|
return async function guard(to, _from) {
|
|
1702
|
+
var _a;
|
|
1618
1703
|
const auth = useAuth();
|
|
1619
1704
|
const config = getRedirectConfig();
|
|
1620
1705
|
const requiresAuth = to.meta[config.authMetaKey];
|
|
@@ -1625,6 +1710,15 @@ function authGuard() {
|
|
|
1625
1710
|
await ensureInitialAuth();
|
|
1626
1711
|
}
|
|
1627
1712
|
const isAuthenticated = !!auth.user.value;
|
|
1713
|
+
if (to.name !== "auth-mfa" && (requiresAuth || requiresNoAuth) && (isAuthenticated || ((_a = auth.pendingMfa) == null ? void 0 : _a.value))) {
|
|
1714
|
+
try {
|
|
1715
|
+
if (await auth.requiresMfa()) {
|
|
1716
|
+
return { name: "auth-mfa", query: { redirect: requiresNoAuth ? config.authenticatedRedirect : to.fullPath } };
|
|
1717
|
+
}
|
|
1718
|
+
} catch {
|
|
1719
|
+
return { name: "auth-mfa", query: { redirect: to.fullPath } };
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1628
1722
|
if (isAuthenticated && requiresNoAuth) {
|
|
1629
1723
|
return config.authenticatedRedirect;
|
|
1630
1724
|
}
|
|
@@ -1700,9 +1794,13 @@ export {
|
|
|
1700
1794
|
getRedirectUrl,
|
|
1701
1795
|
getSSOProvider,
|
|
1702
1796
|
handleSsoPopup,
|
|
1797
|
+
isMfaRequiredError,
|
|
1703
1798
|
isSupportedProvider,
|
|
1704
1799
|
isValidRedirect,
|
|
1800
|
+
mfaChallengeStep,
|
|
1801
|
+
mfaNextStep,
|
|
1705
1802
|
normalizeRedirectConfig,
|
|
1803
|
+
pendingMfaMetadata,
|
|
1706
1804
|
performRedirect,
|
|
1707
1805
|
providers,
|
|
1708
1806
|
resetAuthState,
|
package/dist/mfa.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { AuthenticationResponse } from './types';
|
|
2
|
+
export type MfaNextStep = 'enroll_phone' | 'verify_factor' | 'ready';
|
|
3
|
+
export type MfaMethod = 'sms' | 'email' | 'totp';
|
|
4
|
+
export interface MfaStatus {
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
methods: string[];
|
|
7
|
+
next_step?: MfaNextStep;
|
|
8
|
+
require_mfa?: boolean;
|
|
9
|
+
phone_enrollment_required?: boolean;
|
|
10
|
+
session_verified?: boolean;
|
|
11
|
+
totp_enrolled?: boolean;
|
|
12
|
+
recovery_codes_remaining?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface MfaChallenge {
|
|
15
|
+
token: string;
|
|
16
|
+
methods: string[];
|
|
17
|
+
expires_at: string;
|
|
18
|
+
next_step?: MfaNextStep;
|
|
19
|
+
phone_enrollment_required?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export type MfaStatusPayload = Omit<MfaStatus, 'next_step'> & {
|
|
22
|
+
next_step?: string;
|
|
23
|
+
};
|
|
24
|
+
export type MfaChallengePayload = Omit<MfaChallenge, 'next_step'> & {
|
|
25
|
+
next_step?: string;
|
|
26
|
+
};
|
|
27
|
+
/** Structural mirror of the generated authentication.mfa namespace. */
|
|
28
|
+
export interface MfaFlowApi {
|
|
29
|
+
status(): Promise<MfaStatusPayload>;
|
|
30
|
+
stepUp: {
|
|
31
|
+
start(): Promise<MfaChallengePayload>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Server decisions take precedence; legacy servers retain their previous flow. */
|
|
35
|
+
export declare function mfaNextStep(status: MfaStatusPayload): MfaNextStep;
|
|
36
|
+
export declare function mfaChallengeStep(challenge: Pick<MfaChallengePayload, 'next_step' | 'phone_enrollment_required'>): MfaNextStep;
|
|
37
|
+
export interface PendingMfaMetadata {
|
|
38
|
+
challenge_token: string;
|
|
39
|
+
next_step: MfaNextStep;
|
|
40
|
+
methods: MfaMethod[];
|
|
41
|
+
}
|
|
42
|
+
/** Normalize untyped login metadata once, at the auth-state boundary. */
|
|
43
|
+
export declare function pendingMfaMetadata(response: AuthenticationResponse): PendingMfaMetadata | null;
|
|
44
|
+
export declare function isMfaRequiredError(error: unknown): boolean;
|
package/dist/useAuth.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
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 { MfaFlowApi, PendingMfaMetadata } from './mfa';
|
|
4
5
|
interface InitParams {
|
|
5
6
|
baseURL: string;
|
|
7
|
+
/** Generated MFA namespace; enables shared assurance checks on protected routes. */
|
|
8
|
+
mfa?: MfaFlowApi;
|
|
6
9
|
/**
|
|
7
10
|
* Redirect configuration for authentication flows
|
|
8
11
|
* @see RedirectConfig
|
|
@@ -69,6 +72,8 @@ export declare function useAuth(): {
|
|
|
69
72
|
[key: string]: any;
|
|
70
73
|
};
|
|
71
74
|
challenge_token: string;
|
|
75
|
+
next_step: import('./mfa').MfaNextStep;
|
|
76
|
+
methods: import('./mfa').MfaMethod[];
|
|
72
77
|
} | {
|
|
73
78
|
provider: string;
|
|
74
79
|
sso_user_info: {
|
|
@@ -76,14 +81,16 @@ export declare function useAuth(): {
|
|
|
76
81
|
};
|
|
77
82
|
can_create_account?: boolean | undefined;
|
|
78
83
|
challenge_token: string;
|
|
84
|
+
next_step: import('./mfa').MfaNextStep;
|
|
85
|
+
methods: import('./mfa').MfaMethod[];
|
|
79
86
|
} | {
|
|
80
87
|
[x: string]: any;
|
|
81
88
|
challenge_token: string;
|
|
89
|
+
next_step: import('./mfa').MfaNextStep;
|
|
90
|
+
methods: import('./mfa').MfaMethod[];
|
|
82
91
|
};
|
|
83
92
|
} | null, (AuthenticationResponse & {
|
|
84
|
-
metadata:
|
|
85
|
-
challenge_token: string;
|
|
86
|
-
};
|
|
93
|
+
metadata: PendingMfaMetadata;
|
|
87
94
|
}) | {
|
|
88
95
|
success: boolean;
|
|
89
96
|
account_id?: string | undefined;
|
|
@@ -100,6 +107,8 @@ export declare function useAuth(): {
|
|
|
100
107
|
[key: string]: any;
|
|
101
108
|
};
|
|
102
109
|
challenge_token: string;
|
|
110
|
+
next_step: import('./mfa').MfaNextStep;
|
|
111
|
+
methods: import('./mfa').MfaMethod[];
|
|
103
112
|
} | {
|
|
104
113
|
provider: string;
|
|
105
114
|
sso_user_info: {
|
|
@@ -107,12 +116,25 @@ export declare function useAuth(): {
|
|
|
107
116
|
};
|
|
108
117
|
can_create_account?: boolean | undefined;
|
|
109
118
|
challenge_token: string;
|
|
119
|
+
next_step: import('./mfa').MfaNextStep;
|
|
120
|
+
methods: import('./mfa').MfaMethod[];
|
|
110
121
|
} | {
|
|
111
122
|
[x: string]: any;
|
|
112
123
|
challenge_token: string;
|
|
124
|
+
next_step: import('./mfa').MfaNextStep;
|
|
125
|
+
methods: import('./mfa').MfaMethod[];
|
|
113
126
|
};
|
|
114
127
|
} | null>;
|
|
115
128
|
completeMfa: (response: AuthenticationResponse) => Promise<void>;
|
|
129
|
+
requiresMfa: () => Promise<boolean>;
|
|
130
|
+
beginMfa: (flowApi?: MfaFlowApi, force?: boolean) => Promise<PendingMfaMetadata | null>;
|
|
131
|
+
handleApiError: (error: unknown) => boolean;
|
|
132
|
+
authDestinationRoute: (destination: string) => string | {
|
|
133
|
+
name: string;
|
|
134
|
+
query: {
|
|
135
|
+
redirect: string;
|
|
136
|
+
};
|
|
137
|
+
};
|
|
116
138
|
accountInfo: import('vue').Ref<{
|
|
117
139
|
id: string;
|
|
118
140
|
account_type: string;
|
|
@@ -250,7 +272,9 @@ export declare function useAuth(): {
|
|
|
250
272
|
password: string;
|
|
251
273
|
}) => Promise<AuthenticationResponse>;
|
|
252
274
|
logout: () => Promise<void>;
|
|
253
|
-
signup: (newUser: NewUser
|
|
275
|
+
signup: (newUser: NewUser, options?: {
|
|
276
|
+
login?: boolean;
|
|
277
|
+
}) => Promise<AuthenticationResponse>;
|
|
254
278
|
checkAuth: () => Promise<boolean>;
|
|
255
279
|
refreshSession: () => Promise<void>;
|
|
256
280
|
sendSMS: (data: SMSSendRequest) => Promise<AuthenticationResponse>;
|
package/package.json
CHANGED
package/src/api.ts
CHANGED
|
@@ -91,9 +91,17 @@ export class AuthApi {
|
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
constructor(baseURL: string = '') {
|
|
94
|
+
constructor(baseURL: string = '', private onApiError?: (error: unknown) => void) {
|
|
95
95
|
this.api = createAxiosInstance(baseURL)
|
|
96
96
|
this.setupInterceptors()
|
|
97
|
+
this.observeErrors(this.api)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private observeErrors(instance: AxiosInstance) {
|
|
101
|
+
instance.interceptors.response.use(response => response, (error: unknown) => {
|
|
102
|
+
this.onApiError?.(error)
|
|
103
|
+
return Promise.reject(error)
|
|
104
|
+
})
|
|
97
105
|
}
|
|
98
106
|
|
|
99
107
|
/**
|
|
@@ -101,6 +109,7 @@ export class AuthApi {
|
|
|
101
109
|
* are automatically applied to it when setTenantId() is called.
|
|
102
110
|
*/
|
|
103
111
|
registerAxios(instance: AxiosInstance) {
|
|
112
|
+
if (!this.externalAxiosInstances.has(instance)) this.observeErrors(instance)
|
|
104
113
|
this.externalAxiosInstances.add(instance)
|
|
105
114
|
if (this.sessionToken) instance.defaults.headers.common.Authorization = `Bearer ${this.sessionToken}`
|
|
106
115
|
// Apply current tenant immediately if already set
|
package/src/index.ts
CHANGED
package/src/mfa.test.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { isMfaRequiredError, pendingMfaMetadata } from './mfa'
|
|
3
|
+
|
|
4
|
+
describe('MFA auth-state boundary', () => {
|
|
5
|
+
it('normalizes login metadata and restricts selectable factors', () => {
|
|
6
|
+
expect(pendingMfaMetadata({
|
|
7
|
+
success: false, requires_verification: true,
|
|
8
|
+
metadata: { token: 'challenge', next_step: 'verify_factor', methods: ['sms', 'email', 'totp', 'recovery', 'unsupported'] },
|
|
9
|
+
})).toEqual({
|
|
10
|
+
challenge_token: 'challenge', next_step: 'verify_factor', methods: ['sms', 'email', 'totp'],
|
|
11
|
+
})
|
|
12
|
+
})
|
|
13
|
+
it('supports legacy enrollment metadata', () => {
|
|
14
|
+
expect(pendingMfaMetadata({
|
|
15
|
+
success: false, requires_verification: true,
|
|
16
|
+
metadata: { challenge_token: 'challenge', phone_enrollment_required: true },
|
|
17
|
+
})?.next_step).toBe('enroll_phone')
|
|
18
|
+
})
|
|
19
|
+
it('does not treat ordinary OTP delivery metadata as an MFA challenge', () => {
|
|
20
|
+
expect(pendingMfaMetadata({
|
|
21
|
+
success: false, requires_verification: true,
|
|
22
|
+
metadata: { nonce: 'nonce', verification_hash: 'hash', timestamp: 1 },
|
|
23
|
+
})).toBeNull()
|
|
24
|
+
})
|
|
25
|
+
it('rejects unrecognized server transitions', () => {
|
|
26
|
+
expect(() => pendingMfaMetadata({
|
|
27
|
+
success: false, requires_verification: true,
|
|
28
|
+
metadata: { token: 'challenge', next_step: 'unsupported' },
|
|
29
|
+
})).toThrow('Unsupported MFA next step')
|
|
30
|
+
})
|
|
31
|
+
it('recognizes only MFA-specific forbidden responses', () => {
|
|
32
|
+
for (const code of ['mfa_required', 'mfa_enrollment_required']) {
|
|
33
|
+
expect(isMfaRequiredError({ response: { status: 403, data: { code } } })).toBe(true)
|
|
34
|
+
expect(isMfaRequiredError({ response: { status: 403, data: { detail: { code } } } })).toBe(true)
|
|
35
|
+
}
|
|
36
|
+
for (const error of [null, {}, { response: { status: 401, data: { code: 'mfa_required' } } }, { response: { status: 403, data: { code: 'permission_denied' } } }]) {
|
|
37
|
+
expect(isMfaRequiredError(error)).toBe(false)
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
})
|
package/src/mfa.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { AuthenticationResponse } from './types'
|
|
2
|
+
|
|
3
|
+
export type MfaNextStep = 'enroll_phone' | 'verify_factor' | 'ready'
|
|
4
|
+
export type MfaMethod = 'sms' | 'email' | 'totp'
|
|
5
|
+
export interface MfaStatus {
|
|
6
|
+
enabled: boolean
|
|
7
|
+
methods: string[]
|
|
8
|
+
next_step?: MfaNextStep
|
|
9
|
+
require_mfa?: boolean
|
|
10
|
+
phone_enrollment_required?: boolean
|
|
11
|
+
session_verified?: boolean
|
|
12
|
+
totp_enrolled?: boolean
|
|
13
|
+
recovery_codes_remaining?: number
|
|
14
|
+
}
|
|
15
|
+
export interface MfaChallenge {
|
|
16
|
+
token: string
|
|
17
|
+
methods: string[]
|
|
18
|
+
expires_at: string
|
|
19
|
+
next_step?: MfaNextStep
|
|
20
|
+
phone_enrollment_required?: boolean
|
|
21
|
+
}
|
|
22
|
+
// Current SDK codegen widens inline OpenAPI enums to string. Validate at ingress;
|
|
23
|
+
// application state and UI still receive only the closed MfaNextStep union.
|
|
24
|
+
export type MfaStatusPayload = Omit<MfaStatus, 'next_step'> & { next_step?: string }
|
|
25
|
+
export type MfaChallengePayload = Omit<MfaChallenge, 'next_step'> & { next_step?: string }
|
|
26
|
+
/** Structural mirror of the generated authentication.mfa namespace. */
|
|
27
|
+
export interface MfaFlowApi {
|
|
28
|
+
status(): Promise<MfaStatusPayload>
|
|
29
|
+
stepUp: { start(): Promise<MfaChallengePayload> }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function serverStep(value: unknown): MfaNextStep | undefined {
|
|
33
|
+
if (value === undefined) return undefined
|
|
34
|
+
if (value === 'enroll_phone' || value === 'verify_factor' || value === 'ready') return value
|
|
35
|
+
throw new Error('Unsupported MFA next step')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Server decisions take precedence; legacy servers retain their previous flow. */
|
|
39
|
+
export function mfaNextStep(status: MfaStatusPayload): MfaNextStep {
|
|
40
|
+
const step = serverStep(status.next_step)
|
|
41
|
+
if (step) return step
|
|
42
|
+
if (status.phone_enrollment_required) return 'enroll_phone'
|
|
43
|
+
return (status.require_mfa || status.enabled) && !status.session_verified ? 'verify_factor' : 'ready'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function mfaChallengeStep(challenge: Pick<MfaChallengePayload, 'next_step' | 'phone_enrollment_required'>): MfaNextStep {
|
|
47
|
+
return serverStep(challenge.next_step) ?? (challenge.phone_enrollment_required ? 'enroll_phone' : 'verify_factor')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PendingMfaMetadata {
|
|
51
|
+
challenge_token: string
|
|
52
|
+
next_step: MfaNextStep
|
|
53
|
+
methods: MfaMethod[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Normalize untyped login metadata once, at the auth-state boundary. */
|
|
57
|
+
export function pendingMfaMetadata(response: AuthenticationResponse): PendingMfaMetadata | null {
|
|
58
|
+
const metadata = response.metadata as Record<string, unknown> | undefined
|
|
59
|
+
const token: unknown = metadata?.challenge_token ?? metadata?.token
|
|
60
|
+
if (!response.requires_verification || typeof token !== 'string' || !token) return null
|
|
61
|
+
const next = serverStep(metadata?.next_step)
|
|
62
|
+
const methods: unknown = metadata?.methods
|
|
63
|
+
return {
|
|
64
|
+
challenge_token: token,
|
|
65
|
+
next_step: next ?? (metadata?.phone_enrollment_required === true ? 'enroll_phone' : 'verify_factor'),
|
|
66
|
+
methods: Array.isArray(methods)
|
|
67
|
+
? methods.filter((method): method is MfaMethod => ['sms', 'email', 'totp'].includes(method))
|
|
68
|
+
: [],
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function isMfaRequiredError(error: unknown): boolean {
|
|
73
|
+
const response = (error as { response?: { status?: number; data?: { code?: string; detail?: { code?: string } } } } | null)?.response
|
|
74
|
+
const code = response?.data?.code ?? response?.data?.detail?.code
|
|
75
|
+
return response?.status === 403 && (code === 'mfa_required' || code === 'mfa_enrollment_required')
|
|
76
|
+
}
|
package/src/router.test.ts
CHANGED
|
@@ -4,10 +4,12 @@ import type { RouteLocationNormalized } from 'vue-router'
|
|
|
4
4
|
const authState = vi.hoisted(() => ({
|
|
5
5
|
user: { value: null as object | null },
|
|
6
6
|
ensureInitialAuth: vi.fn<() => Promise<boolean>>(),
|
|
7
|
+
requiresMfa: vi.fn<() => Promise<boolean>>(),
|
|
8
|
+
pendingMfa: { value: null as object | null },
|
|
7
9
|
}))
|
|
8
10
|
|
|
9
11
|
vi.mock('./useAuth', () => ({
|
|
10
|
-
useAuth: () => ({ user: authState.user }),
|
|
12
|
+
useAuth: () => ({ user: authState.user, pendingMfa: authState.pendingMfa, requiresMfa: authState.requiresMfa }),
|
|
11
13
|
getRedirectConfig: () => ({
|
|
12
14
|
authMetaKey: 'auth',
|
|
13
15
|
noAuthRoutes: ['Login'],
|
|
@@ -43,6 +45,8 @@ describe('authGuard', () => {
|
|
|
43
45
|
beforeEach(() => {
|
|
44
46
|
authState.user.value = null
|
|
45
47
|
authState.ensureInitialAuth.mockReset()
|
|
48
|
+
authState.requiresMfa.mockReset().mockResolvedValue(false)
|
|
49
|
+
authState.pendingMfa.value = null
|
|
46
50
|
})
|
|
47
51
|
|
|
48
52
|
it('redirects protected routes when auth bootstrap fails', async () => {
|
|
@@ -59,4 +63,40 @@ describe('authGuard', () => {
|
|
|
59
63
|
|
|
60
64
|
await expect(authGuard()(route(), route())).resolves.toBe(true)
|
|
61
65
|
})
|
|
66
|
+
|
|
67
|
+
it('routes authenticated protected navigation through shared MFA', async () => {
|
|
68
|
+
authState.user.value = {}
|
|
69
|
+
authState.requiresMfa.mockResolvedValue(true)
|
|
70
|
+
await expect(authGuard()(route({ meta: { auth: true } }), route())).resolves.toEqual({
|
|
71
|
+
name: 'auth-mfa', query: { redirect: '/protected' },
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('does not grant access when the assurance probe fails', async () => {
|
|
76
|
+
authState.user.value = {}
|
|
77
|
+
authState.requiresMfa.mockRejectedValue(new Error('offline'))
|
|
78
|
+
await expect(authGuard()(route({ meta: { auth: true } }), route())).resolves.toEqual({
|
|
79
|
+
name: 'auth-mfa', query: { redirect: '/protected' },
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('keeps pending primary login challenges out of protected routes', async () => {
|
|
84
|
+
authState.pendingMfa.value = {}
|
|
85
|
+
authState.requiresMfa.mockResolvedValue(true)
|
|
86
|
+
await expect(authGuard()(route({ meta: { auth: true } }), route())).resolves.toEqual({
|
|
87
|
+
name: 'auth-mfa', query: { redirect: '/protected' },
|
|
88
|
+
})
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('allows the MFA screen without starting another probe', async () => {
|
|
92
|
+
authState.user.value = {}
|
|
93
|
+
await expect(authGuard()(route({ name: 'auth-mfa' }), route())).resolves.toBe(true)
|
|
94
|
+
expect(authState.requiresMfa).not.toHaveBeenCalled()
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('leaves public pages available to authenticated users', async () => {
|
|
98
|
+
authState.user.value = {}
|
|
99
|
+
await expect(authGuard()(route(), route())).resolves.toBe(true)
|
|
100
|
+
expect(authState.requiresMfa).not.toHaveBeenCalled()
|
|
101
|
+
})
|
|
62
102
|
})
|
package/src/router.ts
CHANGED
|
@@ -54,6 +54,17 @@ export function authGuard() {
|
|
|
54
54
|
// Use cached auth state from reactive user ref
|
|
55
55
|
const isAuthenticated = !!auth.user.value
|
|
56
56
|
|
|
57
|
+
if (to.name !== 'auth-mfa' && (requiresAuth || requiresNoAuth) && (isAuthenticated || auth.pendingMfa?.value)) {
|
|
58
|
+
try {
|
|
59
|
+
if (await auth.requiresMfa()) {
|
|
60
|
+
return { name: 'auth-mfa', query: { redirect: requiresNoAuth ? config.authenticatedRedirect : to.fullPath } }
|
|
61
|
+
}
|
|
62
|
+
} catch {
|
|
63
|
+
// An unavailable assurance probe must not grant protected access.
|
|
64
|
+
return { name: 'auth-mfa', query: { redirect: to.fullPath } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
57
68
|
// Redirect authenticated users away from auth pages
|
|
58
69
|
if (isAuthenticated && requiresNoAuth) {
|
|
59
70
|
return config.authenticatedRedirect
|
package/src/useAuth.ts
CHANGED
|
@@ -34,6 +34,7 @@ import { setAuthContext, sso } from './sso'
|
|
|
34
34
|
import { AuthState, accountToUser } from './types'
|
|
35
35
|
import { normalizeRedirectConfig } from './types/redirect'
|
|
36
36
|
import { EventEmitter } from './utils'
|
|
37
|
+
import { isMfaRequiredError, mfaNextStep, pendingMfaMetadata, type MfaFlowApi, type PendingMfaMetadata } from './mfa'
|
|
37
38
|
|
|
38
39
|
// Global state
|
|
39
40
|
let authApi: AuthApi | null = null
|
|
@@ -42,14 +43,17 @@ let redirectConfig: NormalizedRedirectConfig | null = null
|
|
|
42
43
|
let autoRedirectRouter: any = null // Router instance for auto-redirect
|
|
43
44
|
let cachedAuthGuard: any = null // Cached router guard
|
|
44
45
|
let tenancyEnabled = false
|
|
46
|
+
let mfaApi: MfaFlowApi | undefined
|
|
45
47
|
// Challenge credentials live only in memory; never persist them in browser storage.
|
|
46
|
-
const pendingMfa = ref<(AuthenticationResponse & { metadata:
|
|
48
|
+
const pendingMfa = ref<(AuthenticationResponse & { metadata: PendingMfaMetadata }) | null>(null)
|
|
47
49
|
const accountInfo = ref<AccountInfo | null>(null)
|
|
48
50
|
const tenants = ref<TenantInfo[]>([])
|
|
49
51
|
const currentTenant = ref<TenantInfo | null>(null)
|
|
50
52
|
|
|
51
53
|
interface InitParams {
|
|
52
54
|
baseURL: string
|
|
55
|
+
/** Generated MFA namespace; enables shared assurance checks on protected routes. */
|
|
56
|
+
mfa?: MfaFlowApi
|
|
53
57
|
/**
|
|
54
58
|
* Redirect configuration for authentication flows
|
|
55
59
|
* @see RedirectConfig
|
|
@@ -119,7 +123,7 @@ export function getRedirectConfig(): NormalizedRedirectConfig {
|
|
|
119
123
|
// Initialize auth
|
|
120
124
|
export function createAuth(params: InitParams): AuthInstance {
|
|
121
125
|
if (authApi === null) {
|
|
122
|
-
authApi = new AuthApi(params.baseURL)
|
|
126
|
+
authApi = new AuthApi(params.baseURL, error => { useAuth().handleApiError(error) })
|
|
123
127
|
}
|
|
124
128
|
|
|
125
129
|
if (eventEmitter === null) {
|
|
@@ -132,6 +136,7 @@ export function createAuth(params: InitParams): AuthInstance {
|
|
|
132
136
|
}
|
|
133
137
|
|
|
134
138
|
tenancyEnabled = params.tenancy ?? false
|
|
139
|
+
mfaApi = params.mfa
|
|
135
140
|
|
|
136
141
|
// Setup auto-redirect on login if enabled
|
|
137
142
|
if (redirectConfig?.autoRedirect) {
|
|
@@ -355,16 +360,49 @@ export function useAuth() {
|
|
|
355
360
|
}
|
|
356
361
|
|
|
357
362
|
function captureMfa(response: AuthenticationResponse): boolean {
|
|
358
|
-
const metadata = response
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
pendingMfa.value = { ...response, metadata: { ...metadata, challenge_token: token } }
|
|
363
|
+
const metadata = pendingMfaMetadata(response)
|
|
364
|
+
if (metadata) {
|
|
365
|
+
pendingMfa.value = { ...response, metadata }
|
|
362
366
|
return true
|
|
363
367
|
}
|
|
364
368
|
pendingMfa.value = null
|
|
365
369
|
return false
|
|
366
370
|
}
|
|
367
371
|
|
|
372
|
+
async function requiresMfa(): Promise<boolean> {
|
|
373
|
+
if (pendingMfa.value) return true
|
|
374
|
+
if (!mfaApi) return false
|
|
375
|
+
return mfaNextStep(await mfaApi.status()) !== 'ready'
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function beginMfa(flowApi: MfaFlowApi = mfaApi!, force = false) {
|
|
379
|
+
if (pendingMfa.value) return pendingMfa.value.metadata
|
|
380
|
+
if (!flowApi) throw new Error('MFA API is not configured')
|
|
381
|
+
const status = await flowApi.status()
|
|
382
|
+
if (!force && mfaNextStep(status) === 'ready') return null
|
|
383
|
+
if (force && status.session_verified && mfaNextStep(status) === 'ready') return null
|
|
384
|
+
const challenge = await flowApi.stepUp.start()
|
|
385
|
+
const metadata = pendingMfaMetadata({ success: false, requires_verification: true, metadata: { ...challenge } })
|
|
386
|
+
if (!metadata) throw new Error('Invalid MFA challenge')
|
|
387
|
+
pendingMfa.value = { success: false, requires_verification: true, metadata }
|
|
388
|
+
return metadata
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function handleApiError(error: unknown): boolean {
|
|
392
|
+
if (!mfaApi || !isMfaRequiredError(error) || !autoRedirectRouter) return false
|
|
393
|
+
const current = autoRedirectRouter.currentRoute.value
|
|
394
|
+
if (current.name !== 'auth-mfa') {
|
|
395
|
+
void autoRedirectRouter.replace({ name: 'auth-mfa', query: { redirect: current.fullPath } })
|
|
396
|
+
}
|
|
397
|
+
return true
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function authDestinationRoute(destination: string) {
|
|
401
|
+
return pendingMfa.value && pendingMfa.value.metadata.next_step !== 'ready'
|
|
402
|
+
? { name: 'auth-mfa', query: { redirect: destination } }
|
|
403
|
+
: destination
|
|
404
|
+
}
|
|
405
|
+
|
|
368
406
|
async function completeMfa(response: AuthenticationResponse) {
|
|
369
407
|
if (!response.success || response.requires_verification) throw new Error('MFA verification failed')
|
|
370
408
|
if (!response.session_token) throw new Error('MFA response missing replacement session')
|
|
@@ -626,7 +664,7 @@ export function useAuth() {
|
|
|
626
664
|
await checkAuth()
|
|
627
665
|
}
|
|
628
666
|
|
|
629
|
-
async function signup(newUser: NewUser) {
|
|
667
|
+
async function signup(newUser: NewUser, options: { login?: boolean } = {}) {
|
|
630
668
|
// Check password match if password is provided
|
|
631
669
|
const hasPassword = newUser.password !== undefined && newUser.password.length > 0
|
|
632
670
|
if (hasPassword && newUser.password !== newUser.confirmPassword) {
|
|
@@ -640,6 +678,13 @@ export function useAuth() {
|
|
|
640
678
|
phone_number: newUser.phone_number,
|
|
641
679
|
password: newUser.password,
|
|
642
680
|
})
|
|
681
|
+
if (!data.success && !data.requires_verification) throw new Error(data.message || 'Registration failed')
|
|
682
|
+
if (captureMfa(data)) return data
|
|
683
|
+
if (options.login && newUser.password) {
|
|
684
|
+
const response = await login({ email: newUser.email, password: newUser.password })
|
|
685
|
+
emitter.emit(AuthState.SIGNUP)
|
|
686
|
+
return response
|
|
687
|
+
}
|
|
643
688
|
|
|
644
689
|
// If successful and not requiring verification, fetch user data
|
|
645
690
|
if (data.success === true && data.requires_verification !== true) {
|
|
@@ -763,6 +808,10 @@ export function useAuth() {
|
|
|
763
808
|
user,
|
|
764
809
|
pendingMfa,
|
|
765
810
|
completeMfa,
|
|
811
|
+
requiresMfa,
|
|
812
|
+
beginMfa,
|
|
813
|
+
handleApiError,
|
|
814
|
+
authDestinationRoute,
|
|
766
815
|
|
|
767
816
|
// Full account info (for advanced use cases)
|
|
768
817
|
accountInfo,
|