@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.
- package/CHANGELOG.md +74 -0
- package/LICENSE +21 -0
- package/README.md +670 -2
- package/dist/client/api-address.d.ts +17 -0
- package/dist/client/api-address.js +434 -0
- package/dist/client/auth-client.d.ts +226 -0
- package/dist/client/auth-client.js +676 -0
- package/dist/client/errors.d.ts +66 -0
- package/dist/client/errors.js +33 -0
- package/dist/client/guards.d.ts +26 -0
- package/dist/client/guards.js +27 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +2 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/locales/en-GB.json +50 -0
- package/dist/locales/pl.json +50 -0
- package/dist/messages.d.ts +65 -0
- package/dist/messages.js +57 -0
- package/dist/pg/index.d.ts +1 -0
- package/dist/pg/index.js +1 -0
- package/dist/pg/migrations/0001_mielk_auth.sql +65 -0
- package/dist/pg/pg-auth-repository.d.ts +91 -0
- package/dist/pg/pg-auth-repository.js +252 -0
- package/dist/react/auth-provider.d.ts +70 -0
- package/dist/react/auth-provider.js +72 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +1 -0
- package/dist/schemas/index.d.ts +234 -0
- package/dist/schemas/index.js +145 -0
- package/dist/server/access-token.d.ts +48 -0
- package/dist/server/access-token.js +54 -0
- package/dist/server/auth-middleware.d.ts +40 -0
- package/dist/server/auth-middleware.js +61 -0
- package/dist/server/config.d.ts +231 -0
- package/dist/server/config.js +250 -0
- package/dist/server/cookies.d.ts +13 -0
- package/dist/server/cookies.js +35 -0
- package/dist/server/core.d.ts +20 -0
- package/dist/server/core.js +32 -0
- package/dist/server/create-auth.d.ts +38 -0
- package/dist/server/create-auth.js +33 -0
- package/dist/server/errors.d.ts +177 -0
- package/dist/server/errors.js +201 -0
- package/dist/server/http-errors.d.ts +9 -0
- package/dist/server/http-errors.js +34 -0
- package/dist/server/limits.d.ts +95 -0
- package/dist/server/limits.js +98 -0
- package/dist/server/one-time-token.d.ts +49 -0
- package/dist/server/one-time-token.js +60 -0
- package/dist/server/opaque-token.d.ts +6 -0
- package/dist/server/opaque-token.js +7 -0
- package/dist/server/password.d.ts +43 -0
- package/dist/server/password.js +78 -0
- package/dist/server/ports.d.ts +343 -0
- package/dist/server/ports.js +11 -0
- package/dist/server/proxy-check.d.ts +16 -0
- package/dist/server/proxy-check.js +78 -0
- package/dist/server/refresh-token.d.ts +60 -0
- package/dist/server/refresh-token.js +122 -0
- package/dist/server/router.d.ts +29 -0
- package/dist/server/router.js +331 -0
- package/dist/server/service.d.ts +158 -0
- package/dist/server/service.js +270 -0
- package/package.json +136 -5
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request and response schemas of the authentication endpoints (plan TASK-191, 2.1 and 2.2), shared by the server and the
|
|
3
|
+
* clients. Messages of the conditions are message keys (`Msg`, `rest:VAL-4`), translated by the client.
|
|
4
|
+
*/
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { Msg } from '../messages.js';
|
|
7
|
+
/**
|
|
8
|
+
* Minimum length of a new password in characters (`rest:AUT-7`: the password policy is here).
|
|
9
|
+
*
|
|
10
|
+
* @since 2.0.0
|
|
11
|
+
*/
|
|
12
|
+
export const PASSWORD_MIN_LENGTH = 10;
|
|
13
|
+
/**
|
|
14
|
+
* Maximum length of a new password in UTF-8 bytes: bcrypt ignores the bytes after the 72nd.
|
|
15
|
+
*
|
|
16
|
+
* @since 2.0.0
|
|
17
|
+
*/
|
|
18
|
+
export const PASSWORD_MAX_BYTES = 72;
|
|
19
|
+
/**
|
|
20
|
+
* Maximum length of an e-mail address (RFC 5321).
|
|
21
|
+
*
|
|
22
|
+
* @since 2.0.0
|
|
23
|
+
*/
|
|
24
|
+
export const EMAIL_MAX_LENGTH = 254;
|
|
25
|
+
/** Maximum length of a password sent for checking (login, current password); longer ones are rejected as invalid. */
|
|
26
|
+
const PASSWORD_INPUT_MAX_LENGTH = 1000;
|
|
27
|
+
/** Maximum length of a token sent in a request body (refresh token, one-time token): the real ones have 43 characters. */
|
|
28
|
+
const TOKEN_MAX_LENGTH = 512;
|
|
29
|
+
/**
|
|
30
|
+
* Kind of the client that asks for a message with a link: the link leads to the web or to the mobile application.
|
|
31
|
+
*
|
|
32
|
+
* @since 2.0.0
|
|
33
|
+
*/
|
|
34
|
+
export const clientKindSchema = z.enum(['web', 'mobile']);
|
|
35
|
+
/**
|
|
36
|
+
* E-mail address trimmed and in lower case (the form the library stores and compares).
|
|
37
|
+
*
|
|
38
|
+
* @since 2.0.0
|
|
39
|
+
*/
|
|
40
|
+
export const emailSchema = z
|
|
41
|
+
.string({ error: Msg.validation.emailInvalid })
|
|
42
|
+
.trim()
|
|
43
|
+
.toLowerCase()
|
|
44
|
+
.max(EMAIL_MAX_LENGTH, { error: Msg.validation.emailInvalid })
|
|
45
|
+
.pipe(z.email({ error: Msg.validation.emailInvalid }));
|
|
46
|
+
/**
|
|
47
|
+
* A new password: at least `PASSWORD_MIN_LENGTH` characters and at most `PASSWORD_MAX_BYTES` bytes.
|
|
48
|
+
*
|
|
49
|
+
* @since 2.0.0
|
|
50
|
+
*/
|
|
51
|
+
export const newPasswordSchema = z
|
|
52
|
+
.string({ error: Msg.password.required })
|
|
53
|
+
.min(PASSWORD_MIN_LENGTH, { error: Msg.password.tooShort })
|
|
54
|
+
.refine((password) => new TextEncoder().encode(password).length <= PASSWORD_MAX_BYTES, {
|
|
55
|
+
error: Msg.password.tooLong,
|
|
56
|
+
});
|
|
57
|
+
/** A password sent for checking: any non-empty text, the policy applies to new passwords only. */
|
|
58
|
+
const existingPasswordSchema = z
|
|
59
|
+
.string({ error: Msg.password.required })
|
|
60
|
+
.min(1, { error: Msg.password.required })
|
|
61
|
+
.max(PASSWORD_INPUT_MAX_LENGTH, { error: Msg.password.tooLong });
|
|
62
|
+
const tokenSchema = z
|
|
63
|
+
.string({ error: Msg.validation.tokenRequired })
|
|
64
|
+
.min(1, { error: Msg.validation.tokenRequired })
|
|
65
|
+
.max(TOKEN_MAX_LENGTH, { error: Msg.validation.tokenRequired });
|
|
66
|
+
/**
|
|
67
|
+
* Body of `POST /register`. `client` selects the link of the verification e-mail; default `web`.
|
|
68
|
+
*
|
|
69
|
+
* @since 2.0.0
|
|
70
|
+
*/
|
|
71
|
+
export const registerBodySchema = z.object({
|
|
72
|
+
email: emailSchema,
|
|
73
|
+
password: newPasswordSchema,
|
|
74
|
+
client: clientKindSchema.optional(),
|
|
75
|
+
});
|
|
76
|
+
/**
|
|
77
|
+
* Body of `POST /login` and `POST /mobile/login`.
|
|
78
|
+
*
|
|
79
|
+
* @since 2.0.0
|
|
80
|
+
*/
|
|
81
|
+
export const loginBodySchema = z.object({
|
|
82
|
+
email: emailSchema,
|
|
83
|
+
password: existingPasswordSchema,
|
|
84
|
+
});
|
|
85
|
+
/**
|
|
86
|
+
* Body of `POST /mobile/refresh` and `POST /mobile/logout`.
|
|
87
|
+
*
|
|
88
|
+
* @since 2.0.0
|
|
89
|
+
*/
|
|
90
|
+
export const mobileRefreshBodySchema = z.object({
|
|
91
|
+
refreshToken: tokenSchema,
|
|
92
|
+
});
|
|
93
|
+
/**
|
|
94
|
+
* Body of `POST /email-verification` (the account comes from the access token).
|
|
95
|
+
*
|
|
96
|
+
* @since 2.0.0
|
|
97
|
+
*/
|
|
98
|
+
export const resendVerificationBodySchema = z.object({
|
|
99
|
+
client: clientKindSchema.optional(),
|
|
100
|
+
});
|
|
101
|
+
/**
|
|
102
|
+
* Body of `POST /email-verification/confirm`: the token of the link and the password of the account, so only who has
|
|
103
|
+
* both the mailbox and the password confirms the address (audit S4, DEC-281).
|
|
104
|
+
*
|
|
105
|
+
* @since 2.0.0
|
|
106
|
+
*/
|
|
107
|
+
export const confirmEmailBodySchema = z.object({
|
|
108
|
+
token: tokenSchema,
|
|
109
|
+
password: existingPasswordSchema,
|
|
110
|
+
});
|
|
111
|
+
/**
|
|
112
|
+
* Body of `POST /password-reset`.
|
|
113
|
+
*
|
|
114
|
+
* @since 2.0.0
|
|
115
|
+
*/
|
|
116
|
+
export const requestPasswordResetBodySchema = z.object({
|
|
117
|
+
email: emailSchema,
|
|
118
|
+
client: clientKindSchema.optional(),
|
|
119
|
+
});
|
|
120
|
+
/**
|
|
121
|
+
* Body of `POST /password-reset/confirm`.
|
|
122
|
+
*
|
|
123
|
+
* @since 2.0.0
|
|
124
|
+
*/
|
|
125
|
+
export const confirmPasswordResetBodySchema = z.object({
|
|
126
|
+
token: tokenSchema,
|
|
127
|
+
password: newPasswordSchema,
|
|
128
|
+
});
|
|
129
|
+
/**
|
|
130
|
+
* Body of `PUT /password`.
|
|
131
|
+
*
|
|
132
|
+
* @since 2.0.0
|
|
133
|
+
*/
|
|
134
|
+
export const changePasswordBodySchema = z.object({
|
|
135
|
+
currentPassword: existingPasswordSchema,
|
|
136
|
+
newPassword: newPasswordSchema,
|
|
137
|
+
});
|
|
138
|
+
/**
|
|
139
|
+
* Body of `DELETE /me`: the password confirms the irreversible operation.
|
|
140
|
+
*
|
|
141
|
+
* @since 2.0.0
|
|
142
|
+
*/
|
|
143
|
+
export const deleteAccountBodySchema = z.object({
|
|
144
|
+
password: existingPasswordSchema,
|
|
145
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Clock, UserId } from './ports.js';
|
|
2
|
+
/** Issuer of every access token of the library. */
|
|
3
|
+
export declare const ACCESS_TOKEN_ISSUER = "@mielk/auth";
|
|
4
|
+
/** Issued access token. */
|
|
5
|
+
export type IssuedAccessToken = {
|
|
6
|
+
token: string;
|
|
7
|
+
expiresAt: Date;
|
|
8
|
+
};
|
|
9
|
+
/** What a verified access token says: the user and whether the e-mail was verified when the token was issued. */
|
|
10
|
+
export type VerifiedAccessToken = {
|
|
11
|
+
userId: UserId;
|
|
12
|
+
/**
|
|
13
|
+
* Whether the e-mail of the account was verified at the issue of the token (claim `email_verified`). A token issued
|
|
14
|
+
* before the verification keeps `false` until it expires, also after the address was confirmed (r1:U2).
|
|
15
|
+
*/
|
|
16
|
+
emailVerified: boolean;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Issues and verifies access tokens: JWT HS256 of the type `at+jwt` with only `sub`, `iat`, `exp`, `iss`, `aud` and,
|
|
20
|
+
* for a verified e-mail, `email_verified: true` (`rest:AUT-2`: data needed for authorization only). The issuer and the
|
|
21
|
+
* audience are required at verification, so a token of another application signed with the same secret, or another JWT
|
|
22
|
+
* signed with it, is refused (audit S2).
|
|
23
|
+
*/
|
|
24
|
+
export type AccessTokenService = {
|
|
25
|
+
/**
|
|
26
|
+
* Issues a token for the user; `emailVerified`: whether the e-mail of the account is verified now, read under the
|
|
27
|
+
* lock of the user together with the session the token belongs to (default `false`).
|
|
28
|
+
*/
|
|
29
|
+
issue(userId: UserId, emailVerified?: boolean): Promise<IssuedAccessToken>;
|
|
30
|
+
/**
|
|
31
|
+
* Verifies the token and returns what it says.
|
|
32
|
+
*
|
|
33
|
+
* @throws `AccessTokenExpiredError` for an expired token, `InvalidAccessTokenError` for any other invalid token.
|
|
34
|
+
*/
|
|
35
|
+
verify(token: string): Promise<VerifiedAccessToken>;
|
|
36
|
+
};
|
|
37
|
+
/** Options of `createAccessTokenService`. */
|
|
38
|
+
export type AccessTokenOptions = {
|
|
39
|
+
/** Secret validated by the configuration (at least 32 bytes). */
|
|
40
|
+
secret: string;
|
|
41
|
+
/** Lifetime in seconds, validated by the configuration (at most 900). */
|
|
42
|
+
ttlSeconds: number;
|
|
43
|
+
/** Audience of the tokens: the application they are valid for (`limits.appPrefix`). */
|
|
44
|
+
audience: string;
|
|
45
|
+
clock: Clock;
|
|
46
|
+
};
|
|
47
|
+
/** Creates the access token service. */
|
|
48
|
+
export declare const createAccessTokenService: ({ secret, ttlSeconds, audience, clock, }: AccessTokenOptions) => AccessTokenService;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { errors, jwtVerify, SignJWT } from 'jose';
|
|
2
|
+
import { AccessTokenExpiredError, InvalidAccessTokenError } from './errors.js';
|
|
3
|
+
const ALGORITHM = 'HS256';
|
|
4
|
+
/** Type of the header of an access token (RFC 9068), so a JWT made for another purpose is not taken for one. */
|
|
5
|
+
const TOKEN_TYPE = 'at+jwt';
|
|
6
|
+
/** Issuer of every access token of the library. */
|
|
7
|
+
export const ACCESS_TOKEN_ISSUER = '@mielk/auth';
|
|
8
|
+
/** Claim of a token issued for an account whose e-mail was verified (the name of the OpenID Connect claim). */
|
|
9
|
+
const EMAIL_VERIFIED_CLAIM = 'email_verified';
|
|
10
|
+
const toEpochSeconds = (date) => Math.floor(date.getTime() / 1000);
|
|
11
|
+
/** Creates the access token service. */
|
|
12
|
+
export const createAccessTokenService = ({ secret, ttlSeconds, audience, clock, }) => {
|
|
13
|
+
const key = new TextEncoder().encode(secret);
|
|
14
|
+
return {
|
|
15
|
+
issue: async (userId, emailVerified = false) => {
|
|
16
|
+
const issuedAt = toEpochSeconds(clock.now());
|
|
17
|
+
const expiresAtSeconds = issuedAt + ttlSeconds;
|
|
18
|
+
const token = await new SignJWT(emailVerified ? { [EMAIL_VERIFIED_CLAIM]: true } : {})
|
|
19
|
+
.setProtectedHeader({ alg: ALGORITHM, typ: TOKEN_TYPE })
|
|
20
|
+
.setSubject(userId)
|
|
21
|
+
.setIssuer(ACCESS_TOKEN_ISSUER)
|
|
22
|
+
.setAudience(audience)
|
|
23
|
+
.setIssuedAt(issuedAt)
|
|
24
|
+
.setExpirationTime(expiresAtSeconds)
|
|
25
|
+
.sign(key);
|
|
26
|
+
return { token, expiresAt: new Date(expiresAtSeconds * 1000) };
|
|
27
|
+
},
|
|
28
|
+
verify: async (token) => {
|
|
29
|
+
try {
|
|
30
|
+
const { payload } = await jwtVerify(token, key, {
|
|
31
|
+
algorithms: [ALGORITHM],
|
|
32
|
+
typ: TOKEN_TYPE,
|
|
33
|
+
issuer: ACCESS_TOKEN_ISSUER,
|
|
34
|
+
audience,
|
|
35
|
+
currentDate: clock.now(),
|
|
36
|
+
requiredClaims: ['sub', 'iat', 'exp', 'iss', 'aud'],
|
|
37
|
+
});
|
|
38
|
+
if (typeof payload.sub !== 'string' || payload.sub === '') {
|
|
39
|
+
throw new InvalidAccessTokenError();
|
|
40
|
+
}
|
|
41
|
+
return { userId: payload.sub, emailVerified: payload[EMAIL_VERIFIED_CLAIM] === true };
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (err instanceof InvalidAccessTokenError) {
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
if (err instanceof errors.JWTExpired) {
|
|
48
|
+
throw new AccessTokenExpiredError({ cause: err });
|
|
49
|
+
}
|
|
50
|
+
throw new InvalidAccessTokenError({ cause: err });
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Middleware that authenticates a request by the access token (`rest:AUT-1`, `AUT-2`, `AUT-9`). */
|
|
2
|
+
import type { Request, RequestHandler } from 'express';
|
|
3
|
+
import type { AccessTokenService } from './access-token.js';
|
|
4
|
+
import type { AuthRepository, UserId } from './ports.js';
|
|
5
|
+
/**
|
|
6
|
+
* The user the access token belongs to; the only source of the user identifier in a handler (`rest:AUT-9`).
|
|
7
|
+
*
|
|
8
|
+
* @since 2.0.0
|
|
9
|
+
*/
|
|
10
|
+
export type AuthenticatedUser = {
|
|
11
|
+
userId: UserId;
|
|
12
|
+
};
|
|
13
|
+
declare module 'express-serve-static-core' {
|
|
14
|
+
interface Request {
|
|
15
|
+
/** Set by `authMiddleware` after the access token has been verified. */
|
|
16
|
+
user?: AuthenticatedUser;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The requests whose access token was issued for a verified e-mail (r1:U2): `authMiddleware` adds them,
|
|
21
|
+
* `requireVerifiedEmail` reads them. Shared by the two middleware of one `createAuth`; a request object is dropped with
|
|
22
|
+
* the request, so a `WeakSet` keeps nothing alive.
|
|
23
|
+
*/
|
|
24
|
+
export type VerifiedAtIssue = WeakSet<Request>;
|
|
25
|
+
/**
|
|
26
|
+
* Creates the middleware: takes the token from `Authorization: Bearer <token>`, verifies it and sets `req.user`.
|
|
27
|
+
* Without a valid token it fails with `UnauthorizedError` (401) and a message key; an expired token has its own key, so
|
|
28
|
+
* the client knows it should refresh the session. The error goes to the final error handler of the application.
|
|
29
|
+
*/
|
|
30
|
+
export declare const createAuthMiddleware: (accessTokens: AccessTokenService, verifiedAtIssue?: VerifiedAtIssue) => RequestHandler;
|
|
31
|
+
/**
|
|
32
|
+
* Creates the middleware that lets through only an account whose e-mail is verified (audit S4). It runs after
|
|
33
|
+
* `authMiddleware` of the same `createAuth` (the same `verifiedAtIssue`) and requires both: an access token issued
|
|
34
|
+
* after the verification (r1:U2: a token issued before it, e.g. to whoever registered the address of somebody else, is
|
|
35
|
+
* refused until it expires, also after the owner recovered the account and confirmed the address; the confirmation
|
|
36
|
+
* ends every earlier session, so a new token comes only from a new login) and an account that is verified now, read
|
|
37
|
+
* from the repository on every request. Otherwise `EmailNotVerifiedError` (403); an account that no longer exists
|
|
38
|
+
* `InvalidAccessTokenError` (401), a request without `req.user` (no `authMiddleware` before it) 401 as a missing token.
|
|
39
|
+
*/
|
|
40
|
+
export declare const createRequireVerifiedEmail: (repository: AuthRepository, verifiedAtIssue?: VerifiedAtIssue) => RequestHandler;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { UnauthorizedError } from '@mielk/http/http';
|
|
2
|
+
import { Msg } from '../messages.js';
|
|
3
|
+
import { AuthError, EmailNotVerifiedError, InvalidAccessTokenError } from './errors.js';
|
|
4
|
+
import { toHttpError } from './http-errors.js';
|
|
5
|
+
const BEARER = /^Bearer ([^\s]+)$/iu;
|
|
6
|
+
/**
|
|
7
|
+
* Creates the middleware: takes the token from `Authorization: Bearer <token>`, verifies it and sets `req.user`.
|
|
8
|
+
* Without a valid token it fails with `UnauthorizedError` (401) and a message key; an expired token has its own key, so
|
|
9
|
+
* the client knows it should refresh the session. The error goes to the final error handler of the application.
|
|
10
|
+
*/
|
|
11
|
+
export const createAuthMiddleware = (accessTokens, verifiedAtIssue = new WeakSet()) => async (req, _res, next) => {
|
|
12
|
+
const token = BEARER.exec(req.headers.authorization ?? '')?.[1];
|
|
13
|
+
if (token === undefined) {
|
|
14
|
+
next(new UnauthorizedError(Msg.accessToken.missing));
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
const verified = await accessTokens.verify(token);
|
|
19
|
+
req.user = { userId: verified.userId };
|
|
20
|
+
if (verified.emailVerified) {
|
|
21
|
+
verifiedAtIssue.add(req);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
verifiedAtIssue.delete(req);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
next(err instanceof AuthError ? toHttpError(err) : err);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
next();
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Creates the middleware that lets through only an account whose e-mail is verified (audit S4). It runs after
|
|
35
|
+
* `authMiddleware` of the same `createAuth` (the same `verifiedAtIssue`) and requires both: an access token issued
|
|
36
|
+
* after the verification (r1:U2: a token issued before it, e.g. to whoever registered the address of somebody else, is
|
|
37
|
+
* refused until it expires, also after the owner recovered the account and confirmed the address; the confirmation
|
|
38
|
+
* ends every earlier session, so a new token comes only from a new login) and an account that is verified now, read
|
|
39
|
+
* from the repository on every request. Otherwise `EmailNotVerifiedError` (403); an account that no longer exists
|
|
40
|
+
* `InvalidAccessTokenError` (401), a request without `req.user` (no `authMiddleware` before it) 401 as a missing token.
|
|
41
|
+
*/
|
|
42
|
+
export const createRequireVerifiedEmail = (repository, verifiedAtIssue = new WeakSet()) => async (req, _res, next) => {
|
|
43
|
+
if (req.user === undefined) {
|
|
44
|
+
next(new UnauthorizedError(Msg.accessToken.missing));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const user = await repository.findUserById(req.user.userId);
|
|
49
|
+
if (user === null) {
|
|
50
|
+
throw new InvalidAccessTokenError();
|
|
51
|
+
}
|
|
52
|
+
if (user.emailVerifiedAt === null || !verifiedAtIssue.has(req)) {
|
|
53
|
+
throw new EmailNotVerifiedError();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
next(err instanceof AuthError ? toHttpError(err) : err);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
next();
|
|
61
|
+
};
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { type AuthMailer, type AuthRepository, type Clock, type OnUserDeleted } from './ports.js';
|
|
2
|
+
/** Minimum length of the JWT secret in bytes (UTF-8), `rest:AUT-2`. */
|
|
3
|
+
export declare const JWT_SECRET_MIN_BYTES = 32;
|
|
4
|
+
/**
|
|
5
|
+
* Minimum number of different characters of the JWT secret (audit S2). It refuses obvious placeholders such as one
|
|
6
|
+
* repeated character; a random secret of 32 hexadecimal digits has fewer with a probability of about 4 in 100 million.
|
|
7
|
+
*/
|
|
8
|
+
export declare const JWT_SECRET_MIN_DISTINCT_CHARACTERS = 8;
|
|
9
|
+
/** Maximum lifetime of an access token in seconds (15 minutes, `rest:AUT-2`); also the default. */
|
|
10
|
+
export declare const ACCESS_TOKEN_TTL_MAX_SECONDS: number;
|
|
11
|
+
/** Minimum lifetime of an access token in seconds. */
|
|
12
|
+
export declare const ACCESS_TOKEN_TTL_MIN_SECONDS = 60;
|
|
13
|
+
/** Default lifetime of a refresh token in seconds (7 days, `rest:AUT-3`). */
|
|
14
|
+
export declare const REFRESH_TOKEN_TTL_DEFAULT_SECONDS: number;
|
|
15
|
+
/** Minimum lifetime of a refresh token in seconds (1 hour). */
|
|
16
|
+
export declare const REFRESH_TOKEN_TTL_MIN_SECONDS: number;
|
|
17
|
+
/** Maximum lifetime of a refresh token in seconds (30 days). */
|
|
18
|
+
export declare const REFRESH_TOKEN_TTL_MAX_SECONDS: number;
|
|
19
|
+
/**
|
|
20
|
+
* Default grace window in seconds for a repeated rotation of the same refresh token (two tabs refreshing at once, a
|
|
21
|
+
* retry after a lost response); within it the repeated rotation gets a new token of the same session (audit W3).
|
|
22
|
+
*/
|
|
23
|
+
export declare const REFRESH_TOKEN_REUSE_GRACE_DEFAULT_SECONDS = 60;
|
|
24
|
+
/** Maximum grace window for a repeated rotation in seconds (60 seconds, rest:AUT-4); `0` switches the window off. */
|
|
25
|
+
export declare const REFRESH_TOKEN_REUSE_GRACE_MAX_SECONDS = 60;
|
|
26
|
+
/** Default number of bcrypt operations that may run at once (audit W1). */
|
|
27
|
+
export declare const PASSWORD_HASHING_CONCURRENT_DEFAULT = 2;
|
|
28
|
+
/** Default number of bcrypt operations that may wait for a free place. */
|
|
29
|
+
export declare const PASSWORD_HASHING_QUEUED_DEFAULT = 32;
|
|
30
|
+
/** Default limit of registrations per IP address: 10 per hour. */
|
|
31
|
+
export declare const REGISTER_LIMIT_DEFAULT: LimitSetting;
|
|
32
|
+
/** Default limit of password reset requests per IP address: 5 per hour. */
|
|
33
|
+
export declare const PASSWORD_RESET_LIMIT_DEFAULT: LimitSetting;
|
|
34
|
+
/** Default limit of refreshes per IP address: 60 per 15 minutes. */
|
|
35
|
+
export declare const REFRESH_LIMIT_DEFAULT: LimitSetting;
|
|
36
|
+
/** Default limit of login attempts per pair of IP address and e-mail, and per e-mail: 5 per 15 minutes. */
|
|
37
|
+
export declare const LOGIN_LIMIT_DEFAULT: LimitSetting;
|
|
38
|
+
/**
|
|
39
|
+
* Default limit of login attempts per IP address: 5 per 15 minutes (the approved values of all three login limits
|
|
40
|
+
* are equal). The limit per IP address answers first, so one address is stopped by its own 429 on the sixth attempt
|
|
41
|
+
* and does not lock the e-mail; the lock is set when attempts from several addresses exceed the limit per e-mail.
|
|
42
|
+
*/
|
|
43
|
+
export declare const LOGIN_IP_LIMIT_DEFAULT: LimitSetting;
|
|
44
|
+
/**
|
|
45
|
+
* Default limit of password checks of the signed-in user (`PUT /password`, `DELETE /me`), per user: 5 per 15 minutes,
|
|
46
|
+
* as the login limit per e-mail (audit S6).
|
|
47
|
+
*/
|
|
48
|
+
export declare const PASSWORD_CHECK_LIMIT_DEFAULT: LimitSetting;
|
|
49
|
+
/** Default limit of verification links sent again to one account (`POST /email-verification`): 3 per hour (audit S5). */
|
|
50
|
+
export declare const VERIFICATION_EMAIL_LIMIT_DEFAULT: LimitSetting;
|
|
51
|
+
/**
|
|
52
|
+
* Default limit of password reset links sent to one account, the notices of a registration of its address included:
|
|
53
|
+
* 3 per hour (audit S5).
|
|
54
|
+
*/
|
|
55
|
+
export declare const PASSWORD_RESET_EMAIL_LIMIT_DEFAULT: LimitSetting;
|
|
56
|
+
/** Default duration of the lock of an e-mail after the login limit for it is exceeded: 15 minutes. */
|
|
57
|
+
export declare const LOGIN_LOCK_DEFAULT_SECONDS: number;
|
|
58
|
+
/**
|
|
59
|
+
* Limit of requests in a time window.
|
|
60
|
+
*
|
|
61
|
+
* @since 2.0.0
|
|
62
|
+
*/
|
|
63
|
+
export type LimitSetting = {
|
|
64
|
+
/** Number of requests allowed in one window, 1–10000. */
|
|
65
|
+
limit: number;
|
|
66
|
+
/** Length of the window in seconds, 1–86400. */
|
|
67
|
+
windowSeconds: number;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Minimal logger the library uses for failures that do not fail a request; a `pino` logger fits.
|
|
71
|
+
*
|
|
72
|
+
* @since 2.0.0
|
|
73
|
+
*/
|
|
74
|
+
export interface AuthLogger {
|
|
75
|
+
warn(object: object, message: string): void;
|
|
76
|
+
error(object: object, message: string): void;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Limits and locks of the authentication endpoints (`rest:LIM-2`, `LIM-3`, `LIM-4`), kept in Redis with `@mielk/http`
|
|
80
|
+
* (`rest:RED-1`). The global limit of all endpoints is not here: the application sets it in `createExpressApp`
|
|
81
|
+
* (`rest:LIM-1`).
|
|
82
|
+
*
|
|
83
|
+
* @since 2.0.0
|
|
84
|
+
*/
|
|
85
|
+
export type AuthLimitsConfig = {
|
|
86
|
+
/** Prefix of the application in the Redis keys (`<appPrefix>:<area>:<…>`), e.g. `finance` (`rest:RED-1`). */
|
|
87
|
+
appPrefix: string;
|
|
88
|
+
/** Registrations per IP address; default 10 per hour. */
|
|
89
|
+
register?: LimitSetting;
|
|
90
|
+
/** Password reset requests per IP address; default 5 per hour. */
|
|
91
|
+
passwordReset?: LimitSetting;
|
|
92
|
+
/** Refreshes (web and mobile) per IP address; default 60 per 15 minutes. A web refresh without the cookie is not counted. */
|
|
93
|
+
refresh?: LimitSetting;
|
|
94
|
+
/**
|
|
95
|
+
* Checks of the password of one account (`PUT /password`, `DELETE /me` and `POST /email-verification/confirm`
|
|
96
|
+
* together), per account; default 5 per 15 minutes. Over it they answer 429 before bcrypt (`PUT /password` and
|
|
97
|
+
* `DELETE /me` also before the body is read; the confirmation after its link was checked); it sets no lock (audit
|
|
98
|
+
* S6, S4).
|
|
99
|
+
*/
|
|
100
|
+
passwordCheck?: LimitSetting;
|
|
101
|
+
/**
|
|
102
|
+
* Verification links sent again (`POST /email-verification`), per user; default 3 per hour. Over it the request is
|
|
103
|
+
* answered 429 (audit S5).
|
|
104
|
+
*/
|
|
105
|
+
verificationEmail?: LimitSetting;
|
|
106
|
+
/**
|
|
107
|
+
* Password reset links sent to one account, per account, from any address: the links of `POST /password-reset` and
|
|
108
|
+
* the `account_exists` notices of `POST /register`; default 3 per hour. Over it the answer stays the same (202) but
|
|
109
|
+
* no e-mail is sent and no token is issued, so the last link sent keeps working (audit S5).
|
|
110
|
+
*/
|
|
111
|
+
passwordResetEmail?: LimitSetting;
|
|
112
|
+
login?: {
|
|
113
|
+
/** Login attempts per IP address; default 5 per 15 minutes. At or below `email` one address is stopped by its own 429 before it can lock an e-mail. */
|
|
114
|
+
ip?: LimitSetting;
|
|
115
|
+
/** Login attempts per pair of IP address and e-mail; default 5 per 15 minutes. */
|
|
116
|
+
ipEmail?: LimitSetting;
|
|
117
|
+
/** Login attempts per e-mail from any address; default 5 per 15 minutes. Exceeding it locks the e-mail. */
|
|
118
|
+
email?: LimitSetting;
|
|
119
|
+
/** Duration of the lock of an e-mail in seconds (answers 423); default 900. */
|
|
120
|
+
lockSeconds?: number;
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
/** Limits after validation, with the defaults filled in. */
|
|
124
|
+
export type ResolvedAuthLimits = {
|
|
125
|
+
appPrefix: string;
|
|
126
|
+
register: LimitSetting;
|
|
127
|
+
passwordReset: LimitSetting;
|
|
128
|
+
refresh: LimitSetting;
|
|
129
|
+
passwordCheck: LimitSetting;
|
|
130
|
+
verificationEmail: LimitSetting;
|
|
131
|
+
passwordResetEmail: LimitSetting;
|
|
132
|
+
login: {
|
|
133
|
+
ip: LimitSetting;
|
|
134
|
+
ipEmail: LimitSetting;
|
|
135
|
+
email: LimitSetting;
|
|
136
|
+
lockSeconds: number;
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Configuration passed by the application to the library. The library reads no environment variables (`ts:BIB-6`).
|
|
141
|
+
*
|
|
142
|
+
* @since 2.0.0
|
|
143
|
+
*/
|
|
144
|
+
export type AuthConfig = {
|
|
145
|
+
jwt: {
|
|
146
|
+
/**
|
|
147
|
+
* Secret that signs access tokens: at least 32 random bytes, from the application configuration (`ts:ENV-3`),
|
|
148
|
+
* of this application only. A value with fewer than 8 different characters or made of a repeated sequence is
|
|
149
|
+
* refused (audit S2). The tokens carry the audience `limits.appPrefix`, so another application refuses them even
|
|
150
|
+
* with the same secret.
|
|
151
|
+
*/
|
|
152
|
+
secret: string;
|
|
153
|
+
/** Lifetime of an access token in seconds, 60–900; default 900 (15 minutes). */
|
|
154
|
+
accessTokenTtlSeconds?: number;
|
|
155
|
+
};
|
|
156
|
+
refreshToken?: {
|
|
157
|
+
/** Lifetime of a refresh token in seconds, 1 hour – 30 days; default 7 days. */
|
|
158
|
+
ttlSeconds?: number;
|
|
159
|
+
/**
|
|
160
|
+
* Grace window in seconds, 0–60 (`rest:AUT-4`); default 60. A token rotated less than this long ago may be rotated again and
|
|
161
|
+
* gets a new token of the same session (two tabs, a retry after a lost response); later it counts as a reuse
|
|
162
|
+
* and ends that session. `0` treats every repeated rotation as a reuse.
|
|
163
|
+
*/
|
|
164
|
+
reuseGraceSeconds?: number;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Bound on the bcrypt work of the instance (bcryptjs runs on the main thread, audit W1): `maxConcurrent` operations
|
|
168
|
+
* (1-64, default 2) run at once, `maxQueued` (0-1000, default 32) wait; a request beyond them is answered 503 at
|
|
169
|
+
* once (`PasswordHashingBusyError`).
|
|
170
|
+
*/
|
|
171
|
+
passwordHashing?: {
|
|
172
|
+
maxConcurrent?: number;
|
|
173
|
+
maxQueued?: number;
|
|
174
|
+
};
|
|
175
|
+
/** Addresses the links in e-mails lead to; a link never leads anywhere else. */
|
|
176
|
+
links: {
|
|
177
|
+
/** Address of the web application: `https:`, or `http:` only for `localhost` and `127.0.0.1`. */
|
|
178
|
+
web: string;
|
|
179
|
+
/** Base of the deep links of the mobile application (e.g. `myapp://` or an `https:` universal link). */
|
|
180
|
+
mobile?: string;
|
|
181
|
+
};
|
|
182
|
+
/** `Secure` attribute of the refresh token cookie; default `true`; `false` only in development (`rest:AUT-5`). */
|
|
183
|
+
secureCookies?: boolean;
|
|
184
|
+
/** Limits and locks of the endpoints; `appPrefix` is required. */
|
|
185
|
+
limits: AuthLimitsConfig;
|
|
186
|
+
repository: AuthRepository;
|
|
187
|
+
mailer: AuthMailer;
|
|
188
|
+
/** Deletes the application data of a deleted account, in the same transaction. */
|
|
189
|
+
onUserDeleted?: OnUserDeleted;
|
|
190
|
+
/** Source of the current time; default the system clock. */
|
|
191
|
+
clock?: Clock;
|
|
192
|
+
/**
|
|
193
|
+
* Logger of failures that do not fail a request (a verification e-mail that was not sent, a lock that was not
|
|
194
|
+
* removed). A request logger of `@mielk/http` (`req.log`) takes precedence; without both nothing is logged.
|
|
195
|
+
*/
|
|
196
|
+
logger?: AuthLogger;
|
|
197
|
+
};
|
|
198
|
+
/** Configuration after validation, with the defaults filled in. */
|
|
199
|
+
export type ResolvedAuthConfig = {
|
|
200
|
+
jwt: {
|
|
201
|
+
secret: string;
|
|
202
|
+
accessTokenTtlSeconds: number;
|
|
203
|
+
};
|
|
204
|
+
refreshToken: {
|
|
205
|
+
ttlSeconds: number;
|
|
206
|
+
reuseGraceSeconds: number;
|
|
207
|
+
};
|
|
208
|
+
passwordHashing: {
|
|
209
|
+
maxConcurrent: number;
|
|
210
|
+
maxQueued: number;
|
|
211
|
+
};
|
|
212
|
+
links: {
|
|
213
|
+
web: string;
|
|
214
|
+
mobile: string | undefined;
|
|
215
|
+
};
|
|
216
|
+
secureCookies: boolean;
|
|
217
|
+
limits: ResolvedAuthLimits;
|
|
218
|
+
repository: AuthRepository;
|
|
219
|
+
mailer: AuthMailer;
|
|
220
|
+
onUserDeleted: OnUserDeleted | undefined;
|
|
221
|
+
clock: Clock;
|
|
222
|
+
logger: AuthLogger | undefined;
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* Validates the configuration and fills in the defaults.
|
|
226
|
+
*
|
|
227
|
+
* @param config - configuration from the application.
|
|
228
|
+
* @returns the configuration with the defaults.
|
|
229
|
+
* @throws `AuthConfigError` listing every invalid field (never its value).
|
|
230
|
+
*/
|
|
231
|
+
export declare const resolveAuthConfig: (config: AuthConfig) => ResolvedAuthConfig;
|