@bymax-one/nest-auth 1.4.1 → 1.4.3

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.
@@ -1,4 +1,4 @@
1
- import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, Catch, SetMetadata, ValidationPipe } from '@nestjs/common';
1
+ import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, ValidationPipe } from '@nestjs/common';
2
2
  import { JwtService, JwtModule } from '@nestjs/jwt';
3
3
  import { randomInt, scrypt as scrypt$1, randomBytes, timingSafeEqual, randomUUID, createHash, createHmac, createCipheriv, createDecipheriv } from 'crypto';
4
4
  import { Throttle } from '@nestjs/throttler';
@@ -19,6 +19,7 @@ var BYMAX_AUTH_EMAIL_PROVIDER = /* @__PURE__ */ Symbol("BYMAX_AUTH_EMAIL_PROVIDE
19
19
  var BYMAX_AUTH_HOOKS = /* @__PURE__ */ Symbol("BYMAX_AUTH_HOOKS");
20
20
  var BYMAX_AUTH_BREACH_CHECKER = /* @__PURE__ */ Symbol("BYMAX_AUTH_BREACH_CHECKER");
21
21
  var BYMAX_AUTH_REDIS_CLIENT = /* @__PURE__ */ Symbol("BYMAX_AUTH_REDIS_CLIENT");
22
+ var BYMAX_AUTH_REGISTERED_CONTROLLERS = /* @__PURE__ */ Symbol("BYMAX_AUTH_REGISTERED_CONTROLLERS");
22
23
 
23
24
  // src/server/config/default-options.ts
24
25
  var DEFAULT_OPTIONS = {
@@ -1076,7 +1077,7 @@ var AUTH_THROTTLE_CONFIGS = {
1076
1077
  ttl: 6e4
1077
1078
  }
1078
1079
  },
1079
- /** DELETE /auth/sessions/all — 5 requests per minute per IP. */
1080
+ /** POST /auth/sessions/revoke-all — 5 requests per minute per IP. */
1080
1081
  revokeAllSessions: {
1081
1082
  default: {
1082
1083
  limit: 5,
@@ -5336,7 +5337,21 @@ var TokenManagerService = class _TokenManagerService {
5336
5337
  * The `status` claim in the issued access token is intentionally empty during
5337
5338
  * rotation — the Redis session does not store full user data. Guards that enforce
5338
5339
  * status checks must read from the user repository or a status cache, not the
5339
- * JWT `status` claim.
5340
+ * JWT `status` claim. `rust-auth` stamps the same empty string at the same point, with a
5341
+ * test pinning it, so this is a shared contract rather than a local shortcut.
5342
+ *
5343
+ * **What that means for a consumer, which is where the cost lands.** `issueTokens` stamps the
5344
+ * account's value at that moment, this path stamps nothing, and `AuthService.refresh` re-stamps
5345
+ * it from the account when `role`, `tenantId` or `mfaEnabled` changed — so a session's tokens
5346
+ * carry a populated claim, then an empty one, then possibly a populated one again, with no
5347
+ * signal a client can read. A derived backend reading `request.user.status` is wrong in both
5348
+ * directions: `!== 'active'` refuses everyone whose session refreshed ordinarily, and
5349
+ * `=== 'suspended'` refuses nobody, ever.
5350
+ *
5351
+ * Backfilling it here would be worse than leaving it empty: the claim would become *usually*
5352
+ * true, which is the failure mode that survives testing, since status can still change under an
5353
+ * unexpired token. The claim cannot be authoritative, so it is not made to look like it — and
5354
+ * the empty string is the one state that cannot be mistaken for an answer.
5340
5355
  *
5341
5356
  * `mfaVerified` is always `false` after rotation because the Redis session does not
5342
5357
  * persist MFA verification state. A user who authenticated with MFA will lose the
@@ -5628,13 +5643,17 @@ var TokenManagerService = class _TokenManagerService {
5628
5643
  * @param token - The MFA temp JWT issued by {@link issueMfaTempToken}.
5629
5644
  * @returns The `userId`, `context`, and `jti` from the token. Pass the
5630
5645
  * `jti` to {@link consumeMfaTempToken} after TOTP validation succeeds.
5631
- * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` if the
5632
- * Redis entry is missing (already consumed, expired, or never issued).
5633
- * @throws {Error} When JWT signature or expiry validation fails (propagated
5634
- * directly from `JwtService.verify()` — not wrapped in {@link AuthException}).
5646
+ * @throws {@link AuthException} with `MFA_TEMP_TOKEN_INVALID` for every way the token can be
5647
+ * unusable — a bad signature, an expired one, a shape no secret accepts, or a missing Redis
5648
+ * entry (already consumed, expired, or never issued).
5635
5649
  */
5636
5650
  async verifyMfaTempToken(token) {
5637
- const payload = verifyWithRotation(this.jwtService, this.options, token);
5651
+ let payload;
5652
+ try {
5653
+ payload = verifyWithRotation(this.jwtService, this.options, token);
5654
+ } catch {
5655
+ throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5656
+ }
5638
5657
  if (payload.context === "dashboard" && payload.tenantId === void 0 || payload.context === "platform" && payload.tenantId !== void 0) {
5639
5658
  throw new AuthException(AUTH_ERROR_CODES.MFA_TEMP_TOKEN_INVALID);
5640
5659
  }
@@ -5708,6 +5727,14 @@ __name(normalizeEmail, "normalizeEmail");
5708
5727
  // src/server/utils/resolve-tenant-id.ts
5709
5728
  async function resolveTenantId(dtoTenantId, req, resolver) {
5710
5729
  if (resolver) {
5730
+ if (dtoTenantId !== void 0 && dtoTenantId !== null) {
5731
+ throw new AuthException(AUTH_ERROR_CODES.VALIDATION, [
5732
+ {
5733
+ field: "tenantId",
5734
+ message: "tenantId is decided by this deployment and must not be sent"
5735
+ }
5736
+ ]);
5737
+ }
5711
5738
  return await resolver(req);
5712
5739
  }
5713
5740
  if (dtoTenantId === void 0 || dtoTenantId === null) {
@@ -6110,7 +6137,7 @@ var AuthService = class _AuthService {
6110
6137
  */
6111
6138
  async refresh(oldRefreshToken, ip, userAgent) {
6112
6139
  const result = await this.tokenManager.reissueTokens(oldRefreshToken, ip, userAgent);
6113
- const user = await this.userRepo.findById(result.session.userId);
6140
+ const user = await this.userRepo.findById(result.session.userId, result.session.tenantId);
6114
6141
  if (!user) {
6115
6142
  await this.revokeAllSessions(result.session.userId);
6116
6143
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
@@ -10018,6 +10045,23 @@ var ChangePasswordDto = class {
10018
10045
  * Hashed immediately by the service layer — never persisted in plaintext.
10019
10046
  */
10020
10047
  newPassword;
10048
+ /**
10049
+ * The caller's own refresh token, so the device making the change stays signed in.
10050
+ *
10051
+ * Declared because the handler reads it. `TokenDeliveryService.extractRefreshToken` takes it
10052
+ * from the refresh cookie under `tokenDelivery: 'cookie'` and from **this body field** under
10053
+ * `'bearer'`, cookie-first-then-body under `'both'` — and the controller pipe runs
10054
+ * `forbidNonWhitelisted: true`, so an undeclared property is refused. A bearer-mode caller
10055
+ * therefore could not send the field the endpoint needs: the request was answered
10056
+ * `auth.validation` naming `refreshToken`, and the only way to change a password was to give
10057
+ * up every other session.
10058
+ *
10059
+ * It stayed invisible because the E2E harness installed a global `ValidationPipe` with
10060
+ * `whitelist: true`, which STRIPPED the property before the controller's own pipe could refuse
10061
+ * it — so the suite exercised a request production never sees. Optional, because under cookie
10062
+ * delivery the credential arrives in the cookie and no body field exists to declare.
10063
+ */
10064
+ refreshToken;
10021
10065
  };
10022
10066
  _ts_decorate37([
10023
10067
  IsString(),
@@ -10031,6 +10075,12 @@ _ts_decorate37([
10031
10075
  MaxLength(128),
10032
10076
  _ts_metadata36("design:type", String)
10033
10077
  ], ChangePasswordDto.prototype, "newPassword", void 0);
10078
+ _ts_decorate37([
10079
+ IsOptional(),
10080
+ IsString(),
10081
+ MaxLength(512),
10082
+ _ts_metadata36("design:type", String)
10083
+ ], ChangePasswordDto.prototype, "refreshToken", void 0);
10034
10084
  function _ts_decorate38(decorators, target, key, desc) {
10035
10085
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
10036
10086
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -12032,15 +12082,24 @@ var SessionController = class {
12032
12082
  return this.sessionService.listSessions(user.sub, currentHash);
12033
12083
  }
12034
12084
  // ---------------------------------------------------------------------------
12035
- // DELETE /sessions/all
12085
+ // POST /sessions/revoke-all
12036
12086
  // ---------------------------------------------------------------------------
12037
12087
  /**
12038
12088
  * Revokes all sessions for the authenticated user except the current one.
12039
12089
  *
12040
12090
  * Uses the refresh token from the request to determine which session to preserve.
12041
- * Throws `REFRESH_TOKEN_INVALID` if no refresh token is found — the current
12042
- * session cannot be determined without it, and revoking all sessions (including
12043
- * the caller's own) would force an immediate logout.
12091
+ * Throws `SESSION_NOT_FOUND` if no refresh token is found — the current session
12092
+ * cannot be determined without it, and revoking all sessions (including the
12093
+ * caller's own) would force an immediate logout.
12094
+ *
12095
+ * **POST, not DELETE, and the method is load-bearing.** Under
12096
+ * `tokenDelivery: 'bearer'` the refresh token this handler needs arrives in the
12097
+ * request body, and OpenAPI 3.0.3 defers to RFC 7231: a payload on DELETE has no
12098
+ * defined semantics, so `requestBody` there **SHALL be ignored by consumers**. A
12099
+ * generated client therefore dropped the body and every call answered
12100
+ * `SESSION_NOT_FOUND` — an operation the document could not describe and a client
12101
+ * could not reach. POST is the method whose body semantics are defined, so the
12102
+ * contributed fragment describes what the server actually reads.
12044
12103
  *
12045
12104
  * @param user - Verified JWT payload from the access token.
12046
12105
  * @param req - Incoming request (used to extract the current session's refresh token).
@@ -12093,7 +12152,7 @@ _ts_decorate49([
12093
12152
  Throttle(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
12094
12153
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.revokeAllSessions),
12095
12154
  HttpCode(HttpStatus.NO_CONTENT),
12096
- Delete("all"),
12155
+ Post("revoke-all"),
12097
12156
  _ts_param28(0, CurrentUser()),
12098
12157
  _ts_param28(1, Req()),
12099
12158
  _ts_metadata48("design:type", Function),
@@ -12483,10 +12542,11 @@ var OAuthService = class _OAuthService {
12483
12542
  * 5. Issues a 302 redirect via the Express `res` object.
12484
12543
  *
12485
12544
  * @param provider - Provider name matching a registered {@link OAuthProviderPlugin}.
12486
- * @param tenantId - Tenant the user will join on successful login, as named by the caller.
12487
- * Superseded by the configured `tenantIdResolver` when there is one, and never validated
12488
- * against the database — implement `onOAuthLogin` to enforce tenant membership. Without
12489
- * the hook, OAuth sign-in is disabled.
12545
+ * @param tenantId - Tenant the user will join on successful login, as named by the caller in
12546
+ * the query string. **Refused** with `auth.validation` when a `tenantIdResolver` is
12547
+ * configured, since the deployment decides the tenant and a value it discards would only
12548
+ * mislead the caller. Never validated against the database — implement `onOAuthLogin` to
12549
+ * enforce tenant membership. Without the hook, OAuth sign-in is disabled.
12490
12550
  * @param req - Incoming Express request, read by the configured `tenantIdResolver`.
12491
12551
  * @param res - Express response in passthrough mode (used for the 302 redirect).
12492
12552
  * @throws `AuthException(OAUTH_FAILED)` when no plugin is registered for `provider`.
@@ -12739,9 +12799,28 @@ var OAuthCallbackQueryDto = class {
12739
12799
  * is a safe upper bound that rejects clearly malformed payloads.
12740
12800
  *
12741
12801
  * Absent on the error callback RFC 6749 §4.1.2.1 defines — the response a provider sends
12742
- * when the user declines consent. Required whenever `error` is absent, so a callback
12743
- * carrying neither is still the malformed request it always was.
12744
- */
12802
+ * when the user declines consent. Never required here: a callback carrying neither `code`
12803
+ * nor `error` is an OAuth failure rather than a malformed request, and the handler is what
12804
+ * says so — `OAuthController.callback` answers `auth.oauth_failed`, which is also what
12805
+ * rust-auth answers for the same callback. Requiring it here made the handler's branch
12806
+ * unreachable and split one behaviour across two libraries.
12807
+ */
12808
+ // Two conditionals, and they compose conjunctively — class-validator's `ValidationExecutor`
12809
+ // reduces every `CONDITIONAL_VALIDATION` predicate with `&&` before running any validator.
12810
+ // So `code` is validated only when `error` is absent AND `code` is present:
12811
+ //
12812
+ // - `error` present → skipped entirely, whatever `code` carries. That is what keeps a
12813
+ // provider's error callback out of the validation envelope even when it arrives with an
12814
+ // empty or oversized `code` beside it, which is the reason `@ValidateIf` is here at all.
12815
+ // - `code` absent → skipped, and the request reaches the handler. This is the change:
12816
+ // the refusal moved from the pipe to the handler, where the behaviour lives.
12817
+ // - `code` present → the bounds below apply, unchanged.
12818
+ //
12819
+ // Both predicates read `null` as absent, matching `@IsOptional()`'s own
12820
+ // (`value !== null && value !== undefined`). A query string cannot carry `null`, so no
12821
+ // callback reaches this with one; the alignment matters because the declared overlay models
12822
+ // presence with one rule for every DTO, and a predicate that read `null` as *present* would
12823
+ // make this the single field the overlay describes wrongly.
12745
12824
  code;
12746
12825
  /**
12747
12826
  * The provider's error code (RFC 6749 §4.1.2.1) — `access_denied` when the user clicks
@@ -12807,7 +12886,8 @@ var OAuthCallbackQueryDto = class {
12807
12886
  hd;
12808
12887
  };
12809
12888
  _ts_decorate55([
12810
- ValidateIf((query) => query.error === void 0),
12889
+ ValidateIf((query) => query.error === void 0 || query.error === null),
12890
+ IsOptional(),
12811
12891
  IsString(),
12812
12892
  IsNotEmpty(),
12813
12893
  MaxLength(2048),
@@ -13435,6 +13515,350 @@ var OAuthModule = class _OAuthModule {
13435
13515
  OAuthModule = _ts_decorate58([
13436
13516
  Module({})
13437
13517
  ], OAuthModule);
13518
+
13519
+ // src/server/openapi/auth-openapi-fragment.ts
13520
+ var OPENAPI_CONTRACT_VERSION = 1;
13521
+ var OPENAPI_CONTRIBUTOR_METADATA = "bymax-one:openapi-contributor";
13522
+ var AUTH_SECURITY_SCHEMES = {
13523
+ accessCookie: "bymaxAuthAccessCookie",
13524
+ accessBearer: "bymaxAuthAccessBearer",
13525
+ refreshCookie: "bymaxAuthRefreshCookie",
13526
+ platformBearer: "bymaxPlatformAccessBearer"
13527
+ };
13528
+ var OPERATIONS = {
13529
+ auth: {
13530
+ "AuthController.register": "none",
13531
+ "AuthController.login": "none",
13532
+ // Both read the refresh credential, and neither is behind a guard: they are `@Public()`
13533
+ // because an expired access token must not stop a caller from ending or renewing a
13534
+ // session. What authorises them is the refresh token itself.
13535
+ // Measured, and the two differ: `logout` answers 204 with no credential at all, while
13536
+ // `refresh` 401s. Describing them alike would tell a generated client that one demands
13537
+ // something it does not, or that the other tolerates something it will refuse.
13538
+ //
13539
+ // `logout` reads the ACCESS token too, and a document that omitted it caused a weaker
13540
+ // logout than the server performs: the handler blacklists that token's `jti` for whatever
13541
+ // life it has left, so a generated client sending no `Authorization` header revokes the
13542
+ // refresh session and leaves a valid access token in circulation until it expires. Neither
13543
+ // credential is required — this is the operation a signed-out-by-expiry user reaches — so
13544
+ // every form is an alternative beside the empty one.
13545
+ "AuthController.logout": "optionalAccessAndRefresh",
13546
+ "AuthController.refresh": "refreshRequired",
13547
+ "AuthController.me": "access",
13548
+ "AuthController.wsTicket": "access",
13549
+ "AuthController.verifyEmail": "none",
13550
+ "AuthController.resendVerification": "none"
13551
+ },
13552
+ passwordReset: {
13553
+ "PasswordResetController.forgotPassword": "none",
13554
+ "PasswordResetController.resetPassword": "none",
13555
+ // Reads the refresh token to spare the caller's own session when it revokes the others, and
13556
+ // succeeds without it — a password change from a client that sent none simply signs every
13557
+ // session out, including the one that asked.
13558
+ "PasswordResetController.changePassword": "accessWithOptionalRefresh",
13559
+ "PasswordResetController.verifyOtp": "none",
13560
+ "PasswordResetController.resendOtp": "none"
13561
+ },
13562
+ mfa: {
13563
+ "MfaController.setup": "access",
13564
+ "MfaController.verifyEnable": "access",
13565
+ // The challenge is reached with a temp token, not a session — by definition the caller has
13566
+ // no access token yet, which is what the challenge exists to earn.
13567
+ "MfaController.challenge": "none",
13568
+ "MfaController.disable": "access",
13569
+ "MfaController.regenerateRecoveryCodes": "access"
13570
+ },
13571
+ sessions: {
13572
+ // Measured against the controller rather than inferred from the guard stack, and the three
13573
+ // differ. `listSessions` reads the refresh token to mark which session is the caller's own
13574
+ // and answers 200 without it (every `isCurrent` reads false). `revokeAllSessions` refuses
13575
+ // without it — it revokes everything EXCEPT the current session, so a request that cannot
13576
+ // name the current one would sign the caller out, and it answers `auth.session_not_found`
13577
+ // instead. `revokeSession` names its target in the path and reads no refresh token at all.
13578
+ "SessionController.listSessions": "accessWithOptionalRefreshCookie",
13579
+ "SessionController.revokeAllSessions": "accessAndRefreshRequired",
13580
+ "SessionController.revokeSession": "access"
13581
+ },
13582
+ platform: {
13583
+ "PlatformAuthController.login": "none",
13584
+ "PlatformAuthController.mfaChallenge": "none",
13585
+ "PlatformAuthController.me": "platform",
13586
+ // The access token authorises the logout; the refresh token in the body names the session
13587
+ // to end. Both are read, so both are described.
13588
+ "PlatformAuthController.logout": "platformLogout",
13589
+ // Refresh is the one platform operation with no access token at all: the refresh token in
13590
+ // the body is the whole credential.
13591
+ "PlatformAuthController.refresh": "platformRefresh",
13592
+ "PlatformAuthController.revokeSessions": "platform"
13593
+ },
13594
+ platformMfa: {
13595
+ "PlatformMfaController.setup": "platform",
13596
+ "PlatformMfaController.verifyEnable": "platform",
13597
+ "PlatformMfaController.disable": "platform",
13598
+ "PlatformMfaController.regenerateRecoveryCodes": "platform"
13599
+ },
13600
+ invitations: {
13601
+ "InvitationController.invite": "access",
13602
+ "InvitationController.revoke": "access",
13603
+ // Accepting is how an invitee gets their first credential, so it cannot require one.
13604
+ "InvitationController.accept": "none"
13605
+ },
13606
+ emailChange: {
13607
+ "EmailChangeController.requestChange": "access",
13608
+ // Public because the holder is proving control of a mailbox, not of a session.
13609
+ "EmailChangeController.confirmChange": "none"
13610
+ },
13611
+ oauth: {
13612
+ "OAuthController.initiate": "none",
13613
+ "OAuthController.callback": "none"
13614
+ }
13615
+ };
13616
+ var OPERATION_DESCRIPTIONS = /* @__PURE__ */ new Map([
13617
+ [
13618
+ // Measured by a consumer against a running deployment, and the reason this entry exists: a
13619
+ // logout called with no credential answers `204` and revokes NOTHING — the same access token
13620
+ // still gets `200` from `/me` afterwards. Every other imprecision in this fragment costs a
13621
+ // caller one rejected request; this one hands them a success while they stay signed in.
13622
+ //
13623
+ // The operation requires nothing, deliberately, so `security` cannot express any of that: an
13624
+ // empty requirement and an optional one render identically to a reader who is skimming. The
13625
+ // sentence is therefore the only place a person building a sign-out learns that the credential
13626
+ // they omitted was the one doing the work.
13627
+ "AuthController.logout",
13628
+ "Revokes the session and blacklists the access token, using whichever credentials the request carries. NEITHER is required \u2014 an operator whose access token has expired must still be able to sign out \u2014 but a call that carries none succeeds without revoking anything. Under `tokenDelivery: bearer` the refresh token in the request body is the only channel there is, so omitting it makes this a silent no-op."
13629
+ ]
13630
+ ]);
13631
+ var REFRESH_BODY = {
13632
+ required: false,
13633
+ content: {
13634
+ "application/json": {
13635
+ schema: {
13636
+ type: "object",
13637
+ properties: {
13638
+ refreshToken: {
13639
+ type: "string",
13640
+ description: "The refresh token, when it is not delivered as a cookie."
13641
+ }
13642
+ }
13643
+ }
13644
+ }
13645
+ }
13646
+ };
13647
+ var REQUIRED_REFRESH_BODY = {
13648
+ required: true,
13649
+ content: {
13650
+ "application/json": {
13651
+ schema: {
13652
+ type: "object",
13653
+ required: [
13654
+ "refreshToken"
13655
+ ],
13656
+ properties: {
13657
+ refreshToken: {
13658
+ type: "string",
13659
+ description: "The refresh token, when it is not delivered as a cookie."
13660
+ }
13661
+ }
13662
+ }
13663
+ }
13664
+ }
13665
+ };
13666
+ var PLATFORM_REFRESH_BODY = {
13667
+ required: true,
13668
+ content: {
13669
+ "application/json": {
13670
+ schema: {
13671
+ type: "object",
13672
+ required: [
13673
+ "refreshToken"
13674
+ ],
13675
+ properties: {
13676
+ refreshToken: {
13677
+ type: "string",
13678
+ description: "The platform refresh token."
13679
+ }
13680
+ }
13681
+ }
13682
+ }
13683
+ }
13684
+ };
13685
+ function buildAuthOpenApiFragment(options, registered) {
13686
+ const cookieDelivery = options.tokenDelivery === "cookie" || options.tokenDelivery === "both";
13687
+ const bearerDelivery = options.tokenDelivery === "bearer" || options.tokenDelivery === "both";
13688
+ const operations = {};
13689
+ for (const [controller, handlers] of Object.entries(OPERATIONS)) {
13690
+ if (!registered[controller]) continue;
13691
+ for (const [handler, credential] of Object.entries(handlers)) {
13692
+ const described = describe(credential, cookieDelivery, bearerDelivery);
13693
+ const note = OPERATION_DESCRIPTIONS.get(handler);
13694
+ operations[handler] = note === void 0 ? described : {
13695
+ ...described,
13696
+ description: note
13697
+ };
13698
+ }
13699
+ }
13700
+ return {
13701
+ contractVersion: OPENAPI_CONTRACT_VERSION,
13702
+ operations,
13703
+ components: {
13704
+ securitySchemes: schemesFor(options, registered, cookieDelivery, bearerDelivery)
13705
+ }
13706
+ };
13707
+ }
13708
+ __name(buildAuthOpenApiFragment, "buildAuthOpenApiFragment");
13709
+ function describe(credential, cookieDelivery, bearerDelivery) {
13710
+ switch (credential) {
13711
+ case "none":
13712
+ return {
13713
+ security: []
13714
+ };
13715
+ case "access":
13716
+ return {
13717
+ security: [
13718
+ ...cookieDelivery ? [
13719
+ {
13720
+ [AUTH_SECURITY_SCHEMES.accessCookie]: []
13721
+ }
13722
+ ] : [],
13723
+ ...bearerDelivery ? [
13724
+ {
13725
+ [AUTH_SECURITY_SCHEMES.accessBearer]: []
13726
+ }
13727
+ ] : []
13728
+ ]
13729
+ };
13730
+ case "refreshRequired":
13731
+ return {
13732
+ security: cookieDelivery ? bearerDelivery ? [
13733
+ {
13734
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
13735
+ },
13736
+ {}
13737
+ ] : [
13738
+ {
13739
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
13740
+ }
13741
+ ] : [],
13742
+ ...bearerDelivery ? {
13743
+ requestBody: cookieDelivery ? REFRESH_BODY : REQUIRED_REFRESH_BODY
13744
+ } : {}
13745
+ };
13746
+ case "accessAndRefreshRequired":
13747
+ case "accessWithOptionalRefresh":
13748
+ case "accessWithOptionalRefreshCookie":
13749
+ case "optionalAccessAndRefresh":
13750
+ return describeTwoCredentials(credential, cookieDelivery, bearerDelivery);
13751
+ case "platform":
13752
+ return {
13753
+ security: [
13754
+ {
13755
+ [AUTH_SECURITY_SCHEMES.platformBearer]: []
13756
+ }
13757
+ ]
13758
+ };
13759
+ case "platformLogout":
13760
+ return {
13761
+ security: [
13762
+ {
13763
+ [AUTH_SECURITY_SCHEMES.platformBearer]: []
13764
+ },
13765
+ {}
13766
+ ],
13767
+ requestBody: {
13768
+ ...PLATFORM_REFRESH_BODY,
13769
+ required: false
13770
+ }
13771
+ };
13772
+ case "platformRefresh":
13773
+ return {
13774
+ security: [],
13775
+ requestBody: PLATFORM_REFRESH_BODY
13776
+ };
13777
+ }
13778
+ }
13779
+ __name(describe, "describe");
13780
+ function describeTwoCredentials(credential, cookieDelivery, bearerDelivery) {
13781
+ const required = {
13782
+ access: credential !== "optionalAccessAndRefresh",
13783
+ refresh: credential === "accessAndRefreshRequired"
13784
+ };
13785
+ const bodyChannel = bearerDelivery && credential !== "accessWithOptionalRefreshCookie";
13786
+ const accessSchemes = [
13787
+ ...cookieDelivery ? [
13788
+ AUTH_SECURITY_SCHEMES.accessCookie
13789
+ ] : [],
13790
+ ...bearerDelivery ? [
13791
+ AUTH_SECURITY_SCHEMES.accessBearer
13792
+ ] : []
13793
+ ];
13794
+ const withRefreshCookie = cookieDelivery ? accessSchemes.map((access) => ({
13795
+ [access]: [],
13796
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
13797
+ })) : [];
13798
+ const accessAlone = bearerDelivery || !required.refresh ? accessSchemes.map((access) => ({
13799
+ [access]: []
13800
+ })) : [];
13801
+ const refreshAlone = !required.access && cookieDelivery ? [
13802
+ {
13803
+ [AUTH_SECURITY_SCHEMES.refreshCookie]: []
13804
+ }
13805
+ ] : [];
13806
+ const nothing = !required.access && !required.refresh ? [
13807
+ {}
13808
+ ] : [];
13809
+ return {
13810
+ security: [
13811
+ ...withRefreshCookie,
13812
+ ...accessAlone,
13813
+ ...refreshAlone,
13814
+ ...nothing
13815
+ ],
13816
+ ...bodyChannel ? {
13817
+ requestBody: cookieDelivery || !required.refresh ? REFRESH_BODY : REQUIRED_REFRESH_BODY
13818
+ } : {}
13819
+ };
13820
+ }
13821
+ __name(describeTwoCredentials, "describeTwoCredentials");
13822
+ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
13823
+ const schemes = {};
13824
+ const dashboardMounted = registered.auth || registered.passwordReset || registered.mfa || registered.sessions || registered.invitations || registered.emailChange;
13825
+ if (dashboardMounted && cookieDelivery) {
13826
+ schemes[AUTH_SECURITY_SCHEMES.accessCookie] = {
13827
+ type: "apiKey",
13828
+ in: "cookie",
13829
+ name: options.cookies.accessTokenName,
13830
+ description: "Access token, delivered as an HttpOnly cookie."
13831
+ };
13832
+ }
13833
+ if (dashboardMounted && bearerDelivery) {
13834
+ schemes[AUTH_SECURITY_SCHEMES.accessBearer] = {
13835
+ type: "http",
13836
+ scheme: "bearer",
13837
+ bearerFormat: "JWT",
13838
+ description: "Access token, delivered in the Authorization header."
13839
+ };
13840
+ }
13841
+ if ((registered.auth || registered.sessions || registered.passwordReset) && cookieDelivery) {
13842
+ schemes[AUTH_SECURITY_SCHEMES.refreshCookie] = {
13843
+ type: "apiKey",
13844
+ in: "cookie",
13845
+ name: options.cookies.refreshTokenName,
13846
+ description: "Refresh token, delivered as an HttpOnly cookie scoped to the auth prefix."
13847
+ };
13848
+ }
13849
+ if (registered.platform || registered.platformMfa) {
13850
+ schemes[AUTH_SECURITY_SCHEMES.platformBearer] = {
13851
+ type: "http",
13852
+ scheme: "bearer",
13853
+ bearerFormat: "JWT",
13854
+ description: "Platform administrator access token, always delivered in the Authorization header regardless of tokenDelivery."
13855
+ };
13856
+ }
13857
+ return schemes;
13858
+ }
13859
+ __name(schemesFor, "schemesFor");
13860
+
13861
+ // src/server/openapi/auth-openapi.contributor.ts
13438
13862
  function _ts_decorate59(decorators, target, key, desc) {
13439
13863
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13440
13864
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13461,6 +13885,62 @@ function _ts_param34(paramIndex, decorator) {
13461
13885
  };
13462
13886
  }
13463
13887
  __name(_ts_param34, "_ts_param");
13888
+ var AuthOpenApiContributor = class {
13889
+ static {
13890
+ __name(this, "AuthOpenApiContributor");
13891
+ }
13892
+ options;
13893
+ registered;
13894
+ constructor(options, registered) {
13895
+ this.options = options;
13896
+ this.registered = registered;
13897
+ }
13898
+ /**
13899
+ * Produces the fragments for this deployment.
13900
+ *
13901
+ * @returns Operations keyed by handler identity, and the security schemes they reference.
13902
+ */
13903
+ contributeOpenApi() {
13904
+ return buildAuthOpenApiFragment(this.options, this.registered);
13905
+ }
13906
+ };
13907
+ AuthOpenApiContributor = _ts_decorate59([
13908
+ Injectable(),
13909
+ SetMetadata(OPENAPI_CONTRIBUTOR_METADATA, true),
13910
+ _ts_param34(0, Inject(BYMAX_AUTH_OPTIONS)),
13911
+ _ts_param34(1, Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
13912
+ _ts_metadata56("design:type", Function),
13913
+ _ts_metadata56("design:paramtypes", [
13914
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13915
+ typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
13916
+ ])
13917
+ ], AuthOpenApiContributor);
13918
+ function _ts_decorate60(decorators, target, key, desc) {
13919
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13920
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13921
+ r = Reflect.decorate(decorators, target, key, desc);
13922
+ } else {
13923
+ for (var i = decorators.length - 1; i >= 0; i--) {
13924
+ if (d = decorators[i]) {
13925
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13926
+ }
13927
+ }
13928
+ }
13929
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13930
+ }
13931
+ __name(_ts_decorate60, "_ts_decorate");
13932
+ function _ts_metadata57(metadataKey, metadataValue) {
13933
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13934
+ return Reflect.metadata(metadataKey, metadataValue);
13935
+ }
13936
+ }
13937
+ __name(_ts_metadata57, "_ts_metadata");
13938
+ function _ts_param35(paramIndex, decorator) {
13939
+ return function(target, key) {
13940
+ decorator(target, key, paramIndex);
13941
+ };
13942
+ }
13943
+ __name(_ts_param35, "_ts_param");
13464
13944
  var COMMON_BASE_WORDS = [
13465
13945
  // The perennial top of every published list.
13466
13946
  "password",
@@ -13766,16 +14246,16 @@ var CommonPasswordChecker = class {
13766
14246
  return false;
13767
14247
  }
13768
14248
  };
13769
- CommonPasswordChecker = _ts_decorate59([
14249
+ CommonPasswordChecker = _ts_decorate60([
13770
14250
  Injectable(),
13771
- _ts_param34(0, Inject(BYMAX_AUTH_OPTIONS)),
13772
- _ts_param34(0, Optional()),
13773
- _ts_metadata56("design:type", Function),
13774
- _ts_metadata56("design:paramtypes", [
14251
+ _ts_param35(0, Inject(BYMAX_AUTH_OPTIONS)),
14252
+ _ts_param35(0, Optional()),
14253
+ _ts_metadata57("design:type", Function),
14254
+ _ts_metadata57("design:paramtypes", [
13775
14255
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13776
14256
  ])
13777
14257
  ], CommonPasswordChecker);
13778
- function _ts_decorate60(decorators, target, key, desc) {
14258
+ function _ts_decorate61(decorators, target, key, desc) {
13779
14259
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13780
14260
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13781
14261
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13788,7 +14268,7 @@ function _ts_decorate60(decorators, target, key, desc) {
13788
14268
  }
13789
14269
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13790
14270
  }
13791
- __name(_ts_decorate60, "_ts_decorate");
14271
+ __name(_ts_decorate61, "_ts_decorate");
13792
14272
  var NoOpEmailProvider = class _NoOpEmailProvider {
13793
14273
  static {
13794
14274
  __name(this, "NoOpEmailProvider");
@@ -13823,12 +14303,12 @@ var NoOpEmailProvider = class _NoOpEmailProvider {
13823
14303
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
13824
14304
  }
13825
14305
  };
13826
- NoOpEmailProvider = _ts_decorate60([
14306
+ NoOpEmailProvider = _ts_decorate61([
13827
14307
  Injectable()
13828
14308
  ], NoOpEmailProvider);
13829
14309
 
13830
14310
  // src/server/bymax-auth.module.ts
13831
- function _ts_decorate61(decorators, target, key, desc) {
14311
+ function _ts_decorate62(decorators, target, key, desc) {
13832
14312
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13833
14313
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13834
14314
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13841,7 +14321,7 @@ function _ts_decorate61(decorators, target, key, desc) {
13841
14321
  }
13842
14322
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13843
14323
  }
13844
- __name(_ts_decorate61, "_ts_decorate");
14324
+ __name(_ts_decorate62, "_ts_decorate");
13845
14325
  function hasProviderToken(providers, token) {
13846
14326
  return providers.some((p) => {
13847
14327
  if (typeof p === "function") return false;
@@ -14016,6 +14496,30 @@ var BymaxAuthModule = class _BymaxAuthModule {
14016
14496
  ...extraProviders,
14017
14497
  // Resolved options (depends on consumer's inject tokens).
14018
14498
  resolvedOptionsProvider,
14499
+ // Which controllers this registration mounted, and the contributor that reads it.
14500
+ //
14501
+ // The flags are computed above from the `controllers` argument, which Nest reads
14502
+ // synchronously — before any factory runs — so they cannot travel inside the resolved
14503
+ // options. The contributor needs them because a fragment naming a handler the document
14504
+ // does not contain FAILS a consumer's document build: a library that described its
14505
+ // platform routes on a deployment that never mounted them would break the build it was
14506
+ // supposed to describe.
14507
+ {
14508
+ provide: BYMAX_AUTH_REGISTERED_CONTROLLERS,
14509
+ useValue: {
14510
+ auth: includeAuth,
14511
+ passwordReset: includePasswordReset,
14512
+ mfa: includeMfa,
14513
+ sessions: includeSessions,
14514
+ platform: includePlatform,
14515
+ // One switch mounts both platform controllers, so they cannot disagree.
14516
+ platformMfa: includePlatform,
14517
+ invitations: includeInvitations,
14518
+ emailChange: includeEmailChange,
14519
+ oauth: includeOAuth
14520
+ }
14521
+ },
14522
+ AuthOpenApiContributor,
14019
14523
  // Fallback NoOp providers (skipped if consumer already supplied them).
14020
14524
  ...emailProviders,
14021
14525
  ...breachCheckerProviders,
@@ -14141,7 +14645,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
14141
14645
  };
14142
14646
  }
14143
14647
  };
14144
- BymaxAuthModule = _ts_decorate61([
14648
+ BymaxAuthModule = _ts_decorate62([
14145
14649
  Module({})
14146
14650
  ], BymaxAuthModule);
14147
14651
  var CODE_VALIDITY_TEXT = "It expires shortly, so use it soon.";
@@ -14353,7 +14857,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
14353
14857
  }
14354
14858
  }
14355
14859
  };
14356
- function _ts_decorate62(decorators, target, key, desc) {
14860
+ function _ts_decorate63(decorators, target, key, desc) {
14357
14861
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14358
14862
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14359
14863
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14366,13 +14870,13 @@ function _ts_decorate62(decorators, target, key, desc) {
14366
14870
  }
14367
14871
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14368
14872
  }
14369
- __name(_ts_decorate62, "_ts_decorate");
14370
- function _ts_metadata57(metadataKey, metadataValue) {
14873
+ __name(_ts_decorate63, "_ts_decorate");
14874
+ function _ts_metadata58(metadataKey, metadataValue) {
14371
14875
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14372
14876
  return Reflect.metadata(metadataKey, metadataValue);
14373
14877
  }
14374
14878
  }
14375
- __name(_ts_metadata57, "_ts_metadata");
14879
+ __name(_ts_metadata58, "_ts_metadata");
14376
14880
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
14377
14881
  var PREFIX_LENGTH = 5;
14378
14882
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -14429,10 +14933,10 @@ var HibpBreachChecker = class _HibpBreachChecker {
14429
14933
  }
14430
14934
  }
14431
14935
  };
14432
- HibpBreachChecker = _ts_decorate62([
14936
+ HibpBreachChecker = _ts_decorate63([
14433
14937
  Injectable(),
14434
- _ts_metadata57("design:type", Function),
14435
- _ts_metadata57("design:paramtypes", [
14938
+ _ts_metadata58("design:type", Function),
14939
+ _ts_metadata58("design:paramtypes", [
14436
14940
  Number
14437
14941
  ])
14438
14942
  ], HibpBreachChecker);
@@ -14445,10 +14949,10 @@ var AllowAllBreachChecker = class {
14445
14949
  return false;
14446
14950
  }
14447
14951
  };
14448
- AllowAllBreachChecker = _ts_decorate62([
14952
+ AllowAllBreachChecker = _ts_decorate63([
14449
14953
  Injectable()
14450
14954
  ], AllowAllBreachChecker);
14451
- function _ts_decorate63(decorators, target, key, desc) {
14955
+ function _ts_decorate64(decorators, target, key, desc) {
14452
14956
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14453
14957
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14454
14958
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14461,7 +14965,7 @@ function _ts_decorate63(decorators, target, key, desc) {
14461
14965
  }
14462
14966
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14463
14967
  }
14464
- __name(_ts_decorate63, "_ts_decorate");
14968
+ __name(_ts_decorate64, "_ts_decorate");
14465
14969
  var OptionalAuthGuard = class extends JwtAuthGuard {
14466
14970
  static {
14467
14971
  __name(this, "OptionalAuthGuard");
@@ -14476,10 +14980,10 @@ var OptionalAuthGuard = class extends JwtAuthGuard {
14476
14980
  return super.canActivate(context);
14477
14981
  }
14478
14982
  };
14479
- OptionalAuthGuard = _ts_decorate63([
14983
+ OptionalAuthGuard = _ts_decorate64([
14480
14984
  Injectable()
14481
14985
  ], OptionalAuthGuard);
14482
- function _ts_decorate64(decorators, target, key, desc) {
14986
+ function _ts_decorate65(decorators, target, key, desc) {
14483
14987
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14484
14988
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14485
14989
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14492,19 +14996,19 @@ function _ts_decorate64(decorators, target, key, desc) {
14492
14996
  }
14493
14997
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14494
14998
  }
14495
- __name(_ts_decorate64, "_ts_decorate");
14496
- function _ts_metadata58(metadataKey, metadataValue) {
14999
+ __name(_ts_decorate65, "_ts_decorate");
15000
+ function _ts_metadata59(metadataKey, metadataValue) {
14497
15001
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14498
15002
  return Reflect.metadata(metadataKey, metadataValue);
14499
15003
  }
14500
15004
  }
14501
- __name(_ts_metadata58, "_ts_metadata");
14502
- function _ts_param35(paramIndex, decorator) {
15005
+ __name(_ts_metadata59, "_ts_metadata");
15006
+ function _ts_param36(paramIndex, decorator) {
14503
15007
  return function(target, key) {
14504
15008
  decorator(target, key, paramIndex);
14505
15009
  };
14506
15010
  }
14507
- __name(_ts_param35, "_ts_param");
15011
+ __name(_ts_param36, "_ts_param");
14508
15012
  var SelfOrAdminGuard = class {
14509
15013
  static {
14510
15014
  __name(this, "SelfOrAdminGuard");
@@ -14534,11 +15038,11 @@ var SelfOrAdminGuard = class {
14534
15038
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14535
15039
  }
14536
15040
  };
14537
- SelfOrAdminGuard = _ts_decorate64([
15041
+ SelfOrAdminGuard = _ts_decorate65([
14538
15042
  Injectable(),
14539
- _ts_param35(0, Inject(BYMAX_AUTH_OPTIONS)),
14540
- _ts_metadata58("design:type", Function),
14541
- _ts_metadata58("design:paramtypes", [
15043
+ _ts_param36(0, Inject(BYMAX_AUTH_OPTIONS)),
15044
+ _ts_metadata59("design:type", Function),
15045
+ _ts_metadata59("design:paramtypes", [
14542
15046
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14543
15047
  ])
14544
15048
  ], SelfOrAdminGuard);
@@ -14551,7 +15055,7 @@ function isHexLooking(value) {
14551
15055
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
14552
15056
  }
14553
15057
  __name(isHexLooking, "isHexLooking");
14554
- function _ts_decorate65(decorators, target, key, desc) {
15058
+ function _ts_decorate66(decorators, target, key, desc) {
14555
15059
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14556
15060
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14557
15061
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14564,19 +15068,19 @@ function _ts_decorate65(decorators, target, key, desc) {
14564
15068
  }
14565
15069
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14566
15070
  }
14567
- __name(_ts_decorate65, "_ts_decorate");
14568
- function _ts_metadata59(metadataKey, metadataValue) {
15071
+ __name(_ts_decorate66, "_ts_decorate");
15072
+ function _ts_metadata60(metadataKey, metadataValue) {
14569
15073
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14570
15074
  return Reflect.metadata(metadataKey, metadataValue);
14571
15075
  }
14572
15076
  }
14573
- __name(_ts_metadata59, "_ts_metadata");
14574
- function _ts_param36(paramIndex, decorator) {
15077
+ __name(_ts_metadata60, "_ts_metadata");
15078
+ function _ts_param37(paramIndex, decorator) {
14575
15079
  return function(target, key) {
14576
15080
  decorator(target, key, paramIndex);
14577
15081
  };
14578
15082
  }
14579
- __name(_ts_param36, "_ts_param");
15083
+ __name(_ts_param37, "_ts_param");
14580
15084
  var WsJwtGuard = class {
14581
15085
  static {
14582
15086
  __name(this, "WsJwtGuard");
@@ -14604,14 +15108,18 @@ var WsJwtGuard = class {
14604
15108
  }
14605
15109
  async canActivate(context) {
14606
15110
  const client = context.switchToWs().getClient();
14607
- const ticket = readUpgradeTicket(client);
15111
+ const handshake = client.handshake;
15112
+ if (handshake === void 0 || handshake === null) {
15113
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
15114
+ }
15115
+ const ticket = readUpgradeTicket(handshake);
14608
15116
  if (ticket !== void 0) {
14609
15117
  const snapshot = await this.wsTickets.redeem(ticket);
14610
15118
  assertDashboardSnapshot(snapshot);
14611
15119
  client.data.user = snapshot;
14612
15120
  return true;
14613
15121
  }
14614
- const authHeader = client.handshake.headers["authorization"];
15122
+ const authHeader = handshake.headers["authorization"];
14615
15123
  const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : void 0;
14616
15124
  if (!token) {
14617
15125
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
@@ -14634,14 +15142,14 @@ var WsJwtGuard = class {
14634
15142
  return true;
14635
15143
  }
14636
15144
  };
14637
- WsJwtGuard = _ts_decorate65([
15145
+ WsJwtGuard = _ts_decorate66([
14638
15146
  Injectable(),
14639
- _ts_param36(0, Inject(JwtService)),
14640
- _ts_param36(1, Inject(AuthRevocationService)),
14641
- _ts_param36(2, Inject(WsTicketService)),
14642
- _ts_param36(3, Inject(BYMAX_AUTH_OPTIONS)),
14643
- _ts_metadata59("design:type", Function),
14644
- _ts_metadata59("design:paramtypes", [
15147
+ _ts_param37(0, Inject(JwtService)),
15148
+ _ts_param37(1, Inject(AuthRevocationService)),
15149
+ _ts_param37(2, Inject(WsTicketService)),
15150
+ _ts_param37(3, Inject(BYMAX_AUTH_OPTIONS)),
15151
+ _ts_metadata60("design:type", Function),
15152
+ _ts_metadata60("design:paramtypes", [
14645
15153
  typeof JwtService === "undefined" ? Object : JwtService,
14646
15154
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
14647
15155
  typeof WsTicketService === "undefined" ? Object : WsTicketService,
@@ -14657,11 +15165,11 @@ function assertDashboardSnapshot(snapshot) {
14657
15165
  }
14658
15166
  }
14659
15167
  __name(assertDashboardSnapshot, "assertDashboardSnapshot");
14660
- function readUpgradeTicket(client) {
14661
- const fromQuery = client.handshake.query?.["ticket"];
15168
+ function readUpgradeTicket(handshake) {
15169
+ const fromQuery = handshake.query?.["ticket"];
14662
15170
  if (typeof fromQuery === "string" && fromQuery !== "") return fromQuery;
14663
15171
  if (fromQuery !== void 0) return void 0;
14664
- const url = client.handshake.url;
15172
+ const url = handshake.url;
14665
15173
  if (typeof url !== "string") return void 0;
14666
15174
  if (url === "") return void 0;
14667
15175
  let params;
@@ -14674,7 +15182,7 @@ function readUpgradeTicket(client) {
14674
15182
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
14675
15183
  }
14676
15184
  __name(readUpgradeTicket, "readUpgradeTicket");
14677
- function _ts_decorate66(decorators, target, key, desc) {
15185
+ function _ts_decorate67(decorators, target, key, desc) {
14678
15186
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14679
15187
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14680
15188
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14687,7 +15195,7 @@ function _ts_decorate66(decorators, target, key, desc) {
14687
15195
  }
14688
15196
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14689
15197
  }
14690
- __name(_ts_decorate66, "_ts_decorate");
15198
+ __name(_ts_decorate67, "_ts_decorate");
14691
15199
  function isAuthEnvelope(body) {
14692
15200
  if (typeof body !== "object" || body === null) return false;
14693
15201
  const error = body.error;
@@ -14739,8 +15247,68 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
14739
15247
  });
14740
15248
  }
14741
15249
  };
14742
- AuthExceptionFilter = _ts_decorate66([
15250
+ AuthExceptionFilter = _ts_decorate67([
14743
15251
  Catch()
14744
15252
  ], AuthExceptionFilter);
15253
+ function _ts_decorate68(decorators, target, key, desc) {
15254
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15255
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15256
+ r = Reflect.decorate(decorators, target, key, desc);
15257
+ } else {
15258
+ for (var i = decorators.length - 1; i >= 0; i--) {
15259
+ if (d = decorators[i]) {
15260
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
15261
+ }
15262
+ }
15263
+ }
15264
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
15265
+ }
15266
+ __name(_ts_decorate68, "_ts_decorate");
15267
+ function isEmittingClient(client) {
15268
+ return typeof client?.emit === "function";
15269
+ }
15270
+ __name(isEmittingClient, "isEmittingClient");
15271
+ var WS_OPEN = 1;
15272
+ function isSendingClient(client) {
15273
+ const candidate = client;
15274
+ return typeof candidate?.readyState === "number" && typeof candidate.send === "function";
15275
+ }
15276
+ __name(isSendingClient, "isSendingClient");
15277
+ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
15278
+ static {
15279
+ __name(this, "WsAuthExceptionFilter");
15280
+ }
15281
+ logger = new Logger(_WsAuthExceptionFilter.name);
15282
+ /**
15283
+ * Delivers the library envelope to the client whose request was refused.
15284
+ *
15285
+ * @param exception - The `AuthException` a guard, pipe or handler raised.
15286
+ * @param host - The arguments host, used to reach the connected client.
15287
+ */
15288
+ catch(exception, host) {
15289
+ const client = host.switchToWs().getClient();
15290
+ const payload = {
15291
+ status: "error",
15292
+ ...exception.getResponse()
15293
+ };
15294
+ if (isSendingClient(client)) {
15295
+ if (client.readyState === WS_OPEN) {
15296
+ client.send(JSON.stringify({
15297
+ event: "exception",
15298
+ data: payload
15299
+ }));
15300
+ }
15301
+ return;
15302
+ }
15303
+ if (isEmittingClient(client)) {
15304
+ client.emit("exception", payload);
15305
+ return;
15306
+ }
15307
+ this.logger.error("refused a request on a client this filter cannot answer", exception);
15308
+ }
15309
+ };
15310
+ WsAuthExceptionFilter = _ts_decorate68([
15311
+ Catch(AuthException)
15312
+ ], WsAuthExceptionFilter);
14745
15313
 
14746
- export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AllowAllBreachChecker, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, Authenticated, 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, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsJwtGuard, WsTicketService, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
15314
+ export { AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AllowAllBreachChecker, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, Authenticated, 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, BruteForceService, BymaxAuthModule, ChangePasswordDto, CommonPasswordChecker, CreateInvitationDto, CurrentUser, DefaultAuthEmailProvider, EmailChangeService, ForgotPasswordDto, HibpBreachChecker, IS_PUBLIC_KEY, InvitationService, JwtAuthGuard, JwtPlatformGuard, LoginDto, MfaChallengeDto, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, OAuthService, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, PlatformAuthService, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, Roles, RolesGuard, SKIP_MFA_KEY, SelfOrAdminGuard, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, createAuthValidationPipe, decrypt, encrypt, generateSecureToken, hasRole, hmacSha256, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };