@jskit-ai/auth-provider-local-core 0.2.35 → 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 +7 -0
- package/locales/en.json +9 -1
- package/package.json +8 -6
- package/src/server/lib/accounts.js +41 -11
- package/src/server/lib/config.js +70 -51
- package/src/server/lib/deliveries.js +4 -2
- package/src/server/lib/emailChange.js +183 -0
- package/src/server/lib/emailConfirmation.js +5 -22
- package/src/server/lib/fileBackend.js +40 -2
- package/src/server/lib/fileRecords.js +17 -7
- package/src/server/lib/firstAccountSetup.js +4 -4
- package/src/server/lib/index.js +2 -0
- package/src/server/lib/oauthFlows.js +18 -7
- package/src/server/lib/passSignIn.js +16 -6
- package/src/server/lib/passwordFlows.js +7 -23
- package/src/server/lib/registerHookDecorator.js +4 -4
- package/src/server/lib/service.js +30 -9
- package/src/server/lib/sessions.js +97 -19
- package/src/server/providers/AuthLocalProvider.js +64 -16
- package/src/server/types.js +75 -10
- package/test/accountEnumeration.test.js +12 -3
- package/test/codedTexts.test.js +1 -1
- package/test/cookieSameSite.test.js +1 -1
- package/test/emailChange.test.js +37 -0
- package/test/firstAccountSetup.test.js +6 -6
- package/test/oauthSignIn.test.js +14 -2
- package/test/passSignIn.test.js +1 -1
- package/test/providerRuntime.test.js +250 -95
- package/test/secondFactor.test.js +6 -6
- package/test/sessionMetadata.test.js +38 -0
- package/test/signInEvents.test.js +206 -0
- package/test/signInThrottle.test.js +1 -1
- package/test-support/emailChangeScenario.js +139 -0
- package/test-support/localService.js +10 -4
- package/test-support/passSignInScenario.js +10 -4
- package/test-support/sessionMetadataScenario.js +76 -0
|
@@ -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";
|
|
@@ -15,7 +16,7 @@ import { createLocalSecondFactor } from "./secondFactor.js";
|
|
|
15
16
|
import { createLocalSecurityStatus } from "./securityStatus.js";
|
|
16
17
|
import { createLocalSessions } from "./sessions.js";
|
|
17
18
|
|
|
18
|
-
// A production server without AUTH_LOCAL_SECOND_FACTOR_KEY has no second factor: each operation is unsupported.
|
|
19
|
+
// A staging or production server without AUTH_LOCAL_SECOND_FACTOR_KEY has no second factor: each operation is unsupported.
|
|
19
20
|
const NO_SECOND_FACTOR = Object.freeze({
|
|
20
21
|
getSecondFactorStatus: () => throwUnsupportedAuthOperation("getSecondFactorStatus"),
|
|
21
22
|
startSecondFactorSetup: () => throwUnsupportedAuthOperation("startSecondFactorSetup"),
|
|
@@ -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
|
|
46
|
-
* confirmation link
|
|
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,
|
|
@@ -121,7 +130,7 @@ function createLocalAuthService({
|
|
|
121
130
|
secondFactor: Boolean(config.secondFactorKey)
|
|
122
131
|
}
|
|
123
132
|
});
|
|
124
|
-
// While the app has no account, its first one may register, and on a production server that asks for the setup code.
|
|
133
|
+
// While the app has no account, its first one may register, and on a staging or production server that asks for the setup code.
|
|
125
134
|
const capabilitiesForFirstAccount = normalizeAuthCapabilities({
|
|
126
135
|
...capabilities,
|
|
127
136
|
features: { ...capabilities.features, password: { ...capabilities.features.password, selfRegister: true } }
|
|
@@ -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,
|
|
@@ -27,22 +54,22 @@ function unauthenticatedAuthResult(clearSession = false) {
|
|
|
27
54
|
}
|
|
28
55
|
|
|
29
56
|
/**
|
|
30
|
-
* A local auth cookie: httpOnly at Path=/, Secure in production, with the application's SameSite
|
|
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, "
|
|
59
|
+
* @param {Pick<import("../types.js").AuthLocalConfig, "isDeployed" | "cookieSameSite">} config
|
|
33
60
|
* @param {number} maxAge
|
|
34
61
|
*/
|
|
35
|
-
function cookieOptions({
|
|
62
|
+
function cookieOptions({ isDeployed, cookieSameSite }, maxAge) {
|
|
36
63
|
return {
|
|
37
64
|
path: "/",
|
|
38
65
|
httpOnly: true,
|
|
39
66
|
sameSite: cookieSameSite,
|
|
40
|
-
secure:
|
|
67
|
+
secure: isDeployed,
|
|
41
68
|
maxAge
|
|
42
69
|
};
|
|
43
70
|
}
|
|
44
71
|
|
|
45
|
-
/** @param {Pick<import("../types.js").AuthLocalConfig, "
|
|
72
|
+
/** @param {Pick<import("../types.js").AuthLocalConfig, "isDeployed" | "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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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, isDeployed } = config;
|
|
131
|
+
// Staging and production cookies are Secure, so they are also host-only __Host- cookies.
|
|
132
|
+
const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isDeployed);
|
|
133
|
+
const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isDeployed);
|
|
134
|
+
const RECOVERY_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_TOKEN_COOKIE_NAME, isDeployed);
|
|
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
|
-
|
|
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 === "/" || !
|
|
376
|
+
if (options.path === "/" || !isDeployed) {
|
|
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 };
|
|
@@ -4,25 +4,53 @@ import {
|
|
|
4
4
|
} from "@jskit-ai/auth-core/server/deferredAuthService";
|
|
5
5
|
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
6
6
|
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
7
|
-
import {
|
|
7
|
+
import { deliverMessage } from "@jskit-ai/kernel/server/runtime/appEnvironment";
|
|
8
8
|
import { resolveLocalAuthConfig } from "../lib/config.js";
|
|
9
9
|
import { DELIVERY_SHUTDOWN_WAIT_MS, createLocalDeliveries } from "../lib/deliveries.js";
|
|
10
10
|
import {
|
|
11
11
|
confirmEveryRegistrationByLink,
|
|
12
|
-
createLoggedConfirmationSender
|
|
13
|
-
createSimulatedConfirmationSender
|
|
12
|
+
createLoggedConfirmationSender
|
|
14
13
|
} from "../lib/emailConfirmation.js";
|
|
14
|
+
import { createLoggedEmailChangeSender } from "../lib/emailChange.js";
|
|
15
15
|
import { createLocalFileBackend } from "../lib/fileBackend.js";
|
|
16
16
|
import { createFirstAccountSetup } from "../lib/firstAccountSetup.js";
|
|
17
17
|
import { noPassIdentities } from "../lib/passSignIn.js";
|
|
18
|
-
import { createLoggedRecoverySender
|
|
18
|
+
import { createLoggedRecoverySender } from "../lib/passwordFlows.js";
|
|
19
19
|
import { scryptPasswordStrategy } from "../lib/passwords.js";
|
|
20
20
|
import { createLoggedSecondFactorEvents } from "../lib/secondFactor.js";
|
|
21
21
|
import { createLocalAuthService } from "../lib/service.js";
|
|
22
|
+
import { createLoggedSignInEvents } from "../lib/sessions.js";
|
|
22
23
|
|
|
23
24
|
// The emails each started auth service is still sending, by the service its setup gave out, for its shutdown.
|
|
24
25
|
const deliveriesByService = new WeakMap();
|
|
25
26
|
|
|
27
|
+
/**
|
|
28
|
+
* An installed email sender, sending as APP_ENV says (`deliverMessage`): production sends each email to its address;
|
|
29
|
+
* staging only to STAGING_EMAIL_TO, passing the address it was for as `originalEmail`, or logs it when that is unset;
|
|
30
|
+
* development and test log it, link included, which the person testing follows.
|
|
31
|
+
* @template {{ email: string }} D
|
|
32
|
+
* @param {object} dependencies
|
|
33
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
|
|
34
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
35
|
+
* @param {(delivery: D & { originalEmail: string }) => Promise<void>} dependencies.sender
|
|
36
|
+
* @param {string} dependencies.name What the email is, such as "password reset".
|
|
37
|
+
* @returns {(delivery: D) => Promise<void>}
|
|
38
|
+
*/
|
|
39
|
+
function sendAsAppEnvironmentSays({ env, logger, sender, name }) {
|
|
40
|
+
return async (delivery) => {
|
|
41
|
+
const { email, ...link } = delivery;
|
|
42
|
+
await deliverMessage({
|
|
43
|
+
env,
|
|
44
|
+
logger,
|
|
45
|
+
channel: "email",
|
|
46
|
+
to: email,
|
|
47
|
+
summary: `the ${name} email to ${email}`,
|
|
48
|
+
details: link,
|
|
49
|
+
send: (to, { originalTo }) => sender({ ...delivery, email: to, originalEmail: originalTo })
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
26
54
|
const AuthLocalProvider = defineProvider({
|
|
27
55
|
id: "auth.local",
|
|
28
56
|
requires: {
|
|
@@ -35,11 +63,13 @@ const AuthLocalProvider = defineProvider({
|
|
|
35
63
|
backend: "auth.local.backend",
|
|
36
64
|
confirmationMode: "auth.local.confirmation-mode",
|
|
37
65
|
confirmationSender: "auth.local.confirmation-sender",
|
|
66
|
+
emailChangeSender: "auth.local.email-change-sender",
|
|
38
67
|
passIdentity: "auth.local.pass-identity",
|
|
39
68
|
passwordStrategy: "auth.local.password-strategy",
|
|
40
69
|
profileProjector: "auth.profile.projector",
|
|
41
70
|
recoverySender: "auth.local.recovery-sender",
|
|
42
|
-
secondFactorEvents: "auth.local.second-factor-events"
|
|
71
|
+
secondFactorEvents: "auth.local.second-factor-events",
|
|
72
|
+
signInEvents: "auth.local.sign-in-events"
|
|
43
73
|
},
|
|
44
74
|
provides: {
|
|
45
75
|
authService: "auth.service"
|
|
@@ -55,6 +85,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
55
85
|
* `auth.local.confirmation-mode`, when one is installed.
|
|
56
86
|
* @param {import("../types.js").AuthLocalConfirmationSender | null} dependencies.confirmationSender The
|
|
57
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.
|
|
58
90
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
|
|
59
91
|
* @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
|
|
60
92
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
@@ -65,6 +97,8 @@ const AuthLocalProvider = defineProvider({
|
|
|
65
97
|
* @param {import("../types.js").AuthLocalRecoverySender | null} dependencies.recoverySender The `auth.local.recovery-sender`, when one is installed.
|
|
66
98
|
* @param {import("../types.js").AuthLocalSecondFactorEvents | null} dependencies.secondFactorEvents The
|
|
67
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.
|
|
68
102
|
*/
|
|
69
103
|
async boot(
|
|
70
104
|
{
|
|
@@ -72,6 +106,7 @@ const AuthLocalProvider = defineProvider({
|
|
|
72
106
|
backend,
|
|
73
107
|
confirmationMode,
|
|
74
108
|
confirmationSender,
|
|
109
|
+
emailChangeSender,
|
|
75
110
|
env,
|
|
76
111
|
extensions,
|
|
77
112
|
logger,
|
|
@@ -79,24 +114,33 @@ const AuthLocalProvider = defineProvider({
|
|
|
79
114
|
passwordStrategy,
|
|
80
115
|
profileProjector,
|
|
81
116
|
recoverySender,
|
|
82
|
-
secondFactorEvents
|
|
117
|
+
secondFactorEvents,
|
|
118
|
+
signInEvents
|
|
83
119
|
},
|
|
84
120
|
{ outputs }
|
|
85
121
|
) {
|
|
86
122
|
const fileBackend = backend === null;
|
|
87
123
|
const emailRecovery = recoverySender !== null;
|
|
88
124
|
const emailConfirmationSender = confirmationSender !== null;
|
|
89
|
-
const
|
|
125
|
+
const emailedChange = emailChangeSender !== null;
|
|
126
|
+
const config = resolveLocalAuthConfig({
|
|
127
|
+
appRoot,
|
|
128
|
+
env,
|
|
129
|
+
fileBackend,
|
|
130
|
+
emailRecovery,
|
|
131
|
+
emailConfirmationSender,
|
|
132
|
+
emailChangeSender: emailedChange
|
|
133
|
+
});
|
|
90
134
|
if (config.passSignIn && passIdentity === null) {
|
|
91
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.");
|
|
92
136
|
}
|
|
93
137
|
const localBackend = fileBackend ? createLocalFileBackend({ storeDir: config.storeDir }) : backend;
|
|
94
|
-
// A production server without accounts logs its setup code as it starts.
|
|
138
|
+
// A staging or production server without accounts logs its setup code as it starts.
|
|
95
139
|
const firstAccountSetup = createFirstAccountSetup({ backend: localBackend, config, logger });
|
|
96
140
|
await firstAccountSetup.start();
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
|
|
141
|
+
// An installed sender sends as APP_ENV says: only production emails each address; staging emails only
|
|
142
|
+
// STAGING_EMAIL_TO; development and test log each email. The confirmation mode sends nothing, so it applies
|
|
143
|
+
// everywhere.
|
|
100
144
|
const deliveries = createLocalDeliveries({ logger });
|
|
101
145
|
deliveriesByService.set(outputs.authService, deliveries);
|
|
102
146
|
const baseService = createLocalAuthService({
|
|
@@ -104,9 +148,12 @@ const AuthLocalProvider = defineProvider({
|
|
|
104
148
|
config,
|
|
105
149
|
confirmationMode: confirmationMode ?? confirmEveryRegistrationByLink,
|
|
106
150
|
confirmationSender: emailConfirmationSender
|
|
107
|
-
? (
|
|
151
|
+
? sendAsAppEnvironmentSays({ env, logger, sender: confirmationSender, name: "email confirmation" })
|
|
108
152
|
: createLoggedConfirmationSender(logger),
|
|
109
153
|
deliveries,
|
|
154
|
+
emailChangeSender: emailedChange
|
|
155
|
+
? sendAsAppEnvironmentSays({ env, logger, sender: emailChangeSender, name: "email change" })
|
|
156
|
+
: createLoggedEmailChangeSender(logger),
|
|
110
157
|
firstAccountSetup,
|
|
111
158
|
invitationContextResolver: extensions.resolveInvitationContextResolver(),
|
|
112
159
|
logger,
|
|
@@ -114,16 +161,17 @@ const AuthLocalProvider = defineProvider({
|
|
|
114
161
|
passwordStrategy: passwordStrategy ?? scryptPasswordStrategy,
|
|
115
162
|
profileProjector: profileProjector ?? noAppProfiles,
|
|
116
163
|
recoverySender: emailRecovery
|
|
117
|
-
? (
|
|
164
|
+
? sendAsAppEnvironmentSays({ env, logger, sender: recoverySender, name: "password reset" })
|
|
118
165
|
: createLoggedRecoverySender(logger),
|
|
119
|
-
secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger)
|
|
166
|
+
secondFactorEvents: secondFactorEvents ?? createLoggedSecondFactorEvents(logger),
|
|
167
|
+
signInEvents: signInEvents ?? createLoggedSignInEvents(logger)
|
|
120
168
|
});
|
|
121
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
|
|
122
170
|
attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
|
|
123
171
|
},
|
|
124
172
|
/**
|
|
125
|
-
* Waits for the emails local auth is still sending, for a while: a reset
|
|
126
|
-
* 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
|
|
127
175
|
* boot that stopped before making its service sent nothing.
|
|
128
176
|
*/
|
|
129
177
|
async shutdown(_dependencies, { outputs }) {
|
package/src/server/types.js
CHANGED
|
@@ -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
|
-
*
|
|
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.
|
|
@@ -174,14 +219,34 @@
|
|
|
174
219
|
|
|
175
220
|
/**
|
|
176
221
|
* The `auth.local.recovery-sender` capability: sends a password recovery link
|
|
177
|
-
* to the person it belongs to.
|
|
178
|
-
*
|
|
222
|
+
* to the person it belongs to. Local auth calls it as APP_ENV says: in
|
|
223
|
+
* production with that person's address; in staging with STAGING_EMAIL_TO's,
|
|
224
|
+
* and `originalEmail` the person's, which the email should show (for example
|
|
225
|
+
* with `markStagingEmail` from `@jskit-ai/kernel/server/runtime/appEnvironment`);
|
|
226
|
+
* never in development or test, which log the link. `originalEmail` is ""
|
|
227
|
+
* when the email goes to its own address.
|
|
228
|
+
* @typedef {(delivery: { email: string, originalEmail?: string, recoveryUrl: string }) => Promise<void>} AuthLocalRecoverySender
|
|
179
229
|
*/
|
|
180
230
|
|
|
181
231
|
/**
|
|
182
232
|
* The `auth.local.confirmation-sender` capability: sends a new registration's
|
|
183
|
-
* email confirmation link to the address it registered
|
|
184
|
-
*
|
|
233
|
+
* email confirmation link to the address it registered, as APP_ENV says, like
|
|
234
|
+
* `AuthLocalRecoverySender`.
|
|
235
|
+
* @typedef {(delivery: { email: string, originalEmail?: string, confirmationUrl: string }) => Promise<void>} AuthLocalConfirmationSender
|
|
236
|
+
*/
|
|
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
|
|
185
250
|
*/
|
|
186
251
|
|
|
187
252
|
/**
|
|
@@ -190,8 +255,8 @@
|
|
|
190
255
|
* confirmed. "link" sends the confirmation link, as without one; "without-link"
|
|
191
256
|
* creates the account and signs the person in at once, with an address nobody
|
|
192
257
|
* proved, for example while the application's email isn't set up. Any other
|
|
193
|
-
* answer means "link". It sends nothing, so
|
|
194
|
-
*
|
|
258
|
+
* answer means "link". It sends nothing, so it applies in every environment
|
|
259
|
+
* (APP_ENV), whatever happens to the confirmation sender's emails.
|
|
195
260
|
* @typedef {(registration: { email: string }) => Promise<"link" | "without-link">} AuthLocalConfirmationMode
|
|
196
261
|
*/
|
|
197
262
|
|