@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +673 -2
  4. package/dist/client/api-address.d.ts +17 -0
  5. package/dist/client/api-address.js +434 -0
  6. package/dist/client/auth-client.d.ts +226 -0
  7. package/dist/client/auth-client.js +676 -0
  8. package/dist/client/errors.d.ts +66 -0
  9. package/dist/client/errors.js +33 -0
  10. package/dist/client/guards.d.ts +26 -0
  11. package/dist/client/guards.js +27 -0
  12. package/dist/client/index.d.ts +4 -0
  13. package/dist/client/index.js +2 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +4 -0
  16. package/dist/locales/en-GB.json +50 -0
  17. package/dist/locales/pl.json +50 -0
  18. package/dist/messages.d.ts +65 -0
  19. package/dist/messages.js +57 -0
  20. package/dist/pg/index.d.ts +1 -0
  21. package/dist/pg/index.js +1 -0
  22. package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
  23. package/dist/pg/pg-auth-repository.d.ts +91 -0
  24. package/dist/pg/pg-auth-repository.js +252 -0
  25. package/dist/react/auth-provider.d.ts +70 -0
  26. package/dist/react/auth-provider.js +72 -0
  27. package/dist/react/index.d.ts +2 -0
  28. package/dist/react/index.js +1 -0
  29. package/dist/schemas/index.d.ts +234 -0
  30. package/dist/schemas/index.js +145 -0
  31. package/dist/server/access-token.d.ts +48 -0
  32. package/dist/server/access-token.js +54 -0
  33. package/dist/server/auth-middleware.d.ts +40 -0
  34. package/dist/server/auth-middleware.js +61 -0
  35. package/dist/server/config.d.ts +231 -0
  36. package/dist/server/config.js +250 -0
  37. package/dist/server/cookies.d.ts +13 -0
  38. package/dist/server/cookies.js +35 -0
  39. package/dist/server/core.d.ts +20 -0
  40. package/dist/server/core.js +32 -0
  41. package/dist/server/create-auth.d.ts +38 -0
  42. package/dist/server/create-auth.js +33 -0
  43. package/dist/server/errors.d.ts +177 -0
  44. package/dist/server/errors.js +201 -0
  45. package/dist/server/http-errors.d.ts +9 -0
  46. package/dist/server/http-errors.js +34 -0
  47. package/dist/server/limits.d.ts +95 -0
  48. package/dist/server/limits.js +98 -0
  49. package/dist/server/one-time-token.d.ts +49 -0
  50. package/dist/server/one-time-token.js +60 -0
  51. package/dist/server/opaque-token.d.ts +6 -0
  52. package/dist/server/opaque-token.js +7 -0
  53. package/dist/server/password.d.ts +45 -0
  54. package/dist/server/password.js +72 -0
  55. package/dist/server/ports.d.ts +343 -0
  56. package/dist/server/ports.js +11 -0
  57. package/dist/server/proxy-check.d.ts +17 -0
  58. package/dist/server/proxy-check.js +80 -0
  59. package/dist/server/refresh-token.d.ts +60 -0
  60. package/dist/server/refresh-token.js +122 -0
  61. package/dist/server/router.d.ts +29 -0
  62. package/dist/server/router.js +329 -0
  63. package/dist/server/safe-log.d.ts +9 -0
  64. package/dist/server/safe-log.js +24 -0
  65. package/dist/server/service.d.ts +153 -0
  66. package/dist/server/service.js +244 -0
  67. package/package.json +136 -5
