@jskit-ai/auth-provider-local-core 0.2.36 → 0.2.38
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 +7 -0
- package/locales/en.json +9 -1
- package/package.json +8 -6
- package/src/server/lib/accounts.js +41 -11
- package/src/server/lib/config.js +52 -34
- package/src/server/lib/deliveries.js +4 -2
- package/src/server/lib/emailChange.js +183 -0
- package/src/server/lib/emailConfirmation.js +4 -2
- package/src/server/lib/fileBackend.js +40 -2
- package/src/server/lib/fileRecords.js +17 -7
- package/src/server/lib/firstAccountSetup.js +2 -2
- package/src/server/lib/index.js +2 -0
- package/src/server/lib/oauthFlows.js +18 -7
- package/src/server/lib/passSignIn.js +16 -6
- package/src/server/lib/passwordFlows.js +4 -2
- package/src/server/lib/registerHookDecorator.js +4 -4
- package/src/server/lib/service.js +28 -7
- package/src/server/lib/sessions.js +95 -17
- package/src/server/providers/AuthLocalProvider.js +28 -6
- package/src/server/types.js +63 -4
- package/test/accountEnumeration.test.js +12 -3
- package/test/cookieSameSite.test.js +25 -0
- package/test/emailChange.test.js +37 -0
- package/test/oauthSignIn.test.js +13 -1
- package/test/providerRuntime.test.js +133 -8
- package/test/sessionMetadata.test.js +38 -0
- package/test/signInEvents.test.js +206 -0
- package/test-support/emailChangeScenario.js +139 -0
- package/test-support/localService.js +9 -3
- package/test-support/passSignInScenario.js +10 -4
- package/test-support/sessionMetadataScenario.js +76 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- **Breaking:** the local file auth backend in staging and production needs `AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK=true`, in place of `AUTH_LOCAL_FILE_PRODUCTION_ACK`, which it always needed in staging too; a server with the old variable set refuses to start, naming the new one. The resolved configuration (`resolveLocalAuthConfig`) names whether it runs in staging or production `isStagingOrProduction`, in place of `isDeployed`.
|
|
6
|
+
- Email change: the signed-in person asks for a new email with their password (`requestEmailChange(request, { email, password })`), or the application asks for an account it chose, such as an operator's change for a person who lost their old address (`requestEmailChangeForUser({ userId, email })`, who may ask being the application's decision). The account keeps the address as its waiting change (`pendingEmail`) and the new address is sent a link to `/auth/email-change?token=`, signed with the session secret and working for a day; a newer request replaces the waiting change, so an earlier link stops working. Using it (`confirmEmailChange({ token })`) changes the email, which the link proves, ends the password resets sent to the old address and sends the old address a notice; the account's sessions stay signed in. Refusals: `auth.local.emailChange.passwordInvalid` (400), `sameEmail` (400), `emailTaken` (409, also when an account took the address since the link was sent), `linkInvalid` (400, a used, replaced, expired or altered link) and `accountNotFound` (404), each with its message key under `jskit.auth.local.emailChange`. The links and notices go through the new optional `auth.local.email-change-sender` capability (`AuthLocalEmailChangeSender`: `{ type: "confirmation", email, currentEmail, confirmationUrl }` or `{ type: "notice", email, newEmail }`) after the request has answered, through the local deliveries, and send as `APP_ENV` says, like the recovery and confirmation senders (production to each address, staging only to `STAGING_EMAIL_TO` with `originalEmail`, development and test to the log). Without one, development and test log them (`createLoggedEmailChangeSender`, new), and a staging or production server has no email change (`features.emailChange` false, the operations `AUTH_OPERATION_UNSUPPORTED`). A sender needs `APP_PUBLIC_URL`, which its links name.
|
|
7
|
+
- Upgrading: `createLocalAuthService()` takes `emailChangeSender`, and `resolveLocalAuthConfig()` takes `emailChangeSender: true` when one is installed (`config.emailChangeDelivery` is `email`, `dev-log` or `off`); a custom `auth.local.backend` keeps a user's `pendingEmail` and implements `users.updatePendingEmail(userId, pendingEmail)` and `users.updateEmail(userId, email)`, which refuses an email another account has with `auth.local.accounts.exists` and clears the waiting change. The file backend adds `pendingEmail` to each line of `users.passwd` and reads the lines it wrote before as having none.
|
|
8
|
+
- Each sign-in and each refused one is an event for the new optional `auth.local.sign-in-events` capability (`AuthLocalSignInEvent`, `AuthLocalSignInEvents`, also `createLocalAuthService({ signInEvents })`), for an application's list of an account's sign-ins or its audit log: `signedIn` or `failed`, the `method` (`password`, `registration`, `confirmation`, `recovery`, `pass`, or `provider` with the provider's id), a refusal's `reason` (`invalidCredentials`, `locked`, `unconfirmed`, `disabled`), the account's `userId` ("" when the email names none), the `email`, the request's `ip` and `userAgent`, and the time `at`; never a password, secret or token. It is given each event after the request has answered, through the deliveries the emails use, so a refused sign-in takes the same time whatever the recorder does; a recorder that fails is logged (`Sending the sign-in event failed.`), and a stopping server waits for the events still being handed over, as for the emails. Without one, local auth logs each event (`createLoggedSignInEvents`, new). A pass that names no account, and a provider callback refused before it names one, are not events.
|
|
9
|
+
- Upgrading: `createLocalAuthService()` takes `signInEvents` and refuses, with a `TypeError`, to be made without it; pass `createLoggedSignInEvents(logger)` for the logging the provider uses by default.
|
|
10
|
+
- A session keeps where and when it was last seen: `ip` (the request's address), `userAgent` (its `User-Agent`, at most 512 characters) and `lastSeenAt`, each "" when unknown. Signing in sets them from the request that signs in (`login`, `register`, `confirmRegistration`, `completePasswordRecovery` and `signInWithPass` take it as their second parameter, as `oauthComplete` and `devLoginAs` already did; auth-core's actions pass it), and authenticating a request that finds the session more than five minutes after it was last seen sets them again, so most requests write nothing; a request that does not say where it comes from keeps the address and browser. `authenticateRequest` still reads the session once. `createLocalAuthRegisterHookDecorator` passes the request on. Upgrading: a custom `auth.local.backend` keeps a session's `ip`, `userAgent` and `lastSeenAt` from `sessions.create` and implements `sessions.touch(sessionId, { lastSeenAt, ip, userAgent })`, which keeps the old `ip` or `userAgent` when the new one is ""; the file backend adds them to each line of `sessions.passwd` and reads the lines it wrote before as never seen; an application's own auth service decorator around `login`, `register`, `confirmRegistration` or `completePasswordRecovery` passes the request on, or its sessions keep no address.
|
|
11
|
+
- A disabled account's sign-in that proves who it is is told the account is disabled, with the application's own message when it gave one: the right password, a linked provider's sign-in or a one-time pass is refused with 403 `auth.local.login.disabled` (new message key `jskit.auth.local.login.disabled`, "This account is disabled.") and the account's `disabledMessage` as its text when it has one, which the sign-in page shows as written. Before, the right password answered "Invalid email or password.", a provider "This account can't sign in." (`auth.local.oauth.accountUnavailable`, still the answer for an identity whose account is missing) and a pass `auth.pass.unmapped` (still the answer for a pass that names no account), so a suspended person could not be told why. A wrong password for a disabled account is still an ordinary failed sign-in, counted by the sign-in throttle, so only someone who could sign in learns that the account is disabled. A backend's users carry `disabledMessage`; the file backend keeps none. `@jskit-ai/auth-provider-local-db-core`'s `auth.local.accounts.disable` and `enable` set and clear it.
|
|
5
12
|
- **Breaking:** an installed `auth.local.confirmation-sender` or `auth.local.recovery-sender` sends as `APP_ENV` says, through the kernel's `deliverMessage`: production sends each email to its address; staging sends it only to `STAGING_EMAIL_TO`, calling the sender with that address as `email` and the person's address as the new `originalEmail` (show it, for example with `markStagingEmail`), and logs it, link included, when `STAGING_EMAIL_TO` is unset; development and test log it. This replaces the simulated senders a test copy used, and `createSimulatedConfirmationSender` and `createSimulatedRecoverySender` are gone. Staging and production (`APP_ENV`), not `NODE_ENV=production`, require `AUTH_LOCAL_SESSION_SECRET`, ask for the first account's setup code, refuse `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` (`… is for development only and APP_ENV is staging. Remove it from the staging environment.`) and need a confirmation sender while anyone may register.
|
|
6
13
|
- 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()`.
|
|
7
14
|
- 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.
|
package/locales/en.json
CHANGED
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
"email": {
|
|
6
6
|
"invalid": "Enter a valid email address."
|
|
7
7
|
},
|
|
8
|
+
"emailChange": {
|
|
9
|
+
"passwordInvalid": "That is not your password.",
|
|
10
|
+
"sameEmail": "That is already your email address.",
|
|
11
|
+
"emailTaken": "An account already exists for this email.",
|
|
12
|
+
"linkInvalid": "This email change link is invalid, used or expired. Ask for the change again.",
|
|
13
|
+
"accountNotFound": "There is no such account."
|
|
14
|
+
},
|
|
8
15
|
"password": {
|
|
9
16
|
"tooShort": "Password must be at least {min} characters.",
|
|
10
17
|
"currentInvalid": "Current password is invalid.",
|
|
@@ -25,7 +32,8 @@
|
|
|
25
32
|
"codeInvalid": "That is not this app's setup code. Copy it again from the server's log or its hosting service."
|
|
26
33
|
},
|
|
27
34
|
"login": {
|
|
28
|
-
"locked": "Too many failed sign-ins for this account. Try again in {count} minute. | Too many failed sign-ins for this account. Try again in {count} minutes."
|
|
35
|
+
"locked": "Too many failed sign-ins for this account. Try again in {count} minute. | Too many failed sign-ins for this account. Try again in {count} minutes.",
|
|
36
|
+
"disabled": "This account is disabled."
|
|
29
37
|
},
|
|
30
38
|
"recovery": {
|
|
31
39
|
"notConfigured": "Password recovery is not configured.",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/auth-provider-local-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.38",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"./locales/en.json": "./locales/en.json"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@jskit-ai/auth-pass": "0.1.
|
|
15
|
+
"@jskit-ai/auth-pass": "0.1.2",
|
|
16
16
|
"openid-client": "6.8.8"
|
|
17
17
|
},
|
|
18
18
|
"description": "Local auth provider with a file backend default, no database requirement, and optional Google, Microsoft and GitHub sign-in.",
|
|
@@ -49,11 +49,11 @@
|
|
|
49
49
|
},
|
|
50
50
|
{
|
|
51
51
|
"subpath": "./server/lib/index",
|
|
52
|
-
"summary": "Exports the local auth service and its configuration (createLocalAuthService, resolveLocalAuthConfig), the file backend, the password strategy helpers (scryptPasswordStrategy, normalizePasswordStrategy, hashPassword, verifyPassword), the logged recovery and
|
|
52
|
+
"summary": "Exports the local auth service and its configuration (createLocalAuthService, resolveLocalAuthConfig), the file backend, the password strategy helpers (scryptPasswordStrategy, normalizePasswordStrategy, hashPassword, verifyPassword), the logged recovery, confirmation and email change senders (createLoggedRecoverySender, createLoggedConfirmationSender, createLoggedEmailChangeSender), the first account's setup code (createFirstAccountSetup, SETUP_CODE_FILE, SETUP_CODE_ENV), the logged second factor events (createLoggedSecondFactorEvents), the logged sign-in events (createLoggedSignInEvents), and local auth register hook decorators. Google, Microsoft and GitHub sign-in turn on from AUTH_GOOGLE_*, AUTH_MICROSOFT_* and AUTH_GITHUB_* client id and secret pairs."
|
|
53
53
|
},
|
|
54
54
|
{
|
|
55
55
|
"subpath": "./server/types",
|
|
56
|
-
"summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy, auth.local.recovery-sender, auth.local.confirmation-sender, auth.local.confirmation-mode, auth.local.second-factor-events and auth.local.pass-identity capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
56
|
+
"summary": "Types of the auth.local.backend contract (AuthLocalBackend) that every local auth backend implements, of the auth.local.password-strategy, auth.local.recovery-sender, auth.local.confirmation-sender, auth.local.email-change-sender, auth.local.confirmation-mode, auth.local.second-factor-events, auth.local.sign-in-events and auth.local.pass-identity capabilities, and of the configuration, passwords and sessions local auth's modules share."
|
|
57
57
|
}
|
|
58
58
|
],
|
|
59
59
|
"extensionCapabilities": [
|
|
@@ -63,15 +63,17 @@
|
|
|
63
63
|
"auth.profile.projector",
|
|
64
64
|
"auth.local.recovery-sender",
|
|
65
65
|
"auth.local.confirmation-sender",
|
|
66
|
+
"auth.local.email-change-sender",
|
|
66
67
|
"auth.local.confirmation-mode",
|
|
67
68
|
"auth.local.second-factor-events",
|
|
69
|
+
"auth.local.sign-in-events",
|
|
68
70
|
"auth.local.pass-identity"
|
|
69
71
|
]
|
|
70
72
|
}
|
|
71
73
|
}
|
|
72
74
|
},
|
|
73
75
|
"peerDependencies": {
|
|
74
|
-
"@jskit-ai/auth-core": "0.2.
|
|
75
|
-
"@jskit-ai/kernel": "0.2.
|
|
76
|
+
"@jskit-ai/auth-core": "0.2.32",
|
|
77
|
+
"@jskit-ai/kernel": "0.2.28"
|
|
76
78
|
}
|
|
77
79
|
}
|
|
@@ -54,6 +54,16 @@ function validatePasswordInput(password, minLength) {
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The refusal of a disabled account's sign-in that proved who it is (its password, its provider or a pass): what the
|
|
59
|
+
* application wrote when it disabled the account, or a plain sentence when it wrote nothing. Without that proof a
|
|
60
|
+
* sign-in of a disabled account fails as any other does, so the refusal tells no one else the account exists.
|
|
61
|
+
* @param {{ disabledMessage?: string }} user
|
|
62
|
+
*/
|
|
63
|
+
function accountDisabledError(user) {
|
|
64
|
+
return new AppError(403, user.disabledMessage || "This account is disabled.", { code: "auth.local.login.disabled" });
|
|
65
|
+
}
|
|
66
|
+
|
|
57
67
|
function validateEmailInput(email) {
|
|
58
68
|
const normalized = normalizeEmail(email);
|
|
59
69
|
if (!normalized || !normalized.includes("@")) {
|
|
@@ -167,7 +177,7 @@ function createLocalAccounts({
|
|
|
167
177
|
return invitation.expiresAt == null || new Date(invitation.expiresAt).getTime() > Date.now();
|
|
168
178
|
}
|
|
169
179
|
|
|
170
|
-
async function register(input) {
|
|
180
|
+
async function register(input, request = null) {
|
|
171
181
|
const email = validateEmailInput(input.email);
|
|
172
182
|
validatePasswordInput(input.password, config.passwordMinLength);
|
|
173
183
|
const displayName = normalizeDisplayName(input.displayName, email);
|
|
@@ -195,10 +205,11 @@ function createLocalAccounts({
|
|
|
195
205
|
});
|
|
196
206
|
return {
|
|
197
207
|
user,
|
|
198
|
-
session: await sessions.createSessionForUser(tx, user)
|
|
208
|
+
session: await sessions.createSessionForUser(tx, user, { request })
|
|
199
209
|
};
|
|
200
210
|
});
|
|
201
211
|
firstAccountSetup.accountCreated();
|
|
212
|
+
sessions.recordSignInEvent("signedIn", { method: "registration", userId: result.user.id, email: result.user.email }, request);
|
|
202
213
|
return {
|
|
203
214
|
...(await buildAuthPayload({
|
|
204
215
|
user: result.user,
|
|
@@ -226,11 +237,14 @@ function createLocalAccounts({
|
|
|
226
237
|
* not the account exists, so the wait they cause says nothing about which
|
|
227
238
|
* accounts exist; while an account waits its password is not checked. Nor
|
|
228
239
|
* does a failure's time: a sign-in whose email has no password to check (no
|
|
229
|
-
* account,
|
|
230
|
-
*
|
|
231
|
-
*
|
|
240
|
+
* account, or one created through a provider) checks the password against one
|
|
241
|
+
* nobody knows, as long as checking a wrong one takes. A successful sign-in,
|
|
242
|
+
* or a password reset, forgets the failures. A disabled account's right
|
|
243
|
+
* password is refused with the account's message; its wrong one is an
|
|
244
|
+
* ordinary failure. The sign-in, or its refusal with the reason, is a
|
|
245
|
+
* sign-in event.
|
|
232
246
|
*/
|
|
233
|
-
async function login(input) {
|
|
247
|
+
async function login(input, request = null) {
|
|
234
248
|
const email = validateEmailInput(input.email);
|
|
235
249
|
const password = String(input.password || "");
|
|
236
250
|
const outcome = await backend.withTransaction(async (tx) => {
|
|
@@ -238,7 +252,8 @@ function createLocalAccounts({
|
|
|
238
252
|
const failures = await tx.signInFailures.find(email);
|
|
239
253
|
const waitMs = signInWaitMs(failures, now);
|
|
240
254
|
if (waitMs > 0) {
|
|
241
|
-
|
|
255
|
+
// Only for the sign-in event: the password is not checked.
|
|
256
|
+
return { waitMs, userId: (await tx.users.findByEmail(email))?.id || "" };
|
|
242
257
|
}
|
|
243
258
|
let checked = false;
|
|
244
259
|
const passwordMatches = (record) => {
|
|
@@ -251,29 +266,42 @@ function createLocalAccounts({
|
|
|
251
266
|
passwordMatches(registration.password)))) {
|
|
252
267
|
return { unconfirmed: true };
|
|
253
268
|
}
|
|
254
|
-
if (!user ||
|
|
269
|
+
if (!user || !hasPassword(user) || !(await passwordMatches(user.password))) {
|
|
255
270
|
if (!checked) {
|
|
256
271
|
await passwords.verifyPassword(password, await unmatchableRecord());
|
|
257
272
|
}
|
|
258
273
|
await tx.signInFailures.deleteBefore(forgottenFailuresBefore(now));
|
|
259
274
|
await tx.signInFailures.save(recordSignInFailure(config.signInThrottle, failures, email, now));
|
|
260
|
-
return { failed: true };
|
|
275
|
+
return { failed: true, userId: user?.id || "" };
|
|
276
|
+
}
|
|
277
|
+
if (user.disabled) {
|
|
278
|
+
return { disabled: user };
|
|
261
279
|
}
|
|
262
280
|
if (failures) {
|
|
263
281
|
await tx.signInFailures.clear(email);
|
|
264
282
|
}
|
|
265
|
-
return { user, session: await sessions.createSessionForUser(tx, user) };
|
|
283
|
+
return { user, session: await sessions.createSessionForUser(tx, user, { request }) };
|
|
266
284
|
});
|
|
267
285
|
// Refused after the transaction, so the failure it records is kept.
|
|
286
|
+
const refused = (reason, userId = "") =>
|
|
287
|
+
sessions.recordSignInEvent("failed", { method: "password", reason, userId, email }, request);
|
|
268
288
|
if (outcome.waitMs) {
|
|
289
|
+
refused("locked", outcome.userId);
|
|
269
290
|
throw signInLockedError(outcome.waitMs);
|
|
270
291
|
}
|
|
271
292
|
if (outcome.failed) {
|
|
293
|
+
refused("invalidCredentials", outcome.userId);
|
|
272
294
|
throw createAuthError(AUTH_TEXTS.invalidCredentials);
|
|
273
295
|
}
|
|
274
296
|
if (outcome.unconfirmed) {
|
|
297
|
+
refused("unconfirmed");
|
|
275
298
|
throw createAuthError(AUTH_TEXTS.emailUnconfirmed);
|
|
276
299
|
}
|
|
300
|
+
if (outcome.disabled) {
|
|
301
|
+
refused("disabled", outcome.disabled.id);
|
|
302
|
+
throw accountDisabledError(outcome.disabled);
|
|
303
|
+
}
|
|
304
|
+
sessions.recordSignInEvent("signedIn", { method: "password", userId: outcome.user.id, email: outcome.user.email }, request);
|
|
277
305
|
// After the transaction, as register does: the profile projector works in transactions of its own, so a sign-in
|
|
278
306
|
// that synchronized the profile inside this one held two database connections at once.
|
|
279
307
|
return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector });
|
|
@@ -309,7 +337,8 @@ function createLocalAccounts({
|
|
|
309
337
|
throw devLoginAsUserNotFound({ email, userId });
|
|
310
338
|
}
|
|
311
339
|
const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user, {
|
|
312
|
-
purpose: DEV_AUTH_SESSION_PURPOSE
|
|
340
|
+
purpose: DEV_AUTH_SESSION_PURPOSE,
|
|
341
|
+
request
|
|
313
342
|
}));
|
|
314
343
|
return buildAuthResult({ user, session, appProfile });
|
|
315
344
|
}
|
|
@@ -344,6 +373,7 @@ function createLocalAccounts({
|
|
|
344
373
|
|
|
345
374
|
export {
|
|
346
375
|
NO_PASSWORD,
|
|
376
|
+
accountDisabledError,
|
|
347
377
|
createLocalAccounts,
|
|
348
378
|
hasPassword,
|
|
349
379
|
normalizeDisplayName,
|
package/src/server/lib/config.js
CHANGED
|
@@ -27,12 +27,12 @@ function resolveStoreDir(env, appRoot) {
|
|
|
27
27
|
* AUTH_LOCAL_SESSION_SECRET, or in development and test a secret kept in the
|
|
28
28
|
* store directory, generated on first use.
|
|
29
29
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
30
|
-
* @param {{ storeDir: string,
|
|
30
|
+
* @param {{ storeDir: string, isStagingOrProduction: boolean }} options
|
|
31
31
|
*/
|
|
32
|
-
function resolveSessionSecret(env, { storeDir,
|
|
32
|
+
function resolveSessionSecret(env, { storeDir, isStagingOrProduction }) {
|
|
33
33
|
const explicit = String(env.AUTH_LOCAL_SESSION_SECRET || "").trim();
|
|
34
34
|
if (explicit) return explicit;
|
|
35
|
-
if (
|
|
35
|
+
if (isStagingOrProduction) throw new Error("AUTH_LOCAL_SESSION_SECRET is required for local auth in staging and production.");
|
|
36
36
|
|
|
37
37
|
const secretPath = path.join(storeDir, "session.secret");
|
|
38
38
|
try {
|
|
@@ -57,9 +57,9 @@ const SECOND_FACTOR_KEY_MIN_CHARACTERS = 32;
|
|
|
57
57
|
* production server without it has no second factor (""); one shorter than 32
|
|
58
58
|
* characters stops startup.
|
|
59
59
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
60
|
-
* @param {{
|
|
60
|
+
* @param {{ isStagingOrProduction: boolean, sessionSecret: string }} options
|
|
61
61
|
*/
|
|
62
|
-
function resolveSecondFactorKey(env, {
|
|
62
|
+
function resolveSecondFactorKey(env, { isStagingOrProduction, sessionSecret }) {
|
|
63
63
|
const key = String(env.AUTH_LOCAL_SECOND_FACTOR_KEY || "").trim();
|
|
64
64
|
if (key) {
|
|
65
65
|
if (key.length < SECOND_FACTOR_KEY_MIN_CHARACTERS) {
|
|
@@ -67,7 +67,7 @@ function resolveSecondFactorKey(env, { isDeployed, sessionSecret }) {
|
|
|
67
67
|
}
|
|
68
68
|
return key;
|
|
69
69
|
}
|
|
70
|
-
return
|
|
70
|
+
return isStagingOrProduction ? "" : sessionSecret;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
/**
|
|
@@ -75,11 +75,11 @@ function resolveSecondFactorKey(env, { isDeployed, sessionSecret }) {
|
|
|
75
75
|
* supplies it, so that every start and every server asks for the same code.
|
|
76
76
|
* Only staging and production ask for a setup code; elsewhere the variable is ignored.
|
|
77
77
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
78
|
-
* @param {{
|
|
78
|
+
* @param {{ isStagingOrProduction: boolean }} options
|
|
79
79
|
*/
|
|
80
|
-
function resolveSetupCode(env, {
|
|
80
|
+
function resolveSetupCode(env, { isStagingOrProduction }) {
|
|
81
81
|
const code = String(env[SETUP_CODE_ENV] || "").trim();
|
|
82
|
-
if (!
|
|
82
|
+
if (!isStagingOrProduction || !code) return "";
|
|
83
83
|
if (normalizedSetupCode(code).length < SETUP_CODE_MIN_CHARACTERS) {
|
|
84
84
|
throw new Error(`${SETUP_CODE_ENV} must have at least ${SETUP_CODE_MIN_CHARACTERS} letters and digits.`);
|
|
85
85
|
}
|
|
@@ -87,22 +87,23 @@ function resolveSetupCode(env, { isDeployed }) {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
* APP_PUBLIC_URL, from which recovery and
|
|
91
|
-
* redirect addresses are built, and whose host authenticator apps show
|
|
92
|
-
* a second factor's codes. Emailed links, OAuth sign-in and a
|
|
93
|
-
* server's second factor require it.
|
|
90
|
+
* APP_PUBLIC_URL, from which recovery, confirmation and email change links and
|
|
91
|
+
* OAuth redirect addresses are built, and whose host authenticator apps show
|
|
92
|
+
* beside a second factor's codes. Emailed links, OAuth sign-in and a staging or
|
|
93
|
+
* production server's second factor require it.
|
|
94
94
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
95
|
-
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, oauthEnabled: boolean,
|
|
95
|
+
* @param {{ emailRecovery: boolean, emailedConfirmation: boolean, emailedChange: boolean, oauthEnabled: boolean, stagingOrProductionSecondFactor: boolean }} options
|
|
96
96
|
*/
|
|
97
|
-
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled,
|
|
97
|
+
function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, emailedChange, oauthEnabled, stagingOrProductionSecondFactor }) {
|
|
98
98
|
const configured = String(env.APP_PUBLIC_URL || "").trim();
|
|
99
99
|
if (!configured) {
|
|
100
100
|
if (emailRecovery) throw new Error("APP_PUBLIC_URL is required when local auth email recovery is configured.");
|
|
101
|
+
if (emailedChange) throw new Error("APP_PUBLIC_URL is required when local auth emails email change links.");
|
|
101
102
|
if (emailedConfirmation) {
|
|
102
103
|
throw new Error("APP_PUBLIC_URL is required when local auth emails confirmation links.");
|
|
103
104
|
}
|
|
104
105
|
if (oauthEnabled) throw new Error("APP_PUBLIC_URL is required when local auth OAuth sign-in is configured.");
|
|
105
|
-
if (
|
|
106
|
+
if (stagingOrProductionSecondFactor) {
|
|
106
107
|
throw new Error("APP_PUBLIC_URL is required when AUTH_LOCAL_SECOND_FACTOR_KEY is set: authenticator apps show its host.");
|
|
107
108
|
}
|
|
108
109
|
return "http://localhost:5173";
|
|
@@ -126,12 +127,12 @@ function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEna
|
|
|
126
127
|
* production without a sender, recovery is disabled, and
|
|
127
128
|
* AUTH_LOCAL_RECOVERY_DEV_OUTPUT stops startup (resolveLocalAuthConfig).
|
|
128
129
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
129
|
-
* @param {{ emailRecovery: boolean,
|
|
130
|
+
* @param {{ emailRecovery: boolean, isStagingOrProduction: boolean }} options
|
|
130
131
|
* @returns {"email" | "disabled" | "dev-response" | "dev-log"}
|
|
131
132
|
*/
|
|
132
|
-
function resolveRecoveryDelivery(env, { emailRecovery,
|
|
133
|
+
function resolveRecoveryDelivery(env, { emailRecovery, isStagingOrProduction }) {
|
|
133
134
|
if (emailRecovery) return "email";
|
|
134
|
-
if (
|
|
135
|
+
if (isStagingOrProduction) return "disabled";
|
|
135
136
|
const devOutput = String(env.AUTH_LOCAL_RECOVERY_DEV_OUTPUT || "").trim().toLowerCase();
|
|
136
137
|
return devOutput === "response" ? "dev-response" : "dev-log";
|
|
137
138
|
}
|
|
@@ -147,13 +148,13 @@ function resolveRecoveryDelivery(env, { emailRecovery, isDeployed }) {
|
|
|
147
148
|
* (invited accounts and the first one, admitted by its setup code) nothing is
|
|
148
149
|
* confirmed.
|
|
149
150
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
|
|
150
|
-
* @param {{ emailConfirmationSender: boolean,
|
|
151
|
+
* @param {{ emailConfirmationSender: boolean, isStagingOrProduction: boolean, selfRegistration: boolean }} options
|
|
151
152
|
* @returns {"email" | "dev-response" | "off"}
|
|
152
153
|
*/
|
|
153
|
-
function resolveConfirmationDelivery(env, { emailConfirmationSender,
|
|
154
|
+
function resolveConfirmationDelivery(env, { emailConfirmationSender, isStagingOrProduction, selfRegistration }) {
|
|
154
155
|
if (!parseBooleanFlag(env.AUTH_LOCAL_EMAIL_CONFIRMATION, true)) return "off";
|
|
155
156
|
if (emailConfirmationSender) return "email";
|
|
156
|
-
if (
|
|
157
|
+
if (isStagingOrProduction) {
|
|
157
158
|
if (!selfRegistration) return "off";
|
|
158
159
|
throw new Error(
|
|
159
160
|
"Local auth confirms each new account's email address in staging and production, and no auth.local.confirmation-sender " +
|
|
@@ -165,6 +166,19 @@ function resolveConfirmationDelivery(env, { emailConfirmationSender, isDeployed,
|
|
|
165
166
|
return "dev-response";
|
|
166
167
|
}
|
|
167
168
|
|
|
169
|
+
/**
|
|
170
|
+
* How an email change's link and the notice to the old address reach the
|
|
171
|
+
* person: by email through the installed email-change sender; otherwise, in
|
|
172
|
+
* development and test, in the log. A staging or production server without a
|
|
173
|
+
* sender has no email change.
|
|
174
|
+
* @param {{ emailChangeSender: boolean, isStagingOrProduction: boolean }} options
|
|
175
|
+
* @returns {"email" | "dev-log" | "off"}
|
|
176
|
+
*/
|
|
177
|
+
function resolveEmailChangeDelivery({ emailChangeSender, isStagingOrProduction }) {
|
|
178
|
+
if (emailChangeSender) return "email";
|
|
179
|
+
return isStagingOrProduction ? "off" : "dev-log";
|
|
180
|
+
}
|
|
181
|
+
|
|
168
182
|
/**
|
|
169
183
|
* The shortest password local auth accepts: AUTH_LOCAL_PASSWORD_MIN_LENGTH, or 8.
|
|
170
184
|
* It can be raised, up to 64, but not lowered below 8.
|
|
@@ -182,7 +196,7 @@ function resolvePasswordMinLength(env) {
|
|
|
182
196
|
|
|
183
197
|
/**
|
|
184
198
|
* The local auth configuration, resolved and checked once from the environment.
|
|
185
|
-
* Whether it
|
|
199
|
+
* Whether it runs in staging or production (APP_ENV) is worked out once, by
|
|
186
200
|
* auth-core's dev auth policy, so local auth and its dev sign-in agree on it.
|
|
187
201
|
* @param {object} input
|
|
188
202
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} input.appRoot
|
|
@@ -191,34 +205,37 @@ function resolvePasswordMinLength(env) {
|
|
|
191
205
|
* `auth.local.backend` is installed.
|
|
192
206
|
* @param {boolean} input.emailRecovery True when an `auth.local.recovery-sender` is installed.
|
|
193
207
|
* @param {boolean} [input.emailConfirmationSender] True when an `auth.local.confirmation-sender` is installed.
|
|
208
|
+
* @param {boolean} [input.emailChangeSender] True when an `auth.local.email-change-sender` is installed.
|
|
194
209
|
*/
|
|
195
|
-
function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender = false }) {
|
|
210
|
+
function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender = false, emailChangeSender = false }) {
|
|
196
211
|
const devAuth = resolveDevAuthPolicyFromEnv(env);
|
|
197
|
-
const {
|
|
212
|
+
const { isStagingOrProduction } = devAuth;
|
|
198
213
|
const storeDir = resolveStoreDir(env, appRoot);
|
|
199
|
-
if (fileBackend &&
|
|
200
|
-
throw new Error("
|
|
214
|
+
if (fileBackend && isStagingOrProduction && !parseBooleanFlag(env.AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK, false)) {
|
|
215
|
+
throw new Error("AUTH_LOCAL_FILE_STAGING_OR_PRODUCTION_ACK is required to use the local file auth backend in staging and production.");
|
|
201
216
|
}
|
|
202
217
|
assertDevAuthPolicy(devAuth);
|
|
203
218
|
assertDevelopmentOnlySettings(env, ["AUTH_LOCAL_RECOVERY_DEV_OUTPUT"]);
|
|
204
219
|
const oauthProviders = resolveOAuthProviders(env);
|
|
205
220
|
const oauthEnabled = oauthProviders.length > 0;
|
|
206
|
-
const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery,
|
|
221
|
+
const recoveryDelivery = resolveRecoveryDelivery(env, { emailRecovery, isStagingOrProduction });
|
|
207
222
|
// AUTH_LOCAL_SELF_REGISTRATION, on unless set to false: off, an account registers only by an invitation a feature
|
|
208
223
|
// resolves, or as the first account.
|
|
209
224
|
const selfRegistration = parseBooleanFlag(env.AUTH_LOCAL_SELF_REGISTRATION, true);
|
|
210
|
-
const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender,
|
|
211
|
-
const sessionSecret = resolveSessionSecret(env, { storeDir,
|
|
212
|
-
const secondFactorKey = resolveSecondFactorKey(env, {
|
|
225
|
+
const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isStagingOrProduction, selfRegistration });
|
|
226
|
+
const sessionSecret = resolveSessionSecret(env, { storeDir, isStagingOrProduction });
|
|
227
|
+
const secondFactorKey = resolveSecondFactorKey(env, { isStagingOrProduction, sessionSecret });
|
|
228
|
+
const emailChangeDelivery = resolveEmailChangeDelivery({ emailChangeSender, isStagingOrProduction });
|
|
213
229
|
const appPublicUrl = resolveAppPublicUrl(env, {
|
|
214
230
|
emailRecovery,
|
|
215
231
|
emailedConfirmation: confirmationDelivery === "email",
|
|
232
|
+
emailedChange: emailChangeDelivery === "email",
|
|
216
233
|
oauthEnabled,
|
|
217
|
-
|
|
234
|
+
stagingOrProductionSecondFactor: isStagingOrProduction && Boolean(secondFactorKey)
|
|
218
235
|
});
|
|
219
236
|
return Object.freeze({
|
|
220
237
|
storeDir,
|
|
221
|
-
|
|
238
|
+
isStagingOrProduction,
|
|
222
239
|
// The SameSite of every local auth cookie: AUTH_COOKIE_SAME_SITE, "lax" unless set to "strict".
|
|
223
240
|
cookieSameSite: resolveAuthCookieSameSite(env),
|
|
224
241
|
appPublicUrl,
|
|
@@ -227,12 +244,13 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
|
|
|
227
244
|
sessionSecret,
|
|
228
245
|
// "" when the server has no second factor.
|
|
229
246
|
secondFactorKey,
|
|
230
|
-
setupCode: resolveSetupCode(env, {
|
|
247
|
+
setupCode: resolveSetupCode(env, { isStagingOrProduction }),
|
|
231
248
|
recoveryDelivery,
|
|
232
249
|
recoveryEnabled: recoveryDelivery !== "disabled",
|
|
233
250
|
selfRegistration,
|
|
234
251
|
confirmationDelivery,
|
|
235
252
|
emailConfirmation: confirmationDelivery !== "off",
|
|
253
|
+
emailChangeDelivery,
|
|
236
254
|
passwordMinLength: resolvePasswordMinLength(env),
|
|
237
255
|
signInThrottle: resolveSignInThrottle(env),
|
|
238
256
|
// The trusted issuer's key, audience and resource of one-time pass sign-in (AUTH_PASS_*), or null while it is off.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* How long a stopping server waits for the emails local auth is still sending,
|
|
2
|
+
* How long a stopping server waits for the emails local auth is still sending, and the sign-in events it is still
|
|
3
|
+
* handing over, before it stops anyway.
|
|
3
4
|
*/
|
|
4
5
|
const DELIVERY_SHUTDOWN_WAIT_MS = 10_000;
|
|
5
6
|
|
|
@@ -9,7 +10,8 @@ const DELIVERY_SHUTDOWN_WAIT_MS = 10_000;
|
|
|
9
10
|
* 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
11
|
* the sender's own time and failures differ most. That work runs here instead, once the request has answered. Each
|
|
11
12
|
* 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
|
+
* stopping server waits for the emails still being sent (settled). Each sign-in event goes the same way, so a refused
|
|
14
|
+
* sign-in answers in the same time whatever the application's recorder takes.
|
|
13
15
|
* @param {object} dependencies
|
|
14
16
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
15
17
|
*/
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
3
|
+
import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
|
|
4
|
+
import { hasPassword, validateEmailInput } from "./accounts.js";
|
|
5
|
+
import { buildProfileChangePayload } from "./authPayloads.js";
|
|
6
|
+
import { signToken, verifySignedToken } from "./tokens.js";
|
|
7
|
+
|
|
8
|
+
const EMAIL_CHANGE_LINK_TTL_SECONDS = 24 * 60 * 60;
|
|
9
|
+
// What the link's signed token is for, so no other token the session secret signs is taken for one.
|
|
10
|
+
const EMAIL_CHANGE_PURPOSE = "email-change";
|
|
11
|
+
// A password reset's recovery tokens (passwordFlows.js): those sent to the old address end with the change.
|
|
12
|
+
const RESET_TOKEN_PREFIX = "rec_";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The `auth.local.email-change-sender` default when no feature provides one: in development and test, local auth logs
|
|
16
|
+
* each email-change link and notice instead of emailing them. A staging or production server without one has no email
|
|
17
|
+
* change.
|
|
18
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
19
|
+
* @returns {import("../types.js").AuthLocalEmailChangeSender}
|
|
20
|
+
*/
|
|
21
|
+
function createLoggedEmailChangeSender(logger) {
|
|
22
|
+
return async function logEmailChange(delivery) {
|
|
23
|
+
logger.info(delivery, `Local auth email change: ${delivery.type}.`);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The refusal of one field, for the form that sent it: its message under its code. */
|
|
28
|
+
function fieldRefusal(status, { code, message, field }) {
|
|
29
|
+
return new AppError(status, message, {
|
|
30
|
+
code,
|
|
31
|
+
details: { fieldErrors: { [field]: message }, fieldErrorCodes: { [field]: { code, params: {} } } }
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const passwordInvalidError = () =>
|
|
36
|
+
fieldRefusal(400, { code: "auth.local.emailChange.passwordInvalid", message: "That is not your password.", field: "password" });
|
|
37
|
+
const sameEmailError = () =>
|
|
38
|
+
fieldRefusal(400, { code: "auth.local.emailChange.sameEmail", message: "That is already your email address.", field: "email" });
|
|
39
|
+
const emailTakenError = () =>
|
|
40
|
+
fieldRefusal(409, { code: "auth.local.emailChange.emailTaken", message: "An account already exists for this email.", field: "email" });
|
|
41
|
+
const linkInvalidError = () => new AppError(400, "This email change link is invalid, used or expired. Ask for the change again.", {
|
|
42
|
+
code: "auth.local.emailChange.linkInvalid"
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Changing an account's email: the signed-in person asks with their password (requestEmailChange), or the
|
|
47
|
+
* application asks for an account it chose (requestEmailChangeForUser). The account keeps the new address as its
|
|
48
|
+
* waiting change, and the new address is sent a link, signed with the session secret, naming the account and the
|
|
49
|
+
* address and working for a day; a newer request replaces the waiting change, so an earlier link stops working. Using
|
|
50
|
+
* the link (confirmEmailChange) changes the email, which the link proved, ends the password resets sent to the old
|
|
51
|
+
* address, and tells the old address. The links and notices go through `auth.local.email-change-sender` after the
|
|
52
|
+
* request has answered (deliveries). The account's sessions stay signed in.
|
|
53
|
+
* @param {object} dependencies
|
|
54
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
55
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
56
|
+
* @param {import("../types.js").AuthLocalDeliveries} dependencies.deliveries
|
|
57
|
+
* @param {import("../types.js").AuthLocalEmailChangeSender} dependencies.emailChangeSender
|
|
58
|
+
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
59
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
60
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
61
|
+
*/
|
|
62
|
+
function createLocalEmailChange({ backend, config, deliveries, emailChangeSender, passwords, profileProjector, sessions }) {
|
|
63
|
+
if (!emailChangeSender) {
|
|
64
|
+
throw new TypeError("createLocalEmailChange() takes emailChangeSender, the auth.local.email-change-sender that sends its links.");
|
|
65
|
+
}
|
|
66
|
+
const enabled = config.emailChangeDelivery !== "off";
|
|
67
|
+
|
|
68
|
+
function linkFor(user, email) {
|
|
69
|
+
const exp = Math.floor(Date.now() / 1000) + EMAIL_CHANGE_LINK_TTL_SECONDS;
|
|
70
|
+
const token = signToken({ purpose: EMAIL_CHANGE_PURPOSE, sub: user.id, email, exp }, config.sessionSecret);
|
|
71
|
+
return `${config.appPublicUrl}/auth/email-change?token=${encodeURIComponent(token)}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Keeps the new address as the account's waiting change and sends it the link, once the request has answered.
|
|
76
|
+
* @param {(tx: import("../types.js").AuthLocalBackendTransaction) => Promise<object>} findUser The account, or a refusal.
|
|
77
|
+
* @param {string} email The new address, already checked.
|
|
78
|
+
*/
|
|
79
|
+
async function startChange(findUser, email) {
|
|
80
|
+
const user = await backend.withTransaction(async (tx) => {
|
|
81
|
+
const found = await findUser(tx);
|
|
82
|
+
if (found.email === email) {
|
|
83
|
+
throw sameEmailError();
|
|
84
|
+
}
|
|
85
|
+
if (await tx.users.findByEmail(email)) {
|
|
86
|
+
throw emailTakenError();
|
|
87
|
+
}
|
|
88
|
+
return tx.users.updatePendingEmail(found.id, email);
|
|
89
|
+
});
|
|
90
|
+
const confirmationUrl = linkFor(user, email);
|
|
91
|
+
deliveries.send("the email change link", email, () =>
|
|
92
|
+
emailChangeSender({ type: "confirmation", email, currentEmail: user.email, confirmationUrl }));
|
|
93
|
+
return { ok: true, email };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The signed-in person's own change, with their password; an account with no password sets one first, through a
|
|
98
|
+
* password reset.
|
|
99
|
+
* @param {object} request
|
|
100
|
+
* @param {{ email: string, password: string }} input
|
|
101
|
+
*/
|
|
102
|
+
async function requestEmailChange(request, input) {
|
|
103
|
+
if (!enabled) return throwUnsupportedAuthOperation("requestEmailChange");
|
|
104
|
+
const authResult = await sessions.authenticateRequest(request);
|
|
105
|
+
if (authResult.authenticated !== true) {
|
|
106
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
107
|
+
}
|
|
108
|
+
const email = validateEmailInput(input.email);
|
|
109
|
+
const password = String(input.password || "");
|
|
110
|
+
const userId = authResult.actor.providerUserId;
|
|
111
|
+
const user = await backend.withTransaction((tx) => tx.users.findById(userId));
|
|
112
|
+
if (!user || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
|
|
113
|
+
throw passwordInvalidError();
|
|
114
|
+
}
|
|
115
|
+
return startChange(async (tx) => {
|
|
116
|
+
const current = await tx.users.findById(userId);
|
|
117
|
+
if (!current) {
|
|
118
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
119
|
+
}
|
|
120
|
+
return current;
|
|
121
|
+
}, email);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The application's change of an account it chose, such as an operator's for a person who lost their old address:
|
|
126
|
+
* who may ask is the application's decision.
|
|
127
|
+
* @param {{ userId: string, email: string }} input
|
|
128
|
+
*/
|
|
129
|
+
async function requestEmailChangeForUser({ userId, email: given } = {}) {
|
|
130
|
+
if (!enabled) return throwUnsupportedAuthOperation("requestEmailChangeForUser");
|
|
131
|
+
const id = String(userId || "").trim();
|
|
132
|
+
if (!id) {
|
|
133
|
+
throw new TypeError("requestEmailChangeForUser() takes the userId of the account whose email changes.");
|
|
134
|
+
}
|
|
135
|
+
const email = validateEmailInput(given);
|
|
136
|
+
return startChange(async (tx) => {
|
|
137
|
+
const user = await tx.users.findById(id);
|
|
138
|
+
if (!user) {
|
|
139
|
+
throw new AppError(404, "There is no such account.", { code: "auth.local.emailChange.accountNotFound" });
|
|
140
|
+
}
|
|
141
|
+
return user;
|
|
142
|
+
}, email);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Uses the link: while it is the account's waiting change, the email changes to it.
|
|
147
|
+
* @param {{ token: string }} input
|
|
148
|
+
*/
|
|
149
|
+
async function confirmEmailChange(input) {
|
|
150
|
+
if (!enabled) return throwUnsupportedAuthOperation("confirmEmailChange");
|
|
151
|
+
const payload = verifySignedToken(String(input?.token || ""), config.sessionSecret);
|
|
152
|
+
if (payload?.purpose !== EMAIL_CHANGE_PURPOSE || !payload.sub || !payload.email) {
|
|
153
|
+
throw linkInvalidError();
|
|
154
|
+
}
|
|
155
|
+
const email = String(payload.email);
|
|
156
|
+
const changed = await backend.withTransaction(async (tx) => {
|
|
157
|
+
const user = await tx.users.findById(String(payload.sub));
|
|
158
|
+
if (!user || user.pendingEmail !== email) {
|
|
159
|
+
throw linkInvalidError();
|
|
160
|
+
}
|
|
161
|
+
if (await tx.users.findByEmail(email)) {
|
|
162
|
+
throw emailTakenError();
|
|
163
|
+
}
|
|
164
|
+
const updated = await tx.users.updateEmail(user.id, email);
|
|
165
|
+
await tx.recovery.consumeForUser(user.id, { idPrefix: RESET_TOKEN_PREFIX });
|
|
166
|
+
return { user: updated, oldEmail: user.email };
|
|
167
|
+
});
|
|
168
|
+
deliveries.send("the email change notice", changed.oldEmail, () =>
|
|
169
|
+
emailChangeSender({ type: "notice", email: changed.oldEmail, newEmail: email }));
|
|
170
|
+
// After the transaction, so the request holds one database connection at a time: the application's profile
|
|
171
|
+
// takes the new email now, rather than at the account's next request.
|
|
172
|
+
await buildProfileChangePayload({ user: changed.user, profileProjector });
|
|
173
|
+
return { ok: true, email };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
requestEmailChange,
|
|
178
|
+
requestEmailChangeForUser,
|
|
179
|
+
confirmEmailChange
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export { createLocalEmailChange, createLoggedEmailChangeSender };
|