@jskit-ai/auth-core 0.1.246 → 0.2.0

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,75 @@
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
+ - Every auth error has a dotted code (for example `auth.login.invalidCredentials`); the former `AUTH_POLICY_ERROR` sites have their own codes.
7
+ - `createAuthPolicyError(status, message, { code, params })`; OAuth redirects add `error_code` and `error_params`.
8
+
9
+ ### New message keys (26)
10
+
11
+ All keys in `locales/en.json` (exported as `./locales/en.json`) are new in this version.
12
+
13
+ <details><summary>Key list</summary>
14
+
15
+ - `jskit.auth.session.required`
16
+ - `jskit.auth.session.unavailable`
17
+ - `jskit.auth.login.invalidCredentials`
18
+ - `jskit.auth.policy.ownerUnresolved`
19
+ - `jskit.auth.policy.ownerMismatch`
20
+ - `jskit.auth.policy.invalidConfiguration`
21
+ - `jskit.auth.policy.permissionDenied`
22
+ - `jskit.auth.dev.unavailable`
23
+ - `jskit.auth.dev.secretMissing`
24
+ - `jskit.auth.dev.localhostOnly`
25
+ - `jskit.auth.dev.exchangeUnauthorized`
26
+ - `jskit.auth.dev.userRequired`
27
+ - `jskit.auth.dev.userNotFound`
28
+ - `jskit.auth.operation.unsupported`
29
+ - `jskit.auth.validation.emailRequired`
30
+ - `jskit.auth.validation.emailInvalid`
31
+ - `jskit.auth.validation.passwordRequired`
32
+ - `jskit.auth.validation.passwordLength`
33
+ - `jskit.auth.validation.passwordTooLong`
34
+ - `jskit.auth.validation.confirmPasswordRequired`
35
+ - `jskit.auth.validation.passwordsMismatch`
36
+ - `jskit.auth.profile.displayNameRequired`
37
+ - `jskit.auth.recovery.tokenRequired`
38
+ - `jskit.auth.password.updatedSignIn`
39
+ - `jskit.auth.denied.notAllowlisted`
40
+ - `jskit.auth.denied.blocked`
41
+
42
+ </details>
43
+
44
+ ### Codes (26)
45
+
46
+ Error, field-error and message codes this package sends, with their English. Undotted codes kept their existing values and render from `jskit.errors.<code>`.
47
+
48
+ | Code | English |
49
+ | --- | --- |
50
+ | `auth.session.required` | Authentication required. |
51
+ | `auth.session.unavailable` | Authentication service temporarily unavailable. Please retry. |
52
+ | `auth.login.invalidCredentials` | Invalid email or password. |
53
+ | `auth.policy.ownerUnresolved` | Route owner could not be resolved. |
54
+ | `auth.policy.ownerMismatch` | Forbidden. |
55
+ | `auth.policy.invalidConfiguration` | Invalid route auth policy configuration. |
56
+ | `auth.policy.permissionDenied` | Forbidden. |
57
+ | `auth.dev.unavailable` | Not found. |
58
+ | `auth.dev.secretMissing` | AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true. |
59
+ | `auth.dev.localhostOnly` | Dev auth bootstrap is only available from localhost. |
60
+ | `auth.dev.exchangeUnauthorized` | Dev auth exchange is not authorized. |
61
+ | `auth.dev.userRequired` | Provide a user id or email. |
62
+ | `auth.dev.userNotFound` | User not found. |
63
+ | `auth.operation.unsupported` | Auth operation "{operation}" is not supported by the active provider. |
64
+ | `auth.validation.emailRequired` | Email is required. |
65
+ | `auth.validation.emailInvalid` | Provide a valid email address. |
66
+ | `auth.validation.passwordRequired` | Password is required. |
67
+ | `auth.validation.passwordLength` | Password must be between {min} and {max} characters. |
68
+ | `auth.validation.passwordTooLong` | Password must be at most {max} characters. |
69
+ | `auth.validation.confirmPasswordRequired` | Confirm your password. |
70
+ | `auth.validation.passwordsMismatch` | Passwords do not match. |
71
+ | `auth.profile.displayNameRequired` | Display name is required. |
72
+ | `auth.recovery.tokenRequired` | Recovery token is required. |
73
+ | `auth.password.updatedSignIn` | Password updated. Sign in with your new password. |
74
+ | `auth.denied.notAllowlisted` | Sign-in succeeded, but this account is not allowed to access this application. |
75
+ | `auth.denied.blocked` | Sign-in succeeded, but this account has been blocked from accessing this application. |
@@ -0,0 +1,52 @@
1
+ {
2
+ "jskit": {
3
+ "auth": {
4
+ "session": {
5
+ "required": "Authentication required.",
6
+ "unavailable": "Authentication service temporarily unavailable. Please retry."
7
+ },
8
+ "login": {
9
+ "invalidCredentials": "Invalid email or password."
10
+ },
11
+ "policy": {
12
+ "ownerUnresolved": "Route owner could not be resolved.",
13
+ "ownerMismatch": "Forbidden.",
14
+ "invalidConfiguration": "Invalid route auth policy configuration.",
15
+ "permissionDenied": "Forbidden."
16
+ },
17
+ "dev": {
18
+ "unavailable": "Not found.",
19
+ "secretMissing": "AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true.",
20
+ "localhostOnly": "Dev auth bootstrap is only available from localhost.",
21
+ "exchangeUnauthorized": "Dev auth exchange is not authorized.",
22
+ "userRequired": "Provide a user id or email.",
23
+ "userNotFound": "User not found."
24
+ },
25
+ "operation": {
26
+ "unsupported": "Auth operation \"{operation}\" is not supported by the active provider."
27
+ },
28
+ "validation": {
29
+ "emailRequired": "Email is required.",
30
+ "emailInvalid": "Provide a valid email address.",
31
+ "passwordRequired": "Password is required.",
32
+ "passwordLength": "Password must be between {min} and {max} characters.",
33
+ "passwordTooLong": "Password must be at most {max} characters.",
34
+ "confirmPasswordRequired": "Confirm your password.",
35
+ "passwordsMismatch": "Passwords do not match."
36
+ },
37
+ "profile": {
38
+ "displayNameRequired": "Display name is required."
39
+ },
40
+ "recovery": {
41
+ "tokenRequired": "Recovery token is required."
42
+ },
43
+ "password": {
44
+ "updatedSignIn": "Password updated. Sign in with your new password."
45
+ },
46
+ "denied": {
47
+ "notAllowlisted": "Sign-in succeeded, but this account is not allowed to access this application.",
48
+ "blocked": "Sign-in succeeded, but this account has been blocked from accessing this application."
49
+ }
50
+ }
51
+ }
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/auth-core",
3
- "version": "0.1.246",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -15,6 +15,7 @@
15
15
  "./server/authPolicyContextResolverRegistry": "./src/server/authPolicyContextResolverRegistry.js",
16
16
  "./server/authServiceDecoratorRegistry": "./src/server/authServiceDecoratorRegistry.js",
17
17
  "./server/authActor": "./src/server/authActor.js",
18
+ "./server/authTexts": "./src/server/authTexts.js",
18
19
  "./server/booleanFlag": "./src/server/booleanFlag.js",
19
20
  "./server/devAuth": "./src/server/devAuth.js",
20
21
  "./server/deferredAuthService": "./src/server/deferredAuthService.js",
@@ -55,7 +56,8 @@
55
56
  "./shared/commands/authPasswordRecoveryCompleteCommand": "./src/shared/commands/authPasswordRecoveryCompleteCommand.js",
56
57
  "./shared/commands/authPasswordResetCommand": "./src/shared/commands/authPasswordResetCommand.js",
57
58
  "./shared/commands/authLogoutCommand": "./src/shared/commands/authLogoutCommand.js",
58
- "./shared/commands/authSessionReadCommand": "./src/shared/commands/authSessionReadCommand.js"
59
+ "./shared/commands/authSessionReadCommand": "./src/shared/commands/authSessionReadCommand.js",
60
+ "./locales/en.json": "./locales/en.json"
59
61
  },
