@jskit-ai/auth-provider-local-core 0.1.149 → 0.2.1

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 ADDED
@@ -0,0 +1,43 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 - 2026-10-29
4
+
5
+ - Translation ready: every user-visible text is a message key with its English in `locales/en.json`, so an app translates it by supplying translation files only. With no translations, texts and behaviour are unchanged. See the guide "Translating a JSKIT app".
6
+
7
+ ### Upgrading
8
+
9
+ - Local-account errors now have dotted codes instead of `APP_ERROR` (for example `auth.local.password.currentInvalid`); English and status are unchanged.
10
+
11
+ ### New message keys (9)
12
+
13
+ All keys in `locales/en.json` (exported as `./locales/en.json`) are new in this version.
14
+
15
+ <details><summary>Key list</summary>
16
+
17
+ - `jskit.auth.local.email.invalid`
18
+ - `jskit.auth.local.password.tooShort`
19
+ - `jskit.auth.local.password.currentInvalid`
20
+ - `jskit.auth.local.password.changed`
21
+ - `jskit.auth.local.register.emailTaken`
22
+ - `jskit.auth.local.recovery.notConfigured`
23
+ - `jskit.auth.local.recovery.requested`
24
+ - `jskit.auth.local.recovery.tokenInvalid`
25
+ - `jskit.auth.local.recovery.sessionRequired`
26
+
27
+ </details>
28
+
29
+ ### Codes (9)
30
+
31
+ Error, field-error and message codes this package sends, with their English. Undotted codes kept their existing values and render from `jskit.errors.<code>`.
32
+
33
+ | Code | English |
34
+ | --- | --- |
35
+ | `auth.local.email.invalid` | Enter a valid email address. |
36
+ | `auth.local.password.tooShort` | Password must be at least {min} characters. |
37
+ | `auth.local.password.currentInvalid` | Current password is invalid. |
38
+ | `auth.local.password.changed` | Password updated. |
39
+ | `auth.local.register.emailTaken` | An account already exists for this email. |
40
+ | `auth.local.recovery.notConfigured` | Password recovery is not configured. |
41
+ | `auth.local.recovery.requested` | If an account exists for that email, password reset instructions have been sent. |
42
+ | `auth.local.recovery.tokenInvalid` | Recovery token is invalid or expired. |
43
+ | `auth.local.recovery.sessionRequired` | Recovery session required. |
@@ -0,0 +1,25 @@
1
+ {
2
+ "jskit": {
3
+ "auth": {
4
+ "local": {
5
+ "email": {
6
+ "invalid": "Enter a valid email address."
7
+ },
8
+ "password": {
9
+ "tooShort": "Password must be at least {min} characters.",
10
+ "currentInvalid": "Current password is invalid.",
11
+ "changed": "Password updated."
12
+ },
13
+ "register": {
14
+ "emailTaken": "An account already exists for this email."
15
+ },
16
+ "recovery": {
17
+ "notConfigured": "Password recovery is not configured.",
18
+ "requested": "If an account exists for that email, password reset instructions have been sent.",
19
+ "tokenInvalid": "Recovery token is invalid or expired.",
20
+ "sessionRequired": "Recovery session required."
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-provider-local-core",
3
- "version": "0.1.149",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
7
7
  },
8
8
  "exports": {
9
9
  "./server/providers/AuthLocalProvider": "./src/server/providers/AuthLocalProvider.js",
10
- "./server/lib/index": "./src/server/lib/index.js"
10
+ "./server/lib/index": "./src/server/lib/index.js",
11
+ "./locales/en.json": "./locales/en.json"
11
12
  },
12
13
  "description": "Local auth provider with a file backend default and no database requirement.",
13
14
  "jskit": {
@@ -57,7 +58,7 @@
57
58
  }
58
59
  },
59
60
  "peerDependencies": {
60
- "@jskit-ai/auth-core": "0.1.246",
61
- "@jskit-ai/kernel": "0.1.248"
61
+ "@jskit-ai/auth-core": "0.2.1",
62
+ "@jskit-ai/kernel": "0.2.1"
62
63
  }
63
64
  }
@@ -14,6 +14,12 @@ import {
14
14
  } from "@jskit-ai/auth-core/server/devAuth";
15
15
  import { hostOnlyCookieName, normalizeEmail } from "@jskit-ai/auth-core/server/utils";
16
16
  import { throwUnsupportedAuthOperation } from "@jskit-ai/auth-core/server/unsupportedOperation";
17
+ import {
18
+ AUTH_TEXTS,
19
+ authFieldErrorDetails,
20
+ authMessageFields,
21
+ createAuthError
22
+ } from "@jskit-ai/auth-core/server/authTexts";
17
23
  import { normalizePasswordStrategy } from "./passwords.js";
18
24
  import { randomToken, sha256Base64url, signToken, verifySignedToken } from "./tokens.js";
19
25
 
@@ -203,10 +209,16 @@ function validatePasswordInput(password) {
203
209
  normalizedPassword.length < AUTH_PASSWORD_MIN_LENGTH ||
204
210
  normalizedPassword.length > AUTH_PASSWORD_MAX_LENGTH
205
211
  ) {
212
+ const params = { min: AUTH_PASSWORD_MIN_LENGTH };
206
213
  throw new AppError(400, "Password must be at least 8 characters.", {
214
+ code: "auth.local.password.tooShort",
215
+ params,
207
216
  details: {
208
217
  fieldErrors: {
209
218
  password: "Password must be at least 8 characters."
219
+ },
220
+ fieldErrorCodes: {
221
+ password: { code: "auth.local.password.tooShort", params }
210
222
  }
211
223
  }
212
224
  });
@@ -217,9 +229,13 @@ function validateEmailInput(email) {
217
229
  const normalized = normalizeEmail(email);
218
230
  if (!normalized || !normalized.includes("@")) {
219
231
  throw new AppError(400, "Enter a valid email address.", {
232
+ code: "auth.local.email.invalid",
220
233
  details: {
221
234
  fieldErrors: {
222
235
  email: "Enter a valid email address."
236
+ },
237
+ fieldErrorCodes: {
238
+ email: { code: "auth.local.email.invalid", params: {} }
223
239
  }
224
240
  }
225
241
  });
@@ -227,19 +243,18 @@ function validateEmailInput(email) {
227
243
  return normalized;
228
244
  }
229
245
 
230
- function devLoginAsValidationError(fieldErrors = {}) {
231
- const messages = Object.values(fieldErrors).filter(Boolean);
232
- return new AppError(400, messages[0] || "Provide a user id or email.", {
233
- details: {
234
- fieldErrors
235
- }
246
+ // fields: { field: AUTH_TEXTS entry }; the error says the first field's text.
247
+ function devLoginAsValidationError(fields = {}) {
248
+ const [first = AUTH_TEXTS.devUserRequired] = Object.values(fields);
249
+ return createAuthError(first, {
250
+ details: authFieldErrorDetails(fields)
236
251
  });
237
252
  }
238
253
 
239
254
  function devLoginAsUserNotFound({ email = "", userId = "" } = {}) {
240
255
  return devLoginAsValidationError({
241
- ...(userId ? { userId: "User not found." } : {}),
242
- ...(email ? { email: "User not found." } : {})
256
+ ...(userId ? { userId: AUTH_TEXTS.devUserNotFound } : {}),
257
+ ...(email ? { email: AUTH_TEXTS.devUserNotFound } : {})
243
258
  });
244
259
  }
245
260
 
@@ -396,7 +411,7 @@ function createLocalAuthService({
396
411
  const result = await backend.withTransaction(async (tx) => {
397
412
  const existing = await tx.users.findByEmail(email);
398
413
  if (existing) {
399
- throw new AppError(409, "An account already exists for this email.");
414
+ throw new AppError(409, "An account already exists for this email.", { code: "auth.local.register.emailTaken" });
400
415
  }
401
416
  const user = await tx.users.create({
402
417
  id: createId("usr"),
@@ -426,7 +441,7 @@ function createLocalAuthService({
426
441
  return backend.withTransaction(async (tx) => {
427
442
  const user = await tx.users.findByEmail(email);
428
443
  if (!user || user.disabled || !(await passwords.verifyPassword(password, user.password))) {
429
- throw new AppError(401, "Invalid email or password.");
444
+ throw createAuthError(AUTH_TEXTS.invalidCredentials);
430
445
  }
431
446
  const session = await createSessionForUser(tx, user);
432
447
  return buildAuthPayload({ user, session, profileProjector });
@@ -443,8 +458,8 @@ function createLocalAuthService({
443
458
  const email = normalizeEmail(input?.email || "");
444
459
  if (!userId && !email) {
445
460
  throw devLoginAsValidationError({
446
- userId: "Provide a user id or email.",
447
- email: "Provide a user id or email."
461
+ userId: AUTH_TEXTS.devUserRequired,
462
+ email: AUTH_TEXTS.devUserRequired
448
463
  });
449
464
  }
450
465
 
@@ -607,7 +622,7 @@ function createLocalAuthService({
607
622
 
608
623
  async function requestPasswordReset(input = {}) {
609
624
  if (!recoveryEnabled) {
610
- throw new AppError(503, "Password recovery is not configured.");
625
+ throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
611
626
  }
612
627
  const email = validateEmailInput(input.email);
613
628
  let recoveryUrl = "";
@@ -634,28 +649,30 @@ function createLocalAuthService({
634
649
  return {
635
650
  ok: true,
636
651
  message: "If an account exists for that email, password reset instructions have been sent.",
652
+ messageCode: "auth.local.recovery.requested",
653
+ messageParams: {},
637
654
  ...(recoveryUrl && !recoverySender && config.recoveryDevOutput === "response" ? { recoveryUrl } : {})
638
655
  };
639
656
  }
640
657
 
641
658
  async function completePasswordRecovery(input = {}) {
642
659
  if (!recoveryEnabled) {
643
- throw new AppError(503, "Password recovery is not configured.");
660
+ throw new AppError(503, "Password recovery is not configured.", { code: "auth.local.recovery.notConfigured" });
644
661
  }
645
662
  const token = String(input.code || input.token || "").trim();
646
663
  const tokenHash = String(input.tokenHash || "").trim() || (token ? sha256Base64url(token) : "");
647
664
  if (!tokenHash) {
648
- throw new AppError(400, "Recovery token is required.");
665
+ throw createAuthError(AUTH_TEXTS.recoveryTokenRequired);
649
666
  }
650
667
  return backend.withTransaction(async (tx) => {
651
668
  const recovery = await tx.recovery.findByTokenHash(tokenHash);
652
669
  if (!recovery || recovery.usedAt || isExpiredIso(recovery.expiresAt)) {
653
- throw new AppError(401, "Recovery token is invalid or expired.");
670
+ throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
654
671
  }
655
672
  await tx.recovery.consume(recovery.id);
656
673
  const user = await tx.users.findById(recovery.userId);
657
674
  if (!user || user.disabled) {
658
- throw new AppError(401, "Recovery token is invalid or expired.");
675
+ throw new AppError(401, "Recovery token is invalid or expired.", { code: "auth.local.recovery.tokenInvalid" });
659
676
  }
660
677
  const session = await createSessionForUser(tx, user, {
661
678
  purpose: "recovery",
@@ -671,16 +688,16 @@ function createLocalAuthService({
671
688
  const recoveryAccessToken = String(cookies[RECOVERY_TOKEN_COOKIE] || "").trim();
672
689
  const payload = verifySignedToken(recoveryAccessToken, config.sessionSecret);
673
690
  if (!payload?.sub || !payload?.sid) {
674
- throw new AppError(401, "Authentication required.");
691
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
675
692
  }
676
693
  const password = await passwords.hashPassword(input.password);
677
694
  await backend.withTransaction(async (tx) => {
678
695
  const session = await tx.sessions.findById(String(payload.sid));
679
696
  if (!session || session.revokedAt || isExpiredIso(session.expiresAt)) {
680
- throw new AppError(401, "Authentication required.");
697
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
681
698
  }
682
699
  if (session.purpose !== "recovery") {
683
- throw new AppError(401, "Recovery session required.");
700
+ throw new AppError(401, "Recovery session required.", { code: "auth.local.recovery.sessionRequired" });
684
701
  }
685
702
  await tx.users.updatePassword(String(payload.sub), password);
686
703
  await tx.sessions.revokeForUser(String(payload.sub));
@@ -690,7 +707,7 @@ function createLocalAuthService({
690
707
  });
691
708
  return {
692
709
  ok: true,
693
- message: "Password updated. Sign in with your new password."
710
+ ...authMessageFields(AUTH_TEXTS.passwordUpdatedSignIn)
694
711
  };
695
712
  }
696
713
 
@@ -698,7 +715,7 @@ function createLocalAuthService({
698
715
  validatePasswordInput(input.newPassword);
699
716
  const authResult = await authenticateRequest(request);
700
717
  if (authResult.authenticated !== true || authResult.sessionPurpose !== "normal") {
701
- throw new AppError(401, "Authentication required.");
718
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
702
719
  }
703
720
 
704
721
  const currentPassword = String(input.currentPassword || "");
@@ -706,33 +723,35 @@ function createLocalAuthService({
706
723
  await backend.withTransaction(async (tx) => {
707
724
  const user = await tx.users.findById(authResult.actor.providerUserId);
708
725
  if (!user || user.disabled) {
709
- throw new AppError(401, "Authentication required.");
726
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
710
727
  }
711
728
  if (!(await passwords.verifyPassword(currentPassword, user.password))) {
712
- throw new AppError(401, "Current password is invalid.");
729
+ throw new AppError(401, "Current password is invalid.", { code: "auth.local.password.currentInvalid" });
713
730
  }
714
731
  await tx.users.updatePassword(user.id, password);
715
732
  });
716
733
 
717
734
  return {
718
735
  ok: true,
719
- message: "Password updated."
736
+ message: "Password updated.",
737
+ messageCode: "auth.local.password.changed",
738
+ messageParams: {}
720
739
  };
721
740
  }
722
741
 
723
742
  async function updateDisplayName(request, input = {}) {
724
743
  const authResult = await authenticateRequest(request);
725
744
  if (authResult.authenticated !== true) {
726
- throw new AppError(401, "Authentication required.");
745
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
727
746
  }
728
747
  const displayName = String(input.displayName || "").trim();
729
748
  if (!displayName) {
730
- throw new AppError(400, "Display name is required.");
749
+ throw createAuthError(AUTH_TEXTS.displayNameRequired);
731
750
  }
732
751
  return backend.withTransaction(async (tx) => {
733
752
  const user = await tx.users.updateProfile(authResult.actor.providerUserId, { displayName });
734
753
  if (!user) {
735
- throw new AppError(401, "Authentication required.");
754
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
736
755
  }
737
756
  return buildAuthPayload({ user, session: null, profileProjector });
738
757
  });
@@ -741,7 +760,7 @@ function createLocalAuthService({
741
760
  async function getSecurityStatus(request) {
742
761
  const authResult = await authenticateRequest(request);
743
762
  if (authResult.authenticated !== true) {
744
- throw new AppError(401, "Authentication required.");
763
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
745
764
  }
746
765
  return buildSecurityStatusFromAuthMethodsStatus(
747
766
  {
@@ -773,7 +792,7 @@ function createLocalAuthService({
773
792
  async function signOutOtherSessions(request) {
774
793
  const authResult = await authenticateRequest(request);
775
794
  if (authResult.authenticated !== true) {
776
- throw new AppError(401, "Authentication required.");
795
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
777
796
  }
778
797
  const cookies = safeRequestCookies(request);
779
798
  const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
@@ -0,0 +1,72 @@
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 { catalogMessage, formatMessage, mergeCatalogs, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
7
+ import authCoreEnglish from "@jskit-ai/auth-core/locales/en.json" with { type: "json" };
8
+ import localEnglish from "../locales/en.json" with { type: "json" };
9
+ import { createLocalAuthService, createLocalFileBackend } from "../src/server/lib/index.js";
10
+
11
+ const english = mergeCatalogs(authCoreEnglish, localEnglish);
12
+
13
+ function rendered(code, params = {}) {
14
+ const template = catalogMessage(english, messageKeyForCode(code));
15
+ assert.notEqual(template, undefined, `${code} has no English`);
16
+ return formatMessage(template, params);
17
+ }
18
+
19
+ // Every coded text says exactly its catalog English, rendered with its params.
20
+ function assertCoded(error, code) {
21
+ assert.equal(error.code, code);
22
+ assert.equal(rendered(error.code, error.params), error.message);
23
+ for (const [field, coded] of Object.entries(error.details?.fieldErrorCodes || {})) {
24
+ assert.equal(rendered(coded.code, coded.params), error.details.fieldErrors[field], field);
25
+ }
26
+ return true;
27
+ }
28
+
29
+ async function createService(config = {}) {
30
+ const storeDir = await fs.mkdtemp(path.join(os.tmpdir(), "jskit-auth-local-coded-"));
31
+ return createLocalAuthService({
32
+ backend: createLocalFileBackend({ storeDir }),
33
+ config: {
34
+ sessionSecret: "coded-texts-secret",
35
+ nodeEnv: "test",
36
+ appPublicUrl: "http://localhost:5173",
37
+ recoveryDevOutput: "response",
38
+ ...config
39
+ }
40
+ });
41
+ }
42
+
43
+ test("local auth errors carry codes whose English is the thrown message", async () => {
44
+ const service = await createService();
45
+ await assert.rejects(() => service.register({ email: "nope", password: "long enough" }),
46
+ (error) => assertCoded(error, "auth.local.email.invalid"));
47
+ await assert.rejects(() => service.register({ email: "ada@example.com", password: "short" }),
48
+ (error) => assertCoded(error, "auth.local.password.tooShort"));
49
+ await service.register({ email: "ada@example.com", password: "correct horse" });
50
+ await assert.rejects(() => service.register({ email: "ada@example.com", password: "correct horse" }),
51
+ (error) => assertCoded(error, "auth.local.register.emailTaken"));
52
+ await assert.rejects(() => service.login({ email: "ada@example.com", password: "wrong password" }),
53
+ (error) => assertCoded(error, "auth.login.invalidCredentials"));
54
+ await assert.rejects(() => service.completePasswordRecovery({}),
55
+ (error) => assertCoded(error, "auth.recovery.tokenRequired"));
56
+ await assert.rejects(() => service.completePasswordRecovery({ token: "unknown" }),
57
+ (error) => assertCoded(error, "auth.local.recovery.tokenInvalid"));
58
+ await assert.rejects(() => service.updateDisplayName({ cookies: {} }, { displayName: "Ada" }),
59
+ (error) => assertCoded(error, "auth.session.required"));
60
+
61
+ const disabled = await createService({ nodeEnv: "production", recoveryDevOutput: "log" });
62
+ await assert.rejects(() => disabled.requestPasswordReset({ email: "ada@example.com" }),
63
+ (error) => assertCoded(error, "auth.local.recovery.notConfigured"));
64
+ });
65
+
66
+ test("local auth success texts carry a message code next to the English", async () => {
67
+ const service = await createService();
68
+ await service.register({ email: "ada@example.com", password: "correct horse" });
69
+ const requested = await service.requestPasswordReset({ email: "ada@example.com" });
70
+ assert.equal(requested.messageCode, "auth.local.recovery.requested");
71
+ assert.equal(rendered(requested.messageCode, requested.messageParams), requested.message);
72
+ });
@@ -0,0 +1,16 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import test from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { evaluateI18nCatalogContract } from "../../../tooling/test-support/i18nCatalogContract.mjs";
6
+
7
+ const TEST_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
8
+ const REPO_ROOT = path.resolve(TEST_DIRECTORY, "..", "..", "..");
9
+
10
+ test("auth-provider-local-core English catalog matches its source", () => {
11
+ const { problems } = evaluateI18nCatalogContract({
12
+ repoRoot: REPO_ROOT,
13
+ packageDir: path.join(REPO_ROOT, "packages", "auth-provider-local-core")
14
+ });
15
+ assert.deepEqual(problems, []);
16
+ });