@mielk/auth 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +670 -2
  4. package/dist/client/api-address.d.ts +17 -0
  5. package/dist/client/api-address.js +434 -0
  6. package/dist/client/auth-client.d.ts +226 -0
  7. package/dist/client/auth-client.js +676 -0
  8. package/dist/client/errors.d.ts +66 -0
  9. package/dist/client/errors.js +33 -0
  10. package/dist/client/guards.d.ts +26 -0
  11. package/dist/client/guards.js +27 -0
  12. package/dist/client/index.d.ts +4 -0
  13. package/dist/client/index.js +2 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.js +4 -0
  16. package/dist/locales/en-GB.json +50 -0
  17. package/dist/locales/pl.json +50 -0
  18. package/dist/messages.d.ts +65 -0
  19. package/dist/messages.js +57 -0
  20. package/dist/pg/index.d.ts +1 -0
  21. package/dist/pg/index.js +1 -0
  22. package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
  23. package/dist/pg/pg-auth-repository.d.ts +91 -0
  24. package/dist/pg/pg-auth-repository.js +252 -0
  25. package/dist/react/auth-provider.d.ts +70 -0
  26. package/dist/react/auth-provider.js +72 -0
  27. package/dist/react/index.d.ts +2 -0
  28. package/dist/react/index.js +1 -0
  29. package/dist/schemas/index.d.ts +234 -0
  30. package/dist/schemas/index.js +145 -0
  31. package/dist/server/access-token.d.ts +48 -0
  32. package/dist/server/access-token.js +54 -0
  33. package/dist/server/auth-middleware.d.ts +40 -0
  34. package/dist/server/auth-middleware.js +61 -0
  35. package/dist/server/config.d.ts +231 -0
  36. package/dist/server/config.js +250 -0
  37. package/dist/server/cookies.d.ts +13 -0
  38. package/dist/server/cookies.js +35 -0
  39. package/dist/server/core.d.ts +20 -0
  40. package/dist/server/core.js +32 -0
  41. package/dist/server/create-auth.d.ts +38 -0
  42. package/dist/server/create-auth.js +33 -0
  43. package/dist/server/errors.d.ts +177 -0
  44. package/dist/server/errors.js +201 -0
  45. package/dist/server/http-errors.d.ts +9 -0
  46. package/dist/server/http-errors.js +34 -0
  47. package/dist/server/limits.d.ts +95 -0
  48. package/dist/server/limits.js +98 -0
  49. package/dist/server/one-time-token.d.ts +49 -0
  50. package/dist/server/one-time-token.js +60 -0
  51. package/dist/server/opaque-token.d.ts +6 -0
  52. package/dist/server/opaque-token.js +7 -0
  53. package/dist/server/password.d.ts +43 -0
  54. package/dist/server/password.js +78 -0
  55. package/dist/server/ports.d.ts +343 -0
  56. package/dist/server/ports.js +11 -0
  57. package/dist/server/proxy-check.d.ts +16 -0
  58. package/dist/server/proxy-check.js +78 -0
  59. package/dist/server/refresh-token.d.ts +60 -0
  60. package/dist/server/refresh-token.js +122 -0
  61. package/dist/server/router.d.ts +29 -0
  62. package/dist/server/router.js +331 -0
  63. package/dist/server/service.d.ts +158 -0
  64. package/dist/server/service.js +270 -0
  65. package/package.json +136 -5
