@bymax-one/nest-auth 1.4.6 → 1.4.8

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));
@@ -9464,6 +9611,18 @@ function decrypt(ciphertext, keyBase64) {
9464
9611
  }
9465
9612
  __name(decrypt, "decrypt");
9466
9613
 
9614
+ // src/server/utils/run-detached.ts
9615
+ function runDetached(logger, run, failure) {
9616
+ try {
9617
+ void Promise.resolve(run()).catch((err) => {
9618
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9619
+ });
9620
+ } catch (err) {
9621
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9622
+ }
9623
+ }
9624
+ __name(runDetached, "runDetached");
9625
+
9467
9626
  // src/server/services/mfa.service.ts
9468
9627
  function _ts_decorate36(decorators, target, key, desc) {
9469
9628
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -10144,14 +10303,19 @@ var MfaService = class _MfaService {
10144
10303
  userAgent
10145
10304
  });
10146
10305
  }
10306
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
10307
+ id: safeUser.id,
10308
+ tenantId: safeUser.tenantId
10309
+ }), "challenge: updateLastLogin failed");
10147
10310
  if (this.hooks.afterLogin) {
10148
- void Promise.resolve(this.hooks.afterLogin(safeUser, {
10311
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10312
+ runDetached(this.logger, () => afterLogin(safeUser, {
10149
10313
  plane: "dashboard",
10150
10314
  userId,
10151
10315
  ip,
10152
10316
  userAgent,
10153
10317
  sanitizedHeaders: {}
10154
- })).catch(() => void 0);
10318
+ }), "challenge: afterLogin hook threw");
10155
10319
  }
10156
10320
  return result2;
10157
10321
  }
@@ -10159,14 +10323,16 @@ var MfaService = class _MfaService {
10159
10323
  const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10160
10324
  mfaVerified: true
10161
10325
  });
10326
+ runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10162
10327
  if (this.hooks.afterLogin) {
10163
- void Promise.resolve(this.hooks.afterLogin(this.platformUserAsSafeUser(platformUser), {
10328
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10329
+ runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10164
10330
  plane: "platform",
10165
10331
  userId,
10166
10332
  ip,
10167
10333
  userAgent,
10168
10334
  sanitizedHeaders: {}
10169
- })).catch(() => void 0);
10335
+ }), "challenge: afterLogin hook threw");
10170
10336
  }
10171
10337
  return result;
10172
10338
  }
@@ -13310,6 +13476,8 @@ SessionController = _ts_decorate50([
13310
13476
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService
13311
13477
  ])
13312
13478
  ], SessionController);
13479
+ var API_KEY_SCOPES_KEY = /* @__PURE__ */ Symbol("bymax:apiKeyScopes");
13480
+ var ApiKeyScopes = /* @__PURE__ */ __name((...scopes) => SetMetadata(API_KEY_SCOPES_KEY, scopes), "ApiKeyScopes");
13313
13481
  function _ts_decorate51(decorators, target, key, desc) {
13314
13482
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13315
13483
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13336,44 +13504,120 @@ function _ts_param30(paramIndex, decorator) {
13336
13504
  };
13337
13505
  }
13338
13506
  __name(_ts_param30, "_ts_param");