60
62
  "dependencies": {
61
63
  "@fastify/cookie": "^11.1.2",
@@ -135,6 +137,6 @@
135
137
  }
136
138
  },
137
139
  "peerDependencies": {
138
- "@jskit-ai/kernel": "0.1.248"
140
+ "@jskit-ai/kernel": "0.2.0"
139
141
  }
140
142
  }
@@ -0,0 +1,60 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { catalogMessage, formatMessage, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
3
+ import english from "../../locales/en.json" with { type: "json" };
4
+
5
+ // Texts every auth provider means the same way. Each code's English lives once,
6
+ // in auth-core's catalog, so providers use these entries instead of their own
7
+ // copy of the sentence.
8
+ const AUTH_TEXTS = Object.freeze({
9
+ sessionRequired: Object.freeze({ status: 401, code: "auth.session.required" }),
10
+ sessionUnavailable: Object.freeze({ status: 503, code: "auth.session.unavailable" }),
11
+ invalidCredentials: Object.freeze({ status: 401, code: "auth.login.invalidCredentials" }),
12
+ emailRequired: Object.freeze({ status: 400, code: "auth.validation.emailRequired" }),
13
+ devUserRequired: Object.freeze({ status: 400, code: "auth.dev.userRequired" }),
14
+ devUserNotFound: Object.freeze({ status: 400, code: "auth.dev.userNotFound" }),
15
+ displayNameRequired: Object.freeze({ status: 400, code: "auth.profile.displayNameRequired" }),
16
+ recoveryTokenRequired: Object.freeze({ status: 400, code: "auth.recovery.tokenRequired" }),
17
+ passwordUpdatedSignIn: Object.freeze({ code: "auth.password.updatedSignIn" })
18
+ });
19
+
20
+ function authText({ code } = {}, params = {}) {
21
+ const template = catalogMessage(english, messageKeyForCode(code));
22
+ if (template === undefined) {
23
+ throw new TypeError(`Auth text "${code}" is not in auth-core's catalog.`);
24
+ }
25
+ return formatMessage(template, params);
26
+ }
27
+
28
+ function createAuthError(entry, { params = {}, ...options } = {}) {
29
+ return new AppError(entry.status, authText(entry, params), { ...options, code: entry.code, params });
30
+ }
31
+
32
+ // One field's error for createValidationError.
33
+ function authFieldError(entry, params = {}) {
34
+ return { code: entry.code, params, message: authText(entry, params) };
35
+ }
36
+
37
+ // details for an error that names its fields itself: { field: entry }.
38
+ function authFieldErrorDetails(fields = {}) {
39
+ const fieldErrors = {};
40
+ const fieldErrorCodes = {};
41
+ for (const [field, entry] of Object.entries(fields)) {
42
+ fieldErrors[field] = authText(entry);
43
+ fieldErrorCodes[field] = { code: entry.code, params: {} };
44
+ }
45
+ return { fieldErrors, fieldErrorCodes };
46
+ }
47
+
48
+ // A success payload's text: the English message plus the code a client renders.
49
+ function authMessageFields(entry, params = {}) {
50
+ return { message: authText(entry, params), messageCode: entry.code, messageParams: params };
51
+ }
52
+
53
+ export {
54
+ AUTH_TEXTS,
55
+ authFieldError,
56
+ authFieldErrorDetails,
57
+ authMessageFields,
58
+ authText,
59
+ createAuthError
60
+ };
@@ -87,13 +87,15 @@ function assertDevAuthPolicy(policy = {}) {
87
87
 
88
88
  function ensureDevAuthRuntimeAvailable(policy = {}, request = null) {
89
89
  if (!policy.enabled || policy.isProduction) {
90
- throw new AppError(404, "Not found.");
90
+ throw new AppError(404, "Not found.", { code: "auth.dev.unavailable" });
91
91
  }
92
92
  if (!policy.secret) {
93
- throw new AppError(500, "AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true.");
93
+ throw new AppError(500, "AUTH_DEV_BYPASS_SECRET is required when AUTH_DEV_BYPASS_ENABLED=true.", {
94
+ code: "auth.dev.secretMissing"
95
+ });
94
96
  }
95
97
  if (!isLocalDevAuthRequest(request)) {
96
- throw new AppError(403, "Dev auth bootstrap is only available from localhost.");
98
+ throw new AppError(403, "Dev auth bootstrap is only available from localhost.", { code: "auth.dev.localhostOnly" });
97
99
  }
98
100
  }
99
101
 
@@ -112,7 +114,7 @@ function secretMatches(value = "", expected = "") {
112
114
  function ensureDevAuthExchangeAvailable(policy = {}, request = null) {
113
115
  ensureDevAuthRuntimeAvailable(policy, request);
114
116
  if (!secretMatches(requestHeader(request, DEV_AUTH_SECRET_HEADER), policy.secret)) {
115
- throw new AppError(403, "Dev auth exchange is not authorized.");
117
+ throw new AppError(403, "Dev auth exchange is not authorized.", { code: "auth.dev.exchangeUnauthorized" });
116
118
  }
117
119
  }
118
120
 
@@ -7,13 +7,16 @@ const AUTH_POLICY_DENY_REASONS = Object.freeze({
7
7
  FORBIDDEN_PERMISSION: "forbidden_permission"
8
8
  });
9
9
 
10
- function createAuthPolicyError(status, message, { code = "AUTH_POLICY_ERROR" } = {}) {
10
+ // code names the refusal (auth.session.required, auth.policy.permissionDenied...)
11
+ // so a client can show it in the user's language; message stays the English.
12
+ function createAuthPolicyError(status, message, { code, params = {} } = {}) {
11
13
  const normalizedStatus = Number(status) || 500;
12
14
  const error = new Error(String(message || "Request failed."));
13
15
  error.name = "AuthPolicyError";
14
16
  error.status = normalizedStatus;
15
17
  error.statusCode = normalizedStatus;
16
- error.code = String(code || "AUTH_POLICY_ERROR");
18
+ error.code = code;
19
+ error.params = params && typeof params === "object" ? { ...params } : {};
17
20
  return error;
18
21
  }
19
22
 
@@ -97,10 +97,8 @@ function authPolicyPlugin(deps = {}, options = {}) {
97
97
  const csrfCookieOpts =
98
98
  options.csrfCookieOpts && typeof options.csrfCookieOpts === "object" ? options.csrfCookieOpts : {};
99
99
  const resolveCsrfTokenFn = typeof options.resolveCsrfToken === "function" ? options.resolveCsrfToken : resolveCsrfToken;
100
- const createError =
101
- typeof options.createError === "function"
102
- ? options.createError
103
- : (status, message) => createAuthPolicyError(status, message);
100
+ // createError(status, englishMessage, { code }) builds each refusal.
101
+ const createError = typeof options.createError === "function" ? options.createError : createAuthPolicyError;
104
102
 
105
103
  // CSRF uses tokens checked against a secret cookie, never SameSite alone. In
106
104
  // production that cookie is host-only (__Host-), so a sibling host cannot plant
@@ -154,7 +152,9 @@ function authPolicyPlugin(deps = {}, options = {}) {
154
152
  actor: actorResolution.actor,
155
153
  context: null
156
154
  });
157
- throw createError(503, "Authentication service temporarily unavailable. Please retry.");
155
+ throw createError(503, "Authentication service temporarily unavailable. Please retry.", {
156
+ code: "auth.session.unavailable"
157
+ });
158
158
  }
159
159
 
160
160
  if (!actorResolution.authenticated) {
@@ -166,7 +166,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
166
166
  actor: actorResolution.actor,
167
167
  context: null
168
168
  });
169
- throw createError(401, "Authentication required.");
169
+ throw createError(401, "Authentication required.", { code: "auth.session.required" });
170
170
  }
171
171
 
172
172
  request.user = actorResolution.actor;
@@ -187,7 +187,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
187
187
  actor: actorResolution.actor,
188
188
  context: null
189
189
  });