@@ -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,331 @@
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
+ 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
+ contextOf(req, config.logger).log?.error(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), async (req, res) => {
142
+ const { email, password, client } = body(res);
143
+ const ctx = contextOf(req, config.logger);
144
+ const { delivery } = await service.register(email, password, client ?? 'web', ctx);
145
+ // Not awaited, as for the password reset: the answer must not take the time of the e-mail, which differs for a
146
+ // new and a registered address (r1:U1). Its failures are logged; a rejection is caught by `detach` (r2:U1).
147
+ detach(delivery, ctx);
148
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
149
+ });
150
+ /**
151
+ * The cookie of the browser holds one refresh token, so a login replaces the token the request brought (of another
152
+ * account or of the same one); that token is revoked, so it does not stay valid until it expires (TASK-191.10,
153
+ * DEC-315 variant A). Only after the login succeeded: a failed login keeps the session of the cookie. A failure of
154
+ * the revocation does not undo the login: it is logged without the token, and the token expires by itself, as after
155
+ * a logout that does not reach the server.
156
+ */
157
+ const revokeReplacedCookie = async (req) => {
158
+ const replaced = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
159
+ if (replaced === undefined || replaced === '')
160
+ return;
161
+ try {
162
+ await service.logout(replaced, 'web');
163
+ }
164
+ catch (err) {
165
+ logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The refresh token replaced by a login could not be revoked; it expires by itself.');
166
+ }
167
+ };
168
+ router.post('/login', ...loginGuards, async (req, res) => {
169
+ const { email, password } = body(res);
170
+ const result = await service.login(email, password, 'web', resetLoginCounters(req, email));
171
+ await revokeReplacedCookie(req);
172
+ setRefreshCookie(res, result.refreshToken.token, result.refreshToken.expiresAt);
173
+ success(res, HttpResponseStatus.OK, {
174
+ accessToken: result.accessToken.token,
175
+ user: toUserResponse(result.user),
176
+ });
177
+ });
178
+ /**
179
+ * A web refresh without the cookie is answered 401 before the limit, so it is not counted (audit S10, W2 b): the
180
+ * cookie is `httpOnly`, so the client restores the session on every start of the page, also for a visitor without
181
+ * a session, and those requests must not spend the budget of the address shared by the signed-in users behind it.
182
+ * A request with any cookie value is counted, so guessing tokens stays limited.
183
+ */
184
+ const requireRefreshCookie = (req, res, next) => {
185
+ const token = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
186
+ if (token === undefined || token === '') {
187
+ clearRefreshCookie(res);
188
+ next(toHttpError(new InvalidRefreshTokenError()));
189
+ return;
190
+ }
191
+ next();
192
+ };
193
+ router.post('/refresh', requireRefreshCookie, limits.refresh, async (req, res) => {
194
+ try {
195
+ const result = await service.refresh(refreshTokenOf(req), 'web');
196
+ setRefreshCookie(res, result.refreshToken.token, result.refreshToken.expiresAt);
197
+ success(res, HttpResponseStatus.OK, { accessToken: result.accessToken.token });
198
+ }
199
+ catch (err) {
200
+ logReuse(req, err);
201
+ // Only a rejected token is useless; then the cookie goes, so the client does not keep sending it. A transient
202
+ // failure (database, Redis, 5xx) keeps the cookie: the token is still valid and the client retries (DEC-271,
203
+ // audit S7).
204
+ if (isRejectedRefreshToken(err)) {
205
+ clearRefreshCookie(res);
206
+ }
207
+ throw err;
208
+ }
209
+ });
210
+ router.post('/logout', async (req, res) => {
211
+ const token = readCookie(req.headers.cookie, REFRESH_COOKIE_NAME);
212
+ if (token !== undefined && token !== '') {
213
+ await service.logout(token, 'web');
214
+ }
215
+ clearRefreshCookie(res);
216
+ noContent(res);
217
+ });
218
+ // --- Mobile client: the refresh token is in the body; a request from a browser is refused ---------------------
219
+ const mobile = Router();
220
+ mobile.post('/login', ...loginGuards, async (req, res) => {
221
+ const { email, password } = body(res);
222
+ const result = await service.login(email, password, 'mobile', resetLoginCounters(req, email));
223
+ success(res, HttpResponseStatus.OK, {
224
+ accessToken: result.accessToken.token,
225
+ refreshToken: result.refreshToken.token,
226
+ user: toUserResponse(result.user),
227
+ });
228
+ });
229
+ mobile.post('/refresh', limits.refresh, json, withBody(mobileRefreshBodySchema), async (req, res) => {
230
+ const { refreshToken } = body(res);
231
+ const result = await service.refresh(refreshToken, 'mobile').catch((err) => {
232
+ logReuse(req, err);
233
+ throw err;
234
+ });
235
+ success(res, HttpResponseStatus.OK, {
236
+ accessToken: result.accessToken.token,
237
+ refreshToken: result.refreshToken.token,
238
+ });
239
+ });
240
+ mobile.post('/logout', json, withBody(mobileRefreshBodySchema), async (_req, res) => {
241
+ await service.logout(body(res).refreshToken, 'mobile');
242
+ noContent(res);
243
+ });
244
+ router.use('/mobile', mobile);
245
+ // --- Session and account of the signed-in user ----------------------------------------------------------------
246
+ router.post('/sessions/revoke-all', authMiddleware, async (req, res) => {
247
+ await service.revokeAllSessions(userIdOf(req));
248
+ noContent(res);
249
+ });
250
+ router.get('/me', authMiddleware, async (req, res) => {
251
+ success(res, HttpResponseStatus.OK, {
252
+ user: toUserResponse(await service.getUser(userIdOf(req))),
253
+ });
254
+ });
255
+ /**
256
+ * After the right password the counter of password checks starts again. The operation has succeeded by then, so a
257
+ * failure of Redis is only logged: the counter expires with its window.
258
+ */
259
+ const clearPasswordChecks = async (req, userId) => {
260
+ try {
261
+ await limits.clearPasswordChecks(userId);
262
+ }
263
+ catch (err) {
264
+ contextOf(req, config.logger).log?.warn(safeErrorInfo(err), 'The counter of password checks could not be cleared in Redis.');
265
+ }
266
+ };
267
+ // The limit of password checks comes after authMiddleware (it keys on the user) and before the parser and bcrypt.
268
+ router.delete('/me', authMiddleware, limits.passwordCheck, json, withBody(deleteAccountBodySchema), async (req, res) => {
269
+ const userId = userIdOf(req);
270
+ await service.deleteAccount(userId, body(res).password);
271
+ await clearPasswordChecks(req, userId);
272
+ clearRefreshCookie(res);
273
+ noContent(res);
274
+ });
275
+ router.put('/password', authMiddleware, limits.passwordCheck, json, withBody(changePasswordBodySchema), async (req, res) => {
276
+ const { currentPassword, newPassword } = body(res);
277
+ const userId = userIdOf(req);
278
+ await service.changePassword(userId, currentPassword, newPassword);
279
+ await clearPasswordChecks(req, userId);
280
+ clearRefreshCookie(res);
281
+ noContent(res);
282
+ });
283
+ // --- E-mail verification and password reset -------------------------------------------------------------------
284
+ // 202 without a body whether or not a link was sent (`rest:MET-1`, exception 202): an e-mail that is already verified
285
+ // is not told apart from one that is not (`rest:AUT-8`); the owner of the mailbox learns the result from the e-mail.
286
+ router.post('/email-verification', authMiddleware, limits.verificationEmail, json, withBody(resendVerificationBodySchema.default({})), async (req, res) => {
287
+ const client = body(res).client ?? 'web';
288
+ await service.resendVerification(userIdOf(req), client, contextOf(req, config.logger));
289
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
290
+ });
291
+ // The token is checked first (an unknown one is refused without counting anything), then the limit of password
292
+ // checks of its account, shared with PUT /password and DELETE /me, comes before bcrypt (audit S4, DEC-281).
293
+ const verificationOwners = new WeakMap();
294
+ router.post('/email-verification/confirm', json, withBody(confirmEmailBodySchema), async (req, res, next) => {
295
+ verificationOwners.set(req, await service.emailVerificationOwner(body(res).token));
296
+ next();
297
+ }, limits.passwordCheckOf((req) => verificationOwners.get(req)), async (req, res) => {
298
+ const { token, password } = body(res);
299
+ await service.confirmEmail(token, password);
300
+ const userId = verificationOwners.get(req);
301
+ if (userId !== undefined) {
302
+ await clearPasswordChecks(req, userId);
303
+ }
304
+ noContent(res);
305
+ });
306
+ router.post('/password-reset', limits.passwordReset, json, withBody(requestPasswordResetBodySchema), (req, res) => {
307
+ const { email, client } = body(res);
308
+ // Not awaited: the answer must not take longer for a known account than for an unknown one (rest:AUT-8).
309
+ const ctx = contextOf(req, config.logger);
310
+ detach(service.requestPasswordReset(email, client ?? 'web', ctx), ctx);
311
+ res.status(HttpResponseStatus.ACCEPTED.code).end();
312
+ });
313
+ router.post('/password-reset/confirm', json, withBody(confirmPasswordResetBodySchema), async (req, res) => {
314
+ const { token, password } = body(res);
315
+ const user = await service.confirmPasswordReset(token, password);
316
+ // The owner proved access to the mailbox: the lock of the e-mail goes (audit N4). The password is set by then, so
317
+ // a failure of Redis is only logged; the lock expires with its time.
318
+ try {
319
+ await limits.clearEmailLock(user.email);
320
+ }
321
+ catch (err) {
322
+ contextOf(req, config.logger).log?.warn(safeErrorInfo(err), 'The lock of the e-mail could not be removed in Redis after a password reset.');
323
+ }
324
+ noContent(res);
325
+ });
326
+ // --- Errors of the library become API errors; the application's error handler answers them (rest:ERR-1) ------
327
+ router.use((err, _req, _res, next) => {
328
+ next(err instanceof AuthError ? toHttpError(err) : err);
329
+ });
330
+ return router;
331
+ };
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Operations of the authentication endpoints without Express: they take plain values, return plain values and throw the
3
+ * errors of the library (`AuthError`), which the router maps to responses. The router and the tests build on it.
4
+ */
5
+ import type { IssuedAccessToken } from './access-token.js';
6
+ import type { AuthLogger } from './config.js';
7
+ import type { AuthCore } from './core.js';
8
+ import type { AuthUser, ClientKind, UserId } from './ports.js';
9
+ import type { IssuedRefreshToken } from './refresh-token.js';
10
+ /** Context of one request that the operations need: the language of the e-mails and where failures are logged. */
11
+ export type RequestContext = {
12
+ /** Language of the e-mails, e.g. `pl` or `en-GB`. */
13
+ locale: string;
14
+ log: AuthLogger | undefined;
15
+ };
16
+ /** Category of a failure of the mailer: whether it rejected with an `Error` or with another value. */
17
+ export type LinkDeliveryReason = 'mailer_error' | 'mailer_non_error';
18
+ /**
19
+ * Failure of the mailer. It carries no cause, message, name or address of the original error: the errors of mail ports
20
+ * tend to quote the recipient or the link with the token, and their names are chosen by foreign code, so only a fixed
21
+ * category is kept; this error is logged and reaches the final error handler.
22
+ */
23
+ export declare class LinkDeliveryError extends Error {
24
+ readonly name = "LinkDeliveryError";
25
+ /** Fixed category of the original failure, safe to log. */
26
+ readonly reason: LinkDeliveryReason;
27
+ constructor(original: unknown);
28
+ }
29
+ /** Fixed categories of an error for logs: they never come from the error object, whose name or fields may carry data. */
30
+ export type ErrorCategory = 'link_delivery' | 'library_error' | 'unexpected_error';
31
+ /**
32
+ * What of an error may be logged: a fixed category only. The message, name and fields of an error from a dependency
33
+ * (repository, mailer, Redis) may quote an address, a key or a token, and the name is chosen by foreign code too.
34
+ */
35
+ export declare const safeErrorInfo: (err: unknown) => {
36
+ errorCategory: ErrorCategory;
37
+ };
38
+ /**
39
+ * Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
40
+ * method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
41
+ * become an unhandled rejection that ends the process of Node.js after the answer.
42
+ */
43
+ export declare const logError: (log: AuthLogger | undefined, info: object, message: string) => void;
44
+ /** Logs a warning with the same protection against a failing logger as `logError`. */
45
+ export declare const logWarning: (log: AuthLogger | undefined, info: object, message: string) => void;
46
+ /** Result of a login. */
47
+ export type LoginResult = {
48
+ user: AuthUser;
49
+ accessToken: IssuedAccessToken;
50
+ refreshToken: IssuedRefreshToken;
51
+ };
52
+ /** Result of a refresh. */
53
+ export type RefreshResult = {
54
+ accessToken: IssuedAccessToken;
55
+ refreshToken: IssuedRefreshToken;
56
+ };
57
+ /**
58
+ * Result of a registration: the sending of its e-mail, already started (r1:U1). Its failures are logged, and a logger that throws or
59
+ * rejects is ignored (r3:U1), so it does not reject because of the logger; the router still catches any other
60
+ * rejection (r2:U1).
61
+ */
62
+ export type RegisterResult = {
63
+ delivery: Promise<void>;
64
+ };
65
+ /** Operations of the authentication endpoints (plan TASK-191, 2.2). */
66
+ export type AuthService = {
67
+ /**
68
+ * Creates the account and sends the verification link. For an e-mail that is registered already it creates nothing,
69
+ * changes nothing and sends the account the `account_exists` message with a password reset link instead, so the
70
+ * caller cannot tell the two apart (audit S3). It resolves after the account step (the password hashed and the
71
+ * account created or found taken), the same for both; the e-mail, with the reading of the existing account, the
72
+ * limit per account and the mailer, runs on in `delivery`, so the time of the answer does not depend on it (r1:U1).
73
+ * A failure of `delivery` is logged and does not fail the registration (the link can be requested again); a
74
+ * logger that throws or rejects is ignored (r3:U1). A caller that does not await it should still catch any other
75
+ * rejection (r2:U1).
76
+ */
77
+ register(email: string, password: string, client: ClientKind, ctx: RequestContext): Promise<RegisterResult>;
78
+ /**
79
+ * Logs in. The password is checked before the transaction (audit S8); `afterPasswordCheck` runs after the password
80
+ * matched and before the transaction starts (the router clears the login counters there): when it rejects, no
81
+ * session is issued. Neither bcrypt nor the call of `afterPasswordCheck` holds a connection or the lock of the user.
82
+ *
83
+ * @throws `InvalidCredentialsError` for an unknown e-mail and for a wrong password alike (`rest:AUT-8`), also when
84
+ * the password changed between the check and the lock.
85
+ */
86
+ login(email: string, password: string, clientKind: ClientKind, afterPasswordCheck?: () => Promise<void>): Promise<LoginResult>;
87
+ /** @throws the refresh token errors of `RefreshTokenService.rotate`. */
88
+ refresh(refreshToken: string, clientKind: ClientKind): Promise<RefreshResult>;
89
+ /** Revokes the refresh token; idempotent. */
90
+ logout(refreshToken: string, clientKind: ClientKind): Promise<void>;
91
+ /** Revokes all refresh tokens of the user. */
92
+ revokeAllSessions(userId: UserId): Promise<void>;
93
+ /** @throws `InvalidAccessTokenError` when the account of a valid token no longer exists. */
94
+ getUser(userId: UserId): Promise<AuthUser>;
95
+ /**
96
+ * Sends a new verification link; does nothing for a verified e-mail.
97
+ *
98
+ * @throws `LinkDeliveryError` when the mailer fails.
99
+ */
100
+ resendVerification(userId: UserId, client: ClientKind, ctx: RequestContext): Promise<void>;
101
+ /**
102
+ * Returns the account of a verification token that could be used now, without using it: the router keys the limit of
103
+ * password checks on it before `confirmEmail` (audit S4, DEC-281).
104
+ *
105
+ * @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
106
+ */
107
+ emailVerificationOwner(token: string): Promise<UserId>;
108
+ /**
109
+ * Marks the e-mail as verified when the password of the account matches, and revokes all refresh tokens of the
110
+ * account, in one transaction with the use of the token (audit S4, DEC-281): who registered someone else's address
111
+ * has no link, the owner of the mailbox who did not register has no password, so only who has both confirms it. The
112
+ * sessions issued before stay revoked as well; the owner signs in again. The token and the password are checked
113
+ * before the transaction, so no connection and no lock of the user wait for bcrypt (audit S8); the transaction
114
+ * confirms only while the stored hash is still the checked one. A refused confirmation leaves the token usable.
115
+ *
116
+ * @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
117
+ * @throws `CurrentPasswordInvalidError` for a wrong password, also when the password changed after it was checked.
118
+ */
119
+ confirmEmail(token: string, password: string): Promise<void>;
120
+ /**
121
+ * Sends the reset link when the account exists. Gives no sign of whether the account exists (`rest:AUT-8`):
122
+ * failures are logged, and a logger that throws or rejects is ignored (r3:U1). A caller that does not await it
123
+ * should still catch any other rejection (r2:U1).
124
+ */
125
+ requestPasswordReset(email: string, client: ClientKind, ctx: RequestContext): Promise<void>;
126
+ /**
127
+ * Sets the new password and revokes all refresh tokens of the user (`rest:AUT-10`), in one transaction with the use
128
+ * of the token.
129
+ *
130
+ * @returns the account, as read under its lock (the router clears the lock of its e-mail, audit N4).
131
+ * @throws `InvalidAuthTokenError` for a token that is unknown, used, replaced or expired.
132
+ */
133
+ confirmPasswordReset(token: string, password: string): Promise<AuthUser>;
134
+ /**
135
+ * Changes the password and revokes all refresh tokens of the user, also the current session (`rest:AUT-10`).
136
+ *
137
+ * @throws `CurrentPasswordInvalidError`, `InvalidAccessTokenError` when the account no longer exists.
138
+ */
139
+ changePassword(userId: UserId, currentPassword: string, newPassword: string): Promise<void>;
140
+ /**
141
+ * Deletes the account after the password check (before the transaction, audit S8), running `onUserDeleted` in the
142
+ * transaction that deletes it.
143
+ *
144
+ * @throws `CurrentPasswordInvalidError`, `InvalidAccessTokenError` when the account no longer exists.
145
+ */
146
+ deleteAccount(userId: UserId, password: string): Promise<void>;
147
+ };
148
+ /** Options of `createAuthService`. */
149
+ export type AuthServiceOptions = {
150
+ /**
151
+ * Tells whether a password reset link (or a notice of a registration) may be sent to the account now, and counts it
152
+ * (audit S5); default: always. A refusal or a failure sends nothing and issues no token, and the caller is answered
153
+ * the same.
154
+ */
155
+ allowPasswordResetEmail?: (userId: UserId) => Promise<boolean>;
156
+ };
157
+ /** Creates the service on the core of the library. */
158
+ export declare const createAuthService: (core: AuthCore, options?: AuthServiceOptions) => AuthService;