13339
- var MfaRequiredGuard = class {
13507
+ var ApiKeyLastUsedService = class _ApiKeyLastUsedService {
13340
13508
  static {
13341
- __name(this, "MfaRequiredGuard");
13509
+ __name(this, "ApiKeyLastUsedService");
13342
13510
  }
13343
- reflector;
13344
- constructor(reflector) {
13345
- this.reflector = reflector;
13511
+ repository;
13512
+ options;
13513
+ logger = new Logger(_ApiKeyLastUsedService.name);
13514
+ pending = /* @__PURE__ */ new Map();
13515
+ timer = null;
13516
+ closed = false;
13517
+ constructor(repository, options) {
13518
+ this.repository = repository;
13519
+ this.options = options;
13346
13520
  }
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);
13521
+ /**
13522
+ * Notes that a key verified at an instant. Synchronous and free of I/O.
13523
+ *
13524
+ * @param id - The key's row id.
13525
+ * @param at - When it verified.
13526
+ */
13527
+ record(id, at) {
13528
+ const seen = this.pending.get(id);
13529
+ if (seen === void 0 || seen.getTime() < at.getTime()) this.pending.set(id, at);
13530
+ if (this.timer === null && !this.closed) {
13531
+ this.timer = setTimeout(() => {
13532
+ this.timer = null;
13533
+ void this.flush();
13534
+ }, this.options.apiKeys.lastUsedFlushSeconds * 1e3);
13535
+ this.timer.unref();
13358
13536
  }
13359
- if (user.mfaEnabled === true && user.mfaVerified !== true) {
13360
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13537
+ }
13538
+ /**
13539
+ * Writes everything pending in one batch. A failure keeps the entries for the next window.
13540
+ *
13541
+ * @returns Resolves once the batch is written or has been put back.
13542
+ */
13543
+ async flush() {
13544
+ if (this.pending.size === 0) return;
13545
+ const batch = this.pending;
13546
+ this.pending = /* @__PURE__ */ new Map();
13547
+ try {
13548
+ await this.repository.touchLastUsed([
13549
+ ...batch
13550
+ ].map(([id, at]) => ({
13551
+ id,
13552
+ at
13553
+ })));
13554
+ } catch (err) {
13555
+ this.logger.warn(`api-key: last-used flush failed cause=${describeChannelStatus(err)}`);
13556
+ for (const [id, at] of batch) this.record(id, at);
13361
13557
  }
13362
- return true;
13558
+ }
13559
+ /** Flushes what is left so a clean shutdown loses nothing. */
13560
+ async onApplicationShutdown() {
13561
+ this.closed = true;
13562
+ if (this.timer !== null) clearTimeout(this.timer);
13563
+ this.timer = null;
13564
+ await this.flush();
13363
13565
  }
13364
13566
  };
13365
- MfaRequiredGuard = _ts_decorate51([
13567
+ ApiKeyLastUsedService = _ts_decorate51([
13366
13568
  Injectable(),
13367
- _ts_param30(0, Inject(Reflector)),
13569
+ _ts_param30(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13570
+ _ts_param30(1, Inject(BYMAX_AUTH_OPTIONS)),
13368
13571
  _ts_metadata50("design:type", Function),
13369
13572
  _ts_metadata50("design:paramtypes", [
13370
- typeof Reflector === "undefined" ? Object : Reflector
13573
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13574
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13371
13575
  ])
13372
- ], MfaRequiredGuard);
13373
- var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13374
- var PlatformRoles = /* @__PURE__ */ __name((...roles) => SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13576
+ ], ApiKeyLastUsedService);
13577
+ var SEPARATOR = "_";
13578
+ var KEY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13579
+ var SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
13580
+ var SECRET_BYTES = 32;
13581
+ var DIGEST_HEX = /^[0-9a-f]{64}$/;
13582
+ var API_KEY_DUMMY_KEY_ID = "00000000-0000-4000-8000-000000000000";
13583
+ var API_KEY_DUMMY_SECRET = "A".repeat(43);
13584
+ var API_KEY_DUMMY_DIGEST = "0".repeat(64);
13585
+ function generateApiKeySecret() {
13586
+ return randomBytes(SECRET_BYTES).toString("base64url");
13587
+ }
13588
+ __name(generateApiKeySecret, "generateApiKeySecret");
13589
+ function formatApiKey(prefix, keyId, secret) {
13590
+ return `${prefix}${SEPARATOR}${keyId}${SEPARATOR}${secret}`;
13591
+ }
13592
+ __name(formatApiKey, "formatApiKey");
13593
+ function parseApiKey(raw, prefix) {
13594
+ if (typeof raw !== "string") return null;
13595
+ const head = `${prefix}${SEPARATOR}`;
13596
+ if (!raw.startsWith(head)) return null;
13597
+ const rest = raw.slice(head.length);
13598
+ const keyId = rest.slice(0, 36);
13599
+ if (rest[36] !== SEPARATOR) return null;
13600
+ const secret = rest.slice(37);
13601
+ if (!KEY_ID_PATTERN.test(keyId) || !SECRET_PATTERN.test(secret)) return null;
13602
+ return {
13603
+ keyId,
13604
+ secret
13605
+ };
13606
+ }
13607
+ __name(parseApiKey, "parseApiKey");
13608
+ function apiKeyDigest(secret, pepper) {
13609
+ return hmacSha256(secret, pepper);
13610
+ }
13611
+ __name(apiKeyDigest, "apiKeyDigest");
13612
+ function digestsMatch(computed, stored) {
13613
+ const wellFormed = DIGEST_HEX.test(computed) && DIGEST_HEX.test(stored);
13614
+ const left = Buffer.from(wellFormed ? computed : API_KEY_DUMMY_DIGEST, "hex");
13615
+ const right = Buffer.from(wellFormed ? stored : API_KEY_DUMMY_DIGEST, "hex");
13616
+ return timingSafeEqual(left, right) && wellFormed;
13617
+ }
13618
+ __name(digestsMatch, "digestsMatch");
13375
13619
 
13376
- // src/server/guards/platform-roles.guard.ts
13620
+ // src/server/services/api-key-verifier.service.ts
13377
13621
  function _ts_decorate52(decorators, target, key, desc) {
13378
13622
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13379
13623
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13400,53 +13644,81 @@ function _ts_param31(paramIndex, decorator) {
13400
13644
  };
13401
13645
  }
13402
13646
  __name(_ts_param31, "_ts_param");
13403
- var PlatformRolesGuard = class {
13647
+ var ApiKeyVerifierService = class {
13404
13648
  static {
13405
- __name(this, "PlatformRolesGuard");
13649
+ __name(this, "ApiKeyVerifierService");
13406
13650
  }
13407
- reflector;
13651
+ repository;
13652
+ clock;
13408
13653
  options;
13409
- constructor(reflector, options) {
13410
- this.reflector = reflector;
13654
+ lastUsed;
13655
+ constructor(repository, clock, options, lastUsed) {
13656
+ this.repository = repository;
13657
+ this.clock = clock;
13411
13658
  this.options = options;
13659
+ this.lastUsed = lastUsed;
13412
13660
  }
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);
13661
+ /**
13662
+ * Verifies the value of the key header.
13663
+ *
13664
+ * @param header - The header value as the framework delivered it.
13665
+ * @returns The verdict. A store fault propagates: the caller fails closed.
13666
+ */
13667
+ async verify(header) {
13668
+ const parsed = parseApiKey(header, this.options.apiKeys.prefix);
13669
+ const keyId = parsed?.keyId ?? API_KEY_DUMMY_KEY_ID;
13670
+ const secret = parsed?.secret ?? API_KEY_DUMMY_SECRET;
13671
+ const row = await this.repository.findById(keyId);
13672
+ const computed = apiKeyDigest(secret, this.options.apiKeys.pepper);
13673
+ const equal = digestsMatch(computed, row?.digest ?? API_KEY_DUMMY_DIGEST);
13674
+ const now = this.clock.now();
13675
+ const reason = this.rejection(header, parsed !== null, row, equal, now.getTime());
13676
+ if (reason !== null) {
13677
+ return {
13678
+ ok: false,
13679
+ reason,
13680
+ key: parsed === null ? null : row
13681
+ };
13432
13682
  }
13433
- return true;
13683
+ const key = row;
13684
+ this.lastUsed.record(key.id, now);
13685
+ return {
13686
+ ok: true,
13687
+ key
13688
+ };
13689
+ }
13690
+ /**
13691
+ * The single decision, evaluated after every step above has run.
13692
+ *
13693
+ * A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
13694
+ * comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
13695
+ * compares false against everything) reads as lapsed rather than as valid.
13696
+ */
13697
+ rejection(header, parsed, row, equal, nowMs) {
13698
+ if (!parsed) return header === void 0 ? "missing" : "malformed";
13699
+ if (row === null) return "unknown";
13700
+ if (!equal) return "wrong_secret";
13701
+ if (row.revokedAt !== null) return "revoked";
13702
+ if (row.expiresAt !== null && !(row.expiresAt.getTime() > nowMs)) return "expired";
13703
+ return null;
13434
13704
  }
13435
13705
  };
13436
- PlatformRolesGuard = _ts_decorate52([
13706
+ ApiKeyVerifierService = _ts_decorate52([
13437
13707
  Injectable(),
13438
- _ts_param31(0, Inject(Reflector)),
13439
- _ts_param31(1, Inject(BYMAX_AUTH_OPTIONS)),
13708
+ _ts_param31(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13709
+ _ts_param31(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
13710
+ _ts_param31(2, Inject(BYMAX_AUTH_OPTIONS)),
13711
+ _ts_param31(3, Inject(ApiKeyLastUsedService)),
13440
13712
  _ts_metadata51("design:type", Function),
13441
13713
  _ts_metadata51("design:paramtypes", [
13442
- typeof Reflector === "undefined" ? Object : Reflector,
13443
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13714
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13715
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
13716
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13717
+ typeof ApiKeyLastUsedService === "undefined" ? Object : ApiKeyLastUsedService
13444
13718
  ])
13445
- ], PlatformRolesGuard);
13446
- var ROLES_KEY = "roles";
13447
- var Roles = /* @__PURE__ */ __name((...roles) => SetMetadata(ROLES_KEY, roles), "Roles");
13719
+ ], ApiKeyVerifierService);
13448
13720
 
13449
- // src/server/guards/roles.guard.ts
13721
+ // src/server/guards/api-key.guard.ts
13450
13722
  function _ts_decorate53(decorators, target, key, desc) {
13451
13723
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13452
13724
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13473,115 +13745,166 @@ function _ts_param32(paramIndex, decorator) {
13473
13745
  };
13474
13746
  }
13475
13747
  __name(_ts_param32, "_ts_param");
13476
- var RolesGuard = class {
13748
+ var ApiKeyGuard = class _ApiKeyGuard {
13477
13749
  static {
13478
- __name(this, "RolesGuard");
13750
+ __name(this, "ApiKeyGuard");
13479
13751
  }
13480
13752
  reflector;
13753
+ verifier;
13481
13754
  options;
13482
- constructor(reflector, options) {
13755
+ hooks;
13756
+ logger = new Logger(_ApiKeyGuard.name);
13757
+ constructor(reflector, verifier, options, hooks) {
13483
13758
  this.reflector = reflector;
13759
+ this.verifier = verifier;
13484
13760
  this.options = options;
13761
+ this.hooks = hooks;
13485
13762
  }
13486
- canActivate(context) {
13487
- const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
13488
- context.getHandler(),
13489
- context.getClass()
13490
- ]);
13491
- if (!requiredRoles || requiredRoles.length === 0) return true;
13763
+ async canActivate(context) {
13492
13764
  const request = context.switchToHttp().getRequest();
13493
- const userRole = request.user?.role;
13494
- if (!userRole) {
13495
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13496
- }
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);
13765
+ const required = this.declaredScopes(context);
13766
+ const base = {
13767
+ method: request.method,
13768
+ route: routePattern(request),
13769
+ requiredScopes: required ?? []
13770
+ };
13771
+ if (required === null) {
13772
+ this.logger.error(`api-key: ${logSafe(request.method)} ${logSafe(base.route)} is guarded but declares no scopes; refused`);
13773
+ await this.audit(request, {
13774
+ ...base,
13775
+ outcome: "denied",
13776
+ reason: "route_undeclared"
13777
+ });
13778
+ throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN);
13501
13779
  }
13780
+ let verdict;
13781
+ try {
13782
+ verdict = await this.verifier.verify(request.headers[this.options.apiKeys.header]);
13783
+ } catch (err) {
13784
+ this.logger.error(`api-key: key store unavailable cause=${describeChannelStatus(err)}`);
13785
+ await this.audit(request, {
13786
+ ...base,
13787
+ outcome: "denied",
13788
+ reason: "store_error"
13789
+ });
13790
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13791
+ }
13792
+ if (!verdict.ok) {
13793
+ await this.audit(request, {
13794
+ ...base,
13795
+ outcome: "denied",
13796
+ reason: verdict.reason
13797
+ }, verdict.key);
13798
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_INVALID);
13799
+ }
13800
+ const { key } = verdict;
13801
+ if (!required.every((scope) => key.scopes.includes(scope))) {
13802
+ await this.audit(request, {
13803
+ ...base,
13804
+ outcome: "denied",
13805
+ reason: "scope_insufficient"
13806
+ }, key);
13807
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_SCOPE_INSUFFICIENT);
13808
+ }
13809
+ const delivered = await this.audit(request, {
13810
+ ...base,
13811
+ outcome: "allowed",
13812
+ reason: null
13813
+ }, key);
13814
+ if (!delivered) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13815
+ request.apiKey = Object.freeze({
13816
+ id: key.id,
13817
+ label: key.label,
13818
+ scopes: Object.freeze([
13819
+ ...key.scopes
13820
+ ])
13821
+ });
13502
13822
  return true;
13503
13823
  }
13504
- };
13505
- RolesGuard = _ts_decorate53([
13506
- Injectable(),
13507
- _ts_param32(0, Inject(Reflector)),
13508
- _ts_param32(1, Inject(BYMAX_AUTH_OPTIONS)),
13509
- _ts_metadata52("design:type", Function),
13510
- _ts_metadata52("design:paramtypes", [
13511
- typeof Reflector === "undefined" ? Object : Reflector,
13512
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13513
- ])
13514
- ], RolesGuard);
13515
- function _ts_decorate54(decorators, target, key, desc) {
13516
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13517
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13518
- r = Reflect.decorate(decorators, target, key, desc);
13519
- } else {
13520
- for (var i = decorators.length - 1; i >= 0; i--) {
13521
- if (d = decorators[i]) {
13522
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13523
- }
13524
- }
13525
- }
13526
- return c > 3 && r && Object.defineProperty(target, key, r), r;
13527
- }
13528
- __name(_ts_decorate54, "_ts_decorate");
13529
- var NoOpAuthHooks = class {
13530
- static {
13531
- __name(this, "NoOpAuthHooks");
13532
- }
13533
13824
  /**
13534
- * Permits all registration attempts unconditionally.
13825
+ * The route's scope declaration: handler over class, empty or malformed counting as none.
13535
13826
  *
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.
13827
+ * @returns The scopes, or `null` when the route declares none.
13539
13828
  */
13540
- beforeRegister(_data, _context) {
13541
- return {
13542
- allowed: true
13543
- };
13829
+ declaredScopes(context) {
13830
+ const declared = this.reflector.getAllAndOverride(API_KEY_SCOPES_KEY, [
13831
+ context.getHandler(),
13832
+ context.getClass()
13833
+ ]);
13834
+ if (!Array.isArray(declared) || declared.length === 0 || !declared.every((scope) => typeof scope === "string")) {
13835
+ return null;
13836
+ }
13837
+ return declared;
13544
13838
  }
13545
13839
  /**
13546
- * Resolves OAuth login by linking to an existing account, creating a new one,
13547
- * or rejecting on email mismatch.
13840
+ * Emits the audit event.
13548
13841
  *
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.
13842
+ * @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
13843
+ * is fired without being awaited and the result is always `true`.
13553
13844
  */
13554
- onOAuthLogin(profile, existingUser, _context) {
13555
- if (existingUser === null) {
13556
- return {
13557
- action: "create"
13558
- };
13845
+ async audit(request, partial, key = null) {
13846
+ const hook = this.hooks?.onApiKeyRequest;
13847
+ if (hook === void 0) {
13848
+ if (this.options.apiKeys.auditMode !== "required") return true;
13849
+ this.logger.error("api-key: auditMode is required but no onApiKeyRequest hook is implemented; refusing");
13850
+ return false;
13559
13851
  }
13560
- if (existingUser.email === profile.email) {
13561
- return {
13562
- action: "link"
13563
- };
13852
+ const event = {
13853
+ ...partial,
13854
+ keyId: key?.id ?? null,
13855
+ label: key?.label ?? null,
13856
+ ip: request.ip ?? ""
13857
+ };
13858
+ const context = this.hookContext(request);
13859
+ const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
13860
+ if (this.options.apiKeys.auditMode === "required") {
13861
+ try {
13862
+ await run();
13863
+ return true;
13864
+ } catch (err) {
13865
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13866
+ return false;
13867
+ }
13868
+ }
13869
+ try {
13870
+ void Promise.resolve(run()).catch((err) => {
13871
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13872
+ });
13873
+ } catch (err) {
13874
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13564
13875
  }
13876
+ return true;
13877
+ }
13878
+ hookContext(request) {
13879
+ const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13565
13880
  return {
13566
- action: "reject",
13567
- reason: "Email mismatch"
13881
+ ip: request.ip ?? "",
13882
+ userAgent: request.headers["user-agent"] ?? "",
13883
+ sanitizedHeaders: sanitizeHeaders(headers)
13568
13884
  };
13569
13885
  }
13570
13886
  };
13571
- NoOpAuthHooks = _ts_decorate54([
13572
- Injectable()
13573
- ], NoOpAuthHooks);
13574
-
13575
- // src/server/oauth/oauth.constants.ts
13576
- var OAUTH_PLUGINS = /* @__PURE__ */ Symbol("OAUTH_PLUGINS");
13577
-
13578
- // src/server/constants/oauth-state-cookie.ts
13579
- var OAUTH_STATE_COOKIE_NAME = "oauth_state";
13580
- var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
13581
- var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
13582
-
13583
- // src/server/oauth/oauth.service.ts
13584
- function _ts_decorate55(decorators, target, key, desc) {
13887
+ ApiKeyGuard = _ts_decorate53([
13888
+ Injectable(),
13889
+ _ts_param32(0, Inject(Reflector)),
13890
+ _ts_param32(1, Inject(ApiKeyVerifierService)),
13891
+ _ts_param32(2, Inject(BYMAX_AUTH_OPTIONS)),
13892
+ _ts_param32(3, Inject(BYMAX_AUTH_HOOKS)),
13893
+ _ts_param32(3, Optional()),
13894
+ _ts_metadata52("design:type", Function),
13895
+ _ts_metadata52("design:paramtypes", [
13896
+ typeof Reflector === "undefined" ? Object : Reflector,
13897
+ typeof ApiKeyVerifierService === "undefined" ? Object : ApiKeyVerifierService,
13898
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13899
+ Object
13900
+ ])
13901
+ ], ApiKeyGuard);
13902
+ function routePattern(request) {
13903
+ const path = request.route?.path;
13904
+ return typeof path === "string" ? path : "";
13905
+ }
13906
+ __name(routePattern, "routePattern");
13907
+ function _ts_decorate54(decorators, target, key, desc) {
13585
13908
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13586
13909
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13587
13910
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13594,7 +13917,7 @@ function _ts_decorate55(decorators, target, key, desc) {
13594
13917
  }
13595
13918
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13596
13919
  }
13597
- __name(_ts_decorate55, "_ts_decorate");
13920
+ __name(_ts_decorate54, "_ts_decorate");
13598
13921
  function _ts_metadata53(metadataKey, metadataValue) {
13599
13922
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13600
13923
  return Reflect.metadata(metadataKey, metadataValue);
@@ -13607,17 +13930,294 @@ function _ts_param33(paramIndex, decorator) {
13607
13930
  };
13608
13931
  }
13609
13932
  __name(_ts_param33, "_ts_param");
13610
- var OAUTH_STATE_TTL_SECONDS = 600;
13611
- function isStoredOAuthState(value) {
13612
- if (typeof value !== "object" || value === null) return false;
13613
- const v = value;
13614
- if (typeof v["provider"] !== "string") return false;
13615
- if (typeof v["tenantId"] !== "string") return false;
13616
- if (typeof v["codeVerifier"] !== "string") return false;
13617
- return true;
13618
- }
13619
- __name(isStoredOAuthState, "isStoredOAuthState");
13620
- function base64url(input) {
13933
+ var MfaRequiredGuard = class {
13934
+ static {
13935
+ __name(this, "MfaRequiredGuard");
13936
+ }
13937
+ reflector;
13938
+ constructor(reflector) {
13939
+ this.reflector = reflector;
13940
+ }
13941
+ canActivate(context) {
13942
+ const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13943
+ context.getHandler(),
13944
+ context.getClass()
13945
+ ]);
13946
+ if (skipMfa) return true;
13947
+ const request = context.switchToHttp().getRequest();
13948
+ const user = request.user;
13949
+ if (!user) return true;
13950
+ if (typeof user.mfaEnabled !== "boolean") {
13951
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13952
+ }
13953
+ if (user.mfaEnabled === true && user.mfaVerified !== true) {
13954
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13955
+ }
13956
+ return true;
13957
+ }
13958
+ };
13959
+ MfaRequiredGuard = _ts_decorate54([
13960
+ Injectable(),
13961
+ _ts_param33(0, Inject(Reflector)),
13962
+ _ts_metadata53("design:type", Function),
13963
+ _ts_metadata53("design:paramtypes", [
13964
+ typeof Reflector === "undefined" ? Object : Reflector
13965
+ ])
13966
+ ], MfaRequiredGuard);
13967
+ var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13968
+ var PlatformRoles = /* @__PURE__ */ __name((...roles) => SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13969
+
13970
+ // src/server/guards/platform-roles.guard.ts
13971
+ function _ts_decorate55(decorators, target, key, desc) {
13972
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13973
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13974
+ r = Reflect.decorate(decorators, target, key, desc);
13975
+ } else {
13976
+ for (var i = decorators.length - 1; i >= 0; i--) {
13977
+ if (d = decorators[i]) {
13978
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13979
+ }
13980
+ }
13981
+ }
13982
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13983
+ }
13984
+ __name(_ts_decorate55, "_ts_decorate");
13985
+ function _ts_metadata54(metadataKey, metadataValue) {
13986
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13987
+ return Reflect.metadata(metadataKey, metadataValue);
13988
+ }
13989
+ }
13990
+ __name(_ts_metadata54, "_ts_metadata");
13991
+ function _ts_param34(paramIndex, decorator) {
13992
+ return function(target, key) {
13993
+ decorator(target, key, paramIndex);
13994
+ };
13995
+ }
13996
+ __name(_ts_param34, "_ts_param");
13997
+ var PlatformRolesGuard = class {
13998
+ static {
13999
+ __name(this, "PlatformRolesGuard");
14000
+ }
14001
+ reflector;
14002
+ options;
14003
+ constructor(reflector, options) {
14004
+ this.reflector = reflector;
14005
+ this.options = options;
14006
+ }
14007
+ canActivate(context) {
14008
+ const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
14009
+ context.getHandler(),
14010
+ context.getClass()
14011
+ ]);
14012
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14013
+ const request = context.switchToHttp().getRequest();
14014
+ const user = request.user;
14015
+ if (!user || user.type !== "platform") {
14016
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14017
+ }
14018
+ const userRole = user.role;
14019
+ const hierarchy = this.options.roles.platformHierarchy;
14020
+ if (!hierarchy) {
14021
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14022
+ }
14023
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14024
+ if (!allowed) {
14025
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14026
+ }
14027
+ return true;
14028
+ }
14029
+ };
14030
+ PlatformRolesGuard = _ts_decorate55([
14031
+ Injectable(),
14032
+ _ts_param34(0, Inject(Reflector)),
14033
+ _ts_param34(1, Inject(BYMAX_AUTH_OPTIONS)),
14034
+ _ts_metadata54("design:type", Function),
14035
+ _ts_metadata54("design:paramtypes", [
14036
+ typeof Reflector === "undefined" ? Object : Reflector,
14037
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14038
+ ])
14039
+ ], PlatformRolesGuard);
14040
+ var ROLES_KEY = "roles";
14041
+ var Roles = /* @__PURE__ */ __name((...roles) => SetMetadata(ROLES_KEY, roles), "Roles");
14042
+
14043
+ // src/server/guards/roles.guard.ts
14044
+ function _ts_decorate56(decorators, target, key, desc) {
14045
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14046
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14047
+ r = Reflect.decorate(decorators, target, key, desc);
14048
+ } else {
14049
+ for (var i = decorators.length - 1; i >= 0; i--) {
14050
+ if (d = decorators[i]) {
14051
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14052
+ }
14053
+ }
14054
+ }
14055
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14056
+ }
14057
+ __name(_ts_decorate56, "_ts_decorate");
14058
+ function _ts_metadata55(metadataKey, metadataValue) {
14059
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14060
+ return Reflect.metadata(metadataKey, metadataValue);
14061
+ }
14062
+ }
14063
+ __name(_ts_metadata55, "_ts_metadata");
14064
+ function _ts_param35(paramIndex, decorator) {
14065
+ return function(target, key) {
14066
+ decorator(target, key, paramIndex);
14067
+ };
14068
+ }
14069
+ __name(_ts_param35, "_ts_param");
14070
+ var RolesGuard = class {
14071
+ static {
14072
+ __name(this, "RolesGuard");
14073
+ }
14074
+ reflector;
14075
+ options;
14076
+ constructor(reflector, options) {
14077
+ this.reflector = reflector;
14078
+ this.options = options;
14079
+ }
14080
+ canActivate(context) {
14081
+ const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
14082
+ context.getHandler(),
14083
+ context.getClass()
14084
+ ]);
14085
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14086
+ const request = context.switchToHttp().getRequest();
14087
+ const userRole = request.user?.role;
14088
+ if (!userRole) {
14089
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14090
+ }
14091
+ const hierarchy = this.options.roles.hierarchy;
14092
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14093
+ if (!allowed) {
14094
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14095
+ }
14096
+ return true;
14097
+ }
14098
+ };
14099
+ RolesGuard = _ts_decorate56([
14100
+ Injectable(),
14101
+ _ts_param35(0, Inject(Reflector)),
14102
+ _ts_param35(1, Inject(BYMAX_AUTH_OPTIONS)),
14103
+ _ts_metadata55("design:type", Function),
14104
+ _ts_metadata55("design:paramtypes", [
14105
+ typeof Reflector === "undefined" ? Object : Reflector,
14106
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14107
+ ])
14108
+ ], RolesGuard);
14109
+ function _ts_decorate57(decorators, target, key, desc) {
14110
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14111
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14112
+ r = Reflect.decorate(decorators, target, key, desc);
14113
+ } else {
14114
+ for (var i = decorators.length - 1; i >= 0; i--) {
14115
+ if (d = decorators[i]) {
14116
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14117
+ }
14118
+ }
14119
+ }
14120
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14121
+ }
14122
+ __name(_ts_decorate57, "_ts_decorate");
14123
+ var NoOpAuthHooks = class {
14124
+ static {
14125
+ __name(this, "NoOpAuthHooks");
14126
+ }
14127
+ /**
14128
+ * Permits all registration attempts unconditionally.
14129
+ *
14130
+ * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
14131
+ * @param _context - Hook execution context carrying request metadata.
14132
+ * @returns `{ allowed: true }` — never blocks registration.
14133
+ */
14134
+ beforeRegister(_data, _context) {
14135
+ return {
14136
+ allowed: true
14137
+ };
14138
+ }
14139
+ /**
14140
+ * Resolves OAuth login: creates an account for an unlinked identity, keeps an existing link
14141
+ * when the address still matches and the provider vouches for it, and rejects otherwise.
14142
+ *
14143
+ * @param profile - Normalized OAuth profile from the provider.
14144
+ * @param existingUser - The user already linked to this provider identity, or `null`.
14145
+ * @param _context - Hook execution context carrying request metadata.
14146
+ * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
14147
+ */
14148
+ onOAuthLogin(profile, existingUser, _context) {
14149
+ if (existingUser === null) {
14150
+ return {
14151
+ action: "create"
14152
+ };
14153
+ }
14154
+ if (existingUser.email !== profile.email) {
14155
+ return {
14156
+ action: "reject",
14157
+ reason: "Email mismatch"
14158
+ };
14159
+ }
14160
+ if (profile.emailVerified !== true) {
14161
+ return {
14162
+ action: "reject",
14163
+ reason: "Email not verified"
14164
+ };
14165
+ }
14166
+ return {
14167
+ action: "link"
14168
+ };
14169
+ }
14170
+ };
14171
+ NoOpAuthHooks = _ts_decorate57([
14172
+ Injectable()
14173
+ ], NoOpAuthHooks);
14174
+
14175
+ // src/server/oauth/oauth.constants.ts
14176
+ var OAUTH_PLUGINS = /* @__PURE__ */ Symbol("OAUTH_PLUGINS");
14177
+
14178
+ // src/server/constants/oauth-state-cookie.ts
14179
+ var OAUTH_STATE_COOKIE_NAME = "oauth_state";
14180
+ var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
14181
+ var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
14182
+
14183
+ // src/server/oauth/oauth.service.ts
14184
+ function _ts_decorate58(decorators, target, key, desc) {
14185
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14186
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14187
+ r = Reflect.decorate(decorators, target, key, desc);
14188
+ } else {
14189
+ for (var i = decorators.length - 1; i >= 0; i--) {
14190
+ if (d = decorators[i]) {
14191
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14192
+ }
14193
+ }
14194
+ }
14195
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14196
+ }
14197
+ __name(_ts_decorate58, "_ts_decorate");
14198
+ function _ts_metadata56(metadataKey, metadataValue) {
14199
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14200
+ return Reflect.metadata(metadataKey, metadataValue);
14201
+ }
14202
+ }
14203
+ __name(_ts_metadata56, "_ts_metadata");
14204
+ function _ts_param36(paramIndex, decorator) {
14205
+ return function(target, key) {
14206
+ decorator(target, key, paramIndex);
14207
+ };
14208
+ }
14209
+ __name(_ts_param36, "_ts_param");
14210
+ var OAUTH_STATE_TTL_SECONDS = 600;
14211
+ function isStoredOAuthState(value) {
14212
+ if (typeof value !== "object" || value === null) return false;
14213
+ const v = value;
14214
+ if (typeof v["provider"] !== "string") return false;
14215
+ if (typeof v["tenantId"] !== "string") return false;
14216
+ if (typeof v["codeVerifier"] !== "string") return false;
14217
+ return true;
14218
+ }
14219
+ __name(isStoredOAuthState, "isStoredOAuthState");
14220
+ function base64url(input) {
13621
14221
  return input.toString("base64url");
13622
14222
  }
