@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.
- package/CHANGELOG.md +111 -1
- package/README.md +329 -38
- package/dist/server/index.cjs +1317 -280
- package/dist/server/index.d.cts +647 -15
- package/dist/server/index.d.ts +647 -15
- package/dist/server/index.mjs +1314 -284
- package/dist/shared/index.cjs +7 -0
- package/dist/shared/index.d.cts +3 -0
- package/dist/shared/index.d.ts +3 -0
- package/dist/shared/index.mjs +7 -0
- package/package.json +1 -1
package/dist/server/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
|
-
import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit, ExceptionFilter, ArgumentsHost, ValidationPipeOptions, ValidationPipe } from '@nestjs/common';
|
|
2
|
+
import { ModuleMetadata, InjectionToken, OptionalFactoryDependency, Provider, DynamicModule, HttpException, CanActivate, ExecutionContext, OnModuleInit, ExceptionFilter, ArgumentsHost, ValidationPipeOptions, ValidationPipe, OnApplicationShutdown } from '@nestjs/common';
|
|
3
3
|
import { Request, Response } from 'express';
|
|
4
4
|
import { Reflector } from '@nestjs/core';
|
|
5
5
|
import { JwtService } from '@nestjs/jwt';
|
|
@@ -496,6 +496,23 @@ type BymaxAuthRateLimitOptions = {
|
|
|
496
496
|
/** Never read while the limiter is off, so it need not be stated. */
|
|
497
497
|
readonly clientIpSource?: ClientIpSource;
|
|
498
498
|
};
|
|
499
|
+
/**
|
|
500
|
+
* What a {@link BymaxAuthModuleOptions.tenantIdResolver} may rely on, on every transport.
|
|
501
|
+
*
|
|
502
|
+
* Over HTTP the resolver is handed the Express request; on a WebSocket upgrade there is none, so
|
|
503
|
+
* it is handed an object carrying only these fields. Typing the parameter as this, rather than as
|
|
504
|
+
* the full request, makes the compiler refuse a resolver that reads `cookies`, `ip` or `ips` —
|
|
505
|
+
* the fields an upgrade lacks — instead of leaving that to a runtime refusal of every socket.
|
|
506
|
+
*
|
|
507
|
+
* `hostname` is the `Host` header with the port cut (a bracketed IPv6 literal keeps its brackets),
|
|
508
|
+
* `''` when an upgrade carries none or repeats it; it never reads `X-Forwarded-Host`. `url` is `''` when the
|
|
509
|
+
* transport exposes none.
|
|
510
|
+
*/
|
|
511
|
+
interface TenantResolverRequest {
|
|
512
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
513
|
+
readonly url: string;
|
|
514
|
+
readonly hostname: string;
|
|
515
|
+
}
|
|
499
516
|
interface BymaxAuthModuleOptions {
|
|
500
517
|
/**
|
|
501
518
|
* Secret the Redis identifiers derive from. Optional; default: `jwt.secret`.
|
|
@@ -1035,6 +1052,58 @@ interface BymaxAuthModuleOptions {
|
|
|
1035
1052
|
*/
|
|
1036
1053
|
tokenTtlSeconds?: number;
|
|
1037
1054
|
};
|
|
1055
|
+
/**
|
|
1056
|
+
* Scoped service API keys for machine callers.
|
|
1057
|
+
*
|
|
1058
|
+
* Opt-in. Enabling it also requires `BYMAX_AUTH_API_KEY_REPOSITORY` in `extraProviders` (and
|
|
1059
|
+
* supplying that provider without enabling it is refused too), so a half-configured feature
|
|
1060
|
+
* fails at startup instead of silently authenticating nothing.
|
|
1061
|
+
*
|
|
1062
|
+
* Keys are stored only as an HMAC-SHA-256 digest under `pepper`. Changing the pepper makes
|
|
1063
|
+
* every issued key unverifiable, so it means re-issuing all of them.
|
|
1064
|
+
*/
|
|
1065
|
+
apiKeys?: {
|
|
1066
|
+
/** Enables the feature. Default: `false`. */
|
|
1067
|
+
enabled?: boolean;
|
|
1068
|
+
/**
|
|
1069
|
+
* The HMAC key every digest is computed under. Held to the same strength bar as
|
|
1070
|
+
* `jwt.secret`, and refused when it equals `jwt.secret`, `identifierKey` or a retired JWT
|
|
1071
|
+
* secret: a key shared across purposes is one leak away from all of them.
|
|
1072
|
+
*
|
|
1073
|
+
* Keep it in a secrets manager, apart from the database that stores the digests.
|
|
1074
|
+
*/
|
|
1075
|
+
pepper: string;
|
|
1076
|
+
/**
|
|
1077
|
+
* The closed vocabulary of scopes. `issue()` refuses any scope outside it, and the
|
|
1078
|
+
* bootstrap scan refuses a route that declares one. Letters, digits and `: . _ -`.
|
|
1079
|
+
*/
|
|
1080
|
+
scopes: readonly string[];
|
|
1081
|
+
/** Header the key is read from, lowercase. Never the query string. Default: `x-api-key`. */
|
|
1082
|
+
header?: string;
|
|
1083
|
+
/**
|
|
1084
|
+
* Prefix of every issued key: lowercase letters and digits, no underscore (the underscore
|
|
1085
|
+
* separates the parts). A literal prefix lets secret scanners find leaked keys.
|
|
1086
|
+
* Default: `bak`.
|
|
1087
|
+
*/
|
|
1088
|
+
prefix?: string;
|
|
1089
|
+
/**
|
|
1090
|
+
* How often, in seconds, the last-used timestamps coalesced in memory are flushed to the
|
|
1091
|
+
* store in one batch. With N instances a key is written up to N times per window, and a crash
|
|
1092
|
+
* loses at most one window of `lastUsedAt`. Default: `60`. Range: 1 to 3600.
|
|
1093
|
+
*/
|
|
1094
|
+
lastUsedFlushSeconds?: number;
|
|
1095
|
+
/**
|
|
1096
|
+
* What a failing audit hook does to the request it audits.
|
|
1097
|
+
*
|
|
1098
|
+
* - `'best-effort'`: the hook is fired without being awaited and its failure is logged. An
|
|
1099
|
+
* audit outage never changes an answer.
|
|
1100
|
+
* - `'required'`: the hook is awaited, and if it throws the request is DENIED. For hosts whose
|
|
1101
|
+
* audit row is a record they must have.
|
|
1102
|
+
*
|
|
1103
|
+
* Default: `'best-effort'`.
|
|
1104
|
+
*/
|
|
1105
|
+
auditMode?: 'best-effort' | 'required';
|
|
1106
|
+
};
|
|
1038
1107
|
/**
|
|
1039
1108
|
* Role hierarchy configuration. **Required.**
|
|
1040
1109
|
*
|
|
@@ -1223,7 +1292,9 @@ interface BymaxAuthModuleOptions {
|
|
|
1223
1292
|
* none is refused with the same `auth.validation` — the deployment has to choose one of the
|
|
1224
1293
|
* two, and neither choice is guessed on its behalf.
|
|
1225
1294
|
*
|
|
1226
|
-
* @param req - The
|
|
1295
|
+
* @param req - The request, as {@link TenantResolverRequest}: the fields every
|
|
1296
|
+
* transport has. An Express request satisfies it, so on HTTP you can still read the rest at
|
|
1297
|
+
* runtime, but a resolver that does fails the WebSocket upgrade by design.
|
|
1227
1298
|
* @returns The tenant ID string, or a Promise resolving to it
|
|
1228
1299
|
*
|
|
1229
1300
|
* @throws {Error} When the resolver returns an empty string or throws.
|
|
@@ -1250,7 +1321,7 @@ interface BymaxAuthModuleOptions {
|
|
|
1250
1321
|
* }
|
|
1251
1322
|
* ```
|
|
1252
1323
|
*/
|
|
1253
|
-
tenantIdResolver?: (req:
|
|
1324
|
+
tenantIdResolver?: (req: TenantResolverRequest) => string | Promise<string>;
|
|
1254
1325
|
/**
|
|
1255
1326
|
* Whether the dashboard guard re-resolves the request's tenant and rejects a token whose
|
|
1256
1327
|
* `tenantId` claim does not match it.
|
|
@@ -1264,6 +1335,11 @@ interface BymaxAuthModuleOptions {
|
|
|
1264
1335
|
* (subdomain-per-tenant behind an edge that refuses a `Host` it does not serve), turning this on
|
|
1265
1336
|
* closes that gap: the guard calls {@link tenantIdResolver} and refuses a mismatch.
|
|
1266
1337
|
*
|
|
1338
|
+
* `WsJwtGuard` enforces it too, on the bearer and the ticket path. An upgrade has no Express
|
|
1339
|
+
* request, so the resolver is handed one carrying only `headers` (lowercased), `url` and
|
|
1340
|
+
* `hostname` (the `Host` header, port cut); `cookies`, `ip`, `ips` and trust-proxy behaviour are
|
|
1341
|
+
* absent. A resolver that throws on that, or answers another tenant, refuses the connection.
|
|
1342
|
+
*
|
|
1267
1343
|
* Off by default, and requires a resolver to have any effect: with no resolver there is nothing
|
|
1268
1344
|
* to compare against. Leave it off where a token is legitimately used across hosts (a single API
|
|
1269
1345
|
* origin serving many tenants by claim), because there the resolved host tenant and the token
|
|
@@ -1512,6 +1588,20 @@ declare const BYMAX_AUTH_BREACH_CHECKER: unique symbol;
|
|
|
1512
1588
|
* Bound to an `ioredis` `Redis` instance configured for the host environment.
|
|
1513
1589
|
*/
|
|
1514
1590
|
declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
|
|
1591
|
+
/**
|
|
1592
|
+
* Injection token for the host's {@link IApiKeyRepository} implementation.
|
|
1593
|
+
*
|
|
1594
|
+
* Supplying it in `extraProviders` together with `apiKeys.enabled: true` is what registers the
|
|
1595
|
+
* service-key feature; either one without the other is a startup error.
|
|
1596
|
+
*/
|
|
1597
|
+
declare const BYMAX_AUTH_API_KEY_REPOSITORY: unique symbol;
|
|
1598
|
+
/**
|
|
1599
|
+
* Injection token for the clock the service-key feature reads "now" from.
|
|
1600
|
+
*
|
|
1601
|
+
* Optional: the module registers the system clock when the host supplies none. It exists so
|
|
1602
|
+
* that expiry and revocation can be tested at the exact boundary instant.
|
|
1603
|
+
*/
|
|
1604
|
+
declare const BYMAX_AUTH_API_KEY_CLOCK: unique symbol;
|
|
1515
1605
|
|
|
1516
1606
|
/**
|
|
1517
1607
|
* resolveOptions — merge consumer options with defaults and validate security invariants.
|
|
@@ -1535,7 +1625,7 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
|
|
|
1535
1625
|
* interface-extension compatibility check with `exactOptionalPropertyTypes`,
|
|
1536
1626
|
* which rejects intersection widening of optional function properties.
|
|
1537
1627
|
*/
|
|
1538
|
-
type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'environment' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
|
|
1628
|
+
type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenDelivery' | 'cookies' | 'sessions' | 'bruteForce' | 'passwordReset' | 'emailVerification' | 'platform' | 'invitations' | 'apiKeys' | 'controllers' | 'blockedStatuses' | 'redisNamespace' | 'routePrefix' | 'userStatusCacheTtlSeconds' | 'environment' | 'secureCookies' | 'mfa' | 'rateLimit'> & {
|
|
1539
1629
|
jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
|
|
1540
1630
|
password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
|
|
1541
1631
|
tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
|
|
@@ -1546,6 +1636,7 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
|
|
|
1546
1636
|
emailVerification: Required<NonNullable<BymaxAuthModuleOptions['emailVerification']>>;
|
|
1547
1637
|
platform: Required<NonNullable<BymaxAuthModuleOptions['platform']>>;
|
|
1548
1638
|
invitations: Required<NonNullable<BymaxAuthModuleOptions['invitations']>>;
|
|
1639
|
+
apiKeys: Required<NonNullable<BymaxAuthModuleOptions['apiKeys']>>;
|
|
1549
1640
|
emailChange: Required<NonNullable<BymaxAuthModuleOptions['emailChange']>>;
|
|
1550
1641
|
rateLimit: {
|
|
1551
1642
|
enabled: boolean;
|
|
@@ -2166,6 +2257,23 @@ declare const AUTH_ERROR_CODES: {
|
|
|
2166
2257
|
readonly OAUTH_EMAIL_MISMATCH: "auth.oauth_email_mismatch";
|
|
2167
2258
|
/** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
|
|
2168
2259
|
readonly PLATFORM_AUTH_REQUIRED: "auth.platform_auth_required";
|
|
2260
|
+
/**
|
|
2261
|
+
* The presented service key is not accepted.
|
|
2262
|
+
*
|
|
2263
|
+
* One code for every way a credential can fail — absent, malformed, unknown, wrong secret,
|
|
2264
|
+
* revoked, expired — so the answer tells a caller nothing about which of them it was. The
|
|
2265
|
+
* reason is recorded in the audit hook, where only the operator reads it.
|
|
2266
|
+
*/
|
|
2267
|
+
readonly API_KEY_INVALID: "auth.api_key_invalid";
|
|
2268
|
+
/**
|
|
2269
|
+
* The service key is valid but does not hold every scope the route declares.
|
|
2270
|
+
*
|
|
2271
|
+
* Safe to name because the caller has already proved the key. The body does not list the
|
|
2272
|
+
* scopes, so it is no map of what other routes require.
|
|
2273
|
+
*/
|
|
2274
|
+
readonly API_KEY_SCOPE_INSUFFICIENT: "auth.api_key_scope_insufficient";
|
|
2275
|
+
/** A key operation named an id that does not exist. Raised by revoke and rotate only. */
|
|
2276
|
+
readonly API_KEY_NOT_FOUND: "auth.api_key_not_found";
|
|
2169
2277
|
/**
|
|
2170
2278
|
* An unexpected internal failure. The cause is logged and never serialized.
|
|
2171
2279
|
*
|
|
@@ -2868,7 +2976,8 @@ interface OAuthLoginResult {
|
|
|
2868
2976
|
/**
|
|
2869
2977
|
* Desired action for this OAuth login attempt:
|
|
2870
2978
|
* - `'create'` — provision a new user account from the OAuth profile.
|
|
2871
|
-
* - `'link'` —
|
|
2979
|
+
* - `'link'` — keep the OAuth identity linked to the user passed as `existingUser`;
|
|
2980
|
+
* refused when there is none.
|
|
2872
2981
|
* - `'reject'` — deny the login attempt (e.g. domain allowlist enforcement).
|
|
2873
2982
|
*/
|
|
2874
2983
|
action: 'link' | 'create' | 'reject';
|
|
@@ -3128,8 +3237,11 @@ interface IAuthHooks {
|
|
|
3128
3237
|
* identity to an existing account, or reject the login (e.g. domain allowlists).
|
|
3129
3238
|
*
|
|
3130
3239
|
* @param profile - Normalized OAuth profile from the provider.
|
|
3131
|
-
* @param existingUser -
|
|
3132
|
-
*
|
|
3240
|
+
* @param existingUser - The user already linked to this provider identity (credential
|
|
3241
|
+
* fields omitted), found by provider id within the flow's tenant; `null` when this identity
|
|
3242
|
+
* is not linked to anyone. It is NOT looked up by email, so an account that merely shares
|
|
3243
|
+
* the profile's address does not appear here. Choosing `'create'` for an address another
|
|
3244
|
+
* account already owns is refused with `auth.oauth_email_mismatch`.
|
|
3133
3245
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
3134
3246
|
* @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
|
|
3135
3247
|
*/
|
|
@@ -3160,6 +3272,51 @@ interface IAuthHooks {
|
|
|
3160
3272
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
3161
3273
|
*/
|
|
3162
3274
|
onSessionEvicted?(userId: string, evictedSessionHash: string, context: HookContext): Promise<void> | void;
|
|
3275
|
+
/**
|
|
3276
|
+
* Called once for every request guarded by a service API key, refusals included.
|
|
3277
|
+
*
|
|
3278
|
+
* The audit trail for machine callers: who (the key's label), what (method and route
|
|
3279
|
+
* pattern) and how it ended. Fires for an admitted request, for every refused credential, for
|
|
3280
|
+
* a key missing a scope, and for a route that declares no scopes at all.
|
|
3281
|
+
*
|
|
3282
|
+
* By default the call is fired without being awaited and a failure is only logged, as for
|
|
3283
|
+
* every other hook. With `apiKeys.auditMode: 'required'` it is awaited and a failure DENIES
|
|
3284
|
+
* the request, for hosts whose audit row is a record they must have.
|
|
3285
|
+
*
|
|
3286
|
+
* The event never carries the presented key or its secret. `reason` is for the operator: the
|
|
3287
|
+
* caller is always given the same answer for a bad credential.
|
|
3288
|
+
*
|
|
3289
|
+
* @param event - What was asked, by whom, and how it ended.
|
|
3290
|
+
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
3291
|
+
*/
|
|
3292
|
+
onApiKeyRequest?(event: ApiKeyAccessEvent, context: HookContext): Promise<void> | void;
|
|
3293
|
+
}
|
|
3294
|
+
/** Why a service-key request was refused. Absent on an admitted request. */
|
|
3295
|
+
type ApiKeyDenyReason = 'missing' | 'malformed' | 'unknown' | 'wrong_secret' | 'revoked' | 'expired' | 'scope_insufficient' | 'route_undeclared' | 'store_error';
|
|
3296
|
+
/** One audited service-key request. See {@link IAuthHooks.onApiKeyRequest}. */
|
|
3297
|
+
interface ApiKeyAccessEvent {
|
|
3298
|
+
/** Whether the request was admitted. */
|
|
3299
|
+
outcome: 'allowed' | 'denied';
|
|
3300
|
+
/** Why it was refused; `null` when admitted. */
|
|
3301
|
+
reason: ApiKeyDenyReason | null;
|
|
3302
|
+
/**
|
|
3303
|
+
* The row id of the key, when the presented key named an existing row. Public by design: it
|
|
3304
|
+
* is the half of the key that is not secret. `null` when no row was identified.
|
|
3305
|
+
*/
|
|
3306
|
+
keyId: string | null;
|
|
3307
|
+
/** The label of the identified key, or `null` when none was. */
|
|
3308
|
+
label: string | null;
|
|
3309
|
+
/** HTTP method. */
|
|
3310
|
+
method: string;
|
|
3311
|
+
/**
|
|
3312
|
+
* The route PATTERN (`/videos/:id`), never the concrete URL, so identifiers a caller put in
|
|
3313
|
+
* the path do not reach the audit log. Empty when the framework matched no pattern.
|
|
3314
|
+
*/
|
|
3315
|
+
route: string;
|
|
3316
|
+
/** The scopes the route declares. Empty when the route declares none. */
|
|
3317
|
+
requiredScopes: readonly string[];
|
|
3318
|
+
/** Client address as the host's trusted-proxy configuration resolves it. */
|
|
3319
|
+
ip: string;
|
|
3163
3320
|
}
|
|
3164
3321
|
|
|
3165
3322
|
/**
|
|
@@ -3171,8 +3328,8 @@ interface IAuthHooks {
|
|
|
3171
3328
|
* @remarks
|
|
3172
3329
|
* - {@link beforeRegister} returns `{ allowed: true }` unconditionally.
|
|
3173
3330
|
* - {@link onOAuthLogin} applies the standard account-resolution strategy:
|
|
3174
|
-
*
|
|
3175
|
-
*
|
|
3331
|
+
* create if this provider identity is not linked yet, link if the linked user's
|
|
3332
|
+
* address equals the profile's and the provider verified it, and reject otherwise.
|
|
3176
3333
|
* - All other hooks are no-ops (return `void`).
|
|
3177
3334
|
*
|
|
3178
3335
|
* Replace this with a custom `IAuthHooks` implementation to enforce domain
|
|
@@ -3192,11 +3349,11 @@ declare class NoOpAuthHooks implements IAuthHooks {
|
|
|
3192
3349
|
tenantId: string;
|
|
3193
3350
|
}, _context: HookContext): BeforeRegisterResult;
|
|
3194
3351
|
/**
|
|
3195
|
-
* Resolves OAuth login
|
|
3196
|
-
*
|
|
3352
|
+
* Resolves OAuth login: creates an account for an unlinked identity, keeps an existing link
|
|
3353
|
+
* when the address still matches and the provider vouches for it, and rejects otherwise.
|
|
3197
3354
|
*
|
|
3198
3355
|
* @param profile - Normalized OAuth profile from the provider.
|
|
3199
|
-
* @param existingUser -
|
|
3356
|
+
* @param existingUser - The user already linked to this provider identity, or `null`.
|
|
3200
3357
|
* @param _context - Hook execution context carrying request metadata.
|
|
3201
3358
|
* @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
|
|
3202
3359
|
*/
|
|
@@ -9162,6 +9319,17 @@ declare class InvitationService {
|
|
|
9162
9319
|
* allowed to destroy whatever is there now.
|
|
9163
9320
|
*/
|
|
9164
9321
|
private supersedeApprovedInvitation;
|
|
9322
|
+
/**
|
|
9323
|
+
* Removes the invitation record this call wrote, best-effort.
|
|
9324
|
+
*
|
|
9325
|
+
* Used where the call is already ending in a refusal or a failure of its own, so a failing
|
|
9326
|
+
* delete must not replace that outcome: it is logged and the caller still raises the original.
|
|
9327
|
+
* The raw token has not been emailed at that point, so a record that survives is one nobody
|
|
9328
|
+
* holds the token for, until its TTL.
|
|
9329
|
+
*
|
|
9330
|
+
* @param tokenKey - The Redis key of the record written by this call.
|
|
9331
|
+
*/
|
|
9332
|
+
private withdrawRecord;
|
|
9165
9333
|
/**
|
|
9166
9334
|
* Atomically points the invitee index at `tokenHash`, answering with the hash it displaced.
|
|
9167
9335
|
*
|
|
@@ -9650,6 +9818,21 @@ declare class PlatformAuthService {
|
|
|
9650
9818
|
revokeAllPlatformSessions(userId: string): Promise<void>;
|
|
9651
9819
|
}
|
|
9652
9820
|
|
|
9821
|
+
/**
|
|
9822
|
+
* @fileoverview The request a `tenantIdResolver` sees when the caller arrived by WebSocket upgrade.
|
|
9823
|
+
*
|
|
9824
|
+
* @layer Utility
|
|
9825
|
+
*/
|
|
9826
|
+
|
|
9827
|
+
/**
|
|
9828
|
+
* The fields {@link handshakeRequest} reads. A Socket.IO `handshake` fits, and so does an Express
|
|
9829
|
+
* request.
|
|
9830
|
+
*/
|
|
9831
|
+
interface HandshakeLike {
|
|
9832
|
+
headers: Record<string, string | string[] | undefined>;
|
|
9833
|
+
url?: string;
|
|
9834
|
+
}
|
|
9835
|
+
|
|
9653
9836
|
/**
|
|
9654
9837
|
* @fileoverview The whole identity chain for an access token, in one call.
|
|
9655
9838
|
*
|
|
@@ -9720,6 +9903,22 @@ interface VerifyAccessTokenOptions {
|
|
|
9720
9903
|
* @defaultValue true
|
|
9721
9904
|
*/
|
|
9722
9905
|
readonly checkStatus?: boolean;
|
|
9906
|
+
/**
|
|
9907
|
+
* The request the credential arrived on — a Socket.IO `handshake`, an Express request, or any
|
|
9908
|
+
* object with `headers` and `url` — so `enforceTenantBinding` can be applied.
|
|
9909
|
+
*
|
|
9910
|
+
* The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
|
|
9911
|
+
* not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
|
|
9912
|
+
* dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
|
|
9913
|
+
* (lowercased), `url` and `hostname` (the `Host` header, port cut) — no `cookies`, `ip`, `ips`
|
|
9914
|
+
* or trust-proxy behaviour — and a resolver that throws on that, or answers another tenant,
|
|
9915
|
+
* refuses the token with `TOKEN_INVALID`. The platform plane has no tenant and ignores it.
|
|
9916
|
+
*
|
|
9917
|
+
* **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
|
|
9918
|
+
* that is logged once per service instance, because a caller that never passes it has a
|
|
9919
|
+
* binding the HTTP guards enforce and this surface does not.
|
|
9920
|
+
*/
|
|
9921
|
+
readonly request?: HandshakeLike;
|
|
9723
9922
|
}
|
|
9724
9923
|
/**
|
|
9725
9924
|
* Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
|
|
@@ -9759,8 +9958,8 @@ interface VerifyAccessTokenOptions {
|
|
|
9759
9958
|
* **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
|
|
9760
9959
|
* who the caller is, never what they may do, so a `@Roles()` equivalent stays yours to apply on
|
|
9761
9960
|
* every message a stream carries, not only at the handshake. Tenant binding
|
|
9762
|
-
* (`enforceTenantBinding`) needs the request the resolver reads, which a
|
|
9763
|
-
*
|
|
9961
|
+
* (`enforceTenantBinding`) needs the request the resolver reads, which a token does not carry:
|
|
9962
|
+
* pass the handshake as {@link VerifyAccessTokenOptions.request}, or the binding is not applied. And nothing here holds a subscription: it answers at the moment it is called, so a stream
|
|
9764
9963
|
* that calls it once at connect is authorized for the lifetime of the token, not of the session.
|
|
9765
9964
|
* Call it again on a cadence, and treat a rejection as a disconnect.
|
|
9766
9965
|
*
|
|
@@ -9777,6 +9976,9 @@ declare class AuthTokenVerifierService {
|
|
|
9777
9976
|
private readonly options;
|
|
9778
9977
|
private readonly revocation;
|
|
9779
9978
|
private readonly accountStatus;
|
|
9979
|
+
private readonly logger;
|
|
9980
|
+
/** Whether the "binding not applied" warning has been logged by this instance. */
|
|
9981
|
+
private warnedUnbound;
|
|
9780
9982
|
/**
|
|
9781
9983
|
* @param jwtService - The Nest JWT service, configured with the current signing secret.
|
|
9782
9984
|
* @param options - Resolved module options, for the algorithm, the binding claims and the
|
|
@@ -9820,10 +10022,19 @@ declare class AuthTokenVerifierService {
|
|
|
9820
10022
|
* @param token - The compact JWT.
|
|
9821
10023
|
* @param requireMfa - Whether to apply the MFA policy.
|
|
9822
10024
|
* @param checkStatus - Whether to consult the account's current status.
|
|
10025
|
+
* @param request - The request the token arrived on, for `enforceTenantBinding`.
|
|
9823
10026
|
* @returns The verified dashboard payload.
|
|
9824
10027
|
* @throws {@link AuthException} as {@link verifyAccessToken} documents.
|
|
9825
10028
|
*/
|
|
9826
10029
|
private verifyDashboard;
|
|
10030
|
+
/**
|
|
10031
|
+
* Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
|
|
10032
|
+
*
|
|
10033
|
+
* @param tenantId - The tenant the token was issued for.
|
|
10034
|
+
* @param request - The request the token arrived on, when the caller supplied one.
|
|
10035
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
|
|
10036
|
+
*/
|
|
10037
|
+
private assertBound;
|
|
9827
10038
|
/**
|
|
9828
10039
|
* The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
|
|
9829
10040
|
* is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
|
|
@@ -10218,4 +10429,425 @@ declare function AuthRateLimit(config: {
|
|
|
10218
10429
|
default: AuthRateLimitWindow;
|
|
10219
10430
|
}): MethodDecorator;
|
|
10220
10431
|
|
|
10221
|
-
|
|
10432
|
+
/**
|
|
10433
|
+
* @fileoverview Persistence contract and value types for scoped service API keys.
|
|
10434
|
+
*
|
|
10435
|
+
* The host implements {@link IApiKeyRepository} against its own store, as it does for users.
|
|
10436
|
+
* Nothing here is reversible: a row carries the HMAC digest of the secret and never the secret.
|
|
10437
|
+
*
|
|
10438
|
+
* @layer Interface
|
|
10439
|
+
*/
|
|
10440
|
+
/** One stored service key. */
|
|
10441
|
+
interface AuthApiKey {
|
|
10442
|
+
/** Row id, a lowercase UUID. It is the public half of the key a caller presents. */
|
|
10443
|
+
id: string;
|
|
10444
|
+
/**
|
|
10445
|
+
* Human name for the machine caller this key belongs to. NOT unique: several active keys may
|
|
10446
|
+
* share one label, which is what makes an overlapping rotation possible.
|
|
10447
|
+
*/
|
|
10448
|
+
label: string;
|
|
10449
|
+
/** Lowercase hex HMAC-SHA-256 of the secret under the pepper. 64 characters. */
|
|
10450
|
+
digest: string;
|
|
10451
|
+
/** Scopes this key holds. A route is admitted only when the key holds every scope it declares. */
|
|
10452
|
+
scopes: readonly string[];
|
|
10453
|
+
/** When the key was issued. */
|
|
10454
|
+
createdAt: Date;
|
|
10455
|
+
/** The key stops verifying at this instant, when set. */
|
|
10456
|
+
expiresAt: Date | null;
|
|
10457
|
+
/** When set, the key no longer verifies, on every instance, whatever instant it holds. */
|
|
10458
|
+
revokedAt: Date | null;
|
|
10459
|
+
/** Last time the key verified. Advisory and coalesced: see `apiKeys.lastUsedFlushSeconds`. */
|
|
10460
|
+
lastUsedAt: Date | null;
|
|
10461
|
+
}
|
|
10462
|
+
/** A stored key without its digest: what an operator-facing call may return or log. */
|
|
10463
|
+
type AuthApiKeySummary = Omit<AuthApiKey, 'digest'>;
|
|
10464
|
+
/** What the verified request carries as `request.apiKey`. */
|
|
10465
|
+
interface ApiKeyPrincipal {
|
|
10466
|
+
/** The key's row id: the stable handle to bucket a rate limit on after verification. */
|
|
10467
|
+
readonly id: string;
|
|
10468
|
+
/** The machine caller's label. */
|
|
10469
|
+
readonly label: string;
|
|
10470
|
+
/** The scopes the key holds. */
|
|
10471
|
+
readonly scopes: readonly string[];
|
|
10472
|
+
}
|
|
10473
|
+
/**
|
|
10474
|
+
* Persistence port for service API keys.
|
|
10475
|
+
*
|
|
10476
|
+
* @remarks
|
|
10477
|
+
* The library supplies `id` and `digest`; the store only persists them. Verification reads one
|
|
10478
|
+
* row per request, so `findById` should be a primary-key lookup.
|
|
10479
|
+
*/
|
|
10480
|
+
interface IApiKeyRepository {
|
|
10481
|
+
/**
|
|
10482
|
+
* Finds a key by its row id.
|
|
10483
|
+
*
|
|
10484
|
+
* @param id - The id embedded in the presented key.
|
|
10485
|
+
* @returns The row, or `null` when none exists. Revoked and expired rows are still returned:
|
|
10486
|
+
* the library decides validity, so every refusal takes the same steps.
|
|
10487
|
+
*/
|
|
10488
|
+
findById(id: string): Promise<AuthApiKey | null>;
|
|
10489
|
+
/**
|
|
10490
|
+
* Inserts a new key.
|
|
10491
|
+
*
|
|
10492
|
+
* @param row - The row to store. `id` is generated by the library.
|
|
10493
|
+
* @returns The stored row.
|
|
10494
|
+
*/
|
|
10495
|
+
create(row: {
|
|
10496
|
+
id: string;
|
|
10497
|
+
label: string;
|
|
10498
|
+
digest: string;
|
|
10499
|
+
scopes: readonly string[];
|
|
10500
|
+
createdAt: Date;
|
|
10501
|
+
expiresAt: Date | null;
|
|
10502
|
+
}): Promise<AuthApiKey>;
|
|
10503
|
+
/**
|
|
10504
|
+
* Marks a key revoked.
|
|
10505
|
+
*
|
|
10506
|
+
* @param id - The key to revoke.
|
|
10507
|
+
* @param at - The instant it stops verifying.
|
|
10508
|
+
* @returns `false` when no such key exists. Revoking an already revoked key is not an error.
|
|
10509
|
+
*/
|
|
10510
|
+
markRevoked(id: string, at: Date): Promise<boolean>;
|
|
10511
|
+
/**
|
|
10512
|
+
* Sets when a key stops verifying. Used by rotation to retire the old key after an overlap.
|
|
10513
|
+
*
|
|
10514
|
+
* @param id - The key to change.
|
|
10515
|
+
* @param at - The new expiry instant.
|
|
10516
|
+
* @returns `false` when no such key exists.
|
|
10517
|
+
*/
|
|
10518
|
+
setExpiry(id: string, at: Date): Promise<boolean>;
|
|
10519
|
+
/**
|
|
10520
|
+
* Records when keys were last used, in one batch.
|
|
10521
|
+
*
|
|
10522
|
+
* MUST be monotonic: never move `lastUsedAt` backwards (`GREATEST(last_used_at, :at)`, or a
|
|
10523
|
+
* `WHERE last_used_at < :at` guard). Several instances flush independently, and a late flush
|
|
10524
|
+
* from one must not overwrite a newer value written by another.
|
|
10525
|
+
*
|
|
10526
|
+
* @param entries - One entry per key, the most recent use seen by this process.
|
|
10527
|
+
*/
|
|
10528
|
+
touchLastUsed(entries: ReadonlyArray<{
|
|
10529
|
+
id: string;
|
|
10530
|
+
at: Date;
|
|
10531
|
+
}>): Promise<void>;
|
|
10532
|
+
/**
|
|
10533
|
+
* Lists every key that carries a label, active or not.
|
|
10534
|
+
*
|
|
10535
|
+
* @param label - The machine caller's label.
|
|
10536
|
+
*/
|
|
10537
|
+
listByLabel(label: string): Promise<AuthApiKey[]>;
|
|
10538
|
+
}
|
|
10539
|
+
|
|
10540
|
+
/**
|
|
10541
|
+
* @fileoverview The clock the service-key feature reads "now" from.
|
|
10542
|
+
*
|
|
10543
|
+
* @layer Service
|
|
10544
|
+
*/
|
|
10545
|
+
/**
|
|
10546
|
+
* Source of the current instant for expiry and revocation decisions.
|
|
10547
|
+
*
|
|
10548
|
+
* Injectable so a test can stand exactly on a boundary instant, which a wall clock cannot do.
|
|
10549
|
+
* Supply `BYMAX_AUTH_API_KEY_CLOCK` to replace it; production hosts have no reason to.
|
|
10550
|
+
*/
|
|
10551
|
+
interface ApiKeyClock {
|
|
10552
|
+
/** The current instant. */
|
|
10553
|
+
now(): Date;
|
|
10554
|
+
}
|
|
10555
|
+
|
|
10556
|
+
/**
|
|
10557
|
+
* @fileoverview Coalesces "last used" timestamps so a verified request costs no write.
|
|
10558
|
+
*
|
|
10559
|
+
* @layer Service
|
|
10560
|
+
*/
|
|
10561
|
+
|
|
10562
|
+
/**
|
|
10563
|
+
* Remembers the latest use of each key in memory and writes them to the store in one batch per
|
|
10564
|
+
* window.
|
|
10565
|
+
*
|
|
10566
|
+
* A verified request does a `Map` write and nothing else. The trade-off is stated in the
|
|
10567
|
+
* README: with N instances a key is written up to N times per window, and a crash loses at most
|
|
10568
|
+
* one window of an advisory timestamp. Authorization never reads this, so a lost or late value
|
|
10569
|
+
* cannot admit or refuse anything.
|
|
10570
|
+
*/
|
|
10571
|
+
declare class ApiKeyLastUsedService implements OnApplicationShutdown {
|
|
10572
|
+
private readonly repository;
|
|
10573
|
+
private readonly options;
|
|
10574
|
+
private readonly logger;
|
|
10575
|
+
private pending;
|
|
10576
|
+
private timer;
|
|
10577
|
+
private closed;
|
|
10578
|
+
constructor(repository: IApiKeyRepository, options: ResolvedOptions);
|
|
10579
|
+
/**
|
|
10580
|
+
* Notes that a key verified at an instant. Synchronous and free of I/O.
|
|
10581
|
+
*
|
|
10582
|
+
* @param id - The key's row id.
|
|
10583
|
+
* @param at - When it verified.
|
|
10584
|
+
*/
|
|
10585
|
+
record(id: string, at: Date): void;
|
|
10586
|
+
/**
|
|
10587
|
+
* Writes everything pending in one batch. A failure keeps the entries for the next window.
|
|
10588
|
+
*
|
|
10589
|
+
* @returns Resolves once the batch is written or has been put back.
|
|
10590
|
+
*/
|
|
10591
|
+
flush(): Promise<void>;
|
|
10592
|
+
/** Flushes what is left so a clean shutdown loses nothing. */
|
|
10593
|
+
onApplicationShutdown(): Promise<void>;
|
|
10594
|
+
}
|
|
10595
|
+
|
|
10596
|
+
/**
|
|
10597
|
+
* @fileoverview Verifies a presented service key, taking the same steps for every key.
|
|
10598
|
+
*
|
|
10599
|
+
* @layer Service
|
|
10600
|
+
*/
|
|
10601
|
+
|
|
10602
|
+
/** Why a key was not accepted. */
|
|
10603
|
+
type ApiKeyRejection = Extract<ApiKeyDenyReason, 'missing' | 'malformed' | 'unknown' | 'wrong_secret' | 'revoked' | 'expired'>;
|
|
10604
|
+
/** The outcome of verifying one presented key. */
|
|
10605
|
+
type ApiKeyVerdict = {
|
|
10606
|
+
readonly ok: true;
|
|
10607
|
+
readonly key: AuthApiKey;
|
|
10608
|
+
} | {
|
|
10609
|
+
readonly ok: false;
|
|
10610
|
+
readonly reason: ApiKeyRejection;
|
|
10611
|
+
readonly key: AuthApiKey | null;
|
|
10612
|
+
};
|
|
10613
|
+
/**
|
|
10614
|
+
* Verifies a presented key against the store.
|
|
10615
|
+
*
|
|
10616
|
+
* Every call takes the same steps whatever the key is, in this order:
|
|
10617
|
+
* parse (substituting a dummy when it does not parse) → read the row (always) → compute the
|
|
10618
|
+
* digest → compare in constant time against the row's digest or a dummy → only then decide.
|
|
10619
|
+
* No branch leaves before the decision, so an unknown, malformed, wrong, revoked or expired key
|
|
10620
|
+
* cannot be told apart by what the library does.
|
|
10621
|
+
*
|
|
10622
|
+
* @remarks
|
|
10623
|
+
* What this does not hide: the store round trip differs in cost for a present and an absent
|
|
10624
|
+
* row, and no library can remove that. Pre-verification flood protection is a per-address
|
|
10625
|
+
* throttle in front of the guard, documented in the README.
|
|
10626
|
+
*/
|
|
10627
|
+
declare class ApiKeyVerifierService {
|
|
10628
|
+
private readonly repository;
|
|
10629
|
+
private readonly clock;
|
|
10630
|
+
private readonly options;
|
|
10631
|
+
private readonly lastUsed;
|
|
10632
|
+
constructor(repository: IApiKeyRepository, clock: ApiKeyClock, options: ResolvedOptions, lastUsed: ApiKeyLastUsedService);
|
|
10633
|
+
/**
|
|
10634
|
+
* Verifies the value of the key header.
|
|
10635
|
+
*
|
|
10636
|
+
* @param header - The header value as the framework delivered it.
|
|
10637
|
+
* @returns The verdict. A store fault propagates: the caller fails closed.
|
|
10638
|
+
*/
|
|
10639
|
+
verify(header: unknown): Promise<ApiKeyVerdict>;
|
|
10640
|
+
/**
|
|
10641
|
+
* The single decision, evaluated after every step above has run.
|
|
10642
|
+
*
|
|
10643
|
+
* A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
|
|
10644
|
+
* comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
|
|
10645
|
+
* compares false against everything) reads as lapsed rather than as valid.
|
|
10646
|
+
*/
|
|
10647
|
+
private rejection;
|
|
10648
|
+
}
|
|
10649
|
+
|
|
10650
|
+
/**
|
|
10651
|
+
* @fileoverview Authenticates machine callers by service API key and enforces route scopes.
|
|
10652
|
+
*
|
|
10653
|
+
* @layer Guard
|
|
10654
|
+
*/
|
|
10655
|
+
|
|
10656
|
+
/**
|
|
10657
|
+
* Admits a request only when it presents a valid service key holding every scope the route
|
|
10658
|
+
* declares.
|
|
10659
|
+
*
|
|
10660
|
+
* **Fails closed.** A route this guard is bound to with no non-empty scope declaration is
|
|
10661
|
+
* refused before any credential is read, so a forgotten `@ApiKeyScopes` can never become an
|
|
10662
|
+
* open route. That branch deliberately takes different steps from the credential paths: it
|
|
10663
|
+
* depends on route configuration, not on the key, so there is nothing for the key to leak.
|
|
10664
|
+
*
|
|
10665
|
+
* Every request ends in exactly one `onApiKeyRequest` event, refusals included. The presented
|
|
10666
|
+
* key and its secret appear in no log line, exception, event or `request.apiKey`.
|
|
10667
|
+
*
|
|
10668
|
+
* @example
|
|
10669
|
+
* ```typescript
|
|
10670
|
+
* @ServiceKey('read') // binds this guard and lets the route past the user JWT guards
|
|
10671
|
+
* @Get('videos')
|
|
10672
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { ... }
|
|
10673
|
+
* ```
|
|
10674
|
+
*/
|
|
10675
|
+
declare class ApiKeyGuard implements CanActivate {
|
|
10676
|
+
private readonly reflector;
|
|
10677
|
+
private readonly verifier;
|
|
10678
|
+
private readonly options;
|
|
10679
|
+
private readonly hooks;
|
|
10680
|
+
private readonly logger;
|
|
10681
|
+
constructor(reflector: Reflector, verifier: ApiKeyVerifierService, options: ResolvedOptions, hooks: IAuthHooks | null);
|
|
10682
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
10683
|
+
/**
|
|
10684
|
+
* The route's scope declaration: handler over class, empty or malformed counting as none.
|
|
10685
|
+
*
|
|
10686
|
+
* @returns The scopes, or `null` when the route declares none.
|
|
10687
|
+
*/
|
|
10688
|
+
private declaredScopes;
|
|
10689
|
+
/**
|
|
10690
|
+
* Emits the audit event.
|
|
10691
|
+
*
|
|
10692
|
+
* @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
|
|
10693
|
+
* is fired without being awaited and the result is always `true`.
|
|
10694
|
+
*/
|
|
10695
|
+
private audit;
|
|
10696
|
+
private hookContext;
|
|
10697
|
+
}
|
|
10698
|
+
|
|
10699
|
+
/**
|
|
10700
|
+
* Declares the scopes a route requires. A key must hold ALL of them.
|
|
10701
|
+
*
|
|
10702
|
+
* The low-level declaration, for a host that binds `ApiKeyGuard` at controller level or
|
|
10703
|
+
* globally. Most routes want {@link ServiceKey}, which also lets the route past the user JWT
|
|
10704
|
+
* guards and binds the guard, so the three cannot be separated by mistake.
|
|
10705
|
+
*
|
|
10706
|
+
* The most specific declaration wins (handler over class). An empty list counts as no
|
|
10707
|
+
* declaration, and a route with no declaration is refused.
|
|
10708
|
+
*
|
|
10709
|
+
* @param scopes - The required scopes, each from `apiKeys.scopes`.
|
|
10710
|
+
*
|
|
10711
|
+
* @example
|
|
10712
|
+
* ```typescript
|
|
10713
|
+
* @UseGuards(ApiKeyGuard)
|
|
10714
|
+
* @ApiKeyScopes('read')
|
|
10715
|
+
* @Get('videos')
|
|
10716
|
+
* list() { ... }
|
|
10717
|
+
* ```
|
|
10718
|
+
*/
|
|
10719
|
+
declare const ApiKeyScopes: (...scopes: string[]) => MethodDecorator & ClassDecorator;
|
|
10720
|
+
|
|
10721
|
+
/**
|
|
10722
|
+
* @fileoverview `@ServiceKey()` — authenticates a route by service API key.
|
|
10723
|
+
*
|
|
10724
|
+
* @layer Decorator
|
|
10725
|
+
*/
|
|
10726
|
+
/**
|
|
10727
|
+
* Makes a route reachable by a machine caller holding a service key with the given scopes.
|
|
10728
|
+
*
|
|
10729
|
+
* Three things in one decorator, so they cannot be separated by mistake:
|
|
10730
|
+
*
|
|
10731
|
+
* 1. the scopes the key must hold ({@link ApiKeyScopes});
|
|
10732
|
+
* 2. the route stops asking for a user JWT — `JwtAuthGuard` and `JwtPlatformGuard` skip a route
|
|
10733
|
+
* carrying the public marker, so a global JWT guard does not refuse the machine caller;
|
|
10734
|
+
* 3. `ApiKeyGuard` is bound to the route and is the ONLY authenticator in front of it.
|
|
10735
|
+
*
|
|
10736
|
+
* "Public" here means "not a user route", never "unauthenticated": the key guard refuses a
|
|
10737
|
+
* missing or invalid key on every request.
|
|
10738
|
+
*
|
|
10739
|
+
* @param scopes - The required scopes. At least one, each from `apiKeys.scopes`.
|
|
10740
|
+
*
|
|
10741
|
+
* @example
|
|
10742
|
+
* ```typescript
|
|
10743
|
+
* @ServiceKey('read')
|
|
10744
|
+
* @Get('videos')
|
|
10745
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { ... }
|
|
10746
|
+
* ```
|
|
10747
|
+
*/
|
|
10748
|
+
declare const ServiceKey: (...scopes: string[]) => MethodDecorator & ClassDecorator;
|
|
10749
|
+
|
|
10750
|
+
/**
|
|
10751
|
+
* @fileoverview `@CurrentApiKey()` — injects the verified service key into a handler.
|
|
10752
|
+
*
|
|
10753
|
+
* @layer Decorator
|
|
10754
|
+
*/
|
|
10755
|
+
/**
|
|
10756
|
+
* Injects the {@link ApiKeyPrincipal} `ApiKeyGuard` attached to the request.
|
|
10757
|
+
*
|
|
10758
|
+
* Only meaningful after the guard ran; `undefined` on a route the guard did not admit.
|
|
10759
|
+
*
|
|
10760
|
+
* @example
|
|
10761
|
+
* ```typescript
|
|
10762
|
+
* @ServiceKey('read')
|
|
10763
|
+
* @Get('videos')
|
|
10764
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { return this.videos.forKey(key.id) }
|
|
10765
|
+
* ```
|
|
10766
|
+
*/
|
|
10767
|
+
declare const CurrentApiKey: (...dataOrPipes: unknown[]) => ParameterDecorator;
|
|
10768
|
+
|
|
10769
|
+
/**
|
|
10770
|
+
* @fileoverview Issues, revokes and rotates service API keys.
|
|
10771
|
+
*
|
|
10772
|
+
* @layer Service
|
|
10773
|
+
*/
|
|
10774
|
+
|
|
10775
|
+
/** Longest label accepted, in characters. A label names a machine caller, it is not a payload. */
|
|
10776
|
+
declare const API_KEY_MAX_LABEL_LENGTH = 128;
|
|
10777
|
+
/** Longest rotation overlap accepted, in seconds: 30 days. */
|
|
10778
|
+
declare const API_KEY_MAX_OVERLAP_SECONDS = 2592000;
|
|
10779
|
+
/** What issuing a key asks for. */
|
|
10780
|
+
interface IssueApiKeyInput {
|
|
10781
|
+
/** Machine caller's name. Not unique. 1 to {@link API_KEY_MAX_LABEL_LENGTH} characters. */
|
|
10782
|
+
label: string;
|
|
10783
|
+
/** Scopes to grant: non-empty, each from `apiKeys.scopes`. */
|
|
10784
|
+
scopes: readonly string[];
|
|
10785
|
+
/** When the key stops verifying. Must be in the future. Absent means it does not expire. */
|
|
10786
|
+
expiresAt?: Date;
|
|
10787
|
+
}
|
|
10788
|
+
/** A newly issued key. */
|
|
10789
|
+
interface IssuedApiKey {
|
|
10790
|
+
/**
|
|
10791
|
+
* The plaintext key. Returned this once and never retrievable again: only its digest is
|
|
10792
|
+
* stored. Hand it to the machine caller and do not log it.
|
|
10793
|
+
*/
|
|
10794
|
+
key: string;
|
|
10795
|
+
/** The stored row without its digest. */
|
|
10796
|
+
record: AuthApiKeySummary;
|
|
10797
|
+
}
|
|
10798
|
+
/** What rotating a key asks for. */
|
|
10799
|
+
interface RotateApiKeyInput {
|
|
10800
|
+
/**
|
|
10801
|
+
* Seconds the old key keeps verifying after the new one is issued. `0` retires it at once.
|
|
10802
|
+
* An integer from 0 to {@link API_KEY_MAX_OVERLAP_SECONDS}.
|
|
10803
|
+
*/
|
|
10804
|
+
overlapSeconds: number;
|
|
10805
|
+
/** Expiry for the NEW key. Absent means it does not expire; the old key's expiry is not inherited. */
|
|
10806
|
+
expiresAt?: Date;
|
|
10807
|
+
}
|
|
10808
|
+
/**
|
|
10809
|
+
* Issues, revokes and rotates service keys.
|
|
10810
|
+
*
|
|
10811
|
+
* Rotation is not special-cased: it issues a second key with the same label and scopes, and
|
|
10812
|
+
* retires the first after the overlap. Several active keys sharing a label is the ordinary state.
|
|
10813
|
+
*/
|
|
10814
|
+
declare class ApiKeyService {
|
|
10815
|
+
private readonly repository;
|
|
10816
|
+
private readonly clock;
|
|
10817
|
+
private readonly options;
|
|
10818
|
+
constructor(repository: IApiKeyRepository, clock: ApiKeyClock, options: ResolvedOptions);
|
|
10819
|
+
/**
|
|
10820
|
+
* Issues a new key.
|
|
10821
|
+
*
|
|
10822
|
+
* @param input - Label, scopes and optional expiry.
|
|
10823
|
+
* @returns The plaintext key (once) and the stored record.
|
|
10824
|
+
* @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
|
|
10825
|
+
*/
|
|
10826
|
+
issue(input: IssueApiKeyInput): Promise<IssuedApiKey>;
|
|
10827
|
+
/**
|
|
10828
|
+
* Revokes a key now. Revoking an already revoked key succeeds.
|
|
10829
|
+
*
|
|
10830
|
+
* @param id - The key's row id.
|
|
10831
|
+
* @throws {AuthException} `auth.api_key_not_found` when no such key exists.
|
|
10832
|
+
*/
|
|
10833
|
+
revoke(id: string): Promise<void>;
|
|
10834
|
+
/**
|
|
10835
|
+
* Replaces a key with a new one carrying the same label and scopes.
|
|
10836
|
+
*
|
|
10837
|
+
* The new key is issued first and the old one retired second, so a failure between the two
|
|
10838
|
+
* leaves both valid — the safe direction — rather than neither.
|
|
10839
|
+
*
|
|
10840
|
+
* @param id - The active key to replace.
|
|
10841
|
+
* @param input - The overlap and an optional expiry for the new key.
|
|
10842
|
+
* @returns The new key, plaintext once.
|
|
10843
|
+
* @throws {AuthException} `auth.validation` for a bad overlap or expiry;
|
|
10844
|
+
* `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
|
|
10845
|
+
* rotated: that would re-issue access nobody holds).
|
|
10846
|
+
*/
|
|
10847
|
+
rotate(id: string, input: RotateApiKeyInput): Promise<IssuedApiKey>;
|
|
10848
|
+
private validatedLabel;
|
|
10849
|
+
private validatedScopes;
|
|
10850
|
+
private validatedExpiry;
|
|
10851
|
+
}
|
|
10852
|
+
|
|
10853
|
+
export { API_KEY_MAX_LABEL_LENGTH, API_KEY_MAX_OVERLAP_SECONDS, AUTH_EMAIL_KINDS, AUTH_ERROR_CODES, AUTH_ERROR_MESSAGES, AUTH_ERROR_STATUS, AUTH_SECURITY_SCHEMES, AUTH_THROTTLE_CONFIGS, AcceptInvitationDto, AccountStatusService, AllowAllBreachChecker, type ApiKeyAccessEvent, type ApiKeyClock, type ApiKeyDenyReason, ApiKeyGuard, type ApiKeyPrincipal, ApiKeyScopes, ApiKeyService, type AuthApiKey, type AuthApiKeySummary, type AuthDocumentSecurityParams, type AuthEmailCatalogue, type AuthEmailContext, type AuthEmailKind, type AuthEmailMessage, type AuthEmailSink, type AuthErrorCode, AuthException, AuthExceptionFilter, type AuthFieldError, type AuthGuardFamily, type AuthModuleAsyncOptions, type AuthPlane, type AuthPlatformUser, AuthRateLimit, AuthRateLimitGuard, type AuthRateLimitWindow, type AuthResult, AuthRevocationService, AuthService, AuthTokenVerifierService, type AuthUser, Authenticated, type AuthenticatedRequest, BYMAX_AUTH_API_KEY_CLOCK, BYMAX_AUTH_API_KEY_REPOSITORY, BYMAX_AUTH_BREACH_CHECKER, BYMAX_AUTH_EMAIL_PROVIDER, BYMAX_AUTH_HOOKS, BYMAX_AUTH_OPTIONS, BYMAX_AUTH_PLATFORM_USER_REPOSITORY, BYMAX_AUTH_REDIS_CLIENT, BYMAX_AUTH_USER_REPOSITORY, type BearerAuthResponse, type BeforeRegisterResult, type BothAuthResponse, BruteForceService, BymaxAuthModule, type BymaxAuthModuleOptions, type BymaxAuthRateLimitOptions, ChangePasswordDto, type ClientIpSource, CommonPasswordChecker, type CookieAuthResponse, CreateInvitationDto, type CreateSessionParams, type CreateUserData, type CreateWithOAuthData, CurrentApiKey, CurrentUser, type DashboardJwtPayload, DefaultAuthEmailProvider, type DefaultAuthEmailProviderOptions, type DeliveryErrorPolicy, type DeliveryErrorPolicyMap, EmailChangeService, type FindUserByEmailParams, type FindUserByOAuthIdParams, ForgotPasswordDto, HibpBreachChecker, type HookContext, type IApiKeyRepository, type IAuthHooks, type IEmailProvider, type IPasswordBreachChecker, type IPlatformUserRepository, IS_PUBLIC_KEY, type IUserRepository, InvitationService, type InviteData, type IssueApiKeyInput, type IssuedApiKey, JwtAuthGuard, JwtPlatformGuard, type LinkOAuthParams, type ListSessionsParams, LoginDto, MfaChallengeDto, type MfaChallengeResult, MfaDisableDto, MfaRegenerateRecoveryCodesDto, MfaRequiredGuard, MfaService, type MfaSetupResult, type MfaTempPayload, MfaVerifyDto, NoOpAuthHooks, NoOpEmailProvider, type OAuthLoginResult, type OAuthMfaChallengeResult, type OAuthProfile, type OAuthProviderPlugin, OAuthService, type OpenApiSecurityRequirement, OptionalAuthGuard, OtpService, PLATFORM_ROLES_KEY, PasswordResetService, type PlatformAuthResult, PlatformAuthService, type PlatformAuthenticatedRequest, type PlatformBearerAuthResponse, type PlatformJwtPayload, PlatformLoginDto, PlatformRoles, PlatformRolesGuard, Public, ROLES_KEY, RegisterDto, ResendOtpDto, ResendVerificationDto, ResetPasswordDto, type ResolvedOptions, type RevocableTokenPayload, type RevokeAllExceptCurrentParams, type RevokeAllSessionsParams, type RevokeSessionParams, Roles, RolesGuard, type RotateApiKeyInput, type RotatedTokenResult, SKIP_MFA_KEY, type SafeAuthPlatformUser, type SafeAuthUser, SelfOrAdminGuard, ServiceKey, type SessionAlertInfo, type SessionInfo, SessionService, SkipMfa, type TenantResolverRequest, type TenantScopedUserRef, TokenDeliveryService, TrustedOriginGuard, type UpdateEmailParams, type UpdateEmailVerifiedParams, type UpdateMfaData, type UpdateMfaParams, type UpdatePasswordParams, type UpdatePlatformMfaData, type UpdateStatusParams, UserStatusGuard, type VerifiedAccessToken, type VerifyAccessTokenOptions, VerifyEmailDto, VerifyOtpDto, WS_TICKET_TTL_SECONDS, WsAuthExceptionFilter, WsJwtGuard, WsTicketService, type WsTicketSnapshot, authDocumentSecurity, createAuthValidationPipe, decrypt, describeChannelStatus, describeError, encrypt, generateSecureToken, hasRole, hmacSha256, redactSecrets, reduceToBaseWord, sanitizeHeaders, sha256, sleep, timingSafeCompare };
|