@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,12 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  var common = require('@nestjs/common');
4
+ var core = require('@nestjs/core');
4
5
  var jwt = require('@nestjs/jwt');
5
6
  var crypto = require('crypto');
6
7
  var throttler = require('@nestjs/throttler');
7
8
  var classTransformer = require('class-transformer');
8
9
  var classValidator = require('class-validator');
9
- var core = require('@nestjs/core');
10
10
  var net = require('net');
11
11
  var util = require('util');
12
12
 
@@ -22,6 +22,8 @@ var BYMAX_AUTH_HOOKS = /* @__PURE__ */ Symbol("BYMAX_AUTH_HOOKS");
22
22
  var BYMAX_AUTH_BREACH_CHECKER = /* @__PURE__ */ Symbol("BYMAX_AUTH_BREACH_CHECKER");
23
23
  var BYMAX_AUTH_REDIS_CLIENT = /* @__PURE__ */ Symbol("BYMAX_AUTH_REDIS_CLIENT");
24
24
  var BYMAX_AUTH_REGISTERED_CONTROLLERS = /* @__PURE__ */ Symbol("BYMAX_AUTH_REGISTERED_CONTROLLERS");
25
+ var BYMAX_AUTH_API_KEY_REPOSITORY = /* @__PURE__ */ Symbol("BYMAX_AUTH_API_KEY_REPOSITORY");
26
+ var BYMAX_AUTH_API_KEY_CLOCK = /* @__PURE__ */ Symbol("BYMAX_AUTH_API_KEY_CLOCK");
25
27
 
26
28
  // src/server/config/default-options.ts
