@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
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
+
import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
3
|
+
import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
|
|
4
|
+
import { hasPassword, validateEmailInput } from "./accounts.js";
|
|
5
|
+
import { buildProfileChangePayload } from "./authPayloads.js";
|
|
6
|
+
import { signToken, verifySignedToken } from "./tokens.js";
|
|
7
|
+
|
|
8
|
+
const EMAIL_CHANGE_LINK_TTL_SECONDS = 24 * 60 * 60;
|
|
9
|
+
// What the link's signed token is for, so no other token the session secret signs is taken for one.
|
|
10
|
+
const EMAIL_CHANGE_PURPOSE = "email-change";
|
|
11
|
+
// A password reset's recovery tokens (passwordFlows.js): those sent to the old address end with the change.
|
|
12
|
+
const RESET_TOKEN_PREFIX = "rec_";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The `auth.local.email-change-sender` default when no feature provides one: in development and test, local auth logs
|
|
16
|
+
* each email-change link and notice instead of emailing them. A staging or production server without one has no email
|
|
17
|
+
* change.
|
|
18
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
19
|
+
* @returns {import("../types.js").AuthLocalEmailChangeSender}
|
|
20
|
+
*/
|
|
21
|
+
function createLoggedEmailChangeSender(logger) {
|
|
22
|
+
return async function logEmailChange(delivery) {
|
|
23
|
+
logger.info(delivery, `Local auth email change: ${delivery.type}.`);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The refusal of one field, for the form that sent it: its message under its code. */
|
|
28
|
+
function fieldRefusal(status, { code, message, field }) {
|
|
29
|
+
return new AppError(status, message, {
|
|
30
|
+
code,
|
|
31
|
+
details: { fieldErrors: { [field]: message }, fieldErrorCodes: { [field]: { code, params: {} } } }
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const passwordInvalidError = () =>
|
|
36
|
+
fieldRefusal(400, { code: "auth.local.emailChange.passwordInvalid", message: "That is not your password.", field: "password" });
|
|
37
|
+
const sameEmailError = () =>
|
|
38
|
+
fieldRefusal(400, { code: "auth.local.emailChange.sameEmail", message: "That is already your email address.", field: "email" });
|
|
39
|
+
const emailTakenError = () =>
|
|
40
|
+
fieldRefusal(409, { code: "auth.local.emailChange.emailTaken", message: "An account already exists for this email.", field: "email" });
|
|
41
|
+
const linkInvalidError = () => new AppError(400, "This email change link is invalid, used or expired. Ask for the change again.", {
|
|
42
|
+
code: "auth.local.emailChange.linkInvalid"
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Changing an account's email: the signed-in person asks with their password (requestEmailChange), or the
|
|
47
|
+
* application asks for an account it chose (requestEmailChangeForUser). The account keeps the new address as its
|
|
48
|
+
* waiting change, and the new address is sent a link, signed with the session secret, naming the account and the
|
|
49
|
+
* address and working for a day; a newer request replaces the waiting change, so an earlier link stops working. Using
|
|
50
|
+
* the link (confirmEmailChange) changes the email, which the link proved, ends the password resets sent to the old
|
|
51
|
+
* address, and tells the old address. The links and notices go through `auth.local.email-change-sender` after the
|
|
52
|
+
* request has answered (deliveries). The account's sessions stay signed in.
|
|
53
|
+
* @param {object} dependencies
|
|
54
|
+
* @param {import("../types.js").AuthLocalBackend} dependencies.backend
|
|
55
|
+
* @param {import("../types.js").AuthLocalConfig} dependencies.config
|
|
56
|
+
* @param {import("../types.js").AuthLocalDeliveries} dependencies.deliveries
|
|
57
|
+
* @param {import("../types.js").AuthLocalEmailChangeSender} dependencies.emailChangeSender
|
|
58
|
+
* @param {import("../types.js").AuthLocalPasswords} dependencies.passwords
|
|
59
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
|
|
60
|
+
* @param {import("../types.js").AuthLocalSessions} dependencies.sessions
|
|
61
|
+
*/
|
|
62
|
+
function createLocalEmailChange({ backend, config, deliveries, emailChangeSender, passwords, profileProjector, sessions }) {
|
|
63
|
+
if (!emailChangeSender) {
|
|
64
|
+
throw new TypeError("createLocalEmailChange() takes emailChangeSender, the auth.local.email-change-sender that sends its links.");
|
|
65
|
+
}
|
|
66
|
+
const enabled = config.emailChangeDelivery !== "off";
|
|
67
|
+
|
|
68
|
+
function linkFor(user, email) {
|
|
69
|
+
const exp = Math.floor(Date.now() / 1000) + EMAIL_CHANGE_LINK_TTL_SECONDS;
|
|
70
|
+
const token = signToken({ purpose: EMAIL_CHANGE_PURPOSE, sub: user.id, email, exp }, config.sessionSecret);
|
|
71
|
+
return `${config.appPublicUrl}/auth/email-change?token=${encodeURIComponent(token)}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Keeps the new address as the account's waiting change and sends it the link, once the request has answered.
|
|
76
|
+
* @param {(tx: import("../types.js").AuthLocalBackendTransaction) => Promise<object>} findUser The account, or a refusal.
|
|
77
|
+
* @param {string} email The new address, already checked.
|
|
78
|
+
*/
|
|
79
|
+
async function startChange(findUser, email) {
|
|
80
|
+
const user = await backend.withTransaction(async (tx) => {
|
|
81
|
+
const found = await findUser(tx);
|
|
82
|
+
if (found.email === email) {
|
|
83
|
+
throw sameEmailError();
|
|
84
|
+
}
|
|
85
|
+
if (await tx.users.findByEmail(email)) {
|
|
86
|
+
throw emailTakenError();
|
|
87
|
+
}
|
|
88
|
+
return tx.users.updatePendingEmail(found.id, email);
|
|
89
|
+
});
|
|
90
|
+
const confirmationUrl = linkFor(user, email);
|
|
91
|
+
deliveries.send("the email change link", email, () =>
|
|
92
|
+
emailChangeSender({ type: "confirmation", email, currentEmail: user.email, confirmationUrl }));
|
|
93
|
+
return { ok: true, email };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The signed-in person's own change, with their password; an account with no password sets one first, through a
|
|
98
|
+
* password reset.
|
|
99
|
+
* @param {object} request
|
|
100
|
+
* @param {{ email: string, password: string }} input
|
|
101
|
+
*/
|
|
102
|
+
async function requestEmailChange(request, input) {
|
|
103
|
+
if (!enabled) return throwUnsupportedAuthOperation("requestEmailChange");
|
|
104
|
+
const authResult = await sessions.authenticateRequest(request);
|
|
105
|
+
if (authResult.authenticated !== true) {
|
|
106
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
107
|
+
}
|
|
108
|
+
const email = validateEmailInput(input.email);
|
|
109
|
+
const password = String(input.password || "");
|
|
110
|
+
const userId = authResult.actor.providerUserId;
|
|
111
|
+
const user = await backend.withTransaction((tx) => tx.users.findById(userId));
|
|
112
|
+
if (!user || !hasPassword(user) || !(await passwords.verifyPassword(password, user.password))) {
|
|
113
|
+
throw passwordInvalidError();
|
|
114
|
+
}
|
|
115
|
+
return startChange(async (tx) => {
|
|
116
|
+
const current = await tx.users.findById(userId);
|
|
117
|
+
if (!current) {
|
|
118
|
+
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
119
|
+
}
|
|
120
|
+
return current;
|
|
121
|
+
}, email);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The application's change of an account it chose, such as an operator's for a person who lost their old address:
|
|
126
|
+
* who may ask is the application's decision.
|
|
127
|
+
* @param {{ userId: string, email: string }} input
|
|
128
|
+
*/
|
|
129
|
+
async function requestEmailChangeForUser({ userId, email: given } = {}) {
|
|
130
|
+
if (!enabled) return throwUnsupportedAuthOperation("requestEmailChangeForUser");
|
|
131
|
+
const id = String(userId || "").trim();
|
|
132
|
+
if (!id) {
|
|
133
|
+
throw new TypeError("requestEmailChangeForUser() takes the userId of the account whose email changes.");
|
|
134
|
+
}
|
|
135
|
+
const email = validateEmailInput(given);
|
|
136
|
+
return startChange(async (tx) => {
|
|
137
|
+
const user = await tx.users.findById(id);
|
|
138
|
+
if (!user) {
|
|
139
|
+
throw new AppError(404, "There is no such account.", { code: "auth.local.emailChange.accountNotFound" });
|
|
140
|
+
}
|
|
141
|
+
return user;
|
|
142
|
+
}, email);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Uses the link: while it is the account's waiting change, the email changes to it.
|
|
147
|
+
* @param {{ token: string }} input
|
|
148
|
+
*/
|
|
149
|
+
async function confirmEmailChange(input) {
|
|
150
|
+
if (!enabled) return throwUnsupportedAuthOperation("confirmEmailChange");
|
|
151
|
+
const payload = verifySignedToken(String(input?.token || ""), config.sessionSecret);
|
|
152
|
+
if (payload?.purpose !== EMAIL_CHANGE_PURPOSE || !payload.sub || !payload.email) {
|
|
153
|
+
throw linkInvalidError();
|
|
154
|
+
}
|
|
155
|
+
const email = String(payload.email);
|
|
156
|
+
const changed = await backend.withTransaction(async (tx) => {
|
|
157
|
+
const user = await tx.users.findById(String(payload.sub));
|
|
158
|
+
if (!user || user.pendingEmail !== email) {
|
|
159
|
+
throw linkInvalidError();
|
|
160
|
+
}
|
|
161
|
+
if (await tx.users.findByEmail(email)) {
|
|
162
|
+
throw emailTakenError();
|
|
163
|
+
}
|
|
164
|
+
const updated = await tx.users.updateEmail(user.id, email);
|
|
165
|
+
await tx.recovery.consumeForUser(user.id, { idPrefix: RESET_TOKEN_PREFIX });
|
|
166
|
+
return { user: updated, oldEmail: user.email };
|
|
167
|
+
});
|
|
168
|
+
deliveries.send("the email change notice", changed.oldEmail, () =>
|
|
169
|
+
emailChangeSender({ type: "notice", email: changed.oldEmail, newEmail: email }));
|
|
170
|
+
// After the transaction, so the request holds one database connection at a time: the application's profile
|
|
171
|
+
// takes the new email now, rather than at the account's next request.
|
|
172
|
+
await buildProfileChangePayload({ user: changed.user, profileProjector });
|
|
173
|
+
return { ok: true, email };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
requestEmailChange,
|
|
178
|
+
requestEmailChangeForUser,
|
|
179
|
+
confirmEmailChange
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export { createLocalEmailChange, createLoggedEmailChangeSender };
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
-
import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
|
|
3
2
|
import { resolveRegistrationProfileOptions, validateEmailInput } from "./accounts.js";
|
|
4
3
|
import { buildAuthPayload } from "./authPayloads.js";
|
|
5
4
|
import { createId, isExpiredIso, isoFromNow, randomToken, sha256Base64url } from "./tokens.js";
|
|
@@ -29,23 +28,6 @@ function createLoggedConfirmationSender(logger) {
|
|
|
29
28
|
};
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
/**
|
|
33
|
-
* The confirmation sender of a test copy (SIDE_EFFECTS is not `live`) in place of the installed
|
|
34
|
-
* `auth.local.confirmation-sender`: it emails nothing and logs the link, which the person testing follows to
|
|
35
|
-
* confirm. The link stays out of the registration's answer, as with a real sender.
|
|
36
|
-
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
37
|
-
* @returns {import("../types.js").AuthLocalConfirmationSender}
|
|
38
|
-
*/
|
|
39
|
-
function createSimulatedConfirmationSender(logger) {
|
|
40
|
-
return async function simulateConfirmationEmail({ email, confirmationUrl }) {
|
|
41
|
-
logSimulatedSideEffect(logger, {
|
|
42
|
-
kind: "email",
|
|
43
|
-
summary: `the email confirmation email to ${email}`,
|
|
44
|
-
details: { email, confirmationUrl }
|
|
45
|
-
});
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
|
|
49
31
|
function emailTakenError() {
|
|
50
32
|
return new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
|
|
51
33
|
}
|
|
@@ -173,8 +155,9 @@ function createLocalEmailConfirmation({
|
|
|
173
155
|
* code and the password it registered with, and signs the person in. A wrong
|
|
174
156
|
* password creates nothing and keeps the registration and its link.
|
|
175
157
|
* @param {{ token: string, password: string }} input
|
|
158
|
+
* @param {object | null} [request] The request that confirms it, where the new session is first seen from.
|
|
176
159
|
*/
|
|
177
|
-
async function confirm(input) {
|
|
160
|
+
async function confirm(input, request = null) {
|
|
178
161
|
const tokenHash = sha256Base64url(String(input.token || "").trim());
|
|
179
162
|
const waiting = await backend.withTransaction((tx) => tx.registrations.findByTokenHash(tokenHash));
|
|
180
163
|
if (!waiting || isExpiredIso(waiting.expiresAt)) {
|
|
@@ -206,7 +189,7 @@ function createLocalEmailConfirmation({
|
|
|
206
189
|
password: registration.password,
|
|
207
190
|
emailVerifiedAt: new Date().toISOString()
|
|
208
191
|
});
|
|
209
|
-
return { user, session: await sessions.createSessionForUser(tx, user) };
|
|
192
|
+
return { user, session: await sessions.createSessionForUser(tx, user, { request }) };
|
|
210
193
|
});
|
|
211
194
|
// Refused after the transaction, so a used-up registration stays deleted.
|
|
212
195
|
if (outcome.invalid) {
|
|
@@ -216,6 +199,7 @@ function createLocalEmailConfirmation({
|
|
|
216
199
|
throw emailTakenError();
|
|
217
200
|
}
|
|
218
201
|
firstAccountSetup.accountCreated();
|
|
202
|
+
sessions.recordSignInEvent("signedIn", { method: "confirmation", userId: outcome.user.id, email: outcome.user.email }, request);
|
|
219
203
|
return buildAuthPayload({ user: outcome.user, session: outcome.session, profileProjector, profileOptions });
|
|
220
204
|
}
|
|
221
205
|
|
|
@@ -294,6 +278,5 @@ export {
|
|
|
294
278
|
CONFIRMATION_TOKEN_TTL_SECONDS,
|
|
295
279
|
confirmEveryRegistrationByLink,
|
|
296
280
|
createLocalEmailConfirmation,
|
|
297
|
-
createLoggedConfirmationSender
|
|
298
|
-
createSimulatedConfirmationSender
|
|
281
|
+
createLoggedConfirmationSender
|
|
299
282
|
};
|
|
@@ -224,7 +224,8 @@ function createTx(state, touched) {
|
|
|
224
224
|
...clone(input),
|
|
225
225
|
createdAt: input.createdAt || nowIso(),
|
|
226
226
|
updatedAt: input.updatedAt || nowIso(),
|
|
227
|
-
disabled: input.disabled === true
|
|
227
|
+
disabled: input.disabled === true,
|
|
228
|
+
pendingEmail: input.pendingEmail || ""
|
|
228
229
|
};
|
|
229
230
|
state.users.push(user);
|
|
230
231
|
mark("users");
|
|
@@ -260,6 +261,30 @@ function createTx(state, touched) {
|
|
|
260
261
|
user.updatedAt = nowIso();
|
|
261
262
|
mark("users");
|
|
262
263
|
return clone(user);
|
|
264
|
+
},
|
|
265
|
+
async updatePendingEmail(userId, pendingEmail) {
|
|
266
|
+
const user = state.users.find((entry) => entry.id === userId);
|
|
267
|
+
if (!user) {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
user.pendingEmail = String(pendingEmail || "");
|
|
271
|
+
user.updatedAt = nowIso();
|
|
272
|
+
mark("users");
|
|
273
|
+
return clone(user);
|
|
274
|
+
},
|
|
275
|
+
async updateEmail(userId, email) {
|
|
276
|
+
const user = state.users.find((entry) => entry.id === userId);
|
|
277
|
+
if (!user) {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
if (state.users.some((entry) => entry.id !== userId && entry.email === email)) {
|
|
281
|
+
throw new ConflictError("An account with this id or email already exists.", { code: "auth.local.accounts.exists" });
|
|
282
|
+
}
|
|
283
|
+
user.email = email;
|
|
284
|
+
user.pendingEmail = "";
|
|
285
|
+
user.updatedAt = nowIso();
|
|
286
|
+
mark("users");
|
|
287
|
+
return clone(user);
|
|
263
288
|
}
|
|
264
289
|
}),
|
|
265
290
|
sessions: Object.freeze({
|
|
@@ -269,7 +294,10 @@ function createTx(state, touched) {
|
|
|
269
294
|
purpose: input.purpose || "normal",
|
|
270
295
|
createdAt: input.createdAt || nowIso(),
|
|
271
296
|
revokedAt: input.revokedAt || "",
|
|
272
|
-
secondFactorAt: input.secondFactorAt || ""
|
|
297
|
+
secondFactorAt: input.secondFactorAt || "",
|
|
298
|
+
ip: input.ip || "",
|
|
299
|
+
userAgent: input.userAgent || "",
|
|
300
|
+
lastSeenAt: input.lastSeenAt || ""
|
|
273
301
|
};
|
|
274
302
|
state.sessions.push(session);
|
|
275
303
|
mark("sessions");
|
|
@@ -325,6 +353,16 @@ function createTx(state, touched) {
|
|
|
325
353
|
mark("sessions");
|
|
326
354
|
}
|
|
327
355
|
return count;
|
|
356
|
+
},
|
|
357
|
+
async touch(sessionId, { lastSeenAt, ip, userAgent }) {
|
|
358
|
+
const session = state.sessions.find((entry) => entry.id === sessionId);
|
|
359
|
+
if (!session) {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
session.lastSeenAt = lastSeenAt;
|
|
363
|
+
session.ip = ip || session.ip;
|
|
364
|
+
session.userAgent = userAgent || session.userAgent;
|
|
365
|
+
mark("sessions");
|
|
328
366
|
}
|
|
329
367
|
}),
|
|
330
368
|
recovery: Object.freeze({
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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" : "");
|
|
@@ -41,9 +41,9 @@ function setupCodeInvalid() {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
/**
|
|
44
|
-
* The first account of a production server. While local auth has no account,
|
|
44
|
+
* The first account of a staging or production server. While local auth has no account,
|
|
45
45
|
* creating one needs a one-time setup code that only the server's operator can
|
|
46
|
-
* read: each start of an ownerless
|
|
46
|
+
* read: each start of an ownerless deployed server makes a new code, writes
|
|
47
47
|
* it in the log and in `first-account-setup-code` in AUTH_LOCAL_STORE_DIR, and
|
|
48
48
|
* keeps only its hash. A hosting tool that supplies the code in
|
|
49
49
|
* AUTH_LOCAL_SETUP_CODE shows it to the operator itself: the server then uses
|
|
@@ -97,7 +97,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
|
|
|
97
97
|
return;
|
|
98
98
|
}
|
|
99
99
|
ownerless = true;
|
|
100
|
-
if (!config.
|
|
100
|
+
if (!config.isDeployed) {
|
|
101
101
|
return;
|
|
102
102
|
}
|
|
103
103
|
if (config.setupCode) {
|
|
@@ -119,7 +119,7 @@ function createFirstAccountSetup({ backend, config, logger }) {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
/**
|
|
122
|
-
* Checks for an account once, when the server starts;
|
|
122
|
+
* Checks for an account once, when the server starts; in development and test,
|
|
123
123
|
* only whether there is one. Later calls answer the same check.
|
|
124
124
|
*/
|
|
125
125
|
function start() {
|
package/src/server/lib/index.js
CHANGED
|
@@ -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";
|
|
@@ -34,8 +34,8 @@ function createLocalOAuthFlows({
|
|
|
34
34
|
securityStatus,
|
|
35
35
|
sessions
|
|
36
36
|
}) {
|
|
37
|
-
const {
|
|
38
|
-
const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME,
|
|
37
|
+
const { isDeployed, oauthEnabled } = config;
|
|
38
|
+
const OAUTH_ATTEMPT_COOKIE = hostOnlyCookieName(OAUTH_ATTEMPT_COOKIE_NAME, isDeployed);
|
|
39
39
|
const oauthRedirectUri = oauthEnabled ? `${config.appPublicUrl.replace(/\/$/u, "")}${OAUTH_REDIRECT_PATH}` : "";
|
|
40
40
|
const appOrigin = oauthEnabled ? new URL(config.appPublicUrl).origin : "";
|
|
41
41
|
const oauthClients = createOAuthClients({ logger });
|
|
@@ -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
|
|
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
|
|
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
|
-
/**
|
|
32
|
-
|
|
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
|
|
50
|
+
if (!user) {
|
|
46
51
|
throw createPassError(PASS_TEXTS.passUnmapped);
|
|
47
52
|
}
|
|
48
|
-
|
|
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
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
-
import { logSimulatedSideEffect } from "@jskit-ai/kernel/server/runtime/sideEffects";
|
|
3
2
|
import { AUTH_TEXTS, authMessageFields, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
4
3
|
import { validateEmailInput, validatePasswordInput } from "./accounts.js";
|
|
5
4
|
import { buildAuthPayload } from "./authPayloads.js";
|
|
@@ -12,8 +11,8 @@ const RECOVERY_TOKEN_TTL_SECONDS = 60 * 60;
|
|
|
12
11
|
const RESET_TOKEN_KIND = "rec";
|
|
13
12
|
|
|
14
13
|
/**
|
|
15
|
-
* The `auth.local.recovery-sender` default when no feature provides one:
|
|
16
|
-
*
|
|
14
|
+
* The `auth.local.recovery-sender` default when no feature provides one: in
|
|
15
|
+
* development and test, local auth logs each recovery link instead of emailing it.
|
|
17
16
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
18
17
|
* @returns {import("../types.js").AuthLocalRecoverySender}
|
|
19
18
|
*/
|
|
@@ -23,23 +22,6 @@ function createLoggedRecoverySender(logger) {
|
|
|
23
22
|
};
|
|
24
23
|
}
|
|
25
24
|
|
|
26
|
-
/**
|
|
27
|
-
* The recovery sender of a test copy (SIDE_EFFECTS is not `live`) in place of the installed
|
|
28
|
-
* `auth.local.recovery-sender`: it emails nothing and logs the link, which the person testing follows to reset the
|
|
29
|
-
* password.
|
|
30
|
-
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} logger
|
|
31
|
-
* @returns {import("../types.js").AuthLocalRecoverySender}
|
|
32
|
-
*/
|
|
33
|
-
function createSimulatedRecoverySender(logger) {
|
|
34
|
-
return async function simulateRecoveryEmail({ email, recoveryUrl }) {
|
|
35
|
-
logSimulatedSideEffect(logger, {
|
|
36
|
-
kind: "email",
|
|
37
|
-
summary: `the password reset email to ${email}`,
|
|
38
|
-
details: { email, recoveryUrl }
|
|
39
|
-
});
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
|
|
43
25
|
/**
|
|
44
26
|
* Changing a password, and recovering one: a recovery link opens a short
|
|
45
27
|
* recovery session, which can only set a new password.
|
|
@@ -114,7 +96,7 @@ function createLocalPasswordFlows({ backend, config, deliveries, passwords, prof
|
|
|
114
96
|
return requested;
|
|
115
97
|
}
|
|
116
98
|
|
|
117
|
-
async function completePasswordRecovery(input) {
|
|
99
|
+
async function completePasswordRecovery(input, request = null) {
|
|
118
100
|
if (!recoveryEnabled) {
|
|
119
101
|
throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
|
|
120
102
|
}
|
|
@@ -141,10 +123,12 @@ function createLocalPasswordFlows({ backend, config, deliveries, passwords, prof
|
|
|
141
123
|
user,
|
|
142
124
|
session: await sessions.createSessionForUser(tx, user, {
|
|
143
125
|
purpose: "recovery",
|
|
144
|
-
ttlSeconds: RECOVERY_SESSION_TTL_SECONDS
|
|
126
|
+
ttlSeconds: RECOVERY_SESSION_TTL_SECONDS,
|
|
127
|
+
request
|
|
145
128
|
})
|
|
146
129
|
};
|
|
147
130
|
});
|
|
131
|
+
sessions.recordSignInEvent("signedIn", { method: "recovery", userId: user.id, email: user.email }, request);
|
|
148
132
|
// After the transaction, so the request holds one database connection at a time: the profile projector works in
|
|
149
133
|
// transactions of its own.
|
|
150
134
|
return buildAuthPayload({ user, session, profileProjector });
|
|
@@ -216,4 +200,4 @@ function createLocalPasswordFlows({ backend, config, deliveries, passwords, prof
|
|
|
216
200
|
});
|
|
217
201
|
}
|
|
218
202
|
|
|
219
|
-
export { createLocalPasswordFlows, createLoggedRecoverySender
|
|
203
|
+
export { createLocalPasswordFlows, createLoggedRecoverySender };
|
|
@@ -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
|
}
|