@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.
@@ -21,7 +21,8 @@ function parseUsers(content) {
21
21
  const users = [];
22
22
  for (const line of String(content || "").split("\n").filter(Boolean)) {
23
23
  const parts = splitLine(line, "user");
24
- if (parts.length !== 12) {
24
+ // Twelve fields, or thirteen since an account keeps its waiting email change.
25
+ if (parts.length !== 12 && parts.length !== 13) {
25
26
  throw new Error("Invalid user record field count.");
26
27
  }
27
28
  users.push({
@@ -36,7 +37,8 @@ function parseUsers(content) {
36
37
  },
37
38
  createdAt: decodeField(parts[9]),
38
39
  updatedAt: decodeField(parts[10]),
39
- disabled: parts[11] === "1"
40
+ disabled: parts[11] === "1",
41
+ pendingEmail: decodeField(parts[12])
40
42
  });
41
43
  }
42
44
  return users;
@@ -58,7 +60,8 @@ function serializeUsers(users) {
58
60
  user.password.hash,
59
61
  encodeField(user.createdAt),
60
62
  encodeField(user.updatedAt),
61
- user.disabled ? "1" : "0"
63
+ user.disabled ? "1" : "0",
64
+ encodeField(user.pendingEmail)
62
65
  ].join(":")
63
66
  )
64
67
  .join("\n") + (users.length > 0 ? "\n" : "");
@@ -68,8 +71,9 @@ function parseSessions(content) {
68
71
  const sessions = [];
69
72
  for (const line of String(content || "").split("\n").filter(Boolean)) {
70
73
  const parts = splitLine(line, "session");
71
- // A session written before second factors has no tenth field: it has not proved one.
72
- if (parts.length !== 9 && parts.length !== 10) {
74
+ // A session written before second factors has no tenth field: it has not proved one. One written before sessions
75
+ // kept where they were seen has no eleventh to thirteenth: nobody knows where or when it was last seen.
76
+ if (parts.length !== 9 && parts.length !== 10 && parts.length !== 13) {
73
77
  throw new Error("Invalid session record field count.");
74
78
  }
75
79
  sessions.push({
@@ -80,7 +84,10 @@ function parseSessions(content) {
80
84
  createdAt: decodeField(parts[6]),
81
85
  expiresAt: decodeField(parts[7]),
82
86
  revokedAt: decodeField(parts[8] || ""),
83
- secondFactorAt: decodeField(parts[9] || "")
87
+ secondFactorAt: decodeField(parts[9] || ""),
88
+ ip: decodeField(parts[10] || ""),
89
+ userAgent: decodeField(parts[11] || ""),
90
+ lastSeenAt: decodeField(parts[12] || "")
84
91
  });
85
92
  }
86
93
  return sessions;
@@ -100,7 +107,10 @@ function serializeSessions(sessions) {
100
107
  encodeField(session.createdAt),
101
108
  encodeField(session.expiresAt),
102
109
  encodeField(session.revokedAt || ""),
103
- encodeField(session.secondFactorAt || "")
110
+ encodeField(session.secondFactorAt || ""),
111
+ encodeField(session.ip || ""),
112
+ encodeField(session.userAgent || ""),
113
+ encodeField(session.lastSeenAt || "")
104
114
  ].join(":")
105
115
  )
106
116
  .join("\n") + (sessions.length > 0 ? "\n" : "");
@@ -2,9 +2,11 @@ export { createLocalAuthService } from "./service.js";
2
2
  export { createLocalDeliveries } from "./deliveries.js";
3
3
  export { resolveLocalAuthConfig } from "./config.js";
4
4
  export { createLoggedConfirmationSender } from "./emailConfirmation.js";
5
+ export { createLoggedEmailChangeSender } from "./emailChange.js";
5
6
  export { createLoggedRecoverySender } from "./passwordFlows.js";
6
7
  export { createLocalFileBackend } from "./fileBackend.js";
7
8
  export { createLoggedSecondFactorEvents } from "./secondFactor.js";
9
+ export { createLoggedSignInEvents } from "./sessions.js";
8
10
  export { SETUP_CODE_ENV, SETUP_CODE_FILE, createFirstAccountSetup } from "./firstAccountSetup.js";
9
11
  export {
10
12
  LOCAL_AUTH_USER_REGISTERED_EVENT,
@@ -1,7 +1,7 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { hostOnlyCookieName, normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
3
3
  import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
4
- import { NO_PASSWORD, hasPassword, normalizeDisplayName } from "./accounts.js";
4
+ import { NO_PASSWORD, accountDisabledError, hasPassword, normalizeDisplayName } from "./accounts.js";
5
5
  import { buildAuthPayload } from "./authPayloads.js";
6
6
  import { createOAuthClients } from "./oauth.js";
7
7
  import { cookieOptions, safeRequestCookies } from "./sessions.js";
@@ -100,8 +100,9 @@ function createLocalOAuthFlows({
100
100
  /**
101
101
  * Subject first, then a verified email that matches an existing user, then a
102
102
  * new user created like register; profile sync then provisions it as usual.
103
+ * The sign-in, and the refusal of a disabled account, are sign-in events.
103
104
  */
104
- async function signInWithOAuthIdentity(identity) {
105
+ async function signInWithOAuthIdentity(identity, request) {
105
106
  await firstAccountSetup.start();
106
107
  const result = await backend.withTransaction(async (tx) => {
107
108
  const linked = await tx.identities.findByProviderSubject(identity.provider, identity.providerSubject);
@@ -116,9 +117,12 @@ function createLocalOAuthFlows({
116
117
  password: NO_PASSWORD
117
118
  });
118
119
  }
119
- if (!user || user.disabled) {
120
+ if (!user) {
120
121
  throw new AppError(401, "This account can't sign in.", { code: "auth.local.oauth.accountUnavailable" });
121
122
  }
123
+ if (user.disabled) {
124
+ return { disabled: user };
125
+ }
122
126
  if (!linked) {
123
127
  await tx.identities.create({
124
128
  userId: user.id,
@@ -127,11 +131,18 @@ function createLocalOAuthFlows({
127
131
  email: identity.email
128
132
  });
129
133
  }
130
- return { user, registered, session: await sessions.createSessionForUser(tx, user) };
134
+ return { user, registered, session: await sessions.createSessionForUser(tx, user, { request }) };
131
135
  });
136
+ const method = { method: "provider", provider: identity.provider };
137
+ if (result.disabled) {
138
+ const { id: userId, email } = result.disabled;
139
+ sessions.recordSignInEvent("failed", { ...method, reason: "disabled", userId, email }, request);
140
+ throw accountDisabledError(result.disabled);
141
+ }
132
142
  if (result.registered) {
133
143
  firstAccountSetup.accountCreated();
134
144
  }
145
+ sessions.recordSignInEvent("signedIn", { ...method, userId: result.user.id, email: result.user.email }, request);
135
146
  return {
136
147
  ...(await buildAuthPayload({ user: result.user, session: result.session, profileProjector })),
137
148
  registered: result.registered
@@ -197,7 +208,7 @@ function createLocalOAuthFlows({
197
208
  const identity = await oauthClients.verifiedIdentity(provider, { callbackUrl, attempt });
198
209
  const result = attempt.intent === "link"
199
210
  ? await linkOAuthIdentity(request, attempt, identity, provider)
200
- : await signInWithOAuthIdentity(identity);
211
+ : await signInWithOAuthIdentity(identity, request);
201
212
  return { ...result, provider: provider.id, returnTo: attempt.returnTo };
202
213
  }
203
214
 
@@ -1,4 +1,5 @@
1
1
  import { PASS_TEXTS, createPassError, verifyPass } from "@jskit-ai/auth-pass/server";
2
+ import { accountDisabledError } from "./accounts.js";
2
3
  import { buildAuthPayload } from "./authPayloads.js";
3
4
  import { sha256Base64url } from "./tokens.js";
4
5
 
@@ -15,8 +16,9 @@ async function noPassIdentities() {
15
16
  * Sign-in with a one-time signed pass (`@jskit-ai/auth-pass/server`), for a configuration whose passSignIn
16
17
  * holds the issuer's key, audience and resource. A pass is checked, then recorded as used in the backend, so it signs
17
18
  * in once however many servers share the backend's database, and then the application's pass identity names the
18
- * account it signs in: one that is missing or disabled is refused as unmapped. The session is an ordinary one, as a
19
- * password sign-in makes.
19
+ * account it signs in: one that is missing is refused as unmapped, and a disabled one is told it is disabled, as its
20
+ * right password is. The session is an ordinary one, as a password sign-in makes. The sign-in, and the refusal of a
21
+ * disabled account, are sign-in events; a pass that names no account signs no account in, and is none.
20
22
  * @param {object} dependencies
21
23
  * @param {import("../types.js").AuthLocalBackend} dependencies.backend
22
24
  * @param {import("../types.js").AuthLocalConfig} dependencies.config
@@ -28,8 +30,11 @@ async function noPassIdentities() {
28
30
  function createLocalPassSignIn({ backend, config, passIdentity, profileProjector, sessions }) {
29
31
  const settings = config.passSignIn;
30
32
 
31
- /** @param {{ pass: string }} input */
32
- async function signInWithPass(input) {
33
+ /**
34
+ * @param {{ pass: string }} input
35
+ * @param {object | null} [request] The request that posted the pass, where the new session is first seen from.
36
+ */
37
+ async function signInWithPass(input, request = null) {
33
38
  const pass = verifyPass(input.pass, settings);
34
39
  // Kept by the hash of its id, which the issuer chose, until the pass could no longer be used anyway. The expired
35
40
  // ones go in a transaction of their own: in the same one, the range their delete locks would make two concurrent
@@ -42,10 +47,15 @@ function createLocalPassSignIn({ backend, config, passIdentity, profileProjector
42
47
  }
43
48
  const userId = await passIdentity(pass);
44
49
  const user = userId ? await backend.withTransaction((tx) => tx.users.findById(userId)) : null;
45
- if (!user || user.disabled) {
50
+ if (!user) {
46
51
  throw createPassError(PASS_TEXTS.passUnmapped);
47
52
  }
48
- const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user));
53
+ if (user.disabled) {
54
+ sessions.recordSignInEvent("failed", { method: "pass", reason: "disabled", userId: user.id, email: user.email }, request);
55
+ throw accountDisabledError(user);
56
+ }
57
+ const session = await backend.withTransaction((tx) => sessions.createSessionForUser(tx, user, { request }));
58
+ sessions.recordSignInEvent("signedIn", { method: "pass", userId: user.id, email: user.email }, request);
49
59
  // After the transaction, as a password sign-in does: the profile projector works in transactions of its own.
50
60
  return buildAuthPayload({ user, session, profileProjector });
51
61
  }
@@ -96,7 +96,7 @@ function createLocalPasswordFlows({ backend, config, deliveries, passwords, prof
96
96
  return requested;
97
97
  }
98
98
 
99
- async function completePasswordRecovery(input) {
99
+ async function completePasswordRecovery(input, request = null) {
100
100
  if (!recoveryEnabled) {
101
101
  throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
102
102
  }
@@ -123,10 +123,12 @@ function createLocalPasswordFlows({ backend, config, deliveries, passwords, prof
123
123
  user,
124
124
  session: await sessions.createSessionForUser(tx, user, {
125
125
  purpose: "recovery",
126
- ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
126
+ ttlSeconds: RECOVERY_SESSION_TTL_SECONDS,
127
+ request
127
128
  })
128
129
  };
129
130
  });
131
+ sessions.recordSignInEvent("signedIn", { method: "recovery", userId: user.id, email: user.email }, request);
130
132
  // After the transaction, so the request holds one database connection at a time: the profile projector works in
131
133
  // transactions of its own.
132
134
  return buildAuthPayload({ user, session, profileProjector });
@@ -98,8 +98,8 @@ function createLocalAuthRegisterHookDecorator({ decoratorId = "auth.local.regist
98
98
  Object.defineProperties(Object.create(authService), {
99
99
  register: {
100
100
  enumerable: true,
101
- value: async function register(input) {
102
- const result = await authService.register(input);
101
+ value: async function register(input, request = null) {
102
+ const result = await authService.register(input, request);
103
103
  if (result.requiresEmailConfirmation !== true) {
104
104
  await runRegisterHook({ hook: registerHook, result, logger });
105
105
  }
@@ -108,8 +108,8 @@ function createLocalAuthRegisterHookDecorator({ decoratorId = "auth.local.regist
108
108
  },
109
109
  confirmRegistration: {
110
110
  enumerable: true,
111
- value: async function confirmRegistration(input) {
112
- const result = await authService.confirmRegistration(input);
111
+ value: async function confirmRegistration(input, request = null) {
112
+ const result = await authService.confirmRegistration(input, request);
113
113
  await runRegisterHook({ hook: registerHook, result, logger });
114
114
  return result;
115
115
  }
@@ -5,6 +5,7 @@ import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupp
5
5
  import { createLocalAccounts } from "./accounts.js";
6
6
  import { PROVIDER_ID } from "./authPayloads.js";
7
7
  import { createLocalDeliveries } from "./deliveries.js";
8
+ import { createLocalEmailChange } from "./emailChange.js";
8
9
  import { confirmEveryRegistrationByLink, createLocalEmailConfirmation } from "./emailConfirmation.js";
9
10
  import { createFirstAccountSetup } from "./firstAccountSetup.js";
10
11
  import { createLocalOAuthFlows } from "./oauthFlows.js";
@@ -42,9 +43,11 @@ const NO_PASS_SIGN_IN = Object.freeze({
42
43
  * `auth.local.confirmation-mode`; by default every registration waits for its link.
43
44
  * @param {import("../types.js").AuthLocalConfirmationSender} dependencies.confirmationSender The
44
45
  * `auth.local.confirmation-sender`, or one made by createLoggedConfirmationSender.
45
- * @param {import("../types.js").AuthLocalDeliveries} [dependencies.deliveries] Sends the password reset and new
46
- * confirmation link emails after their requests have answered; by default, its own, whose settled() nothing waits
47
- * for. The provider passes the one its shutdown waits for.
46
+ * @param {import("../types.js").AuthLocalDeliveries} [dependencies.deliveries] Sends the password reset, new
47
+ * confirmation link and email change emails, and hands over the sign-in events, after their requests have answered;
48
+ * by default, its own, whose settled() nothing waits for. The provider passes the one its shutdown waits for.
49
+ * @param {import("../types.js").AuthLocalEmailChangeSender} dependencies.emailChangeSender The
50
+ * `auth.local.email-change-sender`, or one made by createLoggedEmailChangeSender.
48
51
  * @param {import("../types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup] The first
49
52
  * account's setup code, already started by the provider; by default, one that starts on first use.
50
53
  * @param {import("@jskit-ai/auth-core/server/types").AuthInvitationContextResolver} dependencies.invitationContextResolver
@@ -59,6 +62,8 @@ const NO_PASS_SIGN_IN = Object.freeze({
59
62
  * `auth.local.recovery-sender`, or one made by createLoggedRecoverySender.
60
63
  * @param {import("../types.js").AuthLocalSecondFactorEvents} dependencies.secondFactorEvents The
61
64
  * `auth.local.second-factor-events`, or one made by createLoggedSecondFactorEvents.
65
+ * @param {import("../types.js").AuthLocalSignInEvents} dependencies.signInEvents The `auth.local.sign-in-events`, or
66
+ * one made by createLoggedSignInEvents; it is given each event through `deliveries`.
62
67
  */
63
68
  function createLocalAuthService({
64
69
  backend,
@@ -66,6 +71,7 @@ function createLocalAuthService({
66
71
  confirmationMode = confirmEveryRegistrationByLink,
67
72
  confirmationSender,
68
73
  deliveries: givenDeliveries = null,
74
+ emailChangeSender,
69
75
  firstAccountSetup: givenFirstAccountSetup = null,
70
76
  invitationContextResolver,
71
77
  logger,
@@ -73,7 +79,8 @@ function createLocalAuthService({
73
79
  passwordStrategy,
74
80
  profileProjector,
75
81
  recoverySender,
76
- secondFactorEvents
82
+ secondFactorEvents,
83
+ signInEvents
77
84
  }) {
78
85
  const passwords = normalizePasswordStrategy(passwordStrategy);
79
86
  const firstAccountSetup = givenFirstAccountSetup ?? createFirstAccountSetup({ backend, config, logger });
@@ -109,6 +116,8 @@ function createLocalAuthService({
109
116
  },
110
117
  emailConfirmation: config.emailConfirmation,
111
118
  emailConfirmationCode: config.emailConfirmation,
119
+ // Off in staging and production without an auth.local.email-change-sender, which sends the links.
120
+ emailChange: config.emailChangeDelivery !== "off",
112
121
  profileUpdate: true,
113
122
  providerLinking: {
114
123
  start: oauthEnabled,
@@ -131,7 +140,7 @@ function createLocalAuthService({
131
140
  features: { ...capabilitiesForFirstAccount.features, firstAccountSetupCode: true }
132
141
  });
133
142
 
134
- const sessions = createLocalSessions({ appProfileProjection, backend, config, profileProjector });
143
+ const sessions = createLocalSessions({ appProfileProjection, backend, config, deliveries, profileProjector, signInEvents });
135
144
  const emailConfirmation = createLocalEmailConfirmation({
136
145
  backend,
137
146
  config,
@@ -165,6 +174,15 @@ function createLocalAuthService({
165
174
  recoverySender,
166
175
  sessions
167
176
  });
177
+ const emailChange = createLocalEmailChange({
178
+ backend,
179
+ config,
180
+ deliveries,
181
+ emailChangeSender,
182
+ passwords,
183
+ profileProjector,
184
+ sessions
185
+ });
168
186
  const securityStatus = createLocalSecurityStatus({ backend, config, oauthProvidersById, sessions });
169
187
  const oauthFlows = createLocalOAuthFlows({
170
188
  backend,
@@ -199,11 +217,11 @@ function createLocalAuthService({
199
217
  return emailConfirmation.resend(input);
200
218
  }
201
219
 
202
- function confirmRegistration(input) {
220
+ function confirmRegistration(input, request = null) {
203
221
  if (!config.emailConfirmation) {
204
222
  return throwUnsupportedAuthOperation("confirmRegistration");
205
223
  }
206
- return emailConfirmation.confirm(input);
224
+ return emailConfirmation.confirm(input, request);
207
225
  }
208
226
 
209
227
  function requestOtpLogin() {
@@ -243,6 +261,9 @@ function createLocalAuthService({
243
261
  resetPassword: passwordFlows.resetPassword,
244
262
  changePassword: passwordFlows.changePassword,
245
263
  updateDisplayName: accounts.updateDisplayName,
264
+ requestEmailChange: emailChange.requestEmailChange,
265
+ requestEmailChangeForUser: emailChange.requestEmailChangeForUser,
266
+ confirmEmailChange: emailChange.confirmEmailChange,
246
267
  getSecurityStatus: securityStatus.getSecurityStatus,
247
268
  // readable-check: allow setter-seam - not a slot: setPasswordSignInEnabled is an auth.service operation
248
269
  setPasswordSignInEnabled,
@@ -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,
@@ -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 }) {
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
+ }
92
130
  const { devAuth, isDeployed } = config;
93
131
  // Staging and production cookies are Secure, so they are also host-only __Host- cookies.
94
132
  const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isDeployed);
95
133
  const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isDeployed);
96
134
  const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isDeployed);
97
135
 
98
- async function createSessionForUser(tx, user, { purpose = "normal", ttlSeconds = REFRESH_TTL_SECONDS } = {}) {
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
  }
@@ -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 }) {