@jskit-ai/auth-provider-local-core 0.2.36 → 0.2.37

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 CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - 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.
6
+ - 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.
7
+ - 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.
8
+ - 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.
9
+ - 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.
10
+ - 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
11
  - **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
12
  - 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
13
  - 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.36",
3
+ "version": "0.2.37",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -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 confirmation senders (createLoggedRecoverySender, createLoggedConfirmationSender), the first account's setup code (createFirstAccountSetup, SETUP_CODE_FILE, SETUP_CODE_ENV), the logged second factor events (createLoggedSecondFactorEvents), 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."
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.30",
76
+ "@jskit-ai/auth-core": "0.2.31",
75
77
  "@jskit-ai/kernel": "0.2.27"
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, 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
231
- * successful sign-in, or a password reset, forgets the failures.
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
- return { waitMs };
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 || user.disabled || !hasPassword(user) || !(await passwordMatches(user.password))) {
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,
@@ -87,17 +87,18 @@ function resolveSetupCode(env, { isDeployed }) {
87
87
  }
88
88
 
89
89
  /**
90
- * APP_PUBLIC_URL, from which recovery and confirmation links and OAuth
91
- * redirect addresses are built, and whose host authenticator apps show beside
92
- * a second factor's codes. Emailed links, OAuth sign-in and a deployed
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 deployed
93
93
  * 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, deployedSecondFactor: boolean }} options
95
+ * @param {{ emailRecovery: boolean, emailedConfirmation: boolean, emailedChange: boolean, oauthEnabled: boolean, deployedSecondFactor: boolean }} options
96
96
  */
97
- function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, oauthEnabled, deployedSecondFactor }) {
97
+ function resolveAppPublicUrl(env, { emailRecovery, emailedConfirmation, emailedChange, oauthEnabled, deployedSecondFactor }) {
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
  }
@@ -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 deployed server (staging or production)
173
+ * without a sender has no email change.
174
+ * @param {{ emailChangeSender: boolean, isDeployed: boolean }} options
175
+ * @returns {"email" | "dev-log" | "off"}
176
+ */
177
+ function resolveEmailChangeDelivery({ emailChangeSender, isDeployed }) {
178
+ if (emailChangeSender) return "email";
179
+ return isDeployed ? "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.
@@ -191,8 +205,9 @@ 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
212
  const { isDeployed } = devAuth;
198
213
  const storeDir = resolveStoreDir(env, appRoot);
@@ -210,9 +225,11 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
210
225
  const confirmationDelivery = resolveConfirmationDelivery(env, { emailConfirmationSender, isDeployed, selfRegistration });
211
226
  const sessionSecret = resolveSessionSecret(env, { storeDir, isDeployed });
212
227
  const secondFactorKey = resolveSecondFactorKey(env, { isDeployed, sessionSecret });
228
+ const emailChangeDelivery = resolveEmailChangeDelivery({ emailChangeSender, isDeployed });
213
229
  const appPublicUrl = resolveAppPublicUrl(env, {
214
230
  emailRecovery,
215
231
  emailedConfirmation: confirmationDelivery === "email",
232
+ emailedChange: emailChangeDelivery === "email",
216
233
  oauthEnabled,
217
234
  deployedSecondFactor: isDeployed && Boolean(secondFactorKey)
218
235
  });
@@ -233,6 +250,7 @@ function resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emai
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, before it stops anyway.
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 };
@@ -155,8 +155,9 @@ function createLocalEmailConfirmation({
155
155
  * code and the password it registered with, and signs the person in. A wrong
156
156
  * password creates nothing and keeps the registration and its link.
157
157
  * @param {{ token: string, password: string }} input
158
+ * @param {object | null} [request] The request that confirms it, where the new session is first seen from.
158
159
  */
159
- async function confirm(input) {
160
+ async function confirm(input, request = null) {
160
161
  const tokenHash = sha256Base64url(String(input.token || "").trim());
161
162
  const waiting = await backend.withTransaction((tx) => tx.registrations.findByTokenHash(tokenHash));
162
163
  if (!waiting || isExpiredIso(waiting.expiresAt)) {
@@ -188,7 +189,7 @@ function createLocalEmailConfirmation({
188
189
  password: registration.password,
189
190
  emailVerifiedAt: new Date().toISOString()
190
191
  });
191
- return { user, session: await sessions.createSessionForUser(tx, user) };
192
+ return { user, session: await sessions.createSessionForUser(tx, user, { request }) };
192
193
  });
193
194
  // Refused after the transaction, so a used-up registration stays deleted.
194
195
  if (outcome.invalid) {
@@ -198,6 +199,7 @@ function createLocalEmailConfirmation({
198
199
  throw emailTakenError();
199
200
  }
200
201
  firstAccountSetup.accountCreated();
202
+ sessions.recordSignInEvent("signedIn", { method: "confirmation", userId: outcome.user.id, email: outcome.user.email }, request);
201
203
  return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector, profileOptions });
202
204
  }
203
205
 
@@ -224,7 +224,8 @@ function createTx(state, touched) {
224
224
  ...clone(input),
225
225
  createdAt: input.createdAt || nowIso(),
226
226
  updatedAt: input.updatedAt || nowIso(),
227
- disabled: input.disabled === true
227
+ disabled: input.disabled === true,
228
+ pendingEmail: input.pendingEmail || ""
228
229
  };
229
230
  state.users.push(user);
230
231
  mark("users");
@@ -260,6 +261,30 @@ function createTx(state, touched) {
260
261
  user.updatedAt = nowIso();
261
262
  mark("users");
262
263
  return clone(user);
264
+ },
265
+ async updatePendingEmail(userId, pendingEmail) {
266
+ const user = state.users.find((entry) => entry.id === userId);
267
+ if (!user) {
268
+ return null;
269
+ }
270
+ user.pendingEmail = String(pendingEmail || "");
271
+ user.updatedAt = nowIso();
272
+ mark("users");
273
+ return clone(user);
274
+ },
275
+ async updateEmail(userId, email) {
276
+ const user = state.users.find((entry) => entry.id === userId);
277
+ if (!user) {
278
+ return null;
279
+ }
280
+ if (state.users.some((entry) => entry.id !== userId && entry.email === email)) {
281
+ throw new ConflictError("An account with this id or email already exists.", { code: "auth.local.accounts.exists" });
282
+ }
283
+ user.email = email;
284
+ user.pendingEmail = "";
285
+ user.updatedAt = nowIso();
286
+ mark("users");
287
+ return clone(user);
263
288
  }
264
289
  }),
265
290
  sessions: Object.freeze({
@@ -269,7 +294,10 @@ function createTx(state, touched) {
269
294
  purpose: input.purpose || "normal",
270
295
  createdAt: input.createdAt || nowIso(),
271
296
  revokedAt: input.revokedAt || "",
272
- secondFactorAt: input.secondFactorAt || ""
297
+ secondFactorAt: input.secondFactorAt || "",
298
+ ip: input.ip || "",
299
+ userAgent: input.userAgent || "",
300
+ lastSeenAt: input.lastSeenAt || ""
273
301
  };
274
302
  state.sessions.push(session);
275
303
  mark("sessions");
@@ -325,6 +353,16 @@ function createTx(state, touched) {
325
353
  mark("sessions");
326
354
  }
327
355
  return count;
356
+ },
357
+ async touch(sessionId, { lastSeenAt, ip, userAgent }) {
358
+ const session = state.sessions.find((entry) => entry.id === sessionId);
359
+ if (!session) {
360
+ return;
361
+ }
362
+ session.lastSeenAt = lastSeenAt;
363
+ session.ip = ip || session.ip;
364
+ session.userAgent = userAgent || session.userAgent;
365
+ mark("sessions");
328
366
  }
329
367
  }),
330
368
  recovery: Object.freeze({