@jskit-ai/auth-provider-local-core 0.2.34 → 0.2.35
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 +5 -0
- package/package.json +1 -1
- package/src/server/lib/accounts.js +26 -4
- package/src/server/lib/deliveries.js +72 -0
- package/src/server/lib/emailConfirmation.js +38 -11
- package/src/server/lib/index.js +1 -0
- package/src/server/lib/passwordFlows.js +42 -16
- package/src/server/lib/service.js +8 -0
- package/src/server/providers/AuthLocalProvider.js +18 -0
- package/src/server/types.js +1 -0
- package/test/accountEnumeration.test.js +154 -0
- package/test/deliveries.test.js +134 -0
- package/test/providerRuntime.test.js +57 -9
- package/test-support/emailConfirmationScenario.js +12 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Security: asking for a password reset (`requestPasswordReset`) or a new confirmation link (`resendRegisterConfirmation`) no longer tells, by how long it takes, which emails have an account or a waiting registration. Both answered the same text for any email, but only for one with an account did they write a new link and wait for the sender, so the time of the answer showed whether the account existed, and a sender's failure reached only an account's requester. Each now validates the email, answers at once, and then looks the account up, writes the link and calls the sender; a sender's rejection is logged as an error with the address (never the link) instead of answered. The email is still sent, rate limits and texts are unchanged, and a stopping server (`AuthLocalProvider` now has a shutdown) waits up to 10 seconds for the emails still being sent. Development's `AUTH_LOCAL_RECOVERY_DEV_OUTPUT=response` and a confirmation link shown in development's answer still find the account first, since their answer carries the link; a new registration's link is still sent before its answer, which already says whether the email is taken. Upgrading: an application whose recovery sender reported delivery failures to the requester (a 502 or 503 from `requestPasswordReset`) now has them only in its log; a test that composes `createLocalAuthService()` and reads the sent email waits for it, passing `deliveries: createLocalDeliveries({ logger })` (new export) and awaiting `deliveries.settled()`.
|
|
6
|
+
- Security: a failed sign-in takes as long whether or not its email has a password to check. A sign-in for an unknown email, a disabled account or one created through a provider checked no password, while one for an account with a password ran the password strategy's check (scrypt by default), so its time showed which emails had accounts. It now checks the password against a record made once from a random password, through the application's password strategy. Answers, the sign-in throttle and successful sign-ins are unchanged.
|
|
7
|
+
|
|
8
|
+
- An account made by an email confirmation link has its email confirmed: `confirmRegistration` creates it with `emailVerifiedAt`, the moment its link was used, which the link sent to the email proves, and the database backend keeps it (the file backend keeps no confirmation time, as before). Until now only `auth.local.accounts.markEmailVerified` set it, so every account confirmed by link read as unconfirmed (`emailVerifiedAt` "").
|
|
9
|
+
|
|
5
10
|
- The pass comes from `@jskit-ai/auth-pass/server`, a new dependency, instead of auth-core's removed `./server/passSignIn`; `AuthLocalPassIdentity` takes auth-pass's `AuthPass`. Pass sign-in behaves as before, with the same refusals and texts.
|
|
6
11
|
|
|
7
12
|
- One-time pass sign-in: with `AUTH_PASS_PUBLIC_KEY`, `AUTH_PASS_AUDIENCE` and `AUTH_PASS_RESOURCE` set, `signInWithPass({ pass })` checks a pass from `@jskit-ai/auth-core/server/passSignIn`, records it as used, and signs in the account the new `auth.local.pass-identity` capability names for it (`AuthLocalPassIdentity`, also `createLocalAuthService({ passIdentity })`); startup stops when the key is set and no mapping is installed. Each pass signs in once: the backend contract gains `passes.use({ id, expiresAt })` and `passes.deleteExpired(now)`, keyed by the hash of the pass's id and kept until 30 seconds after it expires, and the file backend keeps them in `passes.passwd`. Without the key, `signInWithPass` is refused as unsupported and nothing else changes.
|
package/package.json
CHANGED
|
@@ -6,7 +6,7 @@ import { AUTH_TEXTS, authFieldErrorDetails, createAuthError } from "@jskit-ai/au
|
|
|
6
6
|
import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
|
|
7
7
|
import { DEV_AUTH_SESSION_PURPOSE, buildAuthPayload, buildAuthResult, buildProfileChangePayload, findExistingAppProfile } from "./authPayloads.js";
|
|
8
8
|
import { forgottenFailuresBefore, recordSignInFailure, signInLockedError, signInWaitMs } from "./signInThrottle.js";
|
|
9
|
-
import { createId } from "./tokens.js";
|
|
9
|
+
import { createId, randomToken } from "./tokens.js";
|
|
10
10
|
|
|
11
11
|
/** An account created through a provider has no password until recovery sets one. */
|
|
12
12
|
const NO_PASSWORD = Object.freeze({ algorithm: "", version: "", salt: "", hash: "" });
|
|
@@ -210,10 +210,24 @@ function createLocalAccounts({
|
|
|
210
210
|
};
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
+
// The record a sign-in checks its password against when its email has no password to check, made once from a
|
|
214
|
+
// random password nobody knows. A rejected one is not kept, so the next sign-in makes it again.
|
|
215
|
+
let unmatchable = null;
|
|
216
|
+
function unmatchableRecord() {
|
|
217
|
+
unmatchable ??= passwords.hashPassword(randomToken(32)).catch((error) => {
|
|
218
|
+
unmatchable = null;
|
|
219
|
+
throw error;
|
|
220
|
+
});
|
|
221
|
+
return unmatchable;
|
|
222
|
+
}
|
|
223
|
+
|
|
213
224
|
/**
|
|
214
225
|
* Signs in with a password. Each account's failures are counted, whether or
|
|
215
226
|
* not the account exists, so the wait they cause says nothing about which
|
|
216
|
-
* accounts exist; while an account waits its password is not checked.
|
|
227
|
+
* accounts exist; while an account waits its password is not checked. Nor
|
|
228
|
+
* does a failure's time: a sign-in whose email has no password to check (no
|
|
229
|
+
* account, a disabled one, or one created through a provider) checks the
|
|
230
|
+
* password against one nobody knows, as long as checking a wrong one takes. A
|
|
217
231
|
* successful sign-in, or a password reset, forgets the failures.
|
|
218
232
|
*/
|
|
219
233
|
async function login(input) {
|
|
@@ -226,13 +240,21 @@ function createLocalAccounts({
|
|
|
226
240
|
if (waitMs > 0) {
|
|
227
241
|
return { waitMs };
|
|
228
242
|
}
|
|
243
|
+
let checked = false;
|
|
244
|
+
const passwordMatches = (record) => {
|
|
245
|
+
checked = true;
|
|
246
|
+
return passwords.verifyPassword(password, record);
|
|
247
|
+
};
|
|
229
248
|
const user = await tx.users.findByEmail(email);
|
|
230
249
|
// Whatever config.emailConfirmation says now: a registration made while it was on still waits.
|
|
231
250
|
if (!user && (await emailConfirmation.isWaitingWithPassword(tx, email, (registration) =>
|
|
232
|
-
|
|
251
|
+
passwordMatches(registration.password)))) {
|
|
233
252
|
return { unconfirmed: true };
|
|
234
253
|
}
|
|
235
|
-
if (!user || user.disabled || !hasPassword(user) || !(await
|
|
254
|
+
if (!user || user.disabled || !hasPassword(user) || !(await passwordMatches(user.password))) {
|
|
255
|
+
if (!checked) {
|
|
256
|
+
await passwords.verifyPassword(password, await unmatchableRecord());
|
|
257
|
+
}
|
|
236
258
|
await tx.signInFailures.deleteBefore(forgottenFailuresBefore(now));
|
|
237
259
|
await tx.signInFailures.save(recordSignInFailure(config.signInThrottle, failures, email, now));
|
|
238
260
|
return { failed: true };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How long a stopping server waits for the emails local auth is still sending, before it stops anyway.
|
|
3
|
+
*/
|
|
4
|
+
const DELIVERY_SHUTDOWN_WAIT_MS = 10_000;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The emails local auth sends after answering the request that asked for them. Asking for a password reset, or for a
|
|
8
|
+
* new confirmation link, answers the same whether or not the email has an account or a waiting registration, so the
|
|
9
|
+
* answer must not wait on work done only when it has one: looking it up and writing a new link differ in time, and
|
|
10
|
+
* the sender's own time and failures differ most. That work runs here instead, once the request has answered. Each
|
|
11
|
+
* piece starts at once; its failure is logged, never the link it carries, and is not the requester's to see. A
|
|
12
|
+
* stopping server waits for the emails still being sent (settled).
|
|
13
|
+
* @param {object} dependencies
|
|
14
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
15
|
+
*/
|
|
16
|
+
function createLocalDeliveries({ logger }) {
|
|
17
|
+
const sending = new Set();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Starts sending one email, after the request that asked for it has answered.
|
|
21
|
+
* @param {string} what The email, for the log: "the password reset email".
|
|
22
|
+
* @param {string} email The address it goes to, for the log.
|
|
23
|
+
* @param {() => Promise<void>} work Finds what the email needs, and sends it when there is something to send.
|
|
24
|
+
*/
|
|
25
|
+
function send(what, email, work) {
|
|
26
|
+
const delivery = Promise.resolve()
|
|
27
|
+
.then(work)
|
|
28
|
+
.catch((error) => {
|
|
29
|
+
logger.error({ err: error, email }, `Sending ${what} failed.`);
|
|
30
|
+
})
|
|
31
|
+
.finally(() => {
|
|
32
|
+
sending.delete(delivery);
|
|
33
|
+
});
|
|
34
|
+
sending.add(delivery);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Waits for the emails being sent, those they start included, for at most `timeoutMs` when it is given; true when
|
|
39
|
+
* every one finished, false when some were still being sent, which is logged.
|
|
40
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
41
|
+
*/
|
|
42
|
+
async function settled({ timeoutMs } = {}) {
|
|
43
|
+
let timer = null;
|
|
44
|
+
const timedOut = timeoutMs === undefined
|
|
45
|
+
? null
|
|
46
|
+
: new Promise((resolve) => {
|
|
47
|
+
timer = setTimeout(resolve, timeoutMs, false);
|
|
48
|
+
});
|
|
49
|
+
try {
|
|
50
|
+
while (sending.size > 0) {
|
|
51
|
+
const finished = Promise.all(sending).then(() => true);
|
|
52
|
+
if (!(await (timedOut ? Promise.race([finished, timedOut]) : finished))) {
|
|
53
|
+
logger.warn(
|
|
54
|
+
{ unfinishedEmails: sending.size },
|
|
55
|
+
"Local auth stopped waiting for the emails it was still sending; they may not arrive."
|
|
56
|
+
);
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return true;
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return Object.freeze({
|
|
67
|
+
send,
|
|
68
|
+
settled
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export { DELIVERY_SHUTDOWN_WAIT_MS, createLocalDeliveries };
|
|
@@ -87,6 +87,8 @@ function confirmationPasswordInvalidError() {
|
|
|
87
87
|
* @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
|
|
88
88
|
* `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender;
|
|
89
89
|
* in development without a sender, links also go in the response.
|
|
90
|
+
* @param {import("../types.js").AuthLocalDeliveries} dependencies.deliveries Sends each new
|
|
91
|
+
* link a resend asks for after its request has answered.
|
|
90
92
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
91
93
|
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
92
94
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
@@ -97,6 +99,7 @@ function createLocalEmailConfirmation({
|
|
|
97
99
|
config,
|
|
98
100
|
confirmationMode,
|
|
99
101
|
confirmationSender,
|
|
102
|
+
deliveries,
|
|
100
103
|
firstAccountSetup,
|
|
101
104
|
invitationContextResolver,
|
|
102
105
|
logger,
|
|
@@ -195,11 +198,13 @@ function createLocalEmailConfirmation({
|
|
|
195
198
|
if (await tx.users.findByEmail(registration.email)) {
|
|
196
199
|
return { taken: true };
|
|
197
200
|
}
|
|
201
|
+
// The link was sent to the email, so using it confirms the email.
|
|
198
202
|
const user = await tx.users.create({
|
|
199
203
|
id: createId("usr"),
|
|
200
204
|
email: registration.email,
|
|
201
205
|
displayName: registration.displayName,
|
|
202
|
-
password: registration.password
|
|
206
|
+
password: registration.password,
|
|
207
|
+
emailVerifiedAt: new Date().toISOString()
|
|
203
208
|
});
|
|
204
209
|
return { user, session: await sessions.createSessionForUser(tx, user) };
|
|
205
210
|
});
|
|
@@ -215,14 +220,10 @@ function createLocalEmailConfirmation({
|
|
|
215
220
|
}
|
|
216
221
|
|
|
217
222
|
/**
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
* registration no longer waits: it registers again. The answer is the same
|
|
221
|
-
* whether or not a registration waits for that email.
|
|
222
|
-
* @param {{ email: string }} input
|
|
223
|
+
* A new link's code for the registration waiting for this email, replacing its old link; "" when none waits.
|
|
224
|
+
* @param {string} email
|
|
223
225
|
*/
|
|
224
|
-
async function
|
|
225
|
-
const email = validateEmailInput(input.email);
|
|
226
|
+
async function renewLink(email) {
|
|
226
227
|
const { token, tokenHash, expiresAt } = newConfirmation();
|
|
227
228
|
const renewed = await backend.withTransaction(async (tx) => {
|
|
228
229
|
const registration = await tx.registrations.findByEmail(email);
|
|
@@ -232,13 +233,39 @@ function createLocalEmailConfirmation({
|
|
|
232
233
|
await tx.registrations.save({ ...registration, tokenHash, expiresAt });
|
|
233
234
|
return true;
|
|
234
235
|
});
|
|
235
|
-
return
|
|
236
|
+
return renewed ? token : "";
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Sends a waiting registration a new link, which replaces the old one; the
|
|
241
|
+
* registration, its password included, stays as it is. An expired
|
|
242
|
+
* registration no longer waits: it registers again. The answer is the same,
|
|
243
|
+
* at once, whether or not a registration waits for that email: the
|
|
244
|
+
* registration is looked up, and its link renewed and emailed, after the
|
|
245
|
+
* answer (deliveries), and a sender's failure is logged instead.
|
|
246
|
+
* Development's `dev-response` delivery puts the link in the answer instead,
|
|
247
|
+
* so it renews the link first.
|
|
248
|
+
* @param {{ email: string }} input
|
|
249
|
+
*/
|
|
250
|
+
async function resend(input) {
|
|
251
|
+
const email = validateEmailInput(input.email);
|
|
252
|
+
const resent = {
|
|
236
253
|
ok: true,
|
|
237
254
|
message: "If a registration is waiting for that email, a new confirmation link has been sent.",
|
|
238
255
|
messageCode: "auth.local.register.confirmationResent",
|
|
239
|
-
messageParams: {}
|
|
240
|
-
...(renewed ? await deliver(email, token) : {})
|
|
256
|
+
messageParams: {}
|
|
241
257
|
};
|
|
258
|
+
if (confirmationDelivery === "dev-response") {
|
|
259
|
+
const token = await renewLink(email);
|
|
260
|
+
return { ...resent, ...(token ? await deliver(email, token) : {}) };
|
|
261
|
+
}
|
|
262
|
+
deliveries.send("the email confirmation email", email, async () => {
|
|
263
|
+
const token = await renewLink(email);
|
|
264
|
+
if (token) {
|
|
265
|
+
await deliver(email, token);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
return resent;
|
|
242
269
|
}
|
|
243
270
|
|
|
244
271
|
/**
|
package/src/server/lib/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createLocalAuthService } from "./service.js";
|
|
2
|
+
export { createLocalDeliveries } from "./deliveries.js";
|
|
2
3
|
export { resolveLocalAuthConfig } from "./config.js";
|
|
3
4
|
export { createLoggedConfirmationSender } from "./emailConfirmation.js";
|
|
4
5
|
export { createLoggedRecoverySender } from "./passwordFlows.js";
|
|
@@ -46,46 +46,72 @@ function createSimulatedRecoverySender(logger) {
|
|
|
46
46
|
* @param {object} dependencies
|
|
47
47
|
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
48
48
|
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
49
|
+
* @param {import("../types.js").AuthLocalDeliveries} dependencies.deliveries Sends each
|
|
50
|
+
* recovery email after its request has answered.
|
|
49
51
|
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
50
52
|
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
51
53
|
* @param {import("../types.js").AuthLocalRecoverySender} dependencies.recoverySender Sends each recovery
|
|
52
54
|
* link, except when the configuration returns it in the response.
|
|
53
55
|
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
54
56
|
*/
|
|
55
|
-
function createLocalPasswordFlows({ backend, config, passwords, profileProjector, recoverySender, sessions }) {
|
|
57
|
+
function createLocalPasswordFlows({ backend, config, deliveries, passwords, profileProjector, recoverySender, sessions }) {
|
|
56
58
|
const { recoveryEnabled } = config;
|
|
57
59
|
const recoveryInResponse = config.recoveryDelivery === "dev-response";
|
|
58
60
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
/**
|
|
62
|
+
* A new recovery link for the account of this email, its token kept only as a hash; "" when no account can
|
|
63
|
+
* recover with it.
|
|
64
|
+
* @param {string} email
|
|
65
|
+
*/
|
|
66
|
+
async function createRecoveryUrl(email) {
|
|
67
|
+
const token = randomToken(32);
|
|
68
|
+
const created = await backend.withTransaction(async (tx) => {
|
|
66
69
|
const user = await tx.users.findByEmail(email);
|
|
67
70
|
if (!user || user.disabled) {
|
|
68
|
-
return;
|
|
71
|
+
return false;
|
|
69
72
|
}
|
|
70
|
-
const token = randomToken(32);
|
|
71
|
-
recoveryUrl = `${config.appPublicUrl.replace(/\/$/, "")}/auth/reset-password?token=${encodeURIComponent(token)}&type=recovery`;
|
|
72
73
|
await tx.recovery.create({
|
|
73
74
|
id: createId(RESET_TOKEN_KIND),
|
|
74
75
|
userId: user.id,
|
|
75
76
|
tokenHash: sha256Base64url(token),
|
|
76
77
|
expiresAt: isoFromNow(RECOVERY_TOKEN_TTL_SECONDS)
|
|
77
78
|
});
|
|
79
|
+
return true;
|
|
78
80
|
});
|
|
79
|
-
|
|
80
|
-
|
|
81
|
+
return created
|
|
82
|
+
? `${config.appPublicUrl.replace(/\/$/, "")}/auth/reset-password?token=${encodeURIComponent(token)}&type=recovery`
|
|
83
|
+
: "";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Answers the same, at once, whether or not the email has an account: the account is looked up, and its link made
|
|
88
|
+
* and emailed, after the answer (deliveries), so neither the answer nor its time says which emails have accounts,
|
|
89
|
+
* and a sender's failure is logged instead. Development's `dev-response` delivery puts the link in the answer
|
|
90
|
+
* instead, so it finds the account first.
|
|
91
|
+
* @param {{ email: string }} input
|
|
92
|
+
*/
|
|
93
|
+
async function requestPasswordReset(input) {
|
|
94
|
+
if (!recoveryEnabled) {
|
|
95
|
+
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
81
96
|
}
|
|
82
|
-
|
|
97
|
+
const email = validateEmailInput(input.email);
|
|
98
|
+
const requested = {
|
|
83
99
|
ok: true,
|
|
84
100
|
message: "If an account exists for that email, password reset instructions have been sent.",
|
|
85
101
|
messageCode: "auth.local.recovery.requested",
|
|
86
|
-
messageParams: {}
|
|
87
|
-
...(recoveryUrl && recoveryInResponse ? { recoveryUrl } : {})
|
|
102
|
+
messageParams: {}
|
|
88
103
|
};
|
|
104
|
+
if (recoveryInResponse) {
|
|
105
|
+
const recoveryUrl = await createRecoveryUrl(email);
|
|
106
|
+
return { ...requested, ...(recoveryUrl ? { recoveryUrl } : {}) };
|
|
107
|
+
}
|
|
108
|
+
deliveries.send("the password reset email", email, async () => {
|
|
109
|
+
const recoveryUrl = await createRecoveryUrl(email);
|
|
110
|
+
if (recoveryUrl) {
|
|
111
|
+
await recoverySender({ email, recoveryUrl });
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
return requested;
|
|
89
115
|
}
|
|
90
116
|
|
|
91
117
|
async function completePasswordRecovery(input) {
|
|
@@ -4,6 +4,7 @@ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
|
4
4
|
import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
|
|
5
5
|
import { createLocalAccounts } from "./accounts.js";
|
|
6
6
|
import { PROVIDER_ID } from "./authPayloads.js";
|
|
7
|
+
import { createLocalDeliveries } from "./deliveries.js";
|
|
7
8
|
import { confirmEveryRegistrationByLink, createLocalEmailConfirmation } from "./emailConfirmation.js";
|
|
8
9
|
import { createFirstAccountSetup } from "./firstAccountSetup.js";
|
|
9
10
|
import { createLocalOAuthFlows } from "./oauthFlows.js";
|
|
@@ -41,6 +42,9 @@ const NO_PASS_SIGN_IN = Object.freeze({
|
|
|
41
42
|
* `auth.local.confirmation-mode`; by default every registration waits for its link.
|
|
42
43
|
* @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
|
|
43
44
|
* `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender.
|
|
45
|
+
* @param {import("../types.js").AuthLocalDeliveries} [dependencies.deliveries] Sends the password reset and new
|
|
46
|
+
* confirmation link emails after their requests have answered; by default, its own, whose settled() nothing waits
|
|
47
|
+
* for. The provider passes the one its shutdown waits for.
|
|
44
48
|
* @param {import("../types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup] The first
|
|
45
49
|
* account's setup code, already started by the provider; by default, one that starts on first use.
|
|
46
50
|
* @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
|
|
@@ -61,6 +65,7 @@ function createLocalAuthService({
|
|
|
61
65
|
config,
|
|
62
66
|
confirmationMode = confirmEveryRegistrationByLink,
|
|
63
67
|
confirmationSender,
|
|
68
|
+
deliveries: givenDeliveries = null,
|
|
64
69
|
firstAccountSetup: givenFirstAccountSetup = null,
|
|
65
70
|
invitationContextResolver,
|
|
66
71
|
logger,
|
|
@@ -72,6 +77,7 @@ function createLocalAuthService({
|
|
|
72
77
|
}) {
|
|
73
78
|
const passwords = normalizePasswordStrategy(passwordStrategy);
|
|
74
79
|
const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
|
|
80
|
+
const deliveries = givenDeliveries ?? createLocalDeliveries({ logger });
|
|
75
81
|
const oauthProvidersById = new Map(config.oauthProviders.map((provider) => [provider.id, provider]));
|
|
76
82
|
const { oauthEnabled, recoveryEnabled } = config;
|
|
77
83
|
const appProfileProjection = profileProjector !== noAppProfiles;
|
|
@@ -131,6 +137,7 @@ function createLocalAuthService({
|
|
|
131
137
|
config,
|
|
132
138
|
confirmationMode,
|
|
133
139
|
confirmationSender,
|
|
140
|
+
deliveries,
|
|
134
141
|
firstAccountSetup,
|
|
135
142
|
invitationContextResolver,
|
|
136
143
|
logger,
|
|
@@ -152,6 +159,7 @@ function createLocalAuthService({
|
|
|
152
159
|
const passwordFlows = createLocalPasswordFlows({
|
|
153
160
|
backend,
|
|
154
161
|
config,
|
|
162
|
+
deliveries,
|
|
155
163
|
passwords,
|
|
156
164
|
profileProjector,
|
|
157
165
|
recoverySender,
|
|
@@ -6,6 +6,7 @@ import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
|
6
6
|
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
7
7
|
import { sideEffectsAreLive } from "@jskit-ai/kernel/shared/support/sideEffects";
|
|
8
8
|
import { resolveLocalAuthConfig } from "../lib/config.js";
|
|
9
|
+
import { DELIVERY_SHUTDOWN_WAIT_MS, createLocalDeliveries } from "../lib/deliveries.js";
|
|
9
10
|
import {
|
|
10
11
|
confirmEveryRegistrationByLink,
|
|
11
12
|
createLoggedConfirmationSender,
|
|
@@ -19,6 +20,9 @@ import { scryptPasswordStrategy } from "../lib/passwords.js";
|
|
|
19
20
|
import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
|
|
20
21
|
import { createLocalAuthService } from "../lib/service.js";
|
|
21
22
|
|
|
23
|
+
// The emails each started auth service is still sending, by the service its setup gave out, for its shutdown.
|
|
24
|
+
const deliveriesByService = new WeakMap();
|
|
25
|
+
|
|
22
26
|
const AuthLocalProvider = defineProvider({
|
|
23
27
|
id: "auth.local",
|
|
24
28
|
requires: {
|
|
@@ -93,6 +97,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
93
97
|
// A test copy (SIDE_EFFECTS is not live) logs the emails an installed sender would send, and sends none, whatever
|
|
94
98
|
// the sender. The confirmation mode sends nothing, so a test copy keeps it.
|
|
95
99
|
const live = sideEffectsAreLive(env);
|
|
100
|
+
const deliveries = createLocalDeliveries({ logger });
|
|
101
|
+
deliveriesByService.set(outputs.authService, deliveries);
|
|
96
102
|
const baseService = createLocalAuthService({
|
|
97
103
|
backend: localBackend,
|
|
98
104
|
config,
|
|
@@ -100,6 +106,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
100
106
|
confirmationSender: emailConfirmationSender
|
|
101
107
|
? (live ? confirmationSender : createSimulatedConfirmationSender(logger))
|
|
102
108
|
: createLoggedConfirmationSender(logger),
|
|
109
|
+
deliveries,
|
|
103
110
|
firstAccountSetup,
|
|
104
111
|
invitationContextResolver: extensions.resolveInvitationContextResolver(),
|
|
105
112
|
logger,
|
|
@@ -113,6 +120,17 @@ const AuthLocalProvider = defineProvider({
|
|
|
113
120
|
});
|
|
114
121
|
// readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
|
|
115
122
|
attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
|
|
123
|
+
},
|
|
124
|
+
/**
|
|
125
|
+
* Waits for the emails local auth is still sending, for a while: a reset or confirmation link asked for just
|
|
126
|
+
* before the server stops still arrives. It stops before the providers it depends on, such as the sender's. A
|
|
127
|
+
* boot that stopped before making its service sent nothing.
|
|
128
|
+
*/
|
|
129
|
+
async shutdown(_dependencies, { outputs }) {
|
|
130
|
+
const deliveries = deliveriesByService.get(outputs.authService);
|
|
131
|
+
if (deliveries) {
|
|
132
|
+
await deliveries.settled({ timeoutMs: DELIVERY_SHUTDOWN_WAIT_MS });
|
|
133
|
+
}
|
|
116
134
|
}
|
|
117
135
|
});
|
|
118
136
|
|
package/src/server/types.js
CHANGED
|
@@ -196,6 +196,7 @@
|
|
|
196
196
|
*/
|
|
197
197
|
|
|
198
198
|
/** @typedef {ReturnType<typeof import("./lib/config.js").resolveLocalAuthConfig>} AuthLocalConfig */
|
|
199
|
+
/** @typedef {ReturnType<typeof import("./lib/deliveries.js").createLocalDeliveries>} AuthLocalDeliveries */
|
|
199
200
|
/** @typedef {AuthLocalConfig["oauthProviders"][number]} AuthLocalOAuthProvider */
|
|
200
201
|
/** @typedef {ReturnType<typeof import("./lib/firstAccountSetup.js").createFirstAccountSetup>} AuthLocalFirstAccountSetup */
|
|
201
202
|
/** @typedef {ReturnType<typeof import("./lib/passwords.js").normalizePasswordStrategy>} AuthLocalPasswords */
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { createLocalAuthService, createLocalFileBackend, scryptPasswordStrategy } from "../src/server/lib/index.js";
|
|
7
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
8
|
+
|
|
9
|
+
// Asking for a password reset or a new confirmation link, and a failed sign-in, answer alike whether or not the email
|
|
10
|
+
// has an account or a waiting registration: in what they answer and in the work they do before answering, so their
|
|
11
|
+
// time does not say which emails have accounts either. These tests count that work rather than time it.
|
|
12
|
+
|
|
13
|
+
const PASSWORD = "correct horse battery staple";
|
|
14
|
+
const NOT_ANSWERED = Symbol("not answered");
|
|
15
|
+
// Each answer here is checked within this bound, so a request that waits for ever fails instead of hanging the run.
|
|
16
|
+
const BOUND = { timeout: 10_000 };
|
|
17
|
+
|
|
18
|
+
/** The file backend, and a promise for when every transaction it has started has finished. */
|
|
19
|
+
function watchedBackend(storeDir) {
|
|
20
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
21
|
+
const running = new Set();
|
|
22
|
+
return {
|
|
23
|
+
...backend,
|
|
24
|
+
withTransaction(callback) {
|
|
25
|
+
const transaction = backend.withTransaction(callback);
|
|
26
|
+
running.add(transaction);
|
|
27
|
+
transaction.then(() => running.delete(transaction), () => running.delete(transaction));
|
|
28
|
+
return transaction;
|
|
29
|
+
},
|
|
30
|
+
async idle() {
|
|
31
|
+
while (running.size > 0) {
|
|
32
|
+
await Promise.allSettled(running);
|
|
33
|
+
}
|
|
34
|
+
// Then what each transaction's caller does next, such as calling a sender, has run too.
|
|
35
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A sender that keeps each message it is given and finishes sending only the first `finishing` of them: the
|
|
42
|
+
* others never finish, as with a mail server that does not answer.
|
|
43
|
+
* @param {{ finishing?: number }} [options]
|
|
44
|
+
*/
|
|
45
|
+
function stalledSender({ finishing = 0 } = {}) {
|
|
46
|
+
const messages = [];
|
|
47
|
+
const waiting = [];
|
|
48
|
+
return {
|
|
49
|
+
messages,
|
|
50
|
+
send(message) {
|
|
51
|
+
messages.push(message);
|
|
52
|
+
for (const wake of waiting.splice(0)) wake();
|
|
53
|
+
return messages.length <= finishing ? Promise.resolve() : new Promise(() => {});
|
|
54
|
+
},
|
|
55
|
+
async received(count) {
|
|
56
|
+
while (messages.length < count) {
|
|
57
|
+
await new Promise((resolve) => waiting.push(resolve));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The answer of a request that has answered by the next turn of the event loop, or NOT_ANSWERED. */
|
|
64
|
+
function answerByNextTurn(answer) {
|
|
65
|
+
return Promise.race([answer, new Promise((resolve) => setImmediate(resolve, NOT_ANSWERED))]);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function startService(t, { env = {}, emailRecovery = false, emailConfirmationSender = false, ...overrides } = {}) {
|
|
69
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-enumeration-"));
|
|
70
|
+
const backend = watchedBackend(storeDir);
|
|
71
|
+
t.after(async () => {
|
|
72
|
+
await backend.idle();
|
|
73
|
+
await fs.rm(storeDir, { recursive: true, force: true });
|
|
74
|
+
});
|
|
75
|
+
const options = localServiceOptions({ env, emailRecovery, emailConfirmationSender });
|
|
76
|
+
return { backend, service: createLocalAuthService({ ...options, backend, ...overrides }) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
test("a password reset answers before its email is sent, and the same for an account and an unknown email", BOUND, async (t) => {
|
|
80
|
+
const sender = stalledSender();
|
|
81
|
+
const { backend, service } = await startService(t, { emailRecovery: true, recoverySender: sender.send });
|
|
82
|
+
await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
83
|
+
|
|
84
|
+
const answering = service.requestPasswordReset({ email: "ada@example.com" });
|
|
85
|
+
await sender.received(1);
|
|
86
|
+
const forAccount = await answerByNextTurn(answering);
|
|
87
|
+
assert.notEqual(forAccount, NOT_ANSWERED, "the reset waits for its email, which takes time only an account's reset takes");
|
|
88
|
+
const forNobody = await service.requestPasswordReset({ email: "nobody@example.com" });
|
|
89
|
+
assert.deepEqual(forNobody, forAccount);
|
|
90
|
+
assert.deepEqual(forAccount, {
|
|
91
|
+
ok: true,
|
|
92
|
+
message: "If an account exists for that email, password reset instructions have been sent.",
|
|
93
|
+
messageCode: "auth.local.recovery.requested",
|
|
94
|
+
messageParams: {}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// The account's email is still sent, with its link; the unknown email gets none.
|
|
98
|
+
await backend.idle();
|
|
99
|
+
assert.deepEqual(sender.messages.map(({ email }) => email), ["ada@example.com"]);
|
|
100
|
+
assert.match(sender.messages[0].recoveryUrl, /^http:\/\/localhost:5173\/auth\/reset-password\?token=/u);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("a new confirmation link answers before its email is sent, and the same whether or not a registration waits", BOUND, async (t) => {
|
|
104
|
+
// The registration's own email is sent (registering waits for it); the new link's never finishes.
|
|
105
|
+
const sender = stalledSender({ finishing: 1 });
|
|
106
|
+
const { backend, service } = await startService(t, {
|
|
107
|
+
env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
|
|
108
|
+
emailConfirmationSender: true,
|
|
109
|
+
confirmationSender: sender.send
|
|
110
|
+
});
|
|
111
|
+
const registered = await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
112
|
+
assert.equal(registered.requiresEmailConfirmation, true);
|
|
113
|
+
|
|
114
|
+
const answering = service.resendRegisterConfirmation({ email: "ada@example.com" });
|
|
115
|
+
await sender.received(2);
|
|
116
|
+
const forRegistration = await answerByNextTurn(answering);
|
|
117
|
+
assert.notEqual(forRegistration, NOT_ANSWERED, "the new link waits for its email, which takes time only a waiting registration's takes");
|
|
118
|
+
const forNobody = await service.resendRegisterConfirmation({ email: "nobody@example.com" });
|
|
119
|
+
assert.deepEqual(forNobody, forRegistration);
|
|
120
|
+
assert.deepEqual(forRegistration, {
|
|
121
|
+
ok: true,
|
|
122
|
+
message: "If a registration is waiting for that email, a new confirmation link has been sent.",
|
|
123
|
+
messageCode: "auth.local.register.confirmationResent",
|
|
124
|
+
messageParams: {}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// The new link is still sent, and it replaced the first one; the unknown email gets none.
|
|
128
|
+
await backend.idle();
|
|
129
|
+
assert.deepEqual(sender.messages.map(({ email }) => email), ["ada@example.com", "ada@example.com"]);
|
|
130
|
+
assert.notEqual(sender.messages[1].confirmationUrl, sender.messages[0].confirmationUrl);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("a failed sign-in checks one password, whether or not its email has one to check", async (t) => {
|
|
134
|
+
const checks = [];
|
|
135
|
+
const passwordStrategy = {
|
|
136
|
+
hashPassword: scryptPasswordStrategy.hashPassword,
|
|
137
|
+
async verifyPassword(password, record) {
|
|
138
|
+
checks.push(password);
|
|
139
|
+
return scryptPasswordStrategy.verifyPassword(password, record);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const { service } = await startService(t, { passwordStrategy });
|
|
143
|
+
await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
144
|
+
|
|
145
|
+
for (const email of ["ada@example.com", "nobody@example.com", "NOBODY@example.com", "other@example.com"]) {
|
|
146
|
+
checks.length = 0;
|
|
147
|
+
await assert.rejects(service.login({ email, password: "a wrong password" }), { status: 401 }, email);
|
|
148
|
+
assert.deepEqual(checks, ["a wrong password"], email);
|
|
149
|
+
}
|
|
150
|
+
// The right password still signs in, with one check.
|
|
151
|
+
checks.length = 0;
|
|
152
|
+
assert.equal((await service.login({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
|
|
153
|
+
assert.deepEqual(checks, [PASSWORD]);
|
|
154
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { createLocalAuthService, createLocalDeliveries, createLocalFileBackend } from "../src/server/lib/index.js";
|
|
7
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
8
|
+
|
|
9
|
+
const PASSWORD = "correct horse battery staple";
|
|
10
|
+
|
|
11
|
+
// A logger that keeps what it is given, by level.
|
|
12
|
+
function recordingLogger() {
|
|
13
|
+
const logs = { info: [], warn: [], error: [] };
|
|
14
|
+
return {
|
|
15
|
+
logs,
|
|
16
|
+
logger: {
|
|
17
|
+
info: (details, message) => logs.info.push({ details, message }),
|
|
18
|
+
warn: (details, message) => logs.warn.push({ details, message }),
|
|
19
|
+
error: (details, message) => logs.error.push({ details, message }),
|
|
20
|
+
debug() {}
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const nextTurn = () => new Promise((resolve) => setImmediate(resolve));
|
|
26
|
+
|
|
27
|
+
async function startService(t, { env = {}, emailRecovery = false, emailConfirmationSender = false, logger, ...overrides }) {
|
|
28
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-deliveries-"));
|
|
29
|
+
const deliveries = createLocalDeliveries({ logger });
|
|
30
|
+
t.after(async () => {
|
|
31
|
+
await deliveries.settled();
|
|
32
|
+
await fs.rm(storeDir, { recursive: true, force: true });
|
|
33
|
+
});
|
|
34
|
+
const service = createLocalAuthService({
|
|
35
|
+
...localServiceOptions({ env, emailRecovery, emailConfirmationSender }),
|
|
36
|
+
backend: createLocalFileBackend({ storeDir }),
|
|
37
|
+
deliveries,
|
|
38
|
+
logger,
|
|
39
|
+
...overrides
|
|
40
|
+
});
|
|
41
|
+
return { deliveries, service };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
test("a failed password reset email is logged with its address, never its link, and answered as any reset is", async (t) => {
|
|
45
|
+
const { logs, logger } = recordingLogger();
|
|
46
|
+
const failure = new Error("delivery unavailable");
|
|
47
|
+
const links = [];
|
|
48
|
+
const { deliveries, service } = await startService(t, {
|
|
49
|
+
emailRecovery: true,
|
|
50
|
+
logger,
|
|
51
|
+
recoverySender: async ({ recoveryUrl }) => {
|
|
52
|
+
links.push(recoveryUrl);
|
|
53
|
+
throw failure;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
57
|
+
|
|
58
|
+
const answer = await service.requestPasswordReset({ email: "ada@example.com" });
|
|
59
|
+
assert.deepEqual(answer, await service.requestPasswordReset({ email: "nobody@example.com" }));
|
|
60
|
+
assert.equal(await deliveries.settled(), true);
|
|
61
|
+
assert.equal(links.length, 1);
|
|
62
|
+
assert.deepEqual(logs.error, [{ details: { err: failure, email: "ada@example.com" }, message: "Sending the password reset email failed." }]);
|
|
63
|
+
assert.equal(JSON.stringify(logs).includes(new URL(links[0]).searchParams.get("token")), false);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("a failed new confirmation link email is logged with its address, never its link, and answered as any is", async (t) => {
|
|
67
|
+
const { logs, logger } = recordingLogger();
|
|
68
|
+
const failure = new Error("delivery unavailable");
|
|
69
|
+
const links = [];
|
|
70
|
+
let failing = false;
|
|
71
|
+
const { deliveries, service } = await startService(t, {
|
|
72
|
+
env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" },
|
|
73
|
+
emailConfirmationSender: true,
|
|
74
|
+
logger,
|
|
75
|
+
confirmationSender: async ({ confirmationUrl }) => {
|
|
76
|
+
links.push(confirmationUrl);
|
|
77
|
+
if (failing) throw failure;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
81
|
+
failing = true;
|
|
82
|
+
|
|
83
|
+
const answer = await service.resendRegisterConfirmation({ email: "ada@example.com" });
|
|
84
|
+
assert.deepEqual(answer, await service.resendRegisterConfirmation({ email: "nobody@example.com" }));
|
|
85
|
+
assert.equal(await deliveries.settled(), true);
|
|
86
|
+
assert.equal(links.length, 2);
|
|
87
|
+
assert.deepEqual(logs.error, [{ details: { err: failure, email: "ada@example.com" }, message: "Sending the email confirmation email failed." }]);
|
|
88
|
+
for (const link of links) {
|
|
89
|
+
assert.equal(JSON.stringify(logs).includes(new URL(link).searchParams.get("confirmation_token")), false);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("settled() waits for every email being sent, those they start included", async () => {
|
|
94
|
+
const { logs, logger } = recordingLogger();
|
|
95
|
+
const deliveries = createLocalDeliveries({ logger });
|
|
96
|
+
const { promise: gate, resolve: open } = Promise.withResolvers();
|
|
97
|
+
const done = [];
|
|
98
|
+
deliveries.send("the first email", "first@example.com", async () => {
|
|
99
|
+
await gate;
|
|
100
|
+
done.push("first");
|
|
101
|
+
deliveries.send("the second email", "second@example.com", async () => {
|
|
102
|
+
done.push("second");
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
deliveries.send("a failing email", "failing@example.com", () => {
|
|
106
|
+
throw new Error("refused at once");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
let settled = null;
|
|
110
|
+
const settling = deliveries.settled().then((value) => {
|
|
111
|
+
settled = value;
|
|
112
|
+
});
|
|
113
|
+
await nextTurn();
|
|
114
|
+
assert.equal(settled, null, "settled() waits while an email is being sent");
|
|
115
|
+
open();
|
|
116
|
+
await settling;
|
|
117
|
+
assert.equal(settled, true);
|
|
118
|
+
assert.deepEqual(done, ["first", "second"]);
|
|
119
|
+
assert.deepEqual(logs.error.map(({ details, message }) => [details.email, details.err.message, message]), [
|
|
120
|
+
["failing@example.com", "refused at once", "Sending a failing email failed."]
|
|
121
|
+
]);
|
|
122
|
+
assert.equal(await deliveries.settled(), true, "nothing left to wait for");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("settled({ timeoutMs }) stops waiting for an email that never finishes, and logs how many were left", async () => {
|
|
126
|
+
const { logs, logger } = recordingLogger();
|
|
127
|
+
const deliveries = createLocalDeliveries({ logger });
|
|
128
|
+
deliveries.send("a stalled email", "stalled@example.com", () => new Promise(() => {}));
|
|
129
|
+
assert.equal(await deliveries.settled({ timeoutMs: 5 }), false);
|
|
130
|
+
assert.deepEqual(logs.warn, [{
|
|
131
|
+
details: { unfinishedEmails: 1 },
|
|
132
|
+
message: "Local auth stopped waiting for the emails it was still sending; they may not arrive."
|
|
133
|
+
}]);
|
|
134
|
+
});
|
|
@@ -37,6 +37,14 @@ async function firstAccountSetupCode(storeDir) {
|
|
|
37
37
|
return (await fs.readFile(path.join(storeDir, "first-account-setup-code"), "utf8")).trim();
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
// Waits, a turn of the event loop at a time, until done() holds: for what local auth does after it has answered, such
|
|
41
|
+
// as sending a password reset email.
|
|
42
|
+
async function eventually(done) {
|
|
43
|
+
while (!done()) {
|
|
44
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
40
48
|
function createReplyFixture() {
|
|
41
49
|
const cookies = {};
|
|
42
50
|
const cookieOptions = {};
|
|
@@ -1375,16 +1383,19 @@ test("local recovery uses the application sender without returning or logging it
|
|
|
1375
1383
|
assert.equal(app.authService.getCapabilities().features.passwordRecovery.delivery, "email");
|
|
1376
1384
|
const result = await app.authService.requestPasswordReset({ email: "sender@example.com" });
|
|
1377
1385
|
assert.equal(result.recoveryUrl, undefined);
|
|
1378
|
-
|
|
1386
|
+
const unknown = await app.authService.requestPasswordReset({ email: "absent@example.com" });
|
|
1387
|
+
assert.deepEqual(unknown, result);
|
|
1388
|
+
// The email is sent after the answer.
|
|
1389
|
+
await eventually(() => messages.length === 1);
|
|
1379
1390
|
assert.equal(messages[0].email, "sender@example.com");
|
|
1380
1391
|
assert.match(messages[0].recoveryUrl, /^http:\/\/localhost:5173\/auth\/reset-password\?/);
|
|
1381
1392
|
assert.equal(JSON.stringify(logs).includes(messages[0].recoveryUrl), false);
|
|
1382
|
-
const unknown = await app.authService.requestPasswordReset({ email: "absent@example.com" });
|
|
1383
|
-
assert.deepEqual(unknown, result);
|
|
1384
|
-
assert.equal(messages.length, 1);
|
|
1385
1393
|
const token = new URL(messages[0].recoveryUrl).searchParams.get("token");
|
|
1386
1394
|
const recovery = await app.authService.completePasswordRecovery({ code: token, type: "recovery" });
|
|
1387
1395
|
assert.equal(recovery.actor.email, "sender@example.com");
|
|
1396
|
+
// Stopping waits for every email local auth started: the unknown email's sent nothing.
|
|
1397
|
+
await app.runtime.shutdown();
|
|
1398
|
+
assert.equal(messages.length, 1);
|
|
1388
1399
|
});
|
|
1389
1400
|
|
|
1390
1401
|
test("a test copy logs the emails an installed sender would send, sends none and keeps the links out of the answers", async (t) => {
|
|
@@ -1415,9 +1426,12 @@ test("a test copy logs the emails an installed sender would send, sends none and
|
|
|
1415
1426
|
assert.equal(Object.hasOwn(registered, "confirmationUrl"), false);
|
|
1416
1427
|
const reset = await app.authService.requestPasswordReset({ email: "owner@example.com" });
|
|
1417
1428
|
assert.equal(reset.recoveryUrl, undefined);
|
|
1429
|
+
// The reset's email is simulated after the answer.
|
|
1430
|
+
const simulatedLogs = () => logs.filter(({ details }) => details?.sideEffects === "simulate" && details.kind === "email");
|
|
1431
|
+
await eventually(() => simulatedLogs().length === 2);
|
|
1418
1432
|
assert.deepEqual(sent, [], "nothing sent");
|
|
1419
1433
|
|
|
1420
|
-
const simulated =
|
|
1434
|
+
const simulated = simulatedLogs();
|
|
1421
1435
|
assert.deepEqual(simulated.map(({ details }) => details.email), ["tester@example.com", "owner@example.com"]);
|
|
1422
1436
|
assert.match(simulated[0].message, /^Test copy: the email confirmation email to tester@example\.com was simulated, not sent/u);
|
|
1423
1437
|
assert.match(simulated[0].details.confirmationUrl, /^https:\/\/app\.example\.test\/auth\/login\?confirmation_token=/u);
|
|
@@ -1433,18 +1447,52 @@ test("a test copy logs the emails an installed sender would send, sends none and
|
|
|
1433
1447
|
assert.equal(recovery.actor.email, "owner@example.com");
|
|
1434
1448
|
});
|
|
1435
1449
|
|
|
1436
|
-
test("a failing recovery sender does not fall back to development output", async (t) => {
|
|
1450
|
+
test("a failing recovery sender is logged, never answered, and does not fall back to development output", async (t) => {
|
|
1437
1451
|
const logs = [];
|
|
1452
|
+
const errors = [];
|
|
1438
1453
|
const failure = new Error("delivery unavailable");
|
|
1439
1454
|
const app = await createStartedApp({
|
|
1440
1455
|
env: { AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "log" },
|
|
1441
1456
|
recoverySender: async () => { throw failure; },
|
|
1442
|
-
logger: { info: (...args) => logs.push(args), warn() {}, error()
|
|
1457
|
+
logger: { info: (...args) => logs.push(args), warn() {}, error: (...args) => errors.push(args), debug() {} }
|
|
1443
1458
|
});
|
|
1444
1459
|
t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
|
|
1445
1460
|
await app.authService.register({ email: "failure@example.com", password: "correct horse battery staple" });
|
|
1446
|
-
|
|
1447
|
-
|
|
1461
|
+
// The requester gets the answer every email gets: a failure only an account's email can have says nothing.
|
|
1462
|
+
const answer = await app.authService.requestPasswordReset({ email: "failure@example.com" });
|
|
1463
|
+
assert.deepEqual(answer, await app.authService.requestPasswordReset({ email: "nobody@example.com" }));
|
|
1464
|
+
assert.equal(answer.messageCode, "auth.local.recovery.requested");
|
|
1465
|
+
await eventually(() => errors.length === 1);
|
|
1466
|
+
assert.deepEqual(errors, [[{ err: failure, email: "failure@example.com" }, "Sending the password reset email failed."]]);
|
|
1467
|
+
assert.equal([...logs, ...errors].some((args) => JSON.stringify(args).includes("recoveryUrl")), false);
|
|
1468
|
+
assert.equal([...logs, ...errors].some((args) => JSON.stringify(args).includes("reset-password?token")), false);
|
|
1469
|
+
});
|
|
1470
|
+
|
|
1471
|
+
test("stopping the server waits for a password reset email still being sent", async (t) => {
|
|
1472
|
+
const started = [];
|
|
1473
|
+
const sent = [];
|
|
1474
|
+
const { promise: sending, resolve: finishSending } = Promise.withResolvers();
|
|
1475
|
+
const app = await createStartedApp({
|
|
1476
|
+
recoverySender: async ({ email }) => {
|
|
1477
|
+
started.push(email);
|
|
1478
|
+
await sending;
|
|
1479
|
+
sent.push(email);
|
|
1480
|
+
}
|
|
1481
|
+
});
|
|
1482
|
+
t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
|
|
1483
|
+
await app.authService.register({ email: "late@example.com", password: "correct horse battery staple" });
|
|
1484
|
+
await app.authService.requestPasswordReset({ email: "late@example.com" });
|
|
1485
|
+
await eventually(() => started.length === 1);
|
|
1486
|
+
|
|
1487
|
+
let stopped = false;
|
|
1488
|
+
const stopping = app.runtime.shutdown().then(() => {
|
|
1489
|
+
stopped = true;
|
|
1490
|
+
});
|
|
1491
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
1492
|
+
assert.equal(stopped, false, "the server stops only once the email is sent");
|
|
1493
|
+
finishSending();
|
|
1494
|
+
await stopping;
|
|
1495
|
+
assert.deepEqual(sent, ["late@example.com"]);
|
|
1448
1496
|
});
|
|
1449
1497
|
|
|
1450
1498
|
test("in production, email confirmation needs an auth.local.confirmation-sender, or startup stops saying what to do", async () => {
|
|
@@ -19,12 +19,16 @@ function linkToken(result) {
|
|
|
19
19
|
* Registration with email confirmation in development, against any backend:
|
|
20
20
|
* run with Date mocked through `t.mock.timers`. `storedRegistrations` answers
|
|
21
21
|
* what the backend keeps of waiting registrations, as text, so the scenario
|
|
22
|
-
* can check that a link's code is kept only as its hash
|
|
22
|
+
* can check that a link's code is kept only as its hash; `storedAccount`, for a
|
|
23
|
+
* backend that keeps when an email was confirmed (the database's; the file
|
|
24
|
+
* backend keeps no such time), the account it keeps for an email, so it can
|
|
25
|
+
* check that time.
|
|
23
26
|
* @param {import("node:test").TestContext} t
|
|
24
27
|
* @param {import("@jskit-ai/auth-core/server/types").AuthService} service
|
|
25
28
|
* @param {() => Promise<string>} storedRegistrations
|
|
29
|
+
* @param {(email: string) => Promise<{ emailVerifiedAt?: string } | null>} [storedAccount]
|
|
26
30
|
*/
|
|
27
|
-
async function exerciseEmailConfirmation(t, service, storedRegistrations) {
|
|
31
|
+
async function exerciseEmailConfirmation(t, service, storedRegistrations, storedAccount) {
|
|
28
32
|
// Registering keeps the account waiting: nobody is signed in, and development shows the link.
|
|
29
33
|
const registered = await service.register({ email: EMAIL, password: PASSWORD, displayName: "Ada" });
|
|
30
34
|
assert.equal(registered.requiresEmailConfirmation, true);
|
|
@@ -58,11 +62,16 @@ async function exerciseEmailConfirmation(t, service, storedRegistrations) {
|
|
|
58
62
|
await assert.rejects(service.confirmRegistration({ token: secondToken, password: "a wrong password" }), wrongPassword);
|
|
59
63
|
await assert.rejects(service.login({ email: EMAIL, password: PASSWORD }), unconfirmed);
|
|
60
64
|
|
|
61
|
-
// Confirming with the registration's password creates the account
|
|
65
|
+
// Confirming with the registration's password creates the account, its email confirmed then, and signs the person
|
|
66
|
+
// in; its password signs in too.
|
|
67
|
+
const confirmedAt = Date.now();
|
|
62
68
|
const confirmed = await service.confirmRegistration({ token: secondToken, password: PASSWORD });
|
|
63
69
|
assert.ok(confirmed.session.access_token);
|
|
64
70
|
assert.equal(confirmed.actor.email, EMAIL);
|
|
65
71
|
assert.equal(confirmed.actor.displayName, "Ada");
|
|
72
|
+
if (storedAccount) {
|
|
73
|
+
assert.equal(Date.parse((await storedAccount(EMAIL))?.emailVerifiedAt ?? ""), confirmedAt, "the email confirmed when its link was used");
|
|
74
|
+
}
|
|
66
75
|
assert.equal((await service.login({ email: EMAIL, password: PASSWORD })).actor.email, EMAIL);
|
|
67
76
|
assert.equal((await storedRegistrations()).includes(sha256Base64url(secondToken)), false);
|
|
68
77
|
|