@bymax-one/nest-auth 1.4.6 → 1.4.9

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,10 +1,10 @@
1
- import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch } from '@nestjs/common';
1
+ import { createParamDecorator, HttpException, HttpStatus, Injectable, Inject, Logger, Optional, ValidationPipe, Post, Body, Req, Res, HttpCode, UseGuards, Get, UseInterceptors, Controller, UsePipes, Delete, Param, Query, Module, SetMetadata, Catch, applyDecorators } from '@nestjs/common';
2
+ import { Reflector, DiscoveryService, MetadataScanner, DiscoveryModule } from '@nestjs/core';
2
3
  import { JwtService, JwtModule } from '@nestjs/jwt';
3
4
  import { randomInt, scrypt as scrypt$1, randomBytes, timingSafeEqual, randomUUID, createHash, createHmac, createCipheriv, createDecipheriv } from 'crypto';
4
5
  import { Throttle } from '@nestjs/throttler';
5
6
  import { Transform, plainToInstance } from 'class-transformer';
6
7
  import { IsEmail, MaxLength, IsString, MinLength, IsOptional, IsNotEmpty, Matches, Length, ValidateIf } from 'class-validator';
7
- import { Reflector } from '@nestjs/core';
8
8
  import { isIPv6 } from 'net';
9
9
  import { promisify } from 'util';
10
10
 
@@ -20,6 +20,8 @@ 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
22
  var BYMAX_AUTH_REGISTERED_CONTROLLERS = /* @__PURE__ */ Symbol("BYMAX_AUTH_REGISTERED_CONTROLLERS");
23
+ var BYMAX_AUTH_API_KEY_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_AUTH_API_KEY_REPOSITORY");
24
+ var BYMAX_AUTH_API_KEY_CLOCK = /* @__PURE__ */ Symbol("BYMAX_AUTH_API_KEY_CLOCK");
23
25
 
24
26
  // src/server/config/default-options.ts
