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.
This commit is contained in:
parent
a4cae66336
commit
4c06a17d7e
10 changed files with 739 additions and 14 deletions
|
|
@ -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.
|
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`.
|
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 `<img>` 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.
|
||||||
|
|
|
||||||
84
src/api.ts
84
src/api.ts
|
|
@ -12,23 +12,35 @@ export interface HubInfo {
|
||||||
}
|
}
|
||||||
export interface RequestOptions {
|
export interface RequestOptions {
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
method?: "GET" | "POST";
|
method?: "GET" | "POST" | "DELETE";
|
||||||
csrf?: string;
|
csrf?: string;
|
||||||
/** JSON request body; only sent when given. */
|
/** JSON request body; only sent when given. */
|
||||||
body?: unknown;
|
body?: unknown;
|
||||||
|
/** Raw image body; sent with its own content type instead of JSON. */
|
||||||
|
image?: Blob;
|
||||||
fetcher?: (input: string, options: RequestInit) => Promise<Response>;
|
fetcher?: (input: string, options: RequestInit) => Promise<Response>;
|
||||||
}
|
}
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
readonly status: number;
|
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);
|
super(code);
|
||||||
this.name = "ApiError";
|
this.name = "ApiError";
|
||||||
this.status = status;
|
this.status = status;
|
||||||
|
this.detail = detail;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export async function request(
|
export async function request(
|
||||||
path: string,
|
path: string,
|
||||||
{ signal, method = "GET", csrf, body, fetcher = fetch }: RequestOptions = {},
|
{
|
||||||
|
signal,
|
||||||
|
method = "GET",
|
||||||
|
csrf,
|
||||||
|
body,
|
||||||
|
image,
|
||||||
|
fetcher = fetch,
|
||||||
|
}: RequestOptions = {},
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
if (!path.startsWith("/v1/"))
|
if (!path.startsWith("/v1/"))
|
||||||
throw new TypeError("Only same-origin VNOX API paths are allowed");
|
throw new TypeError("Only same-origin VNOX API paths are allowed");
|
||||||
|
|
@ -40,11 +52,33 @@ export async function request(
|
||||||
headers: {
|
headers: {
|
||||||
Accept: "application/json",
|
Accept: "application/json",
|
||||||
...(csrf ? { "X-CSRF-Token": csrf } : {}),
|
...(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;
|
if (response.status === 204) return null;
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
@ -117,7 +151,45 @@ export async function verifyEmailCode(
|
||||||
throw new Error("invalid_session");
|
throw new Error("invalid_session");
|
||||||
return value;
|
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<RequestOptions, "signal" | "fetcher"> = {},
|
||||||
|
): Promise<string> {
|
||||||
|
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<RequestOptions, "signal" | "fetcher"> = {},
|
||||||
|
): Promise<string | null> {
|
||||||
|
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 {
|
export function safeAvatar(value: unknown): string | null {
|
||||||
|
if (isOwnAvatar(value)) return value;
|
||||||
if (typeof value !== "string") return null;
|
if (typeof value !== "string") return null;
|
||||||
try {
|
try {
|
||||||
const url = new URL(value);
|
const url = new URL(value);
|
||||||
|
|
|
||||||
278
src/app.ts
278
src/app.ts
|
|
@ -9,7 +9,20 @@ import {
|
||||||
ApiError,
|
ApiError,
|
||||||
requestEmailCode,
|
requestEmailCode,
|
||||||
verifyEmailCode,
|
verifyEmailCode,
|
||||||
|
uploadAvatar,
|
||||||
|
removeAvatar,
|
||||||
|
isOwnAvatar,
|
||||||
} from "./api";
|
} from "./api";
|
||||||
|
import type { CropState } from "./crop";
|
||||||
|
import {
|
||||||
|
OUTPUT_SIDE,
|
||||||
|
MAX_ZOOM,
|
||||||
|
initialCrop,
|
||||||
|
clampCrop,
|
||||||
|
panBy,
|
||||||
|
sourceRect,
|
||||||
|
zoomTo,
|
||||||
|
} from "./crop";
|
||||||
|
|
||||||
let savedLanguage: string | null | undefined;
|
let savedLanguage: string | null | undefined;
|
||||||
try {
|
try {
|
||||||
|
|
@ -53,6 +66,13 @@ let resendTimer: ReturnType<typeof setInterval> | undefined;
|
||||||
let sessionState: "loading" | "ready" | "error" = "loading";
|
let sessionState: "loading" | "ready" | "error" = "loading";
|
||||||
let infoState: "loading" | "ready" | "error" = "loading";
|
let infoState: "loading" | "ready" | "error" = "loading";
|
||||||
let logoutState: "idle" | "pending" | "error" = "idle";
|
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 t = (key: MessageKey) => translate(language, key);
|
||||||
const icon = (
|
const icon = (
|
||||||
name:
|
name:
|
||||||
|
|
@ -214,7 +234,7 @@ function renderAccount() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (currentSession?.authenticated) {
|
if (currentSession?.authenticated) {
|
||||||
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div></dl>${avatarBlock()}<div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
||||||
const user = currentSession.user;
|
const user = currentSession.user;
|
||||||
find("#profile-name", panel).textContent =
|
find("#profile-name", panel).textContent =
|
||||||
user.display_name || t("profileFallback");
|
user.display_name || t("profileFallback");
|
||||||
|
|
@ -237,6 +257,7 @@ function renderAccount() {
|
||||||
find("#profile-message", panel).textContent = t("copyError");
|
find("#profile-message", panel).textContent = t("copyError");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
setupAvatar(panel, user.avatar_url);
|
||||||
find("#logout", panel).addEventListener("click", logout);
|
find("#logout", panel).addEventListener("click", logout);
|
||||||
if (logoutState === "error")
|
if (logoutState === "error")
|
||||||
find("#profile-message", panel).textContent = t("logoutError");
|
find("#profile-message", panel).textContent = t("logoutError");
|
||||||
|
|
@ -254,6 +275,259 @@ function renderAccount() {
|
||||||
find("#retry-info", panel).addEventListener("click", refresh);
|
find("#retry-info", panel).addEventListener("click", refresh);
|
||||||
renderEmail();
|
renderEmail();
|
||||||
}
|
}
|
||||||
|
function avatarBlock(): string {
|
||||||
|
return `<div class="avatar-block">${tr("avatarTitle", "h3")}${tr("avatarHint", "p", 'class="small"')}<div class="avatar-actions"><button class="button secondary" id="avatar-pick" type="button">${tr("avatarUpload")}</button><button class="button quiet" id="avatar-remove" type="button" hidden>${tr("avatarRemove")}</button></div><input id="avatar-file" type="file" accept="image/png,image/jpeg,image/webp" hidden><p class="form-message" id="avatar-message" role="status"></p><div id="avatar-editor"></div></div>`;
|
||||||
|
}
|
||||||
|
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<HTMLButtonElement>("#avatar-pick", panel);
|
||||||
|
const remove = find<HTMLButtonElement>("#avatar-remove", panel);
|
||||||
|
const input = find<HTMLInputElement>("#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<HTMLElement>("#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 = `<div class="avatar-editor" role="group" aria-labelledby="avatar-editor-title">${tr("avatarEditorTitle", "h4").replace("<h4", '<h4 id="avatar-editor-title"')}<canvas id="avatar-canvas" class="avatar-canvas" width="${AVATAR_VIEW}" height="${AVATAR_VIEW}" tabindex="0" aria-label="${t("avatarCropLabel")}" aria-describedby="avatar-crop-help"></canvas>${tr("avatarCropHelp", "p", 'id="avatar-crop-help" class="small"')}<label class="avatar-zoom" for="avatar-zoom">${tr("avatarZoom", "span")}<input id="avatar-zoom" type="range" min="100" max="${MAX_ZOOM * 100}" step="5"></label><div class="avatar-actions"><button class="button primary" id="avatar-save" type="button">${tr(saving ? "avatarSaving" : "avatarSave")}</button><button class="button secondary" id="avatar-reset" type="button">${tr("avatarReset")}</button><button class="button quiet" id="avatar-cancel" type="button">${tr("avatarCancel")}</button></div></div>`;
|
||||||
|
const canvas = find<HTMLCanvasElement>("#avatar-canvas", host);
|
||||||
|
const zoom = find<HTMLInputElement>("#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<HTMLButtonElement>("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<string, [number, number]> = {
|
||||||
|
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<HTMLElement>("#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<HTMLElement>("#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<Blob | null>((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<HTMLElement>(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<HTMLElement>("#avatar-pick")?.focus();
|
||||||
|
}
|
||||||
function stopResendTimer() {
|
function stopResendTimer() {
|
||||||
clearInterval(resendTimer);
|
clearInterval(resendTimer);
|
||||||
resendTimer = undefined;
|
resendTimer = undefined;
|
||||||
|
|
@ -422,6 +696,8 @@ async function logout() {
|
||||||
});
|
});
|
||||||
currentSession = { authenticated: false };
|
currentSession = { authenticated: false };
|
||||||
logoutState = "idle";
|
logoutState = "idle";
|
||||||
|
closeAvatarEditor();
|
||||||
|
avatarMessage = null;
|
||||||
renderAccount();
|
renderAccount();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ApiError && error.status === 401) {
|
if (error instanceof ApiError && error.status === 401) {
|
||||||
|
|
|
||||||
56
src/crop.ts
Normal file
56
src/crop.ts
Normal file
|
|
@ -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 });
|
||||||
|
}
|
||||||
|
|
@ -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.",
|
"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",
|
privacyCollectTitle: "What we receive",
|
||||||
privacyCollectText:
|
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",
|
privacyCookiesTitle: "Cookies",
|
||||||
privacyCookiesText:
|
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.",
|
"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",
|
privacyTrackTitle: "Tracking and third parties",
|
||||||
privacyTrackText:
|
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",
|
privacyOtherTitle: "Community servers and the client",
|
||||||
privacyOtherText:
|
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.",
|
"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",
|
privacyDeleteTitle: "Deleting your data",
|
||||||
privacyDeleteText:
|
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",
|
lightTitle: "A light client",
|
||||||
lightText:
|
lightText:
|
||||||
"The Rust and Slint client does not carry a browser with it. It uses about 120 MB of memory when idle.",
|
"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",
|
copy: "Copy account ID",
|
||||||
copied: "Account ID copied",
|
copied: "Account ID copied",
|
||||||
copyError: "Could not copy the ID. Select it manually.",
|
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",
|
emailOr: "or",
|
||||||
emailTitle: "Sign in with email",
|
emailTitle: "Sign in with email",
|
||||||
emailText:
|
emailText:
|
||||||
|
|
|
||||||
|
|
@ -63,19 +63,19 @@ export const ru: Catalog = {
|
||||||
"Это политика сайта и Vnox Central. Чаты на серверах сообществ и настольный клиент сюда не входят, о них ниже.",
|
"Это политика сайта и Vnox Central. Чаты на серверах сообществ и настольный клиент сюда не входят, о них ниже.",
|
||||||
privacyCollectTitle: "Что мы получаем",
|
privacyCollectTitle: "Что мы получаем",
|
||||||
privacyCollectText:
|
privacyCollectText:
|
||||||
"При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений.",
|
"При входе через GitHub мы сохраняем числовой ID, имя пользователя, отображаемое имя и ссылку на аватар из вашего публичного профиля. Доступ к репозиториям и приватной почте не запрашивается. Токен GitHub используется один раз, чтобы прочитать профиль, и сразу удаляется. При входе по почте мы сохраняем ваш адрес, приведённый к строчным буквам, как идентификатор входа и используем его только для отправки кода. Сам код хранится не открытым текстом, а в виде HMAC с секретом сервера, действует 10 минут и после использования удаляется. Для защиты от злоупотреблений около часа хранятся только HMAC-отпечатки адреса и сети, из которой пришёл запрос, без самих значений. Если вы загружаете фото, мы сохраняем его как PNG 256 на 256, который сами перекодируем, поэтому EXIF и геометки из оригинала в нём нет. Хранится одно фото на аккаунт, исходный файл не сохраняется.",
|
||||||
privacyCookiesTitle: "Cookie",
|
privacyCookiesTitle: "Cookie",
|
||||||
privacyCookiesText:
|
privacyCookiesText:
|
||||||
"Только необходимые: короткий cookie на время входа через GitHub или по почте (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.",
|
"Только необходимые: короткий cookie на время входа через GitHub или по почте (10 минут) и cookie сессии (7 дней). Они защищены флагами Secure и HttpOnly, а в базе хранится только хеш сессии. Выход из аккаунта завершает сессию.",
|
||||||
privacyTrackTitle: "Слежка и сторонние сервисы",
|
privacyTrackTitle: "Слежка и сторонние сервисы",
|
||||||
privacyTrackText:
|
privacyTrackText:
|
||||||
"На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.",
|
"На сайте нет аналитики, рекламы и сторонних скриптов. Выбранный язык хранится в вашем браузере. Аватар GitHub загружается с avatars.githubusercontent.com, поэтому GitHub видит ваш IP-адрес. Ваше собственное фото загружается с нашего сервера. Запросы входа не попадают в журналы веб-сервера. Письмо с кодом уходит через почтовый SMTP-сервис, поэтому он видит ваш адрес и текст письма.",
|
||||||
privacyOtherTitle: "Серверы сообществ и клиент",
|
privacyOtherTitle: "Серверы сообществ и клиент",
|
||||||
privacyOtherText:
|
privacyOtherText:
|
||||||
"Серверы VNOX ведут сами владельцы. Сообщения и файлы на сервере находятся у его владельца, и правила хранения задаёт он. Настольный клиент хранит ваш ключ и настройки на вашем устройстве.",
|
"Серверы VNOX ведут сами владельцы. Сообщения и файлы на сервере находятся у его владельца, и правила хранения задаёт он. Настольный клиент хранит ваш ключ и настройки на вашем устройстве.",
|
||||||
privacyDeleteTitle: "Удаление данных",
|
privacyDeleteTitle: "Удаление данных",
|
||||||
privacyDeleteText:
|
privacyDeleteText:
|
||||||
"Кнопки удаления аккаунта пока нет. Чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись.",
|
"Нажмите «Убрать фото» на странице аккаунта, и фото будет удалено; оно также удаляется вместе с остальными данными. Кнопки удаления всего аккаунта пока нет: чтобы удалить данные, напишите в issues репозитория сервера, и мы удалим вашу запись. Удалённые данные могут оставаться в резервных копиях базы до 30 дней.",
|
||||||
lightTitle: "Лёгкий клиент",
|
lightTitle: "Лёгкий клиент",
|
||||||
lightText:
|
lightText:
|
||||||
"Клиент на Rust и Slint не носит с собой браузер. В простое он занимает около 120 МБ памяти.",
|
"Клиент на Rust и Slint не носит с собой браузер. В простое он занимает около 120 МБ памяти.",
|
||||||
|
|
@ -163,6 +163,28 @@ export const ru: Catalog = {
|
||||||
copy: "Скопировать ID",
|
copy: "Скопировать ID",
|
||||||
copied: "ID скопирован",
|
copied: "ID скопирован",
|
||||||
copyError: "Не удалось скопировать 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: "или",
|
emailOr: "или",
|
||||||
emailTitle: "Войти по почте",
|
emailTitle: "Войти по почте",
|
||||||
emailText:
|
emailText:
|
||||||
|
|
|
||||||
|
|
@ -2169,3 +2169,73 @@ p {
|
||||||
.privacy-block p {
|
.privacy-block p {
|
||||||
margin-top: 10px;
|
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;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,8 @@ import {
|
||||||
ApiError,
|
ApiError,
|
||||||
requestEmailCode,
|
requestEmailCode,
|
||||||
verifyEmailCode,
|
verifyEmailCode,
|
||||||
|
uploadAvatar,
|
||||||
|
removeAvatar,
|
||||||
} from "../src/api";
|
} from "../src/api";
|
||||||
import { messages, detectLanguage } from "../src/i18n";
|
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,
|
(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,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ Run with an already running npm run dev/preview. All API responses are test fixt
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from playwright.sync_api import sync_playwright
|
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 = Path(args.artifacts)
|
||||||
artifacts.mkdir(parents=True, exist_ok=True)
|
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:
|
with sync_playwright() as p:
|
||||||
browser = p.chromium.launch(executable_path='/usr/bin/chromium', headless=True, args=['--no-sandbox'])
|
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')
|
context = browser.new_context(viewport={'width': 1440, 'height': 1000}, locale='ru-RU')
|
||||||
mail = {'starts': [], 'verifies': [], 'start_status': 202, 'verify_status': 400, 'good_code': '12345678'}
|
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}
|
state = {'info': {'capabilities': {'github_auth': 'enabled'}}, 'session': {'authenticated': False}, 'info_status': 200, 'session_status': 200, 'logout_status': 204}
|
||||||
logouts = []
|
logouts = []
|
||||||
|
avatar = {'status': 200, 'uploads': [], 'deletes': []}
|
||||||
def api(route):
|
def api(route):
|
||||||
path = urlparse(route.request.url).path
|
path = urlparse(route.request.url).path
|
||||||
if path == '/v1/info': route.fulfill(status=state['info_status'], json=state['info'])
|
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}}
|
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'])
|
route.fulfill(status=200, json=state['session'])
|
||||||
else: route.fulfill(status=mail['verify_status'], json={'error': 'invalid_code'})
|
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':
|
elif path == '/v1/auth/logout':
|
||||||
logouts.append({'method': route.request.method, 'headers': route.request.all_headers()})
|
logouts.append({'method': route.request.method, 'headers': route.request.all_headers()})
|
||||||
route.fulfill(status=state['logout_status'], body='' if state['logout_status'] == 204 else '{}')
|
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.locator('#profile-id').wait_for()
|
||||||
page.set_viewport_size({'width': 1440, 'height': 1000})
|
page.set_viewport_size({'width': 1440, 'height': 1000})
|
||||||
page.screenshot(path=str(artifacts / 'account-profile-desktop.png'))
|
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']:
|
for locale in ['ru', 'en']:
|
||||||
page.locator(f'[data-language="{locale}"]').click()
|
page.locator(f'[data-language="{locale}"]').click()
|
||||||
for width in [320,390,768,1440]:
|
for width in [320,390,768,1440]:
|
||||||
|
|
@ -203,4 +297,4 @@ with sync_playwright() as p:
|
||||||
page.locator('.github-login').wait_for()
|
page.locator('.github-login').wait_for()
|
||||||
assert not errors, errors
|
assert not errors, errors
|
||||||
browser.close()
|
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)}))
|
||||||
|
|
|
||||||
40
tests/crop.test.ts
Normal file
40
tests/crop.test.ts
Normal file
|
|
@ -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);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue