@mielk/auth 0.0.0-stage → 2.0.0

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +670 -2
  4. package/dist/client/api-address.d.ts +17 -0
  5. package/dist/client/api-address.js +434 -0
  6. package/dist/client/auth-client.d.ts +226 -0
  7. package/dist/client/auth-client.js +676 -0
  8. package/dist/client/errors.d.ts +66 -0
  9. package/dist/client/errors.js +33 -0
  10. package/dist/client/guards.d.ts +26 -0
  11. package/dist/client/guards.js +27 -0
  12. package/dist/client/index.d.ts +4 -0
  13. package/dist/client/index.js +2 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +4 -0
  16. package/dist/locales/en-GB.json +50 -0
  17. package/dist/locales/pl.json +50 -0
  18. package/dist/messages.d.ts +65 -0
  19. package/dist/messages.js +57 -0
  20. package/dist/pg/index.d.ts +1 -0
  21. package/dist/pg/index.js +1 -0
  22. package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
  23. package/dist/pg/pg-auth-repository.d.ts +91 -0
  24. package/dist/pg/pg-auth-repository.js +252 -0
  25. package/dist/react/auth-provider.d.ts +70 -0
  26. package/dist/react/auth-provider.js +72 -0
  27. package/dist/react/index.d.ts +2 -0
  28. package/dist/react/index.js +1 -0
  29. package/dist/schemas/index.d.ts +234 -0
  30. package/dist/schemas/index.js +145 -0
  31. package/dist/server/access-token.d.ts +48 -0
  32. package/dist/server/access-token.js +54 -0
  33. package/dist/server/auth-middleware.d.ts +40 -0
  34. package/dist/server/auth-middleware.js +61 -0
  35. package/dist/server/config.d.ts +231 -0
  36. package/dist/server/config.js +250 -0
  37. package/dist/server/cookies.d.ts +13 -0
  38. package/dist/server/cookies.js +35 -0
  39. package/dist/server/core.d.ts +20 -0
  40. package/dist/server/core.js +32 -0
  41. package/dist/server/create-auth.d.ts +38 -0
  42. package/dist/server/create-auth.js +33 -0
  43. package/dist/server/errors.d.ts +177 -0
  44. package/dist/server/errors.js +201 -0
  45. package/dist/server/http-errors.d.ts +9 -0
  46. package/dist/server/http-errors.js +34 -0
  47. package/dist/server/limits.d.ts +95 -0
  48. package/dist/server/limits.js +98 -0
  49. package/dist/server/one-time-token.d.ts +49 -0
  50. package/dist/server/one-time-token.js +60 -0
  51. package/dist/server/opaque-token.d.ts +6 -0
  52. package/dist/server/opaque-token.js +7 -0
  53. package/dist/server/password.d.ts +43 -0
  54. package/dist/server/password.js +78 -0
  55. package/dist/server/ports.d.ts +343 -0
  56. package/dist/server/ports.js +11 -0
  57. package/dist/server/proxy-check.d.ts +16 -0
  58. package/dist/server/proxy-check.js +78 -0
  59. package/dist/server/refresh-token.d.ts +60 -0
  60. package/dist/server/refresh-token.js +122 -0
  61. package/dist/server/router.d.ts +29 -0
  62. package/dist/server/router.js +331 -0
  63. package/dist/server/service.d.ts +158 -0
  64. package/dist/server/service.js +270 -0
  65. package/package.json +136 -5
