@jskit-ai/auth-provider-local-core 0.2.36 → 0.2.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,8 +14,15 @@
14
14
  * findByEmail(email: string): Promise<object | null>,
15
15
  * hasAny(): Promise<boolean>,
16
16
  * updatePassword(userId: string, passwordRecord: object): Promise<object | null>,
17
- * updateProfile(userId: string, updates: object): Promise<object | null>
18
- * }} users `hasAny` answers whether any account exists.
17
+ * updateProfile(userId: string, updates: object): Promise<object | null>,
18
+ * updatePendingEmail(userId: string, pendingEmail: string): Promise<object | null>,
19
+ * updateEmail(userId: string, email: string): Promise<object | null>
20
+ * }} users `hasAny` answers whether any account exists. A user whose `disabled` is true has every sign-in and session
21
+ * refused, and a sign-in that proves who it is (the right password, a provider or a pass) is told its
22
+ * `disabledMessage`, or that the account is disabled when it has none; the file backend keeps no message. A user's
23
+ * `pendingEmail` is the address its email change waits to confirm ("" when none): `updatePendingEmail` sets it, and
24
+ * `updateEmail` changes the email to a confirmed address and clears it, refusing an email another account has with
25
+ * a ConflictError.
19
26
  * @property {{
20
27
  * create(input: object): Promise<object>,
21
28
  * findById(sessionId: string): Promise<object | null>,
@@ -23,9 +30,12 @@
23
30
  * revoke(sessionId: string): Promise<object | null>,
24
31
  * revokeForUser(userId: string, options?: object): Promise<number>,
25
32
  * markSecondFactorProved(sessionId: string, secondFactorAt: string): Promise<object | null>,
26
- * clearSecondFactorForUser(userId: string): Promise<number>
33
+ * clearSecondFactorForUser(userId: string): Promise<number>,
34
+ * touch(sessionId: string, seen: { lastSeenAt: string, ip: string, userAgent: string }): Promise<void>
27
35
  * }} sessions A session's `secondFactorAt` is when it last proved its second factor ("" when it has not):
