@jskit-ai/auth-provider-local-core 0.2.9 → 0.2.11

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.
@@ -0,0 +1,88 @@
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 { resolveLocalAuthConfig } from "../src/server/lib/config.js";
8
+ import { localServiceOptions } from "../test-support/localService.js";
9
+ import { exerciseSignInThrottle } from "../test-support/signInThrottleScenario.js";
10
+
11
+ const PASSWORD = "correct horse battery staple";
12
+
13
+ async function startService(t, env = {}) {
14
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-throttle-"));
15
+ t.after(() => fs.rm(storeDir, { recursive: true, force: true }));
16
+ const backend = createLocalFileBackend({ storeDir });
17
+ return createLocalAuthService({ ...localServiceOptions({ env }), backend });
18
+ }
19
+
20
+ test("failed sign-ins make the account wait, doubling, and a success forgets them (file backend)", async (t) => {
21
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
22
+ await exerciseSignInThrottle(t, await startService(t));
23
+ });
24
+
25
+ test("the longest wait caps the doubling", async (t) => {
26
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
27
+ const service = await startService(t, {
28
+ AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT: "2",
29
+ AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS: "30",
30
+ AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS: "100"
31
+ });
32
+ const signIn = () => service.login({ email: "cap@example.com", password: "wrong value" });
33
+ await assert.rejects(signIn(), { status: 401 });
34
+ for (const expectedSeconds of [30, 60, 100, 100]) {
35
+ await assert.rejects(signIn(), { status: 401 });
36
+ await assert.rejects(signIn(), (error) => error.status === 429 && error.params.retryAfterSeconds === expectedSeconds);
37
+ t.mock.timers.tick(expectedSeconds * 1000);
38
+ }
39
+ });
40
+
41
+ test("a password reset ends the wait, so recovery is always the way back in", async (t) => {
42
+ t.mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-11-06T10:00:00.000Z") });
43
+ const service = await startService(t);
44
+ await service.register({ email: "locked@example.com", password: PASSWORD });
45
+ for (let attempt = 0; attempt < 5; attempt += 1) {
46
+ await assert.rejects(service.login({ email: "locked@example.com", password: "a guess" }), { status: 401 });
47
+ }
48
+ await assert.rejects(service.login({ email: "locked@example.com", password: PASSWORD }), { status: 429 });
49
+
50
+ const { recoveryUrl } = await service.requestPasswordReset({ email: "locked@example.com" });
51
+ const recovery = await service.completePasswordRecovery({ code: new URL(recoveryUrl).searchParams.get("token") });
52
+ const cookies = {};
53
+ service.writeSessionCookies({ setCookie: (name, value) => { cookies[name] = value; }, clearCookie() {} }, recovery.session);
54
+ await service.resetPassword({ password: "a brand new password" }, { cookies });
55
+
56
+ const signedIn = await service.login({ email: "locked@example.com", password: "a brand new password" });
57
+ assert.equal(signedIn.actor.email, "locked@example.com");
58
+ });
59
+
60
+ test("sign-in throttle and password length settings are checked at startup", () => {
61
+ const resolve = (env) => resolveLocalAuthConfig({
62
+ appRoot: os.tmpdir(),
63
+ env: { NODE_ENV: "test", AUTH_LOCAL_SESSION_SECRET: "test-session-secret", ...env },
64
+ fileBackend: false,
65
+ emailRecovery: false
66
+ });
67
+ assert.deepEqual(resolve({}).signInThrottle, { failuresBeforeWait: 5, firstWaitMs: 30_000, maxWaitMs: 3_600_000 });
68
+ assert.equal(resolve({}).passwordMinLength, 8);
69
+ assert.equal(resolve({ AUTH_LOCAL_PASSWORD_MIN_LENGTH: "15" }).passwordMinLength, 15);
70
+ assert.throws(() => resolve({ AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT: "0" }), /must be a positive whole number/u);
71
+ assert.throws(() => resolve({ AUTH_LOCAL_SIGN_IN_FAILURES_BEFORE_WAIT: "101" }), /must be at most 100/u);
72
+ assert.throws(() => resolve({ AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS: "soon" }), /must be a positive whole number/u);
73
+ assert.throws(() => resolve({ AUTH_LOCAL_SIGN_IN_FIRST_WAIT_SECONDS: "60", AUTH_LOCAL_SIGN_IN_MAX_WAIT_SECONDS: "30" }),
74
+ /MAX_WAIT_SECONDS must be at least/u);
75
+ assert.throws(() => resolve({ AUTH_LOCAL_PASSWORD_MIN_LENGTH: "7" }), /from 8 to 64/u);
76
+ assert.throws(() => resolve({ AUTH_LOCAL_PASSWORD_MIN_LENGTH: "65" }), /from 8 to 64/u);
77
+ });
78
+
79
+ test("a raised minimum password length is enforced on registration", async (t) => {
80
+ const service = await startService(t, { AUTH_LOCAL_PASSWORD_MIN_LENGTH: "15" });
81
+ await assert.rejects(service.register({ email: "short@example.com", password: "fourteen chars" }), {
82
+ code: "auth.local.password.tooShort",
83
+ params: { min: 15 },
84
+ message: "Password must be at least 15 characters."
85
+ });
86
+ const registered = await service.register({ email: "long@example.com", password: "fifteen chars!!" });
87
+ assert.equal(registered.actor.email, "long@example.com");
88
+ });
@@ -0,0 +1,86 @@
1
+ import assert from "node:assert/strict";
2
+ import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
3
+ import { sha256Base64url } from "../src/server/lib/tokens.js";
4
+
5
+ const PASSWORD = "correct horse battery staple";
6
+ const EMAIL = "ada@example.com";
7
+ const invalidLink = { status: 400, code: "auth.local.register.confirmationInvalid" };
8
+
9
+ /** The code of a development confirmation link. */
10
+ function linkToken(result) {
11
+ assert.match(result.confirmationUrl, /^http:\/\/localhost:5173\/auth\/login\?confirmation_token=/u);
12
+ return new URL(result.confirmationUrl).searchParams.get("confirmation_token");
13
+ }
14
+
15
+ /**
16
+ * Registration with email confirmation in development, against any backend:
17
+ * run with Date mocked through `t.mock.timers`. `storedRegistrations` answers
18
+ * what the backend keeps of waiting registrations, as text, so the scenario
19
+ * can check that a link's code is kept only as its hash.
20
+ * @param {import("node:test").TestContext} t
21
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} service
22
+ * @param {() => Promise<string>} storedRegistrations
23
+ */
24
+ async function exerciseEmailConfirmation(t, service, storedRegistrations) {
25
+ // Registering keeps the account waiting: nobody is signed in, and development shows the link.
26
+ const registered = await service.register({ email: EMAIL, password: PASSWORD, displayName: "Ada" });
27
+ assert.equal(registered.requiresEmailConfirmation, true);
28
+ assert.equal(registered.session, null);
29
+ assert.equal(registered.actor, null);
30
+ const firstToken = linkToken(registered);
31
+ assert.ok(firstToken.length >= 40);
32
+ const stored = await storedRegistrations();
33
+ assert.equal(stored.includes(firstToken), false);
34
+ assert.equal(stored.includes(sha256Base64url(firstToken)), true);
35
+
36
+ // Until it is confirmed, the right password is refused as unconfirmed; a wrong one is an ordinary failure.
37
+ await assert.rejects(service.login({ email: EMAIL, password: PASSWORD }), {
38
+ status: 403,
39
+ code: AUTH_TEXTS.emailUnconfirmed.code
40
+ });
41
+ await assert.rejects(service.login({ email: EMAIL, password: "a wrong password" }), {
42
+ status: 401,
43
+ code: AUTH_TEXTS.invalidCredentials.code
44
+ });
45
+
46
+ // Registering again, or asking for a new link, replaces the link.
47
+ const secondToken = linkToken(await service.register({ email: EMAIL, password: PASSWORD, displayName: "Ada" }));
48
+ await assert.rejects(service.confirmRegistration({ token: firstToken }), invalidLink);
49
+ const resent = await service.resendRegisterConfirmation({ email: EMAIL });
50
+ assert.equal(resent.messageCode, "auth.local.register.confirmationResent");
51
+ const thirdToken = linkToken(resent);
52
+ await assert.rejects(service.confirmRegistration({ token: secondToken }), invalidLink);
53
+ // The answer for an email nobody registered is the same, without a link.
54
+ assert.deepEqual(await service.resendRegisterConfirmation({ email: "nobody@example.com" }), {
55
+ ok: true,
56
+ message: resent.message,
57
+ messageCode: resent.messageCode,
58
+ messageParams: {}
59
+ });
60
+
61
+ // Confirming creates the account and signs the person in; its password signs in too.
62
+ const confirmed = await service.confirmRegistration({ token: thirdToken });
63
+ assert.ok(confirmed.session.access_token);
64
+ assert.equal(confirmed.actor.email, EMAIL);
65
+ assert.equal(confirmed.actor.displayName, "Ada");
66
+ assert.equal((await service.login({ email: EMAIL, password: PASSWORD })).actor.email, EMAIL);
67
+ assert.equal((await storedRegistrations()).includes(sha256Base64url(thirdToken)), false);
68
+
69
+ // The link works once, and the confirmed email cannot register again.
70
+ await assert.rejects(service.confirmRegistration({ token: thirdToken }), invalidLink);
71
+ await assert.rejects(service.register({ email: EMAIL, password: PASSWORD }), {
72
+ status: 409,
73
+ code: "auth.local.register.emailTaken"
74
+ });
75
+
76
+ // A link expires after a day; the waiting password is then an ordinary failed sign-in.
77
+ const lateToken = linkToken(await service.register({ email: "late@example.com", password: PASSWORD }));
78
+ t.mock.timers.tick(24 * 60 * 60 * 1000 + 1000);
79
+ await assert.rejects(service.confirmRegistration({ token: lateToken }), invalidLink);
80
+ await assert.rejects(service.login({ email: "late@example.com", password: PASSWORD }), {
81
+ status: 401,
82
+ code: AUTH_TEXTS.invalidCredentials.code
83
+ });
84
+ }
85
+
86
+ export { exerciseEmailConfirmation };
@@ -3,17 +3,22 @@ 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 { createLoggedConfirmationSender } from "../src/server/lib/emailConfirmation.js";
6
7
  import { createLoggedRecoverySender } from "../src/server/lib/passwordFlows.js";