27
29
  var DEFAULT_OPTIONS = {
@@ -134,6 +136,17 @@ var DEFAULT_OPTIONS = {
134
136
  // link can be accepted by an unintended recipient. Do not increase beyond 7 days.
135
137
  tokenTtlSeconds: 172800
136
138
  },
139
+ apiKeys: {
140
+ enabled: false,
141
+ // Placeholders: validation requires a real pepper and vocabulary before `enabled` can be
142
+ // true, so these values are never used to hash or admit anything.
143
+ pepper: "",
144
+ scopes: [],
145
+ header: "x-api-key",
146
+ prefix: "bak",
147
+ lastUsedFlushSeconds: 60,
148
+ auditMode: "best-effort"
149
+ },
137
150
  controllers: {
138
151
  // auth and passwordReset are opt-out (enabled by default).
139
152
  // All other controllers are opt-in (disabled by default) — they require
@@ -163,6 +176,28 @@ var DEFAULT_OPTIONS = {
163
176
  userStatusCacheTtlSeconds: 60
164
177
  };
165
178
 
179
+ // src/server/constants/request-headers.ts
180
+ var LIBRARY_READ_HEADERS = [
181
+ // The user JWT bearer, on HTTP and on the WebSocket handshake.
182
+ "authorization",
183
+ "proxy-authorization",
184
+ // Session cookies, which the host's cookie parser exposes as `req.cookies`.
185
+ "cookie",
186
+ "set-cookie",
187
+ // Copied into the `userAgent` field of every hook context.
188
+ "user-agent",
189
+ // The cross-site request checks of `TrustedOriginGuard`.
190
+ "origin",
191
+ "sec-fetch-site",
192
+ // What the client address (`request.ip`) is derived from behind a trusted proxy.
193
+ "x-forwarded-for",
194
+ "x-forwarded-host",
195
+ "x-real-ip",
196
+ "x-original-forwarded-for",
197
+ // The `hostname` handed to a `tenantIdResolver` on a WebSocket upgrade, which has no Express request.
198
+ "host"
199
+ ];
200
+
166
201
  // src/server/constants/token-epoch.ts
167
202
  var TOKEN_EPOCH_RETENTION_SECONDS = 30 * 24 * 60 * 60;
168
203
  var TOTP_STEP_SECONDS = 30;
@@ -311,6 +346,7 @@ function resolveOptions(userOptions) {
311
346
  validateOAuthProviders(userOptions.oauth, isProductionDeployment(userOptions));
312
347
  validateClientIpSource(userOptions.rateLimit);
313
348
  validateTenantBinding(userOptions);
349
+ validateApiKeys(userOptions);
314
350
  validateOAuthSuccessRedirectUrl(userOptions);
315
351
  validateOAuthMfaRedirectUrl(userOptions);
316
352
  const { issuer: rawIssuer, audience: rawAudience, ...jwtWithoutBinding } = userOptions.jwt;
@@ -375,6 +411,7 @@ function resolveOptions(userOptions) {
375
411
  ...DEFAULT_OPTIONS.invitations,
376
412
  ...userOptions.invitations
377
413
  },
414
+ apiKeys: resolveApiKeys(userOptions.apiKeys),
378
415
  emailChange: {
379
416
  ...DEFAULT_OPTIONS.emailChange,
380
417
  ...userOptions.emailChange
@@ -434,6 +471,7 @@ function withholdSecrets(resolved) {
434
471
  withholdFromSerialization(resolved.jwt, "previousSecrets");
435
472
  withholdFromSerialization(resolved, "hmacKey");
436
473
  withholdFromSerialization(resolved, "previousHmacKeys");
474
+ withholdFromSerialization(resolved.apiKeys, "pepper");
437
475
  if (resolved.mfa !== void 0) {
438
476
  withholdFromSerialization(resolved.mfa, "encryptionKey");
439
477
  withholdFromSerialization(resolved.mfa, "previousEncryptionKeys");
@@ -470,6 +508,89 @@ function validateTenantBinding(userOptions) {
470
508
  }
471
509
  }
472
510
  __name(validateTenantBinding, "validateTenantBinding");
511
+ var API_KEY_SCOPE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
512
+ var API_KEY_PREFIX_PATTERN = /^[a-z][a-z0-9]{1,15}$/;
513
+ var API_KEY_HEADER_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
514
+ var API_KEY_FORBIDDEN_HEADERS = new Set(LIBRARY_READ_HEADERS);
515
+ function resolveApiKeys(user) {
516
+ const defaults = DEFAULT_OPTIONS.apiKeys;
517
+ return {
518
+ enabled: user?.enabled ?? defaults.enabled,
519
+ pepper: user?.pepper ?? defaults.pepper,
520
+ scopes: user?.scopes ?? defaults.scopes,
521
+ // Node lowercases incoming header names, so a mixed-case option would never match.
522
+ header: typeof user?.header === "string" ? user.header.toLowerCase() : defaults.header,
523
+ prefix: user?.prefix ?? defaults.prefix,
524
+ lastUsedFlushSeconds: user?.lastUsedFlushSeconds ?? defaults.lastUsedFlushSeconds,
525
+ auditMode: user?.auditMode ?? defaults.auditMode
526
+ };
527
+ }
528
+ __name(resolveApiKeys, "resolveApiKeys");
529
+ function validateApiKeys(userOptions) {
530
+ const group = userOptions.apiKeys;
531
+ if (group?.enabled !== true) return;
532
+ validateApiKeyPepper(group.pepper, userOptions);
533
+ validateApiKeyScopes(group.scopes);
534
+ validateApiKeyTransport(group);
535
+ validateApiKeyTuning(group);
536
+ }
537
+ __name(validateApiKeys, "validateApiKeys");
538
+ function validateApiKeyPepper(pepper, userOptions) {
539
+ validateSecretStrength(pepper, "apiKeys.pepper");
540
+ const retired = userOptions.jwt.previousSecrets ?? [];
541
+ const mfaRetired = userOptions.mfa?.previousEncryptionKeys ?? [];
542
+ const mfaKeys = [
543
+ userOptions.mfa?.encryptionKey,
544
+ ...mfaRetired
545
+ ];
546
+ const reused = /* @__PURE__ */ new Set([
547
+ userOptions.jwt.secret,
548
+ userOptions.identifierKey,
549
+ ...retired,
550
+ ...mfaKeys
551
+ ]);
552
+ if (reused.has(pepper)) {
553
+ 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.`);
554
+ }
555
+ }
556
+ __name(validateApiKeyPepper, "validateApiKeyPepper");
557
+ function validateApiKeyScopes(value) {
558
+ if (!Array.isArray(value) || value.length === 0) {
559
+ 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.`);
560
+ }
561
+ const seen = /* @__PURE__ */ new Set();
562
+ for (const [index, scope] of value.entries()) {
563
+ if (typeof scope !== "string" || !API_KEY_SCOPE_PATTERN.test(scope)) {
564
+ throw new Error(`[BymaxAuthModule] apiKeys.scopes[${index}] must be 1 to 64 characters of letters, digits and ':', '.', '_', '-', starting with a letter or digit.`);
565
+ }
566
+ if (seen.has(scope)) {
567
+ throw new Error(`[BymaxAuthModule] apiKeys.scopes[${index}] repeats an earlier scope.`);
568
+ }
569
+ seen.add(scope);
570
+ }
571
+ }
572
+ __name(validateApiKeyScopes, "validateApiKeyScopes");
573
+ function validateApiKeyTransport(group) {
574
+ const { header, prefix } = group;
575
+ const name = typeof header === "string" ? header.toLowerCase() : header;
576
+ if (name !== void 0 && (typeof name !== "string" || !API_KEY_HEADER_PATTERN.test(name) || API_KEY_FORBIDDEN_HEADERS.has(name))) {
577
+ 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.`);
578
+ }
579
+ if (prefix !== void 0 && (typeof prefix !== "string" || !API_KEY_PREFIX_PATTERN.test(prefix))) {
580
+ 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.`);
581
+ }
582
+ }
583
+ __name(validateApiKeyTransport, "validateApiKeyTransport");
584
+ function validateApiKeyTuning(group) {
585
+ const { lastUsedFlushSeconds, auditMode } = group;
586
+ if (lastUsedFlushSeconds !== void 0 && (!Number.isInteger(lastUsedFlushSeconds) || lastUsedFlushSeconds < 1 || lastUsedFlushSeconds > 3600)) {
587
+ throw new Error(`[BymaxAuthModule] apiKeys.lastUsedFlushSeconds must be an integer from 1 to 3600.`);
588
+ }
589
+ if (auditMode !== void 0 && auditMode !== "best-effort" && auditMode !== "required") {
590
+ throw new Error(`[BymaxAuthModule] apiKeys.auditMode must be 'best-effort' or 'required'.`);
591
+ }
592
+ }
593
+ __name(validateApiKeyTuning, "validateApiKeyTuning");
473
594
  function validateJwt(jwt) {
474
595
  if (!jwt) {
475
596
  throw new Error(`[BymaxAuthModule] jwt configuration is required. Provide at least jwt.secret.`);
@@ -1629,6 +1750,26 @@ var AUTH_ERROR_CODES = {
1629
1750
  // ---------------------------------------------------------------------------
1630
1751
  /** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
1631
1752
  PLATFORM_AUTH_REQUIRED: "auth.platform_auth_required",
1753
+ // ---------------------------------------------------------------------------
1754
+ // Service API keys
1755
+ // ---------------------------------------------------------------------------
1756
+ /**
1757
+ * The presented service key is not accepted.
1758
+ *
1759
+ * One code for every way a credential can fail — absent, malformed, unknown, wrong secret,
1760
+ * revoked, expired — so the answer tells a caller nothing about which of them it was. The
1761
+ * reason is recorded in the audit hook, where only the operator reads it.
1762
+ */
1763
+ API_KEY_INVALID: "auth.api_key_invalid",
1764
+ /**
1765
+ * The service key is valid but does not hold every scope the route declares.
1766
+ *
1767
+ * Safe to name because the caller has already proved the key. The body does not list the
1768
+ * scopes, so it is no map of what other routes require.
1769
+ */
1770
+ API_KEY_SCOPE_INSUFFICIENT: "auth.api_key_scope_insufficient",
1771
+ /** A key operation named an id that does not exist. Raised by revoke and rotate only. */
1772
+ API_KEY_NOT_FOUND: "auth.api_key_not_found",
1632
1773
  /**
1633
1774
  * An unexpected internal failure. The cause is logged and never serialized.
1634
1775
  *
@@ -1677,6 +1818,9 @@ var AUTH_ERROR_STATUS = {
1677
1818
  "auth.oauth_failed": 401,
1678
1819
  "auth.oauth_email_mismatch": 409,
1679
1820
  "auth.platform_auth_required": 401,
1821
+ "auth.api_key_invalid": 401,
1822
+ "auth.api_key_scope_insufficient": 403,
1823
+ "auth.api_key_not_found": 404,
1680
1824
  "auth.internal": 500
1681
1825
  };
1682
1826
  var AUTH_ERROR_MESSAGES = {
@@ -1717,6 +1861,9 @@ var AUTH_ERROR_MESSAGES = {
1717
1861
  "auth.oauth_email_mismatch": "OAuth email does not match",
1718
1862
  "auth.token_missing": "Token missing",
1719
1863
  "auth.platform_auth_required": "Platform authentication required",
1864
+ "auth.api_key_invalid": "Invalid API key",
1865
+ "auth.api_key_scope_insufficient": "API key lacks the required scope",
1866
+ "auth.api_key_not_found": "API key not found",
1720
1867
  "auth.internal": "Internal server error"
1721
1868
  };
1722
1869
  var MESSAGE_BY_CODE = new Map(Object.entries(AUTH_ERROR_MESSAGES));
@@ -9466,6 +9613,18 @@ function decrypt(ciphertext, keyBase64) {
9466
9613
  }
9467
9614
  __name(decrypt, "decrypt");
9468
9615
 
9616
+ // src/server/utils/run-detached.ts
9617
+ function runDetached(logger, run, failure) {
9618
+ try {
9619
+ void Promise.resolve(run()).catch((err) => {
9620
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9621
+ });
9622
+ } catch (err) {
9623
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9624
+ }
9625
+ }
9626
+ __name(runDetached, "runDetached");
9627
+
9469
9628
  // src/server/services/mfa.service.ts
9470
9629
  function _ts_decorate36(decorators, target, key, desc) {
9471
9630
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -10146,14 +10305,19 @@ exports.MfaService = class _MfaService {
10146
10305
  userAgent
10147
10306
  });
10148
10307
  }
10308
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
10309
+ id: safeUser.id,
10310
+ tenantId: safeUser.tenantId
10311
+ }), "challenge: updateLastLogin failed");
10149
10312
  if (this.hooks.afterLogin) {
10150
- void Promise.resolve(this.hooks.afterLogin(safeUser, {
10313
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10314
+ runDetached(this.logger, () => afterLogin(safeUser, {
10151
10315
  plane: "dashboard",
10152
10316
  userId,
10153
10317
  ip,
10154
10318
  userAgent,
10155
10319
  sanitizedHeaders: {}
10156
- })).catch(() => void 0);
10320
+ }), "challenge: afterLogin hook threw");
10157
10321
  }
10158
10322
  return result2;
10159
10323
  }
@@ -10161,14 +10325,16 @@ exports.MfaService = class _MfaService {
10161
10325
  const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10162
10326
  mfaVerified: true
10163
10327
  });
10328
+ runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10164
10329
  if (this.hooks.afterLogin) {
10165
- void Promise.resolve(this.hooks.afterLogin(this.platformUserAsSafeUser(platformUser), {
10330
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10331
+ runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10166
10332
  plane: "platform",
10167
10333
  userId,
10168
10334
  ip,
10169
10335
  userAgent,
10170
10336
  sanitizedHeaders: {}
10171
- })).catch(() => void 0);
10337
+ }), "challenge: afterLogin hook threw");
10172
10338
  }
10173
10339
  return result;
10174
10340
  }
@@ -13312,6 +13478,8 @@ SessionController = _ts_decorate50([
13312
13478
  typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
13313
13479
  ])
13314
13480
  ], SessionController);
13481
+ var API_KEY_SCOPES_KEY = /* @__PURE__ */ Symbol("bymax:apiKeyScopes");
13482
+ var ApiKeyScopes = /* @__PURE__ */ __name((...scopes) => common.SetMetadata(API_KEY_SCOPES_KEY, scopes), "ApiKeyScopes");
13315
13483
  function _ts_decorate51(decorators, target, key, desc) {
13316
13484
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13317
13485
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13338,44 +13506,120 @@ function _ts_param30(paramIndex, decorator) {
13338
13506
  };
13339
13507
  }
13340
13508
  __name(_ts_param30, "_ts_param");
13341
- exports.MfaRequiredGuard = class MfaRequiredGuard {
13509
+ var ApiKeyLastUsedService = class _ApiKeyLastUsedService {
13342
13510
  static {
13343
- __name(this, "MfaRequiredGuard");
13511
+ __name(this, "ApiKeyLastUsedService");
13344
13512
  }
13345
- reflector;
13346
- constructor(reflector) {
13347
- this.reflector = reflector;
13513
+ repository;
13514
+ options;
13515
+ logger = new common.Logger(_ApiKeyLastUsedService.name);
13516
+ pending = /* @__PURE__ */ new Map();
13517
+ timer = null;
13518
+ closed = false;
13519
+ constructor(repository, options) {
13520
+ this.repository = repository;
13521
+ this.options = options;
13348
13522
  }
13349
- canActivate(context) {
13350
- const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13351
- context.getHandler(),
13352
- context.getClass()
13353
- ]);
13354
- if (skipMfa) return true;
13355
- const request = context.switchToHttp().getRequest();
13356
- const user = request.user;
13357
- if (!user) return true;
13358
- if (typeof user.mfaEnabled !== "boolean") {
13359
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13523
+ /**
13524
+ * Notes that a key verified at an instant. Synchronous and free of I/O.
13525
+ *
13526
+ * @param id - The key's row id.
13527
+ * @param at - When it verified.
13528
+ */
13529
+ record(id, at) {
13530
+ const seen = this.pending.get(id);
13531
+ if (seen === void 0 || seen.getTime() < at.getTime()) this.pending.set(id, at);
13532
+ if (this.timer === null && !this.closed) {
13533
+ this.timer = setTimeout(() => {
13534
+ this.timer = null;
13535
+ void this.flush();
13536
+ }, this.options.apiKeys.lastUsedFlushSeconds * 1e3);
13537
+ this.timer.unref();
13360
13538
  }
13361
- if (user.mfaEnabled === true && user.mfaVerified !== true) {
13362
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13539
+ }
13540
+ /**
13541
+ * Writes everything pending in one batch. A failure keeps the entries for the next window.
13542
+ *
13543
+ * @returns Resolves once the batch is written or has been put back.
13544
+ */
13545
+ async flush() {
13546
+ if (this.pending.size === 0) return;
13547
+ const batch = this.pending;
13548
+ this.pending = /* @__PURE__ */ new Map();
13549
+ try {
13550
+ await this.repository.touchLastUsed([
13551
+ ...batch
13552
+ ].map(([id, at]) => ({
13553
+ id,
13554
+ at
13555
+ })));
13556
+ } catch (err) {
13557
+ this.logger.warn(`api-key: last-used flush failed cause=${describeChannelStatus(err)}`);
13558
+ for (const [id, at] of batch) this.record(id, at);
13363
13559
  }
13364
- return true;
13560
+ }
13561
+ /** Flushes what is left so a clean shutdown loses nothing. */
13562
+ async onApplicationShutdown() {
13563
+ this.closed = true;
13564
+ if (this.timer !== null) clearTimeout(this.timer);
13565
+ this.timer = null;
13566
+ await this.flush();
13365
13567
  }
13366
13568
  };
13367
- exports.MfaRequiredGuard = _ts_decorate51([
13569
+ ApiKeyLastUsedService = _ts_decorate51([
13368
13570
  common.Injectable(),
13369
- _ts_param30(0, common.Inject(core.Reflector)),
13571
+ _ts_param30(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13572
+ _ts_param30(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13370
13573
  _ts_metadata50("design:type", Function),
13371
13574
  _ts_metadata50("design:paramtypes", [
13372
- typeof core.Reflector === "undefined" ? Object : core.Reflector
13575
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13576
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13373
13577
  ])
13374
- ], exports.MfaRequiredGuard);
13375
- var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13376
- var PlatformRoles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13578
+ ], ApiKeyLastUsedService);
13579
+ var SEPARATOR = "_";
13580
+ var KEY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13581
+ var SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
13582
+ var SECRET_BYTES = 32;
13583
+ var DIGEST_HEX = /^[0-9a-f]{64}$/;
13584
+ var API_KEY_DUMMY_KEY_ID = "00000000-0000-4000-8000-000000000000";
13585
+ var API_KEY_DUMMY_SECRET = "A".repeat(43);
13586
+ var API_KEY_DUMMY_DIGEST = "0".repeat(64);
13587
+ function generateApiKeySecret() {
13588
+ return crypto.randomBytes(SECRET_BYTES).toString("base64url");
13589
+ }
13590
+ __name(generateApiKeySecret, "generateApiKeySecret");
13591
+ function formatApiKey(prefix, keyId, secret) {
13592
+ return `${prefix}${SEPARATOR}${keyId}${SEPARATOR}${secret}`;
13593
+ }
13594
+ __name(formatApiKey, "formatApiKey");
13595
+ function parseApiKey(raw, prefix) {
13596
+ if (typeof raw !== "string") return null;
13597
+ const head = `${prefix}${SEPARATOR}`;
13598
+ if (!raw.startsWith(head)) return null;
13599
+ const rest = raw.slice(head.length);
13600
+ const keyId = rest.slice(0, 36);
13601
+ if (rest[36] !== SEPARATOR) return null;
13602
+ const secret = rest.slice(37);
13603
+ if (!KEY_ID_PATTERN.test(keyId) || !SECRET_PATTERN.test(secret)) return null;
13604
+ return {
13605
+ keyId,
13606
+ secret
13607
+ };
13608
+ }
13609
+ __name(parseApiKey, "parseApiKey");
13610
+ function apiKeyDigest(secret, pepper) {
13611
+ return hmacSha256(secret, pepper);
13612
+ }
13613
+ __name(apiKeyDigest, "apiKeyDigest");
13614
+ function digestsMatch(computed, stored) {
13615
+ const wellFormed = DIGEST_HEX.test(computed) && DIGEST_HEX.test(stored);
13616
+ const left = Buffer.from(wellFormed ? computed : API_KEY_DUMMY_DIGEST, "hex");
13617
+ const right = Buffer.from(wellFormed ? stored : API_KEY_DUMMY_DIGEST, "hex");
13618
+ return crypto.timingSafeEqual(left, right) && wellFormed;
13619
+ }
13620
+ __name(digestsMatch, "digestsMatch");
13377
13621
 
13378
- // src/server/guards/platform-roles.guard.ts
13622
+ // src/server/services/api-key-verifier.service.ts
13379
13623
  function _ts_decorate52(decorators, target, key, desc) {
13380
13624
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13381
13625
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13402,53 +13646,81 @@ function _ts_param31(paramIndex, decorator) {
13402
13646
  };
13403
13647
  }
13404
13648
  __name(_ts_param31, "_ts_param");
13405
- exports.PlatformRolesGuard = class PlatformRolesGuard {
13649
+ var ApiKeyVerifierService = class {
13406
13650
  static {
13407
- __name(this, "PlatformRolesGuard");
13651
+ __name(this, "ApiKeyVerifierService");
13408
13652
  }
13409
- reflector;
13653
+ repository;
13654
+ clock;
13410
13655
  options;
13411
- constructor(reflector, options) {
13412
- this.reflector = reflector;
13656
+ lastUsed;
13657
+ constructor(repository, clock, options, lastUsed) {
13658
+ this.repository = repository;
13659
+ this.clock = clock;
13413
13660
  this.options = options;
13661
+ this.lastUsed = lastUsed;
13414
13662
  }
13415
- canActivate(context) {
13416
- const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
13417
- context.getHandler(),
13418
- context.getClass()
13419
- ]);
13420
- if (!requiredRoles || requiredRoles.length === 0) return true;
13421
- const request = context.switchToHttp().getRequest();
13422
- const user = request.user;
13423
- if (!user || user.type !== "platform") {
13424
- throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13425
- }
13426
- const userRole = user.role;
13427
- const hierarchy = this.options.roles.platformHierarchy;
13428
- if (!hierarchy) {
13429
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13430
- }
13431
- const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
13432
- if (!allowed) {
13433
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13663
+ /**
13664
+ * Verifies the value of the key header.
13665
+ *
13666
+ * @param header - The header value as the framework delivered it.
13667
+ * @returns The verdict. A store fault propagates: the caller fails closed.
13668
+ */
13669
+ async verify(header) {
13670
+ const parsed = parseApiKey(header, this.options.apiKeys.prefix);
13671
+ const keyId = parsed?.keyId ?? API_KEY_DUMMY_KEY_ID;
13672
+ const secret = parsed?.secret ?? API_KEY_DUMMY_SECRET;
13673
+ const row = await this.repository.findById(keyId);
13674
+ const computed = apiKeyDigest(secret, this.options.apiKeys.pepper);
13675
+ const equal = digestsMatch(computed, row?.digest ?? API_KEY_DUMMY_DIGEST);
13676
+ const now = this.clock.now();
13677
+ const reason = this.rejection(header, parsed !== null, row, equal, now.getTime());
13678
+ if (reason !== null) {
13679
+ return {
13680
+ ok: false,
13681
+ reason,
13682
+ key: parsed === null ? null : row
13683
+ };
13434
13684
  }
13435
- return true;
13685
+ const key = row;
13686
+ this.lastUsed.record(key.id, now);
13687
+ return {
13688
+ ok: true,
13689
+ key
13690
+ };
13691
+ }
13692
+ /**
13693
+ * The single decision, evaluated after every step above has run.
13694
+ *
13695
+ * A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
13696
+ * comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
13697
+ * compares false against everything) reads as lapsed rather than as valid.
13698
+ */
13699
+ rejection(header, parsed, row, equal, nowMs) {
13700
+ if (!parsed) return header === void 0 ? "missing" : "malformed";
13701
+ if (row === null) return "unknown";
13702
+ if (!equal) return "wrong_secret";
13703
+ if (row.revokedAt !== null) return "revoked";
13704
+ if (row.expiresAt !== null && !(row.expiresAt.getTime() > nowMs)) return "expired";
13705
+ return null;
13436
13706
  }
13437
13707
  };
13438
- exports.PlatformRolesGuard = _ts_decorate52([
13708
+ ApiKeyVerifierService = _ts_decorate52([
13439
13709
  common.Injectable(),
13440
- _ts_param31(0, common.Inject(core.Reflector)),
13441
- _ts_param31(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13710
+ _ts_param31(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13711
+ _ts_param31(1, common.Inject(BYMAX_AUTH_API_KEY_CLOCK)),
13712
+ _ts_param31(2, common.Inject(BYMAX_AUTH_OPTIONS)),
13713
+ _ts_param31(3, common.Inject(ApiKeyLastUsedService)),
13442
13714
  _ts_metadata51("design:type", Function),
13443
13715
  _ts_metadata51("design:paramtypes", [
13444
- typeof core.Reflector === "undefined" ? Object : core.Reflector,
13445
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13716
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13717
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
13718
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13719
+ typeof ApiKeyLastUsedService === "undefined" ? Object : ApiKeyLastUsedService
13446
13720
  ])
13447
- ], exports.PlatformRolesGuard);
13448
- var ROLES_KEY = "roles";
13449
- var Roles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(ROLES_KEY, roles), "Roles");
13721
+ ], ApiKeyVerifierService);
13450
13722
 
13451
- // src/server/guards/roles.guard.ts
13723
+ // src/server/guards/api-key.guard.ts
13452
13724
  function _ts_decorate53(decorators, target, key, desc) {
13453
13725
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13454
13726
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13475,115 +13747,166 @@ function _ts_param32(paramIndex, decorator) {
13475
13747
  };
13476
13748
  }
13477
13749
  __name(_ts_param32, "_ts_param");
13478
- exports.RolesGuard = class RolesGuard {
13750
+ exports.ApiKeyGuard = class _ApiKeyGuard {
13479
13751
  static {
13480
- __name(this, "RolesGuard");
13752
+ __name(this, "ApiKeyGuard");
13481
13753
  }
13482
13754
  reflector;
13755
+ verifier;
13483
13756
  options;
13484
- constructor(reflector, options) {
13757
+ hooks;
13758
+ logger = new common.Logger(_ApiKeyGuard.name);
13759
+ constructor(reflector, verifier, options, hooks) {
13485
13760
  this.reflector = reflector;
13761
+ this.verifier = verifier;
13486
13762
  this.options = options;
13763
+ this.hooks = hooks;
13487
13764
  }
13488
- canActivate(context) {
13489
- const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
13490
- context.getHandler(),
13491
- context.getClass()
13492
- ]);
13493
- if (!requiredRoles || requiredRoles.length === 0) return true;
13765
+ async canActivate(context) {
13494
13766
  const request = context.switchToHttp().getRequest();
13495
- const userRole = request.user?.role;
13496
- if (!userRole) {
13497
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13498
- }
13499
- const hierarchy = this.options.roles.hierarchy;
13500
- const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
13501
- if (!allowed) {
13502
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13767
+ const required = this.declaredScopes(context);
13768
+ const base = {
13769
+ method: request.method,
13770
+ route: routePattern(request),
13771
+ requiredScopes: required ?? []
13772
+ };
13773
+ if (required === null) {
13774
+ this.logger.error(`api-key: ${logSafe(request.method)} ${logSafe(base.route)} is guarded but declares no scopes; refused`);
13775
+ await this.audit(request, {
13776
+ ...base,
13777
+ outcome: "denied",
13778
+ reason: "route_undeclared"
13779
+ });
13780
+ throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN);
13503
13781
  }
13782
+ let verdict;
13783
+ try {
13784
+ verdict = await this.verifier.verify(request.headers[this.options.apiKeys.header]);
13785
+ } catch (err) {
13786
+ this.logger.error(`api-key: key store unavailable cause=${describeChannelStatus(err)}`);
13787
+ await this.audit(request, {
13788
+ ...base,
13789
+ outcome: "denied",
13790
+ reason: "store_error"
13791
+ });
13792
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13793
+ }
13794
+ if (!verdict.ok) {
13795
+ await this.audit(request, {
13796
+ ...base,
13797
+ outcome: "denied",
13798
+ reason: verdict.reason
13799
+ }, verdict.key);
13800
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_INVALID);
13801
+ }
13802
+ const { key } = verdict;
13803
+ if (!required.every((scope) => key.scopes.includes(scope))) {
13804
+ await this.audit(request, {
13805
+ ...base,
13806
+ outcome: "denied",
13807
+ reason: "scope_insufficient"
13808
+ }, key);
13809
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_SCOPE_INSUFFICIENT);
13810
+ }
13811
+ const delivered = await this.audit(request, {
13812
+ ...base,
13813
+ outcome: "allowed",
13814
+ reason: null
13815
+ }, key);
13816
+ if (!delivered) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13817
+ request.apiKey = Object.freeze({
13818
+ id: key.id,
13819
+ label: key.label,
13820
+ scopes: Object.freeze([
13821
+ ...key.scopes
13822
+ ])
13823
+ });
13504
13824
  return true;
13505
13825
  }
13506
- };
13507
- exports.RolesGuard = _ts_decorate53([
13508
- common.Injectable(),
13509
- _ts_param32(0, common.Inject(core.Reflector)),
13510
- _ts_param32(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13511
- _ts_metadata52("design:type", Function),
13512
- _ts_metadata52("design:paramtypes", [
13513
- typeof core.Reflector === "undefined" ? Object : core.Reflector,
13514
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13515
- ])
13516
- ], exports.RolesGuard);
13517
- function _ts_decorate54(decorators, target, key, desc) {
13518
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13519
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13520
- r = Reflect.decorate(decorators, target, key, desc);
13521
- } else {
13522
- for (var i = decorators.length - 1; i >= 0; i--) {
13523
- if (d = decorators[i]) {
13524
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13525
- }
13526
- }
13527
- }
13528
- return c > 3 && r && Object.defineProperty(target, key, r), r;
13529
- }
13530
- __name(_ts_decorate54, "_ts_decorate");
13531
- exports.NoOpAuthHooks = class NoOpAuthHooks {
13532
- static {
13533
- __name(this, "NoOpAuthHooks");
13534
- }
13535
13826
  /**
13536
- * Permits all registration attempts unconditionally.
13827
+ * The route's scope declaration: handler over class, empty or malformed counting as none.
13537
13828
  *
13538
- * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
13539
- * @param _context - Hook execution context carrying request metadata.
13540
- * @returns `{ allowed: true }` — never blocks registration.
13829
+ * @returns The scopes, or `null` when the route declares none.
13541
13830
  */
13542
- beforeRegister(_data, _context) {
13543
- return {
13544
- allowed: true
13545
- };
13831
+ declaredScopes(context) {
13832
+ const declared = this.reflector.getAllAndOverride(API_KEY_SCOPES_KEY, [
13833
+ context.getHandler(),
13834
+ context.getClass()
13835
+ ]);
13836
+ if (!Array.isArray(declared) || declared.length === 0 || !declared.every((scope) => typeof scope === "string")) {
13837
+ return null;
13838
+ }
13839
+ return declared;
13546
13840
  }
13547
13841
  /**
13548
- * Resolves OAuth login by linking to an existing account, creating a new one,
13549
- * or rejecting on email mismatch.
13842
+ * Emits the audit event.
13550
13843
  *
13551
- * @param profile - Normalized OAuth profile from the provider.
13552
- * @param existingUser - Existing user found by the profile email, or `null`.
13553
- * @param _context - Hook execution context carrying request metadata.
13554
- * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
13844
+ * @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
13845
+ * is fired without being awaited and the result is always `true`.
13555
13846
  */
13556
- onOAuthLogin(profile, existingUser, _context) {
13557
- if (existingUser === null) {
13558
- return {
13559
- action: "create"
13560
- };
13847
+ async audit(request, partial, key = null) {
13848
+ const hook = this.hooks?.onApiKeyRequest;
13849
+ if (hook === void 0) {
13850
+ if (this.options.apiKeys.auditMode !== "required") return true;
13851
+ this.logger.error("api-key: auditMode is required but no onApiKeyRequest hook is implemented; refusing");
13852
+ return false;
13561
13853
  }
13562
- if (existingUser.email === profile.email) {
13563
- return {
13564
- action: "link"
13565
- };
13854
+ const event = {
13855
+ ...partial,
13856
+ keyId: key?.id ?? null,
13857
+ label: key?.label ?? null,
13858
+ ip: request.ip ?? ""
13859
+ };
13860
+ const context = this.hookContext(request);
13861
+ const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
13862
+ if (this.options.apiKeys.auditMode === "required") {
13863
+ try {
13864
+ await run();
13865
+ return true;
13866
+ } catch (err) {
13867
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13868
+ return false;
13869
+ }
13870
+ }
13871
+ try {
13872
+ void Promise.resolve(run()).catch((err) => {
13873
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13874
+ });
13875
+ } catch (err) {
13876
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13566
13877
  }
13878
+ return true;
13879
+ }
13880
+ hookContext(request) {
13881
+ const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13567
13882
  return {
13568
- action: "reject",
13569
- reason: "Email mismatch"
13883
+ ip: request.ip ?? "",
13884
+ userAgent: request.headers["user-agent"] ?? "",
13885
+ sanitizedHeaders: sanitizeHeaders(headers)
13570
13886
  };
13571
13887
  }
13572
13888
  };
13573
- exports.NoOpAuthHooks = _ts_decorate54([
13574
- common.Injectable()
13575
- ], exports.NoOpAuthHooks);
13576
-
13577
- // src/server/oauth/oauth.constants.ts
13578
- var OAUTH_PLUGINS = /* @__PURE__ */ Symbol("OAUTH_PLUGINS");
13579
-
13580
- // src/server/constants/oauth-state-cookie.ts
13581
- var OAUTH_STATE_COOKIE_NAME = "oauth_state";
13582
- var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
13583
- var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
13584
-
13585
- // src/server/oauth/oauth.service.ts
13586
- function _ts_decorate55(decorators, target, key, desc) {
13889
+ exports.ApiKeyGuard = _ts_decorate53([
13890
+ common.Injectable(),
13891
+ _ts_param32(0, common.Inject(core.Reflector)),
13892
+ _ts_param32(1, common.Inject(ApiKeyVerifierService)),
13893
+ _ts_param32(2, common.Inject(BYMAX_AUTH_OPTIONS)),
13894
+ _ts_param32(3, common.Inject(BYMAX_AUTH_HOOKS)),
13895
+ _ts_param32(3, common.Optional()),
13896
+ _ts_metadata52("design:type", Function),
13897
+ _ts_metadata52("design:paramtypes", [
13898
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
13899
+ typeof ApiKeyVerifierService === "undefined" ? Object : ApiKeyVerifierService,
13900
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13901
+ Object
13902
+ ])
13903
+ ], exports.ApiKeyGuard);
13904
+ function routePattern(request) {
13905
+ const path = request.route?.path;
13906
+ return typeof path === "string" ? path : "";
13907
+ }
13908
+ __name(routePattern, "routePattern");
13909
+ function _ts_decorate54(decorators, target, key, desc) {
13587
13910
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13588
13911
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13589
13912
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13596,7 +13919,7 @@ function _ts_decorate55(decorators, target, key, desc) {
13596
13919
  }
13597
13920
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13598
13921
  }
13599
- __name(_ts_decorate55, "_ts_decorate");
13922
+ __name(_ts_decorate54, "_ts_decorate");
13600
13923
  function _ts_metadata53(metadataKey, metadataValue) {
13601
13924
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13602
13925
  return Reflect.metadata(metadataKey, metadataValue);
@@ -13609,15 +13932,292 @@ function _ts_param33(paramIndex, decorator) {
13609
13932
  };
13610
13933
  }
13611
13934
  __name(_ts_param33, "_ts_param");
13612
- var OAUTH_STATE_TTL_SECONDS = 600;
13613
- function isStoredOAuthState(value) {
13614
- if (typeof value !== "object" || value === null) return false;
13615
- const v = value;
13616
- if (typeof v["provider"] !== "string") return false;
13617
- if (typeof v["tenantId"] !== "string") return false;
13618
- if (typeof v["codeVerifier"] !== "string") return false;
13619
- return true;
13620
- }
13935
+ exports.MfaRequiredGuard = class MfaRequiredGuard {
13936
+ static {
13937
+ __name(this, "MfaRequiredGuard");
13938
+ }
13939
+ reflector;
13940
+ constructor(reflector) {
13941
+ this.reflector = reflector;
13942
+ }
13943
+ canActivate(context) {
13944
+ const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13945
+ context.getHandler(),
13946
+ context.getClass()
13947
+ ]);
13948
+ if (skipMfa) return true;
13949
+ const request = context.switchToHttp().getRequest();
13950
+ const user = request.user;
13951
+ if (!user) return true;
13952
+ if (typeof user.mfaEnabled !== "boolean") {
13953
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13954
+ }
13955
+ if (user.mfaEnabled === true && user.mfaVerified !== true) {
13956
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13957
+ }
13958
+ return true;
13959
+ }
13960
+ };
13961
+ exports.MfaRequiredGuard = _ts_decorate54([
13962
+ common.Injectable(),
13963
+ _ts_param33(0, common.Inject(core.Reflector)),
13964
+ _ts_metadata53("design:type", Function),
13965
+ _ts_metadata53("design:paramtypes", [
13966
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
13967
+ ])
13968
+ ], exports.MfaRequiredGuard);
13969
+ var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13970
+ var PlatformRoles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13971
+
13972
+ // src/server/guards/platform-roles.guard.ts
13973
+ function _ts_decorate55(decorators, target, key, desc) {
13974
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13975
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13976
+ r = Reflect.decorate(decorators, target, key, desc);
13977
+ } else {
13978
+ for (var i = decorators.length - 1; i >= 0; i--) {
13979
+ if (d = decorators[i]) {
13980
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13981
+ }
13982
+ }
13983
+ }
13984
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13985
+ }
13986
+ __name(_ts_decorate55, "_ts_decorate");
13987
+ function _ts_metadata54(metadataKey, metadataValue) {
13988
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13989
+ return Reflect.metadata(metadataKey, metadataValue);
13990
+ }
13991
+ }
13992
+ __name(_ts_metadata54, "_ts_metadata");
13993
+ function _ts_param34(paramIndex, decorator) {
13994
+ return function(target, key) {
13995
+ decorator(target, key, paramIndex);
13996
+ };
13997
+ }
13998
+ __name(_ts_param34, "_ts_param");
13999
+ exports.PlatformRolesGuard = class PlatformRolesGuard {
14000
+ static {
14001
+ __name(this, "PlatformRolesGuard");
14002
+ }
14003
+ reflector;
14004
+ options;
14005
+ constructor(reflector, options) {
14006
+ this.reflector = reflector;
14007
+ this.options = options;
14008
+ }
14009
+ canActivate(context) {
14010
+ const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
14011
+ context.getHandler(),
14012
+ context.getClass()
14013
+ ]);
14014
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14015
+ const request = context.switchToHttp().getRequest();
14016
+ const user = request.user;
14017
+ if (!user || user.type !== "platform") {
14018
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14019
+ }
14020
+ const userRole = user.role;
14021
+ const hierarchy = this.options.roles.platformHierarchy;
14022
+ if (!hierarchy) {
14023
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14024
+ }
14025
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14026
+ if (!allowed) {
14027
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14028
+ }
14029
+ return true;
14030
+ }
14031
+ };
14032
+ exports.PlatformRolesGuard = _ts_decorate55([
14033
+ common.Injectable(),
14034
+ _ts_param34(0, common.Inject(core.Reflector)),
14035
+ _ts_param34(1, common.Inject(BYMAX_AUTH_OPTIONS)),
14036
+ _ts_metadata54("design:type", Function),
14037
+ _ts_metadata54("design:paramtypes", [
14038
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
14039
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14040
+ ])
14041
+ ], exports.PlatformRolesGuard);
14042
+ var ROLES_KEY = "roles";
14043
+ var Roles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(ROLES_KEY, roles), "Roles");
14044
+
14045
+ // src/server/guards/roles.guard.ts
14046
+ function _ts_decorate56(decorators, target, key, desc) {
14047
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14048
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14049
+ r = Reflect.decorate(decorators, target, key, desc);
14050
+ } else {
14051
+ for (var i = decorators.length - 1; i >= 0; i--) {
14052
+ if (d = decorators[i]) {
14053
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14054
+ }
14055
+ }
14056
+ }
14057
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14058
+ }
14059
+ __name(_ts_decorate56, "_ts_decorate");
14060
+ function _ts_metadata55(metadataKey, metadataValue) {
14061
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14062
+ return Reflect.metadata(metadataKey, metadataValue);
14063
+ }
14064
+ }
14065
+ __name(_ts_metadata55, "_ts_metadata");
14066
+ function _ts_param35(paramIndex, decorator) {
14067
+ return function(target, key) {
14068
+ decorator(target, key, paramIndex);
14069
+ };
14070
+ }
14071
+ __name(_ts_param35, "_ts_param");
14072
+ exports.RolesGuard = class RolesGuard {
14073
+ static {
14074
+ __name(this, "RolesGuard");
14075
+ }
14076
+ reflector;
14077
+ options;
14078
+ constructor(reflector, options) {
14079
+ this.reflector = reflector;
14080
+ this.options = options;
14081
+ }
14082
+ canActivate(context) {
14083
+ const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
14084
+ context.getHandler(),
14085
+ context.getClass()
14086
+ ]);
14087
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14088
+ const request = context.switchToHttp().getRequest();
14089
+ const userRole = request.user?.role;
14090
+ if (!userRole) {
14091
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14092
+ }
14093
+ const hierarchy = this.options.roles.hierarchy;
14094
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14095
+ if (!allowed) {
14096
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14097
+ }
14098
+ return true;
14099
+ }
14100
+ };
14101
+ exports.RolesGuard = _ts_decorate56([
14102
+ common.Injectable(),
14103
+ _ts_param35(0, common.Inject(core.Reflector)),
14104
+ _ts_param35(1, common.Inject(BYMAX_AUTH_OPTIONS)),
14105
+ _ts_metadata55("design:type", Function),
14106
+ _ts_metadata55("design:paramtypes", [
14107
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
14108
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14109
+ ])
14110
+ ], exports.RolesGuard);
14111
+ function _ts_decorate57(decorators, target, key, desc) {
14112
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14113
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14114
+ r = Reflect.decorate(decorators, target, key, desc);
14115
+ } else {
14116
+ for (var i = decorators.length - 1; i >= 0; i--) {
14117
+ if (d = decorators[i]) {
14118
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14119
+ }
14120
+ }
14121
+ }
14122
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14123
+ }
14124
+ __name(_ts_decorate57, "_ts_decorate");
14125
+ exports.NoOpAuthHooks = class NoOpAuthHooks {
14126
+ static {
14127
+ __name(this, "NoOpAuthHooks");
14128
+ }
14129
+ /**
14130
+ * Permits all registration attempts unconditionally.
14131
+ *
14132
+ * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
14133
+ * @param _context - Hook execution context carrying request metadata.
14134
+ * @returns `{ allowed: true }` — never blocks registration.
14135
+ */
14136
+ beforeRegister(_data, _context) {
14137
+ return {
14138
+ allowed: true
14139
+ };
14140
+ }
14141
+ /**
14142
+ * Resolves OAuth login: creates an account for an unlinked identity, keeps an existing link
14143
+ * when the address still matches and the provider vouches for it, and rejects otherwise.
14144
+ *
14145
+ * @param profile - Normalized OAuth profile from the provider.
14146
+ * @param existingUser - The user already linked to this provider identity, or `null`.
14147
+ * @param _context - Hook execution context carrying request metadata.
14148
+ * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
14149
+ */
14150
+ onOAuthLogin(profile, existingUser, _context) {
14151
+ if (existingUser === null) {
14152
+ return {
14153
+ action: "create"
14154
+ };
14155
+ }
14156
+ if (existingUser.email !== profile.email) {
14157
+ return {
14158
+ action: "reject",
14159
+ reason: "Email mismatch"
14160
+ };
14161
+ }
14162
+ if (profile.emailVerified !== true) {
14163
+ return {
14164
+ action: "reject",
14165
+ reason: "Email not verified"
14166
+ };
14167
+ }
14168
+ return {
14169
+ action: "link"
14170
+ };
14171
+ }
14172
+ };
14173
+ exports.NoOpAuthHooks = _ts_decorate57([
14174
+ common.Injectable()
14175
+ ], exports.NoOpAuthHooks);
14176
+
14177
+ // src/server/oauth/oauth.constants.ts
14178
+ var OAUTH_PLUGINS = /* @__PURE__ */ Symbol("OAUTH_PLUGINS");
14179
+
14180
+ // src/server/constants/oauth-state-cookie.ts
14181
+ var OAUTH_STATE_COOKIE_NAME = "oauth_state";
14182
+ var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
14183
+ var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
14184
+
14185
+ // src/server/oauth/oauth.service.ts
14186
+ function _ts_decorate58(decorators, target, key, desc) {
14187
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14188
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14189
+ r = Reflect.decorate(decorators, target, key, desc);
14190
+ } else {
14191
+ for (var i = decorators.length - 1; i >= 0; i--) {
14192
+ if (d = decorators[i]) {
14193
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14194
+ }
14195
+ }
14196
+ }
14197
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14198
+ }
14199
+ __name(_ts_decorate58, "_ts_decorate");
14200
+ function _ts_metadata56(metadataKey, metadataValue) {
14201
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14202
+ return Reflect.metadata(metadataKey, metadataValue);
14203
+ }
14204
+ }
14205
+ __name(_ts_metadata56, "_ts_metadata");
14206
+ function _ts_param36(paramIndex, decorator) {
14207
+ return function(target, key) {
14208
+ decorator(target, key, paramIndex);
14209
+ };
14210
+ }
14211
+ __name(_ts_param36, "_ts_param");
14212
+ var OAUTH_STATE_TTL_SECONDS = 600;
14213
+ function isStoredOAuthState(value) {
14214
+ if (typeof value !== "object" || value === null) return false;
14215
+ const v = value;
14216
+ if (typeof v["provider"] !== "string") return false;
14217
+ if (typeof v["tenantId"] !== "string") return false;
14218
+ if (typeof v["codeVerifier"] !== "string") return false;
14219
+ return true;
14220
+ }
13621
14221
  __name(isStoredOAuthState, "isStoredOAuthState");
13622
14222
  function base64url(input) {
13623
14223
  return input.toString("base64url");
@@ -13863,6 +14463,17 @@ exports.OAuthService = class _OAuthService {
13863
14463
  });
13864
14464
  }
13865
14465
  this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
14466
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
14467
+ id: safeUser.id,
14468
+ tenantId: safeUser.tenantId
14469
+ }), "oauth: updateLastLogin failed");
14470
+ if (this.hooks?.afterLogin) {
14471
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
14472
+ runDetached(this.logger, () => afterLogin(safeUser, {
14473
+ ...hookContext,
14474
+ userId: safeUser.id
14475
+ }), "oauth: afterLogin hook threw");
14476
+ }
13866
14477
  return result;