28
- * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user.
36
+ * `markSecondFactorProved` marks one session, `clearSecondFactorForUser` every session of the user. A session keeps
37
+ * where it was last seen from, `ip` and `userAgent` (`create` takes them with `lastSeenAt`), and when, `lastSeenAt`,
38
+ * each "" when unknown; `touch` notes it seen again, keeping its `ip` or `userAgent` when the new one is "".
29
39
  * @property {{
30
40
  * create(input: object): Promise<object>,
31
41
  * findByTokenHash(tokenHash: string): Promise<object | null>,
@@ -144,6 +154,41 @@
144
154
  * @typedef {(event: AuthLocalSecondFactorEvent) => Promise<void>} AuthLocalSecondFactorEvents
145
155
  */
146
156
 
157
+ /**
158
+ * One sign-in event: a sign-in (`signedIn`) or a refused one (`failed`), by
159
+ * `method`: `password`, `registration` (registering signed in at once),
160
+ * `confirmation` (a registration's email link), `recovery` (a password reset's
161
+ * link), `pass` (a one-time pass) or `provider` (with `provider`, its id, such
162
+ * as `google`). A refusal's `reason` is `invalidCredentials`, `locked` (the
163
+ * email waits after its failures; the password was not checked),
164
+ * `unconfirmed` (the right password of a registration still waiting for its
165
+ * link) or `disabled` (the right password, provider or pass of a disabled
166
+ * account). `userId` is the local account's id, "" when the email names none;
167
+ * `email` is the email signed in, or typed; `ip` and `userAgent` are the
168
+ * request's, "" when there is no request; `at` is an ISO time. No secret,
169
+ * password or token is in it.
170
+ * @typedef {object} AuthLocalSignInEvent
171
+ * @property {"signedIn" | "failed"} type
172
+ * @property {"password" | "registration" | "confirmation" | "recovery" | "pass" | "provider"} method
173
+ * @property {string} userId
174
+ * @property {string} email
175
+ * @property {string} ip
176
+ * @property {string} userAgent
177
+ * @property {string} at
178
+ * @property {"invalidCredentials" | "locked" | "unconfirmed" | "disabled"} [reason]
179
+ * @property {string} [provider]
180
+ */
181
+
182
+ /**
183
+ * The `auth.local.sign-in-events` capability: records each sign-in and each
184
+ * refused one, for an application's own list of an account's sign-ins or its
185
+ * audit log. It is given each event after the request has answered, so a
186
+ * refused sign-in takes the same time whatever it does; when it fails, local
187
+ * auth logs the failure. A stopping server waits for it, for a while. Without
188
+ * one, local auth logs each event.
189
+ * @typedef {(event: AuthLocalSignInEvent) => Promise<void>} AuthLocalSignInEvents
190
+ */
191
+
147
192
  /**
148
193
  * An account's recent failed sign-ins: how many, the last one, and when it may
149
194
  * try again ("" when it need not wait). Times are ISO strings.
@@ -190,6 +235,20 @@
190
235
  * @typedef {(delivery: { email: string, originalEmail?: string, confirmationUrl: string }) => Promise<void>} AuthLocalConfirmationSender
191
236
  */
192
237
 
238
+ /**
239
+ * The `auth.local.email-change-sender` capability: sends what an account's
240
+ * email change sends, each through the application's email. `confirmation`
241
+ * goes to the new address (`email`) with the link that confirms it
242
+ * (`confirmationUrl`), naming the account's current address
243
+ * (`currentEmail`); `notice` goes to the old address (`email`) once the email
244
+ * changed, naming the new one (`newEmail`). It sends as APP_ENV says, like
245
+ * `AuthLocalRecoverySender`. It must reject on failure, which local auth logs,
246
+ * and must not log the link. Without one, a staging or production server has
247
+ * no email change; development and test log each.
248
+ * @typedef {(delivery: { type: "confirmation", email: string, originalEmail?: string, currentEmail: string, confirmationUrl: string }
249
+ * | { type: "notice", email: string, originalEmail?: string, newEmail: string }) => Promise<void>} AuthLocalEmailChangeSender
250
+ */
251
+
193
252
  /**
194
253
  * The `auth.local.confirmation-mode` capability: the application's choice, for
195
254
  * one registration that would wait for its email to be confirmed, of how it is
@@ -139,16 +139,25 @@ test("a failed sign-in checks one password, whether or not its email has one to
139
139
  return scryptPasswordStrategy.verifyPassword(password, record);
140
140
  }
141
141
  };
142
- const { service } = await startService(t, { passwordStrategy });
142
+ const { backend, service } = await startService(t, { passwordStrategy });
143
143
  await service.register({ email: "ada@example.com", password: PASSWORD });
144
+ const password = await scryptPasswordStrategy.hashPassword(PASSWORD);
145
+ await backend.withTransaction((tx) =>
146
+ tx.users.create({ id: "usr_off", email: "off@example.com", displayName: "Off", password, disabled: true }));
144
147
 
145
- for (const email of ["ada@example.com", "nobody@example.com", "NOBODY@example.com", "other@example.com"]) {
148
+ for (const email of ["ada@example.com", "nobody@example.com", "NOBODY@example.com", "other@example.com", "off@example.com"]) {
146
149
  checks.length = 0;
147
- await assert.rejects(service.login({ email, password: "a wrong password" }), { status: 401 }, email);
150
+ await assert.rejects(service.login({ email, password: "a wrong password" }),
151
+ { status: 401, code: "auth.login.invalidCredentials" }, email);
148
152
  assert.deepEqual(checks, ["a wrong password"], email);
149
153
  }
150
154
  // The right password still signs in, with one check.
151
155
  checks.length = 0;
152
156
  assert.equal((await service.login({ email: "ada@example.com", password: PASSWORD })).actor.email, "ada@example.com");
153
157
  assert.deepEqual(checks, [PASSWORD]);
158
+ // A disabled account's right password, and only that, is told the account is disabled.
159
+ checks.length = 0;
160
+ await assert.rejects(service.login({ email: "off@example.com", password: PASSWORD }),
161
+ { status: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
162
+ assert.deepEqual(checks, [PASSWORD]);
154
163
  });
@@ -0,0 +1,37 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { createLocalFileBackend } from "../src/server/lib/index.js";
7
+ import { emailChangeService, exerciseEmailChange } from "../test-support/emailChangeScenario.js";
8
+
9
+ async function fileBackend(t) {
10
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-email-change-"));
11
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
12
+ return { backend: createLocalFileBackend({ storeDir }), storeDir };
13
+ }
14
+
15
+ test("an account's email changes once the link sent to the new address is used, and the old address is told (file backend)", async (t) => {
16
+ const { backend, storeDir } = await fileBackend(t);
17
+ const { adaId } = await exerciseEmailChange(t, backend);
18
+ // Another server on the same store reads the change.
19
+ const reread = createLocalFileBackend({ storeDir });
20
+ assert.equal((await reread.withTransaction((tx) => tx.users.findById(adaId))).email, "ada.second@example.com");
21
+ });
22
+
23
+ test("a waiting change is kept in the file store, and an account stored before it read as having none", async (t) => {
24
+ const { backend, storeDir } = await fileBackend(t);
25
+ const { service } = emailChangeService(backend);
26
+ const ada = await service.register({ email: "ada@example.com", password: "correct horse battery staple" });
27
+ await service.requestEmailChangeForUser({ userId: ada.actor.providerUserId, email: "ada.new@example.com" });
28
+ const reread = createLocalFileBackend({ storeDir });
29
+ assert.equal((await reread.withTransaction((tx) => tx.users.findById(ada.actor.providerUserId))).pendingEmail, "ada.new@example.com");
30
+
31
+ const usersFile = path.join(storeDir, "users.passwd");
32
+ const line = (await fs.readFile(usersFile, "utf8")).trim();
33
+ // The twelve fields an account had before it kept a waiting change.
34
+ await fs.writeFile(usersFile, `${line.split(":").slice(0, 12).join(":")}\n`);
35
+ const older = createLocalFileBackend({ storeDir });
36
+ assert.equal((await older.withTransaction((tx) => tx.users.findById(ada.actor.providerUserId))).pendingEmail, "");
37
+ });
@@ -12,6 +12,7 @@ import {
12
12
  createLocalAuthRegisterHookDecorator,
13
13
  createLocalFileBackend
14
14
  } from "../src/server/lib/index.js";
15
+ import { NO_PASSWORD } from "../src/server/lib/accounts.js";
15
16
  import { sha256Base64url } from "../src/server/lib/tokens.js";
16
17
  import { resolveLocalAuthConfig } from "../src/server/lib/config.js";
17
18
  import {
@@ -198,6 +199,17 @@ test("a verified email that matches an existing account signs it in and links Go
198
199
  assert.equal(again.actor.email, issuer.account.email);
199
200
  });
200
201
 
202
+ test("a provider sign-in of a disabled account is told the account is disabled, and links nothing", async (t) => {
203
+ const { issuer, backend, service } = await googleSetup(t);
204
+ await backend.withTransaction((tx) => tx.users.create({
205
+ id: "usr_off", email: issuer.account.email, displayName: "Off", password: NO_PASSWORD, disabled: true
206
+ }));
207
+ const { input, request } = await approveAtProvider(service);
208
+ await assert.rejects(service.oauthComplete(input, request),
209
+ { statusCode: 403, code: "auth.local.login.disabled", message: "This account is disabled." });
210
+ assert.deepEqual(await backend.withTransaction((tx) => tx.identities.listForUser("usr_off")), []);
211
+ });
212
+
201
213
  test("a callback with the wrong state, another browser's attempt, or a used attempt is refused", async (t) => {
202
214
  const { backend, service } = await googleSetup(t);
203
215
  const { input, request } = await approveAtProvider(service);
@@ -117,7 +117,9 @@ async function createStartedApp({
117
117
  confirmationMode = null,
118
118
  invitationContextResolver = null,
119
119
  logger = null,
120
- configureExtensions = null
120
+ configureExtensions = null,
121
+ signInEvents = null,
122
+ emailChangeSender = null
121
123
  } = {}) {
122
124
  const storeDir = await temporaryStoreDir("jskit-auth-local-");
123
125
  const backend = createLocalFileBackend({ storeDir });
@@ -168,6 +170,8 @@ async function createStartedApp({
168
170
  ...(recoverySender !== null ? { "auth.local.recovery-sender": recoverySender } : {}),
169
171
  ...(confirmationSender !== null ? { "auth.local.confirmation-sender": confirmationSender } : {}),
170
172
  ...(confirmationMode !== null ? { "auth.local.confirmation-mode": confirmationMode } : {}),
173
+ ...(signInEvents !== null ? { "auth.local.sign-in-events": signInEvents } : {}),
174
+ ...(emailChangeSender !== null ? { "auth.local.email-change-sender": emailChangeSender } : {}),
171
175
  };
172
176
  const runtime = createCapabilityRuntime({
173
177
  inputs,
@@ -1377,6 +1381,93 @@ test("production sessions use host-only __Host- cookies and ignore the old names
1377
1381
  assert.equal((await app.authService.authenticateRequest({ cookies: oldNames })).authenticated, false);
1378
1382
  });
1379
1383
 
1384
+ test("an installed auth.local.sign-in-events is given each sign-in event, and without one each is logged", async (t) => {
1385
+ const PASSWORD = "correct horse battery staple";
1386
+ const events = [];
1387
+ const app = await createStartedApp({ signInEvents: async (event) => { events.push(event); } });
1388
+ t.after(() => fs.rm(app.storeDir, { recursive: true, force: true }));
1389
+ const ada = (await app.authService.register({ email: "ada@example.com", password: PASSWORD })).actor.providerUserId;
1390
+ await assert.rejects(app.authService.login({ email: "ada@example.com", password: "a wrong password" }), { status: 401 });
1391
+ // Stopping waits for the events still being handed over.
1392
+ await app.runtime.shutdown();
1393
+ assert.deepEqual(events.map(({ type, method, reason = "", userId }) => [type, method, reason, userId]), [
1394
+ ["signedIn", "registration", "", ada],
1395
+ ["failed", "password", "invalidCredentials", ada]
1396
+ ]);
1397
+
1398
+ const logs = [];
1399
+ const logged = await createStartedApp({
1400
+ logger: { info: (fields, message) => logs.push([message, fields?.signInEvent?.method]), warn() {}, error() {}, debug() {} }
1401
+ });
1402
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1403
+ await logged.authService.register({ email: "ada@example.com", password: PASSWORD });
1404
+ await logged.runtime.shutdown();
1405
+ assert.deepEqual(logs.filter(([message]) => String(message).startsWith("Local auth sign-in")),
1406
+ [["Local auth sign-in: signedIn.", "registration"]]);
1407
+ });
1408
+
1409
+ test("an installed auth.local.email-change-sender sends as APP_ENV says; without one, development and test log the links and a deployed server has none",
1410
+ async (t) => {
1411
+ const PASSWORD = "correct horse battery staple";
1412
+ const account = async (app, id, email) => {
1413
+ await app.backend.withTransaction(async (tx) => tx.users.create({ id, email, displayName: id, password: await hashPassword(PASSWORD) }));
1414
+ return id;
1415
+ };
1416
+ const deployed = { AUTH_LOCAL_EMAIL_CONFIRMATION: "", AUTH_LOCAL_SELF_REGISTRATION: "false" };
1417
+
1418
+ // Production sends each link to its address.
1419
+ const sent = [];
1420
+ const production = await createStartedApp({ env: { ...PRODUCTION, ...deployed }, emailChangeSender: async (delivery) => { sent.push(delivery); } });
1421
+ t.after(() => fs.rm(production.storeDir, { recursive: true, force: true }));
1422
+ assert.equal(production.authService.getCapabilities().features.emailChange, true);
1423
+ await production.authService.requestEmailChangeForUser({ userId: await account(production, "usr_ada", "ada@example.com"), email: "ada.new@example.com" });
1424
+ // Stopping waits for the links still being sent.
1425
+ await production.runtime.shutdown();
1426
+ assert.deepEqual(sent.map(({ type, email, originalEmail, currentEmail }) => [type, email, originalEmail, currentEmail]),
1427
+ [["confirmation", "ada.new@example.com", "", "ada@example.com"]]);
1428
+ assert.match(sent[0].confirmationUrl, /^http:\/\/localhost:5173\/auth\/email-change\?token=/u);
1429
+
1430
+ // Test (as development) logs the link an installed sender would send, and sends nothing.
1431
+ const logs = [];
1432
+ const logger = { info: (details, message) => logs.push({ details, message }), warn() {}, error() {}, debug() {} };
1433
+ const copy = await createStartedApp({ emailChangeSender: async (delivery) => { sent.push(delivery); }, logger });
1434
+ t.after(() => fs.rm(copy.storeDir, { recursive: true, force: true }));
1435
+ await copy.authService.requestEmailChangeForUser({ userId: await account(copy, "usr_bob", "bob@example.com"), email: "bob.new@example.com" });
1436
+ await copy.runtime.shutdown();
1437
+ assert.equal(sent.length, 1, "nothing more sent");
1438
+ const [link] = logs.filter(({ message }) => String(message).includes("the email change email"));
1439
+ assert.equal(link.message, "Test: the email change email to bob.new@example.com was logged, not sent.");
1440
+ assert.match(link.details.confirmationUrl, /\/auth\/email-change\?token=/u);
1441
+
1442
+ // Without one, development and test log each link.
1443
+ logs.length = 0;
1444
+ const logged = await createStartedApp({ logger });
1445
+ t.after(() => fs.rm(logged.storeDir, { recursive: true, force: true }));
1446
+ await logged.authService.requestEmailChangeForUser({ userId: await account(logged, "usr_eve", "eve@example.com"), email: "eve.new@example.com" });
1447
+ await logged.runtime.shutdown();
1448
+ assert.deepEqual(logs.filter(({ message }) => String(message).startsWith("Local auth email change")).map(({ details, message }) => [message, details.email]),
1449
+ [["Local auth email change: confirmation.", "eve.new@example.com"]]);
1450
+
1451
+ // Staging and production without one offer no email change, and a sender needs the public URL its links name.
1452
+ for (const env of [STAGING, PRODUCTION]) {
1453
+ const without = await createStartedApp({ env: { ...env, ...deployed } });
1454
+ t.after(() => fs.rm(without.storeDir, { recursive: true, force: true }));
1455
+ assert.equal(without.authService.getCapabilities().features.emailChange, false, env.APP_ENV);
1456
+ for (const asked of [
1457
+ without.authService.requestEmailChange({ cookies: {} }, { email: "x@example.com", password: PASSWORD }),
1458
+ without.authService.requestEmailChangeForUser({ userId: "usr_any", email: "x@example.com" }),
1459
+ without.authService.confirmEmailChange({ token: "any" })
1460
+ ]) {
1461
+ await assert.rejects(asked, { status: 501, code: "AUTH_OPERATION_UNSUPPORTED" });
1462
+ }
1463
+ await without.runtime.shutdown();
1464
+ }
1465
+ await assert.rejects(
1466
+ () => createStartedApp({ env: { APP_PUBLIC_URL: "" }, emailChangeSender: async () => {} }),
1467
+ /APP_PUBLIC_URL is required when local auth emails email change links/u
1468
+ );
1469
+ });
1470
+
1380
1471
  test("local recovery uses the application sender without returning or logging its token", async (t) => {
1381
1472
  const messages = [];
1382
1473
  const logs = [];
@@ -0,0 +1,38 @@
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 { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
7
+ import { localServiceOptions } from "../test-support/localService.js";
8
+ import { exerciseSessionMetadata } from "../test-support/sessionMetadataScenario.js";
9
+
10
+ test("a session keeps where and when it was last seen, at most every five minutes (file backend)", async (t) => {
11
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-session-metadata-"));
12
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
13
+ const backend = createLocalFileBackend({ storeDir });
14
+ await exerciseSessionMetadata(t, { service: createLocalAuthService({ ...localServiceOptions(), backend }), backend });
15
+ });
16
+
17
+ test("a session the file backend stored before it kept where sessions are seen reads as never seen", async (t) => {
18
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-session-metadata-"));
19
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
20
+ const field = (value) => Buffer.from(value, "utf8").toString("base64url");
21
+ const line = ["session", "v1", "ses_old", "usr_old", "hash-old", "normal",
22
+ field("2026-11-01T09:00:00.000Z"), field("2026-12-01T09:00:00.000Z"), field(""), field("")].join(":");
23
+ await fs.writeFile(path.join(storeDir, "sessions.passwd"), `${line}\n`);
24
+ const backend = createLocalFileBackend({ storeDir });
25
+ assert.deepEqual(await backend.withTransaction((tx) => tx.sessions.findById("ses_old")), {
26
+ id: "ses_old",
27
+ userId: "usr_old",
28
+ tokenHash: "hash-old",
29
+ purpose: "normal",
30
+ createdAt: "2026-11-01T09:00:00.000Z",
31
+ expiresAt: "2026-12-01T09:00:00.000Z",
32
+ revokedAt: "",
33
+ secondFactorAt: "",
34
+ ip: "",
35
+ userAgent: "",
36
+ lastSeenAt: ""
37
+ });
38
+ });
@@ -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
+ });