@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.
@@ -8,6 +8,10 @@ const REFRESH_TOKEN_COOKIE_NAME = "jskit_local_refresh_token";
8
8
  const RECOVERY_TOKEN_COOKIE_NAME = "jskit_local_recovery_token";
9
9
  const ACCESS_TTL_SECONDS = 15 * 60;
10
10
  const REFRESH_TTL_SECONDS = 60 * 60 * 24 * 30;
11
+ // A session is noted as seen again at most this often, so most requests write nothing.
12
+ const SEEN_AGAIN_AFTER_MS = 5 * 60 * 1000;
13
+ // The longest browser description a session keeps.
14
+ const USER_AGENT_MAX_LENGTH = 512;
11
15
 
12
16
  function nowSeconds() {
13
17
  return Math.floor(Date.now() / 1000);
@@ -17,6 +21,29 @@ function safeRequestCookies(request) {
17
21
  return request && request.cookies && typeof request.cookies === "object" ? request.cookies : {};
18
22
  }
19
23
 
24
+ /**
25
+ * Where a request comes from, as its session keeps it: the client's address and its browser's description, each ""
26
+ * when the request does not say (an internal call has no request).
27
+ * @param {{ ip?: string, headers?: Record<string, unknown> } | null | undefined} request
28
+ */
29
+ function requestClient(request) {
30
+ return {
31
+ ip: String(request?.ip || ""),
32
+ userAgent: String(request?.headers?.["user-agent"] || "").slice(0, USER_AGENT_MAX_LENGTH)
33
+ };
34
+ }
35
+
36
+ /**
37
+ * The `auth.local.sign-in-events` default when no feature provides one: local auth logs each sign-in event.
38
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
39
+ * @returns {import("../types.js").AuthLocalSignInEvents}
40
+ */
41
+ function createLoggedSignInEvents(logger) {
42
+ return async function logSignInEvent(event) {
43
+ logger.info({ signInEvent: event }, `Local auth sign-in: ${event.type}.`);
44
+ };
45
+ }
46
+
20
47
  function unauthenticatedAuthResult(clearSession = false) {
21
48
  return {
22
49
  authenticated: false,
@@ -29,20 +56,20 @@ function unauthenticatedAuthResult(clearSession = false) {
29
56
  /**
30
57
  * A local auth cookie: httpOnly at Path=/, Secure in staging and production, with the application's SameSite
31
58
  * (AUTH_COOKIE_SAME_SITE).
32
- * @param {Pick<import("../types.js").AuthLocalConfig, "isDeployed" | "cookieSameSite">} config
59
+ * @param {Pick<import("../types.js").AuthLocalConfig, "isStagingOrProduction" | "cookieSameSite">} config
33
60
  * @param {number} maxAge
34
61
  */
35
- function cookieOptions({ isDeployed, cookieSameSite }, maxAge) {
62
+ function cookieOptions({ isStagingOrProduction, cookieSameSite }, maxAge) {
36
63
  return {
37
64
  path: "/",
38
65
  httpOnly: true,
39
66
  sameSite: cookieSameSite,
40
- secure: isDeployed,
67
+ secure: isStagingOrProduction,
41
68
  maxAge
42
69
  };
43
70
  }
44
71
 
45
- /** @param {Pick<import("../types.js").AuthLocalConfig, "isDeployed" | "cookieSameSite">} config */
72
+ /** @param {Pick<import("../types.js").AuthLocalConfig, "isStagingOrProduction" | "cookieSameSite">} config */
46
73
  function clearCookieOptions(config) {
47
74
  return [cookieOptions(config, 0), { ...cookieOptions(config, 0), path: "/api" }];
48
75
  }
@@ -82,27 +109,46 @@ function buildSessionPayload({ user, session, refreshToken, secret }) {
82
109
  * cookies, writing and clearing those cookies, and revoking sessions. An
83
110
  * authenticated request's answer names its session (`sessionId`) and when the
84
111
  * session last proved its second factor (`secondFactorAt`, "" when it has not).
112
+ * A session keeps where it was last seen from (`ip`, `userAgent`) and when
113
+ * (`lastSeenAt`): the request that signed it in, then one that finds it more
114
+ * than five minutes later. Each sign-in, and each refused one, is an event for
115
+ * the application's `auth.local.sign-in-events` (recordSignInEvent).
85
116
  * @param {object} dependencies
86
117
  * @param {boolean} dependencies.appProfileProjection True when the application keeps profiles.
87
118
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
88
119
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
120
+ * @param {import("../types.js").AuthLocalDeliveries} dependencies.deliveries Hands each sign-in event over after the
121
+ * request has answered.
89
122
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
123
+ * @param {import("../types.js").AuthLocalSignInEvents} dependencies.signInEvents The `auth.local.sign-in-events`, or
124
+ * one made by createLoggedSignInEvents.
90
125
  */
91
- function createLocalSessions({ appProfileProjection, backend, config, profileProjector }) {
92
- const { devAuth, isDeployed } = config;
126
+ function createLocalSessions({ appProfileProjection, backend, config, deliveries, profileProjector, signInEvents }) {
127
+ if (!signInEvents) {
128
+ throw new TypeError("createLocalSessions() takes signInEvents, the auth.local.sign-in-events function each sign-in event is given.");
129
+ }
130
+ const { devAuth, isStagingOrProduction } = config;
93
131
  // Staging and production cookies are Secure, so they are also host-only __Host- cookies.
94
- const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isDeployed);
95
- const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isDeployed);
96
- const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isDeployed);
97
-
98
- async function createSessionForUser(tx, user, { purpose = "normal", ttlSeconds = REFRESH_TTL_SECONDS } = {}) {
132
+ const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isStagingOrProduction);
133
+ const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isStagingOrProduction);
134
+ const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isStagingOrProduction);
135
+
136
+ /**
137
+ * A new session of the user, seen now from where the request that signs it in comes from.
138
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
139
+ * @param {{ id: string }} user
140
+ * @param {{ purpose?: string, ttlSeconds?: number, request?: object | null }} [options]
141
+ */
142
+ async function createSessionForUser(tx, user, { purpose = "normal", ttlSeconds = REFRESH_TTL_SECONDS, request = null } = {}) {
99
143
  const refreshToken = randomToken(36);
100
144
  const session = await tx.sessions.create({
101
145
  id: createId("ses"),
102
146
  userId: user.id,
103
147
  tokenHash: sha256Base64url(refreshToken),
104
148
  purpose,
105
- expiresAt: isoFromNow(ttlSeconds)
149
+ expiresAt: isoFromNow(ttlSeconds),
150
+ ...requestClient(request),
151
+ lastSeenAt: new Date().toISOString()
106
152
  });
107
153
  return buildSessionPayload({
108
154
  user,
@@ -112,7 +158,22 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
112
158
  });
113
159
  }
114
160
 
115
- async function resolveValidSessionByRefreshToken(refreshToken) {
161
+ /**
162
+ * A session found more than five minutes after it was last seen is seen again now, from where the request comes
163
+ * from; a request that does not say keeps where it was last seen from.
164
+ * @param {import("../types.js").AuthLocalBackendTransaction} tx
165
+ * @param {{ id: string, lastSeenAt?: string }} session
166
+ * @param {object | null} request
167
+ */
168
+ async function noteSessionSeen(tx, session, request) {
169
+ const now = Date.now();
170
+ if (session.lastSeenAt && now - Date.parse(session.lastSeenAt) < SEEN_AGAIN_AFTER_MS) {
171
+ return;
172
+ }
173
+ await tx.sessions.touch(session.id, { lastSeenAt: new Date(now).toISOString(), ...requestClient(request) });
174
+ }
175
+
176
+ async function resolveValidSessionByRefreshToken(refreshToken, request) {
116
177
  const tokenHash = sha256Base64url(refreshToken);
117
178
  return backend.withTransaction(async (tx) => {
118
179
  const session = await tx.sessions.findByTokenHash(tokenHash);
@@ -123,6 +184,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
123
184
  if (!user || user.disabled) {
124
185
  return null;
125
186
  }
187
+ await noteSessionSeen(tx, session, request);
126
188
  return {
127
189
  user,
128
190
  session
@@ -186,6 +248,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
186
248
  if (!user || user.disabled) {
187
249
  return null;
188
250
  }
251
+ await noteSessionSeen(tx, session, request);
189
252
  return { user, session };
190
253
  });
191
254
  if (resolved && isAuthenticatingSession(resolved.session)) {
@@ -221,7 +284,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
221
284
  return unauthenticatedAuthResult(Boolean(accessToken));
222
285
  }
223
286
 
224
- const resolved = await resolveValidSessionByRefreshToken(refreshToken);
287
+ const resolved = await resolveValidSessionByRefreshToken(refreshToken, request);
225
288
  if (!resolved) {
226
289
  return unauthenticatedAuthResult(true);
227
290
  }
@@ -310,7 +373,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
310
373
  }
311
374
  for (const options of clearCookieOptions(config)) {
312
375
  // A __Host- cookie only exists at Path=/.
313
- if (options.path === "/" || !isDeployed) {
376
+ if (options.path === "/" || !isStagingOrProduction) {
314
377
  reply.clearCookie(ACCESS_TOKEN_COOKIE, options);
315
378
  reply.clearCookie(REFRESH_TOKEN_COOKIE, options);
316
379
  reply.clearCookie(RECOVERY_TOKEN_COOKIE, options);
@@ -347,7 +410,7 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
347
410
  }
348
411
  const cookies = safeRequestCookies(request);
349
412
  const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
350
- const currentSession = refreshToken ? await resolveValidSessionByRefreshToken(refreshToken) : null;
413
+ const currentSession = refreshToken ? await resolveValidSessionByRefreshToken(refreshToken, request) : null;
351
414
  const count = await backend.withTransaction((tx) =>
352
415
  tx.sessions.revokeForUser(authResult.actor.providerUserId, {
353
416
  exceptSessionId: currentSession?.session?.id
@@ -360,8 +423,23 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
360
423
  };
361
424
  }
362
425
 
426
+ /**
427
+ * Hands one sign-in event to the application, once the request has answered, so neither the recorder's time nor
428
+ * its failure reaches the person signing in: a sign-in (`signedIn`) or a refused one (`failed`, with its `reason`),
429
+ * by `method`, of the account `userId` names ("" when the email names none) at `email`, from where the request came,
430
+ * now. Called after the sign-in's transaction, so a sign-in that did not happen is never an event.
431
+ * @param {"signedIn" | "failed"} type
432
+ * @param {{ method: string, email: string, userId?: string, reason?: string, provider?: string }} subject
433
+ * @param {object | null} request
434
+ */
435
+ function recordSignInEvent(type, { email, userId = "", ...details }, request) {
436
+ const event = { type, ...details, userId, email, ...requestClient(request), at: new Date().toISOString() };
437
+ deliveries.send("the sign-in event", email, () => signInEvents(event));
438
+ }
439
+
363
440
  return Object.freeze({
364
441
  createSessionForUser,
442
+ recordSignInEvent,
365
443
  authenticateRequest,
366
444
  forgetRequestAuthentication,
367
445
  updateRequestActor,
@@ -376,4 +454,4 @@ function createLocalSessions({ appProfileProjection, backend, config, profilePro
376
454
  });
377
455
  }
378
456
 
379
- export { cookieOptions, createLocalSessions, safeRequestCookies };
457
+ export { cookieOptions, createLocalSessions, createLoggedSignInEvents, safeRequestCookies };
@@ -11,6 +11,7 @@ import {
11
11
  confirmEveryRegistrationByLink,
12
12
  createLoggedConfirmationSender
13
13
  } from "../lib/emailConfirmation.js";
14
+ import { createLoggedEmailChangeSender } from "../lib/emailChange.js";
14
15
  import { createLocalFileBackend } from "../lib/fileBackend.js";
15
16
  import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
16
17
  import { noPassIdentities } from "../lib/passSignIn.js";
@@ -18,6 +19,7 @@ import { createLoggedRecoverySender } from "../lib/passwordFlows.js";
18
19
  import { scryptPasswordStrategy } from "../lib/passwords.js";
19
20
  import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
20
21
  import { createLocalAuthService } from "../lib/service.js";
22
+ import { createLoggedSignInEvents } from "../lib/sessions.js";
21
23
 
22
24
  // The emails each started auth service is still sending, by the service its setup gave out, for its shutdown.
23
25
  const deliveriesByService = new WeakMap();
@@ -61,11 +63,13 @@ const AuthLocalProvider = defineProvider({
61
63
  backend: "auth.local.backend",
62
64
  confirmationMode: "auth.local.confirmation-mode",
63
65
  confirmationSender: "auth.local.confirmation-sender",
66
+ emailChangeSender: "auth.local.email-change-sender",
64
67
  passIdentity: "auth.local.pass-identity",
65
68
  passwordStrategy: "auth.local.password-strategy",
66
69
  profileProjector: "auth.profile.projector",
67
70
  recoverySender: "auth.local.recovery-sender",
68
- secondFactorEvents: "auth.local.second-factor-events"
71
+ secondFactorEvents: "auth.local.second-factor-events",
72
+ signInEvents: "auth.local.sign-in-events"
69
73
  },
70
74
  provides: {
71
75
  authService: "auth.service"
@@ -81,6 +85,8 @@ const AuthLocalProvider = defineProvider({
81
85
  * `auth.local.confirmation-mode`, when one is installed.
82
86
  * @param {import("../types.js").AuthLocalConfirmationSender | null} dependencies.confirmationSender The
83
87
  * `auth.local.confirmation-sender`, when one is installed.
88
+ * @param {import("../types.js").AuthLocalEmailChangeSender | null} dependencies.emailChangeSender The
89
+ * `auth.local.email-change-sender`, when one is installed.
84
90
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
85
91
  * @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
86
92
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
@@ -91,6 +97,8 @@ const AuthLocalProvider = defineProvider({
91
97
  * @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
92
98
  * @param {import("../types.js").AuthLocalSecondFactorEvents | null} dependencies.secondFactorEvents The
93
99
  * `auth.local.second-factor-events`, when one is installed.
100
+ * @param {import("../types.js").AuthLocalSignInEvents | null} dependencies.signInEvents The
101
+ * `auth.local.sign-in-events`, when one is installed.
94
102
  */
95
103
  async boot(
96
104
  {
@@ -98,6 +106,7 @@ const AuthLocalProvider = defineProvider({
98
106
  backend,
99
107
  confirmationMode,
100
108
  confirmationSender,
109
+ emailChangeSender,
101
110
  env,
102
111
  extensions,
103
112
  logger,
@@ -105,14 +114,23 @@ const AuthLocalProvider = defineProvider({
105
114
  passwordStrategy,
106
115
  profileProjector,
107
116
  recoverySender,
108
- secondFactorEvents
117
+ secondFactorEvents,
118
+ signInEvents
109
119
  },
110
120
  { outputs }
111
121
  ) {
112
122
  const fileBackend = backend === null;
113
123
  const emailRecovery = recoverySender !== null;
114
124
  const emailConfirmationSender = confirmationSender !== null;
115
- const config = resolveLocalAuthConfig({ appRoot, env, fileBackend, emailRecovery, emailConfirmationSender });
125
+ const emailedChange = emailChangeSender !== null;
126
+ const config = resolveLocalAuthConfig({
127
+ appRoot,
128
+ env,
129
+ fileBackend,
130
+ emailRecovery,
131
+ emailConfirmationSender,
132
+ emailChangeSender: emailedChange
133
+ });
116
134
  if (config.passSignIn && passIdentity === null) {
117
135
  throw new Error("AUTH_PASS_PUBLIC_KEY turns on one-time pass sign-in, and no auth.local.pass-identity is installed to name the account each pass signs in. Install one, or unset AUTH_PASS_PUBLIC_KEY.");
118
136
  }
@@ -133,6 +151,9 @@ const AuthLocalProvider = defineProvider({
133
151
  ? sendAsAppEnvironmentSays({ env, logger, sender: confirmationSender, name: "email confirmation" })
134
152
  : createLoggedConfirmationSender(logger),
135
153
  deliveries,
154
+ emailChangeSender: emailedChange
155
+ ? sendAsAppEnvironmentSays({ env, logger, sender: emailChangeSender, name: "email change" })
156
+ : createLoggedEmailChangeSender(logger),
136
157
  firstAccountSetup,
137
158
  invitationContextResolver: extensions.resolveInvitationContextResolver(),
138
159
  logger,
@@ -142,14 +163,15 @@ const AuthLocalProvider = defineProvider({
142
163
  recoverySender: emailRecovery
143
164
  ? sendAsAppEnvironmentSays({ env, logger, sender: recoverySender, name: "password reset" })
144
165
  : createLoggedRecoverySender(logger),
145
- secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger)
166
+ secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger),
167
+ signInEvents: signInEvents ?? createLoggedSignInEvents(logger)
146
168
  });
147
169
  // 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
148
170
  attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
149
171
  },
150
172
  /**
151
- * Waits for the emails local auth is still sending, for a while: a reset or confirmation link asked for just
152
- * before the server stops still arrives. It stops before the providers it depends on, such as the sender's. A
173
+ * Waits for the emails local auth is still sending, and the sign-in events it is handing over, for a while: a reset
174
+ * or confirmation link asked for just before the server stops still arrives. It stops before the providers it depends on, such as the sender's. A
153
175
  * boot that stopped before making its service sent nothing.
154
176
  */
155
177
  async shutdown(_dependencies, { outputs }) {
@@ -14,8 +14,15 @@
14
14
  * findByEmail(email: string): Promise<object | null>,
15
15
  * hasAny(): Promise<boolean>,
16
16
  * updatePassword(userId: string, passwordRecord: object): Promise<object | null>,
17
- * updateProfile(userId: string, updates: object): Promise<object | null>
18
- * }} users `hasAny` answers whether any account exists.
17
+ * updateProfile(userId: string, updates: object): Promise<object | null>,
18
+ * updatePendingEmail(userId: string, pendingEmail: string): Promise<object | null>,
19
+ * updateEmail(userId: string, email: string): Promise<object | null>
20
+ * }} users `hasAny` answers whether any account exists. A user whose `disabled` is true has every sign-in and session
21
+ * refused, and a sign-in that proves who it is (the right password, a provider or a pass) is told its
22
+ * `disabledMessage`, or that the account is disabled when it has none; the file backend keeps no message. A user's
23
+ * `pendingEmail` is the address its email change waits to confirm ("" when none): `updatePendingEmail` sets it, and
24
+ * `updateEmail` changes the email to a confirmed address and clears it, refusing an email another account has with
25
+ * a ConflictError.
19
26
  * @property {{
20
27
  * create(input: object): Promise<object>,
21
28
  * findById(sessionId: string): Promise<object | null>,
@@ -23,9 +30,12 @@
23
30
  * revoke(sessionId: string): Promise<object | null>,
24
31
  * revokeForUser(userId: string, options?: object): Promise<number>,
25
32
  * markSecondFactorProved(sessionId: string, secondFactorAt: string): Promise<object | null>,
26
- * clearSecondFactorForUser(userId: string): Promise<number>
33
+ * clearSecondFactorForUser(userId: string): Promise<number>,
34
+ * touch(sessionId: string, seen: { lastSeenAt: string, ip: string, userAgent: string }): Promise<void>
27
35
  * }} sessions A session's `secondFactorAt` is when it last proved its second factor ("" when it has not):
28
- * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user.
36
+ * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user. A session keeps
37
+ * where it was last seen from, `ip` and `userAgent` (`create` takes them with `lastSeenAt`), and when, `lastSeenAt`,
38
+ * each "" when unknown; `touch` notes it seen again, keeping its `ip` or `userAgent` when the new one is "".
29
39
  * @property {{
30
40
  * create(input: object): Promise<object>,
31
41
  * findByTokenHash(tokenHash: string): Promise<object | null>,
@@ -144,6 +154,41 @@
144
154
  * @typedef {(event: AuthLocalSecondFactorEvent) => Promise<void>} AuthLocalSecondFactorEvents
145
155
  */
146
156
 
157
+ /**
158
+ * One sign-in event: a sign-in (`signedIn`) or a refused one (`failed`), by
159
+ * `method`: `password`, `registration` (registering signed in at once),
160
+ * `confirmation` (a registration's email link), `recovery` (a password reset's
161
+ * link), `pass` (a one-time pass) or `provider` (with `provider`, its id, such
162
+ * as `google`). A refusal's `reason` is `invalidCredentials`, `locked` (the
163
+ * email waits after its failures; the password was not checked),
164
+ * `unconfirmed` (the right password of a registration still waiting for its
165
+ * link) or `disabled` (the right password, provider or pass of a disabled
166
+ * account). `userId` is the local account's id, "" when the email names none;
167
+ * `email` is the email signed in, or typed; `ip` and `userAgent` are the
168
+ * request's, "" when there is no request; `at` is an ISO time. No secret,
169
+ * password or token is in it.
170
+ * @typedef {object} AuthLocalSignInEvent
171
+ * @property {"signedIn" | "failed"} type
172
+ * @property {"password" | "registration" | "confirmation" | "recovery" | "pass" | "provider"} method
173
+ * @property {string} userId
174
+ * @property {string} email
175
+ * @property {string} ip
176
+ * @property {string} userAgent
177
+ * @property {string} at
178
+ * @property {"invalidCredentials" | "locked" | "unconfirmed" | "disabled"} [reason]
179
+ * @property {string} [provider]
180
+ */
181
+
182
+ /**
183
+ * The `auth.local.sign-in-events` capability: records each sign-in and each
184
+ * refused one, for an application's own list of an account's sign-ins or its
185
+ * audit log. It is given each event after the request has answered, so a
186
+ * refused sign-in takes the same time whatever it does; when it fails, local
187
+ * auth logs the failure. A stopping server waits for it, for a while. Without
188
+ * one, local auth logs each event.
189
+ * @typedef {(event: AuthLocalSignInEvent) => Promise<void>} AuthLocalSignInEvents
190
+ */
191
+
147
192
  /**
148
193
  * An account's recent failed sign-ins: how many, the last one, and when it may
149
194
  * try again ("" when it need not wait). Times are ISO strings.
@@ -190,6 +235,20 @@
190
235
  * @typedef {(delivery: { email: string, originalEmail?: string, confirmationUrl: string }) => Promise<void>} AuthLocalConfirmationSender
191
236
  */
192
237
 
238
+ /**
239
+ * The `auth.local.email-change-sender` capability: sends what an account's
240
+ * email change sends, each through the application's email. `confirmation`
241
+ * goes to the new address (`email`) with the link that confirms it
242
+ * (`confirmationUrl`), naming the account's current address
243
+ * (`currentEmail`); `notice` goes to the old address (`email`) once the email
244
+ * changed, naming the new one (`newEmail`). It sends as APP_ENV says, like
245
+ * `AuthLocalRecoverySender`. It must reject on failure, which local auth logs,
246
+ * and must not log the link. Without one, a staging or production server has
247
+ * no email change; development and test log each.
248
+ * @typedef {(delivery: { type: "confirmation", email: string, originalEmail?: string, currentEmail: string, confirmationUrl: string }
249
+ * | { type: "notice", email: string, originalEmail?: string, newEmail: string }) => Promise<void>} AuthLocalEmailChangeSender
250
+ */
251
+
193
252
  /**
194
253
  * The `auth.local.confirmation-mode` capability: the application's choice, for
195
254
  * one registration that would wait for its email to be confirmed, of how it is
@@ -139,16 +139,25 @@ test("a failed sign-in checks one password, whether or not its email has one to
139
139
  return scryptPasswordStrategy.verifyPassword(password, record);
140
140
  }
141
141
  };
142
- const { service } = await startService(t, { passwordStrategy });
142
+ const { backend, service } = await startService(t, { passwordStrategy });
143
143
  await service.register({ email: "ada@example.com", password: PASSWORD });
144
+ const password = await scryptPasswordStrategy.hashPassword(PASSWORD);
145
+ await backend.withTransaction((tx) =>
146
+ tx.users.create({ id: "usr_off", email: "off@example.com", displayName: "Off", password, disabled: true }));
144
147
 
145
- for (const email of ["ada@example.com", "nobody@example.com", "NOBODY@example.com", "other@example.com"]) {
148
+ for (const email of ["ada@example.com", "nobody@example.com", "NOBODY@example.com", "other@example.com", "off@example.com"]) {
146
149
  checks.length = 0;
147
- await assert.rejects(service.login({ email, password: "a wrong password" }), { status: 401 }, email);
150
+ await assert.rejects(service.login({ email, password: "a wrong password" }),
151
+ { status: 401, code: "auth.login.invalidCredentials" }, email);
148
152
  assert.deepEqual(checks, ["a wrong password"], email);
149
153
  }
150
154
  // The right password still signs in, with one check.
151
155
  checks.length = 0;
152
156
  assert.equal((await service.login({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
153
157
  assert.deepEqual(checks, [PASSWORD]);
158
+ // A disabled account's right password, and only that, is told the account is disabled.
159
+ checks.length = 0;
160
+ await assert.rejects(service.login({ email: "off@example.com", password: PASSWORD }),
161
+ { status: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
162
+ assert.deepEqual(checks, [PASSWORD]);
154
163
  });
@@ -92,3 +92,28 @@ test("an AUTH_COOKIE_SAME_SITE other than lax or strict stops local auth's start
92
92
  });
93
93
  }
94
94
  });
95
+
96
+ test("in staging and production the OAuth attempt's cookie is the host-only __Host- one, Secure, set and cleared at Path=/",
97
+ async (t) => {
98
+ for (const APP_ENV of ["staging", "production"]) {
99
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-oauth-attempt-"));
100
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
101
+ const service = createService({
102
+ backend: createLocalFileBackend({ storeDir }),
103
+ oauthProviders: [],
104
+ profileProjector: noAppProfiles,
105
+ env: { APP_ENV, NODE_ENV: "production", AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "" }
106
+ });
107
+ const written = [];
108
+ const reply = {
109
+ setCookie: (name, _value, options) => written.push([name, "set", options.path, options.secure]),
110
+ clearCookie: (name, options) => written.push([name, "cleared", options.path, options.secure])
111
+ };
112
+ service.writeOAuthStartCookies(reply, { attempt: "browser-key" });
113
+ service.clearOAuthStartCookies(reply);
114
+ assert.deepEqual(written, [
115
+ ["__Host-jskit_local_oauth_attempt", "set", "/", true],
116
+ ["__Host-jskit_local_oauth_attempt", "cleared", "/", true]
117
+ ], APP_ENV);
118
+ }
119
+ });
@@ -0,0 +1,37 @@
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 { createLocalFileBackend } from "../src/server/lib/index.js";
7
+ import { emailChangeService, exerciseEmailChange } from "../test-support/emailChangeScenario.js";
8
+
9
+ async function fileBackend(t) {
10
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-email-change-"));
11
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
12
+ return { backend: createLocalFileBackend({ storeDir }), storeDir };
13
+ }
14
+
15
+ test("an account's email changes once the link sent to the new address is used, and the old address is told (file backend)", async (t) => {
16
+ const { backend, storeDir } = await fileBackend(t);
17
+ const { adaId } = await exerciseEmailChange(t, backend);
18
+ // Another server on the same store reads the change.
19
+ const reread = createLocalFileBackend({ storeDir });
20
+ assert.equal((await reread.withTransaction((tx) => tx.users.findById(adaId))).email, "ada.second@example.com");
21
+ });
22
+
23
+ test("a waiting change is kept in the file store, and an account stored before it read as having none", async (t) => {
24
+ const { backend, storeDir } = await fileBackend(t);
25
+ const { service } = emailChangeService(backend);
26
+ const ada = await service.register({ email: "ada@example.com", password: "correct horse battery staple" });
27
+ await service.requestEmailChangeForUser({ userId: ada.actor.providerUserId, email: "ada.new@example.com" });
28
+ const reread = createLocalFileBackend({ storeDir });
29
+ assert.equal((await reread.withTransaction((tx) => tx.users.findById(ada.actor.providerUserId))).pendingEmail, "ada.new@example.com");
30
+
31
+ const usersFile = path.join(storeDir, "users.passwd");
32
+ const line = (await fs.readFile(usersFile, "utf8")).trim();
33
+ // The twelve fields an account had before it kept a waiting change.
34
+ await fs.writeFile(usersFile, `${line.split(":").slice(0, 12).join(":")}\n`);
35
+ const older = createLocalFileBackend({ storeDir });
36
+ assert.equal((await older.withTransaction((tx) => tx.users.findById(ada.actor.providerUserId))).pendingEmail, "");
37
+ });
@@ -12,6 +12,7 @@ import {
12
12
  createLocalAuthRegisterHookDecorator,
13
13
  createLocalFileBackend
14
14
  } from "../src/server/lib/index.js";
15
+ import { NO_PASSWORD } from "../src/server/lib/accounts.js";
15
16
  import { sha256Base64url } from "../src/server/lib/tokens.js";
16
17
  import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
17
18
  import {
@@ -153,7 +154,7 @@ test("while a production server waits for its first account, a Google sign-in ca
153
154
  const codes = [];
154
155
  const firstAccountSetup = createFirstAccountSetup({
155
156
  backend,
156
- config: { isDeployed: true, storeDir: backend.storeDir },
157
+ config: { isStagingOrProduction: true, storeDir: backend.storeDir },
157
158
  logger: { warn: (fields) => codes.push(fields.firstAccountSetupCode) }
158
159
  });
159
160
  await firstAccountSetup.start();
@@ -198,6 +199,17 @@ test("a verified email that matches an existing account signs it in and links Go
198
199
  assert.equal(again.actor.email, issuer.account.email);
199
200
  });
200
201
 
202
+ test("a provider sign-in of a disabled account is told the account is disabled, and links nothing", async (t) => {
203
+ const { issuer, backend, service } = await googleSetup(t);
204
+ await backend.withTransaction((tx) => tx.users.create({
205
+ id: "usr_off", email: issuer.account.email, displayName: "Off", password: NO_PASSWORD, disabled: true
206
+ }));
207
+ const { input, request } = await approveAtProvider(service);
208
+ await assert.rejects(service.oauthComplete(input, request),
209
+ { statusCode: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
210
+ assert.deepEqual(await backend.withTransaction((tx) => tx.identities.listForUser("usr_off")), []);
211
+ });
212
+
201
213
  test("a callback with the wrong state, another browser's attempt, or a used attempt is refused", async (t) => {
202
214
  const { backend, service } = await googleSetup(t);
203
215
  const { input, request } = await approveAtProvider(service);