13623
14223
  __name(base64url, "base64url");
@@ -13861,6 +14461,17 @@ var OAuthService = class _OAuthService {
13861
14461
  });
13862
14462
  }
13863
14463
  this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
14464
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
14465
+ id: safeUser.id,
14466
+ tenantId: safeUser.tenantId
14467
+ }), "oauth: updateLastLogin failed");
14468
+ if (this.hooks?.afterLogin) {
14469
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
14470
+ runDetached(this.logger, () => afterLogin(safeUser, {
14471
+ ...hookContext,
14472
+ userId: safeUser.id
14473
+ }), "oauth: afterLogin hook threw");
14474
+ }
13864
14475
  return result;
13865
14476
  }
13866
14477
  // ---------------------------------------------------------------------------
@@ -13889,18 +14500,18 @@ var OAuthService = class _OAuthService {
13889
14500
  return plugin;
13890
14501
  }
13891
14502
  };
13892
- OAuthService = _ts_decorate55([
14503
+ OAuthService = _ts_decorate58([
13893
14504
  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", [
14505
+ _ts_param36(0, Inject(OAUTH_PLUGINS)),
14506
+ _ts_param36(1, Inject(BYMAX_AUTH_USER_REPOSITORY)),
14507
+ _ts_param36(2, Inject(BYMAX_AUTH_HOOKS)),
14508
+ _ts_param36(2, Optional()),
14509
+ _ts_param36(3, Inject(AuthRedisService)),
14510
+ _ts_param36(4, Inject(TokenManagerService)),
14511
+ _ts_param36(5, Inject(SessionService)),
14512
+ _ts_param36(6, Inject(BYMAX_AUTH_OPTIONS)),
14513
+ _ts_metadata56("design:type", Function),
14514
+ _ts_metadata56("design:paramtypes", [
13904
14515
  Array,
13905
14516
  typeof IUserRepository === "undefined" ? Object : IUserRepository,
13906
14517
  Object,
@@ -13910,7 +14521,7 @@ OAuthService = _ts_decorate55([
13910
14521
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13911
14522
  ])
13912
14523
  ], OAuthService);
13913
- function _ts_decorate56(decorators, target, key, desc) {
14524
+ function _ts_decorate59(decorators, target, key, desc) {
13914
14525
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13915
14526
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13916
14527
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13923,13 +14534,13 @@ function _ts_decorate56(decorators, target, key, desc) {
13923
14534
  }
13924
14535
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13925
14536
  }
13926
- __name(_ts_decorate56, "_ts_decorate");
13927
- function _ts_metadata54(metadataKey, metadataValue) {
14537
+ __name(_ts_decorate59, "_ts_decorate");
14538
+ function _ts_metadata57(metadataKey, metadataValue) {
13928
14539
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13929
14540
  return Reflect.metadata(metadataKey, metadataValue);
13930
14541
  }
13931
14542
  }
13932
- __name(_ts_metadata54, "_ts_metadata");
14543
+ __name(_ts_metadata57, "_ts_metadata");
13933
14544
  var OAuthCallbackQueryDto = class {
13934
14545
  static {
13935
14546
  __name(this, "OAuthCallbackQueryDto");
@@ -14028,69 +14639,69 @@ var OAuthCallbackQueryDto = class {
14028
14639
  */
14029
14640
  hd;
14030
14641
  };
14031
- _ts_decorate56([
14642
+ _ts_decorate59([
14032
14643
  ValidateIf((query) => query.error === void 0 || query.error === null),
14033
14644
  IsOptional(),
14034
14645
  IsString(),
14035
14646
  IsNotEmpty(),
14036
14647
  MaxLength(2048),
14037
- _ts_metadata54("design:type", String)
14648
+ _ts_metadata57("design:type", String)
14038
14649
  ], OAuthCallbackQueryDto.prototype, "code", void 0);
14039
- _ts_decorate56([
14650
+ _ts_decorate59([
14040
14651
  IsOptional(),
14041
14652
  IsString(),
14042
14653
  MaxLength(128),
14043
- _ts_metadata54("design:type", String)
14654
+ _ts_metadata57("design:type", String)
14044
14655
  ], OAuthCallbackQueryDto.prototype, "error", void 0);
14045
- _ts_decorate56([
14656
+ _ts_decorate59([
14046
14657
  IsOptional(),
14047
14658
  IsString(),
14048
14659
  MaxLength(512),
14049
- _ts_metadata54("design:type", String)
14660
+ _ts_metadata57("design:type", String)
14050
14661
  ], OAuthCallbackQueryDto.prototype, "error_description", void 0);
14051
- _ts_decorate56([
14662
+ _ts_decorate59([
14052
14663
  IsOptional(),
14053
14664
  IsString(),
14054
14665
  MaxLength(512),
14055
- _ts_metadata54("design:type", String)
14666
+ _ts_metadata57("design:type", String)
14056
14667
  ], OAuthCallbackQueryDto.prototype, "error_uri", void 0);
14057
- _ts_decorate56([
14668
+ _ts_decorate59([
14058
14669
  IsString(),
14059
14670
  IsNotEmpty(),
14060
14671
  MaxLength(128),
14061
- _ts_metadata54("design:type", String)
14672
+ _ts_metadata57("design:type", String)
14062
14673
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
14063
- _ts_decorate56([
14674
+ _ts_decorate59([
14064
14675
  IsOptional(),
14065
14676
  IsString(),
14066
14677
  MaxLength(512),
14067
- _ts_metadata54("design:type", String)
14678
+ _ts_metadata57("design:type", String)
14068
14679
  ], OAuthCallbackQueryDto.prototype, "iss", void 0);
14069
- _ts_decorate56([
14680
+ _ts_decorate59([
14070
14681
  IsOptional(),
14071
14682
  IsString(),
14072
14683
  MaxLength(2048),
14073
- _ts_metadata54("design:type", String)
14684
+ _ts_metadata57("design:type", String)
14074
14685
  ], OAuthCallbackQueryDto.prototype, "scope", void 0);
14075
- _ts_decorate56([
14686
+ _ts_decorate59([
14076
14687
  IsOptional(),
14077
14688
  IsString(),
14078
14689
  MaxLength(16),
14079
- _ts_metadata54("design:type", String)
14690
+ _ts_metadata57("design:type", String)
14080
14691
  ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
14081
- _ts_decorate56([
14692
+ _ts_decorate59([
14082
14693
  IsOptional(),
14083
14694
  IsString(),
14084
14695
  MaxLength(64),
14085
- _ts_metadata54("design:type", String)
14696
+ _ts_metadata57("design:type", String)
14086
14697
  ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
14087
- _ts_decorate56([
14698
+ _ts_decorate59([
14088
14699
  IsOptional(),
14089
14700
  IsString(),
14090
14701
  MaxLength(253),
14091
- _ts_metadata54("design:type", String)
14702
+ _ts_metadata57("design:type", String)
14092
14703
  ], OAuthCallbackQueryDto.prototype, "hd", void 0);
14093
- function _ts_decorate57(decorators, target, key, desc) {
14704
+ function _ts_decorate60(decorators, target, key, desc) {
14094
14705
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14095
14706
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14096
14707
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14103,13 +14714,13 @@ function _ts_decorate57(decorators, target, key, desc) {
14103
14714
  }
14104
14715
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14105
14716
  }
14106
- __name(_ts_decorate57, "_ts_decorate");
14107
- function _ts_metadata55(metadataKey, metadataValue) {
14717
+ __name(_ts_decorate60, "_ts_decorate");
14718
+ function _ts_metadata58(metadataKey, metadataValue) {
14108
14719
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14109
14720
  return Reflect.metadata(metadataKey, metadataValue);
14110
14721
  }
14111
14722
  }
14112
- __name(_ts_metadata55, "_ts_metadata");
14723
+ __name(_ts_metadata58, "_ts_metadata");
14113
14724
  var OAuthInitiateQueryDto = class {
14114
14725
  static {
14115
14726
  __name(this, "OAuthInitiateQueryDto");
@@ -14126,7 +14737,7 @@ var OAuthInitiateQueryDto = class {
14126
14737
  */
14127
14738
  tenantId;
14128
14739
  };
14129
- _ts_decorate57([
14740
+ _ts_decorate60([
14130
14741
  IsOptional(),
14131
14742
  IsString(),
14132
14743
  IsNotEmpty(),
@@ -14134,11 +14745,11 @@ _ts_decorate57([
14134
14745
  Matches(NO_CONTROL_CHARACTERS, {
14135
14746
  message: "tenantId must not contain control characters"
14136
14747
  }),
14137
- _ts_metadata55("design:type", String)
14748
+ _ts_metadata58("design:type", String)
14138
14749
  ], OAuthInitiateQueryDto.prototype, "tenantId", void 0);
14139
14750
 
14140
14751
  // src/server/oauth/oauth.controller.ts
14141
- function _ts_decorate58(decorators, target, key, desc) {
14752
+ function _ts_decorate61(decorators, target, key, desc) {
14142
14753
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14143
14754
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14144
14755
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14151,19 +14762,19 @@ function _ts_decorate58(decorators, target, key, desc) {
14151
14762
  }
14152
14763
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14153
14764
  }
14154
- __name(_ts_decorate58, "_ts_decorate");
14155
- function _ts_metadata56(metadataKey, metadataValue) {
14765
+ __name(_ts_decorate61, "_ts_decorate");
14766
+ function _ts_metadata59(metadataKey, metadataValue) {
14156
14767
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14157
14768
  return Reflect.metadata(metadataKey, metadataValue);
14158
14769
  }
14159
14770
  }
14160
- __name(_ts_metadata56, "_ts_metadata");
14161
- function _ts_param34(paramIndex, decorator) {
14771
+ __name(_ts_metadata59, "_ts_metadata");
14772
+ function _ts_param37(paramIndex, decorator) {
14162
14773
  return function(target, key) {
14163
14774
  decorator(target, key, paramIndex);
14164
14775
  };
14165
14776
  }
14166
- __name(_ts_param34, "_ts_param");
14777
+ __name(_ts_param37, "_ts_param");
14167
14778
  function isOAuthMfaChallenge(result) {
14168
14779
  return "mfaRequired" in result && result.mfaRequired === true;
14169
14780
  }
@@ -14381,46 +14992,46 @@ var OAuthController = class _OAuthController {
14381
14992
  });
14382
14993
  }
14383
14994
  };
14384
- _ts_decorate58([
14995
+ _ts_decorate61([
14385
14996
  Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14386
14997
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14387
14998
  Get(":provider"),
14388
- _ts_param34(0, Param("provider")),
14389
- _ts_param34(1, Query()),
14390
- _ts_param34(2, Req()),
14391
- _ts_param34(3, Res({
14999
+ _ts_param37(0, Param("provider")),
15000
+ _ts_param37(1, Query()),
15001
+ _ts_param37(2, Req()),
15002
+ _ts_param37(3, Res({
14392
15003
  passthrough: true
14393
15004
  })),
14394
- _ts_metadata56("design:type", Function),
14395
- _ts_metadata56("design:paramtypes", [
15005
+ _ts_metadata59("design:type", Function),
15006
+ _ts_metadata59("design:paramtypes", [
14396
15007
  String,
14397
15008
  typeof OAuthInitiateQueryDto === "undefined" ? Object : OAuthInitiateQueryDto,
14398
15009
  typeof Request === "undefined" ? Object : Request,
14399
15010
  typeof Response === "undefined" ? Object : Response
14400
15011
  ]),
14401
- _ts_metadata56("design:returntype", Promise)
15012
+ _ts_metadata59("design:returntype", Promise)
14402
15013
  ], OAuthController.prototype, "initiate", null);
14403
- _ts_decorate58([
15014
+ _ts_decorate61([
14404
15015
  Throttle(AUTH_THROTTLE_CONFIGS.oauthCallback),
14405
15016
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthCallback),
14406
15017
  HttpCode(HttpStatus.OK),
14407
15018
  Get(":provider/callback"),
14408
- _ts_param34(0, Param("provider")),
14409
- _ts_param34(1, Query()),
14410
- _ts_param34(2, Req()),
14411
- _ts_param34(3, Res({
15019
+ _ts_param37(0, Param("provider")),
15020
+ _ts_param37(1, Query()),
15021
+ _ts_param37(2, Req()),
15022
+ _ts_param37(3, Res({
14412
15023
  passthrough: true
14413
15024
  })),
14414
- _ts_metadata56("design:type", Function),
14415
- _ts_metadata56("design:paramtypes", [
15025
+ _ts_metadata59("design:type", Function),
15026
+ _ts_metadata59("design:paramtypes", [
14416
15027
  String,
14417
15028
  typeof OAuthCallbackQueryDto === "undefined" ? Object : OAuthCallbackQueryDto,
14418
15029
  typeof Request === "undefined" ? Object : Request,
14419
15030
  typeof Response === "undefined" ? Object : Response
14420
15031
  ]),
14421
- _ts_metadata56("design:returntype", Promise)
15032
+ _ts_metadata59("design:returntype", Promise)
14422
15033
  ], OAuthController.prototype, "callback", null);
14423
- OAuthController = _ts_decorate58([
15034
+ OAuthController = _ts_decorate61([
14424
15035
  Public(),
14425
15036
  SkipMfa(),
14426
15037
  UseInterceptors(NoStoreInterceptor),
@@ -14429,11 +15040,11 @@ OAuthController = _ts_decorate58([
14429
15040
  UsePipes(createAuthValidationPipe({
14430
15041
  forbidUnknownValues: true
14431
15042
  })),
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", [
15043
+ _ts_param37(0, Inject(OAuthService)),
15044
+ _ts_param37(1, Inject(TokenDeliveryService)),
15045
+ _ts_param37(2, Inject(BYMAX_AUTH_OPTIONS)),
15046
+ _ts_metadata59("design:type", Function),
15047
+ _ts_metadata59("design:paramtypes", [
14437
15048
  typeof OAuthService === "undefined" ? Object : OAuthService,
14438
15049
  typeof TokenDeliveryService === "undefined" ? Object : TokenDeliveryService,
14439
15050
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -14572,7 +15183,7 @@ var GoogleOAuthPlugin = class {
14572
15183
  };
14573
15184
 
14574
15185
  // src/server/oauth/oauth.module.ts
14575
- function _ts_decorate59(decorators, target, key, desc) {
15186
+ function _ts_decorate62(decorators, target, key, desc) {
14576
15187
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14577
15188
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14578
15189
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14585,7 +15196,7 @@ function _ts_decorate59(decorators, target, key, desc) {
14585
15196
  }
14586
15197
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14587
15198
  }
14588
- __name(_ts_decorate59, "_ts_decorate");
15199
+ __name(_ts_decorate62, "_ts_decorate");
14589
15200
  function buildOAuthPlugins(options) {
14590
15201
  const plugins = [];
14591
15202
  if (options.oauth?.google) {
@@ -14655,7 +15266,7 @@ var OAuthModule = class _OAuthModule {
14655
15266
  };
14656
15267
  }
14657
15268
  };
14658
- OAuthModule = _ts_decorate59([
15269
+ OAuthModule = _ts_decorate62([
14659
15270
  Module({})
14660
15271
  ], OAuthModule);
14661
15272
 
@@ -15549,7 +16160,7 @@ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
15549
16160
  __name(schemesFor, "schemesFor");
15550
16161
 
15551
16162
  // src/server/openapi/auth-openapi.contributor.ts
15552
- function _ts_decorate60(decorators, target, key, desc) {
16163
+ function _ts_decorate63(decorators, target, key, desc) {
15553
16164
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15554
16165
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15555
16166
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15562,19 +16173,19 @@ function _ts_decorate60(decorators, target, key, desc) {
15562
16173
  }
15563
16174
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15564
16175
  }
15565
- __name(_ts_decorate60, "_ts_decorate");
15566
- function _ts_metadata57(metadataKey, metadataValue) {
16176
+ __name(_ts_decorate63, "_ts_decorate");
16177
+ function _ts_metadata60(metadataKey, metadataValue) {
15567
16178
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15568
16179
  return Reflect.metadata(metadataKey, metadataValue);
15569
16180
  }
15570
16181
  }
15571
- __name(_ts_metadata57, "_ts_metadata");
15572
- function _ts_param35(paramIndex, decorator) {
16182
+ __name(_ts_metadata60, "_ts_metadata");
16183
+ function _ts_param38(paramIndex, decorator) {
15573
16184
  return function(target, key) {
15574
16185
  decorator(target, key, paramIndex);
15575
16186
  };
15576
16187
  }
15577
- __name(_ts_param35, "_ts_param");
16188
+ __name(_ts_param38, "_ts_param");
15578
16189
  var AuthOpenApiContributor = class {
15579
16190
  static {
15580
16191
  __name(this, "AuthOpenApiContributor");
@@ -15594,18 +16205,18 @@ var AuthOpenApiContributor = class {
15594
16205
  return buildAuthOpenApiFragment(this.options, this.registered);
15595
16206
  }
15596
16207
  };
15597
- AuthOpenApiContributor = _ts_decorate60([
16208
+ AuthOpenApiContributor = _ts_decorate63([
15598
16209
  Injectable(),
15599
16210
  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", [
16211
+ _ts_param38(0, Inject(BYMAX_AUTH_OPTIONS)),
16212
+ _ts_param38(1, Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
16213
+ _ts_metadata60("design:type", Function),
16214
+ _ts_metadata60("design:paramtypes", [
15604
16215
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
15605
16216
  typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
15606
16217
  ])
15607
16218
  ], AuthOpenApiContributor);
15608
- function _ts_decorate61(decorators, target, key, desc) {
16219
+ function _ts_decorate64(decorators, target, key, desc) {
15609
16220
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15610
16221
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15611
16222
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15618,19 +16229,19 @@ function _ts_decorate61(decorators, target, key, desc) {
15618
16229
  }
15619
16230
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15620
16231
  }
15621
- __name(_ts_decorate61, "_ts_decorate");
15622
- function _ts_metadata58(metadataKey, metadataValue) {
16232
+ __name(_ts_decorate64, "_ts_decorate");
16233
+ function _ts_metadata61(metadataKey, metadataValue) {
15623
16234
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15624
16235
  return Reflect.metadata(metadataKey, metadataValue);
15625
16236
  }
15626
16237
  }
15627
- __name(_ts_metadata58, "_ts_metadata");
15628
- function _ts_param36(paramIndex, decorator) {
16238
+ __name(_ts_metadata61, "_ts_metadata");
16239
+ function _ts_param39(paramIndex, decorator) {
15629
16240
  return function(target, key) {
15630
16241
  decorator(target, key, paramIndex);
15631
16242
  };
15632
16243
  }
15633
- __name(_ts_param36, "_ts_param");
16244
+ __name(_ts_param39, "_ts_param");
15634
16245
  var COMMON_BASE_WORDS = [
15635
16246
  // The perennial top of every published list.
15636
16247
  "password",
@@ -15936,16 +16547,16 @@ var CommonPasswordChecker = class {
15936
16547
  return false;
15937
16548
  }
15938
16549
  };
15939
- CommonPasswordChecker = _ts_decorate61([
16550
+ CommonPasswordChecker = _ts_decorate64([
15940
16551
  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", [
16552
+ _ts_param39(0, Inject(BYMAX_AUTH_OPTIONS)),
16553
+ _ts_param39(0, Optional()),
16554
+ _ts_metadata61("design:type", Function),
16555
+ _ts_metadata61("design:paramtypes", [
15945
16556
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
15946
16557
  ])
15947
16558
  ], CommonPasswordChecker);
15948
- function _ts_decorate62(decorators, target, key, desc) {
16559
+ function _ts_decorate65(decorators, target, key, desc) {
15949
16560
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15950
16561
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15951
16562
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15958,7 +16569,7 @@ function _ts_decorate62(decorators, target, key, desc) {
15958
16569
  }
15959
16570
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15960
16571
  }
15961
- __name(_ts_decorate62, "_ts_decorate");
16572
+ __name(_ts_decorate65, "_ts_decorate");
15962
16573
  var NoOpEmailProvider = class _NoOpEmailProvider {
15963
16574
  static {
15964
16575
  __name(this, "NoOpEmailProvider");
@@ -15993,10 +16604,21 @@ var NoOpEmailProvider = class _NoOpEmailProvider {
15993
16604
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
15994
16605
  }
15995
16606
  };
15996
- NoOpEmailProvider = _ts_decorate62([
16607
+ NoOpEmailProvider = _ts_decorate65([
15997
16608
  Injectable()
15998
16609
  ], NoOpEmailProvider);
15999
- function _ts_decorate63(decorators, target, key, desc) {
16610
+
16611
+ // src/server/services/api-key-clock.ts
16612
+ var SystemApiKeyClock = class {
16613
+ static {
16614
+ __name(this, "SystemApiKeyClock");
16615
+ }
16616
+ /** @returns The current instant. */
16617
+ now() {
16618
+ return /* @__PURE__ */ new Date();
16619
+ }
16620
+ };
16621
+ function _ts_decorate66(decorators, target, key, desc) {
16000
16622
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16001
16623
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16002
16624
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16009,20 +16631,330 @@ function _ts_decorate63(decorators, target, key, desc) {
16009
16631
  }
16010
16632
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16011
16633
  }
16012
- __name(_ts_decorate63, "_ts_decorate");
16013
- function _ts_metadata59(metadataKey, metadataValue) {
16634
+ __name(_ts_decorate66, "_ts_decorate");
16635
+ function _ts_metadata62(metadataKey, metadataValue) {
16014
16636
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16015
16637
  return Reflect.metadata(metadataKey, metadataValue);
16016
16638
  }
16017
16639
  }
16018
- __name(_ts_metadata59, "_ts_metadata");
16019
- function _ts_param37(paramIndex, decorator) {
16640
+ __name(_ts_metadata62, "_ts_metadata");
16641
+ function _ts_param40(paramIndex, decorator) {
16020
16642
  return function(target, key) {
16021
16643
  decorator(target, key, paramIndex);
16022
16644
  };
16023
16645
  }
16024
- __name(_ts_param37, "_ts_param");
16025
- var AuthTokenVerifierService = class {
16646
+ __name(_ts_param40, "_ts_param");
16647
+ var ApiKeyScopeAuditService = class {
16648
+ static {
16649
+ __name(this, "ApiKeyScopeAuditService");
16650
+ }
16651
+ discovery;
16652
+ scanner;
16653
+ reflector;
16654
+ options;
16655
+ constructor(discovery, scanner, reflector, options) {
16656
+ this.discovery = discovery;
16657
+ this.scanner = scanner;
16658
+ this.reflector = reflector;
16659
+ this.options = options;
16660
+ }
16661
+ /** @throws {Error} Naming every route that declares a scope the vocabulary lacks. */
16662
+ onApplicationBootstrap() {
16663
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16664
+ const problems = [];
16665
+ for (const wrapper of this.discovery.getControllers()) {
16666
+ const { instance, metatype } = wrapper;
16667
+ if (!instance || typeof metatype !== "function") continue;
16668
+ this.collect(problems, vocabulary, metatype.name, this.reflector.get(API_KEY_SCOPES_KEY, metatype));
16669
+ const prototype = Object.getPrototypeOf(instance);
16670
+ for (const method of this.scanner.getAllMethodNames(prototype)) {
16671
+ const handler = prototype[method];
16672
+ this.collect(problems, vocabulary, `${metatype.name}.${method}`, this.reflector.get(API_KEY_SCOPES_KEY, handler));
16673
+ }
16674
+ }
16675
+ if (problems.length > 0) {
16676
+ throw new Error(`[BymaxAuthModule] ${problems.join("; ")}. Add the scope to apiKeys.scopes or correct the declaration.`);
16677
+ }
16678
+ }
16679
+ collect(problems, vocabulary, where, declared) {
16680
+ if (!Array.isArray(declared)) return;
16681
+ for (const scope of declared) {
16682
+ if (!vocabulary.has(scope)) {
16683
+ problems.push(`${where} declares a scope outside apiKeys.scopes`);
16684
+ return;
16685
+ }
16686
+ }
16687
+ }
16688
+ };
16689
+ ApiKeyScopeAuditService = _ts_decorate66([
16690
+ Injectable(),
16691
+ _ts_param40(0, Inject(DiscoveryService)),
16692
+ _ts_param40(1, Inject(MetadataScanner)),
16693
+ _ts_param40(2, Inject(Reflector)),
16694
+ _ts_param40(3, Inject(BYMAX_AUTH_OPTIONS)),
16695
+ _ts_metadata62("design:type", Function),
16696
+ _ts_metadata62("design:paramtypes", [
16697
+ typeof DiscoveryService === "undefined" ? Object : DiscoveryService,
16698
+ typeof MetadataScanner === "undefined" ? Object : MetadataScanner,
16699
+ typeof Reflector === "undefined" ? Object : Reflector,
16700
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16701
+ ])
16702
+ ], ApiKeyScopeAuditService);
16703
+ function _ts_decorate67(decorators, target, key, desc) {
16704
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16705
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16706
+ r = Reflect.decorate(decorators, target, key, desc);
16707
+ } else {
16708
+ for (var i = decorators.length - 1; i >= 0; i--) {
16709
+ if (d = decorators[i]) {
16710
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16711
+ }
16712
+ }
16713
+ }
16714
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16715
+ }
16716
+ __name(_ts_decorate67, "_ts_decorate");
16717
+ function _ts_metadata63(metadataKey, metadataValue) {
16718
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16719
+ return Reflect.metadata(metadataKey, metadataValue);
16720
+ }
16721
+ }
16722
+ __name(_ts_metadata63, "_ts_metadata");
16723
+ function _ts_param41(paramIndex, decorator) {
16724
+ return function(target, key) {
16725
+ decorator(target, key, paramIndex);
16726
+ };
16727
+ }
16728
+ __name(_ts_param41, "_ts_param");
16729
+ var API_KEY_MAX_LABEL_LENGTH = 128;
16730
+ var API_KEY_MAX_OVERLAP_SECONDS = 2592e3;
16731
+ var CONTROL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
16732
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
16733
+ var ApiKeyService = class {
16734
+ static {
16735
+ __name(this, "ApiKeyService");
16736
+ }
16737
+ repository;
16738
+ clock;
16739
+ options;
16740
+ constructor(repository, clock, options) {
16741
+ this.repository = repository;
16742
+ this.clock = clock;
16743
+ this.options = options;
16744
+ }
16745
+ /**
16746
+ * Issues a new key.
16747
+ *
16748
+ * @param input - Label, scopes and optional expiry.
16749
+ * @returns The plaintext key (once) and the stored record.
16750
+ * @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
16751
+ */
16752
+ async issue(input) {
16753
+ const now = this.clock.now();
16754
+ const label = this.validatedLabel(input.label);
16755
+ const scopes = this.validatedScopes(input.scopes);
16756
+ const expiresAt = this.validatedExpiry("expiresAt", input.expiresAt, now);
16757
+ const id = randomUUID();
16758
+ const secret = generateApiKeySecret();
16759
+ const stored = await this.repository.create({
16760
+ id,
16761
+ label,
16762
+ digest: apiKeyDigest(secret, this.options.apiKeys.pepper),
16763
+ scopes,
16764
+ createdAt: now,
16765
+ expiresAt
16766
+ });
16767
+ return {
16768
+ key: formatApiKey(this.options.apiKeys.prefix, id, secret),
16769
+ record: summary(stored)
16770
+ };
16771
+ }
16772
+ /**
16773
+ * Revokes a key now. Revoking an already revoked key succeeds.
16774
+ *
16775
+ * @param id - The key's row id.
16776
+ * @throws {AuthException} `auth.api_key_not_found` when no such key exists.
16777
+ */
16778
+ async revoke(id) {
16779
+ if (!UUID_PATTERN.test(id) || !await this.repository.markRevoked(id, this.clock.now())) {
16780
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16781
+ }
16782
+ }
16783
+ /**
16784
+ * Replaces a key with a new one carrying the same label and scopes.
16785
+ *
16786
+ * The new key is issued first and the old one retired second, so a failure between the two
16787
+ * leaves both valid — the safe direction — rather than neither.
16788
+ *
16789
+ * @param id - The active key to replace.
16790
+ * @param input - The overlap and an optional expiry for the new key.
16791
+ * @returns The new key, plaintext once.
16792
+ * @throws {AuthException} `auth.validation` for a bad overlap or expiry;
16793
+ * `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
16794
+ * rotated: that would re-issue access nobody holds).
16795
+ */
16796
+ async rotate(id, input) {
16797
+ const now = this.clock.now();
16798
+ const overlap = input.overlapSeconds;
16799
+ if (!Number.isInteger(overlap) || overlap < 0 || overlap > API_KEY_MAX_OVERLAP_SECONDS) {
16800
+ throw validation("overlapSeconds", `overlapSeconds must be an integer from 0 to ${API_KEY_MAX_OVERLAP_SECONDS}`);
16801
+ }
16802
+ const newExpiry = this.validatedExpiry("expiresAt", input.expiresAt, now);
16803
+ const old = UUID_PATTERN.test(id) ? await this.repository.findById(id) : null;
16804
+ if (old === null || !isActive(old, now)) {
16805
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16806
+ }
16807
+ const issued = await this.issue({
16808
+ label: old.label,
16809
+ scopes: old.scopes,
16810
+ ...newExpiry === null ? {} : {
16811
+ expiresAt: newExpiry
16812
+ }
16813
+ });
16814
+ if (overlap === 0) {
16815
+ await this.repository.markRevoked(old.id, now);
16816
+ } else {
16817
+ const retireAt = new Date(now.getTime() + overlap * 1e3);
16818
+ const sooner = (
16819
+ // Stryker disable next-line EqualityOperator: at equal instants both arms yield a Date of the same time, so `<` and `<=` store the same expiry
16820
+ old.expiresAt !== null && old.expiresAt.getTime() < retireAt.getTime() ? old.expiresAt : retireAt
16821
+ );
16822
+ await this.repository.setExpiry(old.id, sooner);
16823
+ }
16824
+ return issued;
16825
+ }
16826
+ validatedLabel(label) {
16827
+ if (typeof label !== "string" || label.trim().length === 0 || label.length > API_KEY_MAX_LABEL_LENGTH || CONTROL_CHARACTERS.test(label)) {
16828
+ throw validation("label", `label must be 1 to ${API_KEY_MAX_LABEL_LENGTH} characters with no control characters`);
16829
+ }
16830
+ return label;
16831
+ }
16832
+ validatedScopes(scopes) {
16833
+ if (!Array.isArray(scopes) || scopes.length === 0) {
16834
+ throw validation("scopes", "scopes must be a non-empty list");
16835
+ }
16836
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16837
+ const seen = /* @__PURE__ */ new Set();
16838
+ for (const scope of scopes) {
16839
+ if (!vocabulary.has(scope)) {
16840
+ throw validation("scopes", "every scope must come from the configured vocabulary");
16841
+ }
16842
+ if (seen.has(scope)) throw validation("scopes", "scopes must not repeat");
16843
+ seen.add(scope);
16844
+ }
16845
+ return [
16846
+ ...scopes
16847
+ ];
16848
+ }
16849
+ validatedExpiry(field, value, now) {
16850
+ if (value === void 0) return null;
16851
+ if (!(value instanceof Date) || Number.isNaN(value.getTime()) || value.getTime() <= now.getTime()) {
16852
+ throw validation(field, `${field} must be a valid date in the future`);
16853
+ }
16854
+ return value;
16855
+ }
16856
+ };
16857
+ ApiKeyService = _ts_decorate67([
16858
+ Injectable(),
16859
+ _ts_param41(0, Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
16860
+ _ts_param41(1, Inject(BYMAX_AUTH_API_KEY_CLOCK)),
16861
+ _ts_param41(2, Inject(BYMAX_AUTH_OPTIONS)),
16862
+ _ts_metadata63("design:type", Function),
16863
+ _ts_metadata63("design:paramtypes", [
16864
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
16865
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
16866
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16867
+ ])
16868
+ ], ApiKeyService);
16869
+ function isActive(key, now) {
16870
+ const nowMs = now.getTime();
16871
+ return key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > nowMs);
16872
+ }
16873
+ __name(isActive, "isActive");
16874
+ function summary(row) {
16875
+ const { digest: _digest, ...rest } = row;
16876
+ return rest;
16877
+ }
16878
+ __name(summary, "summary");
16879
+ function validation(field, message) {
16880
+ return new AuthException(AUTH_ERROR_CODES.VALIDATION, [
16881
+ {
16882
+ field,
16883
+ message
16884
+ }
16885
+ ]);
16886
+ }
16887
+ __name(validation, "validation");
16888
+
16889
+ // src/server/utils/handshake-request.ts
16890
+ function handshakeRequest(handshake) {
16891
+ const headers = {};
16892
+ for (const [name, value] of Object.entries(handshake.headers)) {
16893
+ headers[name.toLowerCase()] = value;
16894
+ }
16895
+ return {
16896
+ headers,
16897
+ url: handshake.url ?? "",
16898
+ hostname: hostnameOf(headers["host"])
16899
+ };
16900
+ }
16901
+ __name(handshakeRequest, "handshakeRequest");
16902
+ function hostnameOf(host) {
16903
+ if (typeof host !== "string") return "";
16904
+ const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
16905
+ const index = host.indexOf(":", offset);
16906
+ return index === -1 ? host : host.substring(0, index);
16907
+ }
16908
+ __name(hostnameOf, "hostnameOf");
16909
+
16910
+ // src/server/utils/assert-tenant-binding.ts
16911
+ function tenantBindingEnforced(options) {
16912
+ return options.enforceTenantBinding === true && options.tenantIdResolver !== void 0;
16913
+ }
16914
+ __name(tenantBindingEnforced, "tenantBindingEnforced");
16915
+ async function assertTenantBinding(options, handshake, tenantId) {
16916
+ const resolver = options.tenantIdResolver;
16917
+ if (options.enforceTenantBinding !== true || !resolver) return;
16918
+ let requestTenant;
16919
+ try {
16920
+ requestTenant = await resolver(handshakeRequest(handshake));
16921
+ } catch {
16922
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16923
+ }
16924
+ if (requestTenant !== tenantId) {
16925
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16926
+ }
16927
+ }
16928
+ __name(assertTenantBinding, "assertTenantBinding");
16929
+
16930
+ // src/server/services/auth-token-verifier.service.ts
16931
+ function _ts_decorate68(decorators, target, key, desc) {
16932
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16933
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16934
+ r = Reflect.decorate(decorators, target, key, desc);
16935
+ } else {
16936
+ for (var i = decorators.length - 1; i >= 0; i--) {
16937
+ if (d = decorators[i]) {
16938
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16939
+ }
16940
+ }
16941
+ }
16942
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16943
+ }
16944
+ __name(_ts_decorate68, "_ts_decorate");
16945
+ function _ts_metadata64(metadataKey, metadataValue) {
16946
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16947
+ return Reflect.metadata(metadataKey, metadataValue);
16948
+ }
16949
+ }
16950
+ __name(_ts_metadata64, "_ts_metadata");
16951
+ function _ts_param42(paramIndex, decorator) {
16952
+ return function(target, key) {
16953
+ decorator(target, key, paramIndex);
16954
+ };
16955
+ }
16956
+ __name(_ts_param42, "_ts_param");
16957
+ var AuthTokenVerifierService = class _AuthTokenVerifierService {
16026
16958
  static {
16027
16959
  __name(this, "AuthTokenVerifierService");
16028
16960
  }
@@ -16030,6 +16962,9 @@ var AuthTokenVerifierService = class {
16030
16962
  options;
16031
16963
  revocation;
16032
16964
  accountStatus;
16965
+ logger = new Logger(_AuthTokenVerifierService.name);
16966
+ /** Whether the "binding not applied" warning has been logged by this instance. */
16967
+ warnedUnbound = false;
16033
16968
  /**
16034
16969
  * @param jwtService - The Nest JWT service, configured with the current signing secret.
16035
16970
  * @param options - Resolved module options, for the algorithm, the binding claims and the
@@ -16073,7 +17008,9 @@ var AuthTokenVerifierService = class {
16073
17008
  */
16074
17009
  async verifyAccessToken(token, options) {
16075
17010
  const { plane, requireMfa = true, checkStatus = true } = options;
16076
- if (plane === "dashboard") return await this.verifyDashboard(token, requireMfa, checkStatus);
17011
+ if (plane === "dashboard") {
17012
+ return await this.verifyDashboard(token, requireMfa, checkStatus, options.request);
17013
+ }
16077
17014
  if (plane === "platform") return await this.verifyPlatform(token, requireMfa, checkStatus);
16078
17015
  throw new TypeError(`verifyAccessToken: plane must be 'dashboard' or 'platform'`);
16079
17016
  }
@@ -16083,10 +17020,11 @@ var AuthTokenVerifierService = class {
16083
17020
  * @param token - The compact JWT.
16084
17021
  * @param requireMfa - Whether to apply the MFA policy.
16085
17022
  * @param checkStatus - Whether to consult the account's current status.
17023
+ * @param request - The request the token arrived on, for `enforceTenantBinding`.
16086
17024
  * @returns The verified dashboard payload.
16087
17025
  * @throws {@link AuthException} as {@link verifyAccessToken} documents.
16088
17026
  */
16089
- async verifyDashboard(token, requireMfa, checkStatus) {
17027
+ async verifyDashboard(token, requireMfa, checkStatus, request) {
16090
17028
  const payload = this.verifySignature(token);
16091
17029
  assertValidJti(payload.jti);
16092
17030
  assertValidSub(payload.sub);
@@ -16095,6 +17033,7 @@ var AuthTokenVerifierService = class {
16095
17033
  if (await this.revocation.isAccessTokenRevoked(payload, "dashboard")) {
16096
17034
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16097
17035
  }
17036
+ await this.assertBound(payload.tenantId, request);
16098
17037
  if (requireMfa) this.assertMfaClaimShape(payload);
16099
17038
  if (checkStatus) {
16100
17039
  await this.accountStatus.assertDashboardAccountUsable({
@@ -16109,6 +17048,23 @@ var AuthTokenVerifierService = class {
16109
17048
  };
16110
17049
  }
16111
17050
  /**
17051
+ * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
17052
+ *
17053
+ * @param tenantId - The tenant the token was issued for.
17054
+ * @param request - The request the token arrived on, when the caller supplied one.
17055
+ * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
17056
+ */
17057
+ async assertBound(tenantId, request) {
17058
+ if (request !== void 0) {
17059
+ await assertTenantBinding(this.options, request, tenantId);
17060
+ return;
17061
+ }
17062
+ if (tenantBindingEnforced(this.options) && !this.warnedUnbound) {
17063
+ this.warnedUnbound = true;
17064
+ 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`.");
17065
+ }
17066
+ }
17067
+ /**
16112
17068
  * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
16113
17069
  * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
16114
17070
  *
@@ -16181,14 +17137,14 @@ var AuthTokenVerifierService = class {
16181
17137
  }
16182
17138
  }
16183
17139
  };
16184
- AuthTokenVerifierService = _ts_decorate63([
17140
+ AuthTokenVerifierService = _ts_decorate68([
16185
17141
  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", [
17142
+ _ts_param42(0, Inject(JwtService)),
17143
+ _ts_param42(1, Inject(BYMAX_AUTH_OPTIONS)),
17144
+ _ts_param42(2, Inject(AuthRevocationService)),
17145
+ _ts_param42(3, Inject(AccountStatusService)),
17146
+ _ts_metadata64("design:type", Function),
17147
+ _ts_metadata64("design:paramtypes", [
16192
17148
  typeof JwtService === "undefined" ? Object : JwtService,
16193
17149
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
16194
17150
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
@@ -16197,7 +17153,7 @@ AuthTokenVerifierService = _ts_decorate63([
16197
17153
  ], AuthTokenVerifierService);
16198
17154
 
16199
17155
  // src/server/bymax-auth.module.ts
16200
- function _ts_decorate64(decorators, target, key, desc) {
17156
+ function _ts_decorate69(decorators, target, key, desc) {
16201
17157
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16202
17158
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16203
17159
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16210,7 +17166,7 @@ function _ts_decorate64(decorators, target, key, desc) {
16210
17166
  }
16211
17167
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16212
17168
  }
16213
- __name(_ts_decorate64, "_ts_decorate");
17169
+ __name(_ts_decorate69, "_ts_decorate");
16214
17170
  function hasProviderToken(providers, token) {
16215
17171
  return providers.some((p) => {
16216
17172
  if (typeof p === "function") return false;
@@ -16218,6 +17174,15 @@ function hasProviderToken(providers, token) {
16218
17174
  });
16219
17175
  }
16220
17176
  __name(hasProviderToken, "hasProviderToken");
17177
+ function cannotAuditApiKeys(providers) {
17178
+ const hooks = providers.find((p) => "provide" in p && p.provide === BYMAX_AUTH_HOOKS);
17179
+ if (hooks === void 0) return true;
17180
+ if ("useValue" in hooks) {
17181
+ return typeof hooks.useValue?.onApiKeyRequest !== "function";
17182
+ }
17183
+ return false;
17184
+ }
17185
+ __name(cannotAuditApiKeys, "cannotAuditApiKeys");
16221
17186
  var BymaxAuthModule = class _BymaxAuthModule {
16222
17187
  static {
16223
17188
  __name(this, "BymaxAuthModule");
@@ -16245,6 +17210,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
16245
17210
  const includePlatform = options.controllers?.platform === true;
16246
17211
  const includeOAuth = options.controllers?.oauth === true;
16247
17212
  const includeInvitations = options.controllers?.invitations === true;
17213
+ const includeApiKeys = hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_REPOSITORY);
16248
17214
  const includeEmailChange = options.controllers?.emailChange === true;
16249
17215
  const resolvedOptionsProvider = {
16250
17216
  provide: BYMAX_AUTH_OPTIONS,
@@ -16278,10 +17244,29 @@ var BymaxAuthModule = class _BymaxAuthModule {
16278
17244
  if (includeInvitations && !resolved.invitations?.enabled) {
16279
17245
  throw new Error("[BymaxAuthModule] controllers.invitations: true requires invitations.enabled: true in the useFactory return value.");
16280
17246
  }
17247
+ if (includeApiKeys !== resolved.apiKeys.enabled) {
17248
+ 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.");
17249
+ }
17250
+ if (resolved.apiKeys.auditMode === "required" && cannotAuditApiKeys(extraProviders)) {
17251
+ 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'.");
17252
+ }
16281
17253
  return resolved;
16282
17254
  }, "useFactory"),
16283
17255
  inject: options.inject ?? []
16284
17256
  };
17257
+ const apiKeyProviders = includeApiKeys ? [
17258
+ ...hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_CLOCK) ? [] : [
17259
+ {
17260
+ provide: BYMAX_AUTH_API_KEY_CLOCK,
17261
+ useClass: SystemApiKeyClock
17262
+ }
17263
+ ],
17264
+ ApiKeyLastUsedService,
17265
+ ApiKeyVerifierService,
17266
+ ApiKeyService,
17267
+ ApiKeyGuard,
17268
+ ApiKeyScopeAuditService
17269
+ ] : [];
16285
17270
  const emailProviders = hasProviderToken(extraProviders, BYMAX_AUTH_EMAIL_PROVIDER) ? [] : [
16286
17271
  {
16287
17272
  provide: BYMAX_AUTH_EMAIL_PROVIDER,
@@ -16362,6 +17347,10 @@ var BymaxAuthModule = class _BymaxAuthModule {
16362
17347
  module: _BymaxAuthModule,
16363
17348
  imports: [
16364
17349
  ...options.imports ?? [],
17350
+ // The bootstrap scope audit walks controllers through the discovery service.
17351
+ ...includeApiKeys ? [
17352
+ DiscoveryModule
17353
+ ] : [],
16365
17354
  // JwtModule reads the secret directly from the consumer factory (without re-running
16366
17355
  // resolveOptions) to avoid double-validation on startup. Full validation happens once
16367
17356
  // in the BYMAX_AUTH_OPTIONS provider above.
@@ -16455,7 +17444,9 @@ var BymaxAuthModule = class _BymaxAuthModule {
16455
17444
  // Invitation service — only when controllers.invitations: true.
16456
17445
  ...invitationProviders,
16457
17446
  // Address-change service — only when controllers.emailChange: true.
16458
- ...emailChangeProviders
17447
+ ...emailChangeProviders,
17448
+ // Service API keys — only when the host supplied the repository.
17449
+ ...apiKeyProviders
16459
17450
  ],
16460
17451
  controllers,
16461
17452
  exports: [
@@ -16543,6 +17534,15 @@ var BymaxAuthModule = class _BymaxAuthModule {
16543
17534
  // export BYMAX_AUTH_USER_REPOSITORY as the instance supplied by the consumer` test, which
16544
17535
  // is the one that fails without it.
16545
17536
  BYMAX_AUTH_USER_REPOSITORY,
17537
+ // Service API keys: the guard is re-instantiated in the consumer's injector by
17538
+ // `@ServiceKey()`, so its direct dependencies must be exported with it — the verifier and
17539
+ // the hooks. The service is public surface for a host's own admin routes.
17540
+ ...includeApiKeys ? [
17541
+ ApiKeyGuard,
17542
+ ApiKeyVerifierService,
17543
+ ApiKeyService,
17544
+ BYMAX_AUTH_HOOKS
17545
+ ] : [],
16546
17546
  // WsTicketService also stands on its own as public surface: single-use ticket
16547
17547
  // handshakes are the credential a realtime transport is meant to use, and a consumer
16548
17548
  // cannot mint one without injecting this service.
@@ -16554,7 +17554,7 @@ var BymaxAuthModule = class _BymaxAuthModule {
16554
17554
  };
16555
17555
  }
16556
17556
  };
16557
- BymaxAuthModule = _ts_decorate64([
17557
+ BymaxAuthModule = _ts_decorate69([
16558
17558
  Module({})
16559
17559
  ], BymaxAuthModule);
16560
17560
 
@@ -16882,7 +17882,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
16882
17882
  }
16883
17883
  }
16884
17884
  };
16885
- function _ts_decorate65(decorators, target, key, desc) {
17885
+ function _ts_decorate70(decorators, target, key, desc) {
16886
17886
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16887
17887
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16888
17888
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16895,13 +17895,13 @@ function _ts_decorate65(decorators, target, key, desc) {
16895
17895
  }
16896
17896
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16897
17897
  }
16898
- __name(_ts_decorate65, "_ts_decorate");
16899
- function _ts_metadata60(metadataKey, metadataValue) {
17898
+ __name(_ts_decorate70, "_ts_decorate");
17899
+ function _ts_metadata65(metadataKey, metadataValue) {
16900
17900
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16901
17901
  return Reflect.metadata(metadataKey, metadataValue);
16902
17902
  }
16903
17903
  }
16904
- __name(_ts_metadata60, "_ts_metadata");
17904
+ __name(_ts_metadata65, "_ts_metadata");
16905
17905
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
16906
17906
  var PREFIX_LENGTH = 5;
16907
17907
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -16958,10 +17958,10 @@ var HibpBreachChecker = class _HibpBreachChecker {
16958
17958
  }
16959
17959
  }
16960
17960
  };
16961
- HibpBreachChecker = _ts_decorate65([
17961
+ HibpBreachChecker = _ts_decorate70([
16962
17962
  Injectable(),
16963
- _ts_metadata60("design:type", Function),
16964
- _ts_metadata60("design:paramtypes", [
17963
+ _ts_metadata65("design:type", Function),
17964
+ _ts_metadata65("design:paramtypes", [
16965
17965
  Number
16966
17966
  ])
16967
17967
  ], HibpBreachChecker);
@@ -16974,10 +17974,10 @@ var AllowAllBreachChecker = class {
16974
17974
  return false;
16975
17975
  }
16976
17976
  };
16977
- AllowAllBreachChecker = _ts_decorate65([
17977
+ AllowAllBreachChecker = _ts_decorate70([
16978
17978
  Injectable()
16979
17979
  ], AllowAllBreachChecker);
16980
- function _ts_decorate66(decorators, target, key, desc) {
17980
+ function _ts_decorate71(decorators, target, key, desc) {
16981
17981
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16982
17982
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16983
17983
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16990,7 +17990,7 @@ function _ts_decorate66(decorators, target, key, desc) {
16990
17990
  }
16991
17991
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16992
17992
  }
16993
- __name(_ts_decorate66, "_ts_decorate");
17993
+ __name(_ts_decorate71, "_ts_decorate");
16994
17994
  var OptionalAuthGuard = class extends JwtAuthGuard {
16995
17995
  static {
16996
17996
  __name(this, "OptionalAuthGuard");
@@ -17005,10 +18005,10 @@ var OptionalAuthGuard = class extends JwtAuthGuard {
17005
18005
  return super.canActivate(context);
17006
18006
  }
17007
18007
  };
17008
- OptionalAuthGuard = _ts_decorate66([
18008
+ OptionalAuthGuard = _ts_decorate71([
17009
18009
  Injectable()
17010
18010
  ], OptionalAuthGuard);
17011
- function _ts_decorate67(decorators, target, key, desc) {
18011
+ function _ts_decorate72(decorators, target, key, desc) {
17012
18012
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17013
18013
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17014
18014
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17021,19 +18021,19 @@ function _ts_decorate67(decorators, target, key, desc) {
17021
18021
  }
17022
18022
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17023
18023
  }
17024
- __name(_ts_decorate67, "_ts_decorate");
17025
- function _ts_metadata61(metadataKey, metadataValue) {
18024
+ __name(_ts_decorate72, "_ts_decorate");
18025
+ function _ts_metadata66(metadataKey, metadataValue) {
17026
18026
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17027
18027
  return Reflect.metadata(metadataKey, metadataValue);
17028
18028
  }
17029
18029
  }
17030
- __name(_ts_metadata61, "_ts_metadata");
17031
- function _ts_param38(paramIndex, decorator) {
18030
+ __name(_ts_metadata66, "_ts_metadata");
18031
+ function _ts_param43(paramIndex, decorator) {
17032
18032
  return function(target, key) {
17033
18033
  decorator(target, key, paramIndex);
17034
18034
  };
17035
18035
  }
17036
- __name(_ts_param38, "_ts_param");
18036
+ __name(_ts_param43, "_ts_param");
17037
18037
  var SelfOrAdminGuard = class {
17038
18038
  static {
17039
18039
  __name(this, "SelfOrAdminGuard");
@@ -17063,11 +18063,11 @@ var SelfOrAdminGuard = class {
17063
18063
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
17064
18064
  }
17065
18065
  };
17066
- SelfOrAdminGuard = _ts_decorate67([
18066
+ SelfOrAdminGuard = _ts_decorate72([
17067
18067
  Injectable(),
17068
- _ts_param38(0, Inject(BYMAX_AUTH_OPTIONS)),
17069
- _ts_metadata61("design:type", Function),
17070
- _ts_metadata61("design:paramtypes", [
18068
+ _ts_param43(0, Inject(BYMAX_AUTH_OPTIONS)),
18069
+ _ts_metadata66("design:type", Function),
18070
+ _ts_metadata66("design:paramtypes", [
17071
18071
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
17072
18072
  ])
17073
18073
  ], SelfOrAdminGuard);
@@ -17080,7 +18080,7 @@ function isHexLooking(value) {
17080
18080
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
17081
18081
  }
17082
18082
  __name(isHexLooking, "isHexLooking");
17083
- function _ts_decorate68(decorators, target, key, desc) {
18083
+ function _ts_decorate73(decorators, target, key, desc) {
17084
18084
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17085
18085
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17086
18086
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17093,19 +18093,19 @@ function _ts_decorate68(decorators, target, key, desc) {
17093
18093
  }
17094
18094
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17095
18095
  }
17096
- __name(_ts_decorate68, "_ts_decorate");
17097
- function _ts_metadata62(metadataKey, metadataValue) {
18096
+ __name(_ts_decorate73, "_ts_decorate");
18097
+ function _ts_metadata67(metadataKey, metadataValue) {
17098
18098
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17099
18099
  return Reflect.metadata(metadataKey, metadataValue);
17100
18100
  }
17101
18101
  }
17102
- __name(_ts_metadata62, "_ts_metadata");
17103
- function _ts_param39(paramIndex, decorator) {
18102
+ __name(_ts_metadata67, "_ts_metadata");
18103
+ function _ts_param44(paramIndex, decorator) {
17104
18104
  return function(target, key) {
17105
18105
  decorator(target, key, paramIndex);
17106
18106
  };
17107
18107
  }
17108
- __name(_ts_param39, "_ts_param");
18108
+ __name(_ts_param44, "_ts_param");
17109
18109
  var WsJwtGuard = class {
17110
18110
  static {
17111
18111
  __name(this, "WsJwtGuard");
@@ -17141,6 +18141,7 @@ var WsJwtGuard = class {
17141
18141
  if (ticket !== void 0) {
17142
18142
  const snapshot = await this.wsTickets.redeem(ticket);
17143
18143
  assertDashboardSnapshot(snapshot);
18144
+ await assertTenantBinding(this.options, handshake, snapshot.tenantId);
17144
18145
  client.data.user = snapshot;
17145
18146
  return true;
17146
18147
  }
@@ -17163,18 +18164,19 @@ var WsJwtGuard = class {
17163
18164
  if (await this.revocation.isAccessTokenRevoked(payload)) {
17164
18165
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
17165
18166
  }
18167
+ await assertTenantBinding(this.options, handshake, payload.tenantId);
17166
18168
  client.data.user = payload;
17167
18169
  return true;
17168
18170
  }
17169
18171
  };
17170
- WsJwtGuard = _ts_decorate68([
18172
+ WsJwtGuard = _ts_decorate73([
17171
18173
  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", [
18174
+ _ts_param44(0, Inject(JwtService)),
18175
+ _ts_param44(1, Inject(AuthRevocationService)),
18176
+ _ts_param44(2, Inject(WsTicketService)),
18177
+ _ts_param44(3, Inject(BYMAX_AUTH_OPTIONS)),
18178
+ _ts_metadata67("design:type", Function),
18179
+ _ts_metadata67("design:paramtypes", [
17178
18180
  typeof JwtService === "undefined" ? Object : JwtService,
17179
18181
  typeof AuthRevocationService === "undefined" ? Object : AuthRevocationService,
17180
18182
  typeof WsTicketService === "undefined" ? Object : WsTicketService,
@@ -17207,7 +18209,7 @@ function readUpgradeTicket(handshake) {
17207
18209
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
17208
18210
  }
17209
18211
  __name(readUpgradeTicket, "readUpgradeTicket");
17210
- function _ts_decorate69(decorators, target, key, desc) {
18212
+ function _ts_decorate74(decorators, target, key, desc) {
17211
18213
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17212
18214
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17213
18215
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17220,7 +18222,7 @@ function _ts_decorate69(decorators, target, key, desc) {
17220
18222
  }
17221
18223
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17222
18224
  }
17223
- __name(_ts_decorate69, "_ts_decorate");
18225
+ __name(_ts_decorate74, "_ts_decorate");
17224
18226
  function isAuthEnvelope(body) {
17225
18227
  if (typeof body !== "object" || body === null) return false;
17226
18228
  const error = body.error;
@@ -17272,10 +18274,10 @@ var AuthExceptionFilter = class _AuthExceptionFilter {
17272
18274
  });
17273
18275
  }
17274
18276
  };
17275
- AuthExceptionFilter = _ts_decorate69([
18277
+ AuthExceptionFilter = _ts_decorate74([
17276
18278
  Catch()
17277
18279
  ], AuthExceptionFilter);
17278
- function _ts_decorate70(decorators, target, key, desc) {
18280
+ function _ts_decorate75(decorators, target, key, desc) {
17279
18281
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17280
18282
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17281
18283
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17288,7 +18290,7 @@ function _ts_decorate70(decorators, target, key, desc) {
17288
18290
  }
17289
18291
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17290
18292
  }
17291
- __name(_ts_decorate70, "_ts_decorate");
18293
+ __name(_ts_decorate75, "_ts_decorate");
17292
18294
  function isEmittingClient(client) {
17293
18295
  return typeof client?.emit === "function";
17294
18296
  }
@@ -17332,8 +18334,10 @@ var WsAuthExceptionFilter = class _WsAuthExceptionFilter {
17332
18334
  this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
17333
18335
  }
17334
18336
  };
17335
- WsAuthExceptionFilter = _ts_decorate70([
18337
+ WsAuthExceptionFilter = _ts_decorate75([
17336
18338
  Catch(AuthException)
17337
18339
  ], WsAuthExceptionFilter);
18340
+ var ServiceKey = /* @__PURE__ */ __name((...scopes) => applyDecorators(SetMetadata(IS_PUBLIC_KEY, true), ApiKeyScopes(...scopes), UseGuards(ApiKeyGuard)), "ServiceKey");
18341
+ var CurrentApiKey = createParamDecorator((_data, ctx) => ctx.switchToHttp().getRequest().apiKey);
17338
18342
 
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 };
18343
+ 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 };