@jskit-ai/oidc-issuer-core 0.1.12 → 0.1.14

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/README.md CHANGED
@@ -34,5 +34,28 @@ Commands, run from the hub project: `npx jskit-oidc-issuer keys rotate` and
34
34
  `npx jskit-oidc-issuer import-accounts --in accounts.jsonl [--apply]` (a dry run
35
35
  unless `--apply`).
36
36
 
37
+ ## Languages
38
+
39
+ The hub's texts are message keys under `jskit.accounts.*`, with their English
40
+ in `locales/en.json` (exported as `./locales/en.json`). With no translations
41
+ everything stays in that English.
42
+
43
+ - **Choosing the language.** A page or email uses the first language the hub
44
+ has a translation for, in this order: the app's `ui_locales` on the
45
+ authorization request (for the sign-out, signed-out and sign-in problem
46
+ pages), then the browser's `Accept-Language`, then English. `it-CH` uses an
47
+ `it` translation. Emails follow the request that sent them, since hub
48
+ accounts keep no saved language. `GET /hub/interaction/:uid/details` answers
49
+ `locale` so the hub project's own sign-in pages can show the same language.
50
+ - **Translating.** Put the translations in the hub project's
51
+ `src/locales/<code>/jskit.json` (the file `jskit i18n export <code>` writes).
52
+ The hub reads them once per process. Pages carry `<html lang>`.
53
+ - **Rewording English.** `src/locales/en/jskit.json` overrides the bundled
54
+ English. A hub built directly with `createOidcIssuer` can also pass
55
+ `catalogs`, extra English catalogs merged over the bundled one.
56
+ - **API refusals.** The hub's API answers in English with its `error` code,
57
+ plus `messageCode` and `messageParams`, so a JSKIT page translates the
58
+ sentence with `serverMessage`.
59
+
37
60
  Guides: "Run an accounts hub" and "Sign in through an OIDC issuer" in the JSKIT
38
61
  guide (`packages/agent-docs/site/guide/app-setup/`).
