From 76f8371a7e572a0b1585a9df77ef0e62616d6b47 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 21:48:05 +0200 Subject: [PATCH 1/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); +}); From 22999f33f16e09bda80a70729e4a6dd732837764 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 24 Oct 2026 22:33:52 +0200 Subject: [PATCH 2/2] feat(web): add a transparent V mark for emails Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4 --- public/assets/vnox-mark-email.png | Bin 0 -> 1433 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 public/assets/vnox-mark-email.png diff --git a/public/assets/vnox-mark-email.png b/public/assets/vnox-mark-email.png new file mode 100644 index 0000000000000000000000000000000000000000..c271ce0327c8079265b970a0d65691e4536b6cb4 GIT binary patch literal 1433 zcmb7^X;4#F7>3UcxvVOXgs@4B5`riqvW%dFvLrxIs8JD6KnyJ+yA?1cC_#|PB8eiR zQa0n38O0`I3qcCE$YR9+){deC3?NV`YP1@H3-mgj@n2``kF(5sp6`9 zrgo+PfW^!(`d0MheOktb=zhz8PcHy)B9k7tom2h1W+Oj7iV*P79&g4RxWEcb?+lU4 z2ZCVO$%a}p$iH}8Z)?e_Sh*q4VMTbA%~vTdL}5*EIsu!6|20Uijm8Gv?+i0!lz9@T zXcnrwBU8iNHtyOpFVx)ivkkM#gS5$rHs4on;&`Hm!`|{|K9Lk9cJOx2Qs?qGjL)et zj7<;hE;dVCYK{1~@%G1o@n+DyA38Svr4Pv%{j9Fc1CO*fWf2O^{=@5X1?WX=I~L0n z3w_Ws1Ce9jO`qW@CEc^`Z0*UJ&88nD_5HkE9u8?RCtu^AfL$VX7nS0XhO=V$X(1d# zeNt>bT4et^TpreDw5&rJ+sA30!T6QWae&0?abCjp+Vg76%$)*1-Vdf38`sA6pE!Dj z_ZAwelwAm(ETcAo_HX=2h_%7bG~dUB{KKm6qCPODX7E~2|~ z|IpJhqYmFYA%cEz5VSk17wohqa>?i{IP)UuNlsmw<4l(4JkU|p3$V*_#AU25>L9MI zNj5jcJf42rbD{leFT z^b!ew$ADIo0+M2WW%fR4Y^l7s**?^{s0pu)0_BIWLEp6;u6c6*Cwis)paSAHadg#p;vdWIPhvnScL_gWqNn^$2}S$y)mV^ zT08RNgrlaI-guXhfdPIc{w;AK=XS}qB|v$rAI=;4RcBW!Wh~ydk{$IE{z0&R=I^Gk4Ep9|_2QFnNu70~~>IPld4GMUQ+V_wI53sye zg=`L`q(I4LS)&dNh41VBD)de`HfyAl(p7)-8%gDG2`k>wAC0(@J1oKGU&L6$@A8*x>~NWB_&P}xum)QGhkZNMJf__Lz;zl z$V->C=%>z*EZ>;kRpaxQwlu~Rz}fRh|KGR?bwnt0gvfPXm~={Ahf8TY{3SDM0m#!` VwswV|T7iySz+^