@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
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { getQueryExecutor, isUniqueViolation, withTransaction } from '@mielk/db/pg';
|
|
3
|
+
import { AccountBusyError, EmailTakenError } from '../server/errors.js';
|
|
4
|
+
const USER_COLUMNS = 'user_id, email, password_hash, email_verified_at, created_at, updated_at';
|
|
5
|
+
const REFRESH_TOKEN_COLUMNS = 'user_id, token_hash, family_id, client_kind, expires_at, revoked_at, revoked_reason, created_at';
|
|
6
|
+
const AUTH_TOKEN_COLUMNS = 'user_id, purpose, token_hash, expires_at, used_at, created_at';
|
|
7
|
+
const toUser = (row) => ({
|
|
8
|
+
userId: row.user_id,
|
|
9
|
+
email: row.email,
|
|
10
|
+
passwordHash: row.password_hash,
|
|
11
|
+
emailVerifiedAt: row.email_verified_at,
|
|
12
|
+
createdAt: row.created_at,
|
|
13
|
+
updatedAt: row.updated_at,
|
|
14
|
+
});
|
|
15
|
+
const toRefreshToken = (row) => ({
|
|
16
|
+
userId: row.user_id,
|
|
17
|
+
tokenHash: row.token_hash,
|
|
18
|
+
familyId: row.family_id,
|
|
19
|
+
clientKind: row.client_kind,
|
|
20
|
+
expiresAt: row.expires_at,
|
|
21
|
+
revokedAt: row.revoked_at,
|
|
22
|
+
revokedReason: row.revoked_reason,
|
|
23
|
+
createdAt: row.created_at,
|
|
24
|
+
});
|
|
25
|
+
/*
|
|
26
|
+
* Ends sessions in one statement (`revokeRefreshTokenFamily`, `revokeAllRefreshTokens`): valid tokens get `revoked_at`,
|
|
27
|
+
* rotated ones keep theirs, all get the reason `revoked`. The self-join reads the row before the change, so the
|
|
28
|
+
* statement can return which tokens were valid.
|
|
29
|
+
*/
|
|
30
|
+
const END_SESSIONS = (column) => `UPDATE refresh_tokens AS t
|
|
31
|
+
SET revoked_at = COALESCE(t.revoked_at, $2), revoked_reason = 'revoked'
|
|
32
|
+
FROM refresh_tokens AS previous
|
|
33
|
+
WHERE previous.refresh_token_id = t.refresh_token_id
|
|
34
|
+
AND t.${column} = $1
|
|
35
|
+
AND (t.revoked_reason IS NULL OR t.revoked_reason = 'rotated')
|
|
36
|
+
RETURNING previous.revoked_at IS NULL AS was_valid`;
|
|
37
|
+
const toAuthToken = (row) => ({
|
|
38
|
+
userId: row.user_id,
|
|
39
|
+
purpose: row.purpose,
|
|
40
|
+
tokenHash: row.token_hash,
|
|
41
|
+
expiresAt: row.expires_at,
|
|
42
|
+
usedAt: row.used_at,
|
|
43
|
+
createdAt: row.created_at,
|
|
44
|
+
});
|
|
45
|
+
/** Default of `PgAuthRepositoryOptions.lockTimeoutMs`. */
|
|
46
|
+
export const LOCK_TIMEOUT_DEFAULT_MS = 3000;
|
|
47
|
+
/** Upper bound of `lockTimeoutMs`: a longer wait holds a connection of the shared pool too long. */
|
|
48
|
+
const LOCK_TIMEOUT_MAX_MS = 60_000;
|
|
49
|
+
/** SQLSTATE `lock_not_available`: the lock was not granted within `lock_timeout`. */
|
|
50
|
+
const LOCK_NOT_AVAILABLE = '55P03';
|
|
51
|
+
/** Name of the unique index of the e-mail created by the migration `0001_mielk_auth.sql`. */
|
|
52
|
+
const EMAIL_UNIQUE_INDEX = 'users_email_lower_key';
|
|
53
|
+
/**
|
|
54
|
+
* `AuthRepository` on PostgreSQL, on the connection pool of `@mielk/db/pg` (the application calls `initDb`).
|
|
55
|
+
*
|
|
56
|
+
* Every statement runs on the executor of the current call chain (`getQueryExecutor`): the pool outside a transaction
|
|
57
|
+
* and the client of the transaction inside `withTransaction`. So the repository passed to `work` and this one see the
|
|
58
|
+
* same transaction, and a `withTransaction` of the application around it joins that transaction. The tables are the
|
|
59
|
+
* ones of the reference migration `migrations/0001_mielk_auth.sql`; the connection must find them on its `search_path`.
|
|
60
|
+
*
|
|
61
|
+
* @since 2.0.0
|
|
62
|
+
*/
|
|
63
|
+
export class PgAuthRepository {
|
|
64
|
+
/** Set inside `withTransaction` of this class, so `lockUser` can tell a transaction from the autocommit mode. */
|
|
65
|
+
#inTransaction = new AsyncLocalStorage();
|
|
66
|
+
/** `lock_timeout` of `lockUser`, as the text `set_config` takes (milliseconds). */
|
|
67
|
+
#lockTimeout;
|
|
68
|
+
/** @throws `RangeError` when `lockTimeoutMs` is not an integer from 1 to 60000. */
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
const lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_DEFAULT_MS;
|
|
71
|
+
if (!Number.isInteger(lockTimeoutMs) || lockTimeoutMs < 1 || lockTimeoutMs > LOCK_TIMEOUT_MAX_MS) {
|
|
72
|
+
throw new RangeError(`lockTimeoutMs must be an integer from 1 to ${String(LOCK_TIMEOUT_MAX_MS)}`);
|
|
73
|
+
}
|
|
74
|
+
this.#lockTimeout = String(lockTimeoutMs);
|
|
75
|
+
}
|
|
76
|
+
/** {@inheritDoc AuthRepository.withTransaction} */
|
|
77
|
+
withTransaction(work) {
|
|
78
|
+
return withTransaction(() => this.#inTransaction.run(true, () => work(this)));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Locks the row of the user with `FOR NO KEY UPDATE`: the lock excludes another `lockUser` of the same user and the
|
|
82
|
+
* updates of the row, but not the inserts of tokens of other transactions (their foreign keys take the weaker
|
|
83
|
+
* `FOR KEY SHARE`). The next statement of the transaction takes a new snapshot (`READ COMMITTED`), so it sees what
|
|
84
|
+
* the previous holder committed.
|
|
85
|
+
*
|
|
86
|
+
* The wait is bounded by `lockTimeoutMs` (`SET LOCAL lock_timeout` for this statement only; the previous value is
|
|
87
|
+
* restored after the lock is granted), so requests of one account cannot queue up and take the whole pool (audit S8).
|
|
88
|
+
*
|
|
89
|
+
* @returns resolves when the lock is held, or at once when the user does not exist: nothing is locked then.
|
|
90
|
+
* @throws `Error` when called outside `withTransaction`: the lock would be released at once; `AccountBusyError` when
|
|
91
|
+
* the lock is not granted within `lockTimeoutMs` (the transaction is aborted then and rolls back).
|
|
92
|
+
*/
|
|
93
|
+
async lockUser(userId) {
|
|
94
|
+
if (this.#inTransaction.getStore() === undefined) {
|
|
95
|
+
throw new Error(`lockUser(${userId}) must be called inside withTransaction`);
|
|
96
|
+
}
|
|
97
|
+
const executor = getQueryExecutor();
|
|
98
|
+
// The subquery with OFFSET 0 is evaluated first, so `previous` is the value before `set_config` changes it.
|
|
99
|
+
const setting = await executor.query(`SELECT previous, set_config('lock_timeout', $1, true) AS applied
|
|
100
|
+
FROM (SELECT current_setting('lock_timeout') AS previous OFFSET 0) AS current`, [this.#lockTimeout]);
|
|
101
|
+
try {
|
|
102
|
+
await executor.query('SELECT 1 FROM users WHERE user_id = $1 FOR NO KEY UPDATE', [userId]);
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
if (Reflect.get(Object(err), 'code') === LOCK_NOT_AVAILABLE) {
|
|
106
|
+
throw new AccountBusyError();
|
|
107
|
+
}
|
|
108
|
+
throw err;
|
|
109
|
+
}
|
|
110
|
+
await executor.query("SELECT set_config('lock_timeout', $1, true)", [setting.rows[0]?.previous ?? '0']);
|
|
111
|
+
}
|
|
112
|
+
/** {@inheritDoc AuthRepository.findUserByEmail} */
|
|
113
|
+
async findUserByEmail(email) {
|
|
114
|
+
const result = await getQueryExecutor().query(`SELECT ${USER_COLUMNS} FROM users WHERE lower(email) = lower($1)`, [email]);
|
|
115
|
+
return result.rows[0] === undefined ? null : toUser(result.rows[0]);
|
|
116
|
+
}
|
|
117
|
+
/** {@inheritDoc AuthRepository.findUserById} */
|
|
118
|
+
async findUserById(userId) {
|
|
119
|
+
const result = await getQueryExecutor().query(`SELECT ${USER_COLUMNS} FROM users WHERE user_id = $1`, [
|
|
120
|
+
userId,
|
|
121
|
+
]);
|
|
122
|
+
return result.rows[0] === undefined ? null : toUser(result.rows[0]);
|
|
123
|
+
}
|
|
124
|
+
/** {@inheritDoc AuthRepository.createUser} */
|
|
125
|
+
async createUser(user) {
|
|
126
|
+
// One statement for a new and for a registered e-mail (r1:U1, review r2): the e-mail is looked up in the snapshot
|
|
127
|
+
// of the statement and the row is inserted only when no account has it, so a registered address is recognised
|
|
128
|
+
// without a further read on the path of the answer, whatever the name of its unique index (audit N19 a).
|
|
129
|
+
let rows;
|
|
130
|
+
try {
|
|
131
|
+
const result = await getQueryExecutor().query(`WITH existing AS (SELECT EXISTS (SELECT 1 FROM users WHERE lower(email) = lower($1::text)) AS found)
|
|
132
|
+
INSERT INTO users (email, password_hash, created_at, updated_at)
|
|
133
|
+
SELECT $1::text, $2::text, $3::timestamptz, $3::timestamptz FROM existing WHERE NOT existing.found
|
|
134
|
+
RETURNING ${USER_COLUMNS}`, [user.email, user.passwordHash, user.createdAt]);
|
|
135
|
+
rows = result.rows;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (!isUniqueViolation(error)) {
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
// `isUniqueViolation` above checked that this is a PostgreSQL error, which carries the name of the constraint.
|
|
142
|
+
if (error.constraint === EMAIL_UNIQUE_INDEX) {
|
|
143
|
+
throw new EmailTakenError();
|
|
144
|
+
}
|
|
145
|
+
// Another index, while the e-mail was free when the statement started: either a parallel registration of
|
|
146
|
+
// the same e-mail committed in between and its unique index has its own name, or the violation is of the
|
|
147
|
+
// primary key or of an index added by the application. The e-mail is looked up; this path never runs for an
|
|
148
|
+
// address registered before the request, so the lookup cannot reveal one. A row with it means "taken";
|
|
149
|
+
// otherwise the violation is passed on unchanged. Inside a transaction of the application the lookup cannot
|
|
150
|
+
// run (the transaction is aborted), and the violation is passed on as well.
|
|
151
|
+
let taken;
|
|
152
|
+
try {
|
|
153
|
+
taken = (await this.findUserByEmail(user.email)) !== null;
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
if (taken) {
|
|
159
|
+
throw new EmailTakenError();
|
|
160
|
+
}
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
if (rows[0] === undefined) {
|
|
164
|
+
throw new EmailTakenError();
|
|
165
|
+
}
|
|
166
|
+
return toUser(rows[0]);
|
|
167
|
+
}
|
|
168
|
+
/** {@inheritDoc AuthRepository.updatePasswordHash} */
|
|
169
|
+
async updatePasswordHash(userId, passwordHash, updatedAt) {
|
|
170
|
+
await getQueryExecutor().query('UPDATE users SET password_hash = $2, updated_at = $3 WHERE user_id = $1', [
|
|
171
|
+
userId,
|
|
172
|
+
passwordHash,
|
|
173
|
+
updatedAt,
|
|
174
|
+
]);
|
|
175
|
+
}
|
|
176
|
+
/** {@inheritDoc AuthRepository.markEmailVerified} */
|
|
177
|
+
async markEmailVerified(userId, verifiedAt) {
|
|
178
|
+
await getQueryExecutor().query('UPDATE users SET email_verified_at = $2, updated_at = $2 WHERE user_id = $1 AND email_verified_at IS NULL', [userId, verifiedAt]);
|
|
179
|
+
}
|
|
180
|
+
/** {@inheritDoc AuthRepository.deleteUser} */
|
|
181
|
+
async deleteUser(userId) {
|
|
182
|
+
// The tokens go with the user: their foreign keys are `ON DELETE CASCADE`.
|
|
183
|
+
await getQueryExecutor().query('DELETE FROM users WHERE user_id = $1', [userId]);
|
|
184
|
+
}
|
|
185
|
+
/** {@inheritDoc AuthRepository.createRefreshToken} */
|
|
186
|
+
async createRefreshToken(token) {
|
|
187
|
+
await getQueryExecutor().query(`INSERT INTO refresh_tokens (user_id, token_hash, family_id, client_kind, expires_at, created_at)
|
|
188
|
+
VALUES ($1, $2, $3, $4, $5, $6)`, [token.userId, token.tokenHash, token.familyId, token.clientKind, token.expiresAt, token.createdAt]);
|
|
189
|
+
}
|
|
190
|
+
/** {@inheritDoc AuthRepository.findRefreshToken} */
|
|
191
|
+
async findRefreshToken(tokenHash) {
|
|
192
|
+
const result = await getQueryExecutor().query(`SELECT ${REFRESH_TOKEN_COLUMNS} FROM refresh_tokens WHERE token_hash = $1`, [tokenHash]);
|
|
193
|
+
return result.rows[0] === undefined ? null : toRefreshToken(result.rows[0]);
|
|
194
|
+
}
|
|
195
|
+
/** {@inheritDoc AuthRepository.revokeRefreshToken} */
|
|
196
|
+
async revokeRefreshToken(tokenHash, revokedAt, reason) {
|
|
197
|
+
const result = await getQueryExecutor().query(`UPDATE refresh_tokens SET revoked_at = $2, revoked_reason = $3 WHERE token_hash = $1 AND revoked_at IS NULL
|
|
198
|
+
RETURNING ${REFRESH_TOKEN_COLUMNS}`, [tokenHash, revokedAt, reason]);
|
|
199
|
+
return result.rows[0] === undefined ? null : toRefreshToken(result.rows[0]);
|
|
200
|
+
}
|
|
201
|
+
/** {@inheritDoc AuthRepository.revokeRefreshTokenFamily} */
|
|
202
|
+
async revokeRefreshTokenFamily(familyId, revokedAt) {
|
|
203
|
+
const result = await getQueryExecutor().query(END_SESSIONS('family_id'), [
|
|
204
|
+
familyId,
|
|
205
|
+
revokedAt,
|
|
206
|
+
]);
|
|
207
|
+
return result.rows.filter((row) => row.was_valid).length;
|
|
208
|
+
}
|
|
209
|
+
/** {@inheritDoc AuthRepository.revokeAllRefreshTokens} */
|
|
210
|
+
async revokeAllRefreshTokens(userId, revokedAt) {
|
|
211
|
+
const result = await getQueryExecutor().query(END_SESSIONS('user_id'), [
|
|
212
|
+
userId,
|
|
213
|
+
revokedAt,
|
|
214
|
+
]);
|
|
215
|
+
return result.rows.filter((row) => row.was_valid).length;
|
|
216
|
+
}
|
|
217
|
+
/** {@inheritDoc AuthRepository.createAuthToken} */
|
|
218
|
+
async createAuthToken(token) {
|
|
219
|
+
await getQueryExecutor().query(`INSERT INTO auth_tokens (user_id, purpose, token_hash, expires_at, created_at)
|
|
220
|
+
VALUES ($1, $2, $3, $4, $5)`, [token.userId, token.purpose, token.tokenHash, token.expiresAt, token.createdAt]);
|
|
221
|
+
}
|
|
222
|
+
/** {@inheritDoc AuthRepository.invalidateAuthTokens} */
|
|
223
|
+
async invalidateAuthTokens(userId, purpose, usedAt) {
|
|
224
|
+
await getQueryExecutor().query('UPDATE auth_tokens SET used_at = $3 WHERE user_id = $1 AND purpose = $2 AND used_at IS NULL', [userId, purpose, usedAt]);
|
|
225
|
+
}
|
|
226
|
+
/** {@inheritDoc AuthRepository.findAuthToken} */
|
|
227
|
+
async findAuthToken(tokenHash) {
|
|
228
|
+
const result = await getQueryExecutor().query(`SELECT ${AUTH_TOKEN_COLUMNS} FROM auth_tokens WHERE token_hash = $1`, [tokenHash]);
|
|
229
|
+
return result.rows[0] === undefined ? null : toAuthToken(result.rows[0]);
|
|
230
|
+
}
|
|
231
|
+
/** {@inheritDoc AuthRepository.consumeAuthToken} */
|
|
232
|
+
async consumeAuthToken(tokenHash, purpose, usedAt) {
|
|
233
|
+
const result = await getQueryExecutor().query(`UPDATE auth_tokens SET used_at = $3
|
|
234
|
+
WHERE token_hash = $1 AND purpose = $2 AND used_at IS NULL AND expires_at > $3
|
|
235
|
+
RETURNING ${AUTH_TOKEN_COLUMNS}`, [tokenHash, purpose, usedAt]);
|
|
236
|
+
return result.rows[0] === undefined ? null : toAuthToken(result.rows[0]);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Creates the PostgreSQL adapter of `AuthRepository` for `AuthConfig.repository`.
|
|
241
|
+
*
|
|
242
|
+
* @param options - `lockTimeoutMs`, how long `lockUser` waits for the lock of a user (default 3000).
|
|
243
|
+
* @returns A repository on the pool of `@mielk/db/pg`; the application calls `initDb` before the first request.
|
|
244
|
+
* @throws `RangeError` when `lockTimeoutMs` is not an integer from 1 to 60000.
|
|
245
|
+
* @example
|
|
246
|
+
* ```ts
|
|
247
|
+
* await initDb(dbConfig);
|
|
248
|
+
* const auth = createAuth({ ...config, repository: createPgAuthRepository() });
|
|
249
|
+
* ```
|
|
250
|
+
* @since 2.0.0
|
|
251
|
+
*/
|
|
252
|
+
export const createPgAuthRepository = (options = {}) => new PgAuthRepository(options);
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React layer of the session (plan TASK-191, 2.6): the provider restores the session of the previous run and shares the
|
|
3
|
+
* state; the hooks read it and run the actions. No JSX, so the library needs no JSX setting of the compiler.
|
|
4
|
+
*/
|
|
5
|
+
import { type ReactNode } from 'react';
|
|
6
|
+
import type { AuthClient, AuthState } from '../client/index.js';
|
|
7
|
+
/**
|
|
8
|
+
* Props of `AuthProvider`.
|
|
9
|
+
*
|
|
10
|
+
* @since 2.0.0
|
|
11
|
+
*/
|
|
12
|
+
export type AuthProviderProps = {
|
|
13
|
+
/** The client from `createAuthClient`, created once for the application (outside the components). */
|
|
14
|
+
client: AuthClient;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Provides the client to the hooks and restores the session once, at the start: the state is `loading` until it ends
|
|
19
|
+
* (`rn:SES-3`: show the splash screen, not the login screen). The state is read from the client with
|
|
20
|
+
* `useSyncExternalStore`, so every change of the session (a login, a refresh token the server rejected, a logout in
|
|
21
|
+
* another component) reaches the components at once.
|
|
22
|
+
*
|
|
23
|
+
* @param props - `client` from `createAuthClient`, and the `children` that use the hooks.
|
|
24
|
+
* @returns the provider element wrapping `children`.
|
|
25
|
+
* @since 2.0.0
|
|
26
|
+
*/
|
|
27
|
+
export declare const AuthProvider: ({ client, children }: AuthProviderProps) => ReactNode;
|
|
28
|
+
/**
|
|
29
|
+
* The client of the nearest `AuthProvider`, for the calls `useAuth` does not wrap (e-mail verification, password reset, `authorizedFetch`).
|
|
30
|
+
*
|
|
31
|
+
* @returns the client passed to the provider.
|
|
32
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
33
|
+
* @since 2.0.0
|
|
34
|
+
*/
|
|
35
|
+
export declare const useAuthClient: () => AuthClient;
|
|
36
|
+
/**
|
|
37
|
+
* The state of the session: `loading` until the session is restored, then `authenticated` with the user, or `anonymous`.
|
|
38
|
+
*
|
|
39
|
+
* @returns the current state; the component renders again on every change.
|
|
40
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
41
|
+
* @since 2.0.0
|
|
42
|
+
*/
|
|
43
|
+
export declare const useSession: () => AuthState;
|
|
44
|
+
/**
|
|
45
|
+
* The state of the session with the actions of the user.
|
|
46
|
+
*
|
|
47
|
+
* @since 2.0.0
|
|
48
|
+
*/
|
|
49
|
+
export type UseAuthResult = {
|
|
50
|
+
state: AuthState;
|
|
51
|
+
login: AuthClient['login'];
|
|
52
|
+
register: AuthClient['register'];
|
|
53
|
+
logout: AuthClient['logout'];
|
|
54
|
+
changePassword: AuthClient['changePassword'];
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The state of the session and the actions of signing in, registration, signing out and password change. The actions
|
|
58
|
+
* reject with `AuthClientError` (`@mielk/auth/client`): its `message` is a message key to translate, `issues` list the
|
|
59
|
+
* fields of a rejected form. After a password change the state is `anonymous`: the user signs in with the new password.
|
|
60
|
+
*
|
|
61
|
+
* @returns the state and the actions; the object changes with the state.
|
|
62
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
63
|
+
* @example
|
|
64
|
+
* ```ts
|
|
65
|
+
* const { state, login, logout } = useAuth();
|
|
66
|
+
* if (state.status === 'authenticated') return `Hello ${state.user.email}`;
|
|
67
|
+
* ```
|
|
68
|
+
* @since 2.0.0
|
|
69
|
+
*/
|
|
70
|
+
export declare const useAuth: () => UseAuthResult;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React layer of the session (plan TASK-191, 2.6): the provider restores the session of the previous run and shares the
|
|
3
|
+
* state; the hooks read it and run the actions. No JSX, so the library needs no JSX setting of the compiler.
|
|
4
|
+
*/
|
|
5
|
+
import { createContext, createElement, useContext, useEffect, useMemo, useSyncExternalStore, } from 'react';
|
|
6
|
+
const AuthClientContext = createContext(null);
|
|
7
|
+
/**
|
|
8
|
+
* Provides the client to the hooks and restores the session once, at the start: the state is `loading` until it ends
|
|
9
|
+
* (`rn:SES-3`: show the splash screen, not the login screen). The state is read from the client with
|
|
10
|
+
* `useSyncExternalStore`, so every change of the session (a login, a refresh token the server rejected, a logout in
|
|
11
|
+
* another component) reaches the components at once.
|
|
12
|
+
*
|
|
13
|
+
* @param props - `client` from `createAuthClient`, and the `children` that use the hooks.
|
|
14
|
+
* @returns the provider element wrapping `children`.
|
|
15
|
+
* @since 2.0.0
|
|
16
|
+
*/
|
|
17
|
+
export const AuthProvider = ({ client, children }) => {
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
// `restoreSession` never rejects: a failure ends as the state `anonymous`.
|
|
20
|
+
void client.restoreSession();
|
|
21
|
+
}, [client]);
|
|
22
|
+
return createElement(AuthClientContext.Provider, { value: client }, children);
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The client of the nearest `AuthProvider`, for the calls `useAuth` does not wrap (e-mail verification, password reset, `authorizedFetch`).
|
|
26
|
+
*
|
|
27
|
+
* @returns the client passed to the provider.
|
|
28
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
29
|
+
* @since 2.0.0
|
|
30
|
+
*/
|
|
31
|
+
export const useAuthClient = () => {
|
|
32
|
+
const client = useContext(AuthClientContext);
|
|
33
|
+
if (client === null)
|
|
34
|
+
throw new Error('useAuthClient must be used inside <AuthProvider>.');
|
|
35
|
+
return client;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* The state of the session: `loading` until the session is restored, then `authenticated` with the user, or `anonymous`.
|
|
39
|
+
*
|
|
40
|
+
* @returns the current state; the component renders again on every change.
|
|
41
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
42
|
+
* @since 2.0.0
|
|
43
|
+
*/
|
|
44
|
+
export const useSession = () => {
|
|
45
|
+
const client = useAuthClient();
|
|
46
|
+
return useSyncExternalStore(client.subscribe, client.getState, client.getState);
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The state of the session and the actions of signing in, registration, signing out and password change. The actions
|
|
50
|
+
* reject with `AuthClientError` (`@mielk/auth/client`): its `message` is a message key to translate, `issues` list the
|
|
51
|
+
* fields of a rejected form. After a password change the state is `anonymous`: the user signs in with the new password.
|
|
52
|
+
*
|
|
53
|
+
* @returns the state and the actions; the object changes with the state.
|
|
54
|
+
* @throws `Error` when called outside `<AuthProvider>`.
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* const { state, login, logout } = useAuth();
|
|
58
|
+
* if (state.status === 'authenticated') return `Hello ${state.user.email}`;
|
|
59
|
+
* ```
|
|
60
|
+
* @since 2.0.0
|
|
61
|
+
*/
|
|
62
|
+
export const useAuth = () => {
|
|
63
|
+
const client = useAuthClient();
|
|
64
|
+
const state = useSession();
|
|
65
|
+
return useMemo(() => ({
|
|
66
|
+
state,
|
|
67
|
+
login: (body) => client.login(body),
|
|
68
|
+
register: (body) => client.register(body),
|
|
69
|
+
logout: () => client.logout(),
|
|
70
|
+
changePassword: (body) => client.changePassword(body),
|
|
71
|
+
}), [client, state]);
|
|
72
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { AuthProvider, useAuth, useAuthClient, useSession } from './auth-provider.js';
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request and response schemas of the authentication endpoints (plan TASK-191, 2.1 and 2.2), shared by the server and the
|
|
3
|
+
* clients. Messages of the conditions are message keys (`Msg`, `rest:VAL-4`), translated by the client.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
/**
|
|
7
|
+
* Minimum length of a new password in characters (`rest:AUT-7`: the password policy is here).
|
|
8
|
+
*
|
|
9
|
+
* @since 2.0.0
|
|
10
|
+
*/
|
|
11
|
+
export declare const PASSWORD_MIN_LENGTH = 10;
|
|
12
|
+
/**
|
|
13
|
+
* Maximum length of a new password in UTF-8 bytes: bcrypt ignores the bytes after the 72nd.
|
|
14
|
+
*
|
|
15
|
+
* @since 2.0.0
|
|
16
|
+
*/
|
|
17
|
+
export declare const PASSWORD_MAX_BYTES = 72;
|
|
18
|
+
/**
|
|
19
|
+
* Maximum length of an e-mail address (RFC 5321).
|
|
20
|
+
*
|
|
21
|
+
* @since 2.0.0
|
|
22
|
+
*/
|
|
23
|
+
export declare const EMAIL_MAX_LENGTH = 254;
|
|
24
|
+
/**
|
|
25
|
+
* Kind of the client that asks for a message with a link: the link leads to the web or to the mobile application.
|
|
26
|
+
*
|
|
27
|
+
* @since 2.0.0
|
|
28
|
+
*/
|
|
29
|
+
export declare const clientKindSchema: z.ZodEnum<{
|
|
30
|
+
mobile: "mobile";
|
|
31
|
+
web: "web";
|
|
32
|
+
}>;
|
|
33
|
+
/**
|
|
34
|
+
* E-mail address trimmed and in lower case (the form the library stores and compares).
|
|
35
|
+
*
|
|
36
|
+
* @since 2.0.0
|
|
37
|
+
*/
|
|
38
|
+
export declare const emailSchema: z.ZodPipe<z.ZodString, z.ZodEmail>;
|
|
39
|
+
/**
|
|
40
|
+
* A new password: at least `PASSWORD_MIN_LENGTH` characters and at most `PASSWORD_MAX_BYTES` bytes.
|
|
41
|
+
*
|
|
42
|
+
* @since 2.0.0
|
|
43
|
+
*/
|
|
44
|
+
export declare const newPasswordSchema: z.ZodString;
|
|
45
|
+
/**
|
|
46
|
+
* Body of `POST /register`. `client` selects the link of the verification e-mail; default `web`.
|
|
47
|
+
*
|
|
48
|
+
* @since 2.0.0
|
|
49
|
+
*/
|
|
50
|
+
export declare const registerBodySchema: z.ZodObject<{
|
|
51
|
+
email: z.ZodPipe<z.ZodString, z.ZodEmail>;
|
|
52
|
+
password: z.ZodString;
|
|
53
|
+
client: z.ZodOptional<z.ZodEnum<{
|
|
54
|
+
mobile: "mobile";
|
|
55
|
+
web: "web";
|
|
56
|
+
}>>;
|
|
57
|
+
}, z.core.$strip>;
|
|
58
|
+
/**
|
|
59
|
+
* Body of `POST /login` and `POST /mobile/login`.
|
|
60
|
+
*
|
|
61
|
+
* @since 2.0.0
|
|
62
|
+
*/
|
|
63
|
+
export declare const loginBodySchema: z.ZodObject<{
|
|
64
|
+
email: z.ZodPipe<z.ZodString, z.ZodEmail>;
|
|
65
|
+
password: z.ZodString;
|
|
66
|
+
}, z.core.$strip>;
|
|
67
|
+
/**
|
|
68
|
+
* Body of `POST /mobile/refresh` and `POST /mobile/logout`.
|
|
69
|
+
*
|
|
70
|
+
* @since 2.0.0
|
|
71
|
+
*/
|
|
72
|
+
export declare const mobileRefreshBodySchema: z.ZodObject<{
|
|
73
|
+
refreshToken: z.ZodString;
|
|
74
|
+
}, z.core.$strip>;
|
|
75
|
+
/**
|
|
76
|
+
* Body of `POST /email-verification` (the account comes from the access token).
|
|
77
|
+
*
|
|
78
|
+
* @since 2.0.0
|
|
79
|
+
*/
|
|
80
|
+
export declare const resendVerificationBodySchema: z.ZodObject<{
|
|
81
|
+
client: z.ZodOptional<z.ZodEnum<{
|
|
82
|
+
mobile: "mobile";
|
|
83
|
+
web: "web";
|
|
84
|
+
}>>;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
/**
|
|
87
|
+
* Body of `POST /email-verification/confirm`: the token of the link and the password of the account, so only who has
|
|
88
|
+
* both the mailbox and the password confirms the address (audit S4, DEC-281).
|
|
89
|
+
*
|
|
90
|
+
* @since 2.0.0
|
|
91
|
+
*/
|
|
92
|
+
export declare const confirmEmailBodySchema: z.ZodObject<{
|
|
93
|
+
token: z.ZodString;
|
|
94
|
+
password: z.ZodString;
|
|
95
|
+
}, z.core.$strip>;
|
|
96
|
+
/**
|
|
97
|
+
* Body of `POST /password-reset`.
|
|
98
|
+
*
|
|
99
|
+
* @since 2.0.0
|
|
100
|
+
*/
|
|
101
|
+
export declare const requestPasswordResetBodySchema: z.ZodObject<{
|
|
102
|
+
email: z.ZodPipe<z.ZodString, z.ZodEmail>;
|
|
103
|
+
client: z.ZodOptional<z.ZodEnum<{
|
|
104
|
+
mobile: "mobile";
|
|
105
|
+
web: "web";
|
|
106
|
+
}>>;
|
|
107
|
+
}, z.core.$strip>;
|
|
108
|
+
/**
|
|
109
|
+
* Body of `POST /password-reset/confirm`.
|
|
110
|
+
*
|
|
111
|
+
* @since 2.0.0
|
|
112
|
+
*/
|
|
113
|
+
export declare const confirmPasswordResetBodySchema: z.ZodObject<{
|
|
114
|
+
token: z.ZodString;
|
|
115
|
+
password: z.ZodString;
|
|
116
|
+
}, z.core.$strip>;
|
|
117
|
+
/**
|
|
118
|
+
* Body of `PUT /password`.
|
|
119
|
+
*
|
|
120
|
+
* @since 2.0.0
|
|
121
|
+
*/
|
|
122
|
+
export declare const changePasswordBodySchema: z.ZodObject<{
|
|
123
|
+
currentPassword: z.ZodString;
|
|
124
|
+
newPassword: z.ZodString;
|
|
125
|
+
}, z.core.$strip>;
|
|
126
|
+
/**
|
|
127
|
+
* Body of `DELETE /me`: the password confirms the irreversible operation.
|
|
128
|
+
*
|
|
129
|
+
* @since 2.0.0
|
|
130
|
+
*/
|
|
131
|
+
export declare const deleteAccountBodySchema: z.ZodObject<{
|
|
132
|
+
password: z.ZodString;
|
|
133
|
+
}, z.core.$strip>;
|
|
134
|
+
/** Request body validated by `registerBodySchema` (the output type of the schema).
|
|
135
|
+
*
|
|
136
|
+
* @since 2.0.0
|
|
137
|
+
*/
|
|
138
|
+
export type RegisterBody = z.output<typeof registerBodySchema>;
|
|
139
|
+
/** Request body validated by `loginBodySchema` (the output type of the schema).
|
|
140
|
+
*
|
|
141
|
+
* @since 2.0.0
|
|
142
|
+
*/
|
|
143
|
+
export type LoginBody = z.output<typeof loginBodySchema>;
|
|
144
|
+
/** Request body validated by `mobileRefreshBodySchema` (the output type of the schema).
|
|
145
|
+
*
|
|
146
|
+
* @since 2.0.0
|
|
147
|
+
*/
|
|
148
|
+
export type MobileRefreshBody = z.output<typeof mobileRefreshBodySchema>;
|
|
149
|
+
/** Request body validated by `resendVerificationBodySchema` (the output type of the schema).
|
|
150
|
+
*
|
|
151
|
+
* @since 2.0.0
|
|
152
|
+
*/
|
|
153
|
+
export type ResendVerificationBody = z.output<typeof resendVerificationBodySchema>;
|
|
154
|
+
/** Request body validated by `confirmEmailBodySchema` (the output type of the schema).
|
|
155
|
+
*
|
|
156
|
+
* @since 2.0.0
|
|
157
|
+
*/
|
|
158
|
+
export type ConfirmEmailBody = z.output<typeof confirmEmailBodySchema>;
|
|
159
|
+
/** Request body validated by `requestPasswordResetBodySchema` (the output type of the schema).
|
|
160
|
+
*
|
|
161
|
+
* @since 2.0.0
|
|
162
|
+
*/
|
|
163
|
+
export type RequestPasswordResetBody = z.output<typeof requestPasswordResetBodySchema>;
|
|
164
|
+
/** Request body validated by `confirmPasswordResetBodySchema` (the output type of the schema).
|
|
165
|
+
*
|
|
166
|
+
* @since 2.0.0
|
|
167
|
+
*/
|
|
168
|
+
export type ConfirmPasswordResetBody = z.output<typeof confirmPasswordResetBodySchema>;
|
|
169
|
+
/** Request body validated by `changePasswordBodySchema` (the output type of the schema).
|
|
170
|
+
*
|
|
171
|
+
* @since 2.0.0
|
|
172
|
+
*/
|
|
173
|
+
export type ChangePasswordBody = z.output<typeof changePasswordBodySchema>;
|
|
174
|
+
/** Request body validated by `deleteAccountBodySchema` (the output type of the schema).
|
|
175
|
+
*
|
|
176
|
+
* @since 2.0.0
|
|
177
|
+
*/
|
|
178
|
+
export type DeleteAccountBody = z.output<typeof deleteAccountBodySchema>;
|
|
179
|
+
/**
|
|
180
|
+
* Account data in the responses; the fields are picked explicitly, never the whole record (`rest:RES-10`).
|
|
181
|
+
*
|
|
182
|
+
* @since 2.0.0
|
|
183
|
+
*/
|
|
184
|
+
export type AuthUserResponse = {
|
|
185
|
+
userId: string;
|
|
186
|
+
email: string;
|
|
187
|
+
emailVerified: boolean;
|
|
188
|
+
/** ISO 8601 time. */
|
|
189
|
+
createdAt: string;
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* Data of `GET /me` (200). `POST /register` answers 202 without a body.
|
|
193
|
+
*
|
|
194
|
+
* @since 2.0.0
|
|
195
|
+
*/
|
|
196
|
+
export type UserResponse = {
|
|
197
|
+
user: AuthUserResponse;
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* Data of `POST /login` (200); the refresh token is in the cookie.
|
|
201
|
+
*
|
|
202
|
+
* @since 2.0.0
|
|
203
|
+
*/
|
|
204
|
+
export type LoginResponse = {
|
|
205
|
+
accessToken: string;
|
|
206
|
+
user: AuthUserResponse;
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* Data of `POST /refresh` (200); the new refresh token is in the cookie.
|
|
210
|
+
*
|
|
211
|
+
* @since 2.0.0
|
|
212
|
+
*/
|
|
213
|
+
export type RefreshResponse = {
|
|
214
|
+
accessToken: string;
|
|
215
|
+
};
|
|
216
|
+
/**
|
|
217
|
+
* Data of `POST /mobile/login` (200).
|
|
218
|
+
*
|
|
219
|
+
* @since 2.0.0
|
|
220
|
+
*/
|
|
221
|
+
export type MobileLoginResponse = {
|
|
222
|
+
accessToken: string;
|
|
223
|
+
refreshToken: string;
|
|
224
|
+
user: AuthUserResponse;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Data of `POST /mobile/refresh` (200).
|
|
228
|
+
*
|
|
229
|
+
* @since 2.0.0
|
|
230
|
+
*/
|
|
231
|
+
export type MobileRefreshResponse = {
|
|
232
|
+
accessToken: string;
|
|
233
|
+
refreshToken: string;
|
|
234
|
+
};
|