Сервер: миграция 001 со всей схемой storage.md, store на modernc.org/sqlite (WAL, foreign_keys, один писатель), фоновая чистка раз в час, argon2id с параметрами ADR-021 и сверкой constant-time, сессии по SHA-256 токена, cookie bare_session, глобальная проверка Origin, девять эндпоинтов аккаунта. Ник в журнал не попадает: для /api/ пишется шаблон маршрута. Клиент: crypto.js по crypto.md построчно — мастер из пароля, два независимых ключа из мастера, ключевой блоб с ником в AAD, отпечаток от сырой точки; db.js со всеми хранилищами версии 1; экран входа и регистрации, настройки со сменой пароля, выходом и удалением аккаунта. Пароль не покидает клиент: проверено на боевом сервере — ни пароля, ни priv.d ни в одном теле запроса, вход на втором устройстве даёт тот же отпечаток. ADR-027: код internal для 500, причина только в журнале. ADR-028: тексты состояний клиента сведены в ui.md. ADR-029: вход под другим ником стирает историю только после подтверждения. ADR-030: верхняя граница итераций KDF, проверка границ на обеих сторонах. ADR-031: служебный выход перед повторным входом не заканчивает сеанс. ADR-032: каталог состояния 0700, файлы базы 0600. Прямые зависимости: modernc.org/sqlite, golang.org/x/crypto. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015DbCjVfTFq4ZFG8juD45YJ
180 lines
6.1 KiB
JavaScript
180 lines
6.1 KiB
JavaScript
// Настройки — docs/ui.md, «Настройки». На этом этапе только разделы,
|
|
// которые уже работают: кто ты, смена пароля, выход, удаление аккаунта.
|
|
// Уведомления, устройства, история и установка приложения — дальше по плану.
|
|
|
|
import { ApiError } from "../api.js";
|
|
import { fingerprintGroups } from "../crypto.js";
|
|
import { button, confirmPanel, el, field, message, setError, setNote } from "./dom.js";
|
|
|
|
export function renderSettings(root, ctx) {
|
|
root.append(head(ctx));
|
|
const body = el("div", "body settings");
|
|
body.append(identity(ctx), passwordBlock(ctx), exitBlock(ctx), deleteBlock(ctx));
|
|
root.append(body);
|
|
}
|
|
|
|
function head(ctx) {
|
|
const bar = el("div", "head");
|
|
const back = button("назад", "back");
|
|
back.addEventListener("click", () => ctx.go("#/"));
|
|
bar.append(back, el("span", "title", "настройки"));
|
|
return bar;
|
|
}
|
|
|
|
// identity — «ты: @nick» и свой отпечаток группами по 4 в две строки.
|
|
function identity(ctx) {
|
|
const box = el("section", "block block--first");
|
|
box.append(el("p", "self", `ты: @${ctx.me.nick}`));
|
|
const groups = fingerprintGroups(ctx.me.fingerprint ?? "");
|
|
box.append(el("p", "fp", groups.slice(0, 8).join(" ")));
|
|
box.append(el("p", "fp", groups.slice(8).join(" ")));
|
|
return box;
|
|
}
|
|
|
|
function passwordBlock(ctx) {
|
|
const box = block("сменить пароль");
|
|
const form = el("form", "form");
|
|
form.noValidate = true;
|
|
|
|
const current = field("старый", { type: "password", autocomplete: "current-password" });
|
|
const next = field("новый", { type: "password", autocomplete: "new-password" });
|
|
const again = field("повтор", { type: "password", autocomplete: "new-password" });
|
|
form.append(current.wrap, next.wrap, again.wrap);
|
|
|
|
const check = el("label", "check");
|
|
const others = el("input");
|
|
others.type = "checkbox";
|
|
// Смена пароля по желанию завершает остальные сессии (ADR-015);
|
|
// снять галочку можно, но это осознанный выбор, а не умолчание.
|
|
others.checked = true;
|
|
check.append(others, el("span", null, "выйти на других устройствах"));
|
|
form.append(check);
|
|
|
|
const submit = el("button", "button", "сменить пароль");
|
|
submit.type = "submit";
|
|
const note = message();
|
|
form.append(submit, note);
|
|
|
|
form.addEventListener("submit", async (event) => {
|
|
event.preventDefault();
|
|
if (submit.disabled) {
|
|
return;
|
|
}
|
|
setNote(note, "");
|
|
if (next.input.value !== again.input.value) {
|
|
setError(note, "пароли не совпадают");
|
|
return;
|
|
}
|
|
if ([...next.input.value].length < ctx.minPassword) {
|
|
setError(note, `пароль: не короче ${ctx.minPassword} символов`);
|
|
return;
|
|
}
|
|
submit.disabled = true;
|
|
submit.textContent = "вычисляем ключ…";
|
|
try {
|
|
await ctx.changePassword(current.input.value, next.input.value, others.checked);
|
|
for (const input of [current.input, next.input, again.input]) {
|
|
input.value = "";
|
|
}
|
|
setNote(note, "пароль изменён");
|
|
} catch (err) {
|
|
setError(note, passwordError(ctx, err));
|
|
} finally {
|
|
submit.disabled = false;
|
|
submit.textContent = "сменить пароль";
|
|
}
|
|
});
|
|
|
|
box.append(form);
|
|
return box;
|
|
}
|
|
|
|
function exitBlock(ctx) {
|
|
const box = block("выйти");
|
|
const start = button("выйти");
|
|
// Кнопки «экспортировать» пока нет: экспорт — этап 5 (docs/plan.md).
|
|
const panel = confirmPanel("история на этом устройстве будет удалена. экспортировать сначала?", "выйти");
|
|
|
|
start.addEventListener("click", () => {
|
|
start.hidden = true;
|
|
panel.root.hidden = false;
|
|
panel.yes.focus();
|
|
});
|
|
panel.no.addEventListener("click", () => {
|
|
panel.root.hidden = true;
|
|
start.hidden = false;
|
|
start.focus();
|
|
});
|
|
panel.yes.addEventListener("click", async () => {
|
|
panel.yes.disabled = true;
|
|
panel.no.disabled = true;
|
|
await ctx.signOut();
|
|
ctx.go("#/");
|
|
});
|
|
|
|
box.append(start, panel.root);
|
|
return box;
|
|
}
|
|
|
|
function deleteBlock(ctx) {
|
|
const box = block("удалить аккаунт");
|
|
const form = el("form", "form");
|
|
form.noValidate = true;
|
|
|
|
const password = field("пароль", { type: "password", autocomplete: "current-password" });
|
|
const submit = el("button", "button", "удалить аккаунт");
|
|
submit.type = "submit";
|
|
const panel = confirmPanel("аккаунт и вся история будут удалены навсегда.", "удалить");
|
|
const note = message();
|
|
form.append(password.wrap, submit, panel.root, note);
|
|
|
|
const back = () => {
|
|
panel.root.hidden = true;
|
|
panel.yes.disabled = false;
|
|
panel.no.disabled = false;
|
|
panel.yes.textContent = "удалить";
|
|
submit.hidden = false;
|
|
};
|
|
|
|
form.addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
setNote(note, "");
|
|
submit.hidden = true;
|
|
panel.root.hidden = false;
|
|
panel.yes.focus();
|
|
});
|
|
panel.no.addEventListener("click", () => {
|
|
back();
|
|
submit.focus();
|
|
});
|
|
panel.yes.addEventListener("click", async () => {
|
|
panel.yes.disabled = true;
|
|
panel.no.disabled = true;
|
|
panel.yes.textContent = "вычисляем ключ…";
|
|
try {
|
|
await ctx.deleteAccount(password.input.value);
|
|
ctx.go("#/");
|
|
} catch (err) {
|
|
back();
|
|
setError(note, passwordError(ctx, err));
|
|
}
|
|
});
|
|
|
|
box.append(form);
|
|
return box;
|
|
}
|
|
|
|
function block(title) {
|
|
const box = el("section", "block");
|
|
box.append(el("h2", "section", title));
|
|
return box;
|
|
}
|
|
|
|
// passwordError: в настройках 401 означает ровно одно — не тот пароль.
|
|
function passwordError(ctx, err) {
|
|
if (err instanceof ApiError && err.code === "invalid_credentials") {
|
|
return "неверный пароль";
|
|
}
|
|
return ctx.errorText(err);
|
|
}
|