@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,250 @@
1
+ import { z } from 'zod';
2
+ import { AuthConfigError } from './errors.js';
3
+ import { systemClock } from './ports.js';
4
+ /** Minimum length of the JWT secret in bytes (UTF-8), `rest:AUT-2`. */
5
+ export const JWT_SECRET_MIN_BYTES = 32;
6
+ /**
7
+ * Minimum number of different characters of the JWT secret (audit S2). It refuses obvious placeholders such as one
8
+ * repeated character; a random secret of 32 hexadecimal digits has fewer with a probability of about 4 in 100 million.
9
+ */
10
+ export const JWT_SECRET_MIN_DISTINCT_CHARACTERS = 8;
11
+ /** Maximum lifetime of an access token in seconds (15 minutes, `rest:AUT-2`); also the default. */
12
+ export const ACCESS_TOKEN_TTL_MAX_SECONDS = 15 * 60;
13
+ /** Minimum lifetime of an access token in seconds. */
14
+ export const ACCESS_TOKEN_TTL_MIN_SECONDS = 60;
15
+ /** Default lifetime of a refresh token in seconds (7 days, `rest:AUT-3`). */
16
+ export const REFRESH_TOKEN_TTL_DEFAULT_SECONDS = 7 * 24 * 60 * 60;
17
+ /** Minimum lifetime of a refresh token in seconds (1 hour). */
18
+ export const REFRESH_TOKEN_TTL_MIN_SECONDS = 60 * 60;
19
+ /** Maximum lifetime of a refresh token in seconds (30 days). */
20
+ export const REFRESH_TOKEN_TTL_MAX_SECONDS = 30 * 24 * 60 * 60;
21
+ /**
22
+ * Default grace window in seconds for a repeated rotation of the same refresh token (two tabs refreshing at once, a
23
+ * retry after a lost response); within it the repeated rotation gets a new token of the same session (audit W3).
24
+ */
25
+ export const REFRESH_TOKEN_REUSE_GRACE_DEFAULT_SECONDS = 60;
26
+ /** Maximum grace window for a repeated rotation in seconds (60 seconds, rest:AUT-4); `0` switches the window off. */
27
+ export const REFRESH_TOKEN_REUSE_GRACE_MAX_SECONDS = 60;
28
+ /** Default number of bcrypt operations that may run at once (audit W1). */
29
+ export const PASSWORD_HASHING_CONCURRENT_DEFAULT = 2;
30
+ /** Default number of bcrypt operations that may wait for a free place. */
31
+ export const PASSWORD_HASHING_QUEUED_DEFAULT = 32;
32
+ /** Default limit of registrations per IP address: 10 per hour. */
33
+ export const REGISTER_LIMIT_DEFAULT = { limit: 10, windowSeconds: 60 * 60 };
34
+ /** Default limit of password reset requests per IP address: 5 per hour. */
35
+ export const PASSWORD_RESET_LIMIT_DEFAULT = { limit: 5, windowSeconds: 60 * 60 };
36
+ /** Default limit of refreshes per IP address: 60 per 15 minutes. */
37
+ export const REFRESH_LIMIT_DEFAULT = { limit: 60, windowSeconds: 15 * 60 };
38
+ /** Default limit of login attempts per pair of IP address and e-mail, and per e-mail: 5 per 15 minutes. */
39
+ export const LOGIN_LIMIT_DEFAULT = { limit: 5, windowSeconds: 15 * 60 };
40
+ /**
41
+ * Default limit of login attempts per IP address: 5 per 15 minutes (the approved values of all three login limits
42
+ * are equal). The limit per IP address answers first, so one address is stopped by its own 429 on the sixth attempt
43
+ * and does not lock the e-mail; the lock is set when attempts from several addresses exceed the limit per e-mail.
44
+ */
45
+ export const LOGIN_IP_LIMIT_DEFAULT = { limit: 5, windowSeconds: 15 * 60 };
46
+ /**
47
+ * Default limit of password checks of the signed-in user (`PUT /password`, `DELETE /me`), per user: 5 per 15 minutes,
48
+ * as the login limit per e-mail (audit S6).
49
+ */
50
+ export const PASSWORD_CHECK_LIMIT_DEFAULT = { limit: 5, windowSeconds: 15 * 60 };
51
+ /** Default limit of verification links sent again to one account (`POST /email-verification`): 3 per hour (audit S5). */
52
+ export const VERIFICATION_EMAIL_LIMIT_DEFAULT = { limit: 3, windowSeconds: 60 * 60 };
53
+ /**
54
+ * Default limit of password reset links sent to one account, the notices of a registration of its address included:
55
+ * 3 per hour (audit S5).
56
+ */
57
+ export const PASSWORD_RESET_EMAIL_LIMIT_DEFAULT = { limit: 3, windowSeconds: 60 * 60 };
58
+ /** Default duration of the lock of an e-mail after the login limit for it is exceeded: 15 minutes. */
59
+ export const LOGIN_LOCK_DEFAULT_SECONDS = 15 * 60;
60
+ /** Upper bounds that keep a mistyped setting (e.g. milliseconds for seconds) from disabling a limit. */
61
+ const LIMIT_MAX = 10_000;
62
+ const WINDOW_MAX_SECONDS = 24 * 60 * 60;
63
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
64
+ /**
65
+ * Schemes a custom deep link base must not use: the special schemes of the URL standard other than `https:` (their
66
+ * links open a browser, a file or a socket, not the application) and the schemes that run or embed content.
67
+ */
68
+ const FORBIDDEN_DEEP_LINK_PROTOCOLS = new Set([
69
+ 'http:',
70
+ 'ftp:',
71
+ 'ws:',
72
+ 'wss:',
73
+ 'file:',
74
+ 'javascript:',
75
+ 'data:',
76
+ 'vbscript:',
77
+ 'blob:',
78
+ 'about:',
79
+ ]);
80
+ /** A base must start with `<scheme>://`, so that `<base>/<page>` is a path of the base and not an opaque string. */
81
+ const HIERARCHICAL_BASE = /^[a-z][a-z0-9+.-]*:\/\//iu;
82
+ /**
83
+ * Characters a base must not contain even where the URL parser would accept or drop them: `?` and `#` (also as empty
84
+ * delimiters, which `URL.search` and `URL.hash` report as empty), `\` (read as `/` in special schemes), `@` (user
85
+ * information), white space and control characters (the parser removes some of them silently).
86
+ */
87
+ const FORBIDDEN_BASE_CHARACTERS = /[\s\p{Cc}?#\\@]/u;
88
+ /**
89
+ * Parses a link base. With the rules above, `buildAuthLink` turns every accepted base into a link of the form of plan
90
+ * TASK-191, 2.3: `<base>/<page>#token=…`, the base unchanged, no query, the token in the fragment only (checked by the
91
+ * tests of the accepted bases). Returns `null` for any other base.
92
+ */
93
+ const parseLinkBase = (value) => HIERARCHICAL_BASE.test(value) && !FORBIDDEN_BASE_CHARACTERS.test(value) && URL.canParse(value)
94
+ ? new URL(value)
95
+ : null;
96
+ /** `https:` address of the web application, or `http:` only for `localhost`, `127.0.0.1` and `[::1]`. */
97
+ const isWebAppUrl = (value) => {
98
+ const url = parseLinkBase(value);
99
+ if (url === null) {
100
+ return false;
101
+ }
102
+ return url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname));
103
+ };
104
+ /** `https:` universal link, or `<scheme>://…` of the application with a scheme outside the forbidden ones. */
105
+ const isDeepLinkBase = (value) => {
106
+ const url = parseLinkBase(value);
107
+ return url !== null && !FORBIDDEN_DEEP_LINK_PROTOCOLS.has(url.protocol);
108
+ };
109
+ const implementsMethods = (methods) => z.custom((value) => typeof value === 'object' &&
110
+ value !== null &&
111
+ methods.every((method) => typeof Reflect.get(value, method) === 'function'), { message: `must implement ${methods.join(', ')}` });
112
+ const REPOSITORY_METHODS = [
113
+ 'withTransaction',
114
+ 'lockUser',
115
+ 'findUserByEmail',
116
+ 'findUserById',
117
+ 'createUser',
118
+ 'updatePasswordHash',
119
+ 'markEmailVerified',
120
+ 'deleteUser',
121
+ 'createRefreshToken',
122
+ 'findRefreshToken',
123
+ 'revokeRefreshToken',
124
+ 'revokeRefreshTokenFamily',
125
+ 'revokeAllRefreshTokens',
126
+ 'createAuthToken',
127
+ 'invalidateAuthTokens',
128
+ 'findAuthToken',
129
+ 'consumeAuthToken',
130
+ ];
131
+ const limitSettingSchema = (fallback) => z
132
+ .strictObject({
133
+ limit: z.int().min(1).max(LIMIT_MAX),
134
+ windowSeconds: z.int().min(1).max(WINDOW_MAX_SECONDS),
135
+ })
136
+ .default(fallback);
137
+ /** Prefix of a Redis key: the rule of `@mielk/http` (`assertRedisKeyScope`), checked here so the error is in the configuration. */
138
+ const APP_PREFIX = /^[a-z0-9][a-z0-9-]*$/u;
139
+ /** Whether the text is a shorter sequence repeated: it is then found in itself doubled before its own length. */
140
+ const isRepeatedSequence = (value) => (value + value).indexOf(value, 1) < value.length;
141
+ /**
142
+ * Checks of the secret, one issue at most and never its value: the length first, then the signs of a value that is not
143
+ * random (audit S2). They cannot prove that a secret is random or that no other application uses it.
144
+ */
145
+ const secretSchema = z.string().superRefine((secret, ctx) => {
146
+ if (Buffer.byteLength(secret, 'utf8') < JWT_SECRET_MIN_BYTES) {
147
+ ctx.addIssue({ code: 'custom', message: `must be at least ${String(JWT_SECRET_MIN_BYTES)} bytes` });
148
+ }
149
+ else if (new Set(secret).size < JWT_SECRET_MIN_DISTINCT_CHARACTERS || isRepeatedSequence(secret)) {
150
+ ctx.addIssue({
151
+ code: 'custom',
152
+ message: `must be random: at least ${String(JWT_SECRET_MIN_DISTINCT_CHARACTERS)} different characters and not a repeated sequence`,
153
+ });
154
+ }
155
+ });
156
+ const authConfigSchema = z.strictObject({
157
+ jwt: z.strictObject({
158
+ secret: secretSchema,
159
+ accessTokenTtlSeconds: z
160
+ .int()
161
+ .min(ACCESS_TOKEN_TTL_MIN_SECONDS)
162
+ .max(ACCESS_TOKEN_TTL_MAX_SECONDS)
163
+ .default(ACCESS_TOKEN_TTL_MAX_SECONDS),
164
+ }),
165
+ refreshToken: z
166
+ .strictObject({
167
+ ttlSeconds: z
168
+ .int()
169
+ .min(REFRESH_TOKEN_TTL_MIN_SECONDS)
170
+ .max(REFRESH_TOKEN_TTL_MAX_SECONDS)
171
+ .default(REFRESH_TOKEN_TTL_DEFAULT_SECONDS),
172
+ reuseGraceSeconds: z
173
+ .int()
174
+ .min(0)
175
+ .max(REFRESH_TOKEN_REUSE_GRACE_MAX_SECONDS)
176
+ .default(REFRESH_TOKEN_REUSE_GRACE_DEFAULT_SECONDS),
177
+ })
178
+ .default({
179
+ ttlSeconds: REFRESH_TOKEN_TTL_DEFAULT_SECONDS,
180
+ reuseGraceSeconds: REFRESH_TOKEN_REUSE_GRACE_DEFAULT_SECONDS,
181
+ }),
182
+ passwordHashing: z
183
+ .strictObject({
184
+ maxConcurrent: z.int().min(1).max(64).default(PASSWORD_HASHING_CONCURRENT_DEFAULT),
185
+ maxQueued: z.int().min(0).max(1000).default(PASSWORD_HASHING_QUEUED_DEFAULT),
186
+ })
187
+ .default({ maxConcurrent: PASSWORD_HASHING_CONCURRENT_DEFAULT, maxQueued: PASSWORD_HASHING_QUEUED_DEFAULT }),
188
+ links: z.strictObject({
189
+ web: z.string().refine(isWebAppUrl, {
190
+ message: 'must be an https: address (http: only for localhost) without query and fragment',
191
+ }),
192
+ mobile: z
193
+ .string()
194
+ .refine(isDeepLinkBase, {
195
+ message: 'must be a deep link base or an https: address without query and fragment',
196
+ })
197
+ .optional(),
198
+ }),
199
+ secureCookies: z.boolean().default(true),
200
+ limits: z.strictObject({
201
+ appPrefix: z.string().regex(APP_PREFIX, { message: 'must be lower-case letters, digits and hyphens' }),
202
+ register: limitSettingSchema(REGISTER_LIMIT_DEFAULT),
203
+ passwordReset: limitSettingSchema(PASSWORD_RESET_LIMIT_DEFAULT),
204
+ refresh: limitSettingSchema(REFRESH_LIMIT_DEFAULT),
205
+ passwordCheck: limitSettingSchema(PASSWORD_CHECK_LIMIT_DEFAULT),
206
+ verificationEmail: limitSettingSchema(VERIFICATION_EMAIL_LIMIT_DEFAULT),
207
+ passwordResetEmail: limitSettingSchema(PASSWORD_RESET_EMAIL_LIMIT_DEFAULT),
208
+ login: z
209
+ .strictObject({
210
+ ip: limitSettingSchema(LOGIN_IP_LIMIT_DEFAULT),
211
+ ipEmail: limitSettingSchema(LOGIN_LIMIT_DEFAULT),
212
+ email: limitSettingSchema(LOGIN_LIMIT_DEFAULT),
213
+ lockSeconds: z.int().min(1).max(WINDOW_MAX_SECONDS).default(LOGIN_LOCK_DEFAULT_SECONDS),
214
+ })
215
+ .default({
216
+ ip: LOGIN_IP_LIMIT_DEFAULT,
217
+ ipEmail: LOGIN_LIMIT_DEFAULT,
218
+ email: LOGIN_LIMIT_DEFAULT,
219
+ lockSeconds: LOGIN_LOCK_DEFAULT_SECONDS,
220
+ }),
221
+ }),
222
+ repository: implementsMethods(REPOSITORY_METHODS),
223
+ mailer: implementsMethods(['send']),
224
+ onUserDeleted: z
225
+ .custom((value) => typeof value === 'function', { message: 'must be a function' })
226
+ .optional(),
227
+ clock: implementsMethods(['now']).optional(),
228
+ logger: implementsMethods(['warn', 'error']).optional(),
229
+ });
230
+ /**
231
+ * Validates the configuration and fills in the defaults.
232
+ *
233
+ * @param config - configuration from the application.
234
+ * @returns the configuration with the defaults.
235
+ * @throws `AuthConfigError` listing every invalid field (never its value).
236
+ */
237
+ export const resolveAuthConfig = (config) => {
238
+ const result = authConfigSchema.safeParse(config);
239
+ if (!result.success) {
240
+ throw new AuthConfigError(result.error.issues.map((issue) => `${issue.path.map(String).join('.') || '(root)'}: ${issue.message}`));
241
+ }
242
+ const { links, onUserDeleted, clock, logger, ...rest } = result.data;
243
+ return {
244
+ ...rest,
245
+ links: { web: links.web, mobile: links.mobile },
246
+ onUserDeleted,
247
+ clock: clock ?? systemClock,
248
+ logger,
249
+ };
250
+ };
@@ -0,0 +1,13 @@
1
+ /** The refresh token cookie of the web client (`rest:AUT-5`, `AUT-10`) and reading of the `Cookie` header. */
2
+ import type { CookieOptions } from 'express';
3
+ /** Name of the cookie with the refresh token. */
4
+ export declare const REFRESH_COOKIE_NAME = "refreshToken";
5
+ /** Path of the cookie: the refresh and logout endpoints only (`rest:AUT-5`). */
6
+ export declare const REFRESH_COOKIE_PATH = "/v1/auth";
7
+ /**
8
+ * Returns the value of the cookie from the `Cookie` header, or `undefined`. Own parser instead of `cookie-parser`: the
9
+ * library needs one cookie. A value that is not valid percent-encoding is taken as it is.
10
+ */
11
+ export declare const readCookie: (header: string | undefined, name: string) => string | undefined;
12
+ /** Attributes of the refresh token cookie; `Secure` is off only in development (`rest:AUT-5`). */
13
+ export declare const refreshCookieOptions: (secure: boolean) => CookieOptions;
@@ -0,0 +1,35 @@
1
+ /** Name of the cookie with the refresh token. */
2
+ export const REFRESH_COOKIE_NAME = 'refreshToken';
3
+ /** Path of the cookie: the refresh and logout endpoints only (`rest:AUT-5`). */
4
+ export const REFRESH_COOKIE_PATH = '/v1/auth';
5
+ /**
6
+ * Returns the value of the cookie from the `Cookie` header, or `undefined`. Own parser instead of `cookie-parser`: the
7
+ * library needs one cookie. A value that is not valid percent-encoding is taken as it is.
8
+ */
9
+ export const readCookie = (header, name) => {
10
+ if (header === undefined) {
11
+ return undefined;
12
+ }
13
+ for (const pair of header.split(';')) {
14
+ const separator = pair.indexOf('=');
15
+ if (separator === -1 || pair.slice(0, separator).trim() !== name) {
16
+ continue;
17
+ }
18
+ const raw = pair.slice(separator + 1).trim();
19
+ const value = raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2 ? raw.slice(1, -1) : raw;
20
+ try {
21
+ return decodeURIComponent(value);
22
+ }
23
+ catch {
24
+ return value;
25
+ }
26
+ }
27
+ return undefined;
28
+ };
29
+ /** Attributes of the refresh token cookie; `Secure` is off only in development (`rest:AUT-5`). */
30
+ export const refreshCookieOptions = (secure) => ({
31
+ httpOnly: true,
32
+ secure,
33
+ sameSite: 'strict',
34
+ path: REFRESH_COOKIE_PATH,
35
+ });
@@ -0,0 +1,20 @@
1
+ import { type AccessTokenService } from './access-token.js';
2
+ import { type AuthConfig, type ResolvedAuthConfig } from './config.js';
3
+ import { type OneTimeTokenService } from './one-time-token.js';
4
+ import { type PasswordHasher } from './password.js';
5
+ import { type RefreshTokenService } from './refresh-token.js';
6
+ /** Services of the library without Express; the router of `createAuth` builds on them. */
7
+ export type AuthCore = {
8
+ config: ResolvedAuthConfig;
9
+ accessTokens: AccessTokenService;
10
+ refreshTokens: RefreshTokenService;
11
+ oneTimeTokens: OneTimeTokenService;
12
+ /** Hashing and checking of passwords within `passwordHashing` (audit W1). */
13
+ passwords: PasswordHasher;
14
+ };
15
+ /**
16
+ * Validates the configuration and creates the services.
17
+ *
18
+ * @throws `AuthConfigError` for an invalid configuration.
19
+ */
20
+ export declare const createAuthCore: (input: AuthConfig) => AuthCore;
@@ -0,0 +1,32 @@
1
+ import { createAccessTokenService } from './access-token.js';
2
+ import { resolveAuthConfig } from './config.js';
3
+ import { createOneTimeTokenService } from './one-time-token.js';
4
+ import { createPasswordHasher } from './password.js';
5
+ import { createRefreshTokenService } from './refresh-token.js';
6
+ /**
7
+ * Validates the configuration and creates the services.
8
+ *
9
+ * @throws `AuthConfigError` for an invalid configuration.
10
+ */
11
+ export const createAuthCore = (input) => {
12
+ const config = resolveAuthConfig(input);
13
+ const { repository, clock } = config;
14
+ return {
15
+ config,
16
+ accessTokens: createAccessTokenService({
17
+ secret: config.jwt.secret,
18
+ ttlSeconds: config.jwt.accessTokenTtlSeconds,
19
+ // The prefix of the application is its name in Redis too, so two applications never share it (rest:RED-1).
20
+ audience: config.limits.appPrefix,
21
+ clock,
22
+ }),
23
+ refreshTokens: createRefreshTokenService({
24
+ repository,
25
+ ttlSeconds: config.refreshToken.ttlSeconds,
26
+ reuseGraceSeconds: config.refreshToken.reuseGraceSeconds,
27
+ clock,
28
+ }),
29
+ oneTimeTokens: createOneTimeTokenService({ repository, clock }),
30
+ passwords: createPasswordHasher(config.passwordHashing),
31
+ };
32
+ };
@@ -0,0 +1,38 @@
1
+ import type { RequestHandler, Router } from 'express';
2
+ import type { AuthConfig } from './config.js';
3
+ /**
4
+ * What `createAuth` returns.
5
+ *
6
+ * @since 2.0.0
7
+ */
8
+ export type Auth = {
9
+ /** Router with the endpoints of the library; mount it under `/v1/auth` (`rest:URL-4`). */
10
+ router: Router;
11
+ /**
12
+ * Middleware that requires a valid access token and sets `req.user` (`rest:AUT-1`); the application puts it in front
13
+ * of the routers of its modules. A request without a valid token ends with 401 through the error handler.
14
+ */
15
+ authMiddleware: RequestHandler;
16
+ /**
17
+ * Middleware that lets through only an account whose e-mail is verified (audit S4); it comes after `authMiddleware`
18
+ * of the same `createAuth` (`app.use('/v1/shared', auth.authMiddleware, auth.requireVerifiedEmail, sharedRouter)`)
19
+ * and reads the account on every request. The access token must also have been issued after the verification
20
+ * (r1:U2): a token from before it gets 403 until it expires, the user signs in again. An unverified account gets 403
21
+ * `api/auth/emailVerification:required`, an account that no longer exists 401. Put it in front of the routes that
22
+ * trust the e-mail address (invitations, sharing by address).
23
+ */
24
+ requireVerifiedEmail: RequestHandler;
25
+ };
26
+ /**
27
+ * Creates the router and the middleware of the library from the configuration of the application.
28
+ *
29
+ * The application registers the final handlers of `@mielk/http` after the routers: `notFoundHandler` and `errorHandler`,
30
+ * which answer the errors of the library (`rest:ERR-1`), and gives `createExpressApp` the global limit (`rest:LIM-1`).
31
+ *
32
+ * @param config - configuration; see `AuthConfig`.
33
+ * @returns the router and `authMiddleware`.
34
+ * @throws `AuthConfigError` for an invalid configuration, at startup.
35
+ *
36
+ * @since 2.0.0
37
+ */
38
+ export declare const createAuth: (config: AuthConfig) => Auth;
@@ -0,0 +1,33 @@
1
+ import { createAuthMiddleware, createRequireVerifiedEmail } from './auth-middleware.js';
2
+ import { createAuthCore } from './core.js';
3
+ import { createAuthLimits } from './limits.js';
4
+ import { createAuthRouter } from './router.js';
5
+ import { createAuthService } from './service.js';
6
+ /**
7
+ * Creates the router and the middleware of the library from the configuration of the application.
8
+ *
9
+ * The application registers the final handlers of `@mielk/http` after the routers: `notFoundHandler` and `errorHandler`,
10
+ * which answer the errors of the library (`rest:ERR-1`), and gives `createExpressApp` the global limit (`rest:LIM-1`).
11
+ *
12
+ * @param config - configuration; see `AuthConfig`.
13
+ * @returns the router and `authMiddleware`.
14
+ * @throws `AuthConfigError` for an invalid configuration, at startup.
15
+ *
16
+ * @since 2.0.0
17
+ */
18
+ export const createAuth = (config) => {
19
+ const core = createAuthCore(config);
20
+ const verifiedAtIssue = new WeakSet();
21
+ const authMiddleware = createAuthMiddleware(core.accessTokens, verifiedAtIssue);
22
+ const limits = createAuthLimits(core.config.limits);
23
+ const router = createAuthRouter({
24
+ config: core.config,
25
+ service: createAuthService(core, {
26
+ allowPasswordResetEmail: (userId) => limits.allowPasswordResetEmail(userId),
27
+ }),
28
+ limits,
29
+ authMiddleware,
30
+ });
31
+ const requireVerifiedEmail = createRequireVerifiedEmail(core.config.repository, verifiedAtIssue);
32
+ return { router, authMiddleware, requireVerifiedEmail };
33
+ };
@@ -0,0 +1,177 @@
1
+ import { type MessageKey } from '../messages.js';
2
+ import type { AuthTokenPurpose } from './ports.js';
3
+ /**
4
+ * Codes of the library errors; the field `code` distinguishes them (`ts:ERR-6`).
5
+ *
6
+ * @since 2.0.0
7
+ */
8
+ export type AuthErrorCode = 'CONFIG_INVALID' | 'INVALID_CREDENTIALS' | 'PASSWORD_TOO_LONG' | 'CURRENT_PASSWORD_INVALID' | 'PASSWORD_HASHING_BUSY' | 'ACCOUNT_BUSY' | 'EMAIL_TAKEN' | 'EMAIL_NOT_VERIFIED' | 'ACCESS_TOKEN_INVALID' | 'ACCESS_TOKEN_EXPIRED' | 'REFRESH_TOKEN_INVALID' | 'REFRESH_TOKEN_EXPIRED' | 'REFRESH_TOKEN_REUSED' | 'AUTH_TOKEN_INVALID';
9
+ /**
10
+ * Base class of the errors thrown by the library. The errors do not depend on HTTP: the Express layer maps `code` to a
11
+ * status code and sends `messageKey` to the client.
12
+ *
13
+ * @since 2.0.0
14
+ */
15
+ export declare abstract class AuthError extends Error {
16
+ /** Code that distinguishes the error. */
17
+ abstract readonly code: AuthErrorCode;
18
+ /** Message key for the client (`Msg`). */
19
+ abstract readonly messageKey: MessageKey;
20
+ constructor(message: string, options?: ErrorOptions);
21
+ }
22
+ /**
23
+ * The configuration passed to the library is invalid. Thrown at startup; `issues` lists the invalid fields with the
24
+ * reason, never their values, so the message does not reveal a secret.
25
+ *
26
+ * @since 2.0.0
27
+ */
28
+ export declare class AuthConfigError extends AuthError {
29
+ readonly code = "CONFIG_INVALID";
30
+ readonly messageKey: "api/auth/config:invalid";
31
+ /** Invalid fields, each as `<path>: <reason>`. */
32
+ readonly issues: readonly string[];
33
+ /** @param issues - invalid fields, each as `<path>: <reason>`, without the field values. */
34
+ constructor(issues: readonly string[]);
35
+ }
36
+ /**
37
+ * Unknown e-mail or wrong password; both cases give the same error, so it does not reveal the account (`rest:AUT-8`).
38
+ *
39
+ * @since 2.0.0
40
+ */
41
+ export declare class InvalidCredentialsError extends AuthError {
42
+ readonly code = "INVALID_CREDENTIALS";
43
+ readonly messageKey: "api/auth/login:invalidCredentials";
44
+ constructor();
45
+ }
46
+ /**
47
+ * Too many password checks and hashings run or wait already (`passwordHashing` of the configuration); the request is
48
+ * refused at once instead of queueing more bcrypt work on the main thread (audit W1). Answered 503.
49
+ *
50
+ * @since 2.0.0
51
+ */
52
+ export declare class PasswordHashingBusyError extends AuthError {
53
+ readonly code = "PASSWORD_HASHING_BUSY";
54
+ readonly messageKey: "api/auth/password:busy";
55
+ constructor();
56
+ }
57
+ /**
58
+ * The lock of the account was not granted in time (`lockTimeoutMs` of the PostgreSQL adapter): other operations of the
59
+ * same account hold it. Waiting on would hold a connection of the shared pool, so the request is refused (audit S8).
60
+ * Answered 503.
61
+ *
62
+ * @since 2.0.0
63
+ */
64
+ export declare class AccountBusyError extends AuthError {
65
+ readonly code = "ACCOUNT_BUSY";
66
+ readonly messageKey: "api/auth/account:busy";
67
+ constructor();
68
+ }
69
+ /**
70
+ * The password is longer than bcrypt accepts (`PASSWORD_MAX_BYTES`); bcrypt would silently truncate it.
71
+ *
72
+ * @since 2.0.0
73
+ */
74
+ export declare class PasswordTooLongError extends AuthError {
75
+ readonly code = "PASSWORD_TOO_LONG";
76
+ readonly messageKey: "api/auth/password:tooLong";
77
+ constructor();
78
+ }
79
+ /**
80
+ * The current password given for a password change, an account deletion or an e-mail confirmation is wrong.
81
+ *
82
+ * @since 2.0.0
83
+ */
84
+ export declare class CurrentPasswordInvalidError extends AuthError {
85
+ readonly code = "CURRENT_PASSWORD_INVALID";
86
+ readonly messageKey: "api/auth/password:currentInvalid";
87
+ constructor();
88
+ }
89
+ /**
90
+ * An account with the e-mail already exists. A repository adapter throws it when the database reports a unique
91
+ * violation on the e-mail (`rest:SQL-5`).
92
+ *
93
+ * @since 2.0.0
94
+ */
95
+ export declare class EmailTakenError extends AuthError {
96
+ readonly code = "EMAIL_TAKEN";
97
+ readonly messageKey: "api/auth/register:emailTaken";
98
+ /** @param options - `cause`: the original database error. */
99
+ constructor(options?: ErrorOptions);
100
+ }
101
+ /**
102
+ * The e-mail of the signed-in account is not verified; thrown by `requireVerifiedEmail` (audit S4). Answered 403.
103
+ *
104
+ * @since 2.0.0
105
+ */
106
+ export declare class EmailNotVerifiedError extends AuthError {
107
+ readonly code = "EMAIL_NOT_VERIFIED";
108
+ readonly messageKey: "api/auth/emailVerification:required";
109
+ constructor();
110
+ }
111
+ /**
112
+ * The access token is missing, malformed, signed with another key or algorithm, or has an invalid subject.
113
+ *
114
+ * @since 2.0.0
115
+ */
116
+ export declare class InvalidAccessTokenError extends AuthError {
117
+ readonly code = "ACCESS_TOKEN_INVALID";
118
+ readonly messageKey: "api/auth/accessToken:invalid";
119
+ /** @param options - `cause`: the original verification error, if any. */
120
+ constructor(options?: ErrorOptions);
121
+ }
122
+ /**
123
+ * The access token is valid but expired; the client refreshes the session.
124
+ *
125
+ * @since 2.0.0
126
+ */
127
+ export declare class AccessTokenExpiredError extends AuthError {
128
+ readonly code = "ACCESS_TOKEN_EXPIRED";
129
+ readonly messageKey: "api/auth/accessToken:expired";
130
+ /** @param options - `cause`: the original verification error. */
131
+ constructor(options?: ErrorOptions);
132
+ }
133
+ /**
134
+ * The refresh token is unknown or belongs to another kind of client (web or mobile).
135
+ *
136
+ * @since 2.0.0
137
+ */
138
+ export declare class InvalidRefreshTokenError extends AuthError {
139
+ readonly code = "REFRESH_TOKEN_INVALID";
140
+ readonly messageKey: "api/auth/refreshToken:invalid";
141
+ constructor();
142
+ }
143
+ /**
144
+ * The refresh token has expired.
145
+ *
146
+ * @since 2.0.0
147
+ */
148
+ export declare class RefreshTokenExpiredError extends AuthError {
149
+ readonly code = "REFRESH_TOKEN_EXPIRED";
150
+ readonly messageKey: "api/auth/refreshToken:expired";
151
+ constructor();
152
+ }
153
+ /**
154
+ * The refresh token was already revoked: a possible theft. All refresh tokens of the user have been revoked before the
155
+ * error was thrown (`rest:AUT-11`).
156
+ *
157
+ * @since 2.0.0
158
+ */
159
+ export declare class RefreshTokenReusedError extends AuthError {
160
+ readonly code = "REFRESH_TOKEN_REUSED";
161
+ readonly messageKey: "api/auth/refreshToken:reused";
162
+ constructor();
163
+ }
164
+ /**
165
+ * The one-time token (e-mail verification or password reset) is unknown, already used, replaced by a newer one or
166
+ * expired. One error for all cases: the holder of a token learns nothing about other tokens.
167
+ *
168
+ * @since 2.0.0
169
+ */
170
+ export declare class InvalidAuthTokenError extends AuthError {
171
+ readonly code = "AUTH_TOKEN_INVALID";
172
+ readonly messageKey: MessageKey;
173
+ /** Purpose of the rejected token. */
174
+ readonly purpose: AuthTokenPurpose;
175
+ /** @param purpose - purpose of the rejected token; selects the message key. */
176
+ constructor(purpose: AuthTokenPurpose);
177
+ }