package/CHANGELOG.md ADDED
@@ -0,0 +1,74 @@
1
+ # Changelog
2
+
3
+ All notable changes to this library are documented in this file. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the library uses [Semantic Versioning](https://semver.org/).
5
+ Entries are written by hand; `npm version` moves them from Unreleased to the released version.
6
+ Versions up to 1.1.6 were generated by standard-version and are kept unchanged.
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [2.0.0] - 2026-11-22
11
+
12
+ ### Changed
13
+
14
+ - **Breaking:** the package is renamed from `mielk-auth` to `@mielk/auth` (scope `@mielk` of the npm account `mielk`); `mielk-auth` gets no new versions, and after 2.0.0 is published it is to be marked deprecated on npm in a separate step. Migration: replace `mielk-auth` with `@mielk/auth` in `package.json` and in every import, including subpaths (e.g. `mielk-auth/schemas` becomes `@mielk/auth/schemas`); do not keep both packages in one application (TASK-230).
15
+ - **Breaking:** access tokens issued before 2.0.0 are refused: 2.0.0 verifies the header type `at+jwt` and the claims `iss` (`@mielk/auth`) and `aud` (`limits.appPrefix`), so the tokens of 1.1.6 (signed without `iss`, `aud` and the type) and of earlier unreleased 2.0.0 builds (`iss` `mielk-auth`) are not accepted (see Fixed, audit TASK-191.13, S2). Migration: after the upgrade every client gets a new access token from 2.0.0 (a refresh, or a new login where its refresh token is refused too), and a service outside the library that verifies the access tokens itself is changed to the same `typ`, `iss` and `aud` checks in the same deployment (TASK-230).
16
+ - `npm run test:dist` runs the tests that need the built package after `npm run build`, in CI and in `prepublishOnly`: `check:readme` refuses an example that calls a method `AuthClient` does not have or a property `createAuth` does not have (TASK-230). The code of the library is unchanged.
17
+ - The test of r1:U1 (`POST /register` answers 202 while the mailer is still sending) counts its 1 s from the call of the mailer, not from the request, so the bcrypt hash under the load of parallel test files no longer fails it; a regression test runs it with the processors kept busy, which reproduced the old limit in most runs, not in all (TASK-388). The code of the library is unchanged.
18
+ - `npm run check:readme` reports an unclosed code fence as an error, ends with a one-line message and exit code 1 for a file that does not exist, and also compiles `typescript` blocks and any letter case of `ts`, `tsx` and `typescript`; the README lists the command in "Development" (TASK-391).
19
+ - `npm run check:readme` compiles the `ts` and `tsx` examples of the README against the built package with the settings of the project (`noUnusedLocals` included), and runs in CI and in `prepublishOnly`; it found and fixed two examples with unused names (`onUserDeleted`, `authorizedFetch`; TASK-191.15).
20
+ - **Breaking:** `refreshToken.reuseGraceSeconds` accepts 0-60 (was 0-300), as `rest:AUT-4` requires; a larger value is a configuration error. `REFRESH_TOKEN_REUSE_GRACE_MAX_SECONDS` is 60. A token issued in the grace window now expires no later than the token presented (it used to get the full lifetime), and a detected reuse of a rotated token is logged as a warning (`errorCategory: 'refresh_token_reused'`, no token) through the `AuthLogger` of the application (`rest:AUT-4`, `AUT-11`; TASK-191.8).
21
+ - The tests that start a server are named `*.integration.spec.ts`, and the tests on PostgreSQL are a separate suite (`vitest.pg.config.ts`, `npm run test:pg`) that accepts only a local host (`ts:TST-5`; TASK-191.8).
22
+ - **Breaking:** the library is rebuilt from scratch (TASK-191). The old exports, the Jest and Babel setup and the `standard-version` release script are removed. `createAuth(config)` replaces `createAuthServices(config, repository)`: the repository is passed as `config.repository`, the router replaces the old controllers, and `authMiddleware` replaces the old middleware (see Added). The old `mielk-http` and `mielk-api` imports are replaced: `@mielk/http` (`^3`) is now an optional peer dependency of the server part, used for the limits, the API errors and the validation. The migration of applications is described in the README ("Connecting in an Nx application", step 5). Dependencies: `express`, `jose`, `bcryptjs`, `react`, `@mielk/db`, `@mielk/http` and `pg` are optional peer dependencies, `zod` is a required one. Entry points: `@mielk/auth` (server) and `@mielk/auth/schemas` have content, and so do `client`, `react`, `pg` and `locales/*`.
23
+ - Development dependencies updated to the latest patch and minor versions (`eslint` 10.15.0, `vitest` and `@vitest/coverage-v8` 5.1.1, `jose` 6.2.18, `pg` and `@types/pg` 8.23.1, `typescript` 5.9.3; `ts:DEP-8`); major versions are left on purpose (TypeScript 7 needs its own task by `ts:DEP-7`; `redis` stays at 5.12.4, because the installed `@mielk/fn` 2.1.0 and `@mielk/http` declare the peer dependency `redis` `^5`, so `redis` 6.3.1 would break their peer range and `npm ci` (Node does not block it, `engines` `>= 20`); moving to 6 needs those packages released first, a separate task; `@types/node` 24.x matches the minimum Node.js 24; `jsdom` stays at 29.1.1, because 30.x and 31.0.1 declare `engines` `^22.22.2 || ^24.15.0 || >=26.0.0` and the repository pins Node 24.13.0, which matches none of them; `ts:DEP-3`, TASK-191.6 U6); no change for users. `npm audit` reports no vulnerabilities (two moderate ones in `eslint` through `minimatch` are gone).
24
+
25
+ ### Fixed
26
+
27
+ - A login over a session (another account, or the same one, without a logout first) left the refresh token it replaced valid on the server until it expired (TASK-191.10, DEC-315). `@mielk/auth/client` in the `mobile` mode now revokes the token the login overwrote in the token store (`POST /mobile/logout`, also a stored token not restored yet), after the new session is put in place; a failure of that request is ignored. `POST /login` (web) revokes the refresh token of the cookie the request brought, only after the login succeeded; when the revocation fails the login still answers 200 and a warning is logged through the `AuthLogger` without the token.
28
+ - Only `confirmEmail` refused a redirect; the other calls the library builds itself (`login`, `register`, `refresh`, `logout`, `getMe`, `changePassword`, `revokeAllSessions`, `deleteAccount`, `resendEmailVerification`, `requestPasswordReset`, `confirmPasswordReset`, `restoreSession`) followed a 307 or 308 with the body (the password or the refresh token) to the new address, of any origin. They now send `redirect: 'error'`, so the request fails as a network failure and nothing is sent to the new address. The public call then does what it does for any network failure: `login`, `register`, `refreshAccessToken`, `getMe` and the other account calls reject with an `AuthClientError` of the kind `network`; `restoreSession()` ends `anonymous` and keeps the refresh token; `logout()` ends the local session and resolves. A `fetch` passed in the options must honour `redirect: 'error'`. `authorizedFetch` is unchanged: it follows a redirect and relies on the `fetch` dropping `Authorization` on another origin (DEC-314, TASK-191.17).
29
+ - The mobile `refresh` and `logout` (refresh token in the body), the web `refresh` and `logout`, `requestPasswordReset` and the internal `GET /me` of `restoreSession()` sent a relative address under an empty or a path-only `baseUrl`, which a browser resolves against the `<base>` of the document (audit TASK-191.12, TASK-191.14): every call of `AuthClient` now builds its address as `authorizedFetch` does (origin from `location.href`, never the document base; without `location` a `TypeError` before sending; `restoreSession()` ends `anonymous`, `logout()` ends the local session (mobile: removes the token; web: sends no request, the cookie stays), and the revoking of a dropped token sends no request). `mobile` mode needs an absolute `baseUrl`. The public types of the client carry `@since 2.0.0`.
30
+ - Links sent to one account had no limit (audit TASK-191.13, S5): `POST /email-verification` could mail a link on every request and reset requests from many addresses replaced the link of the owner. New limits per account: `limits.verificationEmail` (default 3 per hour, per user, after `authMiddleware`; over it 429) and `limits.passwordResetEmail` (default 3 per hour per account, from any address, for the reset links and the `account_exists` notices of a registration; over it the answer stays 202 but no e-mail is sent and no token is issued, so the last link sent keeps working). A failure of Redis there sends nothing and is logged.
31
+ - Sessions from before the e-mail verification and confirmation without the password (audit TASK-191.13, S4; DEC-281): **breaking for 2.0.0 drafts:** `POST /email-verification/confirm` takes `{ token, password }` (`confirmEmailBodySchema`, `ConfirmEmailBody`, `AuthClient.confirmEmail`), so only who has both the link and the password of the account confirms the address; a wrong password answers 400 `api/auth/password:currentInvalid` and leaves the link usable, and the attempts count in `limits.passwordCheck` of the account of the link (with `PUT /password` and `DELETE /me`). `AuthClient.confirmEmail` sends the token and the password only to the origin of `baseUrl` by the address rules of `authorizedFetch`: with an empty or a path-only `baseUrl` to the origin of `location.href`, never to the base URL of the document, and without `location` it rejects with a `TypeError` before sending; `login`, `register`, `confirmPasswordReset`, `changePassword`, `revokeAllSessions` and `deleteAccount` build their address the same way (DEC-293). `confirmEmail` does not follow a redirect (`redirect: 'error'`; a 307 or 308 would send the body to the new address): the answer of a redirect rejects with an `AuthClientError` of the kind `network`. Confirming the e-mail also revokes every refresh token of the account in the same transaction; the owner signs in again. New middleware `requireVerifiedEmail` returned by `createAuth` (after `authMiddleware`) lets through only an account with a verified e-mail and an access token issued after the verification (the token carries the claim `email_verified: true`, set at login and refresh from the account read under the lock of the user; a token from before the confirmation is refused until it expires, also after the owner recovered the account): 403 `api/auth/emailVerification:required` (new `EmailNotVerifiedError`, code `EMAIL_NOT_VERIFIED`) for an unverified one, 401 for an account that no longer exists.
32
+ - `@mielk/auth/pg`: with a unique index of the e-mail named other than `users_email_lower_key` (an existing `users` table adapted to the migration), registering a registered address failed with the raw unique violation and `POST /register` answered 500 instead of 202, which revealed the account again (audit TASK-191.13, N19 a; DEC-281). `createUser` now looks the e-mail up in the statement of the insert and inserts only when no account has it, so a registered address is `EmailTakenError` without a further read, whatever the name of the index, and inside a transaction of the application the transaction stays usable; a violation of another index with a free e-mail is passed on unchanged.
33
+ - `POST /register` revealed whether an address has an account (audit TASK-191.13, S3): it answered 409 `api/auth/register:emailTaken` for a registered address and 201 with the user for a new one. **Breaking for 2.0.0 drafts:** it now answers 202 without a body in both cases; a registered address gets no new account and no change, and the mailer is asked for the new kind `account_exists` (type `AuthMailKind`) with a password reset link of that account; the mailer of the application must handle it. `AuthClient.register` resolves with nothing. The password is hashed in both cases, and the answer is sent after the account step, before the e-mail: the verification link, or the reading of the registered account, its limit per account and the notice, are sent after the answer, as for `POST /password-reset`, so the time of the answer does not reveal the account either (r1:U1); a logger that throws or returns a rejected promise while it logs a failure of the mailer is ignored (`logError`; r3:U1), and any other rejection of that work is caught by the router and does not end the process, also for `POST /password-reset` (r2:U1). `EmailTakenError` stays the contract of `AuthRepository.createUser`.
34
+ - Access tokens of one application were valid in another with the same secret (audit TASK-191.13, S2): an access token now has the header type `at+jwt` and the claims `iss` (`@mielk/auth`) and `aud` (`limits.appPrefix`), and verification requires all three, so a token of an application with another `appPrefix`, or any other JWT signed with the secret, is refused. Tokens issued before the change are refused too (the client refreshes the session). `jwt.secret` with fewer than 8 different characters or made of a repeated sequence is refused at start (`AuthConfigError`, without the value).
35
+ - Transactions and the shared pool (audit TASK-191.13, S8): login, account deletion and password reset no longer run bcrypt or Redis inside their transaction. The password is checked before the transaction and, under the lock of the user, only the stored hash is compared with the checked one (a change of the password meanwhile refuses the operation); a reset refuses a token that cannot be used before any bcrypt work and hashes the new password before its transaction; the login counters are reset after the password check and before the session is issued. The PostgreSQL adapter waits for the lock of a user at most `lockTimeoutMs` (new option of `createPgAuthRepository`, default 3000 ms) and then fails with the new `AccountBusyError` (`ACCOUNT_BUSY`, 503, `api/auth/account:busy`). The README asks for `idle_in_transaction_session_timeout` and `statement_timeout` on the role of the application.
36
+ - Lock of an e-mail (audit TASK-191.13, N4): a confirmed password reset removes the lock and the counter per e-mail of its account, so the new password logs in at once; a login body is validated before the guards per e-mail, so a body without a password (400) counts only against the address and can no longer lock an e-mail.
37
+ - `PUT /password` and `DELETE /me` were an unlimited password oracle for a holder of the access token (audit TASK-191.13, S6; TASK-300): the new limit `limits.passwordCheck` (default 5 per 15 minutes) counts both together per user, before the body is read and before bcrypt, answers 429 over it without locking the e-mail, and is cleared after the right password.
38
+ - Limits per IP address and `trust proxy` (audit TASK-191.13, W2 and S10): a web `POST /refresh` without the refresh cookie is answered 401 before the limit and is no longer counted, so anonymous page loads (the client restores the session on every start) do not spend the refresh budget of an address shared by signed-in users. The router logs a warning once (field `proxyCheck`, no address) when a request has `X-Forwarded-For` while `req.ip` is a loopback or private address (`trust proxy` missing behind a proxy) and when `trust proxy` is `true`; the README describes the setting and both mistakes.
39
+ - `@mielk/auth/client`: with a path-only `baseUrl` (`/gateway`) `getMe` and `resendEmailVerification` went to `/gateway/gateway/v1/auth/...`; they now go under the prefix of `baseUrl` once, like the other operations (audit TASK-191.13, S9).
40
+ - Password hashing (audit TASK-191.13, W1): the bcrypt work running at once is bounded by the new option `passwordHashing` (`maxConcurrent` default 2, `maxQueued` default 32); a request beyond it is refused at once with 503 `PasswordHashingBusyError` (`PASSWORD_HASHING_BUSY`, `api/auth/password:busy`). `PUT /password` checks the current password first and hashes the new one only after it matched, both outside the transaction; under the lock of the user it checks that the stored hash is still the checked one.
41
+ - `POST /refresh` clears the refresh cookie only when the token is rejected (`REFRESH_TOKEN_INVALID`, `REFRESH_TOKEN_EXPIRED`, `REFRESH_TOKEN_REUSED`); a transient failure such as a database error (500) keeps it, so the client can retry as DEC-271 intends (audit TASK-191.13, S7).
42
+ - Refresh tokens (audit TASK-191.13, W3 and S1): a session is a token family (`familyId`, column `refresh_tokens.family_id`), and a detected reuse ends only that session instead of all sessions of the user. A token rotated at most `refreshToken.reuseGraceSeconds` ago (new option, 0-60, default 60) gets another new token of its session, so two tabs restoring the session with one cookie and a retry after a lost response no longer sign the user out everywhere. The expiry is checked first: an expired token is `REFRESH_TOKEN_EXPIRED` without side effects. A token whose session ended (logout, revoke all sessions, password change or reset) is `REFRESH_TOKEN_INVALID` without side effects; only a rotated token raises `REFRESH_TOKEN_REUSED`. Logout ends the whole session of the presented token; an expired token changes nothing, so an old cookie cannot end a session that lives on in its valid successor. **Port change:** `RefreshTokenRecord` has `familyId` and `revokedReason`, `revokeRefreshToken` takes the reason, `revokeRefreshTokenFamily` is new; the reference migration has the columns `family_id` and `revoked_reason`.
43
+ - `authorizedFetch` sends the access token only to the origin of `baseUrl`, provided the `fetch` used drops `Authorization` on a redirect to another origin (browsers and Node.js do, tested on Node.js; not verified in React Native). An address of another origin rejects with a `TypeError` without sending anything. The client decides the target on the text of the address without the global `URL` (the same in a browser, Node.js and React Native) and hands `fetch` the absolute address it built, with the canonical origin of the URL Standard (default port also with leading zeros, IPv6 and IPv4 notations, percent-encoded host letters), so nothing is resolved against the base URL of a document. A relative address is appended to the path of `baseUrl` and stays under it; dot segments (`.`, `..`, also `%2e`) are refused, empty segments kept. An empty or path-only `baseUrl` takes the origin of `location.href` and rejects where there is none. User information, a backslash, whitespace, a non-ASCII host, an `xn--` label outside the strict subset the client checks (see the README) and an input that is neither a string nor an object with a string `href` (a `Request` included) reject with a `TypeError`. **Migration:** with a `baseUrl` that has a path (`https://api.example.com/gateway`), `authorizedFetch('/v1/accounts')` now goes to `/gateway/v1/accounts` instead of `/v1/accounts`; to keep the old target pass the absolute address of the same origin (`https://api.example.com/v1/accounts`). An empty string in the token store of the mobile mode means no session, not a refresh token (TASK-191.12).
44
+
45
+ ### Added
46
+
47
+ - `@mielk/auth/pg`: `createPgAuthRepository()`, the PostgreSQL adapter of `AuthRepository` on the pool of `@mielk/db/pg` (the application calls `initDb`; `pg` is an optional peer dependency). `lockUser` is `SELECT … FOR NO KEY UPDATE` of the row of the user inside the transaction of `withTransaction`; only a violation of the unique index of the e-mail (`users_email_lower_key`) is `EmailTakenError`, other violations are passed on; the tables carry `DELETE-ALLOWED:` comments. The reference migration `@mielk/auth/pg/migrations/0001_mielk_auth.sql` (tables `users`, `refresh_tokens`, `auth_tokens`) is copied by the application to its own migrations. The contract tests of the port run on a real PostgreSQL when `MIELK_AUTH_TEST_PG_HOST` and `MIELK_AUTH_TEST_PG_PASSWORD` (and optionally `_PORT`, `_USER`) point at a local server.
48
+ - Entry points `@mielk/auth`, `@mielk/auth/schemas`, `@mielk/auth/client`, `@mielk/auth/react`, `@mielk/auth/pg` and `@mielk/auth/locales/*` (JSON translations, imported without the extension, e.g. `@mielk/auth/locales/pl`).
49
+ - `@mielk/auth`: types of the configuration (`AuthConfig`) and of the ports the application implements (`AuthRepository`, `AuthMailer`, `OnUserDeleted`, `Clock`) with their records; `AuthRepository` documents the concurrency guarantees an adapter must give, including `lockUser`, which serializes the token changes of one user (the user is always locked before the rows of its tokens, so `findAuthToken` reads the owner of a token before it is used); the error classes (`AuthError` with a `code` and a `messageKey`, and its subclasses) and the message keys `Msg` (`api/auth/<area>:<name>`). The server core behind them (configuration validation, access tokens JWT HS256 on `jose`, refresh token rotation with reuse detection, one-time tokens, bcrypt cost 12 password hashing) is internal until `createAuth` arrives.
50
+ - `@mielk/auth`: the login checks the password and issues the session under the lock of the user, so a parallel change or reset of the password cannot leave a session of the old password; the failures of the mailer are logged and thrown without the address, the link or the original message (`LinkDeliveryError`); logs carry fixed error categories (`errorCategory`), never the name or the fields of an error from a dependency.
51
+ - `@mielk/auth`: `createAuth(config)` returns `{ router, authMiddleware }`. The router (mount it under `/v1/auth`) has the endpoints of registration, login and logout for the web (refresh token only in the `httpOnly`, `SameSite=Strict`, `Path=/v1/auth` cookie) and for mobile clients (`/mobile/*`, refresh token in the body, a request with an `Origin` header is refused with 403 before the router parses the body; an application that parses JSON earlier, e.g. on `createExpressApp` of `@mielk/http`, mounts the exported `mobileOriginGuard` before that parser, otherwise a malformed body is answered 400 by the parser, without a token), refresh with rotation and reuse detection, `GET` and `DELETE /me`, `POST /sessions/revoke-all`, e-mail verification, password reset and `PUT /password`. Password change and reset revoke all refresh tokens. Errors of the library are turned into the API errors of `@mielk/http` (`UnauthorizedError`, `ConflictError`, ...), so the application registers `notFoundHandler` and `errorHandler` of `@mielk/http` after the router. `authMiddleware` sets `req.user.userId`.
52
+ - `@mielk/auth`: limits and locks of the authentication endpoints on `@mielk/http/rate-limit` (`rest:LIM-2`–`LIM-5`): registration, password reset and refresh per IP address; login per IP address, per IP address and e-mail, and per e-mail with a lock of the e-mail (423) after the limit is exceeded; a successful login resets the counters of the e-mail and removes its lock (when Redis cannot do it, the login is answered 503, its transaction is rolled back and no session exists). Every answer of the login guards, the 423 and the 400 of a rejected or malformed body included, carries `X-RateLimit-*` (the router parses the body after the limit per IP address; a body parsed earlier by the application is answered by its parser without the headers). Defaults: 5 login attempts per 15 minutes per IP address, per e-mail and per IP address and e-mail, and a 15-minute lock (the limit per IP address answers first, so one address is stopped by its own 429 without locking the e-mail; the lock is set when attempts from several addresses exceed the limit per e-mail); every setting is in `AuthConfig.limits`, which also takes the required prefix of the application in the Redis keys (`appPrefix`). The e-mail is in a key only as the SHA-256 of its trimmed lower-case form. While Redis is unavailable these endpoints answer 503. The global limit of all endpoints is not set by the library: the application passes it to `createExpressApp` of `@mielk/http`.
53
+ - `@mielk/auth/schemas`: Zod schemas of the request bodies (the password policy: at least 10 characters, at most 72 bytes) and the types of the request and response bodies. New message keys: `api/auth/validation:*`, `api/auth/mobile:originForbidden`, `api/auth/accessToken:missing`, `api/auth/password:{tooShort,required,currentInvalid}`; new error class `CurrentPasswordInvalidError`.
54
+ - `@mielk/auth/client`: `createAuthClient({ baseUrl, mode, tokenStore?, fetch?, getLocale? })`, the session manager for web (refresh token in the cookie) and mobile (refresh token in the store of the application; `RefreshTokenStore`). The access token lives only in memory; `authorizedFetch` repeats a request once after one refresh shared by all parallel 401 answers; the new refresh token is stored before it is used; a logout, a rejected refresh token and a password change clear the stored token and the state. Every operation that changes the session (login, logout, refresh, restore, password change and reset, account deletion, revoke-all, and every operation on the token store) runs whole in one queue of session operations, in the order they were called, so their requests, store writes and state changes never interleave; nothing about the session changes when such an operation is called, only in its turn (a login that succeeds is put in place even when a later login or logout was asked for meanwhile, and that one then replaces or ends it); each network request of a session operation has one time limit of 30 seconds from `fetch` to the end of reading its body (then the request and the reading are aborted through its signal and fail as a network error, and the queue goes on); other requests (`authorizedFetch`, `getMe`, `resendEmailVerification`) run in parallel, wait only for the session operations asked for before them, and parallel 401 answers of one session share one queued refresh, which uses the access token an operation queued before it has already renewed for that session (recognised by the count of ended refreshes, not by the text of the token) instead of refreshing again; a logout clears the state in its turn and then revokes and removes the stored token; every asynchronous call belongs to the session in place when it is called (a logout or a successful login replaces it, a login only asked for does not) and has an effect only while that session is in place, so an answer of a session that has ended or been replaced changes nothing in the current one, a request is never sent or repeated with the token of another session, and in the mobile mode a refresh token that arrives in time for it is revoked on the server (an answer that comes after the 30-second limit is ignored, its refresh token neither stored nor revoked); the session is checked right before each request is handed to `fetch`, after the application's `getLocale`, and the access token, the session and the state change together; password change, revoke-all, account deletion and `authorizedFetch` send nothing for a replaced session and reject with the kind `session-changed`; a password reset ends the session of the client in its operation; in the mobile mode a login whose token cannot be saved leaves the store as it found it and revokes its token, so the stored token always belongs to the session in memory or to no session; a subscriber or a `getLocale` that throws (or a `getLocale` value the headers refuse) changes nothing in the client, the other subscribers are still called and the exception is reported as an uncaught error in a microtask (a value that is not an `Error` is wrapped in one, as its `cause`; a token store that rejects with such a value does the same for the caller). A web logout whose cookie stays can be restored by a new client with `restoreSession`; on the same client `restoreSession` runs once and returns its first result. A failed reading of the body of an answer rejects the operation with an `AuthClientError` of the kind `network`. A refresh that fails for a transient reason (no network, no answer in time, 5xx, 429) keeps the refresh token; only 401 or 403 ends the session. Actions: login, registration, logout, `getMe`, password change and reset, e-mail verification, revoking all sessions and deleting the account. Errors are `AuthClientError` with `kind`, a message key, `status`, `issues` and `retryAfterSeconds`. No runtime dependencies.
55
+ - `@mielk/auth/react`: `AuthProvider` (restores the session once, also in StrictMode), `useSession()` (`loading` / `anonymous` / `authenticated`), `useAuth()` (state with login, registration, logout and password change) and `useAuthClient()`.
56
+ - `@mielk/auth/locales/pl` and `@mielk/auth/locales/en-GB`: translations of every message key of the library, grouped by the namespace of the key; a test compares them with `Msg`. New message keys `api/auth/client:networkError`, `api/auth/client:invalidResponse` and `api/auth/client:sessionChanged`.
57
+ - Documentation: the README has a guide to connect the library in an Nx application (database migration, API, web, mobile, migration from 1.x). Public elements have TSDoc with `@since 2.0.0`; `tsdoc.json` declares the custom tags `@tag` and `@edge`. Documentation for agents is in `doc/agent/` (TASK-191.7).
58
+ - Tooling of the `@mielk` libraries: Vitest with coverage, ESLint, Prettier, `.nvmrc`, `.gitattributes`, `LICENSE`, and the CI workflow with the package check and the package import check (`npm run check:import`).
59
+
60
+ ### [1.1.6](https://github.com/mielk/mielk-auth/compare/v1.1.5...v1.1.6) (2026-04-20)
61
+
62
+ ### [1.1.5](https://github.com/mielk/mielk-auth/compare/v1.1.4...v1.1.5) (2026-04-03)
63
+
64
+ ### [1.1.4](https://github.com/mielk/mielk-auth/compare/v1.1.3...v1.1.4) (2026-04-03)
65
+
66
+ ### [1.1.3](https://github.com/mielk/mielk-auth/compare/v1.1.2...v1.1.3) (2026-04-03)
67
+
68
+ ### [1.1.2](https://github.com/mielk/mielk-auth/compare/v1.1.1...v1.1.2) (2026-04-03)
69
+
70
+ ### [1.1.1](https://github.com/mielk/mielk-auth/compare/v1.1.0...v1.1.1) (2026-04-03)
71
+
72
+ ## [1.1.0](https://github.com/mielk/mielk-auth/compare/v1.0.1...v1.1.0) (2026-04-03)
73
+
74
+ ### 1.0.1 (2026-04-03)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mielk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.