190
- throw createError(400, "Route owner could not be resolved.");
190
+ throw createError(400, "Route owner could not be resolved.", { code: "auth.policy.ownerUnresolved" });
191
191
  }
192
192
 
193
193
  if (String(ownerValue) !== String(userValue)) {
@@ -199,7 +199,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
199
199
  actor: actorResolution.actor,
200
200
  context: null
201
201
  });
202
- throw createError(403, "Forbidden.");
202
+ throw createError(403, "Forbidden.", { code: "auth.policy.ownerMismatch" });
203
203
  }
204
204
  } else if (meta.authPolicy !== AUTH_POLICIES.REQUIRED) {
205
205
  notifyPolicyDenied(onPolicyDenied, {
@@ -210,7 +210,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
210
210
  actor: actorResolution.actor,
211
211
  context: null
212
212
  });
213
- throw createError(500, "Invalid route auth policy configuration.");
213
+ throw createError(500, "Invalid route auth policy configuration.", { code: "auth.policy.invalidConfiguration" });
214
214
  }
215
215
 
216
216
  let context = null;
@@ -246,7 +246,7 @@ function authPolicyPlugin(deps = {}, options = {}) {
246
246
  actor: actorResolution.actor,
247
247
  context
248
248
  });
249
- throw createError(403, "Forbidden.");
249
+ throw createError(403, "Forbidden.", { code: "auth.policy.permissionDenied" });
250
250
  }