7
8
  import { scryptPasswordStrategy } from "../src/server/lib/passwords.js";
8
9
 
9
10
  /**
10
11
  * What a test passes to createLocalAuthService besides its backend: a complete
11
12
  * configuration resolved from a test environment, and each collaborator's default.
13
+ * Registration signs in at once, as with AUTH_LOCAL_EMAIL_CONFIRMATION=false,
14
+ * so tests of other flows can register their accounts; the email confirmation
15
+ * tests pass AUTH_LOCAL_EMAIL_CONFIRMATION: "" for the default.
12
16
  * @param {object} [options]
13
17
  * @param {Record<string, string>} [options.env] Environment values over the test ones.
14
18
  * @param {boolean} [options.emailRecovery] True when the test passes its own recoverySender.
19
+ * @param {boolean} [options.emailConfirmationSender] True when the test passes its own confirmationSender.
15
20
  */
16
- function localServiceOptions({ env = {}, emailRecovery = false } = {}) {
21
+ function localServiceOptions({ env = {}, emailRecovery = false, emailConfirmationSender = false } = {}) {
17
22
  return {
18
23
  config: resolveLocalAuthConfig({
19
24
  appRoot: os.tmpdir(),
@@ -22,16 +27,19 @@ function localServiceOptions({ env = {}, emailRecovery = false } = {}) {
22
27
  AUTH_LOCAL_SESSION_SECRET: "test-session-secret",
23
28
  APP_PUBLIC_URL: "http://localhost:5173",
24
29
  AUTH_LOCAL_RECOVERY_DEV_OUTPUT: "response",
30
+ AUTH_LOCAL_EMAIL_CONFIRMATION: "false",
25
31
  ...env
26
32
  },
27
33
  fileBackend: false,
28
- emailRecovery
34
+ emailRecovery,
35
+ emailConfirmationSender
29
36
  }),
30
37
  invitationContextResolver: invitationAsGiven,
31
38
  logger: silentLogger,
32
39
  passwordStrategy: scryptPasswordStrategy,
33
40
  profileProjector: noAppProfiles,
34
- recoverySender: createLoggedRecoverySender(silentLogger)
41
+ recoverySender: createLoggedRecoverySender(silentLogger),
42
+ confirmationSender: createLoggedConfirmationSender(silentLogger)
35
43
  };
36
44
  }
37
45
 
@@ -124,14 +124,16 @@ function oidcProviderEntry(issuer, { id = "google", label = "Google" } = {}) {
124
124
  * @param {import("../src/server/types.js").AuthLocalBackend} dependencies.backend
125
125
  * @param {import("../src/server/types.js").AuthLocalOAuthProvider[]} dependencies.oauthProviders
126
126
  * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
127
+ * @param {import("../src/server/types.js").AuthLocalFirstAccountSetup} [dependencies.firstAccountSetup]
127
128
  */
128
- function createService({ backend, oauthProviders, profileProjector }) {
129
+ function createService({ backend, oauthProviders, profileProjector, firstAccountSetup }) {
129
130
  const options = localServiceOptions({ env: { APP_PUBLIC_URL: APP_URL } });
130
131
  return createLocalAuthService({
131
132
  ...options,
132
133
  backend,
133
134
  config: { ...options.config, oauthProviders, oauthEnabled: oauthProviders.length > 0 },
134
- profileProjector
135
+ profileProjector,
136
+ firstAccountSetup
135
137
  });
136
138
  }
137
139
 
@@ -0,0 +1,71 @@
1
+ import assert from "node:assert/strict";
2
+ import { AUTH_TEXTS } from "@jskit-ai/auth-core/server/authTexts";
3
+
4
+ const PASSWORD = "correct horse battery staple";
5
+
6
+ /**
7
+ * Checks one refusal of a waiting account: status, code, the wait in minutes
8
+ * and seconds, and the Retry-After header.
9
+ * @param {number} seconds
10
+ */
11
+ function lockedFor(seconds) {
12
+ return (error) => {
13
+ assert.equal(error.status, 429);
14
+ assert.equal(error.code, "auth.local.login.locked");
15
+ assert.deepEqual(error.params, { count: Math.ceil(seconds / 60), retryAfterSeconds: seconds });
16
+ assert.equal(error.headers["retry-after"], String(seconds));
17
+ return true;
18
+ };
19
+ }
20
+
21
+ /**
22
+ * The per-account sign-in throttle with its default settings, against any
23
+ * backend: run with Date mocked through `t.mock.timers`.
24
+ * @param {import("node:test").TestContext} t
25
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} service
26
+ */
27
+ async function exerciseSignInThrottle(t, service) {
28
+ await service.register({ email: "ada@example.com", password: PASSWORD, displayName: "Ada" });
29
+ const signIn = (password, email = "ada@example.com") => service.login({ email, password });
30
+ const invalid = { status: 401, code: AUTH_TEXTS.invalidCredentials.code };
31
+
32
+ // 25 rapid guesses: five are checked, then the account waits, even for the right password.
33
+ for (let attempt = 0; attempt < 5; attempt += 1) {
34
+ await assert.rejects(signIn(`guess ${attempt}`), invalid);
35
+ }
36
+ for (let attempt = 5; attempt < 25; attempt += 1) {
37
+ await assert.rejects(signIn(`guess ${attempt}`), lockedFor(30));
38
+ }
39
+ await assert.rejects(signIn(PASSWORD), lockedFor(30));
40
+
41
+ // The next failure after the wait doubles it.
42
+ t.mock.timers.tick(30_000);
43
+ await assert.rejects(signIn("another guess"), invalid);
44
+ await assert.rejects(signIn(PASSWORD), lockedFor(60));
45
+
46
+ // A success after the wait forgets the failures.
47
+ t.mock.timers.tick(60_000);
48
+ assert.equal((await signIn(PASSWORD)).actor.email, "ada@example.com");
49
+ for (let attempt = 0; attempt < 4; attempt += 1) {
50
+ await assert.rejects(signIn(`fresh guess ${attempt}`), invalid);
51
+ }
52
+ assert.equal((await signIn(PASSWORD)).actor.email, "ada@example.com");
53
+
54
+ // An email without an account waits the same way, so waiting reveals nothing.
55
+ for (let attempt = 0; attempt < 5; attempt += 1) {
56
+ await assert.rejects(signIn(`guess ${attempt}`, "nobody@example.com"), invalid);
57
+ }
58
+ await assert.rejects(signIn("any", "nobody@example.com"), lockedFor(30));
59
+
60
+ // Failures are forgotten a day after the last one.
61
+ for (let attempt = 0; attempt < 4; attempt += 1) {
62
+ await assert.rejects(signIn(`old guess ${attempt}`), invalid);
63
+ }
64
+ t.mock.timers.tick(24 * 60 * 60 * 1000 + 1000);
65
+ for (let attempt = 0; attempt < 4; attempt += 1) {
66
+ await assert.rejects(signIn(`new guess ${attempt}`), invalid);
67
+ }
68
+ assert.equal((await signIn(PASSWORD)).actor.email, "ada@example.com");
69
+ }
70
+
71
+ export { exerciseSignInThrottle, lockedFor };