@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,206 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
7
|
+
import {
|
|
8
|
+
createLocalAuthService,
|
|
9
|
+
createLocalDeliveries,
|
|
10
|
+
createLocalFileBackend,
|
|
11
|
+
createLoggedSignInEvents,
|
|
12
|
+
hashPassword
|
|
13
|
+
} from "../src/server/lib/index.js";
|
|
14
|
+
import { NO_PASSWORD } from "../src/server/lib/accounts.js";
|
|
15
|
+
import { APP_URL, approveAtProvider, oidcProviderEntry, startOidcProvider } from "../test-support/oauthHarness.js";
|
|
16
|
+
import { localServiceOptions } from "../test-support/localService.js";
|
|
17
|
+
import { createPassIssuer, passIdentityByEmail, passwordlessAccount } from "../test-support/passSignInScenario.js";
|
|
18
|
+
import { requestFrom } from "../test-support/sessionMetadataScenario.js";
|
|
19
|
+
|
|
20
|
+
const PASSWORD = "correct horse battery staple";
|
|
21
|
+
const BROWSER = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
|
|
22
|
+
const START = Date.parse("2026-11-15T09:00:00.000Z");
|
|
23
|
+
const FROM = requestFrom("203.0.113.7", BROWSER);
|
|
24
|
+
const WHERE = Object.freeze({ ip: "203.0.113.7", userAgent: BROWSER });
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A local auth service over a file store of the test's own that keeps every sign-in event it is given, sent through
|
|
28
|
+
* deliveries the test waits for.
|
|
29
|
+
* @param {import("node:test").TestContext} t
|
|
30
|
+
* @param {{ env?: Record<string, string>, signInEvents?: (event: object) => Promise<void>, config?: (config: object) => object, passIdentity?: boolean }} [options]
|
|
31
|
+
*/
|
|
32
|
+
async function startService(t, { env = {}, signInEvents = null, config = (given) => given, passIdentity = false } = {}) {
|
|
33
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
|
|
34
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
35
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
36
|
+
const deliveries = createLocalDeliveries({ logger: silentLogger });
|
|
37
|
+
const events = [];
|
|
38
|
+
const options = localServiceOptions({ env });
|
|
39
|
+
const service = createLocalAuthService({
|
|
40
|
+
...options,
|
|
41
|
+
backend,
|
|
42
|
+
config: config(options.config),
|
|
43
|
+
deliveries,
|
|
44
|
+
...(passIdentity ? { passIdentity: passIdentityByEmail(backend) } : {}),
|
|
45
|
+
signInEvents: signInEvents ?? (async (event) => {
|
|
46
|
+
events.push(event);
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
/** The events sent so far, once every one of them was handed over; it forgets them. */
|
|
50
|
+
async function takeEvents() {
|
|
51
|
+
await deliveries.settled();
|
|
52
|
+
return events.splice(0);
|
|
53
|
+
}
|
|
54
|
+
return { backend, service, takeEvents };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const at = (ms = 0) => new Date(START + ms).toISOString();
|
|
58
|
+
|
|
59
|
+
test("each sign-in and each refused password sign-in is an event, with the account, where it came from and when", async (t) => {
|
|
60
|
+
t.mock.timers.enable({ apis: ["Date"], now: START });
|
|
61
|
+
const { backend, service, takeEvents } = await startService(t, { env: { AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT: "1" } });
|
|
62
|
+
const ada = await service.register({ email: "ada@example.com", password: PASSWORD }, FROM);
|
|
63
|
+
const adaId = ada.actor.providerUserId;
|
|
64
|
+
await service.login({ email: "ada@example.com", password: PASSWORD }, FROM);
|
|
65
|
+
await backend.withTransaction(async (tx) => tx.users.create({
|
|
66
|
+
id: "usr_off", email: "off@example.com", displayName: "Off", password: await hashPassword(PASSWORD), disabled: true
|
|
67
|
+
}));
|
|
68
|
+
await assert.rejects(service.login({ email: "off@example.com", password: PASSWORD }, FROM), { code: "auth.local.login.disabled" });
|
|
69
|
+
await assert.rejects(service.login({ email: "nobody@example.com", password: "a wrong password" }, FROM), { status: 401 });
|
|
70
|
+
await assert.rejects(service.login({ email: "ada@example.com", password: "a wrong password" }, FROM), { status: 401 });
|
|
71
|
+
// One failure makes ada wait: then even the right password is refused, unchecked.
|
|
72
|
+
await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }, FROM), { status: 429 });
|
|
73
|
+
// A sign-in with no request says nothing of where it came from.
|
|
74
|
+
t.mock.timers.tick(31_000);
|
|
75
|
+
await service.login({ email: "ada@example.com", password: PASSWORD });
|
|
76
|
+
|
|
77
|
+
assert.deepEqual(await takeEvents(), [
|
|
78
|
+
{ type: "signedIn", method: "registration", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
|
|
79
|
+
{ type: "signedIn", method: "password", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
|
|
80
|
+
{ type: "failed", method: "password", reason: "disabled", userId: "usr_off", email: "off@example.com", ...WHERE, at: at() },
|
|
81
|
+
{ type: "failed", method: "password", reason: "invalidCredentials", userId: "", email: "nobody@example.com", ...WHERE, at: at() },
|
|
82
|
+
{ type: "failed", method: "password", reason: "invalidCredentials", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
|
|
83
|
+
{ type: "failed", method: "password", reason: "locked", userId: adaId, email: "ada@example.com", ...WHERE, at: at() },
|
|
84
|
+
{ type: "signedIn", method: "password", userId: adaId, email: "ada@example.com", ip: "", userAgent: "", at: at(31_000) }
|
|
85
|
+
]);
|
|
86
|
+
|
|
87
|
+
// A password reset's link signs in too, for the reset.
|
|
88
|
+
const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
|
|
89
|
+
await service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") }, FROM);
|
|
90
|
+
assert.deepEqual(await takeEvents(), [
|
|
91
|
+
{ type: "signedIn", method: "recovery", userId: adaId, email: "ada@example.com", ...WHERE, at: at(31_000) }
|
|
92
|
+
]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("a registration waiting for its email is an event when its right password is refused, and when its link signs in", async (t) => {
|
|
96
|
+
t.mock.timers.enable({ apis: ["Date"], now: START });
|
|
97
|
+
const { service, takeEvents } = await startService(t, { env: { AUTH_LOCAL_EMAIL_CONFIRMATION: "" } });
|
|
98
|
+
const waiting = await service.register({ email: "eve@example.com", password: PASSWORD }, FROM);
|
|
99
|
+
await assert.rejects(service.login({ email: "eve@example.com", password: PASSWORD }, FROM), { code: "auth.login.emailUnconfirmed" });
|
|
100
|
+
const token = new URL(waiting.confirmationUrl).searchParams.get("confirmation_token");
|
|
101
|
+
const confirmed = await service.confirmRegistration({ token, password: PASSWORD }, FROM);
|
|
102
|
+
assert.deepEqual(await takeEvents(), [
|
|
103
|
+
{ type: "failed", method: "password", reason: "unconfirmed", userId: "", email: "eve@example.com", ...WHERE, at: at() },
|
|
104
|
+
{ type: "signedIn", method: "confirmation", userId: confirmed.actor.providerUserId, email: "eve@example.com", ...WHERE, at: at() }
|
|
105
|
+
]);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("a one-time pass's sign-in, and its refusal for a disabled account, are events", async (t) => {
|
|
109
|
+
t.mock.timers.enable({ apis: ["Date"], now: START });
|
|
110
|
+
const issuer = createPassIssuer();
|
|
111
|
+
const { backend, service, takeEvents } = await startService(t, { env: issuer.env, passIdentity: true });
|
|
112
|
+
await backend.withTransaction(async (tx) => {
|
|
113
|
+
await tx.users.create(passwordlessAccount({ id: "usr_ada", email: "ada@example.com", displayName: "Ada" }));
|
|
114
|
+
await tx.users.create(passwordlessAccount({ id: "usr_off", email: "off@example.com", displayName: "Off", disabled: true }));
|
|
115
|
+
});
|
|
116
|
+
await service.signInWithPass({ pass: issuer.pass("ada@example.com") }, FROM);
|
|
117
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("off@example.com") }, FROM), { code: "auth.local.login.disabled" });
|
|
118
|
+
// A pass that names nobody signs no account in or out: no event.
|
|
119
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("nobody@example.com") }, FROM), { code: "auth.pass.unmapped" });
|
|
120
|
+
assert.deepEqual(await takeEvents(), [
|
|
121
|
+
{ type: "signedIn", method: "pass", userId: "usr_ada", email: "ada@example.com", ...WHERE, at: at() },
|
|
122
|
+
{ type: "failed", method: "pass", reason: "disabled", userId: "usr_off", email: "off@example.com", ...WHERE, at: at() }
|
|
123
|
+
]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("a provider's sign-in, and its refusal for a disabled account, are events naming the provider", async (t) => {
|
|
127
|
+
const issuer = await startOidcProvider();
|
|
128
|
+
t.after(() => issuer.close());
|
|
129
|
+
const withGoogle = { env: { APP_PUBLIC_URL: APP_URL }, config: (given) => ({ ...given, oauthProviders: [oidcProviderEntry(issuer)], oauthEnabled: true }) };
|
|
130
|
+
const fromBrowser = (request) => ({ ...request, ...FROM, cookies: request.cookies });
|
|
131
|
+
const { service, takeEvents } = await startService(t, withGoogle);
|
|
132
|
+
const approved = await approveAtProvider(service);
|
|
133
|
+
const signedIn = await service.oauthComplete(approved.input, fromBrowser(approved.request));
|
|
134
|
+
const [event] = await takeEvents();
|
|
135
|
+
assert.deepEqual({ ...event, at: "" }, {
|
|
136
|
+
type: "signedIn",
|
|
137
|
+
method: "provider",
|
|
138
|
+
provider: "google",
|
|
139
|
+
userId: signedIn.actor.providerUserId,
|
|
140
|
+
email: issuer.account.email,
|
|
141
|
+
...WHERE,
|
|
142
|
+
at: ""
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const off = await startService(t, withGoogle);
|
|
146
|
+
await off.backend.withTransaction((tx) => tx.users.create({
|
|
147
|
+
id: "usr_off", email: issuer.account.email, displayName: "Off", password: NO_PASSWORD, disabled: true
|
|
148
|
+
}));
|
|
149
|
+
const refused = await approveAtProvider(off.service);
|
|
150
|
+
await assert.rejects(off.service.oauthComplete(refused.input, fromBrowser(refused.request)), { code: "auth.local.login.disabled" });
|
|
151
|
+
const [refusal] = await off.takeEvents();
|
|
152
|
+
assert.deepEqual({ ...refusal, at: "" }, {
|
|
153
|
+
type: "failed",
|
|
154
|
+
method: "provider",
|
|
155
|
+
provider: "google",
|
|
156
|
+
reason: "disabled",
|
|
157
|
+
userId: "usr_off",
|
|
158
|
+
email: issuer.account.email,
|
|
159
|
+
...WHERE,
|
|
160
|
+
at: ""
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("a refused sign-in answers without waiting for its event, and an event that fails is logged, never the sign-in's failure", async (t) => {
|
|
165
|
+
const warnings = [];
|
|
166
|
+
const logger = { ...silentLogger, error: (fields, message) => warnings.push({ fields, message }) };
|
|
167
|
+
const stalled = await startService(t, { signInEvents: () => new Promise(() => {}) });
|
|
168
|
+
await stalled.service.register({ email: "ada@example.com", password: PASSWORD });
|
|
169
|
+
for (const email of ["ada@example.com", "nobody@example.com"]) {
|
|
170
|
+
await assert.rejects(stalled.service.login({ email, password: "a wrong password" }), { status: 401 }, email);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
|
|
174
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
175
|
+
const deliveries = createLocalDeliveries({ logger });
|
|
176
|
+
const failing = createLocalAuthService({
|
|
177
|
+
...localServiceOptions(),
|
|
178
|
+
backend: createLocalFileBackend({ storeDir }),
|
|
179
|
+
deliveries,
|
|
180
|
+
logger,
|
|
181
|
+
signInEvents: async () => {
|
|
182
|
+
throw new Error("The audit log is unavailable.");
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
assert.equal((await failing.register({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
|
|
186
|
+
await deliveries.settled();
|
|
187
|
+
assert.deepEqual(warnings.map(({ fields, message }) => [fields.err.message, fields.email, message]), [
|
|
188
|
+
["The audit log is unavailable.", "ada@example.com", "Sending the sign-in event failed."]
|
|
189
|
+
]);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test("a local auth service given no sign-in events recorder is refused when it is made", async (t) => {
|
|
193
|
+
const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-sign-in-events-"));
|
|
194
|
+
t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
|
|
195
|
+
const backend = createLocalFileBackend({ storeDir });
|
|
196
|
+
assert.throws(() => createLocalAuthService({ ...localServiceOptions(), backend, signInEvents: undefined }),
|
|
197
|
+
{ name: "TypeError", message: /signInEvents/u });
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("without an application's own, each sign-in event is logged", async () => {
|
|
201
|
+
const logged = [];
|
|
202
|
+
const logSignInEvent = createLoggedSignInEvents({ ...silentLogger, info: (fields, message) => logged.push({ fields, message }) });
|
|
203
|
+
const event = { type: "failed", method: "password", reason: "invalidCredentials", userId: "", email: "nobody@example.com", ip: "", userAgent: "", at: at() };
|
|
204
|
+
await logSignInEvent(event);
|
|
205
|
+
assert.deepEqual(logged, [{ fields: { signInEvent: event }, message: "Local auth sign-in: failed." }]);
|
|
206
|
+
});
|
|
@@ -60,7 +60,7 @@ test("a password reset ends the wait, so recovery is always the way back in", as
|
|
|
60
60
|
test("sign-in throttle and password length settings are checked at startup", () => {
|
|
61
61
|
const resolve = (env) => resolveLocalAuthConfig({
|
|
62
62
|
appRoot: os.tmpdir(),
|
|
63
|
-
env: {
|
|
63
|
+
env: { APP_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "test-session-secret", ...env },
|
|
64
64
|
fileBackend: false,
|
|
65
65
|
emailRecovery: false
|
|
66
66
|
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createLocalAuthService, createLocalDeliveries } from "../src/server/lib/index.js";
|
|
3
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
4
|
+
import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
|
|
5
|
+
import { localServiceOptions } from "./localService.js";
|
|
6
|
+
|
|
7
|
+
const PASSWORD = "correct horse battery staple";
|
|
8
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A local auth service over the backend whose email-change sender keeps what it is given, sent through deliveries the
|
|
12
|
+
* test waits for.
|
|
13
|
+
* @param {import("../src/server/types.js").AuthLocalBackend} backend
|
|
14
|
+
*/
|
|
15
|
+
function emailChangeService(backend) {
|
|
16
|
+
const deliveries = createLocalDeliveries({ logger: silentLogger });
|
|
17
|
+
const sent = [];
|
|
18
|
+
const service = createLocalAuthService({
|
|
19
|
+
...localServiceOptions({ emailChangeSender: true }),
|
|
20
|
+
backend,
|
|
21
|
+
deliveries,
|
|
22
|
+
emailChangeSender: async (delivery) => {
|
|
23
|
+
sent.push(delivery);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
/** What was sent so far, once every send finished; it forgets them. */
|
|
27
|
+
async function takeSent() {
|
|
28
|
+
await deliveries.settled();
|
|
29
|
+
return sent.splice(0);
|
|
30
|
+
}
|
|
31
|
+
return { service, takeSent };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sessionCookies(session) {
|
|
35
|
+
return { jskit_local_access_token: session.access_token, jskit_local_refresh_token: session.refresh_token };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const tokenOf = (delivery) => new URL(delivery.confirmationUrl).searchParams.get("token");
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* An account's email change, against any backend, with Date mocked through `t.mock.timers`: the signed-in person
|
|
42
|
+
* asks with their password, or the application asks for an account; a link goes to the new address, and using it
|
|
43
|
+
* changes the email and tells the old address. A newer request, a used link, an expired one and one for an email
|
|
44
|
+
* taken since are refused; refusals change and send nothing.
|
|
45
|
+
* @param {import("node:test").TestContext} t
|
|
46
|
+
* @param {import("../src/server/types.js").AuthLocalBackend} backend
|
|
47
|
+
* @returns {Promise<{ adaId: string, bobId: string }>} The accounts it changed, for the backend's own checks.
|
|
48
|
+
*/
|
|
49
|
+
async function exerciseEmailChange(t, backend) {
|
|
50
|
+
t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-15T09:00:00.000Z") });
|
|
51
|
+
const { service, takeSent } = emailChangeService(backend);
|
|
52
|
+
const ada = await service.register({ email: "ada@example.com", password: PASSWORD });
|
|
53
|
+
const bob = await service.register({ email: "bob@example.com", password: PASSWORD });
|
|
54
|
+
const adaId = ada.actor.providerUserId;
|
|
55
|
+
const bobId = bob.actor.providerUserId;
|
|
56
|
+
const signedIn = { cookies: sessionCookies(ada.session) };
|
|
57
|
+
const user = (id) => backend.withTransaction((tx) => tx.users.findById(id));
|
|
58
|
+
|
|
59
|
+
// Refused: no session, a wrong password, no email or not an email, the same email, another account's email.
|
|
60
|
+
await assert.rejects(service.requestEmailChange({ cookies: {} }, { email: "new@example.com", password: PASSWORD }),
|
|
61
|
+
AUTH_TEXTS.sessionRequired);
|
|
62
|
+
await assert.rejects(service.requestEmailChange(signedIn, { email: "new@example.com", password: "a wrong password" }),
|
|
63
|
+
{ status: 400, code: "auth.local.emailChange.passwordInvalid" });
|
|
64
|
+
for (const email of ["", "not an email"]) {
|
|
65
|
+
await assert.rejects(service.requestEmailChange(signedIn, { email, password: PASSWORD }),
|
|
66
|
+
{ status: 400, code: "auth.local.email.invalid" }, email);
|
|
67
|
+
}
|
|
68
|
+
await assert.rejects(service.requestEmailChange(signedIn, { email: "Ada@Example.com", password: PASSWORD }),
|
|
69
|
+
{ status: 400, code: "auth.local.emailChange.sameEmail" });
|
|
70
|
+
await assert.rejects(service.requestEmailChange(signedIn, { email: "bob@example.com", password: PASSWORD }),
|
|
71
|
+
{ status: 409, code: "auth.local.emailChange.emailTaken" });
|
|
72
|
+
assert.deepEqual(await takeSent(), []);
|
|
73
|
+
assert.equal((await user(adaId)).pendingEmail, "");
|
|
74
|
+
|
|
75
|
+
// A request answers the new address and sends it a link; the email is unchanged until the link is used. A userId
|
|
76
|
+
// in the request changes nothing: the session names the account.
|
|
77
|
+
assert.deepEqual(
|
|
78
|
+
await service.requestEmailChange(signedIn, { email: "Ada.First@example.com", password: PASSWORD, userId: bobId }),
|
|
79
|
+
{ ok: true, email: "ada.first@example.com" }
|
|
80
|
+
);
|
|
81
|
+
const [first] = await takeSent();
|
|
82
|
+
assert.deepEqual({ ...first, confirmationUrl: "" },
|
|
83
|
+
{ type: "confirmation", email: "ada.first@example.com", currentEmail: "ada@example.com", confirmationUrl: "" });
|
|
84
|
+
assert.match(first.confirmationUrl, /^http:\/\/localhost:5173\/auth\/email-change\?token=/u);
|
|
85
|
+
assert.equal((await user(adaId)).email, "ada@example.com");
|
|
86
|
+
assert.equal((await user(adaId)).pendingEmail, "ada.first@example.com");
|
|
87
|
+
assert.equal((await user(bobId)).pendingEmail, "");
|
|
88
|
+
|
|
89
|
+
// A newer request replaces it, so the first link no longer works.
|
|
90
|
+
await service.requestEmailChange(signedIn, { email: "ada.second@example.com", password: PASSWORD });
|
|
91
|
+
const [second] = await takeSent();
|
|
92
|
+
await assert.rejects(service.confirmEmailChange({ token: tokenOf(first) }), { status: 400, code: "auth.local.emailChange.linkInvalid" });
|
|
93
|
+
// A password reset sent to the old address before the change stops working once the email changes.
|
|
94
|
+
const { recoveryUrl } = await service.requestPasswordReset({ email: "ada@example.com" });
|
|
95
|
+
|
|
96
|
+
assert.deepEqual(await service.confirmEmailChange({ token: tokenOf(second) }), { ok: true, email: "ada.second@example.com" });
|
|
97
|
+
assert.deepEqual(await takeSent(), [{ type: "notice", email: "ada@example.com", newEmail: "ada.second@example.com" }]);
|
|
98
|
+
const changed = await user(adaId);
|
|
99
|
+
assert.deepEqual([changed.email, changed.pendingEmail], ["ada.second@example.com", ""]);
|
|
100
|
+
await assert.rejects(service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") }),
|
|
101
|
+
{ code: "auth.local.recovery.tokenInvalid" });
|
|
102
|
+
await assert.rejects(service.login({ email: "ada@example.com", password: PASSWORD }), { status: 401 });
|
|
103
|
+
assert.equal((await service.login({ email: "ada.second@example.com", password: PASSWORD })).actor.email, "ada.second@example.com");
|
|
104
|
+
// The session stays signed in, with the new email from its next request on.
|
|
105
|
+
assert.equal((await service.authenticateRequest({ cookies: signedIn.cookies })).actor.email, "ada.second@example.com");
|
|
106
|
+
// A used link, a link that is not one, and a link changed by hand are refused.
|
|
107
|
+
for (const token of [tokenOf(second), "", "not-a-link", `${tokenOf(second)}x`]) {
|
|
108
|
+
await assert.rejects(service.confirmEmailChange({ token }), { status: 400, code: "auth.local.emailChange.linkInvalid" }, token);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The application asks for an account, without a password; a missing id is a programming error, a missing account
|
|
112
|
+
// is refused.
|
|
113
|
+
assert.deepEqual(await service.requestEmailChangeForUser({ userId: bobId, email: "bob.new@example.com" }),
|
|
114
|
+
{ ok: true, email: "bob.new@example.com" });
|
|
115
|
+
const [bobLink] = await takeSent();
|
|
116
|
+
assert.deepEqual([bobLink.type, bobLink.email, bobLink.currentEmail], ["confirmation", "bob.new@example.com", "bob@example.com"]);
|
|
117
|
+
await assert.rejects(service.requestEmailChangeForUser({ userId: "", email: "x@example.com" }), TypeError);
|
|
118
|
+
await assert.rejects(service.requestEmailChangeForUser({ userId: "usr_missing", email: "x@example.com" }),
|
|
119
|
+
{ status: 404, code: "auth.local.emailChange.accountNotFound" });
|
|
120
|
+
await assert.rejects(service.requestEmailChangeForUser({ userId: bobId, email: "ada.second@example.com" }),
|
|
121
|
+
{ status: 409, code: "auth.local.emailChange.emailTaken" });
|
|
122
|
+
assert.deepEqual(await takeSent(), []);
|
|
123
|
+
|
|
124
|
+
// A link expires after a day.
|
|
125
|
+
t.mock.timers.tick(DAY + 1000);
|
|
126
|
+
await assert.rejects(service.confirmEmailChange({ token: tokenOf(bobLink) }), { status: 400, code: "auth.local.emailChange.linkInvalid" });
|
|
127
|
+
assert.equal((await user(bobId)).email, "bob@example.com");
|
|
128
|
+
|
|
129
|
+
// An address an account took since the request is refused, and nothing changes.
|
|
130
|
+
await service.requestEmailChangeForUser({ userId: bobId, email: "carol@example.com" });
|
|
131
|
+
const [toCarol] = await takeSent();
|
|
132
|
+
await service.register({ email: "carol@example.com", password: PASSWORD });
|
|
133
|
+
await assert.rejects(service.confirmEmailChange({ token: tokenOf(toCarol) }), { status: 409, code: "auth.local.emailChange.emailTaken" });
|
|
134
|
+
assert.equal((await user(bobId)).email, "bob@example.com");
|
|
135
|
+
assert.deepEqual(await takeSent(), []);
|
|
136
|
+
return { adaId, bobId };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { emailChangeService, exerciseEmailChange };
|
|
@@ -3,10 +3,12 @@ import { invitationAsGiven } from "@jskit-ai/auth-core/server/authExtensions";
|
|
|
3
3
|
import { noAppProfiles } from "@jskit-ai/auth-core/server/noAppProfiles";
|
|
4
4
|
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
5
|
import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
|
|
6
|
+
import { createLoggedEmailChangeSender } from "../src/server/lib/emailChange.js";
|
|
6
7
|
import { createLoggedConfirmationSender } from "../src/server/lib/emailConfirmation.js";
|
|
7
8
|
import { createLoggedRecoverySender } from "../src/server/lib/passwordFlows.js";
|
|
8
9
|
import { scryptPasswordStrategy } from "../src/server/lib/passwords.js";
|
|
9
10
|
import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.js";
|
|
11
|
+
import { createLoggedSignInEvents } from "../src/server/lib/sessions.js";
|
|
10
12
|
|
|
11
13
|
/**
|
|
12
14
|
* What a test passes to createLocalAuthService besides its backend: a complete
|
|
@@ -18,13 +20,14 @@ import { createLoggedSecondFactorEvents } from "../src/server/lib/secondFactor.j
|
|
|
18
20
|
* @param {Record<string, string>} [options.env] Environment values over the test ones.
|
|
19
21
|
* @param {boolean} [options.emailRecovery] True when the test passes its own recoverySender.
|
|
20
22
|
* @param {boolean} [options.emailConfirmationSender] True when the test passes its own confirmationSender.
|
|
23
|
+
* @param {boolean} [options.emailChangeSender] True when the test passes its own emailChangeSender.
|
|
21
24
|
*/
|
|
22
|
-
function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmationSender = false } = {}) {
|
|
25
|
+
function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmationSender = false, emailChangeSender = false } = {}) {
|
|
23
26
|
return {
|
|
24
27
|
config: resolveLocalAuthConfig({
|
|
25
28
|
appRoot: os.tmpdir(),
|
|
26
29
|
env: {
|
|
27
|
-
|
|
30
|
+
APP_ENV: "test",
|
|
28
31
|
AUTH_LOCAL_SESSION_SECRET: "test-session-secret",
|
|
29
32
|
APP_PUBLIC_URL: "http://localhost:5173",
|
|
30
33
|
AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "response",
|
|
@@ -33,7 +36,8 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
|
|
|
33
36
|
},
|
|
34
37
|
fileBackend: false,
|
|
35
38
|
emailRecovery,
|
|
36
|
-
emailConfirmationSender
|
|
39
|
+
emailConfirmationSender,
|
|
40
|
+
emailChangeSender
|
|
37
41
|
}),
|
|
38
42
|
invitationContextResolver: invitationAsGiven,
|
|
39
43
|
logger: silentLogger,
|
|
@@ -41,7 +45,9 @@ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmatio
|
|
|
41
45
|
profileProjector: noAppProfiles,
|
|
42
46
|
recoverySender: createLoggedRecoverySender(silentLogger),
|
|
43
47
|
confirmationSender: createLoggedConfirmationSender(silentLogger),
|
|
44
|
-
|
|
48
|
+
emailChangeSender: createLoggedEmailChangeSender(silentLogger),
|
|
49
|
+
secondFactorEvents: createLoggedSecondFactorEvents(silentLogger),
|
|
50
|
+
signInEvents: createLoggedSignInEvents(silentLogger)
|
|
45
51
|
};
|
|
46
52
|
}
|
|
47
53
|
|
|
@@ -70,24 +70,30 @@ async function exercisePassSignIn(service, { backend, issuer }) {
|
|
|
70
70
|
await tx.users.create(passwordlessAccount({ id: "usr_off", email: "off@example.com", displayName: "Off", disabled: true }));
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
-
// A pass signs its person in, with an ordinary session, though the account has no password
|
|
73
|
+
// A pass signs its person in, with an ordinary session, though the account has no password; the session keeps the
|
|
74
|
+
// address and browser the pass came from.
|
|
74
75
|
const pass = issuer.pass("ada@example.com");
|
|
75
|
-
const signedIn = await service.signInWithPass({ pass });
|
|
76
|
+
const signedIn = await service.signInWithPass({ pass }, { ip: "203.0.113.7", headers: { "user-agent": "Pass Browser/1.0" } });
|
|
76
77
|
assert.equal(signedIn.actor.id, "usr_ada");
|
|
77
78
|
assert.equal(signedIn.actor.email, "ada@example.com");
|
|
78
79
|
const authenticated = await service.authenticateRequest({ cookies: sessionCookies(signedIn.session) });
|
|
79
80
|
assert.equal(authenticated.authenticated, true);
|
|
80
81
|
assert.equal(authenticated.actor.id, "usr_ada");
|
|
82
|
+
const session = await backend.withTransaction((tx) => tx.sessions.findById(authenticated.sessionId));
|
|
83
|
+
assert.deepEqual([session.ip, session.userAgent], ["203.0.113.7", "Pass Browser/1.0"]);
|
|
81
84
|
|
|
82
85
|
// Only once.
|
|
83
86
|
await assert.rejects(service.signInWithPass({ pass }), refused("auth.pass.replayed"));
|
|
84
87
|
// Another pass for the same person signs in again.
|
|
85
88
|
assert.equal((await service.signInWithPass({ pass: issuer.pass("ada@example.com") })).actor.id, "usr_ada");
|
|
86
89
|
|
|
87
|
-
// A pass whose subject has no account, names an account that does not exist
|
|
88
|
-
for (const subject of ["nobody@example.com", "ghost"
|
|
90
|
+
// A pass whose subject has no account, or names an account that does not exist.
|
|
91
|
+
for (const subject of ["nobody@example.com", "ghost"]) {
|
|
89
92
|
await assert.rejects(service.signInWithPass({ pass: issuer.pass(subject) }), refused("auth.pass.unmapped", 403));
|
|
90
93
|
}
|
|
94
|
+
// A pass that names a disabled account proves who it is, so it is told the account is disabled.
|
|
95
|
+
await assert.rejects(service.signInWithPass({ pass: issuer.pass("off@example.com") }),
|
|
96
|
+
{ status: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
|
|
91
97
|
// An unmapped pass was used all the same: it is refused as replayed, even once its subject has an account.
|
|
92
98
|
const early = issuer.pass("late@example.com");
|
|
93
99
|
await assert.rejects(service.signInWithPass({ pass: early }), refused("auth.pass.unmapped", 403));
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
|
|
3
|
+
const PASSWORD = "correct horse battery staple";
|
|
4
|
+
const FIREFOX = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
|
|
5
|
+
const PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148 Safari/604.1";
|
|
6
|
+
const MINUTE = 60_000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A request as Fastify gives it: from this address and browser, with these cookies.
|
|
10
|
+
* @param {string} ip
|
|
11
|
+
* @param {string} userAgent
|
|
12
|
+
* @param {Record<string, string>} [cookies]
|
|
13
|
+
*/
|
|
14
|
+
function requestFrom(ip, userAgent, cookies = {}) {
|
|
15
|
+
return { ip, headers: { "user-agent": userAgent }, cookies };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function sessionCookies(session) {
|
|
19
|
+
return { jskit_local_access_token: session.access_token, jskit_local_refresh_token: session.refresh_token };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Where and when a session was last seen, against any backend, for a service whose Date the test mocks: a session
|
|
24
|
+
* keeps the address and browser of the request that signed it in, and those of a request that finds it more than five
|
|
25
|
+
* minutes after it was last seen, with when that was; requests in between write nothing.
|
|
26
|
+
* @param {import("node:test").TestContext} t
|
|
27
|
+
* @param {object} fixtures
|
|
28
|
+
* @param {import("@jskit-ai/auth-core/server/types").AuthService} fixtures.service
|
|
29
|
+
* @param {import("../src/server/types.js").AuthLocalBackend} fixtures.backend
|
|
30
|
+
*/
|
|
31
|
+
async function exerciseSessionMetadata(t, { service, backend }) {
|
|
32
|
+
const start = Date.parse("2026-11-15T09:00:00.000Z");
|
|
33
|
+
const at = (minutes) => new Date(start + minutes * MINUTE).toISOString();
|
|
34
|
+
t.mock.timers.enable({ apis: ["Date"], now: start });
|
|
35
|
+
const registered = await service.register({ email: "ada@example.com", password: PASSWORD }, requestFrom("192.0.2.1", PHONE));
|
|
36
|
+
const signedIn = await service.login({ email: "ada@example.com", password: PASSWORD }, requestFrom("203.0.113.7", FIREFOX));
|
|
37
|
+
const cookies = sessionCookies(signedIn.session);
|
|
38
|
+
const seen = async (request) => {
|
|
39
|
+
const answer = await service.authenticateRequest(request);
|
|
40
|
+
assert.equal(answer.authenticated, true);
|
|
41
|
+
const session = await backend.withTransaction((tx) => tx.sessions.findById(answer.sessionId));
|
|
42
|
+
return { ip: session.ip, userAgent: session.userAgent, lastSeenAt: session.lastSeenAt, createdAt: session.createdAt };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// The sign-in's request, and the registration's for the session registering made.
|
|
46
|
+
assert.deepEqual(await seen(requestFrom("203.0.113.7", FIREFOX, cookies)),
|
|
47
|
+
{ ip: "203.0.113.7", userAgent: FIREFOX, lastSeenAt: at(0), createdAt: at(0) });
|
|
48
|
+
assert.deepEqual(await seen(requestFrom("192.0.2.1", PHONE, sessionCookies(registered.session))),
|
|
49
|
+
{ ip: "192.0.2.1", userAgent: PHONE, lastSeenAt: at(0), createdAt: at(0) });
|
|
50
|
+
|
|
51
|
+
// Within five minutes of being seen, a request from elsewhere changes nothing.
|
|
52
|
+
t.mock.timers.tick(4 * MINUTE);
|
|
53
|
+
assert.deepEqual(await seen(requestFrom("198.51.100.9", PHONE, cookies)),
|
|
54
|
+
{ ip: "203.0.113.7", userAgent: FIREFOX, lastSeenAt: at(0), createdAt: at(0) });
|
|
55
|
+
// After them, it is seen again from there.
|
|
56
|
+
t.mock.timers.tick(2 * MINUTE);
|
|
57
|
+
assert.deepEqual(await seen(requestFrom("198.51.100.9", PHONE, cookies)),
|
|
58
|
+
{ ip: "198.51.100.9", userAgent: PHONE, lastSeenAt: at(6), createdAt: at(0) });
|
|
59
|
+
// A request that does not say where it is from keeps where the session was last seen from.
|
|
60
|
+
t.mock.timers.tick(6 * MINUTE);
|
|
61
|
+
assert.deepEqual(await seen({ cookies }), { ip: "198.51.100.9", userAgent: PHONE, lastSeenAt: at(12), createdAt: at(0) });
|
|
62
|
+
// A session found by its refresh token, once its access token has expired, is seen too.
|
|
63
|
+
t.mock.timers.tick(20 * MINUTE);
|
|
64
|
+
assert.deepEqual(await seen(requestFrom("203.0.113.7", FIREFOX, { jskit_local_refresh_token: cookies.jskit_local_refresh_token })),
|
|
65
|
+
{ ip: "203.0.113.7", userAgent: FIREFOX, lastSeenAt: at(32), createdAt: at(0) });
|
|
66
|
+
|
|
67
|
+
// A browser that names itself at length is kept to its first 512 characters; a sign-in with no request keeps no place.
|
|
68
|
+
const long = `${FIREFOX} ${"x".repeat(600)}`;
|
|
69
|
+
const longSignIn = await service.login({ email: "ada@example.com", password: PASSWORD }, requestFrom("203.0.113.8", long));
|
|
70
|
+
assert.equal((await seen({ cookies: sessionCookies(longSignIn.session) })).userAgent, long.slice(0, 512));
|
|
71
|
+
const internal = await service.login({ email: "ada@example.com", password: PASSWORD });
|
|
72
|
+
assert.deepEqual(await seen({ cookies: sessionCookies(internal.session) }),
|
|
73
|
+
{ ip: "", userAgent: "", lastSeenAt: at(32), createdAt: at(32) });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { exerciseSessionMetadata, requestFrom };
|