13867
14478
  }
13868
14479
  // ---------------------------------------------------------------------------
@@ -13891,18 +14502,18 @@ exports.OAuthService = class _OAuthService {
13891
14502
  return plugin;
13892
14503
  }
13893
14504
  };
13894
- exports.OAuthService = _ts_decorate55([
14505
+ exports.OAuthService = _ts_decorate58([
13895
14506
  common.Injectable(),
13896
- _ts_param33(0, common.Inject(OAUTH_PLUGINS)),
13897
- _ts_param33(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
13898
- _ts_param33(2, common.Inject(BYMAX_AUTH_HOOKS)),
13899
- _ts_param33(2, common.Optional()),
13900
- _ts_param33(3, common.Inject(AuthRedisService)),
13901
- _ts_param33(4, common.Inject(TokenManagerService)),
13902
- _ts_param33(5, common.Inject(exports.SessionService)),
13903
- _ts_param33(6, common.Inject(BYMAX_AUTH_OPTIONS)),
13904
- _ts_metadata53("design:type", Function),
13905
- _ts_metadata53("design:paramtypes", [
14507
+ _ts_param36(0, common.Inject(OAUTH_PLUGINS)),
14508
+ _ts_param36(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
14509
+ _ts_param36(2, common.Inject(BYMAX_AUTH_HOOKS)),
14510
+ _ts_param36(2, common.Optional()),
14511
+ _ts_param36(3, common.Inject(AuthRedisService)),
14512
+ _ts_param36(4, common.Inject(TokenManagerService)),
14513
+ _ts_param36(5, common.Inject(exports.SessionService)),
14514
+ _ts_param36(6, common.Inject(BYMAX_AUTH_OPTIONS)),
14515
+ _ts_metadata56("design:type", Function),
14516
+ _ts_metadata56("design:paramtypes", [
13906
14517
  Array,
13907
14518
  typeof IUserRepository === "undefined" ? Object : IUserRepository,
13908
14519
  Object,
@@ -13912,7 +14523,7 @@ exports.OAuthService = _ts_decorate55([
13912
14523
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13913
14524
  ])
13914
14525
  ], exports.OAuthService);
13915
- function _ts_decorate56(decorators, target, key, desc) {
14526
+ function _ts_decorate59(decorators, target, key, desc) {
13916
14527
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13917
14528
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13918
14529
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13925,13 +14536,13 @@ function _ts_decorate56(decorators, target, key, desc) {
13925
14536
  }
13926
14537
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13927
14538
  }
13928
- __name(_ts_decorate56, "_ts_decorate");
13929
- function _ts_metadata54(metadataKey, metadataValue) {
14539
+ __name(_ts_decorate59, "_ts_decorate");
14540
+ function _ts_metadata57(metadataKey, metadataValue) {
13930
14541
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13931
14542
  return Reflect.metadata(metadataKey, metadataValue);
13932
14543
  }
13933
14544
  }
13934
- __name(_ts_metadata54, "_ts_metadata");
14545
+ __name(_ts_metadata57, "_ts_metadata");
13935
14546
  var OAuthCallbackQueryDto = class {
13936
14547
  static {
13937
14548
  __name(this, "OAuthCallbackQueryDto");
@@ -14030,69 +14641,69 @@ var OAuthCallbackQueryDto = class {
14030
14641
  */
14031
14642
  hd;
14032
14643
  };
14033
- _ts_decorate56([
14644
+ _ts_decorate59([
14034
14645
  classValidator.ValidateIf((query) => query.error === void 0 || query.error === null),
14035
14646
  classValidator.IsOptional(),
14036
14647
  classValidator.IsString(),
14037
14648
  classValidator.IsNotEmpty(),
14038
14649
  classValidator.MaxLength(2048),
14039
- _ts_metadata54("design:type", String)
14650
+ _ts_metadata57("design:type", String)
14040
14651
  ], OAuthCallbackQueryDto.prototype, "code", void 0);
14041
- _ts_decorate56([
14652
+ _ts_decorate59([
14042
14653
  classValidator.IsOptional(),
14043
14654
  classValidator.IsString(),
14044
14655
  classValidator.MaxLength(128),
14045
- _ts_metadata54("design:type", String)
14656
+ _ts_metadata57("design:type", String)
14046
14657
  ], OAuthCallbackQueryDto.prototype, "error", void 0);
14047
- _ts_decorate56([
14658
+ _ts_decorate59([
14048
14659
  classValidator.IsOptional(),
14049
14660
  classValidator.IsString(),
14050
14661
  classValidator.MaxLength(512),
14051
- _ts_metadata54("design:type", String)
14662
+ _ts_metadata57("design:type", String)
14052
14663
  ], OAuthCallbackQueryDto.prototype, "error_description", void 0);
14053
- _ts_decorate56([
14664
+ _ts_decorate59([
14054
14665
  classValidator.IsOptional(),
14055
14666
  classValidator.IsString(),
14056
14667
  classValidator.MaxLength(512),
14057
- _ts_metadata54("design:type", String)
14668
+ _ts_metadata57("design:type", String)
14058
14669
  ], OAuthCallbackQueryDto.prototype, "error_uri", void 0);
14059
- _ts_decorate56([
14670
+ _ts_decorate59([
14060
14671
  classValidator.IsString(),
14061
14672
  classValidator.IsNotEmpty(),
14062
14673
  classValidator.MaxLength(128),
14063
- _ts_metadata54("design:type", String)
14674
+ _ts_metadata57("design:type", String)
14064
14675
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
14065
- _ts_decorate56([
14676
+ _ts_decorate59([
14066
14677
  classValidator.IsOptional(),
14067
14678
  classValidator.IsString(),
14068
14679
  classValidator.MaxLength(512),
14069
- _ts_metadata54("design:type", String)
14680
+ _ts_metadata57("design:type", String)
14070
14681
  ], OAuthCallbackQueryDto.prototype, "iss", void 0);
14071
- _ts_decorate56([
14682
+ _ts_decorate59([
14072
14683
  classValidator.IsOptional(),
14073
14684
  classValidator.IsString(),
14074
14685
  classValidator.MaxLength(2048),
14075
- _ts_metadata54("design:type", String)
14686
+ _ts_metadata57("design:type", String)
14076
14687
  ], OAuthCallbackQueryDto.prototype, "scope", void 0);
14077
- _ts_decorate56([
14688
+ _ts_decorate59([
14078
14689
  classValidator.IsOptional(),
14079
14690
  classValidator.IsString(),
14080
14691
  classValidator.MaxLength(16),
14081
- _ts_metadata54("design:type", String)
14692
+ _ts_metadata57("design:type", String)
14082
14693
  ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
14083
- _ts_decorate56([
14694
+ _ts_decorate59([
14084
14695
  classValidator.IsOptional(),
14085
14696
  classValidator.IsString(),
14086
14697
  classValidator.MaxLength(64),
14087
- _ts_metadata54("design:type", String)
14698
+ _ts_metadata57("design:type", String)
14088
14699
  ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
14089
- _ts_decorate56([
14700
+ _ts_decorate59([
14090
14701
  classValidator.IsOptional(),
14091
14702
  classValidator.IsString(),
14092
14703
  classValidator.MaxLength(253),
14093
- _ts_metadata54("design:type", String)
14704
+ _ts_metadata57("design:type", String)
14094
14705
  ], OAuthCallbackQueryDto.prototype, "hd", void 0);
14095
- function _ts_decorate57(decorators, target, key, desc) {
14706
+ function _ts_decorate60(decorators, target, key, desc) {
14096
14707
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14097
14708
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14098
14709
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14105,13 +14716,13 @@ function _ts_decorate57(decorators, target, key, desc) {
14105
14716
  }
14106
14717
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14107
14718
  }
14108
- __name(_ts_decorate57, "_ts_decorate");
14109
- function _ts_metadata55(metadataKey, metadataValue) {
14719
+ __name(_ts_decorate60, "_ts_decorate");
14720
+ function _ts_metadata58(metadataKey, metadataValue) {
14110
14721
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14111
14722
  return Reflect.metadata(metadataKey, metadataValue);
14112
14723
  }
14113
14724
  }
14114
- __name(_ts_metadata55, "_ts_metadata");
14725
+ __name(_ts_metadata58, "_ts_metadata");
14115
14726
  var OAuthInitiateQueryDto = class {
14116
14727
  static {
14117
14728
  __name(this, "OAuthInitiateQueryDto");
@@ -14128,7 +14739,7 @@ var OAuthInitiateQueryDto = class {
14128
14739
  */
14129
14740
  tenantId;
14130
14741
  };
14131
- _ts_decorate57([
14742
+ _ts_decorate60([
14132
14743
  classValidator.IsOptional(),
14133
14744
  classValidator.IsString(),
14134
14745
  classValidator.IsNotEmpty(),
@@ -14136,11 +14747,11 @@ _ts_decorate57([
14136
14747
  classValidator.Matches(NO_CONTROL_CHARACTERS, {
14137
14748
  message: "tenantId must not contain control characters"
14138
14749
  }),
14139
- _ts_metadata55("design:type", String)
14750
+ _ts_metadata58("design:type", String)
14140
14751
  ], OAuthInitiateQueryDto.prototype, "tenantId", void 0);
14141
14752
 
14142
14753
  // src/server/oauth/oauth.controller.ts
14143
- function _ts_decorate58(decorators, target, key, desc) {
14754
+ function _ts_decorate61(decorators, target, key, desc) {
14144
14755
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14145
14756
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14146
14757
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14153,19 +14764,19 @@ function _ts_decorate58(decorators, target, key, desc) {
14153
14764
  }
14154
14765
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14155
14766
  }
14156
- __name(_ts_decorate58, "_ts_decorate");
14157
- function _ts_metadata56(metadataKey, metadataValue) {
14767
+ __name(_ts_decorate61, "_ts_decorate");
14768
+ function _ts_metadata59(metadataKey, metadataValue) {
14158
14769
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14159
14770
  return Reflect.metadata(metadataKey, metadataValue);
14160
14771
  }
14161
14772
  }
14162
- __name(_ts_metadata56, "_ts_metadata");
14163
- function _ts_param34(paramIndex, decorator) {
14773
+ __name(_ts_metadata59, "_ts_metadata");
14774
+ function _ts_param37(paramIndex, decorator) {
14164
14775
  return function(target, key) {
14165
14776
  decorator(target, key, paramIndex);
14166
14777
  };
14167
14778
  }
14168
- __name(_ts_param34, "_ts_param");
14779
+ __name(_ts_param37, "_ts_param");
14169
14780
  function isOAuthMfaChallenge(result) {
14170
14781
  return "mfaRequired" in result && result.mfaRequired === true;
14171
14782
  }
@@ -14383,46 +14994,46 @@ var OAuthController = class _OAuthController {
14383
14994
  });
14384
14995
  }
14385
14996
  };
14386
- _ts_decorate58([
14997
+ _ts_decorate61([
14387
14998
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14388
14999
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14389
15000
  common.Get(":provider"),
14390
- _ts_param34(0, common.Param("provider")),
14391
- _ts_param34(1, common.Query()),
14392
- _ts_param34(2, common.Req()),
14393
- _ts_param34(3, common.Res({
15001
+ _ts_param37(0, common.Param("provider")),
15002
+ _ts_param37(1, common.Query()),
15003
+ _ts_param37(2, common.Req()),
15004
+ _ts_param37(3, common.Res({
14394
15005
  passthrough: true
14395
15006
  })),
14396
- _ts_metadata56("design:type", Function),
14397
- _ts_metadata56("design:paramtypes", [
15007
+ _ts_metadata59("design:type", Function),
15008
+ _ts_metadata59("design:paramtypes", [
14398
15009
  String,
14399
15010
  typeof OAuthInitiateQueryDto === "undefined" ? Object : OAuthInitiateQueryDto,
14400
15011
  typeof Request === "undefined" ? Object : Request,
14401
15012
  typeof Response === "undefined" ? Object : Response
14402
15013
  ]),
14403
- _ts_metadata56("design:returntype", Promise)
15014
+ _ts_metadata59("design:returntype", Promise)
14404
15015
  ], OAuthController.prototype, "initiate", null);
14405
- _ts_decorate58([
15016
+ _ts_decorate61([
14406
15017
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthCallback),
14407
15018
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthCallback),
14408
15019
  common.HttpCode(common.HttpStatus.OK),
14409
15020
  common.Get(":provider/callback"),
14410
- _ts_param34(0, common.Param("provider")),
14411
- _ts_param34(1, common.Query()),
14412
- _ts_param34(2, common.Req()),
14413
- _ts_param34(3, common.Res({
15021
+ _ts_param37(0, common.Param("provider")),
15022
+ _ts_param37(1, common.Query()),
15023
+ _ts_param37(2, common.Req()),
15024
+ _ts_param37(3, common.Res({
14414
15025
  passthrough: true
14415
15026
  })),
14416
- _ts_metadata56("design:type", Function),
14417
- _ts_metadata56("design:paramtypes", [
15027
+ _ts_metadata59("design:type", Function),
15028
+ _ts_metadata59("design:paramtypes", [
14418
15029
  String,
14419
15030
  typeof OAuthCallbackQueryDto === "undefined" ? Object : OAuthCallbackQueryDto,
14420
15031
  typeof Request === "undefined" ? Object : Request,
14421
15032
  typeof Response === "undefined" ? Object : Response
14422
15033
  ]),
14423
- _ts_metadata56("design:returntype", Promise)
15034
+ _ts_metadata59("design:returntype", Promise)
14424
15035
  ], OAuthController.prototype, "callback", null);
14425
- OAuthController = _ts_decorate58([
15036
+ OAuthController = _ts_decorate61([
14426
15037
  Public(),
14427
15038
  SkipMfa(),
14428
15039
  common.UseInterceptors(NoStoreInterceptor),
@@ -14431,11 +15042,11 @@ OAuthController = _ts_decorate58([
14431
15042
  common.UsePipes(createAuthValidationPipe({
14432
15043
  forbidUnknownValues: true
14433
15044
  })),
14434
- _ts_param34(0, common.Inject(exports.OAuthService)),
14435
- _ts_param34(1, common.Inject(exports.TokenDeliveryService)),
14436
- _ts_param34(2, common.Inject(BYMAX_AUTH_OPTIONS)),
14437
- _ts_metadata56("design:type", Function),
14438
- _ts_metadata56("design:paramtypes", [
15045
+ _ts_param37(0, common.Inject(exports.OAuthService)),
15046
+ _ts_param37(1, common.Inject(exports.TokenDeliveryService)),
15047
+ _ts_param37(2, common.Inject(BYMAX_AUTH_OPTIONS)),
15048
+ _ts_metadata59("design:type", Function),
15049
+ _ts_metadata59("design:paramtypes", [
14439
15050
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
14440
15051
  typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
14441
15052
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -14574,7 +15185,7 @@ var GoogleOAuthPlugin = class {
14574
15185
  };
14575
15186
 
14576
15187
  // src/server/oauth/oauth.module.ts
14577
- function _ts_decorate59(decorators, target, key, desc) {
15188
+ function _ts_decorate62(decorators, target, key, desc) {
14578
15189
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14579
15190
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14580
15191
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14587,7 +15198,7 @@ function _ts_decorate59(decorators, target, key, desc) {
14587
15198
  }
14588
15199
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14589
15200
  }
14590
- __name(_ts_decorate59, "_ts_decorate");
15201
+ __name(_ts_decorate62, "_ts_decorate");
14591
15202
  function buildOAuthPlugins(options) {
14592
15203
  const plugins = [];
14593
15204
  if (options.oauth?.google) {
@@ -14657,7 +15268,7 @@ var OAuthModule = class _OAuthModule {
14657
15268
  };
14658
15269
  }
14659
15270
  };
14660
- OAuthModule = _ts_decorate59([
15271
+ OAuthModule = _ts_decorate62([
14661
15272
  common.Module({})
14662
15273
  ], OAuthModule);
14663
15274
 
@@ -15551,7 +16162,7 @@ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
15551
16162
  __name(schemesFor, "schemesFor");
15552
16163
 
15553
16164
  // src/server/openapi/auth-openapi.contributor.ts
15554
- function _ts_decorate60(decorators, target, key, desc) {
16165
+ function _ts_decorate63(decorators, target, key, desc) {
15555
16166
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15556
16167
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15557
16168
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15564,19 +16175,19 @@ function _ts_decorate60(decorators, target, key, desc) {
15564
16175
  }
15565
16176
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15566
16177
  }
15567
- __name(_ts_decorate60, "_ts_decorate");
15568
- function _ts_metadata57(metadataKey, metadataValue) {
16178
+ __name(_ts_decorate63, "_ts_decorate");
16179
+ function _ts_metadata60(metadataKey, metadataValue) {
15569
16180
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15570
16181
  return Reflect.metadata(metadataKey, metadataValue);
15571
16182
  }
15572
16183
  }
15573
- __name(_ts_metadata57, "_ts_metadata");
15574
- function _ts_param35(paramIndex, decorator) {
16184
+ __name(_ts_metadata60, "_ts_metadata");
16185
+ function _ts_param38(paramIndex, decorator) {
15575
16186
  return function(target, key) {
15576
16187
  decorator(target, key, paramIndex);
15577
16188
  };
15578
16189
  }
15579
- __name(_ts_param35, "_ts_param");
16190
+ __name(_ts_param38, "_ts_param");
15580
16191
  var AuthOpenApiContributor = class {
15581
16192
  static {
15582
16193
  __name(this, "AuthOpenApiContributor");
@@ -15596,18 +16207,18 @@ var AuthOpenApiContributor = class {
15596
16207
  return buildAuthOpenApiFragment(this.options, this.registered);
15597
16208
  }
15598
16209
  };
15599
- AuthOpenApiContributor = _ts_decorate60([
16210
+ AuthOpenApiContributor = _ts_decorate63([
15600
16211
  common.Injectable(),
15601
16212
  common.SetMetadata(OPENAPI_CONTRIBUTOR_METADATA, true),
15602
- _ts_param35(0, common.Inject(BYMAX_AUTH_OPTIONS)),
15603
- _ts_param35(1, common.Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
15604
- _ts_metadata57("design:type", Function),
15605
- _ts_metadata57("design:paramtypes", [
16213
+ _ts_param38(0, common.Inject(BYMAX_AUTH_OPTIONS)),
16214
+ _ts_param38(1, common.Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
16215
+ _ts_metadata60("design:type", Function),
16216
+ _ts_metadata60("design:paramtypes", [
15606
16217
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
15607
16218
  typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
15608
16219
  ])
15609
16220
  ], AuthOpenApiContributor);
15610
- function _ts_decorate61(decorators, target, key, desc) {
16221
+ function _ts_decorate64(decorators, target, key, desc) {
15611
16222
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15612
16223
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15613
16224
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15620,19 +16231,19 @@ function _ts_decorate61(decorators, target, key, desc) {
15620
16231
  }
15621
16232
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15622
16233
  }
15623
- __name(_ts_decorate61, "_ts_decorate");
15624
- function _ts_metadata58(metadataKey, metadataValue) {
16234
+ __name(_ts_decorate64, "_ts_decorate");
16235
+ function _ts_metadata61(metadataKey, metadataValue) {
15625
16236
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15626
16237
  return Reflect.metadata(metadataKey, metadataValue);
15627
16238
  }
15628
16239
  }
15629
- __name(_ts_metadata58, "_ts_metadata");
15630
- function _ts_param36(paramIndex, decorator) {
16240
+ __name(_ts_metadata61, "_ts_metadata");
16241
+ function _ts_param39(paramIndex, decorator) {
15631
16242
  return function(target, key) {
15632
16243
  decorator(target, key, paramIndex);
15633
16244
  };
15634
16245
  }
15635
- __name(_ts_param36, "_ts_param");
16246
+ __name(_ts_param39, "_ts_param");
15636
16247
  var COMMON_BASE_WORDS = [
15637
16248
  // The perennial top of every published list.
15638
16249
  "password",
@@ -15938,16 +16549,16 @@ exports.CommonPasswordChecker = class CommonPasswordChecker {
15938
16549
  return false;
15939
16550
  }
15940
16551
  };
15941
- exports.CommonPasswordChecker = _ts_decorate61([
16552
+ exports.CommonPasswordChecker = _ts_decorate64([
15942
16553
  common.Injectable(),
15943
- _ts_param36(0, common.Inject(BYMAX_AUTH_OPTIONS)),
15944
- _ts_param36(0, common.Optional()),
15945
- _ts_metadata58("design:type", Function),
15946
- _ts_metadata58("design:paramtypes", [
16554
+ _ts_param39(0, common.Inject(BYMAX_AUTH_OPTIONS)),
16555
+ _ts_param39(0, common.Optional()),
16556
+ _ts_metadata61("design:type", Function),
16557
+ _ts_metadata61("design:paramtypes", [
15947
16558
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
15948
16559
  ])
15949
16560
  ], exports.CommonPasswordChecker);
15950
- function _ts_decorate62(decorators, target, key, desc) {
16561
+ function _ts_decorate65(decorators, target, key, desc) {
15951
16562
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15952
16563
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15953
16564
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15960,7 +16571,7 @@ function _ts_decorate62(decorators, target, key, desc) {
15960
16571
  }
15961
16572
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15962
16573
  }
15963
- __name(_ts_decorate62, "_ts_decorate");
16574
+ __name(_ts_decorate65, "_ts_decorate");
15964
16575
  exports.NoOpEmailProvider = class _NoOpEmailProvider {
15965
16576
  static {
15966
16577
  __name(this, "NoOpEmailProvider");
@@ -15995,10 +16606,21 @@ exports.NoOpEmailProvider = class _NoOpEmailProvider {
15995
16606
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
15996
16607
  }
15997
16608
  };
15998
- exports.NoOpEmailProvider = _ts_decorate62([
16609
+ exports.NoOpEmailProvider = _ts_decorate65([
15999
16610
  common.Injectable()
16000
16611
  ], exports.NoOpEmailProvider);
16001
- function _ts_decorate63(decorators, target, key, desc) {
16612
+
16613
+ // src/server/services/api-key-clock.ts
16614
+ var SystemApiKeyClock = class {
16615
+ static {
16616
+ __name(this, "SystemApiKeyClock");
16617
+ }
16618
+ /** @returns The current instant. */
16619
+ now() {
16620
+ return /* @__PURE__ */ new Date();
16621
+ }
16622
+ };
16623
+ function _ts_decorate66(decorators, target, key, desc) {
16002
16624
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16003
16625
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16004
16626
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16011,20 +16633,330 @@ function _ts_decorate63(decorators, target, key, desc) {
16011
16633
  }
16012
16634
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16013
16635
  }
16014
- __name(_ts_decorate63, "_ts_decorate");
16015
- function _ts_metadata59(metadataKey, metadataValue) {
16636
+ __name(_ts_decorate66, "_ts_decorate");
16637
+ function _ts_metadata62(metadataKey, metadataValue) {
16016
16638
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16017
16639
  return Reflect.metadata(metadataKey, metadataValue);
16018
16640
  }
16019
16641
  }
16020
- __name(_ts_metadata59, "_ts_metadata");
16021
- function _ts_param37(paramIndex, decorator) {
16642
+ __name(_ts_metadata62, "_ts_metadata");
16643
+ function _ts_param40(paramIndex, decorator) {
16022
16644
  return function(target, key) {
16023
16645
  decorator(target, key, paramIndex);
16024
16646
  };
16025
16647
  }
16026
- __name(_ts_param37, "_ts_param");
16027
- exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16648
+ __name(_ts_param40, "_ts_param");
16649
+ var ApiKeyScopeAuditService = class {
16650
+ static {
16651
+ __name(this, "ApiKeyScopeAuditService");
16652
+ }
16653
+ discovery;
16654
+ scanner;
16655
+ reflector;
16656
+ options;
16657
+ constructor(discovery, scanner, reflector, options) {
16658
+ this.discovery = discovery;
16659
+ this.scanner = scanner;
16660
+ this.reflector = reflector;
16661
+ this.options = options;
16662
+ }
16663
+ /** @throws {Error} Naming every route that declares a scope the vocabulary lacks. */
16664
+ onApplicationBootstrap() {
16665
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16666
+ const problems = [];
16667
+ for (const wrapper of this.discovery.getControllers()) {
16668
+ const { instance, metatype } = wrapper;
16669
+ if (!instance || typeof metatype !== "function") continue;
16670
+ this.collect(problems, vocabulary, metatype.name, this.reflector.get(API_KEY_SCOPES_KEY, metatype));
16671
+ const prototype = Object.getPrototypeOf(instance);
16672
+ for (const method of this.scanner.getAllMethodNames(prototype)) {
16673
+ const handler = prototype[method];
16674
+ this.collect(problems, vocabulary, `${metatype.name}.${method}`, this.reflector.get(API_KEY_SCOPES_KEY, handler));
16675
+ }
16676
+ }
16677
+ if (problems.length > 0) {
16678
+ throw new Error(`[BymaxAuthModule] ${problems.join("; ")}. Add the scope to apiKeys.scopes or correct the declaration.`);
16679
+ }
16680
+ }
16681
+ collect(problems, vocabulary, where, declared) {
16682
+ if (!Array.isArray(declared)) return;
16683
+ for (const scope of declared) {
16684
+ if (!vocabulary.has(scope)) {
16685
+ problems.push(`${where} declares a scope outside apiKeys.scopes`);
16686
+ return;
16687
+ }
16688
+ }
16689
+ }
16690
+ };
16691
+ ApiKeyScopeAuditService = _ts_decorate66([
16692
+ common.Injectable(),
16693
+ _ts_param40(0, common.Inject(core.DiscoveryService)),
16694
+ _ts_param40(1, common.Inject(core.MetadataScanner)),
16695
+ _ts_param40(2, common.Inject(core.Reflector)),
16696
+ _ts_param40(3, common.Inject(BYMAX_AUTH_OPTIONS)),
16697
+ _ts_metadata62("design:type", Function),
16698
+ _ts_metadata62("design:paramtypes", [
16699
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
16700
+ typeof core.MetadataScanner === "undefined" ? Object : core.MetadataScanner,
16701
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
16702
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16703
+ ])
16704
+ ], ApiKeyScopeAuditService);
16705
+ function _ts_decorate67(decorators, target, key, desc) {
16706
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16707
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16708
+ r = Reflect.decorate(decorators, target, key, desc);
16709
+ } else {
16710
+ for (var i = decorators.length - 1; i >= 0; i--) {
16711
+ if (d = decorators[i]) {
16712
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16713
+ }
16714
+ }
16715
+ }
16716
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16717
+ }
16718
+ __name(_ts_decorate67, "_ts_decorate");
16719
+ function _ts_metadata63(metadataKey, metadataValue) {
16720
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16721
+ return Reflect.metadata(metadataKey, metadataValue);
16722
+ }
16723
+ }
16724
+ __name(_ts_metadata63, "_ts_metadata");
16725
+ function _ts_param41(paramIndex, decorator) {
16726
+ return function(target, key) {
16727
+ decorator(target, key, paramIndex);
16728
+ };
16729
+ }
16730
+ __name(_ts_param41, "_ts_param");
16731
+ var API_KEY_MAX_LABEL_LENGTH = 128;
16732
+ var API_KEY_MAX_OVERLAP_SECONDS = 2592e3;
16733
+ var CONTROL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
16734
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
16735
+ exports.ApiKeyService = class ApiKeyService {
16736
+ static {
16737
+ __name(this, "ApiKeyService");
16738
+ }
16739
+ repository;
16740
+ clock;
16741
+ options;
16742
+ constructor(repository, clock, options) {
16743
+ this.repository = repository;
16744
+ this.clock = clock;
16745
+ this.options = options;
16746
+ }
16747
+ /**
16748
+ * Issues a new key.
16749
+ *
16750
+ * @param input - Label, scopes and optional expiry.
16751
+ * @returns The plaintext key (once) and the stored record.
16752
+ * @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
16753
+ */
16754
+ async issue(input) {
16755
+ const now = this.clock.now();
16756
+ const label = this.validatedLabel(input.label);
16757
+ const scopes = this.validatedScopes(input.scopes);
16758
+ const expiresAt = this.validatedExpiry("expiresAt", input.expiresAt, now);
16759
+ const id = crypto.randomUUID();
16760
+ const secret = generateApiKeySecret();
16761
+ const stored = await this.repository.create({
16762
+ id,
16763
+ label,
16764
+ digest: apiKeyDigest(secret, this.options.apiKeys.pepper),
16765
+ scopes,
16766
+ createdAt: now,
16767
+ expiresAt
16768
+ });
16769
+ return {
16770
+ key: formatApiKey(this.options.apiKeys.prefix, id, secret),
16771
+ record: summary(stored)
16772
+ };
16773
+ }
16774
+ /**
16775
+ * Revokes a key now. Revoking an already revoked key succeeds.
16776
+ *
16777
+ * @param id - The key's row id.
16778
+ * @throws {AuthException} `auth.api_key_not_found` when no such key exists.
16779
+ */
16780
+ async revoke(id) {
16781
+ if (!UUID_PATTERN.test(id) || !await this.repository.markRevoked(id, this.clock.now())) {
16782
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16783
+ }
16784
+ }
16785
+ /**
16786
+ * Replaces a key with a new one carrying the same label and scopes.
16787
+ *
16788
+ * The new key is issued first and the old one retired second, so a failure between the two
16789
+ * leaves both valid — the safe direction — rather than neither.
16790
+ *
16791
+ * @param id - The active key to replace.
16792
+ * @param input - The overlap and an optional expiry for the new key.
16793
+ * @returns The new key, plaintext once.
16794
+ * @throws {AuthException} `auth.validation` for a bad overlap or expiry;
16795
+ * `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
16796
+ * rotated: that would re-issue access nobody holds).
16797
+ */
16798
+ async rotate(id, input) {
16799
+ const now = this.clock.now();
16800
+ const overlap = input.overlapSeconds;
16801
+ if (!Number.isInteger(overlap) || overlap < 0 || overlap > API_KEY_MAX_OVERLAP_SECONDS) {
16802
+ throw validation("overlapSeconds", `overlapSeconds must be an integer from 0 to ${API_KEY_MAX_OVERLAP_SECONDS}`);
16803
+ }
16804
+ const newExpiry = this.validatedExpiry("expiresAt", input.expiresAt, now);
16805
+ const old = UUID_PATTERN.test(id) ? await this.repository.findById(id) : null;
16806
+ if (old === null || !isActive(old, now)) {
16807
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16808
+ }
16809
+ const issued = await this.issue({
16810
+ label: old.label,
16811
+ scopes: old.scopes,
16812
+ ...newExpiry === null ? {} : {
16813
+ expiresAt: newExpiry
16814
+ }
16815
+ });
16816
+ if (overlap === 0) {
16817
+ await this.repository.markRevoked(old.id, now);
16818
+ } else {
16819
+ const retireAt = new Date(now.getTime() + overlap * 1e3);
16820
+ const sooner = (
16821
+ // Stryker disable next-line EqualityOperator: at equal instants both arms yield a Date of the same time, so `<` and `<=` store the same expiry
16822
+ old.expiresAt !== null && old.expiresAt.getTime() < retireAt.getTime() ? old.expiresAt : retireAt
16823
+ );
16824
+ await this.repository.setExpiry(old.id, sooner);
16825
+ }
16826
+ return issued;
16827
+ }
16828
+ validatedLabel(label) {
16829
+ if (typeof label !== "string" || label.trim().length === 0 || label.length > API_KEY_MAX_LABEL_LENGTH || CONTROL_CHARACTERS.test(label)) {
16830
+ throw validation("label", `label must be 1 to ${API_KEY_MAX_LABEL_LENGTH} characters with no control characters`);
16831
+ }
16832
+ return label;
16833
+ }
16834
+ validatedScopes(scopes) {
16835
+ if (!Array.isArray(scopes) || scopes.length === 0) {
16836
+ throw validation("scopes", "scopes must be a non-empty list");
16837
+ }
16838
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16839
+ const seen = /* @__PURE__ */ new Set();
16840
+ for (const scope of scopes) {
16841
+ if (!vocabulary.has(scope)) {
16842
+ throw validation("scopes", "every scope must come from the configured vocabulary");
16843
+ }
16844
+ if (seen.has(scope)) throw validation("scopes", "scopes must not repeat");
16845
+ seen.add(scope);
16846
+ }
16847
+ return [
16848
+ ...scopes
16849
+ ];
16850
+ }
16851
+ validatedExpiry(field, value, now) {
16852
+ if (value === void 0) return null;
16853
+ if (!(value instanceof Date) || Number.isNaN(value.getTime()) || value.getTime() <= now.getTime()) {
16854
+ throw validation(field, `${field} must be a valid date in the future`);
16855
+ }
16856
+ return value;
16857
+ }
16858
+ };
16859
+ exports.ApiKeyService = _ts_decorate67([
16860
+ common.Injectable(),
16861
+ _ts_param41(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
16862
+ _ts_param41(1, common.Inject(BYMAX_AUTH_API_KEY_CLOCK)),
16863
+ _ts_param41(2, common.Inject(BYMAX_AUTH_OPTIONS)),
16864
+ _ts_metadata63("design:type", Function),
16865
+ _ts_metadata63("design:paramtypes", [
16866
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
16867
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
16868
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16869
+ ])
16870
+ ], exports.ApiKeyService);
16871
+ function isActive(key, now) {
16872
+ const nowMs = now.getTime();
16873
+ return key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > nowMs);
16874
+ }
16875
+ __name(isActive, "isActive");
16876
+ function summary(row) {
16877
+ const { digest: _digest, ...rest } = row;
16878
+ return rest;
16879
+ }
16880
+ __name(summary, "summary");
16881
+ function validation(field, message) {
16882
+ return new AuthException(AUTH_ERROR_CODES.VALIDATION, [
16883
+ {
16884
+ field,
16885
+ message
16886
+ }
16887
+ ]);
16888
+ }
16889
+ __name(validation, "validation");
16890
+
16891
+ // src/server/utils/handshake-request.ts
16892
+ function handshakeRequest(handshake) {
16893
+ const headers = {};
16894
+ for (const [name, value] of Object.entries(handshake.headers)) {
16895
+ headers[name.toLowerCase()] = value;
16896
+ }
16897
+ return {
16898
+ headers,
16899
+ url: handshake.url ?? "",
16900
+ hostname: hostnameOf(headers["host"])
16901
+ };
16902
+ }
16903
+ __name(handshakeRequest, "handshakeRequest");
16904
+ function hostnameOf(host) {
16905
+ if (typeof host !== "string") return "";
16906
+ const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
16907
+ const index = host.indexOf(":", offset);
16908
+ return index === -1 ? host : host.substring(0, index);
16909
+ }
16910
+ __name(hostnameOf, "hostnameOf");
16911
+
16912
+ // src/server/utils/assert-tenant-binding.ts
16913
+ function tenantBindingEnforced(options) {
16914
+ return options.enforceTenantBinding === true && options.tenantIdResolver !== void 0;
16915
+ }
16916
+ __name(tenantBindingEnforced, "tenantBindingEnforced");
16917
+ async function assertTenantBinding(options, handshake, tenantId) {
16918
+ const resolver = options.tenantIdResolver;
16919
+ if (options.enforceTenantBinding !== true || !resolver) return;
16920
+ let requestTenant;
16921
+ try {
16922
+ requestTenant = await resolver(handshakeRequest(handshake));
16923
+ } catch {
16924
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16925
+ }
16926
+ if (requestTenant !== tenantId) {
16927
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16928
+ }
16929
+ }
16930
+ __name(assertTenantBinding, "assertTenantBinding");
16931
+
16932
+ // src/server/services/auth-token-verifier.service.ts
16933
+ function _ts_decorate68(decorators, target, key, desc) {
16934
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16935
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16936
+ r = Reflect.decorate(decorators, target, key, desc);
16937
+ } else {
16938
+ for (var i = decorators.length - 1; i >= 0; i--) {
16939
+ if (d = decorators[i]) {
16940
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16941
+ }
16942
+ }
16943
+ }
16944
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16945
+ }
16946
+ __name(_ts_decorate68, "_ts_decorate");
16947
+ function _ts_metadata64(metadataKey, metadataValue) {
16948
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16949
+ return Reflect.metadata(metadataKey, metadataValue);
16950
+ }
16951
+ }
16952
+ __name(_ts_metadata64, "_ts_metadata");
16953
+ function _ts_param42(paramIndex, decorator) {
16954
+ return function(target, key) {
16955
+ decorator(target, key, paramIndex);
16956
+ };
16957
+ }
16958
+ __name(_ts_param42, "_ts_param");
16959
+ exports.AuthTokenVerifierService = class _AuthTokenVerifierService {
16028
16960
  static {
16029
16961
  __name(this, "AuthTokenVerifierService");
16030
16962
  }
@@ -16032,6 +16964,9 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16032
16964
  options;
16033
16965
  revocation;
16034
16966
  accountStatus;
16967
+ logger = new common.Logger(_AuthTokenVerifierService.name);
16968
+ /** Whether the "binding not applied" warning has been logged by this instance. */
16969
+ warnedUnbound = false;
16035
16970
  /**
16036
16971
  * @param jwtService - The Nest JWT service, configured with the current signing secret.
16037
16972
  * @param options - Resolved module options, for the algorithm, the binding claims and the
@@ -16075,7 +17010,9 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16075
17010
  */
16076
17011
  async verifyAccessToken(token, options) {
16077
17012
  const { plane, requireMfa = true, checkStatus = true } = options;
16078
- if (plane === "dashboard") return await this.verifyDashboard(token, requireMfa, checkStatus);
17013
+ if (plane === "dashboard") {
17014
+ return await this.verifyDashboard(token, requireMfa, checkStatus, options.request);
17015
+ }
16079
17016
  if (plane === "platform") return await this.verifyPlatform(token, requireMfa, checkStatus);
16080
17017
  throw new TypeError(`verifyAccessToken: plane must be 'dashboard' or 'platform'`);
16081
17018
  }
@@ -16085,10 +17022,11 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16085
17022
  * @param token - The compact JWT.
16086
17023
  * @param requireMfa - Whether to apply the MFA policy.
16087
17024
  * @param checkStatus - Whether to consult the account's current status.
17025
+ * @param request - The request the token arrived on, for `enforceTenantBinding`.
16088
17026
  * @returns The verified dashboard payload.
16089
17027
  * @throws {@link AuthException} as {@link verifyAccessToken} documents.
16090
17028
  */
16091
- async verifyDashboard(token, requireMfa, checkStatus) {
17029
+ async verifyDashboard(token, requireMfa, checkStatus, request) {
16092
17030
  const payload = this.verifySignature(token);
16093
17031
  assertValidJti(payload.jti);
16094
17032
  assertValidSub(payload.sub);
@@ -16097,6 +17035,7 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16097
17035
  if (await this.revocation.isAccessTokenRevoked(payload, "dashboard")) {
16098
17036
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16099
17037
  }
17038
+ await this.assertBound(payload.tenantId, request);
16100
17039
  if (requireMfa) this.assertMfaClaimShape(payload);
16101
17040
  if (checkStatus) {
16102
17041
  await this.accountStatus.assertDashboardAccountUsable({
@@ -16111,6 +17050,23 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16111
17050
  };
16112
17051
  }
16113
17052
  /**
17053
+ * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
17054
+ *
17055
+ * @param tenantId - The tenant the token was issued for.
17056
+ * @param request - The request the token arrived on, when the caller supplied one.
17057
+ * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
17058
+ */
17059
+ async assertBound(tenantId, request) {
17060
+ if (request !== void 0) {
17061
+ await assertTenantBinding(this.options, request, tenantId);
17062
+ return;
17063
+ }
17064
+ if (tenantBindingEnforced(this.options) && !this.warnedUnbound) {
17065
+ this.warnedUnbound = true;
17066
+ 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`.");
17067
+ }
17068
+ }
17069
+ /**
16114
17070
  * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
16115
17071
  * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
16116
17072
  *
@@ -16183,14 +17139,14 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16183
17139
  }
16184
17140
  }
16185
17141
  };
16186
- exports.AuthTokenVerifierService = _ts_decorate63([
17142
+ exports.AuthTokenVerifierService = _ts_decorate68([
16187
17143
  common.Injectable(),
16188
- _ts_param37(0, common.Inject(jwt.JwtService)),
16189
- _ts_param37(1, common.Inject(BYMAX_AUTH_OPTIONS)),
16190
- _ts_param37(2, common.Inject(exports.AuthRevocationService)),
16191
- _ts_param37(3, common.Inject(exports.AccountStatusService)),
16192
- _ts_metadata59("design:type", Function),
16193
- _ts_metadata59("design:paramtypes", [
17144
+ _ts_param42(0, common.Inject(jwt.JwtService)),
17145
+ _ts_param42(1, common.Inject(BYMAX_AUTH_OPTIONS)),
17146
+ _ts_param42(2, common.Inject(exports.AuthRevocationService)),
17147
+ _ts_param42(3, common.Inject(exports.AccountStatusService)),
17148
+ _ts_metadata64("design:type", Function),
17149
+ _ts_metadata64("design:paramtypes", [
16194
17150
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
16195
17151
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
16196
17152
  typeof exports.AuthRevocationService === "undefined" ? Object : exports.AuthRevocationService,
@@ -16199,7 +17155,7 @@ exports.AuthTokenVerifierService = _ts_decorate63([
16199
17155
  ], exports.AuthTokenVerifierService);
16200
17156
 
16201
17157
  // src/server/bymax-auth.module.ts
16202
- function _ts_decorate64(decorators, target, key, desc) {
17158
+ function _ts_decorate69(decorators, target, key, desc) {
16203
17159
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16204
17160
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16205
17161
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16212,7 +17168,7 @@ function _ts_decorate64(decorators, target, key, desc) {
16212
17168
  }
16213
17169
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16214
17170
  }
16215
- __name(_ts_decorate64, "_ts_decorate");
17171
+ __name(_ts_decorate69, "_ts_decorate");
16216
17172
  function hasProviderToken(providers, token) {
16217
17173
  return providers.some((p) => {
16218
17174
  if (typeof p === "function") return false;
@@ -16220,6 +17176,15 @@ function hasProviderToken(providers, token) {
16220
17176
  });
16221
17177
  }
16222
17178
  __name(hasProviderToken, "hasProviderToken");
17179
+ function cannotAuditApiKeys(providers) {
17180
+ const hooks = providers.find((p) => "provide" in p && p.provide === BYMAX_AUTH_HOOKS);
17181
+ if (hooks === void 0) return true;
17182
+ if ("useValue" in hooks) {
17183
+ return typeof hooks.useValue?.onApiKeyRequest !== "function";
17184
+ }
17185
+ return false;
17186
+ }
17187
+ __name(cannotAuditApiKeys, "cannotAuditApiKeys");
16223
17188
  exports.BymaxAuthModule = class _BymaxAuthModule {
16224
17189
  static {
16225
17190
  __name(this, "BymaxAuthModule");
@@ -16247,6 +17212,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16247
17212
  const includePlatform = options.controllers?.platform === true;
16248
17213
  const includeOAuth = options.controllers?.oauth === true;
16249
17214
  const includeInvitations = options.controllers?.invitations === true;
17215
+ const includeApiKeys = hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_REPOSITORY);
16250
17216
  const includeEmailChange = options.controllers?.emailChange === true;
16251
17217
  const resolvedOptionsProvider = {
16252
17218
  provide: BYMAX_AUTH_OPTIONS,
@@ -16280,10 +17246,29 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16280
17246
  if (includeInvitations && !resolved.invitations?.enabled) {
16281
17247
  throw new Error("[BymaxAuthModule] controllers.invitations: true requires invitations.enabled: true in the useFactory return value.");
16282
17248
  }
17249
+ if (includeApiKeys !== resolved.apiKeys.enabled) {
17250
+ 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.");
17251
+ }
17252
+ if (resolved.apiKeys.auditMode === "required" && cannotAuditApiKeys(extraProviders)) {
17253
+ 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'.");
17254
+ }
16283
17255
  return resolved;
16284
17256
  }, "useFactory"),
16285
17257
  inject: options.inject ?? []
16286
17258
  };
17259
+ const apiKeyProviders = includeApiKeys ? [
17260
+ ...hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_CLOCK) ? [] : [
17261
+ {
17262
+ provide: BYMAX_AUTH_API_KEY_CLOCK,
17263
+ useClass: SystemApiKeyClock
17264
+ }
17265
+ ],
17266
+ ApiKeyLastUsedService,
17267
+ ApiKeyVerifierService,
17268
+ exports.ApiKeyService,
17269
+ exports.ApiKeyGuard,
17270
+ ApiKeyScopeAuditService
17271
+ ] : [];
16287
17272
  const emailProviders = hasProviderToken(extraProviders, BYMAX_AUTH_EMAIL_PROVIDER) ? [] : [
16288
17273
  {
16289
17274
  provide: BYMAX_AUTH_EMAIL_PROVIDER,
@@ -16364,6 +17349,10 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16364
17349
  module: _BymaxAuthModule,
16365
17350
  imports: [
16366
17351
  ...options.imports ?? [],
17352
+ // The bootstrap scope audit walks controllers through the discovery service.
17353
+ ...includeApiKeys ? [
17354
+ core.DiscoveryModule
17355
+ ] : [],
16367
17356
  // JwtModule reads the secret directly from the consumer factory (without re-running
16368
17357
  // resolveOptions) to avoid double-validation on startup. Full validation happens once
16369
17358
  // in the BYMAX_AUTH_OPTIONS provider above.
@@ -16457,7 +17446,9 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16457
17446
  // Invitation service — only when controllers.invitations: true.
16458
17447
  ...invitationProviders,
16459
17448
  // Address-change service — only when controllers.emailChange: true.
16460
- ...emailChangeProviders
17449
+ ...emailChangeProviders,
17450
+ // Service API keys — only when the host supplied the repository.
17451
+ ...apiKeyProviders
16461
17452
  ],
16462
17453
  controllers,
16463
17454
  exports: [
@@ -16545,6 +17536,15 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16545
17536
  // export BYMAX_AUTH_USER_REPOSITORY as the instance supplied by the consumer` test, which
16546
17537
  // is the one that fails without it.
16547
17538
  BYMAX_AUTH_USER_REPOSITORY,
17539
+ // Service API keys: the guard is re-instantiated in the consumer's injector by
17540
+ // `@ServiceKey()`, so its direct dependencies must be exported with it — the verifier and
17541
+ // the hooks. The service is public surface for a host's own admin routes.
17542
+ ...includeApiKeys ? [
17543
+ exports.ApiKeyGuard,
17544
+ ApiKeyVerifierService,
17545
+ exports.ApiKeyService,
17546
+ BYMAX_AUTH_HOOKS
17547
+ ] : [],
16548
17548
  // WsTicketService also stands on its own as public surface: single-use ticket
16549
17549
  // handshakes are the credential a realtime transport is meant to use, and a consumer
16550
17550
  // cannot mint one without injecting this service.
@@ -16556,7 +17556,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16556
17556
  };
16557
17557
  }
16558
17558
  };
16559
- exports.BymaxAuthModule = _ts_decorate64([
17559
+ exports.BymaxAuthModule = _ts_decorate69([
16560
17560
  common.Module({})
16561
17561
  ], exports.BymaxAuthModule);
16562
17562
 
@@ -16884,7 +17884,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
16884
17884
  }
16885
17885
  }
16886
17886
  };
16887
- function _ts_decorate65(decorators, target, key, desc) {
17887
+ function _ts_decorate70(decorators, target, key, desc) {
16888
17888
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16889
17889
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16890
17890
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16897,13 +17897,13 @@ function _ts_decorate65(decorators, target, key, desc) {
16897
17897
  }
16898
17898
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16899
17899
  }
16900
- __name(_ts_decorate65, "_ts_decorate");
16901
- function _ts_metadata60(metadataKey, metadataValue) {
17900
+ __name(_ts_decorate70, "_ts_decorate");
17901
+ function _ts_metadata65(metadataKey, metadataValue) {
16902
17902
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16903
17903
  return Reflect.metadata(metadataKey, metadataValue);
16904
17904
  }
16905
17905
  }
16906
- __name(_ts_metadata60, "_ts_metadata");
17906
+ __name(_ts_metadata65, "_ts_metadata");
16907
17907
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
16908
17908
  var PREFIX_LENGTH = 5;
16909
17909
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -16960,10 +17960,10 @@ exports.HibpBreachChecker = class _HibpBreachChecker {
16960
17960
  }
16961
17961
  }
16962
17962
  };
16963
- exports.HibpBreachChecker = _ts_decorate65([
17963
+ exports.HibpBreachChecker = _ts_decorate70([
16964
17964
  common.Injectable(),
16965
- _ts_metadata60("design:type", Function),
16966
- _ts_metadata60("design:paramtypes", [
17965
+ _ts_metadata65("design:type", Function),
17966
+ _ts_metadata65("design:paramtypes", [
16967
17967
  Number
16968
17968
  ])
16969
17969
  ], exports.HibpBreachChecker);
@@ -16976,10 +17976,10 @@ exports.AllowAllBreachChecker = class AllowAllBreachChecker {
16976
17976
  return false;
16977
17977
  }
16978
17978
  };
16979
- exports.AllowAllBreachChecker = _ts_decorate65([
17979
+ exports.AllowAllBreachChecker = _ts_decorate70([
16980
17980
  common.Injectable()
16981
17981
  ], exports.AllowAllBreachChecker);
16982
- function _ts_decorate66(decorators, target, key, desc) {
17982
+ function _ts_decorate71(decorators, target, key, desc) {
16983
17983
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16984
17984
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16985
17985
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16992,7 +17992,7 @@ function _ts_decorate66(decorators, target, key, desc) {
16992
17992
  }
16993
17993
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16994
17994
  }
16995
- __name(_ts_decorate66, "_ts_decorate");
17995
+ __name(_ts_decorate71, "_ts_decorate");
16996
17996
  exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard {
16997
17997
  static {
16998
17998
  __name(this, "OptionalAuthGuard");
@@ -17007,10 +18007,10 @@ exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard
17007
18007
  return super.canActivate(context);
17008
18008
  }
17009
18009
  };
17010
- exports.OptionalAuthGuard = _ts_decorate66([
18010
+ exports.OptionalAuthGuard = _ts_decorate71([
17011
18011
  common.Injectable()
17012
18012
  ], exports.OptionalAuthGuard);
17013
- function _ts_decorate67(decorators, target, key, desc) {
18013
+ function _ts_decorate72(decorators, target, key, desc) {
17014
18014
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17015
18015
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17016
18016
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17023,19 +18023,19 @@ function _ts_decorate67(decorators, target, key, desc) {
17023
18023
  }
17024
18024
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17025
18025
  }
17026
- __name(_ts_decorate67, "_ts_decorate");
17027
- function _ts_metadata61(metadataKey, metadataValue) {
18026
+ __name(_ts_decorate72, "_ts_decorate");
18027
+ function _ts_metadata66(metadataKey, metadataValue) {
17028
18028
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17029
18029
  return Reflect.metadata(metadataKey, metadataValue);
17030
18030
  }
17031
18031
  }
17032
- __name(_ts_metadata61, "_ts_metadata");
17033
- function _ts_param38(paramIndex, decorator) {
18032
+ __name(_ts_metadata66, "_ts_metadata");
18033
+ function _ts_param43(paramIndex, decorator) {
17034
18034
  return function(target, key) {
17035
18035
  decorator(target, key, paramIndex);
17036
18036
  };
17037
18037
  }
17038
- __name(_ts_param38, "_ts_param");
18038
+ __name(_ts_param43, "_ts_param");
17039
18039
  exports.SelfOrAdminGuard = class SelfOrAdminGuard {
17040
18040
  static {
17041
18041
  __name(this, "SelfOrAdminGuard");
@@ -17065,11 +18065,11 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
17065
18065
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
17066
18066
  }
17067
18067
  };
17068
- exports.SelfOrAdminGuard = _ts_decorate67([
18068
+ exports.SelfOrAdminGuard = _ts_decorate72([
17069
18069
  common.Injectable(),
17070
- _ts_param38(0, common.Inject(BYMAX_AUTH_OPTIONS)),
17071
- _ts_metadata61("design:type", Function),
17072
- _ts_metadata61("design:paramtypes", [
18070
+ _ts_param43(0, common.Inject(BYMAX_AUTH_OPTIONS)),
18071
+ _ts_metadata66("design:type", Function),
18072
+ _ts_metadata66("design:paramtypes", [
17073
18073
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
17074
18074
  ])
17075
18075
  ], exports.SelfOrAdminGuard);
@@ -17082,7 +18082,7 @@ function isHexLooking(value) {
17082
18082
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
17083
18083
  }
17084
18084
  __name(isHexLooking, "isHexLooking");
17085
- function _ts_decorate68(decorators, target, key, desc) {
18085
+ function _ts_decorate73(decorators, target, key, desc) {
17086
18086
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17087
18087
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17088
18088
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17095,19 +18095,19 @@ function _ts_decorate68(decorators, target, key, desc) {
17095
18095
  }
17096
18096
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17097
18097
  }
17098
- __name(_ts_decorate68, "_ts_decorate");
17099
- function _ts_metadata62(metadataKey, metadataValue) {
18098
+ __name(_ts_decorate73, "_ts_decorate");
18099
+ function _ts_metadata67(metadataKey, metadataValue) {
17100
18100
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17101
18101
  return Reflect.metadata(metadataKey, metadataValue);
17102
18102
  }
17103
18103
  }
17104
- __name(_ts_metadata62, "_ts_metadata");
17105
- function _ts_param39(paramIndex, decorator) {
18104
+ __name(_ts_metadata67, "_ts_metadata");
18105
+ function _ts_param44(paramIndex, decorator) {
17106
18106
  return function(target, key) {
17107
18107
  decorator(target, key, paramIndex);
17108
18108
  };
17109
18109
  }
17110
- __name(_ts_param39, "_ts_param");
18110
+ __name(_ts_param44, "_ts_param");
17111
18111
  exports.WsJwtGuard = class WsJwtGuard {
17112
18112
  static {
17113
18113
  __name(this, "WsJwtGuard");
@@ -17143,6 +18143,7 @@ exports.WsJwtGuard = class WsJwtGuard {
17143
18143
  if (ticket !== void 0) {
17144
18144
  const snapshot = await this.wsTickets.redeem(ticket);
17145
18145
  assertDashboardSnapshot(snapshot);
18146
+ await assertTenantBinding(this.options, handshake, snapshot.tenantId);
17146
18147
  client.data.user = snapshot;
17147
18148
  return true;
17148
18149
  }
@@ -17165,18 +18166,19 @@ exports.WsJwtGuard = class WsJwtGuard {
17165
18166
  if (await this.revocation.isAccessTokenRevoked(payload)) {
17166
18167
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
17167
18168
  }
18169
+ await assertTenantBinding(this.options, handshake, payload.tenantId);
17168
18170
  client.data.user = payload;
17169
18171
  return true;
17170
18172
  }
17171
18173
  };
17172
- exports.WsJwtGuard = _ts_decorate68([
18174
+ exports.WsJwtGuard = _ts_decorate73([
17173
18175
  common.Injectable(),
17174
- _ts_param39(0, common.Inject(jwt.JwtService)),
17175
- _ts_param39(1, common.Inject(exports.AuthRevocationService)),
17176
- _ts_param39(2, common.Inject(exports.WsTicketService)),
17177
- _ts_param39(3, common.Inject(BYMAX_AUTH_OPTIONS)),
17178
- _ts_metadata62("design:type", Function),
17179
- _ts_metadata62("design:paramtypes", [
18176
+ _ts_param44(0, common.Inject(jwt.JwtService)),
18177
+ _ts_param44(1, common.Inject(exports.AuthRevocationService)),
18178
+ _ts_param44(2, common.Inject(exports.WsTicketService)),
18179
+ _ts_param44(3, common.Inject(BYMAX_AUTH_OPTIONS)),
18180
+ _ts_metadata67("design:type", Function),
18181
+ _ts_metadata67("design:paramtypes", [
17180
18182
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
17181
18183
  typeof exports.AuthRevocationService === "undefined" ? Object : exports.AuthRevocationService,
17182
18184
  typeof exports.WsTicketService === "undefined" ? Object : exports.WsTicketService,
@@ -17209,7 +18211,7 @@ function readUpgradeTicket(handshake) {
17209
18211
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
17210
18212
  }
17211
18213
  __name(readUpgradeTicket, "readUpgradeTicket");
17212
- function _ts_decorate69(decorators, target, key, desc) {
18214
+ function _ts_decorate74(decorators, target, key, desc) {
17213
18215
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17214
18216
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17215
18217
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17222,7 +18224,7 @@ function _ts_decorate69(decorators, target, key, desc) {
17222
18224
  }
17223
18225
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17224
18226
  }
17225
- __name(_ts_decorate69, "_ts_decorate");
18227
+ __name(_ts_decorate74, "_ts_decorate");
17226
18228
  function isAuthEnvelope(body) {
17227
18229
  if (typeof body !== "object" || body === null) return false;
17228
18230
  const error = body.error;
@@ -17274,10 +18276,10 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
17274
18276
  });
17275
18277
  }
17276
18278
  };
17277
- exports.AuthExceptionFilter = _ts_decorate69([
18279
+ exports.AuthExceptionFilter = _ts_decorate74([
17278
18280
  common.Catch()
17279
18281
  ], exports.AuthExceptionFilter);
17280
- function _ts_decorate70(decorators, target, key, desc) {
18282
+ function _ts_decorate75(decorators, target, key, desc) {
17281
18283
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17282
18284
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17283
18285
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17290,7 +18292,7 @@ function _ts_decorate70(decorators, target, key, desc) {
17290
18292
  }
17291
18293
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17292
18294
  }
17293
- __name(_ts_decorate70, "_ts_decorate");
18295
+ __name(_ts_decorate75, "_ts_decorate");
17294
18296
  function isEmittingClient(client) {
17295
18297
  return typeof client?.emit === "function";
17296
18298
  }
@@ -17334,10 +18336,14 @@ exports.WsAuthExceptionFilter = class _WsAuthExceptionFilter {
17334
18336
  this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
17335
18337
  }
17336
18338
  };
17337
- exports.WsAuthExceptionFilter = _ts_decorate70([
18339
+ exports.WsAuthExceptionFilter = _ts_decorate75([
17338
18340
  common.Catch(AuthException)
17339
18341
  ], exports.WsAuthExceptionFilter);
18342
+ var ServiceKey = /* @__PURE__ */ __name((...scopes) => common.applyDecorators(common.SetMetadata(IS_PUBLIC_KEY, true), ApiKeyScopes(...scopes), common.UseGuards(exports.ApiKeyGuard)), "ServiceKey");
18343
+ var CurrentApiKey = common.createParamDecorator((_data, ctx) => ctx.switchToHttp().getRequest().apiKey);
17340
18344
 
18345
+ exports.API_KEY_MAX_LABEL_LENGTH = API_KEY_MAX_LABEL_LENGTH;
18346
+ exports.API_KEY_MAX_OVERLAP_SECONDS = API_KEY_MAX_OVERLAP_SECONDS;
17341
18347
  exports.AUTH_EMAIL_KINDS = AUTH_EMAIL_KINDS;
17342
18348
  exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
17343
18349
  exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
@@ -17345,9 +18351,12 @@ exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
17345
18351
  exports.AUTH_SECURITY_SCHEMES = AUTH_SECURITY_SCHEMES;
17346
18352
  exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
17347
18353
  exports.AcceptInvitationDto = AcceptInvitationDto;
18354
+ exports.ApiKeyScopes = ApiKeyScopes;
17348
18355
  exports.AuthException = AuthException;
17349
18356
  exports.AuthRateLimit = AuthRateLimit;
17350
18357
  exports.Authenticated = Authenticated;
18358
+ exports.BYMAX_AUTH_API_KEY_CLOCK = BYMAX_AUTH_API_KEY_CLOCK;
18359
+ exports.BYMAX_AUTH_API_KEY_REPOSITORY = BYMAX_AUTH_API_KEY_REPOSITORY;
17351
18360
  exports.BYMAX_AUTH_BREACH_CHECKER = BYMAX_AUTH_BREACH_CHECKER;
17352
18361
  exports.BYMAX_AUTH_EMAIL_PROVIDER = BYMAX_AUTH_EMAIL_PROVIDER;
17353
18362
  exports.BYMAX_AUTH_HOOKS = BYMAX_AUTH_HOOKS;
@@ -17357,6 +18366,7 @@ exports.BYMAX_AUTH_REDIS_CLIENT = BYMAX_AUTH_REDIS_CLIENT;
17357
18366
  exports.BYMAX_AUTH_USER_REPOSITORY = BYMAX_AUTH_USER_REPOSITORY;
17358
18367
  exports.ChangePasswordDto = ChangePasswordDto;
17359
18368
  exports.CreateInvitationDto = CreateInvitationDto;
18369
+ exports.CurrentApiKey = CurrentApiKey;
17360
18370
  exports.CurrentUser = CurrentUser;
17361
18371
  exports.DefaultAuthEmailProvider = DefaultAuthEmailProvider;
17362
18372
  exports.ForgotPasswordDto = ForgotPasswordDto;
@@ -17377,6 +18387,7 @@ exports.ResendVerificationDto = ResendVerificationDto;
17377
18387
  exports.ResetPasswordDto = ResetPasswordDto;
17378
18388
  exports.Roles = Roles;
17379
18389
  exports.SKIP_MFA_KEY = SKIP_MFA_KEY;
18390
+ exports.ServiceKey = ServiceKey;
17380
18391
  exports.SkipMfa = SkipMfa;
17381
18392
  exports.VerifyEmailDto = VerifyEmailDto;
17382
18393
  exports.VerifyOtpDto = VerifyOtpDto;