Progmasoft Git

progmaweb

The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.

Clonegit clone https://git.progmasoft.com/progmaweb

Switch language in place and add Russian

The language control no longer reloads the page. It calls a server action
that stores the preference cookie; Next.js then renders the current route
again and applies it in place, so scroll position, theme and client state
stay. The lang query parameter remains for links and for browsers without
script, and is the fallback when the action cannot reach the server. Both
paths write the cookie with the same attributes from one function.

The toggle button is now a language menu, a native select that lists each
language by its own name, and Russian (ru-RU) is the third locale with a
complete translation of every message.

Tests require every locale to have exactly the message shape of the default
locale with no empty text, and cover the cookie attributes and host
normalization. Verified locally: prettier, eslint, type check, tests, the
production build, and a browser run on the apex and ViGet hosts where the
language changed with no navigation and the scroll position kept.
Commit
35158de28f4a0dfc300f2d3b5787d2064a06105c
Author
Leitwolf11 ·
Parents
bcf10c927358

Files · Download .tar.gz

Changes

 apps/web/app/globals.css                   |  18 +-
 apps/web/components/PreferenceControls.tsx |  49 +++-
 apps/web/lib/locale.actions.ts             |  38 +++
 apps/web/lib/locale.server.ts              |   4 +-
 apps/web/lib/localization.ts               | 385 ++++++++++++++++++++++++++++-
 apps/web/proxy.ts                          |  34 +--
 apps/web/tests/localization.test.mjs       | 108 +++++++-
 7 files changed, 602 insertions(+), 34 deletions(-)

diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index 936a53b..2022863 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -216,7 +216,8 @@ a {
   padding-left: 4px;
 }
 
