`;
+ const form = find("#email-form", area);
+ find("#email-message", area).textContent = emailMessage
+ ? t(emailMessage)
+ : "";
+ if (emailStep === "address") {
+ const input = find("#email-input", area);
+ input.value = emailAddress;
+ input.addEventListener("input", () => (emailAddress = input.value));
+ } else {
+ find("#email-sent", area).textContent = t("emailCodeSent").replace(
+ "{address}",
+ emailAddress.trim().toLowerCase(),
+ );
+ const input = find("#code-input", area);
+ input.value = emailCode;
+ input.addEventListener("input", () => {
+ input.value = input.value.replace(/\D/g, "").slice(0, 8);
+ emailCode = input.value;
+ });
+ find("#resend", area).addEventListener("click", () => submitEmail(true));
+ find("#change-email", area).addEventListener("click", () => {
+ emailStep = "address";
+ emailCode = "";
+ emailMessage = null;
+ emailField = null;
+ resendUntil = 0;
+ renderEmail();
+ find("#email-input").focus();
+ });
+ tickResend();
+ if (resendUntil > Date.now()) resendTimer = setInterval(tickResend, 1000);
+ }
+ form.addEventListener("submit", (event) => {
+ event.preventDefault();
+ if (emailBusy === "idle")
+ void (emailStep === "address" ? submitEmail(false) : submitCode());
+ });
+}
+function focusEmailField() {
+ document
+ .querySelector(
+ emailStep === "address" ? "#email-input" : "#code-input",
+ )
+ ?.focus();
+}
+async function submitEmail(resend: boolean) {
+ if (emailBusy !== "idle") return;
+ const address = emailAddress.trim();
+ if (!looksLikeEmail(address)) {
+ emailMessage = "emailInvalid";
+ emailField = "address";
+ renderEmail();
+ focusEmailField();
+ return;
+ }
+ emailAddress = address;
+ emailBusy = "sending";
+ emailMessage = null;
+ emailField = null;
+ renderEmail();
+ try {
+ const result = await requestEmailCode(address, language, {
+ signal: AbortSignal.timeout(30000),
+ });
+ emailStep = "code";
+ emailCode = "";
+ resendUntil = Date.now() + result.resendAfter * 1000;
+ emailMessage = resend ? "emailResent" : null;
+ emailField = null;
+ emailBusy = "idle";
+ renderEmail();
+ focusEmailField();
+ } catch (error) {
+ emailBusy = "idle";
+ emailMessage = emailFailure(error, "emailInvalid");
+ emailField = emailMessage === "emailInvalid" ? "address" : null;
+ // A failed resend keeps the code step; the old code stays usable until it expires.
+ renderEmail();
+ if (emailStep === "address") focusEmailField();
+ }
+}
+async function submitCode() {
+ if (emailBusy !== "idle") return;
+ if (!/^[0-9]{8}$/.test(emailCode)) {
+ emailMessage = "emailCodeShape";
+ emailField = "code";
+ renderEmail();
+ focusEmailField();
+ return;
+ }
+ emailBusy = "verifying";
+ emailMessage = null;
+ emailField = null;
+ renderEmail();
+ try {
+ currentSession = await verifyEmailCode(emailAddress, emailCode, {
+ signal: AbortSignal.timeout(30000),
+ });
+ emailStep = "address";
+ emailAddress = "";
+ emailCode = "";
+ emailBusy = "idle";
+ emailMessage = null;
+ logoutState = "idle";
+ renderAccount();
+ } catch (error) {
+ emailBusy = "idle";
+ emailCode = "";
+ emailMessage = emailFailure(error, "emailInvalidCode");
+ emailField = emailMessage === "emailInvalidCode" ? "code" : null;
+ renderEmail();
+ focusEmailField();
+ }
}
async function logout() {
if (!currentSession?.authenticated || logoutState === "pending") return;
@@ -247,6 +696,8 @@ async function logout() {
});
currentSession = { authenticated: false };
logoutState = "idle";
+ closeAvatarEditor();
+ avatarMessage = null;
renderAccount();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
@@ -290,11 +741,13 @@ async function refresh() {
if (controller !== currentController) return;
if (!isInfo(value)) throw new Error("invalid_info");
githubEnabled = value.capabilities.github_auth === "enabled";
+ emailEnabled = value.capabilities.email_auth === "enabled";
infoState = "ready";
})
.catch(() => {
if (!currentController.signal.aborted) {
githubEnabled = false;
+ emailEnabled = false;
infoState = "error";
}
})
diff --git a/src/crop.ts b/src/crop.ts
new file mode 100644
index 0000000..022ab89
--- /dev/null
+++ b/src/crop.ts
@@ -0,0 +1,56 @@
+/** Square crop geometry for the avatar editor. Pure, so it can be tested without a browser. */
+export interface CropState {
+ /** Source image size. */
+ width: number;
+ height: number;
+ /** Zoom from 1 (image fills the square) up to MAX_ZOOM. */
+ zoom: number;
+ /** Image point shown in the middle of the square. */
+ x: number;
+ y: number;
+}
+export const MAX_ZOOM = 4;
+export const OUTPUT_SIDE = 256;
+
+export function initialCrop(width: number, height: number): CropState {
+ return { width, height, zoom: 1, x: width / 2, y: height / 2 };
+}
+/** Side of the source area that is visible, in source pixels. */
+export function visibleSide(state: CropState): number {
+ return Math.min(state.width, state.height) / state.zoom;
+}
+/** Keeps the zoom in range and the visible area inside the image: no empty edges. */
+export function clampCrop(state: CropState): CropState {
+ const zoom = Math.min(MAX_ZOOM, Math.max(1, state.zoom));
+ const half = visibleSide({ ...state, zoom }) / 2;
+ return {
+ ...state,
+ zoom,
+ x: Math.min(state.width - half, Math.max(half, state.x)),
+ y: Math.min(state.height - half, Math.max(half, state.y)),
+ };
+}
+/** Source rectangle (sx, sy, side) to draw into the square. */
+export function sourceRect(state: CropState) {
+ const clamped = clampCrop(state);
+ const side = visibleSide(clamped);
+ return { sx: clamped.x - side / 2, sy: clamped.y - side / 2, side };
+}
+/** Moves the image by a pointer or key delta given in on-screen pixels of a `view`-pixel square. */
+export function panBy(
+ state: CropState,
+ dx: number,
+ dy: number,
+ view: number,
+): CropState {
+ const perPixel = visibleSide(state) / view;
+ return clampCrop({
+ ...state,
+ x: state.x - dx * perPixel,
+ y: state.y - dy * perPixel,
+ });
+}
+/** Changes the zoom keeping the same centre. */
+export function zoomTo(state: CropState, zoom: number): CropState {
+ return clampCrop({ ...state, zoom });
+}
diff --git a/src/i18n/en.ts b/src/i18n/en.ts
index 0d32230..6798b07 100644
--- a/src/i18n/en.ts
+++ b/src/i18n/en.ts
@@ -53,7 +53,7 @@ export const en = {
"The gateway (TCP) handles chat, guilds and roles, and the voice node (UDP) relays audio. There is also a combined daemon that runs both.",
projectCentral: "Vnox Central",
projectCentralText:
- "A web account with GitHub sign-in. It is not linked to the desktop client key yet.",
+ "A web account with GitHub or email sign-in. It is not linked to the desktop client key yet.",
privacyLink: "Privacy",
privacyTitle: "Privacy policy",
privacyUpdated: "Updated 24 October 2026",
@@ -61,19 +61,19 @@ export const en = {
"This policy covers the website and Vnox Central. Chats on community servers and the desktop client are not part of it, see below.",
privacyCollectTitle: "What we receive",
privacyCollectText:
- "When you sign in with GitHub we store the numeric ID, username, display name and avatar link from your public profile. We do not ask for repository access or your private email. The GitHub token is used once to read the profile and is discarded right away.",
+ "When you sign in with GitHub we store the numeric ID, username, display name and avatar link from your public profile. We do not ask for repository access or your private email. The GitHub token is used once to read the profile and is discarded right away. When you sign in by email we store your address, converted to lowercase, as the sign-in identifier and use it only to send the code. The code itself is not stored as plain text but as an HMAC with a server secret, is valid for 10 minutes and is deleted once used. To fight abuse we keep, for about an hour, only HMAC fingerprints of the address and of the network the request came from, not the values themselves. If you upload a photo, we store it as a 256 by 256 PNG that we re-encode ourselves, so EXIF data and location from the original are gone. We keep one photo per account and not the original file.",
privacyCookiesTitle: "Cookies",
privacyCookiesText:
- "Only the necessary ones: a short sign-in cookie (10 minutes) and a session cookie (7 days). Both are Secure and HttpOnly, and the database stores only a hash of the session. Signing out ends the session.",
+ "Only the necessary ones: a short sign-in cookie for GitHub or email sign-in (10 minutes) and a session cookie (7 days). Both are Secure and HttpOnly, and the database stores only a hash of the session. Signing out ends the session.",
privacyTrackTitle: "Tracking and third parties",
privacyTrackText:
- "The website has no analytics, ads or third-party scripts. Your language choice is kept in your browser. The avatar loads from avatars.githubusercontent.com, so GitHub sees your IP address. Sign-in requests are not written to the web server logs.",
+ "The website has no analytics, ads or third-party scripts. Your language choice is kept in your browser. A GitHub avatar loads from avatars.githubusercontent.com, so GitHub sees your IP address. Your own photo loads from our server. Sign-in requests are not written to the web server logs. The code email goes out through an SMTP mail service, so that service sees your address and the text of the message.",
privacyOtherTitle: "Community servers and the client",
privacyOtherText:
"VNOX servers are run by their owners. Messages and files on a server are held by its owner, who sets the retention rules. The desktop client keeps your key and settings on your device.",
privacyDeleteTitle: "Deleting your data",
privacyDeleteText:
- "There is no delete button yet. To remove your data, open an issue in the server repository and we will delete your record.",
+ "Press Remove photo on the account page and your photo is deleted; it is also deleted together with the rest of your data. There is no button to delete the whole account yet: to remove your data, open an issue in the server repository and we will delete your record. Deleted data can stay in database backups for up to 30 days.",
lightTitle: "A light client",
lightText:
"The Rust and Slint client does not carry a browser with it. It uses about 120 MB of memory when idle.",
@@ -108,7 +108,8 @@ export const en = {
availableOne: "Client, text channels and voice",
availableTwo: "Direct messages, friends, guilds and roles",
availableThree: "Voice encryption (ChaCha20-Poly1305) and key-based sign-in",
- availableFour: "Web account through GitHub, site in Russian and English",
+ availableFour:
+ "Web account (GitHub or an emailed code), site in Russian and English",
availableFive: "Incoming and signed outgoing webhooks on the server",
nextOne: "Webhook management in the client",
nextTwo: "Screen sharing with separate audio",
@@ -121,7 +122,7 @@ export const en = {
"No. The gateway and the voice node can run as one daemon (serverd).",
faqCentral: "What is Vnox Central for?",
faqCentralAnswer:
- "It is a web account with GitHub sign-in. A community server runs on its own and does not depend on Central.",
+ "It is a web account with GitHub or email sign-in. A community server runs on its own and does not depend on Central.",
faqRelease: "Where can I download the client?",
faqReleaseAnswer:
"Nowhere yet. The client and server sources are open, and build instructions are in their repositories.",
@@ -133,7 +134,7 @@ export const en = {
back: "Back to home",
accountHeading: "Your Vnox Central account",
accountIntro:
- "For now you can sign in with GitHub. There is nothing else to do with the account yet.",
+ "You can sign in with GitHub or with a code sent by email. There is nothing else to do with the account yet.",
loginTitle: "Continue with GitHub",
loginText:
"VNOX gets your public GitHub profile. It does not ask for access to your repositories.",
@@ -141,15 +142,15 @@ export const en = {
loginLoading: "Checking sign-in availability…",
loginDisabled: "GitHub sign-in is turned off on the server.",
loginUnavailable: "Could not check sign-in availability. Try again.",
- privacy: "You sign in on github.com. Your GitHub password stays with GitHub.",
+ privacy:
+ "GitHub sign-in happens on github.com. Your GitHub password stays with GitHub.",
accountStage:
"The account is not linked to the desktop client keys yet. Friends, servers and messages will be added later.",
sessionLoading: "Loading your account…",
profileTitle: "You are signed in",
- profileIntro: "Signed in with GitHub. This is your VNOX Central account.",
+ profileIntro: "You are signed in. This is your VNOX Central account.",
handle: "Account handle",
userId: "Account ID",
- provider: "Signed in with",
logout: "Sign out",
loggingOut: "Signing out…",
logoutError: "Could not sign out. Try again.",
@@ -160,5 +161,49 @@ export const en = {
copy: "Copy account ID",
copied: "Account ID copied",
copyError: "Could not copy the ID. Select it manually.",
+ avatarTitle: "Profile photo",
+ avatarHint:
+ "PNG, JPEG or WebP, up to 10 MB. We crop it to a square and keep it at 256 by 256 pixels.",
+ avatarUpload: "Upload photo",
+ avatarRemove: "Remove photo",
+ avatarRemoving: "Removing…",
+ avatarEditorTitle: "Choose the crop",
+ avatarCropLabel: "Photo crop",
+ avatarCropHelp:
+ "Drag the photo or move it with the arrow keys. The plus and minus keys, the wheel and the slider change the zoom.",
+ avatarZoom: "Zoom",
+ avatarReset: "Reset",
+ avatarCancel: "Cancel",
+ avatarSave: "Save",
+ avatarSaving: "Saving…",
+ avatarSaved: "Photo updated.",
+ avatarRemoved: "Photo removed.",
+ avatarTooBig: "The file is too large. Choose a photo under 10 MB.",
+ avatarBadType: "Only PNG, JPEG and WebP files work.",
+ avatarBadImage: "Could not open this image. Choose another photo.",
+ avatarLimit: "Too many changes. Wait a little and try again.",
+ avatarFailed: "Could not save the photo. Try again in a moment.",
+ emailOr: "or",
+ emailTitle: "Sign in with email",
+ emailText:
+ "We send an 8-digit code to your address. No password needed. If there is no account yet, it is created once you enter the code.",
+ emailLabel: "Email address",
+ emailSend: "Send code",
+ emailSending: "Sending…",
+ emailCodeSent:
+ "We sent a code to {address}. It is valid for 10 minutes. If the message is missing, check your spam folder.",
+ codeLabel: "Code from the email",
+ codeVerify: "Sign in",
+ codeVerifying: "Checking…",
+ emailResend: "Send the code again",
+ emailResendIn: "Send again in {seconds} s",
+ emailResent: "A new code is on its way. The old one no longer works.",
+ emailChange: "Use another address",
+ emailInvalid: "Check the address. It should look like name@example.com.",
+ emailCodeShape: "Enter the 8 digits from the email.",
+ emailInvalidCode:
+ "The code is wrong or expired. Check the digits or ask for a new one.",
+ emailTooMany: "Too many requests. Wait a little and try again.",
+ emailFailed: "That did not work. Try again in a moment.",
} as const;
export type Catalog = Record;
diff --git a/src/i18n/ru.ts b/src/i18n/ru.ts
index 09132a4..bdd8d63 100644
--- a/src/i18n/ru.ts
+++ b/src/i18n/ru.ts
@@ -55,7 +55,7 @@ export const ru: Catalog = {
"Шлюз (TCP) отвечает за чат, гильдии и роли, голосовой узел (UDP) пересылает звук. Есть и общий демон для обоих.",
projectCentral: "Vnox Central",
projectCentralText:
- "Веб-аккаунт с входом через GitHub. С ключом настольного клиента он пока не связан.",
+ "Веб-аккаунт с входом через GitHub или по почте. С ключом настольного клиента он пока не связан.",
privacyLink: "Конфиденциальность",
privacyTitle: "Политика конфиденциальности",
privacyUpdated: "Обновлено 24 октября 2026",
@@ -63,19 +63,19 @@ export const ru: Catalog = {
"Это политика сайта и Vnox Central. Чаты на серверах сообществ и настольный клиент сюда не входят, о них ниже.",
privacyCollectTitle: "Что мы получаем",
privacyCollectText:
- "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется.",
+ "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений. Если вы загружаете фото, мы сохраняем его как PNG 256 на 256, который сами перекодируем, поэтому EXIF и геометки из оригинала в нём нет. Хранится одно фото на аккаунт, исходный файл не сохраняется.",
privacyCookiesTitle: "Cookie",
privacyCookiesText:
- "Только необходимые: короткий cookie на время входа (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.",
+ "Только необходимые: короткий cookie на время входа через GitHub или по почте (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.",
privacyTrackTitle: "Слежка и сторонние сервисы",
privacyTrackText:
- "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Запросы входа не попадают в журналы веб-сервера.",
+ "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар GitHub загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Ваше собственное фото загружается с нашего сервера. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.",
privacyOtherTitle: "Серверы сообществ и клиент",
privacyOtherText:
"Серверы VNOX ведут сами владельцы. Сообщения и файлы на сервере находятся у его владельца, и правила хранения задаёт он. Настольный клиент хранит ваш ключ и настройки на вашем устройстве.",
privacyDeleteTitle: "Удаление данных",
privacyDeleteText:
- "Кнопки удаления аккаунта пока нет. Чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись.",
+ "Нажмите «Убрать фото» на странице аккаунта, и фото будет удалено; оно также удаляется вместе с остальными данными. Кнопки удаления всего аккаунта пока нет: чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись. Удалённые данные могут оставаться в резервных копиях базы до 30 дней.",
lightTitle: "Лёгкий клиент",
lightText:
"Клиент на Rust и Slint не носит с собой браузер. В простое он занимает около 120 МБ памяти.",
@@ -109,7 +109,8 @@ export const ru: Catalog = {
availableOne: "Клиент, текстовые каналы и голос",
availableTwo: "Личные сообщения, друзья, гильдии и роли",
availableThree: "Шифрование голоса (ChaCha20-Poly1305) и вход по ключу",
- availableFour: "Веб-аккаунт через GitHub, сайт на русском и английском",
+ availableFour:
+ "Веб-аккаунт (GitHub или код на почту), сайт на русском и английском",
availableFive: "Входящие и подписанные исходящие вебхуки на сервере",
nextOne: "Управление вебхуками в клиенте",
nextTwo: "Трансляция экрана с отдельным звуком",
@@ -122,7 +123,7 @@ export const ru: Catalog = {
"Нет. Шлюз и голосовой узел можно запустить одним демоном (serverd).",
faqCentral: "Зачем нужен Vnox Central?",
faqCentralAnswer:
- "Это веб-аккаунт с входом через GitHub. Сервер сообщества работает отдельно и от Central не зависит.",
+ "Это веб-аккаунт с входом через GitHub или по почте. Сервер сообщества работает отдельно и от Central не зависит.",
faqRelease: "Где скачать клиент?",
faqReleaseAnswer:
"Пока нигде. Исходники клиента и сервера открыты, инструкции по сборке лежат в их репозиториях.",
@@ -134,7 +135,7 @@ export const ru: Catalog = {
back: "На главную",
accountHeading: "Аккаунт Vnox Central",
accountIntro:
- "Пока можно войти через GitHub. Больше с аккаунтом ничего не сделать.",
+ "Войти можно через GitHub или по коду из письма. Больше с аккаунтом пока ничего не сделать.",
loginTitle: "Продолжить с GitHub",
loginText:
"VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям не запрашивается.",
@@ -143,15 +144,15 @@ export const ru: Catalog = {
loginDisabled: "Вход через GitHub на сервере пока выключен.",
loginUnavailable:
"Не удалось проверить доступность входа. Повторите попытку.",
- privacy: "Вход проходит на github.com. Пароль от GitHub остаётся у GitHub.",
+ privacy:
+ "Вход через GitHub проходит на github.com. Пароль от GitHub остаётся у GitHub.",
accountStage:
"Аккаунт пока не связан с ключами настольного клиента. Друзья, серверы и сообщения в нём появятся позже.",
sessionLoading: "Загружаем аккаунт…",
profileTitle: "Вы вошли",
- profileIntro: "Вход через GitHub выполнен. Это ваш аккаунт VNOX Central.",
+ profileIntro: "Вход выполнен. Это ваш аккаунт VNOX Central.",
handle: "Имя аккаунта",
userId: "ID аккаунта",
- provider: "Способ входа",
logout: "Выйти из аккаунта",
loggingOut: "Выходим…",
logoutError: "Не удалось выйти. Повторите попытку.",
@@ -162,4 +163,48 @@ export const ru: Catalog = {
copy: "Скопировать ID",
copied: "ID скопирован",
copyError: "Не удалось скопировать ID. Выделите его вручную.",
+ avatarTitle: "Фото профиля",
+ avatarHint:
+ "PNG, JPEG или WebP, до 10 МБ. Мы обрежем его до квадрата и сохраним размером 256 на 256 пикселей.",
+ avatarUpload: "Загрузить фото",
+ avatarRemove: "Убрать фото",
+ avatarRemoving: "Убираем…",
+ avatarEditorTitle: "Выберите кадр",
+ avatarCropLabel: "Кадр фото",
+ avatarCropHelp:
+ "Перетащите фото или двигайте его стрелками. Клавиши плюс и минус, колесо мыши и ползунок меняют масштаб.",
+ avatarZoom: "Масштаб",
+ avatarReset: "Сбросить",
+ avatarCancel: "Отмена",
+ avatarSave: "Сохранить",
+ avatarSaving: "Сохраняем…",
+ avatarSaved: "Фото обновлено.",
+ avatarRemoved: "Фото убрано.",
+ avatarTooBig: "Файл слишком большой. Выберите фото до 10 МБ.",
+ avatarBadType: "Подойдут только файлы PNG, JPEG и WebP.",
+ avatarBadImage: "Не удалось открыть это изображение. Выберите другое фото.",
+ avatarLimit: "Слишком много изменений. Подождите немного и повторите.",
+ avatarFailed: "Не удалось сохранить фото. Повторите попытку чуть позже.",
+ emailOr: "или",
+ emailTitle: "Войти по почте",
+ emailText:
+ "Пришлём на адрес код из 8 цифр. Пароль не нужен. Если аккаунта нет, он создастся после ввода кода.",
+ emailLabel: "Электронная почта",
+ emailSend: "Получить код",
+ emailSending: "Отправляем…",
+ emailCodeSent:
+ "Мы отправили код на адрес {address}. Он действует 10 минут. Если письма нет, загляните в папку «Спам».",
+ codeLabel: "Код из письма",
+ codeVerify: "Войти",
+ codeVerifying: "Проверяем…",
+ emailResend: "Отправить код ещё раз",
+ emailResendIn: "Отправить ещё раз через {seconds} с",
+ emailResent: "Новый код отправлен. Старый больше не подойдёт.",
+ emailChange: "Другой адрес",
+ emailInvalid: "Проверьте адрес. Он должен быть вида name@example.com.",
+ emailCodeShape: "Введите 8 цифр из письма.",
+ emailInvalidCode:
+ "Код не подошёл или устарел. Проверьте цифры или запросите новый.",
+ emailTooMany: "Слишком много запросов. Подождите немного и повторите.",
+ emailFailed: "Не получилось. Повторите попытку чуть позже.",
};
diff --git a/src/styles.css b/src/styles.css
index 67566a0..280f2e4 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -970,6 +970,70 @@ p {
margin-top: 14px !important;
overflow-wrap: anywhere;
}
+.login-divider {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ margin: 28px 0 22px;
+ color: var(--muted);
+ font-size: 0.78rem;
+}
+.login-divider::before,
+.login-divider::after {
+ content: "";
+ flex: 1;
+ border-top: 1px solid #ffffff12;
+}
+.email-form h3 {
+ font-size: 1.15rem;
+ letter-spacing: -0.02em;
+}
+.email-form p {
+ font-size: 0.85rem;
+ margin-top: 10px;
+}
+.email-form label {
+ display: block;
+ margin: 18px 0 8px;
+ font-size: 0.78rem;
+ color: #c5c0b8;
+}
+.field {
+ width: 100%;
+ min-height: 48px;
+ padding: 11px 14px;
+ background: #1b1b1d;
+ color: var(--ink);
+ border: 1px solid #4d4b47;
+ border-radius: 7px;
+ font-size: 1rem;
+ font-family: inherit;
+}
+.field:focus-visible {
+ outline: 2px solid var(--sand);
+ outline-offset: 2px;
+}
+.field[aria-invalid="true"] {
+ border-color: #d2b7a5;
+}
+.code-field {
+ font-variant-numeric: tabular-nums;
+ letter-spacing: 0.2em;
+}
+.email-form .button {
+ width: 100%;
+ margin-top: 14px;
+}
+.email-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 22px;
+ margin-top: 14px;
+}
+.email-actions .text-button:disabled {
+ cursor: default;
+ text-decoration: none;
+}
.privacy-note {
display: flex;
gap: 10px;
@@ -2105,3 +2169,73 @@ p {
.privacy-block p {
margin-top: 10px;
}
+
+/* Avatar editor */
+.avatar-block {
+ margin: 0 0 25px;
+ padding-top: 22px;
+ border-top: 1px solid #ffffff0c;
+}
+.avatar-block h3 {
+ font-size: 1rem;
+ margin-bottom: 8px;
+}
+.avatar-block .small {
+ margin-bottom: 14px;
+}
+.avatar-actions {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+.avatar-actions .button {
+ padding: 11px 13px;
+ min-height: 43px;
+ font-size: 0.76rem;
+}
+.avatar-block .form-message {
+ margin-top: 10px !important;
+}
+.avatar-editor {
+ margin-top: 16px;
+ display: grid;
+ gap: 14px;
+ justify-items: start;
+}
+.avatar-editor h4 {
+ font-size: 0.9rem;
+}
+.avatar-canvas {
+ width: 280px;
+ max-width: 100%;
+ height: auto;
+ aspect-ratio: 1;
+ border-radius: 50%;
+ background: #1a1a1b;
+ border: 1px solid #44413c;
+ cursor: grab;
+ touch-action: none;
+}
+.avatar-canvas.dragging {
+ cursor: grabbing;
+}
+.avatar-canvas.disabled {
+ opacity: 0.6;
+ cursor: default;
+}
+.avatar-canvas:focus-visible,
+.avatar-zoom input:focus-visible {
+ outline: 2px solid var(--sand);
+ outline-offset: 3px;
+}
+.avatar-zoom {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ font-size: 0.78rem;
+ max-width: 100%;
+}
+.avatar-zoom input {
+ width: 180px;
+ max-width: 55vw;
+}
diff --git a/tests/api.test.ts b/tests/api.test.ts
index d0ef16e..a5af93b 100644
--- a/tests/api.test.ts
+++ b/tests/api.test.ts
@@ -1,6 +1,16 @@
import { test } from "bun:test";
import assert from "node:assert/strict";
-import { request, isSession, isInfo, safeAvatar, ApiError } from "../src/api";
+import {
+ request,
+ isSession,
+ isInfo,
+ safeAvatar,
+ ApiError,
+ requestEmailCode,
+ verifyEmailCode,
+ uploadAvatar,
+ removeAvatar,
+} from "../src/api";
import { messages, detectLanguage } from "../src/i18n";
test("catalogs match and never silently fall back to a missing translation", () => {
@@ -105,3 +115,130 @@ test("Hub capabilities reject malformed JSON before enabling sign-in", () => {
assert.equal(isInfo(value), false);
}
});
+
+test("email_auth capability must be a string when present", () => {
+ assert.ok(
+ isInfo({ capabilities: { github_auth: "enabled", email_auth: "enabled" } }),
+ );
+ assert.ok(isInfo({ capabilities: { github_auth: "enabled" } }));
+ assert.equal(
+ isInfo({ capabilities: { github_auth: "enabled", email_auth: true } }),
+ false,
+ );
+});
+test("email code requests send JSON same-origin and bound the resend delay", async () => {
+ let seen: { path: string; init: RequestInit } | undefined;
+ const result = await requestEmailCode("a@example.com", "en", {
+ fetcher: async (path, init) => {
+ seen = { path, init };
+ return Response.json({ resend_after: 999999 }, { status: 202 });
+ },
+ });
+ assert.equal(result.resendAfter, 60);
+ assert.ok(seen);
+ assert.equal(seen.path, "/v1/auth/email/start");
+ assert.equal(seen.init.method, "POST");
+ assert.equal(seen.init.credentials, "same-origin");
+ assert.equal(
+ new Headers(seen.init.headers).get("Content-Type"),
+ "application/json",
+ );
+ assert.deepEqual(JSON.parse(String(seen.init.body)), {
+ email: "a@example.com",
+ lang: "en",
+ });
+ const short = await requestEmailCode("a@example.com", "ru", {
+ fetcher: async () => Response.json({ resend_after: 30 }, { status: 202 }),
+ });
+ assert.equal(short.resendAfter, 30);
+});
+test("email verification accepts only an authenticated session and keeps the status", async () => {
+ const session = {
+ authenticated: true,
+ csrf_token: "fixture",
+ user: { user_id: "u", handle: "h", display_name: "n" },
+ };
+ const ok = await verifyEmailCode("a@example.com", "12345678", {
+ fetcher: async () => Response.json(session),
+ });
+ assert.equal(ok.authenticated, true);
+ await assert.rejects(
+ verifyEmailCode("a@example.com", "12345678", {
+ fetcher: async () => Response.json({ authenticated: false }),
+ }),
+ );
+ await assert.rejects(
+ verifyEmailCode("a@example.com", "12345678", {
+ fetcher: async () =>
+ Response.json({ error: "invalid_code" }, { status: 400 }),
+ }),
+ (error: unknown) => error instanceof ApiError && error.status === 400,
+ );
+});
+test("own avatars are same-origin content-hash paths only", () => {
+ const own = `/v1/avatars/${"a1".repeat(32)}`;
+ assert.equal(safeAvatar(own), own);
+ for (const value of [
+ "/v1/avatars/abc",
+ `/v1/avatars/${"A".repeat(64)}`,
+ `/v1/avatars/${"a".repeat(64)}/x`,
+ `//evil.example/v1/avatars/${"a".repeat(64)}`,
+ `https://evil.example/v1/avatars/${"a".repeat(64)}`,
+ "/v1/auth/session",
+ ])
+ assert.equal(safeAvatar(value), null);
+});
+test("avatar upload sends the PNG with CSRF and keeps the Hub error code", async () => {
+ const own = `/v1/avatars/${"b2".repeat(32)}`;
+ let seen: { path: string; init: RequestInit } | undefined;
+ const png = new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" });
+ const url = await uploadAvatar(png, "csrf-fixture", {
+ fetcher: async (path, init) => {
+ seen = { path, init };
+ return Response.json({ avatar_url: own });
+ },
+ });
+ assert.equal(url, own);
+ assert.ok(seen);
+ assert.equal(seen.path, "/v1/account/avatar");
+ assert.equal(seen.init.method, "POST");
+ assert.equal(seen.init.credentials, "same-origin");
+ assert.equal(seen.init.body, png);
+ const headers = new Headers(seen.init.headers);
+ assert.equal(headers.get("Content-Type"), "image/png");
+ assert.equal(headers.get("X-CSRF-Token"), "csrf-fixture");
+ await assert.rejects(
+ uploadAvatar(png, "c", {
+ fetcher: async () =>
+ Response.json({ error: "too_large" }, { status: 413 }),
+ }),
+ (error: unknown) =>
+ error instanceof ApiError &&
+ error.status === 413 &&
+ error.detail === "too_large",
+ );
+ await assert.rejects(
+ uploadAvatar(png, "c", {
+ fetcher: async () =>
+ Response.json({ avatar_url: "https://evil.example/x" }),
+ }),
+ );
+});
+test("avatar removal returns the provider avatar only when it is a safe URL", async () => {
+ const github = "https://avatars.githubusercontent.com/u/1?v=4";
+ let method = "";
+ const result = await removeAvatar("c", {
+ fetcher: async (_path, init) => {
+ method = String(init.method);
+ return Response.json({ avatar_url: github });
+ },
+ });
+ assert.equal(method, "DELETE");
+ assert.equal(result, github);
+ assert.equal(
+ await removeAvatar("c", {
+ fetcher: async () => Response.json({ avatar_url: "javascript:alert(1)" }),
+ }),
+ null,
+ );
+});
diff --git a/tests/browser_qa.py b/tests/browser_qa.py
index 50616f1..da7bd03 100644
--- a/tests/browser_qa.py
+++ b/tests/browser_qa.py
@@ -3,6 +3,8 @@ Run with an already running npm run dev/preview. All API responses are test fixt
"""
import argparse
import json
+import struct
+import zlib
from pathlib import Path
from urllib.parse import urlparse
from playwright.sync_api import sync_playwright
@@ -16,15 +18,48 @@ if urlparse(args.url).hostname not in {'127.0.0.1', 'localhost', '::1'}:
artifacts = Path(args.artifacts)
artifacts.mkdir(parents=True, exist_ok=True)
+def make_png(width, height):
+ rows = b''.join(b'\x00' + bytes(v for x in range(width) for v in ((x * 255 // width), (y * 255 // height), 128)) for y in range(height))
+ def chunk(kind, data):
+ body = kind + data
+ return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
+ return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'')
+
+PHOTO = make_png(600, 400)
+OWN_AVATAR = '/v1/avatars/' + 'ab' * 32
+
with sync_playwright() as p:
browser = p.chromium.launch(executable_path='/usr/bin/chromium', headless=True, args=['--no-sandbox'])
context = browser.new_context(viewport={'width': 1440, 'height': 1000}, locale='ru-RU')
+ mail = {'starts': [], 'verifies': [], 'start_status': 202, 'verify_status': 400, 'good_code': '12345678'}
state = {'info': {'capabilities': {'github_auth': 'enabled'}}, 'session': {'authenticated': False}, 'info_status': 200, 'session_status': 200, 'logout_status': 204}
logouts = []
+ avatar = {'status': 200, 'uploads': [], 'deletes': []}
def api(route):
path = urlparse(route.request.url).path
if path == '/v1/info': route.fulfill(status=state['info_status'], json=state['info'])
elif path == '/v1/auth/session': route.fulfill(status=state['session_status'], json=state['session'])
+ elif path == '/v1/auth/email/start':
+ body = json.loads(route.request.post_data or '{}')
+ mail['starts'].append({'body': body, 'headers': route.request.all_headers()})
+ route.fulfill(status=mail['start_status'], json={'status': 'code_requested', 'expires_in': 600, 'resend_after': 3} if mail['start_status'] == 202 else {'error': 'try_later'})
+ elif path == '/v1/auth/email/verify':
+ body = json.loads(route.request.post_data or '{}')
+ mail['verifies'].append(body)
+ if body.get('code') == mail['good_code']:
+ state['session'] = {'authenticated': True, 'csrf_token': 'email-csrf', 'user': {'user_id': 'email-id', 'handle': 'u_emailfixture', 'display_name': 'Vnox user', 'avatar_url': None}}
+ route.fulfill(status=200, json=state['session'])
+ else: route.fulfill(status=mail['verify_status'], json={'error': 'invalid_code'})
+ elif path == '/v1/account/avatar':
+ record = {'method': route.request.method, 'headers': route.request.all_headers(), 'body': route.request.post_data_buffer}
+ if route.request.method == 'POST':
+ avatar['uploads'].append(record)
+ route.fulfill(status=avatar['status'], json={'avatar_url': OWN_AVATAR} if avatar['status'] == 200 else {'error': avatar['error']})
+ else:
+ avatar['deletes'].append(record)
+ route.fulfill(status=200, json={'avatar_url': None})
+ elif path == OWN_AVATAR:
+ route.fulfill(status=200, body=PHOTO, content_type='image/png')
elif path == '/v1/auth/logout':
logouts.append({'method': route.request.method, 'headers': route.request.all_headers()})
route.fulfill(status=state['logout_status'], body='' if state['logout_status'] == 204 else '{}')
@@ -77,6 +112,81 @@ with sync_playwright() as p:
page.reload()
page.locator('#login-availability').filter(has_text='выключен').wait_for()
assert page.locator('.github-login').get_attribute('href') is None
+ # Email sign-in: hidden unless Hub reports email_auth enabled.
+ assert page.locator('#email-form').count() == 0
+ state['info'] = {'capabilities': {'github_auth': 'enabled', 'email_auth': 'not_enabled'}}
+ page.reload()
+ page.locator('.github-login').wait_for()
+ page.wait_for_timeout(300)
+ assert page.locator('#email-form').count() == 0
+ state['info'] = {'capabilities': {'github_auth': 'enabled', 'email_auth': 'enabled'}}
+ page.reload()
+ page.locator('#email-input').wait_for()
+ page.screenshot(path=str(artifacts / 'account-email-address.png'), full_page=True)
+ # Invalid address is caught in the browser, with focus and aria state.
+ page.locator('#email-input').fill('not-an-address')
+ page.locator('#email-input').press('Enter')
+ page.locator('#email-message').filter(has_text='Проверьте адрес').wait_for()
+ assert page.locator('#email-input').get_attribute('aria-invalid') == 'true'
+ assert page.evaluate("document.activeElement.id") == 'email-input'
+ assert page.locator('#email-message').get_attribute('role') == 'status'
+ assert not mail['starts']
+ # Server-side rate limit and outage are reported without leaving the step.
+ mail['start_status'] = 429
+ page.locator('#email-input').fill(' Person@Example.com ')
+ page.locator('#email-submit').click()
+ page.locator('#email-message').filter(has_text='Слишком много').wait_for()
+ mail['start_status'] = 503
+ page.locator('#email-submit').click()
+ page.locator('#email-message').filter(has_text='Не получилось').wait_for()
+ mail['start_status'] = 202
+ page.locator('#email-input').press('Enter')
+ page.locator('#code-input').wait_for()
+ assert page.evaluate("document.activeElement.id") == 'code-input'
+ sent = mail['starts'][-1]
+ assert sent['body'] == {'email': 'Person@Example.com', 'lang': 'ru'}, sent['body']
+ assert sent['headers']['origin'] == args.url
+ assert sent['headers']['content-type'] == 'application/json'
+ assert page.locator('#email-sent').inner_text().count('person@example.com') == 1
+ page.screenshot(path=str(artifacts / 'account-email-code.png'), full_page=True)
+ # Resend is locked by the timer (3 s fixture), then works.
+ assert page.locator('#resend').is_disabled()
+ assert 'через' in page.locator('#resend').inner_text()
+ page.locator('#resend:not([disabled])').wait_for(timeout=6000)
+ page.locator('#resend').click()
+ page.locator('#email-message').filter(has_text='Новый код отправлен').wait_for()
+ assert len(mail['starts']) == 4
+ # Language switch keeps the step and the typed address, and relabels the form.
+ page.locator('#code-input').fill('12ab34')
+ assert page.locator('#code-input').input_value() == '1234'
+ page.locator('[data-language="en"]').click()
+ assert page.locator('label[for="code-input"]').inner_text() == 'Code from the email'
+ assert page.locator('#code-input').input_value() == '1234'
+ page.locator('[data-language="ru"]').click()
+ # Short code, wrong code, then the right one.
+ page.locator('#email-submit').click()
+ page.locator('#email-message').filter(has_text='8 цифр').wait_for()
+ page.locator('#code-input').fill('00000000')
+ page.locator('#email-submit').click()
+ page.locator('#email-message').filter(has_text='не подошёл').wait_for()
+ assert page.locator('#code-input').get_attribute('aria-invalid') == 'true'
+ assert page.locator('#code-input').input_value() == ''
+ page.locator('#change-email').click()
+ assert page.locator('#email-input').input_value() == 'Person@Example.com'
+ page.locator('#email-submit').click()
+ page.locator('#code-input').wait_for()
+ for width in [320, 390, 768, 1440]:
+ page.set_viewport_size({'width': width, 'height': 844})
+ assert not page.evaluate('document.documentElement.scrollWidth > innerWidth'), ('email', width)
+ page.set_viewport_size({'width': 1440, 'height': 1000})
+ page.locator('#code-input').fill('12345678')
+ page.locator('#code-input').press('Enter')
+ page.locator('#profile-id').wait_for()
+ assert mail['verifies'][-1] == {'email': 'Person@Example.com', 'code': '12345678'}
+ assert page.locator('#email-form').count() == 0
+ assert page.evaluate('Object.keys(localStorage)') == ['vnox-web-language']
+ state['session'] = {'authenticated': False}
+ state['info'] = {'capabilities': {'github_auth': 'enabled'}}
state['info_status'] = 503
page.reload()
page.locator('#retry-info:not([hidden])').wait_for()
@@ -98,6 +208,77 @@ with sync_playwright() as p:
page.locator('#profile-id').wait_for()
page.set_viewport_size({'width': 1440, 'height': 1000})
page.screenshot(path=str(artifacts / 'account-profile-desktop.png'))
+ # Own avatar: pick, crop with the keyboard, errors, upload, remove.
+ assert page.locator('#avatar-remove').is_hidden()
+ assert page.evaluate("[...document.querySelectorAll('[style]')].filter(e => e.getAttribute('style').trim() !== '').length") == 0
+ page.locator('#avatar-file').set_input_files(files=[{'name': 'note.txt', 'mimeType': 'text/plain', 'buffer': b'hello'}])
+ page.locator('#avatar-message').filter(has_text='Подойдут только').wait_for()
+ assert page.locator('#avatar-canvas').count() == 0
+ page.locator('#avatar-file').set_input_files(files=[{'name': 'big.png', 'mimeType': 'image/png', 'buffer': b'\x89PNG' + bytes(11 * 1024 * 1024)}])
+ page.locator('#avatar-message').filter(has_text='слишком большой').wait_for()
+ page.locator('#avatar-file').set_input_files(files=[{'name': 'broken.png', 'mimeType': 'image/png', 'buffer': b'\x89PNG\r\n\x1a\nnot really'}])
+ page.locator('#avatar-message').filter(has_text='Не удалось открыть').wait_for()
+ page.locator('#avatar-file').set_input_files(files=[{'name': 'photo.png', 'mimeType': 'image/png', 'buffer': PHOTO}])
+ page.locator('#avatar-canvas').wait_for()
+ assert page.evaluate("document.activeElement.id") == 'avatar-canvas'
+ assert page.locator('#avatar-canvas').get_attribute('aria-label') == 'Кадр фото'
+ assert page.locator('#avatar-zoom').input_value() == '100'
+ page.keyboard.press('+')
+ page.keyboard.press('+')
+ assert page.locator('#avatar-zoom').input_value() == '120'
+ page.keyboard.press('ArrowRight')
+ page.keyboard.press('Shift+ArrowDown')
+ box = page.locator('#avatar-canvas').bounding_box()
+ page.mouse.move(box['x'] + 100, box['y'] + 100)
+ page.mouse.down()
+ page.mouse.move(box['x'] + 140, box['y'] + 120, steps=4)
+ page.mouse.up()
+ page.locator('#avatar-zoom').fill('200')
+ assert page.locator('#avatar-zoom').input_value() == '200'
+ page.screenshot(path=str(artifacts / 'account-avatar-editor.png'), full_page=True)
+ page.locator('#avatar-reset').click()
+ assert page.locator('#avatar-zoom').input_value() == '100'
+ page.locator('[data-language="en"]').click()
+ assert page.locator('#avatar-canvas').get_attribute('aria-label') == 'Photo crop'
+ assert page.locator('#avatar-save').inner_text() == 'Save'
+ page.locator('[data-language="ru"]').click()
+ for width in [320, 390, 768, 1440]:
+ page.set_viewport_size({'width': width, 'height': 844})
+ assert not page.evaluate('document.documentElement.scrollWidth > innerWidth'), ('avatar editor', width)
+ page.set_viewport_size({'width': 1440, 'height': 1000})
+ assert page.evaluate("[...document.querySelectorAll('[style]')].filter(e => e.getAttribute('style').trim() !== '').length") == 0
+ for status, error, text in [(413, 'too_large', 'слишком большой'), (415, 'unsupported_type', 'Подойдут только'), (422, 'invalid_image', 'Не удалось открыть'), (429, 'try_later', 'Слишком много'), (503, 'try_later', 'Не удалось сохранить')]:
+ avatar['status'], avatar['error'] = status, error
+ page.locator('#avatar-save').click()
+ page.locator('#avatar-message').filter(has_text=text).wait_for()
+ assert page.locator('#avatar-canvas').count() == 1
+ assert page.locator('#avatar-save').is_enabled()
+ avatar['status'] = 200
+ page.locator('#avatar-save').click()
+ page.locator('#avatar-message').filter(has_text='Фото обновлено').wait_for()
+ assert page.locator('#avatar-canvas').count() == 0
+ sent = avatar['uploads'][-1]
+ assert sent['headers']['x-csrf-token'] == 'fixture-csrf-token'
+ assert sent['headers']['content-type'] == 'image/png'
+ assert sent['headers']['origin'] == args.url
+ assert sent['body'][:8] == b'\x89PNG\r\n\x1a\n' and struct.unpack('>II', sent['body'][16:24]) == (256, 256), sent['body'][:24]
+ page.locator('#profile-avatar img').wait_for()
+ assert page.locator('#profile-avatar img').get_attribute('src') == OWN_AVATAR
+ page.locator('#avatar-remove').wait_for(state='visible')
+ page.screenshot(path=str(artifacts / 'account-avatar-saved.png'), full_page=True)
+ page.locator('#avatar-remove').click()
+ page.locator('#avatar-message').filter(has_text='Фото убрано').wait_for()
+ assert avatar['deletes'][-1]['headers']['x-csrf-token'] == 'fixture-csrf-token'
+ assert avatar['deletes'][-1]['headers']['origin'] == args.url
+ assert page.locator('#profile-avatar img').count() == 0
+ assert page.locator('#avatar-remove').is_hidden()
+ # Escape cancels the editor and returns focus to the upload button.
+ page.locator('#avatar-file').set_input_files(files=[{'name': 'photo.png', 'mimeType': 'image/png', 'buffer': PHOTO}])
+ page.locator('#avatar-canvas').wait_for()
+ page.keyboard.press('Escape')
+ assert page.locator('#avatar-canvas').count() == 0
+ assert page.evaluate("document.activeElement.id") == 'avatar-pick'
+ assert page.evaluate('Object.keys(localStorage)') == ['vnox-web-language']
for locale in ['ru', 'en']:
page.locator(f'[data-language="{locale}"]').click()
for width in [320,390,768,1440]:
@@ -116,4 +297,4 @@ with sync_playwright() as p:
page.locator('.github-login').wait_for()
assert not errors, errors
browser.close()
- print(json.dumps({'result':'passed','assertions':'tabs, theme, RU/EN, 320/390/768/1440 layout, login enabled/disabled/errors, session/profile XSS safety, CSRF logout/expired session, no persisted secrets','artifacts':str(artifacts)}))
+ print(json.dumps({'result':'passed','assertions':'tabs, theme, RU/EN, 320/390/768/1440 layout, login enabled/disabled/errors, email code flow with fixtures, session/profile XSS safety, CSRF logout/expired session, own avatar crop/upload/errors/remove with keyboard, no persisted secrets','artifacts':str(artifacts)}))
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 044eb00..903737a 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -108,3 +108,16 @@ test("app templates avoid inline style attributes blocked by the site CSP", asyn
const source = await Bun.file("src/app.ts").text();
assert.doesNotMatch(source, /style="/);
});
+
+test("privacy text describes email sign-in in both languages", () => {
+ for (const [name, catalog] of Object.entries(messages)) {
+ const text = [
+ catalog.privacyCollectText,
+ catalog.privacyTrackText,
+ catalog.privacyCookiesText,
+ ].join(" ");
+ assert.match(text, /HMAC/, name);
+ assert.match(text, /10/, name);
+ assert.match(text, /SMTP/, name);
+ }
+});
diff --git a/tests/crop.test.ts b/tests/crop.test.ts
new file mode 100644
index 0000000..3c4196f
--- /dev/null
+++ b/tests/crop.test.ts
@@ -0,0 +1,40 @@
+import { test } from "bun:test";
+import assert from "node:assert/strict";
+import {
+ MAX_ZOOM,
+ clampCrop,
+ initialCrop,
+ panBy,
+ sourceRect,
+ zoomTo,
+} from "../src/crop";
+
+test("the first frame is centred and fills the square", () => {
+ const rect = sourceRect(initialCrop(400, 200));
+ assert.deepEqual(rect, { sx: 100, sy: 0, side: 200 });
+});
+test("panning never leaves empty edges and never stretches", () => {
+ let state = initialCrop(400, 200);
+ state = panBy(state, -10_000, 10_000, 280);
+ let rect = sourceRect(state);
+ assert.equal(rect.sx + rect.side, 400);
+ assert.equal(rect.sy, 0);
+ state = zoomTo(state, 2);
+ state = panBy(state, 10_000, -10_000, 280);
+ rect = sourceRect(state);
+ assert.equal(rect.side, 100);
+ assert.equal(rect.sx, 0);
+ assert.equal(rect.sy, 100);
+});
+test("zoom is clamped and keeps the area inside the image", () => {
+ const state = clampCrop({
+ ...initialCrop(300, 300),
+ zoom: 99,
+ x: -5,
+ y: 900,
+ });
+ assert.equal(state.zoom, MAX_ZOOM);
+ const { sx, sy, side } = sourceRect(state);
+ assert.ok(sx >= 0 && sy >= 0 && sx + side <= 300 && sy + side <= 300);
+ assert.equal(zoomTo(initialCrop(300, 300), 0.2).zoom, 1);
+});