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
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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)}))
|
||||
|
|
|
|||
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