25
27
  var DEFAULT_OPTIONS = {
@@ -132,6 +134,17 @@ var DEFAULT_OPTIONS = {
132
134
  // link can be accepted by an unintended recipient. Do not increase beyond 7 days.
133
135
  tokenTtlSeconds: 172800
134
136
  },
137
+ apiKeys: {
138
+ enabled: false,
139
+ // Placeholders: validation requires a real pepper and vocabulary before `enabled` can be
140
+ // true, so these values are never used to hash or admit anything.
141
+ pepper: "",
142
+ scopes: [],
143
+ header: "x-api-key",
144
+ prefix: "bak",
145
+ lastUsedFlushSeconds: 60,
146
+ auditMode: "best-effort"
147
+ },
135
148
  controllers: {
136
149
  // auth and passwordReset are opt-out (enabled by default).
137
150
  // All other controllers are opt-in (disabled by default) — they require
@@ -161,6 +174,28 @@ var DEFAULT_OPTIONS = {
161
174
  userStatusCacheTtlSeconds: 60
162
175
  };
163
176
 
177
+ // src/server/constants/request-headers.ts
178
+ var LIBRARY_READ_HEADERS = [
179
+ // The user JWT bearer, on HTTP and on the WebSocket handshake.
180
+ "authorization",
181
+ "proxy-authorization",
182
+ // Session cookies, which the host's cookie parser exposes as `req.cookies`.
183
+ "cookie",
184
+ "set-cookie",
185
+ // Copied into the `userAgent` field of every hook context.
186
+ "user-agent",
187
+ // The cross-site request checks of `TrustedOriginGuard`.
188
+ "origin",
189
+ "sec-fetch-site",
190
+ // What the client address (`request.ip`) is derived from behind a trusted proxy.
191
+ "x-forwarded-for",
192
+ "x-forwarded-host",
193
+ "x-real-ip",
194
+ "x-original-forwarded-for",
195
+ // The `hostname` handed to a `tenantIdResolver` on a WebSocket upgrade, which has no Express request.
196
+ "host"
197
+ ];
198
+
164
199
  // src/server/constants/token-epoch.ts
165
200
  var TOKEN_EPOCH_RETENTION_SECONDS = 30 * 24 * 60 * 60;
166
201
  var TOTP_STEP_SECONDS = 30;
@@ -309,6 +344,7 @@ function resolveOptions(userOptions) {
309
344
  validateOAuthProviders(userOptions.oauth, isProductionDeployment(userOptions));
310
345
  validateClientIpSource(userOptions.rateLimit);
311
346
  validateTenantBinding(userOptions);
347
+ validateApiKeys(userOptions);
312
348
  validateOAuthSuccessRedirectUrl(userOptions);
313
349
  validateOAuthMfaRedirectUrl(userOptions);
314
350
  const { issuer: rawIssuer, audience: rawAudience, ...jwtWithoutBinding } = userOptions.jwt;
@@ -373,6 +409,7 @@ function resolveOptions(userOptions) {
373
409
  ...DEFAULT_OPTIONS.invitations,
374
410
  ...userOptions.invitations
375
411
  },
412
+ apiKeys: resolveApiKeys(userOptions.apiKeys),
376
413
  emailChange: {
377
414
  ...DEFAULT_OPTIONS.emailChange,
378
415
  ...userOptions.emailChange
@@ -432,6 +469,7 @@ function withholdSecrets(resolved) {
432
469
  withholdFromSerialization(resolved.jwt, "previousSecrets");
433
470
  withholdFromSerialization(resolved, "hmacKey");
434
471
  withholdFromSerialization(resolved, "previousHmacKeys");
472
+ withholdFromSerialization(resolved.apiKeys, "pepper");
435
473
  if (resolved.mfa !== void 0) {
436
474
  withholdFromSerialization(resolved.mfa, "encryptionKey");
437
475
  withholdFromSerialization(resolved.mfa, "previousEncryptionKeys");
@@ -468,6 +506,89 @@ function validateTenantBinding(userOptions) {
468
506
  }
469
507
  }
470
508
  __name(validateTenantBinding, "validateTenantBinding");
509
+ var API_KEY_SCOPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
510
+ var API_KEY_PREFIX_PATTERN = /^[a-z][a-z0-9]{1,15}$/;
511
+ var API_KEY_HEADER_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
512
+ var API_KEY_FORBIDDEN_HEADERS = new Set(LIBRARY_READ_HEADERS);
513
+ function resolveApiKeys(user) {
514
+ const defaults = DEFAULT_OPTIONS.apiKeys;
515
+ return {
516
+ enabled: user?.enabled ?? defaults.enabled,
517
+ pepper: user?.pepper ?? defaults.pepper,
518
+ scopes: user?.scopes ?? defaults.scopes,
519
+ // Node lowercases incoming header names, so a mixed-case option would never match.
520
+ header: typeof user?.header === "string" ? user.header.toLowerCase() : defaults.header,
521
+ prefix: user?.prefix ?? defaults.prefix,
522
+ lastUsedFlushSeconds: user?.lastUsedFlushSeconds ?? defaults.lastUsedFlushSeconds,
523
+ auditMode: user?.auditMode ?? defaults.auditMode
524
+ };
525
+ }
526
+ __name(resolveApiKeys, "resolveApiKeys");
527
+ function validateApiKeys(userOptions) {
528
+ const group = userOptions.apiKeys;
529
+ if (group?.enabled !== true) return;
530
+ validateApiKeyPepper(group.pepper, userOptions);
531
+ validateApiKeyScopes(group.scopes);
532
+ validateApiKeyTransport(group);
533
+ validateApiKeyTuning(group);
534
+ }
535
+ __name(validateApiKeys, "validateApiKeys");
536
+ function validateApiKeyPepper(pepper, userOptions) {
537
+ validateSecretStrength(pepper, "apiKeys.pepper");
538
+ const retired = userOptions.jwt.previousSecrets ?? [];
539
+ const mfaRetired = userOptions.mfa?.previousEncryptionKeys ?? [];
540
+ const mfaKeys = [
541
+ userOptions.mfa?.encryptionKey,
542
+ ...mfaRetired
543
+ ];
544
+ const reused = /* @__PURE__ */ new Set([
545
+ userOptions.jwt.secret,
546
+ userOptions.identifierKey,
547
+ ...retired,
548
+ ...mfaKeys
549
+ ]);
550
+ if (reused.has(pepper)) {
551
+ throw new Error(`[BymaxAuthModule] apiKeys.pepper must not equal jwt.secret, a retired jwt secret, identifierKey or an MFA encryption key. A key shared across purposes is one leak away from all of them.`);
552
+ }
553
+ }
554
+ __name(validateApiKeyPepper, "validateApiKeyPepper");
555
+ function validateApiKeyScopes(value) {
556
+ if (!Array.isArray(value) || value.length === 0) {
557
+ throw new Error(`[BymaxAuthModule] apiKeys.scopes must be a non-empty array: it is the closed vocabulary every route declaration and every issued key is checked against.`);
558
+ }
559
+ const seen = /* @__PURE__ */ new Set();
560
+ for (const [index, scope] of value.entries()) {
561
+ if (typeof scope !== "string" || !API_KEY_SCOPE_PATTERN.test(scope)) {
562
+ throw new Error(`[BymaxAuthModule] apiKeys.scopes[${index}] must be 1 to 64 characters of letters, digits and ':', '.', '_', '-', starting with a letter or digit.`);
563
+ }
564
+ if (seen.has(scope)) {
565
+ throw new Error(`[BymaxAuthModule] apiKeys.scopes[${index}] repeats an earlier scope.`);
566
+ }
567
+ seen.add(scope);
568
+ }
569
+ }
570
+ __name(validateApiKeyScopes, "validateApiKeyScopes");
571
+ function validateApiKeyTransport(group) {
572
+ const { header, prefix } = group;
573
+ const name = typeof header === "string" ? header.toLowerCase() : header;
574
+ if (name !== void 0 && (typeof name !== "string" || !API_KEY_HEADER_PATTERN.test(name) || API_KEY_FORBIDDEN_HEADERS.has(name))) {
575
+ throw new Error(`[BymaxAuthModule] apiKeys.header must be a header name other than a header the library reads or derives a field from (authorization, cookie, user-agent, origin, the forwarded-address headers and the like): a key read from one would travel through a path built for something else.`);
576
+ }
577
+ if (prefix !== void 0 && (typeof prefix !== "string" || !API_KEY_PREFIX_PATTERN.test(prefix))) {
578
+ throw new Error(`[BymaxAuthModule] apiKeys.prefix must be 2 to 16 lowercase letters and digits, starting with a letter. An underscore is not allowed: it separates the parts of a key.`);
579
+ }
580
+ }
581
+ __name(validateApiKeyTransport, "validateApiKeyTransport");
582
+ function validateApiKeyTuning(group) {
583
+ const { lastUsedFlushSeconds, auditMode } = group;
584
+ if (lastUsedFlushSeconds !== void 0 && (!Number.isInteger(lastUsedFlushSeconds) || lastUsedFlushSeconds < 1 || lastUsedFlushSeconds > 3600)) {
585
+ throw new Error(`[BymaxAuthModule] apiKeys.lastUsedFlushSeconds must be an integer from 1 to 3600.`);
586
+ }
587
+ if (auditMode !== void 0 && auditMode !== "best-effort" && auditMode !== "required") {
588
+ throw new Error(`[BymaxAuthModule] apiKeys.auditMode must be 'best-effort' or 'required'.`);
589
+ }
590
+ }
591
+ __name(validateApiKeyTuning, "validateApiKeyTuning");
471
592
  function validateJwt(jwt) {
472
593
  if (!jwt) {
473
594
  throw new Error(`[BymaxAuthModule] jwt configuration is required. Provide at least jwt.secret.`);
@@ -1627,6 +1748,26 @@ var AUTH_ERROR_CODES = {
1627
1748
  // ---------------------------------------------------------------------------
1628
1749
  /** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
1629
1750
  PLATFORM_AUTH_REQUIRED: "auth.platform_auth_required",
1751
+ // ---------------------------------------------------------------------------
1752
+ // Service API keys
1753
+ // ---------------------------------------------------------------------------
1754
+ /**
1755
+ * The presented service key is not accepted.
1756
+ *
1757
+ * One code for every way a credential can fail — absent, malformed, unknown, wrong secret,
1758
+ * revoked, expired — so the answer tells a caller nothing about which of them it was. The
1759
+ * reason is recorded in the audit hook, where only the operator reads it.
1760
+ */
1761
+ API_KEY_INVALID: "auth.api_key_invalid",
1762
+ /**
1763
+ * The service key is valid but does not hold every scope the route declares.
1764
+ *
1765
+ * Safe to name because the caller has already proved the key. The body does not list the
1766
+ * scopes, so it is no map of what other routes require.
1767
+ */
1768
+ API_KEY_SCOPE_INSUFFICIENT: "auth.api_key_scope_insufficient",
1769
+ /** A key operation named an id that does not exist. Raised by revoke and rotate only. */
1770
+ API_KEY_NOT_FOUND: "auth.api_key_not_found",
1630
1771
  /**
1631
1772
  * An unexpected internal failure. The cause is logged and never serialized.
1632
1773
  *
@@ -1675,6 +1816,9 @@ var AUTH_ERROR_STATUS = {
1675
1816
  "auth.oauth_failed": 401,
1676
1817
  "auth.oauth_email_mismatch": 409,
1677
1818
  "auth.platform_auth_required": 401,
1819
+ "auth.api_key_invalid": 401,
1820
+ "auth.api_key_scope_insufficient": 403,
1821
+ "auth.api_key_not_found": 404,
1678
1822
  "auth.internal": 500
1679
1823
  };
1680
1824
  var AUTH_ERROR_MESSAGES = {
@@ -1715,6 +1859,9 @@ var AUTH_ERROR_MESSAGES = {
1715
1859
  "auth.oauth_email_mismatch": "OAuth email does not match",
1716
1860
  "auth.token_missing": "Token missing",
1717
1861
  "auth.platform_auth_required": "Platform authentication required",
1862
+ "auth.api_key_invalid": "Invalid API key",
1863
+ "auth.api_key_scope_insufficient": "API key lacks the required scope",
1864
+ "auth.api_key_not_found": "API key not found",
1718
1865
  "auth.internal": "Internal server error"
1719
1866
  };
1720
1867
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
@@ -8617,6 +8764,17 @@ var InvitationService = class _InvitationService {
8617
8764
  await this.redis.del(`inv:${supersededHash}`);
8618
8765
  }
8619
8766
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
8767
+ let stillNamed;
8768
+ try {
8769
+ stillNamed = await this.claimInviteeIndex(normalizedEmail, tenantId, tokenHash, ttl, tokenHash);
8770
+ } catch (err) {
8771
+ await this.withdrawRecord(tokenKey);
8772
+ throw err;
8773
+ }
8774
+ if (!stillNamed.claimed) {
8775
+ await this.withdrawRecord(tokenKey);
8776
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8777
+ }
8620
8778
  const displayTenantName = tenantName ?? tenantId;
8621
8779
  const expiresAt = new Date(Date.now() + ttl * 1e3);
8622
8780
  try {
@@ -8743,6 +8901,21 @@ var InvitationService = class _InvitationService {
8743
8901
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8744
8902
  }
8745
8903
  /**
8904
+ * Removes the invitation record this call wrote, best-effort.
8905
+ *
8906
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
8907
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
8908
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
8909
+ * holds the token for, until its TTL.
8910
+ *
8911
+ * @param tokenKey - The Redis key of the record written by this call.
8912
+ */
8913
+ async withdrawRecord(tokenKey) {
8914
+ await this.redis.del(tokenKey).catch((err) => {
8915
+ this.logger.warn(`invite: could not withdraw the record \u2014 ${describeChannelStatus(err)}`);
8916
+ });
8917
+ }
8918
+ /**
8746
8919
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
8747
8920
  *
8748
8921
  * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
@@ -9464,6 +9637,18 @@ function decrypt(ciphertext, keyBase64) {
9464
9637
  }
9465
9638
  __name(decrypt, "decrypt");
9466
9639
 
9640
+ // src/server/utils/run-detached.ts
9641
+ function runDetached(logger, run, failure) {
9642
+ try {
9643
+ void Promise.resolve(run()).catch((err) => {
9644
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9645
+ });
9646
+ } catch (err) {
9647
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9648
+ }
9649
+ }
9650
+ __name(runDetached, "runDetached");
9651
+
9467
9652
  // src/server/services/mfa.service.ts
9468
9653
  function _ts_decorate36(decorators, target, key, desc) {
9469
9654
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -10144,14 +10329,19 @@ var MfaService = class _MfaService {
10144
10329
  userAgent
10145
10330
  });
10146
10331
  }
10332
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
10333
+ id: safeUser.id,
10334
+ tenantId: safeUser.tenantId
10335
+ }), "challenge: updateLastLogin failed");
10147
10336
  if (this.hooks.afterLogin) {
10148
- void Promise.resolve(this.hooks.afterLogin(safeUser, {
10337
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10338
+ runDetached(this.logger, () => afterLogin(safeUser, {
10149
10339
  plane: "dashboard",
10150
10340
  userId,
10151
10341
  ip,
10152
10342
  userAgent,
10153
10343
  sanitizedHeaders: {}
10154
- })).catch(() => void 0);
10344
+ }), "challenge: afterLogin hook threw");
10155
10345
  }
10156
10346
  return result2;
10157
10347
  }
@@ -10159,14 +10349,16 @@ var MfaService = class _MfaService {
10159
10349
  const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10160
10350
  mfaVerified: true
10161
10351
  });
10352
+ runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10162
10353
  if (this.hooks.afterLogin) {
10163
- void Promise.resolve(this.hooks.afterLogin(this.platformUserAsSafeUser(platformUser), {
10354
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10355
+ runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10164
10356
  plane: "platform",
10165
10357
  userId,
10166
10358
  ip,
10167
10359
  userAgent,
10168
10360
  sanitizedHeaders: {}
10169
- })).catch(() => void 0);
10361
+ }), "challenge: afterLogin hook threw");
10170
10362
  }
10171
10363
  return result;
10172
10364
  }
@@ -13310,6 +13502,8 @@ SessionController = _ts_decorate50([
13310
13502
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
13311
13503
  ])
13312
13504
  ], SessionController);
13505
+ var API_KEY_SCOPES_KEY = /* @__PURE__ */ Symbol("bymax:apiKeyScopes");
13506
+ var ApiKeyScopes = /* @__PURE__ */ __name((...scopes) => SetMetadata(API_KEY_SCOPES_KEY, scopes), "ApiKeyScopes");
13313
13507
  function _ts_decorate51(decorators, target, key, desc) {
13314
13508
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13315
13509
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13336,44 +13530,120 @@ function _ts_param30(paramIndex, decorator) {
13336
13530
  };
13337
13531
  }
13338
13532
  __name(_ts_param30, "_ts_param");
13339
- var MfaRequiredGuard = class {
13533
+ var ApiKeyLastUsedService = class _ApiKeyLastUsedService {
13340
13534
  static {
13341
- __name(this, "MfaRequiredGuard");
13535
+ __name(this, "ApiKeyLastUsedService");
13342
13536
  }
13343
- reflector;
13344
- constructor(reflector) {
13345
- this.reflector = reflector;
13537
+ repository;
13538
+ options;
13539
+ logger = new Logger(_ApiKeyLastUsedService.name);
13540
+ pending = /* @__PURE__ */ new Map();
13541
+ timer = null;
13542
+ closed = false;
13543
+ constructor(repository, options) {
13544
+ this.repository = repository;
13545
+ this.options = options;
13346
13546
  }
13347
- canActivate(context) {
13348
- const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13349
- context.getHandler(),
13350
- context.getClass()
13351
- ]);
13352
- if (skipMfa) return true;
13353
- const request = context.switchToHttp().getRequest();
13354
- const user = request.user;
13355
- if (!user) return true;
13356
- if (typeof user.mfaEnabled !== "boolean") {
13357
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13547
+ /**
13548
+ * Notes that a key verified at an instant. Synchronous and free of I/O.
13549
+ *
13550
+ * @param id - The key's row id.
13551
+ * @param at - When it verified.
13552
+ */
13553
+ record(id, at) {
13554
+ const seen = this.pending.get(id);
13555
+ if (seen === void 0 || seen.getTime() < at.getTime()) this.pending.set(id, at);
13556
+ if (this.timer === null && !this.closed) {
13557
+ this.timer = setTimeout(() => {
13558
+ this.timer = null;
13559
+ void this.flush();
13560
+ }, this.options.apiKeys.lastUsedFlushSeconds * 1e3);
13561
+ this.timer.unref();
13358
13562
  }
13359
- if (user.mfaEnabled === true && user.mfaVerified !== true) {
13360
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13563
+ }
13564
+ /**
13565
+ * Writes everything pending in one batch. A failure keeps the entries for the next window.
13566
+ *
13567
+ * @returns Resolves once the batch is written or has been put back.
13568
+ */
13569
+ async flush() {
13570
+ if (this.pending.size === 0) return;
13571
+ const batch = this.pending;
13572
+ this.pending = /* @__PURE__ */ new Map();
13573
+ try {
13574
+ await this.repository.touchLastUsed([
13575
+ ...batch
13576
+ ].map(([id, at]) => ({
13577
+ id,
13578
+ at
13579
+ })));
13580
+ } catch (err) {
13581
+ this.logger.warn(`api-key: last-used flush failed cause=${describeChannelStatus(err)}`);
13582
+ for (const [id, at] of batch) this.record(id, at);
13361
13583
  }
13362
- return true;
13584
+ }
13585
+ /** Flushes what is left so a clean shutdown loses nothing. */
13586
+ async onApplicationShutdown() {
13587
+ this.closed = true;
13588
+ if (this.timer !== null) clearTimeout(this.timer);
13589
+ this.timer = null;
13590
+ await this.flush();
13363
13591
  }
13364
13592
  };
13365
- MfaRequiredGuard = _ts_decorate51([
13593
+ ApiKeyLastUsedService = _ts_decorate51([
13366
13594
  Injectable(),
13367
- _ts_param30(0, Inject(Reflector)),
13595
+ _ts_param30(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13596
+ _ts_param30(1, Inject(BYMAX_AUTH_OPTIONS)),
13368
13597
  _ts_metadata50("design:type", Function),
13369
13598
  _ts_metadata50("design:paramtypes", [
13370
- typeof Reflector === "undefined" ? Object : Reflector
13599
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13600
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13371
13601
  ])
13372
- ], MfaRequiredGuard);
13373
- var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13374
- var PlatformRoles = /* @__PURE__ */ __name((...roles) => SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13602
+ ], ApiKeyLastUsedService);
13603
+ var SEPARATOR = "_";
13604
+ var KEY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13605
+ var SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
13606
+ var SECRET_BYTES = 32;
13607
+ var DIGEST_HEX = /^[0-9a-f]{64}$/;
13608
+ var API_KEY_DUMMY_KEY_ID = "00000000-0000-4000-8000-000000000000";
13609
+ var API_KEY_DUMMY_SECRET = "A".repeat(43);
13610
+ var API_KEY_DUMMY_DIGEST = "0".repeat(64);
13611
+ function generateApiKeySecret() {
13612
+ return randomBytes(SECRET_BYTES).toString("base64url");
13613
+ }
13614
+ __name(generateApiKeySecret, "generateApiKeySecret");
13615
+ function formatApiKey(prefix, keyId, secret) {
13616
+ return `${prefix}${SEPARATOR}${keyId}${SEPARATOR}${secret}`;
13617
+ }
13618
+ __name(formatApiKey, "formatApiKey");
13619
+ function parseApiKey(raw, prefix) {
13620
+ if (typeof raw !== "string") return null;
13621
+ const head = `${prefix}${SEPARATOR}`;
13622
+ if (!raw.startsWith(head)) return null;
13623
+ const rest = raw.slice(head.length);
13624
+ const keyId = rest.slice(0, 36);
13625
+ if (rest[36] !== SEPARATOR) return null;
13626
+ const secret = rest.slice(37);
13627
+ if (!KEY_ID_PATTERN.test(keyId) || !SECRET_PATTERN.test(secret)) return null;
13628
+ return {
13629
+ keyId,
13630
+ secret
13631
+ };
13632
+ }
13633
+ __name(parseApiKey, "parseApiKey");
13634
+ function apiKeyDigest(secret, pepper) {
13635
+ return hmacSha256(secret, pepper);
13636
+ }
13637
+ __name(apiKeyDigest, "apiKeyDigest");
13638
+ function digestsMatch(computed, stored) {
13639
+ const wellFormed = DIGEST_HEX.test(computed) && DIGEST_HEX.test(stored);
13640
+ const left = Buffer.from(wellFormed ? computed : API_KEY_DUMMY_DIGEST, "hex");
13641
+ const right = Buffer.from(wellFormed ? stored : API_KEY_DUMMY_DIGEST, "hex");
13642
+ return timingSafeEqual(left, right) && wellFormed;
13643
+ }
13644
+ __name(digestsMatch, "digestsMatch");
13375
13645
 
13376
- // src/server/guards/platform-roles.guard.ts
13646
+ // src/server/services/api-key-verifier.service.ts
13377
13647
  function _ts_decorate52(decorators, target, key, desc) {
13378
13648
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13379
13649
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13400,53 +13670,81 @@ function _ts_param31(paramIndex, decorator) {
13400
13670
  };
13401
13671
  }
13402
13672
  __name(_ts_param31, "_ts_param");
13403
- var PlatformRolesGuard = class {
13673
+ var ApiKeyVerifierService = class {
13404
13674
  static {
13405
- __name(this, "PlatformRolesGuard");
13675
+ __name(this, "ApiKeyVerifierService");
13406
13676
  }
13407
- reflector;
13677
+ repository;
13678
+ clock;
13408
13679
  options;
13409
- constructor(reflector, options) {
13410
- this.reflector = reflector;
13680
+ lastUsed;
13681
+ constructor(repository, clock, options, lastUsed) {
13682
+ this.repository = repository;
13683
+ this.clock = clock;
13411
13684
  this.options = options;
13685
+ this.lastUsed = lastUsed;
13412
13686
  }
13413
- canActivate(context) {
13414
- const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
13415
- context.getHandler(),
13416
- context.getClass()
13417
- ]);
13418
- if (!requiredRoles || requiredRoles.length === 0) return true;
13419
- const request = context.switchToHttp().getRequest();
13420
- const user = request.user;
13421
- if (!user || user.type !== "platform") {
13422
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13423
- }
13424
- const userRole = user.role;
13425
- const hierarchy = this.options.roles.platformHierarchy;
13426
- if (!hierarchy) {
13427
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13428
- }
13429
- const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
13430
- if (!allowed) {
13431
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13687
+ /**
13688
+ * Verifies the value of the key header.
13689
+ *
13690
+ * @param header - The header value as the framework delivered it.
13691
+ * @returns The verdict. A store fault propagates: the caller fails closed.
13692
+ */
13693
+ async verify(header) {
13694
+ const parsed = parseApiKey(header, this.options.apiKeys.prefix);
13695
+ const keyId = parsed?.keyId ?? API_KEY_DUMMY_KEY_ID;
13696
+ const secret = parsed?.secret ?? API_KEY_DUMMY_SECRET;
13697
+ const row = await this.repository.findById(keyId);
13698
+ const computed = apiKeyDigest(secret, this.options.apiKeys.pepper);
13699
+ const equal = digestsMatch(computed, row?.digest ?? API_KEY_DUMMY_DIGEST);
13700
+ const now = this.clock.now();
13701
+ const reason = this.rejection(header, parsed !== null, row, equal, now.getTime());
13702
+ if (reason !== null) {
13703
+ return {
13704
+ ok: false,
13705
+ reason,
13706
+ key: parsed === null ? null : row
13707
+ };
13432
13708
  }
13433
- return true;
13709
+ const key = row;
13710
+ this.lastUsed.record(key.id, now);
13711
+ return {
13712
+ ok: true,
13713
+ key
13714
+ };
13715
+ }
13716
+ /**
13717
+ * The single decision, evaluated after every step above has run.
13718
+ *
13719
+ * A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
13720
+ * comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
13721
+ * compares false against everything) reads as lapsed rather than as valid.
13722
+ */
13723
+ rejection(header, parsed, row, equal, nowMs) {
13724
+ if (!parsed) return header === void 0 ? "missing" : "malformed";
13725
+ if (row === null) return "unknown";
13726
+ if (!equal) return "wrong_secret";
13727
+ if (row.revokedAt !== null) return "revoked";
13728
+ if (row.expiresAt !== null && !(row.expiresAt.getTime() > nowMs)) return "expired";
13729
+ return null;
13434
13730
  }
13435
13731
  };
13436
- PlatformRolesGuard = _ts_decorate52([
13732
+ ApiKeyVerifierService = _ts_decorate52([
13437
13733
  Injectable(),
13438
- _ts_param31(0, Inject(Reflector)),
13439
- _ts_param31(1, Inject(BYMAX_AUTH_OPTIONS)),
13734
+ _ts_param31(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13735
+ _ts_param31(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
13736
+ _ts_param31(2, Inject(BYMAX_AUTH_OPTIONS)),
13737
+ _ts_param31(3, Inject(ApiKeyLastUsedService)),
13440
13738
  _ts_metadata51("design:type", Function),
13441
13739
  _ts_metadata51("design:paramtypes", [
13442
- typeof Reflector === "undefined" ? Object : Reflector,
13443
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13740
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13741
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
13742
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13743
+ typeof ApiKeyLastUsedService === "undefined" ? Object : ApiKeyLastUsedService
13444
13744
  ])
13445
- ], PlatformRolesGuard);
13446
- var ROLES_KEY = "roles";
13447
- var Roles = /* @__PURE__ */ __name((...roles) => SetMetadata(ROLES_KEY, roles), "Roles");
13745
+ ], ApiKeyVerifierService);
13448
13746
 
13449
- // src/server/guards/roles.guard.ts
13747
+ // src/server/guards/api-key.guard.ts
13450
13748
  function _ts_decorate53(decorators, target, key, desc) {
13451
13749
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13452
13750
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13473,45 +13771,165 @@ function _ts_param32(paramIndex, decorator) {
13473
13771
  };
13474
13772
  }
13475
13773
  __name(_ts_param32, "_ts_param");
13476
- var RolesGuard = class {
13774
+ var ApiKeyGuard = class _ApiKeyGuard {
13477
13775
  static {
13478
- __name(this, "RolesGuard");
13776
+ __name(this, "ApiKeyGuard");
13479
13777
  }
13480
13778
  reflector;
13779
+ verifier;
13481
13780
  options;
13482
- constructor(reflector, options) {
13781
+ hooks;
13782
+ logger = new Logger(_ApiKeyGuard.name);
13783
+ constructor(reflector, verifier, options, hooks) {
13483
13784
  this.reflector = reflector;
13785
+ this.verifier = verifier;
13484
13786
  this.options = options;
13787
+ this.hooks = hooks;
13485
13788
  }
13486
- canActivate(context) {
13487
- const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
13789
+ async canActivate(context) {
13790
+ const request = context.switchToHttp().getRequest();
13791
+ const required = this.declaredScopes(context);
13792
+ const base = {
13793
+ method: request.method,
13794
+ route: routePattern(request),
13795
+ requiredScopes: required ?? []
13796
+ };
13797
+ if (required === null) {
13798
+ this.logger.error(`api-key: ${logSafe(request.method)} ${logSafe(base.route)} is guarded but declares no scopes; refused`);
13799
+ await this.audit(request, {
13800
+ ...base,
13801
+ outcome: "denied",
13802
+ reason: "route_undeclared"
13803
+ });
13804
+ throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN);
13805
+ }
13806
+ let verdict;
13807
+ try {
13808
+ verdict = await this.verifier.verify(request.headers[this.options.apiKeys.header]);
13809
+ } catch (err) {
13810
+ this.logger.error(`api-key: key store unavailable cause=${describeChannelStatus(err)}`);
13811
+ await this.audit(request, {
13812
+ ...base,
13813
+ outcome: "denied",
13814
+ reason: "store_error"
13815
+ });
13816
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13817
+ }
13818
+ if (!verdict.ok) {
13819
+ await this.audit(request, {
13820
+ ...base,
13821
+ outcome: "denied",
13822
+ reason: verdict.reason
13823
+ }, verdict.key);
13824
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_INVALID);
13825
+ }
13826
+ const { key } = verdict;
13827
+ if (!required.every((scope) => key.scopes.includes(scope))) {
13828
+ await this.audit(request, {
13829
+ ...base,
13830
+ outcome: "denied",
13831
+ reason: "scope_insufficient"
13832
+ }, key);
13833
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_SCOPE_INSUFFICIENT);
13834
+ }
13835
+ const delivered = await this.audit(request, {
13836
+ ...base,
13837
+ outcome: "allowed",
13838
+ reason: null
13839
+ }, key);
13840
+ if (!delivered) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13841
+ request.apiKey = Object.freeze({
13842
+ id: key.id,
13843
+ label: key.label,
13844
+ scopes: Object.freeze([
13845
+ ...key.scopes
13846
+ ])
13847
+ });
13848
+ return true;
13849
+ }
13850
+ /**
13851
+ * The route's scope declaration: handler over class, empty or malformed counting as none.
13852
+ *
13853
+ * @returns The scopes, or `null` when the route declares none.
13854
+ */
13855
+ declaredScopes(context) {
13856
+ const declared = this.reflector.getAllAndOverride(API_KEY_SCOPES_KEY, [
13488
13857
  context.getHandler(),
13489
13858
  context.getClass()
13490
13859
  ]);
13491
- if (!requiredRoles || requiredRoles.length === 0) return true;
13492
- const request = context.switchToHttp().getRequest();
13493
- const userRole = request.user?.role;
13494
- if (!userRole) {
13495
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13860
+ if (!Array.isArray(declared) || declared.length === 0 || !declared.every((scope) => typeof scope === "string")) {
13861
+ return null;
13496
13862
  }
13497
- const hierarchy = this.options.roles.hierarchy;
13498
- const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
13499
- if (!allowed) {
13500
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13863
+ return declared;
13864
+ }
13865
+ /**
13866
+ * Emits the audit event.
13867
+ *
13868
+ * @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
13869
+ * is fired without being awaited and the result is always `true`.
13870
+ */
13871
+ async audit(request, partial, key = null) {
13872
+ const hook = this.hooks?.onApiKeyRequest;
13873
+ if (hook === void 0) {
13874
+ if (this.options.apiKeys.auditMode !== "required") return true;
13875
+ this.logger.error("api-key: auditMode is required but no onApiKeyRequest hook is implemented; refusing");
13876
+ return false;
13877
+ }
13878
+ const event = {
13879
+ ...partial,
13880
+ keyId: key?.id ?? null,
13881
+ label: key?.label ?? null,
13882
+ ip: request.ip ?? ""
13883
+ };
13884
+ const context = this.hookContext(request);
13885
+ const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
13886
+ if (this.options.apiKeys.auditMode === "required") {
13887
+ try {
13888
+ await run();
13889
+ return true;
13890
+ } catch (err) {
13891
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13892
+ return false;
13893
+ }
13894
+ }
13895
+ try {
13896
+ void Promise.resolve(run()).catch((err) => {
13897
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13898
+ });
13899
+ } catch (err) {
13900
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13501
13901
  }
13502
13902
  return true;
13503
13903
  }
13904
+ hookContext(request) {
13905
+ const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13906
+ return {
13907
+ ip: request.ip ?? "",
13908
+ userAgent: request.headers["user-agent"] ?? "",
13909
+ sanitizedHeaders: sanitizeHeaders(headers)
13910
+ };
13911
+ }
13504
13912
  };
13505
- RolesGuard = _ts_decorate53([
13913
+ ApiKeyGuard = _ts_decorate53([
13506
13914
  Injectable(),
13507
13915
  _ts_param32(0, Inject(Reflector)),
13508
- _ts_param32(1, Inject(BYMAX_AUTH_OPTIONS)),
13916
+ _ts_param32(1, Inject(ApiKeyVerifierService)),
13917
+ _ts_param32(2, Inject(BYMAX_AUTH_OPTIONS)),
13918
+ _ts_param32(3, Inject(BYMAX_AUTH_HOOKS)),
13919
+ _ts_param32(3, Optional()),
13509
13920
  _ts_metadata52("design:type", Function),
13510
13921
  _ts_metadata52("design:paramtypes", [
13511
13922
  typeof Reflector === "undefined" ? Object : Reflector,
13512
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13923
+ typeof ApiKeyVerifierService === "undefined" ? Object : ApiKeyVerifierService,
13924
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13925
+ Object
13513
13926
  ])
13514
- ], RolesGuard);
13927
+ ], ApiKeyGuard);
13928
+ function routePattern(request) {
13929
+ const path = request.route?.path;
13930
+ return typeof path === "string" ? path : "";
13931
+ }
13932
+ __name(routePattern, "routePattern");
13515
13933
  function _ts_decorate54(decorators, target, key, desc) {
13516
13934
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13517
13935
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13526,49 +13944,257 @@ function _ts_decorate54(decorators, target, key, desc) {
13526
13944
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13527
13945
  }
13528
13946
  __name(_ts_decorate54, "_ts_decorate");
13529
- var NoOpAuthHooks = class {
13947
+ function _ts_metadata53(metadataKey, metadataValue) {
13948
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13949
+ return Reflect.metadata(metadataKey, metadataValue);
13950
+ }
13951
+ }
13952
+ __name(_ts_metadata53, "_ts_metadata");
13953
+ function _ts_param33(paramIndex, decorator) {
13954
+ return function(target, key) {
13955
+ decorator(target, key, paramIndex);
13956
+ };
13957
+ }
13958
+ __name(_ts_param33, "_ts_param");
13959
+ var MfaRequiredGuard = class {
13530
13960
  static {
13531
- __name(this, "NoOpAuthHooks");
13961
+ __name(this, "MfaRequiredGuard");
13532
13962
  }
13533
- /**
13534
- * Permits all registration attempts unconditionally.
13535
- *
13536
- * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
13537
- * @param _context - Hook execution context carrying request metadata.
13538
- * @returns `{ allowed: true }` — never blocks registration.
13539
- */
13540
- beforeRegister(_data, _context) {
13541
- return {
13542
- allowed: true
13543
- };
13963
+ reflector;
13964
+ constructor(reflector) {
13965
+ this.reflector = reflector;
13544
13966
  }
13545
- /**
13546
- * Resolves OAuth login by linking to an existing account, creating a new one,
13547
- * or rejecting on email mismatch.
13548
- *
13549
- * @param profile - Normalized OAuth profile from the provider.
13550
- * @param existingUser - Existing user found by the profile email, or `null`.
13551
- * @param _context - Hook execution context carrying request metadata.
13552
- * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
13553
- */
13554
- onOAuthLogin(profile, existingUser, _context) {
13555
- if (existingUser === null) {
13556
- return {
13557
- action: "create"
13558
- };
13967
+ canActivate(context) {
13968
+ const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13969
+ context.getHandler(),
13970
+ context.getClass()
13971
+ ]);
13972
+ if (skipMfa) return true;
13973
+ const request = context.switchToHttp().getRequest();
13974
+ const user = request.user;
13975
+ if (!user) return true;
13976
+ if (typeof user.mfaEnabled !== "boolean") {
13977
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13559
13978
  }
13560
- if (existingUser.email === profile.email) {
13561
- return {
13562
- action: "link"
13563
- };
13979
+ if (user.mfaEnabled === true && user.mfaVerified !== true) {
13980
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13564
13981
  }
13565
- return {
13566
- action: "reject",
13567
- reason: "Email mismatch"
13568
- };
13982
+ return true;
13983
+ }
13984
+ };
13985
+ MfaRequiredGuard = _ts_decorate54([
13986
+ Injectable(),
13987
+ _ts_param33(0, Inject(Reflector)),
13988
+ _ts_metadata53("design:type", Function),
13989
+ _ts_metadata53("design:paramtypes", [
13990
+ typeof Reflector === "undefined" ? Object : Reflector
13991
+ ])
13992
+ ], MfaRequiredGuard);
13993
+ var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13994
+ var PlatformRoles = /* @__PURE__ */ __name((...roles) => SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13995
+
13996
+ // src/server/guards/platform-roles.guard.ts
13997
+ function _ts_decorate55(decorators, target, key, desc) {
13998
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13999
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14000
+ r = Reflect.decorate(decorators, target, key, desc);
14001
+ } else {
14002
+ for (var i = decorators.length - 1; i >= 0; i--) {
14003
+ if (d = decorators[i]) {
14004
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14005
+ }
14006
+ }
14007
+ }
14008
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14009
+ }
14010
+ __name(_ts_decorate55, "_ts_decorate");
14011
+ function _ts_metadata54(metadataKey, metadataValue) {
14012
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14013
+ return Reflect.metadata(metadataKey, metadataValue);
14014
+ }
14015
+ }
14016
+ __name(_ts_metadata54, "_ts_metadata");
14017
+ function _ts_param34(paramIndex, decorator) {
14018
+ return function(target, key) {
14019
+ decorator(target, key, paramIndex);
14020
+ };
14021
+ }
14022
+ __name(_ts_param34, "_ts_param");
14023
+ var PlatformRolesGuard = class {
14024
+ static {
14025
+ __name(this, "PlatformRolesGuard");
14026
+ }
14027
+ reflector;
14028
+ options;
14029
+ constructor(reflector, options) {
14030
+ this.reflector = reflector;
14031
+ this.options = options;
14032
+ }
14033
+ canActivate(context) {
14034
+ const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
14035
+ context.getHandler(),
14036
+ context.getClass()
14037
+ ]);
14038
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14039
+ const request = context.switchToHttp().getRequest();
14040
+ const user = request.user;
14041
+ if (!user || user.type !== "platform") {
14042
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14043
+ }
14044
+ const userRole = user.role;
14045
+ const hierarchy = this.options.roles.platformHierarchy;
14046
+ if (!hierarchy) {
14047
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14048
+ }
14049
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14050
+ if (!allowed) {
14051
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14052
+ }
14053
+ return true;
14054
+ }
14055
+ };
14056
+ PlatformRolesGuard = _ts_decorate55([
14057
+ Injectable(),
14058
+ _ts_param34(0, Inject(Reflector)),
14059
+ _ts_param34(1, Inject(BYMAX_AUTH_OPTIONS)),
14060
+ _ts_metadata54("design:type", Function),
14061
+ _ts_metadata54("design:paramtypes", [
14062
+ typeof Reflector === "undefined" ? Object : Reflector,
14063
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14064
+ ])
14065
+ ], PlatformRolesGuard);
14066
+ var ROLES_KEY = "roles";
14067
+ var Roles = /* @__PURE__ */ __name((...roles) => SetMetadata(ROLES_KEY, roles), "Roles");
14068
+
14069
+ // src/server/guards/roles.guard.ts
14070
+ function _ts_decorate56(decorators, target, key, desc) {
14071
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14072
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14073
+ r = Reflect.decorate(decorators, target, key, desc);
14074
+ } else {
14075
+ for (var i = decorators.length - 1; i >= 0; i--) {
14076
+ if (d = decorators[i]) {
14077
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14078
+ }
14079
+ }
14080
+ }
14081
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14082
+ }
14083
+ __name(_ts_decorate56, "_ts_decorate");
14084
+ function _ts_metadata55(metadataKey, metadataValue) {
14085
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14086
+ return Reflect.metadata(metadataKey, metadataValue);
14087
+ }
14088
+ }
14089
+ __name(_ts_metadata55, "_ts_metadata");
14090
+ function _ts_param35(paramIndex, decorator) {
14091
+ return function(target, key) {
14092
+ decorator(target, key, paramIndex);
14093
+ };
14094
+ }
14095
+ __name(_ts_param35, "_ts_param");
14096
+ var RolesGuard = class {
14097
+ static {
14098
+ __name(this, "RolesGuard");
14099
+ }
14100
+ reflector;
14101
+ options;
14102
+ constructor(reflector, options) {
14103
+ this.reflector = reflector;
14104
+ this.options = options;
14105
+ }
14106
+ canActivate(context) {
14107
+ const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
14108
+ context.getHandler(),
14109
+ context.getClass()
14110
+ ]);
14111
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14112
+ const request = context.switchToHttp().getRequest();
14113
+ const userRole = request.user?.role;
14114
+ if (!userRole) {
14115
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14116
+ }
14117
+ const hierarchy = this.options.roles.hierarchy;
14118
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14119
+ if (!allowed) {
14120
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14121
+ }
14122
+ return true;
14123
+ }
14124
+ };
14125
+ RolesGuard = _ts_decorate56([
14126
+ Injectable(),
14127
+ _ts_param35(0, Inject(Reflector)),
14128
+ _ts_param35(1, Inject(BYMAX_AUTH_OPTIONS)),
14129
+ _ts_metadata55("design:type", Function),
14130
+ _ts_metadata55("design:paramtypes", [
14131
+ typeof Reflector === "undefined" ? Object : Reflector,
14132
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14133
+ ])
14134
+ ], RolesGuard);
14135
+ function _ts_decorate57(decorators, target, key, desc) {
14136
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14137
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14138
+ r = Reflect.decorate(decorators, target, key, desc);
14139
+ } else {
14140
+ for (var i = decorators.length - 1; i >= 0; i--) {
14141
+ if (d = decorators[i]) {
14142
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14143
+ }
14144
+ }
14145
+ }
14146
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14147
+ }
14148
+ __name(_ts_decorate57, "_ts_decorate");
14149
+ var NoOpAuthHooks = class {
14150
+ static {
14151
+ __name(this, "NoOpAuthHooks");
14152
+ }
14153
+ /**
14154
+ * Permits all registration attempts unconditionally.
14155
+ *
14156
+ * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
14157
+ * @param _context - Hook execution context carrying request metadata.
14158
+ * @returns `{ allowed: true }` — never blocks registration.
14159
+ */
14160
+ beforeRegister(_data, _context) {
14161
+ return {
14162
+ allowed: true
14163
+ };
14164
+ }
14165
+ /**
14166
+ * Resolves OAuth login: creates an account for an unlinked identity, keeps an existing link
14167
+ * when the address still matches and the provider vouches for it, and rejects otherwise.
14168
+ *
14169
+ * @param profile - Normalized OAuth profile from the provider.
14170
+ * @param existingUser - The user already linked to this provider identity, or `null`.
14171
+ * @param _context - Hook execution context carrying request metadata.
14172
+ * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
14173
+ */
14174
+ onOAuthLogin(profile, existingUser, _context) {
14175
+ if (existingUser === null) {
14176
+ return {
14177
+ action: "create"
14178
+ };
14179
+ }
14180
+ if (existingUser.email !== profile.email) {
14181
+ return {
14182
+ action: "reject",
14183
+ reason: "Email mismatch"
14184
+ };
14185
+ }
14186
+ if (profile.emailVerified !== true) {
14187
+ return {
14188
+ action: "reject",
14189
+ reason: "Email not verified"
14190
+ };
14191
+ }
14192
+ return {
14193
+ action: "link"
14194
+ };
13569
14195
  }
13570
14196
  };
13571
- NoOpAuthHooks = _ts_decorate54([
14197
+ NoOpAuthHooks = _ts_decorate57([
13572
14198
  Injectable()
13573
14199
  ], NoOpAuthHooks);
13574
14200
 
@@ -13581,7 +14207,7 @@ var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
13581
14207
  var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
13582
14208
 
13583
14209
  // src/server/oauth/oauth.service.ts
13584
- function _ts_decorate55(decorators, target, key, desc) {
14210
+ function _ts_decorate58(decorators, target, key, desc) {
13585
14211
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13586
14212
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13587
14213
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13594,19 +14220,19 @@ function _ts_decorate55(decorators, target, key, desc) {
13594
14220
  }
13595
14221
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13596
14222
  }
13597
- __name(_ts_decorate55, "_ts_decorate");
13598
- function _ts_metadata53(metadataKey, metadataValue) {
14223
+ __name(_ts_decorate58, "_ts_decorate");
14224
+ function _ts_metadata56(metadataKey, metadataValue) {
13599
14225
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13600
14226
  return Reflect.metadata(metadataKey, metadataValue);
13601
14227
  }
13602
14228
  }
13603
- __name(_ts_metadata53, "_ts_metadata");
13604
- function _ts_param33(paramIndex, decorator) {
14229
+ __name(_ts_metadata56, "_ts_metadata");
14230
+ function _ts_param36(paramIndex, decorator) {
13605
14231
  return function(target, key) {
13606
14232
  decorator(target, key, paramIndex);
13607
14233
  };
13608
14234
  }
13609
- __name(_ts_param33, "_ts_param");
14235
+ __name(_ts_param36, "_ts_param");
13610
14236
  var OAUTH_STATE_TTL_SECONDS = 600;
13611
14237
  function isStoredOAuthState(value) {
13612
14238
  if (typeof value !== "object" || value === null) return false;
@@ -13861,6 +14487,17 @@ var OAuthService = class _OAuthService {
13861
14487
  });
13862
14488
  }
13863
14489
  this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
14490
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
14491
+ id: safeUser.id,
14492
+ tenantId: safeUser.tenantId
14493
+ }), "oauth: updateLastLogin failed");
14494
+ if (this.hooks?.afterLogin) {
14495
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
14496
+ runDetached(this.logger, () => afterLogin(safeUser, {
14497
+ ...hookContext,
14498
+ userId: safeUser.id
14499
+ }), "oauth: afterLogin hook threw");
14500
+ }
13864
14501
  return result;
13865
14502
  }
13866
14503
  // ---------------------------------------------------------------------------
@@ -13889,18 +14526,18 @@ var OAuthService = class _OAuthService {
13889
14526
  return plugin;
13890
14527
  }
13891
14528
  };
13892
- OAuthService = _ts_decorate55([
14529
+ OAuthService = _ts_decorate58([
13893
14530
  Injectable(),
13894
- _ts_param33(0, Inject(OAUTH_PLUGINS)),
13895
- _ts_param33(1, Inject(BYMAX_AUTH_USER_REPOSITORY)),
13896
- _ts_param33(2, Inject(BYMAX_AUTH_HOOKS)),
13897
- _ts_param33(2, Optional()),
13898
- _ts_param33(3, Inject(AuthRedisService)),
13899
- _ts_param33(4, Inject(TokenManagerService)),
13900
- _ts_param33(5, Inject(SessionService)),
13901
- _ts_param33(6, Inject(BYMAX_AUTH_OPTIONS)),
13902
- _ts_metadata53("design:type", Function),
13903
- _ts_metadata53("design:paramtypes", [
14531
+ _ts_param36(0, Inject(OAUTH_PLUGINS)),
14532
+ _ts_param36(1, Inject(BYMAX_AUTH_USER_REPOSITORY)),
14533
+ _ts_param36(2, Inject(BYMAX_AUTH_HOOKS)),
14534
+ _ts_param36(2, Optional()),
14535
+ _ts_param36(3, Inject(AuthRedisService)),
14536
+ _ts_param36(4, Inject(TokenManagerService)),
14537
+ _ts_param36(5, Inject(SessionService)),
14538
+ _ts_param36(6, Inject(BYMAX_AUTH_OPTIONS)),
14539
+ _ts_metadata56("design:type", Function),
14540
+ _ts_metadata56("design:paramtypes", [
13904
14541
  Array,
13905
14542
  typeof IUserRepository === "undefined" ? Object : IUserRepository,
13906
14543
  Object,
@@ -13910,7 +14547,7 @@ OAuthService = _ts_decorate55([
13910
14547
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13911
14548
  ])
13912
14549
  ], OAuthService);
13913
- function _ts_decorate56(decorators, target, key, desc) {
14550
+ function _ts_decorate59(decorators, target, key, desc) {
13914
14551
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13915
14552
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13916
14553
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13923,13 +14560,13 @@ function _ts_decorate56(decorators, target, key, desc) {
13923
14560
  }
13924
14561
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13925
14562
  }
13926
- __name(_ts_decorate56, "_ts_decorate");
13927
- function _ts_metadata54(metadataKey, metadataValue) {
14563
+ __name(_ts_decorate59, "_ts_decorate");
14564
+ function _ts_metadata57(metadataKey, metadataValue) {
13928
14565
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13929
14566
  return Reflect.metadata(metadataKey, metadataValue);
13930
14567
  }
13931
14568
  }
13932
- __name(_ts_metadata54, "_ts_metadata");
14569
+ __name(_ts_metadata57, "_ts_metadata");
13933
14570
  var OAuthCallbackQueryDto = class {
13934
14571
  static {
13935
14572
  __name(this, "OAuthCallbackQueryDto");
@@ -14028,69 +14665,69 @@ var OAuthCallbackQueryDto = class {
14028
14665
  */
14029
14666
  hd;
14030
14667
  };
14031
- _ts_decorate56([
14668
+ _ts_decorate59([
14032
14669
  ValidateIf((query) => query.error === void 0 || query.error === null),
14033
14670
  IsOptional(),
14034
14671
  IsString(),
14035
14672
  IsNotEmpty(),
14036
14673
  MaxLength(2048),
14037
- _ts_metadata54("design:type", String)
14674
+ _ts_metadata57("design:type", String)
14038
14675
  ], OAuthCallbackQueryDto.prototype, "code", void 0);
14039
- _ts_decorate56([
14676
+ _ts_decorate59([
14040
14677
  IsOptional(),
14041
14678
  IsString(),
14042
14679
  MaxLength(128),
14043
- _ts_metadata54("design:type", String)
14680
+ _ts_metadata57("design:type", String)
14044
14681
  ], OAuthCallbackQueryDto.prototype, "error", void 0);
14045
- _ts_decorate56([
14682
+ _ts_decorate59([
14046
14683
  IsOptional(),
14047
14684
  IsString(),
14048
14685
  MaxLength(512),
14049
- _ts_metadata54("design:type", String)
14686
+ _ts_metadata57("design:type", String)
14050
14687
  ], OAuthCallbackQueryDto.prototype, "error_description", void 0);
14051
- _ts_decorate56([
14688
+ _ts_decorate59([
14052
14689
  IsOptional(),
14053
14690
  IsString(),
14054
14691
  MaxLength(512),
14055
- _ts_metadata54("design:type", String)
14692
+ _ts_metadata57("design:type", String)
14056
14693
  ], OAuthCallbackQueryDto.prototype, "error_uri", void 0);
14057
- _ts_decorate56([
14694
+ _ts_decorate59([
14058
14695
  IsString(),
14059
14696
  IsNotEmpty(),
14060
14697
  MaxLength(128),
14061
- _ts_metadata54("design:type", String)
14698
+ _ts_metadata57("design:type", String)
14062
14699
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
14063
- _ts_decorate56([
14700
+ _ts_decorate59([
14064
14701
  IsOptional(),
14065
14702
  IsString(),
14066
14703
  MaxLength(512),
14067
- _ts_metadata54("design:type", String)
14704
+ _ts_metadata57("design:type", String)
14068
14705
  ], OAuthCallbackQueryDto.prototype, "iss", void 0);
14069
- _ts_decorate56([
14706
+ _ts_decorate59([
14070
14707
  IsOptional(),
14071
14708
  IsString(),
14072
14709
  MaxLength(2048),
14073
- _ts_metadata54("design:type", String)
14710
+ _ts_metadata57("design:type", String)
14074
14711
  ], OAuthCallbackQueryDto.prototype, "scope", void 0);
14075
- _ts_decorate56([
14712
+ _ts_decorate59([
14076
14713
  IsOptional(),
14077
14714
  IsString(),
14078
14715
  MaxLength(16),
14079
- _ts_metadata54("design:type", String)
14716
+ _ts_metadata57("design:type", String)
14080
14717
  ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
14081
- _ts_decorate56([
14718
+ _ts_decorate59([
14082
14719
  IsOptional(),
14083
14720
  IsString(),
14084
14721
  MaxLength(64),
14085
- _ts_metadata54("design:type", String)
14722
+ _ts_metadata57("design:type", String)
14086
14723
  ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
14087
- _ts_decorate56([
14724
+ _ts_decorate59([
14088
14725
  IsOptional(),
14089
14726
  IsString(),
14090
14727
  MaxLength(253),
14091
- _ts_metadata54("design:type", String)
14728
+ _ts_metadata57("design:type", String)
14092
14729
  ], OAuthCallbackQueryDto.prototype, "hd", void 0);
14093
- function _ts_decorate57(decorators, target, key, desc) {
14730
+ function _ts_decorate60(decorators, target, key, desc) {
14094
14731
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14095
14732
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14096
14733
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14103,13 +14740,13 @@ function _ts_decorate57(decorators, target, key, desc) {
14103
14740
  }
14104
14741
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14105
14742
  }
14106
- __name(_ts_decorate57, "_ts_decorate");
14107
- function _ts_metadata55(metadataKey, metadataValue) {
14743
+ __name(_ts_decorate60, "_ts_decorate");
14744
+ function _ts_metadata58(metadataKey, metadataValue) {
14108
14745
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14109
14746
  return Reflect.metadata(metadataKey, metadataValue);
14110
14747
  }
14111
14748
  }
14112
- __name(_ts_metadata55, "_ts_metadata");
14749
+ __name(_ts_metadata58, "_ts_metadata");
14113
14750
  var OAuthInitiateQueryDto = class {
14114
14751
  static {
14115
14752
  __name(this, "OAuthInitiateQueryDto");
@@ -14126,7 +14763,7 @@ var OAuthInitiateQueryDto = class {
14126
14763
  */
14127
14764
  tenantId;
14128
14765
  };
14129
- _ts_decorate57([
14766
+ _ts_decorate60([
14130
14767
  IsOptional(),
14131
14768
  IsString(),
14132
14769
  IsNotEmpty(),
@@ -14134,11 +14771,11 @@ _ts_decorate57([
14134
14771
  Matches(NO_CONTROL_CHARACTERS, {
14135
14772
  message: "tenantId must not contain control characters"
14136
14773
  }),
14137
- _ts_metadata55("design:type", String)
14774
+ _ts_metadata58("design:type", String)
14138
14775
  ], OAuthInitiateQueryDto.prototype, "tenantId", void 0);
14139
14776
 
14140
14777
  // src/server/oauth/oauth.controller.ts
14141
- function _ts_decorate58(decorators, target, key, desc) {
14778
+ function _ts_decorate61(decorators, target, key, desc) {
14142
14779
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14143
14780
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14144
14781
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14151,19 +14788,19 @@ function _ts_decorate58(decorators, target, key, desc) {
14151
14788
  }
14152
14789
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14153
14790
  }
14154
- __name(_ts_decorate58, "_ts_decorate");
14155
- function _ts_metadata56(metadataKey, metadataValue) {
14791
+ __name(_ts_decorate61, "_ts_decorate");
14792
+ function _ts_metadata59(metadataKey, metadataValue) {
14156
14793
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14157
14794
  return Reflect.metadata(metadataKey, metadataValue);
14158
14795
  }
14159
14796
  }
14160
- __name(_ts_metadata56, "_ts_metadata");
14161
- function _ts_param34(paramIndex, decorator) {
14797
+ __name(_ts_metadata59, "_ts_metadata");
14798
+ function _ts_param37(paramIndex, decorator) {
14162
14799
  return function(target, key) {
14163
14800
  decorator(target, key, paramIndex);
14164
14801
  };
14165
14802
  }
14166
- __name(_ts_param34, "_ts_param");
14803
+ __name(_ts_param37, "_ts_param");
14167
14804
  function isOAuthMfaChallenge(result) {
14168
14805
  return "mfaRequired" in result && result.mfaRequired === true;
14169
14806
  }
@@ -14381,46 +15018,46 @@ var OAuthController = class _OAuthController {
14381
15018
  });
14382
15019
  }
14383
15020
  };
14384
- _ts_decorate58([
15021
+ _ts_decorate61([
14385
15022
  Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14386
15023
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14387
15024
  Get(":provider"),
14388
- _ts_param34(0, Param("provider")),
14389
- _ts_param34(1, Query()),
14390
- _ts_param34(2, Req()),
14391
- _ts_param34(3, Res({
15025
+ _ts_param37(0, Param("provider")),
15026
+ _ts_param37(1, Query()),
15027
+ _ts_param37(2, Req()),
15028
+ _ts_param37(3, Res({
14392
15029
  passthrough: true
14393
15030
  })),
14394
- _ts_metadata56("design:type", Function),
14395
- _ts_metadata56("design:paramtypes", [
15031
+ _ts_metadata59("design:type", Function),
15032
+ _ts_metadata59("design:paramtypes", [
14396
15033
  String,
14397
15034
  typeof OAuthInitiateQueryDto === "undefined" ? Object : OAuthInitiateQueryDto,
14398
15035
  typeof Request === "undefined" ? Object : Request,
14399
15036
  typeof Response === "undefined" ? Object : Response
14400
15037
  ]),
14401
- _ts_metadata56("design:returntype", Promise)
15038
+ _ts_metadata59("design:returntype", Promise)
14402
15039
  ], OAuthController.prototype, "initiate", null);
14403
- _ts_decorate58([
15040
+ _ts_decorate61([
14404
15041
  Throttle(AUTH_THROTTLE_CONFIGS.oauthCallback),
14405
15042
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthCallback),
14406
15043
  HttpCode(HttpStatus.OK),
14407
15044
  Get(":provider/callback"),
14408
- _ts_param34(0, Param("provider")),
14409
- _ts_param34(1, Query()),
14410
- _ts_param34(2, Req()),
14411
- _ts_param34(3, Res({
15045
+ _ts_param37(0, Param("provider")),
15046
+ _ts_param37(1, Query()),
15047
+ _ts_param37(2, Req()),
15048
+ _ts_param37(3, Res({
14412
15049
  passthrough: true
14413
15050
  })),
14414
- _ts_metadata56("design:type", Function),
14415
- _ts_metadata56("design:paramtypes", [
15051
+ _ts_metadata59("design:type", Function),
15052
+ _ts_metadata59("design:paramtypes", [
14416
15053
  String,
14417
15054
  typeof OAuthCallbackQueryDto === "undefined" ? Object : OAuthCallbackQueryDto,
14418
15055
  typeof Request === "undefined" ? Object : Request,
14419
15056
  typeof Response === "undefined" ? Object : Response
14420
15057
  ]),
14421
- _ts_metadata56("design:returntype", Promise)
15058
+ _ts_metadata59("design:returntype", Promise)
14422
15059
  ], OAuthController.prototype, "callback", null);
14423
- OAuthController = _ts_decorate58([
15060
+ OAuthController = _ts_decorate61([
14424
15061
  Public(),
14425
15062
  SkipMfa(),
14426
15063
  UseInterceptors(NoStoreInterceptor),
@@ -14429,11 +15066,11 @@ OAuthController = _ts_decorate58([
14429
15066
  UsePipes(createAuthValidationPipe({
14430
15067
  forbidUnknownValues: true
14431
15068
  })),
14432
- _ts_param34(0, Inject(OAuthService)),
14433
- _ts_param34(1, Inject(TokenDeliveryService)),
14434
- _ts_param34(2, Inject(BYMAX_AUTH_OPTIONS)),
14435
- _ts_metadata56("design:type", Function),
14436
- _ts_metadata56("design:paramtypes", [
15069
+ _ts_param37(0, Inject(OAuthService)),
15070
+ _ts_param37(1, Inject(TokenDeliveryService)),
15071
+ _ts_param37(2, Inject(BYMAX_AUTH_OPTIONS)),
15072
+ _ts_metadata59("design:type", Function),
15073
+ _ts_metadata59("design:paramtypes", [
14437
15074
  typeof OAuthService === "undefined" ? Object : OAuthService,
14438
15075
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
14439
15076
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -14572,7 +15209,7 @@ var GoogleOAuthPlugin = class {
14572
15209
  };
14573
15210
 
14574
15211
  // src/server/oauth/oauth.module.ts
14575
- function _ts_decorate59(decorators, target, key, desc) {
15212
+ function _ts_decorate62(decorators, target, key, desc) {
14576
15213
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14577
15214
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14578
15215
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14585,7 +15222,7 @@ function _ts_decorate59(decorators, target, key, desc) {
14585
15222
  }
14586
15223
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14587
15224
  }
14588
- __name(_ts_decorate59, "_ts_decorate");
15225
+ __name(_ts_decorate62, "_ts_decorate");
14589
15226
  function buildOAuthPlugins(options) {
14590
15227
  const plugins = [];
14591
15228
  if (options.oauth?.google) {
@@ -14655,7 +15292,7 @@ var OAuthModule = class _OAuthModule {
14655
15292
  };
14656
15293
  }
14657
15294
  };
14658
- OAuthModule = _ts_decorate59([
15295
+ OAuthModule = _ts_decorate62([
14659
15296
  Module({})
14660
15297
  ], OAuthModule);
14661
15298
 
@@ -15549,7 +16186,7 @@ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
15549
16186
  __name(schemesFor, "schemesFor");
15550
16187
 
15551
16188
  // src/server/openapi/auth-openapi.contributor.ts
15552
- function _ts_decorate60(decorators, target, key, desc) {
16189
+ function _ts_decorate63(decorators, target, key, desc) {
15553
16190
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15554
16191
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15555
16192
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15562,19 +16199,19 @@ function _ts_decorate60(decorators, target, key, desc) {
15562
16199
  }
15563
16200
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15564
16201
  }
15565
- __name(_ts_decorate60, "_ts_decorate");
15566
- function _ts_metadata57(metadataKey, metadataValue) {
16202
+ __name(_ts_decorate63, "_ts_decorate");
16203
+ function _ts_metadata60(metadataKey, metadataValue) {
15567
16204
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15568
16205
  return Reflect.metadata(metadataKey, metadataValue);
15569
16206
  }
15570
16207
  }
15571
- __name(_ts_metadata57, "_ts_metadata");
15572
- function _ts_param35(paramIndex, decorator) {
16208
+ __name(_ts_metadata60, "_ts_metadata");
16209
+ function _ts_param38(paramIndex, decorator) {
15573
16210
  return function(target, key) {
15574
16211
  decorator(target, key, paramIndex);
15575
16212
  };
15576
16213
  }
15577
- __name(_ts_param35, "_ts_param");
16214
+ __name(_ts_param38, "_ts_param");
15578
16215
  var AuthOpenApiContributor = class {
15579
16216
  static {
15580
16217
  __name(this, "AuthOpenApiContributor");
@@ -15594,18 +16231,18 @@ var AuthOpenApiContributor = class {
15594
16231
  return buildAuthOpenApiFragment(this.options, this.registered);
15595
16232
  }
15596
16233
  };
15597
- AuthOpenApiContributor = _ts_decorate60([
16234
+ AuthOpenApiContributor = _ts_decorate63([
15598
16235
  Injectable(),
15599
16236
  SetMetadata(OPENAPI_CONTRIBUTOR_METADATA, true),
15600
- _ts_param35(0, Inject(BYMAX_AUTH_OPTIONS)),
15601
- _ts_param35(1, Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
15602
- _ts_metadata57("design:type", Function),
15603
- _ts_metadata57("design:paramtypes", [
16237
+ _ts_param38(0, Inject(BYMAX_AUTH_OPTIONS)),
16238
+ _ts_param38(1, Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
16239
+ _ts_metadata60("design:type", Function),
16240
+ _ts_metadata60("design:paramtypes", [
15604
16241
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
15605
16242
  typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
15606
16243
  ])
15607
16244
  ], AuthOpenApiContributor);
15608
- function _ts_decorate61(decorators, target, key, desc) {
16245
+ function _ts_decorate64(decorators, target, key, desc) {
15609
16246
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15610
16247
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15611
16248
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15618,19 +16255,19 @@ function _ts_decorate61(decorators, target, key, desc) {
15618
16255
  }
15619
16256
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15620
16257
  }
15621
- __name(_ts_decorate61, "_ts_decorate");
15622
- function _ts_metadata58(metadataKey, metadataValue) {
16258
+ __name(_ts_decorate64, "_ts_decorate");
16259
+ function _ts_metadata61(metadataKey, metadataValue) {
15623
16260
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15624
16261
  return Reflect.metadata(metadataKey, metadataValue);
15625
16262
  }
15626
16263
  }
15627
- __name(_ts_metadata58, "_ts_metadata");
15628
- function _ts_param36(paramIndex, decorator) {
16264
+ __name(_ts_metadata61, "_ts_metadata");
16265
+ function _ts_param39(paramIndex, decorator) {
15629
16266
  return function(target, key) {
15630
16267
  decorator(target, key, paramIndex);
15631
16268
  };
15632
16269
  }
15633
- __name(_ts_param36, "_ts_param");
16270
+ __name(_ts_param39, "_ts_param");
15634
16271
  var COMMON_BASE_WORDS = [
15635
16272
  // The perennial top of every published list.
15636
16273
  "password",
@@ -15936,16 +16573,16 @@ var CommonPasswordChecker = class {
15936
16573
  return false;
15937
16574
  }
15938
16575
  };
15939
- CommonPasswordChecker = _ts_decorate61([
16576
+ CommonPasswordChecker = _ts_decorate64([
15940
16577
  Injectable(),
15941
- _ts_param36(0, Inject(BYMAX_AUTH_OPTIONS)),
15942
- _ts_param36(0, Optional()),
15943
- _ts_metadata58("design:type", Function),
15944
- _ts_metadata58("design:paramtypes", [
16578
+ _ts_param39(0, Inject(BYMAX_AUTH_OPTIONS)),
16579
+ _ts_param39(0, Optional()),
16580
+ _ts_metadata61("design:type", Function),
16581
+ _ts_metadata61("design:paramtypes", [
15945
16582
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
15946
16583
  ])
15947
16584
  ], CommonPasswordChecker);
15948
- function _ts_decorate62(decorators, target, key, desc) {
16585
+ function _ts_decorate65(decorators, target, key, desc) {
15949
16586
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15950
16587
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15951
16588
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15958,7 +16595,7 @@ function _ts_decorate62(decorators, target, key, desc) {
15958
16595
  }
15959
16596
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15960
16597
  }
15961
- __name(_ts_decorate62, "_ts_decorate");
16598
+ __name(_ts_decorate65, "_ts_decorate");
15962
16599
  var NoOpEmailProvider = class _NoOpEmailProvider {
15963
16600
  static {
15964
16601
  __name(this, "NoOpEmailProvider");
@@ -15993,10 +16630,21 @@ var NoOpEmailProvider = class _NoOpEmailProvider {
15993
16630
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
15994
16631
  }
15995
16632
  };
15996
- NoOpEmailProvider = _ts_decorate62([
16633
+ NoOpEmailProvider = _ts_decorate65([
15997
16634
  Injectable()
15998
16635
  ], NoOpEmailProvider);
15999
- function _ts_decorate63(decorators, target, key, desc) {
16636
+
16637
+ // src/server/services/api-key-clock.ts
16638
+ var SystemApiKeyClock = class {
16639
+ static {
16640
+ __name(this, "SystemApiKeyClock");
16641
+ }
16642
+ /** @returns The current instant. */
16643
+ now() {
16644
+ return /* @__PURE__ */ new Date();
16645
+ }
16646
+ };
16647
+ function _ts_decorate66(decorators, target, key, desc) {
16000
16648
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16001
16649
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16002
16650
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16009,20 +16657,330 @@ function _ts_decorate63(decorators, target, key, desc) {
16009
16657
  }
16010
16658
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16011
16659
  }
16012
- __name(_ts_decorate63, "_ts_decorate");
16013
- function _ts_metadata59(metadataKey, metadataValue) {
16660
+ __name(_ts_decorate66, "_ts_decorate");
16661
+ function _ts_metadata62(metadataKey, metadataValue) {
16014
16662
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16015
16663
  return Reflect.metadata(metadataKey, metadataValue);
16016
16664
  }
16017
16665
  }
16018
- __name(_ts_metadata59, "_ts_metadata");
16019
- function _ts_param37(paramIndex, decorator) {
16666
+ __name(_ts_metadata62, "_ts_metadata");
16667
+ function _ts_param40(paramIndex, decorator) {
16020
16668
  return function(target, key) {
16021
16669
  decorator(target, key, paramIndex);
16022
16670
  };
16023
16671
  }
16024
- __name(_ts_param37, "_ts_param");
16025
- var AuthTokenVerifierService = class {
16672
+ __name(_ts_param40, "_ts_param");
16673
+ var ApiKeyScopeAuditService = class {
16674
+ static {
16675
+ __name(this, "ApiKeyScopeAuditService");
16676
+ }
16677
+ discovery;
16678
+ scanner;
16679
+ reflector;
16680
+ options;
16681
+ constructor(discovery, scanner, reflector, options) {
16682
+ this.discovery = discovery;
16683
+ this.scanner = scanner;
16684
+ this.reflector = reflector;
16685
+ this.options = options;
16686
+ }
16687
+ /** @throws {Error} Naming every route that declares a scope the vocabulary lacks. */
16688
+ onApplicationBootstrap() {
16689
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16690
+ const problems = [];
16691
+ for (const wrapper of this.discovery.getControllers()) {
16692
+ const { instance, metatype } = wrapper;
16693
+ if (!instance || typeof metatype !== "function") continue;
16694
+ this.collect(problems, vocabulary, metatype.name, this.reflector.get(API_KEY_SCOPES_KEY, metatype));
16695
+ const prototype = Object.getPrototypeOf(instance);
16696
+ for (const method of this.scanner.getAllMethodNames(prototype)) {
16697
+ const handler = prototype[method];
16698
+ this.collect(problems, vocabulary, `${metatype.name}.${method}`, this.reflector.get(API_KEY_SCOPES_KEY, handler));
16699
+ }
16700
+ }
16701
+ if (problems.length > 0) {
16702
+ throw new Error(`[BymaxAuthModule] ${problems.join("; ")}. Add the scope to apiKeys.scopes or correct the declaration.`);
16703
+ }
16704
+ }
16705
+ collect(problems, vocabulary, where, declared) {
16706
+ if (!Array.isArray(declared)) return;
16707
+ for (const scope of declared) {
16708
+ if (!vocabulary.has(scope)) {
16709
+ problems.push(`${where} declares a scope outside apiKeys.scopes`);
16710
+ return;
16711
+ }
16712
+ }
16713
+ }
16714
+ };
16715
+ ApiKeyScopeAuditService = _ts_decorate66([
16716
+ Injectable(),
16717
+ _ts_param40(0, Inject(DiscoveryService)),
16718
+ _ts_param40(1, Inject(MetadataScanner)),
16719
+ _ts_param40(2, Inject(Reflector)),
16720
+ _ts_param40(3, Inject(BYMAX_AUTH_OPTIONS)),
16721
+ _ts_metadata62("design:type", Function),
16722
+ _ts_metadata62("design:paramtypes", [
16723
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
16724
+ typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
16725
+ typeof Reflector === "undefined" ? Object : Reflector,
16726
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16727
+ ])
16728
+ ], ApiKeyScopeAuditService);
16729
+ function _ts_decorate67(decorators, target, key, desc) {
16730
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16731
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16732
+ r = Reflect.decorate(decorators, target, key, desc);
16733
+ } else {
16734
+ for (var i = decorators.length - 1; i >= 0; i--) {
16735
+ if (d = decorators[i]) {
16736
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16737
+ }
16738
+ }
16739
+ }
16740
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16741
+ }
16742
+ __name(_ts_decorate67, "_ts_decorate");
16743
+ function _ts_metadata63(metadataKey, metadataValue) {
16744
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16745
+ return Reflect.metadata(metadataKey, metadataValue);
16746
+ }
16747
+ }
16748
+ __name(_ts_metadata63, "_ts_metadata");
16749
+ function _ts_param41(paramIndex, decorator) {
16750
+ return function(target, key) {
16751
+ decorator(target, key, paramIndex);
16752
+ };
16753
+ }
16754
+ __name(_ts_param41, "_ts_param");
16755
+ var API_KEY_MAX_LABEL_LENGTH = 128;
16756
+ var API_KEY_MAX_OVERLAP_SECONDS = 2592e3;
16757
+ var CONTROL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
16758
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
16759
+ var ApiKeyService = class {
16760
+ static {
16761
+ __name(this, "ApiKeyService");
16762
+ }
16763
+ repository;
16764
+ clock;
16765
+ options;
16766
+ constructor(repository, clock, options) {
16767
+ this.repository = repository;
16768
+ this.clock = clock;
16769
+ this.options = options;
16770
+ }
16771
+ /**
16772
+ * Issues a new key.
16773
+ *
16774
+ * @param input - Label, scopes and optional expiry.
16775
+ * @returns The plaintext key (once) and the stored record.
16776
+ * @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
16777
+ */
16778
+ async issue(input) {
16779
+ const now = this.clock.now();
16780
+ const label = this.validatedLabel(input.label);
16781
+ const scopes = this.validatedScopes(input.scopes);
16782
+ const expiresAt = this.validatedExpiry("expiresAt", input.expiresAt, now);
16783
+ const id = randomUUID();
16784
+ const secret = generateApiKeySecret();
16785
+ const stored = await this.repository.create({
16786
+ id,
16787
+ label,
16788
+ digest: apiKeyDigest(secret, this.options.apiKeys.pepper),
16789
+ scopes,
16790
+ createdAt: now,
16791
+ expiresAt
16792
+ });
16793
+ return {
16794
+ key: formatApiKey(this.options.apiKeys.prefix, id, secret),
16795
+ record: summary(stored)
16796
+ };
16797
+ }
16798
+ /**
16799
+ * Revokes a key now. Revoking an already revoked key succeeds.
16800
+ *
16801
+ * @param id - The key's row id.
16802
+ * @throws {AuthException} `auth.api_key_not_found` when no such key exists.
16803
+ */
16804
+ async revoke(id) {
16805
+ if (!UUID_PATTERN.test(id) || !await this.repository.markRevoked(id, this.clock.now())) {
16806
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16807
+ }
16808
+ }
16809
+ /**
16810
+ * Replaces a key with a new one carrying the same label and scopes.
16811
+ *
16812
+ * The new key is issued first and the old one retired second, so a failure between the two
16813
+ * leaves both valid — the safe direction — rather than neither.
16814
+ *
16815
+ * @param id - The active key to replace.
16816
+ * @param input - The overlap and an optional expiry for the new key.
16817
+ * @returns The new key, plaintext once.
16818
+ * @throws {AuthException} `auth.validation` for a bad overlap or expiry;
16819
+ * `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
16820
+ * rotated: that would re-issue access nobody holds).
16821
+ */
16822
+ async rotate(id, input) {
16823
+ const now = this.clock.now();
16824
+ const overlap = input.overlapSeconds;
16825
+ if (!Number.isInteger(overlap) || overlap < 0 || overlap > API_KEY_MAX_OVERLAP_SECONDS) {
16826
+ throw validation("overlapSeconds", `overlapSeconds must be an integer from 0 to ${API_KEY_MAX_OVERLAP_SECONDS}`);
16827
+ }
16828
+ const newExpiry = this.validatedExpiry("expiresAt", input.expiresAt, now);
16829
+ const old = UUID_PATTERN.test(id) ? await this.repository.findById(id) : null;
16830
+ if (old === null || !isActive(old, now)) {
16831
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16832
+ }
16833
+ const issued = await this.issue({
16834
+ label: old.label,
16835
+ scopes: old.scopes,
16836
+ ...newExpiry === null ? {} : {
16837
+ expiresAt: newExpiry
16838
+ }
16839
+ });
16840
+ if (overlap === 0) {
16841
+ await this.repository.markRevoked(old.id, now);
16842
+ } else {
16843
+ const retireAt = new Date(now.getTime() + overlap * 1e3);
16844
+ const sooner = (
16845
+ // Stryker disable next-line EqualityOperator: at equal instants both arms yield a Date of the same time, so `<` and `<=` store the same expiry
16846
+ old.expiresAt !== null && old.expiresAt.getTime() < retireAt.getTime() ? old.expiresAt : retireAt
16847
+ );
16848
+ await this.repository.setExpiry(old.id, sooner);
16849
+ }
16850
+ return issued;
16851
+ }
16852
+ validatedLabel(label) {
16853
+ if (typeof label !== "string" || label.trim().length === 0 || label.length > API_KEY_MAX_LABEL_LENGTH || CONTROL_CHARACTERS.test(label)) {
16854
+ throw validation("label", `label must be 1 to ${API_KEY_MAX_LABEL_LENGTH} characters with no control characters`);
16855
+ }
16856
+ return label;
16857
+ }
16858
+ validatedScopes(scopes) {
16859
+ if (!Array.isArray(scopes) || scopes.length === 0) {
16860
+ throw validation("scopes", "scopes must be a non-empty list");
16861
+ }
16862
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16863
+ const seen = /* @__PURE__ */ new Set();
16864
+ for (const scope of scopes) {
16865
+ if (!vocabulary.has(scope)) {
16866
+ throw validation("scopes", "every scope must come from the configured vocabulary");
16867
+ }
16868
+ if (seen.has(scope)) throw validation("scopes", "scopes must not repeat");
16869
+ seen.add(scope);
16870
+ }
16871
+ return [
16872
+ ...scopes
16873
+ ];
16874
+ }
16875
+ validatedExpiry(field, value, now) {
16876
+ if (value === void 0) return null;
16877
+ if (!(value instanceof Date) || Number.isNaN(value.getTime()) || value.getTime() <= now.getTime()) {
16878
+ throw validation(field, `${field} must be a valid date in the future`);
16879
+ }
16880
+ return value;
16881
+ }
16882
+ };
16883
+ ApiKeyService = _ts_decorate67([
16884
+ Injectable(),
16885
+ _ts_param41(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
16886
+ _ts_param41(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
16887
+ _ts_param41(2, Inject(BYMAX_AUTH_OPTIONS)),
16888
+ _ts_metadata63("design:type", Function),
16889
+ _ts_metadata63("design:paramtypes", [
16890
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
16891
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
16892
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16893
+ ])
16894
+ ], ApiKeyService);
16895
+ function isActive(key, now) {
16896
+ const nowMs = now.getTime();
16897
+ return key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > nowMs);
16898
+ }
16899
+ __name(isActive, "isActive");
16900
+ function summary(row) {
16901
+ const { digest: _digest, ...rest } = row;
16902
+ return rest;
16903
+ }
16904
+ __name(summary, "summary");
16905
+ function validation(field, message) {
16906
+ return new AuthException(AUTH_ERROR_CODES.VALIDATION, [
16907
+ {
16908
+ field,
16909
+ message
16910
+ }
16911
+ ]);
16912
+ }
16913
+ __name(validation, "validation");
16914
+
16915
+ // src/server/utils/handshake-request.ts
16916
+ function handshakeRequest(handshake) {
16917
+ const headers = {};
16918
+ for (const [name, value] of Object.entries(handshake.headers)) {
16919
+ headers[name.toLowerCase()] = value;
16920
+ }
16921
+ return {
16922
+ headers,
16923
+ url: handshake.url ?? "",
16924
+ hostname: hostnameOf(headers["host"])
16925
+ };
16926
+ }
16927
+ __name(handshakeRequest, "handshakeRequest");
16928
+ function hostnameOf(host) {
16929
+ if (typeof host !== "string") return "";
16930
+ const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
16931
+ const index = host.indexOf(":", offset);
16932
+ return index === -1 ? host : host.substring(0, index);
16933
+ }
16934
+ __name(hostnameOf, "hostnameOf");
16935
+
16936
+ // src/server/utils/assert-tenant-binding.ts
16937
+ function tenantBindingEnforced(options) {
16938
+ return options.enforceTenantBinding === true && options.tenantIdResolver !== void 0;
16939
+ }
16940
+ __name(tenantBindingEnforced, "tenantBindingEnforced");
16941
+ async function assertTenantBinding(options, handshake, tenantId) {
16942
+ const resolver = options.tenantIdResolver;
16943
+ if (options.enforceTenantBinding !== true || !resolver) return;
16944
+ let requestTenant;
16945
+ try {
16946
+ requestTenant = await resolver(handshakeRequest(handshake));
16947
+ } catch {
16948
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16949
+ }
16950
+ if (requestTenant !== tenantId) {
16951
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16952
+ }
16953
+ }
16954
+ __name(assertTenantBinding, "assertTenantBinding");
16955
+
16956
+ // src/server/services/auth-token-verifier.service.ts
16957
+ function _ts_decorate68(decorators, target, key, desc) {
16958
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16959
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16960
+ r = Reflect.decorate(decorators, target, key, desc);
16961
+ } else {
16962
+ for (var i = decorators.length - 1; i >= 0; i--) {
16963
+ if (d = decorators[i]) {
16964
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16965
+ }
16966
+ }
16967
+ }
16968
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16969
+ }
16970
+ __name(_ts_decorate68, "_ts_decorate");
16971
+ function _ts_metadata64(metadataKey, metadataValue) {
16972
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16973
+ return Reflect.metadata(metadataKey, metadataValue);
16974
+ }
16975
+ }
16976
+ __name(_ts_metadata64, "_ts_metadata");
16977
+ function _ts_param42(paramIndex, decorator) {
16978
+ return function(target, key) {
16979
+ decorator(target, key, paramIndex);
16980
+ };
16981
+ }
16982
+ __name(_ts_param42, "_ts_param");
16983
+ var AuthTokenVerifierService = class _AuthTokenVerifierService {
16026
16984
  static {
16027
16985
  __name(this, "AuthTokenVerifierService");
16028
16986
  }
@@ -16030,6 +16988,9 @@ var AuthTokenVerifierService = class {
16030
16988
  options;
16031
16989
  revocation;
16032
16990
  accountStatus;
16991
+ logger = new Logger(_AuthTokenVerifierService.name);
16992
+ /** Whether the "binding not applied" warning has been logged by this instance. */
16993
+ warnedUnbound = false;
16033
16994
  /**
16034
16995
  * @param jwtService - The Nest JWT service, configured with the current signing secret.
16035
16996
  * @param options - Resolved module options, for the algorithm, the binding claims and the
@@ -16073,7 +17034,9 @@ var AuthTokenVerifierService = class {
16073
17034
  */
16074
17035
  async verifyAccessToken(token, options) {
16075
17036
  const { plane, requireMfa = true, checkStatus = true } = options;
16076
- if (plane === "dashboard") return await this.verifyDashboard(token, requireMfa, checkStatus);
17037
+ if (plane === "dashboard") {
17038
+ return await this.verifyDashboard(token, requireMfa, checkStatus, options.request);
17039
+ }
16077
17040
  if (plane === "platform") return await this.verifyPlatform(token, requireMfa, checkStatus);
16078
17041
  throw new TypeError(`verifyAccessToken: plane must be 'dashboard' or 'platform'`);
16079
17042
  }
@@ -16083,10 +17046,11 @@ var AuthTokenVerifierService = class {
16083
17046
  * @param token - The compact JWT.
16084
17047
  * @param requireMfa - Whether to apply the MFA policy.
16085
17048
  * @param checkStatus - Whether to consult the account's current status.
17049
+ * @param request - The request the token arrived on, for `enforceTenantBinding`.
16086
17050
  * @returns The verified dashboard payload.
16087
17051
  * @throws {@link AuthException} as {@link verifyAccessToken} documents.
16088
17052
  */
16089
- async verifyDashboard(token, requireMfa, checkStatus) {
17053
+ async verifyDashboard(token, requireMfa, checkStatus, request) {
16090
17054
  const payload = this.verifySignature(token);
16091
17055
  assertValidJti(payload.jti);
16092
17056
  assertValidSub(payload.sub);
@@ -16095,6 +17059,7 @@ var AuthTokenVerifierService = class {
16095
17059
  if (await this.revocation.isAccessTokenRevoked(payload, "dashboard")) {
16096
17060
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16097
17061
  }
17062
+ await this.assertBound(payload.tenantId, request);
16098
17063
  if (requireMfa) this.assertMfaClaimShape(payload);
16099
17064
  if (checkStatus) {
16100
17065
  await this.accountStatus.assertDashboardAccountUsable({
@@ -16109,6 +17074,23 @@ var AuthTokenVerifierService = class {
16109
17074
  };
16110
17075
  }
16111
17076
  /**
17077
+ * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
17078
+ *
17079
+ * @param tenantId - The tenant the token was issued for.
17080
+ * @param request - The request the token arrived on, when the caller supplied one.
17081
+ * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
17082
+ */
17083
+ async assertBound(tenantId, request) {
17084
+ if (request !== void 0) {
17085
+ await assertTenantBinding(this.options, request, tenantId);
17086
+ return;
17087
+ }
17088
+ if (tenantBindingEnforced(this.options) && !this.warnedUnbound) {
17089
+ this.warnedUnbound = true;
17090
+ this.logger.warn("verifyAccessToken: enforceTenantBinding is on but no request was passed, so the tenant binding is not applied to this call. Pass the handshake as `request`.");
17091
+ }
17092
+ }
17093
+ /**
16112
17094
  * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
16113
17095
  * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
16114
17096
  *
@@ -16181,14 +17163,14 @@ var AuthTokenVerifierService = class {
16181
17163
  }
16182
17164
  }
16183
17165
  };
16184
- AuthTokenVerifierService = _ts_decorate63([
17166
+ AuthTokenVerifierService = _ts_decorate68([
16185
17167
  Injectable(),
16186
- _ts_param37(0, Inject(JwtService)),
16187
- _ts_param37(1, Inject(BYMAX_AUTH_OPTIONS)),
16188
- _ts_param37(2, Inject(AuthRevocationService)),
16189
- _ts_param37(3, Inject(AccountStatusService)),
16190
- _ts_metadata59("design:type", Function),
16191
- _ts_metadata59("design:paramtypes", [
17168
+ _ts_param42(0, Inject(JwtService)),
17169
+ _ts_param42(1, Inject(BYMAX_AUTH_OPTIONS)),
17170
+ _ts_param42(2, Inject(AuthRevocationService)),
17171
+ _ts_param42(3, Inject(AccountStatusService)),
17172
+ _ts_metadata64("design:type", Function),
17173
+ _ts_metadata64("design:paramtypes", [
16192
17174
  typeof JwtService === "undefined" ? Object : JwtService,
16193
17175
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
16194
17176
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
@@ -16197,7 +17179,7 @@ AuthTokenVerifierService = _ts_decorate63([
16197
17179
  ], AuthTokenVerifierService);
16198
17180
 
16199
17181
  // src/server/bymax-auth.module.ts
16200
- function _ts_decorate64(decorators, target, key, desc) {
17182
+ function _ts_decorate69(decorators, target, key, desc) {
16201
17183
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16202
17184
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16203
17185
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16210,7 +17192,7 @@ function _ts_decorate64(decorators, target, key, desc) {
16210
17192
  }
16211
17193
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16212
17194
  }
16213
- __name(_ts_decorate64, "_ts_decorate");
17195
+ __name(_ts_decorate69, "_ts_decorate");
16214
17196
  function hasProviderToken(providers, token) {
16215
17197
  return providers.some((p) => {
16216
17198
  if (typeof p === "function") return false;
@@ -16218,6 +17200,15 @@ function hasProviderToken(providers, token) {
16218
17200
  });
16219
17201
  }
16220
17202
  __name(hasProviderToken, "hasProviderToken");
17203
+ function cannotAuditApiKeys(providers) {
17204
+ const hooks = providers.find((p) => "provide" in p && p.provide === BYMAX_AUTH_HOOKS);
17205
+ if (hooks === void 0) return true;
17206
+ if ("useValue" in hooks) {
17207
+ return typeof hooks.useValue?.onApiKeyRequest !== "function";
17208
+ }
17209
+ return false;
17210
+ }
17211
+ __name(cannotAuditApiKeys, "cannotAuditApiKeys");
16221
17212
  var BymaxAuthModule = class _BymaxAuthModule {
16222
17213
  static {
16223
17214
  __name(this, "BymaxAuthModule");
@@ -16245,6 +17236,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
16245
17236
  const includePlatform = options.controllers?.platform === true;
16246
17237
  const includeOAuth = options.controllers?.oauth === true;
16247
17238
  const includeInvitations = options.controllers?.invitations === true;
17239
+ const includeApiKeys = hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_REPOSITORY);
16248
17240
  const includeEmailChange = options.controllers?.emailChange === true;
16249
17241
  const resolvedOptionsProvider = {
16250
17242
  provide: BYMAX_AUTH_OPTIONS,
@@ -16278,10 +17270,29 @@ var BymaxAuthModule = class _BymaxAuthModule {
16278
17270
  if (includeInvitations && !resolved.invitations?.enabled) {
16279
17271
  throw new Error("[BymaxAuthModule] controllers.invitations: true requires invitations.enabled: true in the useFactory return value.");
16280
17272
  }
17273
+ if (includeApiKeys !== resolved.apiKeys.enabled) {
17274
+ throw new Error(includeApiKeys ? "[BymaxAuthModule] BYMAX_AUTH_API_KEY_REPOSITORY is provided but apiKeys.enabled is not true. Enable apiKeys in the useFactory return value, or remove the provider." : "[BymaxAuthModule] apiKeys.enabled: true requires BYMAX_AUTH_API_KEY_REPOSITORY in extraProviders. Provide your IApiKeyRepository implementation.");
17275
+ }
17276
+ if (resolved.apiKeys.auditMode === "required" && cannotAuditApiKeys(extraProviders)) {
17277
+ throw new Error("[BymaxAuthModule] apiKeys.auditMode: 'required' needs an onApiKeyRequest hook, and the BYMAX_AUTH_HOOKS provider has none. Implement it, or use auditMode: 'best-effort'.");
17278
+ }
16281
17279
  return resolved;
16282
17280
  }, "useFactory"),
16283
17281
  inject: options.inject ?? []
16284
17282
  };
17283
+ const apiKeyProviders = includeApiKeys ? [
17284
+ ...hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_CLOCK) ? [] : [
17285
+ {
17286
+ provide: BYMAX_AUTH_API_KEY_CLOCK,
17287
+ useClass: SystemApiKeyClock
17288
+ }
17289
+ ],
17290
+ ApiKeyLastUsedService,
17291
+ ApiKeyVerifierService,
17292
+ ApiKeyService,
17293
+ ApiKeyGuard,
17294
+ ApiKeyScopeAuditService
17295
+ ] : [];
16285
17296
  const emailProviders = hasProviderToken(extraProviders, BYMAX_AUTH_EMAIL_PROVIDER) ? [] : [
16286
17297
  {
16287
17298
  provide: BYMAX_AUTH_EMAIL_PROVIDER,
@@ -16362,6 +17373,10 @@ var BymaxAuthModule = class _BymaxAuthModule {
16362
17373
  module: _BymaxAuthModule,
16363
17374
  imports: [
16364
17375
  ...options.imports ?? [],
17376
+ // The bootstrap scope audit walks controllers through the discovery service.
17377
+ ...includeApiKeys ? [
17378
+ DiscoveryModule
17379
+ ] : [],
16365
17380
  // JwtModule reads the secret directly from the consumer factory (without re-running
16366
17381
  // resolveOptions) to avoid double-validation on startup. Full validation happens once
16367
17382
  // in the BYMAX_AUTH_OPTIONS provider above.
@@ -16455,7 +17470,9 @@ var BymaxAuthModule = class _BymaxAuthModule {
16455
17470
  // Invitation service — only when controllers.invitations: true.
16456
17471
  ...invitationProviders,
16457
17472
  // Address-change service — only when controllers.emailChange: true.
16458
- ...emailChangeProviders
17473
+ ...emailChangeProviders,
17474
+ // Service API keys — only when the host supplied the repository.
17475
+ ...apiKeyProviders
16459
17476
  ],
16460
17477
  controllers,
16461
17478
  exports: [
@@ -16543,6 +17560,15 @@ var BymaxAuthModule = class _BymaxAuthModule {
16543
17560
  // export BYMAX_AUTH_USER_REPOSITORY as the instance supplied by the consumer` test, which
16544
17561
  // is the one that fails without it.
16545
17562
  BYMAX_AUTH_USER_REPOSITORY,
17563
+ // Service API keys: the guard is re-instantiated in the consumer's injector by
17564
+ // `@ServiceKey()`, so its direct dependencies must be exported with it — the verifier and
17565
+ // the hooks. The service is public surface for a host's own admin routes.
17566
+ ...includeApiKeys ? [
17567
+ ApiKeyGuard,
17568
+ ApiKeyVerifierService,
17569
+ ApiKeyService,
17570
+ BYMAX_AUTH_HOOKS
17571
+ ] : [],
16546
17572
  // WsTicketService also stands on its own as public surface: single-use ticket
16547
17573
  // handshakes are the credential a realtime transport is meant to use, and a consumer
16548
17574
  // cannot mint one without injecting this service.
@@ -16554,7 +17580,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
16554
17580
  };
16555
17581
  }
16556
17582
  };
16557
- BymaxAuthModule = _ts_decorate64([
17583
+ BymaxAuthModule = _ts_decorate69([
16558
17584
  Module({})
16559
17585
  ], BymaxAuthModule);
16560
17586
 
@@ -16882,7 +17908,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
16882
17908
  }
16883
17909
  }
16884
17910
  };
16885
- function _ts_decorate65(decorators, target, key, desc) {
17911
+ function _ts_decorate70(decorators, target, key, desc) {
16886
17912
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16887
17913
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16888
17914
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16895,13 +17921,13 @@ function _ts_decorate65(decorators, target, key, desc) {
16895
17921
  }
16896
17922
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16897
17923
  }
16898
- __name(_ts_decorate65, "_ts_decorate");
16899
- function _ts_metadata60(metadataKey, metadataValue) {
17924
+ __name(_ts_decorate70, "_ts_decorate");
17925
+ function _ts_metadata65(metadataKey, metadataValue) {
16900
17926
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16901
17927
  return Reflect.metadata(metadataKey, metadataValue);
16902
17928
  }
16903
17929
  }
16904
- __name(_ts_metadata60, "_ts_metadata");
17930
+ __name(_ts_metadata65, "_ts_metadata");
16905
17931
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
16906
17932
  var PREFIX_LENGTH = 5;
16907
17933
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -16958,10 +17984,10 @@ var HibpBreachChecker = class _HibpBreachChecker {
16958
17984
  }
16959
17985
  }
16960
17986
  };
16961
- HibpBreachChecker = _ts_decorate65([
17987
+ HibpBreachChecker = _ts_decorate70([
16962
17988
  Injectable(),
16963
- _ts_metadata60("design:type", Function),
16964
- _ts_metadata60("design:paramtypes", [
17989
+ _ts_metadata65("design:type", Function),
17990
+ _ts_metadata65("design:paramtypes", [
16965
17991
  Number
16966
17992
  ])
16967
17993
  ], HibpBreachChecker);
@@ -16974,10 +18000,10 @@ var AllowAllBreachChecker = class {
16974
18000
  return false;
16975
18001
  }
16976
18002
  };
16977
- AllowAllBreachChecker = _ts_decorate65([
18003
+ AllowAllBreachChecker = _ts_decorate70([
16978
18004
  Injectable()
16979
18005
  ], AllowAllBreachChecker);
16980
- function _ts_decorate66(decorators, target, key, desc) {
18006
+ function _ts_decorate71(decorators, target, key, desc) {
16981
18007
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16982
18008
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16983
18009
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16990,7 +18016,7 @@ function _ts_decorate66(decorators, target, key, desc) {
16990
18016
  }
16991
18017
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16992
18018
  }
16993
- __name(_ts_decorate66, "_ts_decorate");
18019
+ __name(_ts_decorate71, "_ts_decorate");
16994
18020
  var OptionalAuthGuard = class extends JwtAuthGuard {
16995
18021
  static {
16996
18022
  __name(this, "OptionalAuthGuard");
@@ -17005,10 +18031,10 @@ var OptionalAuthGuard = class extends JwtAuthGuard {
17005
18031
  return super.canActivate(context);
17006
18032
  }
17007
18033
  };
17008
- OptionalAuthGuard = _ts_decorate66([
18034
+ OptionalAuthGuard = _ts_decorate71([
17009
18035
  Injectable()
17010
18036
  ], OptionalAuthGuard);
17011
- function _ts_decorate67(decorators, target, key, desc) {
18037
+ function _ts_decorate72(decorators, target, key, desc) {
17012
18038
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17013
18039
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17014
18040
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17021,19 +18047,19 @@ function _ts_decorate67(decorators, target, key, desc) {
17021
18047
  }
17022
18048
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17023
18049
  }
17024
- __name(_ts_decorate67, "_ts_decorate");
17025
- function _ts_metadata61(metadataKey, metadataValue) {
18050
+ __name(_ts_decorate72, "_ts_decorate");
18051
+ function _ts_metadata66(metadataKey, metadataValue) {
17026
18052
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17027
18053
  return Reflect.metadata(metadataKey, metadataValue);
17028
18054
  }
17029
18055
  }
17030
- __name(_ts_metadata61, "_ts_metadata");
17031
- function _ts_param38(paramIndex, decorator) {
18056
+ __name(_ts_metadata66, "_ts_metadata");
18057
+ function _ts_param43(paramIndex, decorator) {
17032
18058
  return function(target, key) {
17033
18059
  decorator(target, key, paramIndex);
17034
18060
  };
17035
18061
  }
17036
- __name(_ts_param38, "_ts_param");
18062
+ __name(_ts_param43, "_ts_param");
17037
18063
  var SelfOrAdminGuard = class {
17038
18064
  static {
17039
18065
  __name(this, "SelfOrAdminGuard");
@@ -17063,11 +18089,11 @@ var SelfOrAdminGuard = class {
17063
18089
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
17064
18090
  }
17065
18091
  };
17066
- SelfOrAdminGuard = _ts_decorate67([
18092
+ SelfOrAdminGuard = _ts_decorate72([
17067
18093
  Injectable(),
17068
- _ts_param38(0, Inject(BYMAX_AUTH_OPTIONS)),
17069
- _ts_metadata61("design:type", Function),
17070
- _ts_metadata61("design:paramtypes", [
18094
+ _ts_param43(0, Inject(BYMAX_AUTH_OPTIONS)),
18095
+ _ts_metadata66("design:type", Function),
18096
+ _ts_metadata66("design:paramtypes", [
17071
18097
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
17072
18098
  ])
17073
18099
  ], SelfOrAdminGuard);
@@ -17080,7 +18106,7 @@ function isHexLooking(value) {
17080
18106
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
17081
18107
  }
17082
18108
  __name(isHexLooking, "isHexLooking");
17083
- function _ts_decorate68(decorators, target, key, desc) {
18109
+ function _ts_decorate73(decorators, target, key, desc) {
17084
18110
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17085
18111
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17086
18112
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17093,19 +18119,19 @@ function _ts_decorate68(decorators, target, key, desc) {
17093
18119
  }
17094
18120
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17095
18121
  }
17096
- __name(_ts_decorate68, "_ts_decorate");
17097
- function _ts_metadata62(metadataKey, metadataValue) {
18122
+ __name(_ts_decorate73, "_ts_decorate");
18123
+ function _ts_metadata67(metadataKey, metadataValue) {
17098
18124
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17099
18125
  return Reflect.metadata(metadataKey, metadataValue);
17100
18126
  }
17101
18127
  }
17102
- __name(_ts_metadata62, "_ts_metadata");
17103
- function _ts_param39(paramIndex, decorator) {
18128
+ __name(_ts_metadata67, "_ts_metadata");
18129
+ function _ts_param44(paramIndex, decorator) {
17104
18130
  return function(target, key) {
17105
18131
  decorator(target, key, paramIndex);
17106
18132
  };
17107
18133
  }
17108
- __name(_ts_param39, "_ts_param");
18134
+ __name(_ts_param44, "_ts_param");
17109
18135
  var WsJwtGuard = class {
17110
18136
  static {
17111
18137
  __name(this, "WsJwtGuard");
@@ -17141,6 +18167,7 @@ var WsJwtGuard = class {
17141
18167
  if (ticket !== void 0) {
17142
18168
  const snapshot = await this.wsTickets.redeem(ticket);
17143
18169
  assertDashboardSnapshot(snapshot);
18170
+ await assertTenantBinding(this.options, handshake, snapshot.tenantId);
17144
18171
  client.data.user = snapshot;
17145
18172
  return true;
17146
18173
  }
@@ -17163,18 +18190,19 @@ var WsJwtGuard = class {
17163
18190
  if (await this.revocation.isAccessTokenRevoked(payload)) {
17164
18191
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
17165
18192
  }
18193
+ await assertTenantBinding(this.options, handshake, payload.tenantId);
17166
18194
  client.data.user = payload;
17167
18195
  return true;
17168
18196
  }
17169
18197
  };
17170
- WsJwtGuard = _ts_decorate68([
18198
+ WsJwtGuard = _ts_decorate73([
17171
18199
  Injectable(),
17172
- _ts_param39(0, Inject(JwtService)),
17173
- _ts_param39(1, Inject(AuthRevocationService)),
17174
- _ts_param39(2, Inject(WsTicketService)),
17175
- _ts_param39(3, Inject(BYMAX_AUTH_OPTIONS)),
17176
- _ts_metadata62("design:type", Function),
17177
- _ts_metadata62("design:paramtypes", [
18200
+ _ts_param44(0, Inject(JwtService)),
18201
+ _ts_param44(1, Inject(AuthRevocationService)),
18202
+ _ts_param44(2, Inject(WsTicketService)),
18203
+ _ts_param44(3, Inject(BYMAX_AUTH_OPTIONS)),
18204
+ _ts_metadata67("design:type", Function),
18205
+ _ts_metadata67("design:paramtypes", [
17178
18206
  typeof JwtService === "undefined" ? Object : JwtService,
17179
18207
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
17180
18208
  typeof WsTicketService === "undefined" ? Object : WsTicketService,
@@ -17207,7 +18235,7 @@ function readUpgradeTicket(handshake) {
17207
18235
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
17208
18236
  }
17209
18237
  __name(readUpgradeTicket, "readUpgradeTicket");
17210
- function _ts_decorate69(decorators, target, key, desc) {
18238
+ function _ts_decorate74(decorators, target, key, desc) {
17211
18239
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17212
18240
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17213
18241
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17220,7 +18248,7 @@ function _ts_decorate69(decorators, target, key, desc) {
17220
18248
  }
17221
18249
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17222
18250
  }
17223
- __name(_ts_decorate69, "_ts_decorate");
18251
+ __name(_ts_decorate74, "_ts_decorate");
17224
18252
  function isAuthEnvelope(body) {
17225
18253
  if (typeof body !== "object" || body === null) return false;
17226
18254
  const error = body.error;
@@ -17272,10 +18300,10 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
17272
18300
  });
17273
18301
  }
17274
18302
  };
17275
- AuthExceptionFilter = _ts_decorate69([
18303
+ AuthExceptionFilter = _ts_decorate74([
17276
18304
  Catch()
17277
18305
  ], AuthExceptionFilter);
17278
- function _ts_decorate70(decorators, target, key, desc) {
18306
+ function _ts_decorate75(decorators, target, key, desc) {
17279
18307
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17280
18308
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17281
18309
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17288,7 +18316,7 @@ function _ts_decorate70(decorators, target, key, desc) {
17288
18316
  }
17289
18317
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17290
18318
  }
17291
- __name(_ts_decorate70, "_ts_decorate");
18319
+ __name(_ts_decorate75, "_ts_decorate");
17292
18320
  function isEmittingClient(client) {
17293
18321
  return typeof client?.emit === "function";
17294
18322
  }
@@ -17332,8 +18360,10 @@ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
17332
18360
  this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
17333
18361
  }
17334
18362
  };
17335
- WsAuthExceptionFilter = _ts_decorate70([
18363
+ WsAuthExceptionFilter = _ts_decorate75([
17336
18364
  Catch(AuthException)
17337
18365
  ], WsAuthExceptionFilter);
18366
+ var ServiceKey = /* @__PURE__ */ __name((...scopes) => applyDecorators(SetMetadata(IS_PUBLIC_KEY, true), ApiKeyScopes(...scopes), UseGuards(ApiKeyGuard)), "ServiceKey");
18367
+ var CurrentApiKey = createParamDecorator((_data, ctx) => ctx.switchToHttp().getRequest().apiKey);
17338
18368
 
17339
- export { AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, 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, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
18369
+ export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, ApiKeyGuard, ApiKeyScopes, ApiKeyService, AuthException, AuthExceptionFilter, AuthRateLimit, AuthRateLimitGuard, AuthRevocationService, AuthService, AuthTokenVerifierService, Authenticated, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, 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, CurrentApiKey, 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, ServiceKey, SessionService, SkipMfa, TokenDeliveryService, TrustedOriginGuard, UserStatusGuard, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };