@bymax-one/nest-auth 1.4.0 → 1.4.2
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/CHANGELOG.md +208 -3
- package/README.md +86 -1
- package/dist/server/index.cjs +109 -50
- package/dist/server/index.d.cts +55 -21
- package/dist/server/index.d.ts +55 -21
- package/dist/server/index.mjs +109 -51
- package/package.json +2 -1
package/dist/server/index.cjs
CHANGED
|
@@ -1622,6 +1622,46 @@ var AUTH_ERROR_CODES = {
|
|
|
1622
1622
|
*/
|
|
1623
1623
|
INTERNAL: "auth.internal"
|
|
1624
1624
|
};
|
|
1625
|
+
var AUTH_ERROR_STATUS = {
|
|
1626
|
+
"auth.invalid_credentials": 401,
|
|
1627
|
+
"auth.account_locked": 429,
|
|
1628
|
+
"auth.account_inactive": 403,
|
|
1629
|
+
"auth.account_suspended": 403,
|
|
1630
|
+
"auth.account_banned": 403,
|
|
1631
|
+
"auth.pending_approval": 403,
|
|
1632
|
+
"auth.token_expired": 401,
|
|
1633
|
+
"auth.token_revoked": 401,
|
|
1634
|
+
"auth.token_invalid": 401,
|
|
1635
|
+
"auth.token_missing": 401,
|
|
1636
|
+
"auth.refresh_token_invalid": 401,
|
|
1637
|
+
"auth.session_not_found": 404,
|
|
1638
|
+
"auth.email_already_exists": 409,
|
|
1639
|
+
"auth.email_not_verified": 403,
|
|
1640
|
+
"auth.email_change_token_invalid": 400,
|
|
1641
|
+
"auth.mfa_required": 403,
|
|
1642
|
+
"auth.mfa_invalid_code": 401,
|
|
1643
|
+
"auth.mfa_already_enabled": 409,
|
|
1644
|
+
"auth.mfa_not_enabled": 400,
|
|
1645
|
+
"auth.mfa_setup_required": 400,
|
|
1646
|
+
"auth.mfa_temp_token_invalid": 401,
|
|
1647
|
+
"auth.mfa_state_conflict": 409,
|
|
1648
|
+
"auth.password_compromised": 400,
|
|
1649
|
+
"auth.password_reset_token_invalid": 400,
|
|
1650
|
+
"auth.otp_invalid": 401,
|
|
1651
|
+
"auth.otp_expired": 401,
|
|
1652
|
+
"auth.otp_max_attempts": 401,
|
|
1653
|
+
"auth.insufficient_role": 403,
|
|
1654
|
+
"auth.forbidden": 403,
|
|
1655
|
+
"auth.validation": 400,
|
|
1656
|
+
"auth.too_many_requests": 429,
|
|
1657
|
+
"auth.untrusted_origin": 403,
|
|
1658
|
+
"auth.reauthentication_required": 403,
|
|
1659
|
+
"auth.invalid_invitation_token": 400,
|
|
1660
|
+
"auth.oauth_failed": 401,
|
|
1661
|
+
"auth.oauth_email_mismatch": 409,
|
|
1662
|
+
"auth.platform_auth_required": 401,
|
|
1663
|
+
"auth.internal": 500
|
|
1664
|
+
};
|
|
1625
1665
|
var AUTH_ERROR_MESSAGES = {
|
|
1626
1666
|
"auth.invalid_credentials": "Invalid email or password",
|
|
1627
1667
|
"auth.account_locked": "Account temporarily locked. Please try again in a few minutes.",
|
|
@@ -1662,27 +1702,34 @@ var AUTH_ERROR_MESSAGES = {
|
|
|
1662
1702
|
"auth.platform_auth_required": "Platform authentication required",
|
|
1663
1703
|
"auth.internal": "Internal server error"
|
|
1664
1704
|
};
|
|
1705
|
+
var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
|
|
1706
|
+
var STATUS_BY_CODE = new Map(Object.entries(AUTH_ERROR_STATUS));
|
|
1665
1707
|
var AuthException = class extends common.HttpException {
|
|
1666
1708
|
static {
|
|
1667
1709
|
__name(this, "AuthException");
|
|
1668
1710
|
}
|
|
1669
1711
|
/**
|
|
1670
|
-
* @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
|
|
1671
|
-
*
|
|
1712
|
+
* @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`. Determines both
|
|
1713
|
+
* the default message and the HTTP status.
|
|
1672
1714
|
* @param details - Optional structured payload attached to the error body under
|
|
1673
1715
|
* `error.details`. An array where the failure is a list — `auth.validation` renders its
|
|
1674
1716
|
* per-field failures that way, matching what rust-auth serializes for the same code.
|
|
1675
1717
|
*/
|
|
1676
|
-
constructor(code,
|
|
1677
|
-
super(
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1718
|
+
constructor(code, details) {
|
|
1719
|
+
super(
|
|
1720
|
+
{
|
|
1721
|
+
error: {
|
|
1722
|
+
code,
|
|
1723
|
+
// Runtime fallback for future/unknown codes not yet in AUTH_ERROR_MESSAGES (type cast in tests, forward-compat).
|
|
1724
|
+
message: MESSAGE_BY_CODE.get(code) ?? code,
|
|
1725
|
+
details: details ?? null
|
|
1726
|
+
}
|
|
1727
|
+
},
|
|
1728
|
+
// A code with no entry is a programming error on the throwing side, not something the
|
|
1729
|
+
// caller did — 500 says so, and says it with a number rather than the `undefined` an
|
|
1730
|
+
// unguarded lookup used to hand to Express.
|
|
1731
|
+
STATUS_BY_CODE.get(code) ?? common.HttpStatus.INTERNAL_SERVER_ERROR
|
|
1732
|
+
);
|
|
1686
1733
|
}
|
|
1687
1734
|
};
|
|
1688
1735
|
function _ts_decorate5(decorators, target, key, desc) {
|
|
@@ -2696,7 +2743,7 @@ exports.AuthRateLimitGuard = class AuthRateLimitGuard {
|
|
|
2696
2743
|
const hits = await this.redis.incrWithFixedTtl(key, windowSeconds);
|
|
2697
2744
|
if (hits <= limit.limit) return true;
|
|
2698
2745
|
context.switchToHttp().getResponse().setHeader("Retry-After", windowSeconds);
|
|
2699
|
-
throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS
|
|
2746
|
+
throw new AuthException(AUTH_ERROR_CODES.TOO_MANY_REQUESTS);
|
|
2700
2747
|
}
|
|
2701
2748
|
/**
|
|
2702
2749
|
* The counter key for one caller on one route.
|
|
@@ -2774,7 +2821,7 @@ function assertNotBlocked(status, blockedStatuses) {
|
|
|
2774
2821
|
if (!blockedStatuses.some((blocked) => blocked.toLowerCase() === canonical)) {
|
|
2775
2822
|
return;
|
|
2776
2823
|
}
|
|
2777
|
-
throw new AuthException(BLOCKED_STATUS_CODES.get(canonical) ?? AUTH_ERROR_CODES.ACCOUNT_INACTIVE
|
|
2824
|
+
throw new AuthException(BLOCKED_STATUS_CODES.get(canonical) ?? AUTH_ERROR_CODES.ACCOUNT_INACTIVE);
|
|
2778
2825
|
}
|
|
2779
2826
|
__name(assertNotBlocked, "assertNotBlocked");
|
|
2780
2827
|
|
|
@@ -3431,12 +3478,12 @@ exports.TrustedOriginGuard = class TrustedOriginGuard {
|
|
|
3431
3478
|
if (typeof origin === "string") {
|
|
3432
3479
|
if (this.options.cookies.trustedOrigins.includes(origin)) return true;
|
|
3433
3480
|
if (sawFetchSite || this.options.cookies.trustedOrigins.length > 0) {
|
|
3434
|
-
throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN
|
|
3481
|
+
throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN);
|
|
3435
3482
|
}
|
|
3436
3483
|
return true;
|
|
3437
3484
|
}
|
|
3438
3485
|
if (sawFetchSite) {
|
|
3439
|
-
throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN
|
|
3486
|
+
throw new AuthException(AUTH_ERROR_CODES.UNTRUSTED_ORIGIN);
|
|
3440
3487
|
}
|
|
3441
3488
|
return true;
|
|
3442
3489
|
}
|
|
@@ -3584,7 +3631,7 @@ function createAuthValidationPipe(options = {}) {
|
|
|
3584
3631
|
whitelist: true,
|
|
3585
3632
|
forbidNonWhitelisted: true,
|
|
3586
3633
|
...options,
|
|
3587
|
-
exceptionFactory: /* @__PURE__ */ __name((errors) => new AuthException(AUTH_ERROR_CODES.VALIDATION,
|
|
3634
|
+
exceptionFactory: /* @__PURE__ */ __name((errors) => new AuthException(AUTH_ERROR_CODES.VALIDATION, flattenValidationErrors(errors)), "exceptionFactory")
|
|
3588
3635
|
});
|
|
3589
3636
|
}
|
|
3590
3637
|
__name(createAuthValidationPipe, "createAuthValidationPipe");
|
|
@@ -4073,7 +4120,7 @@ var PasswordService = class _PasswordService {
|
|
|
4073
4120
|
*/
|
|
4074
4121
|
assertLongEnough(plain, field) {
|
|
4075
4122
|
if (plain.length >= this.minLength) return;
|
|
4076
|
-
throw new AuthException(AUTH_ERROR_CODES.VALIDATION,
|
|
4123
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
4077
4124
|
{
|
|
4078
4125
|
field,
|
|
4079
4126
|
message: `${field} must be at least ${String(this.minLength)} characters`
|
|
@@ -4113,7 +4160,7 @@ var PasswordService = class _PasswordService {
|
|
|
4113
4160
|
return;
|
|
4114
4161
|
}
|
|
4115
4162
|
if (breached) {
|
|
4116
|
-
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_COMPROMISED
|
|
4163
|
+
throw new AuthException(AUTH_ERROR_CODES.PASSWORD_COMPROMISED);
|
|
4117
4164
|
}
|
|
4118
4165
|
}
|
|
4119
4166
|
async hash(plain) {
|
|
@@ -5659,12 +5706,22 @@ function normalizeEmail(email) {
|
|
|
5659
5706
|
return email.trim().toLowerCase();
|
|
5660
5707
|
}
|
|
5661
5708
|
__name(normalizeEmail, "normalizeEmail");
|
|
5709
|
+
|
|
5710
|
+
// src/server/utils/resolve-tenant-id.ts
|
|
5662
5711
|
async function resolveTenantId(dtoTenantId, req, resolver) {
|
|
5663
5712
|
if (resolver) {
|
|
5713
|
+
if (dtoTenantId !== void 0 && dtoTenantId !== null) {
|
|
5714
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
5715
|
+
{
|
|
5716
|
+
field: "tenantId",
|
|
5717
|
+
message: "tenantId is decided by this deployment and must not be sent"
|
|
5718
|
+
}
|
|
5719
|
+
]);
|
|
5720
|
+
}
|
|
5664
5721
|
return await resolver(req);
|
|
5665
5722
|
}
|
|
5666
5723
|
if (dtoTenantId === void 0 || dtoTenantId === null) {
|
|
5667
|
-
throw new AuthException(AUTH_ERROR_CODES.VALIDATION,
|
|
5724
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
5668
5725
|
{
|
|
5669
5726
|
field: "tenantId",
|
|
5670
5727
|
message: "tenantId is required unless the deployment configures tenantIdResolver"
|
|
@@ -5912,7 +5969,7 @@ exports.AuthService = class _AuthService {
|
|
|
5912
5969
|
tenantId,
|
|
5913
5970
|
reason: "locked_out"
|
|
5914
5971
|
}, context);
|
|
5915
|
-
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED,
|
|
5972
|
+
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, {
|
|
5916
5973
|
retryAfterSeconds: remainingSeconds
|
|
5917
5974
|
});
|
|
5918
5975
|
}
|
|
@@ -6537,7 +6594,7 @@ exports.WsTicketService = class _WsTicketService {
|
|
|
6537
6594
|
}
|
|
6538
6595
|
if (payload.mfaEnabled && payload.mfaVerified !== true) {
|
|
6539
6596
|
this.logger.warn(`ws-ticket: refused, MFA not satisfied userId=${payload.sub}`);
|
|
6540
|
-
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED
|
|
6597
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
|
|
6541
6598
|
}
|
|
6542
6599
|
const user = await this.userRepo.findById(payload.sub);
|
|
6543
6600
|
if (!user) throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
@@ -7630,17 +7687,17 @@ exports.InvitationService = class _InvitationService {
|
|
|
7630
7687
|
const normalizedEmail = normalizeEmail(email);
|
|
7631
7688
|
const hierarchy = this.options.roles.hierarchy;
|
|
7632
7689
|
if (!Object.hasOwn(hierarchy, role)) {
|
|
7633
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7690
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7634
7691
|
}
|
|
7635
7692
|
const inviter = await this.userRepo.findById(inviterUserId);
|
|
7636
7693
|
if (!inviter) {
|
|
7637
7694
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7638
7695
|
}
|
|
7639
7696
|
if (inviter.tenantId !== tenantId) {
|
|
7640
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7697
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7641
7698
|
}
|
|
7642
7699
|
if (!hasRole(inviter.role, role, hierarchy)) {
|
|
7643
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7700
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7644
7701
|
}
|
|
7645
7702
|
const rawToken = generateSecureToken(32);
|
|
7646
7703
|
const tokenHash = sha256(rawToken);
|
|
@@ -7769,7 +7826,7 @@ exports.InvitationService = class _InvitationService {
|
|
|
7769
7826
|
const pending = raw === null ? null : this.parseInvitation(raw);
|
|
7770
7827
|
if (pending !== null && !this.mayWithdraw(inviter, pending)) {
|
|
7771
7828
|
this.logger.warn(`create: refused email=${maskEmail(email)} tenantId=${logSafe(tenantId)} inviterRole=${logSafe(inviter.role)} \u2014 outranked by the pending invitation`);
|
|
7772
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7829
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7773
7830
|
}
|
|
7774
7831
|
return tokenHash;
|
|
7775
7832
|
}
|
|
@@ -7804,7 +7861,7 @@ exports.InvitationService = class _InvitationService {
|
|
|
7804
7861
|
if (claim.claimed) return approved;
|
|
7805
7862
|
}
|
|
7806
7863
|
this.logger.warn(`create: refused email=${maskEmail(email)} tenantId=${logSafe(tenantId)} \u2014 the pending invitation kept changing under the rank check`);
|
|
7807
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7864
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7808
7865
|
}
|
|
7809
7866
|
/**
|
|
7810
7867
|
* Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
|
|
@@ -7871,10 +7928,10 @@ exports.InvitationService = class _InvitationService {
|
|
|
7871
7928
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
7872
7929
|
}
|
|
7873
7930
|
if (revoker.tenantId !== tenantId) {
|
|
7874
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7931
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7875
7932
|
}
|
|
7876
7933
|
if (!this.inGoodStanding(revoker)) {
|
|
7877
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
7934
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
7878
7935
|
}
|
|
7879
7936
|
const indexKey = this.inviteeKey(normalizedEmail, tenantId);
|
|
7880
7937
|
const tokenHash = await this.redis.get(indexKey);
|
|
@@ -8650,7 +8707,7 @@ exports.MfaService = class _MfaService {
|
|
|
8650
8707
|
const acquireLegacy = legacyLockKey !== scopedLockKey;
|
|
8651
8708
|
const lockToken = crypto.randomBytes(16).toString("hex");
|
|
8652
8709
|
if (!await this.redis.setIfAbsent(scopedLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
|
|
8653
|
-
throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT
|
|
8710
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
|
|
8654
8711
|
}
|
|
8655
8712
|
if (acquireLegacy && !await this.redis.setIfAbsent(legacyLockKey, lockToken, MFA_TRANSITION_LOCK_TTL_SECONDS)) {
|
|
8656
8713
|
await this.redis.eval(RELEASE_LOCK_LUA, [
|
|
@@ -8658,7 +8715,7 @@ exports.MfaService = class _MfaService {
|
|
|
8658
8715
|
], [
|
|
8659
8716
|
lockToken
|
|
8660
8717
|
]);
|
|
8661
|
-
throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT
|
|
8718
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_STATE_CONFLICT);
|
|
8662
8719
|
}
|
|
8663
8720
|
try {
|
|
8664
8721
|
const current = await this.fetchUserForContext(context, userId, tenantId);
|
|
@@ -9443,7 +9500,7 @@ exports.MfaService = class _MfaService {
|
|
|
9443
9500
|
const recent = await this.redis.get(recentAuthKey(context, userId, this.options.hmacKey, tenantId));
|
|
9444
9501
|
if (recent === null) {
|
|
9445
9502
|
this.logger.warn(`reauthenticate: no recent authentication userId=${userId} context=${context}`);
|
|
9446
|
-
throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED
|
|
9503
|
+
throw new AuthException(AUTH_ERROR_CODES.REAUTHENTICATION_REQUIRED);
|
|
9447
9504
|
}
|
|
9448
9505
|
return;
|
|
9449
9506
|
}
|
|
@@ -9502,7 +9559,7 @@ exports.MfaService = class _MfaService {
|
|
|
9502
9559
|
*/
|
|
9503
9560
|
assertPlaneTenant(context, tenantId) {
|
|
9504
9561
|
if (context === "dashboard" && (tenantId === void 0 || tenantId === "") || context === "platform" && tenantId !== void 0) {
|
|
9505
|
-
throw new AuthException(AUTH_ERROR_CODES.VALIDATION,
|
|
9562
|
+
throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
|
|
9506
9563
|
{
|
|
9507
9564
|
field: "tenantId",
|
|
9508
9565
|
message: "tenantId must be a non-empty value on the dashboard plane and absent on the platform plane"
|
|
@@ -11273,7 +11330,7 @@ exports.PlatformAuthService = class _PlatformAuthService {
|
|
|
11273
11330
|
if (locked) {
|
|
11274
11331
|
this.logger.warn(`login: account locked email=${maskEmail(dto.email)}`);
|
|
11275
11332
|
const retryAfterSeconds = await this.bruteForce.getRemainingLockoutSeconds(bfIdentifier);
|
|
11276
|
-
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED,
|
|
11333
|
+
throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, {
|
|
11277
11334
|
retryAfterSeconds
|
|
11278
11335
|
});
|
|
11279
11336
|
}
|
|
@@ -12130,7 +12187,7 @@ exports.MfaRequiredGuard = class MfaRequiredGuard {
|
|
|
12130
12187
|
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
12131
12188
|
}
|
|
12132
12189
|
if (user.mfaEnabled === true && user.mfaVerified !== true) {
|
|
12133
|
-
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED
|
|
12190
|
+
throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
|
|
12134
12191
|
}
|
|
12135
12192
|
return true;
|
|
12136
12193
|
}
|
|
@@ -12197,11 +12254,11 @@ exports.PlatformRolesGuard = class PlatformRolesGuard {
|
|
|
12197
12254
|
const userRole = user.role;
|
|
12198
12255
|
const hierarchy = this.options.roles.platformHierarchy;
|
|
12199
12256
|
if (!hierarchy) {
|
|
12200
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
12257
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
12201
12258
|
}
|
|
12202
12259
|
const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
|
|
12203
12260
|
if (!allowed) {
|
|
12204
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
12261
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
12205
12262
|
}
|
|
12206
12263
|
return true;
|
|
12207
12264
|
}
|
|
@@ -12265,12 +12322,12 @@ exports.RolesGuard = class RolesGuard {
|
|
|
12265
12322
|
const request = context.switchToHttp().getRequest();
|
|
12266
12323
|
const userRole = request.user?.role;
|
|
12267
12324
|
if (!userRole) {
|
|
12268
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
12325
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
12269
12326
|
}
|
|
12270
12327
|
const hierarchy = this.options.roles.hierarchy;
|
|
12271
12328
|
const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
|
|
12272
12329
|
if (!allowed) {
|
|
12273
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
12330
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
12274
12331
|
}
|
|
12275
12332
|
return true;
|
|
12276
12333
|
}
|
|
@@ -12436,10 +12493,11 @@ exports.OAuthService = class _OAuthService {
|
|
|
12436
12493
|
* 5. Issues a 302 redirect via the Express `res` object.
|
|
12437
12494
|
*
|
|
12438
12495
|
* @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
|
|
12439
|
-
* @param tenantId - Tenant the user will join on successful login, as named by the caller
|
|
12440
|
-
*
|
|
12441
|
-
*
|
|
12442
|
-
* the
|
|
12496
|
+
* @param tenantId - Tenant the user will join on successful login, as named by the caller in
|
|
12497
|
+
* the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
|
|
12498
|
+
* configured, since the deployment decides the tenant and a value it discards would only
|
|
12499
|
+
* mislead the caller. Never validated against the database — implement `onOAuthLogin` to
|
|
12500
|
+
* enforce tenant membership. Without the hook, OAuth sign-in is disabled.
|
|
12443
12501
|
* @param req - Incoming Express request, read by the configured `tenantIdResolver`.
|
|
12444
12502
|
* @param res - Express response in passthrough mode (used for the 302 redirect).
|
|
12445
12503
|
* @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
|
|
@@ -12560,7 +12618,7 @@ exports.OAuthService = class _OAuthService {
|
|
|
12560
12618
|
const derivedName = profile.name ?? profile.email.split("@")[0] ?? profile.email;
|
|
12561
12619
|
if (await this.userRepo.findByEmail(profile.email, tenantId)) {
|
|
12562
12620
|
this.logger.warn(`oauth: create refused \u2014 ${maskEmail(profile.email)} already exists in tenant ${tenantId}`);
|
|
12563
|
-
throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH
|
|
12621
|
+
throw new AuthException(AUTH_ERROR_CODES.OAUTH_EMAIL_MISMATCH);
|
|
12564
12622
|
}
|
|
12565
12623
|
authUser = await this.userRepo.createWithOAuth({
|
|
12566
12624
|
email: profile.email,
|
|
@@ -12595,7 +12653,7 @@ exports.OAuthService = class _OAuthService {
|
|
|
12595
12653
|
}
|
|
12596
12654
|
assertNotBlocked(authUser.status, this.options.blockedStatuses);
|
|
12597
12655
|
if (this.options.emailVerification.required && !authUser.emailVerified) {
|
|
12598
|
-
throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED
|
|
12656
|
+
throw new AuthException(AUTH_ERROR_CODES.EMAIL_NOT_VERIFIED);
|
|
12599
12657
|
}
|
|
12600
12658
|
if (authUser.mfaEnabled) {
|
|
12601
12659
|
const mfaTempToken = await this.tokenManager.issueMfaTempToken(authUser.id, "dashboard", authUser.tenantId);
|
|
@@ -14469,22 +14527,22 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
|
|
|
14469
14527
|
canActivate(context) {
|
|
14470
14528
|
const request = context.switchToHttp().getRequest();
|
|
14471
14529
|
if (request.user == null) {
|
|
14472
|
-
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID
|
|
14530
|
+
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
14473
14531
|
}
|
|
14474
14532
|
const rawParam = request.params["userId"] ?? request.params["id"];
|
|
14475
14533
|
if (rawParam === void 0) {
|
|
14476
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
14534
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
14477
14535
|
}
|
|
14478
14536
|
const paramValue = resolveParamString(rawParam);
|
|
14479
14537
|
if (paramValue === void 0) {
|
|
14480
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
14538
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
14481
14539
|
}
|
|
14482
14540
|
if (isHexLooking(paramValue) && !STRICT_SHA256_RE.test(paramValue)) {
|
|
14483
|
-
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID
|
|
14541
|
+
throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
|
|
14484
14542
|
}
|
|
14485
14543
|
if (request.user.sub === paramValue) return true;
|
|
14486
14544
|
if (hasRole(request.user.role, "admin", this.options.roles.hierarchy)) return true;
|
|
14487
|
-
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE
|
|
14545
|
+
throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
|
|
14488
14546
|
}
|
|
14489
14547
|
};
|
|
14490
14548
|
exports.SelfOrAdminGuard = _ts_decorate64([
|
|
@@ -14698,6 +14756,7 @@ exports.AuthExceptionFilter = _ts_decorate66([
|
|
|
14698
14756
|
|
|
14699
14757
|
exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
|
|
14700
14758
|
exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
|
|
14759
|
+
exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
|
|
14701
14760
|
exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
|
|
14702
14761
|
exports.AcceptInvitationDto = AcceptInvitationDto;
|
|
14703
14762
|
exports.AuthException = AuthException;
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1070,15 +1070,18 @@ interface BymaxAuthModuleOptions {
|
|
|
1070
1070
|
/**
|
|
1071
1071
|
* Tenant ID resolver function.
|
|
1072
1072
|
*
|
|
1073
|
-
* When provided, the module resolves the tenant ID from the request object and
|
|
1074
|
-
*
|
|
1075
|
-
* spoofing where a client sends a different tenant's ID
|
|
1076
|
-
*
|
|
1077
|
-
*
|
|
1078
|
-
*
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1073
|
+
* When provided, the module resolves the tenant ID from the request object and **refuses** any
|
|
1074
|
+
* `tenantId` the request names — with `400 auth.validation` on the `tenantId` field. This
|
|
1075
|
+
* prevents tenant spoofing where a client sends a different tenant's ID, and it refuses rather
|
|
1076
|
+
* than ignoring on purpose: a discarded value answers `201` while putting the account
|
|
1077
|
+
* somewhere else, so the caller's belief and the server's state diverge on the tenancy
|
|
1078
|
+
* boundary with nothing saying so.
|
|
1079
|
+
*
|
|
1080
|
+
* A client under a resolver must therefore **omit the field**; `null` and an absent field are
|
|
1081
|
+
* both accepted, since neither asserts anything to contradict. With no resolver configured the
|
|
1082
|
+
* body is the only thing that can name a tenant, so there it is honoured, and a request naming
|
|
1083
|
+
* none is refused with the same `auth.validation` — the deployment has to choose one of the
|
|
1084
|
+
* two, and neither choice is guessed on its behalf.
|
|
1082
1085
|
*
|
|
1083
1086
|
* @param req - The Express request object
|
|
1084
1087
|
* @returns The tenant ID string, or a Promise resolving to it
|
|
@@ -2040,6 +2043,31 @@ declare const AUTH_ERROR_CODES: {
|
|
|
2040
2043
|
* `AuthException` and related APIs.
|
|
2041
2044
|
*/
|
|
2042
2045
|
type AuthErrorCode = (typeof AUTH_ERROR_CODES)[keyof typeof AUTH_ERROR_CODES];
|
|
2046
|
+
/**
|
|
2047
|
+
* HTTP status answered for each error code.
|
|
2048
|
+
*
|
|
2049
|
+
* The status is a property of the CODE, not of the call site: `AuthException` derives it from
|
|
2050
|
+
* this table and takes no status argument. That is deliberate, and it is the fix for a real
|
|
2051
|
+
* defect — the constructor used to default to `401`, so omitting the argument was neither a
|
|
2052
|
+
* type error nor a lint error but a plausible-looking wrong answer. Thirteen codes drifted
|
|
2053
|
+
* that way, and five answered *different* statuses at different throw sites (`auth.account_locked`
|
|
2054
|
+
* was `429` on login and `401` on the MFA and password-reset lockouts, so a client backing off
|
|
2055
|
+
* on `429` did not back off on the others).
|
|
2056
|
+
*
|
|
2057
|
+
* Pinned by `conformance/wire-contract.json` (`errorCatalog.statuses`) and asserted against it
|
|
2058
|
+
* by `conformance.spec.ts`, because rust-auth answers the same codes for the same deployment:
|
|
2059
|
+
* a client switching on `error.code` and `response.status` must see one contract whichever
|
|
2060
|
+
* implementation is behind it. Changing a value here is a breaking change to that contract —
|
|
2061
|
+
* make it in both repos in the same change.
|
|
2062
|
+
*
|
|
2063
|
+
* @remarks
|
|
2064
|
+
* These are WIRE statuses. An internal-only code carries the status of the public code it
|
|
2065
|
+
* collapses onto rather than one of its own — `auth.otp_max_attempts` is 401 because it reaches
|
|
2066
|
+
* a caller as `auth.otp_invalid`, and a 429 would hand back through the status line exactly what
|
|
2067
|
+
* the collapse removes from the body: only a record that exists can reach an attempt ceiling, so
|
|
2068
|
+
* a 429 says the address was registered.
|
|
2069
|
+
*/
|
|
2070
|
+
declare const AUTH_ERROR_STATUS: Readonly<Record<AuthErrorCode, number>>;
|
|
2043
2071
|
/**
|
|
2044
2072
|
* Human-readable message for each error code.
|
|
2045
2073
|
*
|
|
@@ -2074,24 +2102,29 @@ declare const AUTH_ERROR_MESSAGES: Readonly<Record<AuthErrorCode, string>>;
|
|
|
2074
2102
|
* }
|
|
2075
2103
|
* ```
|
|
2076
2104
|
*
|
|
2105
|
+
* The HTTP status is NOT a parameter — it is derived from the code via
|
|
2106
|
+
* {@link AUTH_ERROR_STATUS}. There is no way to answer one code with two statuses, which is
|
|
2107
|
+
* what a defaulted status argument allowed: thirteen codes drifted from the status rust-auth
|
|
2108
|
+
* answers for the same code, and five answered differently at different throw sites, none of
|
|
2109
|
+
* it visible to the type system, the linter, or either library's suite. Pass a `details`
|
|
2110
|
+
* payload where the failure carries one; the status follows the code.
|
|
2111
|
+
*
|
|
2077
2112
|
* @example
|
|
2078
2113
|
* ```typescript
|
|
2079
2114
|
* throw new AuthException(AUTH_ERROR_CODES.INVALID_CREDENTIALS)
|
|
2080
|
-
* throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN
|
|
2081
|
-
* throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED,
|
|
2082
|
-
* retryAfterSeconds: 300
|
|
2083
|
-
* })
|
|
2115
|
+
* throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN)
|
|
2116
|
+
* throw new AuthException(AUTH_ERROR_CODES.ACCOUNT_LOCKED, { retryAfterSeconds: 300 })
|
|
2084
2117
|
* ```
|
|
2085
2118
|
*/
|
|
2086
2119
|
declare class AuthException extends HttpException {
|
|
2087
2120
|
/**
|
|
2088
|
-
* @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`.
|
|
2089
|
-
*
|
|
2121
|
+
* @param code - Stable machine-readable error code from `AUTH_ERROR_CODES`. Determines both
|
|
2122
|
+
* the default message and the HTTP status.
|
|
2090
2123
|
* @param details - Optional structured payload attached to the error body under
|
|
2091
2124
|
* `error.details`. An array where the failure is a list — `auth.validation` renders its
|
|
2092
2125
|
* per-field failures that way, matching what rust-auth serializes for the same code.
|
|
2093
2126
|
*/
|
|
2094
|
-
constructor(code: AuthErrorCode,
|
|
2127
|
+
constructor(code: AuthErrorCode, details?: Record<string, unknown> | readonly unknown[]);
|
|
2095
2128
|
}
|
|
2096
2129
|
|
|
2097
2130
|
/**
|
|
@@ -8513,10 +8546,11 @@ declare class OAuthService {
|
|
|
8513
8546
|
* 5. Issues a 302 redirect via the Express `res` object.
|
|
8514
8547
|
*
|
|
8515
8548
|
* @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
|
|
8516
|
-
* @param tenantId - Tenant the user will join on successful login, as named by the caller
|
|
8517
|
-
*
|
|
8518
|
-
*
|
|
8519
|
-
* the
|
|
8549
|
+
* @param tenantId - Tenant the user will join on successful login, as named by the caller in
|
|
8550
|
+
* the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
|
|
8551
|
+
* configured, since the deployment decides the tenant and a value it discards would only
|
|
8552
|
+
* mislead the caller. Never validated against the database — implement `onOAuthLogin` to
|
|
8553
|
+
* enforce tenant membership. Without the hook, OAuth sign-in is disabled.
|
|
8520
8554
|
* @param req - Incoming Express request, read by the configured `tenantIdResolver`.
|
|
8521
8555
|
* @param res - Express response in passthrough mode (used for the 302 redirect).
|
|
8522
8556
|
* @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
|
|
@@ -8714,4 +8748,4 @@ declare function AuthRateLimit(config: {
|
|
|
8714
8748
|
default: AuthRateLimitWindow;
|
|
8715
8749
|
}): MethodDecorator;
|
|
8716
8750
|
|
|
8717
|
-
export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthEmailCatalogue, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
|
|
8751
|
+
export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, type SessionInfo as ActiveSessionInfo, AllowAllBreachChecker, type AuthEmailCatalogue, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthModuleAsyncOptions, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateUserData, type CreateWithOAuthData, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, Roles, RolesGuard, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, type SessionInfo$1 as SessionInfo, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, type UpdateMfaData, type UpdatePlatformMfaData, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, type WsTicketSnapshot, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
|