@bymax-one/nest-auth 1.5.10 β 1.5.12
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 +138 -1
- package/README.md +204 -30
- package/dist/observability/index.cjs +166 -0
- package/dist/observability/index.d.cts +83 -0
- package/dist/observability/index.d.ts +83 -0
- package/dist/observability/index.mjs +163 -0
- package/dist/server/index.cjs +3695 -1854
- package/dist/server/index.d.cts +120 -27
- package/dist/server/index.d.ts +120 -27
- package/dist/server/index.mjs +3694 -1857
- package/package.json +33 -2
package/CHANGELOG.md
CHANGED
|
@@ -18,6 +18,141 @@ what moves, and that note is the compatibility contract until strict SemVer begi
|
|
|
18
18
|
|
|
19
19
|
## [Unreleased]
|
|
20
20
|
|
|
21
|
+
## [1.5.12] - 2026-11-21
|
|
22
|
+
|
|
23
|
+
A patch release.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- **A host getter, Proxy or factory that throws no longer leaves the library as the host's own error.** The options a
|
|
28
|
+
host returns are read inside one boundary: a failure ends as `[BymaxAuthModule] the options could not be readβ¦` with
|
|
29
|
+
the host's error as its `cause` and none of its text. Each repository the host provides is read through a guarded
|
|
30
|
+
view that the library's own services use: an answer is read for the fields its method promises and for nothing
|
|
31
|
+
else (a contract for each repository method, checked by the compiler), so an entity whose relation throws until it
|
|
32
|
+
is loaded still answers, a field the contract names that throws ends as `auth.internal` with the cause, and a failure
|
|
33
|
+
of the repository itself is the same error. A typed `HttpException` the repository throws goes out as it is. Any
|
|
34
|
+
other own data field of the host's record is passed on by reference without being read, host callbacks
|
|
35
|
+
(`maxSessionsResolver`) still receive the host's own entity, the token the module exports is still the host's own
|
|
36
|
+
instance, and `OAuthModule.register` used on its own provides its own guarded view.
|
|
37
|
+
- **A field that decides an admission is read as the kind its contract gives it.** The contract of each repository
|
|
38
|
+
method names, for every field, the kind of the type the interface declares, and the compiler checks it. The fields
|
|
39
|
+
a service reads to allow or to deny (`mfaEnabled`, `emailVerified`, `status`, `role`, the credentials, an
|
|
40
|
+
API key's `digest`, `scopes`, `expiresAt` and `revokedAt`, a workspace's `deletionScheduledAt`) are strict: a boolean
|
|
41
|
+
is a boolean and not a wrapper of one (`new Boolean(false)` is truthy), a string is a string, a date is a date with a
|
|
42
|
+
real time, a list of strings holds strings, and a field the interface requires is refused when a record lacks it. A
|
|
43
|
+
function, a symbol, a bigint or a wrapper there ends as `auth.internal` instead of being dropped as absent or
|
|
44
|
+
coerced: read as absent, `mfaEnabled` served as a function would have issued tokens where a second factor is due, and
|
|
45
|
+
a wrapper in `emailVerified` would have passed an unverified account. A field the interface allows to be absent may
|
|
46
|
+
be absent or `null`. The fields that only inform (an id, a name, the dates the library returns or displays) are
|
|
47
|
+
lenient: an id may be a string, a finite number or an instance of a class of the host (the id type of a driver, kept
|
|
48
|
+
as the host's own object), a date may be a date, a string, a number or an instance of another class (a date
|
|
49
|
+
library's), and absence is accepted; a function, a symbol, a bigint and the other values no reader lists are still
|
|
50
|
+
refused there. A method that owes a record, a page or a list and answers nothing ends as `auth.internal`; only a
|
|
51
|
+
lookup that may find nothing passes the nothing on.
|
|
52
|
+
- **A date a host wraps in a Proxy is read as a date.** A valid API key whose `expiresAt` was a Proxy of a `Date` was
|
|
53
|
+
refused, and a workspace whose `deletionScheduledAt` was one could be neither restored nor finalized, because the copy
|
|
54
|
+
of the record turned the Proxy into a plain object with no `getTime`. A Proxy whose prototype chain holds
|
|
55
|
+
`Date.prototype` is now copied as the date it answers as, and an object that only has methods named like a date's is
|
|
56
|
+
not taken for one. An answer with more elements or keys than a copy follows, or an array where a record is promised, is
|
|
57
|
+
refused as `auth.internal`.
|
|
58
|
+
|
|
59
|
+
### Changed
|
|
60
|
+
|
|
61
|
+
- **A date that is not a time is refused.** A record a repository returns with a date in a field that decides an
|
|
62
|
+
admission that compares false with every instant (an Invalid Date, or a Proxy whose `getTime` answers something that
|
|
63
|
+
is not a time, a string and an empty value among it) ends as `auth.internal`. Before, and in 1.5.11 and earlier, it was copied as it was, and a workspace
|
|
64
|
+
pending deletion whose deadline was such a date was finalized, because `due.getTime() > now` is false for it, and
|
|
65
|
+
could be restored past its grace period.
|
|
66
|
+
- **The fields of the contract are visible to a spread of the copy.** An entity that serves its fields through its
|
|
67
|
+
prototype (a Sequelize or Mongoose one) used to log in and then fail every later request with a 401, because the copy
|
|
68
|
+
kept those fields out of the token payload. They are now enumerable, except the credentials (`passwordHash`,
|
|
69
|
+
`mfaSecret`, `mfaRecoveryCodes`, `digest`), which are as visible as the host's record made them, so no spread of the
|
|
70
|
+
copy can carry them out.
|
|
71
|
+
- **Apply to a derived backend:** a repository has to serve every field a service decides on, as the type the
|
|
72
|
+
interface declares. A record that does not now ends as `auth.internal` (HTTP 500, no token) where 1.5.11 and earlier
|
|
73
|
+
accepted it: a field a service decides on that is absent (`mfaEnabled`, `emailVerified`, `status`, `role` or
|
|
74
|
+
`tenantId` missing from the row, which used to read as the default of its type, so an absent `mfaEnabled` was a user
|
|
75
|
+
without a second factor); a number where a string is declared (a numeric `tenantId`); a wrapper where a boolean is
|
|
76
|
+
declared (`new Boolean(false)` is truthy); a date of another class, or an Invalid Date, where a deadline is declared;
|
|
77
|
+
and a function, a symbol or a bigint in any field the contract names. A real `false` for `mfaEnabled` still logs in,
|
|
78
|
+
and a real `true` still gets the second-factor challenge. A column that holds nothing may be `null` or absent where
|
|
79
|
+
the interface marks the field optional.
|
|
80
|
+
|
|
81
|
+
## [1.5.11] - 2026-11-20
|
|
82
|
+
|
|
83
|
+
A patch release.
|
|
84
|
+
|
|
85
|
+
### Added
|
|
86
|
+
|
|
87
|
+
- **An optional `@bymax-one/nest-auth/observability` subpath**, with a metrics contributor (`AuthMetrics`) and a readiness
|
|
88
|
+
indicator (`AuthRedisHealthIndicator`, name `auth-redis`, which gives up after 4 seconds or when the aggregator's signal aborts). Four counters, all with closed labels and none carrying an
|
|
89
|
+
id, tenant, user or address: `bymax_auth_logins_total`, `bymax_auth_refresh_total` and
|
|
90
|
+
`bymax_auth_mfa_verifications_total` by `plane` (`dashboard` or `platform`) and `outcome`, and
|
|
91
|
+
`bymax_auth_bruteforce_lockouts_total`. `POST /mfa/challenge` serves both planes, so its `plane` comes from the
|
|
92
|
+
session it ends with or the token it verified, and a token that does not verify counts as `dashboard`. The server entry exports `AuthMetricsTally`, the closed sets
|
|
93
|
+
(`AUTH_PLANES`, `LOGIN_OUTCOMES`, `REFRESH_OUTCOMES`, `MFA_OUTCOMES`) and `AuthHealthProbe`. Routes run inside the
|
|
94
|
+
spans `auth.login`, `auth.refresh`, `auth.mfa.verify` and `auth.password_reset` when `@opentelemetry/api` is
|
|
95
|
+
installed and an SDK is registered; without them nothing is created. The subpath needs `prom-client`, which is an
|
|
96
|
+
optional peer, and imports no other Bymax library.
|
|
97
|
+
- **Log events.** The flows write their events as one object through the Nest `Logger`
|
|
98
|
+
(`{ ...fields, event, message }`), listed in the README "Log events" table. The line
|
|
99
|
+
a host log filter used to match is gone: the text of these lines changed. A refusal or failure names no user and no
|
|
100
|
+
tenant; a success or audit event may carry `userId` and `tenantId` (and `actorUserId` for an invitation) as declared
|
|
101
|
+
fields; no event carries an email address, a provider name, a token or text a host or a store wrote. The no-op email provider logs which method was called and no address. A host logger
|
|
102
|
+
that is asynchronous and rejects is the host's own unhandled rejection and ends the process unless the application
|
|
103
|
+
handles it.
|
|
104
|
+
Every other line the library wrote is an event too, bar the operator guidance sentences: a failed hook or fire-and-forget step (`AUTH_HOOK_FAILED`), a
|
|
105
|
+
store or repository operation that failed (`AUTH_STORE_FAILED`, `AUTH_STORE_DEGRADED`), a stored record that does not
|
|
106
|
+
parse, a missing email provider, an unavailable breach check, a refused API-key route, an unhandled exception. They
|
|
107
|
+
carry the name of the hook or the operation from a closed set, and the library's description of the failure, never
|
|
108
|
+
the text of the error. An account an
|
|
109
|
+
OAuth login creates now writes `AUTH_USER_REGISTERED` with `via: oauth`.
|
|
110
|
+
- **README names everything the server exports.** Every export of the server entry, every module option (among them `secureCookies`, `enforceTenantBinding`, `isTrustedProxy` and the OAuth redirect URLs) and every
|
|
111
|
+
closed value of the log discriminators is in the README, and a spec keeps the README and the code in step both ways.
|
|
112
|
+
- `rxjs` is declared as a peer dependency of the server entry. It is already required by `@nestjs/common`, and the
|
|
113
|
+
interceptor that counts the observed routes imports it.
|
|
114
|
+
|
|
115
|
+
### Fixed
|
|
116
|
+
|
|
117
|
+
- A verification code the store refuses no longer fails the registration that created the account. `POST /register` and
|
|
118
|
+
`POST /resend-verification` answer as they do when the code is stored, no email is sent for a code that was not stored,
|
|
119
|
+
and one event, `AUTH_OTP_STORE_FAILED`, records the refusal without the address or the user id. Before, the refusal reached the caller as an error for an account that existed.
|
|
120
|
+
- **A text option, a list of text and a group of settings given a value of the wrong type are refused at startup, naming the
|
|
121
|
+
option and the type received.** `jwt.accessExpiresIn` given a number, a boolean, an object, a symbol or a bigint failed
|
|
122
|
+
with `value.trim is not a function`; it now gets the same refusal as an unreadable string. `jwt.issuer`, `jwt.audience`,
|
|
123
|
+
the three cookie names, `cookies.refreshCookiePath`, `cookies.mfaTempCookiePath`, `mfa.issuer`, `apiKeys.pepper`,
|
|
124
|
+
`redisNamespace` and `routePrefix` must be strings. `blockedStatuses`, `cookies.trustedOrigins` and `password.blocklist`
|
|
125
|
+
must be arrays of strings: `blockedStatuses: 'evil'` was accepted and read as no list. The groups `password`, `cookies`,
|
|
126
|
+
`sessions`, `bruteForce`, `passwordReset`, `emailVerification`, `platform`, `invitations`, `emailChange` and `oauth`
|
|
127
|
+
must be objects, where a string was read as an empty group. The `controllers` argument of `registerAsync` must be an
|
|
128
|
+
object. A refusal prints a number as it is and names any other value by its type, never its content.
|
|
129
|
+
- Three refusals no longer print what the host typed: a `cookies.trustedOrigins` entry that is not an absolute origin is
|
|
130
|
+
named by its position, a `workspaces.permissions.<action>` entry that is not a workspace role is named by its position,
|
|
131
|
+
and the `routePrefix` refusal says "followed by the routePrefix" instead of repeating it. A log filter that matched the
|
|
132
|
+
old text must change.
|
|
133
|
+
- A nested `oauth.google` given as a class with getters, an accessor pair or a Proxy is read through its properties, so
|
|
134
|
+
the provider block carries its values; it resolved as an empty object, and the provider was never built.
|
|
135
|
+
- The `controllers` flags are read once, by `registerAsync`, and that one reading is what the registration uses; a flag that
|
|
136
|
+
is a getter was evaluated twice, once to check it and once to apply it.
|
|
137
|
+
|
|
138
|
+
### Apply to a derived backend
|
|
139
|
+
|
|
140
|
+
Nothing is removed from the public declarations. The `@bymax-one/nest-auth/observability` subpath is new and needs no
|
|
141
|
+
change until you use it: its counters need `prom-client`, its spans need `@opentelemetry/api`, and `@bymax-one/nest-core`
|
|
142
|
+
`>=1.6.15` is a new optional peer whose metrics-contributor and readiness contracts the subpath meets without importing it;
|
|
143
|
+
all three are optional. `rxjs` is now declared as a peer of the server entry; `@nestjs/common` already requires it. The server entry adds
|
|
144
|
+
`AuthMetricsTally`, `AuthHealthProbe`, `AUTH_PLANES`, `LOGIN_OUTCOMES`, `REFRESH_OUTCOMES`, `MFA_OUTCOMES` and the
|
|
145
|
+
matching outcome types. `BruteForceService` takes an optional third constructor argument, the tally, and the methods of
|
|
146
|
+
`NoOpEmailProvider` name their address parameter `_email` instead of `email` (the types are the same).
|
|
147
|
+
|
|
148
|
+
What changes at run time is the log. Every line the library writes, bar the operator guidance sentences, is an object, `{ ...fields, event, message }`, with
|
|
149
|
+
the code and the message of the README "Log events" table, and the text of the old lines is gone. A log filter, an
|
|
150
|
+
alert or a test that matches the old text must match the event code instead, and a host logger now receives an object
|
|
151
|
+
where it used to receive a string. A refusal or failure carries no user, tenant, address or provider; a success or
|
|
152
|
+
audit event carries `userId` and `tenantId`. A configuration that booted before is refused at startup when a text
|
|
153
|
+
option, a list of text or a group of settings has the wrong type. A registration whose verification code the store
|
|
154
|
+
refuses now succeeds as it does when the code is stored.
|
|
155
|
+
|
|
21
156
|
## [1.5.10] - 2026-11-18
|
|
22
157
|
|
|
23
158
|
A patch release.
|
|
@@ -5377,7 +5512,9 @@ ever installable.
|
|
|
5377
5512
|
- Phase 4 password-reset tests cover: both `token` and `otp` flows, mutual exclusivity validation, `verifiedToken` exchange, resend cooldown, anti-enumeration (no error on unknown email), and session invalidation on reset
|
|
5378
5513
|
- Phase 5 tests cover: platform login with MFA path and brute-force lockout, `JwtPlatformGuard` cross-context rejection, `PlatformRolesGuard` hierarchy enforcement, OAuth CSRF state lifecycle, `onOAuthLogin` hook resolution strategies, and invitation role-authorization + acceptance single-use enforcement
|
|
5379
5514
|
|
|
5380
|
-
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.
|
|
5515
|
+
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.12...HEAD
|
|
5516
|
+
[1.5.12]: https://github.com/bymaxone/nest-auth/compare/v1.5.11...v1.5.12
|
|
5517
|
+
[1.5.11]: https://github.com/bymaxone/nest-auth/compare/v1.5.10...v1.5.11
|
|
5381
5518
|
[1.5.10]: https://github.com/bymaxone/nest-auth/compare/v1.5.9...v1.5.10
|
|
5382
5519
|
[1.5.9]: https://github.com/bymaxone/nest-auth/compare/v1.5.8...v1.5.9
|
|
5383
5520
|
[1.5.8]: https://github.com/bymaxone/nest-auth/compare/v1.5.7...v1.5.8
|
package/README.md
CHANGED
|
@@ -97,15 +97,16 @@ pnpm add @bymax-one/nest-auth
|
|
|
97
97
|
|
|
98
98
|
## π¦ Subpath Exports
|
|
99
99
|
|
|
100
|
-
One package,
|
|
100
|
+
One package, six entry points β import only what your app needs:
|
|
101
101
|
|
|
102
|
-
| Subpath
|
|
103
|
-
|
|
|
104
|
-
| **Server**
|
|
105
|
-
| **Shared**
|
|
106
|
-
| **Client**
|
|
107
|
-
| **React**
|
|
108
|
-
| **Next.js**
|
|
102
|
+
| Subpath | Import | Purpose | Dependencies |
|
|
103
|
+
| ----------------- | ------------------------------------ | ------------------------------------------------------ | :----------------: |
|
|
104
|
+
| **Server** | `@bymax-one/nest-auth` | NestJS module, guards, decorators, services | NestJS 11, ioredis |
|
|
105
|
+
| **Shared** | `@bymax-one/nest-auth/shared` | Types, constants, error codes | None |
|
|
106
|
+
| **Client** | `@bymax-one/nest-auth/client` | Fetch-based auth client | None |
|
|
107
|
+
| **React** | `@bymax-one/nest-auth/react` | Hooks & AuthProvider | React 19 |
|
|
108
|
+
| **Next.js** | `@bymax-one/nest-auth/nextjs` | Proxy, route handlers, JWT helpers | Next.js 16 |
|
|
109
|
+
| **Observability** | `@bymax-one/nest-auth/observability` | Metrics contributor and readiness indicator (optional) | `prom-client` |
|
|
109
110
|
|
|
110
111
|
```
|
|
111
112
|
shared (zero deps)
|
|
@@ -142,7 +143,7 @@ yarn add @bymax-one/nest-auth
|
|
|
142
143
|
|
|
143
144
|
```bash
|
|
144
145
|
# Server subpath (required)
|
|
145
|
-
pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/websockets express ioredis class-validator class-transformer reflect-metadata
|
|
146
|
+
pnpm add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/throttler @nestjs/websockets express ioredis class-validator class-transformer reflect-metadata rxjs
|
|
146
147
|
pnpm add -D @types/express
|
|
147
148
|
|
|
148
149
|
# Also needed with `tokenDelivery: 'cookie'` or `'both'` (see step 4): the library reads `req.cookies`
|
|
@@ -785,32 +786,43 @@ export const POST = createLogoutHandler({
|
|
|
785
786
|
|
|
786
787
|
All options are configurable via `registerAsync()`. Here are the key configuration groups:
|
|
787
788
|
|
|
788
|
-
| Group
|
|
789
|
-
|
|
|
790
|
-
| **jwt**
|
|
791
|
-
| **identifierKey**
|
|
792
|
-
| **environment**
|
|
793
|
-
| **password**
|
|
794
|
-
| **tokenDelivery**
|
|
795
|
-
| **cookies**
|
|
796
|
-
| **mfa**
|
|
797
|
-
| **sessions**
|
|
798
|
-
|
|
|
799
|
-
| **rateLimit**
|
|
800
|
-
| **passwordReset**
|
|
801
|
-
| **platform**
|
|
802
|
-
| **invitations**
|
|
803
|
-
| **apiKeys**
|
|
804
|
-
| **roles**
|
|
805
|
-
| **oauth**
|
|
806
|
-
|
|
|
807
|
-
| **password** (screen)
|
|
808
|
-
| **
|
|
789
|
+
| Group | Key Options | Default |
|
|
790
|
+
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- |
|
|
791
|
+
| **jwt** | `secret` (required), `previousSecrets`, `accessExpiresIn`, `refreshExpiresInDays`, `absoluteSessionLifetimeDays`, `algorithm`, `issuer`, `audience` | `15m`, `7d`, `30d` cap, `HS256`, both off |
|
|
792
|
+
| **identifierKey** | Top-level secret the Redis account identifiers and MFA recovery-code digests derive from; pin it before rotating `jwt.secret` | `jwt.secret` |
|
|
793
|
+
| **environment** | `'production'` \| `'development'` \| `'test'` β the only input that answers "is this production" | `'production'` |
|
|
794
|
+
| **password** | `minLength`, `costFactor`, `blockSize`, `parallelization` | `15`, scrypt N=2ΒΉβ·, r=8, p=1 |
|
|
795
|
+
| **tokenDelivery** | `'cookie'` \| `'bearer'` \| `'both'` | `'cookie'` |
|
|
796
|
+
| **cookies** | `accessTokenName`, `refreshTokenName`, `sessionSignalName`, `refreshCookiePath`, `sameSite`, `trustedOrigins`, `resolveDomains` | `'lax'`, `[]` (see cookie section) |
|
|
797
|
+
| **mfa** | `encryptionKey`, `previousEncryptionKeys`, `issuer`, `totpWindow`, `recoveryCodeCount` | `totpWindow` `1`, `recoveryCodeCount` `8` |
|
|
798
|
+
| **sessions** | `enabled`, `defaultMaxSessions`, `maxSessionsResolver` | `false`, `5`, β |
|
|
799
|
+
| **`bruteForce`** | `maxAttempts`, `windowSeconds` | `5`, `900` |
|
|
800
|
+
| **rateLimit** | `enabled`, `clientIpSource` (`'peer'` \| `'trusted-proxy'`) β per-IP limits over Redis | `true`, **required** |
|
|
801
|
+
| **passwordReset** | `method` (`'token'` \| `'otp'`), `otpLength`, `otpTtlSeconds` | `'token'` |
|
|
802
|
+
| **platform** | `enabled` | `false` |
|
|
803
|
+
| **invitations** | `enabled`, `tokenTtlSeconds` | `false` |
|
|
804
|
+
| **apiKeys** | `enabled`, `pepper` and `scopes` (required when enabled), `header`, `prefix`, `lastUsedFlushSeconds`, `auditMode` β see [Service API keys](#-service-api-keys-machine-callers) | `false`, `'x-api-key'`, `'bak'`, `60`, `'best-effort'` |
|
|
805
|
+
| **roles** | `hierarchy` (required), `platformHierarchy` | β |
|
|
806
|
+
| **oauth** | `google: { clientId, clientSecret, callbackUrl, scope }` | `scope`: `['openid', 'email', 'profile']` |
|
|
807
|
+
| **`emailVerification`** | `required`, `otpTtlSeconds` | `true`, `600` |
|
|
808
|
+
| **password** (screen) | `blocklist` β extra words the default screen refuses, on top of the ones it ships | `[]` |
|
|
809
|
+
| **jwt** (cookie, refresh) | `accessCookieMaxAgeMs`, `refreshGraceWindowSeconds` | `900000`, `30` |
|
|
810
|
+
| **`secureCookies`** | Top-level `Secure` flag on the auth cookies; `false` is refused unless `environment` is `development` or `test` | `true`, unless `environment` is `development` or `test` |
|
|
811
|
+
| **cookies** (MFA) | `mfaTempCookiePath` β set it to the real `/mfa` path when the app uses a Nest global prefix or a different `routePrefix` | `/auth/mfa` (it does not follow `routePrefix`) |
|
|
812
|
+
| **emailChange** | `tokenTtlSeconds`; the flow itself is switched on by `controllers.emailChange` | `3600` |
|
|
813
|
+
| **oauth** (redirects) | `successRedirectUrl`, `mfaRedirectUrl`, `errorRedirectUrl` | β |
|
|
814
|
+
| **`enforceTenantBinding`** | Top-level: the guards re-resolve the tenant and refuse a token whose `tenantId` differs; needs `tenantIdResolver` | `false` |
|
|
815
|
+
| **`isTrustedProxy`** | Top-level predicate: whether the peer of a WebSocket upgrade is a proxy whose `X-Forwarded-Host` may be believed | unset |
|
|
816
|
+
| **controllers** | Toggle individual controllers on/off β passed to `registerAsync()` itself, never returned from `useFactory` (which refuses it at startup) | `auth`, `passwordReset` on; rest opt-in |
|
|
809
817
|
|
|
810
818
|
An option that is omitted, or that holds `undefined` or `null`, is unset and takes its default; it never means "no limit". To switch
|
|
811
819
|
a cap off, use the documented value (`0` for `jwt.absoluteSessionLifetimeDays`), not an absent one. A host-defined map or a required value (`oauth.<provider>`, the `oauth` redirect URLs, `roles.hierarchy.<role>`, `workspaces.permissions.<action>`) refuses `null` by name.
|
|
812
820
|
A flag must be exactly `true` or `false` (`workspaces.allowCreate` may also be a function), and an option with a documented set of values exactly one of them: anything else, an empty string and `'false'` included, is
|
|
813
821
|
refused at startup naming the option, never read as off or as a default.
|
|
822
|
+
A text option (`jwt.issuer`, `jwt.audience`, the cookie names and paths, `mfa.issuer`, `apiKeys.pepper`, `redisNamespace`,
|
|
823
|
+
`routePrefix`) must be a string, `blockedStatuses`, `cookies.trustedOrigins` and `password.blocklist` an array of strings, and each
|
|
824
|
+
settings group an object; any other type is refused at startup naming the option and the type received, and never printing the content of a value that is not a number. `controllers` is read once, by
|
|
825
|
+
`registerAsync()`, and a `controllers` key in what `useFactory` returns is refused whatever its value, `null` and `undefined` included.
|
|
814
826
|
|
|
815
827
|
> [!NOTE]
|
|
816
828
|
> When a feature is not enabled (e.g., `mfa`, `sessions`, `platform`), its controllers and services are **not registered** in the NestJS container β zero overhead. A feature is enabled by `controllers.<name>: true` on the `registerAsync()` call together with its configuration group (`mfa.encryptionKey` and `mfa.issuer`, `sessions.enabled`, `platform.enabled`); either half alone leaves it unregistered or fails at startup.
|
|
@@ -1363,6 +1375,130 @@ or a stored default, and non-members and nonexistent workspaces are indistinguis
|
|
|
1363
1375
|
|
|
1364
1376
|
---
|
|
1365
1377
|
|
|
1378
|
+
## π Observability
|
|
1379
|
+
|
|
1380
|
+
The flows count what they do whether or not anything publishes it: the module registers `AuthMetricsTally`, a few integer counts keyed by closed sets, and the optional `@bymax-one/nest-auth/observability` subpath reads them. It needs `prom-client` and a metrics registry that discovers contributors by the `bymax-one:metrics-contributor` metadata key (`@bymax-one/nest-core` >= 1.6.15 does); the package itself imports no other Bymax library.
|
|
1381
|
+
|
|
1382
|
+
```ts
|
|
1383
|
+
import { AuthMetrics, AuthRedisHealthIndicator } from '@bymax-one/nest-auth/observability'
|
|
1384
|
+
|
|
1385
|
+
@Module({
|
|
1386
|
+
imports: [BymaxAuthModule.registerAsync({/* ... */})],
|
|
1387
|
+
providers: [AuthMetrics, AuthRedisHealthIndicator] // discovered by the metrics and health modules
|
|
1388
|
+
})
|
|
1389
|
+
export class ObservabilityModule {}
|
|
1390
|
+
```
|
|
1391
|
+
|
|
1392
|
+
### Metrics
|
|
1393
|
+
|
|
1394
|
+
Every label is a member of a closed set, a sample exists for each plane and outcome from the first scrape, and no id, tenant, user, address or message is ever a label. `plane` is `dashboard` or `platform`.
|
|
1395
|
+
|
|
1396
|
+
| Name | Type | Labels | Meaning |
|
|
1397
|
+
| -------------------------------------- | ------- | ------------------ | --------------------------------------------------------------------------------------------------------- |
|
|
1398
|
+
| `bymax_auth_logins_total` | counter | `plane`, `outcome` | Login attempts. `outcome`: `success`, `invalid_credentials`, `locked`, `mfa_required`, `blocked` |
|
|
1399
|
+
| `bymax_auth_refresh_total` | counter | `plane`, `outcome` | Refresh attempts. `outcome`: `rotated`, `reuse_detected`, `expired`, `invalid` |
|
|
1400
|
+
| `bymax_auth_mfa_verifications_total` | counter | `plane`, `outcome` | MFA challenges. `outcome`: `success`, `invalid` (a wrong code, or a token that does not verify), `locked` |
|
|
1401
|
+
| `bymax_auth_bruteforce_lockouts_total` | counter | none | Identifiers locked out after too many failures, counted once at the failure that reaches the threshold |
|
|
1402
|
+
|
|
1403
|
+
A login that ends any other way (an unverified address, a server error) is not counted. `POST /mfa/challenge` serves both planes, so its `plane` is the plane of the session it ends with and, for a refused challenge, the plane of the token it verified; a token that does not verify (counted as `invalid`) has no plane and counts as `dashboard`. `reuse_detected` is a refresh that presented an already-consumed token; `expired` is a session past `jwt.absoluteSessionLifetimeDays`. The caller receives the same `auth.refresh_token_invalid` for every refused refresh.
|
|
1404
|
+
|
|
1405
|
+
### Spans
|
|
1406
|
+
|
|
1407
|
+
With `@opentelemetry/api` installed and an SDK registered, each of these routes runs inside a span carrying `bymax.auth.plane`, except `POST /mfa/challenge`, which serves both planes and whose span names none because the token decides it; without them nothing is created. A failed span carries the library error code (`auth.invalid_credentials`) and never the message.
|
|
1408
|
+
|
|
1409
|
+
| Span | Routes |
|
|
1410
|
+
| --------------------- | ----------------------------------------------------------------- |
|
|
1411
|
+
| `auth.login` | `POST /login`, `POST /platform/auth/login` |
|
|
1412
|
+
| `auth.refresh` | `POST /refresh`, `POST /platform/auth/refresh` |
|
|
1413
|
+
| `auth.mfa.verify` | `POST /mfa/challenge`, `POST /platform/auth/mfa/challenge` |
|
|
1414
|
+
| `auth.password_reset` | `POST /password/forgot-password`, `POST /password/reset-password` |
|
|
1415
|
+
|
|
1416
|
+
### Readiness
|
|
1417
|
+
|
|
1418
|
+
`AuthRedisHealthIndicator` (name `auth-redis`) asks the Redis client the module was given for a `PING`: one round trip, nothing written, no detail reported. It gives up after 4 seconds, under the 5 seconds the readiness aggregator of `@bymax-one/nest-core` waits by default, or as soon as the aggregator's signal aborts, and probes that arrive while a `PING` is still pending share it, so a store that never answers is asked at most once per 4-second window rather than once per probe; a `PING` that has outlived the timeout is dropped and the next probe sends a fresh one, so readiness recovers when the store does. `AuthHealthProbe` is the same question for a host that wires its own check.
|
|
1419
|
+
|
|
1420
|
+
### Log events
|
|
1421
|
+
|
|
1422
|
+
The flows write each event as one object through the plain Nest `Logger`: `{ ...fields, event, message }`, so a field can never replace the code or the message. The `event` is a code from the table, the `message` is the library's own text for it (the Message column), and every field is a closed value, a library-made id or `detail`, a description the library composed of a failure.
|
|
1423
|
+
|
|
1424
|
+
Who an event may name is split by what it records. A **success or audit event** (level `log`) may carry `userId` and `tenantId` as declared fields, because an audit trail without "who" is useless; these are the ids of your own database, and `actorUserId` is the user who performed an invitation. A **refusal or failure** names no user and no tenant, because a log that says which account was refused lets whoever reads it enumerate accounts; the refresh reuse events carry `familyId`, the lineage of a refresh token, which is library-made. No event of any level carries an email address, a provider name, an IP address, a token or a code, and no text a host or a store wrote. `detail` is never the `Error` the host or the store threw, because a relay can quote the code it was sent; it is the library's description of the failure (`describeChannelStatus`), which drops the channel's text. A spec pins both halves of this: the catalog lists only the field names above, only `log` events name a user or a tenant, and no logger call in the library writes an identity as text.
|
|
1425
|
+
|
|
1426
|
+
A Nest `Logger` calls the host logger and discards what it returns, so a host logger that throws synchronously cannot change what the flow does (the throw is swallowed), while a host logger that is asynchronous and rejects is the host's own unhandled rejection. Measured: behind a Nest `Logger` that rejection is not caught anywhere, and it ends the process with exit code 1 unless your application handles `unhandledRejection`. Make a host logger synchronous, or handle `unhandledRejection` at the process level.
|
|
1427
|
+
|
|
1428
|
+
| Code | Level | Message | When | Fields |
|
|
1429
|
+
| ------------------------------------- | ----- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------ |
|
|
1430
|
+
| `AUTH_LOGIN_LOCKED` | warn | login: account locked | A login is refused because the account is at its failure ceiling | `plane` |
|
|
1431
|
+
| `AUTH_LOGIN_INVALID_CREDENTIALS` | warn | login: invalid credentials | A login is refused for a wrong password (the platform plane also writes it for an unknown account) | `plane` |
|
|
1432
|
+
| `AUTH_MFA_CODE_INVALID` | warn | MFA: invalid code | An MFA code is refused (flow: challenge, enable, disable, recovery_codes) | `plane`, `flow` |
|
|
1433
|
+
| `AUTH_MFA_LOCKED` | warn | MFA: account locked | An MFA step is refused because the account is at its failure ceiling (flow: challenge, disable, recovery_codes) | `plane`, `flow` |
|
|
1434
|
+
| `AUTH_MFA_RESET` | warn | MFA: removed administratively | An administrator removes the MFA factor of an account | `plane` |
|
|
1435
|
+
| `AUTH_PASSWORD_REJECTED` | warn | the current password was rejected | A password re-proof is refused (flow: change_password, email_change) | `flow` |
|
|
1436
|
+
| `AUTH_ACCOUNT_LOCKED` | warn | account locked | A password re-proof is refused because the account is at its failure ceiling (flow: change_password, email_change, reauthentication) | `flow` |
|
|
1437
|
+
| `AUTH_REAUTHENTICATION_REFUSED` | warn | reauthentication refused | A sensitive action is refused for lack of a recent authentication (reason: no_recent_authentication) | `plane`, `reason` |
|
|
1438
|
+
| `AUTH_REFRESH_REUSE_DETECTED` | warn | refresh: reuse of a consumed token detected, revoking its family | A refresh token that was already exchanged is presented again | `plane`, `familyId` |
|
|
1439
|
+
| `AUTH_REFRESH_FAMILY_REVOKED` | warn | refresh: token family revoked after reuse detection | The family of a reused refresh token has been revoked | `plane`, `familyId` |
|
|
1440
|
+
| `AUTH_REFRESH_REFUSED` | warn | refresh: no valid session or grace window found | A refresh token matches no live session and no grace window | `plane` |
|
|
1441
|
+
| `AUTH_SESSION_LIFETIME_EXCEEDED` | warn | refresh: the session has outlived the absolute lifetime cap | A rotation is refused because the login it descends from is older than jwt.absoluteSessionLifetimeDays | none |
|
|
1442
|
+
| `AUTH_TOKEN_REVOCATION_REFUSED` | warn | a dashboard token carrying no tenant is refused without a store read | A revocation check cannot name the epoch key of a token (reason: missing_tenant) | `reason` |
|
|
1443
|
+
| `AUTH_WS_TICKET_REFUSED` | warn | ws-ticket: refused | A WebSocket ticket is refused (reason: mfa_not_satisfied, no_life_left, unknown_or_used, session_revoked) | `reason` |
|
|
1444
|
+
| `AUTH_OAUTH_STATE_REFUSED` | warn | oauth: callback state refused | An OAuth callback is refused (reason: not_bound, provider_mismatch, invalid_or_expired, unparseable) | `reason` |
|
|
1445
|
+
| `AUTH_OTP_STORE_FAILED` | error | email verification: the code could not be stored | The store refuses the write of an email-verification code | `detail` |
|
|
1446
|
+
| `AUTH_IDENTIFIER_REFUSED` | error | brute-force: an identifier was refused | An identifier passed to the lockout counter is not usable (reason: forbidden_characters, too_long) | `reason` |
|
|
1447
|
+
| `AUTH_LOGIN_SUCCEEDED` | log | login: succeeded | A login completes and its tokens are issued (via: password, oauth) | `plane`, `userId`, `tenantId`, `via` |
|
|
1448
|
+
| `AUTH_LOGIN_MFA_CHALLENGED` | log | login: MFA challenge issued | A login is answered with an MFA challenge instead of tokens (via: password, oauth) | `plane`, `userId`, `tenantId`, `via` |
|
|
1449
|
+
| `AUTH_LOGOUT` | log | logout | A session is logged out; the user id is left out when no live session was found | `plane`, `userId` |
|
|
1450
|
+
| `AUTH_USER_REGISTERED` | log | register: user registered | A registration, or an OAuth login that creates one, makes an account (via: password, oauth) | `userId`, `tenantId`, `via` |
|
|
1451
|
+
| `AUTH_TOKENS_ISSUED` | log | tokens issued for an existing user | The host asks the library to issue tokens for a user id it has already authenticated | `userId`, `tenantId` |
|
|
1452
|
+
| `AUTH_EMAIL_VERIFIED` | log | email verified | The email address of an account is verified | `userId`, `tenantId` |
|
|
1453
|
+
| `AUTH_ACCOUNT_UNLOCKED` | log | lockout cleared by an administrator | An administrator clears the lockout of an account | `tenantId` |
|
|
1454
|
+
| `AUTH_EMAIL_CHANGE_REQUESTED` | log | email change: verification sent | A verification is sent for a requested email change | `userId` |
|
|
1455
|
+
| `AUTH_EMAIL_CHANGED` | log | email change: address changed | An email change is confirmed | `userId` |
|
|
1456
|
+
| `AUTH_INVITATION_CREATED` | log | invitation created | An invitation is created (actorUserId: the inviter) | `tenantId`, `actorUserId` |
|
|
1457
|
+
| `AUTH_INVITATION_REVOKED` | log | invitation withdrawn | An invitation is withdrawn (actorUserId: who withdrew it) | `tenantId`, `actorUserId` |
|
|
1458
|
+
| `AUTH_INVITATION_ACCEPTED` | log | invitation accepted | An invitation is accepted and the account joins the tenant | `userId`, `tenantId` |
|
|
1459
|
+
| `AUTH_MFA_CHALLENGE_PASSED` | log | MFA: challenge passed | An MFA challenge is answered correctly | `plane`, `userId` |
|
|
1460
|
+
| `AUTH_MFA_SETUP_STARTED` | log | MFA: setup initiated | An MFA setup is started | `plane`, `userId` |
|
|
1461
|
+
| `AUTH_MFA_ENABLED` | log | MFA: enabled | An MFA factor is confirmed and enabled | `plane`, `userId` |
|
|
1462
|
+
| `AUTH_MFA_DISABLED` | log | MFA: disabled | An MFA factor is disabled by its owner | `plane`, `userId` |
|
|
1463
|
+
| `AUTH_MFA_RECOVERY_CODES_REGENERATED` | log | MFA: recovery codes regenerated | The recovery codes of an account are replaced | `plane`, `userId` |
|
|
1464
|
+
| `AUTH_MFA_NOTHING_TO_RESET` | log | MFA: no second factor to remove | An administrator resets the MFA of an account that has no factor | `plane`, `userId` |
|
|
1465
|
+
| `AUTH_WS_TICKET_ISSUED` | log | ws-ticket: issued | A WebSocket ticket is issued | `userId`, `tenantId` |
|
|
1466
|
+
| `AUTH_REHASH_SKIPPED` | log | rehash on verify skipped: the stored hash changed | A password rehash after a successful login is skipped because the stored hash changed in the meantime | none |
|
|
1467
|
+
| `AUTH_LOCKOUT_STATE_UNREADABLE` | warn | login: lockout state unreadable for the onLockout hook | The lockout state cannot be read when the onLockout hook is about to run | `detail` |
|
|
1468
|
+
| `AUTH_EMAIL_CHANGE_TOKEN_STALE` | warn | email change: the token is no longer bound to the account password | A confirmation is refused because the password changed after the token was issued | none |
|
|
1469
|
+
| `AUTH_PASSWORD_RESET_TOKEN_STALE` | warn | password reset: the token was issued against a password that has since changed | A reset is refused because the password changed after the token was issued | none |
|
|
1470
|
+
| `AUTH_MFA_SETUP_KEY_CONSUMED` | warn | MFA: the setup key was consumed by a concurrent request | Two requests race to confirm the same MFA setup and one loses | none |
|
|
1471
|
+
| `AUTH_INVITATION_REFUSED` | warn | invitation: refused | An invitation is refused (reason: outranked, changed_under_rank_check, revoke_outranked, inviter_cannot_grant) | `reason` |
|
|
1472
|
+
| `AUTH_OAUTH_CREATE_REFUSED` | warn | oauth: create refused, the account already exists | An OAuth profile would create an account that already exists in the tenant | none |
|
|
1473
|
+
| `AUTH_OAUTH_PROVIDER_ERROR` | warn | oauth: the provider returned an error on the callback | The provider redirects back with an error instead of a code (error: an RFC 6749 code, or other) | `error` |
|
|
1474
|
+
| `AUTH_OAUTH_EXCHANGE_FAILED` | error | oauth: the code exchange or profile fetch failed | The plugin fails during the code exchange or the profile fetch | `detail` |
|
|
1475
|
+
| `AUTH_DELIVERY_FAILED` | error | delivery failed | A notification cannot be delivered (kind: the notification that failed) | `kind`, `detail` |
|
|
1476
|
+
| `AUTH_PASSWORD_RESET_ROLLBACK_FAILED` | error | password reset: the rollback delete failed | The stored reset token cannot be deleted after its delivery failed | `detail` |
|
|
1477
|
+
| `AUTH_SESSION_EVICTION_SKIPPED` | error | session limit: eviction skipped | A session record cannot be read while the session limit is enforced | `detail` |
|
|
1478
|
+
| `AUTH_SESSION_EVICTION_FAILED` | error | session limit: eviction failed | An evicted session cannot be removed while the session limit is enforced | `detail` |
|
|
1479
|
+
| `AUTH_SESSION_LIMIT_RESOLVER_INVALID` | error | session limit: maxSessionsResolver returned a value that is not a positive whole number | The answer of the resolver is unusable and defaultMaxSessions applies | none |
|
|
1480
|
+
| `AUTH_EMAIL_NOT_SENT` | log | no-op email provider: nothing was sent | The no-op provider receives a message to deliver (kind: the method called) | `kind` |
|
|
1481
|
+
| `AUTH_MFA_SETUP_PAYLOAD_INVALID` | warn | MFA: a stored payload is not valid JSON | A stored MFA payload cannot be parsed (kind: setup, recovery_codes) | `kind` |
|
|
1482
|
+
| `AUTH_HOOK_FAILED` | error | a hook or a fire-and-forget step failed | A hook, or a step that runs beside a flow such as the last-login write, fails (how: threw, rejected) | `hook`, `how` |
|
|
1483
|
+
| `AUTH_STORE_FAILED` | error | a store or repository operation failed | A store or repository operation fails and the flow reports it (operation: the named step) | `operation`, `detail` |
|
|
1484
|
+
| `AUTH_STORE_DEGRADED` | warn | a store or repository operation failed and the flow went on | A store or repository operation fails and the flow goes on without it (operation: the named step) | `operation`, `detail` |
|
|
1485
|
+
| `AUTH_RECORD_INVALID` | warn | a stored record is not valid | A stored record cannot be parsed (record: stored_invitation, reset_context, session_json) | `record` |
|
|
1486
|
+
| `AUTH_PROVIDER_MISSING` | warn | no email provider is configured | A flow needs the email provider and none is configured (flow: email_verification_otp, password_reset_token, password_reset_otp) | `flow` |
|
|
1487
|
+
| `AUTH_BREACH_CHECK_UNAVAILABLE` | warn | the breach check did not answer and the password was admitted | The breach checker does not answer (reason: unavailable, unreachable, threw) | `reason` |
|
|
1488
|
+
| `AUTH_API_KEY_REFUSED` | error | api key: refused | An API-key route is refused for a configuration the host must fix (reason: unscoped_route, audit_hook_missing) | `reason` |
|
|
1489
|
+
| `AUTH_TENANT_SCOPE_VIOLATED` | warn | login: the repository returned an account outside the requested tenant | The user repository returns an account of another tenant, so findByEmail does not scope by its tenant argument | none |
|
|
1490
|
+
| `AUTH_UNHANDLED_EXCEPTION` | error | unhandled exception | An exception reaches the library's filter (surface: http, ws) | `surface`, `detail` |
|
|
1491
|
+
|
|
1492
|
+
#### Discriminators
|
|
1493
|
+
|
|
1494
|
+
The fields that name a step come from sets the library owns, typed in the code and listed here; none is ever text a host or a store wrote.
|
|
1495
|
+
|
|
1496
|
+
- **`hook`** of `AUTH_HOOK_FAILED`: `beforeRegister`, `afterRegister`, `beforeLogin`, `afterLogin`, `afterLogout`, `afterPlatformLogout`, `onLoginFailed`, `onLockout`, `onRefreshTokenReuseDetected`, `afterMfaEnabled`, `afterMfaDisabled`, `afterMfaRecoveryCodesRegenerated`, `onNewSession`, `afterEmailVerified`, `afterPasswordReset`, `onOAuthLogin`, `afterInvitationAccepted`, `onSessionEvicted`, `onApiKeyRequest`, `beforeWorkspaceCreate`, `onWorkspaceEvent`, `updateLastLogin`, `accessDenied`, `maxSessionsResolver`.
|
|
1497
|
+
- **`operation`** of `AUTH_STORE_FAILED` and `AUTH_STORE_DEGRADED`: `account_status_cache_write`, `api_key_last_used_flush`, `api_key_lookup`, `cache_invalidation`, `dead_member_prune`, `grace_pointer_prune`, `invitation_withdraw`, `logout_marker_clear`, `logout_owner_keep`, `mfa_lock_release`, `mfa_reencryption`, `new_session_user_lookup`, `rehash_on_verify`, `reset_account_lookup`, `reset_cooldown_release`, `reset_cooldown_store`, `reset_issue`, `session_cleanup`, `session_detail_read`, `session_detail_rotation`, `workspace_cache_read`, `workspace_cache_write`.
|
|
1498
|
+
- **`kind`** of `AUTH_DELIVERY_FAILED`: `passwordResetToken`, `passwordResetOtp`, `emailVerificationOtp`, `passwordChanged`, `emailChangeVerification`, `emailChanged`, `mfaEnabled`, `mfaDisabled`, `newSessionAlert`, `invitation`, `workspaceInvitation`, `email_verification_otp`, `password_changed_notice`, `password_reset_token`, `password_reset_otp`, `mfa_enabled_notice`, `mfa_disabled_notice`, `mfa_reset_notice`, `email_change_notice`.
|
|
1499
|
+
|
|
1500
|
+
---
|
|
1501
|
+
|
|
1366
1502
|
## ποΈ Architecture
|
|
1367
1503
|
|
|
1368
1504
|
The package runs **inside** your NestJS application as a dynamic module β not as a separate service:
|
|
@@ -1789,6 +1925,12 @@ import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared
|
|
|
1789
1925
|
> (`auth.otp_invalid`) at one status (`401`) β a `429` on the ceiling would say the address was
|
|
1790
1926
|
> registered, since only a record that exists can reach one.
|
|
1791
1927
|
|
|
1928
|
+
> **A verification code that cannot be stored.** `POST /register` stores the code after the account is created, and
|
|
1929
|
+
> `POST /resend-verification` stores it before it sends. When the store refuses the write, both answer exactly as
|
|
1930
|
+
> they do when it succeeds, no email is sent (it would carry a code nothing holds), and one error line records
|
|
1931
|
+
> `[AUTH_OTP_STORE_FAILED] email_verification` and only the shape of the failure, never the address, the user id or text the store wrote. The user
|
|
1932
|
+
> asks for a new code through `POST /resend-verification`.
|
|
1933
|
+
|
|
1792
1934
|
> **When a password-reset request fails.** A failure that is the same for every address answers
|
|
1793
1935
|
> after the same timing floor as every other exit: `503` (`auth.service_unavailable`) when the
|
|
1794
1936
|
> resend-cooldown store cannot answer, `500` (`auth.internal`) for any other failure of it and for
|
|
@@ -1815,6 +1957,38 @@ import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared
|
|
|
1815
1957
|
| `@CurrentApiKey()` | Inject the verified key: `@CurrentApiKey() key: ApiKeyPrincipal` |
|
|
1816
1958
|
| `@SkipMfa()` | Skip MFA verification for this route |
|
|
1817
1959
|
|
|
1960
|
+
### Every other server export
|
|
1961
|
+
|
|
1962
|
+
Everything the server entry exports that the sections above do not describe. The row groups what the names are; the types and the contracts are in the code that exports them, and a spec keeps this list in step with `src/server/index.ts` both ways.
|
|
1963
|
+
|
|
1964
|
+
| Group | Exports | What they are |
|
|
1965
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1966
|
+
| Injection tokens | `BYMAX_AUTH_API_KEY_CLOCK`, `BYMAX_AUTH_API_KEY_REPOSITORY`, `BYMAX_AUTH_BREACH_CHECKER`, `BYMAX_AUTH_MEMBERSHIP_REPOSITORY`, `BYMAX_AUTH_OPTIONS`, `BYMAX_AUTH_PLATFORM_USER_REPOSITORY`, `BYMAX_AUTH_USER_REPOSITORY`, `BYMAX_AUTH_WORKSPACE_REPOSITORY` | Symbols you provide the options, the repositories, the breach checker and the API-key clock under. |
|
|
1967
|
+
| Option types | `AUTH_SECRET_MIN_LENGTH`, `AuthModuleAsyncOptions`, `BymaxAuthModuleOptions`, `BymaxAuthRateLimitOptions`, `ClientIpSource`, `RegistrationMode`, `ResolvedOptions`, `TenantResolverRequest`, `WorkspaceOptions`, `WorkspacePermissionOptions`, `WorkspaceRoleList` | The types of the module options, of the async registration and of the resolved options, and the minimum secret length. |
|
|
1968
|
+
| Crypto helpers | `decrypt`, `encrypt`, `generateSecureToken`, `hmacSha256`, `sha256`, `timingSafeCompare` | The `node:crypto` helpers the library itself uses, exported for hosts that must match them. |
|
|
1969
|
+
| Error catalogue | `AUTH_ERROR_MESSAGES`, `AuthErrorCode` | The default end-user message of each error code and the type of a code. |
|
|
1970
|
+
| OpenAPI | `AUTH_SECURITY_SCHEMES`, `AuthDocumentSecurityParams`, `AuthGuardFamily`, `OpenApiSecurityRequirement` | The security schemes and the helpers that describe which guard family protects a route. |
|
|
1971
|
+
| Hooks | `ApiKeyAccessEvent`, `ApiKeyDenyReason`, `BeforeRegisterResult`, `BeforeWorkspaceCreateResult`, `HookContext`, `NoOpAuthHooks`, `OAuthLoginResult` | The no-op implementation of the hooks and the types their arguments and results use. |
|
|
1972
|
+
| Request types | `AuthenticatedRequest`, `PlatformAuthenticatedRequest`, `WorkspaceRequest` | The request as the guards leave it, for the dashboard plane, the platform plane and the workspace. |
|
|
1973
|
+
| Results | `AuthResult`, `MfaChallengeResult`, `MfaSetupResult`, `OAuthMfaChallengeResult`, `PlatformAuthResult`, `RotatedTokenResult` | What the flows answer with: tokens, an MFA challenge, the platform result, a rotated token, the MFA setup. |
|
|
1974
|
+
| Email provider | `AUTH_EMAIL_KINDS`, `AuthEmailCatalogue`, `AuthEmailContext`, `AuthEmailKind`, `AuthEmailMessage`, `AuthEmailSink`, `DefaultAuthEmailProviderOptions`, `DeliveryErrorPolicy`, `DeliveryErrorPolicyMap`, `InviteData`, `NoOpEmailProvider`, `SessionAlertInfo`, `WorkspaceInviteData` | The bundled providers and the types of the messages, the catalogue, the sink and the delivery policy. |
|
|
1975
|
+
| Token payloads | `AuthPlane`, `MfaTempPayload`, `PlatformJwtPayload`, `RevocableTokenPayload`, `VerifiedAccessToken`, `VerifiedWorkspaceAccessToken`, `VerifyAccessTokenOptions`, `WorkspaceCheck` | The payloads of the tokens the library signs, the verified access token, the claims a revocation check reads, and the plane, the options and the workspace check of the verifier. |
|
|
1976
|
+
| OAuth | `OAuthProfile`, `OAuthProviderPlugin`, `OAuthService` | The plugin contract, the profile a plugin returns and the service that runs the flow. |
|
|
1977
|
+
| Platform repository | `AuthPlatformUser`, `IPlatformUserRepository`, `SafeAuthPlatformUser`, `UpdatePlatformMfaData` | The contract you implement for platform administrators and the types it exchanges. |
|
|
1978
|
+
| User repository types | `CreateUserData`, `CreateWithOAuthData`, `FindUserByEmailParams`, `FindUserByOAuthIdParams`, `LinkOAuthParams`, `SafeAuthUser`, `TenantScopedUserRef`, `UpdateEmailParams`, `UpdateEmailVerifiedParams`, `UpdateMfaData`, `UpdateMfaParams`, `UpdatePasswordParams`, `UpdateStatusParams` | The parameter and data types of the user repository you implement. |
|
|
1979
|
+
| Membership and workspace repositories | `ANY_WORKSPACE_MEMBER`, `AccountRemovalAudit`, `ActingMember`, `AuthMembership`, `AuthWorkspace`, `ChangeMembershipRoleParams`, `CountOwnedParams`, `CreateMembershipParams`, `CreateMembershipResult`, `CreateWorkspaceResult`, `CreateWorkspaceWithOwnerParams`, `GuardedWriteResult`, `LastActiveWorkspaceRef`, `ListMembershipsForUserParams`, `ListMembershipsForWorkspaceParams`, `ListSoleOwnedParams`, `MemberChangeResult`, `MembershipPage`, `MembershipRef`, `MembershipStatus`, `MembershipWithWorkspace`, `RemoveAllMembershipsParams`, `RemoveAllMembershipsResult`, `RemoveMembershipParams`, `RemovedMembership`, `RenameWorkspaceParams`, `RenameWorkspaceResult`, `SetLastActiveWorkspaceParams`, `TransferOwnershipParams`, `TransferOwnershipResult`, `UpdateWorkspaceStatusParams`, `UpdateWorkspaceStatusResult`, `WorkspaceActor`, `WorkspaceAuditEvent`, `WorkspaceRef`, `WorkspaceStatus` | The parameter, result and record types of the membership and workspace repositories, the acting member, and the any-member role marker. |
|
|
1980
|
+
| Password checkers | `AllowAllBreachChecker`, `CommonPasswordChecker`, `HibpBreachChecker`, `IPasswordBreachChecker`, `reduceToBaseWord` | The common-password screen, the breach checkers and the contract a breach checker implements. |
|
|
1981
|
+
| Guards and pipe | `AuthFieldError`, `AuthRateLimitGuard`, `RequestEncodingGuard` | The rate-limit and request-encoding guards and the shape of a field error the validation pipe returns. |
|
|
1982
|
+
| Decorator keys and types | `ALLOW_PENDING_WORKSPACE_KEY`, `AuthRateLimit`, `AuthRateLimitWindow`, `Authenticated`, `CurrentWorkspaceContext`, `IS_PUBLIC_KEY`, `PLATFORM_ROLES_KEY`, `ROLES_KEY`, `RequestEncoding`, `RequestEncodingPolicy`, `SKIP_MFA_KEY`, `WORKSPACE_PERMISSION_KEY`, `WORKSPACE_ROLES_KEY`, `WorkspaceAction` | Decorators not described above, the metadata keys behind the decorators and the types of their arguments. |
|
|
1983
|
+
| Request DTOs | `AcceptInvitationDto`, `ChangePasswordDto`, `CreateInvitationDto`, `ForgotPasswordDto`, `LoginDto`, `MfaChallengeDto`, `MfaDisableDto`, `MfaRegenerateRecoveryCodesDto`, `MfaVerifyDto`, `PlatformLoginDto`, `RegisterDto`, `ResendOtpDto`, `ResendVerificationDto`, `ResetPasswordDto`, `VerifyEmailDto`, `VerifyOtpDto` | The validated request bodies of the routes. |
|
|
1984
|
+
| Services | `AuthService`, `BruteForceService`, `EmailChangeService`, `InvitationService`, `MembershipService`, `MfaService`, `OtpService`, `PasswordResetService`, `PlatformAuthService`, `ReauthenticationService`, `SessionService`, `TokenDeliveryService`, `WorkspaceActionsService`, `WorkspaceCallerService`, `WorkspaceInvitationService`, `WorkspaceService`, `WsTicketService` | The services a host can inject to run a flow from its own code. |
|
|
1985
|
+
| Service parameter and response types | `BearerAuthResponse`, `BothAuthResponse`, `CookieAuthResponse`, `CreateSessionParams`, `ListSessionsParams`, `LiveSessionParams`, `PlatformBearerAuthResponse`, `RevokeAllExceptCurrentParams`, `RevokeAllSessionsParams`, `RevokeSessionParams`, `SessionInfo` | The parameters of the session service and the token-delivery responses. |
|
|
1986
|
+
| Metrics outcomes | `AUTH_PLANES`, `LOGIN_OUTCOMES`, `LoginOutcome`, `MFA_OUTCOMES`, `MfaOutcome`, `REFRESH_OUTCOMES`, `RefreshOutcome` | The closed sets of outcomes the login, MFA and refresh counters count, and the planes. |
|
|
1987
|
+
| WebSocket tickets | `WS_TICKET_TTL_SECONDS`, `WsTicketSnapshot` | The lifetime of a ticket and the snapshot a ticket stands for. |
|
|
1988
|
+
| Utilities | `describeError`, `hasRole`, `redactSecrets`, `sanitizeHeaders`, `sleep` | Small helpers the library uses and exports: error description with redaction, role check, header sanitising, sleep. |
|
|
1989
|
+
| API keys | `API_KEY_MAX_LABEL_LENGTH`, `ApiKeyClock`, `AuthApiKey`, `AuthApiKeySummary`, `IssueApiKeyInput`, `IssuedApiKey`, `RotateApiKeyInput` | The key records, the inputs to issue and rotate a key, the label limit and the clock. |
|
|
1990
|
+
| Workspace helpers and records | `AcceptedInvitation`, `AcceptedSignup`, `BootstrapInvitationRecord`, `FinalizeResult`, `MemberInvitationRecord`, `MembershipBumpFailedError`, `MyWorkspaces`, `ResolvedWorkspaceMember`, `ScheduledDeletion`, `SignupRequest`, `StoredWorkspaceInvitation`, `WORKSPACE_CURSOR_MAX_LENGTH`, `WORKSPACE_CURSOR_PART_MAX_LENGTH`, `WORKSPACE_ID_MAX_LENGTH`, `WORKSPACE_OWNER_ROLE_MAX_LENGTH`, `WorkspaceAccess`, `WorkspaceAccessView`, `WorkspaceInvitationPreview`, `WorkspaceInvitationView`, `WorkspaceJobContext`, `assertWorkspaceId`, `decodeWorkspaceCursor`, `decodeWorkspaceScopedName`, `encodeWorkspaceCursor`, `isWorkspaceOwnerRole`, `readWorkspacePosition`, `workspacePositionOf`, `workspaceQueryKey` | Helpers, limits, views, records and one error class of the workspace feature. |
|
|
1991
|
+
|
|
1818
1992
|
### React Hooks
|
|
1819
1993
|
|
|
1820
1994
|
| Hook | Returns |
|