251
251
  }
252
252
  });
@@ -2,10 +2,14 @@ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
 
3
3
  const AUTH_OPERATION_UNSUPPORTED_CODE = "AUTH_OPERATION_UNSUPPORTED";
4
4
 
5
+ // The code stays AUTH_OPERATION_UNSUPPORTED for callers that branch on it; the
6
+ // messageCode lets a client show the default sentence in the user's language.
5
7
  function createUnsupportedAuthOperationError(operation, message = "") {
6
8
  const operationName = String(operation || "auth operation").trim() || "auth operation";
7
9
  return new AppError(501, message || `Auth operation "${operationName}" is not supported by the active provider.`, {
8
10
  code: AUTH_OPERATION_UNSUPPORTED_CODE,
11
+ messageCode: "auth.operation.unsupported",
12
+ messageParams: { operation: operationName },
9
13
  details: {
10
14
  operation: operationName
11
15
  }
@@ -7,103 +7,107 @@ import {
7
7
  } from "../shared/authConstraints.js";
8
8
  import { normalizeEmail } from "./utils.js";
9
9
 
10
+ // Each failed check carries its English error plus the code and params a client
11
+ // renders it from, so the English stays as it is and a translation can replace it.
12
+ function failure({ code, params = {}, message }) {
13
+ return { error: message, errorCode: code, errorParams: params };
14
+ }
15
+
16
+ const PASSED = Object.freeze({ error: "", errorCode: "", errorParams: Object.freeze({}) });
17
+
10
18
  function validateEmail(rawEmail) {
11
19
  const email = normalizeEmail(rawEmail);
12
20
 
13
21
  if (!email) {
14
- return {
15
- email,
16
- error: "Email is required."
17
- };
22
+ return { email, ...failure({ code: "auth.validation.emailRequired", message: "Email is required." }) };
18
23
  }
19
24
 
20
25
  if (email.length > AUTH_EMAIL_MAX_LENGTH || !AUTH_EMAIL_REGEX.test(email)) {
21
- return {
22
- email,
23
- error: "Provide a valid email address."
24
- };
26
+ return { email, ...failure({ code: "auth.validation.emailInvalid", message: "Provide a valid email address." }) };
25
27
  }
26
28
 
27
- return {
28
- email,
29
- error: ""
30
- };
29
+ return { email, ...PASSED };
31
30
  }
32
31
 
33
32
  function registerPassword(rawPassword) {
34
33
  const password = String(rawPassword || "");
35
34
  if (!password) {
36
- return {
37
- password,
38
- error: "Password is required."
39
- };
35
+ return { password, ...failure({ code: "auth.validation.passwordRequired", message: "Password is required." }) };
40
36
  }
41
37
 
42
38
  if (password.length < AUTH_PASSWORD_MIN_LENGTH || password.length > AUTH_PASSWORD_MAX_LENGTH) {
43
39
  return {
44
40
  password,
45
- error: "Password must be between 8 and 128 characters."
41
+ ...failure({
42
+ code: "auth.validation.passwordLength",
43
+ params: { min: AUTH_PASSWORD_MIN_LENGTH, max: AUTH_PASSWORD_MAX_LENGTH },
44
+ message: "Password must be between 8 and 128 characters."
45
+ })
46
46
  };
47
47
  }
48
48
 
49
- return {
50
- password,
51
- error: ""
52
- };
49
+ return { password, ...PASSED };
53
50
  }
54
51
 
55
52
  function loginPassword(rawPassword) {
56
53
  const password = String(rawPassword || "");
57
54
  if (!password) {
58
- return {
59
- password,
60
- error: "Password is required."
61
- };
55
+ return { password, ...failure({ code: "auth.validation.passwordRequired", message: "Password is required." }) };
62
56
  }
63
57
 
64
58
  if (password.length > AUTH_LOGIN_PASSWORD_MAX_LENGTH) {
65
59
  return {
66
60
  password,
67
- error: `Password must be at most ${AUTH_LOGIN_PASSWORD_MAX_LENGTH} characters.`
61
+ ...failure({
62
+ code: "auth.validation.passwordTooLong",
63
+ params: { max: AUTH_LOGIN_PASSWORD_MAX_LENGTH },
64
+ message: `Password must be at most ${AUTH_LOGIN_PASSWORD_MAX_LENGTH} characters.`
65
+ })
68
66
  };
69
67
  }
70
68
 
71
- return {
72
- password,
73
- error: ""
74
- };
69
+ return { password, ...PASSED };
75
70
  }
76
71
 
77
- function confirmPassword(rawPassword, rawConfirmPassword) {
72
+ function checkConfirmPassword(rawPassword, rawConfirmPassword) {
78
73
  const password = String(rawPassword || "");
79
74
  const confirmPassword = String(rawConfirmPassword || "");
80
75
 
81
76
  if (!confirmPassword) {
82
- return "Confirm your password.";
77
+ return failure({ code: "auth.validation.confirmPasswordRequired", message: "Confirm your password." });
83
78
  }
84
79
 
85
80
  if (password !== confirmPassword) {
86
- return "Passwords do not match.";
81
+ return failure({ code: "auth.validation.passwordsMismatch", message: "Passwords do not match." });
87
82
  }
88
83
 
89
- return "";
84
+ return PASSED;
85
+ }
86
+
87
+ function confirmPassword(rawPassword, rawConfirmPassword) {
88
+ return checkConfirmPassword(rawPassword, rawConfirmPassword).error;
90
89
  }
91
90
 
92
91
  function resetPassword(rawPassword) {
93
92
  return registerPassword(rawPassword);
94
93
  }
95
94
 
95
+ // fieldErrors keeps the English; fieldErrorCodes carries each one's code.
96
96
  function buildFieldErrors(entries = []) {
97
97
  const fieldErrors = {};
98
+ const fieldErrorCodes = {};
98
99
  for (const entry of Array.isArray(entries) ? entries : []) {
99
100
  const field = String(entry?.field || "").trim();
100
- const error = String(entry?.error || "").trim();
101
+ const error = String(entry?.check?.error || "").trim();
101
102
  if (!field || !error) {
102
103
  continue;
103
104
  }
104
105
  fieldErrors[field] = error;
106
+ if (entry.check.errorCode) {
107
+ fieldErrorCodes[field] = { code: entry.check.errorCode, params: { ...entry.check.errorParams } };
108
+ }
105
109
  }
106
- return fieldErrors;
110
+ return { fieldErrors, fieldErrorCodes };
107
111
  }
108
112
 
109
113
  function buildEmailPasswordInput(payload = {}, { passwordValidator } = {}) {
@@ -114,14 +118,14 @@ function buildEmailPasswordInput(payload = {}, { passwordValidator } = {}) {
114
118
  return {
115
119
  email: emailCheck.email,
116
120
  password: passwordCheck.password,
117
- fieldErrors: buildFieldErrors([
121
+ ...buildFieldErrors([
118
122
  {
119
123
  field: "email",
120
- error: emailCheck.error
124
+ check: emailCheck
121
125
  },
122
126
  {
123
127
  field: "password",
124
- error: passwordCheck.error
128
+ check: passwordCheck
125
129
  }
126
130
  ])
127
131
  };
@@ -144,10 +148,10 @@ function forgotPasswordInput(payload = {}) {
144
148
 
145
149
  return {
146
150
  email: emailCheck.email,
147
- fieldErrors: buildFieldErrors([
151
+ ...buildFieldErrors([
148
152
  {
149
153
  field: "email",
150
- error: emailCheck.error
154
+ check: emailCheck
151
155
  }
152
156
  ])
153
157
  };
@@ -158,10 +162,10 @@ function resetPasswordInput(payload = {}) {
158
162
 
159
163
  return {
160
164
  password: passwordCheck.password,
161
- fieldErrors: buildFieldErrors([
165
+ ...buildFieldErrors([
162
166
  {
163
167
  field: "password",
164
- error: passwordCheck.error
168
+ check: passwordCheck
165
169
  }
166
170
  ])
167
171
  };
@@ -12,13 +12,23 @@ const AUTH_DENIED_DEFAULT_MESSAGES = Object.freeze({
12
12
  [AUTH_DENIED_CODES.BLOCKED]: "This account has been blocked from accessing this application."
13
13
  });
14
14
 
15
- const AUTH_DENIED_LOGIN_MESSAGES = Object.freeze({
16
- [AUTH_DENIED_CODES.NOT_ALLOWLISTED]:
17
- "Sign-in succeeded, but this account is not allowed to access this application.",
18
- [AUTH_DENIED_CODES.BLOCKED]:
19
- "Sign-in succeeded, but this account has been blocked from accessing this application."
15
+ // The sign-in error for each built-in reason: its English and the code a client
16
+ // renders it from in the user's language.
17
+ const AUTH_DENIED_LOGIN_TEXTS = Object.freeze({
18
+ [AUTH_DENIED_CODES.NOT_ALLOWLISTED]: Object.freeze({
19
+ message: "Sign-in succeeded, but this account is not allowed to access this application.",
20
+ messageCode: "auth.denied.notAllowlisted"
21
+ }),
22
+ [AUTH_DENIED_CODES.BLOCKED]: Object.freeze({
23
+ message: "Sign-in succeeded, but this account has been blocked from accessing this application.",
24
+ messageCode: "auth.denied.blocked"
25
+ })
20
26
  });
21
27
 
28
+ const AUTH_DENIED_LOGIN_MESSAGES = Object.freeze(Object.fromEntries(
29
+ Object.entries(AUTH_DENIED_LOGIN_TEXTS).map(([code, text]) => [code, text.message])
30
+ ));
31
+
22
32
  function normalizeAuthDeniedCode(value = "") {
23
33
  const code = String(value || "")
24
34
  .trim()
@@ -48,13 +58,19 @@ function normalizeAuthDenied(input = null) {
48
58
  });
49
59
  }
50
60
 
51
- function resolveAuthDeniedLoginMessage(input = null) {
61
+ // { message, messageCode? } for a denied session, or null. A reason the app
62
+ // defined itself keeps the message it sent, without a code.
63
+ function resolveAuthDeniedLoginText(input = null) {
52
64
  const authDenied = normalizeAuthDenied(input);
53
65
  if (!authDenied) {
54
- return "";
66
+ return null;
55
67
  }
56
68
 
57
- return AUTH_DENIED_LOGIN_MESSAGES[authDenied.code] || authDenied.message;
69
+ return AUTH_DENIED_LOGIN_TEXTS[authDenied.code] || Object.freeze({ message: authDenied.message });
70
+ }
71
+
72
+ function resolveAuthDeniedLoginMessage(input = null) {
73
+ return resolveAuthDeniedLoginText(input)?.message || "";
58
74
  }
59
75
 
60
76
  export {
@@ -63,8 +79,10 @@ export {
63
79
  AUTH_DENIED_CODES,
64
80
  AUTH_DENIED_DEFAULT_MESSAGES,
65
81
  AUTH_DENIED_LOGIN_MESSAGES,
82
+ AUTH_DENIED_LOGIN_TEXTS,
66
83
  AUTH_DENIED_MESSAGE_MAX_LENGTH,
67
84
  normalizeAuthDenied,
68
85
  normalizeAuthDeniedCode,
69
- resolveAuthDeniedLoginMessage
86
+ resolveAuthDeniedLoginMessage,
87
+ resolveAuthDeniedLoginText
70
88
  };
@@ -143,10 +143,18 @@ const okOutputValidator = deepFreeze({
143
143
  mode: "replace"
144
144
  });
145
145
 
146
+ // A success message's code and params, so a client can show it in the user's
147
+ // language; message stays the English.
148
+ const messageCodeFieldDefinitions = deepFreeze({
149
+ messageCode: { type: "string", required: false, minLength: 1 },
150
+ messageParams: { type: "object", required: false, additionalProperties: true }
151
+ });
152
+
146
153
  const okMessageOutputValidator = deepFreeze({
147
154
  schema: createSchema({
148
155
  ok: { type: "boolean", required: true },
149
- message: { type: "string", required: true, minLength: 1 }
156
+ message: { type: "string", required: true, minLength: 1 },
157
+ ...messageCodeFieldDefinitions
150
158
  }),
151
159
  mode: "replace"
152
160
  });
@@ -156,7 +164,8 @@ const registerOutputValidator = deepFreeze({
156
164
  ok: { type: "boolean", required: true },
157
165
  requiresEmailConfirmation: { type: "boolean", required: true },
158
166
  username: { type: "string", required: false, minLength: 1, maxLength: 120 },
159
- message: { type: "string", required: false, minLength: 1 }
167
+ message: { type: "string", required: false, minLength: 1 },
168
+ ...messageCodeFieldDefinitions
160
169
  }),
161
170
  mode: "replace"
162
171
  });
@@ -378,6 +387,8 @@ const sessionOutputValidator = deepFreeze({
378
387
 
379
388
  const sessionUnavailableOutputSchema = createSchema({
380
389
  error: { type: "string", required: true, minLength: 1 },
390
+ code: { type: "string", required: false, minLength: 1 },
391
+ params: { type: "object", required: false, additionalProperties: true },
381
392
  csrfToken: { type: "string", required: true, minLength: 1 },
382
393
  authCapabilities: {
383
394
  type: "object",
@@ -0,0 +1,78 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { catalogMessage, formatMessage, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
4
+
5
+ import english from "../locales/en.json" with { type: "json" };
6
+ import {
7
+ AUTH_TEXTS,
8
+ authFieldError,
9
+ authFieldErrorDetails,
10
+ authMessageFields,
11
+ createAuthError
12
+ } from "../src/server/authTexts.js";
13
+ import { createUnsupportedAuthOperationError } from "../src/server/unsupportedOperation.js";
14
+ import { loginInput, registerInput, resetPasswordInput, confirmPassword } from "../src/server/validators.js";
15
+ import { AUTH_DENIED_CODES, resolveAuthDeniedLoginText } from "../src/shared/authDenied.js";
16
+
17
+ function rendered(code, params = {}) {
18
+ return formatMessage(catalogMessage(english, messageKeyForCode(code)), params);
19
+ }
20
+
21
+ test("shared auth texts throw their catalog English under their code", () => {
22
+ const error = createAuthError(AUTH_TEXTS.sessionRequired);
23
+ assert.equal(error.status, 401);
24
+ assert.equal(error.message, "Authentication required.");
25
+ assert.equal(error.code, "auth.session.required");
26
+ assert.deepEqual(error.params, {});
27
+
28
+ assert.equal(createAuthError(AUTH_TEXTS.sessionUnavailable).message,
29
+ "Authentication service temporarily unavailable. Please retry.");
30
+ assert.equal(createAuthError(AUTH_TEXTS.invalidCredentials).message, "Invalid email or password.");
31
+ assert.deepEqual(authFieldError(AUTH_TEXTS.displayNameRequired), {
32
+ code: "auth.profile.displayNameRequired",
33
+ params: {},
34
+ message: "Display name is required."
35
+ });
36
+ assert.deepEqual(authFieldErrorDetails({ userId: AUTH_TEXTS.devUserNotFound }), {
37
+ fieldErrors: { userId: "User not found." },
38
+ fieldErrorCodes: { userId: { code: "auth.dev.userNotFound", params: {} } }
39
+ });
40
+ assert.deepEqual(authMessageFields(AUTH_TEXTS.passwordUpdatedSignIn), {
41
+ message: "Password updated. Sign in with your new password.",
42
+ messageCode: "auth.password.updatedSignIn",
43
+ messageParams: {}
44
+ });
45
+ });
46
+
47
+ test("an unsupported operation keeps its code and adds a translatable message code", () => {
48
+ const error = createUnsupportedAuthOperationError("oauthStart");
49
+ assert.equal(error.code, "AUTH_OPERATION_UNSUPPORTED");
50
+ assert.equal(error.messageCode, "auth.operation.unsupported");
51
+ assert.equal(rendered(error.messageCode, error.messageParams), error.message);
52
+ });
53
+
54
+ test("server validator field errors render the same from their codes", () => {
55
+ const results = [
56
+ registerInput({ email: "", password: "" }),
57
+ registerInput({ email: "not-an-email", password: "short" }),
58
+ loginInput({ email: "a@example.com", password: "x".repeat(2000) }),
59
+ resetPasswordInput({ password: "" })
60
+ ];
61
+ for (const { fieldErrors, fieldErrorCodes } of results) {
62
+ assert.deepEqual(Object.keys(fieldErrorCodes), Object.keys(fieldErrors));
63
+ for (const [field, message] of Object.entries(fieldErrors)) {
64
+ assert.equal(rendered(fieldErrorCodes[field].code, fieldErrorCodes[field].params), message, field);
65
+ }
66
+ }
67
+ assert.equal(confirmPassword("one", "two"), "Passwords do not match.");
68
+ });
69
+
70
+ test("built-in sign-in denials carry the code of their English", () => {
71
+ for (const code of Object.values(AUTH_DENIED_CODES)) {
72
+ const text = resolveAuthDeniedLoginText({ code });
73
+ assert.equal(rendered(text.messageCode), text.message);
74
+ }
75
+ assert.deepEqual(resolveAuthDeniedLoginText({ code: "app_specific", message: "Ask your admin." }), {
76
+ message: "Ask your admin."
77
+ });
78
+ });
@@ -101,3 +101,21 @@ test("dev auth exchange requires the exact fixed-header secret", () => {
101
101
  /not authorized/
102
102
  );
103
103
  });
104
+
105
+ test("dev auth refusals carry their own codes", () => {
106
+ const codeOf = (run) => {
107
+ try {
108
+ run();
109
+ } catch (error) {
110
+ return error.code;
111
+ }
112
+ return null;
113
+ };
114
+ assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(resolveDevAuthPolicy(), createRequest())), "auth.dev.unavailable");
115
+ assert.equal(codeOf(() => ensureDevAuthRuntimeAvailable(enabledPolicy({ secret: "" }), createRequest())), "auth.dev.secretMissing");
116
+ assert.equal(
117
+ codeOf(() => ensureDevAuthRuntimeAvailable(enabledPolicy(), createRequest({ host: "example.com" }))),
118
+ "auth.dev.localhostOnly"
119
+ );
120
+ assert.equal(codeOf(() => ensureDevAuthExchangeAvailable(enabledPolicy(), createRequest())), "auth.dev.exchangeUnauthorized");
121
+ });
@@ -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-core English catalog matches its source", () => {
11
+ const { problems } = evaluateI18nCatalogContract({
12
+ repoRoot: REPO_ROOT,
13
+ packageDir: path.join(REPO_ROOT, "packages", "auth-core")
14
+ });
15
+ assert.deepEqual(problems, []);
16
+ });
@@ -324,3 +324,46 @@ test("enforces permission checks and resolves workspace context when requested",
324
324
 
325
325
  assert.deepEqual(denyEvents.map((event) => event.reason), ["forbidden_permission"]);
326
326
  });
327
+
328
+ test("each policy refusal carries its own code next to the English", async () => {
329
+ const { fastify, state } = createFakeFastifyPolicyRuntime();
330
+ let resolution = { authenticated: true, actor: { id: 7 }, transientFailure: false };
331
+ await authPolicyPlugin({
332
+ async resolveActor() {
333
+ return resolution;
334
+ },
335
+ hasPermission() {
336
+ return false;
337
+ }
338
+ })(fastify);
339
+
340
+ async function refusal(config, params = {}) {
341
+ try {
342
+ await state.preHandler({ method: "GET", raw: { url: "/api/x" }, headers: {}, params, routeOptions: { config } }, {});
343
+ } catch (error) {
344
+ return { status: error.statusCode, message: error.message, code: error.code };
345
+ }
346
+ return null;
347
+ }
348
+
349
+ assert.deepEqual(await refusal({ authPolicy: "own", ownerParam: "id" }), {
350
+ status: 400, message: "Route owner could not be resolved.", code: "auth.policy.ownerUnresolved"
351
+ });
352
+ assert.deepEqual(await refusal({ authPolicy: "own", ownerParam: "id", userField: "id" }, { id: 9 }), {
353
+ status: 403, message: "Forbidden.", code: "auth.policy.ownerMismatch"
354
+ });
355
+ assert.deepEqual(await refusal({ authPolicy: "bogus" }), {
356
+ status: 500, message: "Invalid route auth policy configuration.", code: "auth.policy.invalidConfiguration"
357
+ });
358
+ assert.deepEqual(await refusal({ authPolicy: "required", permission: "x.read" }), {
359
+ status: 403, message: "Forbidden.", code: "auth.policy.permissionDenied"
360
+ });
361
+ resolution = { authenticated: false, actor: null, transientFailure: false };
362
+ assert.deepEqual(await refusal({ authPolicy: "required" }), {
363
+ status: 401, message: "Authentication required.", code: "auth.session.required"
364
+ });
365
+ resolution = { authenticated: false, actor: null, transientFailure: true };
366
+ assert.deepEqual(await refusal({ authPolicy: "required" }), {
367
+ status: 503, message: "Authentication service temporarily unavailable. Please retry.", code: "auth.session.unavailable"
368
+ });
369
+ });