-.preference-controls button {
+.preference-controls button,
+.preference-controls select {
   min-height: 34px;
   display: inline-flex;
   gap: 6px;
@@ -231,11 +232,24 @@ a {
   font-weight: 700;
 }
 
-.preference-controls button:hover {
+.preference-controls button:hover,
+.preference-controls select:hover {
   border-color: var(--blue-600);
   background: var(--surface-blue);
 }
 
+/* The language menu is the native select: the browser supplies the list,
+   keyboard handling and the accessible name without any script. */
+.preference-controls select {
+  display: inline-block;
+  font-family: inherit;
+}
+
+.preference-controls select:disabled {
+  cursor: progress;
+  opacity: 0.7;
+}
+
 .primary-nav > a {
   color: var(--ink-800);
   font-size: 14px;
diff --git a/apps/web/components/PreferenceControls.tsx b/apps/web/components/PreferenceControls.tsx
index f5f6b71..c4f5690 100644
--- a/apps/web/components/PreferenceControls.tsx
+++ b/apps/web/components/PreferenceControls.tsx
@@ -3,8 +3,14 @@
 
 "use client";
 
-import { useEffect, useSyncExternalStore } from "react";
-import type { Locale } from "@/lib/localization";
+import { useEffect, useSyncExternalStore, useTransition } from "react";
+import { selectLocale } from "@/lib/locale.actions";
+import {
+  isLocale,
+  localeNames,
+  supportedLocales,
+  type Locale,
+} from "@/lib/localization";
 
 interface PreferenceControlsProps {
   locale: Locale;
@@ -40,6 +46,7 @@ export function PreferenceControls({
   labels,
 }: PreferenceControlsProps) {
   const theme = useSyncExternalStore(subscribeTheme, readTheme, () => "light");
+  const [switchingLocale, startLocaleSwitch] = useTransition();
 
   useEffect(() => {
     document.documentElement.dataset.theme = theme;
@@ -52,10 +59,24 @@ export function PreferenceControls({
     window.dispatchEvent(new Event(themeEvent));
   }
 
-  function toggleLocale() {
-    const url = new URL(window.location.href);
-    url.searchParams.set("lang", locale === "en-US" ? "de-DE" : "en-US");
-    window.location.assign(url);
+  // The server stores the preference and re-renders the current route in the
+  // selected language, so the page changes in place: nothing is reloaded and
+  // scroll position, theme and client state stay as they are.
+  function chooseLocale(selected: string) {
+    if (!isLocale(selected) || selected === locale) {
+      return;
+    }
+    startLocaleSwitch(async () => {
+      try {
+        await selectLocale(selected);
+      } catch {
+        // The request did not reach the server. The query parameter asks the
+        // proxy for the same preference with an ordinary navigation.
+        const url = new URL(window.location.href);
+        url.searchParams.set("lang", selected);
+        window.location.assign(url);
+      }
+    });
   }
 
   return (
@@ -69,14 +90,20 @@ export function PreferenceControls({
         <span aria-hidden="true">{theme === "light" ? "◐" : "◑"}</span>
         <span>{theme === "light" ? labels.dark : labels.light}</span>
       </button>
-      <button
-        type="button"
-        onClick={toggleLocale}
+      <select
+        value={locale}
+        onChange={(event) => chooseLocale(event.target.value)}
+        aria-busy={switchingLocale}
+        disabled={switchingLocale}
         aria-label={labels.language}
         title={labels.language}
       >
-        {locale === "en-US" ? "DE" : "EN"}
-      </button>
+        {supportedLocales.map((supported) => (
+          <option key={supported} value={supported} lang={supported}>
+            {localeNames[supported]}
+          </option>
+        ))}
+      </select>
     </div>
   );
 }
diff --git a/apps/web/lib/locale.actions.ts b/apps/web/lib/locale.actions.ts
new file mode 100644
index 0000000..6950311
--- /dev/null
+++ b/apps/web/lib/locale.actions.ts
@@ -0,0 +1,38 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+"use server";
+
+import { cookies, headers } from "next/headers";
+import {
+  isLocale,
+  localeCookieName,
+  localeCookieOptions,
+  requestHost,
+} from "./localization";
+
+/**
+ * Stores the language preference of the visitor.
+ *
+ * Setting a cookie in a server action makes Next.js render the current route
+ * again on the server and apply the result in place, so the language changes
+ * without a page load. A value that is not a published locale is ignored: the
+ * argument arrives from the browser and is not trusted.
+ */
+export async function selectLocale(value: string): Promise<void> {
+  if (!isLocale(value)) {
+    return;
+  }
+  const requestHeaders = await headers();
+  const host = requestHost(
+    requestHeaders.get("x-forwarded-host"),
+    requestHeaders.get("host"),
+  );
+  // TLS terminates at Nginx, which reports the public scheme in this header.
+  const secure = requestHeaders.get("x-forwarded-proto") === "https";
+  (await cookies()).set(
+    localeCookieName,
+    value,
+    localeCookieOptions(host, secure),
+  );
+}
diff --git a/apps/web/lib/locale.server.ts b/apps/web/lib/locale.server.ts
index 3c9c168..590bf2d 100644
--- a/apps/web/lib/locale.server.ts
+++ b/apps/web/lib/locale.server.ts
@@ -3,9 +3,9 @@
 
 import "server-only";
 import { cookies } from "next/headers";
-import { isLocale, type Locale } from "./localization";
+import { isLocale, localeCookieName, type Locale } from "./localization";
 
-export const localeCookieName = "progmasoft_locale";
+export { localeCookieName };
 
 export async function getLocale(): Promise<Locale> {
   const value = (await cookies()).get(localeCookieName)?.value;
diff --git a/apps/web/lib/localization.ts b/apps/web/lib/localization.ts
index 1e57e53..7410520 100644
--- a/apps/web/lib/localization.ts
+++ b/apps/web/lib/localization.ts
@@ -1,13 +1,62 @@
 // SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
 // SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
 
-export const supportedLocales = ["en-US", "de-DE"] as const;
+export const supportedLocales = ["en-US", "de-DE", "ru-RU"] as const;
 export type Locale = (typeof supportedLocales)[number];
 
 export function isLocale(value: string | undefined): value is Locale {
   return supportedLocales.includes(value as Locale);
 }
 
+/** Each language named in that language, as a language menu shows it. */
+export const localeNames: Record<Locale, string> = {
+  "en-US": "English",
+  "de-DE": "Deutsch",
+  "ru-RU": "Русский",
+};
+
+export const localeCookieName = "progmasoft_locale";
+
+export interface LocaleCookieOptions {
+  domain: string | undefined;
+  httpOnly: true;
+  maxAge: number;
+  sameSite: "lax";
+  secure: boolean;
+}
+
+/**
+ * Attributes of the language-preference cookie.
+ *
+ * The preference is shared by every Progmasoft host, so on a production host
+ * the cookie belongs to the registrable domain. Any other host, such as a
+ * local development name, keeps a host-only cookie. The proxy redirect and
+ * the in-page language switch must write the same cookie, or one would leave
+ * a second cookie behind that shadows the other.
+ */
+export function localeCookieOptions(
+  host: string,
+  secure: boolean,
+): LocaleCookieOptions {
+  const isProductionHost =
+    host === "progmasoft.com" || host.endsWith(".progmasoft.com");
+  return {
+    domain: isProductionHost ? ".progmasoft.com" : undefined,
+    httpOnly: true,
+    maxAge: 60 * 60 * 24 * 365,
+    sameSite: "lax",
+    secure,
+  };
+}
+
+/** The host a request was addressed to, without its port and in lower case. */
+export function requestHost(
+  forwardedHost: string | null,
+  host: string | null,
+): string {
+  return (forwardedHost ?? host)?.split(":", 1)[0]?.toLowerCase() ?? "";
+}
+
 export const messages = {
   "en-US": {
     metadata: {
@@ -672,6 +721,340 @@ export const messages = {
       footerClosing: "ViGet-Paketregistrierung von Progmasoft",
     },
   },
+  "ru-RU": {
+    metadata: {
+      homeTitle: "Progmasoft",
+      homeDescription:
+        "Progmasoft разрабатывает системы для языков программирования, управления пакетами и инструментов разработчика.",
+      accountTitle: "Аккаунт",
+      accountDescription: "Откройте свой аккаунт Progmasoft и управляйте им.",
+      loginTitle: "Вход",
+      registerTitle: "Создание аккаунта",
+      recoveryTitle: "Восстановление аккаунта",
+      recoveryDescription:
+        "Получите помощь в восстановлении доступа к аккаунту Progmasoft.",
+      dashboardTitle: "Панель управления",
+      vigetTitle: "Реестр пакетов ViGet от Progmasoft",
+      vigetDescription:
+        "Реестр пакетов Visual X# работает, но опубликованных пакетов пока нет.",
+      dslPluginsTitle: "DSL-плагины · Реестр пакетов ViGet от Progmasoft",
+      dslPluginsDescription:
+        "Каталог Kotlin DSL-плагинов ViGet работает, но опубликованных плагинов пока нет.",
+    },
+    navigation: {
+      primary: "Основная навигация",
+      organization: "Организация",
+      products: "Продукты",
+      principles: "Принципы",
+      account: "Аккаунт",
+      dashboard: "Панель управления",
+      signIn: "Войти",
+      createAccount: "Создать аккаунт",
+      theme: "Тема",
+      light: "Светлая",
+      dark: "Тёмная",
+      language: "Язык",
+    },
+    footer: {
+      summary:
+        "Инфраструктура языков программирования и системы для разработчиков, построенные на надёжных контрактах.",
+      products: "Продукты",
+      openSource: "Открытый исходный код",
+      organization: "Организация",
+      support: "Поддержка",
+      websiteSource: "Исходный код сайта",
+      closing:
+        "Создано ради ясности, безопасности и долгосрочного сопровождения.",
+    },
+    home: {
+      heroEyebrow: "Системы для разработчиков от Progmasoft",
+      heroTitleStart: "Инструменты должны делать сложную работу",
+      heroTitleAccent: "понятной.",
+      heroDescription:
+        "Мы создаём инфраструктуру языков программирования, системы пакетов и инструменты разработчика на основе явных контрактов, а не случайной сложности.",
+      exploreProducts: "Обзор продуктов",
+      browseSource: "Исходный код",
+      facts: [
+        ["Открыто", "Публичная разработка"],
+        ["Типизировано", "Контракты важнее обходных путей"],
+        ["Нативно", "Производительность без загадок"],
+      ],
+      visualLabel: "Принципы продуктов Progmasoft",
+      stack: [
+        [
+          "Продукты",
+          "Сфокусированные решения",
+          "Ясное назначение · устойчивые имена · публичная идентичность",
+        ],
+        [
+          "Платформа",
+          "Общая основа аккаунтов",
+          "Аутентификация · доступ к сервисам · восстановление",
+        ],
+        [
+          "Эксплуатация",
+          "Собственная инфраструктура",
+          "Наблюдаемая · сопровождаемая · под нашим прямым управлением",
+        ],
+      ],
+      productsEyebrow: "Продукты и проекты",
+      productsTitle: "Одна экосистема, чёткие границы.",
+      productsDescription:
+        "У каждой части одна зона ответственности и документированный контракт со следующим уровнем.",
+      products: [
+        [
+          "Язык программирования",
+          "Visual X#",
+          "Современный язык программирования, разрабатываемый Progmasoft, с собственным сайтом продукта и документации.",
+          "Подробнее о Visual X#",
+        ],
+        [
+          "Реестр пакетов",
+          "ViGet",
+          "Канонический реестр пакетов и DSL-плагинов экосистемы Visual X#, которым напрямую управляет Progmasoft.",
+          "Открыть ViGet",
+        ],
+        [
+          "Инструменты разработчика",
+          "Открытая разработка",
+          "Компилятор, форматтер, линтер, анализатор, система проектов и редактор разрабатываются в публичных репозиториях.",
+          "Смотреть на GitHub",
+        ],
+      ],
+      principlesEyebrow: "Инженерные принципы",
+      principlesTitle: "Создано, чтобы оставаться понятным.",
+      principlesDescription:
+        "Архитектура полезна только тогда, когда новый участник может понять, к чему относится решение и как его проверить.",
+      principles: [
+        [
+          "Явные контракты",
+          "Типизированные границы делают видимыми ответственность, совместимость и поведение при сбоях.",
+        ],
+        [
+          "Настоящая проверка",
+          "Тесты проверяют установленные артефакты, пути, близкие к рабочим, и наблюдаемое поведение.",
+        ],
+        [
+          "Устойчивые имена",
+          "Публичная терминология следует модели продукта, а не историческим случайностям реализации.",
+        ],
+      ],
+      accountEyebrow: "Аккаунт Progmasoft",
+      accountTitle: "Единая учётная запись для сервисов Progmasoft.",
+      accountDescription:
+        "Управляйте профилем и будущим доступом к сервисам на отдельном сайте аккаунта.",
+      openAccount: "Открыть аккаунт",
+    },
+    account: {
+      securityLabel: "Свойства безопасности аккаунта",
+      trust: [
+        "Защищённый сеансовый cookie",
+        "Хеширование паролей на сервере",
+        "Ограничение частоты попыток входа",
+      ],
+      landingEyebrow: "Аккаунт Progmasoft",
+      landingTitle:
+        "Одна понятная учётная запись для всех поддерживаемых сервисов.",
+      landingDescription:
+        "Аккаунт хранит профиль, аутентификацию и доступ к сервисам в отдельном контуре безопасности.",
+      identity: [
+        [
+          "Имя аккаунта",
+          "Ваше постоянное публичное имя и имя издателя в ViGet",
+        ],
+        ["Эл. почта", "Восстановление и уведомления безопасности"],
+        ["Сеанс", "Защищённый отзываемый доступ из браузера"],
+      ],
+      features: [
+        [
+          "Продуманная безопасность",
+          "Пароли хешируются на сервере, а токены сеансов хранятся только в виде дайджестов.",
+        ],
+        [
+          "Предсказуемые имена",
+          "Канонические имена аккаунтов исключают неоднозначные URL и подмену имени, отличающегося только регистром. ViGet использует именно это имя как издателя пакетов и не создаёт вторую учётную запись.",
+        ],
+        [
+          "Границы сервисов",
+          "Продукты запрашивают явный доступ к аккаунту, а не разделяют скрытое состояние приложения.",
+        ],
+      ],
+      loginEyebrow: "Аккаунт Progmasoft",
+      loginTitle: "Безопасный вход.",
+      loginDescription:
+        "Перейдите к панели управления аккаунтом и подключённым сервисам.",
+      registerEyebrow: "Создание учётной записи",
+      registerTitle: "Начните с постоянного аккаунта.",
+      registerDescription:
+        "Выберите имя, которое будет использоваться в URL вашего аккаунта Progmasoft.",
+      recoveryEyebrow: "Поддержка аккаунта",
+      recoveryTitle: "Восстановите свой аккаунт.",
+      recoveryDescription:
+        "Если вы больше не можете войти, используйте проверенный канал поддержки.",
+      recoveryPanelEyebrow: "Восстановление аккаунта",
+      recoveryPanelTitle: "Безопасное восстановление доступа",
+      recoveryPanelDescription:
+        "Автоматическое восстановление пароля недоступно на этапе первоначального запуска системы аккаунтов. Напишите в поддержку Progmasoft с адреса электронной почты, указанного в вашем аккаунте, чтобы мы могли подтвердить право владения.",
+      recoveryEmailSubject: "Восстановление аккаунта Progmasoft",
+      contactSupport: "Написать в поддержку",
+      rememberedPassword: "Вспомнили пароль?",
+      returnToSignIn: "Вернуться ко входу",
+    },
+    auth: {
+      createHeading: "Создайте аккаунт",
+      loginHeading: "С возвращением",
+      createDescription:
+        "Используйте одну учётную запись Progmasoft во всех поддерживаемых сервисах.",
+      loginDescription:
+        "Войдите, указав адрес электронной почты, привязанный к вашему аккаунту Progmasoft.",
+      accountName: "Имя аккаунта",
+      accountHint:
+        "От 8 до 128 букв ASCII или цифр; первая буква должна быть заглавной.",
+      email: "Адрес электронной почты",
+      password: "Пароль",
+      forgotPassword: "Забыли пароль?",
+      passwordHint:
+        "Не менее 12 символов. Длинные парольные фразы поддерживаются.",
+      confirmPassword: "Подтверждение пароля",
+      show: "Показать",
+      hide: "Скрыть",
+      working: "Выполняется…",
+      create: "Создать аккаунт",
+      signIn: "Войти",
+      or: "или",
+      google: "Продолжить с Google",
+      already: "Уже есть аккаунт?",
+      newUser: "Впервые в Progmasoft?",
+      createLink: "Создайте аккаунт",
+      mismatch: "Подтверждение пароля не совпадает.",
+      unreachable:
+        "Сервис аккаунтов временно недоступен. Повторите попытку чуть позже.",
+      missingName: "Сервер не вернул имя аккаунта.",
+      unreadableName: "Не удалось прочитать поле «Имя аккаунта».",
+      requestFailed: "Не удалось выполнить запрос.",
+      googleSignInFailed:
+        "Не удалось выполнить вход через Google. Повторите попытку.",
+      googleAccountNameRequired:
+        "Выберите имя аккаунта, прежде чем продолжить с Google.",
+      googleAccountNameUnavailable:
+        "Это имя аккаунта недоступно. Выберите другое.",
+      googleInvalidAccountName:
+        "Укажите допустимое имя аккаунта, прежде чем продолжить с Google.",
+    },
+    dashboard: {
+      loading: "Загрузка аккаунта…",
+      loadFailed: "Не удалось загрузить панель управления.",
+      unreachable: "Сервис аккаунтов временно недоступен.",
+      navigation: "Навигация панели управления",
+      overview: "Обзор",
+      security: "Безопасность",
+      services: "Сервисы",
+      signOut: "Выйти",
+      eyebrow: "Обзор аккаунта",
+      welcome: "Добро пожаловать",
+      description:
+        "Управляйте учётной записью, которую используют сервисы Progmasoft.",
+      profile: "Профиль",
+      identity: "Учётная запись",
+      accountName: "Имя аккаунта",
+      publisherName: "Имя издателя в ViGet",
+      email: "Эл. почта",
+      created: "Создан",
+      passwordSessions: "Пароль и сеансы",
+      securityDescription:
+        "Ваш браузер использует защищённый сеансовый cookie с флагом HttpOnly. Секреты сеансов никогда не хранятся в открытом виде.",
+      changePassword: "Сменить пароль",
+      products: "Подключённые продукты Progmasoft",
+      publisherPrefix: "Имя издателя",
+      sameAccount: "ваше имя аккаунта",
+      profileDescription: "Профиль в экосистеме разработчика",
+      planned: "Запланировано",
+    },
+    viget: {
+      navigationLabel: "Навигация реестра",
+      packages: "Пакеты",
+      dslPlugins: "DSL-плагины",
+      account: "Аккаунт",
+      login: "Войти",
+      register: "Регистрация",
+      homeEyebrow: "Реестр пакетов ViGet",
+      homeTitle: "Пакеты для экосистемы Visual X#.",
+      homeDescription:
+        "ViGet — канонический источник пакетов Visual X# и DSL-плагинов проектов, которым напрямую управляет Progmasoft.",
+      createAccount: "Создать аккаунт",
+      exploreVisualXSharp: "Подробнее о Visual X#",
+      available: "Реестр доступен",
+      emptyTitle: "Публичный каталог пуст.",
+      emptyDescription:
+        "Ни один выпуск пакета пока не опубликован. ViGet покажет здесь настоящие пакеты, когда они появятся.",
+      packageFormat: "Формат пакета",
+      publisherIdentity: "Имя издателя",
+      publishing: "Публикация",
+      publishingClosed: "Пока не открыта",
+      catalogsEyebrow: "Каталоги",
+      catalogsTitle: "Два вида артефактов, один реестр.",
+      catalogsDescription:
+        "У пакетов и DSL-плагинов проектов отдельные предсказуемые пространства координат.",
+      visualPackages: "Пакеты Visual X#",
+      vipkgCatalog: "Каталог ViPkg",
+      vipkgDescription:
+        "Библиотеки и приложения, написанные на Visual X#, распространяются как артефакты .vipkg.",
+      projectExtensions: "Расширения проектов",
+      kotlinPlugins: "Kotlin DSL-плагины",
+      kotlinDescription:
+        "Плагины в виде Kotlin JAR, расширяющие конфигурацию проекта Visual.XSharp.kts.",
+      openCatalog: "Открыть каталог",
+      contractEyebrow: "Контракт реестра",
+      contractTitle: "Ясная ответственность от учётной записи до артефакта.",
+      principles: [
+        [
+          "Одно имя аккаунта",
+          "Имя вашего аккаунта Progmasoft — это и ваше имя издателя в ViGet.",
+        ],
+        [
+          "Координаты с учётом регистра",
+          "Имена издателей и пакетов сохраняют точное публичное написание.",
+        ],
+        [
+          "Никаких выпусков-заглушек",
+          "Каталог честно остаётся пустым, пока не опубликован настоящий подписанный артефакт.",
+        ],
+      ],
+      pluginEyebrow: "ViGet · Kotlin DSL-плагины",
+      pluginTitle: "Расширяйте модель проекта.",
+      pluginDescription:
+        "Kotlin DSL-плагины — это JAR-артефакты для Visual.XSharp.kts. Они отделены от пакетов Visual X# в формате .vipkg.",
+      backToPackages: "Назад к пакетам",
+      followDevelopment: "Следить за разработкой",
+      pluginAvailable: "Каталог доступен",
+      pluginEmptyTitle: "Публичных DSL-плагинов пока нет.",
+      pluginEmptyDescription:
+        "Каталог готов и намеренно не содержит артефактов-заглушек.",
+      guidance: [
+        [
+          "Формат",
+          "Kotlin JAR",
+          "DSL-плагины работают как расширения проектов на Kotlin/JVM.",
+        ],
+        [
+          "Расположение",
+          "Отдельный каталог",
+          "Координаты плагинов всегда начинаются с /dslplugins.",
+        ],
+        [
+          "Доступность",
+          "Публикация закрыта",
+          "Публикация откроется только после завершения контракта подписанных плагинов.",
+        ],
+      ],
+      footerDescription:
+        "ViGet — реестр пакетов и Kotlin DSL-плагинов экосистемы Visual X#.",
+      registry: "Реестр",
+      support: "Поддержка",
+      source: "Исходный код",
+      footerClosing: "Реестр пакетов ViGet от Progmasoft",
+    },
+  },
 } as const;
 
 export function getMessages(locale: Locale) {
diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts
index 1c1ca81..3eb5e60 100644
--- a/apps/web/proxy.ts
+++ b/apps/web/proxy.ts
@@ -3,21 +3,28 @@
 
 import type { NextRequest } from "next/server";
 import { NextResponse } from "next/server";
-import { isLocale } from "@/lib/localization";
+import {
+  isLocale,
+  localeCookieName,
+  localeCookieOptions,
+  requestHost,
+} from "@/lib/localization";
 
 const accountHosts = new Set(["account.progmasoft.com", "account.localhost"]);
 const vigetHosts = new Set(["viget.progmasoft.com", "viget.localhost"]);
 
 export function proxy(request: NextRequest) {
-  const host =
-    (request.headers.get("x-forwarded-host") ?? request.headers.get("host"))
-      ?.split(":", 1)[0]
-      ?.toLowerCase() ?? "";
+  const host = requestHost(
+    request.headers.get("x-forwarded-host"),
+    request.headers.get("host"),
+  );
   const pathname = request.nextUrl.pathname;
 
   // Language selection is a user preference, not a second canonical URL.
   // Consume the query parameter once, persist it across Progmasoft hosts, and
   // redirect to the clean URL so crawlers never index preference variants.
+  // The header control switches in place through a server action; this
+  // parameter remains for links and for browsers that run no script.
   const requestedLocale = request.nextUrl.searchParams.get("lang") ?? undefined;
   if (isLocale(requestedLocale)) {
     const destination = request.nextUrl.clone();
@@ -29,17 +36,14 @@ export function proxy(request: NextRequest) {
       ? "https:"
       : request.nextUrl.protocol;
     const response = NextResponse.redirect(destination);
-    response.cookies.set("progmasoft_locale", requestedLocale, {
-      domain:
-        host === "progmasoft.com" || host.endsWith(".progmasoft.com")
-          ? ".progmasoft.com"
-          : undefined,
-      httpOnly: true,
-      maxAge: 60 * 60 * 24 * 365,
-      sameSite: "lax",
-      secure:
+    response.cookies.set(
+      localeCookieName,
+      requestedLocale,
+      localeCookieOptions(
+        host,
         forwardedProtocol === "https" || request.nextUrl.protocol === "https:",
-    });
+      ),
+    );
     return response;
   }
 
diff --git a/apps/web/tests/localization.test.mjs b/apps/web/tests/localization.test.mjs
index 3d499ed..47d7549 100644
--- a/apps/web/tests/localization.test.mjs
+++ b/apps/web/tests/localization.test.mjs
@@ -6,15 +6,20 @@ import { test } from "node:test";
 import {
   getMessages,
   isLocale,
+  localeCookieName,
+  localeNames,
+  localeCookieOptions,
   messages,
+  requestHost,
   supportedLocales,
 } from "../lib/localization.ts";
 
-test("only the two published locales are accepted", () => {
-  assert.deepEqual(supportedLocales, ["en-US", "de-DE"]);
+test("only the published locales are accepted", () => {
+  assert.deepEqual(supportedLocales, ["en-US", "de-DE", "ru-RU"]);
   assert.equal(isLocale("en-US"), true);
   assert.equal(isLocale("de-DE"), true);
-  for (const value of ["en", "de", "en-us", "tr-TR", "", undefined]) {
+  assert.equal(isLocale("ru-RU"), true);
+  for (const value of ["en", "de", "ru", "en-us", "tr-TR", "", undefined]) {
     assert.equal(isLocale(value), false, `unexpected locale: ${value}`);
   }
 });
@@ -60,3 +65,100 @@ test("each supported locale resolves to its own complete message tree", () => {
 
   assert.deepEqual(shape(messages["de-DE"]), shape(messages["en-US"]));
 });
+
+test("the language cookie is shared by production hosts and host-only elsewhere", () => {
+  assert.equal(localeCookieName, "progmasoft_locale");
+  for (const host of [
+    "progmasoft.com",
+    "account.progmasoft.com",
+    "viget.progmasoft.com",
+  ]) {
+    assert.equal(localeCookieOptions(host, true).domain, ".progmasoft.com");
+  }
+  for (const host of [
+    "localhost",
+    "viget.localhost",
+    "notprogmasoft.com",
+    "progmasoft.com.example",
+    "",
+  ]) {
+    assert.equal(localeCookieOptions(host, false).domain, undefined, host);
+  }
+});
+
+test("the language cookie is unreadable by scripts and secure only over TLS", () => {
+  const overTls = localeCookieOptions("progmasoft.com", true);
+  assert.equal(overTls.httpOnly, true);
+  assert.equal(overTls.sameSite, "lax");
+  assert.equal(overTls.secure, true);
+  assert.equal(overTls.maxAge, 60 * 60 * 24 * 365);
+  assert.equal(localeCookieOptions("localhost", false).secure, false);
+});
+
+test("the request host prefers the forwarded host and drops port and case", () => {
+  assert.equal(
+    requestHost("Account.Progmasoft.com", "127.0.0.1:3010"),
+    "account.progmasoft.com",
+  );
+  assert.equal(requestHost(null, "viget.localhost:3000"), "viget.localhost");
+  assert.equal(requestHost(null, null), "");
+});
+
+// The shape of a message tree: object keys, array lengths and leaf types,
+// without the text itself.
+function shapeOf(value) {
+  if (Array.isArray(value)) {
+    return value.map(shapeOf);
+  }
+  if (value !== null && typeof value === "object") {
+    return Object.fromEntries(
+      Object.keys(value)
+        .sort()
+        .map((key) => [key, shapeOf(value[key])]),
+    );
+  }
+  return typeof value;
+}
+
+function leavesOf(value) {
+  if (Array.isArray(value)) {
+    return value.flatMap(leavesOf);
+  }
+  if (value !== null && typeof value === "object") {
+    return Object.values(value).flatMap(leavesOf);
+  }
+  return [value];
+}
+
+test("every locale has exactly the messages of the default locale", () => {
+  const reference = shapeOf(messages["en-US"]);
+  for (const locale of supportedLocales) {
+    assert.deepEqual(shapeOf(messages[locale]), reference, locale);
+    for (const text of leavesOf(messages[locale])) {
+      assert.equal(typeof text, "string", locale);
+      assert.notEqual(text.trim(), "", `${locale} has an empty message`);
+    }
+  }
+});
+
+test("every locale has a name in its own language for the language menu", () => {
+  assert.deepEqual(Object.keys(localeNames), [...supportedLocales]);
+  assert.equal(localeNames["ru-RU"], "Русский");
+  assert.equal(
+    new Set(Object.values(localeNames)).size,
+    supportedLocales.length,
+  );
+});
+
+test("the Russian messages are written in Cyrillic", () => {
+  const russian = messages["ru-RU"];
+  for (const text of [
+    russian.navigation.language,
+    russian.home.heroTitleStart,
+    russian.auth.signIn,
+    russian.viget.emptyTitle,
+  ]) {
+    assert.match(text, /[А-Яа-яЁё]/);
+  }
+  assert.notEqual(russian.auth.signIn, messages["en-US"].auth.signIn);
+});