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