@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/README.md CHANGED
@@ -1,3 +1,671 @@
1
- # Temporary Holding Version
1
+ # @mielk/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Authentication for mielk applications: a server part for Express, a client for web and mobile, a React layer and a
4
+ PostgreSQL adapter, in one package with several entry points.
5
+
6
+ Versions 1.x were published as `mielk-auth` (the last one on npm is 1.1.5). Version 2.0.0 and later are to be published as `@mielk/auth` (repository `mielk-auth`); `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. The migration is described in [CHANGELOG.md](CHANGELOG.md).
7
+
8
+ Version 2 is a rebuild of the library (TASK-191) and is not compatible with 1.x: see "Connecting in an Nx application" and its migration table. The main entry point `@mielk/auth` has the server part: `createAuth(config)`
9
+ returns the Express router of the endpoints, `authMiddleware` and `requireVerifiedEmail`; it also exports the configuration and port types
10
+ (`AuthRepository`, `AuthMailer`, `OnUserDeleted`, `Clock`), the error classes and the message keys (`Msg`).
11
+ `@mielk/auth/schemas` has the Zod schemas of the requests and the TypeScript types of the requests and responses, `@mielk/auth/client` the session client,
12
+ `@mielk/auth/react` the provider and hooks, and `@mielk/auth/locales/<l>` the translations of the message keys; `@mielk/auth/pg`
13
+ has the PostgreSQL adapter and the reference migration.
14
+
15
+ ## Installation
16
+
17
+ Requires Node.js 24 or newer (`engines.node` is `>=24`). `zod` is a required peer dependency; install the other peer
18
+ dependencies only for the entry points you use. The server part needs `express`, `jose`, `bcryptjs` and `@mielk/http`
19
+ (`^3`, with Redis, which keeps the limits and locks):
20
+
21
+ ```
22
+ npm install @mielk/auth zod express jose bcryptjs @mielk/http
23
+ ```
24
+
25
+ The command above works once `@mielk/auth` 2.0.0 is published on the registry. Until a version is on the registry (2.0.0
26
+ before its publication, or a change not published yet that you check in an application, `npm:WYD-5`), build a tarball in this repository and
27
+ install that file instead of the registry name; the `import` lines stay the same (`@mielk/auth`, `@mielk/auth/client`,
28
+ ...), because the package in the tarball has the name `@mielk/auth`:
29
+
30
+ ```
31
+ # in the @mielk/auth repository, on the branch to verify
32
+ npm ci
33
+ npm run build
34
+ npm pack # creates mielk-auth-<version>.tgz
35
+ # in the application
36
+ npm install ../mielk-auth/mielk-auth-<version>.tgz zod express jose bcryptjs @mielk/http
37
+ ```
38
+
39
+ The package is ESM only. Changes between versions are listed in [CHANGELOG.md](CHANGELOG.md).
40
+
41
+ ## Entry points
42
+
43
+ | Entry point | Purpose | Environment | Peer dependencies (besides required `zod ^4`; all optional) |
44
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------- | ----------------------------------------------------------- |
45
+ | `@mielk/auth` | Server side: authentication services and Express wiring | Node.js | `express ^5`, `jose ^6`, `bcryptjs ^3`, `@mielk/http ^3` |
46
+ | `@mielk/auth/schemas` | Zod schemas of the requests, types of the requests and responses | Node.js, web, mobile | `zod ^4` (required) |
47
+ | `@mielk/auth/client` | Client for the authentication API (framework independent) | web, mobile | none |
48
+ | `@mielk/auth/react` | React layer: provider and hooks on top of the client | web, mobile | `react ^19` |
49
+ | `@mielk/auth/pg` | PostgreSQL adapter of the repository | Node.js | `@mielk/db ^3`, `pg ^8` |
50
+ | `@mielk/auth/pg/migrations/<file>` | Reference SQL migration `0001_mielk_auth.sql` (copied by the application to its own migrations) | Node.js | none |
51
+ | `@mielk/auth/locales/<l>` | JSON translations (`pl`, `en-GB`) | all | none |
52
+
53
+ ## Connecting in an Nx application
54
+
55
+ What the application provides: a PostgreSQL database (the library stores accounts and tokens there), Redis (counters
56
+ and locks of the limits, through `@mielk/http`), a mailer (the library only asks for a message to be sent) and secrets
57
+ in its own configuration (the library reads no environment variables). The steps below connect the API, a web
58
+ application and a mobile application; each step names what to install.
59
+
60
+ ### 1. Database
61
+
62
+ The library ships one reference migration, `@mielk/auth/pg/migrations/0001_mielk_auth.sql`, with the tables `users`,
63
+ `refresh_tokens` and `auth_tokens` (only SHA-256 hashes of tokens are stored). The library does not run it:
64
+
65
+ 1. Copy the file from `node_modules/@mielk/auth/dist/pg/migrations/0001_mielk_auth.sql` to the migrations of the
66
+ application as `<schema>/NNNN_mielk_auth.sql`, with the next number of its sequence.
67
+ 2. Replace `app` in `SET LOCAL search_path = app, pg_catalog;` with the schema of the application. The connection of
68
+ the application must find the three tables on its `search_path`.
69
+ 3. Run it as the owner role of the schema, in one transaction (the file is one transaction, so a failed run leaves
70
+ nothing behind).
71
+ 4. An application that already has the table `users` adapts the file instead of creating the table. Settle the
72
+ identifier first, before the token tables are created:
73
+ - `user_id` must be `bigint` and the primary key of `users`; the foreign keys `refresh_tokens.user_id` and
74
+ `auth_tokens.user_id` reference it. The adapter selects it and passes it back as a string, but never inserts it:
75
+ the database must generate it on `INSERT` (an identity column or a sequence default). A table whose key has another
76
+ type, another name or no generated value is migrated (or mapped to a new `user_id`) by the application first.
77
+ - Existing accounts keep their rows: map each account to a `user_id`, its e-mail to `email` and its bcrypt hash to
78
+ `password_hash` (`NULL` for an account without a password).
79
+ - Add the missing columns (`email`, `password_hash`, `email_verified_at`, `created_at`, `updated_at`) and the unique
80
+ index `users_email_lower_key` on `lower(email)`. An existing unique index on `lower(email)` may keep its own name:
81
+ `createUser` looks the e-mail up in the same statement as the insert and inserts only when no account has it, so a
82
+ registered address is recognised whatever the name of the index (`POST /register` answers 202 either way, audit
83
+ N19 a, r1:U1).
84
+ 5. Rollback of a deployed migration is a new migration of the application that drops `auth_tokens` and
85
+ `refresh_tokens` in this order. It drops `users` only when this migration created it; an application that adapted an
86
+ existing `users` table keeps it (it removes only the columns and the index it added, when nothing else uses them).
87
+ The library never changes the tables itself.
88
+ 6. The adapter uses the pool of `@mielk/db/pg`, the same pool as the rest of the application (one per process). Its
89
+ transactions are short: bcrypt and Redis run before them, and the lock of a user is waited for at most
90
+ `lockTimeoutMs` (`createPgAuthRepository({ lockTimeoutMs })`, 1-60000, default 3000); then the request is answered
91
+ 503 (`AccountBusyError`, `api/auth/account:busy`) instead of holding a connection while requests of one account
92
+ queue up. Set limits for the role of the application as well, so a transaction stuck in application code cannot hold
93
+ the pool either (`pg:TRX-1`, `pg:TRX-4`), for example:
94
+
95
+ ```sql
96
+ ALTER ROLE app_finance SET idle_in_transaction_session_timeout = '15s';
97
+ ALTER ROLE app_finance SET statement_timeout = '30s';
98
+ ```
99
+
100
+ ### 2. API (Node.js)
101
+
102
+ ```
103
+ npm install @mielk/auth zod express jose bcryptjs @mielk/http @mielk/db pg helmet # or the tarball of a version not on the registry yet, see Installation
104
+ ```
105
+
106
+ ```ts
107
+ import express from 'express';
108
+ import helmet from 'helmet';
109
+ import { initDb } from '@mielk/db/pg';
110
+ import { createExpressApp, errorHandler, notFoundHandler } from '@mielk/http';
111
+ import { createAuth, mobileOriginGuard, type AuthMailer } from '@mielk/auth';
112
+ import { createPgAuthRepository } from '@mielk/auth/pg';
113
+
114
+ // Provided by the application (not part of the library): config, dbConfig, redisConfig, pinoLogger, accountsRouter,
115
+ // sendMail, renderTemplate.
116
+
117
+ initDb(dbConfig); // 1. @mielk/db/pg: the pool the repository uses
118
+
119
+ const mailer: AuthMailer = {
120
+ async send({ kind, to, url, locale }) {
121
+ // kind: 'email_verification' | 'password_reset' | 'account_exists'; the mailer must handle all three (a
122
+ // mailer written for an earlier 2.0.0 draft must add 'account_exists'). url carries the one-time token in its
123
+ // fragment (#token=...). 'account_exists': somebody registered the address of an existing account; url is a
124
+ // password reset link of that account, and the text says the account exists and may be ignored if it was not them.
125
+ // The page of the 'email_verification' link asks for the password of the account (audit S4).
126
+ // The text and its translation into `locale` belong to the application. A failure of the mailer is logged by the
127
+ // library without the address and the link.
128
+ await sendMail(to, renderTemplate(kind, locale, url));
129
+ },
130
+ };
131
+
132
+ // 2. The inner application: request logger, security headers, shared Redis client, global limit, JSON parser.
133
+ const app = await createExpressApp({
134
+ appPrefix: 'finance', // the same prefix as limits.appPrefix below
135
+ redis: redisConfig,
136
+ globalRateLimit: { limit: 300, windowSec: 60 }, // example limit per IP address; choose it in the configuration of the application
137
+ // trustProxy: left out on purpose: the limiters key on req.ip, and with a direct connection to the application a client
138
+ // could spoof it through X-Forwarded-For. Behind a reverse proxy set it to the exact number of trusted proxy hops
139
+ // (e.g. trustProxy: 1 for one proxy in front of the application), only when that proxy overwrites X-Forwarded-For
140
+ // itself and the application is reachable only through it.
141
+ });
142
+
143
+ // 3. The library: it needs the Redis client of createExpressApp, so it comes after it.
144
+ const auth = createAuth({
145
+ jwt: { secret: config.jwtSecret }, // at least 32 random bytes, from the configuration, of this application only
146
+ links: { web: config.webUrl, mobile: config.mobileLinkBase }, // the links in e-mails lead only here
147
+ secureCookies: config.isProduction, // default true; false only in development (HTTP)
148
+ limits: { appPrefix: 'finance' }, // prefix of the Redis keys, required
149
+ repository: createPgAuthRepository(),
150
+ mailer,
151
+ onUserDeleted: async (_userId, _repository) => {
152
+ // Optional. Delete the application data of the account; runs in the transaction that deletes it.
153
+ },
154
+ logger: pinoLogger, // optional: failures that do not fail a request
155
+ });
156
+
157
+ // 4. Routers, then the final handlers (so the errors of the library are answered).
158
+ app.use('/v1/auth', auth.router);
159
+ app.use('/v1/accounts', auth.authMiddleware, accountsRouter); // in a handler: req.user.userId
160
+ app.use('/v1/invitations', auth.authMiddleware, auth.requireVerifiedEmail, invitationsRouter); // verified e-mail only
161
+ app.use(notFoundHandler);
162
+ app.use(errorHandler);
163
+
164
+ // 5. The outer application: the guard of the mobile endpoints must run before the JSON parser of createExpressApp.
165
+ const root = express();
166
+ root.disable('x-powered-by'); // the outer application answers the 403 of the guard
167
+ root.use(helmet()); // security headers also on that 403
168
+ root.use('/v1/auth/mobile', mobileOriginGuard);
169
+ root.use(app);
170
+ root.listen(config.port);
171
+ ```
172
+
173
+ - An invalid configuration throws `AuthConfigError` at start; it lists the invalid fields, never their values.
174
+ - `jwt.secret` is at least 32 bytes and random, e.g. `openssl rand -base64 32`, and belongs to one application only. A
175
+ secret with fewer than 8 different characters or made of a repeated sequence is refused at start. Access tokens are
176
+ JWT HS256 of the type `at+jwt` with `sub`, `iat`, `exp`, `iss` (`@mielk/auth`) and `aud` (`limits.appPrefix`); a token
177
+ of another type, issuer or audience is refused, so an application with another `appPrefix` refuses the tokens of this
178
+ one even when the secret is the same. This check cannot tell a weak secret that looks random, so do not reuse a secret.
179
+ - `jwt.accessTokenTtlSeconds` is 60-900 seconds (default 900); `refreshToken.ttlSeconds` is 1 hour to 30 days (default 7
180
+ days); `refreshToken.reuseGraceSeconds` (0-60, default 60) lets a token rotated that recently be rotated again
181
+ (two tabs restoring the session at once, a retry after a lost response) and get a new token of the same session;
182
+ a later repeat counts as a reuse and ends only that session, not the other devices of the user;
183
+ `passwordHashing.maxConcurrent` (1-64, default 2) and `passwordHashing.maxQueued` (0-1000, default 32) bound the
184
+ bcrypt work of the process (bcryptjs runs on the main thread, each check at cost 12 takes about 0.4 s of CPU): a
185
+ login, registration, password change or reset, or account deletion beyond them is answered 503
186
+ (`api/auth/password:busy`) at once; the limits are described in the next section. `links.web` is `https:` (`http:` for `localhost` only);
187
+ `links.mobile` is a deep link base such as `myapp://` or an `https:` universal link.
188
+ - `mobileOriginGuard` (step 5) is needed because `createExpressApp` parses JSON before any router (see "Server:
189
+ connecting and limits"); an application that does not parse JSON itself needs no outer application.
190
+ - The routers of the application read the user only from `req.user.userId`, never from the body or the query.
191
+ - An account can sign in before its e-mail is verified. Routes that trust the address (invitations, sharing by e-mail)
192
+ put `auth.requireVerifiedEmail` after `auth.authMiddleware` of the same `createAuth`: it reads the account on every
193
+ request and answers 403 `api/auth/emailVerification:required` for an unverified one (401 for an account that no
194
+ longer exists). It also answers 403 for an access token issued before the verification, until that token expires
195
+ (r1:U2): a token of whoever registered the address of somebody else does not pass after the owner recovered the
196
+ account and confirmed the address. The confirmation ends every earlier session, so a token that passes comes from a
197
+ login after it. Confirming the
198
+ e-mail needs the token of the link and the password of the account (`client.confirmEmail({ token, password })`,
199
+ audit S4): whoever registered the address of somebody else has no link, and the owner of the mailbox who did not
200
+ register has no password, so nobody confirms an address alone. A wrong password answers 400
201
+ `api/auth/password:currentInvalid` and the link stays usable; the attempts count in the limit `passwordCheck` of the
202
+ account of the link. The page of the link therefore asks for the password; an owner who does not know it (somebody
203
+ else registered the address) uses the password reset, which ends the sessions of the account, and then confirms
204
+ with the new password. Confirming also ends every session of the account issued before it; the owner signs in again
205
+ (the client becomes `anonymous` at its next refresh).
206
+ - `POST /register` does not reveal whether an address has an account (audit S3): it answers 202 without a body in both
207
+ cases. A new address gets an account and the verification link; a registered one gets no new account and no change,
208
+ and its owner gets the message `account_exists` with a password reset link. The answer comes before the e-mail is
209
+ sent (as for `POST /password-reset`), so its time does not reveal the account either; a failure of the mailer is
210
+ only logged (r1:U1), also when the logger itself throws or rejects (r3:U1). The client shows the same text for both,
211
+ e.g. "Check your mailbox".
212
+
213
+ Endpoints under `/v1/auth` (answers are `ApiResponse` of `@mielk/http`; the types are in `@mielk/auth/schemas`):
214
+
215
+ | Endpoint | Access | Purpose |
216
+ | --------------------------------------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------- |
217
+ | `POST /register` | public | 202 without a body for any address: new gets the link, registered a notice |
218
+ | `POST /login`, `POST /refresh`, `POST /logout` | public (refresh cookie) | web session: the refresh token is in the `httpOnly` cookie |
219
+ | `POST /mobile/login`, `/mobile/refresh`, `/mobile/logout` | public (refresh token in the body) | mobile session: a request with `Origin`: 403 |
220
+ | `GET /me`, `DELETE /me` | access token | the account of the access token; deleting it needs the password |
221
+ | `PUT /password` | access token | changes the password; the user signs in again |
222
+ | `POST /sessions/revoke-all` | access token | ends all sessions of the user |
223
+ | `POST /email-verification` | access token | sends the link again (202 without a body, also when the e-mail is already verified) |
224
+ | `POST /email-verification/confirm` | public (link token and password) | confirms the e-mail, ends sessions |
225
+ | `POST /password-reset`, `POST /password-reset/confirm` | public (link token for the confirmation) | asks for a reset link (answers the same for any address); sets the password |
226
+
227
+ Errors carry a message key (`api/auth/<area>:<name>`, `Msg`); the status follows from the error: 401 for credentials and
228
+ tokens, 403 for an unverified e-mail behind `requireVerifiedEmail`, 400 for a too long password, a wrong current password and an invalid one-time token,
229
+ 423 and 429 for the limits, 503 when Redis is unavailable, when the bcrypt work of the process is at its bound
230
+ (`api/auth/password:busy`) and when the lock of the account is not granted in time (`api/auth/account:busy`).
231
+
232
+ ### 3. Web application
233
+
234
+ ```
235
+ npm install @mielk/auth zod react # or the tarball of a version not on the registry yet, see Installation
236
+ ```
237
+
238
+ Create the client once and wrap the application, as in "Client and React" below; validate the forms with
239
+ `@mielk/auth/schemas` (the schemas the API uses, so the rules match) and register the translations of
240
+ `@mielk/auth/locales/<l>` in i18next. The e-mail links lead to `links.web`: the page there reads the token from the
241
+ fragment (`#token=...`) and calls `client.confirmEmail` or `client.confirmPasswordReset`. The refresh token cookie is
242
+ `httpOnly`, `SameSite=Strict` and `Path=/v1/auth`, so the browser sends it only to a request of the same site: the web
243
+ application and the API must be served from one site (for example `app.example.com` and `api.example.com`; a different
244
+ registrable domain does not work). Between different origins of the same site, the API also needs CORS with
245
+ credentials: `Access-Control-Allow-Origin` set to the exact origin of the web application (not `*`),
246
+ `Access-Control-Allow-Credentials: true` (the client of the library sends the credentials itself). CORS does not replace the
247
+ same-site condition.
248
+
249
+ The cookie path is fixed in the library: `Path=/v1/auth`, and the client calls `<baseUrl>/v1/auth/...`. The browser
250
+ sends the cookie only to requests whose public path starts with the path of the cookie, so what decides is the public
251
+ path of the request, not what a proxy forwards. With `baseUrl` without a path (public `https://api.example.com/v1/auth/...`)
252
+ no proxy setting is needed. With `baseUrl` with a prefix (e.g. `https://api.example.com/gateway`, public
253
+ `/gateway/v1/auth/*`) the proxy must strip the prefix before the server (the server sees `/v1/auth/*`) and rewrite the
254
+ path of the cookie in the `Set-Cookie` of the answers to the public path; otherwise the browser does not send the cookie
255
+ and refresh, the server logout and the revocation of the replaced token at the next login do not work. With nginx:
256
+ `proxy_cookie_path /v1/auth /gateway/v1/auth;`. The mobile client keeps the token in the body and does not depend on it.
257
+
258
+ ### 4. Mobile application (Expo)
259
+
260
+ ```
261
+ npm install @mielk/auth zod react expo-secure-store # or the tarball of a version not on the registry yet, see Installation
262
+ ```
263
+
264
+ ```ts
265
+ import * as SecureStore from 'expo-secure-store';
266
+ import { createAuthClient } from '@mielk/auth/client';
267
+
268
+ const KEY = 'refreshToken';
269
+ // React Native has no `location`: the address must be absolute (http or https), an empty one would make every call fail.
270
+ function apiBaseUrl(value: string | undefined): string {
271
+ try {
272
+ const url = new URL(value ?? '');
273
+ if ((url.protocol === 'http:' || url.protocol === 'https:') && url.hostname !== '') return url.href;
274
+ } catch {
275
+ // not a parsable absolute URL: reported below
276
+ }
277
+ throw new Error(
278
+ 'EXPO_PUBLIC_API_URL must be an absolute http(s) address with a host, e.g. https://api.example.com',
279
+ );
280
+ }
281
+ export const authClient = createAuthClient({
282
+ baseUrl: apiBaseUrl(process.env.EXPO_PUBLIC_API_URL),
283
+ mode: 'mobile',
284
+ tokenStore: {
285
+ read: () => SecureStore.getItemAsync(KEY),
286
+ save: (token) =>
287
+ SecureStore.setItemAsync(KEY, token, { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY }),
288
+ remove: () => SecureStore.deleteItemAsync(KEY),
289
+ },
290
+ });
291
+ ```
292
+
293
+ Show the splash screen while the state is `loading`, not the login screen. The deep links of the e-mails lead to
294
+ `links.mobile`; read `#token=...` there.
295
+
296
+ ### 5. Migrating from version 1.x
297
+
298
+ Version 2 is not compatible with 1.x (see `CHANGELOG.md`):
299
+
300
+ | 1.x | 2.x |
301
+ | ---------------------------------------- | ------------------------------------------------------------------------------------- |
302
+ | `createAuthServices(config, repository)` | `createAuth(config)`; the repository is `config.repository` |
303
+ | controllers, own routers, old middleware | `auth.router` mounted under `/v1/auth`, and `auth.authMiddleware` |
304
+ | own `AuthRepository` for the old tables | `createPgAuthRepository()` with the reference migration, or your own `AuthRepository` |
305
+ | `mielk-http`, `mielk-api` | `@mielk/http` `^3` (optional peer dependency) |
306
+ | one entry point | `@mielk/auth`, `/schemas`, `/client`, `/react`, `/pg`, `/locales/<l>` |
307
+
308
+ Existing accounts: map the old tables to the new ones in a migration of the application (accounts keep their bcrypt
309
+ hashes; refresh tokens of 1.x are not valid, so users sign in once). Do this in the pilot application first.
310
+
311
+ ## Server: connecting and limits
312
+
313
+ ```ts
314
+ const auth = createAuth({ jwt, links, limits: { appPrefix: 'finance' }, repository, mailer });
315
+ app.use('/v1/auth', auth.router); // then notFoundHandler and errorHandler of @mielk/http
316
+ app.use('/v1/accounts', auth.authMiddleware, accountsRouter);
317
+ ```
318
+
319
+ `limits.appPrefix` is required: it is the prefix of the application in the Redis keys (`<appPrefix>:<area>:<...>`). An
320
+ e-mail is in a key only as the SHA-256 of its trimmed lower-case form. The limits of the links sent to one account
321
+ (audit S5) keep a mailbox from being flooded and a valid reset link from being replaced by others: over
322
+ `passwordResetEmail` the reset request and the registration of a registered address still answer 202, but no e-mail
323
+ is sent and no token is issued, so the last link sent keeps working; it counts per account from any IP address. The library does not set the global limit of all
324
+ endpoints: pass it to `createExpressApp` of `@mielk/http`.
325
+
326
+ | Setting (`limits.…`) | Endpoint | Default |
327
+ | -------------------- | ------------------------------------------------- | --------------------------------------------- |
328
+ | `register` | registration, per IP address | 10 per hour |
329
+ | `passwordReset` | reset request, per IP address | 5 per hour |
330
+ | `refresh` | refresh (web and mobile), per IP | 60 per 15 minutes |
331
+ | `passwordCheck` | password checks of one account (see below) | 5 attempts per 15 minutes; no lock |
332
+ | `verificationEmail` | `POST /email-verification`, per user | 3 per hour; over it 429 |
333
+ | `passwordResetEmail` | reset links and registration notices, per account | 3 per hour; over it 202, but nothing is sent |
334
+ | `login.ip` | login, per IP address | 5 attempts per 15 minutes |
335
+ | `login.ipEmail` | login, per IP address and e-mail | 5 attempts per 15 minutes |
336
+ | `login.email` | login, per e-mail, any address | 5 attempts per 15 minutes; exceeding it locks |
337
+ | `login.lockSeconds` | lock of an e-mail | 900 seconds (15 minutes), answers 423 |
338
+
339
+ Each setting except `login.lockSeconds` is `{ limit, windowSeconds }`; `login.lockSeconds` is one integer, the duration
340
+ of the lock in seconds (1 to 86400). Every counted answer carries `X-RateLimit-Limit`, `-Remaining` and `-Reset`;
341
+ a 429 also `Retry-After`. A successful login resets the counters of the e-mail (per e-mail and per IP address and
342
+ e-mail) and removes its lock. While Redis is unavailable the limited endpoints answer 503; so does a login whose
343
+ counters cannot be reset (the counters are reset after the password matched and before the session is issued, outside
344
+ the transaction, so the failure leaves no session and no token is returned).
345
+
346
+ `passwordCheck` limits the guesses of a password with an access token alone (a token taken by XSS lives up to 15
347
+ minutes) or with an e-mail verification link alone: one counter per account for `PUT /password`, `DELETE /me` and
348
+ `POST /email-verification/confirm` together. It keys on the account (of the access token, or of the link after the link
349
+ was checked; an invalid link is refused before it and counts nothing), not on the address, comes before bcrypt, and is
350
+ cleared after the right password. Over it the three endpoints answer 429; it sets no lock, so the owner can still log in.
351
+
352
+ A confirmed password reset (`POST /password-reset/confirm`) removes the lock of the e-mail of its account and clears its
353
+ counter per e-mail: the owner has proved access to the mailbox, so attempts of others no longer keep the new password
354
+ out (the counters per address and e-mail stay until they expire). A login body is validated before the guards that read
355
+ its e-mail, so a body without a password (400) counts only against the address and cannot lock an e-mail.
356
+
357
+ The three login limits are equal by default (5 attempts per 15 minutes). The limit per IP address answers first: one
358
+ address is stopped by its own 429 on the sixth attempt and does not lock the e-mail; the lock is set when attempts from
359
+ several addresses exceed the limit per e-mail. A lock from a single address needs `login.ip` above
360
+ `login.email` (for example `login.ip` 20 and `login.email` 5). When the budget of an address is spent, its 429 answers before the 423 of a locked e-mail. The body of the limited endpoints is parsed after the limit per IP address, so a
361
+ malformed JSON body is counted and its 400 carries `X-RateLimit-*`; a body parsed earlier by the application (see below)
362
+ is answered by the application's parser, without them. A web `POST /refresh` without the refresh cookie is answered 401
363
+ before the limit and is not counted: the client restores the session on every start of the page, also for a visitor
364
+ without a session, and those requests must not spend the budget of an address that signed-in users share (an office,
365
+ a mobile operator's NAT). A request with any cookie value is counted.
366
+
367
+ ### IP addresses and `trust proxy`
368
+
369
+ Every limit per IP address keys on `req.ip`, which Express computes from `X-Forwarded-For` only as far as its setting
370
+ `trust proxy` allows (`trustProxy` of `createExpressApp`). Set it to the exact number of reverse proxies in front of the
371
+ application (`1` for one nginx), only when that proxy overwrites `X-Forwarded-For` itself and the application is
372
+ reachable only through it; never `true`. Both mistakes break the limits:
373
+
374
+ - behind a proxy without `trust proxy`, `req.ip` is the address of the proxy: all clients share one counter, so five
375
+ failed logins (of anybody, on any address) answer 429 to the login of everybody for 15 minutes;
376
+ - with `true` (or more hops than there are proxies), the client writes its own address into `X-Forwarded-For`: it gets a
377
+ new counter for every request and the limits per address no longer exist (the limit per e-mail still protects one
378
+ account).
379
+
380
+ The router logs a warning once (field `proxyCheck`, no address in the entry) when a request has `X-Forwarded-For` but
381
+ `req.ip` is a loopback or private address (`forwarded_for_without_trust_proxy`, the symptom of the first mistake) and
382
+ when `trust proxy` is `true` (`trust_proxy_true`); it never refuses a request for it. Also with the right setting,
383
+ clients behind one shared address (an office, a school, carrier-grade NAT) share the limits per address, and an IPv6
384
+ address counts as a whole, not by its `/64` prefix.
385
+
386
+ Mobile endpoints (`/mobile/*`) refuse a request with an `Origin` header with 403. `createExpressApp` of `@mielk/http`
387
+ parses JSON before any router, so the application must mount `mobileOriginGuard` (exported by `@mielk/auth`) **before**
388
+ that parser; otherwise a browser request with a malformed body gets 400 there instead of 403 (no token is returned either
389
+ way). The guard answers itself, so it needs no error handler. Its 403 is sent by the outer application, so that
390
+ application needs the headers `createExpressApp` sets for the inner one (`rest:GEN-4`): `X-Powered-By` disabled and
391
+ `helmet()` mounted before the guard (`helmet` is a dependency of the application). Wrap the application of
392
+ `createExpressApp`:
393
+
394
+ ```ts
395
+ import express from 'express';
396
+ import helmet from 'helmet';
397
+ import { createExpressApp } from '@mielk/http';
398
+ import { mobileOriginGuard } from '@mielk/auth';
399
+
400
+ // `config` is the ExpressAppConfig of the application (appPrefix, redis, globalRateLimit, ...).
401
+ const app = await createExpressApp(config); // global limit, logger, JSON parser
402
+ const root = express();
403
+ root.disable('x-powered-by'); // the outer application answers the 403 of the guard
404
+ root.use(helmet()); // security headers also on that 403
405
+ root.use('/v1/auth/mobile', mobileOriginGuard); // before the parser of createExpressApp
406
+ root.use(app);
407
+ ```
408
+
409
+ The router mounts the same guard for `/mobile/*`, so an application that does not parse JSON itself needs nothing more.
410
+
411
+ ## Client and React
412
+
413
+ `createAuthClient` (`@mielk/auth/client`) keeps the session of a web or mobile application. The access token lives only in
414
+ memory; the refresh token is in the `httpOnly` cookie (`mode: 'web'`) or in a store you pass (`mode: 'mobile'`, on
415
+ `expo-secure-store` with `keychainAccessible: WHEN_UNLOCKED_THIS_DEVICE_ONLY`). `baseUrl` is the address of the API
416
+ without `/v1/auth`: an absolute http(s) address (`https://api.example.com`, `https://api.example.com/gateway`), or, for
417
+ the origin of the page (web only), an empty string or a path from the root (`/gateway`). In a mobile application the
418
+ address must be absolute. A prefix in the public address of a web API also moves the path of the refresh cookie, see
419
+ "Web application" above for the proxy setting.
420
+
421
+ ```ts
422
+ import { createAuthClient } from '@mielk/auth/client';
423
+
424
+ export const authClient = createAuthClient({
425
+ baseUrl: import.meta.env.VITE_API_URL,
426
+ mode: 'web', // 'mobile' needs tokenStore: { read, save, remove } over the secure store
427
+ getLocale: () => i18n.language, // optional: the language of the e-mails with a link
428
+ });
429
+
430
+ // In the API client of the application:
431
+ const res = await authClient.authorizedFetch(`${apiUrl}/v1/accounts`); // bearer token, one refresh and one repeat on 401
432
+ if (!res.ok) throw new Error(`Request failed: ${res.status}`);
433
+ // The token goes only to the origin of baseUrl, provided the fetch drops it on a redirect to another origin (browsers
434
+ // and Node.js do; not verified in React Native). An address of another origin rejects with a TypeError, nothing is sent.
435
+ ```
436
+
437
+ The client runs every operation that changes the session in one queue of session operations: login, logout, refresh,
438
+ the restore at start, password change and reset, account deletion, revoking all sessions, and every operation on the
439
+ token store (`mobile`). Each runs whole (its store reads and writes, its requests, the change of the memory and the
440
+ publication of the state) before the next one starts, in the order they were called, and nothing about the session
441
+ changes when it is called; an operation asked for meanwhile, also by a subscriber or by the token store, waits for its
442
+ turn and acts on the result of the operations before it. So a late answer of one operation cannot clear or replace what
443
+ a later one set, and the stored refresh token (`mobile`) is always the token of the session in memory, or of no session
444
+ (a token the restore kept after a transient failure).
445
+
446
+ Every asynchronous call belongs to the session in place when it is called, and has an effect (a request sent or
447
+ repeated, a token kept, a state or profile published, the session ended) only while that session is still in place.
448
+ A session is replaced in the turn of a logout or of a login that succeeds; a login that fails does not replace the
449
+ session still shown. A login that succeeds is put in place even when a later login or logout was asked for while it was
450
+ under way: that one replaces or ends it in its own turn.
451
+
452
+ Other requests (`authorizedFetch`, `getMe`, `resendEmailVerification`) run in parallel and are not queued. While no
453
+ session operation is queued they are sent at once; otherwise they wait for the session operations asked for before
454
+ them (for example the restore, a refresh, or a login asked for just before) and then go with the access token of the
455
+ session of their call. When that session ended or was replaced meanwhile, they send nothing and reject with an
456
+ `AuthClientError` of the kind `session-changed`. A 401 answer queues one refresh for the session, shared by all its
457
+ parallel 401 answers (`rn:SES-5`), and the request is repeated once, only while its session is still in place. When an
458
+ operation queued before that refresh (for example a password change that got a 401 itself) has already renewed the
459
+ access token of the session, the refresh uses that token and does not ask the server again.
460
+
461
+ Each network request of a session operation has one time limit of 30 seconds, from the call of `fetch` to the end of
462
+ reading the answer (headers and body), so a request that hangs cannot hold up the session operations after it. When the
463
+ limit passes, the request and the reading of its body are aborted through the `signal` of its `RequestInit` and the
464
+ operation goes on as if the network had failed
465
+ (an `AuthClientError` of the kind `network`): a refresh or the restore keeps the session and its refresh token (see
466
+ below), a login rejects and changes nothing, a logout still ends the session on this client, and the queue goes on with
467
+ the next operation. An answer that still comes after the limit (from a `fetch` that ignores the signal) is ignored; a
468
+ refresh token in it is neither stored nor revoked, so it stays valid on the server until it expires. The calls of the
469
+ token store have no time limit: a store that never settles holds up the session operations, and the token store must
470
+ not wait for an operation of the client (that operation waits for the store).
471
+
472
+ A refresh token is removed only when the server rejects it (401 or 403 to a refresh), by a logout, a password change,
473
+ a password reset made while signed in, or an account deletion. A refresh that fails for a transient reason (no network,
474
+ no answer in time, 5xx, 429) keeps it:
475
+
476
+ - at start, `restoreSession` ends in the state `anonymous`, and the stored token (`mobile`) or the cookie (`web`) stays,
477
+ so the next start can restore the session;
478
+ - in an active session, `refreshAccessToken` and `authorizedFetch` reject with the `AuthClientError` of the failure; the
479
+ state stays `authenticated` and both tokens stay, so a later request can try again.
480
+
481
+ A logout ends the session whatever the server answers:
482
+
483
+ 1. Nothing changes at the call: the logout is a session operation and waits for the operations asked for before it (a
484
+ login under way is put in place when it succeeds, and the logout then ends it; until its turn `getState` and
485
+ `getAccessToken` still show the session).
486
+ 2. In its turn the state becomes `anonymous` and the access token is cleared; subscribers hear it, and a login a
487
+ subscriber asks for then comes after the logout.
488
+ 3. Then the logout reads the stored token (`mobile`), removes it, and sends it to the server to be revoked (ignoring
489
+ the answer); in `web` it sends the logout request with the cookie.
490
+ 4. The promise of `logout` resolves when that request has been answered, has failed or has run out of time.
491
+
492
+ In the `web` mode the client cannot remove the `httpOnly` cookie: it is removed only when an answer of the
493
+ server that clears it reaches the browser and is accepted. When the logout request does not reach the server, or the
494
+ server answers with an error without clearing the cookie, the cookie stays. A new client (for example after the application restarts) can then restore the session with its
495
+ `restoreSession`; on the same client `restoreSession` runs once, so after an earlier restore (also the one of
496
+ `AuthProvider`) it returns the first result without a new request.
497
+
498
+ `changePassword`, `revokeAllSessions` and `deleteAccount` act only on the session seen when they are called. When a
499
+ logout, or a login that succeeded, comes before their turn, nothing is sent and they reject with an `AuthClientError`
500
+ of the kind `session-changed` (key `api/auth/client:sessionChanged`). A login only asked for does not end the session
501
+ still shown: until it succeeds, they act on that session. Called while the state is `loading`, they run after the
502
+ restore and act on its result:
503
+
504
+ - the restore worked: the request carries the token of the restored session;
505
+ - the restore found no session (the refresh token was missing, or the server answered the refresh with 401 or 403): the
506
+ request is sent without the client's token, and they reject with the `AuthClientError` of the API's answer (usually
507
+ 401, kind `api`); the state stays `anonymous`.
508
+
509
+ After a successful answer the session ends on this client, in the same operation; a login asked for meanwhile then
510
+ replaces it if it works, and otherwise the state stays `anonymous`. `confirmPasswordReset` ends the session of this
511
+ client in the same way, also a session that the restore has put in place.
512
+
513
+ A request of a session is checked against the session in place right before it is handed to `fetch`, after the client
514
+ has called the application's code for it (`getLocale`, the headers of `init`). A logout or a login that this code asks
515
+ for is queued after the request, so the request still goes with its session. The access token, the identity of the
516
+ session and the state change together, in one step, so `getAccessToken` never returns the token of a login whose state
517
+ is not yet shown.
518
+
519
+ In the `mobile` mode a login stores its refresh token and puts its session in place in its operation. When the store
520
+ cannot save the new token, it holds again the token it held before (the token of the session still shown, so it stays
521
+ usable) and the new token is revoked on the server. When the store cannot put that token back either, the session
522
+ whose token it was ends on this client and its token is revoked too. A login over a session (of another account or of
523
+ the same one, also over a stored token not restored yet) revokes on the server the refresh token it overwrote, after its
524
+ own session is put in place; a failure of that request is ignored and the token expires by itself (TASK-191.10). In the
525
+ `web` mode the server does the same: `POST /login` revokes the refresh token of the cookie the request brought, after
526
+ the login succeeded (a failed login keeps that session); when the revocation fails the login still stands and a warning
527
+ is logged without the token.
528
+
529
+ A subscriber or a `getLocale` that throws changes nothing in the client: the other subscribers are still called and the
530
+ operation goes on. When `getLocale` throws or returns a value the headers refuse (for example with a line break), the
531
+ client adds no `Accept-Language`; an `Accept-Language` the caller put in
532
+ `init` is sent unchanged. The exception is reported as an uncaught error of the platform, in a microtask, as an
533
+ exception of a DOM event listener is; a thrown value that is not an `Error` is reported as an `Error` with that value as
534
+ its `cause`. The report is detached from the client's state and from the other subscribers, but not from the host: in
535
+ Node.js an uncaught exception ends the process by default (unless the application handles `uncaughtException`), maybe
536
+ before the caller gets the result of the operation, and in a browser or React Native it goes to the global error handler.
537
+ Subscribers and `getLocale` should therefore not throw.
538
+
539
+ `authorizedFetch` sends the access token only to the origin of `baseUrl` (scheme, host and port), provided the `fetch`
540
+ of the client drops `Authorization` on a redirect to another origin: browsers and Node.js do, the redirect handling of
541
+ React Native is not verified (see below). Within that limit the token cannot reach a third party.
542
+
543
+ The client decides the target itself, on the text of the address and not with the global `URL`, so the decision is the
544
+ same in a browser, Node.js and React Native, and it hands `fetch` an absolute address it built: `fetch` resolves nothing,
545
+ not against the base URL of the document (a `<base>` element) either. The contract of the address:
546
+
547
+ - A relative address (`accounts` or `/accounts`) is appended to the path of `baseUrl` and stays under it: with
548
+ `https://api.example.com/gateway/` it goes to `/gateway/accounts`. An empty `baseUrl` or a path from the root
549
+ (`/gateway`) takes the origin of `location.href`; without `location` (Node.js, React Native) such a `baseUrl` makes
550
+ `authorizedFetch` reject, so give those platforms an absolute `baseUrl`; the other calls do the same, except three that
551
+ never reject for the address: `restoreSession()` ends `anonymous` (the failure of its `GET /me` is not an error of the
552
+ caller), `logout()` still ends the local session (mobile: removes the refresh token from `tokenStore`; web: sends no request, so the cookie stays), and the
553
+ revoking of a dropped token sends no request. `login`, `register`, `confirmPasswordReset`,
554
+ `confirmEmail`, `changePassword`, `revokeAllSessions` and `deleteAccount` send a password or a token, so they build
555
+ their address by the same rules and reject the same way, before anything is sent (r1:U4, DEC-293); `confirmEmail`
556
+ does not follow a redirect either (`redirect: 'error'`): the answer of a redirect fails the request as a network failure (`confirmEmail` rejects with `network`), and the
557
+ body is not sent to its address (r2:U2). Neither does any other call the library builds itself (`refresh`, `logout`,
558
+ `getMe`, `requestPasswordReset` and the rest, DEC-314): the API of the library never redirects, and a 307 or 308 would
559
+ send the password or the token to the new address. A `fetch` passed in the options must honour `redirect: 'error'`. A redirect is handled as any network failure: the calls reject with `network`, except `restoreSession()` (ends `anonymous`, keeps the refresh token) and `logout()` (ends the local session, resolves).
560
+ - An absolute address must have the origin of `baseUrl` and may have any path on it. Origins are compared in their
561
+ canonical form, as the URL Standard serialises them: scheme and host in lower case, percent-encoded ASCII in the host
562
+ decoded, the default port left out also when written with leading zeros (`:00443`), IPv6 compressed (`[::1]`) and
563
+ IPv4 in dotted decimal (`127.1` is `127.0.0.1`). The address sent carries that canonical origin.
564
+ - Dot segments (`.` and `..`, also percent-encoded as `%2e`) are refused in the address and in `baseUrl`, so no address
565
+ leaves the path prefix of `baseUrl` by resolution; empty segments (`a//b`) are kept as given. A query or a fragment of
566
+ the address is sent unchanged; `baseUrl` itself must have none.
567
+ - Refused, with a `TypeError` before anything is sent: an address of another origin (also another port or `http` instead
568
+ of `https`), a protocol-relative one (`//host`), another scheme, user information (`user@host`), a backslash,
569
+ whitespace or a control character, a host with a non-ASCII character (write an internationalised name in its `xn--`
570
+ form) or one the URL Standard does not parse, a port above 65535, and an input that is neither a string nor an object
571
+ with a string `href` (a `URL`, also of another realm or a polyfill, is read through its `href` and the checked text is
572
+ sent; a `Request` is refused).
573
+ - An `xn--` label is taken only when the client can check it without the IDNA tables: valid Punycode in its canonical
574
+ encoding, with at least one non-ASCII character, in NFC, not starting with a combining mark, made of lower-case or
575
+ caseless letters, combining marks and decimal digits that NFKC case folding leaves unchanged, and with no character of
576
+ a right-to-left script (Hebrew, Arabic and the like), whose Punycode part does not start with `xn--` again
577
+ (`xn--xn--...`). Every other `xn--` label is refused, also one the URL Standard
578
+ accepts (an emoji, `ß`, a right-to-left name); for such a host use the plain `fetch`. This keeps the client from
579
+ accepting a host the URL Standard refuses.
580
+
581
+ Migration: before TASK-191.12 an address from the root was resolved like a URL, so with
582
+ `baseUrl: 'https://api.example.com/gateway'` the call `authorizedFetch('/v1/accounts')` went to
583
+ `https://api.example.com/v1/accounts`; now it goes to `https://api.example.com/gateway/v1/accounts`. To keep the old
584
+ target, pass the absolute address of the same origin: `authorizedFetch('https://api.example.com/v1/accounts')`. For
585
+ other services use the plain `fetch`.
586
+
587
+ Only the first address is checked, and only `authorizedFetch` follows a redirect (the request is the application's own
588
+ and its API may redirect within its origin): a redirect is followed by the `fetch` of the client (`options.fetch` or the global
589
+ one), which must drop `Authorization` on a redirect to another origin, as the Fetch Standard requires. Browsers and
590
+ Node.js do (the library tests it on the Node.js `fetch`); the redirect handling of React Native is not verified, so the
591
+ API should not redirect to another origin, and a `fetch` passed in the options
592
+ must keep the rule. An empty string in the token store (mobile mode) means no session, as a missing token does.
593
+
594
+ `authorizedFetch` passes `init.credentials` on unchanged, so the default of `fetch` applies. Subscribe with
595
+ `client.subscribe` to clear the query cache of the application when the state becomes `anonymous`. Failed calls reject
596
+ with `AuthClientError`: `kind` tells the cases apart (`network`, `invalid-response`, `api`, `session-changed`), `message`
597
+ is a message key to translate, `status`, `issues` (the fields of a rejected form) and `retryAfterSeconds` (429, 423)
598
+ carry the rest.
599
+
600
+ ```tsx
601
+ import { AuthProvider, useAuth } from '@mielk/auth/react';
602
+
603
+ const Profile = () => {
604
+ // A child of AuthProvider: the hook works only while a component is rendered below the provider.
605
+ const { state } = useAuth(); // loading | anonymous | authenticated; also login, register, logout, changePassword
606
+ return <p>{state.status}</p>;
607
+ };
608
+
609
+ <AuthProvider client={authClient}>
610
+ <Profile />
611
+ </AuthProvider>;
612
+ ```
613
+
614
+ `useSession()` returns only the state and `useAuthClient()` the client, for e-mail verification and password reset.
615
+ Validate the forms with the schemas of `@mielk/auth/schemas`.
616
+
617
+ Translations: `@mielk/auth/locales/pl` and `@mielk/auth/locales/en-GB` map the namespaces of the message keys
618
+ (`api/auth/login`, ...) to their texts; register each namespace in i18next:
619
+
620
+ ```ts
621
+ import pl from '@mielk/auth/locales/pl' with { type: 'json' };
622
+
623
+ for (const [namespace, texts] of Object.entries(pl)) i18n.addResourceBundle('pl', namespace, texts);
624
+ ```
625
+
626
+ ## Development
627
+
628
+ `npm ci`, then `npm run format:check`, `npm run lint`, `npm run typecheck`, `npm test`, `npm run build`,
629
+ `npm run test:dist` (tests that need `dist/`: `check:readme` refuses a wrong use of the library in an example),
630
+ `npm run check:package`, `npm run check:import` (packs the library, installs it in an empty folder and imports every
631
+ entry point) and `npm run check:readme` (compiles the `ts`, `tsx` and `typescript` code blocks of this README against
632
+ `dist/`, language case-insensitive; an unclosed fence is an error; `-- <file>` checks another file), as in `.github/workflows/ci.yml`.
633
+
634
+ ### Tests against PostgreSQL
635
+
636
+ The contract tests of the PostgreSQL adapter (`src/pg/pg-auth-repository.integration.spec.ts`) need a local server and a role with
637
+ `CREATEDB` (the tests create and drop their own database). Run them with:
638
+
639
+ ```
640
+ npm run test:pg
641
+ ```
642
+
643
+ The script reads the connection data from the Windows Credential Manager, passes it to the test process only (as the
644
+ variables below) and never prints the password, also not in the output of the tests. Without the credential it ends
645
+ with a message and a non-zero exit code; the tests are not skipped. It also refuses to run (exit code 2, before reading the password) when `NODE_OPTIONS` or `NODE_DEBUG` is set,
646
+ because Node.js diagnostics, heap snapshots or preloaded code could print or save the password; clear them for the run. The tests are a separate suite (`vitest.pg.config.ts`): plain `npm test` does not run them, whatever the variables. The host of the entry must be `127.0.0.1`, `localhost` or a local socket; the script and the tests refuse another host (`ts:TST-5`).
647
+
648
+ One-time setup (Windows, once per machine and user):
649
+
650
+ 1. Open a terminal (PowerShell or cmd) as your normal user.
651
+ 2. Run, with your own user, host and port:
652
+
653
+ ```
654
+ cmdkey /generic:mielk-auth-test-pg /user:postgres@127.0.0.1:5432 /pass
655
+ ```
656
+
657
+ The entry is named `mielk-auth-test-pg`; the user name field has the form `<user>@<host>[:<port>]` (the port
658
+ defaults to `5432`; use a host name, not an IPv6 literal).
659
+
660
+ 3. `cmdkey` asks for the password; type it (it is not shown and does not reach the shell history).
661
+ 4. Check the entry with `cmdkey /list:mielk-auth-test-pg`; remove it with `cmdkey /delete:mielk-auth-test-pg`.
662
+
663
+ `MIELK_AUTH_TEST_PG_CREDENTIAL` names another entry. The tests read these variables, which you can also set yourself
664
+ to run them without the script:
665
+
666
+ - `MIELK_AUTH_TEST_PG_HOST` (required, e.g. `127.0.0.1`),
667
+ - `MIELK_AUTH_TEST_PG_PASSWORD` (required),
668
+ - `MIELK_AUTH_TEST_PG_PORT` (default `5432`),
669
+ - `MIELK_AUTH_TEST_PG_USER` (default `postgres`).
670
+
671
+ Never commit the password; keep it in the Credential Manager or another secret store.