@bymax-one/nest-auth 1.4.5 → 1.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +633 -3
- package/README.md +528 -70
- package/dist/nextjs/index.d.cts +10 -12
- package/dist/nextjs/index.d.ts +10 -12
- package/dist/react/index.cjs +4 -4
- package/dist/react/index.d.cts +15 -2
- package/dist/react/index.d.ts +15 -2
- package/dist/react/index.mjs +4 -4
- package/dist/server/index.cjs +3254 -1047
- package/dist/server/index.d.cts +1269 -95
- package/dist/server/index.d.ts +1269 -95
- package/dist/server/index.mjs +3252 -1052
- 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 +5 -4
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,7 +496,48 @@ 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 {
|
|
517
|
+
/**
|
|
518
|
+
* Secret the Redis identifiers derive from. Optional; default: `jwt.secret`.
|
|
519
|
+
*
|
|
520
|
+
* Every name that identifies an account in Redis — the session index, the token epoch, the MFA
|
|
521
|
+
* keys, the recent-authentication marker, the OTP and rate-limit identifiers — is an HMAC under
|
|
522
|
+
* a key derived from one secret. By default that secret is `jwt.secret`, so rotating
|
|
523
|
+
* `jwt.secret` renames all of them: live sessions lose their index and every token epoch reads
|
|
524
|
+
* zero, which accepts again the tokens a password reset or a revoke-all had refused.
|
|
525
|
+
*
|
|
526
|
+
* Setting `identifierKey` makes the identifiers derive from it instead, so `jwt.secret` can be
|
|
527
|
+
* rotated without moving a single name. Set it once, to the value `jwt.secret` has now, and leave
|
|
528
|
+
* it as it is through later rotations; every derived name stays exactly where it is. It is
|
|
529
|
+
* validated like `jwt.secret` and is never used to sign or verify a token. It names keys and it
|
|
530
|
+
* keys the stored MFA recovery-code digests, which are an HMAC under the same derived key.
|
|
531
|
+
*
|
|
532
|
+
* Choose a NEW value instead when the point of the rotation is to cut the link to the old
|
|
533
|
+
* secret. The identifiers then move: sessions lose their index until they next refresh (they leave the session list and
|
|
534
|
+
* cannot be revoked through it meanwhile, while their opaque refresh tokens keep working), epochs reset,
|
|
535
|
+
* and recovery-code digests stop verifying unless the old secret stays in
|
|
536
|
+
* `jwt.previousSecrets`. Revoke what has to be revoked before moving the key.
|
|
537
|
+
*
|
|
538
|
+
* @throws {Error} When the value fails validation at module initialisation.
|
|
539
|
+
*/
|
|
540
|
+
identifierKey?: string;
|
|
500
541
|
/**
|
|
501
542
|
* JWT signing configuration.
|
|
502
543
|
* `secret` is required and must be at least 32 characters with sufficient entropy.
|
|
@@ -1011,6 +1052,58 @@ interface BymaxAuthModuleOptions {
|
|
|
1011
1052
|
*/
|
|
1012
1053
|
tokenTtlSeconds?: number;
|
|
1013
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
|
+
};
|
|
1014
1107
|
/**
|
|
1015
1108
|
* Role hierarchy configuration. **Required.**
|
|
1016
1109
|
*
|
|
@@ -1199,7 +1292,9 @@ interface BymaxAuthModuleOptions {
|
|
|
1199
1292
|
* none is refused with the same `auth.validation` — the deployment has to choose one of the
|
|
1200
1293
|
* two, and neither choice is guessed on its behalf.
|
|
1201
1294
|
*
|
|
1202
|
-
* @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.
|
|
1203
1298
|
* @returns The tenant ID string, or a Promise resolving to it
|
|
1204
1299
|
*
|
|
1205
1300
|
* @throws {Error} When the resolver returns an empty string or throws.
|
|
@@ -1226,7 +1321,7 @@ interface BymaxAuthModuleOptions {
|
|
|
1226
1321
|
* }
|
|
1227
1322
|
* ```
|
|
1228
1323
|
*/
|
|
1229
|
-
tenantIdResolver?: (req:
|
|
1324
|
+
tenantIdResolver?: (req: TenantResolverRequest) => string | Promise<string>;
|
|
1230
1325
|
/**
|
|
1231
1326
|
* Whether the dashboard guard re-resolves the request's tenant and rejects a token whose
|
|
1232
1327
|
* `tenantId` claim does not match it.
|
|
@@ -1240,6 +1335,11 @@ interface BymaxAuthModuleOptions {
|
|
|
1240
1335
|
* (subdomain-per-tenant behind an edge that refuses a `Host` it does not serve), turning this on
|
|
1241
1336
|
* closes that gap: the guard calls {@link tenantIdResolver} and refuses a mismatch.
|
|
1242
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
|
+
*
|
|
1243
1343
|
* Off by default, and requires a resolver to have any effect: with no resolver there is nothing
|
|
1244
1344
|
* to compare against. Leave it off where a token is legitimately used across hosts (a single API
|
|
1245
1345
|
* origin serving many tenants by claim), because there the resolved host tenant and the token
|
|
@@ -1488,6 +1588,20 @@ declare const BYMAX_AUTH_BREACH_CHECKER: unique symbol;
|
|
|
1488
1588
|
* Bound to an `ioredis` `Redis` instance configured for the host environment.
|
|
1489
1589
|
*/
|
|
1490
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;
|
|
1491
1605
|
|
|
1492
1606
|
/**
|
|
1493
1607
|
* resolveOptions — merge consumer options with defaults and validate security invariants.
|
|
@@ -1511,7 +1625,7 @@ declare const BYMAX_AUTH_REDIS_CLIENT: unique symbol;
|
|
|
1511
1625
|
* interface-extension compatibility check with `exactOptionalPropertyTypes`,
|
|
1512
1626
|
* which rejects intersection widening of optional function properties.
|
|
1513
1627
|
*/
|
|
1514
|
-
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'> & {
|
|
1515
1629
|
jwt: Required<Omit<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>> & Pick<BymaxAuthModuleOptions['jwt'], 'previousSecrets' | 'issuer' | 'audience'>;
|
|
1516
1630
|
password: Required<NonNullable<BymaxAuthModuleOptions['password']>>;
|
|
1517
1631
|
tokenDelivery: NonNullable<BymaxAuthModuleOptions['tokenDelivery']>;
|
|
@@ -1522,6 +1636,7 @@ type ResolvedOptions = Omit<BymaxAuthModuleOptions, 'jwt' | 'password' | 'tokenD
|
|
|
1522
1636
|
emailVerification: Required<NonNullable<BymaxAuthModuleOptions['emailVerification']>>;
|
|
1523
1637
|
platform: Required<NonNullable<BymaxAuthModuleOptions['platform']>>;
|
|
1524
1638
|
invitations: Required<NonNullable<BymaxAuthModuleOptions['invitations']>>;
|
|
1639
|
+
apiKeys: Required<NonNullable<BymaxAuthModuleOptions['apiKeys']>>;
|
|
1525
1640
|
emailChange: Required<NonNullable<BymaxAuthModuleOptions['emailChange']>>;
|
|
1526
1641
|
rateLimit: {
|
|
1527
1642
|
enabled: boolean;
|
|
@@ -2142,6 +2257,23 @@ declare const AUTH_ERROR_CODES: {
|
|
|
2142
2257
|
readonly OAUTH_EMAIL_MISMATCH: "auth.oauth_email_mismatch";
|
|
2143
2258
|
/** Platform-admin endpoint accessed with a dashboard JWT instead of a platform JWT. */
|
|
2144
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";
|
|
2145
2277
|
/**
|
|
2146
2278
|
* An unexpected internal failure. The cause is logged and never serialized.
|
|
2147
2279
|
*
|
|
@@ -2774,6 +2906,20 @@ interface HookContext {
|
|
|
2774
2906
|
email?: string;
|
|
2775
2907
|
/** Tenant identifier, available in multi-tenant flows. */
|
|
2776
2908
|
tenantId?: string;
|
|
2909
|
+
/**
|
|
2910
|
+
* Which identity plane the event belongs to.
|
|
2911
|
+
*
|
|
2912
|
+
* Set on every context this library builds. It exists because the tenant alone cannot answer the
|
|
2913
|
+
* question: a platform administrator belongs to no tenant, and `MfaService` renders one as a
|
|
2914
|
+
* `SafeAuthUser` with the sentinel `tenantId: ''` because the type demands the field — while a
|
|
2915
|
+
* platform access token carries no tenant claim at all and reads `undefined`. A consumer
|
|
2916
|
+
* correlating a hook against a live connection by comparing those two values matches nothing on
|
|
2917
|
+
* the platform plane and silently skips every platform admin.
|
|
2918
|
+
*
|
|
2919
|
+
* Branch on this rather than on the shape of `tenantId`. Absent only on a context a consumer
|
|
2920
|
+
* built itself.
|
|
2921
|
+
*/
|
|
2922
|
+
plane?: 'dashboard' | 'platform';
|
|
2777
2923
|
/**
|
|
2778
2924
|
* IP address of the originating request.
|
|
2779
2925
|
*
|
|
@@ -2830,7 +2976,8 @@ interface OAuthLoginResult {
|
|
|
2830
2976
|
/**
|
|
2831
2977
|
* Desired action for this OAuth login attempt:
|
|
2832
2978
|
* - `'create'` — provision a new user account from the OAuth profile.
|
|
2833
|
-
* - `'link'` —
|
|
2979
|
+
* - `'link'` — keep the OAuth identity linked to the user passed as `existingUser`;
|
|
2980
|
+
* refused when there is none.
|
|
2834
2981
|
* - `'reject'` — deny the login attempt (e.g. domain allowlist enforcement).
|
|
2835
2982
|
*/
|
|
2836
2983
|
action: 'link' | 'create' | 'reject';
|
|
@@ -2925,6 +3072,23 @@ interface IAuthHooks {
|
|
|
2925
3072
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
2926
3073
|
*/
|
|
2927
3074
|
afterLogout?(userId: string, context: HookContext): Promise<void> | void;
|
|
3075
|
+
/**
|
|
3076
|
+
* Called after a platform administrator's session has been invalidated.
|
|
3077
|
+
*
|
|
3078
|
+
* Separate from {@link IAuthHooks.afterLogout} rather than sharing it with a `plane` marker,
|
|
3079
|
+
* deliberately: an existing `afterLogout` handler was written for dashboard users and may look up
|
|
3080
|
+
* a tenant, so routing platform events into it would change what that handler receives without
|
|
3081
|
+
* the handler asking. A distinct member is additive and unambiguous.
|
|
3082
|
+
*
|
|
3083
|
+
* **`PlatformAuthService` reports a completed logout only through this hook**, and emits no
|
|
3084
|
+
* other. A consumer that does not implement it learns nothing when an administrator signs out:
|
|
3085
|
+
* the access token stays presentable until it expires, and the session's removal is unobserved.
|
|
3086
|
+
* That matters most for a live platform stream, which has no other signal to close on.
|
|
3087
|
+
*
|
|
3088
|
+
* @param userId - The internal ID of the administrator who logged out.
|
|
3089
|
+
* @param context - Request metadata; `plane` is `'platform'` and there is no tenant.
|
|
3090
|
+
*/
|
|
3091
|
+
afterPlatformLogout?(userId: string, context: HookContext): Promise<void> | void;
|
|
2928
3092
|
/**
|
|
2929
3093
|
* Called when a login attempt is refused.
|
|
2930
3094
|
*
|
|
@@ -2976,7 +3140,11 @@ interface IAuthHooks {
|
|
|
2976
3140
|
email: string;
|
|
2977
3141
|
/** The tenant the lockout is scoped to. */
|
|
2978
3142
|
tenantId: string;
|
|
2979
|
-
/**
|
|
3143
|
+
/**
|
|
3144
|
+
* Seconds until the window expires and attempts are accepted again. When the remaining
|
|
3145
|
+
* time cannot be read from the store this is the configured `bruteForce.windowSeconds`,
|
|
3146
|
+
* an upper bound, rather than the exact remainder.
|
|
3147
|
+
*/
|
|
2980
3148
|
retryAfterSeconds: number;
|
|
2981
3149
|
}, context: HookContext): Promise<void> | void;
|
|
2982
3150
|
/**
|
|
@@ -3069,8 +3237,11 @@ interface IAuthHooks {
|
|
|
3069
3237
|
* identity to an existing account, or reject the login (e.g. domain allowlists).
|
|
3070
3238
|
*
|
|
3071
3239
|
* @param profile - Normalized OAuth profile from the provider.
|
|
3072
|
-
* @param existingUser -
|
|
3073
|
-
*
|
|
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`.
|
|
3074
3245
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
3075
3246
|
* @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
|
|
3076
3247
|
*/
|
|
@@ -3101,6 +3272,51 @@ interface IAuthHooks {
|
|
|
3101
3272
|
* @param context - Request metadata (IP, user agent, sanitized headers).
|
|
3102
3273
|
*/
|
|
3103
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;
|
|
3104
3320
|
}
|
|
3105
3321
|
|
|
3106
3322
|
/**
|
|
@@ -3112,8 +3328,8 @@ interface IAuthHooks {
|
|
|
3112
3328
|
* @remarks
|
|
3113
3329
|
* - {@link beforeRegister} returns `{ allowed: true }` unconditionally.
|
|
3114
3330
|
* - {@link onOAuthLogin} applies the standard account-resolution strategy:
|
|
3115
|
-
*
|
|
3116
|
-
*
|
|
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.
|
|
3117
3333
|
* - All other hooks are no-ops (return `void`).
|
|
3118
3334
|
*
|
|
3119
3335
|
* Replace this with a custom `IAuthHooks` implementation to enforce domain
|
|
@@ -3133,11 +3349,11 @@ declare class NoOpAuthHooks implements IAuthHooks {
|
|
|
3133
3349
|
tenantId: string;
|
|
3134
3350
|
}, _context: HookContext): BeforeRegisterResult;
|
|
3135
3351
|
/**
|
|
3136
|
-
* Resolves OAuth login
|
|
3137
|
-
*
|
|
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.
|
|
3138
3354
|
*
|
|
3139
3355
|
* @param profile - Normalized OAuth profile from the provider.
|
|
3140
|
-
* @param existingUser -
|
|
3356
|
+
* @param existingUser - The user already linked to this provider identity, or `null`.
|
|
3141
3357
|
* @param _context - Hook execution context carrying request metadata.
|
|
3142
3358
|
* @returns An {@link OAuthLoginResult} controlling the account resolution strategy.
|
|
3143
3359
|
*/
|
|
@@ -3867,61 +4083,65 @@ interface AuthEmailMessage {
|
|
|
3867
4083
|
*/
|
|
3868
4084
|
readonly containsCredential?: boolean | undefined;
|
|
3869
4085
|
}
|
|
4086
|
+
/**
|
|
4087
|
+
* What every renderer is told about the delivery it renders for.
|
|
4088
|
+
*
|
|
4089
|
+
* A link built inside a renderer has to carry the tenant: a recipient who opens it in a browser
|
|
4090
|
+
* with no tenant cookie is refused by a `tenantIdResolver` otherwise. The renderer is the only
|
|
4091
|
+
* place that URL is built, so it receives the tenant and the recipient rather than having the
|
|
4092
|
+
* host stash them on the provider, which is a singleton shared by concurrent requests.
|
|
4093
|
+
*/
|
|
4094
|
+
interface AuthEmailContext {
|
|
4095
|
+
/** The tenant the message is attributed to. */
|
|
4096
|
+
readonly tenantId: string;
|
|
4097
|
+
/** The address the message is delivered to. */
|
|
4098
|
+
readonly email: string;
|
|
4099
|
+
/** BCP 47 locale tag the message is rendered in, when the caller supplied one. */
|
|
4100
|
+
readonly locale?: string | undefined;
|
|
4101
|
+
}
|
|
3870
4102
|
/**
|
|
3871
4103
|
* The copy for every message the port can send, as pure renderers keyed by event.
|
|
3872
4104
|
*
|
|
3873
|
-
* Each
|
|
4105
|
+
* Each receives an {@link AuthEmailContext} together with its own fields and returns an
|
|
4106
|
+
* {@link AuthEmailMessage}; the provider attaches the tenant and recipient and
|
|
3874
4107
|
* handles escaping and delivery. Override any subset through
|
|
3875
4108
|
* {@link DefaultAuthEmailProviderOptions.messages} — an entry left unset keeps the secure default.
|
|
3876
4109
|
*/
|
|
3877
4110
|
interface AuthEmailCatalogue {
|
|
3878
4111
|
/** Password-reset link carrying a signed token. */
|
|
3879
|
-
passwordResetToken(input: {
|
|
4112
|
+
passwordResetToken(input: AuthEmailContext & {
|
|
3880
4113
|
token: string;
|
|
3881
|
-
locale?: string | undefined;
|
|
3882
4114
|
}): AuthEmailMessage;
|
|
3883
4115
|
/** One-time code for the password-reset flow. */
|
|
3884
|
-
passwordResetOtp(input: {
|
|
4116
|
+
passwordResetOtp(input: AuthEmailContext & {
|
|
3885
4117
|
otp: string;
|
|
3886
|
-
locale?: string | undefined;
|
|
3887
4118
|
}): AuthEmailMessage;
|
|
3888
4119
|
/** One-time code that activates a newly registered account. */
|
|
3889
|
-
emailVerificationOtp(input: {
|
|
4120
|
+
emailVerificationOtp(input: AuthEmailContext & {
|
|
3890
4121
|
otp: string;
|
|
3891
|
-
locale?: string | undefined;
|
|
3892
4122
|
}): AuthEmailMessage;
|
|
3893
4123
|
/** Notice that the account password changed (NIST SP 800-63B §4.6). */
|
|
3894
|
-
passwordChanged(input:
|
|
3895
|
-
locale?: string | undefined;
|
|
3896
|
-
}): AuthEmailMessage;
|
|
4124
|
+
passwordChanged(input: AuthEmailContext): AuthEmailMessage;
|
|
3897
4125
|
/** Code confirming ownership of an address the user is moving to. */
|
|
3898
|
-
emailChangeVerification(input: {
|
|
4126
|
+
emailChangeVerification(input: AuthEmailContext & {
|
|
3899
4127
|
token: string;
|
|
3900
|
-
locale?: string | undefined;
|
|
3901
4128
|
}): AuthEmailMessage;
|
|
3902
4129
|
/** Notice to the previous address that the account's email moved. */
|
|
3903
|
-
emailChanged(input: {
|
|
4130
|
+
emailChanged(input: AuthEmailContext & {
|
|
3904
4131
|
oldEmail: string;
|
|
3905
4132
|
newEmail: string;
|
|
3906
|
-
locale?: string | undefined;
|
|
3907
4133
|
}): AuthEmailMessage;
|
|
3908
4134
|
/** Notice that a second factor was added. */
|
|
3909
|
-
mfaEnabled(input:
|
|
3910
|
-
locale?: string | undefined;
|
|
3911
|
-
}): AuthEmailMessage;
|
|
4135
|
+
mfaEnabled(input: AuthEmailContext): AuthEmailMessage;
|
|
3912
4136
|
/** Notice that a second factor was removed. */
|
|
3913
|
-
mfaDisabled(input:
|
|
3914
|
-
locale?: string | undefined;
|
|
3915
|
-
}): AuthEmailMessage;
|
|
4137
|
+
mfaDisabled(input: AuthEmailContext): AuthEmailMessage;
|
|
3916
4138
|
/** Security alert about a newly established session. */
|
|
3917
|
-
newSessionAlert(input: {
|
|
4139
|
+
newSessionAlert(input: AuthEmailContext & {
|
|
3918
4140
|
sessionInfo: SessionAlertInfo;
|
|
3919
|
-
locale?: string | undefined;
|
|
3920
4141
|
}): AuthEmailMessage;
|
|
3921
4142
|
/** Invitation to join a tenant. */
|
|
3922
|
-
invitation(input: {
|
|
4143
|
+
invitation(input: AuthEmailContext & {
|
|
3923
4144
|
invite: InviteData;
|
|
3924
|
-
locale?: string | undefined;
|
|
3925
4145
|
}): AuthEmailMessage;
|
|
3926
4146
|
}
|
|
3927
4147
|
/** How the provider reacts to a delivery failure. */
|
|
@@ -4283,7 +4503,8 @@ declare const WS_TICKET_TTL_SECONDS = 30;
|
|
|
4283
4503
|
* A snapshot, never a token: it is what the access JWT already proved at mint time, frozen for
|
|
4284
4504
|
* the socket's lifetime. It carries no signature, no expiry of its own, and nothing that can be
|
|
4285
4505
|
* presented back to the REST surface — a leaked snapshot buys an attacker a socket, not a
|
|
4286
|
-
* session.
|
|
4506
|
+
* session. It does carry the minting token's `jti` and `epoch`, the two keys the revocation
|
|
4507
|
+
* channels are read by, so that redeeming it can be refused exactly when that token would be.
|
|
4287
4508
|
*
|
|
4288
4509
|
* The field names are the wire contract shared with rust-auth
|
|
4289
4510
|
* (`conformance/wire-contract.json`, `recordEncodings.wsTicket`): both backends read each
|
|
@@ -4302,6 +4523,16 @@ interface WsTicketSnapshot {
|
|
|
4302
4523
|
mfaEnabled: boolean;
|
|
4303
4524
|
/** Whether the originating session had already satisfied MFA. */
|
|
4304
4525
|
mfaVerified: boolean;
|
|
4526
|
+
/**
|
|
4527
|
+
* The `jti` of the access token that minted the ticket — the key of the per-token blacklist.
|
|
4528
|
+
* An identifier, not a credential: it cannot be presented to the REST surface.
|
|
4529
|
+
*/
|
|
4530
|
+
jti: string;
|
|
4531
|
+
/**
|
|
4532
|
+
* The user's token epoch stamped on the minting access token, `0` when it carried none. A ticket
|
|
4533
|
+
* whose epoch is below the user's current one belongs to a session a bulk revocation ended.
|
|
4534
|
+
*/
|
|
4535
|
+
epoch: number;
|
|
4305
4536
|
}
|
|
4306
4537
|
|
|
4307
4538
|
/** The rotation bundle {@link AuthRedisService.rotateRefreshSession} consumes. */
|
|
@@ -5429,14 +5660,132 @@ declare class TrustedOriginGuard implements CanActivate {
|
|
|
5429
5660
|
canActivate(context: ExecutionContext): boolean;
|
|
5430
5661
|
}
|
|
5431
5662
|
|
|
5663
|
+
/**
|
|
5664
|
+
* @fileoverview Account lifecycle gate shared by the status guard and the token verifier.
|
|
5665
|
+
*
|
|
5666
|
+
* @layer Service
|
|
5667
|
+
*/
|
|
5668
|
+
|
|
5669
|
+
/**
|
|
5670
|
+
* Resolves an account's current lifecycle state and refuses the ones a deployment blocks.
|
|
5671
|
+
*
|
|
5672
|
+
* The answer a token carries is a snapshot taken at issuance: `DashboardJwtPayload.status` says
|
|
5673
|
+
* what the account was when it signed in, not what it is now. Anything that outlives a single
|
|
5674
|
+
* request — an access token's whole lifetime, a stream held open for hours — therefore has to ask
|
|
5675
|
+
* again, which is what this service exists to do.
|
|
5676
|
+
*
|
|
5677
|
+
* It reads through a Redis cache (`us:{tenantId}:{userId}`, and `uev:` for the verified flag)
|
|
5678
|
+
* rather than the repository, so asking on every request or on every reconnect costs one `get`
|
|
5679
|
+
* rather than a database round trip. A miss resolves both facts from a single tenant-scoped read
|
|
5680
|
+
* and writes both back for `userStatusCacheTtlSeconds`.
|
|
5681
|
+
*
|
|
5682
|
+
* Both {@link UserStatusGuard} and {@link AuthTokenVerifierService} delegate here rather than
|
|
5683
|
+
* carrying a copy: the cache key shape, the miss path and the order of the two refusals are one
|
|
5684
|
+
* rule, and a second implementation of it is how the two drift apart.
|
|
5685
|
+
*
|
|
5686
|
+
* @layer Service
|
|
5687
|
+
*/
|
|
5688
|
+
declare class AccountStatusService {
|
|
5689
|
+
private readonly redis;
|
|
5690
|
+
private readonly userRepo;
|
|
5691
|
+
private readonly options;
|
|
5692
|
+
private readonly platformUserRepo?;
|
|
5693
|
+
/**
|
|
5694
|
+
* @param redis - The auth module's Redis service, holding the status and verified caches.
|
|
5695
|
+
* @param userRepo - The consumer's dashboard user repository, read on a cache miss.
|
|
5696
|
+
* @param options - Resolved module options, for the cache TTL and the blocked-status set.
|
|
5697
|
+
* @param platformUserRepo - The consumer's platform administrator repository. Absent unless
|
|
5698
|
+
* `controllers.platform` is on, which is also the only configuration that can mint a
|
|
5699
|
+
* platform token — so its absence is never a gap, and is refused rather than skipped.
|
|
5700
|
+
*/
|
|
5701
|
+
constructor(redis: AuthRedisService, userRepo: IUserRepository, options: ResolvedOptions, platformUserRepo?: IPlatformUserRepository | undefined);
|
|
5702
|
+
/**
|
|
5703
|
+
* Drops the cached status and email-verified flag for one account, so the next check re-reads
|
|
5704
|
+
* them from the repository.
|
|
5705
|
+
*
|
|
5706
|
+
* **Call this whenever you change an account's status outside this library.** A host suspending
|
|
5707
|
+
* a user through its own admin surface leaves this cache holding `active` until it expires, and
|
|
5708
|
+
* the suspended user keeps reaching protected routes for up to `userStatusCacheTtlSeconds`. This
|
|
5709
|
+
* is the supported way to close that window; reaching into the key prefix is not, because the
|
|
5710
|
+
* format is this library's to change and a delete that stops matching fails silently.
|
|
5711
|
+
*
|
|
5712
|
+
* Both keys go, not only the one a given caller cares about. They are written together and
|
|
5713
|
+
* dropping the other costs one repository read on the next request — a smaller price than an API
|
|
5714
|
+
* where the caller has to know which of two entries their change invalidated.
|
|
5715
|
+
*
|
|
5716
|
+
* Idempotent: deleting an absent key is not an error, so a caller need not know whether the
|
|
5717
|
+
* account was ever cached.
|
|
5718
|
+
*
|
|
5719
|
+
* **What it does not guarantee.** A request already in flight can repopulate the entry. The read
|
|
5720
|
+
* path fills the cache in two steps — resolve from the repository, then write — so a request
|
|
5721
|
+
* that resolved `active` just before your update lands will write `active` afterwards, with a
|
|
5722
|
+
* full TTL, however promptly you call this. The window is one repository read wide, not one TTL,
|
|
5723
|
+
* which is the whole improvement over letting the entry expire; it is not zero. **Order your own
|
|
5724
|
+
* writes accordingly: persist the status change first, then invalidate** — that way any request
|
|
5725
|
+
* whose repository read starts after your write already sees the new value, and only the
|
|
5726
|
+
* genuinely concurrent ones can lose the race.
|
|
5727
|
+
*
|
|
5728
|
+
* Closing it entirely needs the fill to be conditional on nothing having invalidated in between —
|
|
5729
|
+
* a per-account generation the write compares against — which is a mechanism this service does
|
|
5730
|
+
* not have. Tracked rather than implied.
|
|
5731
|
+
*
|
|
5732
|
+
* @param ref - The account whose cached facts are now stale. Both fields must be non-empty.
|
|
5733
|
+
* @throws {TypeError} When either id is empty or blank. Refused rather than attempted: an empty
|
|
5734
|
+
* tenant builds `us::{userId}`, which names no entry any read ever wrote, so the delete would
|
|
5735
|
+
* remove nothing and resolve normally — the caller's admin surface reports the suspension
|
|
5736
|
+
* applied while the cached `active` survives its full TTL. That is the exact silent failure
|
|
5737
|
+
* this method exists to eliminate, and an unset resolver value or a `undefined` coerced by a
|
|
5738
|
+
* JavaScript host is how it arrives. A caller error, so not an `AuthException`.
|
|
5739
|
+
*/
|
|
5740
|
+
invalidate(ref: {
|
|
5741
|
+
readonly userId: string;
|
|
5742
|
+
readonly tenantId: string;
|
|
5743
|
+
}): Promise<void>;
|
|
5744
|
+
/**
|
|
5745
|
+
* Refuses a dashboard account that is blocked, deleted, or unverified where verification gates
|
|
5746
|
+
* API access.
|
|
5747
|
+
*
|
|
5748
|
+
* @param ref - The account to resolve. The tenant is required, not optional: a repository id is
|
|
5749
|
+
* unique only WITHIN a tenant, so a status cached or read under a bare id could answer for a
|
|
5750
|
+
* colliding id in another tenant.
|
|
5751
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` when no such account exists, the matching
|
|
5752
|
+
* `ACCOUNT_*` code when the status is blocked, or `EMAIL_NOT_VERIFIED` when verification is
|
|
5753
|
+
* required and the address is not verified.
|
|
5754
|
+
*/
|
|
5755
|
+
assertDashboardAccountUsable(ref: {
|
|
5756
|
+
readonly userId: string;
|
|
5757
|
+
readonly tenantId: string;
|
|
5758
|
+
}): Promise<void>;
|
|
5759
|
+
/**
|
|
5760
|
+
* Refuses a platform administrator whose account is blocked or gone.
|
|
5761
|
+
*
|
|
5762
|
+
* Uncached, unlike the dashboard side. The platform repository exposes `findById(id)` with no
|
|
5763
|
+
* tenant to scope a cache key by, and the population is small enough that a read per call is
|
|
5764
|
+
* cheaper than a keyspace whose entries no flow invalidates.
|
|
5765
|
+
*
|
|
5766
|
+
* There is no email-verification arm: `emailVerification.required` gates tenant registration,
|
|
5767
|
+
* and a platform administrator is provisioned rather than self-registered.
|
|
5768
|
+
*
|
|
5769
|
+
* @param userId - The administrator's identifier, the token's `sub`.
|
|
5770
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` when no platform repository is registered
|
|
5771
|
+
* or no such administrator exists, or the matching `ACCOUNT_*` code when the status is
|
|
5772
|
+
* blocked.
|
|
5773
|
+
*/
|
|
5774
|
+
assertPlatformAccountUsable(userId: string): Promise<void>;
|
|
5775
|
+
}
|
|
5776
|
+
|
|
5432
5777
|
/**
|
|
5433
5778
|
* Verifies that the authenticated user's account status is not blocked.
|
|
5434
5779
|
*
|
|
5435
|
-
*
|
|
5436
|
-
*
|
|
5437
|
-
*
|
|
5438
|
-
*
|
|
5439
|
-
*
|
|
5780
|
+
* The decision itself lives in {@link AccountStatusService}, which resolves the status through a
|
|
5781
|
+
* Redis cache and applies the two refusals — a blocked status, and an unverified address where
|
|
5782
|
+
* `emailVerification.required` makes verification a gate on API access. This guard is the HTTP
|
|
5783
|
+
* adapter over it: it names the account from `request.user` and translates the outcome into a
|
|
5784
|
+
* `canActivate` answer.
|
|
5785
|
+
*
|
|
5786
|
+
* Sharing that service with {@link AuthTokenVerifierService} is what keeps the cache key shape,
|
|
5787
|
+
* the miss path and the order of the two refusals identical between a guarded route and a
|
|
5788
|
+
* long-lived transport, which have to reach the same verdict about the same account.
|
|
5440
5789
|
*
|
|
5441
5790
|
* Status-specific errors allow the client to display the correct message:
|
|
5442
5791
|
* - `BANNED` → `ACCOUNT_BANNED` (403)
|
|
@@ -5444,15 +5793,6 @@ declare class TrustedOriginGuard implements CanActivate {
|
|
|
5444
5793
|
* - `SUSPENDED` → `ACCOUNT_SUSPENDED` (403)
|
|
5445
5794
|
* - `PENDING` → `PENDING_APPROVAL` (403)
|
|
5446
5795
|
*
|
|
5447
|
-
* When `emailVerification.required` is enabled (the default), this guard also
|
|
5448
|
-
* refuses an account whose email is not yet verified, with `EMAIL_NOT_VERIFIED`.
|
|
5449
|
-
* This is what makes verification a gate on API access and not only on `login`:
|
|
5450
|
-
* registration issues a session before verification, and without this check that
|
|
5451
|
-
* session would reach every route this guard protects for the access token's
|
|
5452
|
-
* lifetime. The verified flag is cached alongside the status under
|
|
5453
|
-
* `uev:{tenantId}:{userId}`, on the same miss and the same TTL, so the check costs no
|
|
5454
|
-
* extra round-trip.
|
|
5455
|
-
*
|
|
5456
5796
|
* Routes without an authenticated user (`request.user` absent) are passed
|
|
5457
5797
|
* through — this guard is designed to be composed after {@link JwtAuthGuard}.
|
|
5458
5798
|
*
|
|
@@ -5466,10 +5806,17 @@ declare class TrustedOriginGuard implements CanActivate {
|
|
|
5466
5806
|
* @layer Guard
|
|
5467
5807
|
*/
|
|
5468
5808
|
declare class UserStatusGuard implements CanActivate {
|
|
5469
|
-
private readonly
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5809
|
+
private readonly accountStatus;
|
|
5810
|
+
/**
|
|
5811
|
+
* @param accountStatus - The shared account lifecycle gate.
|
|
5812
|
+
*/
|
|
5813
|
+
constructor(accountStatus: AccountStatusService);
|
|
5814
|
+
/**
|
|
5815
|
+
* @param context - The Nest execution context; the request must already carry `user`.
|
|
5816
|
+
* @returns `true` when the account is usable, or when no user is populated.
|
|
5817
|
+
* @throws {@link AuthException} with the matching `ACCOUNT_*` code, `EMAIL_NOT_VERIFIED`, or
|
|
5818
|
+
* `TOKEN_INVALID` when the account no longer exists.
|
|
5819
|
+
*/
|
|
5473
5820
|
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
5474
5821
|
}
|
|
5475
5822
|
|
|
@@ -5494,30 +5841,68 @@ declare class WsTicketService {
|
|
|
5494
5841
|
private readonly redis;
|
|
5495
5842
|
private readonly options;
|
|
5496
5843
|
private readonly userRepo;
|
|
5844
|
+
private readonly revocation;
|
|
5497
5845
|
private readonly logger;
|
|
5498
|
-
constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository);
|
|
5846
|
+
constructor(redis: AuthRedisService, options: ResolvedOptions, userRepo: IUserRepository, revocation: AuthRevocationService);
|
|
5499
5847
|
/**
|
|
5500
5848
|
* Mints a ticket from an already-verified access-token payload.
|
|
5501
5849
|
*
|
|
5502
5850
|
* The caller is responsible for having run the authentication, status and MFA guards — the
|
|
5503
5851
|
* payload reaching here is what those guards admitted. Nothing from the token itself is
|
|
5504
|
-
* copied into the ticket beyond the identity it proved
|
|
5505
|
-
* could be replayed against the REST
|
|
5852
|
+
* copied into the ticket beyond the identity it proved and the two keys its revocation is read
|
|
5853
|
+
* by (`jti`, `epoch`): no expiry, no signature, nothing that could be replayed against the REST
|
|
5854
|
+
* surface.
|
|
5855
|
+
*
|
|
5856
|
+
* A ticket expires no later than the access token that minted it. A logout blacklists the
|
|
5857
|
+
* token's `jti` only for the token's remaining life, so a ticket given longer than that would
|
|
5858
|
+
* outlive the entry that refuses it and redeem after its session ended. The lifetime is
|
|
5859
|
+
* therefore the smaller of {@link WS_TICKET_TTL_SECONDS} and the token's remaining seconds less
|
|
5860
|
+
* a one-second margin, and a token with none left mints nothing.
|
|
5506
5861
|
*
|
|
5507
5862
|
* @param payload - The verified dashboard access-token payload.
|
|
5508
|
-
* @returns The raw ticket and how long it is valid for.
|
|
5863
|
+
* @returns The raw ticket and how long it is valid for, in seconds.
|
|
5864
|
+
* @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
|
|
5509
5865
|
*/
|
|
5510
5866
|
issue(payload: DashboardJwtPayload): Promise<{
|
|
5511
5867
|
ticket: string;
|
|
5512
5868
|
expiresIn: number;
|
|
5513
5869
|
}>;
|
|
5870
|
+
/**
|
|
5871
|
+
* Refuses a token whose session has not satisfied the second factor it is enrolled in.
|
|
5872
|
+
*
|
|
5873
|
+
* Applied here rather than through `MfaRequiredGuard`: that guard is only registered when MFA is
|
|
5874
|
+
* configured, and this endpoint has to work on deployments without it. The rule itself is the
|
|
5875
|
+
* guard's, unchanged.
|
|
5876
|
+
*
|
|
5877
|
+
* @param payload - The verified access-token payload.
|
|
5878
|
+
* @throws {@link AuthException} `auth.token_invalid` for a malformed `mfaEnabled`, and
|
|
5879
|
+
* `auth.mfa_required` for an enrolled session that has not cleared its challenge.
|
|
5880
|
+
*/
|
|
5881
|
+
private assertSecondFactor;
|
|
5882
|
+
/**
|
|
5883
|
+
* The seconds a ticket minted now may live: the smaller of {@link WS_TICKET_TTL_SECONDS} and what
|
|
5884
|
+
* the access token has left.
|
|
5885
|
+
*
|
|
5886
|
+
* Kept short of the token's expiry on purpose. `ceil` on the clock leaves between 0 and 1 second
|
|
5887
|
+
* of slack, and one further second is held back, so the ticket still ends no later than the
|
|
5888
|
+
* token when the write reaches Redis up to a second after this reading, at every sub-second
|
|
5889
|
+
* offset. An absent or non-numeric `exp` is NaN here and fails the comparison, which refuses
|
|
5890
|
+
* rather than mints.
|
|
5891
|
+
*
|
|
5892
|
+
* @param payload - The verified access-token payload the ticket is minted from.
|
|
5893
|
+
* @returns A positive whole number of seconds.
|
|
5894
|
+
* @throws {@link AuthException} `auth.token_invalid` when the token has no life left.
|
|
5895
|
+
*/
|
|
5896
|
+
private lifetimeFor;
|
|
5514
5897
|
/**
|
|
5515
5898
|
* Redeems a ticket at the handshake, consuming it.
|
|
5516
5899
|
*
|
|
5517
5900
|
* @param ticket - The raw ticket from the upgrade request.
|
|
5518
5901
|
* @returns The identity the socket is authorized as.
|
|
5519
|
-
* @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired
|
|
5520
|
-
* already redeemed
|
|
5902
|
+
* @throws {@link AuthException} `auth.token_invalid` when the ticket is unknown, expired,
|
|
5903
|
+
* already redeemed, or minted by a session that has since been revoked — a logout or a bulk
|
|
5904
|
+
* revocation between the mint and the upgrade. These are deliberately indistinguishable to the
|
|
5905
|
+
* caller.
|
|
5521
5906
|
*/
|
|
5522
5907
|
redeem(ticket: string): Promise<WsTicketSnapshot>;
|
|
5523
5908
|
}
|
|
@@ -7391,6 +7776,15 @@ declare class TokenManagerService {
|
|
|
7391
7776
|
* or missing required `userId` / `role` fields.
|
|
7392
7777
|
*/
|
|
7393
7778
|
private parseSession;
|
|
7779
|
+
/**
|
|
7780
|
+
* Completes a validated session record with its optional fields, each read strictly.
|
|
7781
|
+
*
|
|
7782
|
+
* @param parsed - The stored record, already shape-checked by {@link parseSession}.
|
|
7783
|
+
* @param rec - The same record as untyped keys, for the strict reads.
|
|
7784
|
+
* @param mfaEnabled - The validated required flag.
|
|
7785
|
+
* @returns The record with `familyId`, `familyCreatedAt` and `mfaVerified` normalized.
|
|
7786
|
+
*/
|
|
7787
|
+
private withOptionalFields;
|
|
7394
7788
|
/**
|
|
7395
7789
|
* Serializes a session record for storage, omitting an empty `familyId`.
|
|
7396
7790
|
*
|
|
@@ -7412,6 +7806,8 @@ declare class TokenManagerService {
|
|
|
7412
7806
|
* @param device - Human-readable device description (parsed from User-Agent).
|
|
7413
7807
|
* @param mfaEnabled - Whether MFA is enabled on the account at session creation time.
|
|
7414
7808
|
* @param familyId - Login lineage this session belongs to; `''` when it belongs to none.
|
|
7809
|
+
* @param familyCreatedAt - Birth of the lineage, carried unchanged through every rotation.
|
|
7810
|
+
* @param mfaVerified - Whether the session was established by completing the MFA challenge.
|
|
7415
7811
|
*/
|
|
7416
7812
|
private buildSession;
|
|
7417
7813
|
/**
|
|
@@ -7437,10 +7833,11 @@ declare class TokenManagerService {
|
|
|
7437
7833
|
* unexpired token. The claim cannot be authoritative, so it is not made to look like it — and
|
|
7438
7834
|
* the empty string is the one state that cannot be mistaken for an answer.
|
|
7439
7835
|
*
|
|
7440
|
-
* `mfaVerified` is
|
|
7441
|
-
*
|
|
7442
|
-
*
|
|
7443
|
-
*
|
|
7836
|
+
* `mfaVerified` is the stored session's: `true` only when the session was established by
|
|
7837
|
+
* completing the MFA challenge, and `false` for a record without the field. Rotation copies it
|
|
7838
|
+
* forward, because the library offers no route that lets an authenticated session re-acquire
|
|
7839
|
+
* the claim, so dropping it would lock every MFA user out of the routes behind
|
|
7840
|
+
* `MfaRequiredGuard` each time the access token ages out.
|
|
7444
7841
|
*/
|
|
7445
7842
|
private buildRotatedResult;
|
|
7446
7843
|
/**
|
|
@@ -7477,8 +7874,7 @@ declare class TokenManagerService {
|
|
|
7477
7874
|
* Issues a platform access token and assembles a {@link RotatedTokenResult} from a session record.
|
|
7478
7875
|
*
|
|
7479
7876
|
* @remarks
|
|
7480
|
-
* `mfaVerified` is
|
|
7481
|
-
* Platform admins must re-complete the MFA challenge flow to re-acquire a verified token.
|
|
7877
|
+
* `mfaVerified` is the stored session's, as in {@link buildRotatedResult}.
|
|
7482
7878
|
*/
|
|
7483
7879
|
private buildPlatformRotatedResult;
|
|
7484
7880
|
/**
|
|
@@ -7641,7 +8037,26 @@ declare class AuthService {
|
|
|
7641
8037
|
private readonly redis;
|
|
7642
8038
|
private readonly otpService;
|
|
7643
8039
|
private readonly sessionService;
|
|
8040
|
+
private readonly accountStatus;
|
|
7644
8041
|
private readonly logger;
|
|
8042
|
+
/**
|
|
8043
|
+
* Drops an account's cached status facts after a change this service just committed.
|
|
8044
|
+
*
|
|
8045
|
+
* Delegated rather than deleting a key built here: the key format belongs to the service that
|
|
8046
|
+
* writes it, and a second statement of it drifts out of agreement silently — the delete stops
|
|
8047
|
+
* matching and the stale entry survives to its TTL, with nothing failing.
|
|
8048
|
+
*
|
|
8049
|
+
* **Best effort, deliberately.** Callers reach this after the irreversible part of their flow is
|
|
8050
|
+
* committed, so a thrown error would report failure for work that succeeded — and where the flow
|
|
8051
|
+
* consumed a single-use credential there is nothing left to retry. The worst a missed
|
|
8052
|
+
* invalidation costs is the staleness the call exists to avoid, bounded by the cache TTL, which
|
|
8053
|
+
* is strictly better than an unretryable failure. Logged rather than swallowed, so a Redis
|
|
8054
|
+
* problem is visible as itself instead of only as accounts briefly refused.
|
|
8055
|
+
*
|
|
8056
|
+
* @param userId - The account whose cached facts are now stale.
|
|
8057
|
+
* @param tenantId - Its tenant; a repository id is unique only within one.
|
|
8058
|
+
*/
|
|
8059
|
+
private dropCachedAccountFacts;
|
|
7645
8060
|
/**
|
|
7646
8061
|
* Whether the tenant-mismatch misconfiguration has already been reported.
|
|
7647
8062
|
*
|
|
@@ -7652,7 +8067,7 @@ declare class AuthService {
|
|
|
7652
8067
|
* be indistinguishable from the other two. Once is enough to make the defect visible.
|
|
7653
8068
|
*/
|
|
7654
8069
|
private warnedTenantMismatch;
|
|
7655
|
-
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService);
|
|
8070
|
+
constructor(options: ResolvedOptions, userRepo: IUserRepository, emailProvider: IEmailProvider | null, hooks: IAuthHooks | null, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, otpService: OtpService, sessionService: SessionService, accountStatus: AccountStatusService);
|
|
7656
8071
|
/**
|
|
7657
8072
|
* Re-derive a proven password at the current parameters and store it.
|
|
7658
8073
|
*
|
|
@@ -7740,6 +8155,30 @@ declare class AuthService {
|
|
|
7740
8155
|
* matched the presented refresh token (already logged out, or expired).
|
|
7741
8156
|
*/
|
|
7742
8157
|
logout(accessToken: string, rawRefreshToken: string): Promise<string>;
|
|
8158
|
+
/**
|
|
8159
|
+
* Announces a completed logout, the only hook `AuthService.logout` emits.
|
|
8160
|
+
*
|
|
8161
|
+
* Owns three concerns the session-revocation flow does not need: whether a hook is registered,
|
|
8162
|
+
* the fire-and-forget discipline, and the rejection log. It mirrors
|
|
8163
|
+
* `PlatformAuthService.emitPlatformLogout` and `TokenManagerService.emitReuseDetected`, which
|
|
8164
|
+
* carry the same three.
|
|
8165
|
+
*
|
|
8166
|
+
* The context names the account, because `logout` knows it — `readSessionOwner` returns both
|
|
8167
|
+
* fields and the session revoke is keyed on them. A consumer disconnecting live sockets must
|
|
8168
|
+
* match the tenant as well as the id, since a repository id is unique only within a tenant, so a
|
|
8169
|
+
* hook naming only the id cannot be acted on safely: acting on it would reach another tenant's
|
|
8170
|
+
* account.
|
|
8171
|
+
*
|
|
8172
|
+
* `ip` and `userAgent` stay empty because `logout` receives two tokens and no request, and an
|
|
8173
|
+
* invented value would be worse than an empty string a consumer can see is empty. `tenantId` is
|
|
8174
|
+
* omitted rather than set to `undefined` when the session record carries none, so its absence
|
|
8175
|
+
* reads as "the record did not say" rather than as a tenant literally named `undefined`.
|
|
8176
|
+
*
|
|
8177
|
+
* @param userId - The account that signed out; empty when the record named no owner, in which
|
|
8178
|
+
* case there is nobody to announce and nothing fires.
|
|
8179
|
+
* @param tenantId - The tenant from the session record, absent on a record that carries none.
|
|
8180
|
+
*/
|
|
8181
|
+
private emitLogout;
|
|
7743
8182
|
/**
|
|
7744
8183
|
* Rotates a dashboard refresh token.
|
|
7745
8184
|
*
|
|
@@ -7985,6 +8424,19 @@ declare class AuthService {
|
|
|
7985
8424
|
* would sit locked with nothing having announced it.
|
|
7986
8425
|
*/
|
|
7987
8426
|
private recordLoginFailure;
|
|
8427
|
+
/**
|
|
8428
|
+
* Fires {@link IAuthHooks.onLockout} when the failure just recorded closed the window.
|
|
8429
|
+
*
|
|
8430
|
+
* The two reads here exist only to feed the hook, so a store that cannot answer them must cost
|
|
8431
|
+
* the event and nothing else: the caller still receives the refusal it would have had. The
|
|
8432
|
+
* pre-check and `recordFailure` are the opposite — counting is security state — and stay
|
|
8433
|
+
* fail-closed.
|
|
8434
|
+
*
|
|
8435
|
+
* An unreadable flag leaves the lock unknown, so the hook is skipped. An unreadable TTL after
|
|
8436
|
+
* the flag read `true` leaves it confirmed: the event is still owed, and the counter's own
|
|
8437
|
+
* lifetime, `windowSeconds`, is a truthful upper bound where `0` would read as "not locked".
|
|
8438
|
+
*/
|
|
8439
|
+
private fireLockoutIfCrossed;
|
|
7988
8440
|
/** Emits {@link IAuthHooks.onLoginFailed}, fire-and-forget. */
|
|
7989
8441
|
private emitLoginFailed;
|
|
7990
8442
|
/**
|
|
@@ -8729,6 +9181,29 @@ declare class MfaService {
|
|
|
8729
9181
|
private fetchUserForContext;
|
|
8730
9182
|
}
|
|
8731
9183
|
|
|
9184
|
+
/**
|
|
9185
|
+
* Manages tenant invitation flows — creating and accepting invitations.
|
|
9186
|
+
*
|
|
9187
|
+
* @remarks
|
|
9188
|
+
* Invitation tokens are generated with `generateSecureToken(32)` (64 hex chars),
|
|
9189
|
+
* stored in Redis under `inv:{sha256(token)}` with a configured TTL, and consumed
|
|
9190
|
+
* atomically (single-use) via `AuthRedisService.getdel()` when accepted. The raw
|
|
9191
|
+
* token is never persisted server-side — only the SHA-256 hash is kept as the key.
|
|
9192
|
+
*
|
|
9193
|
+
* Role authorization is validated in `invite()` using `hasRole()` from
|
|
9194
|
+
* `roles.util.ts` — the inviter cannot invite a role higher than their own.
|
|
9195
|
+
*
|
|
9196
|
+
* @example
|
|
9197
|
+
* ```typescript
|
|
9198
|
+
* // Inviting a new member (inviter must hold a role >= 'member')
|
|
9199
|
+
* await invitationService.invite(inviterUserId, 'new@example.com', 'member', tenantId)
|
|
9200
|
+
*
|
|
9201
|
+
* // Accepting an invitation
|
|
9202
|
+
* await invitationService.acceptInvitation(dto, ip, userAgent, headers)
|
|
9203
|
+
* ```
|
|
9204
|
+
*
|
|
9205
|
+
* @layer Service
|
|
9206
|
+
*/
|
|
8732
9207
|
declare class InvitationService {
|
|
8733
9208
|
private readonly userRepo;
|
|
8734
9209
|
private readonly emailProvider;
|
|
@@ -8762,30 +9237,6 @@ declare class InvitationService {
|
|
|
8762
9237
|
* @throws `AuthException` with `TOKEN_INVALID` when the inviter user is not found.
|
|
8763
9238
|
*/
|
|
8764
9239
|
invite(inviterUserId: string, email: string, role: string, tenantId: string, tenantName?: string): Promise<void>;
|
|
8765
|
-
/**
|
|
8766
|
-
* Accepts a pending invitation and creates the new user account.
|
|
8767
|
-
*
|
|
8768
|
-
* Steps:
|
|
8769
|
-
* 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
|
|
8770
|
-
* Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
|
|
8771
|
-
* race conditions where two concurrent requests both read a valid token before
|
|
8772
|
-
* either deletes it.
|
|
8773
|
-
* 2. Validates and parses the stored JSON — rejects malformed payloads.
|
|
8774
|
-
* 3. Re-validates the stored `role` against the configured hierarchy to prevent
|
|
8775
|
-
* privilege escalation from a tampered Redis value.
|
|
8776
|
-
* 4. Verifies the invitee email is not already registered in the tenant.
|
|
8777
|
-
* 5. Hashes `dto.password` via `PasswordService`.
|
|
8778
|
-
* 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
|
|
8779
|
-
* 7. Issues dashboard tokens.
|
|
8780
|
-
* 8. Calls `hooks.afterInvitationAccepted` if implemented.
|
|
8781
|
-
*
|
|
8782
|
-
* @param dto - Validated AcceptInvitationDto from the request body.
|
|
8783
|
-
* @param ip - Client IP address (for session audit and hooks).
|
|
8784
|
-
* @param userAgent - User-Agent string (for session audit and hooks).
|
|
8785
|
-
* @returns Full `AuthResult` with access + refresh tokens and the new user record.
|
|
8786
|
-
* @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
|
|
8787
|
-
* @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
|
|
8788
|
-
*/
|
|
8789
9240
|
/**
|
|
8790
9241
|
* Whether an account's status still permits it to act.
|
|
8791
9242
|
*
|
|
@@ -8945,6 +9396,30 @@ declare class InvitationService {
|
|
|
8945
9396
|
* grant what the invitation grants.
|
|
8946
9397
|
*/
|
|
8947
9398
|
private assertInviterStillAuthorised;
|
|
9399
|
+
/**
|
|
9400
|
+
* Accepts a pending invitation and creates the new user account.
|
|
9401
|
+
*
|
|
9402
|
+
* Steps:
|
|
9403
|
+
* 1. Atomically reads and deletes `inv:{sha256(dto.token)}` via `getdel()`.
|
|
9404
|
+
* Missing key → `INVALID_INVITATION_TOKEN`. The atomic consumption prevents
|
|
9405
|
+
* race conditions where two concurrent requests both read a valid token before
|
|
9406
|
+
* either deletes it.
|
|
9407
|
+
* 2. Validates and parses the stored JSON — rejects malformed payloads.
|
|
9408
|
+
* 3. Re-validates the stored `role` against the configured hierarchy to prevent
|
|
9409
|
+
* privilege escalation from a tampered Redis value.
|
|
9410
|
+
* 4. Verifies the invitee email is not already registered in the tenant.
|
|
9411
|
+
* 5. Hashes `dto.password` via `PasswordService`.
|
|
9412
|
+
* 6. Creates the user with `emailVerified: true` (invitation implies email ownership).
|
|
9413
|
+
* 7. Issues dashboard tokens.
|
|
9414
|
+
* 8. Calls `hooks.afterInvitationAccepted` if implemented.
|
|
9415
|
+
*
|
|
9416
|
+
* @param dto - Validated AcceptInvitationDto from the request body.
|
|
9417
|
+
* @param ip - Client IP address (for session audit and hooks).
|
|
9418
|
+
* @param userAgent - User-Agent string (for session audit and hooks).
|
|
9419
|
+
* @returns Full `AuthResult` with access + refresh tokens and the new user record.
|
|
9420
|
+
* @throws `AuthException` with `INVALID_INVITATION_TOKEN` if the token is missing or malformed.
|
|
9421
|
+
* @throws `AuthException` with `EMAIL_ALREADY_EXISTS` if the email is taken.
|
|
9422
|
+
*/
|
|
8948
9423
|
acceptInvitation(dto: AcceptInvitationDto, ip: string, userAgent: string, headers: Record<string, string | string[] | undefined>): Promise<AuthResult>;
|
|
8949
9424
|
}
|
|
8950
9425
|
|
|
@@ -9225,8 +9700,9 @@ declare class PlatformAuthService {
|
|
|
9225
9700
|
private readonly bruteForce;
|
|
9226
9701
|
private readonly redis;
|
|
9227
9702
|
private readonly options;
|
|
9703
|
+
private readonly hooks;
|
|
9228
9704
|
private readonly logger;
|
|
9229
|
-
constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions);
|
|
9705
|
+
constructor(platformUserRepo: IPlatformUserRepository, passwordService: PasswordService, tokenManager: TokenManagerService, bruteForce: BruteForceService, redis: AuthRedisService, options: ResolvedOptions, hooks?: IAuthHooks | null);
|
|
9230
9706
|
/**
|
|
9231
9707
|
* Authenticates a platform administrator with email and password.
|
|
9232
9708
|
*
|
|
@@ -9253,6 +9729,23 @@ declare class PlatformAuthService {
|
|
|
9253
9729
|
* @param rawRefreshToken - The raw opaque platform refresh token.
|
|
9254
9730
|
*/
|
|
9255
9731
|
logout(accessToken: string, rawRefreshToken: string): Promise<string>;
|
|
9732
|
+
/**
|
|
9733
|
+
* Announces a completed platform logout, the only hook `PlatformAuthService` emits.
|
|
9734
|
+
*
|
|
9735
|
+
* Owns three concerns a reader of `logout` does not need: whether a hook is registered, the
|
|
9736
|
+
* fire-and-forget discipline, and the rejection log. It mirrors `TokenManagerService`'s
|
|
9737
|
+
* `emitReuseDetected`, which carries the same three for the same reason.
|
|
9738
|
+
*
|
|
9739
|
+
* The event is its own hook rather than a share of `afterLogout`, because a consumer's dashboard
|
|
9740
|
+
* handler may resolve a tenant and a platform administrator has none. Fire-and-forget: a hook
|
|
9741
|
+
* that throws must not turn a completed logout into a failed one, so the rejection is logged
|
|
9742
|
+
* rather than propagated — and logged rather than swallowed, so a broken consumer hook stays
|
|
9743
|
+
* visible.
|
|
9744
|
+
*
|
|
9745
|
+
* @param userId - The administrator who signed out; empty when the record named no owner, in
|
|
9746
|
+
* which case there is nobody to announce and nothing fires.
|
|
9747
|
+
*/
|
|
9748
|
+
private emitPlatformLogout;
|
|
9256
9749
|
/**
|
|
9257
9750
|
* Rotates a platform administrator's refresh token.
|
|
9258
9751
|
*
|
|
@@ -9314,6 +9807,266 @@ declare class PlatformAuthService {
|
|
|
9314
9807
|
revokeAllPlatformSessions(userId: string): Promise<void>;
|
|
9315
9808
|
}
|
|
9316
9809
|
|
|
9810
|
+
/**
|
|
9811
|
+
* @fileoverview The request a `tenantIdResolver` sees when the caller arrived by WebSocket upgrade.
|
|
9812
|
+
*
|
|
9813
|
+
* @layer Utility
|
|
9814
|
+
*/
|
|
9815
|
+
|
|
9816
|
+
/**
|
|
9817
|
+
* The fields {@link handshakeRequest} reads. A Socket.IO `handshake` fits, and so does an Express
|
|
9818
|
+
* request.
|
|
9819
|
+
*/
|
|
9820
|
+
interface HandshakeLike {
|
|
9821
|
+
headers: Record<string, string | string[] | undefined>;
|
|
9822
|
+
url?: string;
|
|
9823
|
+
}
|
|
9824
|
+
|
|
9825
|
+
/**
|
|
9826
|
+
* @fileoverview The whole identity chain for an access token, in one call.
|
|
9827
|
+
*
|
|
9828
|
+
* @layer Service
|
|
9829
|
+
*/
|
|
9830
|
+
|
|
9831
|
+
/**
|
|
9832
|
+
* Which identity plane a caller expects a token to belong to.
|
|
9833
|
+
*
|
|
9834
|
+
* Always supplied by the caller and never inferred from the token's own `type` claim: inferring
|
|
9835
|
+
* would make the plane attacker-chosen, so a platform token would open a dashboard stream simply
|
|
9836
|
+
* by saying it is one.
|
|
9837
|
+
*/
|
|
9838
|
+
type AuthPlane = 'dashboard' | 'platform';
|
|
9839
|
+
/**
|
|
9840
|
+
* The outcome of a successful verification, discriminated by the plane so a caller can narrow to
|
|
9841
|
+
* the payload it actually got.
|
|
9842
|
+
*
|
|
9843
|
+
* `plane` is the same value the caller asked for — it is on the result because a consumer keying
|
|
9844
|
+
* live connections needs to record it, and because a tenant cannot answer the question: a platform
|
|
9845
|
+
* token carries no tenant claim at all.
|
|
9846
|
+
*/
|
|
9847
|
+
type VerifiedAccessToken = {
|
|
9848
|
+
readonly plane: 'dashboard';
|
|
9849
|
+
readonly payload: DashboardJwtPayload;
|
|
9850
|
+
} | {
|
|
9851
|
+
readonly plane: 'platform';
|
|
9852
|
+
readonly payload: PlatformJwtPayload;
|
|
9853
|
+
};
|
|
9854
|
+
/**
|
|
9855
|
+
* What a verification checks beyond the signature.
|
|
9856
|
+
*
|
|
9857
|
+
* Both flags default to `true`. They exist to be turned OFF deliberately, by a caller that has
|
|
9858
|
+
* already established the same fact by another route — never as a way to make a reconnect cheaper.
|
|
9859
|
+
*/
|
|
9860
|
+
interface VerifyAccessTokenOptions {
|
|
9861
|
+
/** The plane the caller expects. Required; see {@link AuthPlane}. */
|
|
9862
|
+
readonly plane: AuthPlane;
|
|
9863
|
+
/**
|
|
9864
|
+
* Refuse a token whose account has MFA enabled but which was not itself issued after a
|
|
9865
|
+
* successful challenge — the rule {@link MfaRequiredGuard} applies to an HTTP route.
|
|
9866
|
+
*
|
|
9867
|
+
* It matters most on a reconnect: a refresh carries `mfaVerified` forward only from a session
|
|
9868
|
+
* that completed the challenge, so a token that is otherwise entirely valid can still represent
|
|
9869
|
+
* a session that never did. The token's `type` does not imply it.
|
|
9870
|
+
*
|
|
9871
|
+
* @defaultValue true
|
|
9872
|
+
*/
|
|
9873
|
+
readonly requireMfa?: boolean;
|
|
9874
|
+
/**
|
|
9875
|
+
* Re-resolve the account's lifecycle status instead of trusting the snapshot the token carries,
|
|
9876
|
+
* refusing a blocked, deleted or — on the dashboard plane, where verification gates API
|
|
9877
|
+
* access — unverified account.
|
|
9878
|
+
*
|
|
9879
|
+
* The only check that can answer differently between two calls: a suspension lands between two
|
|
9880
|
+
* reconnects, and nothing in the token would say so.
|
|
9881
|
+
*
|
|
9882
|
+
* **Its freshness on the dashboard plane is bounded by `userStatusCacheTtlSeconds`, not by how
|
|
9883
|
+
* often you call.** That plane reads the `us:`/`uev:` cache, so a stream re-verifying every five
|
|
9884
|
+
* seconds still serves a banned account until the entry expires (default 60 s) — a tighter
|
|
9885
|
+
* cadence does not shorten that. What does is
|
|
9886
|
+
* {@link AccountStatusService.invalidate}: call it wherever you change an account's status, and
|
|
9887
|
+
* read what that method does **not** promise — a request already resolving when you invalidate
|
|
9888
|
+
* can write the old value back, so the window narrows to one repository read rather than to
|
|
9889
|
+
* zero. Failing that, lower the TTL. The platform plane is uncached and therefore genuinely
|
|
9890
|
+
* current, at the cost of a repository read per call.
|
|
9891
|
+
*
|
|
9892
|
+
* @defaultValue true
|
|
9893
|
+
*/
|
|
9894
|
+
readonly checkStatus?: boolean;
|
|
9895
|
+
/**
|
|
9896
|
+
* The request the credential arrived on — a Socket.IO `handshake`, an Express request, or any
|
|
9897
|
+
* object with `headers` and `url` — so `enforceTenantBinding` can be applied.
|
|
9898
|
+
*
|
|
9899
|
+
* The binding needs the request the host's `tenantIdResolver` reads, which a token alone does
|
|
9900
|
+
* not carry. With `enforceTenantBinding` on and a request passed, the resolver runs on the
|
|
9901
|
+
* dashboard plane exactly as it does in `WsJwtGuard`: it receives an object with only `headers`
|
|
9902
|
+
* (lowercased), `url` and `hostname` (the `Host` header, port cut) — no `cookies`, `ip`, `ips`
|
|
9903
|
+
* or trust-proxy behaviour — and a resolver that throws on that, or answers another tenant,
|
|
9904
|
+
* refuses the token with `TOKEN_INVALID`. The platform plane has no tenant and ignores it.
|
|
9905
|
+
*
|
|
9906
|
+
* **Omit it and the binding is not applied for that call.** With `enforceTenantBinding` on,
|
|
9907
|
+
* that is logged once per service instance, because a caller that never passes it has a
|
|
9908
|
+
* binding the HTTP guards enforce and this surface does not.
|
|
9909
|
+
*/
|
|
9910
|
+
readonly request?: HandshakeLike;
|
|
9911
|
+
}
|
|
9912
|
+
/**
|
|
9913
|
+
* Performs, in one call, every identity check a guarded HTTP route performs before a handler runs.
|
|
9914
|
+
*
|
|
9915
|
+
* A long-lived transport — a WebSocket, an SSE stream, a message consumer — has no guard in front
|
|
9916
|
+
* of it, so it has to establish the same facts itself, on a cadence, for as long as the connection
|
|
9917
|
+
* lives. Assembling that from the parts is where it goes wrong: {@link AuthRevocationService}
|
|
9918
|
+
* answers two channels and nothing else, and a bridge that calls it alone has verified a signature
|
|
9919
|
+
* and consulted a blacklist while checking neither the token's type, nor its `exp`, nor whether the
|
|
9920
|
+
* account behind it still exists.
|
|
9921
|
+
*
|
|
9922
|
+
* What one call establishes, in the order the refusals fire:
|
|
9923
|
+
*
|
|
9924
|
+
* 1. **Signature**, under the pinned algorithm and any secret retired by a rotation, plus the
|
|
9925
|
+
* configured `issuer` and `audience` — all of `verifyWithRotation`.
|
|
9926
|
+
* 2. **Expiry.** `exp` is enforced by the same verification. It is worth naming separately because
|
|
9927
|
+
* {@link AuthRevocationService.isAccessTokenRevoked} never reads it: a revocation check answers
|
|
9928
|
+
* "was this withdrawn", not "is this still current".
|
|
9929
|
+
* 3. **Claim shape** — `jti` a UUID v4, `sub` and (on the dashboard plane) `tenantId` bounded
|
|
9930
|
+
* non-empty strings. These become Redis keys downstream; a malformed one builds a key nobody
|
|
9931
|
+
* intended.
|
|
9932
|
+
* 4. **Token type**, matched against the plane the caller named. Without it an `mfa_challenge`
|
|
9933
|
+
* token — signed with the same secret, holding half a credential — reads as a valid session.
|
|
9934
|
+
* 5. **Revocation**, both channels: the per-token blacklist a logout writes and the per-user epoch
|
|
9935
|
+
* a password reset or an administrative revoke-all advances.
|
|
9936
|
+
* 6. **Account status**, unless the caller opted out. See
|
|
9937
|
+
* {@link VerifyAccessTokenOptions.checkStatus}.
|
|
9938
|
+
* 7. **MFA policy**, unless the caller opted out. See {@link VerifyAccessTokenOptions.requireMfa}.
|
|
9939
|
+
* Its claim-shape refusal (`mfaEnabled` missing or not a boolean, answered `TOKEN_INVALID`)
|
|
9940
|
+
* belongs to the token checks and fires before step 6; only the `MFA_REQUIRED` decision follows it.
|
|
9941
|
+
*
|
|
9942
|
+
* **Account status precedes the MFA policy.** A blocked account is refused with its own code even
|
|
9943
|
+
* while a challenge is pending, which is the answer a route guarded by `UserStatusGuard` ahead of
|
|
9944
|
+
* `MfaRequiredGuard` gives; a pending challenge is something the caller can act on only when the
|
|
9945
|
+
* account is usable, and the definitive refusal is the one it must see first.
|
|
9946
|
+
*
|
|
9947
|
+
* **What it still does not do, and cannot.** Route authorization is the consumer's — this answers
|
|
9948
|
+
* who the caller is, never what they may do, so a `@Roles()` equivalent stays yours to apply on
|
|
9949
|
+
* every message a stream carries, not only at the handshake. Tenant binding
|
|
9950
|
+
* (`enforceTenantBinding`) needs the request the resolver reads, which a token does not carry:
|
|
9951
|
+
* 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
|
|
9952
|
+
* that calls it once at connect is authorized for the lifetime of the token, not of the session.
|
|
9953
|
+
* Call it again on a cadence, and treat a rejection as a disconnect.
|
|
9954
|
+
*
|
|
9955
|
+
* @example
|
|
9956
|
+
* ```ts
|
|
9957
|
+
* const { plane, payload } = await this.verifier.verifyAccessToken(token, { plane: 'dashboard' })
|
|
9958
|
+
* registry.add(socket, { plane, userId: payload.sub, tenantId: payload.tenantId })
|
|
9959
|
+
* ```
|
|
9960
|
+
*
|
|
9961
|
+
* @layer Service
|
|
9962
|
+
*/
|
|
9963
|
+
declare class AuthTokenVerifierService {
|
|
9964
|
+
private readonly jwtService;
|
|
9965
|
+
private readonly options;
|
|
9966
|
+
private readonly revocation;
|
|
9967
|
+
private readonly accountStatus;
|
|
9968
|
+
private readonly logger;
|
|
9969
|
+
/** Whether the "binding not applied" warning has been logged by this instance. */
|
|
9970
|
+
private warnedUnbound;
|
|
9971
|
+
/**
|
|
9972
|
+
* @param jwtService - The Nest JWT service, configured with the current signing secret.
|
|
9973
|
+
* @param options - Resolved module options, for the algorithm, the binding claims and the
|
|
9974
|
+
* secrets retired by a rotation.
|
|
9975
|
+
* @param revocation - The two revocation channels, shared with the mounted guards.
|
|
9976
|
+
* @param accountStatus - The account lifecycle gate, shared with {@link UserStatusGuard}.
|
|
9977
|
+
*/
|
|
9978
|
+
constructor(jwtService: JwtService, options: ResolvedOptions, revocation: AuthRevocationService, accountStatus: AccountStatusService);
|
|
9979
|
+
/**
|
|
9980
|
+
* Verifies an access token and returns its payload, or throws.
|
|
9981
|
+
*
|
|
9982
|
+
* Every refusal is an {@link AuthException}, and each mirrors the code the equivalent guard
|
|
9983
|
+
* already answers, so a consumer moving a surface onto this service keeps branching on what it
|
|
9984
|
+
* branched on before.
|
|
9985
|
+
*
|
|
9986
|
+
* Most token-shaped failures answer `TOKEN_INVALID` without naming which check refused: telling
|
|
9987
|
+
* "valid but revoked" apart from "never valid" is an oracle for no benefit. Three name
|
|
9988
|
+
* themselves, because a legitimate client acts on each differently — `MFA_REQUIRED` means
|
|
9989
|
+
* complete the challenge, the `ACCOUNT_*` codes mean the account itself is refused, and
|
|
9990
|
+
* `PLATFORM_AUTH_REQUIRED` means a token for the other context was presented. That last one is
|
|
9991
|
+
* the platform plane only, and it is what {@link JwtPlatformGuard} answers there; the dashboard
|
|
9992
|
+
* plane collapses a wrong type into `TOKEN_INVALID`, as {@link JwtAuthGuard} does.
|
|
9993
|
+
*
|
|
9994
|
+
* @param token - The compact JWT, exactly as presented. Never a decoded payload: a caller that
|
|
9995
|
+
* already decoded it has skipped the signature, which is the check everything else rests on.
|
|
9996
|
+
* @param options - The plane, and which of the two optional checks to run.
|
|
9997
|
+
* @returns The verified payload, tagged with the plane it was checked against.
|
|
9998
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` when the signature, expiry, claim shape,
|
|
9999
|
+
* dashboard token type or revocation state refuses the token; `PLATFORM_AUTH_REQUIRED` when a
|
|
10000
|
+
* non-platform token is presented on the platform plane; the matching `ACCOUNT_*` /
|
|
10001
|
+
* `EMAIL_NOT_VERIFIED` code when the account is no longer usable, whether or not a challenge is
|
|
10002
|
+
* pending; or `MFA_REQUIRED` when the account is usable, has MFA enabled and this token
|
|
10003
|
+
* predates its challenge.
|
|
10004
|
+
* @throws {TypeError} When `options.plane` is neither `'dashboard'` nor `'platform'` — a caller
|
|
10005
|
+
* error rather than an authentication outcome, so it is deliberately not an `AuthException`.
|
|
10006
|
+
*/
|
|
10007
|
+
verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<VerifiedAccessToken>;
|
|
10008
|
+
/**
|
|
10009
|
+
* The dashboard arm: the full chain plus the tenant claim and the tenant-scoped status gate.
|
|
10010
|
+
*
|
|
10011
|
+
* @param token - The compact JWT.
|
|
10012
|
+
* @param requireMfa - Whether to apply the MFA policy.
|
|
10013
|
+
* @param checkStatus - Whether to consult the account's current status.
|
|
10014
|
+
* @param request - The request the token arrived on, for `enforceTenantBinding`.
|
|
10015
|
+
* @returns The verified dashboard payload.
|
|
10016
|
+
* @throws {@link AuthException} as {@link verifyAccessToken} documents.
|
|
10017
|
+
*/
|
|
10018
|
+
private verifyDashboard;
|
|
10019
|
+
/**
|
|
10020
|
+
* Applies `enforceTenantBinding` when a request was passed, and says so once when it could not.
|
|
10021
|
+
*
|
|
10022
|
+
* @param tenantId - The tenant the token was issued for.
|
|
10023
|
+
* @param request - The request the token arrived on, when the caller supplied one.
|
|
10024
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` as {@link assertTenantBinding} documents.
|
|
10025
|
+
*/
|
|
10026
|
+
private assertBound;
|
|
10027
|
+
/**
|
|
10028
|
+
* The platform arm. No tenant claim exists to assert or to scope by — a platform administrator
|
|
10029
|
+
* is cross-tenant, which is also why the revocation read is told which epoch namespace to use.
|
|
10030
|
+
*
|
|
10031
|
+
* @param token - The compact JWT.
|
|
10032
|
+
* @param requireMfa - Whether to apply the MFA policy.
|
|
10033
|
+
* @param checkStatus - Whether to consult the administrator's current status.
|
|
10034
|
+
* @returns The verified platform payload.
|
|
10035
|
+
* @throws {@link AuthException} as {@link verifyAccessToken} documents.
|
|
10036
|
+
*/
|
|
10037
|
+
private verifyPlatform;
|
|
10038
|
+
/**
|
|
10039
|
+
* Verifies signature, algorithm, binding claims and expiry, collapsing every failure to one
|
|
10040
|
+
* opaque refusal.
|
|
10041
|
+
*
|
|
10042
|
+
* @typeParam T - The payload shape the caller's plane expects.
|
|
10043
|
+
* @param token - The compact JWT.
|
|
10044
|
+
* @returns The decoded payload, cast to `T`. The claims are asserted by the caller.
|
|
10045
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` when no configured secret accepts it.
|
|
10046
|
+
*/
|
|
10047
|
+
private verifySignature;
|
|
10048
|
+
/**
|
|
10049
|
+
* Refuses a token whose `mfaEnabled` claim is missing or not a boolean.
|
|
10050
|
+
*
|
|
10051
|
+
* The `typeof` arm is not defensive noise: the payload is cast from a token, so a signed token
|
|
10052
|
+
* that simply omits `mfaEnabled` would otherwise compare `undefined === true`, read as "MFA is
|
|
10053
|
+
* off" and pass a gate it was never shown to. It is a claim-shape refusal, so it runs with the
|
|
10054
|
+
* other token checks and ahead of the account lookup.
|
|
10055
|
+
*
|
|
10056
|
+
* @param payload - The verified payload, either plane.
|
|
10057
|
+
* @throws {@link AuthException} with `TOKEN_INVALID` when the claim is missing or not a boolean.
|
|
10058
|
+
*/
|
|
10059
|
+
private assertMfaClaimShape;
|
|
10060
|
+
/**
|
|
10061
|
+
* Applies the MFA policy to a payload whose claim shape was already checked.
|
|
10062
|
+
*
|
|
10063
|
+
* @param payload - The verified payload, either plane.
|
|
10064
|
+
* @throws {@link AuthException} with `MFA_REQUIRED` when MFA is enabled and this token predates
|
|
10065
|
+
* the challenge.
|
|
10066
|
+
*/
|
|
10067
|
+
private assertMfaVerified;
|
|
10068
|
+
}
|
|
10069
|
+
|
|
9317
10070
|
/**
|
|
9318
10071
|
* @fileoverview OAuth 2.0 Authorization Code flow service for @bymax-one/nest-auth.
|
|
9319
10072
|
*
|
|
@@ -9665,4 +10418,425 @@ declare function AuthRateLimit(config: {
|
|
|
9665
10418
|
default: AuthRateLimitWindow;
|
|
9666
10419
|
}): MethodDecorator;
|
|
9667
10420
|
|
|
9668
|
-
|
|
10421
|
+
/**
|
|
10422
|
+
* @fileoverview Persistence contract and value types for scoped service API keys.
|
|
10423
|
+
*
|
|
10424
|
+
* The host implements {@link IApiKeyRepository} against its own store, as it does for users.
|
|
10425
|
+
* Nothing here is reversible: a row carries the HMAC digest of the secret and never the secret.
|
|
10426
|
+
*
|
|
10427
|
+
* @layer Interface
|
|
10428
|
+
*/
|
|
10429
|
+
/** One stored service key. */
|
|
10430
|
+
interface AuthApiKey {
|
|
10431
|
+
/** Row id, a lowercase UUID. It is the public half of the key a caller presents. */
|
|
10432
|
+
id: string;
|
|
10433
|
+
/**
|
|
10434
|
+
* Human name for the machine caller this key belongs to. NOT unique: several active keys may
|
|
10435
|
+
* share one label, which is what makes an overlapping rotation possible.
|
|
10436
|
+
*/
|
|
10437
|
+
label: string;
|
|
10438
|
+
/** Lowercase hex HMAC-SHA-256 of the secret under the pepper. 64 characters. */
|
|
10439
|
+
digest: string;
|
|
10440
|
+
/** Scopes this key holds. A route is admitted only when the key holds every scope it declares. */
|
|
10441
|
+
scopes: readonly string[];
|
|
10442
|
+
/** When the key was issued. */
|
|
10443
|
+
createdAt: Date;
|
|
10444
|
+
/** The key stops verifying at this instant, when set. */
|
|
10445
|
+
expiresAt: Date | null;
|
|
10446
|
+
/** When set, the key no longer verifies, on every instance, whatever instant it holds. */
|
|
10447
|
+
revokedAt: Date | null;
|
|
10448
|
+
/** Last time the key verified. Advisory and coalesced: see `apiKeys.lastUsedFlushSeconds`. */
|
|
10449
|
+
lastUsedAt: Date | null;
|
|
10450
|
+
}
|
|
10451
|
+
/** A stored key without its digest: what an operator-facing call may return or log. */
|
|
10452
|
+
type AuthApiKeySummary = Omit<AuthApiKey, 'digest'>;
|
|
10453
|
+
/** What the verified request carries as `request.apiKey`. */
|
|
10454
|
+
interface ApiKeyPrincipal {
|
|
10455
|
+
/** The key's row id: the stable handle to bucket a rate limit on after verification. */
|
|
10456
|
+
readonly id: string;
|
|
10457
|
+
/** The machine caller's label. */
|
|
10458
|
+
readonly label: string;
|
|
10459
|
+
/** The scopes the key holds. */
|
|
10460
|
+
readonly scopes: readonly string[];
|
|
10461
|
+
}
|
|
10462
|
+
/**
|
|
10463
|
+
* Persistence port for service API keys.
|
|
10464
|
+
*
|
|
10465
|
+
* @remarks
|
|
10466
|
+
* The library supplies `id` and `digest`; the store only persists them. Verification reads one
|
|
10467
|
+
* row per request, so `findById` should be a primary-key lookup.
|
|
10468
|
+
*/
|
|
10469
|
+
interface IApiKeyRepository {
|
|
10470
|
+
/**
|
|
10471
|
+
* Finds a key by its row id.
|
|
10472
|
+
*
|
|
10473
|
+
* @param id - The id embedded in the presented key.
|
|
10474
|
+
* @returns The row, or `null` when none exists. Revoked and expired rows are still returned:
|
|
10475
|
+
* the library decides validity, so every refusal takes the same steps.
|
|
10476
|
+
*/
|
|
10477
|
+
findById(id: string): Promise<AuthApiKey | null>;
|
|
10478
|
+
/**
|
|
10479
|
+
* Inserts a new key.
|
|
10480
|
+
*
|
|
10481
|
+
* @param row - The row to store. `id` is generated by the library.
|
|
10482
|
+
* @returns The stored row.
|
|
10483
|
+
*/
|
|
10484
|
+
create(row: {
|
|
10485
|
+
id: string;
|
|
10486
|
+
label: string;
|
|
10487
|
+
digest: string;
|
|
10488
|
+
scopes: readonly string[];
|
|
10489
|
+
createdAt: Date;
|
|
10490
|
+
expiresAt: Date | null;
|
|
10491
|
+
}): Promise<AuthApiKey>;
|
|
10492
|
+
/**
|
|
10493
|
+
* Marks a key revoked.
|
|
10494
|
+
*
|
|
10495
|
+
* @param id - The key to revoke.
|
|
10496
|
+
* @param at - The instant it stops verifying.
|
|
10497
|
+
* @returns `false` when no such key exists. Revoking an already revoked key is not an error.
|
|
10498
|
+
*/
|
|
10499
|
+
markRevoked(id: string, at: Date): Promise<boolean>;
|
|
10500
|
+
/**
|
|
10501
|
+
* Sets when a key stops verifying. Used by rotation to retire the old key after an overlap.
|
|
10502
|
+
*
|
|
10503
|
+
* @param id - The key to change.
|
|
10504
|
+
* @param at - The new expiry instant.
|
|
10505
|
+
* @returns `false` when no such key exists.
|
|
10506
|
+
*/
|
|
10507
|
+
setExpiry(id: string, at: Date): Promise<boolean>;
|
|
10508
|
+
/**
|
|
10509
|
+
* Records when keys were last used, in one batch.
|
|
10510
|
+
*
|
|
10511
|
+
* MUST be monotonic: never move `lastUsedAt` backwards (`GREATEST(last_used_at, :at)`, or a
|
|
10512
|
+
* `WHERE last_used_at < :at` guard). Several instances flush independently, and a late flush
|
|
10513
|
+
* from one must not overwrite a newer value written by another.
|
|
10514
|
+
*
|
|
10515
|
+
* @param entries - One entry per key, the most recent use seen by this process.
|
|
10516
|
+
*/
|
|
10517
|
+
touchLastUsed(entries: ReadonlyArray<{
|
|
10518
|
+
id: string;
|
|
10519
|
+
at: Date;
|
|
10520
|
+
}>): Promise<void>;
|
|
10521
|
+
/**
|
|
10522
|
+
* Lists every key that carries a label, active or not.
|
|
10523
|
+
*
|
|
10524
|
+
* @param label - The machine caller's label.
|
|
10525
|
+
*/
|
|
10526
|
+
listByLabel(label: string): Promise<AuthApiKey[]>;
|
|
10527
|
+
}
|
|
10528
|
+
|
|
10529
|
+
/**
|
|
10530
|
+
* @fileoverview The clock the service-key feature reads "now" from.
|
|
10531
|
+
*
|
|
10532
|
+
* @layer Service
|
|
10533
|
+
*/
|
|
10534
|
+
/**
|
|
10535
|
+
* Source of the current instant for expiry and revocation decisions.
|
|
10536
|
+
*
|
|
10537
|
+
* Injectable so a test can stand exactly on a boundary instant, which a wall clock cannot do.
|
|
10538
|
+
* Supply `BYMAX_AUTH_API_KEY_CLOCK` to replace it; production hosts have no reason to.
|
|
10539
|
+
*/
|
|
10540
|
+
interface ApiKeyClock {
|
|
10541
|
+
/** The current instant. */
|
|
10542
|
+
now(): Date;
|
|
10543
|
+
}
|
|
10544
|
+
|
|
10545
|
+
/**
|
|
10546
|
+
* @fileoverview Coalesces "last used" timestamps so a verified request costs no write.
|
|
10547
|
+
*
|
|
10548
|
+
* @layer Service
|
|
10549
|
+
*/
|
|
10550
|
+
|
|
10551
|
+
/**
|
|
10552
|
+
* Remembers the latest use of each key in memory and writes them to the store in one batch per
|
|
10553
|
+
* window.
|
|
10554
|
+
*
|
|
10555
|
+
* A verified request does a `Map` write and nothing else. The trade-off is stated in the
|
|
10556
|
+
* README: with N instances a key is written up to N times per window, and a crash loses at most
|
|
10557
|
+
* one window of an advisory timestamp. Authorization never reads this, so a lost or late value
|
|
10558
|
+
* cannot admit or refuse anything.
|
|
10559
|
+
*/
|
|
10560
|
+
declare class ApiKeyLastUsedService implements OnApplicationShutdown {
|
|
10561
|
+
private readonly repository;
|
|
10562
|
+
private readonly options;
|
|
10563
|
+
private readonly logger;
|
|
10564
|
+
private pending;
|
|
10565
|
+
private timer;
|
|
10566
|
+
private closed;
|
|
10567
|
+
constructor(repository: IApiKeyRepository, options: ResolvedOptions);
|
|
10568
|
+
/**
|
|
10569
|
+
* Notes that a key verified at an instant. Synchronous and free of I/O.
|
|
10570
|
+
*
|
|
10571
|
+
* @param id - The key's row id.
|
|
10572
|
+
* @param at - When it verified.
|
|
10573
|
+
*/
|
|
10574
|
+
record(id: string, at: Date): void;
|
|
10575
|
+
/**
|
|
10576
|
+
* Writes everything pending in one batch. A failure keeps the entries for the next window.
|
|
10577
|
+
*
|
|
10578
|
+
* @returns Resolves once the batch is written or has been put back.
|
|
10579
|
+
*/
|
|
10580
|
+
flush(): Promise<void>;
|
|
10581
|
+
/** Flushes what is left so a clean shutdown loses nothing. */
|
|
10582
|
+
onApplicationShutdown(): Promise<void>;
|
|
10583
|
+
}
|
|
10584
|
+
|
|
10585
|
+
/**
|
|
10586
|
+
* @fileoverview Verifies a presented service key, taking the same steps for every key.
|
|
10587
|
+
*
|
|
10588
|
+
* @layer Service
|
|
10589
|
+
*/
|
|
10590
|
+
|
|
10591
|
+
/** Why a key was not accepted. */
|
|
10592
|
+
type ApiKeyRejection = Extract<ApiKeyDenyReason, 'missing' | 'malformed' | 'unknown' | 'wrong_secret' | 'revoked' | 'expired'>;
|
|
10593
|
+
/** The outcome of verifying one presented key. */
|
|
10594
|
+
type ApiKeyVerdict = {
|
|
10595
|
+
readonly ok: true;
|
|
10596
|
+
readonly key: AuthApiKey;
|
|
10597
|
+
} | {
|
|
10598
|
+
readonly ok: false;
|
|
10599
|
+
readonly reason: ApiKeyRejection;
|
|
10600
|
+
readonly key: AuthApiKey | null;
|
|
10601
|
+
};
|
|
10602
|
+
/**
|
|
10603
|
+
* Verifies a presented key against the store.
|
|
10604
|
+
*
|
|
10605
|
+
* Every call takes the same steps whatever the key is, in this order:
|
|
10606
|
+
* parse (substituting a dummy when it does not parse) → read the row (always) → compute the
|
|
10607
|
+
* digest → compare in constant time against the row's digest or a dummy → only then decide.
|
|
10608
|
+
* No branch leaves before the decision, so an unknown, malformed, wrong, revoked or expired key
|
|
10609
|
+
* cannot be told apart by what the library does.
|
|
10610
|
+
*
|
|
10611
|
+
* @remarks
|
|
10612
|
+
* What this does not hide: the store round trip differs in cost for a present and an absent
|
|
10613
|
+
* row, and no library can remove that. Pre-verification flood protection is a per-address
|
|
10614
|
+
* throttle in front of the guard, documented in the README.
|
|
10615
|
+
*/
|
|
10616
|
+
declare class ApiKeyVerifierService {
|
|
10617
|
+
private readonly repository;
|
|
10618
|
+
private readonly clock;
|
|
10619
|
+
private readonly options;
|
|
10620
|
+
private readonly lastUsed;
|
|
10621
|
+
constructor(repository: IApiKeyRepository, clock: ApiKeyClock, options: ResolvedOptions, lastUsed: ApiKeyLastUsedService);
|
|
10622
|
+
/**
|
|
10623
|
+
* Verifies the value of the key header.
|
|
10624
|
+
*
|
|
10625
|
+
* @param header - The header value as the framework delivered it.
|
|
10626
|
+
* @returns The verdict. A store fault propagates: the caller fails closed.
|
|
10627
|
+
*/
|
|
10628
|
+
verify(header: unknown): Promise<ApiKeyVerdict>;
|
|
10629
|
+
/**
|
|
10630
|
+
* The single decision, evaluated after every step above has run.
|
|
10631
|
+
*
|
|
10632
|
+
* A key is valid strictly before `expiresAt`, and not at all once `revokedAt` is set. The
|
|
10633
|
+
* comparisons are written as "is still ahead", so a date the store could not parse (`NaN`, which
|
|
10634
|
+
* compares false against everything) reads as lapsed rather than as valid.
|
|
10635
|
+
*/
|
|
10636
|
+
private rejection;
|
|
10637
|
+
}
|
|
10638
|
+
|
|
10639
|
+
/**
|
|
10640
|
+
* @fileoverview Authenticates machine callers by service API key and enforces route scopes.
|
|
10641
|
+
*
|
|
10642
|
+
* @layer Guard
|
|
10643
|
+
*/
|
|
10644
|
+
|
|
10645
|
+
/**
|
|
10646
|
+
* Admits a request only when it presents a valid service key holding every scope the route
|
|
10647
|
+
* declares.
|
|
10648
|
+
*
|
|
10649
|
+
* **Fails closed.** A route this guard is bound to with no non-empty scope declaration is
|
|
10650
|
+
* refused before any credential is read, so a forgotten `@ApiKeyScopes` can never become an
|
|
10651
|
+
* open route. That branch deliberately takes different steps from the credential paths: it
|
|
10652
|
+
* depends on route configuration, not on the key, so there is nothing for the key to leak.
|
|
10653
|
+
*
|
|
10654
|
+
* Every request ends in exactly one `onApiKeyRequest` event, refusals included. The presented
|
|
10655
|
+
* key and its secret appear in no log line, exception, event or `request.apiKey`.
|
|
10656
|
+
*
|
|
10657
|
+
* @example
|
|
10658
|
+
* ```typescript
|
|
10659
|
+
* @ServiceKey('read') // binds this guard and lets the route past the user JWT guards
|
|
10660
|
+
* @Get('videos')
|
|
10661
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { ... }
|
|
10662
|
+
* ```
|
|
10663
|
+
*/
|
|
10664
|
+
declare class ApiKeyGuard implements CanActivate {
|
|
10665
|
+
private readonly reflector;
|
|
10666
|
+
private readonly verifier;
|
|
10667
|
+
private readonly options;
|
|
10668
|
+
private readonly hooks;
|
|
10669
|
+
private readonly logger;
|
|
10670
|
+
constructor(reflector: Reflector, verifier: ApiKeyVerifierService, options: ResolvedOptions, hooks: IAuthHooks | null);
|
|
10671
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
10672
|
+
/**
|
|
10673
|
+
* The route's scope declaration: handler over class, empty or malformed counting as none.
|
|
10674
|
+
*
|
|
10675
|
+
* @returns The scopes, or `null` when the route declares none.
|
|
10676
|
+
*/
|
|
10677
|
+
private declaredScopes;
|
|
10678
|
+
/**
|
|
10679
|
+
* Emits the audit event.
|
|
10680
|
+
*
|
|
10681
|
+
* @returns `false` only in `required` mode when the hook threw. In `best-effort` mode the hook
|
|
10682
|
+
* is fired without being awaited and the result is always `true`.
|
|
10683
|
+
*/
|
|
10684
|
+
private audit;
|
|
10685
|
+
private hookContext;
|
|
10686
|
+
}
|
|
10687
|
+
|
|
10688
|
+
/**
|
|
10689
|
+
* Declares the scopes a route requires. A key must hold ALL of them.
|
|
10690
|
+
*
|
|
10691
|
+
* The low-level declaration, for a host that binds `ApiKeyGuard` at controller level or
|
|
10692
|
+
* globally. Most routes want {@link ServiceKey}, which also lets the route past the user JWT
|
|
10693
|
+
* guards and binds the guard, so the three cannot be separated by mistake.
|
|
10694
|
+
*
|
|
10695
|
+
* The most specific declaration wins (handler over class). An empty list counts as no
|
|
10696
|
+
* declaration, and a route with no declaration is refused.
|
|
10697
|
+
*
|
|
10698
|
+
* @param scopes - The required scopes, each from `apiKeys.scopes`.
|
|
10699
|
+
*
|
|
10700
|
+
* @example
|
|
10701
|
+
* ```typescript
|
|
10702
|
+
* @UseGuards(ApiKeyGuard)
|
|
10703
|
+
* @ApiKeyScopes('read')
|
|
10704
|
+
* @Get('videos')
|
|
10705
|
+
* list() { ... }
|
|
10706
|
+
* ```
|
|
10707
|
+
*/
|
|
10708
|
+
declare const ApiKeyScopes: (...scopes: string[]) => MethodDecorator & ClassDecorator;
|
|
10709
|
+
|
|
10710
|
+
/**
|
|
10711
|
+
* @fileoverview `@ServiceKey()` — authenticates a route by service API key.
|
|
10712
|
+
*
|
|
10713
|
+
* @layer Decorator
|
|
10714
|
+
*/
|
|
10715
|
+
/**
|
|
10716
|
+
* Makes a route reachable by a machine caller holding a service key with the given scopes.
|
|
10717
|
+
*
|
|
10718
|
+
* Three things in one decorator, so they cannot be separated by mistake:
|
|
10719
|
+
*
|
|
10720
|
+
* 1. the scopes the key must hold ({@link ApiKeyScopes});
|
|
10721
|
+
* 2. the route stops asking for a user JWT — `JwtAuthGuard` and `JwtPlatformGuard` skip a route
|
|
10722
|
+
* carrying the public marker, so a global JWT guard does not refuse the machine caller;
|
|
10723
|
+
* 3. `ApiKeyGuard` is bound to the route and is the ONLY authenticator in front of it.
|
|
10724
|
+
*
|
|
10725
|
+
* "Public" here means "not a user route", never "unauthenticated": the key guard refuses a
|
|
10726
|
+
* missing or invalid key on every request.
|
|
10727
|
+
*
|
|
10728
|
+
* @param scopes - The required scopes. At least one, each from `apiKeys.scopes`.
|
|
10729
|
+
*
|
|
10730
|
+
* @example
|
|
10731
|
+
* ```typescript
|
|
10732
|
+
* @ServiceKey('read')
|
|
10733
|
+
* @Get('videos')
|
|
10734
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { ... }
|
|
10735
|
+
* ```
|
|
10736
|
+
*/
|
|
10737
|
+
declare const ServiceKey: (...scopes: string[]) => MethodDecorator & ClassDecorator;
|
|
10738
|
+
|
|
10739
|
+
/**
|
|
10740
|
+
* @fileoverview `@CurrentApiKey()` — injects the verified service key into a handler.
|
|
10741
|
+
*
|
|
10742
|
+
* @layer Decorator
|
|
10743
|
+
*/
|
|
10744
|
+
/**
|
|
10745
|
+
* Injects the {@link ApiKeyPrincipal} `ApiKeyGuard` attached to the request.
|
|
10746
|
+
*
|
|
10747
|
+
* Only meaningful after the guard ran; `undefined` on a route the guard did not admit.
|
|
10748
|
+
*
|
|
10749
|
+
* @example
|
|
10750
|
+
* ```typescript
|
|
10751
|
+
* @ServiceKey('read')
|
|
10752
|
+
* @Get('videos')
|
|
10753
|
+
* list(@CurrentApiKey() key: ApiKeyPrincipal) { return this.videos.forKey(key.id) }
|
|
10754
|
+
* ```
|
|
10755
|
+
*/
|
|
10756
|
+
declare const CurrentApiKey: (...dataOrPipes: unknown[]) => ParameterDecorator;
|
|
10757
|
+
|
|
10758
|
+
/**
|
|
10759
|
+
* @fileoverview Issues, revokes and rotates service API keys.
|
|
10760
|
+
*
|
|
10761
|
+
* @layer Service
|
|
10762
|
+
*/
|
|
10763
|
+
|
|
10764
|
+
/** Longest label accepted, in characters. A label names a machine caller, it is not a payload. */
|
|
10765
|
+
declare const API_KEY_MAX_LABEL_LENGTH = 128;
|
|
10766
|
+
/** Longest rotation overlap accepted, in seconds: 30 days. */
|
|
10767
|
+
declare const API_KEY_MAX_OVERLAP_SECONDS = 2592000;
|
|
10768
|
+
/** What issuing a key asks for. */
|
|
10769
|
+
interface IssueApiKeyInput {
|
|
10770
|
+
/** Machine caller's name. Not unique. 1 to {@link API_KEY_MAX_LABEL_LENGTH} characters. */
|
|
10771
|
+
label: string;
|
|
10772
|
+
/** Scopes to grant: non-empty, each from `apiKeys.scopes`. */
|
|
10773
|
+
scopes: readonly string[];
|
|
10774
|
+
/** When the key stops verifying. Must be in the future. Absent means it does not expire. */
|
|
10775
|
+
expiresAt?: Date;
|
|
10776
|
+
}
|
|
10777
|
+
/** A newly issued key. */
|
|
10778
|
+
interface IssuedApiKey {
|
|
10779
|
+
/**
|
|
10780
|
+
* The plaintext key. Returned this once and never retrievable again: only its digest is
|
|
10781
|
+
* stored. Hand it to the machine caller and do not log it.
|
|
10782
|
+
*/
|
|
10783
|
+
key: string;
|
|
10784
|
+
/** The stored row without its digest. */
|
|
10785
|
+
record: AuthApiKeySummary;
|
|
10786
|
+
}
|
|
10787
|
+
/** What rotating a key asks for. */
|
|
10788
|
+
interface RotateApiKeyInput {
|
|
10789
|
+
/**
|
|
10790
|
+
* Seconds the old key keeps verifying after the new one is issued. `0` retires it at once.
|
|
10791
|
+
* An integer from 0 to {@link API_KEY_MAX_OVERLAP_SECONDS}.
|
|
10792
|
+
*/
|
|
10793
|
+
overlapSeconds: number;
|
|
10794
|
+
/** Expiry for the NEW key. Absent means it does not expire; the old key's expiry is not inherited. */
|
|
10795
|
+
expiresAt?: Date;
|
|
10796
|
+
}
|
|
10797
|
+
/**
|
|
10798
|
+
* Issues, revokes and rotates service keys.
|
|
10799
|
+
*
|
|
10800
|
+
* Rotation is not special-cased: it issues a second key with the same label and scopes, and
|
|
10801
|
+
* retires the first after the overlap. Several active keys sharing a label is the ordinary state.
|
|
10802
|
+
*/
|
|
10803
|
+
declare class ApiKeyService {
|
|
10804
|
+
private readonly repository;
|
|
10805
|
+
private readonly clock;
|
|
10806
|
+
private readonly options;
|
|
10807
|
+
constructor(repository: IApiKeyRepository, clock: ApiKeyClock, options: ResolvedOptions);
|
|
10808
|
+
/**
|
|
10809
|
+
* Issues a new key.
|
|
10810
|
+
*
|
|
10811
|
+
* @param input - Label, scopes and optional expiry.
|
|
10812
|
+
* @returns The plaintext key (once) and the stored record.
|
|
10813
|
+
* @throws {AuthException} `auth.validation` for a bad label, scope list or expiry.
|
|
10814
|
+
*/
|
|
10815
|
+
issue(input: IssueApiKeyInput): Promise<IssuedApiKey>;
|
|
10816
|
+
/**
|
|
10817
|
+
* Revokes a key now. Revoking an already revoked key succeeds.
|
|
10818
|
+
*
|
|
10819
|
+
* @param id - The key's row id.
|
|
10820
|
+
* @throws {AuthException} `auth.api_key_not_found` when no such key exists.
|
|
10821
|
+
*/
|
|
10822
|
+
revoke(id: string): Promise<void>;
|
|
10823
|
+
/**
|
|
10824
|
+
* Replaces a key with a new one carrying the same label and scopes.
|
|
10825
|
+
*
|
|
10826
|
+
* The new key is issued first and the old one retired second, so a failure between the two
|
|
10827
|
+
* leaves both valid — the safe direction — rather than neither.
|
|
10828
|
+
*
|
|
10829
|
+
* @param id - The active key to replace.
|
|
10830
|
+
* @param input - The overlap and an optional expiry for the new key.
|
|
10831
|
+
* @returns The new key, plaintext once.
|
|
10832
|
+
* @throws {AuthException} `auth.validation` for a bad overlap or expiry;
|
|
10833
|
+
* `auth.api_key_not_found` when no ACTIVE key has this id (a revoked or expired key is not
|
|
10834
|
+
* rotated: that would re-issue access nobody holds).
|
|
10835
|
+
*/
|
|
10836
|
+
rotate(id: string, input: RotateApiKeyInput): Promise<IssuedApiKey>;
|
|
10837
|
+
private validatedLabel;
|
|
10838
|
+
private validatedScopes;
|
|
10839
|
+
private validatedExpiry;
|
|
10840
|
+
}
|
|
10841
|
+
|
|
10842
|
+
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 };
|