@@ -0,0 +1,122 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { InvalidRefreshTokenError, RefreshTokenExpiredError, RefreshTokenReusedError } from './errors.js';
3
+ import { generateOpaqueToken, hashOpaqueToken } from './opaque-token.js';
4
+ /** Creates the refresh token service. */
5
+ export const createRefreshTokenService = ({ repository, ttlSeconds, reuseGraceSeconds = 0, clock, }) => {
6
+ const store = async (userId, clientKind, familyId, target, notAfter, createdAt = clock.now()) => {
7
+ const fullExpiry = createdAt.getTime() + ttlSeconds * 1000;
8
+ // A token issued in the grace window never outlives the token presented (`rest:AUT-4`, condition 4).
9
+ const expiresAt = new Date(notAfter === undefined ? fullExpiry : Math.min(fullExpiry, notAfter.getTime()));
10
+ const token = generateOpaqueToken();
11
+ await target.createRefreshToken({
12
+ userId,
13
+ tokenHash: hashOpaqueToken(token),
14
+ familyId,
15
+ clientKind,
16
+ expiresAt,
17
+ createdAt,
18
+ });
19
+ return { userId, token, expiresAt };
20
+ };
21
+ const issue = (userId, clientKind, target = repository) => store(userId, clientKind, randomUUID(), target);
22
+ const revokeAll = async (userId, target) => {
23
+ if (target === undefined) {
24
+ return repository.withTransaction((tx) => revokeAll(userId, tx));
25
+ }
26
+ await target.lockUser(userId);
27
+ return target.revokeAllRefreshTokens(userId, clock.now());
28
+ };
29
+ /**
30
+ * Issues the next token of the session of `record` under the lock of the user, with the state of the e-mail read in
31
+ * the same transaction. The rotation decides nothing by the account: an account that no longer exists (its tokens go
32
+ * with it in the reference schema) counts as not verified. `notAfter` caps the expiry of the new token (grace window).
33
+ */
34
+ const next = async (record, tx, notAfter) => {
35
+ const user = await tx.findUserById(record.userId);
36
+ // The time is read once: a token that expires while the rotation runs must not get a successor that is already
37
+ // expired (`rest:AUT-4`, condition 2).
38
+ const at = clock.now();
39
+ if (notAfter !== undefined && notAfter.getTime() <= at.getTime()) {
40
+ return { kind: 'expired' };
41
+ }
42
+ const issued = await store(record.userId, record.clientKind, record.familyId, tx, notAfter, at);
43
+ return { kind: 'rotated', issued: { ...issued, emailVerified: user?.emailVerifiedAt != null } };
44
+ };
45
+ /** Whether a rotated token is still within the grace window at `now`. */
46
+ const withinGrace = (record, now) => reuseGraceSeconds > 0 &&
47
+ record.revokedAt !== null &&
48
+ now.getTime() - record.revokedAt.getTime() <= reuseGraceSeconds * 1000;
49
+ /** Decides about a token that is already revoked (read under the lock of the user). */
50
+ const rotateRevoked = async (record, now, tx) => {
51
+ if (record.revokedReason !== 'rotated') {
52
+ // The session ended (logout, revoke all, a reuse already detected): no alarm, nothing changes (audit S1).
53
+ return { kind: 'invalid' };
54
+ }
55
+ if (withinGrace(record, now)) {
56
+ return next(record, tx, record.expiresAt);
57
+ }
58
+ // A token replaced longer ago is presented again: the session may be stolen, end it (rest:AUT-11).
59
+ await tx.revokeRefreshTokenFamily(record.familyId, now);
60
+ return { kind: 'reused' };
61
+ };
62
+ /*
63
+ * The outcome is returned from the transaction instead of thrown inside it: a rejection would roll back the
64
+ * revocation of the session after a reuse, which must stay committed (rest:AUT-11).
65
+ * The token is read twice: first to learn the user to lock (lock order: the user first), then again under the
66
+ * lock, so a parallel rotation or logout that committed in the meantime is seen.
67
+ */
68
+ const rotate = async (token, clientKind) => {
69
+ const tokenHash = hashOpaqueToken(token);
70
+ const outcome = await repository.withTransaction(async (tx) => {
71
+ const unlocked = await tx.findRefreshToken(tokenHash);
72
+ if (unlocked === null || unlocked.clientKind !== clientKind) {
73
+ return { kind: 'invalid' };
74
+ }
75
+ await tx.lockUser(unlocked.userId);
76
+ const now = clock.now();
77
+ const record = await tx.findRefreshToken(tokenHash);
78
+ if (record === null) {
79
+ return { kind: 'invalid' };
80
+ }
81
+ // Expiry first: an expired token has no side effects, however it was revoked (audit S1, E3).
82
+ if (record.expiresAt.getTime() <= now.getTime()) {
83
+ return { kind: 'expired' };
84
+ }
85
+ if (record.revokedAt !== null) {
86
+ return rotateRevoked(record, now, tx);
87
+ }
88
+ const revoked = await tx.revokeRefreshToken(tokenHash, now, 'rotated');
89
+ if (revoked === null) {
90
+ // Only an adapter without a working lock of the user gets here: read the token again and decide.
91
+ const current = await tx.findRefreshToken(tokenHash);
92
+ return current?.revokedAt == null ? { kind: 'invalid' } : rotateRevoked(current, now, tx);
93
+ }
94
+ return next(record, tx);
95
+ });
96
+ switch (outcome.kind) {
97
+ case 'rotated':
98
+ return outcome.issued;
99
+ case 'invalid':
100
+ throw new InvalidRefreshTokenError();
101
+ case 'expired':
102
+ throw new RefreshTokenExpiredError();
103
+ case 'reused':
104
+ throw new RefreshTokenReusedError();
105
+ }
106
+ };
107
+ const revoke = async (token, clientKind) => {
108
+ const tokenHash = hashOpaqueToken(token);
109
+ const record = await repository.findRefreshToken(tokenHash);
110
+ // An expired token has no side effects, as in `rotate`: its session may live on in a valid successor, which an old
111
+ // cookie or a token stolen long ago must not end (r1:U3). Its own expiry never changes, so no lock is needed.
112
+ if (record?.clientKind !== clientKind || record.expiresAt.getTime() <= clock.now().getTime()) {
113
+ return;
114
+ }
115
+ // Under the lock of the user, so a parallel rotation either sees the session ended or its new token is revoked.
116
+ await repository.withTransaction(async (tx) => {
117
+ await tx.lockUser(record.userId);
118
+ await tx.revokeRefreshTokenFamily(record.familyId, clock.now());
119
+ });
120
+ };
121
+ return { issue, rotate, revoke, revokeAll };
122
+ };
@@ -0,0 +1,29 @@
1
+ /** Router Express of the authentication endpoints (plan TASK-191, 2.2). The application mounts it under `/v1/auth`. */
2
+ import { Router, type RequestHandler } from 'express';
3
+ import type { ResolvedAuthConfig } from './config.js';
4
+ import type { AuthLimits } from './limits.js';
5
+ import { type AuthService } from './service.js';
6
+ /**
7
+ * Rejects a request that has an `Origin` header with 403: browser code must not receive a refresh token in the body
8
+ * (`AUT-13`). It answers itself (no error handler is needed), so the application can mount it outside the application
9
+ * of `createExpressApp`, before the JSON parser of `@mielk/http`, which would answer a malformed body 400 first (K17):
10
+ * `root.use('/v1/auth/mobile', mobileOriginGuard)`. The router mounts it for `/mobile/*` as well.
11
+ *
12
+ * @param req - the request; one with an `Origin` header is answered 403.
13
+ * @param res - the response.
14
+ * @param next - called for a request without `Origin`.
15
+ * @returns nothing.
16
+ * @example
17
+ * root.use('/v1/auth/mobile', mobileOriginGuard); // before the JSON parser
18
+ * @since 2.0.0
19
+ */
20
+ export declare const mobileOriginGuard: RequestHandler;
21
+ /** Dependencies of the router. */
22
+ export type AuthRouterOptions = {
23
+ config: ResolvedAuthConfig;
24
+ service: AuthService;
25
+ limits: AuthLimits;
26
+ authMiddleware: RequestHandler;
27
+ };
28
+ /** Creates the router with all the endpoints of the library. Errors of the library are turned into API errors at its end. */
29
+ export declare const createAuthRouter: ({ config, service, limits, authMiddleware }: AuthRouterOptions) => Router;
@@ -0,0 +1,329 @@
1
+ /** Router Express of the authentication endpoints (plan TASK-191, 2.2). The application mounts it under `/v1/auth`. */
2
+ import express, { Router } from 'express';
3
+ import { HttpError, HttpResponseStatus, UnauthorizedError, failure, noContent, success } from '@mielk/http/http';
4
+ import { getValidated, validateRequest } from '@mielk/http/validation';
5
+ import { z } from 'zod';
6
+ import { Msg } from '../messages.js';
7
+ import { changePasswordBodySchema, confirmEmailBodySchema, confirmPasswordResetBodySchema, deleteAccountBodySchema, loginBodySchema, mobileRefreshBodySchema, registerBodySchema, requestPasswordResetBodySchema, resendVerificationBodySchema, } from '../schemas/index.js';
8
+ import { readCookie, refreshCookieOptions, REFRESH_COOKIE_NAME } from './cookies.js';
9
+ import { AuthError, InvalidRefreshTokenError, RefreshTokenExpiredError, RefreshTokenReusedError } from './errors.js';
10
+ import { toHttpError } from './http-errors.js';
11
+ import { createProxyCheck } from './proxy-check.js';
12
+ import { logError, logWarning, safeErrorInfo } from './service.js';
13
+ /** Maximum size of a request body: the largest legitimate body is a few hundred bytes. */
14
+ const BODY_LIMIT = '16kb';
15
+ /** Languages of the library's e-mails; the application chooses the actual texts. */
16
+ const DEFAULT_LOCALE = 'en-GB';
17
+ const POLISH_LOCALE = 'pl';
18
+ const toUserResponse = (user) => ({
19
+ userId: user.userId,
20
+ email: user.email,
21
+ emailVerified: user.emailVerifiedAt !== null,
22
+ createdAt: user.createdAt.toISOString(),
23
+ });
24
+ /** Language of the e-mail: Polish when the first language of `Accept-Language` is Polish, otherwise English. */
25
+ const localeOf = (req) => {
26
+ const first = (req.headers['accept-language'] ?? '').split(',')[0]?.trim().toLowerCase() ?? '';
27
+ return first === POLISH_LOCALE || first.startsWith(`${POLISH_LOCALE}-`) ? POLISH_LOCALE : DEFAULT_LOCALE;
28
+ };
29
+ const isLogger = (value) => typeof value === 'object' &&
30
+ value !== null &&
31
+ typeof Reflect.get(value, 'warn') === 'function' &&
32
+ typeof Reflect.get(value, 'error') === 'function';
33
+ /** The request logger of `@mielk/http` (it carries the request identifier) or the logger of the configuration. */
34
+ const contextOf = (req, fallback) => {
35
+ const requestLogger = Reflect.get(req, 'log');
36
+ return { locale: localeOf(req), log: isLogger(requestLogger) ? requestLogger : fallback };
37
+ };
38
+ /**
39
+ * Leaves work that the answer does not wait for (r2:U1). The work logs its own failures and `logError` ignores a logger
40
+ * that throws or rejects, so the work does not reject because of the logger. This is the fallback for any other
41
+ * rejection: it is caught here, so it never becomes an unhandled rejection that ends the process of Node.js, and
42
+ * it is logged once, if the logger allows.
43
+ */
44
+ const detach = (work, ctx) => {
45
+ void work.catch((err) => {
46
+ logError(ctx.log, safeErrorInfo(err), 'The work after the answer failed.');
47
+ });
48
+ };
49
+ const userIdOf = (req) => {
50
+ if (req.user === undefined) {
51
+ // The route has no authMiddleware before the handler: a programming error, answered as 401 anyway.
52
+ throw new UnauthorizedError(Msg.accessToken.missing);
53
+ }
54
+ return req.user.userId;
55
+ };
56
+ /**
57
+ * Rejects a request that has an `Origin` header with 403: browser code must not receive a refresh token in the body
58
+ * (`AUT-13`). It answers itself (no error handler is needed), so the application can mount it outside the application
59
+ * of `createExpressApp`, before the JSON parser of `@mielk/http`, which would answer a malformed body 400 first (K17):
60
+ * `root.use('/v1/auth/mobile', mobileOriginGuard)`. The router mounts it for `/mobile/*` as well.
61
+ *
62
+ * @param req - the request; one with an `Origin` header is answered 403.
63
+ * @param res - the response.
64
+ * @param next - called for a request without `Origin`.
65
+ * @returns nothing.
66
+ * @example
67
+ * root.use('/v1/auth/mobile', mobileOriginGuard); // before the JSON parser
68
+ * @since 2.0.0
69
+ */
70
+ export const mobileOriginGuard = (req, res, next) => {
71
+ if (req.headers.origin === undefined) {
72
+ next();
73
+ return;
74
+ }
75
+ failure(res, HttpResponseStatus.FORBIDDEN, { message: Msg.mobile.originForbidden });
76
+ };
77
+ /** Creates the router with all the endpoints of the library. Errors of the library are turned into API errors at its end. */
78
+ export const createAuthRouter = ({ config, service, limits, authMiddleware }) => {
79
+ const router = Router();
80
+ const cookie = refreshCookieOptions(config.secureCookies);
81
+ const setRefreshCookie = (res, token, expiresAt) => {
82
+ res.cookie(REFRESH_COOKIE_NAME, token, { ...cookie, expires: expiresAt });
83
+ };
84
+ const clearRefreshCookie = (res) => {
85
+ res.clearCookie(REFRESH_COOKIE_NAME, cookie);
86
+ };
87
+ const refreshTokenOf = (req) => {
88
+ const token = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
89
+ if (token === undefined || token === '') {
90
+ throw new InvalidRefreshTokenError();
91
+ }
92
+ return token;
93
+ };
94
+ /**
95
+ * The step of a login that runs after the password matched and before the transaction of the session starts:
96
+ * resets the login counters (the next failed attempts count from one, `L1`). It runs outside the transaction, so a
97
+ * slow Redis holds no connection and no lock of the user (audit S8). When Redis cannot do it, the login does not
98
+ * stand: the limits of the endpoint reject the request while Redis is unavailable (`rest:LIM-4`), so no session is
99
+ * issued and the request is answered with 503 without a token. The counters may be reset for a login that then fails
100
+ * (the password changed meanwhile, the database fails): its password was right when it was checked.
101
+ */
102
+ const resetLoginCounters = (req, email) => async () => {
103
+ try {
104
+ await limits.clearLoginCounters(req, email);
105
+ }
106
+ catch (err) {
107
+ logError(contextOf(req, config.logger).log, safeErrorInfo(err), 'The login counters could not be cleared in Redis; the login is rejected.');
108
+ throw new HttpError(HttpResponseStatus.SERVICE_UNAVAILABLE);
109
+ }
110
+ };
111
+ /** Whether the refresh failed because the token itself was rejected (unknown, expired, reused). */
112
+ const isRejectedRefreshToken = (err) => err instanceof InvalidRefreshTokenError ||
113
+ err instanceof RefreshTokenExpiredError ||
114
+ err instanceof RefreshTokenReusedError;
115
+ /** Logs a reuse of a rotated refresh token: a fixed category and a fixed message, no token and no data of the user (`rest:AUT-11`, `LOG-4`). */
116
+ const logReuse = (req, err) => {
117
+ if (err instanceof RefreshTokenReusedError) {
118
+ logWarning(contextOf(req, config.logger).log, { errorCategory: 'refresh_token_reused' }, 'A refresh token that was already rotated was presented again; its session was ended.');
119
+ }
120
+ };
121
+ /** Validates the body with the schema (rest:VAL-1); the handler reads the result with `body`. */
122
+ const withBody = (schema) => validateRequest(z.object({ body: schema }));
123
+ const body = (res) => getValidated(res).body;
124
+ // The parser runs per route, after the limit per IP address, so a malformed JSON body is counted and its 400 carries
125
+ // `X-RateLimit-*` (`rest:LIM-3`). The check of `Origin` of the mobile endpoints comes before everything, so a browser
126
+ // request is answered 403 whatever its body is (K17). An application that parses JSON itself before the router
127
+ // (`createExpressApp` of `@mielk/http` does) must mount `mobileOriginGuard` before that parser; see the README. A parser that has run already is not run again.
128
+ // The limits per IP address depend on `trust proxy`: a wrong setting is logged once (audit W2).
129
+ router.use(createProxyCheck((req) => contextOf(req, config.logger).log));
130
+ router.use('/mobile', mobileOriginGuard);
131
+ const json = express.json({ limit: BODY_LIMIT });
132
+ // The login guards: the limit per IP address first, then the parser and the validation, then the guards that read
133
+ // the e-mail of the validated body, so a body without a password is counted only per address (audit N4).
134
+ const [loginIpGuard, ...loginBodyGuards] = limits.login;
135
+ if (loginIpGuard === undefined) {
136
+ throw new Error('The login guards are empty.');
137
+ }
138
+ const loginGuards = [loginIpGuard, json, withBody(loginBodySchema), ...loginBodyGuards];
139
+ // --- Web client -----------------------------------------------------------------------------------------------
140
+ // 202 without a body for a new and for a registered e-mail alike, so the answer does not reveal an account (audit S3).
141
+ router.post('/register', limits.register, json, withBody(registerBodySchema), (req, res) => {
142
+ const { email, password, client } = body(res);
143
+ const ctx = contextOf(req, config.logger);
144
+ // Reserve hashing capacity before 202. The account work runs in the promise after the response.
145
+ detach(service.register(email, password, client ?? 'web', ctx).then(({ delivery }) => delivery), ctx);
146
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
147
+ });
148
+ /**
149
+ * The cookie of the browser holds one refresh token, so a login replaces the token the request brought (of another
150
+ * account or of the same one); that token is revoked, so it does not stay valid until it expires (TASK-191.10,
151
+ * DEC-315 variant A). Only after the login succeeded: a failed login keeps the session of the cookie. A failure of
152
+ * the revocation does not undo the login: it is logged without the token, and the token expires by itself, as after
153
+ * a logout that does not reach the server.
154
+ */
155
+ const revokeReplacedCookie = async (req) => {
156
+ const replaced = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
157
+ if (replaced === undefined || replaced === '')
158
+ return;
159
+ try {
160
+ await service.logout(replaced, 'web');
161
+ }
162
+ catch (err) {
163
+ logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The refresh token replaced by a login could not be revoked; it expires by itself.');
164
+ }
165
+ };
166
+ router.post('/login', ...loginGuards, async (req, res) => {
167
+ const { email, password } = body(res);
168
+ const result = await service.login(email, password, 'web', resetLoginCounters(req, email));
169
+ await revokeReplacedCookie(req);
170
+ setRefreshCookie(res, result.refreshToken.token, result.refreshToken.expiresAt);
171
+ success(res, HttpResponseStatus.OK, {
172
+ accessToken: result.accessToken.token,
173
+ user: toUserResponse(result.user),
174
+ });
175
+ });
176
+ /**
177
+ * A web refresh without the cookie is answered 401 before the limit, so it is not counted (audit S10, W2 b): the
178
+ * cookie is `httpOnly`, so the client restores the session on every start of the page, also for a visitor without
179
+ * a session, and those requests must not spend the budget of the address shared by the signed-in users behind it.
180
+ * A request with any cookie value is counted, so guessing tokens stays limited.
181
+ */
182
+ const requireRefreshCookie = (req, res, next) => {
183
+ const token = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
184
+ if (token === undefined || token === '') {
185
+ clearRefreshCookie(res);
186
+ next(toHttpError(new InvalidRefreshTokenError()));
187
+ return;
188
+ }
189
+ next();
190
+ };
191
+ router.post('/refresh', requireRefreshCookie, limits.refresh, async (req, res) => {
192
+ try {
193
+ const result = await service.refresh(refreshTokenOf(req), 'web');
194
+ setRefreshCookie(res, result.refreshToken.token, result.refreshToken.expiresAt);
195
+ success(res, HttpResponseStatus.OK, { accessToken: result.accessToken.token });
196
+ }
197
+ catch (err) {
198
+ logReuse(req, err);
199
+ // Only a rejected token is useless; then the cookie goes, so the client does not keep sending it. A transient
200
+ // failure (database, Redis, 5xx) keeps the cookie: the token is still valid and the client retries (DEC-271,
201
+ // audit S7).
202
+ if (isRejectedRefreshToken(err)) {
203
+ clearRefreshCookie(res);
204
+ }
205
+ throw err;
206
+ }
207
+ });
208
+ router.post('/logout', async (req, res) => {
209
+ const token = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
210
+ if (token !== undefined && token !== '') {
211
+ await service.logout(token, 'web');
212
+ }
213
+ clearRefreshCookie(res);
214
+ noContent(res);
215
+ });
216
+ // --- Mobile client: the refresh token is in the body; a request from a browser is refused ---------------------
217
+ const mobile = Router();
218
+ mobile.post('/login', ...loginGuards, async (req, res) => {
219
+ const { email, password } = body(res);
220
+ const result = await service.login(email, password, 'mobile', resetLoginCounters(req, email));
221
+ success(res, HttpResponseStatus.OK, {
222
+ accessToken: result.accessToken.token,
223
+ refreshToken: result.refreshToken.token,
224
+ user: toUserResponse(result.user),
225
+ });
226
+ });
227
+ mobile.post('/refresh', limits.refresh, json, withBody(mobileRefreshBodySchema), async (req, res) => {
228
+ const { refreshToken } = body(res);
229
+ const result = await service.refresh(refreshToken, 'mobile').catch((err) => {
230
+ logReuse(req, err);
231
+ throw err;
232
+ });
233
+ success(res, HttpResponseStatus.OK, {
234
+ accessToken: result.accessToken.token,
235
+ refreshToken: result.refreshToken.token,
236
+ });
237
+ });
238
+ mobile.post('/logout', json, withBody(mobileRefreshBodySchema), async (_req, res) => {
239
+ await service.logout(body(res).refreshToken, 'mobile');
240
+ noContent(res);
241
+ });
242
+ router.use('/mobile', mobile);
243
+ // --- Session and account of the signed-in user ----------------------------------------------------------------
244
+ router.post('/sessions/revoke-all', authMiddleware, async (req, res) => {
245
+ await service.revokeAllSessions(userIdOf(req));
246
+ noContent(res);
247
+ });
248
+ router.get('/me', authMiddleware, async (req, res) => {
249
+ success(res, HttpResponseStatus.OK, {
250
+ user: toUserResponse(await service.getUser(userIdOf(req))),
251
+ });
252
+ });
253
+ /**
254
+ * After the right password the counter of password checks starts again. The operation has succeeded by then, so a
255
+ * failure of Redis is only logged: the counter expires with its window.
256
+ */
257
+ const clearPasswordChecks = async (req, userId) => {
258
+ try {
259
+ await limits.clearPasswordChecks(userId);
260
+ }
261
+ catch (err) {
262
+ logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The counter of password checks could not be cleared in Redis.');
263
+ }
264
+ };
265
+ // The limit of password checks comes after authMiddleware (it keys on the user) and before the parser and bcrypt.
266
+ router.delete('/me', authMiddleware, limits.passwordCheck, json, withBody(deleteAccountBodySchema), async (req, res) => {
267
+ const userId = userIdOf(req);
268
+ await service.deleteAccount(userId, body(res).password);
269
+ await clearPasswordChecks(req, userId);
270
+ clearRefreshCookie(res);
271
+ noContent(res);
272
+ });
273
+ router.put('/password', authMiddleware, limits.passwordCheck, json, withBody(changePasswordBodySchema), async (req, res) => {
274
+ const { currentPassword, newPassword } = body(res);
275
+ const userId = userIdOf(req);
276
+ await service.changePassword(userId, currentPassword, newPassword);
277
+ await clearPasswordChecks(req, userId);
278
+ clearRefreshCookie(res);
279
+ noContent(res);
280
+ });
281
+ // --- E-mail verification and password reset -------------------------------------------------------------------
282
+ // 202 without a body whether or not a link was sent (`rest:MET-1`, exception 202): an e-mail that is already verified
283
+ // is not told apart from one that is not (`rest:AUT-8`); the owner of the mailbox learns the result from the e-mail.
284
+ router.post('/email-verification', authMiddleware, limits.verificationEmail, json, withBody(resendVerificationBodySchema.default({})), async (req, res) => {
285
+ const client = body(res).client ?? 'web';
286
+ await service.resendVerification(userIdOf(req), client, contextOf(req, config.logger));
287
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
288
+ });
289
+ // The token is checked first (an unknown one is refused without counting anything), then the limit of password
290
+ // checks of its account, shared with PUT /password and DELETE /me, comes before bcrypt (audit S4, DEC-281).
291
+ const verificationOwners = new WeakMap();
292
+ router.post('/email-verification/confirm', json, withBody(confirmEmailBodySchema), async (req, res, next) => {
293
+ verificationOwners.set(req, await service.emailVerificationOwner(body(res).token));
294
+ next();
295
+ }, limits.passwordCheckOf((req) => verificationOwners.get(req)), async (req, res) => {
296
+ const { token, password } = body(res);
297
+ await service.confirmEmail(token, password);
298
+ const userId = verificationOwners.get(req);
299
+ if (userId !== undefined) {
300
+ await clearPasswordChecks(req, userId);
301
+ }
302
+ noContent(res);
303
+ });
304
+ router.post('/password-reset', limits.passwordReset, json, withBody(requestPasswordResetBodySchema), (req, res) => {
305
+ const { email, client } = body(res);
306
+ // Not awaited: the answer must not take longer for a known account than for an unknown one (rest:AUT-8).
307
+ const ctx = contextOf(req, config.logger);
308
+ detach(service.requestPasswordReset(email, client ?? 'web', ctx), ctx);
309
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
310
+ });
311
+ router.post('/password-reset/confirm', json, withBody(confirmPasswordResetBodySchema), async (req, res) => {
312
+ const { token, password } = body(res);
313
+ const user = await service.confirmPasswordReset(token, password);
314
+ // The owner proved access to the mailbox: the lock of the e-mail goes (audit N4). The password is set by then, so
315
+ // a failure of Redis is only logged; the lock expires with its time.
316
+ try {
317
+ await limits.clearEmailLock(user.email);
318
+ }
319
+ catch (err) {
320
+ logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The lock of the e-mail could not be removed in Redis after a password reset.');
321
+ }
322
+ noContent(res);
323
+ });
324
+ // --- Errors of the library become API errors; the application's error handler answers them (rest:ERR-1) ------
325
+ router.use((err, _req, _res, next) => {
326
+ next(err instanceof AuthError ? toHttpError(err) : err);
327
+ });
328
+ return router;
329
+ };
@@ -0,0 +1,9 @@
1
+ import type { AuthLogger } from './config.js';
2
+ /**
3
+ * Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
4
+ * method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
5
+ * become an unhandled rejection that ends the process of Node.js after the answer.
6
+ */
7
+ export declare const logError: (log: AuthLogger | undefined, info: object, message: string) => void;
8
+ /** Logs a warning with the same protection against a failing logger as `logError`. */
9
+ export declare const logWarning: (log: AuthLogger | undefined, info: object, message: string) => void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
3
+ * method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
4
+ * become an unhandled rejection that ends the process of Node.js after the answer.
5
+ */
6
+ export const logError = (log, info, message) => {
7
+ logSafely(log, 'error', info, message);
8
+ };
9
+ /** Logs a warning with the same protection against a failing logger as `logError`. */
10
+ export const logWarning = (log, info, message) => {
11
+ logSafely(log, 'warn', info, message);
12
+ };
13
+ const logSafely = (log, level, info, message) => {
14
+ try {
15
+ const result = log?.[level](info, message);
16
+ // A logger that is declared to return `void` may return a promise anyway: the cast only reads `then`, and the check is the `typeof`.
17
+ if (typeof result?.then === 'function') {
18
+ result.then(undefined, () => undefined);
19
+ }
20
+ }
21
+ catch {
22
+ // The logger itself fails: nothing else could report it, the process goes on.
23
+ }
24
+ };