@bymax-one/nest-auth 1.4.3 → 1.4.5

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/README.md CHANGED
@@ -170,8 +170,16 @@ import type {
170
170
  AuthUser,
171
171
  CreateUserData,
172
172
  CreateWithOAuthData,
173
+ FindUserByEmailParams,
174
+ FindUserByOAuthIdParams,
173
175
  IUserRepository,
174
- UpdateMfaData
176
+ LinkOAuthParams,
177
+ TenantScopedUserRef,
178
+ UpdateEmailParams,
179
+ UpdateEmailVerifiedParams,
180
+ UpdateMfaParams,
181
+ UpdatePasswordParams,
182
+ UpdateStatusParams
175
183
  } from '@bymax-one/nest-auth'
176
184
  import { PrismaService } from './prisma.service'
177
185
 
@@ -179,12 +187,13 @@ import { PrismaService } from './prisma.service'
179
187
  export class PrismaUserRepository implements IUserRepository {
180
188
  constructor(private readonly prisma: PrismaService) {}
181
189
 
182
- async findById(id: string, tenantId?: string): Promise<AuthUser | null> {
183
- const where = tenantId ? { id, tenantId } : { id }
184
- return this.prisma.user.findFirst({ where })
190
+ async findById({ id, tenantId }: TenantScopedUserRef): Promise<AuthUser | null> {
191
+ // Both halves of the key, always. An id is unique only within a tenant, so `findUnique`
192
+ // by id alone can answer with another tenant's row.
193
+ return this.prisma.user.findFirst({ where: { id, tenantId } })
185
194
  }
186
195
 
187
- async findByEmail(email: string, tenantId: string): Promise<AuthUser | null> {
196
+ async findByEmail({ email, tenantId }: FindUserByEmailParams): Promise<AuthUser | null> {
188
197
  return this.prisma.user.findUnique({
189
198
  where: { email_tenantId: { email: email.toLowerCase(), tenantId } }
190
199
  })
@@ -205,13 +214,15 @@ export class PrismaUserRepository implements IUserRepository {
205
214
  })
206
215
  }
207
216
 
208
- async updatePassword(id: string, passwordHash: string): Promise<void> {
209
- await this.prisma.user.update({ where: { id }, data: { passwordHash } })
217
+ // Every mutator below uses `updateMany` rather than `update`, for one reason: `update` takes a
218
+ // UNIQUE where-clause, so it cannot accept `{ id, tenantId }` unless your schema declares that
219
+ // pair unique — and `update({ where: { id } })` is the tenant-blind write this port exists to
220
+ // prevent. `updateMany` accepts the compound filter and touches nothing outside the tenant.
221
+ async updatePassword({ id, tenantId, passwordHash }: UpdatePasswordParams): Promise<void> {
222
+ await this.prisma.user.updateMany({ where: { id, tenantId }, data: { passwordHash } })
210
223
  }
211
224
 
212
- async updateMfa(id: string, tenantId: string | undefined, data: UpdateMfaData): Promise<void> {
213
- // Scoped by tenant, like findById: `updateMany` with both id and tenantId so an id shared
214
- // across tenants cannot cross the write onto the wrong account.
225
+ async updateMfa({ id, tenantId, data }: UpdateMfaParams): Promise<void> {
215
226
  await this.prisma.user.updateMany({
216
227
  where: { id, tenantId },
217
228
  data: {
@@ -222,35 +233,44 @@ export class PrismaUserRepository implements IUserRepository {
222
233
  })
223
234
  }
224
235
 
225
- async updateLastLogin(id: string): Promise<void> {
226
- await this.prisma.user.update({ where: { id }, data: { lastLoginAt: new Date() } })
236
+ async updateLastLogin({ id, tenantId }: TenantScopedUserRef): Promise<void> {
237
+ await this.prisma.user.updateMany({
238
+ where: { id, tenantId },
239
+ data: { lastLoginAt: new Date() }
240
+ })
227
241
  }
228
242
 
229
- async updateStatus(id: string, status: string): Promise<void> {
230
- await this.prisma.user.update({ where: { id }, data: { status } })
243
+ async updateStatus({ id, tenantId, status }: UpdateStatusParams): Promise<void> {
244
+ await this.prisma.user.updateMany({ where: { id, tenantId }, data: { status } })
231
245
  }
232
246
 
233
- async updateEmailVerified(id: string, verified: boolean): Promise<void> {
234
- await this.prisma.user.update({ where: { id }, data: { emailVerified: verified } })
247
+ async updateEmailVerified({ id, tenantId, verified }: UpdateEmailVerifiedParams): Promise<void> {
248
+ await this.prisma.user.updateMany({
249
+ where: { id, tenantId },
250
+ data: { emailVerified: verified }
251
+ })
235
252
  }
236
253
 
237
- async updateEmail(id: string, email: string): Promise<void> {
238
- await this.prisma.user.update({ where: { id }, data: { email: email.toLowerCase() } })
254
+ async updateEmail({ id, tenantId, email }: UpdateEmailParams): Promise<void> {
255
+ await this.prisma.user.updateMany({
256
+ where: { id, tenantId },
257
+ data: { email: email.toLowerCase() }
258
+ })
239
259
  }
240
260
 
241
- async findByOAuthId(
242
- provider: string,
243
- providerId: string,
244
- tenantId: string
245
- ): Promise<AuthUser | null> {
261
+ async findByOAuthId({
262
+ provider,
263
+ providerId,
264
+ tenantId
265
+ }: FindUserByOAuthIdParams): Promise<AuthUser | null> {
246
266
  return this.prisma.user.findFirst({
247
267
  where: { oauthProvider: provider, oauthProviderId: providerId, tenantId }
248
268
  })
249
269
  }
250
270
 
251
- async linkOAuth(userId: string, provider: string, providerId: string): Promise<void> {
252
- await this.prisma.user.update({
253
- where: { id: userId },
271
+ async linkOAuth({ id, tenantId, provider, providerId }: LinkOAuthParams): Promise<void> {
272
+ await this.prisma.user.updateMany({
273
+ where: { id, tenantId },
254
274
  data: { oauthProvider: provider, oauthProviderId: providerId }
255
275
  })
256
276
  }
@@ -281,10 +301,76 @@ Email delivery is fully delegated to the consumer — the library never imports
281
301
  > [!WARNING]
282
302
  > Any user-supplied value (display name, tenant name, inviter name) interpolated into HTML email bodies MUST be escaped to prevent stored XSS in notification content. Tokens and OTPs are library-generated and safe, but `inviterName`, `tenantName`, device strings, and any consumer-supplied placeholder are attacker-controllable.
283
303
 
304
+ > [!CAUTION]
305
+ > **Never log the error your transport rejects with — it can contain the code you just sent.**
306
+ > A policy, DLP or anti-spam relay answering `550` commonly **quotes the offending message body**,
307
+ > so the error your `send()` throws carries the OTP or token this library rendered into it. Logging
308
+ > that error, or attaching it as a `cause` to one you log, puts a working credential into your log
309
+ > pipeline in clear text until it expires. Measured on a real relay, not hypothesised.
310
+ >
311
+ > This is your half: the library cannot reach inside your provider implementation.
312
+ > **`describeChannelStatus` is exported for it** — the same helper the bundled provider uses on
313
+ > every one of its own log lines, so you get the whole treatment rather than just redaction:
314
+ >
315
+ > ```typescript
316
+ > import { describeChannelStatus } from '@bymax-one/nest-auth'
317
+ >
318
+ > async sendPasswordResetOtp(tenantId: string, email: string, otp: string): Promise<void> {
319
+ > try {
320
+ > await this.resend.emails.send({ /* ... */ })
321
+ > } catch (error: unknown) {
322
+ > // Never `logger.error(msg, error)` here, and never `new Error(msg, { cause: error })`
323
+ > // into something that logs — both carry the quoted body.
324
+ > this.logger.error(`reset OTP delivery failed: ${describeChannelStatus(error)}`)
325
+ > throw error
326
+ > }
327
+ > }
328
+ > ```
329
+ >
330
+ > Two functions, not one with a mode: which one you call IS the decision, and there is no
331
+ > permissive default to inherit by forgetting.
332
+ >
333
+ > **`describeChannelStatus(error)` wherever the body rendered something you would withhold.** It
334
+ > takes no secrets, and that is the guarantee rather than an omission — nothing the channel wrote
335
+ > is published, so there is nothing to name. Redaction alone does not close this, and neither does
336
+ > a length cap. A relay may quote the body it rejected in transfer encoding rather
337
+ > than verbatim; base64 is the ordinary case and defeats both at once — substring matching finds
338
+ > nothing because the credential's characters are not in the line, and the cap does not help
339
+ > because the encoding runs from the body's first byte, so the code is in the first sentence.
340
+ > Measured: a reset-code body is 96 base64 characters end to end, and the first 200 characters of
341
+ > the line decode straight back to the OTP. Under `describeChannelStatus` NOTHING the channel wrote
342
+ > reaches the line — not the message, not the `name`, not a status parsed off the front. Each of
343
+ > those was tried and each fell: shape validation admits `MTIzNDU2`, the base64 of OTP `123456`;
344
+ > and a status grammar admits `424-242`, an OTP grouped, publishing `424`. What you keep is which
345
+ > message failed. What you lose is the transient-versus-permanent split, which your mail provider's
346
+ > dashboard has and this library does not.
347
+ >
348
+ > **`describeError(error, [values])` for errors whose text you have a reason to trust**, where the
349
+ > values you name appear the way you wrote them and redaction reaches them. The bundled provider
350
+ > uses it nowhere — every one of its paths uses the opaque form, including the notices that
351
+ > render nothing secret, because a relay may re-encode whatever it quotes and the recipient address
352
+ > is in the message either way. If you can say the same about your channel, prefer
353
+ > `describeChannelStatus` and keep this one for strings you built yourself.
354
+ >
355
+ > Neither reads `stack`, and neither reads the transport's own fields — nodemailer hangs the
356
+ > server's full reply on `response`. Beyond that they differ, and the difference is the point:
357
+ > `describeError` reads `name` and `message`, strips the values you named, caps the length and
358
+ > removes control characters so a relay cannot forge extra records in a line-oriented pipeline.
359
+ > `describeChannelStatus` reads **neither** — the only thing it touches is `cause`, walked to count
360
+ > the links. Both walk that chain and never throw, whatever the transport's error does.
361
+ >
362
+ > `redactSecrets(text, [otp])` is exported too, for a string you built yourself and know contains
363
+ > the literal value. It is **not** a substitute for either description on a transport's error: a
364
+ > substring match cannot see through an encoding, which is the whole reason the bundled provider
365
+ > stopped relying on it.
366
+ >
367
+ > If you use the bundled `DefaultAuthEmailProvider` with `onDeliveryError: 'rethrow'`, the error it
368
+ > re-throws is the channel's original and is still yours to contain the same way.
369
+
284
370
  ```typescript
285
371
  // email.provider.ts
286
372
  import { Injectable } from '@nestjs/common'
287
- import type { IEmailProvider, InviteData, SessionInfo } from '@bymax-one/nest-auth'
373
+ import type { IEmailProvider, InviteData, SessionAlertInfo } from '@bymax-one/nest-auth'
288
374
  import { Resend } from 'resend'
289
375
 
290
376
  const escapeHtml = (s: string): string =>
@@ -344,6 +430,13 @@ export class ResendEmailProvider implements IEmailProvider {
344
430
  })
345
431
  }
346
432
 
433
+ // The library does NOT await the three MFA notices — by the time one is sent the factor is
434
+ // already enabled or removed, so a bounced notice must not answer the caller with an error for
435
+ // an operation that succeeded. The consequence is here: an inline send like this one can be
436
+ // lost to a process shutdown or a serverless freeze arriving between the response and the send
437
+ // completing. Where these alerts matter — the administrative reset most of all, since it is what
438
+ // makes a support-desk takeover detectable — enqueue durably and resolve instead of sending
439
+ // inline. Awaiting would not fix it either: a freeze mid-await loses the notice AND the response.
347
440
  async sendMfaEnabledNotification(
348
441
  _tenantId: string,
349
442
  email: string,
@@ -373,7 +466,7 @@ export class ResendEmailProvider implements IEmailProvider {
373
466
  async sendNewSessionAlert(
374
467
  _tenantId: string,
375
468
  email: string,
376
- sessionInfo: SessionInfo,
469
+ sessionInfo: SessionAlertInfo,
377
470
  _locale?: string
378
471
  ): Promise<void> {
379
472
  await this.client.emails.send({
@@ -863,10 +956,9 @@ All options are configurable via `registerAsync()`. Here are the key configurati
863
956
  >
864
957
  > Status is resolved per request or not at all: mount `UserStatusGuard` on the route, and for
865
958
  > anything richer read the account **tenant-scoped**, the way that guard does —
866
- > `findById(request.user.sub, request.user.tenantId)`. The tenant argument is not optional in
867
- > practice: ids may collide across tenants, and `findById` accepts an absent tenant only for
868
- > flows that are deliberately cross-tenant, so dropping it here can resolve another tenant's
869
- > account. That is what the library's own guards do, which
959
+ > `findById({ id: request.user.sub, tenantId: request.user.tenantId })`. The tenant argument is required by the
960
+ > port and cannot be dropped: ids may collide across tenants, so a lookup by bare id can resolve
961
+ > another tenant's account. That is what the library's own guards do, which
870
962
  > is why the claim can be left as it is. `mfaVerified` behaves the same way and for the same
871
963
  > reason — it is always `false` after a rotation, so step-up does not survive a refresh and a
872
964
  > user re-acquires it through the MFA challenge.
@@ -1205,6 +1297,18 @@ The four names — `bymaxAuthAccessCookie`, `bymaxAuthAccessBearer`, `bymaxAuthR
1205
1297
  `bymaxPlatformAccessBearer` — are stable identifiers. Renaming one is a break a generated client
1206
1298
  feels, so they will not change; their **definitions** are config-derived.
1207
1299
 
1300
+ Import them rather than spelling them. A platform-only deployment guarding its own routes with
1301
+ `JwtAuthGuard` has to declare the dashboard access scheme itself — the fragment will not, because
1302
+ `schemesFor` gates dashboard schemes on what you mounted — and a hand-written literal in a section
1303
+ about literals drifting from configuration is the wrong instruction:
1304
+
1305
+ ```typescript
1306
+ import { AUTH_SECURITY_SCHEMES } from '@bymax-one/nest-auth'
1307
+
1308
+ // [{ bymaxAuthAccessCookie: [] }], spelled by the package that owns the name
1309
+ const security = [{ [AUTH_SECURITY_SCHEMES.accessCookie]: [] }]
1310
+ ```
1311
+
1208
1312
  > **This package does not depend on `@bymax-one/nest-core`** — not as a dependency, a peer, or a
1209
1313
  > devDependency. The contract revision is inlined, the discovery marker is the documented string
1210
1314
  > literal, and a gate fails the build if any file here imports another Bymax library. That keeps
@@ -1242,6 +1346,212 @@ nest-core's policy. So a stale scheme name or an override for an auth route keep
1242
1346
  contributed one never lands — the document goes on describing whatever you wrote when you wrote
1243
1347
  it, including cookie names you have since changed.
1244
1348
 
1349
+ > **Delete the entries for THESE routes. Keep your document-level `security`.** They are usually
1350
+ > written in the same options block, and taking the block out is the failure this warning exists
1351
+ > for — reported by a consumer who ran the comparison below and found their document **more wrong
1352
+ > after adopting than before**. The mechanism is in `augmentOperation`: an operation with no
1353
+ > requirement of its own, no override and no fragment falls through to `ownRouteSecurity`, which
1354
+ > answers `undefined` for anything that is not a route nest-core answers for itself — the health
1355
+ > probes, and from **nest-core 1.5.3** an unprotected metrics endpoint (through 1.5.2 metrics was
1356
+ > not among them). So **your** guarded routes carry no requirement and inherit the document
1357
+ > default. Remove that default and every one of those routes reads as needing no credential.
1358
+ >
1359
+ > **Keep the condition attached, because it decides how much of your API is affected.** This
1360
+ > reaches the routes that state nothing of their own — no `@ApiSecurity`-style decorator feeding
1361
+ > the scanned operation, no entry in nest-core's `operationSecurity`, and not a route nest-core
1362
+ > answers for itself. Anything carrying its own requirement outranks the document default and is
1363
+ > untouched, which is exactly why the fix works at all. If your backend annotates every guarded
1364
+ > route individually, this note does not apply to you; the reason it bit two consumers is that
1365
+ > annotating each route is the thing a document-level default exists to avoid.
1366
+ >
1367
+ > **nest-core's own routes are the exception that still moves.** It emits an explicit `security: []`
1368
+ > for the health probes — and, from 1.5.3, for a metrics endpoint left unprotected — but only when
1369
+ > the **served document actually carries a non-empty top-level `security`**, whether that came from
1370
+ > `openapi.security` or was already on the generated document handed to nest-core.
1371
+ > Remove the default and the `[]` goes with it. Write the default as an explicit empty list and
1372
+ > nothing is being overridden, so the member stays absent either way.
1373
+ >
1374
+ > (Through 1.5.2 that condition read `openapi.security.length > 0` alone, which answered `false`
1375
+ > for a document that carried its own default without one being configured — so those routes
1376
+ > inherited a credential nest-core does not check. If you build the document yourself rather than
1377
+ > handing the default to `openapi.security`, that is your shape, and 1.5.3 is the fix.)
1378
+ >
1379
+ > **On nest-core below 1.5.0, nothing reports this.** No error, no unmatched key, no failing
1380
+ > build — the document simply stops asking for credentials on the routes the library never knew
1381
+ > about, which are the ones your backend owns. **nest-core 1.5.0 warns**, on exactly this shape:
1382
+ > a document with no top-level `security` where some other operation does state a requirement, so
1383
+ > the bare ones are bare against a described posture rather than in a document that describes
1384
+ > none. It names the operations and never throws. That makes the failure visible, not impossible —
1385
+ > a warning in a build log is still something a person has to read.
1386
+ >
1387
+ > Keep the default, and **derive it rather than writing a literal**. Since 1.4.4 the derivation
1388
+ > ships, so the common case is one call rather than a rule you apply by hand:
1389
+ >
1390
+ > ```ts
1391
+ > import { authDocumentSecurity } from '@bymax-one/nest-auth'
1392
+ >
1393
+ > BymaxCoreModule.forRoot({
1394
+ > openapi: {
1395
+ > // `tokenDelivery` here is the SAME value you pass to BymaxAuthModule.forRoot — read it from
1396
+ > // one place. A default derived from a second copy drifts exactly like a literal does.
1397
+ > security: authDocumentSecurity({ guard: 'dashboard', tokenDelivery })
1398
+ > }
1399
+ > })
1400
+ > ```
1401
+ >
1402
+ > It answers the delivery axis of both questions below — the scheme name for your guard family,
1403
+ > and the two-entry alternation under `'both'` that a hand-written default usually collapses into
1404
+ > a single AND entry. **It does not know what you mounted**, which is the third row of the table
1405
+ > in question 2 and the one case you still have to answer yourself. Read on for that, and for why
1406
+ > the recipe takes two questions rather than one:
1407
+ >
1408
+ > **1. Which guard protects your own routes?** That decides the credential family, and
1409
+ > `tokenDelivery` does not enter into it for one of them.
1410
+ >
1411
+ > - `JwtAuthGuard` (the dashboard family) → an access scheme, chosen by delivery. Go to question 2.
1412
+ > - `JwtPlatformGuard` → **`bymaxPlatformAccessBearer`, in every mode**. `extractPlatformAccessToken`
1413
+ > reads the `Authorization` header whatever `tokenDelivery` says, and `schemesFor` declares that
1414
+ > scheme with no delivery condition on it. A platform-guarded route wants it under `cookie`
1415
+ > delivery exactly as much as under `bearer`.
1416
+ > - **Both, on different routes** → the default cannot express this, though not because it is
1417
+ > limited to one entry. A document `security` array may hold both requirements — but the entries
1418
+ > are **alternatives**, and the whole array applies to every operation that inherits it. Listing
1419
+ > both therefore documents each credential as valid for _either_ family, which says your platform
1420
+ > routes accept a member token. That is not a missing detail; it is a false statement about who
1421
+ > can call what. Give the minority family per-operation `security` (via your own decorator or
1422
+ > nest-core's `operationSecurity`) and let the default cover the majority.
1423
+ >
1424
+ > **2. For the dashboard family — which schemes does this deployment actually declare?** Delivery
1425
+ > decides, and so does what you mounted. Take a default written as `[{ bymaxAuthAccessCookie: [] }]`:
1426
+ >
1427
+ > | deployment | this contributor declares | that literal default |
1428
+ > | -------------------------------------- | --------------------------------- | ----------------------------------------------------------- |
1429
+ > | dashboard mounted, `cookie` | the cookie scheme only | correct |
1430
+ > | dashboard mounted, `both` | the cookie **and** bearer schemes | resolves, but describes only one of the two channels |
1431
+ > | dashboard mounted, `bearer` | no cookie scheme at all | names an undeclared scheme — `assertSchemesDeclared` throws |
1432
+ > | **no dashboard surface, any delivery** | **neither dashboard scheme** | names an undeclared scheme — throws, `cookie` included |
1433
+ >
1434
+ > That last row is the one a delivery-only recipe gets wrong, and **"no dashboard surface" is
1435
+ > wider than it first sounds.** `schemesFor` gates both dashboard schemes on one of `auth`,
1436
+ > `passwordReset`, `mfa`, `sessions`, `invitations` or `emailChange` being registered. `oauth` is
1437
+ > **not** in that list — its operations are public and reference no credential — so an OAuth-only
1438
+ > deployment contributes operations and zero schemes, exactly like a platform-only one. Any
1439
+ > deployment with no dashboard controller is in this row, and `cookie` delivery, which the recipe
1440
+ > would call the safe case, throws just as hard as `bearer`.
1441
+ >
1442
+ > **And that row needs a remedy, not just a warning, because these deployments are legitimate.**
1443
+ > `JwtAuthGuard` is registered and exported unconditionally — it is not gated on any controller
1444
+ > flag — so mounting no dashboard controller does **not** stop you from guarding your own routes
1445
+ > with a dashboard access token. Both shapes are real: the platform surface plus your own routes
1446
+ > on the member credential; or the OAuth surface alone, where sign-in happens through a provider
1447
+ > and your app issues member tokens itself. In each case the guard is available and the scheme
1448
+ > describing it is not. Deriving correctly there lands you on "the scheme I need does not exist",
1449
+ > which is an accurate answer and not a usable
1450
+ > one.
1451
+ >
1452
+ > **Declare it yourself, in your own `openapi.securitySchemes`.** This is the one case where
1453
+ > "delete your hand-written `securitySchemes`" has an exception, and the exception exists because
1454
+ > the contributor deliberately declares only what its own operations reference — defining a
1455
+ > dashboard scheme on a deployment with no dashboard operation would put an unreferenced
1456
+ > credential in every such document, which is the opposite error and the reason for the gate.
1457
+ >
1458
+ > **Which scheme you declare is still a function of delivery** — the exception is to the deletion
1459
+ > rule, not to the derivation rule, and writing one fixed definition here reintroduces the very
1460
+ > literal this section is about:
1461
+ >
1462
+ > - `cookie` → the `apiKey`-in-cookie definition, carrying the `cookies.accessTokenName` you
1463
+ > configured. The cookie name is yours to choose, so this is the one that must match what the
1464
+ > server actually reads.
1465
+ > - `bearer` → the HTTP bearer definition. There is no cookie name to carry.
1466
+ > - `both` → **both of them**, or your document is incomplete in exactly the quiet way described
1467
+ > above.
1468
+ >
1469
+ > One note on doing any of it: **`AUTH_SECURITY_SCHEMES` is exported from the package entry**, so
1470
+ > import the names rather than writing `bymaxAuthAccessCookie` and `bymaxAuthAccessBearer` as
1471
+ > string literals. The compiler then checks the PROPERTY you reach for, so a typo is a build
1472
+ > error rather than a document declaring a scheme nothing defines — and if a scheme's identifier
1473
+ > is ever renamed, your document carries the new one instead of a literal that has quietly gone
1474
+ > stale. Renaming the value is not itself a build error, since `AUTH_SECURITY_SCHEMES.accessCookie`
1475
+ > stays valid and only its string changes; that is precisely why importing beats copying.
1476
+ >
1477
+ > **The wrong outcomes are not one failure, and the difference is the point.** Where the scheme
1478
+ > does not exist, nest-core's `assertSchemesDeclared` **throws** and the document never builds —
1479
+ > loud, immediate, impossible to ship. Under `both` the scheme does exist, so nothing throws; the
1480
+ > default is merely **incomplete**, telling a reader that your own routes take a cookie when they
1481
+ > equally accept a bearer token. That one is quiet, and it is the same class of quiet as the bug
1482
+ > this whole note is about. A literal written against a bearer-only deployment inverts the table
1483
+ > and fails under `cookie` for the same reasons.
1484
+ >
1485
+ > So the advice that fixes a silently wrong document can introduce a loud broken one **or a second
1486
+ > quiet one**, depending on where you land. Derive from the same inputs the contributor reads —
1487
+ > the guard your routes use, your delivery mode, and the controllers you registered — and the
1488
+ > answer is right everywhere at once, instead of correct in one configuration and checked forever.
1489
+ >
1490
+ > The default is what covers your routes, and it cannot disturb this library's: a per-operation
1491
+ > requirement outranks a document-level one, and every operation the contributor describes carries
1492
+ > its own.
1493
+ >
1494
+ > **What an empty `{}` alternative says, and where this library uses it as an approximation.**
1495
+ > In OpenAPI it means one thing: authentication is **optional** for that operation — a caller
1496
+ > presenting none of the named schemes is valid. Tooling reads it as anonymous access and infers
1497
+ > nothing about a request body from it.
1498
+ >
1499
+ > On `logout` that is exactly right, in **every** delivery mode including `cookie`: the operation
1500
+ > really does answer a caller who presents nothing, which is why a user whose access token
1501
+ > expired can still sign out. How many alternatives you see depends on the mode, since each one
1502
+ > is a combination of the credentials that mode actually has:
1503
+ >
1504
+ > | operation | `cookie` | `bearer` | `both` |
1505
+ > | ----------------- | -------- | -------- | ------ |
1506
+ > | `logout` | 4 | 2 | 6 |
1507
+ > | `password/change` | 2 | 1 | 4 |
1508
+ >
1509
+ > On `refresh` under `tokenDelivery: 'both'` it is an **approximation, and a permissive one**.
1510
+ > That operation refuses a caller with no credential at all; the token may simply arrive in the
1511
+ > request body, which `security` has no vocabulary for. The empty entry is what lets the document
1512
+ > describe the body-only caller, and the cost is that it also tells tooling anonymous access is
1513
+ > acceptable when it is not.
1514
+ >
1515
+ > The `requestBody` beside it **documents the body channel; it does not carry the requirement**.
1516
+ > Under `'both'` it is `required: false` and its schema does not list `refreshToken` as required,
1517
+ > because either channel satisfies the server and a body that omits the token is valid when the
1518
+ > cookie carries it. So the document as a whole permits a request with neither, and the server
1519
+ > refuses that request. **OpenAPI cannot express "one of these two channels" across a security
1520
+ > requirement and a request body**, and this is the shape of that limitation rather than an
1521
+ > oversight. Under `'bearer'`, where the cookie does not exist, the body becomes required at both
1522
+ > levels and the document is exact.
1523
+ >
1524
+ > Written out because two earlier versions of this note were wrong in opposite directions: one
1525
+ > called `{}` "a credential this member cannot model", which is the intent rather than the
1526
+ > notation; the other claimed the `requestBody` carried the requirement, which it does not.
1527
+ >
1528
+ > **Verify with a diff, not by reasoning.** Render the document with the contributor active and
1529
+ > again with your entries in place, and compare only the operations you mount. The consumer who
1530
+ > did this found their own three differences were improvements — a configured cookie name over
1531
+ > the exported default, `logout` gaining the access-only and refresh-only alternatives their map
1532
+ > called unsatisfiable — and one regression that no status-code probe could have surfaced,
1533
+ > because the routes it broke still answered correctly at runtime.
1534
+ >
1535
+ > **And there is one shape no warning will catch for you, however new your nest-core.** If you
1536
+ > remove _every_ requirement at once — no library describing anything, no decorator, no override,
1537
+ > no document default — what remains is indistinguishable from the document of an API that is
1538
+ > public on purpose. Both are a set of operations that ask for nothing. **No general-purpose tool** can separate the two from the rendered document alone
1539
+ > without also shouting at every genuinely public API, which is how a warning earns the right to
1540
+ > be ignored. This is why nest-core's warning requires that _some_ operation still state a
1541
+ > requirement: the gap is deliberate, not an omission, and no version closes it.
1542
+ >
1543
+ > **But it is a limit on document-only checks, not on you** — and the distinction matters, because
1544
+ > the better answer is the one a general-purpose tool cannot supply. **You** know your API is not
1545
+ > public, which is exactly the intent no renderer can recover, so write it down as an assertion in
1546
+ > your own suite: that the built document carries a top-level `security`, or that every route
1547
+ > behind your auth guard renders with some requirement. That is a standing check, it runs on every
1548
+ > commit, and it does not depend on anyone remembering to compare. Prefer it to the diff.
1549
+ >
1550
+ > Render the document twice and compare when you are **changing** this — adopting the contributor,
1551
+ > moving delivery mode, adding a surface — because a diff shows you what moved without your having
1552
+ > to predict it in advance. Then turn what you learned into the assertion, so the next change is
1553
+ > caught rather than inspected.
1554
+
1245
1555
  **That chain is about `security` alone, and the other members run the opposite rule** — worth
1246
1556
  stating because generalising either one produces a wrong belief about the other. There is no
1247
1557
  configuration channel for a `description`, a `summary` or a tag: `mergeFragment` merges the
@@ -1336,6 +1646,56 @@ disputable. Idempotent; throws for an id that resolves to nobody, so a typo cann
1336
1646
  > `MfaService` is only registered when `controllers.mfa` or `controllers.platform` is on —
1337
1647
  > otherwise add it to `extraProviders` to inject it.
1338
1648
 
1649
+ ### Checking revocation outside a guard — `AuthRevocationService`
1650
+
1651
+ The three JWT guards do not decide revocation themselves; they delegate to one service, and that
1652
+ service is exported so **you can consult the same two channels from a transport the guards never
1653
+ see** — a WebSocket, an SSE stream, a message consumer. Without it there is no way to ask the
1654
+ question at all outside an HTTP request: a connection whose user logs out keeps its stream until
1655
+ the access token expires, while that user's HTTP calls are refused at once.
1656
+
1657
+ ```ts
1658
+ import { AuthRevocationService } from '@bymax-one/nest-auth'
1659
+
1660
+ const revoked = await this.revocation.isAccessTokenRevoked(
1661
+ { jti: payload.jti, sub: payload.sub, epoch: payload.epoch, tenantId: payload.tenantId },
1662
+ 'dashboard'
1663
+ )
1664
+ ```
1665
+
1666
+ It is registered and exported unconditionally, so it is injectable wherever `BymaxAuthModule` is
1667
+ imported — no `extraProviders` entry and no controller flag to turn on.
1668
+
1669
+ > [!IMPORTANT]
1670
+ > **On the dashboard plane you must forward `tenantId` from the verified token.** It is optional
1671
+ > on `RevocableTokenPayload` because the platform plane genuinely has none — its admins are
1672
+ > cross-tenant — so **`tsc` will not catch the omission**, and a dashboard payload without it is
1673
+ > treated as **revoked** without a store read, with a `warn` naming the missing field.
1674
+ >
1675
+ > Failing closed is deliberate. The epoch key derives from the tenant-scoped subject, so an absent
1676
+ > tenant names a keyspace belonging to no tenant, where nothing has ever been bumped: the read
1677
+ > would answer `0`, `stamped < 0` is false for every token, and a bulk-revoked token would be
1678
+ > reported **valid**. A revocation check that fails open on malformed input is worse than no check.
1679
+ >
1680
+ > **Recognise the symptom, because it does not look like an auth bug.** The refusal answers the
1681
+ > same `true` a genuinely revoked token answers, throws nothing and emits no event — so a
1682
+ > transport that gates a stream on it simply registers nothing. Measured on a consumer's realtime
1683
+ > bridge: the SSE handshake answered `200` and the connection registry stayed at `count: 0`.
1684
+ > Declaring the tenant **required** on your own port type is the stronger fix, because it turns the
1685
+ > next occurrence into a compile error rather than a log line.
1686
+
1687
+ **What this method is and is not.** It answers two channels at the moment you call it: the
1688
+ per-token blacklist and the user's token epoch. It reads no `exp`, holds no subscription, emits no
1689
+ event, and knows nothing about account status, roles, tenant binding or the identity plane. It is
1690
+ therefore **one check among the many a guarded HTTP route performs**, and not a substitute for
1691
+ them.
1692
+
1693
+ Using it to authorise a long-lived transport — a WebSocket, an SSE stream — takes more than this
1694
+ method, and this library does not yet export the pieces that would make that safe. See
1695
+ [#172](https://github.com/bymaxone/nest-auth/issues/172), which records what a stream must
1696
+ establish beyond revocation, the gaps that make each one consumer-built today, and the library
1697
+ changes that would close them.
1698
+
1339
1699
  ### Server Guards
1340
1700
 
1341
1701
  | Guard | Decorator | Purpose |
@@ -1462,8 +1822,19 @@ chosen at the throw site — `AuthException` takes no status argument. A client
1462
1822
  | `429` | `auth.account_locked` · `auth.too_many_requests` |
1463
1823
  | `500` | `auth.internal` |
1464
1824
 
1465
- `AUTH_ERROR_STATUS` is exported if you need the mapping at runtime — for a typed client, an
1466
- API document, or a test that asserts against it.
1825
+ `AUTH_ERROR_STATUS` ships from `@bymax-one/nest-auth/shared`, beside `AUTH_ERROR_CODES`, if you
1826
+ need the mapping at runtime — for a typed client, an API document, or a test that asserts against
1827
+ it:
1828
+
1829
+ ```ts
1830
+ import { AUTH_ERROR_CODES, AUTH_ERROR_STATUS } from '@bymax-one/nest-auth/shared'
1831
+ ```
1832
+
1833
+ Shown as an import rather than described, on purpose: this package's README contract test reads
1834
+ import statements, so a symbol that stops being exported from the subpath named here fails the
1835
+ suite. It scans prose too — for scheme names it invented and for claims that something is not
1836
+ public — but it cannot check a sentence that merely _says_ where a symbol ships from. That claim
1837
+ went one release stated and unenforced.
1467
1838
 
1468
1839
  > **Assert your fixtures against the catalogue, not against string literals.** `AUTH_ERROR_CODES`
1469
1840
  > is exported from `@bymax-one/nest-auth/shared` so a suite can check that every code it branches