@bymax-one/nest-auth 1.4.6 → 1.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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));
@@ -8619,6 +8766,17 @@ exports.InvitationService = class _InvitationService {
8619
8766
  await this.redis.del(`inv:${supersededHash}`);
8620
8767
  }
8621
8768
  await this.redis.set(tokenKey, JSON.stringify(stored), ttl);
8769
+ let stillNamed;
8770
+ try {
8771
+ stillNamed = await this.claimInviteeIndex(normalizedEmail, tenantId, tokenHash, ttl, tokenHash);
8772
+ } catch (err) {
8773
+ await this.withdrawRecord(tokenKey);
8774
+ throw err;
8775
+ }
8776
+ if (!stillNamed.claimed) {
8777
+ await this.withdrawRecord(tokenKey);
8778
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8779
+ }
8622
8780
  const displayTenantName = tenantName ?? tenantId;
8623
8781
  const expiresAt = new Date(Date.now() + ttl * 1e3);
8624
8782
  try {
@@ -8745,6 +8903,21 @@ exports.InvitationService = class _InvitationService {
8745
8903
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
8746
8904
  }
8747
8905
  /**
8906
+ * Removes the invitation record this call wrote, best-effort.
8907
+ *
8908
+ * Used where the call is already ending in a refusal or a failure of its own, so a failing
8909
+ * delete must not replace that outcome: it is logged and the caller still raises the original.
8910
+ * The raw token has not been emailed at that point, so a record that survives is one nobody
8911
+ * holds the token for, until its TTL.
8912
+ *
8913
+ * @param tokenKey - The Redis key of the record written by this call.
8914
+ */
8915
+ async withdrawRecord(tokenKey) {
8916
+ await this.redis.del(tokenKey).catch((err) => {
8917
+ this.logger.warn(`invite: could not withdraw the record \u2014 ${describeChannelStatus(err)}`);
8918
+ });
8919
+ }
8920
+ /**
8748
8921
  * Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
8749
8922
  *
8750
8923
  * A compare-and-swap, not a plain write: the claim proceeds only when the index still holds
@@ -9466,6 +9639,18 @@ function decrypt(ciphertext, keyBase64) {
9466
9639
  }
9467
9640
  __name(decrypt, "decrypt");
9468
9641
 
9642
+ // src/server/utils/run-detached.ts
9643
+ function runDetached(logger, run, failure) {
9644
+ try {
9645
+ void Promise.resolve(run()).catch((err) => {
9646
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9647
+ });
9648
+ } catch (err) {
9649
+ logger.error(`${failure}: ${describeChannelStatus(err)}`);
9650
+ }
9651
+ }
9652
+ __name(runDetached, "runDetached");
9653
+
9469
9654
  // src/server/services/mfa.service.ts
9470
9655
  function _ts_decorate36(decorators, target, key, desc) {
9471
9656
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -10146,14 +10331,19 @@ exports.MfaService = class _MfaService {
10146
10331
  userAgent
10147
10332
  });
10148
10333
  }
10334
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
10335
+ id: safeUser.id,
10336
+ tenantId: safeUser.tenantId
10337
+ }), "challenge: updateLastLogin failed");
10149
10338
  if (this.hooks.afterLogin) {
10150
- void Promise.resolve(this.hooks.afterLogin(safeUser, {
10339
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10340
+ runDetached(this.logger, () => afterLogin(safeUser, {
10151
10341
  plane: "dashboard",
10152
10342
  userId,
10153
10343
  ip,
10154
10344
  userAgent,
10155
10345
  sanitizedHeaders: {}
10156
- })).catch(() => void 0);
10346
+ }), "challenge: afterLogin hook threw");
10157
10347
  }
10158
10348
  return result2;
10159
10349
  }
@@ -10161,14 +10351,16 @@ exports.MfaService = class _MfaService {
10161
10351
  const result = await this.tokenManager.issuePlatformTokens(this.toSafePlatformUser(platformUser), ip, userAgent, {
10162
10352
  mfaVerified: true
10163
10353
  });
10354
+ runDetached(this.logger, () => this.platformUserRepo.updateLastLogin(platformUser.id), "challenge: platform updateLastLogin failed");
10164
10355
  if (this.hooks.afterLogin) {
10165
- void Promise.resolve(this.hooks.afterLogin(this.platformUserAsSafeUser(platformUser), {
10356
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
10357
+ runDetached(this.logger, () => afterLogin(this.platformUserAsSafeUser(platformUser), {
10166
10358
  plane: "platform",
10167
10359
  userId,
10168
10360
  ip,
10169
10361
  userAgent,
10170
10362
  sanitizedHeaders: {}
10171
- })).catch(() => void 0);
10363
+ }), "challenge: afterLogin hook threw");
10172
10364
  }
10173
10365
  return result;
10174
10366
  }
@@ -13312,6 +13504,8 @@ SessionController = _ts_decorate50([
13312
13504
  typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService
13313
13505
  ])
13314
13506
  ], SessionController);
13507
+ var API_KEY_SCOPES_KEY = /* @__PURE__ */ Symbol("bymax:apiKeyScopes");
13508
+ var ApiKeyScopes = /* @__PURE__ */ __name((...scopes) => common.SetMetadata(API_KEY_SCOPES_KEY, scopes), "ApiKeyScopes");
13315
13509
  function _ts_decorate51(decorators, target, key, desc) {
13316
13510
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13317
13511
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13338,44 +13532,120 @@ function _ts_param30(paramIndex, decorator) {
13338
13532
  };
13339
13533
  }
13340
13534
  __name(_ts_param30, "_ts_param");
13341
- exports.MfaRequiredGuard = class MfaRequiredGuard {
13535
+ var ApiKeyLastUsedService = class _ApiKeyLastUsedService {
13342
13536
  static {
13343
- __name(this, "MfaRequiredGuard");
13537
+ __name(this, "ApiKeyLastUsedService");
13344
13538
  }
13345
- reflector;
13346
- constructor(reflector) {
13347
- this.reflector = reflector;
13539
+ repository;
13540
+ options;
13541
+ logger = new common.Logger(_ApiKeyLastUsedService.name);
13542
+ pending = /* @__PURE__ */ new Map();
13543
+ timer = null;
13544
+ closed = false;
13545
+ constructor(repository, options) {
13546
+ this.repository = repository;
13547
+ this.options = options;
13348
13548
  }
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);
13549
+ /**
13550
+ * Notes that a key verified at an instant. Synchronous and free of I/O.
13551
+ *
13552
+ * @param id - The key's row id.
13553
+ * @param at - When it verified.
13554
+ */
13555
+ record(id, at) {
13556
+ const seen = this.pending.get(id);
13557
+ if (seen === void 0 || seen.getTime() < at.getTime()) this.pending.set(id, at);
13558
+ if (this.timer === null && !this.closed) {
13559
+ this.timer = setTimeout(() => {
13560
+ this.timer = null;
13561
+ void this.flush();
13562
+ }, this.options.apiKeys.lastUsedFlushSeconds * 1e3);
13563
+ this.timer.unref();
13360
13564
  }
13361
- if (user.mfaEnabled === true && user.mfaVerified !== true) {
13362
- throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13565
+ }
13566
+ /**
13567
+ * Writes everything pending in one batch. A failure keeps the entries for the next window.
13568
+ *
13569
+ * @returns Resolves once the batch is written or has been put back.
13570
+ */
13571
+ async flush() {
13572
+ if (this.pending.size === 0) return;
13573
+ const batch = this.pending;
13574
+ this.pending = /* @__PURE__ */ new Map();
13575
+ try {
13576
+ await this.repository.touchLastUsed([
13577
+ ...batch
13578
+ ].map(([id, at]) => ({
13579
+ id,
13580
+ at
13581
+ })));
13582
+ } catch (err) {
13583
+ this.logger.warn(`api-key: last-used flush failed cause=${describeChannelStatus(err)}`);
13584
+ for (const [id, at] of batch) this.record(id, at);
13363
13585
  }
13364
- return true;
13586
+ }
13587
+ /** Flushes what is left so a clean shutdown loses nothing. */
13588
+ async onApplicationShutdown() {
13589
+ this.closed = true;
13590
+ if (this.timer !== null) clearTimeout(this.timer);
13591
+ this.timer = null;
13592
+ await this.flush();
13365
13593
  }
13366
13594
  };
13367
- exports.MfaRequiredGuard = _ts_decorate51([
13595
+ ApiKeyLastUsedService = _ts_decorate51([
13368
13596
  common.Injectable(),
13369
- _ts_param30(0, common.Inject(core.Reflector)),
13597
+ _ts_param30(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13598
+ _ts_param30(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13370
13599
  _ts_metadata50("design:type", Function),
13371
13600
  _ts_metadata50("design:paramtypes", [
13372
- typeof core.Reflector === "undefined" ? Object : core.Reflector
13601
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13602
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13373
13603
  ])
13374
- ], exports.MfaRequiredGuard);
13375
- var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13376
- var PlatformRoles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13604
+ ], ApiKeyLastUsedService);
13605
+ var SEPARATOR = "_";
13606
+ var KEY_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13607
+ var SECRET_PATTERN = /^[A-Za-z0-9_-]{43}$/;
13608
+ var SECRET_BYTES = 32;
13609
+ var DIGEST_HEX = /^[0-9a-f]{64}$/;
13610
+ var API_KEY_DUMMY_KEY_ID = "00000000-0000-4000-8000-000000000000";
13611
+ var API_KEY_DUMMY_SECRET = "A".repeat(43);
13612
+ var API_KEY_DUMMY_DIGEST = "0".repeat(64);
13613
+ function generateApiKeySecret() {
13614
+ return crypto.randomBytes(SECRET_BYTES).toString("base64url");
13615
+ }
13616
+ __name(generateApiKeySecret, "generateApiKeySecret");
13617
+ function formatApiKey(prefix, keyId, secret) {
13618
+ return `${prefix}${SEPARATOR}${keyId}${SEPARATOR}${secret}`;
13619
+ }
13620
+ __name(formatApiKey, "formatApiKey");
13621
+ function parseApiKey(raw, prefix) {
13622
+ if (typeof raw !== "string") return null;
13623
+ const head = `${prefix}${SEPARATOR}`;
13624
+ if (!raw.startsWith(head)) return null;
13625
+ const rest = raw.slice(head.length);
13626
+ const keyId = rest.slice(0, 36);
13627
+ if (rest[36] !== SEPARATOR) return null;
13628
+ const secret = rest.slice(37);
13629
+ if (!KEY_ID_PATTERN.test(keyId) || !SECRET_PATTERN.test(secret)) return null;
13630
+ return {
13631
+ keyId,
13632
+ secret
13633
+ };
13634
+ }
13635
+ __name(parseApiKey, "parseApiKey");
13636
+ function apiKeyDigest(secret, pepper) {
13637
+ return hmacSha256(secret, pepper);
13638
+ }
13639
+ __name(apiKeyDigest, "apiKeyDigest");
13640
+ function digestsMatch(computed, stored) {
13641
+ const wellFormed = DIGEST_HEX.test(computed) && DIGEST_HEX.test(stored);
13642
+ const left = Buffer.from(wellFormed ? computed : API_KEY_DUMMY_DIGEST, "hex");
13643
+ const right = Buffer.from(wellFormed ? stored : API_KEY_DUMMY_DIGEST, "hex");
13644
+ return crypto.timingSafeEqual(left, right) && wellFormed;
13645
+ }
13646
+ __name(digestsMatch, "digestsMatch");
13377
13647
 
13378
- // src/server/guards/platform-roles.guard.ts
13648
+ // src/server/services/api-key-verifier.service.ts
13379
13649
  function _ts_decorate52(decorators, target, key, desc) {
13380
13650
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13381
13651
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13402,53 +13672,81 @@ function _ts_param31(paramIndex, decorator) {
13402
13672
  };
13403
13673
  }
13404
13674
  __name(_ts_param31, "_ts_param");
13405
- exports.PlatformRolesGuard = class PlatformRolesGuard {
13675
+ var ApiKeyVerifierService = class {
13406
13676
  static {
13407
- __name(this, "PlatformRolesGuard");
13677
+ __name(this, "ApiKeyVerifierService");
13408
13678
  }
13409
- reflector;
13679
+ repository;
13680
+ clock;
13410
13681
  options;
13411
- constructor(reflector, options) {
13412
- this.reflector = reflector;
13682
+ lastUsed;
13683
+ constructor(repository, clock, options, lastUsed) {
13684
+ this.repository = repository;
13685
+ this.clock = clock;
13413
13686
  this.options = options;
13687
+ this.lastUsed = lastUsed;
13414
13688
  }
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);
13689
+ /**
13690
+ * Verifies the value of the key header.
13691
+ *
13692
+ * @param header - The header value as the framework delivered it.
13693
+ * @returns The verdict. A store fault propagates: the caller fails closed.
13694
+ */
13695
+ async verify(header) {
13696
+ const parsed = parseApiKey(header, this.options.apiKeys.prefix);
13697
+ const keyId = parsed?.keyId ?? API_KEY_DUMMY_KEY_ID;
13698
+ const secret = parsed?.secret ?? API_KEY_DUMMY_SECRET;
13699
+ const row = await this.repository.findById(keyId);
13700
+ const computed = apiKeyDigest(secret, this.options.apiKeys.pepper);
13701
+ const equal = digestsMatch(computed, row?.digest ?? API_KEY_DUMMY_DIGEST);
13702
+ const now = this.clock.now();
13703
+ const reason = this.rejection(header, parsed !== null, row, equal, now.getTime());
13704
+ if (reason !== null) {
13705
+ return {
13706
+ ok: false,
13707
+ reason,
13708
+ key: parsed === null ? null : row
13709
+ };
13434
13710
  }
13435
- return true;
13711
+ const key = row;
13712
+ this.lastUsed.record(key.id, now);
13713
+ return {
13714
+ ok: true,
13715
+ key
13716
+ };
13717
+ }
13718
+ /**
13719
+ * The single decision, evaluated after every step above has run.
13720
+ *
13721
+ * A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
13722
+ * comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
13723
+ * compares false against everything) reads as lapsed rather than as valid.
13724
+ */
13725
+ rejection(header, parsed, row, equal, nowMs) {
13726
+ if (!parsed) return header === void 0 ? "missing" : "malformed";
13727
+ if (row === null) return "unknown";
13728
+ if (!equal) return "wrong_secret";
13729
+ if (row.revokedAt !== null) return "revoked";
13730
+ if (row.expiresAt !== null && !(row.expiresAt.getTime() > nowMs)) return "expired";
13731
+ return null;
13436
13732
  }
13437
13733
  };
13438
- exports.PlatformRolesGuard = _ts_decorate52([
13734
+ ApiKeyVerifierService = _ts_decorate52([
13439
13735
  common.Injectable(),
13440
- _ts_param31(0, common.Inject(core.Reflector)),
13441
- _ts_param31(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13736
+ _ts_param31(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
13737
+ _ts_param31(1, common.Inject(BYMAX_AUTH_API_KEY_CLOCK)),
13738
+ _ts_param31(2, common.Inject(BYMAX_AUTH_OPTIONS)),
13739
+ _ts_param31(3, common.Inject(ApiKeyLastUsedService)),
13442
13740
  _ts_metadata51("design:type", Function),
13443
13741
  _ts_metadata51("design:paramtypes", [
13444
- typeof core.Reflector === "undefined" ? Object : core.Reflector,
13445
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13742
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
13743
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
13744
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13745
+ typeof ApiKeyLastUsedService === "undefined" ? Object : ApiKeyLastUsedService
13446
13746
  ])
13447
- ], exports.PlatformRolesGuard);
13448
- var ROLES_KEY = "roles";
13449
- var Roles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(ROLES_KEY, roles), "Roles");
13747
+ ], ApiKeyVerifierService);
13450
13748
 
13451
- // src/server/guards/roles.guard.ts
13749
+ // src/server/guards/api-key.guard.ts
13452
13750
  function _ts_decorate53(decorators, target, key, desc) {
13453
13751
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13454
13752
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13475,45 +13773,165 @@ function _ts_param32(paramIndex, decorator) {
13475
13773
  };
13476
13774
  }
13477
13775
  __name(_ts_param32, "_ts_param");
13478
- exports.RolesGuard = class RolesGuard {
13776
+ exports.ApiKeyGuard = class _ApiKeyGuard {
13479
13777
  static {
13480
- __name(this, "RolesGuard");
13778
+ __name(this, "ApiKeyGuard");
13481
13779
  }
13482
13780
  reflector;
13781
+ verifier;
13483
13782
  options;
13484
- constructor(reflector, options) {
13783
+ hooks;
13784
+ logger = new common.Logger(_ApiKeyGuard.name);
13785
+ constructor(reflector, verifier, options, hooks) {
13485
13786
  this.reflector = reflector;
13787
+ this.verifier = verifier;
13486
13788
  this.options = options;
13789
+ this.hooks = hooks;
13487
13790
  }
13488
- canActivate(context) {
13489
- const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
13791
+ async canActivate(context) {
13792
+ const request = context.switchToHttp().getRequest();
13793
+ const required = this.declaredScopes(context);
13794
+ const base = {
13795
+ method: request.method,
13796
+ route: routePattern(request),
13797
+ requiredScopes: required ?? []
13798
+ };
13799
+ if (required === null) {
13800
+ this.logger.error(`api-key: ${logSafe(request.method)} ${logSafe(base.route)} is guarded but declares no scopes; refused`);
13801
+ await this.audit(request, {
13802
+ ...base,
13803
+ outcome: "denied",
13804
+ reason: "route_undeclared"
13805
+ });
13806
+ throw new AuthException(AUTH_ERROR_CODES.FORBIDDEN);
13807
+ }
13808
+ let verdict;
13809
+ try {
13810
+ verdict = await this.verifier.verify(request.headers[this.options.apiKeys.header]);
13811
+ } catch (err) {
13812
+ this.logger.error(`api-key: key store unavailable cause=${describeChannelStatus(err)}`);
13813
+ await this.audit(request, {
13814
+ ...base,
13815
+ outcome: "denied",
13816
+ reason: "store_error"
13817
+ });
13818
+ throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13819
+ }
13820
+ if (!verdict.ok) {
13821
+ await this.audit(request, {
13822
+ ...base,
13823
+ outcome: "denied",
13824
+ reason: verdict.reason
13825
+ }, verdict.key);
13826
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_INVALID);
13827
+ }
13828
+ const { key } = verdict;
13829
+ if (!required.every((scope) => key.scopes.includes(scope))) {
13830
+ await this.audit(request, {
13831
+ ...base,
13832
+ outcome: "denied",
13833
+ reason: "scope_insufficient"
13834
+ }, key);
13835
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_SCOPE_INSUFFICIENT);
13836
+ }
13837
+ const delivered = await this.audit(request, {
13838
+ ...base,
13839
+ outcome: "allowed",
13840
+ reason: null
13841
+ }, key);
13842
+ if (!delivered) throw new AuthException(AUTH_ERROR_CODES.INTERNAL);
13843
+ request.apiKey = Object.freeze({
13844
+ id: key.id,
13845
+ label: key.label,
13846
+ scopes: Object.freeze([
13847
+ ...key.scopes
13848
+ ])
13849
+ });
13850
+ return true;
13851
+ }
13852
+ /**
13853
+ * The route's scope declaration: handler over class, empty or malformed counting as none.
13854
+ *
13855
+ * @returns The scopes, or `null` when the route declares none.
13856
+ */
13857
+ declaredScopes(context) {
13858
+ const declared = this.reflector.getAllAndOverride(API_KEY_SCOPES_KEY, [
13490
13859
  context.getHandler(),
13491
13860
  context.getClass()
13492
13861
  ]);
13493
- if (!requiredRoles || requiredRoles.length === 0) return true;
13494
- const request = context.switchToHttp().getRequest();
13495
- const userRole = request.user?.role;
13496
- if (!userRole) {
13497
- throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
13862
+ if (!Array.isArray(declared) || declared.length === 0 || !declared.every((scope) => typeof scope === "string")) {
13863
+ return null;
13498
13864
  }
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);
13865
+ return declared;
13866
+ }
13867
+ /**
13868
+ * Emits the audit event.
13869
+ *
13870
+ * @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
13871
+ * is fired without being awaited and the result is always `true`.
13872
+ */
13873
+ async audit(request, partial, key = null) {
13874
+ const hook = this.hooks?.onApiKeyRequest;
13875
+ if (hook === void 0) {
13876
+ if (this.options.apiKeys.auditMode !== "required") return true;
13877
+ this.logger.error("api-key: auditMode is required but no onApiKeyRequest hook is implemented; refusing");
13878
+ return false;
13879
+ }
13880
+ const event = {
13881
+ ...partial,
13882
+ keyId: key?.id ?? null,
13883
+ label: key?.label ?? null,
13884
+ ip: request.ip ?? ""
13885
+ };
13886
+ const context = this.hookContext(request);
13887
+ const run = /* @__PURE__ */ __name(() => hook.call(this.hooks, event, context), "run");
13888
+ if (this.options.apiKeys.auditMode === "required") {
13889
+ try {
13890
+ await run();
13891
+ return true;
13892
+ } catch (err) {
13893
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13894
+ return false;
13895
+ }
13896
+ }
13897
+ try {
13898
+ void Promise.resolve(run()).catch((err) => {
13899
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13900
+ });
13901
+ } catch (err) {
13902
+ this.logger.error(`api-key: audit hook failed cause=${describeChannelStatus(err)}`);
13503
13903
  }
13504
13904
  return true;
13505
13905
  }
13906
+ hookContext(request) {
13907
+ const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => name !== this.options.apiKeys.header));
13908
+ return {
13909
+ ip: request.ip ?? "",
13910
+ userAgent: request.headers["user-agent"] ?? "",
13911
+ sanitizedHeaders: sanitizeHeaders(headers)
13912
+ };
13913
+ }
13506
13914
  };
13507
- exports.RolesGuard = _ts_decorate53([
13915
+ exports.ApiKeyGuard = _ts_decorate53([
13508
13916
  common.Injectable(),
13509
13917
  _ts_param32(0, common.Inject(core.Reflector)),
13510
- _ts_param32(1, common.Inject(BYMAX_AUTH_OPTIONS)),
13918
+ _ts_param32(1, common.Inject(ApiKeyVerifierService)),
13919
+ _ts_param32(2, common.Inject(BYMAX_AUTH_OPTIONS)),
13920
+ _ts_param32(3, common.Inject(BYMAX_AUTH_HOOKS)),
13921
+ _ts_param32(3, common.Optional()),
13511
13922
  _ts_metadata52("design:type", Function),
13512
13923
  _ts_metadata52("design:paramtypes", [
13513
13924
  typeof core.Reflector === "undefined" ? Object : core.Reflector,
13514
- typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13925
+ typeof ApiKeyVerifierService === "undefined" ? Object : ApiKeyVerifierService,
13926
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
13927
+ Object
13515
13928
  ])
13516
- ], exports.RolesGuard);
13929
+ ], exports.ApiKeyGuard);
13930
+ function routePattern(request) {
13931
+ const path = request.route?.path;
13932
+ return typeof path === "string" ? path : "";
13933
+ }
13934
+ __name(routePattern, "routePattern");
13517
13935
  function _ts_decorate54(decorators, target, key, desc) {
13518
13936
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13519
13937
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
@@ -13528,49 +13946,257 @@ function _ts_decorate54(decorators, target, key, desc) {
13528
13946
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13529
13947
  }
13530
13948
  __name(_ts_decorate54, "_ts_decorate");
13531
- exports.NoOpAuthHooks = class NoOpAuthHooks {
13949
+ function _ts_metadata53(metadataKey, metadataValue) {
13950
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13951
+ return Reflect.metadata(metadataKey, metadataValue);
13952
+ }
13953
+ }
13954
+ __name(_ts_metadata53, "_ts_metadata");
13955
+ function _ts_param33(paramIndex, decorator) {
13956
+ return function(target, key) {
13957
+ decorator(target, key, paramIndex);
13958
+ };
13959
+ }
13960
+ __name(_ts_param33, "_ts_param");
13961
+ exports.MfaRequiredGuard = class MfaRequiredGuard {
13532
13962
  static {
13533
- __name(this, "NoOpAuthHooks");
13963
+ __name(this, "MfaRequiredGuard");
13534
13964
  }
13535
- /**
13536
- * Permits all registration attempts unconditionally.
13537
- *
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.
13541
- */
13542
- beforeRegister(_data, _context) {
13543
- return {
13544
- allowed: true
13545
- };
13965
+ reflector;
13966
+ constructor(reflector) {
13967
+ this.reflector = reflector;
13546
13968
  }
13547
- /**
13548
- * Resolves OAuth login by linking to an existing account, creating a new one,
13549
- * or rejecting on email mismatch.
13550
- *
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.
13555
- */
13556
- onOAuthLogin(profile, existingUser, _context) {
13557
- if (existingUser === null) {
13558
- return {
13559
- action: "create"
13560
- };
13969
+ canActivate(context) {
13970
+ const skipMfa = this.reflector.getAllAndOverride(SKIP_MFA_KEY, [
13971
+ context.getHandler(),
13972
+ context.getClass()
13973
+ ]);
13974
+ if (skipMfa) return true;
13975
+ const request = context.switchToHttp().getRequest();
13976
+ const user = request.user;
13977
+ if (!user) return true;
13978
+ if (typeof user.mfaEnabled !== "boolean") {
13979
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
13561
13980
  }
13562
- if (existingUser.email === profile.email) {
13563
- return {
13564
- action: "link"
13565
- };
13981
+ if (user.mfaEnabled === true && user.mfaVerified !== true) {
13982
+ throw new AuthException(AUTH_ERROR_CODES.MFA_REQUIRED);
13566
13983
  }
13984
+ return true;
13985
+ }
13986
+ };
13987
+ exports.MfaRequiredGuard = _ts_decorate54([
13988
+ common.Injectable(),
13989
+ _ts_param33(0, common.Inject(core.Reflector)),
13990
+ _ts_metadata53("design:type", Function),
13991
+ _ts_metadata53("design:paramtypes", [
13992
+ typeof core.Reflector === "undefined" ? Object : core.Reflector
13993
+ ])
13994
+ ], exports.MfaRequiredGuard);
13995
+ var PLATFORM_ROLES_KEY = /* @__PURE__ */ Symbol("platformRoles");
13996
+ var PlatformRoles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(PLATFORM_ROLES_KEY, roles), "PlatformRoles");
13997
+
13998
+ // src/server/guards/platform-roles.guard.ts
13999
+ function _ts_decorate55(decorators, target, key, desc) {
14000
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14001
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14002
+ r = Reflect.decorate(decorators, target, key, desc);
14003
+ } else {
14004
+ for (var i = decorators.length - 1; i >= 0; i--) {
14005
+ if (d = decorators[i]) {
14006
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14007
+ }
14008
+ }
14009
+ }
14010
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14011
+ }
14012
+ __name(_ts_decorate55, "_ts_decorate");
14013
+ function _ts_metadata54(metadataKey, metadataValue) {
14014
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14015
+ return Reflect.metadata(metadataKey, metadataValue);
14016
+ }
14017
+ }
14018
+ __name(_ts_metadata54, "_ts_metadata");
14019
+ function _ts_param34(paramIndex, decorator) {
14020
+ return function(target, key) {
14021
+ decorator(target, key, paramIndex);
14022
+ };
14023
+ }
14024
+ __name(_ts_param34, "_ts_param");
14025
+ exports.PlatformRolesGuard = class PlatformRolesGuard {
14026
+ static {
14027
+ __name(this, "PlatformRolesGuard");
14028
+ }
14029
+ reflector;
14030
+ options;
14031
+ constructor(reflector, options) {
14032
+ this.reflector = reflector;
14033
+ this.options = options;
14034
+ }
14035
+ canActivate(context) {
14036
+ const requiredRoles = this.reflector.getAllAndOverride(PLATFORM_ROLES_KEY, [
14037
+ context.getHandler(),
14038
+ context.getClass()
14039
+ ]);
14040
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14041
+ const request = context.switchToHttp().getRequest();
14042
+ const user = request.user;
14043
+ if (!user || user.type !== "platform") {
14044
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
14045
+ }
14046
+ const userRole = user.role;
14047
+ const hierarchy = this.options.roles.platformHierarchy;
14048
+ if (!hierarchy) {
14049
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14050
+ }
14051
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14052
+ if (!allowed) {
14053
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14054
+ }
14055
+ return true;
14056
+ }
14057
+ };
14058
+ exports.PlatformRolesGuard = _ts_decorate55([
14059
+ common.Injectable(),
14060
+ _ts_param34(0, common.Inject(core.Reflector)),
14061
+ _ts_param34(1, common.Inject(BYMAX_AUTH_OPTIONS)),
14062
+ _ts_metadata54("design:type", Function),
14063
+ _ts_metadata54("design:paramtypes", [
14064
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
14065
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14066
+ ])
14067
+ ], exports.PlatformRolesGuard);
14068
+ var ROLES_KEY = "roles";
14069
+ var Roles = /* @__PURE__ */ __name((...roles) => common.SetMetadata(ROLES_KEY, roles), "Roles");
14070
+
14071
+ // src/server/guards/roles.guard.ts
14072
+ function _ts_decorate56(decorators, target, key, desc) {
14073
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14074
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14075
+ r = Reflect.decorate(decorators, target, key, desc);
14076
+ } else {
14077
+ for (var i = decorators.length - 1; i >= 0; i--) {
14078
+ if (d = decorators[i]) {
14079
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14080
+ }
14081
+ }
14082
+ }
14083
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14084
+ }
14085
+ __name(_ts_decorate56, "_ts_decorate");
14086
+ function _ts_metadata55(metadataKey, metadataValue) {
14087
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14088
+ return Reflect.metadata(metadataKey, metadataValue);
14089
+ }
14090
+ }
14091
+ __name(_ts_metadata55, "_ts_metadata");
14092
+ function _ts_param35(paramIndex, decorator) {
14093
+ return function(target, key) {
14094
+ decorator(target, key, paramIndex);
14095
+ };
14096
+ }
14097
+ __name(_ts_param35, "_ts_param");
14098
+ exports.RolesGuard = class RolesGuard {
14099
+ static {
14100
+ __name(this, "RolesGuard");
14101
+ }
14102
+ reflector;
14103
+ options;
14104
+ constructor(reflector, options) {
14105
+ this.reflector = reflector;
14106
+ this.options = options;
14107
+ }
14108
+ canActivate(context) {
14109
+ const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
14110
+ context.getHandler(),
14111
+ context.getClass()
14112
+ ]);
14113
+ if (!requiredRoles || requiredRoles.length === 0) return true;
14114
+ const request = context.switchToHttp().getRequest();
14115
+ const userRole = request.user?.role;
14116
+ if (!userRole) {
14117
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14118
+ }
14119
+ const hierarchy = this.options.roles.hierarchy;
14120
+ const allowed = requiredRoles.some((required) => hasRole(userRole, required, hierarchy));
14121
+ if (!allowed) {
14122
+ throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
14123
+ }
14124
+ return true;
14125
+ }
14126
+ };
14127
+ exports.RolesGuard = _ts_decorate56([
14128
+ common.Injectable(),
14129
+ _ts_param35(0, common.Inject(core.Reflector)),
14130
+ _ts_param35(1, common.Inject(BYMAX_AUTH_OPTIONS)),
14131
+ _ts_metadata55("design:type", Function),
14132
+ _ts_metadata55("design:paramtypes", [
14133
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
14134
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
14135
+ ])
14136
+ ], exports.RolesGuard);
14137
+ function _ts_decorate57(decorators, target, key, desc) {
14138
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14139
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14140
+ r = Reflect.decorate(decorators, target, key, desc);
14141
+ } else {
14142
+ for (var i = decorators.length - 1; i >= 0; i--) {
14143
+ if (d = decorators[i]) {
14144
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14145
+ }
14146
+ }
14147
+ }
14148
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
14149
+ }
14150
+ __name(_ts_decorate57, "_ts_decorate");
14151
+ exports.NoOpAuthHooks = class NoOpAuthHooks {
14152
+ static {
14153
+ __name(this, "NoOpAuthHooks");
14154
+ }
14155
+ /**
14156
+ * Permits all registration attempts unconditionally.
14157
+ *
14158
+ * @param _data - Registration payload containing `email`, `name`, and `tenantId`.
14159
+ * @param _context - Hook execution context carrying request metadata.
14160
+ * @returns `{ allowed: true }` — never blocks registration.
14161
+ */
14162
+ beforeRegister(_data, _context) {
13567
14163
  return {
13568
- action: "reject",
13569
- reason: "Email mismatch"
14164
+ allowed: true
14165
+ };
14166
+ }
14167
+ /**
14168
+ * Resolves OAuth login: creates an account for an unlinked identity, keeps an existing link
14169
+ * when the address still matches and the provider vouches for it, and rejects otherwise.
14170
+ *
14171
+ * @param profile - Normalized OAuth profile from the provider.
14172
+ * @param existingUser - The user already linked to this provider identity, or `null`.
14173
+ * @param _context - Hook execution context carrying request metadata.
14174
+ * @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
14175
+ */
14176
+ onOAuthLogin(profile, existingUser, _context) {
14177
+ if (existingUser === null) {
14178
+ return {
14179
+ action: "create"
14180
+ };
14181
+ }
14182
+ if (existingUser.email !== profile.email) {
14183
+ return {
14184
+ action: "reject",
14185
+ reason: "Email mismatch"
14186
+ };
14187
+ }
14188
+ if (profile.emailVerified !== true) {
14189
+ return {
14190
+ action: "reject",
14191
+ reason: "Email not verified"
14192
+ };
14193
+ }
14194
+ return {
14195
+ action: "link"
13570
14196
  };
13571
14197
  }
13572
14198
  };
13573
- exports.NoOpAuthHooks = _ts_decorate54([
14199
+ exports.NoOpAuthHooks = _ts_decorate57([
13574
14200
  common.Injectable()
13575
14201
  ], exports.NoOpAuthHooks);
13576
14202
 
@@ -13583,7 +14209,7 @@ var OAUTH_STATE_COOKIE_SAME_SITE = "lax";
13583
14209
  var OAUTH_STATE_COOKIE_MAX_AGE_SECONDS = 600;
13584
14210
 
13585
14211
  // src/server/oauth/oauth.service.ts
13586
- function _ts_decorate55(decorators, target, key, desc) {
14212
+ function _ts_decorate58(decorators, target, key, desc) {
13587
14213
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13588
14214
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13589
14215
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13596,19 +14222,19 @@ function _ts_decorate55(decorators, target, key, desc) {
13596
14222
  }
13597
14223
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13598
14224
  }
13599
- __name(_ts_decorate55, "_ts_decorate");
13600
- function _ts_metadata53(metadataKey, metadataValue) {
14225
+ __name(_ts_decorate58, "_ts_decorate");
14226
+ function _ts_metadata56(metadataKey, metadataValue) {
13601
14227
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13602
14228
  return Reflect.metadata(metadataKey, metadataValue);
13603
14229
  }
13604
14230
  }
13605
- __name(_ts_metadata53, "_ts_metadata");
13606
- function _ts_param33(paramIndex, decorator) {
14231
+ __name(_ts_metadata56, "_ts_metadata");
14232
+ function _ts_param36(paramIndex, decorator) {
13607
14233
  return function(target, key) {
13608
14234
  decorator(target, key, paramIndex);
13609
14235
  };
13610
14236
  }
13611
- __name(_ts_param33, "_ts_param");
14237
+ __name(_ts_param36, "_ts_param");
13612
14238
  var OAUTH_STATE_TTL_SECONDS = 600;
13613
14239
  function isStoredOAuthState(value) {
13614
14240
  if (typeof value !== "object" || value === null) return false;
@@ -13863,6 +14489,17 @@ exports.OAuthService = class _OAuthService {
13863
14489
  });
13864
14490
  }
13865
14491
  this.logger.log(`handleCallback: OAuth login success provider=${provider} userId=${logSafe(safeUser.id)} tenantId=${logSafe(tenantId)} action=${hookResult.action}`);
14492
+ runDetached(this.logger, () => this.userRepo.updateLastLogin({
14493
+ id: safeUser.id,
14494
+ tenantId: safeUser.tenantId
14495
+ }), "oauth: updateLastLogin failed");
14496
+ if (this.hooks?.afterLogin) {
14497
+ const afterLogin = this.hooks.afterLogin.bind(this.hooks);
14498
+ runDetached(this.logger, () => afterLogin(safeUser, {
14499
+ ...hookContext,
14500
+ userId: safeUser.id
14501
+ }), "oauth: afterLogin hook threw");
14502
+ }
13866
14503
  return result;
13867
14504
  }
13868
14505
  // ---------------------------------------------------------------------------
@@ -13891,18 +14528,18 @@ exports.OAuthService = class _OAuthService {
13891
14528
  return plugin;
13892
14529
  }
13893
14530
  };
13894
- exports.OAuthService = _ts_decorate55([
14531
+ exports.OAuthService = _ts_decorate58([
13895
14532
  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", [
14533
+ _ts_param36(0, common.Inject(OAUTH_PLUGINS)),
14534
+ _ts_param36(1, common.Inject(BYMAX_AUTH_USER_REPOSITORY)),
14535
+ _ts_param36(2, common.Inject(BYMAX_AUTH_HOOKS)),
14536
+ _ts_param36(2, common.Optional()),
14537
+ _ts_param36(3, common.Inject(AuthRedisService)),
14538
+ _ts_param36(4, common.Inject(TokenManagerService)),
14539
+ _ts_param36(5, common.Inject(exports.SessionService)),
14540
+ _ts_param36(6, common.Inject(BYMAX_AUTH_OPTIONS)),
14541
+ _ts_metadata56("design:type", Function),
14542
+ _ts_metadata56("design:paramtypes", [
13906
14543
  Array,
13907
14544
  typeof IUserRepository === "undefined" ? Object : IUserRepository,
13908
14545
  Object,
@@ -13912,7 +14549,7 @@ exports.OAuthService = _ts_decorate55([
13912
14549
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
13913
14550
  ])
13914
14551
  ], exports.OAuthService);
13915
- function _ts_decorate56(decorators, target, key, desc) {
14552
+ function _ts_decorate59(decorators, target, key, desc) {
13916
14553
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13917
14554
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
13918
14555
  r = Reflect.decorate(decorators, target, key, desc);
@@ -13925,13 +14562,13 @@ function _ts_decorate56(decorators, target, key, desc) {
13925
14562
  }
13926
14563
  return c > 3 && r && Object.defineProperty(target, key, r), r;
13927
14564
  }
13928
- __name(_ts_decorate56, "_ts_decorate");
13929
- function _ts_metadata54(metadataKey, metadataValue) {
14565
+ __name(_ts_decorate59, "_ts_decorate");
14566
+ function _ts_metadata57(metadataKey, metadataValue) {
13930
14567
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
13931
14568
  return Reflect.metadata(metadataKey, metadataValue);
13932
14569
  }
13933
14570
  }
13934
- __name(_ts_metadata54, "_ts_metadata");
14571
+ __name(_ts_metadata57, "_ts_metadata");
13935
14572
  var OAuthCallbackQueryDto = class {
13936
14573
  static {
13937
14574
  __name(this, "OAuthCallbackQueryDto");
@@ -14030,69 +14667,69 @@ var OAuthCallbackQueryDto = class {
14030
14667
  */
14031
14668
  hd;
14032
14669
  };
14033
- _ts_decorate56([
14670
+ _ts_decorate59([
14034
14671
  classValidator.ValidateIf((query) => query.error === void 0 || query.error === null),
14035
14672
  classValidator.IsOptional(),
14036
14673
  classValidator.IsString(),
14037
14674
  classValidator.IsNotEmpty(),
14038
14675
  classValidator.MaxLength(2048),
14039
- _ts_metadata54("design:type", String)
14676
+ _ts_metadata57("design:type", String)
14040
14677
  ], OAuthCallbackQueryDto.prototype, "code", void 0);
14041
- _ts_decorate56([
14678
+ _ts_decorate59([
14042
14679
  classValidator.IsOptional(),
14043
14680
  classValidator.IsString(),
14044
14681
  classValidator.MaxLength(128),
14045
- _ts_metadata54("design:type", String)
14682
+ _ts_metadata57("design:type", String)
14046
14683
  ], OAuthCallbackQueryDto.prototype, "error", void 0);
14047
- _ts_decorate56([
14684
+ _ts_decorate59([
14048
14685
  classValidator.IsOptional(),
14049
14686
  classValidator.IsString(),
14050
14687
  classValidator.MaxLength(512),
14051
- _ts_metadata54("design:type", String)
14688
+ _ts_metadata57("design:type", String)
14052
14689
  ], OAuthCallbackQueryDto.prototype, "error_description", void 0);
14053
- _ts_decorate56([
14690
+ _ts_decorate59([
14054
14691
  classValidator.IsOptional(),
14055
14692
  classValidator.IsString(),
14056
14693
  classValidator.MaxLength(512),
14057
- _ts_metadata54("design:type", String)
14694
+ _ts_metadata57("design:type", String)
14058
14695
  ], OAuthCallbackQueryDto.prototype, "error_uri", void 0);
14059
- _ts_decorate56([
14696
+ _ts_decorate59([
14060
14697
  classValidator.IsString(),
14061
14698
  classValidator.IsNotEmpty(),
14062
14699
  classValidator.MaxLength(128),
14063
- _ts_metadata54("design:type", String)
14700
+ _ts_metadata57("design:type", String)
14064
14701
  ], OAuthCallbackQueryDto.prototype, "state", void 0);
14065
- _ts_decorate56([
14702
+ _ts_decorate59([
14066
14703
  classValidator.IsOptional(),
14067
14704
  classValidator.IsString(),
14068
14705
  classValidator.MaxLength(512),
14069
- _ts_metadata54("design:type", String)
14706
+ _ts_metadata57("design:type", String)
14070
14707
  ], OAuthCallbackQueryDto.prototype, "iss", void 0);
14071
- _ts_decorate56([
14708
+ _ts_decorate59([
14072
14709
  classValidator.IsOptional(),
14073
14710
  classValidator.IsString(),
14074
14711
  classValidator.MaxLength(2048),
14075
- _ts_metadata54("design:type", String)
14712
+ _ts_metadata57("design:type", String)
14076
14713
  ], OAuthCallbackQueryDto.prototype, "scope", void 0);
14077
- _ts_decorate56([
14714
+ _ts_decorate59([
14078
14715
  classValidator.IsOptional(),
14079
14716
  classValidator.IsString(),
14080
14717
  classValidator.MaxLength(16),
14081
- _ts_metadata54("design:type", String)
14718
+ _ts_metadata57("design:type", String)
14082
14719
  ], OAuthCallbackQueryDto.prototype, "authuser", void 0);
14083
- _ts_decorate56([
14720
+ _ts_decorate59([
14084
14721
  classValidator.IsOptional(),
14085
14722
  classValidator.IsString(),
14086
14723
  classValidator.MaxLength(64),
14087
- _ts_metadata54("design:type", String)
14724
+ _ts_metadata57("design:type", String)
14088
14725
  ], OAuthCallbackQueryDto.prototype, "prompt", void 0);
14089
- _ts_decorate56([
14726
+ _ts_decorate59([
14090
14727
  classValidator.IsOptional(),
14091
14728
  classValidator.IsString(),
14092
14729
  classValidator.MaxLength(253),
14093
- _ts_metadata54("design:type", String)
14730
+ _ts_metadata57("design:type", String)
14094
14731
  ], OAuthCallbackQueryDto.prototype, "hd", void 0);
14095
- function _ts_decorate57(decorators, target, key, desc) {
14732
+ function _ts_decorate60(decorators, target, key, desc) {
14096
14733
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14097
14734
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14098
14735
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14105,13 +14742,13 @@ function _ts_decorate57(decorators, target, key, desc) {
14105
14742
  }
14106
14743
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14107
14744
  }
14108
- __name(_ts_decorate57, "_ts_decorate");
14109
- function _ts_metadata55(metadataKey, metadataValue) {
14745
+ __name(_ts_decorate60, "_ts_decorate");
14746
+ function _ts_metadata58(metadataKey, metadataValue) {
14110
14747
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14111
14748
  return Reflect.metadata(metadataKey, metadataValue);
14112
14749
  }
14113
14750
  }
14114
- __name(_ts_metadata55, "_ts_metadata");
14751
+ __name(_ts_metadata58, "_ts_metadata");
14115
14752
  var OAuthInitiateQueryDto = class {
14116
14753
  static {
14117
14754
  __name(this, "OAuthInitiateQueryDto");
@@ -14128,7 +14765,7 @@ var OAuthInitiateQueryDto = class {
14128
14765
  */
14129
14766
  tenantId;
14130
14767
  };
14131
- _ts_decorate57([
14768
+ _ts_decorate60([
14132
14769
  classValidator.IsOptional(),
14133
14770
  classValidator.IsString(),
14134
14771
  classValidator.IsNotEmpty(),
@@ -14136,11 +14773,11 @@ _ts_decorate57([
14136
14773
  classValidator.Matches(NO_CONTROL_CHARACTERS, {
14137
14774
  message: "tenantId must not contain control characters"
14138
14775
  }),
14139
- _ts_metadata55("design:type", String)
14776
+ _ts_metadata58("design:type", String)
14140
14777
  ], OAuthInitiateQueryDto.prototype, "tenantId", void 0);
14141
14778
 
14142
14779
  // src/server/oauth/oauth.controller.ts
14143
- function _ts_decorate58(decorators, target, key, desc) {
14780
+ function _ts_decorate61(decorators, target, key, desc) {
14144
14781
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14145
14782
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14146
14783
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14153,19 +14790,19 @@ function _ts_decorate58(decorators, target, key, desc) {
14153
14790
  }
14154
14791
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14155
14792
  }
14156
- __name(_ts_decorate58, "_ts_decorate");
14157
- function _ts_metadata56(metadataKey, metadataValue) {
14793
+ __name(_ts_decorate61, "_ts_decorate");
14794
+ function _ts_metadata59(metadataKey, metadataValue) {
14158
14795
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
14159
14796
  return Reflect.metadata(metadataKey, metadataValue);
14160
14797
  }
14161
14798
  }
14162
- __name(_ts_metadata56, "_ts_metadata");
14163
- function _ts_param34(paramIndex, decorator) {
14799
+ __name(_ts_metadata59, "_ts_metadata");
14800
+ function _ts_param37(paramIndex, decorator) {
14164
14801
  return function(target, key) {
14165
14802
  decorator(target, key, paramIndex);
14166
14803
  };
14167
14804
  }
14168
- __name(_ts_param34, "_ts_param");
14805
+ __name(_ts_param37, "_ts_param");
14169
14806
  function isOAuthMfaChallenge(result) {
14170
14807
  return "mfaRequired" in result && result.mfaRequired === true;
14171
14808
  }
@@ -14383,46 +15020,46 @@ var OAuthController = class _OAuthController {
14383
15020
  });
14384
15021
  }
14385
15022
  };
14386
- _ts_decorate58([
15023
+ _ts_decorate61([
14387
15024
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14388
15025
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthInitiate),
14389
15026
  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({
15027
+ _ts_param37(0, common.Param("provider")),
15028
+ _ts_param37(1, common.Query()),
15029
+ _ts_param37(2, common.Req()),
15030
+ _ts_param37(3, common.Res({
14394
15031
  passthrough: true
14395
15032
  })),
14396
- _ts_metadata56("design:type", Function),
14397
- _ts_metadata56("design:paramtypes", [
15033
+ _ts_metadata59("design:type", Function),
15034
+ _ts_metadata59("design:paramtypes", [
14398
15035
  String,
14399
15036
  typeof OAuthInitiateQueryDto === "undefined" ? Object : OAuthInitiateQueryDto,
14400
15037
  typeof Request === "undefined" ? Object : Request,
14401
15038
  typeof Response === "undefined" ? Object : Response
14402
15039
  ]),
14403
- _ts_metadata56("design:returntype", Promise)
15040
+ _ts_metadata59("design:returntype", Promise)
14404
15041
  ], OAuthController.prototype, "initiate", null);
14405
- _ts_decorate58([
15042
+ _ts_decorate61([
14406
15043
  throttler.Throttle(AUTH_THROTTLE_CONFIGS.oauthCallback),
14407
15044
  AuthRateLimit(AUTH_THROTTLE_CONFIGS.oauthCallback),
14408
15045
  common.HttpCode(common.HttpStatus.OK),
14409
15046
  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({
15047
+ _ts_param37(0, common.Param("provider")),
15048
+ _ts_param37(1, common.Query()),
15049
+ _ts_param37(2, common.Req()),
15050
+ _ts_param37(3, common.Res({
14414
15051
  passthrough: true
14415
15052
  })),
14416
- _ts_metadata56("design:type", Function),
14417
- _ts_metadata56("design:paramtypes", [
15053
+ _ts_metadata59("design:type", Function),
15054
+ _ts_metadata59("design:paramtypes", [
14418
15055
  String,
14419
15056
  typeof OAuthCallbackQueryDto === "undefined" ? Object : OAuthCallbackQueryDto,
14420
15057
  typeof Request === "undefined" ? Object : Request,
14421
15058
  typeof Response === "undefined" ? Object : Response
14422
15059
  ]),
14423
- _ts_metadata56("design:returntype", Promise)
15060
+ _ts_metadata59("design:returntype", Promise)
14424
15061
  ], OAuthController.prototype, "callback", null);
14425
- OAuthController = _ts_decorate58([
15062
+ OAuthController = _ts_decorate61([
14426
15063
  Public(),
14427
15064
  SkipMfa(),
14428
15065
  common.UseInterceptors(NoStoreInterceptor),
@@ -14431,11 +15068,11 @@ OAuthController = _ts_decorate58([
14431
15068
  common.UsePipes(createAuthValidationPipe({
14432
15069
  forbidUnknownValues: true
14433
15070
  })),
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", [
15071
+ _ts_param37(0, common.Inject(exports.OAuthService)),
15072
+ _ts_param37(1, common.Inject(exports.TokenDeliveryService)),
15073
+ _ts_param37(2, common.Inject(BYMAX_AUTH_OPTIONS)),
15074
+ _ts_metadata59("design:type", Function),
15075
+ _ts_metadata59("design:paramtypes", [
14439
15076
  typeof exports.OAuthService === "undefined" ? Object : exports.OAuthService,
14440
15077
  typeof exports.TokenDeliveryService === "undefined" ? Object : exports.TokenDeliveryService,
14441
15078
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
@@ -14574,7 +15211,7 @@ var GoogleOAuthPlugin = class {
14574
15211
  };
14575
15212
 
14576
15213
  // src/server/oauth/oauth.module.ts
14577
- function _ts_decorate59(decorators, target, key, desc) {
15214
+ function _ts_decorate62(decorators, target, key, desc) {
14578
15215
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
14579
15216
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
14580
15217
  r = Reflect.decorate(decorators, target, key, desc);
@@ -14587,7 +15224,7 @@ function _ts_decorate59(decorators, target, key, desc) {
14587
15224
  }
14588
15225
  return c > 3 && r && Object.defineProperty(target, key, r), r;
14589
15226
  }
14590
- __name(_ts_decorate59, "_ts_decorate");
15227
+ __name(_ts_decorate62, "_ts_decorate");
14591
15228
  function buildOAuthPlugins(options) {
14592
15229
  const plugins = [];
14593
15230
  if (options.oauth?.google) {
@@ -14657,7 +15294,7 @@ var OAuthModule = class _OAuthModule {
14657
15294
  };
14658
15295
  }
14659
15296
  };
14660
- OAuthModule = _ts_decorate59([
15297
+ OAuthModule = _ts_decorate62([
14661
15298
  common.Module({})
14662
15299
  ], OAuthModule);
14663
15300
 
@@ -15551,7 +16188,7 @@ function schemesFor(options, registered, cookieDelivery, bearerDelivery) {
15551
16188
  __name(schemesFor, "schemesFor");
15552
16189
 
15553
16190
  // src/server/openapi/auth-openapi.contributor.ts
15554
- function _ts_decorate60(decorators, target, key, desc) {
16191
+ function _ts_decorate63(decorators, target, key, desc) {
15555
16192
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15556
16193
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15557
16194
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15564,19 +16201,19 @@ function _ts_decorate60(decorators, target, key, desc) {
15564
16201
  }
15565
16202
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15566
16203
  }
15567
- __name(_ts_decorate60, "_ts_decorate");
15568
- function _ts_metadata57(metadataKey, metadataValue) {
16204
+ __name(_ts_decorate63, "_ts_decorate");
16205
+ function _ts_metadata60(metadataKey, metadataValue) {
15569
16206
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15570
16207
  return Reflect.metadata(metadataKey, metadataValue);
15571
16208
  }
15572
16209
  }
15573
- __name(_ts_metadata57, "_ts_metadata");
15574
- function _ts_param35(paramIndex, decorator) {
16210
+ __name(_ts_metadata60, "_ts_metadata");
16211
+ function _ts_param38(paramIndex, decorator) {
15575
16212
  return function(target, key) {
15576
16213
  decorator(target, key, paramIndex);
15577
16214
  };
15578
16215
  }
15579
- __name(_ts_param35, "_ts_param");
16216
+ __name(_ts_param38, "_ts_param");
15580
16217
  var AuthOpenApiContributor = class {
15581
16218
  static {
15582
16219
  __name(this, "AuthOpenApiContributor");
@@ -15596,18 +16233,18 @@ var AuthOpenApiContributor = class {
15596
16233
  return buildAuthOpenApiFragment(this.options, this.registered);
15597
16234
  }
15598
16235
  };
15599
- AuthOpenApiContributor = _ts_decorate60([
16236
+ AuthOpenApiContributor = _ts_decorate63([
15600
16237
  common.Injectable(),
15601
16238
  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", [
16239
+ _ts_param38(0, common.Inject(BYMAX_AUTH_OPTIONS)),
16240
+ _ts_param38(1, common.Inject(BYMAX_AUTH_REGISTERED_CONTROLLERS)),
16241
+ _ts_metadata60("design:type", Function),
16242
+ _ts_metadata60("design:paramtypes", [
15606
16243
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
15607
16244
  typeof RegisteredControllers === "undefined" ? Object : RegisteredControllers
15608
16245
  ])
15609
16246
  ], AuthOpenApiContributor);
15610
- function _ts_decorate61(decorators, target, key, desc) {
16247
+ function _ts_decorate64(decorators, target, key, desc) {
15611
16248
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15612
16249
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15613
16250
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15620,19 +16257,19 @@ function _ts_decorate61(decorators, target, key, desc) {
15620
16257
  }
15621
16258
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15622
16259
  }
15623
- __name(_ts_decorate61, "_ts_decorate");
15624
- function _ts_metadata58(metadataKey, metadataValue) {
16260
+ __name(_ts_decorate64, "_ts_decorate");
16261
+ function _ts_metadata61(metadataKey, metadataValue) {
15625
16262
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
15626
16263
  return Reflect.metadata(metadataKey, metadataValue);
15627
16264
  }
15628
16265
  }
15629
- __name(_ts_metadata58, "_ts_metadata");
15630
- function _ts_param36(paramIndex, decorator) {
16266
+ __name(_ts_metadata61, "_ts_metadata");
16267
+ function _ts_param39(paramIndex, decorator) {
15631
16268
  return function(target, key) {
15632
16269
  decorator(target, key, paramIndex);
15633
16270
  };
15634
16271
  }
15635
- __name(_ts_param36, "_ts_param");
16272
+ __name(_ts_param39, "_ts_param");
15636
16273
  var COMMON_BASE_WORDS = [
15637
16274
  // The perennial top of every published list.
15638
16275
  "password",
@@ -15938,16 +16575,16 @@ exports.CommonPasswordChecker = class CommonPasswordChecker {
15938
16575
  return false;
15939
16576
  }
15940
16577
  };
15941
- exports.CommonPasswordChecker = _ts_decorate61([
16578
+ exports.CommonPasswordChecker = _ts_decorate64([
15942
16579
  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", [
16580
+ _ts_param39(0, common.Inject(BYMAX_AUTH_OPTIONS)),
16581
+ _ts_param39(0, common.Optional()),
16582
+ _ts_metadata61("design:type", Function),
16583
+ _ts_metadata61("design:paramtypes", [
15947
16584
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
15948
16585
  ])
15949
16586
  ], exports.CommonPasswordChecker);
15950
- function _ts_decorate62(decorators, target, key, desc) {
16587
+ function _ts_decorate65(decorators, target, key, desc) {
15951
16588
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15952
16589
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
15953
16590
  r = Reflect.decorate(decorators, target, key, desc);
@@ -15960,7 +16597,7 @@ function _ts_decorate62(decorators, target, key, desc) {
15960
16597
  }
15961
16598
  return c > 3 && r && Object.defineProperty(target, key, r), r;
15962
16599
  }
15963
- __name(_ts_decorate62, "_ts_decorate");
16600
+ __name(_ts_decorate65, "_ts_decorate");
15964
16601
  exports.NoOpEmailProvider = class _NoOpEmailProvider {
15965
16602
  static {
15966
16603
  __name(this, "NoOpEmailProvider");
@@ -15995,10 +16632,21 @@ exports.NoOpEmailProvider = class _NoOpEmailProvider {
15995
16632
  this.logger.log(`sendInvitation \u2192 ${maskEmail(email)} (no-op)`);
15996
16633
  }
15997
16634
  };
15998
- exports.NoOpEmailProvider = _ts_decorate62([
16635
+ exports.NoOpEmailProvider = _ts_decorate65([
15999
16636
  common.Injectable()
16000
16637
  ], exports.NoOpEmailProvider);
16001
- function _ts_decorate63(decorators, target, key, desc) {
16638
+
16639
+ // src/server/services/api-key-clock.ts
16640
+ var SystemApiKeyClock = class {
16641
+ static {
16642
+ __name(this, "SystemApiKeyClock");
16643
+ }
16644
+ /** @returns The current instant. */
16645
+ now() {
16646
+ return /* @__PURE__ */ new Date();
16647
+ }
16648
+ };
16649
+ function _ts_decorate66(decorators, target, key, desc) {
16002
16650
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16003
16651
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16004
16652
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16011,20 +16659,330 @@ function _ts_decorate63(decorators, target, key, desc) {
16011
16659
  }
16012
16660
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16013
16661
  }
16014
- __name(_ts_decorate63, "_ts_decorate");
16015
- function _ts_metadata59(metadataKey, metadataValue) {
16662
+ __name(_ts_decorate66, "_ts_decorate");
16663
+ function _ts_metadata62(metadataKey, metadataValue) {
16016
16664
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16017
16665
  return Reflect.metadata(metadataKey, metadataValue);
16018
16666
  }
16019
16667
  }
16020
- __name(_ts_metadata59, "_ts_metadata");
16021
- function _ts_param37(paramIndex, decorator) {
16668
+ __name(_ts_metadata62, "_ts_metadata");
16669
+ function _ts_param40(paramIndex, decorator) {
16022
16670
  return function(target, key) {
16023
16671
  decorator(target, key, paramIndex);
16024
16672
  };
16025
16673
  }
16026
- __name(_ts_param37, "_ts_param");
16027
- exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16674
+ __name(_ts_param40, "_ts_param");
16675
+ var ApiKeyScopeAuditService = class {
16676
+ static {
16677
+ __name(this, "ApiKeyScopeAuditService");
16678
+ }
16679
+ discovery;
16680
+ scanner;
16681
+ reflector;
16682
+ options;
16683
+ constructor(discovery, scanner, reflector, options) {
16684
+ this.discovery = discovery;
16685
+ this.scanner = scanner;
16686
+ this.reflector = reflector;
16687
+ this.options = options;
16688
+ }
16689
+ /** @throws {Error} Naming every route that declares a scope the vocabulary lacks. */
16690
+ onApplicationBootstrap() {
16691
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16692
+ const problems = [];
16693
+ for (const wrapper of this.discovery.getControllers()) {
16694
+ const { instance, metatype } = wrapper;
16695
+ if (!instance || typeof metatype !== "function") continue;
16696
+ this.collect(problems, vocabulary, metatype.name, this.reflector.get(API_KEY_SCOPES_KEY, metatype));
16697
+ const prototype = Object.getPrototypeOf(instance);
16698
+ for (const method of this.scanner.getAllMethodNames(prototype)) {
16699
+ const handler = prototype[method];
16700
+ this.collect(problems, vocabulary, `${metatype.name}.${method}`, this.reflector.get(API_KEY_SCOPES_KEY, handler));
16701
+ }
16702
+ }
16703
+ if (problems.length > 0) {
16704
+ throw new Error(`[BymaxAuthModule] ${problems.join("; ")}. Add the scope to apiKeys.scopes or correct the declaration.`);
16705
+ }
16706
+ }
16707
+ collect(problems, vocabulary, where, declared) {
16708
+ if (!Array.isArray(declared)) return;
16709
+ for (const scope of declared) {
16710
+ if (!vocabulary.has(scope)) {
16711
+ problems.push(`${where} declares a scope outside apiKeys.scopes`);
16712
+ return;
16713
+ }
16714
+ }
16715
+ }
16716
+ };
16717
+ ApiKeyScopeAuditService = _ts_decorate66([
16718
+ common.Injectable(),
16719
+ _ts_param40(0, common.Inject(core.DiscoveryService)),
16720
+ _ts_param40(1, common.Inject(core.MetadataScanner)),
16721
+ _ts_param40(2, common.Inject(core.Reflector)),
16722
+ _ts_param40(3, common.Inject(BYMAX_AUTH_OPTIONS)),
16723
+ _ts_metadata62("design:type", Function),
16724
+ _ts_metadata62("design:paramtypes", [
16725
+ typeof core.DiscoveryService === "undefined" ? Object : core.DiscoveryService,
16726
+ typeof core.MetadataScanner === "undefined" ? Object : core.MetadataScanner,
16727
+ typeof core.Reflector === "undefined" ? Object : core.Reflector,
16728
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16729
+ ])
16730
+ ], ApiKeyScopeAuditService);
16731
+ function _ts_decorate67(decorators, target, key, desc) {
16732
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16733
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16734
+ r = Reflect.decorate(decorators, target, key, desc);
16735
+ } else {
16736
+ for (var i = decorators.length - 1; i >= 0; i--) {
16737
+ if (d = decorators[i]) {
16738
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16739
+ }
16740
+ }
16741
+ }
16742
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16743
+ }
16744
+ __name(_ts_decorate67, "_ts_decorate");
16745
+ function _ts_metadata63(metadataKey, metadataValue) {
16746
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16747
+ return Reflect.metadata(metadataKey, metadataValue);
16748
+ }
16749
+ }
16750
+ __name(_ts_metadata63, "_ts_metadata");
16751
+ function _ts_param41(paramIndex, decorator) {
16752
+ return function(target, key) {
16753
+ decorator(target, key, paramIndex);
16754
+ };
16755
+ }
16756
+ __name(_ts_param41, "_ts_param");
16757
+ var API_KEY_MAX_LABEL_LENGTH = 128;
16758
+ var API_KEY_MAX_OVERLAP_SECONDS = 2592e3;
16759
+ var CONTROL_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
16760
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
16761
+ exports.ApiKeyService = class ApiKeyService {
16762
+ static {
16763
+ __name(this, "ApiKeyService");
16764
+ }
16765
+ repository;
16766
+ clock;
16767
+ options;
16768
+ constructor(repository, clock, options) {
16769
+ this.repository = repository;
16770
+ this.clock = clock;
16771
+ this.options = options;
16772
+ }
16773
+ /**
16774
+ * Issues a new key.
16775
+ *
16776
+ * @param input - Label, scopes and optional expiry.
16777
+ * @returns The plaintext key (once) and the stored record.
16778
+ * @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
16779
+ */
16780
+ async issue(input) {
16781
+ const now = this.clock.now();
16782
+ const label = this.validatedLabel(input.label);
16783
+ const scopes = this.validatedScopes(input.scopes);
16784
+ const expiresAt = this.validatedExpiry("expiresAt", input.expiresAt, now);
16785
+ const id = crypto.randomUUID();
16786
+ const secret = generateApiKeySecret();
16787
+ const stored = await this.repository.create({
16788
+ id,
16789
+ label,
16790
+ digest: apiKeyDigest(secret, this.options.apiKeys.pepper),
16791
+ scopes,
16792
+ createdAt: now,
16793
+ expiresAt
16794
+ });
16795
+ return {
16796
+ key: formatApiKey(this.options.apiKeys.prefix, id, secret),
16797
+ record: summary(stored)
16798
+ };
16799
+ }
16800
+ /**
16801
+ * Revokes a key now. Revoking an already revoked key succeeds.
16802
+ *
16803
+ * @param id - The key's row id.
16804
+ * @throws {AuthException} `auth.api_key_not_found` when no such key exists.
16805
+ */
16806
+ async revoke(id) {
16807
+ if (!UUID_PATTERN.test(id) || !await this.repository.markRevoked(id, this.clock.now())) {
16808
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16809
+ }
16810
+ }
16811
+ /**
16812
+ * Replaces a key with a new one carrying the same label and scopes.
16813
+ *
16814
+ * The new key is issued first and the old one retired second, so a failure between the two
16815
+ * leaves both valid — the safe direction — rather than neither.
16816
+ *
16817
+ * @param id - The active key to replace.
16818
+ * @param input - The overlap and an optional expiry for the new key.
16819
+ * @returns The new key, plaintext once.
16820
+ * @throws {AuthException} `auth.validation` for a bad overlap or expiry;
16821
+ * `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
16822
+ * rotated: that would re-issue access nobody holds).
16823
+ */
16824
+ async rotate(id, input) {
16825
+ const now = this.clock.now();
16826
+ const overlap = input.overlapSeconds;
16827
+ if (!Number.isInteger(overlap) || overlap < 0 || overlap > API_KEY_MAX_OVERLAP_SECONDS) {
16828
+ throw validation("overlapSeconds", `overlapSeconds must be an integer from 0 to ${API_KEY_MAX_OVERLAP_SECONDS}`);
16829
+ }
16830
+ const newExpiry = this.validatedExpiry("expiresAt", input.expiresAt, now);
16831
+ const old = UUID_PATTERN.test(id) ? await this.repository.findById(id) : null;
16832
+ if (old === null || !isActive(old, now)) {
16833
+ throw new AuthException(AUTH_ERROR_CODES.API_KEY_NOT_FOUND);
16834
+ }
16835
+ const issued = await this.issue({
16836
+ label: old.label,
16837
+ scopes: old.scopes,
16838
+ ...newExpiry === null ? {} : {
16839
+ expiresAt: newExpiry
16840
+ }
16841
+ });
16842
+ if (overlap === 0) {
16843
+ await this.repository.markRevoked(old.id, now);
16844
+ } else {
16845
+ const retireAt = new Date(now.getTime() + overlap * 1e3);
16846
+ const sooner = (
16847
+ // Stryker disable next-line EqualityOperator: at equal instants both arms yield a Date of the same time, so `<` and `<=` store the same expiry
16848
+ old.expiresAt !== null && old.expiresAt.getTime() < retireAt.getTime() ? old.expiresAt : retireAt
16849
+ );
16850
+ await this.repository.setExpiry(old.id, sooner);
16851
+ }
16852
+ return issued;
16853
+ }
16854
+ validatedLabel(label) {
16855
+ if (typeof label !== "string" || label.trim().length === 0 || label.length > API_KEY_MAX_LABEL_LENGTH || CONTROL_CHARACTERS.test(label)) {
16856
+ throw validation("label", `label must be 1 to ${API_KEY_MAX_LABEL_LENGTH} characters with no control characters`);
16857
+ }
16858
+ return label;
16859
+ }
16860
+ validatedScopes(scopes) {
16861
+ if (!Array.isArray(scopes) || scopes.length === 0) {
16862
+ throw validation("scopes", "scopes must be a non-empty list");
16863
+ }
16864
+ const vocabulary = new Set(this.options.apiKeys.scopes);
16865
+ const seen = /* @__PURE__ */ new Set();
16866
+ for (const scope of scopes) {
16867
+ if (!vocabulary.has(scope)) {
16868
+ throw validation("scopes", "every scope must come from the configured vocabulary");
16869
+ }
16870
+ if (seen.has(scope)) throw validation("scopes", "scopes must not repeat");
16871
+ seen.add(scope);
16872
+ }
16873
+ return [
16874
+ ...scopes
16875
+ ];
16876
+ }
16877
+ validatedExpiry(field, value, now) {
16878
+ if (value === void 0) return null;
16879
+ if (!(value instanceof Date) || Number.isNaN(value.getTime()) || value.getTime() <= now.getTime()) {
16880
+ throw validation(field, `${field} must be a valid date in the future`);
16881
+ }
16882
+ return value;
16883
+ }
16884
+ };
16885
+ exports.ApiKeyService = _ts_decorate67([
16886
+ common.Injectable(),
16887
+ _ts_param41(0, common.Inject(BYMAX_AUTH_API_KEY_REPOSITORY)),
16888
+ _ts_param41(1, common.Inject(BYMAX_AUTH_API_KEY_CLOCK)),
16889
+ _ts_param41(2, common.Inject(BYMAX_AUTH_OPTIONS)),
16890
+ _ts_metadata63("design:type", Function),
16891
+ _ts_metadata63("design:paramtypes", [
16892
+ typeof IApiKeyRepository === "undefined" ? Object : IApiKeyRepository,
16893
+ typeof ApiKeyClock === "undefined" ? Object : ApiKeyClock,
16894
+ typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
16895
+ ])
16896
+ ], exports.ApiKeyService);
16897
+ function isActive(key, now) {
16898
+ const nowMs = now.getTime();
16899
+ return key.revokedAt === null && (key.expiresAt === null || key.expiresAt.getTime() > nowMs);
16900
+ }
16901
+ __name(isActive, "isActive");
16902
+ function summary(row) {
16903
+ const { digest: _digest, ...rest } = row;
16904
+ return rest;
16905
+ }
16906
+ __name(summary, "summary");
16907
+ function validation(field, message) {
16908
+ return new AuthException(AUTH_ERROR_CODES.VALIDATION, [
16909
+ {
16910
+ field,
16911
+ message
16912
+ }
16913
+ ]);
16914
+ }
16915
+ __name(validation, "validation");
16916
+
16917
+ // src/server/utils/handshake-request.ts
16918
+ function handshakeRequest(handshake) {
16919
+ const headers = {};
16920
+ for (const [name, value] of Object.entries(handshake.headers)) {
16921
+ headers[name.toLowerCase()] = value;
16922
+ }
16923
+ return {
16924
+ headers,
16925
+ url: handshake.url ?? "",
16926
+ hostname: hostnameOf(headers["host"])
16927
+ };
16928
+ }
16929
+ __name(handshakeRequest, "handshakeRequest");
16930
+ function hostnameOf(host) {
16931
+ if (typeof host !== "string") return "";
16932
+ const offset = host.startsWith("[") ? host.indexOf("]") + 1 : 0;
16933
+ const index = host.indexOf(":", offset);
16934
+ return index === -1 ? host : host.substring(0, index);
16935
+ }
16936
+ __name(hostnameOf, "hostnameOf");
16937
+
16938
+ // src/server/utils/assert-tenant-binding.ts
16939
+ function tenantBindingEnforced(options) {
16940
+ return options.enforceTenantBinding === true && options.tenantIdResolver !== void 0;
16941
+ }
16942
+ __name(tenantBindingEnforced, "tenantBindingEnforced");
16943
+ async function assertTenantBinding(options, handshake, tenantId) {
16944
+ const resolver = options.tenantIdResolver;
16945
+ if (options.enforceTenantBinding !== true || !resolver) return;
16946
+ let requestTenant;
16947
+ try {
16948
+ requestTenant = await resolver(handshakeRequest(handshake));
16949
+ } catch {
16950
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16951
+ }
16952
+ if (requestTenant !== tenantId) {
16953
+ throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16954
+ }
16955
+ }
16956
+ __name(assertTenantBinding, "assertTenantBinding");
16957
+
16958
+ // src/server/services/auth-token-verifier.service.ts
16959
+ function _ts_decorate68(decorators, target, key, desc) {
16960
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16961
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16962
+ r = Reflect.decorate(decorators, target, key, desc);
16963
+ } else {
16964
+ for (var i = decorators.length - 1; i >= 0; i--) {
16965
+ if (d = decorators[i]) {
16966
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
16967
+ }
16968
+ }
16969
+ }
16970
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16971
+ }
16972
+ __name(_ts_decorate68, "_ts_decorate");
16973
+ function _ts_metadata64(metadataKey, metadataValue) {
16974
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16975
+ return Reflect.metadata(metadataKey, metadataValue);
16976
+ }
16977
+ }
16978
+ __name(_ts_metadata64, "_ts_metadata");
16979
+ function _ts_param42(paramIndex, decorator) {
16980
+ return function(target, key) {
16981
+ decorator(target, key, paramIndex);
16982
+ };
16983
+ }
16984
+ __name(_ts_param42, "_ts_param");
16985
+ exports.AuthTokenVerifierService = class _AuthTokenVerifierService {
16028
16986
  static {
16029
16987
  __name(this, "AuthTokenVerifierService");
16030
16988
  }
@@ -16032,6 +16990,9 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16032
16990
  options;
16033
16991
  revocation;
16034
16992
  accountStatus;
16993
+ logger = new common.Logger(_AuthTokenVerifierService.name);
16994
+ /** Whether the "binding not applied" warning has been logged by this instance. */
16995
+ warnedUnbound = false;
16035
16996
  /**
16036
16997
  * @param jwtService - The Nest JWT service, configured with the current signing secret.
16037
16998
  * @param options - Resolved module options, for the algorithm, the binding claims and the
@@ -16075,7 +17036,9 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16075
17036
  */
16076
17037
  async verifyAccessToken(token, options) {
16077
17038
  const { plane, requireMfa = true, checkStatus = true } = options;
16078
- if (plane === "dashboard") return await this.verifyDashboard(token, requireMfa, checkStatus);
17039
+ if (plane === "dashboard") {
17040
+ return await this.verifyDashboard(token, requireMfa, checkStatus, options.request);
17041
+ }
16079
17042
  if (plane === "platform") return await this.verifyPlatform(token, requireMfa, checkStatus);
16080
17043
  throw new TypeError(`verifyAccessToken: plane must be 'dashboard' or 'platform'`);
16081
17044
  }
@@ -16085,10 +17048,11 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16085
17048
  * @param token - The compact JWT.
16086
17049
  * @param requireMfa - Whether to apply the MFA policy.
16087
17050
  * @param checkStatus - Whether to consult the account's current status.
17051
+ * @param request - The request the token arrived on, for `enforceTenantBinding`.
16088
17052
  * @returns The verified dashboard payload.
16089
17053
  * @throws {@link AuthException} as {@link verifyAccessToken} documents.
16090
17054
  */
16091
- async verifyDashboard(token, requireMfa, checkStatus) {
17055
+ async verifyDashboard(token, requireMfa, checkStatus, request) {
16092
17056
  const payload = this.verifySignature(token);
16093
17057
  assertValidJti(payload.jti);
16094
17058
  assertValidSub(payload.sub);
@@ -16097,6 +17061,7 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16097
17061
  if (await this.revocation.isAccessTokenRevoked(payload, "dashboard")) {
16098
17062
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
16099
17063
  }
17064
+ await this.assertBound(payload.tenantId, request);
16100
17065
  if (requireMfa) this.assertMfaClaimShape(payload);
16101
17066
  if (checkStatus) {
16102
17067
  await this.accountStatus.assertDashboardAccountUsable({
@@ -16111,6 +17076,23 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16111
17076
  };
16112
17077
  }
16113
17078
  /**
17079
+ * Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
17080
+ *
17081
+ * @param tenantId - The tenant the token was issued for.
17082
+ * @param request - The request the token arrived on, when the caller supplied one.
17083
+ * @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
17084
+ */
17085
+ async assertBound(tenantId, request) {
17086
+ if (request !== void 0) {
17087
+ await assertTenantBinding(this.options, request, tenantId);
17088
+ return;
17089
+ }
17090
+ if (tenantBindingEnforced(this.options) && !this.warnedUnbound) {
17091
+ this.warnedUnbound = true;
17092
+ 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`.");
17093
+ }
17094
+ }
17095
+ /**
16114
17096
  * The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
16115
17097
  * is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
16116
17098
  *
@@ -16183,14 +17165,14 @@ exports.AuthTokenVerifierService = class AuthTokenVerifierService {
16183
17165
  }
16184
17166
  }
16185
17167
  };
16186
- exports.AuthTokenVerifierService = _ts_decorate63([
17168
+ exports.AuthTokenVerifierService = _ts_decorate68([
16187
17169
  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", [
17170
+ _ts_param42(0, common.Inject(jwt.JwtService)),
17171
+ _ts_param42(1, common.Inject(BYMAX_AUTH_OPTIONS)),
17172
+ _ts_param42(2, common.Inject(exports.AuthRevocationService)),
17173
+ _ts_param42(3, common.Inject(exports.AccountStatusService)),
17174
+ _ts_metadata64("design:type", Function),
17175
+ _ts_metadata64("design:paramtypes", [
16194
17176
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
16195
17177
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions,
16196
17178
  typeof exports.AuthRevocationService === "undefined" ? Object : exports.AuthRevocationService,
@@ -16199,7 +17181,7 @@ exports.AuthTokenVerifierService = _ts_decorate63([
16199
17181
  ], exports.AuthTokenVerifierService);
16200
17182
 
16201
17183
  // src/server/bymax-auth.module.ts
16202
- function _ts_decorate64(decorators, target, key, desc) {
17184
+ function _ts_decorate69(decorators, target, key, desc) {
16203
17185
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16204
17186
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16205
17187
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16212,7 +17194,7 @@ function _ts_decorate64(decorators, target, key, desc) {
16212
17194
  }
16213
17195
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16214
17196
  }
16215
- __name(_ts_decorate64, "_ts_decorate");
17197
+ __name(_ts_decorate69, "_ts_decorate");
16216
17198
  function hasProviderToken(providers, token) {
16217
17199
  return providers.some((p) => {
16218
17200
  if (typeof p === "function") return false;
@@ -16220,6 +17202,15 @@ function hasProviderToken(providers, token) {
16220
17202
  });
16221
17203
  }
16222
17204
  __name(hasProviderToken, "hasProviderToken");
17205
+ function cannotAuditApiKeys(providers) {
17206
+ const hooks = providers.find((p) => "provide" in p && p.provide === BYMAX_AUTH_HOOKS);
17207
+ if (hooks === void 0) return true;
17208
+ if ("useValue" in hooks) {
17209
+ return typeof hooks.useValue?.onApiKeyRequest !== "function";
17210
+ }
17211
+ return false;
17212
+ }
17213
+ __name(cannotAuditApiKeys, "cannotAuditApiKeys");
16223
17214
  exports.BymaxAuthModule = class _BymaxAuthModule {
16224
17215
  static {
16225
17216
  __name(this, "BymaxAuthModule");
@@ -16247,6 +17238,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16247
17238
  const includePlatform = options.controllers?.platform === true;
16248
17239
  const includeOAuth = options.controllers?.oauth === true;
16249
17240
  const includeInvitations = options.controllers?.invitations === true;
17241
+ const includeApiKeys = hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_REPOSITORY);
16250
17242
  const includeEmailChange = options.controllers?.emailChange === true;
16251
17243
  const resolvedOptionsProvider = {
16252
17244
  provide: BYMAX_AUTH_OPTIONS,
@@ -16280,10 +17272,29 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16280
17272
  if (includeInvitations && !resolved.invitations?.enabled) {
16281
17273
  throw new Error("[BymaxAuthModule] controllers.invitations: true requires invitations.enabled: true in the useFactory return value.");
16282
17274
  }
17275
+ if (includeApiKeys !== resolved.apiKeys.enabled) {
17276
+ 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.");
17277
+ }
17278
+ if (resolved.apiKeys.auditMode === "required" && cannotAuditApiKeys(extraProviders)) {
17279
+ 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'.");
17280
+ }
16283
17281
  return resolved;
16284
17282
  }, "useFactory"),
16285
17283
  inject: options.inject ?? []
16286
17284
  };
17285
+ const apiKeyProviders = includeApiKeys ? [
17286
+ ...hasProviderToken(extraProviders, BYMAX_AUTH_API_KEY_CLOCK) ? [] : [
17287
+ {
17288
+ provide: BYMAX_AUTH_API_KEY_CLOCK,
17289
+ useClass: SystemApiKeyClock
17290
+ }
17291
+ ],
17292
+ ApiKeyLastUsedService,
17293
+ ApiKeyVerifierService,
17294
+ exports.ApiKeyService,
17295
+ exports.ApiKeyGuard,
17296
+ ApiKeyScopeAuditService
17297
+ ] : [];
16287
17298
  const emailProviders = hasProviderToken(extraProviders, BYMAX_AUTH_EMAIL_PROVIDER) ? [] : [
16288
17299
  {
16289
17300
  provide: BYMAX_AUTH_EMAIL_PROVIDER,
@@ -16364,6 +17375,10 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16364
17375
  module: _BymaxAuthModule,
16365
17376
  imports: [
16366
17377
  ...options.imports ?? [],
17378
+ // The bootstrap scope audit walks controllers through the discovery service.
17379
+ ...includeApiKeys ? [
17380
+ core.DiscoveryModule
17381
+ ] : [],
16367
17382
  // JwtModule reads the secret directly from the consumer factory (without re-running
16368
17383
  // resolveOptions) to avoid double-validation on startup. Full validation happens once
16369
17384
  // in the BYMAX_AUTH_OPTIONS provider above.
@@ -16457,7 +17472,9 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16457
17472
  // Invitation service — only when controllers.invitations: true.
16458
17473
  ...invitationProviders,
16459
17474
  // Address-change service — only when controllers.emailChange: true.
16460
- ...emailChangeProviders
17475
+ ...emailChangeProviders,
17476
+ // Service API keys — only when the host supplied the repository.
17477
+ ...apiKeyProviders
16461
17478
  ],
16462
17479
  controllers,
16463
17480
  exports: [
@@ -16545,6 +17562,15 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16545
17562
  // export BYMAX_AUTH_USER_REPOSITORY as the instance supplied by the consumer` test, which
16546
17563
  // is the one that fails without it.
16547
17564
  BYMAX_AUTH_USER_REPOSITORY,
17565
+ // Service API keys: the guard is re-instantiated in the consumer's injector by
17566
+ // `@ServiceKey()`, so its direct dependencies must be exported with it — the verifier and
17567
+ // the hooks. The service is public surface for a host's own admin routes.
17568
+ ...includeApiKeys ? [
17569
+ exports.ApiKeyGuard,
17570
+ ApiKeyVerifierService,
17571
+ exports.ApiKeyService,
17572
+ BYMAX_AUTH_HOOKS
17573
+ ] : [],
16548
17574
  // WsTicketService also stands on its own as public surface: single-use ticket
16549
17575
  // handshakes are the credential a realtime transport is meant to use, and a consumer
16550
17576
  // cannot mint one without injecting this service.
@@ -16556,7 +17582,7 @@ exports.BymaxAuthModule = class _BymaxAuthModule {
16556
17582
  };
16557
17583
  }
16558
17584
  };
16559
- exports.BymaxAuthModule = _ts_decorate64([
17585
+ exports.BymaxAuthModule = _ts_decorate69([
16560
17586
  common.Module({})
16561
17587
  ], exports.BymaxAuthModule);
16562
17588
 
@@ -16884,7 +17910,7 @@ var DefaultAuthEmailProvider = class _DefaultAuthEmailProvider {
16884
17910
  }
16885
17911
  }
16886
17912
  };
16887
- function _ts_decorate65(decorators, target, key, desc) {
17913
+ function _ts_decorate70(decorators, target, key, desc) {
16888
17914
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16889
17915
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16890
17916
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16897,13 +17923,13 @@ function _ts_decorate65(decorators, target, key, desc) {
16897
17923
  }
16898
17924
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16899
17925
  }
16900
- __name(_ts_decorate65, "_ts_decorate");
16901
- function _ts_metadata60(metadataKey, metadataValue) {
17926
+ __name(_ts_decorate70, "_ts_decorate");
17927
+ function _ts_metadata65(metadataKey, metadataValue) {
16902
17928
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
16903
17929
  return Reflect.metadata(metadataKey, metadataValue);
16904
17930
  }
16905
17931
  }
16906
- __name(_ts_metadata60, "_ts_metadata");
17932
+ __name(_ts_metadata65, "_ts_metadata");
16907
17933
  var HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
16908
17934
  var PREFIX_LENGTH = 5;
16909
17935
  var DEFAULT_TIMEOUT_MS = 1500;
@@ -16960,10 +17986,10 @@ exports.HibpBreachChecker = class _HibpBreachChecker {
16960
17986
  }
16961
17987
  }
16962
17988
  };
16963
- exports.HibpBreachChecker = _ts_decorate65([
17989
+ exports.HibpBreachChecker = _ts_decorate70([
16964
17990
  common.Injectable(),
16965
- _ts_metadata60("design:type", Function),
16966
- _ts_metadata60("design:paramtypes", [
17991
+ _ts_metadata65("design:type", Function),
17992
+ _ts_metadata65("design:paramtypes", [
16967
17993
  Number
16968
17994
  ])
16969
17995
  ], exports.HibpBreachChecker);
@@ -16976,10 +18002,10 @@ exports.AllowAllBreachChecker = class AllowAllBreachChecker {
16976
18002
  return false;
16977
18003
  }
16978
18004
  };
16979
- exports.AllowAllBreachChecker = _ts_decorate65([
18005
+ exports.AllowAllBreachChecker = _ts_decorate70([
16980
18006
  common.Injectable()
16981
18007
  ], exports.AllowAllBreachChecker);
16982
- function _ts_decorate66(decorators, target, key, desc) {
18008
+ function _ts_decorate71(decorators, target, key, desc) {
16983
18009
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16984
18010
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16985
18011
  r = Reflect.decorate(decorators, target, key, desc);
@@ -16992,7 +18018,7 @@ function _ts_decorate66(decorators, target, key, desc) {
16992
18018
  }
16993
18019
  return c > 3 && r && Object.defineProperty(target, key, r), r;
16994
18020
  }
16995
- __name(_ts_decorate66, "_ts_decorate");
18021
+ __name(_ts_decorate71, "_ts_decorate");
16996
18022
  exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard {
16997
18023
  static {
16998
18024
  __name(this, "OptionalAuthGuard");
@@ -17007,10 +18033,10 @@ exports.OptionalAuthGuard = class OptionalAuthGuard extends exports.JwtAuthGuard
17007
18033
  return super.canActivate(context);
17008
18034
  }
17009
18035
  };
17010
- exports.OptionalAuthGuard = _ts_decorate66([
18036
+ exports.OptionalAuthGuard = _ts_decorate71([
17011
18037
  common.Injectable()
17012
18038
  ], exports.OptionalAuthGuard);
17013
- function _ts_decorate67(decorators, target, key, desc) {
18039
+ function _ts_decorate72(decorators, target, key, desc) {
17014
18040
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17015
18041
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17016
18042
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17023,19 +18049,19 @@ function _ts_decorate67(decorators, target, key, desc) {
17023
18049
  }
17024
18050
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17025
18051
  }
17026
- __name(_ts_decorate67, "_ts_decorate");
17027
- function _ts_metadata61(metadataKey, metadataValue) {
18052
+ __name(_ts_decorate72, "_ts_decorate");
18053
+ function _ts_metadata66(metadataKey, metadataValue) {
17028
18054
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17029
18055
  return Reflect.metadata(metadataKey, metadataValue);
17030
18056
  }
17031
18057
  }
17032
- __name(_ts_metadata61, "_ts_metadata");
17033
- function _ts_param38(paramIndex, decorator) {
18058
+ __name(_ts_metadata66, "_ts_metadata");
18059
+ function _ts_param43(paramIndex, decorator) {
17034
18060
  return function(target, key) {
17035
18061
  decorator(target, key, paramIndex);
17036
18062
  };
17037
18063
  }
17038
- __name(_ts_param38, "_ts_param");
18064
+ __name(_ts_param43, "_ts_param");
17039
18065
  exports.SelfOrAdminGuard = class SelfOrAdminGuard {
17040
18066
  static {
17041
18067
  __name(this, "SelfOrAdminGuard");
@@ -17065,11 +18091,11 @@ exports.SelfOrAdminGuard = class SelfOrAdminGuard {
17065
18091
  throw new AuthException(AUTH_ERROR_CODES.INSUFFICIENT_ROLE);
17066
18092
  }
17067
18093
  };
17068
- exports.SelfOrAdminGuard = _ts_decorate67([
18094
+ exports.SelfOrAdminGuard = _ts_decorate72([
17069
18095
  common.Injectable(),
17070
- _ts_param38(0, common.Inject(BYMAX_AUTH_OPTIONS)),
17071
- _ts_metadata61("design:type", Function),
17072
- _ts_metadata61("design:paramtypes", [
18096
+ _ts_param43(0, common.Inject(BYMAX_AUTH_OPTIONS)),
18097
+ _ts_metadata66("design:type", Function),
18098
+ _ts_metadata66("design:paramtypes", [
17073
18099
  typeof ResolvedOptions === "undefined" ? Object : ResolvedOptions
17074
18100
  ])
17075
18101
  ], exports.SelfOrAdminGuard);
@@ -17082,7 +18108,7 @@ function isHexLooking(value) {
17082
18108
  return value.length === 64 && /^[a-fA-F0-9]{64}$/.test(value);
17083
18109
  }
17084
18110
  __name(isHexLooking, "isHexLooking");
17085
- function _ts_decorate68(decorators, target, key, desc) {
18111
+ function _ts_decorate73(decorators, target, key, desc) {
17086
18112
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17087
18113
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17088
18114
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17095,19 +18121,19 @@ function _ts_decorate68(decorators, target, key, desc) {
17095
18121
  }
17096
18122
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17097
18123
  }
17098
- __name(_ts_decorate68, "_ts_decorate");
17099
- function _ts_metadata62(metadataKey, metadataValue) {
18124
+ __name(_ts_decorate73, "_ts_decorate");
18125
+ function _ts_metadata67(metadataKey, metadataValue) {
17100
18126
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
17101
18127
  return Reflect.metadata(metadataKey, metadataValue);
17102
18128
  }
17103
18129
  }
17104
- __name(_ts_metadata62, "_ts_metadata");
17105
- function _ts_param39(paramIndex, decorator) {
18130
+ __name(_ts_metadata67, "_ts_metadata");
18131
+ function _ts_param44(paramIndex, decorator) {
17106
18132
  return function(target, key) {
17107
18133
  decorator(target, key, paramIndex);
17108
18134
  };
17109
18135
  }
17110
- __name(_ts_param39, "_ts_param");
18136
+ __name(_ts_param44, "_ts_param");
17111
18137
  exports.WsJwtGuard = class WsJwtGuard {
17112
18138
  static {
17113
18139
  __name(this, "WsJwtGuard");
@@ -17143,6 +18169,7 @@ exports.WsJwtGuard = class WsJwtGuard {
17143
18169
  if (ticket !== void 0) {
17144
18170
  const snapshot = await this.wsTickets.redeem(ticket);
17145
18171
  assertDashboardSnapshot(snapshot);
18172
+ await assertTenantBinding(this.options, handshake, snapshot.tenantId);
17146
18173
  client.data.user = snapshot;
17147
18174
  return true;
17148
18175
  }
@@ -17165,18 +18192,19 @@ exports.WsJwtGuard = class WsJwtGuard {
17165
18192
  if (await this.revocation.isAccessTokenRevoked(payload)) {
17166
18193
  throw new AuthException(AUTH_ERROR_CODES.TOKEN_INVALID);
17167
18194
  }
18195
+ await assertTenantBinding(this.options, handshake, payload.tenantId);
17168
18196
  client.data.user = payload;
17169
18197
  return true;
17170
18198
  }
17171
18199
  };
17172
- exports.WsJwtGuard = _ts_decorate68([
18200
+ exports.WsJwtGuard = _ts_decorate73([
17173
18201
  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", [
18202
+ _ts_param44(0, common.Inject(jwt.JwtService)),
18203
+ _ts_param44(1, common.Inject(exports.AuthRevocationService)),
18204
+ _ts_param44(2, common.Inject(exports.WsTicketService)),
18205
+ _ts_param44(3, common.Inject(BYMAX_AUTH_OPTIONS)),
18206
+ _ts_metadata67("design:type", Function),
18207
+ _ts_metadata67("design:paramtypes", [
17180
18208
  typeof jwt.JwtService === "undefined" ? Object : jwt.JwtService,
17181
18209
  typeof exports.AuthRevocationService === "undefined" ? Object : exports.AuthRevocationService,
17182
18210
  typeof exports.WsTicketService === "undefined" ? Object : exports.WsTicketService,
@@ -17209,7 +18237,7 @@ function readUpgradeTicket(handshake) {
17209
18237
  return all.length === 1 && all[0] !== "" ? all[0] : void 0;
17210
18238
  }
17211
18239
  __name(readUpgradeTicket, "readUpgradeTicket");
17212
- function _ts_decorate69(decorators, target, key, desc) {
18240
+ function _ts_decorate74(decorators, target, key, desc) {
17213
18241
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17214
18242
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17215
18243
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17222,7 +18250,7 @@ function _ts_decorate69(decorators, target, key, desc) {
17222
18250
  }
17223
18251
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17224
18252
  }
17225
- __name(_ts_decorate69, "_ts_decorate");
18253
+ __name(_ts_decorate74, "_ts_decorate");
17226
18254
  function isAuthEnvelope(body) {
17227
18255
  if (typeof body !== "object" || body === null) return false;
17228
18256
  const error = body.error;
@@ -17274,10 +18302,10 @@ exports.AuthExceptionFilter = class _AuthExceptionFilter {
17274
18302
  });
17275
18303
  }
17276
18304
  };
17277
- exports.AuthExceptionFilter = _ts_decorate69([
18305
+ exports.AuthExceptionFilter = _ts_decorate74([
17278
18306
  common.Catch()
17279
18307
  ], exports.AuthExceptionFilter);
17280
- function _ts_decorate70(decorators, target, key, desc) {
18308
+ function _ts_decorate75(decorators, target, key, desc) {
17281
18309
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17282
18310
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
17283
18311
  r = Reflect.decorate(decorators, target, key, desc);
@@ -17290,7 +18318,7 @@ function _ts_decorate70(decorators, target, key, desc) {
17290
18318
  }
17291
18319
  return c > 3 && r && Object.defineProperty(target, key, r), r;
17292
18320
  }
17293
- __name(_ts_decorate70, "_ts_decorate");
18321
+ __name(_ts_decorate75, "_ts_decorate");
17294
18322
  function isEmittingClient(client) {
17295
18323
  return typeof client?.emit === "function";
17296
18324
  }
@@ -17334,10 +18362,14 @@ exports.WsAuthExceptionFilter = class _WsAuthExceptionFilter {
17334
18362
  this.logger.error(`refused a request on a client this filter cannot answer: ${describeChannelStatus(exception)}`);
17335
18363
  }
17336
18364
  };
17337
- exports.WsAuthExceptionFilter = _ts_decorate70([
18365
+ exports.WsAuthExceptionFilter = _ts_decorate75([
17338
18366
  common.Catch(AuthException)
17339
18367
  ], exports.WsAuthExceptionFilter);
18368
+ var ServiceKey = /* @__PURE__ */ __name((...scopes) => common.applyDecorators(common.SetMetadata(IS_PUBLIC_KEY, true), ApiKeyScopes(...scopes), common.UseGuards(exports.ApiKeyGuard)), "ServiceKey");
18369
+ var CurrentApiKey = common.createParamDecorator((_data, ctx) => ctx.switchToHttp().getRequest().apiKey);
17340
18370
 
18371
+ exports.API_KEY_MAX_LABEL_LENGTH = API_KEY_MAX_LABEL_LENGTH;
18372
+ exports.API_KEY_MAX_OVERLAP_SECONDS = API_KEY_MAX_OVERLAP_SECONDS;
17341
18373
  exports.AUTH_EMAIL_KINDS = AUTH_EMAIL_KINDS;
17342
18374
  exports.AUTH_ERROR_CODES = AUTH_ERROR_CODES;
17343
18375
  exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
@@ -17345,9 +18377,12 @@ exports.AUTH_ERROR_STATUS = AUTH_ERROR_STATUS;
17345
18377
  exports.AUTH_SECURITY_SCHEMES = AUTH_SECURITY_SCHEMES;
17346
18378
  exports.AUTH_THROTTLE_CONFIGS = AUTH_THROTTLE_CONFIGS;
17347
18379
  exports.AcceptInvitationDto = AcceptInvitationDto;
18380
+ exports.ApiKeyScopes = ApiKeyScopes;
17348
18381
  exports.AuthException = AuthException;
17349
18382
  exports.AuthRateLimit = AuthRateLimit;
17350
18383
  exports.Authenticated = Authenticated;
18384
+ exports.BYMAX_AUTH_API_KEY_CLOCK = BYMAX_AUTH_API_KEY_CLOCK;
18385
+ exports.BYMAX_AUTH_API_KEY_REPOSITORY = BYMAX_AUTH_API_KEY_REPOSITORY;
17351
18386
  exports.BYMAX_AUTH_BREACH_CHECKER = BYMAX_AUTH_BREACH_CHECKER;
17352
18387
  exports.BYMAX_AUTH_EMAIL_PROVIDER = BYMAX_AUTH_EMAIL_PROVIDER;
17353
18388
  exports.BYMAX_AUTH_HOOKS = BYMAX_AUTH_HOOKS;
@@ -17357,6 +18392,7 @@ exports.BYMAX_AUTH_REDIS_CLIENT = BYMAX_AUTH_REDIS_CLIENT;
17357
18392
  exports.BYMAX_AUTH_USER_REPOSITORY = BYMAX_AUTH_USER_REPOSITORY;
17358
18393
  exports.ChangePasswordDto = ChangePasswordDto;
17359
18394
  exports.CreateInvitationDto = CreateInvitationDto;
18395
+ exports.CurrentApiKey = CurrentApiKey;
17360
18396
  exports.CurrentUser = CurrentUser;
17361
18397
  exports.DefaultAuthEmailProvider = DefaultAuthEmailProvider;
17362
18398
  exports.ForgotPasswordDto = ForgotPasswordDto;
@@ -17377,6 +18413,7 @@ exports.ResendVerificationDto = ResendVerificationDto;
17377
18413
  exports.ResetPasswordDto = ResetPasswordDto;
17378
18414
  exports.Roles = Roles;
17379
18415
  exports.SKIP_MFA_KEY = SKIP_MFA_KEY;
18416
+ exports.ServiceKey = ServiceKey;
17380
18417
  exports.SkipMfa = SkipMfa;
17381
18418
  exports.VerifyEmailDto = VerifyEmailDto;
17382
18419
  exports.VerifyOtpDto = VerifyOtpDto;