From a4cae66336544596b90dc4d1b4b29449ee465ee4 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 17:49:41 +0200 Subject: [PATCH 1/2] feat(web): sign in by emailed code on the account page Adds the email form (address, code, resend timer, aria-live status) shown only when /v1/info reports email_auth enabled, RU/EN strings, privacy policy update, API helpers, tests and browser QA with a mocked Hub. --- docs/verification.md | 1 + src/api.ts | 50 +++++++++++- src/app.ts | 183 ++++++++++++++++++++++++++++++++++++++++++- src/i18n/en.ts | 43 +++++++--- src/i18n/ru.ts | 43 +++++++--- src/styles.css | 64 +++++++++++++++ tests/api.test.ts | 70 ++++++++++++++++- tests/browser_qa.py | 89 ++++++++++++++++++++- tests/copy.test.ts | 13 +++ 9 files changed, 528 insertions(+), 28 deletions(-) diff --git a/docs/verification.md b/docs/verification.md index 3aeb14a..ac7dd78 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -15,6 +15,7 @@ The optional browser script requires the loopback preview from `bun run dev` or - Keyboard-operated illustration tabs and theme selection. - Runtime RU/EN changes and layouts at 320, 390, 768 and 1440 pixels, including account views. - Enabled, disabled and unavailable GitHub sign-in; retry after session failure. +- Email sign-in form (shown only when `/v1/info` reports `email_auth: enabled`): address validation, rate-limit and outage messages, code step with focus and `aria-invalid`, resend timer, language switch keeping state, wrong and right code. Hub is mocked; no mail is sent. - Profile values rendered as text, rejected unsafe avatar URLs and no script execution from hostile profile fixtures. - CSRF-header/Origin/POST sign-out and expired-session handling. - Browser storage contains only the UI language; no account tokens are persisted. diff --git a/src/api.ts b/src/api.ts index 027f11e..83b6c5c 100644 --- a/src/api.ts +++ b/src/api.ts @@ -8,12 +8,14 @@ export type Session = | { authenticated: false } | { authenticated: true; user: User; csrf_token: string }; export interface HubInfo { - capabilities: { github_auth: string }; + capabilities: { github_auth: string; email_auth?: string }; } export interface RequestOptions { signal?: AbortSignal; method?: "GET" | "POST"; csrf?: string; + /** JSON request body; only sent when given. */ + body?: unknown; fetcher?: (input: string, options: RequestInit) => Promise; } export class ApiError extends Error { @@ -26,7 +28,7 @@ export class ApiError extends Error { } export async function request( path: string, - { signal, method = "GET", csrf, fetcher = fetch }: RequestOptions = {}, + { signal, method = "GET", csrf, body, fetcher = fetch }: RequestOptions = {}, ): Promise { if (!path.startsWith("/v1/")) throw new TypeError("Only same-origin VNOX API paths are allowed"); @@ -38,7 +40,9 @@ export async function request( headers: { Accept: "application/json", ...(csrf ? { "X-CSRF-Token": csrf } : {}), + ...(body === undefined ? {} : { "Content-Type": "application/json" }), }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); if (!response.ok) throw new ApiError(response.status, "request_failed"); if (response.status === 204) return null; @@ -70,9 +74,49 @@ export function isInfo(value: unknown): value is HubInfo { return ( record(value) && record(value.capabilities) && - typeof value.capabilities.github_auth === "string" + typeof value.capabilities.github_auth === "string" && + (value.capabilities.email_auth === undefined || + typeof value.capabilities.email_auth === "string") ); } +/** Result of asking Hub to mail a sign-in code. */ +export interface CodeRequest { + resendAfter: number; +} +/** Asks Hub to email a one-time code. Resolves with a bounded resend delay in seconds. */ +export async function requestEmailCode( + email: string, + lang: "ru" | "en", + options: Pick = {}, +): Promise { + const value = await request("/v1/auth/email/start", { + ...options, + method: "POST", + body: { email, lang }, + }); + const delay = record(value) ? value.resend_after : undefined; + return { + resendAfter: + typeof delay === "number" && delay >= 1 && delay <= 3600 + ? Math.ceil(delay) + : 60, + }; +} +/** Redeems the code. Resolves only with an authenticated session. */ +export async function verifyEmailCode( + email: string, + code: string, + options: Pick = {}, +): Promise { + const value = await request("/v1/auth/email/verify", { + ...options, + method: "POST", + body: { email, code }, + }); + if (!isSession(value) || !value.authenticated) + throw new Error("invalid_session"); + return value; +} export function safeAvatar(value: unknown): string | null { if (typeof value !== "string") return null; try { diff --git a/src/app.ts b/src/app.ts index f3571c4..b54323a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,7 +1,15 @@ import type { Language, MessageKey } from "./i18n"; import type { Session } from "./api"; import { detectLanguage, translate } from "./i18n"; -import { request, isSession, isInfo, safeAvatar, ApiError } from "./api"; +import { + request, + isSession, + isInfo, + safeAvatar, + ApiError, + requestEmailCode, + verifyEmailCode, +} from "./api"; let savedLanguage: string | null | undefined; try { @@ -31,6 +39,17 @@ let activeTheme: Theme = "dark"; let controller: AbortController | undefined; let currentSession: Session | null = null; let githubEnabled = false; +let emailEnabled = false; +// Email sign-in form state. Kept outside the DOM so a language switch or a +// re-render does not lose what was typed. +let emailStep: "address" | "code" = "address"; +let emailAddress = ""; +let emailCode = ""; +let emailBusy: "idle" | "sending" | "verifying" = "idle"; +let emailMessage: MessageKey | null = null; +let emailField: "address" | "code" | null = null; +let resendUntil = 0; +let resendTimer: ReturnType | undefined; let sessionState: "loading" | "ready" | "error" = "loading"; let infoState: "loading" | "ready" | "error" = "loading"; let logoutState: "idle" | "pending" | "error" = "idle"; @@ -195,7 +214,7 @@ function renderAccount() { return; } if (currentSession?.authenticated) { - panel.innerHTML = `
${tr("profileTitle", "h2")}

${tr("profileIntro", "p")}
${tr("handle")}
${tr("userId")}
${tr("provider")}
GitHub

`; + panel.innerHTML = `
${tr("profileTitle", "h2")}

${tr("profileIntro", "p")}
${tr("handle")}
${tr("userId")}

`; const user = currentSession.user; find("#profile-name", panel).textContent = user.display_name || t("profileFallback"); @@ -223,7 +242,7 @@ function renderAccount() { find("#profile-message", panel).textContent = t("logoutError"); return; } - panel.innerHTML = `${tr("loginTitle", "h2")}${tr("loginText", "p")}

${icon("check", 16)}${tr("privacy", "p")}
`; + panel.innerHTML = `${tr("loginTitle", "h2")}${tr("loginText", "p")}

${icon("check", 16)}${tr("privacy", "p")}
`; find("#login-availability", panel).textContent = infoState === "loading" ? t("loginLoading") @@ -233,6 +252,162 @@ function renderAccount() { ? "" : t("loginDisabled"); find("#retry-info", panel).addEventListener("click", refresh); + renderEmail(); +} +function stopResendTimer() { + clearInterval(resendTimer); + resendTimer = undefined; +} +function tickResend() { + const button = document.querySelector("#resend"); + if (!button) return stopResendTimer(); + const left = Math.max(0, Math.ceil((resendUntil - Date.now()) / 1000)); + button.disabled = left > 0 || emailBusy !== "idle"; + button.textContent = + left > 0 + ? t("emailResendIn").replace("{seconds}", String(left)) + : t("emailResend"); + if (left === 0) stopResendTimer(); +} +const looksLikeEmail = (value: string) => + value.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); +function emailFailure(error: unknown, rejected: MessageKey): MessageKey { + if (error instanceof ApiError) { + if (error.status === 400) return rejected; + if (error.status === 429) return "emailTooMany"; + } + return "emailFailed"; +} +/** Draws the email form into #email-area. Hidden unless Hub reports email_auth: enabled. */ +function renderEmail() { + const area = document.querySelector("#email-area"); + if (!area) return; + stopResendTimer(); + area.replaceChildren(); + if (!emailEnabled) return; + const busy = emailBusy !== "idle"; + const invalid = emailMessage !== null && emailField !== null; + const describedBy = 'aria-describedby="email-message"'; + const aria = (field: "address" | "code") => + invalid && emailField === field ? 'aria-invalid="true"' : ""; + const stepHtml = + emailStep === "address" + ? `` + : `

`; + area.innerHTML = ``; + 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; @@ -290,11 +465,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/i18n/en.ts b/src/i18n/en.ts index 0d32230..89d707e 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,13 +61,13 @@ 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.", 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. 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 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.", @@ -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,27 @@ export const en = { copy: "Copy account ID", copied: "Account ID copied", copyError: "Could not copy the ID. Select it manually.", + 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..6859454 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,13 +63,13 @@ export const ru: Catalog = { "Это политика сайта и Vnox Central. Чаты на серверах сообществ и настольный клиент сюда не входят, о них ниже.", privacyCollectTitle: "Что мы получаем", privacyCollectText: - "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется.", + "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений.", privacyCookiesTitle: "Cookie", privacyCookiesText: - "Только необходимые: короткий cookie на время входа (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.", + "Только необходимые: короткий cookie на время входа через GitHub или по почте (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.", privacyTrackTitle: "Слежка и сторонние сервисы", privacyTrackText: - "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Запросы входа не попадают в журналы веб-сервера.", + "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.", privacyOtherTitle: "Серверы сообществ и клиент", privacyOtherText: "Серверы VNOX ведут сами владельцы. Сообщения и файлы на сервере находятся у его владельца, и правила хранения задаёт он. Настольный клиент хранит ваш ключ и настройки на вашем устройстве.", @@ -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,26 @@ export const ru: Catalog = { copy: "Скопировать ID", copied: "ID скопирован", copyError: "Не удалось скопировать ID. Выделите его вручную.", + 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..a0e8f2b 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; diff --git a/tests/api.test.ts b/tests/api.test.ts index d0ef16e..000e219 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -1,6 +1,14 @@ 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, +} from "../src/api"; import { messages, detectLanguage } from "../src/i18n"; test("catalogs match and never silently fall back to a missing translation", () => { @@ -105,3 +113,63 @@ 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, + ); +}); diff --git a/tests/browser_qa.py b/tests/browser_qa.py index 50616f1..880c299 100644 --- a/tests/browser_qa.py +++ b/tests/browser_qa.py @@ -19,12 +19,24 @@ artifacts.mkdir(parents=True, exist_ok=True) 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 = [] 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/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 +89,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() @@ -116,4 +203,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, 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); + } +}); From 76f8371a7e572a0b1585a9df77ef0e62616d6b47 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 21:48:05 +0200 Subject: [PATCH 2/2] feat(web): let users set their own photo on the account page Pick a PNG/JPEG/WebP file, crop it to a square on a canvas (drag, wheel, slider or keyboard), export a 256x256 PNG and send it to Hub. Adds remove photo, error states, RU/EN copy and privacy policy text about the stored photo and 30-day backups. Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- docs/design.md | 4 + src/api.ts | 84 ++++++++++++- src/app.ts | 278 +++++++++++++++++++++++++++++++++++++++++++- src/crop.ts | 56 +++++++++ src/i18n/en.ts | 28 ++++- src/i18n/ru.ts | 28 ++++- src/styles.css | 70 +++++++++++ tests/api.test.ts | 69 +++++++++++ tests/browser_qa.py | 96 ++++++++++++++- tests/crop.test.ts | 40 +++++++ 10 files changed, 739 insertions(+), 14 deletions(-) create mode 100644 src/crop.ts create mode 100644 tests/crop.test.ts diff --git a/docs/design.md b/docs/design.md index d6fb66c..f6a0d6d 100644 --- a/docs/design.md +++ b/docs/design.md @@ -25,3 +25,7 @@ Central status Footer Review: a giant neutral product screenshot alone would feel like any desktop-app page. The hero instead explains persistent voice while browsing text through an intentionally small, labelled diagram. Real native-client imagery appears where it supports the appearance/settings explanation. Sand is the approved V brand colour, not a secondary decorative accent. Motion: sections fade in on scroll (IntersectionObserver), the hero enters once, the voice waveform and connection dots pulse softly, buttons and cards lift on hover. The memory block draws a short sand bar for VNOX against a long stone bar and counts up to 120 MB when it scrolls into view. All of it is plain CSS plus a small script, and it is switched off under `prefers-reduced-motion: reduce` (the final values are shown at once). Memory numbers and their sources: `docs/memory-sources.md`. + +## Account photo + +The account page lets a signed-in user upload their own photo (`/v1/account/avatar`, see the Hub `AUTH.md`). The file is decoded with `createImageBitmap` (no `` or blob URL, so the CSP needs no `blob:`), cropped to a square on a canvas (drag, wheel, slider, arrow keys and plus/minus), exported with `canvas.toBlob` as a 256 by 256 PNG and sent with the CSRF header. Crop geometry is in `src/crop.ts` and unit tested. No inline `style` attributes are used. Own avatars are shown from the same origin (`/v1/avatars/<64 hex>`), which `img-src 'self'` already allows. The privacy text says that a re-encoded photo is stored, that "Remove photo" deletes it, and that deleted data can stay in database backups for up to 30 days; that retention is an owner decision that still needs backup rotation on the server. diff --git a/src/api.ts b/src/api.ts index 83b6c5c..50d2c08 100644 --- a/src/api.ts +++ b/src/api.ts @@ -12,23 +12,35 @@ export interface HubInfo { } export interface RequestOptions { signal?: AbortSignal; - method?: "GET" | "POST"; + method?: "GET" | "POST" | "DELETE"; csrf?: string; /** JSON request body; only sent when given. */ body?: unknown; + /** Raw image body; sent with its own content type instead of JSON. */ + image?: Blob; fetcher?: (input: string, options: RequestInit) => Promise; } export class ApiError extends Error { readonly status: number; - constructor(status: number, code: string) { + /** Short machine code from the Hub error body, such as "too_large", or "". */ + readonly detail: string; + constructor(status: number, code: string, detail = "") { super(code); this.name = "ApiError"; this.status = status; + this.detail = detail; } } export async function request( path: string, - { signal, method = "GET", csrf, body, fetcher = fetch }: RequestOptions = {}, + { + signal, + method = "GET", + csrf, + body, + image, + fetcher = fetch, + }: RequestOptions = {}, ): Promise { if (!path.startsWith("/v1/")) throw new TypeError("Only same-origin VNOX API paths are allowed"); @@ -40,11 +52,33 @@ export async function request( headers: { Accept: "application/json", ...(csrf ? { "X-CSRF-Token": csrf } : {}), - ...(body === undefined ? {} : { "Content-Type": "application/json" }), + ...(image + ? { "Content-Type": image.type } + : body === undefined + ? {} + : { "Content-Type": "application/json" }), }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), + ...(image + ? { body: image } + : body === undefined + ? {} + : { body: JSON.stringify(body) }), }); - if (!response.ok) throw new ApiError(response.status, "request_failed"); + if (!response.ok) { + let detail = ""; + try { + const failure: unknown = await response.json(); + if ( + record(failure) && + typeof failure.error === "string" && + /^[a-z_]{1,40}$/.test(failure.error) + ) + detail = failure.error; + } catch { + /* The body is optional. */ + } + throw new ApiError(response.status, "request_failed", detail); + } if (response.status === 204) return null; return response.json(); } @@ -117,7 +151,45 @@ export async function verifyEmailCode( throw new Error("invalid_session"); return value; } +/** Hub's own avatar path: same origin, 64 hex characters of content hash. */ +const OWN_AVATAR = /^\/v1\/avatars\/[0-9a-f]{64}$/; +export function isOwnAvatar(value: unknown): value is string { + return typeof value === "string" && OWN_AVATAR.test(value); +} +function avatarUrl(value: unknown): string { + if (!record(value) || !isOwnAvatar(value.avatar_url)) + throw new Error("invalid_avatar"); + return value.avatar_url; +} +/** Uploads the cropped PNG. Resolves with the new same-origin avatar path. */ +export async function uploadAvatar( + image: Blob, + csrf: string, + options: Pick = {}, +): Promise { + return avatarUrl( + await request("/v1/account/avatar", { + ...options, + method: "POST", + csrf, + image, + }), + ); +} +/** Removes the own photo. Resolves with the avatar now in effect (provider's) or null. */ +export async function removeAvatar( + csrf: string, + options: Pick = {}, +): Promise { + const value = await request("/v1/account/avatar", { + ...options, + method: "DELETE", + csrf, + }); + return record(value) ? safeAvatar(value.avatar_url) : null; +} export function safeAvatar(value: unknown): string | null { + if (isOwnAvatar(value)) return value; if (typeof value !== "string") return null; try { const url = new URL(value); diff --git a/src/app.ts b/src/app.ts index b54323a..9c01fdf 100644 --- a/src/app.ts +++ b/src/app.ts @@ -9,7 +9,20 @@ import { ApiError, requestEmailCode, verifyEmailCode, + uploadAvatar, + removeAvatar, + isOwnAvatar, } from "./api"; +import type { CropState } from "./crop"; +import { + OUTPUT_SIDE, + MAX_ZOOM, + initialCrop, + clampCrop, + panBy, + sourceRect, + zoomTo, +} from "./crop"; let savedLanguage: string | null | undefined; try { @@ -53,6 +66,13 @@ let resendTimer: ReturnType | undefined; let sessionState: "loading" | "ready" | "error" = "loading"; let infoState: "loading" | "ready" | "error" = "loading"; let logoutState: "idle" | "pending" | "error" = "idle"; +// Avatar editor state also lives outside the DOM, so a language switch keeps the crop. +const AVATAR_VIEW = 280; +const AVATAR_MAX_FILE = 10 * 1024 * 1024; +const AVATAR_MAX_SIDE = 8192; +let avatarBusy: "idle" | "saving" | "removing" = "idle"; +let avatarMessage: MessageKey | null = null; +let avatarCrop: { bitmap: ImageBitmap; state: CropState } | null = null; const t = (key: MessageKey) => translate(language, key); const icon = ( name: @@ -214,7 +234,7 @@ function renderAccount() { return; } if (currentSession?.authenticated) { - panel.innerHTML = `
${tr("profileTitle", "h2")}

${tr("profileIntro", "p")}
${tr("handle")}
${tr("userId")}

`; + panel.innerHTML = `
${tr("profileTitle", "h2")}

${tr("profileIntro", "p")}
${tr("handle")}
${tr("userId")}
${avatarBlock()}

`; const user = currentSession.user; find("#profile-name", panel).textContent = user.display_name || t("profileFallback"); @@ -237,6 +257,7 @@ function renderAccount() { find("#profile-message", panel).textContent = t("copyError"); } }); + setupAvatar(panel, user.avatar_url); find("#logout", panel).addEventListener("click", logout); if (logoutState === "error") find("#profile-message", panel).textContent = t("logoutError"); @@ -254,6 +275,259 @@ function renderAccount() { find("#retry-info", panel).addEventListener("click", refresh); renderEmail(); } +function avatarBlock(): string { + return `
${tr("avatarTitle", "h3")}${tr("avatarHint", "p", 'class="small"')}

`; +} +function avatarFailure(error: unknown): MessageKey { + if (error instanceof ApiError) { + if (error.detail === "too_large") return "avatarTooBig"; + if (error.detail === "unsupported_type" || error.detail === "type_mismatch") + return "avatarBadType"; + if (error.detail === "bad_dimensions" || error.detail === "invalid_image") + return "avatarBadImage"; + if (error.status === 429) return "avatarLimit"; + } + return "avatarFailed"; +} +function closeAvatarEditor() { + avatarCrop?.bitmap.close(); + avatarCrop = null; +} +function setupAvatar(panel: Element, avatarUrl: string | null | undefined) { + const pick = find("#avatar-pick", panel); + const remove = find("#avatar-remove", panel); + const input = find("#avatar-file", panel); + const message = find("#avatar-message", panel); + const busy = avatarBusy !== "idle"; + pick.disabled = busy; + remove.hidden = !isOwnAvatar(avatarUrl); + remove.disabled = busy; + if (avatarBusy === "removing") remove.textContent = t("avatarRemoving"); + if (avatarMessage) message.textContent = t(avatarMessage); + pick.addEventListener("click", () => input.click()); + input.addEventListener("change", async () => { + const file = input.files?.[0]; + input.value = ""; + if (!file) return; + avatarMessage = null; + if (!["image/png", "image/jpeg", "image/webp"].includes(file.type)) + avatarMessage = "avatarBadType"; + else if (file.size > AVATAR_MAX_FILE) avatarMessage = "avatarTooBig"; + else { + try { + const bitmap = await createImageBitmap(file); + if ( + bitmap.width > AVATAR_MAX_SIDE || + bitmap.height > AVATAR_MAX_SIDE || + bitmap.width < 32 || + bitmap.height < 32 + ) { + bitmap.close(); + avatarMessage = "avatarBadImage"; + } else { + closeAvatarEditor(); + avatarCrop = { + bitmap, + state: initialCrop(bitmap.width, bitmap.height), + }; + } + } catch { + avatarMessage = "avatarBadImage"; + } + } + renderAccount(); + if (avatarCrop) + document.querySelector("#avatar-canvas")?.focus(); + }); + remove.addEventListener("click", removeOwnAvatar); + if (avatarCrop) renderAvatarEditor(find("#avatar-editor", panel)); +} +function renderAvatarEditor(host: Element) { + const crop = avatarCrop; + if (!crop) return; + const saving = avatarBusy === "saving"; + host.innerHTML = `
${tr("avatarEditorTitle", "h4").replace("${tr("avatarCropHelp", "p", 'id="avatar-crop-help" class="small"')}
`; + const canvas = find("#avatar-canvas", host); + const zoom = find("#avatar-zoom", host); + const context = canvas.getContext("2d"); + if (!context) return; + const draw = () => { + const { sx, sy, side } = sourceRect(crop.state); + context.clearRect(0, 0, AVATAR_VIEW, AVATAR_VIEW); + context.imageSmoothingQuality = "high"; + context.drawImage( + crop.bitmap, + sx, + sy, + side, + side, + 0, + 0, + AVATAR_VIEW, + AVATAR_VIEW, + ); + zoom.value = String(Math.round(crop.state.zoom * 100)); + }; + const set = (state: CropState) => { + crop.state = state; + draw(); + }; + draw(); + for (const control of host.querySelectorAll("button")) + control.disabled = saving; + canvas.classList.toggle("disabled", saving); + zoom.disabled = saving; + let last: { x: number; y: number } | null = null; + canvas.addEventListener("pointerdown", (event) => { + if (saving) return; + last = { x: event.clientX, y: event.clientY }; + canvas.setPointerCapture(event.pointerId); + canvas.classList.add("dragging"); + }); + canvas.addEventListener("pointermove", (event) => { + if (!last) return; + const width = canvas.getBoundingClientRect().width || AVATAR_VIEW; + set( + panBy(crop.state, event.clientX - last.x, event.clientY - last.y, width), + ); + last = { x: event.clientX, y: event.clientY }; + }); + const release = () => { + last = null; + canvas.classList.remove("dragging"); + }; + canvas.addEventListener("pointerup", release); + canvas.addEventListener("pointercancel", release); + canvas.addEventListener( + "wheel", + (event) => { + event.preventDefault(); + if (saving) return; + set(zoomTo(crop.state, crop.state.zoom - event.deltaY * 0.002)); + }, + { passive: false }, + ); + canvas.addEventListener("keydown", (event) => { + if (saving) return; + const step = event.shiftKey ? 40 : 10; + const moves: Record = { + ArrowLeft: [step, 0], + ArrowRight: [-step, 0], + ArrowUp: [0, step], + ArrowDown: [0, -step], + }; + const move = moves[event.key]; + if (move) set(panBy(crop.state, move[0], move[1], AVATAR_VIEW)); + else if (event.key === "+" || event.key === "=") + set(zoomTo(crop.state, crop.state.zoom + 0.1)); + else if (event.key === "-" || event.key === "_") + set(zoomTo(crop.state, crop.state.zoom - 0.1)); + else if (event.key === "Escape") { + closeAvatarEditor(); + renderAccount(); + document.querySelector("#avatar-pick")?.focus(); + } else return; + event.preventDefault(); + }); + zoom.addEventListener("input", () => + set(zoomTo(crop.state, Number(zoom.value) / 100)), + ); + find("#avatar-reset", host).addEventListener("click", () => + set(initialCrop(crop.state.width, crop.state.height)), + ); + find("#avatar-cancel", host).addEventListener("click", () => { + closeAvatarEditor(); + avatarMessage = null; + renderAccount(); + document.querySelector("#avatar-pick")?.focus(); + }); + find("#avatar-save", host).addEventListener("click", saveAvatar); +} +function cropToPng(crop: { bitmap: ImageBitmap; state: CropState }) { + const out = document.createElement("canvas"); + out.width = OUTPUT_SIDE; + out.height = OUTPUT_SIDE; + const context = out.getContext("2d"); + if (!context) return Promise.resolve(null); + const { sx, sy, side } = sourceRect(clampCrop(crop.state)); + context.imageSmoothingQuality = "high"; + context.drawImage( + crop.bitmap, + sx, + sy, + side, + side, + 0, + 0, + OUTPUT_SIDE, + OUTPUT_SIDE, + ); + return new Promise((resolve) => + out.toBlob(resolve, "image/png"), + ); +} +function applyAvatarSession(url: string | null) { + if (currentSession?.authenticated) + currentSession = { + ...currentSession, + user: { ...currentSession.user, avatar_url: url }, + }; +} +/** A rejected request with 401 means the session ended: show the sign-in view. */ +function sessionEnded(error: unknown): boolean { + if (!(error instanceof ApiError) || error.status !== 401) return false; + currentSession = { authenticated: false }; + closeAvatarEditor(); + avatarBusy = "idle"; + avatarMessage = null; + renderAccount(); + return true; +} +async function saveAvatar() { + if (!currentSession?.authenticated || !avatarCrop || avatarBusy !== "idle") + return; + const csrf = currentSession.csrf_token; + avatarBusy = "saving"; + avatarMessage = null; + renderAccount(); + try { + const blob = await cropToPng(avatarCrop); + if (!blob) throw new Error("export_failed"); + const url = await uploadAvatar(blob, csrf, { + signal: AbortSignal.timeout(30000), + }); + applyAvatarSession(url); + closeAvatarEditor(); + avatarMessage = "avatarSaved"; + } catch (error) { + if (sessionEnded(error)) return; + avatarMessage = avatarFailure(error); + } + avatarBusy = "idle"; + renderAccount(); + document + .querySelector(avatarCrop ? "#avatar-save" : "#avatar-pick") + ?.focus(); +} +async function removeOwnAvatar() { + if (!currentSession?.authenticated || avatarBusy !== "idle") return; + const csrf = currentSession.csrf_token; + avatarBusy = "removing"; + avatarMessage = null; + renderAccount(); + try { + applyAvatarSession( + await removeAvatar(csrf, { signal: AbortSignal.timeout(15000) }), + ); + avatarMessage = "avatarRemoved"; + } catch (error) { + if (sessionEnded(error)) return; + avatarMessage = avatarFailure(error); + } + avatarBusy = "idle"; + renderAccount(); + document.querySelector("#avatar-pick")?.focus(); +} function stopResendTimer() { clearInterval(resendTimer); resendTimer = undefined; @@ -422,6 +696,8 @@ async function logout() { }); currentSession = { authenticated: false }; logoutState = "idle"; + closeAvatarEditor(); + avatarMessage = null; renderAccount(); } catch (error) { if (error instanceof ApiError && error.status === 401) { 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 89d707e..6798b07 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -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 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.", + "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 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 code email goes out through an SMTP mail service, so that service sees your address and the text of the message.", + "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.", @@ -161,6 +161,28 @@ 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: diff --git a/src/i18n/ru.ts b/src/i18n/ru.ts index 6859454..bdd8d63 100644 --- a/src/i18n/ru.ts +++ b/src/i18n/ru.ts @@ -63,19 +63,19 @@ export const ru: Catalog = { "Это политика сайта и Vnox Central. Чаты на серверах сообществ и настольный клиент сюда не входят, о них ниже.", privacyCollectTitle: "Что мы получаем", privacyCollectText: - "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений.", + "При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений. Если вы загружаете фото, мы сохраняем его как PNG 256 на 256, который сами перекодируем, поэтому EXIF и геометки из оригинала в нём нет. Хранится одно фото на аккаунт, исходный файл не сохраняется.", privacyCookiesTitle: "Cookie", privacyCookiesText: "Только необходимые: короткий cookie на время входа через GitHub или по почте (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.", privacyTrackTitle: "Слежка и сторонние сервисы", privacyTrackText: - "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.", + "На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар GitHub загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Ваше собственное фото загружается с нашего сервера. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.", privacyOtherTitle: "Серверы сообществ и клиент", privacyOtherText: "Серверы VNOX ведут сами владельцы. Сообщения и файлы на сервере находятся у его владельца, и правила хранения задаёт он. Настольный клиент хранит ваш ключ и настройки на вашем устройстве.", privacyDeleteTitle: "Удаление данных", privacyDeleteText: - "Кнопки удаления аккаунта пока нет. Чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись.", + "Нажмите «Убрать фото» на странице аккаунта, и фото будет удалено; оно также удаляется вместе с остальными данными. Кнопки удаления всего аккаунта пока нет: чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись. Удалённые данные могут оставаться в резервных копиях базы до 30 дней.", lightTitle: "Лёгкий клиент", lightText: "Клиент на Rust и Slint не носит с собой браузер. В простое он занимает около 120 МБ памяти.", @@ -163,6 +163,28 @@ 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: diff --git a/src/styles.css b/src/styles.css index a0e8f2b..280f2e4 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2169,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 000e219..a5af93b 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -8,6 +8,8 @@ import { ApiError, requestEmailCode, verifyEmailCode, + uploadAvatar, + removeAvatar, } from "../src/api"; import { messages, detectLanguage } from "../src/i18n"; @@ -173,3 +175,70 @@ test("email verification accepts only an authenticated session and keeps the sta (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 880c299..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,12 +18,23 @@ 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']) @@ -37,6 +50,16 @@ with sync_playwright() as p: 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 '{}') @@ -185,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]: @@ -203,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, email code flow with fixtures, 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/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); +});