@@ -0,0 +1,95 @@
1
+ {
2
+ "jskit": {
3
+ "accounts": {
4
+ "request": {
5
+ "failed": "Something went wrong. Try again in a moment.",
6
+ "hubPagesOnly": "This request must come from the hub's own pages.",
7
+ "tooManyAttempts": "Too many attempts. Wait a little and try again."
8
+ },
9
+ "signIn": {
10
+ "required": "Sign in to continue.",
11
+ "expired": "This sign-in has expired. Go back to the app and try again.",
12
+ "noMatch": "That email and password don't match.",
13
+ "emailUnconfirmed": "Confirm your email to continue: open the link we sent you, then press Continue."
14
+ },
15
+ "app": {
16
+ "pending": "This app is waiting for approval by the hub's owner."
17
+ },
18
+ "account": {
19
+ "emailInvalid": "Enter a valid email address.",
20
+ "emailTaken": "This email already has an account. Sign in, or reset its password.",
21
+ "displayNameRequired": "Enter the name your apps should show.",
22
+ "confirmLinkExpired": "This link has expired or was already used. Send a new one from your account."
23
+ },
24
+ "password": {
25
+ "tooShort": "Use at least {min} characters.",
26
+ "tooLong": "Use at most {max} characters.",
27
+ "tooCommon": "That password is too common. Choose one that is harder to guess.",
28
+ "currentWrong": "Your current password is not right.",
29
+ "recoveryLinkExpired": "This link has expired or was already used. Ask for a new one."
30
+ },
31
+ "google": {
32
+ "disabled": "Continue with Google is not set up on this hub.",
33
+ "connectionExpired": "This Google connection has expired. Continue with Google again.",
34
+ "linkExpired": "This link has expired or was already used. Continue with Google again.",
35
+ "taken": "This Google account is already connected to another account.",
36
+ "passwordRequired": "Set a password first, so you can still sign in without Google."
37
+ },
38
+ "admin": {
39
+ "ownerRequired": "Only the hub's owner can open this page.",
40
+ "unknownAction": "That action does not exist.",
41
+ "appNotFound": "This app is no longer registered. Refresh the page.",
42
+ "ownerSelf": "You cannot turn off your own account.",
43
+ "personNotFound": "This person no longer has an account. Refresh the page.",
44
+ "testEmailFailed": "The test email was not sent: {reason}"
45
+ },
46
+ "mail": {
47
+ "footer": "Sent by your accounts hub at {host}. If you did not ask for this, ignore this email.",
48
+ "confirm": {
49
+ "subject": "Confirm your email",
50
+ "heading": "Confirm your email",
51
+ "body": "Confirm {email} so your apps know it is really yours.",
52
+ "action": "Confirm email"
53
+ },
54
+ "recovery": {
55
+ "subject": "Reset your password",
56
+ "heading": "Reset your password",
57
+ "body": "Someone asked to reset the password of your account. The link works once, for one hour.",
58
+ "action": "Choose a new password"
59
+ },
60
+ "googleLink": {
61
+ "subject": "Connect Google to your account",
62
+ "heading": "Connect Google to your account",
63
+ "body": "Open the link to connect your Google sign-in and choose a new password. The link works once, for one hour.",
64
+ "action": "Connect Google"
65
+ },
66
+ "test": {
67
+ "subject": "Your accounts hub can send email",
68
+ "heading": "Email works",
69
+ "body": "Your hub sent this message with your own sender, so confirmation and recovery emails will arrive.",
70
+ "action": "Open your hub",
71
+ "footer": "Sent by your accounts hub at {host}."
72
+ }
73
+ },
74
+ "page": {
75
+ "signOut": {
76
+ "title": "Sign out",
77
+ "heading": "Sign out of your apps?",
78
+ "body": "You will need to sign in again the next time you open one of them.",
79
+ "confirm": "Sign out",
80
+ "stay": "Stay signed in"
81
+ },
82
+ "signedOut": {
83
+ "title": "Signed out",
84
+ "heading": "You are signed out.",
85
+ "body": "You can close this window."
86
+ },
87
+ "error": {
88
+ "title": "Sign-in problem",
89
+ "heading": "This sign-in could not continue.",
90
+ "body": "Go back to the app and try again."
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/oidc-issuer-core",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -8,6 +8,7 @@
8
8
  "files": [
9
9
  "bin",
10
10
  "data",
11
+ "locales",
11
12
  "migrations",
12
13
  "patterns",
13
14
  "src"
@@ -16,6 +17,7 @@
16
17
  "jskit-oidc-issuer": "./bin/jskit-oidc-issuer.js"
17
18
  },
18
19
  "exports": {
20
+ "./locales/en.json": "./locales/en.json",
19
21
  "./server": "./src/server/index.js",
20
22
  "./server/providers/OidcIssuerProvider": "./src/server/providers/OidcIssuerProvider.js",
21
23
  "./server/types": "./src/server/types.js"
@@ -111,16 +113,16 @@
111
113
  }
112
114
  },
113
115
  "dependencies": {
114
- "@jskit-ai/database-runtime": "0.1.254",
116
+ "@jskit-ai/database-runtime": "0.1.256",
115
117
  "jose": "6.2.12",
116
118
  "knex": "^3.1.0",
117
119
  "nodemailer": "10.2.1",
118
120
  "oidc-provider": "9.12.2"
119
121
  },
120
122
  "devDependencies": {
121
- "@jskit-ai/auth-provider-local-core": "0.2.7"
123
+ "@jskit-ai/auth-provider-local-core": "0.2.9"
122
124
  },
123
125
  "peerDependencies": {
124
- "@jskit-ai/kernel": "0.2.5"
126
+ "@jskit-ai/kernel": "0.2.7"
125
127
  }
126
128
  }
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/database-runtime-mysql": "0.1.252",
6
- "@jskit-ai/oidc-issuer-core": "0.1.12"
5
+ "@jskit-ai/database-runtime-mysql": "0.1.254",
6
+ "@jskit-ai/oidc-issuer-core": "0.1.14"
7
7
  }
8
8
  }
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { createAccountId, hashPassword, verifyPassword } from "./crypto.js";
3
+ import { hubEnglish } from "./hubTexts.js";
3
4
 
4
5
  const ACCOUNTS_TABLE = "oidc_issuer_accounts";
5
6
  const PASSWORD_MIN_LENGTH = 8;
@@ -9,22 +10,56 @@ const COMMON_PASSWORDS_URL = new URL("../../data/common-passwords.txt", import.m
9
10
 
10
11
  let commonPasswords = null;
11
12
 
13
+ // Each refusal a person can see: its code, status and the messageCode (with
14
+ // params) its English renders from.
15
+ const ACCOUNT_ERRORS = Object.freeze({
16
+ emailInvalid: { code: "email_invalid", status: 400, messageCode: "accounts.account.emailInvalid" },
17
+ emailTaken: { code: "email_taken", status: 409, messageCode: "accounts.account.emailTaken" },
18
+ displayNameRequired: { code: "display_name_required", status: 400, messageCode: "accounts.account.displayNameRequired" },
19
+ passwordRequired: { code: "password_required", status: 400, messageCode: "accounts.google.passwordRequired" },
20
+ passwordTooShort: {
21
+ code: "password_too_short",
22
+ status: 400,
23
+ messageCode: "accounts.password.tooShort",
24
+ params: { min: PASSWORD_MIN_LENGTH }
25
+ },
26
+ passwordTooLong: {
27
+ code: "password_too_long",
28
+ status: 400,
29
+ messageCode: "accounts.password.tooLong",
30
+ params: { max: PASSWORD_MAX_LENGTH }
31
+ },
32
+ passwordTooCommon: { code: "password_too_common", status: 400, messageCode: "accounts.password.tooCommon" }
33
+ });
34
+
35
+ /** One refusal as its code, English, messageCode and params. */
36
+ function accountText(entry) {
37
+ const messageParams = entry.params || {};
38
+ return { code: entry.code, message: hubEnglish(entry.messageCode, messageParams), messageCode: entry.messageCode, messageParams };
39
+ }
40
+
12
41
  function isCommonPassword(password) {
13
42
  commonPasswords ??= new Set(readFileSync(COMMON_PASSWORDS_URL, "utf8").split("\n").filter(Boolean));
14
43
  return commonPasswords.has(String(password).toLowerCase());
15
44
  }
16
45
 
46
+ function passwordProblemEntry(password) {
47
+ const value = String(password ?? "");
48
+ if (value.length < PASSWORD_MIN_LENGTH) return ACCOUNT_ERRORS.passwordTooShort;
49
+ if (value.length > PASSWORD_MAX_LENGTH) return ACCOUNT_ERRORS.passwordTooLong;
50
+ if (isCommonPassword(value)) return ACCOUNT_ERRORS.passwordTooCommon;
51
+ return null;
52
+ }
53
+
17
54
  /**
18
- * Why a password is refused, as its own code and English, or null when it is acceptable.
55
+ * Why a password is refused, as its own code, English, messageCode and params,
56
+ * or null when it is acceptable.
19
57
  * @param {unknown} password
20
- * @returns {{ code: string, message: string } | null}
58
+ * @returns {{ code: string, message: string, messageCode: string, messageParams: Record<string, unknown> } | null}
21
59
  */
22
60
  function passwordProblem(password) {
23
- const value = String(password ?? "");
24
- if (value.length < PASSWORD_MIN_LENGTH) return { code: "password_too_short", message: "Use at least 8 characters." };
25
- if (value.length > PASSWORD_MAX_LENGTH) return { code: "password_too_long", message: "Use at most 128 characters." };
26
- if (isCommonPassword(value)) return { code: "password_too_common", message: "That password is too common. Choose one that is harder to guess." };
27
- return null;
61
+ const entry = passwordProblemEntry(password);
62
+ return entry ? accountText(entry) : null;
28
63
  }
29
64
 
30
65
  function normalizeEmail(value) {
@@ -75,13 +110,22 @@ function toAccount(row) {
75
110
  }
76
111
 
77
112
  class AccountError extends Error {
78
- constructor(code, message, status = 400) {
113
+ constructor(code, message, status = 400, { messageCode = "", messageParams = {} } = {}) {
79
114
  super(message);
80
115
  this.code = code;
81
116
  this.status = status;
117
+ if (messageCode) {
118
+ this.messageCode = messageCode;
119
+ this.messageParams = messageParams;
120
+ }
82
121
  }
83
122
  }
84
123
 
124
+ function accountError(entry) {
125
+ const { code, message, messageCode, messageParams } = accountText(entry);
126
+ return new AccountError(code, message, entry.status, { messageCode, messageParams });
127
+ }
128
+
85
129
  /**
86
130
  * The hub's accounts: their emails, passwords, Google links and lockouts.
87
131
  * @param {object} dependencies
@@ -119,14 +163,14 @@ function createAccountStore({ knex, now }) {
119
163
  async function create({ email, password = null, displayName = "", emailVerified = false, googleSub = null }) {
120
164
  const normalizedEmail = normalizeEmail(email);
121
165
  if (!isEmail(normalizedEmail)) {
122
- throw new AccountError("email_invalid", "Enter a valid email address.");
166
+ throw accountError(ACCOUNT_ERRORS.emailInvalid);
123
167
  }
124
168
  if (password !== null) {
125
- const problem = passwordProblem(password);
126
- if (problem) throw new AccountError(problem.code, problem.message);
169
+ const problem = passwordProblemEntry(password);
170
+ if (problem) throw accountError(problem);
127
171
  }
128
172
  if (await rowByEmail(normalizedEmail)) {
129
- throw new AccountError("email_taken", "This email already has an account. Sign in, or reset its password.", 409);
173
+ throw accountError(ACCOUNT_ERRORS.emailTaken);
130
174
  }
131
175
  const id = createAccountId();
132
176
  const timestamp = now();
@@ -176,8 +220,8 @@ function createAccountStore({ knex, now }) {
176
220
  }
177
221
 
178
222
  async function setPassword(id, password) {
179
- const problem = passwordProblem(password);
180
- if (problem) throw new AccountError(problem.code, problem.message);
223
+ const problem = passwordProblemEntry(password);
224
+ if (problem) throw accountError(problem);
181
225
  return update(id, { ...passwordColumns(await hashPassword(password)), failed_logins: 0 });
182
226
  }
183
227
 
@@ -192,7 +236,7 @@ function createAccountStore({ knex, now }) {
192
236
 
193
237
  async function updateProfile(id, { displayName }) {
194
238
  const name = String(displayName ?? "").trim();
195
- if (!name) throw new AccountError("display_name_required", "Enter the name your apps should show.");
239
+ if (!name) throw accountError(ACCOUNT_ERRORS.displayNameRequired);
196
240
  return update(id, { display_name: name.slice(0, 160) });
197
241
  }
198
242
 
@@ -207,7 +251,7 @@ function createAccountStore({ knex, now }) {
207
251
  async function unlinkGoogle(id) {
208
252
  const row = await table().where({ id }).first();
209
253
  if (!row?.password_hash) {
210
- throw new AccountError("password_required", "Set a password first, so you can still sign in without Google.");
254
+ throw accountError(ACCOUNT_ERRORS.passwordRequired);
211
255
  }
212
256
  return update(id, { google_sub: null });
213
257
  }
@@ -1,10 +1,19 @@
1
1
  /** Small HTTP helpers shared by the hub's Fastify routes. */
2
2
 
3
+ /**
4
+ * A refusal the hub's API answers with: its status, its code, its English and,
5
+ * for a sentence a person sees, the messageCode and params that render it in
6
+ * their language.
7
+ */
3
8
  class HubError extends Error {
4
- constructor(status, code, message) {
9
+ constructor(status, code, message, { messageCode = "", messageParams = {} } = {}) {
5
10
  super(message);
6
11
  this.status = status;
7
12
  this.code = code;
13
+ if (messageCode) {
14
+ this.messageCode = messageCode;
15
+ this.messageParams = messageParams;
16
+ }
8
17
  }
9
18
  }
10
19
 
@@ -45,12 +54,12 @@ function escapeHtml(value) {
45
54
 
46
55
  /**
47
56
  * A calm standalone page for the few screens oidc-provider renders itself
48
- * (errors and the sign-out confirmation). It follows the light or dark
49
- * preference of the device.
57
+ * (errors and the sign-out confirmation), in the language `lang`. It follows
58
+ * the light or dark preference of the device.
50
59
  */
51
- function hubPage({ title, heading, body, content = "" }) {
60
+ function hubPage({ title, heading, body, content = "", lang = "en" }) {
52
61
  return `<!doctype html>
53
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
62
+ <html lang="${escapeHtml(lang)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
54
63
  <title>${escapeHtml(title)}</title>
55
64
  <style>
56
65
  :root{color-scheme:light dark;--bg:#f4f5fb;--card:#fff;--text:#1b1c22;--muted:#5d5f6a;--primary:#315da8;--on-primary:#fff;--line:#e2e3ec}
package/src/server/hub.js CHANGED
@@ -22,8 +22,9 @@ import { createSigningKeyStore } from "./signingKeys.js";
22
22
  * @param {import("./types.js").HubClock} dependencies.now
23
23
  * @param {import("./types.js").GoogleEndpoints} dependencies.googleEndpoints
24
24
  * @param {typeof fetch} dependencies.fetchImpl
25
+ * @param {import("./types.js").HubTexts} dependencies.texts The hub's pages and emails in a person's language.
25
26
  */
26
- async function createHub({ knex, config, devAuth, logger, mailer, now, googleEndpoints, fetchImpl }) {
27
+ async function createHub({ knex, config, devAuth, logger, mailer, now, googleEndpoints, fetchImpl, texts }) {
27
28
  const Adapter = createKnexAdapterClass({ knex, now });
28
29
  const accounts = createAccountStore({ knex, now });
29
30
  const clients = createClientStore({ knex, now });
@@ -46,6 +47,7 @@ async function createHub({ knex, config, devAuth, logger, mailer, now, googleEnd
46
47
  Adapter,
47
48
  accounts,
48
49
  clients,
50
+ texts,
49
51
  async hasHubSession(ctx, accountId) {
50
52
  const session = await sessions.find(ctx.cookies.get(hubSessionCookieName(config), { signed: false }));
51
53
  return session?.accountId === accountId;
@@ -121,6 +123,7 @@ async function createHub({ knex, config, devAuth, logger, mailer, now, googleEnd
121
123
  emailTokens,
122
124
  rateLimiter,
123
125
  mailer,
126
+ texts,
124
127
  google,
125
128
  oidcProvider,
126
129
  handleProtocolRequest,
@@ -0,0 +1,52 @@
1
+ import { HubError } from "./http.js";
2
+ import { hubEnglish } from "./hubTexts.js";
3
+
4
+ // Each refusal a person can see: its status, its code and the messageCode its
5
+ // English renders from. The hub's pages show it in the person's language.
6
+ const HUB_ERRORS = Object.freeze({
7
+ signInRequired: { status: 401, code: "sign_in_required", messageCode: "accounts.signIn.required" },
8
+ ownerRequired: { status: 403, code: "owner_required", messageCode: "accounts.admin.ownerRequired" },
9
+ tooManyAttempts: { status: 429, code: "rate_limited", messageCode: "accounts.request.tooManyAttempts" },
10
+ interactionExpired: { status: 404, code: "interaction_expired", messageCode: "accounts.signIn.expired" },
11
+ appPending: { status: 409, code: "app_pending", messageCode: "accounts.app.pending" },
12
+ emailUnconfirmed: { status: 409, code: "email_unconfirmed", messageCode: "accounts.signIn.emailUnconfirmed" },
13
+ signInFailed: { status: 401, code: "sign_in_failed", messageCode: "accounts.signIn.noMatch" },
14
+ confirmLinkExpired: { status: 410, code: "confirm_link_expired", messageCode: "accounts.account.confirmLinkExpired" },
15
+ emailInvalid: { status: 400, code: "email_invalid", messageCode: "accounts.account.emailInvalid" },
16
+ recoveryLinkExpired: { status: 410, code: "recovery_link_expired", messageCode: "accounts.password.recoveryLinkExpired" },
17
+ currentPasswordWrong: { status: 400, code: "current_password_wrong", messageCode: "accounts.password.currentWrong" },
18
+ googleDisabled: { status: 404, code: "google_disabled", messageCode: "accounts.google.disabled" },
19
+ googleConnectionExpired: {
20
+ status: 410,
21
+ code: "google_connection_expired",
22
+ messageCode: "accounts.google.connectionExpired"
23
+ },
24
+ googleLinkExpired: { status: 410, code: "google_link_expired", messageCode: "accounts.google.linkExpired" },
25
+ googleTaken: { status: 409, code: "google_taken", messageCode: "accounts.google.taken" },
26
+ unknownAction: { status: 404, code: "unknown_action", messageCode: "accounts.admin.unknownAction" },
27
+ appNotFound: { status: 404, code: "app_not_found", messageCode: "accounts.admin.appNotFound" },
28
+ ownerSelf: { status: 400, code: "owner_self", messageCode: "accounts.admin.ownerSelf" },
29
+ personNotFound: { status: 404, code: "person_not_found", messageCode: "accounts.admin.personNotFound" },
30
+ testEmailFailed: { status: 502, code: "email_failed", messageCode: "accounts.admin.testEmailFailed" },
31
+ hubRequestRequired: { status: 403, code: "hub_request_required", messageCode: "accounts.request.hubPagesOnly" },
32
+ failed: { status: 500, code: "hub_failed", messageCode: "accounts.request.failed" }
33
+ });
34
+
35
+ /** A refusal in English, with the messageCode and params that render it. */
36
+ function hubError(entry, messageParams = {}) {
37
+ return new HubError(entry.status, entry.code, hubEnglish(entry.messageCode, messageParams), {
38
+ messageCode: entry.messageCode,
39
+ messageParams
40
+ });
41
+ }
42
+
43
+ /** The API's answer to a refusal: its code and English, and its messageCode when it has one. */
44
+ function errorBody(error) {
45
+ return {
46
+ error: error.code,
47
+ message: error.message,
48
+ ...(error.messageCode ? { messageCode: error.messageCode, messageParams: error.messageParams } : {})
49
+ };
50
+ }
51
+
52
+ export { HUB_ERRORS, errorBody, hubError };
@@ -3,6 +3,7 @@ import { DEV_AUTH_SECRET_HEADER } from "./config.js";
3
3
  import { constantEquals, randomToken } from "./crypto.js";
4
4
  import { HubError, appendCookie, clientIp, parseCookies, serializeCookie } from "./http.js";
5
5
  import { hubSessionCookieName } from "./hubSessions.js";
6
+ import { HUB_ERRORS, errorBody, hubError } from "./hubErrors.js";
6
7
  import { composeMessage } from "./mailer.js";
7
8
  import { ACTIVE_STATUSES, HUB_SCOPES } from "./oidcProvider.js";
8
9
 
@@ -10,10 +11,10 @@ const GOOGLE_STATE_COOKIE = "hub_google_state";
10
11
  const GOOGLE_LINK_COOKIE = "hub_google_link";
11
12
  const GOOGLE_LINK_KIND = "GoogleLink";
12
13
  const GOOGLE_LINK_TTL_SECONDS = 600;
13
- const PENDING_SENTENCE = "This app is waiting for approval by the hub's owner.";
14
- const UNCONFIRMED_SENTENCE = "Confirm your email to continue: open the link we sent you, then press Continue.";
15
- const NO_MATCH_SENTENCE = "That email and password don't match.";
16
- const TOO_MANY_SENTENCE = "Too many attempts. Wait a little and try again.";
14
+ /** The locale an API request's emails go out in: the browser's Accept-Language, then English. */
15
+ function requestLocale(texts, request) {
16
+ return texts.localeFor({ acceptLanguage: request.headers["accept-language"] });
17
+ }
17
18
 
18
19
  function accountView(account) {
19
20
  return {
@@ -51,7 +52,7 @@ function isLoopbackRequest(request) {
51
52
  * @param {import("./types.js").Hub} hub
52
53
  */
53
54
  function createHubRouteSupport(hub) {
54
- const { config, accounts, sessions, rateLimiter, mailer } = hub;
55
+ const { config, accounts, sessions, rateLimiter, mailer, texts } = hub;
55
56
  const sessionCookie = hubSessionCookieName(config);
56
57
  const hubHost = new URL(config.issuer).host;
57
58
 
@@ -73,7 +74,7 @@ function createHubRouteSupport(hub) {
73
74
 
74
75
  async function requireAccount(request) {
75
76
  const signedIn = await current(request);
76
- if (!signedIn) throw new HubError(401, "sign_in_required", "Sign in to continue.");
77
+ if (!signedIn) throw hubError(HUB_ERRORS.signInRequired);
77
78
  return signedIn;
78
79
  }
79
80
 
@@ -84,7 +85,7 @@ function createHubRouteSupport(hub) {
84
85
  async function requireOwner(request) {
85
86
  const signedIn = await requireAccount(request);
86
87
  if (!isOwner(signedIn.account)) {
87
- throw new HubError(403, "owner_required", "Only the hub's owner can open this page.");
88
+ throw hubError(HUB_ERRORS.ownerRequired);
88
89
  }
89
90
  return signedIn;
90
91
  }
@@ -95,28 +96,34 @@ function createHubRouteSupport(hub) {
95
96
  writeCookie(reply, sessionCookie, token, sessions.ttlSeconds);
96
97
  }
97
98
 
98
- async function sendEmail(account, purpose, token) {
99
+ /**
100
+ * Sends one of the hub's emails in the language of the request that asked for
101
+ * it (hub accounts keep no saved language).
102
+ */
103
+ async function sendEmail(request, account, purpose, token) {
104
+ const locale = requestLocale(texts, request);
105
+ const t = (key, params) => texts.t(locale, key, params);
99
106
  const link = (path) => `${config.issuer}${path}?token=${encodeURIComponent(token)}`;
100
107
  const messages = {
101
108
  confirm: {
102
- subject: "Confirm your email",
103
- heading: "Confirm your email",
104
- body: `Confirm ${account.email} so your apps know it is really yours.`,
105
- actionLabel: "Confirm email",
109
+ subject: t("jskit.accounts.mail.confirm.subject"),
110
+ heading: t("jskit.accounts.mail.confirm.heading"),
111
+ body: t("jskit.accounts.mail.confirm.body", { email: account.email }),
112
+ actionLabel: t("jskit.accounts.mail.confirm.action"),
106
113
  actionUrl: link("/auth/confirm-email")
107
114
  },
108
115
  recovery: {
109
- subject: "Reset your password",
110
- heading: "Reset your password",
111
- body: "Someone asked to reset the password of your account. The link works once, for one hour.",
112
- actionLabel: "Choose a new password",
116
+ subject: t("jskit.accounts.mail.recovery.subject"),
117
+ heading: t("jskit.accounts.mail.recovery.heading"),
118
+ body: t("jskit.accounts.mail.recovery.body"),
119
+ actionLabel: t("jskit.accounts.mail.recovery.action"),
113
120
  actionUrl: link("/auth/reset-password")
114
121
  },
115
122
  "google-link": {
116
- subject: "Connect Google to your account",
117
- heading: "Connect Google to your account",
118
- body: "Open the link to connect your Google sign-in and choose a new password. The link works once, for one hour.",
119
- actionLabel: "Connect Google",
123
+ subject: t("jskit.accounts.mail.googleLink.subject"),
124
+ heading: t("jskit.accounts.mail.googleLink.heading"),
125
+ body: t("jskit.accounts.mail.googleLink.body"),
126
+ actionLabel: t("jskit.accounts.mail.googleLink.action"),
120
127
  actionUrl: link("/auth/connect-google")
121
128
  }
122
129
  };
@@ -124,7 +131,7 @@ function createHubRouteSupport(hub) {
124
131
  await mailer.send({
125
132
  to: account.email,
126
133
  subject,
127
- ...composeMessage({ ...content, footer: `Sent by your accounts hub at ${hubHost}. If you did not ask for this, ignore this email.` })
134
+ ...composeMessage({ ...content, footer: t("jskit.accounts.mail.footer", { host: hubHost }) })
128
135
  });
129
136
  }
130
137
 
@@ -135,11 +142,11 @@ function createHubRouteSupport(hub) {
135
142
  }
136
143
 
137
144
  async function guardSignInRate(request) {
138
- if (!(await rateLimiter.signIn(clientIp(request)))) throw new HubError(429, "rate_limited", TOO_MANY_SENTENCE);
145
+ if (!(await rateLimiter.signIn(clientIp(request)))) throw hubError(HUB_ERRORS.tooManyAttempts);
139
146
  }
140
147
 
141
148
  async function guardEmailRate(request, email) {
142
- if (!(await rateLimiter.email(email, clientIp(request)))) throw new HubError(429, "rate_limited", TOO_MANY_SENTENCE);
149
+ if (!(await rateLimiter.email(email, clientIp(request)))) throw hubError(HUB_ERRORS.tooManyAttempts);
143
150
  }
144
151
 
145
152
  return Object.freeze({
@@ -177,7 +184,7 @@ function registerInteractionRoutes(app, hub, support) {
177
184
  details = null;
178
185
  }
179
186
  if (!details || details.uid !== request.params.uid) {
180
- throw new HubError(404, "interaction_expired", "This sign-in has expired. Go back to the app and try again.");
187
+ throw hubError(HUB_ERRORS.interactionExpired);
181
188
  }
182
189
  const appRow = await clients.get(details.params.client_id);
183
190
  return { details, appRow };
@@ -185,10 +192,10 @@ function registerInteractionRoutes(app, hub, support) {
185
192
 
186
193
  async function finishInteraction(request, reply, account) {
187
194
  const { details, appRow } = await loadInteraction(request, reply);
188
- if (!appRow || !ACTIVE_STATUSES.has(appRow.status)) throw new HubError(409, "app_pending", PENDING_SENTENCE);
195
+ if (!appRow || !ACTIVE_STATUSES.has(appRow.status)) throw hubError(HUB_ERRORS.appPending);
189
196
  // Apps trust the email they receive (invitations, for example), so an
190
197
  // address nobody has confirmed never reaches them.
191
- if (!account.emailVerified) throw new HubError(409, "email_unconfirmed", UNCONFIRMED_SENTENCE);
198
+ if (!account.emailVerified) throw hubError(HUB_ERRORS.emailUnconfirmed);
192
199
  let result = { login: { accountId: account.id } };
193
200
  if (details.prompt.name === "consent" && details.session?.accountId === account.id) {
194
201
  const grant = new hub.oidcProvider().Grant({ accountId: account.id, clientId: appRow.client_id });
@@ -208,12 +215,15 @@ function registerInteractionRoutes(app, hub, support) {
208
215
  });
209
216
 
210
217
  app.get("/hub/interaction/:uid/details", async (request, reply) => {
211
- const { appRow } = await loadInteraction(request, reply);
218
+ const { details, appRow } = await loadInteraction(request, reply);
212
219
  const signedIn = await current(request);
213
220
  return {
214
221
  app: appRow ? { name: appRow.client_name, origin: appRow.origin, status: appRow.status } : null,
215
222
  account: signedIn ? accountView(signedIn.account) : null,
216
- google: Boolean(hub.google)
223
+ google: Boolean(hub.google),
224
+ // The app's ui_locales, then the browser's Accept-Language: the language
225
+ // the hub's pages show this sign-in in.
226
+ locale: hub.texts.localeFor({ uiLocales: details.params.ui_locales, acceptLanguage: request.headers["accept-language"] })
217
227
  };
218
228
  });
219
229
 
@@ -266,7 +276,7 @@ function registerSignInRoutes(app, hub, support) {
266
276
  app.post("/hub/api/sign-in", async (request, reply) => {
267
277
  await guardSignInRate(request);
268
278
  const account = await accounts.authenticate(request.body?.email, request.body?.password);
269
- if (!account) throw new HubError(401, "sign_in_failed", NO_MATCH_SENTENCE);
279
+ if (!account) throw hubError(HUB_ERRORS.signInFailed);
270
280
  await signIn(request, reply, account, "password");
271
281
  return { account: accountView(account), isOwner: isOwner(account) };
272
282
  });
@@ -285,14 +295,14 @@ function registerSignInRoutes(app, hub, support) {
285
295
  password: String(request.body?.password ?? ""),
286
296
  displayName: request.body?.displayName
287
297
  });
288
- await sendEmail(account, "confirm", await emailTokens.create(account.id, "confirm"));
298
+ await sendEmail(request, account, "confirm", await emailTokens.create(account.id, "confirm"));
289
299
  await signIn(request, reply, account, "password");
290
300
  return { account: accountView(account), isOwner: isOwner(account) };
291
301
  });
292
302
 
293
303
  app.post("/hub/api/email/confirm", async (request) => {
294
304
  const used = await emailTokens.consume(request.body?.token, "confirm");
295
- if (!used) throw new HubError(410, "confirm_link_expired", "This link has expired or was already used. Send a new one from your account.");
305
+ if (!used) throw hubError(HUB_ERRORS.confirmLinkExpired);
296
306
  const account = await accounts.markEmailVerified(used.accountId);
297
307
  return { account: accountView(account) };
298
308
  });
@@ -301,17 +311,17 @@ function registerSignInRoutes(app, hub, support) {
301
311
  const { account } = await requireAccount(request);
302
312
  if (account.emailVerified) return { ok: true };
303
313
  await guardEmailRate(request, account.email);
304
- await sendEmail(account, "confirm", await emailTokens.create(account.id, "confirm"));
314
+ await sendEmail(request, account, "confirm", await emailTokens.create(account.id, "confirm"));
305
315
  return { ok: true };
306
316
  });
307
317
 
308
318
  app.post("/hub/api/recovery/start", async (request) => {
309
319
  const email = normalizeEmail(request.body?.email);
310
- if (!isEmail(email)) throw new HubError(400, "email_invalid", "Enter a valid email address.");
320
+ if (!isEmail(email)) throw hubError(HUB_ERRORS.emailInvalid);
311
321
  await guardEmailRate(request, email);
312
322
  const account = await accounts.findByEmail(email);
313
323
  if (account && !account.disabled) {
314
- await sendEmail(account, "recovery", await emailTokens.create(account.id, "recovery"));
324
+ await sendEmail(request, account, "recovery", await emailTokens.create(account.id, "recovery"));
315
325
  }
316
326
  return { ok: true };
317
327
  });
@@ -319,7 +329,7 @@ function registerSignInRoutes(app, hub, support) {
319
329
  app.post("/hub/api/recovery/finish", async (request, reply) => {
320
330
  const password = String(request.body?.password ?? "");
321
331
  const used = await emailTokens.consume(request.body?.token, "recovery");
322
- if (!used) throw new HubError(410, "recovery_link_expired", "This link has expired or was already used. Ask for a new one.");
332
+ if (!used) throw hubError(HUB_ERRORS.recoveryLinkExpired);
323
333
  await accounts.setPassword(used.accountId, password);
324
334
  const account = await accounts.markEmailVerified(used.accountId);
325
335
  await endEverySession(account.id);
@@ -361,7 +371,7 @@ function registerAccountRoutes(app, hub, support) {
361
371
  if (account.hasPassword) {
362
372
  await guardSignInRate(request);
363
373
  if (!(await accounts.checkPassword(account.id, request.body?.currentPassword))) {
364
- throw new HubError(400, "current_password_wrong", "Your current password is not right.");
374
+ throw hubError(HUB_ERRORS.currentPasswordWrong);
365
375
  }
366
376
  }
367
377
  return { account: accountView(await accounts.setPassword(account.id, String(request.body?.newPassword ?? ""))) };
@@ -399,7 +409,7 @@ function registerGoogleRoutes(app, hub, support) {
399
409
  const googleLinks = new hub.Adapter(GOOGLE_LINK_KIND);
400
410
 
401
411
  function requireGoogle() {
402
- if (!hub.google) throw new HubError(404, "google_disabled", "Continue with Google is not set up on this hub.");
412
+ if (!hub.google) throw hubError(HUB_ERRORS.googleDisabled);
403
413
  }
404
414
 
405
415
  function googleDone(uid) {
@@ -483,7 +493,7 @@ function registerGoogleRoutes(app, hub, support) {
483
493
  async function pendingGoogleLink(request) {
484
494
  const id = cookies(request)[GOOGLE_LINK_COOKIE];
485
495
  const link = id ? await googleLinks.find(id) : null;
486
- if (!link) throw new HubError(410, "google_connection_expired", "This Google connection has expired. Continue with Google again.");
496
+ if (!link) throw hubError(HUB_ERRORS.googleConnectionExpired);
487
497
  return { id, link, account: await accounts.findById(link.accountId) };
488
498
  }
489
499
 
@@ -496,7 +506,7 @@ function registerGoogleRoutes(app, hub, support) {
496
506
  const { id, link, account } = await pendingGoogleLink(request);
497
507
  await guardSignInRate(request);
498
508
  const verified = await accounts.authenticate(account.email, request.body?.password);
499
- if (!verified) throw new HubError(401, "sign_in_failed", NO_MATCH_SENTENCE);
509
+ if (!verified) throw hubError(HUB_ERRORS.signInFailed);
500
510
  await accounts.linkGoogle(account.id, link.googleSub);
501
511
  // Google confirmed this same address, so it counts as confirmed here.
502
512
  await accounts.markEmailVerified(account.id);
@@ -509,15 +519,15 @@ function registerGoogleRoutes(app, hub, support) {
509
519
  app.post("/hub/api/google/link/email", async (request) => {
510
520
  const { link, account } = await pendingGoogleLink(request);
511
521
  await guardEmailRate(request, account.email);
512
- await sendEmail(account, "google-link", await emailTokens.create(account.id, "google-link", { googleSub: link.googleSub }));
522
+ await sendEmail(request, account, "google-link", await emailTokens.create(account.id, "google-link", { googleSub: link.googleSub }));
513
523
  return { ok: true };
514
524
  });
515
525
 
516
526
  app.post("/hub/api/google/link/finish", async (request, reply) => {
517
527
  const used = await emailTokens.consume(request.body?.token, "google-link");
518
- if (!used) throw new HubError(410, "google_link_expired", "This link has expired or was already used. Continue with Google again.");
528
+ if (!used) throw hubError(HUB_ERRORS.googleLinkExpired);
519
529
  if (await accounts.findByGoogleSub(used.payload.googleSub)) {
520
- throw new HubError(409, "google_taken", "This Google account is already connected to another account.");
530
+ throw hubError(HUB_ERRORS.googleTaken);
521
531
  }
522
532
  await accounts.clearPassword(used.accountId);
523
533
  await accounts.setPassword(used.accountId, String(request.body?.password ?? ""));
@@ -536,7 +546,7 @@ function registerGoogleRoutes(app, hub, support) {
536
546
  * @param {HubRouteSupport} support
537
547
  */
538
548
  function registerAdminRoutes(app, hub, support) {
539
- const { config, accounts, clients, settings, mailer } = hub;
549
+ const { config, accounts, clients, settings, mailer, texts } = hub;
540
550
  const { hubHost, isOwner, requireOwner, endEverySession } = support;
541
551
 
542
552
  app.get("/hub/api/admin/apps", async (request) => {
@@ -559,8 +569,8 @@ function registerAdminRoutes(app, hub, support) {
559
569
  block: () => clients.blockOrigin(clientId),
560
570
  remove: () => clients.remove(clientId)
561
571
  }[action];
562
- if (!done) throw new HubError(404, "unknown_action", "That action does not exist.");
563
- if (!(await done())) throw new HubError(404, "app_not_found", "This app is no longer registered. Refresh the page.");
572
+ if (!done) throw hubError(HUB_ERRORS.unknownAction);
573
+ if (!(await done())) throw hubError(HUB_ERRORS.appNotFound);
564
574
  return { ok: true };
565
575
  });
566
576
 
@@ -585,10 +595,10 @@ function registerAdminRoutes(app, hub, support) {
585
595
  app.post("/hub/api/admin/people/:id/:action", async (request) => {
586
596
  const { account: owner } = await requireOwner(request);
587
597
  const { id, action } = request.params;
588
- if (!["disable", "enable"].includes(action)) throw new HubError(404, "unknown_action", "That action does not exist.");
589
- if (id === owner.id) throw new HubError(400, "owner_self", "You cannot turn off your own account.");
598
+ if (!["disable", "enable"].includes(action)) throw hubError(HUB_ERRORS.unknownAction);
599
+ if (id === owner.id) throw hubError(HUB_ERRORS.ownerSelf);
590
600
  const target = await accounts.findById(id);
591
- if (!target) throw new HubError(404, "person_not_found", "This person no longer has an account. Refresh the page.");
601
+ if (!target) throw hubError(HUB_ERRORS.personNotFound);
592
602
  await accounts.setDisabled(id, action === "disable");
593
603
  if (action === "disable") await endEverySession(id);
594
604
  return { ok: true };
@@ -624,21 +634,22 @@ function registerAdminRoutes(app, hub, support) {
624
634
 
625
635
  app.post("/hub/api/admin/setup/test-email", async (request) => {
626
636
  const { account } = await requireOwner(request);
637
+ const locale = requestLocale(texts, request);
627
638
  try {
628
639
  await mailer.send({
629
640
  to: account.email,
630
- subject: "Your accounts hub can send email",
641
+ subject: texts.t(locale, "jskit.accounts.mail.test.subject"),
631
642
  ...composeMessage({
632
- heading: "Email works",
633
- body: "Your hub sent this message with your own sender, so confirmation and recovery emails will arrive.",
634
- actionLabel: "Open your hub",
643
+ heading: texts.t(locale, "jskit.accounts.mail.test.heading"),
644
+ body: texts.t(locale, "jskit.accounts.mail.test.body"),
645
+ actionLabel: texts.t(locale, "jskit.accounts.mail.test.action"),
635
646
  actionUrl: `${config.issuer}/admin/setup`,
636
- footer: `Sent by your accounts hub at ${hubHost}.`
647
+ footer: texts.t(locale, "jskit.accounts.mail.test.footer", { host: hubHost })
637
648
  })
638
649
  });
639
650
  } catch (error) {
640
651
  await settings.set("email-test", { ok: false, at: hub.now().toISOString() });
641
- throw new HubError(502, "email_failed", `The test email was not sent: ${error.message}`);
652
+ throw hubError(HUB_ERRORS.testEmailFailed, { reason: error.message });
642
653
  }
643
654
  await settings.set("email-test", { ok: true, at: hub.now().toISOString() });
644
655
  return { ok: true };
@@ -691,16 +702,16 @@ function registerDevelopmentRoutes(app, hub, support) {
691
702
  function registerHubRoutes(app, hub) {
692
703
  app.setErrorHandler((error, _request, reply) => {
693
704
  if (error instanceof HubError || error instanceof AccountError) {
694
- return reply.code(error.status).send({ error: error.code, message: error.message });
705
+ return reply.code(error.status).send(errorBody(error));
695
706
  }
696
707
  hub.logger.error({ err: error }, "Accounts hub request failed.");
697
- return reply.code(500).send({ error: "hub_failed", message: "Something went wrong. Try again in a moment." });
708
+ return reply.code(HUB_ERRORS.failed.status).send(errorBody(hubError(HUB_ERRORS.failed)));
698
709
  });
699
710
 
700
711
  app.addHook("onRequest", async (request) => {
701
712
  if (["GET", "HEAD", "OPTIONS"].includes(request.method)) return;
702
713
  if (request.headers["x-hub-request"] !== "1") {
703
- throw new HubError(403, "hub_request_required", "This request must come from the hub's own pages.");
714
+ throw hubError(HUB_ERRORS.hubRequestRequired);
704
715
  }
705
716
  });
706
717
 
@@ -0,0 +1,65 @@
1
+ import { createServerI18n } from "@jskit-ai/kernel/server/i18n";
2
+ import { catalogMessage, formatMessage, messageKeyForCode } from "@jskit-ai/kernel/shared/i18n";
3
+ import english from "../../locales/en.json" with { type: "json" };
4
+
5
+ /**
6
+ * The English of one hub message code, rendered with its params. The hub's API
7
+ * answers in English with the code, so the hub's pages can show it in the
8
+ * person's language.
9
+ * @param {string} messageCode
10
+ * @param {Record<string, unknown>} [params]
11
+ */
12
+ function hubEnglish(messageCode, params = {}) {
13
+ const template = catalogMessage(english, messageKeyForCode(messageCode));
14
+ if (template === undefined) {
15
+ throw new TypeError(`Hub text "${messageCode}" is not in oidc-issuer-core's catalog.`);
16
+ }
17
+ return formatMessage(template, params);
18
+ }
19
+
20
+ /** An Accept-Language header's locales, most preferred first; q=0 means not acceptable. */
21
+ function acceptLanguages(header) {
22
+ return String(header || "")
23
+ .split(",")
24
+ .map((part, index) => {
25
+ const [tag, ...parameters] = part.trim().split(";");
26
+ const quality = parameters.map((parameter) => parameter.trim()).find((parameter) => parameter.startsWith("q="));
27
+ return { tag: tag.trim(), weight: quality ? Number(quality.slice(2)) : 1, index };
28
+ })
29
+ .filter((entry) => entry.tag && Number.isFinite(entry.weight) && entry.weight > 0)
30
+ .sort((left, right) => right.weight - left.weight || left.index - right.index)
31
+ .map((entry) => entry.tag);
32
+ }
33
+
34
+ /** An OpenID Connect ui_locales value's locales, most preferred first. */
35
+ function uiLocales(value) {
36
+ return String(value || "").split(/\s+/u).filter(Boolean);
37
+ }
38
+
39
+ /**
40
+ * The hub's pages and emails in a person's language: the bundled English, any
41
+ * extra English catalogs the host registers (later ones reword earlier ones), and
42
+ * the app's translations in <appRoot>/src/locales/<code>/jskit.json.
43
+ * @param {object} [options]
44
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} [options.appRoot]
45
+ * @param {ReadonlyArray<object>} [options.catalogs] Extra English catalogs from the host app.
46
+ */
47
+ function createHubTexts({ appRoot = "", catalogs = [] } = {}) {
48
+ const i18n = createServerI18n({ appRoot, catalogs: [english, ...catalogs] });
49
+
50
+ /**
51
+ * The locale to answer in: the authorization request's ui_locales first, then
52
+ * the browser's Accept-Language, then English.
53
+ * @param {{ uiLocales?: unknown, acceptLanguage?: unknown }} [request]
54
+ */
55
+ function localeFor({ uiLocales: requested = "", acceptLanguage = "" } = {}) {
56
+ return i18n.resolveLocale([...uiLocales(requested), ...acceptLanguages(acceptLanguage)]);
57
+ }
58
+
59
+ return Object.freeze({
60
+ t: i18n.t,
61
+ localeFor
62
+ });
63
+ }
64
+
65
+ export { acceptLanguages, createHubTexts, hubEnglish, uiLocales };
@@ -4,6 +4,7 @@ import { resolveHubConfig, resolveHubDevAuth } from "./config.js";
4
4
  import { constantEquals, randomToken } from "./crypto.js";
5
5
  import { GOOGLE_ENDPOINTS } from "./google.js";
6
6
  import { createHub } from "./hub.js";
7
+ import { createHubTexts } from "./hubTexts.js";
7
8
  import { registerHubRoutes } from "./hubRoutes.js";
8
9
  import { createMailer } from "./mailer.js";
9
10
 
@@ -54,7 +55,8 @@ function parseJsonBody(buffer) {
54
55
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
55
56
  * @param {import("./types.js").HubMailer} [dependencies.mailer] Sends the hub's emails instead of the configured sender.
56
57
  * @param {import("./types.js").HubClock} [dependencies.now]
57
- * @param {string} [dependencies.appRoot]
58
+ * @param {string} [dependencies.appRoot] The app's root; its src/locales/<code>/jskit.json files translate the hub's pages and emails.
59
+ * @param {ReadonlyArray<object>} [dependencies.catalogs] Extra English catalogs that reword the hub's pages and emails.
58
60
  * @param {import("./types.js").GoogleEndpoints} [dependencies.googleEndpoints]
59
61
  * @param {typeof fetch} [dependencies.fetchImpl]
60
62
  */
@@ -65,6 +67,7 @@ async function createOidcIssuer({
65
67
  mailer,
66
68
  now = systemClock,
67
69
  appRoot = "",
70
+ catalogs,
68
71
  googleEndpoints = GOOGLE_ENDPOINTS,
69
72
  fetchImpl = globalThis.fetch
70
73
  }) {
@@ -77,7 +80,8 @@ async function createOidcIssuer({
77
80
  mailer: mailer || createMailer({ mail: config.mail, logger, isProduction: config.isProduction, fetchImpl }),
78
81
  now,
79
82
  googleEndpoints,
80
- fetchImpl
83
+ fetchImpl,
84
+ texts: createHubTexts({ appRoot, catalogs })
81
85
  });
82
86
  const { clients } = hub;
83
87
  let timer = null;
@@ -1,7 +1,7 @@
1
1
  import Provider, { interactionPolicy } from "oidc-provider";
2
2
  import { isLoopbackHostname } from "./config.js";
3
3
  import { deriveKey } from "./crypto.js";
4
- import { hubPage } from "./http.js";
4
+ import { escapeHtml, hubPage } from "./http.js";
5
5
 
6
6
  const ACTIVE_STATUSES = new Set(["active", "active-dev"]);
7
7
  const HUB_SCOPES = "openid email profile";
@@ -26,6 +26,20 @@ function interactionPath(uid) {
26
26
  return `/hub/interaction/${uid}`;
27
27
  }
28
28
 
29
+ /**
30
+ * The language of a page oidc-provider renders: the request's ui_locales, then
31
+ * the browser's Accept-Language, then English.
32
+ * @param {import("./types.js").HubTexts} texts
33
+ * @param {any} ctx oidc-provider's request context.
34
+ */
35
+ function pageText(texts, ctx) {
36
+ const lang = texts.localeFor({
37
+ uiLocales: ctx.oidc?.params?.ui_locales ?? ctx.query?.ui_locales,
38
+ acceptLanguage: ctx.headers?.["accept-language"]
39
+ });
40
+ return { lang, t: (key) => texts.t(lang, key) };
41
+ }
42
+
29
43
  /**
30
44
  * The hub's own session is the single sign-in state: oidc-provider's session
31
45
  * only counts while this browser is still signed in to the hub as the same
@@ -62,8 +76,9 @@ function interactionsPolicy(hasHubSession) {
62
76
  * @param {ReturnType<typeof import("./clients.js").createClientStore>} dependencies.clients
63
77
  * @param {(ctx: any, accountId: string) => Promise<boolean>} dependencies.hasHubSession
64
78
  * Answers whether the browser still has the hub session of the account.
79
+ * @param {import("./types.js").HubTexts} dependencies.texts The hub's pages in a person's language.
65
80
  */
66
- function createOidcProvider({ config, jwks, Adapter, accounts, clients, hasHubSession }) {
81
+ function createOidcProvider({ config, jwks, Adapter, accounts, clients, hasHubSession, texts }) {
67
82
  const provider = new Provider(config.issuer, {
68
83
  adapter: Adapter,
69
84
  jwks,
@@ -105,20 +120,26 @@ function createOidcProvider({ config, jwks, Adapter, accounts, clients, hasHubSe
105
120
  rpInitiatedLogout: {
106
121
  enabled: true,
107
122
  async logoutSource(ctx, form) {
123
+ const { lang, t } = pageText(texts, ctx);
124
+ const confirm = escapeHtml(t("jskit.accounts.page.signOut.confirm"));
125
+ const stay = escapeHtml(t("jskit.accounts.page.signOut.stay"));
108
126
  ctx.type = "html";
109
127
  ctx.body = hubPage({
110
- title: "Sign out",
111
- heading: "Sign out of your apps?",
112
- body: "You will need to sign in again the next time you open one of them.",
113
- content: `${form}<div class="actions"><button class="primary" autofocus type="submit" form="op.logoutForm" value="yes" name="logout">Sign out</button><button class="secondary" type="submit" form="op.logoutForm">Stay signed in</button></div>`
128
+ lang,
129
+ title: t("jskit.accounts.page.signOut.title"),
130
+ heading: t("jskit.accounts.page.signOut.heading"),
131
+ body: t("jskit.accounts.page.signOut.body"),
132
+ content: `${form}<div class="actions"><button class="primary" autofocus type="submit" form="op.logoutForm" value="yes" name="logout">${confirm}</button><button class="secondary" type="submit" form="op.logoutForm">${stay}</button></div>`
114
133
  });
115
134
  },
116
135
  async postLogoutSuccessSource(ctx) {
136
+ const { lang, t } = pageText(texts, ctx);
117
137
  ctx.type = "html";
118
138
  ctx.body = hubPage({
119
- title: "Signed out",
120
- heading: "You are signed out.",
121
- body: "You can close this window."
139
+ lang,
140
+ title: t("jskit.accounts.page.signedOut.title"),
141
+ heading: t("jskit.accounts.page.signedOut.heading"),
142
+ body: t("jskit.accounts.page.signedOut.body")
122
143
  });
123
144
  }
124
145
  },
@@ -171,11 +192,14 @@ function createOidcProvider({ config, jwks, Adapter, accounts, clients, hasHubSe
171
192
  return grant;
172
193
  },
173
194
  async renderError(ctx, out) {
195
+ const { lang, t } = pageText(texts, ctx);
174
196
  ctx.type = "html";
175
197
  ctx.body = hubPage({
176
- title: "Sign-in problem",
177
- heading: "This sign-in could not continue.",
178
- body: out.error_description || "Go back to the app and try again."
198
+ lang,
199
+ title: t("jskit.accounts.page.error.title"),
200
+ heading: t("jskit.accounts.page.error.heading"),
201
+ // oidc-provider's own description of the protocol error stays as it wrote it.
202
+ body: out.error_description || t("jskit.accounts.page.error.body")
179
203
  });
180
204
  }
181
205
  });
@@ -6,6 +6,7 @@
6
6
  /** @typedef {ReturnType<typeof import("./adapter.js").createKnexAdapterClass>} HubAdapterClass The class the hub and oidc-provider keep short-lived records with. */
7
7
  /** @typedef {Awaited<ReturnType<typeof import("./hub.js").createHub>>} Hub The collaborators the hub's routes share. */
8
8
  /** @typedef {ReturnType<typeof import("./mailer.js").createMailer>} HubMailer Sends the hub's emails. */
9
+ /** @typedef {ReturnType<typeof import("./hubTexts.js").createHubTexts>} HubTexts The hub's pages and emails in a person's language. */
9
10
  /** @typedef {typeof import("./clock.js").systemClock} HubClock The hub's clock: answers the current time. */
10
11
  /** @typedef {typeof import("./google.js").GOOGLE_ENDPOINTS} GoogleEndpoints Google's sign-in addresses. */
11
12