feat(web): sign in by emailed code on the account page

Adds the email form (address, code, resend timer, aria-live status) shown only when
/v1/info reports email_auth enabled, RU/EN strings, privacy policy update, API
helpers, tests and browser QA with a mocked Hub.
This commit is contained in:
Loki 2026-10-24 17:49:41 +02:00
parent 309b77e63c
commit a4cae66336
Signed by: boba
GPG key ID: 253067914055423B
9 changed files with 528 additions and 28 deletions

View file

@ -1,6 +1,14 @@
import { test } from "bun:test";
import assert from "node:assert/strict";
import { request, isSession, isInfo, safeAvatar, ApiError } from "../src/api";
import {
request,
isSession,
isInfo,
safeAvatar,
ApiError,
requestEmailCode,
verifyEmailCode,
} from "../src/api";
import { messages, detectLanguage } from "../src/i18n";
test("catalogs match and never silently fall back to a missing translation", () => {
@ -105,3 +113,63 @@ test("Hub capabilities reject malformed JSON before enabling sign-in", () => {
assert.equal(isInfo(value), false);
}
});
test("email_auth capability must be a string when present", () => {
assert.ok(
isInfo({ capabilities: { github_auth: "enabled", email_auth: "enabled" } }),
);
assert.ok(isInfo({ capabilities: { github_auth: "enabled" } }));
assert.equal(
isInfo({ capabilities: { github_auth: "enabled", email_auth: true } }),
false,
);
});
test("email code requests send JSON same-origin and bound the resend delay", async () => {
let seen: { path: string; init: RequestInit } | undefined;
const result = await requestEmailCode("a@example.com", "en", {
fetcher: async (path, init) => {
seen = { path, init };
return Response.json({ resend_after: 999999 }, { status: 202 });
},
});
assert.equal(result.resendAfter, 60);
assert.ok(seen);
assert.equal(seen.path, "/v1/auth/email/start");
assert.equal(seen.init.method, "POST");
assert.equal(seen.init.credentials, "same-origin");
assert.equal(
new Headers(seen.init.headers).get("Content-Type"),
"application/json",
);
assert.deepEqual(JSON.parse(String(seen.init.body)), {
email: "a@example.com",
lang: "en",
});
const short = await requestEmailCode("a@example.com", "ru", {
fetcher: async () => Response.json({ resend_after: 30 }, { status: 202 }),
});
assert.equal(short.resendAfter, 30);
});
test("email verification accepts only an authenticated session and keeps the status", async () => {
const session = {
authenticated: true,
csrf_token: "fixture",
user: { user_id: "u", handle: "h", display_name: "n" },
};
const ok = await verifyEmailCode("a@example.com", "12345678", {
fetcher: async () => Response.json(session),
});
assert.equal(ok.authenticated, true);
await assert.rejects(
verifyEmailCode("a@example.com", "12345678", {
fetcher: async () => Response.json({ authenticated: false }),
}),
);
await assert.rejects(
verifyEmailCode("a@example.com", "12345678", {
fetcher: async () =>
Response.json({ error: "invalid_code" }, { status: 400 }),
}),
(error: unknown) => error instanceof ApiError && error.status === 400,
);
});

View file

@ -19,12 +19,24 @@ artifacts.mkdir(parents=True, exist_ok=True)
with sync_playwright() as p:
browser = p.chromium.launch(executable_path='/usr/bin/chromium', headless=True, args=['--no-sandbox'])
context = browser.new_context(viewport={'width': 1440, 'height': 1000}, locale='ru-RU')
mail = {'starts': [], 'verifies': [], 'start_status': 202, 'verify_status': 400, 'good_code': '12345678'}
state = {'info': {'capabilities': {'github_auth': 'enabled'}}, 'session': {'authenticated': False}, 'info_status': 200, 'session_status': 200, 'logout_status': 204}
logouts = []
def api(route):
path = urlparse(route.request.url).path
if path == '/v1/info': route.fulfill(status=state['info_status'], json=state['info'])
elif path == '/v1/auth/session': route.fulfill(status=state['session_status'], json=state['session'])
elif path == '/v1/auth/email/start':
body = json.loads(route.request.post_data or '{}')
mail['starts'].append({'body': body, 'headers': route.request.all_headers()})
route.fulfill(status=mail['start_status'], json={'status': 'code_requested', 'expires_in': 600, 'resend_after': 3} if mail['start_status'] == 202 else {'error': 'try_later'})
elif path == '/v1/auth/email/verify':
body = json.loads(route.request.post_data or '{}')
mail['verifies'].append(body)
if body.get('code') == mail['good_code']:
state['session'] = {'authenticated': True, 'csrf_token': 'email-csrf', 'user': {'user_id': 'email-id', 'handle': 'u_emailfixture', 'display_name': 'Vnox user', 'avatar_url': None}}
route.fulfill(status=200, json=state['session'])
else: route.fulfill(status=mail['verify_status'], json={'error': 'invalid_code'})
elif path == '/v1/auth/logout':
logouts.append({'method': route.request.method, 'headers': route.request.all_headers()})
route.fulfill(status=state['logout_status'], body='' if state['logout_status'] == 204 else '{}')
@ -77,6 +89,81 @@ with sync_playwright() as p:
page.reload()
page.locator('#login-availability').filter(has_text='выключен').wait_for()
assert page.locator('.github-login').get_attribute('href') is None
# Email sign-in: hidden unless Hub reports email_auth enabled.
assert page.locator('#email-form').count() == 0
state['info'] = {'capabilities': {'github_auth': 'enabled', 'email_auth': 'not_enabled'}}
page.reload()
page.locator('.github-login').wait_for()
page.wait_for_timeout(300)
assert page.locator('#email-form').count() == 0
state['info'] = {'capabilities': {'github_auth': 'enabled', 'email_auth': 'enabled'}}
page.reload()
page.locator('#email-input').wait_for()
page.screenshot(path=str(artifacts / 'account-email-address.png'), full_page=True)
# Invalid address is caught in the browser, with focus and aria state.
page.locator('#email-input').fill('not-an-address')
page.locator('#email-input').press('Enter')
page.locator('#email-message').filter(has_text='Проверьте адрес').wait_for()
assert page.locator('#email-input').get_attribute('aria-invalid') == 'true'
assert page.evaluate("document.activeElement.id") == 'email-input'
assert page.locator('#email-message').get_attribute('role') == 'status'
assert not mail['starts']
# Server-side rate limit and outage are reported without leaving the step.
mail['start_status'] = 429
page.locator('#email-input').fill(' Person@Example.com ')
page.locator('#email-submit').click()
page.locator('#email-message').filter(has_text='Слишком много').wait_for()
mail['start_status'] = 503
page.locator('#email-submit').click()
page.locator('#email-message').filter(has_text='Не получилось').wait_for()
mail['start_status'] = 202
page.locator('#email-input').press('Enter')
page.locator('#code-input').wait_for()
assert page.evaluate("document.activeElement.id") == 'code-input'
sent = mail['starts'][-1]
assert sent['body'] == {'email': 'Person@Example.com', 'lang': 'ru'}, sent['body']
assert sent['headers']['origin'] == args.url
assert sent['headers']['content-type'] == 'application/json'
assert page.locator('#email-sent').inner_text().count('person@example.com') == 1
page.screenshot(path=str(artifacts / 'account-email-code.png'), full_page=True)
# Resend is locked by the timer (3 s fixture), then works.
assert page.locator('#resend').is_disabled()
assert 'через' in page.locator('#resend').inner_text()
page.locator('#resend:not([disabled])').wait_for(timeout=6000)
page.locator('#resend').click()
page.locator('#email-message').filter(has_text='Новый код отправлен').wait_for()
assert len(mail['starts']) == 4
# Language switch keeps the step and the typed address, and relabels the form.
page.locator('#code-input').fill('12ab34')
assert page.locator('#code-input').input_value() == '1234'
page.locator('[data-language="en"]').click()
assert page.locator('label[for="code-input"]').inner_text() == 'Code from the email'
assert page.locator('#code-input').input_value() == '1234'
page.locator('[data-language="ru"]').click()
# Short code, wrong code, then the right one.
page.locator('#email-submit').click()
page.locator('#email-message').filter(has_text='8 цифр').wait_for()
page.locator('#code-input').fill('00000000')
page.locator('#email-submit').click()
page.locator('#email-message').filter(has_text='не подошёл').wait_for()
assert page.locator('#code-input').get_attribute('aria-invalid') == 'true'
assert page.locator('#code-input').input_value() == ''
page.locator('#change-email').click()
assert page.locator('#email-input').input_value() == 'Person@Example.com'
page.locator('#email-submit').click()
page.locator('#code-input').wait_for()
for width in [320, 390, 768, 1440]:
page.set_viewport_size({'width': width, 'height': 844})
assert not page.evaluate('document.documentElement.scrollWidth > innerWidth'), ('email', width)
page.set_viewport_size({'width': 1440, 'height': 1000})
page.locator('#code-input').fill('12345678')
page.locator('#code-input').press('Enter')
page.locator('#profile-id').wait_for()
assert mail['verifies'][-1] == {'email': 'Person@Example.com', 'code': '12345678'}
assert page.locator('#email-form').count() == 0
assert page.evaluate('Object.keys(localStorage)') == ['vnox-web-language']
state['session'] = {'authenticated': False}
state['info'] = {'capabilities': {'github_auth': 'enabled'}}
state['info_status'] = 503
page.reload()
page.locator('#retry-info:not([hidden])').wait_for()
@ -116,4 +203,4 @@ with sync_playwright() as p:
page.locator('.github-login').wait_for()
assert not errors, errors
browser.close()
print(json.dumps({'result':'passed','assertions':'tabs, theme, RU/EN, 320/390/768/1440 layout, login enabled/disabled/errors, session/profile XSS safety, CSRF logout/expired session, no persisted secrets','artifacts':str(artifacts)}))
print(json.dumps({'result':'passed','assertions':'tabs, theme, RU/EN, 320/390/768/1440 layout, login enabled/disabled/errors, email code flow with fixtures, session/profile XSS safety, CSRF logout/expired session, no persisted secrets','artifacts':str(artifacts)}))

View file

@ -108,3 +108,16 @@ test("app templates avoid inline style attributes blocked by the site CSP", asyn
const source = await Bun.file("src/app.ts").text();
assert.doesNotMatch(source, /style="/);
});
test("privacy text describes email sign-in in both languages", () => {
for (const [name, catalog] of Object.entries(messages)) {
const text = [
catalog.privacyCollectText,
catalog.privacyTrackText,
catalog.privacyCookiesText,
].join(" ");
assert.match(text, /HMAC/, name);
assert.match(text, /10/, name);
assert.match(text, /SMTP/, name);
}
});