@mielk/auth 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +14 -11
- package/dist/server/password.d.ts +2 -0
- package/dist/server/password.js +8 -14
- package/dist/server/proxy-check.d.ts +1 -0
- package/dist/server/proxy-check.js +3 -1
- package/dist/server/router.js +7 -9
- package/dist/server/safe-log.d.ts +9 -0
- package/dist/server/safe-log.js +24 -0
- package/dist/server/service.d.ts +7 -12
- package/dist/server/service.js +4 -30
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,11 +7,21 @@ Versions up to 1.1.6 were generated by standard-version and are kept unchanged.
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.0.1] - 2026-11-23
|
|
11
|
+
|
|
12
|
+
### Security
|
|
13
|
+
|
|
14
|
+
- `POST /register` reserves bcrypt capacity before answering. When capacity is full it returns a retryable 503 for both new and registered addresses. Admitted requests receive 202 before account storage or mail delivery, removing account-dependent work from response timing. Deferred store and mail failures are logged after 202, replacing any 5xx response these failures previously produced (TASK-393).
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- A logger that throws or rejects while reporting an Express `trust proxy` warning or a Redis counter or lock cleanup failure no longer changes the response or causes an unhandled rejection (TASK-406).
|
|
19
|
+
|
|
10
20
|
## [2.0.0] - 2026-11-22
|
|
11
21
|
|
|
12
22
|
### Changed
|
|
13
23
|
|
|
14
|
-
- **Breaking:** the package is renamed from `mielk-auth` to `@mielk/auth` (scope `@mielk` of the npm account `mielk`); `mielk-auth` gets no new versions
|
|
24
|
+
- **Breaking:** the package is renamed from `mielk-auth` to `@mielk/auth` (scope `@mielk` of the npm account `mielk`); `mielk-auth` gets no new versions and is marked deprecated on npm ("renamed to @mielk/auth"). Migration: replace `mielk-auth` with `@mielk/auth` in `package.json` and in every import, including subpaths (e.g. `mielk-auth/schemas` becomes `@mielk/auth/schemas`); do not keep both packages in one application (TASK-230).
|
|
15
25
|
- **Breaking:** access tokens issued before 2.0.0 are refused: 2.0.0 verifies the header type `at+jwt` and the claims `iss` (`@mielk/auth`) and `aud` (`limits.appPrefix`), so the tokens of 1.1.6 (signed without `iss`, `aud` and the type) and of earlier unreleased 2.0.0 builds (`iss` `mielk-auth`) are not accepted (see Fixed, audit TASK-191.13, S2). Migration: after the upgrade every client gets a new access token from 2.0.0 (a refresh, or a new login where its refresh token is refused too), and a service outside the library that verifies the access tokens itself is changed to the same `typ`, `iss` and `aud` checks in the same deployment (TASK-230).
|
|
16
26
|
- `npm run test:dist` runs the tests that need the built package after `npm run build`, in CI and in `prepublishOnly`: `check:readme` refuses an example that calls a method `AuthClient` does not have or a property `createAuth` does not have (TASK-230). The code of the library is unchanged.
|
|
17
27
|
- The test of r1:U1 (`POST /register` answers 202 while the mailer is still sending) counts its 1 s from the call of the mailer, not from the request, so the bcrypt hash under the load of parallel test files no longer fails it; a regression test runs it with the processors kept busy, which reproduced the old limit in most runs, not in all (TASK-388). The code of the library is unchanged.
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Authentication for mielk applications: a server part for Express, a client for web and mobile, a React layer and a
|
|
4
4
|
PostgreSQL adapter, in one package with several entry points.
|
|
5
5
|
|
|
6
|
-
Versions 1.x were published as `mielk-auth` (the last one on npm is 1.1.5). Version 2.0.0 and later are
|
|
6
|
+
Versions 1.x were published as `mielk-auth` (the last one on npm is 1.1.5). Version 2.0.0 and later are published as `@mielk/auth` (repository `mielk-auth`); `mielk-auth` gets no new versions and is marked deprecated on npm ("renamed to @mielk/auth"). The migration is described in [CHANGELOG.md](CHANGELOG.md).
|
|
7
7
|
|
|
8
8
|
Version 2 is a rebuild of the library (TASK-191) and is not compatible with 1.x: see "Connecting in an Nx application" and its migration table. The main entry point `@mielk/auth` has the server part: `createAuth(config)`
|
|
9
9
|
returns the Express router of the endpoints, `authMiddleware` and `requireVerifiedEmail`; it also exports the configuration and port types
|
|
@@ -22,8 +22,7 @@ dependencies only for the entry points you use. The server part needs `express`,
|
|
|
22
22
|
npm install @mielk/auth zod express jose bcryptjs @mielk/http
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
The command above
|
|
26
|
-
before its publication, or a change not published yet that you check in an application, `npm:WYD-5`), build a tarball in this repository and
|
|
25
|
+
The command above installs the latest published version of `@mielk/auth` from the registry (2.0.0 is published). For a change not published yet that you check in an application (`npm:WYD-5`), build a tarball in this repository and
|
|
27
26
|
install that file instead of the registry name; the `import` lines stay the same (`@mielk/auth`, `@mielk/auth/client`,
|
|
28
27
|
...), because the package in the tarball has the name `@mielk/auth`:
|
|
29
28
|
|
|
@@ -205,16 +204,20 @@ root.listen(config.port);
|
|
|
205
204
|
(the client becomes `anonymous` at its next refresh).
|
|
206
205
|
- `POST /register` does not reveal whether an address has an account (audit S3): it answers 202 without a body in both
|
|
207
206
|
cases. A new address gets an account and the verification link; a registered one gets no new account and no change,
|
|
208
|
-
and its owner gets the message `account_exists` with a password reset link
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
207
|
+
and its owner gets the message `account_exists` with a password reset link, subject to the per-account reset limit.
|
|
208
|
+
The server reserves a bcrypt slot before sending 202. If all running and queued slots are occupied, it sends a
|
|
209
|
+
retryable 503 for either address. Once admitted, hashing, account storage and mail delivery run after the response
|
|
210
|
+
(TASK-393). Configure `config.logger` or provide `req.log` to record account storage and mail delivery failures after 202.
|
|
211
|
+
Without either logger, these failures leave no trace in the response or in library logs.
|
|
212
|
+
The library provides no shutdown drain for this work, so keep the process running after the response for
|
|
213
|
+
registration and delivery to finish.
|
|
214
|
+
The client shows the same text for both cases, e.g. "Check your mailbox".
|
|
212
215
|
|
|
213
216
|
Endpoints under `/v1/auth` (answers are `ApiResponse` of `@mielk/http`; the types are in `@mielk/auth/schemas`):
|
|
214
217
|
|
|
215
218
|
| Endpoint | Access | Purpose |
|
|
216
219
|
| --------------------------------------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
217
|
-
| `POST /register` | public | 202 without a body
|
|
220
|
+
| `POST /register` | public | 202 without a body once admitted, 503 when bcrypt capacity is full |
|
|
218
221
|
| `POST /login`, `POST /refresh`, `POST /logout` | public (refresh cookie) | web session: the refresh token is in the `httpOnly` cookie |
|
|
219
222
|
| `POST /mobile/login`, `/mobile/refresh`, `/mobile/logout` | public (refresh token in the body) | mobile session: a request with `Origin`: 403 |
|
|
220
223
|
| `GET /me`, `DELETE /me` | access token | the account of the access token; deleting it needs the password |
|
|
@@ -379,9 +382,9 @@ reachable only through it; never `true`. Both mistakes break the limits:
|
|
|
379
382
|
|
|
380
383
|
The router logs a warning once (field `proxyCheck`, no address in the entry) when a request has `X-Forwarded-For` but
|
|
381
384
|
`req.ip` is a loopback or private address (`forwarded_for_without_trust_proxy`, the symptom of the first mistake) and
|
|
382
|
-
when `trust proxy` is `true` (`trust_proxy_true`)
|
|
383
|
-
clients behind one shared address (an office, a school, carrier-grade NAT) share the limits per
|
|
384
|
-
address counts as a whole, not by its `/64` prefix.
|
|
385
|
+
when `trust proxy` is `true` (`trust_proxy_true`). The request proceeds even if the logger throws or rejects.
|
|
386
|
+
Also with the right setting, clients behind one shared address (an office, a school, carrier-grade NAT) share the limits per
|
|
387
|
+
address, and an IPv6 address counts as a whole, not by its `/64` prefix.
|
|
385
388
|
|
|
386
389
|
Mobile endpoints (`/mobile/*`) refuse a request with an `Origin` header with 403. `createExpressApp` of `@mielk/http`
|
|
387
390
|
parses JSON before any router, so the application must mount `mobileOriginGuard` (exported by `@mielk/auth`) **before**
|
|
@@ -25,6 +25,8 @@ export declare const verifyPassword: (password: string, hash: string | null) =>
|
|
|
25
25
|
export type PasswordHasher = {
|
|
26
26
|
/** `hashPassword` within the bound. @throws `PasswordHashingBusyError` when the bound and the queue are full. */
|
|
27
27
|
hash(password: string): Promise<string>;
|
|
28
|
+
/** Reserves bcrypt capacity immediately. @throws `PasswordHashingBusyError` synchronously if full. */
|
|
29
|
+
enqueueHash(password: string): Promise<string>;
|
|
28
30
|
/** `verifyPassword` within the bound. @throws `PasswordHashingBusyError` when the bound and the queue are full. */
|
|
29
31
|
verify(password: string, hash: string | null): Promise<boolean>;
|
|
30
32
|
};
|
package/dist/server/password.js
CHANGED
|
@@ -40,16 +40,16 @@ export const verifyPassword = async (password, hash) => {
|
|
|
40
40
|
export const createPasswordHasher = ({ maxConcurrent, maxQueued }) => {
|
|
41
41
|
let running = 0;
|
|
42
42
|
const waiting = [];
|
|
43
|
-
const acquire =
|
|
43
|
+
const acquire = () => {
|
|
44
44
|
if (running < maxConcurrent) {
|
|
45
45
|
running++;
|
|
46
|
-
return;
|
|
46
|
+
return Promise.resolve();
|
|
47
47
|
}
|
|
48
48
|
if (waiting.length >= maxQueued) {
|
|
49
49
|
throw new PasswordHashingBusyError();
|
|
50
50
|
}
|
|
51
51
|
// The place is handed over by `release` without being given back first, so `running` stays the same.
|
|
52
|
-
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
53
|
waiting.push(resolve);
|
|
54
54
|
});
|
|
55
55
|
};
|
|
@@ -62,17 +62,11 @@ export const createPasswordHasher = ({ maxConcurrent, maxQueued }) => {
|
|
|
62
62
|
next();
|
|
63
63
|
}
|
|
64
64
|
};
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
try {
|
|
68
|
-
return await work();
|
|
69
|
-
}
|
|
70
|
-
finally {
|
|
71
|
-
release();
|
|
72
|
-
}
|
|
73
|
-
};
|
|
65
|
+
const enqueue = (work) => acquire().then(work).finally(release);
|
|
66
|
+
const enqueueHash = (password) => enqueue(() => hashPassword(password));
|
|
74
67
|
return {
|
|
75
|
-
hash: (password) =>
|
|
76
|
-
|
|
68
|
+
hash: async (password) => enqueueHash(password),
|
|
69
|
+
enqueueHash,
|
|
70
|
+
verify: async (password, hash) => enqueue(() => verifyPassword(password, hash)),
|
|
77
71
|
};
|
|
78
72
|
};
|
|
@@ -10,6 +10,7 @@ export declare const isNonPublicAddress: (address: string) => boolean;
|
|
|
10
10
|
/**
|
|
11
11
|
* Creates the middleware of the check. It never answers and never fails the request; each kind of warning is logged
|
|
12
12
|
* at most once by this middleware (so once per router), with the field `proxyCheck` and no address.
|
|
13
|
+
* Logger errors and rejections are ignored.
|
|
13
14
|
*
|
|
14
15
|
* @param logOf - the logger of the request (`req.log` of `@mielk/http` or the logger of the configuration).
|
|
15
16
|
*/
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* requests would turn a wrong setting into an outage.
|
|
14
14
|
*/
|
|
15
15
|
import { BlockList, isIP } from 'node:net';
|
|
16
|
+
import { logWarning } from './safe-log.js';
|
|
16
17
|
/** Loopback, private, link-local and shared (carrier-grade NAT) ranges: not the address of a client on the Internet. */
|
|
17
18
|
const NON_PUBLIC = new BlockList();
|
|
18
19
|
for (const [network, prefix] of [
|
|
@@ -60,6 +61,7 @@ const warningOf = (req) => {
|
|
|
60
61
|
/**
|
|
61
62
|
* Creates the middleware of the check. It never answers and never fails the request; each kind of warning is logged
|
|
62
63
|
* at most once by this middleware (so once per router), with the field `proxyCheck` and no address.
|
|
64
|
+
* Logger errors and rejections are ignored.
|
|
63
65
|
*
|
|
64
66
|
* @param logOf - the logger of the request (`req.log` of `@mielk/http` or the logger of the configuration).
|
|
65
67
|
*/
|
|
@@ -70,7 +72,7 @@ export const createProxyCheck = (logOf) => {
|
|
|
70
72
|
const warning = warningOf(req);
|
|
71
73
|
if (warning !== undefined && !warned.has(warning)) {
|
|
72
74
|
warned.add(warning);
|
|
73
|
-
logOf(req)
|
|
75
|
+
logWarning(logOf(req), { proxyCheck: warning }, MESSAGES[warning]);
|
|
74
76
|
}
|
|
75
77
|
}
|
|
76
78
|
next();
|
package/dist/server/router.js
CHANGED
|
@@ -42,7 +42,7 @@ const contextOf = (req, fallback) => {
|
|
|
42
42
|
* it is logged once, if the logger allows.
|
|
43
43
|
*/
|
|
44
44
|
const detach = (work, ctx) => {
|
|
45
|
-
work.catch((err) => {
|
|
45
|
+
void work.catch((err) => {
|
|
46
46
|
logError(ctx.log, safeErrorInfo(err), 'The work after the answer failed.');
|
|
47
47
|
});
|
|
48
48
|
};
|
|
@@ -104,7 +104,7 @@ export const createAuthRouter = ({ config, service, limits, authMiddleware }) =>
|
|
|
104
104
|
await limits.clearLoginCounters(req, email);
|
|
105
105
|
}
|
|
106
106
|
catch (err) {
|
|
107
|
-
contextOf(req, config.logger).log
|
|
107
|
+
logError(contextOf(req, config.logger).log, safeErrorInfo(err), 'The login counters could not be cleared in Redis; the login is rejected.');
|
|
108
108
|
throw new HttpError(HttpResponseStatus.SERVICE_UNAVAILABLE);
|
|
109
109
|
}
|
|
110
110
|
};
|
|
@@ -138,13 +138,11 @@ export const createAuthRouter = ({ config, service, limits, authMiddleware }) =>
|
|
|
138
138
|
const loginGuards = [loginIpGuard, json, withBody(loginBodySchema), ...loginBodyGuards];
|
|
139
139
|
// --- Web client -----------------------------------------------------------------------------------------------
|
|
140
140
|
// 202 without a body for a new and for a registered e-mail alike, so the answer does not reveal an account (audit S3).
|
|
141
|
-
router.post('/register', limits.register, json, withBody(registerBodySchema),
|
|
141
|
+
router.post('/register', limits.register, json, withBody(registerBodySchema), (req, res) => {
|
|
142
142
|
const { email, password, client } = body(res);
|
|
143
143
|
const ctx = contextOf(req, config.logger);
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
// new and a registered address (r1:U1). Its failures are logged; a rejection is caught by `detach` (r2:U1).
|
|
147
|
-
detach(delivery, ctx);
|
|
144
|
+
// Reserve hashing capacity before 202. The account work runs in the promise after the response.
|
|
145
|
+
detach(service.register(email, password, client ?? 'web', ctx).then(({ delivery }) => delivery), ctx);
|
|
148
146
|
res.status(HttpResponseStatus.ACCEPTED.code).end();
|
|
149
147
|
});
|
|
150
148
|
/**
|
|
@@ -261,7 +259,7 @@ export const createAuthRouter = ({ config, service, limits, authMiddleware }) =>
|
|
|
261
259
|
await limits.clearPasswordChecks(userId);
|
|
262
260
|
}
|
|
263
261
|
catch (err) {
|
|
264
|
-
contextOf(req, config.logger).log
|
|
262
|
+
logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The counter of password checks could not be cleared in Redis.');
|
|
265
263
|
}
|
|
266
264
|
};
|
|
267
265
|
// The limit of password checks comes after authMiddleware (it keys on the user) and before the parser and bcrypt.
|
|
@@ -319,7 +317,7 @@ export const createAuthRouter = ({ config, service, limits, authMiddleware }) =>
|
|
|
319
317
|
await limits.clearEmailLock(user.email);
|
|
320
318
|
}
|
|
321
319
|
catch (err) {
|
|
322
|
-
contextOf(req, config.logger).log
|
|
320
|
+
logWarning(contextOf(req, config.logger).log, safeErrorInfo(err), 'The lock of the e-mail could not be removed in Redis after a password reset.');
|
|
323
321
|
}
|
|
324
322
|
noContent(res);
|
|
325
323
|
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AuthLogger } from './config.js';
|
|
2
|
+
/**
|
|
3
|
+
* Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
|
|
4
|
+
* method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
|
|
5
|
+
* become an unhandled rejection that ends the process of Node.js after the answer.
|
|
6
|
+
*/
|
|
7
|
+
export declare const logError: (log: AuthLogger | undefined, info: object, message: string) => void;
|
|
8
|
+
/** Logs a warning with the same protection against a failing logger as `logError`. */
|
|
9
|
+
export declare const logWarning: (log: AuthLogger | undefined, info: object, message: string) => void;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
|
|
3
|
+
* method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
|
|
4
|
+
* become an unhandled rejection that ends the process of Node.js after the answer.
|
|
5
|
+
*/
|
|
6
|
+
export const logError = (log, info, message) => {
|
|
7
|
+
logSafely(log, 'error', info, message);
|
|
8
|
+
};
|
|
9
|
+
/** Logs a warning with the same protection against a failing logger as `logError`. */
|
|
10
|
+
export const logWarning = (log, info, message) => {
|
|
11
|
+
logSafely(log, 'warn', info, message);
|
|
12
|
+
};
|
|
13
|
+
const logSafely = (log, level, info, message) => {
|
|
14
|
+
try {
|
|
15
|
+
const result = log?.[level](info, message);
|
|
16
|
+
// A logger that is declared to return `void` may return a promise anyway: the cast only reads `then`, and the check is the `typeof`.
|
|
17
|
+
if (typeof result?.then === 'function') {
|
|
18
|
+
result.then(undefined, () => undefined);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// The logger itself fails: nothing else could report it, the process goes on.
|
|
23
|
+
}
|
|
24
|
+
};
|
package/dist/server/service.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { AuthLogger } from './config.js';
|
|
|
7
7
|
import type { AuthCore } from './core.js';
|
|
8
8
|
import type { AuthUser, ClientKind, UserId } from './ports.js';
|
|
9
9
|
import type { IssuedRefreshToken } from './refresh-token.js';
|
|
10
|
+
export { logError, logWarning } from './safe-log.js';
|
|
10
11
|
/** Context of one request that the operations need: the language of the e-mails and where failures are logged. */
|
|
11
12
|
export type RequestContext = {
|
|
12
13
|
/** Language of the e-mails, e.g. `pl` or `en-GB`. */
|
|
@@ -35,14 +36,6 @@ export type ErrorCategory = 'link_delivery' | 'library_error' | 'unexpected_erro
|
|
|
35
36
|
export declare const safeErrorInfo: (err: unknown) => {
|
|
36
37
|
errorCategory: ErrorCategory;
|
|
37
38
|
};
|
|
38
|
-
/**
|
|
39
|
-
* Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
|
|
40
|
-
* method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
|
|
41
|
-
* become an unhandled rejection that ends the process of Node.js after the answer.
|
|
42
|
-
*/
|
|
43
|
-
export declare const logError: (log: AuthLogger | undefined, info: object, message: string) => void;
|
|
44
|
-
/** Logs a warning with the same protection against a failing logger as `logError`. */
|
|
45
|
-
export declare const logWarning: (log: AuthLogger | undefined, info: object, message: string) => void;
|
|
46
39
|
/** Result of a login. */
|
|
47
40
|
export type LoginResult = {
|
|
48
41
|
user: AuthUser;
|
|
@@ -66,13 +59,15 @@ export type RegisterResult = {
|
|
|
66
59
|
export type AuthService = {
|
|
67
60
|
/**
|
|
68
61
|
* Creates the account and sends the verification link. For an e-mail that is registered already it creates nothing,
|
|
69
|
-
* changes nothing and sends the account the `account_exists` message with a password reset link instead
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
62
|
+
* changes nothing and sends the account the `account_exists` message with a password reset link instead (audit S3).
|
|
63
|
+
* Reserves hashing capacity synchronously so the router can answer before account storage (TASK-393). The promise
|
|
64
|
+
* resolves after hashing and attempting to create the account. Reading the existing account, applying its limit and
|
|
65
|
+
* sending mail run in `delivery`.
|
|
73
66
|
* A failure of `delivery` is logged and does not fail the registration (the link can be requested again); a
|
|
74
67
|
* logger that throws or rejects is ignored (r3:U1). A caller that does not await it should still catch any other
|
|
75
68
|
* rejection (r2:U1).
|
|
69
|
+
*
|
|
70
|
+
* @throws `PasswordHashingBusyError` synchronously when hashing capacity is full.
|
|
76
71
|
*/
|
|
77
72
|
register(email: string, password: string, client: ClientKind, ctx: RequestContext): Promise<RegisterResult>;
|
|
78
73
|
/**
|
package/dist/server/service.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { AuthError, CurrentPasswordInvalidError, EmailTakenError, InvalidAccessTokenError, InvalidAuthTokenError, InvalidCredentialsError, } from './errors.js';
|
|
2
2
|
import { buildAuthLink } from './one-time-token.js';
|
|
3
|
+
import { logError } from './safe-log.js';
|
|
4
|
+
export { logError, logWarning } from './safe-log.js';
|
|
3
5
|
/**
|
|
4
6
|
* Failure of the mailer. It carries no cause, message, name or address of the original error: the errors of mail ports
|
|
5
7
|
* tend to quote the recipient or the link with the token, and their names are chosen by foreign code, so only a fixed
|
|
@@ -25,30 +27,6 @@ export const safeErrorInfo = (err) => ({
|
|
|
25
27
|
? 'library_error'
|
|
26
28
|
: 'unexpected_error',
|
|
27
29
|
});
|
|
28
|
-
/**
|
|
29
|
-
* Logs a failure without letting the logger fail the work (r3:U1): a logger that throws is ignored, and so is one whose
|
|
30
|
-
* method returns a promise that rejects (an `async` method fits the `void` contract of `AuthLogger`), so neither can
|
|
31
|
-
* become an unhandled rejection that ends the process of Node.js after the answer.
|
|
32
|
-
*/
|
|
33
|
-
export const logError = (log, info, message) => {
|
|
34
|
-
logSafely(log, 'error', info, message);
|
|
35
|
-
};
|
|
36
|
-
/** Logs a warning with the same protection against a failing logger as `logError`. */
|
|
37
|
-
export const logWarning = (log, info, message) => {
|
|
38
|
-
logSafely(log, 'warn', info, message);
|
|
39
|
-
};
|
|
40
|
-
const logSafely = (log, level, info, message) => {
|
|
41
|
-
try {
|
|
42
|
-
const result = log?.[level](info, message);
|
|
43
|
-
// A logger that is declared to return `void` may return a promise anyway: the cast only reads `then`, and the check is the `typeof`.
|
|
44
|
-
if (typeof result?.then === 'function') {
|
|
45
|
-
result.then(undefined, () => undefined);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
catch {
|
|
49
|
-
// The logger itself fails: nothing else could report it, the process goes on.
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
30
|
/** Creates the service on the core of the library. */
|
|
53
31
|
export const createAuthService = (core, options = {}) => {
|
|
54
32
|
const { config, accessTokens, refreshTokens, oneTimeTokens, passwords } = core;
|
|
@@ -125,8 +103,7 @@ export const createAuthService = (core, options = {}) => {
|
|
|
125
103
|
}
|
|
126
104
|
};
|
|
127
105
|
return {
|
|
128
|
-
register:
|
|
129
|
-
const passwordHash = await passwords.hash(password);
|
|
106
|
+
register: (email, password, client, ctx) => passwords.enqueueHash(password).then(async (passwordHash) => {
|
|
130
107
|
let user = null;
|
|
131
108
|
try {
|
|
132
109
|
user = await repository.createUser({ email, passwordHash, createdAt: clock.now() });
|
|
@@ -136,14 +113,11 @@ export const createAuthService = (core, options = {}) => {
|
|
|
136
113
|
throw err;
|
|
137
114
|
}
|
|
138
115
|
}
|
|
139
|
-
// The answer waits for the same steps in both cases; what differs (the token and the mailer for a new
|
|
140
|
-
// account; the reading of the account, the limit and the mailer for a taken address, whose owner gets a
|
|
141
|
-
// reset link, audit S3) runs on in `delivery`, not awaited here (r1:U1).
|
|
142
116
|
const delivery = user === null
|
|
143
117
|
? trySendAccountNotice(email, client, ctx)
|
|
144
118
|
: trySendLink(user, 'email_verification', client, ctx);
|
|
145
119
|
return { delivery };
|
|
146
|
-
},
|
|
120
|
+
}),
|
|
147
121
|
login: async (email, password, clientKind, afterPasswordCheck) => {
|
|
148
122
|
const found = await repository.findUserByEmail(email);
|
|
149
123
|
// The password is checked before the transaction, so no connection and no lock of the user wait for bcrypt
|