@bymax-one/nest-auth 1.5.15 → 1.5.16

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 CHANGED
@@ -18,6 +18,41 @@ what moves, and that note is the compatibility contract until strict SemVer begi
18
18
 
19
19
  ## [Unreleased]
20
20
 
21
+ ## [1.5.16] - 2026-11-25
22
+
23
+ A patch release.
24
+
25
+ ### Fixed
26
+
27
+ - **A key planted on `Object.prototype` after the module started is not an OAuth option.** The group of the OAuth providers and each provider were rebuilt after the resolved options had been copied without a prototype, so they inherited the root object again: a planted `errorRedirectUrl` sent the browser of a failed callback to an address the host never wrote. The resolved options are copied once more at the end, and the OAuth start and callback refuse with `auth.internal` while the root object holds a planted entry.
28
+ - **A planted key does not decide whether an expiry is ignored, or which attributes a cookie carries.** The flag that lets a verification ignore the expiry is read by own key, after the guard; the cookie options carry an own `httpOnly`, `secure`, `sameSite`, `path` and `maxAge`, so a cookie the library writes with none of them (the access cookie is cleared with none) does not pick one up. Two limits remain: `express` removes `maxAge` from its copy in `clearCookie`, and the sign options `keyid` and `notBefore` have no neutral value (the schema of `jsonwebtoken` refuses an own `undefined`), so for those two the guard is what refuses.
29
+ - **A polluted process answers 500, not 401.** The refusal of the guard passes through the access guards, the token verifier and the temporary token of the second factor as `auth.internal`, so an operator sees the fault and a client does not read every session as invalid.
30
+ - **The root guard and the verify and sign paths do not call a live built-in.** A flaw that can plant a key can also replace a built-in after the module loaded, and a check that called the live one was blinded. `Object.hasOwn`, `Object.getPrototypeOf`, `Object.getOwnPropertyDescriptor`, `Object.create`, `Object.assign`, `Reflect.ownKeys`, `Reflect.get` and `Error` are taken when the module loads, and the guard no longer uses the array iterator, `Map`, `Set` or the array methods. The refusal is recognised by a mark of its own and not by `instanceof`. The refusal itself is built once when the module loads, so an accessor planted under a name an exception assigns (`response`, `status`, `options`, `message`, `name`, `cause`) cannot turn building it into a `TypeError`. When the root already held such an accessor at load, the refusal is made without running the constructor, so the import still never throws. The `node:crypto` primitives the library compares, hashes and generates with (`timingSafeEqual`, `createHmac`, `createHash`, `randomBytes`, `randomInt`, `randomUUID`, the ciphers and `scrypt`) are taken once, in one module, and a method of `node:crypto` replaced afterwards changes nothing they compute. `jwa` reads `crypto.timingSafeEqual` and `crypto.createHmac` at each call inside `verify`, so a replaced one verified a forged administrator token; the functions the JWT libraries read from `node:crypto` (found by a spec that reads the installed `jsonwebtoken`, `jws` and `jwa`), `JwtService.prototype.sign` and `verify`, `Reflect.getMetadata`, the methods of `Reflector` and the `update`, `digest`, `sign` and `verify` methods of the `Hash`, `Hmac`, `Sign`, `Verify`, `Cipheriv` and `Decipheriv` objects (the library's own digests and ciphers and the ones `jwa` calls), and every built-in the JWT chain reads (`JSON.parse`, which `jws` uses to decode a payload after the signature was checked, `JSON.stringify`, `Buffer`, `Object`, `Math`), are now recorded and compared by a set that a test derives from the installed packages, together with the protocol the language dispatches through without a source naming it (the symbol-keyed functions of `RegExp.prototype`, the iterators, `Symbol.toPrimitive`, the flag accessors of a regular expression, a symbol key added to one of those prototypes, a symbol key planted on `Object.prototype`, and the `Symbol.species` accessor and the `constructor` of the prototypes of the `Array`, `ArrayBuffer`, `Map`, `RegExp`, `Set`, typed-array, `Buffer` and `Uint8Array` classes, which every `map`, `filter` and `slice` reads); the exports of `jsonwebtoken`, `jws` and `jwa` are third-party code and are not. The guards that decide (`RolesGuard`, `PlatformRolesGuard`, `MfaRequiredGuard`, `SelfOrAdminGuard`, `JwtAuthGuard`, `JwtPlatformGuard`, `ApiKeyGuard`, `UserStatusGuard`, `WorkspaceGuard`, `WsWorkspaceGuard`), the services that decide a revocation, an account status, a membership and an API key, and the helpers that hash, compare or derive from a secret check the runtime at the decision, and again after each lookup they wait for, so a replacement made while a guard waits is refused. The `isIP` and `isIPv6` of `node:net`, which key the rate limit and the client address, are taken once at load too (a replaced `isIPv6` split one IPv6 /64 into separate buckets and a replaced `isIP` let an arbitrary value key a counter), and the workspace decision of `verifyAccessToken` checks the runtime right before it decides, after the membership lookup it waits for. Each refusal is its own object, built from references taken at load, and a `catch` that turned the failure of a verification into "nothing to blacklist" (the logout of both planes) now lets the refusal through. The built-ins the services and guards make their decisions with (`Array.prototype.some` and `includes`, `Set.prototype.has`, `Map.prototype.get`, the string and regular-expression methods, `Object.keys` and the rest of the namespaces the sources call, the global bindings the sources name) are recorded when the module loads and compared by identity whenever the root guard runs, so a role check, a tenant match or a revocation lookup made with a replaced built-in is refused with `auth.internal` and a count, with a reason distinct from a planted key. Only what the sources call or read is recorded (the methods and accessors of arrays, strings, maps, sets, regular expressions, URLs, `URLSearchParams`, buffers and the rest of the types the sources use, found by a spec that reads them as syntax and fails both for a function used and not listed and for one listed and not used), so a polyfill or a monitor that patches a function nothing calls never makes the guard refuse. `JSON` is not compared but captured: what the library parses and serialises goes through the `JSON.parse` and `JSON.stringify` taken at load. The methods of dates (`getTime`, `toISOString`), which key expiry and cursors are decided with, are compared; the clock source (the `Date` binding, `Date.now`, `Date.parse`), `Promise` and `Intl` are exempt, because the test doubles of a host replace them. A function that a library of the host patches after the module loaded and that a source calls is refused while it is not the function that was recorded. A sweep replaces every function of the globals in turn with a spy and shows that the root guard, the judgement of whose a key is, the options handed to the dependencies and the verification call none of them live; it found the `for...of` over the retired secrets, now an indexed loop. A row replaces each built-in a check could call and expects the guard to count a planted key and to accept a standard root.
31
+ - **No decision waits through a static of `Promise`.** A flaw that can run code in the process could replace `Promise.all` or `Promise.race` after the library loaded and answer for a read of a repository or a plugin: a membership the repository never returned (a non-member read as an owner), a profile the plugin never fetched. Decisions now wait with `await` alone (`utils/settle`), and a spec fails on a static of `Promise` in the sources under `src`. The helpers do not trust the global `Promise`, `Function.prototype.call` or `apply`: they use the language's own, taken at load, and the helpers of `utils/settle` check the root of the promise machinery immediately before each `await` they make, because `await` and the engine's handling of a returned object read `constructor` and `then`. The services pin each promise they await, so the wait never reads `Promise.prototype.constructor`, `then` or the species, and check the root immediately before they return an object. A constructor replaced and put back, or a `then` planted before a decision, is refused with `auth.internal`. A refusal over a read that failed does not end the process with an unhandled rejection, and a combined wait settles on the first failure, as `Promise.all` did. The promise a decision hands to its caller is pinned the same way, so the last hop is covered too. The pin is a constructor that cannot be replaced or redefined afterwards. A descriptor is read for its own fields only, so a `value` planted on `Object.prototype` answers for no accessor; detached work is an async function that awaits the pinned promise inside a `try`, so it never asks a promise for its `then`. `checked` looks through the whole chain of prototypes of an answer for a `then`, so a DTO made by `plainToInstance` cannot carry one in. A promise that cannot be pinned (a frozen one) is refused with `auth.internal`, and the wait that found the root not standard no longer leaves the rejection of the promise it had already started unhandled. A constructor of `Promise` already replaced before the module loads stops it from loading. Specs run real decisions in a child process under a replaced constructor and a planted `then`, and expect them refused with `auth.internal`.
32
+ - **A repository that finds nothing is copied for the same work per field as one that finds a row.** Since 1.5.12 the guarded view copied a row that was found and returned a missing one uncopied, so a lookup that missed (a login for an address that does not exist, a workspace or a membership that is not there) did less work than one that hit. A miss now copies a decoy record built once per contract, which holds every field with a value each reader accepts, and answers `null` or `undefined` as the repository did. This is the same work, not the same time: how long a host's database takes for each row is outside the library, and a spec counts the calls of the copy, never a clock.
33
+ - **The peer range of `next` starts at `^16.4.5`.** The floor `^16.4.1` admitted versions with seven published advisories, all moderate, and `16.4.5` carries the fixes. A host on `16.4.1` to `16.4.4` upgrades `next`.
34
+
35
+ ### Known limits
36
+
37
+ - A miss copies the fields its contract names and nothing else: the work a found row adds for its own fields outside the contract, and for the length of a list it carries, is not repeated, so that part of the cost still depends on the row's size. The guarantee is the same work per field the contract names, not the same time.
38
+ - Code that runs in the same process is trusted, as in Node itself: the guards in this release that refuse a replaced built-in, a planted `then` or a polluted prototype are best-effort hardening, not a security boundary (see `SECURITY.md`, "Threat model: same-process code"). Every "cannot" and "never" in the entries above holds against the cases the specs run, not against arbitrary code in the process.
39
+ - A host that replaces exports of `jsonwebtoken`, `jws` or `jwa` after load is outside what the library checks: that is code targeting a dependency. The set is exact for the versions the library is tested with.
40
+ - A monitor, polyfill or test double that replaces a recorded function after the library loaded makes the library refuse until it is put back, including a spy on `JSON.parse` or `JSON.stringify`. The README says how to load such a patch before the library.
41
+ - A frozen promise together with a species that throws: the library refuses the frozen promise with `auth.internal` and does not wait for it where a decision depends on it. The handler that marks a rejection as heard is attached by a native `await` while `Promise.prototype.constructor` is still the language's own data property (that `await` reads neither `then` nor the species), and by the language's `then` otherwise, so that combination leaves no rejection unhandled; the engine still reads a species accessor a host planted on its own resolution paths, outside what the library can pin, and that is refused or answered by the host's own code, never by a value the library forged.
42
+ - The statics of `Promise` and `Promise.prototype.then` are not compared, because the monitors and the test doubles of a host wrap them; the library waits with a native `await` on promises it pinned, which attaches its handler without reading `then`. A host that replaces them is not refused, so the answers of a promise the library did not pin are the host's to keep honest. `Promise.prototype.constructor` is compared. A promise a dependency or the host hands to the library is not left alone: just before the library awaits it, the library gives it an own `constructor` that is the language's, permanent, and refuses the wait when the promise cannot take one (a frozen promise, or one whose own constructor the host made permanent). A host that had put an own constructor on its promise loses it there. Not covered: a `then` planted and erased again between the check and the resolution by code that runs in that gap, and the dependencies (`jsonwebtoken` and the like) that read statics inside their own code.
43
+ - A runtime whose `Promise` was replaced, or whose `Promise.prototype` was polluted, before the module loaded is outside what it can detect beyond the constructor check at load: the intrinsics are taken from the first async function the module runs, so code that ran earlier decides what they are.
44
+ - What Nest and Express do with the value a route handler returns is not the library's: they read `then` of the plain object after the controller returns, with no check of the library in between, so a `then` planted on `Object.prototype` after the last check of the library is read there. The same holds for what a dependency does inside the call of a service the library awaits.
45
+ - The browser-side code (`./client`, `./react`) and the `./nextjs` helpers cannot import the pin from the server entry, so they await promises without it; a host that forges the root in the browser or in the Next.js runtime decides what those promises yield, as it does for every other call it can intercept.
46
+ - `express`'s `clearCookie` deletes `maxAge` from its own copy; the guard stays the closer for `keyid` and `notBefore`.
47
+ - The root guard compares the recorded built-ins in full at each decision, and a request decides more than once: about 960 calls of `Object` and `Reflect` per comparison, 13 comparisons for `me` and 45 for a refresh. Measured on Node 24.21.0 on an Apple M4 Max, plain node over the built package, in six rounds of 300 requests with the two versions alternated in separate processes, under a one-minute load average of about 3 to 8: `me` costs 0.164 to 0.315 ms of CPU more per request than 1.5.15 (p50 1.8 to 2.4 times), a refresh 0.48 to 0.92 ms more, and a failed login nothing measurable (scrypt takes 160 to 175 ms). One process serves 2.2 to 2.8 times fewer `me` requests per second. What it buys is that a built-in replaced between two awaits is refused at the next decision and not read by it. A later release may make the comparison cheaper without making it see less.
48
+
49
+ ### Apply to a derived backend
50
+
51
+ A decision no longer waits through a static of `Promise`, nor through a
52
+ derived promise of `then` or `catch`; a repository, a hook or a plugin that returns a promise that is frozen, or whose
53
+ own `constructor` is not the language's, is refused with `auth.internal` where its answer is waited for, which it was
54
+ not before. A host that reads the descriptor of a property of the library's options sees its own fields only.
55
+
21
56
  ## [1.5.15] - 2026-11-22
22
57
 
23
58
  A patch release.
@@ -5608,7 +5643,8 @@ ever installable.
5608
5643
  - 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
5609
5644
  - 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
5610
5645
 
5611
- [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.15...HEAD
5646
+ [Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.5.16...HEAD
5647
+ [1.5.16]: https://github.com/bymaxone/nest-auth/compare/v1.5.15...v1.5.16
5612
5648
  [1.5.15]: https://github.com/bymaxone/nest-auth/compare/v1.5.14...v1.5.15
5613
5649
  [1.5.14]: https://github.com/bymaxone/nest-auth/compare/v1.5.13...v1.5.14
5614
5650
  [1.5.13]: https://github.com/bymaxone/nest-auth/compare/v1.5.12...v1.5.13
package/README.md CHANGED
@@ -1563,6 +1563,20 @@ The `tenantId` is always extracted from the validated JWT — never from the req
1563
1563
 
1564
1564
  Access tokens are short-lived (default 15 minutes) and immediately revocable via a Redis JTI blacklist. Refresh tokens rotate on every use with a configurable grace window to handle concurrent requests. This is the industry-standard hybrid approach used by Auth0, Okta, and SuperTokens — combining short lifetimes for low-latency revocation with rotating refresh tokens for session continuity.
1565
1565
 
1566
+ ### A Process That Changes Its Own Built-ins
1567
+
1568
+ Code running in your process can plant a key on `Object.prototype` or replace a built-in after the library loaded (`Array.prototype.some`, `Map.prototype.get`, `crypto.timingSafeEqual`, `Reflect.getMetadata`). A role check, a revocation lookup, a token signature check and an `@Public()` route are all decided with such built-ins, so the library does not decide with a runtime it cannot vouch for.
1569
+
1570
+ - The primitives the library calls itself (the comparisons of secrets, the digests, the random bytes, `JSON.parse` and `JSON.stringify`) are taken once, when the module loads.
1571
+ - What it cannot copy (the functions the JWT libraries read at each call: `node:crypto` and the `Hash`, `Hmac`, `Sign` and `Verify` objects it hands back, `JSON.parse` and `JSON.stringify`, `Buffer`; `Reflector`; the methods of arrays, strings, maps and sets that the guards and services decide with) is recorded when the module loads and compared whenever a decision is made: at the entry of a verification, a signature, a hash and a cookie, at the start of each guard that decides, and again after each lookup a guard or a service waits for.
1572
+ - A call made while one of them differs, or while a key is planted on `Object.prototype`, is refused with `auth.internal` (HTTP 500) and a count, never a name. A refusal is not turned into another answer, so a polluted process answers 500 and does not look like every token being invalid.
1573
+
1574
+ The trade-off: a monitoring agent, polyfill or test double that **replaces** one of the recorded functions after the library loaded makes the library refuse until it is put back. Only the functions the library's sources call or read are recorded, so a function nothing calls can be patched freely, and `Promise`, `Date`, `Intl` and the timers (which test doubles replace) are never compared. Load such a patch before the library, or have it wrap without replacing the recorded functions.
1575
+
1576
+ The set is the union of what the library's sources call and what the JWT chain (`@nestjs/jwt`, `jsonwebtoken`, `jws`, `jwa` and their dependencies) reads, found by a test that reads the installed packages, so it is exact for the versions the library is tested with; a newer version of those packages that reads another built-in is covered once the list is updated.
1577
+
1578
+ The boundary: the library checks the runtime's own built-ins (JavaScript globals and their prototypes, and the `node:*` modules). A host that replaces exports of `jsonwebtoken`, `jws` or `jwa` after load is outside what the library checks: that is code targeting a dependency, the same class as replacing the library itself.
1579
+
1566
1580
  ### Security Checklist
1567
1581
 
1568
1582
  When integrating `@bymax-one/nest-auth` in production, verify each of the following:
@@ -298,7 +298,6 @@ function readErrorEnvelope(value, response) {
298
298
  // other branch returns. Block form because the mutant sits two lines below a wrapped
299
299
  // comment, where the per-line directive points at the comment's own continuation.
300
300
  details: typeof details === "object" && details !== null ? details : null
301
- // Stryker restore ConditionalExpression
302
301
  };
303
302
  }
304
303
  function isAuthErrorBody(value) {
@@ -386,10 +385,9 @@ function createAuthClient(config) {
386
385
  return result;
387
386
  },
388
387
  async forgotPassword(email, tenantId) {
389
- return postNoContent(shared.AUTH_PASSWORD_ROUTES.forgotPassword, {
390
- email,
391
- ...tenantId !== void 0 ? { tenantId } : {}
392
- });
388
+ const payload = { email };
389
+ if (tenantId !== void 0) payload["tenantId"] = tenantId;
390
+ return postNoContent(shared.AUTH_PASSWORD_ROUTES.forgotPassword, payload);
393
391
  },
394
392
  async resetPassword(input) {
395
393
  const payload = {
@@ -297,7 +297,6 @@ function readErrorEnvelope(value, response) {
297
297
  // other branch returns. Block form because the mutant sits two lines below a wrapped
298
298
  // comment, where the per-line directive points at the comment's own continuation.
299
299
  details: typeof details === "object" && details !== null ? details : null
300
- // Stryker restore ConditionalExpression
301
300
  };
302
301
  }
303
302
  function isAuthErrorBody(value) {
@@ -385,10 +384,9 @@ function createAuthClient(config) {
385
384
  return result;
386
385
  },
387
386
  async forgotPassword(email, tenantId) {
388
- return postNoContent(AUTH_PASSWORD_ROUTES.forgotPassword, {
389
- email,
390
- ...tenantId !== void 0 ? { tenantId } : {}
391
- });
387
+ const payload = { email };
388
+ if (tenantId !== void 0) payload["tenantId"] = tenantId;
389
+ return postNoContent(AUTH_PASSWORD_ROUTES.forgotPassword, payload);
392
390
  },
393
391
  async resetPassword(input) {
394
392
  const payload = {
@@ -117,7 +117,11 @@ function createWorkspaceAccessReader(config) {
117
117
  response.status
118
118
  );
119
119
  }
120
- const body = await response.json().catch(() => void 0);
120
+ let body;
121
+ try {
122
+ body = await response.json();
123
+ } catch {
124
+ }
121
125
  if (!isAccess(body)) {
122
126
  throw new shared.AuthClientError("Workspace access answer has an unexpected shape", response.status);
123
127
  }
@@ -115,7 +115,11 @@ function createWorkspaceAccessReader(config) {
115
115
  response.status
116
116
  );
117
117
  }
118
- const body = await response.json().catch(() => void 0);
118
+ let body;
119
+ try {
120
+ body = await response.json();
121
+ } catch {
122
+ }
119
123
  if (!isAccess(body)) {
120
124
  throw new AuthClientError("Workspace access answer has an unexpected shape", response.status);
121
125
  }