@bymax-one/nest-auth 1.4.18 → 1.4.20
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 +120 -1
- package/README.md +29 -1
- package/dist/nextjs/index.cjs +22 -3
- package/dist/nextjs/index.d.cts +23 -8
- package/dist/nextjs/index.d.ts +23 -8
- package/dist/nextjs/index.mjs +22 -3
- package/dist/react/index.cjs +29 -8
- package/dist/react/index.d.cts +28 -8
- package/dist/react/index.d.ts +28 -8
- package/dist/react/index.mjs +29 -8
- package/dist/server/index.cjs +298 -328
- package/dist/server/index.d.cts +52 -136
- package/dist/server/index.d.ts +52 -136
- package/dist/server/index.mjs +298 -328
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -18,6 +18,123 @@ what moves, and that note is the compatibility contract until strict SemVer begi
|
|
|
18
18
|
|
|
19
19
|
## [Unreleased]
|
|
20
20
|
|
|
21
|
+
## [1.4.20] - 2026-11-07
|
|
22
|
+
|
|
23
|
+
### Apply to a derived backend
|
|
24
|
+
|
|
25
|
+
- **`SelfOrAdminGuard` no longer admits a request addressed to another tenant.** It decided by the
|
|
26
|
+
caller's id and role alone, so a token for tenant `t1` and user `u1` was admitted on
|
|
27
|
+
`/tenants/t2/users/u1`, and the `admin` role, which is held inside one tenant, was admitted on any
|
|
28
|
+
tenant's users; the guard's documentation left the tenant check to the controller. When the route
|
|
29
|
+
captures the tenant as `tenantId`, `tenant_id` or `tenant`, every capture present must now equal
|
|
30
|
+
the token's `tenantId`, otherwise the guard answers `INSUFFICIENT_ROLE` (`403`) before it looks at
|
|
31
|
+
the id or the role. Captures that disagree with one another, are empty, or are arrays are refused,
|
|
32
|
+
and so is a token with no tenant. A route that captures no tenant is not tenant-checked, and
|
|
33
|
+
the controller or service must still enforce the tenant there. A host that relied on the guard
|
|
34
|
+
to admit an admin across tenants on such a route now gets a `403`. The `userId` or `id` capture
|
|
35
|
+
must now be one non-empty path segment: an empty value or one carrying a slash (a decoded `%2F`)
|
|
36
|
+
is refused with `INSUFFICIENT_ROLE` for an admin as well, and so is an owner whose own id contains a
|
|
37
|
+
slash, who could reach their own resource through a `%2F` before. A route that names the tenant any
|
|
38
|
+
other way, or sits on a router mounted without `mergeParams`, is not tenant-checked either.
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
|
|
42
|
+
- **A cross-tenant request is no longer admitted by `SelfOrAdminGuard`.** See the note above.
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- **`MfaService` moves private methods to internal modules.** They moved out of the class as plain
|
|
47
|
+
functions; behaviour, error codes and log text are unchanged, and none of them was part of the
|
|
48
|
+
public API.
|
|
49
|
+
|
|
50
|
+
### Documentation
|
|
51
|
+
|
|
52
|
+
- **The shared contract states when the password-reset cooldown is released.**
|
|
53
|
+
`responseBodies.passwordResetRequest.failures.cooldown` said "released on any failure"; it now says
|
|
54
|
+
the cooldown is released when the request itself observes the failure (the account lookup, the
|
|
55
|
+
code or token store, or a send awaited inside the request), and that a send which fails after the
|
|
56
|
+
response has left never releases it. No behaviour changes. The contract's sha256 changes with it, so a copy kept elsewhere is refreshed
|
|
57
|
+
from `conformance/wire-contract.json`.
|
|
58
|
+
- **Correction to the 1.4.19 notes on the resend cooldown.** The 1.4.19 entry for the password-reset
|
|
59
|
+
`500` split says the cooldown a request took "is released on any failure". That is wrong for a
|
|
60
|
+
send that fails after the response has left (a detached send): it keeps the cooldown, as the code
|
|
61
|
+
and its documentation state. The cooldown is released only for a failure the request
|
|
62
|
+
itself observes. The 1.4.19 text stands as published; this line supersedes it.
|
|
63
|
+
|
|
64
|
+
## [1.4.19] - 2026-11-07
|
|
65
|
+
|
|
66
|
+
### Apply to a derived backend
|
|
67
|
+
|
|
68
|
+
- **A logout whose retry marker cannot be removed no longer announces itself twice or never.** When
|
|
69
|
+
the owner comes from the stored session and the store refuses to remove a leftover `lp:` or
|
|
70
|
+
`plp:` marker, the logout reads the marker again. With no marker left it completes and announces;
|
|
71
|
+
with the marker still there it answers `500` `auth.internal` and announces nothing, because the
|
|
72
|
+
session is already gone and the retry claims the marker and announces once; when that read is
|
|
73
|
+
refused too, the owner is recorded again, best effort, and the logout answers `500`. When the
|
|
74
|
+
owner comes from the marker and the store refuses the claim, the logout answers `500` and
|
|
75
|
+
announces nothing: answering success would keep the client from retrying, so nothing would ever
|
|
76
|
+
announce it. A client that retries a `5xx` logout needs no change; a monitor can see these `500`s
|
|
77
|
+
during a Redis fault. The delivery guarantee in the shared contract is unchanged.
|
|
78
|
+
`settlePendingLogout` takes the owner and the marker lifetime as two more parameters; it is not
|
|
79
|
+
exported from the package.
|
|
80
|
+
- **A password-reset request that cannot be served answers `500` instead of a silent `200` when
|
|
81
|
+
the failure is the same for every address.** `POST /password/forgot-password` and
|
|
82
|
+
`POST /password/resend-otp` used to acknowledge `200` whatever failed. A failure before the
|
|
83
|
+
account is known, the resend-cooldown store or the account lookup, now answers `500`
|
|
84
|
+
`auth.internal` after the usual floor, because it tells the caller nothing about the
|
|
85
|
+
address. A failure after the account is known, issuing or storing the code, is logged and still
|
|
86
|
+
answers `200`, because it happens only for a registered address. The resend cooldown a request
|
|
87
|
+
took is released on any failure, so the retry a `500` invites is not refused for the rest of the cooldown window. A
|
|
88
|
+
cooldown hit takes the same floor as every other exit. A client or monitor that treated these
|
|
89
|
+
routes as always `200` sees `500` during a Redis or repository outage. The contract's
|
|
90
|
+
`responseBodies.passwordResetRequest` gains a `failures` note stating the rule. Private `answerResetRequest` appears in the `PasswordResetService` declarations.
|
|
91
|
+
- **The Next.js logout handler keeps the cookies when the upstream logout did not complete.**
|
|
92
|
+
`createLogoutHandler` clears the three auth cookies only once the upstream has given a final
|
|
93
|
+
answer below `500` other than `429` (a `2xx`, or a `4xx` such as an expired or already-revoked
|
|
94
|
+
session). When the upstream answers `5xx`, the handler answers that status and touches no cookie; a `429` from the
|
|
95
|
+
throttled logout route, answered before anything is revoked, is handled the same way and passes
|
|
96
|
+
on the upstream `Retry-After`; when the upstream is unreachable or the request fails, it answers
|
|
97
|
+
`502` and touches no cookie. In `'redirect'` mode none of these redirects. The cookies are the client's only handle for retrying the same logout, and the
|
|
98
|
+
upstream endpoint is idempotent, so the retry completes it. A caller that treated the handler's
|
|
99
|
+
answer as always successful sees a `5xx`, `502` or `429` it did not see before; `AuthClient.logout()`
|
|
100
|
+
rejects on it, as it does for any non-2xx. Cross-site and non-`POST` requests are answered as
|
|
101
|
+
before.
|
|
102
|
+
- **The React `logout()` keeps the authenticated state when the server logout did not
|
|
103
|
+
complete.** `AuthProvider` clears the session state after a successful logout and after a final
|
|
104
|
+
answer, an `AuthClientError` with a status below `500` and not `429`, and rethrows in the second
|
|
105
|
+
case. After a `5xx` (`502` included), a `429` or a failure with no answer at all, such as a
|
|
106
|
+
network failure, the state stays `authenticated` with the same user and the error is rethrown, because the session may be
|
|
107
|
+
alive and the UI must not read signed-out. A consumer that relied on the state being cleared
|
|
108
|
+
whenever `logout()` rejected now finds it still `authenticated` after such a rejection and
|
|
109
|
+
should offer a retry; repeating the call is safe because the server logout is idempotent. A
|
|
110
|
+
session probe already in flight is applied after a failed logout, not discarded. The rule is
|
|
111
|
+
written in the `logout` documentation on `AuthContextValue`, which also says which statuses the
|
|
112
|
+
hook can see behind the proxy route. The error is recognized by its `name` and an integer `status` of at least 100,
|
|
113
|
+
not by `instanceof`, so a second copy of the error class decides the same way; the check that
|
|
114
|
+
fires `onSessionExpired` on a `401` uses the same recognition, so an application that loads the
|
|
115
|
+
client and the provider through different module formats of the package no longer misses it.
|
|
116
|
+
No contract change.
|
|
117
|
+
|
|
118
|
+
### Fixed
|
|
119
|
+
|
|
120
|
+
- **A password-reset request no longer hides an outage behind `200`.** See the note above.
|
|
121
|
+
- **A logout no longer announces itself twice, or never, when its marker cannot be removed.** See
|
|
122
|
+
the note above.
|
|
123
|
+
- **A failed logout through the Next.js proxy no longer looks successful.** See the note above.
|
|
124
|
+
- **A failed logout no longer shows the UI as signed out while the session is alive.** See the
|
|
125
|
+
note above.
|
|
126
|
+
|
|
127
|
+
### Documentation
|
|
128
|
+
|
|
129
|
+
- **A password-reset lookup slower than the resend cooldown can remove a later request's
|
|
130
|
+
cooldown.** The flows release the cooldown by key when the lookup throws, so a lookup that
|
|
131
|
+
fails after more than the cooldown (60 seconds) releases a key that may by then belong to a
|
|
132
|
+
later request. Keep `findByEmail` well under the cooldown; the library does not guard against it.
|
|
133
|
+
- **A host `updateMfa` that outlasts the MFA transition lock can reorder MFA writes.** The lock
|
|
134
|
+
expires on its own after `MFA_TRANSITION_LOCK_TTL_SECONDS` (10 seconds), a write still running then is
|
|
135
|
+
overtaken and lands after the next change, and the interface has no compare-and-set for the
|
|
136
|
+
library to use. Keep `updateMfa` well under the lock's lifetime; a guard of your own inside it narrows the window only for a stall after its own read, because the library passes the new values and not the ones it read.
|
|
137
|
+
|
|
21
138
|
## [1.4.18] - 2026-11-07
|
|
22
139
|
|
|
23
140
|
### Apply to a derived backend
|
|
@@ -4483,7 +4600,9 @@ ever installable.
|
|
|
4483
4600
|
- 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
|
|
4484
4601
|
- 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
|
|
4485
4602
|
|
|
4486
|
-
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.
|
|
4603
|
+
[Unreleased]: https://github.com/bymaxone/nest-auth/compare/v1.4.20...HEAD
|
|
4604
|
+
[1.4.20]: https://github.com/bymaxone/nest-auth/compare/v1.4.19...v1.4.20
|
|
4605
|
+
[1.4.19]: https://github.com/bymaxone/nest-auth/compare/v1.4.18...v1.4.19
|
|
4487
4606
|
[1.4.18]: https://github.com/bymaxone/nest-auth/compare/v1.4.17...v1.4.18
|
|
4488
4607
|
[1.4.17]: https://github.com/bymaxone/nest-auth/compare/v1.4.16...v1.4.17
|
|
4489
4608
|
[1.4.16]: https://github.com/bymaxone/nest-auth/compare/v1.4.15...v1.4.16
|
package/README.md
CHANGED
|
@@ -1058,6 +1058,23 @@ All options are configurable via `registerAsync()`. Here are the key configurati
|
|
|
1058
1058
|
> otherwise surface at a user's first challenge rather than at boot. Drop the entry once your
|
|
1059
1059
|
> enrolled users have had time to authenticate at least once.
|
|
1060
1060
|
|
|
1061
|
+
> [!WARNING]
|
|
1062
|
+
> **Keep your `updateMfa` fast.** Every MFA state change
|
|
1063
|
+
> rewrites the account's MFA record through your repository's `updateMfa`, and the library
|
|
1064
|
+
> serializes those writes per account with a lock that expires on its own
|
|
1065
|
+
> (`MFA_TRANSITION_LOCK_TTL_SECONDS`, 10 seconds) so a process that dies mid-write cannot strand
|
|
1066
|
+
> the account. The lock cannot outlast a write that is still running: if your `updateMfa` stalls
|
|
1067
|
+
> past that time, a second change takes the lock, reads the record, and writes it, and the stalled
|
|
1068
|
+
> write then lands _after_ it and overwrites it. The repository interface offers no
|
|
1069
|
+
> compare-and-set for the library to use, so it cannot detect this. Keep `updateMfa` well under the
|
|
1070
|
+
> lock's lifetime (a plain single-row update is, but a call that waits on a contended lock or a slow
|
|
1071
|
+
> replica may not be). A guard of your own inside `updateMfa` can narrow the window only for a stall
|
|
1072
|
+
> that happens after the guard's own read, such as a wait on a row lock inside the `UPDATE`: the
|
|
1073
|
+
> library passes `updateMfa` the new values and not the ones it read, so closing the window
|
|
1074
|
+
> completely would need those values passed in. The lock is held
|
|
1075
|
+
> across the read the transition makes inside it as well as the write, so a slow `findById` counts
|
|
1076
|
+
> against the same lifetime.
|
|
1077
|
+
|
|
1061
1078
|
> [!IMPORTANT]
|
|
1062
1079
|
> **The parameters that carry a control's strength are bounded at startup.** `mfa.totpWindow`
|
|
1063
1080
|
> must be `0..=10`: the window counts 30-second steps on _either_ side of now, so `2n + 1`
|
|
@@ -2246,7 +2263,7 @@ conditional on nothing having invalidated in between, which this service does no
|
|
|
2246
2263
|
| `ApiKeyGuard` | `@ServiceKey('read')` | Service API key for machine callers; fails closed without scopes |
|
|
2247
2264
|
|
|
2248
2265
|
> [!NOTE]
|
|
2249
|
-
> Three additional guards — `SelfOrAdminGuard` (ownership checks), `OptionalAuthGuard` (routes that behave differently for anonymous vs authenticated users), and `WsJwtGuard` (JWT authentication on WebSocket gateways) — are exported from the public `@bymax-one/nest-auth` barrel. Use them exactly like the core guards above.
|
|
2266
|
+
> Three additional guards — `SelfOrAdminGuard` (ownership checks), `OptionalAuthGuard` (routes that behave differently for anonymous vs authenticated users), and `WsJwtGuard` (JWT authentication on WebSocket gateways) — are exported from the public `@bymax-one/nest-auth` barrel. Use them exactly like the core guards above. `SelfOrAdminGuard` also holds a route that captures the tenant (`:tenantId`, `:tenant_id` or `:tenant`) to the token's tenant: a capture that differs from `req.user.tenantId`, disagrees with another capture, or is empty is refused with `403` before the self-or-admin decision, so neither a matching id nor the `admin` role reaches into another tenant. A wildcard capture arrives as an array and is refused, and the id (`:userId` or `:id`) must be one non-empty path segment, so an empty value or a decoded `%2F` is refused too. Only those three capture names are read: a route that names the tenant `{org}` or captures none is decided by identity and role alone, and your handler must bind the tenant itself. If a capture name is used at two nesting levels Express keeps the inner value, and a parent router mounted without `mergeParams` does not expose its captures to the inner route, so the guard does not see them.
|
|
2250
2267
|
|
|
2251
2268
|
### One error envelope
|
|
2252
2269
|
|
|
@@ -2399,6 +2416,17 @@ went one release stated and unenforced.
|
|
|
2399
2416
|
> (`auth.otp_invalid`) at one status (`401`) — a `429` on the ceiling would say the address was
|
|
2400
2417
|
> registered, since only a record that exists can reach one.
|
|
2401
2418
|
|
|
2419
|
+
> **When a password-reset request fails.** A failure that is the same for every address, the
|
|
2420
|
+
> resend-cooldown store or your repository's `findByEmail` throwing, answers `500`
|
|
2421
|
+
> (`auth.internal`) after the same timing floor as every other exit, and the cooldown that request
|
|
2422
|
+
> took is released so the retry is not refused. A failure after the account is known (storing the
|
|
2423
|
+
> code, or the mail provider failing after the response has left) is logged and the `200` stands,
|
|
2424
|
+
> because it happens only for a registered address. Two limits are left as they are. A `findByEmail`
|
|
2425
|
+
> that takes longer than the cooldown (60 seconds) and then fails releases the cooldown by key, and
|
|
2426
|
+
> by then that key may belong to a later request, whose cooldown is removed early: keep
|
|
2427
|
+
> `findByEmail` well under the cooldown. A mail provider that fails late never touches the
|
|
2428
|
+
> cooldown, so the address stays throttled for the rest of its window.
|
|
2429
|
+
|
|
2402
2430
|
### Server Decorators
|
|
2403
2431
|
|
|
2404
2432
|
| Decorator | Usage |
|
package/dist/nextjs/index.cjs
CHANGED
|
@@ -1086,6 +1086,9 @@ function buildUnauthorisedResponse() {
|
|
|
1086
1086
|
__name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
|
|
1087
1087
|
var CLIENT_REFRESH_ROUTE = shared.AUTH_PROXY_ROUTES.clientRefresh;
|
|
1088
1088
|
var DEFAULT_LOGOUT_PATH = `/auth/${shared.AUTH_DASHBOARD_ROUTES.logout}`;
|
|
1089
|
+
var SERVER_ERROR_STATUS = 500;
|
|
1090
|
+
var TOO_MANY_REQUESTS_STATUS = 429;
|
|
1091
|
+
var BAD_GATEWAY_STATUS = 502;
|
|
1089
1092
|
var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
|
|
1090
1093
|
function createLogoutHandler(config) {
|
|
1091
1094
|
const refreshCookiePath = validateLogoutConfig(config);
|
|
@@ -1114,15 +1117,20 @@ function createLogoutHandler(config) {
|
|
|
1114
1117
|
};
|
|
1115
1118
|
const incomingAuth = request.headers.get("authorization");
|
|
1116
1119
|
if (incomingAuth) upstreamHeaders.authorization = incomingAuth;
|
|
1120
|
+
let upstream;
|
|
1117
1121
|
try {
|
|
1118
|
-
await fetch(logoutUrl, {
|
|
1122
|
+
upstream = await fetch(logoutUrl, {
|
|
1119
1123
|
method: "POST",
|
|
1120
1124
|
headers: upstreamHeaders,
|
|
1121
1125
|
redirect: "manual"
|
|
1122
1126
|
});
|
|
1123
1127
|
} catch {
|
|
1128
|
+
return failedLogoutResponse(BAD_GATEWAY_STATUS);
|
|
1129
|
+
}
|
|
1130
|
+
if (upstream.status >= SERVER_ERROR_STATUS || upstream.status === TOO_MANY_REQUESTS_STATUS) {
|
|
1131
|
+
return failedLogoutResponse(upstream.status, upstream.headers.get("retry-after"));
|
|
1124
1132
|
}
|
|
1125
|
-
return buildLogoutResponse(
|
|
1133
|
+
return buildLogoutResponse(config, refreshCookiePath);
|
|
1126
1134
|
}, "logoutHandler");
|
|
1127
1135
|
}
|
|
1128
1136
|
__name(createLogoutHandler, "createLogoutHandler");
|
|
@@ -1143,7 +1151,18 @@ function validateLogoutConfig(config) {
|
|
|
1143
1151
|
return refreshCookiePath;
|
|
1144
1152
|
}
|
|
1145
1153
|
__name(validateLogoutConfig, "validateLogoutConfig");
|
|
1146
|
-
function
|
|
1154
|
+
function failedLogoutResponse(status, retryAfter = null) {
|
|
1155
|
+
const headers = new Headers({
|
|
1156
|
+
"Cache-Control": "no-store, no-cache"
|
|
1157
|
+
});
|
|
1158
|
+
if (retryAfter !== null) headers.set("Retry-After", retryAfter);
|
|
1159
|
+
return new Response(null, {
|
|
1160
|
+
status,
|
|
1161
|
+
headers
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
__name(failedLogoutResponse, "failedLogoutResponse");
|
|
1165
|
+
function buildLogoutResponse(config, refreshCookiePath) {
|
|
1147
1166
|
if (config.mode === "redirect") {
|
|
1148
1167
|
const response2 = redirectToPath(config.loginPath);
|
|
1149
1168
|
attachClearCookies(response2, config, refreshCookiePath);
|
package/dist/nextjs/index.d.cts
CHANGED
|
@@ -1032,14 +1032,29 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
|
|
|
1032
1032
|
*
|
|
1033
1033
|
* The handler forwards the incoming cookies to the upstream NestJS
|
|
1034
1034
|
* `POST /auth/logout` endpoint (which revokes the refresh token
|
|
1035
|
-
* server-side) and
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1038
|
-
*
|
|
1039
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
*
|
|
1042
|
-
*
|
|
1035
|
+
* server-side) and clears the three auth cookies on the browser once the
|
|
1036
|
+
* upstream has given a final answer.
|
|
1037
|
+
*
|
|
1038
|
+
* Rule, one line per upstream outcome:
|
|
1039
|
+
*
|
|
1040
|
+
* - the upstream answers below 500 other than 429 (2xx, and a 4xx such as
|
|
1041
|
+
* an expired or already-revoked session): the logout is final, so the
|
|
1042
|
+
* three cookies are cleared and the configured response (200, or the
|
|
1043
|
+
* redirect) is sent;
|
|
1044
|
+
* - the upstream answers 5xx: the logout did not complete and the session
|
|
1045
|
+
* is still alive, so NO cookie is touched and the upstream status is
|
|
1046
|
+
* answered as it is, with no redirect in `'redirect'` mode;
|
|
1047
|
+
* - the upstream answers 429: the logout route is throttled before it
|
|
1048
|
+
* revokes anything, so the session is still alive. Same as 5xx: 429 is
|
|
1049
|
+
* answered with the upstream `Retry-After`, no cookie is touched and
|
|
1050
|
+
* there is no redirect;
|
|
1051
|
+
* - the upstream is unreachable or the request fails: NO cookie is touched
|
|
1052
|
+
* and 502 is answered, with no redirect in `'redirect'` mode.
|
|
1053
|
+
*
|
|
1054
|
+
* The cookies are the client's only handle for retrying the same logout, so
|
|
1055
|
+
* clearing them after a failed revocation would leave a live session the
|
|
1056
|
+
* user believes is gone. The idempotent retry of the NestJS endpoint is
|
|
1057
|
+
* what completes it.
|
|
1043
1058
|
*
|
|
1044
1059
|
* Two response modes are supported, expressed as a discriminated
|
|
1045
1060
|
* union on {@link LogoutHandlerConfig}:
|
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -1032,14 +1032,29 @@ declare const CLIENT_REFRESH_ROUTE: "/api/auth/client-refresh";
|
|
|
1032
1032
|
*
|
|
1033
1033
|
* The handler forwards the incoming cookies to the upstream NestJS
|
|
1034
1034
|
* `POST /auth/logout` endpoint (which revokes the refresh token
|
|
1035
|
-
* server-side) and
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1038
|
-
*
|
|
1039
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
*
|
|
1042
|
-
*
|
|
1035
|
+
* server-side) and clears the three auth cookies on the browser once the
|
|
1036
|
+
* upstream has given a final answer.
|
|
1037
|
+
*
|
|
1038
|
+
* Rule, one line per upstream outcome:
|
|
1039
|
+
*
|
|
1040
|
+
* - the upstream answers below 500 other than 429 (2xx, and a 4xx such as
|
|
1041
|
+
* an expired or already-revoked session): the logout is final, so the
|
|
1042
|
+
* three cookies are cleared and the configured response (200, or the
|
|
1043
|
+
* redirect) is sent;
|
|
1044
|
+
* - the upstream answers 5xx: the logout did not complete and the session
|
|
1045
|
+
* is still alive, so NO cookie is touched and the upstream status is
|
|
1046
|
+
* answered as it is, with no redirect in `'redirect'` mode;
|
|
1047
|
+
* - the upstream answers 429: the logout route is throttled before it
|
|
1048
|
+
* revokes anything, so the session is still alive. Same as 5xx: 429 is
|
|
1049
|
+
* answered with the upstream `Retry-After`, no cookie is touched and
|
|
1050
|
+
* there is no redirect;
|
|
1051
|
+
* - the upstream is unreachable or the request fails: NO cookie is touched
|
|
1052
|
+
* and 502 is answered, with no redirect in `'redirect'` mode.
|
|
1053
|
+
*
|
|
1054
|
+
* The cookies are the client's only handle for retrying the same logout, so
|
|
1055
|
+
* clearing them after a failed revocation would leave a live session the
|
|
1056
|
+
* user believes is gone. The idempotent retry of the NestJS endpoint is
|
|
1057
|
+
* what completes it.
|
|
1043
1058
|
*
|
|
1044
1059
|
* Two response modes are supported, expressed as a discriminated
|
|
1045
1060
|
* union on {@link LogoutHandlerConfig}:
|
package/dist/nextjs/index.mjs
CHANGED
|
@@ -1084,6 +1084,9 @@ function buildUnauthorisedResponse() {
|
|
|
1084
1084
|
__name(buildUnauthorisedResponse, "buildUnauthorisedResponse");
|
|
1085
1085
|
var CLIENT_REFRESH_ROUTE = AUTH_PROXY_ROUTES.clientRefresh;
|
|
1086
1086
|
var DEFAULT_LOGOUT_PATH = `/auth/${AUTH_DASHBOARD_ROUTES.logout}`;
|
|
1087
|
+
var SERVER_ERROR_STATUS = 500;
|
|
1088
|
+
var TOO_MANY_REQUESTS_STATUS = 429;
|
|
1089
|
+
var BAD_GATEWAY_STATUS = 502;
|
|
1087
1090
|
var DEFAULT_REFRESH_COOKIE_PATH2 = "/api/auth";
|
|
1088
1091
|
function createLogoutHandler(config) {
|
|
1089
1092
|
const refreshCookiePath = validateLogoutConfig(config);
|
|
@@ -1112,15 +1115,20 @@ function createLogoutHandler(config) {
|
|
|
1112
1115
|
};
|
|
1113
1116
|
const incomingAuth = request.headers.get("authorization");
|
|
1114
1117
|
if (incomingAuth) upstreamHeaders.authorization = incomingAuth;
|
|
1118
|
+
let upstream;
|
|
1115
1119
|
try {
|
|
1116
|
-
await fetch(logoutUrl, {
|
|
1120
|
+
upstream = await fetch(logoutUrl, {
|
|
1117
1121
|
method: "POST",
|
|
1118
1122
|
headers: upstreamHeaders,
|
|
1119
1123
|
redirect: "manual"
|
|
1120
1124
|
});
|
|
1121
1125
|
} catch {
|
|
1126
|
+
return failedLogoutResponse(BAD_GATEWAY_STATUS);
|
|
1127
|
+
}
|
|
1128
|
+
if (upstream.status >= SERVER_ERROR_STATUS || upstream.status === TOO_MANY_REQUESTS_STATUS) {
|
|
1129
|
+
return failedLogoutResponse(upstream.status, upstream.headers.get("retry-after"));
|
|
1122
1130
|
}
|
|
1123
|
-
return buildLogoutResponse(
|
|
1131
|
+
return buildLogoutResponse(config, refreshCookiePath);
|
|
1124
1132
|
}, "logoutHandler");
|
|
1125
1133
|
}
|
|
1126
1134
|
__name(createLogoutHandler, "createLogoutHandler");
|
|
@@ -1141,7 +1149,18 @@ function validateLogoutConfig(config) {
|
|
|
1141
1149
|
return refreshCookiePath;
|
|
1142
1150
|
}
|
|
1143
1151
|
__name(validateLogoutConfig, "validateLogoutConfig");
|
|
1144
|
-
function
|
|
1152
|
+
function failedLogoutResponse(status, retryAfter = null) {
|
|
1153
|
+
const headers = new Headers({
|
|
1154
|
+
"Cache-Control": "no-store, no-cache"
|
|
1155
|
+
});
|
|
1156
|
+
if (retryAfter !== null) headers.set("Retry-After", retryAfter);
|
|
1157
|
+
return new Response(null, {
|
|
1158
|
+
status,
|
|
1159
|
+
headers
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
__name(failedLogoutResponse, "failedLogoutResponse");
|
|
1163
|
+
function buildLogoutResponse(config, refreshCookiePath) {
|
|
1145
1164
|
if (config.mode === "redirect") {
|
|
1146
1165
|
const response2 = redirectToPath(config.loginPath);
|
|
1147
1166
|
attachClearCookies(response2, config, refreshCookiePath);
|
package/dist/react/index.cjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var React = require('react');
|
|
4
|
-
var shared = require('@bymax-one/nest-auth/shared');
|
|
5
4
|
|
|
6
5
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
7
6
|
|
|
@@ -13,6 +12,20 @@ var AuthContext = React.createContext(null);
|
|
|
13
12
|
|
|
14
13
|
// src/react/AuthProvider.tsx
|
|
15
14
|
var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
|
|
15
|
+
var HTTP_STATUS_MIN = 100;
|
|
16
|
+
function clientErrorStatus(error) {
|
|
17
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
18
|
+
const { name, status } = error;
|
|
19
|
+
if (name !== "AuthClientError" || !Number.isInteger(status)) return void 0;
|
|
20
|
+
const code = status;
|
|
21
|
+
return code >= HTTP_STATUS_MIN ? code : void 0;
|
|
22
|
+
}
|
|
23
|
+
__name(clientErrorStatus, "clientErrorStatus");
|
|
24
|
+
function isFinalAnswer(error) {
|
|
25
|
+
const status = clientErrorStatus(error);
|
|
26
|
+
return status !== void 0 && status < 500 && status !== 429;
|
|
27
|
+
}
|
|
28
|
+
__name(isFinalAnswer, "isFinalAnswer");
|
|
16
29
|
var INITIAL_STATE = {
|
|
17
30
|
user: null,
|
|
18
31
|
status: "loading",
|
|
@@ -47,7 +60,7 @@ function authReducer(state, action) {
|
|
|
47
60
|
}
|
|
48
61
|
__name(authReducer, "authReducer");
|
|
49
62
|
function isSessionExpiredError(error) {
|
|
50
|
-
return error
|
|
63
|
+
return clientErrorStatus(error) === 401;
|
|
51
64
|
}
|
|
52
65
|
__name(isSessionExpiredError, "isSessionExpiredError");
|
|
53
66
|
function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
|
|
@@ -197,17 +210,25 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
197
210
|
}, [
|
|
198
211
|
syncedDispatch
|
|
199
212
|
]);
|
|
213
|
+
const clearSession = React.useCallback(() => {
|
|
214
|
+
sessionGenerationRef.current = {};
|
|
215
|
+
syncedDispatch({
|
|
216
|
+
type: "CLEAR_SESSION"
|
|
217
|
+
});
|
|
218
|
+
}, [
|
|
219
|
+
syncedDispatch
|
|
220
|
+
]);
|
|
200
221
|
const logout = React.useCallback(async () => {
|
|
201
222
|
try {
|
|
202
223
|
await clientRef.current.logout();
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
});
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (!isFinalAnswer(error)) throw error;
|
|
226
|
+
clearSession();
|
|
227
|
+
throw error;
|
|
208
228
|
}
|
|
229
|
+
clearSession();
|
|
209
230
|
}, [
|
|
210
|
-
|
|
231
|
+
clearSession
|
|
211
232
|
]);
|
|
212
233
|
const refresh = React.useCallback(async () => {
|
|
213
234
|
await revalidate(false);
|
package/dist/react/index.d.cts
CHANGED
|
@@ -135,15 +135,35 @@ interface AuthContextValue {
|
|
|
135
135
|
register: (data: RegisterInput) => Promise<AuthResult>;
|
|
136
136
|
/**
|
|
137
137
|
* Revoke the current session server-side and clear the local
|
|
138
|
-
* context state.
|
|
138
|
+
* context state once the server has confirmed or finally answered.
|
|
139
139
|
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
140
|
+
* Rule, by what the server logout did:
|
|
141
|
+
*
|
|
142
|
+
* - it succeeds: the session is revoked and the context state clears;
|
|
143
|
+
* - it fails with a final answer, an `AuthClientError` whose status is
|
|
144
|
+
* below 500 and not 429 (the session is gone or was never valid, and
|
|
145
|
+
* the proxy has cleared the cookies): the context state clears and the
|
|
146
|
+
* error is rethrown;
|
|
147
|
+
* - it fails with a 5xx (502 included), with a 429 (the logout route's
|
|
148
|
+
* throttle, answered before anything is revoked) or with no answer at
|
|
149
|
+
* all (a network failure, an abort): the logout is unconfirmed and the
|
|
150
|
+
* session may be alive, so the context state stays authenticated and
|
|
151
|
+
* the error is rethrown.
|
|
152
|
+
*
|
|
153
|
+
* Which statuses the hook can see depends on the topology. Behind the
|
|
154
|
+
* Next.js proxy route, an upstream answer below 500 other than 429 is
|
|
155
|
+
* answered 200 (or a redirect) after the cookies are cleared, so an
|
|
156
|
+
* upstream 4xx is never relayed: the hook sees a 5xx, a 502 or a 429,
|
|
157
|
+
* which keep the cookies. A 4xx the route answers itself (403 for a
|
|
158
|
+
* cross-site request, 405 for another method) or one from something in
|
|
159
|
+
* front of it reaches the hook and clears the context. Talking to the
|
|
160
|
+
* NestJS server directly, the hook sees the server's own 4xx.
|
|
161
|
+
*
|
|
162
|
+
* @throws The underlying error raised by `AuthClient.logout`. A caller
|
|
163
|
+
* that finds the status still `authenticated` after the rejection
|
|
164
|
+
* should offer a retry; repeating the call is safe because the server
|
|
165
|
+
* logout is idempotent. Callers that do not care about the server-side
|
|
166
|
+
* outcome should wrap the call in a try/catch and ignore the error.
|
|
147
167
|
*/
|
|
148
168
|
logout: () => Promise<void>;
|
|
149
169
|
/**
|
package/dist/react/index.d.ts
CHANGED
|
@@ -135,15 +135,35 @@ interface AuthContextValue {
|
|
|
135
135
|
register: (data: RegisterInput) => Promise<AuthResult>;
|
|
136
136
|
/**
|
|
137
137
|
* Revoke the current session server-side and clear the local
|
|
138
|
-
* context state.
|
|
138
|
+
* context state once the server has confirmed or finally answered.
|
|
139
139
|
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
140
|
+
* Rule, by what the server logout did:
|
|
141
|
+
*
|
|
142
|
+
* - it succeeds: the session is revoked and the context state clears;
|
|
143
|
+
* - it fails with a final answer, an `AuthClientError` whose status is
|
|
144
|
+
* below 500 and not 429 (the session is gone or was never valid, and
|
|
145
|
+
* the proxy has cleared the cookies): the context state clears and the
|
|
146
|
+
* error is rethrown;
|
|
147
|
+
* - it fails with a 5xx (502 included), with a 429 (the logout route's
|
|
148
|
+
* throttle, answered before anything is revoked) or with no answer at
|
|
149
|
+
* all (a network failure, an abort): the logout is unconfirmed and the
|
|
150
|
+
* session may be alive, so the context state stays authenticated and
|
|
151
|
+
* the error is rethrown.
|
|
152
|
+
*
|
|
153
|
+
* Which statuses the hook can see depends on the topology. Behind the
|
|
154
|
+
* Next.js proxy route, an upstream answer below 500 other than 429 is
|
|
155
|
+
* answered 200 (or a redirect) after the cookies are cleared, so an
|
|
156
|
+
* upstream 4xx is never relayed: the hook sees a 5xx, a 502 or a 429,
|
|
157
|
+
* which keep the cookies. A 4xx the route answers itself (403 for a
|
|
158
|
+
* cross-site request, 405 for another method) or one from something in
|
|
159
|
+
* front of it reaches the hook and clears the context. Talking to the
|
|
160
|
+
* NestJS server directly, the hook sees the server's own 4xx.
|
|
161
|
+
*
|
|
162
|
+
* @throws The underlying error raised by `AuthClient.logout`. A caller
|
|
163
|
+
* that finds the status still `authenticated` after the rejection
|
|
164
|
+
* should offer a retry; repeating the call is safe because the server
|
|
165
|
+
* logout is idempotent. Callers that do not care about the server-side
|
|
166
|
+
* outcome should wrap the call in a try/catch and ignore the error.
|
|
147
167
|
*/
|
|
148
168
|
logout: () => Promise<void>;
|
|
149
169
|
/**
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import React, { createContext, useReducer, useRef, useEffect, useCallback, useMemo, useContext } from 'react';
|
|
2
|
-
import { AuthClientError } from '@bymax-one/nest-auth/shared';
|
|
3
2
|
|
|
4
3
|
var __defProp = Object.defineProperty;
|
|
5
4
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
@@ -7,6 +6,20 @@ var AuthContext = createContext(null);
|
|
|
7
6
|
|
|
8
7
|
// src/react/AuthProvider.tsx
|
|
9
8
|
var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
|
|
9
|
+
var HTTP_STATUS_MIN = 100;
|
|
10
|
+
function clientErrorStatus(error) {
|
|
11
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
12
|
+
const { name, status } = error;
|
|
13
|
+
if (name !== "AuthClientError" || !Number.isInteger(status)) return void 0;
|
|
14
|
+
const code = status;
|
|
15
|
+
return code >= HTTP_STATUS_MIN ? code : void 0;
|
|
16
|
+
}
|
|
17
|
+
__name(clientErrorStatus, "clientErrorStatus");
|
|
18
|
+
function isFinalAnswer(error) {
|
|
19
|
+
const status = clientErrorStatus(error);
|
|
20
|
+
return status !== void 0 && status < 500 && status !== 429;
|
|
21
|
+
}
|
|
22
|
+
__name(isFinalAnswer, "isFinalAnswer");
|
|
10
23
|
var INITIAL_STATE = {
|
|
11
24
|
user: null,
|
|
12
25
|
status: "loading",
|
|
@@ -41,7 +54,7 @@ function authReducer(state, action) {
|
|
|
41
54
|
}
|
|
42
55
|
__name(authReducer, "authReducer");
|
|
43
56
|
function isSessionExpiredError(error) {
|
|
44
|
-
return error
|
|
57
|
+
return clientErrorStatus(error) === 401;
|
|
45
58
|
}
|
|
46
59
|
__name(isSessionExpiredError, "isSessionExpiredError");
|
|
47
60
|
function AuthProvider({ children, client, onSessionExpired, revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS }) {
|
|
@@ -191,17 +204,25 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
191
204
|
}, [
|
|
192
205
|
syncedDispatch
|
|
193
206
|
]);
|
|
207
|
+
const clearSession = useCallback(() => {
|
|
208
|
+
sessionGenerationRef.current = {};
|
|
209
|
+
syncedDispatch({
|
|
210
|
+
type: "CLEAR_SESSION"
|
|
211
|
+
});
|
|
212
|
+
}, [
|
|
213
|
+
syncedDispatch
|
|
214
|
+
]);
|
|
194
215
|
const logout = useCallback(async () => {
|
|
195
216
|
try {
|
|
196
217
|
await clientRef.current.logout();
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
});
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (!isFinalAnswer(error)) throw error;
|
|
220
|
+
clearSession();
|
|
221
|
+
throw error;
|
|
202
222
|
}
|
|
223
|
+
clearSession();
|
|
203
224
|
}, [
|
|
204
|
-
|
|
225
|
+
clearSession
|
|
205
226
|
]);
|
|
206
227
|
const refresh = useCallback(async () => {
|
|
207
228
|
await revalidate(false);
|