@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,201 @@
1
+ import { Msg } from '../messages.js';
2
+ /**
3
+ * Base class of the errors thrown by the library. The errors do not depend on HTTP: the Express layer maps `code` to a
4
+ * status code and sends `messageKey` to the client.
5
+ *
6
+ * @since 2.0.0
7
+ */
8
+ export class AuthError extends Error {
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = new.target.name;
12
+ }
13
+ }
14
+ /**
15
+ * The configuration passed to the library is invalid. Thrown at startup; `issues` lists the invalid fields with the
16
+ * reason, never their values, so the message does not reveal a secret.
17
+ *
18
+ * @since 2.0.0
19
+ */
20
+ export class AuthConfigError extends AuthError {
21
+ code = 'CONFIG_INVALID';
22
+ messageKey = Msg.config.invalid;
23
+ /** Invalid fields, each as `<path>: <reason>`. */
24
+ issues;
25
+ /** @param issues - invalid fields, each as `<path>: <reason>`, without the field values. */
26
+ constructor(issues) {
27
+ super(`Invalid @mielk/auth configuration: ${issues.join('; ')}`);
28
+ this.issues = issues;
29
+ }
30
+ }
31
+ /**
32
+ * Unknown e-mail or wrong password; both cases give the same error, so it does not reveal the account (`rest:AUT-8`).
33
+ *
34
+ * @since 2.0.0
35
+ */
36
+ export class InvalidCredentialsError extends AuthError {
37
+ code = 'INVALID_CREDENTIALS';
38
+ messageKey = Msg.login.invalidCredentials;
39
+ constructor() {
40
+ super('Invalid e-mail or password');
41
+ }
42
+ }
43
+ /**
44
+ * Too many password checks and hashings run or wait already (`passwordHashing` of the configuration); the request is
45
+ * refused at once instead of queueing more bcrypt work on the main thread (audit W1). Answered 503.
46
+ *
47
+ * @since 2.0.0
48
+ */
49
+ export class PasswordHashingBusyError extends AuthError {
50
+ code = 'PASSWORD_HASHING_BUSY';
51
+ messageKey = Msg.password.busy;
52
+ constructor() {
53
+ super('Too many password hashings at once');
54
+ }
55
+ }
56
+ /**
57
+ * The lock of the account was not granted in time (`lockTimeoutMs` of the PostgreSQL adapter): other operations of the
58
+ * same account hold it. Waiting on would hold a connection of the shared pool, so the request is refused (audit S8).
59
+ * Answered 503.
60
+ *
61
+ * @since 2.0.0
62
+ */
63
+ export class AccountBusyError extends AuthError {
64
+ code = 'ACCOUNT_BUSY';
65
+ messageKey = Msg.account.busy;
66
+ constructor() {
67
+ super('The lock of the account was not granted in time');
68
+ }
69
+ }
70
+ /**
71
+ * The password is longer than bcrypt accepts (`PASSWORD_MAX_BYTES`); bcrypt would silently truncate it.
72
+ *
73
+ * @since 2.0.0
74
+ */
75
+ export class PasswordTooLongError extends AuthError {
76
+ code = 'PASSWORD_TOO_LONG';
77
+ messageKey = Msg.password.tooLong;
78
+ constructor() {
79
+ super('Password is too long');
80
+ }
81
+ }
82
+ /**
83
+ * The current password given for a password change, an account deletion or an e-mail confirmation is wrong.
84
+ *
85
+ * @since 2.0.0
86
+ */
87
+ export class CurrentPasswordInvalidError extends AuthError {
88
+ code = 'CURRENT_PASSWORD_INVALID';
89
+ messageKey = Msg.password.currentInvalid;
90
+ constructor() {
91
+ super('Invalid current password');
92
+ }
93
+ }
94
+ /**
95
+ * An account with the e-mail already exists. A repository adapter throws it when the database reports a unique
96
+ * violation on the e-mail (`rest:SQL-5`).
97
+ *
98
+ * @since 2.0.0
99
+ */
100
+ export class EmailTakenError extends AuthError {
101
+ code = 'EMAIL_TAKEN';
102
+ messageKey = Msg.register.emailTaken;
103
+ /** @param options - `cause`: the original database error. */
104
+ constructor(options) {
105
+ super('E-mail is already registered', options);
106
+ }
107
+ }
108
+ /**
109
+ * The e-mail of the signed-in account is not verified; thrown by `requireVerifiedEmail` (audit S4). Answered 403.
110
+ *
111
+ * @since 2.0.0
112
+ */
113
+ export class EmailNotVerifiedError extends AuthError {
114
+ code = 'EMAIL_NOT_VERIFIED';
115
+ messageKey = Msg.emailVerification.required;
116
+ constructor() {
117
+ super('The e-mail of the account is not verified');
118
+ }
119
+ }
120
+ /**
121
+ * The access token is missing, malformed, signed with another key or algorithm, or has an invalid subject.
122
+ *
123
+ * @since 2.0.0
124
+ */
125
+ export class InvalidAccessTokenError extends AuthError {
126
+ code = 'ACCESS_TOKEN_INVALID';
127
+ messageKey = Msg.accessToken.invalid;
128
+ /** @param options - `cause`: the original verification error, if any. */
129
+ constructor(options) {
130
+ super('Invalid access token', options);
131
+ }
132
+ }
133
+ /**
134
+ * The access token is valid but expired; the client refreshes the session.
135
+ *
136
+ * @since 2.0.0
137
+ */
138
+ export class AccessTokenExpiredError extends AuthError {
139
+ code = 'ACCESS_TOKEN_EXPIRED';
140
+ messageKey = Msg.accessToken.expired;
141
+ /** @param options - `cause`: the original verification error. */
142
+ constructor(options) {
143
+ super('Access token expired', options);
144
+ }
145
+ }
146
+ /**
147
+ * The refresh token is unknown or belongs to another kind of client (web or mobile).
148
+ *
149
+ * @since 2.0.0
150
+ */
151
+ export class InvalidRefreshTokenError extends AuthError {
152
+ code = 'REFRESH_TOKEN_INVALID';
153
+ messageKey = Msg.refreshToken.invalid;
154
+ constructor() {
155
+ super('Invalid refresh token');
156
+ }
157
+ }
158
+ /**
159
+ * The refresh token has expired.
160
+ *
161
+ * @since 2.0.0
162
+ */
163
+ export class RefreshTokenExpiredError extends AuthError {
164
+ code = 'REFRESH_TOKEN_EXPIRED';
165
+ messageKey = Msg.refreshToken.expired;
166
+ constructor() {
167
+ super('Refresh token expired');
168
+ }
169
+ }
170
+ /**
171
+ * The refresh token was already revoked: a possible theft. All refresh tokens of the user have been revoked before the
172
+ * error was thrown (`rest:AUT-11`).
173
+ *
174
+ * @since 2.0.0
175
+ */
176
+ export class RefreshTokenReusedError extends AuthError {
177
+ code = 'REFRESH_TOKEN_REUSED';
178
+ messageKey = Msg.refreshToken.reused;
179
+ constructor() {
180
+ super('Refresh token reused; all sessions of the user were revoked');
181
+ }
182
+ }
183
+ /**
184
+ * The one-time token (e-mail verification or password reset) is unknown, already used, replaced by a newer one or
185
+ * expired. One error for all cases: the holder of a token learns nothing about other tokens.
186
+ *
187
+ * @since 2.0.0
188
+ */
189
+ export class InvalidAuthTokenError extends AuthError {
190
+ code = 'AUTH_TOKEN_INVALID';
191
+ messageKey;
192
+ /** Purpose of the rejected token. */
193
+ purpose;
194
+ /** @param purpose - purpose of the rejected token; selects the message key. */
195
+ constructor(purpose) {
196
+ super(`Invalid ${purpose} token`);
197
+ this.purpose = purpose;
198
+ this.messageKey =
199
+ purpose === 'email_verification' ? Msg.emailVerification.invalidToken : Msg.passwordReset.invalidToken;
200
+ }
201
+ }
@@ -0,0 +1,9 @@
1
+ import type { AuthError } from './errors.js';
2
+ /**
3
+ * Returns the API error that answers the error of the library: the status by the `code`, the message key from
4
+ * `messageKey`. The final error handler of `@mielk/http` turns it into the response (`rest:ERR-1`).
5
+ *
6
+ * `AuthConfigError` has no status: it is thrown at startup and never reaches a request, so it is returned as it is
7
+ * (the error handler answers 500 for it).
8
+ */
9
+ export declare const toHttpError: (error: AuthError) => Error;
@@ -0,0 +1,34 @@
1
+ /** Mapping of the errors of the library to the API errors of `@mielk/http` (`rest:ERR-2`). */
2
+ import { BadRequestError, ConflictError, ForbiddenError, HttpError, HttpResponseStatus, UnauthorizedError, } from '@mielk/http/http';
3
+ /**
4
+ * Returns the API error that answers the error of the library: the status by the `code`, the message key from
5
+ * `messageKey`. The final error handler of `@mielk/http` turns it into the response (`rest:ERR-1`).
6
+ *
7
+ * `AuthConfigError` has no status: it is thrown at startup and never reaches a request, so it is returned as it is
8
+ * (the error handler answers 500 for it).
9
+ */
10
+ export const toHttpError = (error) => {
11
+ const options = { cause: error };
12
+ switch (error.code) {
13
+ case 'INVALID_CREDENTIALS':
14
+ case 'ACCESS_TOKEN_INVALID':
15
+ case 'ACCESS_TOKEN_EXPIRED':
16
+ case 'REFRESH_TOKEN_INVALID':
17
+ case 'REFRESH_TOKEN_EXPIRED':
18
+ case 'REFRESH_TOKEN_REUSED':
19
+ return new UnauthorizedError(error.messageKey, undefined, options);
20
+ case 'EMAIL_TAKEN':
21
+ return new ConflictError(error.messageKey, undefined, options);
22
+ case 'EMAIL_NOT_VERIFIED':
23
+ return new ForbiddenError(error.messageKey, undefined, options);
24
+ case 'PASSWORD_TOO_LONG':
25
+ case 'CURRENT_PASSWORD_INVALID':
26
+ case 'AUTH_TOKEN_INVALID':
27
+ return new BadRequestError(error.messageKey, undefined, options);
28
+ case 'PASSWORD_HASHING_BUSY':
29
+ case 'ACCOUNT_BUSY':
30
+ return new HttpError(HttpResponseStatus.SERVICE_UNAVAILABLE, error.messageKey, undefined, options);
31
+ case 'CONFIG_INVALID':
32
+ return error;
33
+ }
34
+ };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Limits and locks of the authentication endpoints (`rest:LIM-2`–`LIM-5`, `RED-1`, `RED-5`), built on the generic
3
+ * `createRateLimiter` and `createLockChecker` of `@mielk/http`. Counters and locks live in Redis under
4
+ * `<appPrefix>:<area>:<parts>`; an e-mail address is in a key only as the SHA-256 hash of its trimmed lower-case form.
5
+ *
6
+ * Every request is counted when it reaches the limiter, so a failed login counts as it happens; a successful login
7
+ * resets the counters of the e-mail and the lock (`clearLoginCounters`), and so does a confirmed password reset for the
8
+ * e-mail of its account (`clearEmailLock`, audit N4).
9
+ */
10
+ import type { Request } from 'express';
11
+ import type { Middleware } from '@mielk/http/middlewares';
12
+ import type { ResolvedAuthLimits } from './config.js';
13
+ /** Areas of the Redis keys (after the application prefix). */
14
+ export declare const LIMIT_AREAS: {
15
+ readonly register: "auth.register";
16
+ readonly passwordReset: "auth.passwordReset";
17
+ readonly refresh: "auth.refresh";
18
+ readonly passwordCheck: "auth.passwordCheck";
19
+ readonly verificationEmail: "auth.verificationEmail";
20
+ readonly passwordResetEmail: "auth.passwordResetEmail";
21
+ readonly loginIp: "auth.login.ip";
22
+ readonly loginIpEmail: "auth.login.ipEmail";
23
+ readonly loginEmail: "auth.login.email";
24
+ readonly lockEmail: "auth.lock:email";
25
+ };
26
+ /** The middleware of the limits and the function that clears the login counters after a successful login. */
27
+ export type AuthLimits = {
28
+ /** Limit of registrations per IP address. */
29
+ register: Middleware;
30
+ /** Limit of password reset requests per IP address. */
31
+ passwordReset: Middleware;
32
+ /** Limit of refreshes per IP address. */
33
+ refresh: Middleware;
34
+ /**
35
+ * Limit of password checks of the signed-in user (`PUT /password`, `DELETE /me`), keyed on `req.user.userId`, so it
36
+ * runs after `authMiddleware`. Not on the address: a stolen access token must not try passwords from many addresses,
37
+ * and users behind one address must not limit each other (audit S6, W2). It sets no lock: the owner of the account
38
+ * can still log in. `passwordCheckOf` counts in the same counter for the e-mail confirmation.
39
+ */
40
+ passwordCheck: Middleware;
41
+ /**
42
+ * The same limit and counter as `passwordCheck`, keyed on the account that `userIdOf` gives for the request, for an
43
+ * endpoint without an access token whose password belongs to another known account (the e-mail confirmation, audit
44
+ * S4, DEC-281). Created once per endpoint.
45
+ */
46
+ passwordCheckOf(userIdOf: (req: Request) => string | undefined): Middleware;
47
+ /**
48
+ * Clears the counter of password checks of the user after the right password.
49
+ *
50
+ * @throws the error of Redis when it fails; the caller logs it (the operation has already succeeded).
51
+ */
52
+ clearPasswordChecks(userId: string): Promise<void>;
53
+ /** Limit of verification links sent again to the signed-in user, keyed on `req.user.userId` (audit S5). */
54
+ verificationEmail: Middleware;
55
+ /**
56
+ * Counts a password reset link (or a notice of a registration) for the account and tells whether it may be sent
57
+ * (audit S5). The caller answers the same either way.
58
+ *
59
+ * @throws the error of Redis when it fails; the caller sends nothing then.
60
+ */
61
+ allowPasswordResetEmail(userId: string): Promise<boolean>;
62
+ /**
63
+ * Guards of the login endpoints, in order: limit per IP address, lock of the e-mail (423), limit per e-mail (sets the
64
+ * lock when exceeded), limit per IP address and e-mail. The limit per IP address comes first, so every answer of
65
+ * the guards, the 423 and the 400 of an invalid body included, carries `X-RateLimit-*` (`rest:LIM-3`). The router
66
+ * parses and validates the body after the first guard (so the 400 of a malformed or invalid body has the headers
67
+ * too, and is counted only per IP address); the others read the `email` of the validated body, so a body without a
68
+ * password does not count against the e-mail and cannot lock it (audit N4). When the budget of the IP address is
69
+ * spent, the 429 of the first guard answers before the 423 of a locked e-mail: the limit per IP address is the outer
70
+ * guard.
71
+ */
72
+ login: readonly Middleware[];
73
+ /**
74
+ * Clears what a successful login resets: the counters per e-mail and per IP address and e-mail, and the lock of the
75
+ * e-mail, so the next failed attempts count from one. The counter per IP address stays.
76
+ *
77
+ * Every part is attempted even when another fails.
78
+ *
79
+ * @returns resolves when every part is cleared.
80
+ * @throws `Error` when any part fails. It carries only the number of failed parts: the cause is left out on purpose,
81
+ * because the error of Redis may quote the key, which holds the hash of the e-mail. The caller decides what a
82
+ * failure means for the request.
83
+ */
84
+ clearLoginCounters(req: Request, email: string): Promise<void>;
85
+ /**
86
+ * Clears the counter per e-mail and the lock of the e-mail, after a confirmed password reset of its account: the
87
+ * owner has proved access to the mailbox, so the lock set by attempts of others must not keep the new password out
88
+ * (audit N4). The counters per IP address and e-mail stay (they cannot be found without the address) and expire.
89
+ *
90
+ * @throws `Error` with only the number of failed parts, as `clearLoginCounters`.
91
+ */
92
+ clearEmailLock(email: string): Promise<void>;
93
+ };
94
+ /** Creates the middleware of the limits for the application prefix and the settings of the configuration. */
95
+ export declare const createAuthLimits: (limits: ResolvedAuthLimits) => AuthLimits;
@@ -0,0 +1,98 @@
1
+ import { clientIp, createLockChecker, createRateLimiter, hashKeyPart, hitRateLimit, ipKeyParts, redisKey, removeLock, resetRateLimit, } from '@mielk/http/rate-limit';
2
+ /** Areas of the Redis keys (after the application prefix). */
3
+ export const LIMIT_AREAS = {
4
+ register: 'auth.register',
5
+ passwordReset: 'auth.passwordReset',
6
+ refresh: 'auth.refresh',
7
+ passwordCheck: 'auth.passwordCheck',
8
+ verificationEmail: 'auth.verificationEmail',
9
+ passwordResetEmail: 'auth.passwordResetEmail',
10
+ loginIp: 'auth.login.ip',
11
+ loginIpEmail: 'auth.login.ipEmail',
12
+ loginEmail: 'auth.login.email',
13
+ lockEmail: 'auth.lock:email',
14
+ };
15
+ const emailOf = (req) => {
16
+ const body = req.body;
17
+ if (typeof body !== 'object' || body === null) {
18
+ return undefined;
19
+ }
20
+ const email = Reflect.get(body, 'email');
21
+ return typeof email === 'string' && email.trim() !== '' ? email : undefined;
22
+ };
23
+ const userKeyParts = (req) => (req.user === undefined ? undefined : [req.user.userId]);
24
+ const emailKeyParts = (req) => {
25
+ const email = emailOf(req);
26
+ return email === undefined ? undefined : [hashKeyPart(email)];
27
+ };
28
+ const ipEmailKeyParts = (req) => {
29
+ const ip = clientIp(req);
30
+ const email = emailOf(req);
31
+ return ip === undefined || email === undefined ? undefined : [ip, hashKeyPart(email)];
32
+ };
33
+ /** Creates the middleware of the limits for the application prefix and the settings of the configuration. */
34
+ export const createAuthLimits = (limits) => {
35
+ const { appPrefix } = limits;
36
+ // The limits of authentication reject the request while Redis is unavailable (rest:LIM-4).
37
+ const limiter = (area, setting, keyParts, extra = {}) => createRateLimiter({
38
+ appPrefix,
39
+ area,
40
+ keyParts,
41
+ limit: setting.limit,
42
+ windowSec: setting.windowSeconds,
43
+ whenRedisUnavailable: 'reject',
44
+ ...extra,
45
+ });
46
+ return {
47
+ register: limiter(LIMIT_AREAS.register, limits.register, ipKeyParts),
48
+ passwordReset: limiter(LIMIT_AREAS.passwordReset, limits.passwordReset, ipKeyParts),
49
+ refresh: limiter(LIMIT_AREAS.refresh, limits.refresh, ipKeyParts),
50
+ passwordCheck: limiter(LIMIT_AREAS.passwordCheck, limits.passwordCheck, userKeyParts),
51
+ passwordCheckOf: (userIdOf) => limiter(LIMIT_AREAS.passwordCheck, limits.passwordCheck, (req) => {
52
+ const userId = userIdOf(req);
53
+ return userId === undefined ? undefined : [userId];
54
+ }),
55
+ clearPasswordChecks: (userId) => resetRateLimit(redisKey({ appPrefix, area: LIMIT_AREAS.passwordCheck }, [userId])),
56
+ verificationEmail: limiter(LIMIT_AREAS.verificationEmail, limits.verificationEmail, userKeyParts),
57
+ allowPasswordResetEmail: async (userId) => {
58
+ const { limit, windowSeconds } = limits.passwordResetEmail;
59
+ const key = redisKey({ appPrefix, area: LIMIT_AREAS.passwordResetEmail }, [userId]);
60
+ return (await hitRateLimit(key, limit, windowSeconds)).allowed;
61
+ },
62
+ login: [
63
+ limiter(LIMIT_AREAS.loginIp, limits.login.ip, ipKeyParts),
64
+ createLockChecker({ appPrefix, area: LIMIT_AREAS.lockEmail, keyParts: emailKeyParts }),
65
+ limiter(LIMIT_AREAS.loginEmail, limits.login.email, emailKeyParts, {
66
+ lock: { area: LIMIT_AREAS.lockEmail, ttlSeconds: limits.login.lockSeconds },
67
+ }),
68
+ limiter(LIMIT_AREAS.loginIpEmail, limits.login.ipEmail, ipEmailKeyParts),
69
+ ],
70
+ clearEmailLock: async (email) => {
71
+ const emailPart = hashKeyPart(email);
72
+ const results = await Promise.allSettled([
73
+ resetRateLimit(redisKey({ appPrefix, area: LIMIT_AREAS.loginEmail }, [emailPart])),
74
+ removeLock(redisKey({ appPrefix, area: LIMIT_AREAS.lockEmail }, [emailPart])),
75
+ ]);
76
+ const failed = results.filter((result) => result.status === 'rejected');
77
+ if (failed.length > 0) {
78
+ throw new Error(`${String(failed.length)} of ${String(results.length)} e-mail counters could not be cleared.`);
79
+ }
80
+ },
81
+ clearLoginCounters: async (req, email) => {
82
+ const emailPart = hashKeyPart(email);
83
+ const ip = clientIp(req);
84
+ const results = await Promise.allSettled([
85
+ resetRateLimit(redisKey({ appPrefix, area: LIMIT_AREAS.loginEmail }, [emailPart])),
86
+ ip === undefined
87
+ ? Promise.resolve()
88
+ : resetRateLimit(redisKey({ appPrefix, area: LIMIT_AREAS.loginIpEmail }, [ip, emailPart])),
89
+ removeLock(redisKey({ appPrefix, area: LIMIT_AREAS.lockEmail }, [emailPart])),
90
+ ]);
91
+ const failed = results.filter((result) => result.status === 'rejected');
92
+ if (failed.length > 0) {
93
+ // The Redis error may quote the key, which holds the e-mail hash and the address: only the count stays.
94
+ throw new Error(`${String(failed.length)} of ${String(results.length)} login counters could not be cleared.`);
95
+ }
96
+ },
97
+ };
98
+ };
@@ -0,0 +1,49 @@
1
+ import type { AuthRepository, AuthTokenPurpose, Clock, UserId } from './ports.js';
2
+ /** Lifetime of one-time tokens in seconds: e-mail verification 24 hours, password reset 1 hour (plan TASK-191, 2.3). */
3
+ export declare const AUTH_TOKEN_TTL_SECONDS: Readonly<Record<AuthTokenPurpose, number>>;
4
+ /** Issued one-time token; `token` goes only into the link of the e-mail and is never stored. */
5
+ export type IssuedAuthToken = {
6
+ token: string;
7
+ expiresAt: Date;
8
+ };
9
+ /** One-time tokens of e-mail verification and password reset. */
10
+ export type OneTimeTokenService = {
11
+ /**
12
+ * Issues a token and invalidates the earlier unused tokens of the user with the same purpose, in one transaction
13
+ * that first locks the user (`AuthRepository.lockUser`), so parallel issues leave exactly one usable token.
14
+ */
15
+ issue(userId: UserId, purpose: AuthTokenPurpose): Promise<IssuedAuthToken>;
16
+ /**
17
+ * Uses the token up and returns its user. Locks the user first, then marks the token as used: the same order as
18
+ * `issue` (user, then token rows), so a parallel issue and a use of the token cannot wait for each other. The user
19
+ * stays locked until the end of the transaction, so the caller can change the account right away.
20
+ *
21
+ * @param repository - repository of an open transaction, when the caller changes more rows together with the use;
22
+ * without it the use runs in a transaction of its own.
23
+ * @throws `InvalidAuthTokenError` for an unknown, used, replaced or expired token, or a token of another purpose.
24
+ */
25
+ consume(token: string, purpose: AuthTokenPurpose, repository?: AuthRepository): Promise<UserId>;
26
+ /**
27
+ * Checks, without a lock and without using it, that the token could be used now: known, of the purpose, not used or
28
+ * replaced, not expired. A cheap test before expensive work (bcrypt); `consume` decides.
29
+ *
30
+ * @returns the user of the token.
31
+ * @throws `InvalidAuthTokenError` when it could not.
32
+ */
33
+ check(token: string, purpose: AuthTokenPurpose): Promise<UserId>;
34
+ };
35
+ /** Options of `createOneTimeTokenService`. */
36
+ export type OneTimeTokenOptions = {
37
+ repository: AuthRepository;
38
+ clock: Clock;
39
+ };
40
+ /** Creates the one-time token service. */
41
+ export declare const createOneTimeTokenService: ({ repository, clock }: OneTimeTokenOptions) => OneTimeTokenService;
42
+ /**
43
+ * Builds the link of an e-mail: `<base>/<page>#token=<token>` (no slash is added after a base ending with `/`, e.g.
44
+ * `myapp://` gives `myapp://verify-email#token=…`). The token is in the fragment, which the browser does not
45
+ * send to the server, so it does not reach server logs (`rest:URL-6`); the application sends it in a request body.
46
+ *
47
+ * @param base - link base validated by the configuration (`links.web` or `links.mobile`).
48
+ */
49
+ export declare const buildAuthLink: (base: string, purpose: AuthTokenPurpose, token: string) => string;
@@ -0,0 +1,60 @@
1
+ import { InvalidAuthTokenError } from './errors.js';
2
+ import { generateOpaqueToken, hashOpaqueToken } from './opaque-token.js';
3
+ /** Lifetime of one-time tokens in seconds: e-mail verification 24 hours, password reset 1 hour (plan TASK-191, 2.3). */
4
+ export const AUTH_TOKEN_TTL_SECONDS = {
5
+ email_verification: 24 * 60 * 60,
6
+ password_reset: 60 * 60,
7
+ };
8
+ /** Paths of the pages that receive one-time tokens, relative to the link base. */
9
+ const LINK_PATHS = {
10
+ email_verification: 'verify-email',
11
+ password_reset: 'reset-password',
12
+ };
13
+ /** Creates the one-time token service. */
14
+ export const createOneTimeTokenService = ({ repository, clock }) => ({
15
+ issue: (userId, purpose) => repository.withTransaction(async (tx) => {
16
+ await tx.lockUser(userId);
17
+ const createdAt = clock.now();
18
+ const expiresAt = new Date(createdAt.getTime() + AUTH_TOKEN_TTL_SECONDS[purpose] * 1000);
19
+ const token = generateOpaqueToken();
20
+ await tx.invalidateAuthTokens(userId, purpose, createdAt);
21
+ await tx.createAuthToken({ userId, purpose, tokenHash: hashOpaqueToken(token), expiresAt, createdAt });
22
+ return { token, expiresAt };
23
+ }),
24
+ consume: (token, purpose, target) => {
25
+ const tokenHash = hashOpaqueToken(token);
26
+ const consume = async (tx) => {
27
+ // The owner is read without a lock; the lock comes before the update of the token row, because `issue` takes
28
+ // them in this order (r2:U1). An unknown token takes no lock.
29
+ const found = await tx.findAuthToken(tokenHash);
30
+ if (found === null) {
31
+ throw new InvalidAuthTokenError(purpose);
32
+ }
33
+ await tx.lockUser(found.userId);
34
+ const record = await tx.consumeAuthToken(tokenHash, purpose, clock.now());
35
+ if (record === null) {
36
+ throw new InvalidAuthTokenError(purpose);
37
+ }
38
+ return record.userId;
39
+ };
40
+ return target === undefined ? repository.withTransaction(consume) : consume(target);
41
+ },
42
+ check: async (token, purpose) => {
43
+ const found = await repository.findAuthToken(hashOpaqueToken(token));
44
+ if (found === null ||
45
+ found.purpose !== purpose ||
46
+ found.usedAt !== null ||
47
+ found.expiresAt.getTime() <= clock.now().getTime()) {
48
+ throw new InvalidAuthTokenError(purpose);
49
+ }
50
+ return found.userId;
51
+ },
52
+ });
53
+ /**
54
+ * Builds the link of an e-mail: `<base>/<page>#token=<token>` (no slash is added after a base ending with `/`, e.g.
55
+ * `myapp://` gives `myapp://verify-email#token=…`). The token is in the fragment, which the browser does not
56
+ * send to the server, so it does not reach server logs (`rest:URL-6`); the application sends it in a request body.
57
+ *
58
+ * @param base - link base validated by the configuration (`links.web` or `links.mobile`).
59
+ */
60
+ export const buildAuthLink = (base, purpose, token) => `${base}${base.endsWith('/') ? '' : '/'}${LINK_PATHS[purpose]}#token=${encodeURIComponent(token)}`;
@@ -0,0 +1,6 @@
1
+ /** Number of random bytes of a refresh token and a one-time token (`rest:AUT-3`). */
2
+ export declare const OPAQUE_TOKEN_BYTES = 32;
3
+ /** Returns a new random token: 32 bytes from `crypto.randomBytes`, encoded as base64url (43 characters). */
4
+ export declare const generateOpaqueToken: () => string;
5
+ /** Returns the SHA-256 hash of the token as 64 hexadecimal characters; only the hash is stored. */
6
+ export declare const hashOpaqueToken: (token: string) => string;
@@ -0,0 +1,7 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ /** Number of random bytes of a refresh token and a one-time token (`rest:AUT-3`). */
3
+ export const OPAQUE_TOKEN_BYTES = 32;
4
+ /** Returns a new random token: 32 bytes from `crypto.randomBytes`, encoded as base64url (43 characters). */
5
+ export const generateOpaqueToken = () => randomBytes(OPAQUE_TOKEN_BYTES).toString('base64url');
6
+ /** Returns the SHA-256 hash of the token as 64 hexadecimal characters; only the hash is stored. */
7
+ export const hashOpaqueToken = (token) => createHash('sha256').update(token, 'utf8').digest('hex');
@@ -0,0 +1,43 @@
1
+ import { PASSWORD_MAX_BYTES } from '../schemas/index.js';
2
+ /** bcrypt cost of new password hashes (`rest:AUT-7`: at least 12). */
3
+ export declare const PASSWORD_HASH_COST = 12;
4
+ export { PASSWORD_MAX_BYTES };
5
+ /**
6
+ * bcrypt hash with cost `PASSWORD_HASH_COST` of a random password that was thrown away. Comparing with it takes as long
7
+ * as comparing with a real hash, so the time of a login does not reveal whether the account exists (`rest:AUT-8`). It is
8
+ * a constant and not computed at the first login: computing it would add a whole hashing to the first check of an
9
+ * unknown account. Even a match would log nobody in, because `verifyPassword` returns `false` for a missing hash.
10
+ */
11
+ export declare const DUMMY_PASSWORD_HASH = "$2b$12$N/oSdCXhBWtCig3A.bM6veb9avwhgfmjU6WIASnHhh4EWpIhwhCmy";
12
+ /**
13
+ * Returns the bcrypt hash of the password with cost `PASSWORD_HASH_COST`.
14
+ *
15
+ * @throws `PasswordTooLongError` when the password has more than `PASSWORD_MAX_BYTES` bytes.
16
+ */
17
+ export declare const hashPassword: (password: string) => Promise<string>;
18
+ /**
19
+ * Checks the password against the stored hash. With `hash === null` (unknown e-mail, or an account without a password)
20
+ * it compares with a dummy hash and returns `false`, so it takes the same time as with an account. A password longer
21
+ * than `PASSWORD_MAX_BYTES` never matches, because bcrypt would compare only its first 72 bytes.
22
+ */
23
+ export declare const verifyPassword: (password: string, hash: string | null) => Promise<boolean>;
24
+ /** Password hashing and checking with a bound on the bcrypt work running at once (audit W1). */
25
+ export type PasswordHasher = {
26
+ /** `hashPassword` within the bound. @throws `PasswordHashingBusyError` when the bound and the queue are full. */
27
+ hash(password: string): Promise<string>;
28
+ /** `verifyPassword` within the bound. @throws `PasswordHashingBusyError` when the bound and the queue are full. */
29
+ verify(password: string, hash: string | null): Promise<boolean>;
30
+ };
31
+ /** Options of `createPasswordHasher`, validated by the configuration (`passwordHashing`). */
32
+ export type PasswordHasherOptions = {
33
+ /** How many bcrypt operations may run at once. */
34
+ maxConcurrent: number;
35
+ /** How many may wait for a free place; one more is refused with `PasswordHashingBusyError`. */
36
+ maxQueued: number;
37
+ };
38
+ /**
39
+ * Creates the hasher of one instance of the library. bcryptjs runs on the main thread, so every operation that runs at
40
+ * once slows all requests of the process; the bound keeps that work limited and refuses the excess at once (503)
41
+ * instead of letting it pile up.
42
+ */
43
+ export declare const createPasswordHasher: ({ maxConcurrent, maxQueued }: PasswordHasherOptions) => PasswordHasher;