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:
parent
309b77e63c
commit
a4cae66336
9 changed files with 528 additions and 28 deletions
183
src/app.ts
183
src/app.ts
|
|
@ -1,7 +1,15 @@
|
|||
import type { Language, MessageKey } from "./i18n";
|
||||
import type { Session } from "./api";
|
||||
import { detectLanguage, translate } from "./i18n";
|
||||
import { request, isSession, isInfo, safeAvatar, ApiError } from "./api";
|
||||
import {
|
||||
request,
|
||||
isSession,
|
||||
isInfo,
|
||||
safeAvatar,
|
||||
ApiError,
|
||||
requestEmailCode,
|
||||
verifyEmailCode,
|
||||
} from "./api";
|
||||
|
||||
let savedLanguage: string | null | undefined;
|
||||
try {
|
||||
|
|
@ -31,6 +39,17 @@ let activeTheme: Theme = "dark";
|
|||
let controller: AbortController | undefined;
|
||||
let currentSession: Session | null = null;
|
||||
let githubEnabled = false;
|
||||
let emailEnabled = false;
|
||||
// Email sign-in form state. Kept outside the DOM so a language switch or a
|
||||
// re-render does not lose what was typed.
|
||||
let emailStep: "address" | "code" = "address";
|
||||
let emailAddress = "";
|
||||
let emailCode = "";
|
||||
let emailBusy: "idle" | "sending" | "verifying" = "idle";
|
||||
let emailMessage: MessageKey | null = null;
|
||||
let emailField: "address" | "code" | null = null;
|
||||
let resendUntil = 0;
|
||||
let resendTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let sessionState: "loading" | "ready" | "error" = "loading";
|
||||
let infoState: "loading" | "ready" | "error" = "loading";
|
||||
let logoutState: "idle" | "pending" | "error" = "idle";
|
||||
|
|
@ -195,7 +214,7 @@ function renderAccount() {
|
|||
return;
|
||||
}
|
||||
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><div><dt>${tr("provider")}</dt><dd>GitHub</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><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;
|
||||
find("#profile-name", panel).textContent =
|
||||
user.display_name || t("profileFallback");
|
||||
|
|
@ -223,7 +242,7 @@ function renderAccount() {
|
|||
find("#profile-message", panel).textContent = t("logoutError");
|
||||
return;
|
||||
}
|
||||
panel.innerHTML = `<div class="login-provider">${icon("github", 33)}</div>${tr("loginTitle", "h2")}${tr("loginText", "p")}<a class="button primary github-login ${githubEnabled ? "" : "unavailable"}" ${githubEnabled ? 'href="/v1/auth/github/start"' : 'aria-disabled="true" tabindex="-1"'}>${icon("github", 21)}${tr("loginButton")}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState === "error" ? "" : "hidden"}>${tr("retry")}</button><div class="privacy-note">${icon("check", 16)}${tr("privacy", "p")}</div>`;
|
||||
panel.innerHTML = `<div class="login-provider">${icon("github", 33)}</div>${tr("loginTitle", "h2")}${tr("loginText", "p")}<a class="button primary github-login ${githubEnabled ? "" : "unavailable"}" ${githubEnabled ? 'href="/v1/auth/github/start"' : 'aria-disabled="true" tabindex="-1"'}>${icon("github", 21)}${tr("loginButton")}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState === "error" ? "" : "hidden"}>${tr("retry")}</button><div id="email-area"></div><div class="privacy-note">${icon("check", 16)}${tr("privacy", "p")}</div>`;
|
||||
find("#login-availability", panel).textContent =
|
||||
infoState === "loading"
|
||||
? t("loginLoading")
|
||||
|
|
@ -233,6 +252,162 @@ function renderAccount() {
|
|||
? ""
|
||||
: t("loginDisabled");
|
||||
find("#retry-info", panel).addEventListener("click", refresh);
|
||||
renderEmail();
|
||||
}
|
||||
function stopResendTimer() {
|
||||
clearInterval(resendTimer);
|
||||
resendTimer = undefined;
|
||||
}
|
||||
function tickResend() {
|
||||
const button = document.querySelector<HTMLButtonElement>("#resend");
|
||||
if (!button) return stopResendTimer();
|
||||
const left = Math.max(0, Math.ceil((resendUntil - Date.now()) / 1000));
|
||||
button.disabled = left > 0 || emailBusy !== "idle";
|
||||
button.textContent =
|
||||
left > 0
|
||||
? t("emailResendIn").replace("{seconds}", String(left))
|
||||
: t("emailResend");
|
||||
if (left === 0) stopResendTimer();
|
||||
}
|
||||
const looksLikeEmail = (value: string) =>
|
||||
value.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
||||
function emailFailure(error: unknown, rejected: MessageKey): MessageKey {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.status === 400) return rejected;
|
||||
if (error.status === 429) return "emailTooMany";
|
||||
}
|
||||
return "emailFailed";
|
||||
}
|
||||
/** Draws the email form into #email-area. Hidden unless Hub reports email_auth: enabled. */
|
||||
function renderEmail() {
|
||||
const area = document.querySelector("#email-area");
|
||||
if (!area) return;
|
||||
stopResendTimer();
|
||||
area.replaceChildren();
|
||||
if (!emailEnabled) return;
|
||||
const busy = emailBusy !== "idle";
|
||||
const invalid = emailMessage !== null && emailField !== null;
|
||||
const describedBy = 'aria-describedby="email-message"';
|
||||
const aria = (field: "address" | "code") =>
|
||||
invalid && emailField === field ? 'aria-invalid="true"' : "";
|
||||
const stepHtml =
|
||||
emailStep === "address"
|
||||
? `<label for="email-input">${tr("emailLabel")}</label><input id="email-input" class="field" type="email" name="email" autocomplete="email" inputmode="email" autocapitalize="none" spellcheck="false" maxlength="254" required ${describedBy} ${aria("address")}><button class="button secondary" type="submit" id="email-submit" ${busy ? "disabled" : ""}>${t(emailBusy === "sending" ? "emailSending" : "emailSend")}</button>`
|
||||
: `<p id="email-sent"></p><label for="code-input">${tr("codeLabel")}</label><input id="code-input" class="field code-field" type="text" name="code" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code" autocapitalize="none" spellcheck="false" maxlength="8" required ${describedBy} ${aria("code")}><button class="button secondary" type="submit" id="email-submit" ${busy ? "disabled" : ""}>${t(emailBusy === "verifying" ? "codeVerifying" : "codeVerify")}</button><div class="email-actions"><button class="text-button" type="button" id="resend"></button><button class="text-button" type="button" id="change-email" ${busy ? "disabled" : ""}>${tr("emailChange")}</button></div>`;
|
||||
area.innerHTML = `<div class="login-divider" role="separator"><span>${tr("emailOr")}</span></div><form class="email-form" id="email-form" novalidate aria-busy="${busy}">${tr("emailTitle", "h3")}${emailStep === "address" ? tr("emailText", "p", 'class="email-text"') : ""}${stepHtml}<p class="form-message" id="email-message" role="status" aria-live="polite"></p></form>`;
|
||||
const form = find<HTMLFormElement>("#email-form", area);
|
||||
find("#email-message", area).textContent = emailMessage
|
||||
? t(emailMessage)
|
||||
: "";
|
||||
if (emailStep === "address") {
|
||||
const input = find<HTMLInputElement>("#email-input", area);
|
||||
input.value = emailAddress;
|
||||
input.addEventListener("input", () => (emailAddress = input.value));
|
||||
} else {
|
||||
find("#email-sent", area).textContent = t("emailCodeSent").replace(
|
||||
"{address}",
|
||||
emailAddress.trim().toLowerCase(),
|
||||
);
|
||||
const input = find<HTMLInputElement>("#code-input", area);
|
||||
input.value = emailCode;
|
||||
input.addEventListener("input", () => {
|
||||
input.value = input.value.replace(/\D/g, "").slice(0, 8);
|
||||
emailCode = input.value;
|
||||
});
|
||||
find("#resend", area).addEventListener("click", () => submitEmail(true));
|
||||
find("#change-email", area).addEventListener("click", () => {
|
||||
emailStep = "address";
|
||||
emailCode = "";
|
||||
emailMessage = null;
|
||||
emailField = null;
|
||||
resendUntil = 0;
|
||||
renderEmail();
|
||||
find<HTMLInputElement>("#email-input").focus();
|
||||
});
|
||||
tickResend();
|
||||
if (resendUntil > Date.now()) resendTimer = setInterval(tickResend, 1000);
|
||||
}
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (emailBusy === "idle")
|
||||
void (emailStep === "address" ? submitEmail(false) : submitCode());
|
||||
});
|
||||
}
|
||||
function focusEmailField() {
|
||||
document
|
||||
.querySelector<HTMLInputElement>(
|
||||
emailStep === "address" ? "#email-input" : "#code-input",
|
||||
)
|
||||
?.focus();
|
||||
}
|
||||
async function submitEmail(resend: boolean) {
|
||||
if (emailBusy !== "idle") return;
|
||||
const address = emailAddress.trim();
|
||||
if (!looksLikeEmail(address)) {
|
||||
emailMessage = "emailInvalid";
|
||||
emailField = "address";
|
||||
renderEmail();
|
||||
focusEmailField();
|
||||
return;
|
||||
}
|
||||
emailAddress = address;
|
||||
emailBusy = "sending";
|
||||
emailMessage = null;
|
||||
emailField = null;
|
||||
renderEmail();
|
||||
try {
|
||||
const result = await requestEmailCode(address, language, {
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
emailStep = "code";
|
||||
emailCode = "";
|
||||
resendUntil = Date.now() + result.resendAfter * 1000;
|
||||
emailMessage = resend ? "emailResent" : null;
|
||||
emailField = null;
|
||||
emailBusy = "idle";
|
||||
renderEmail();
|
||||
focusEmailField();
|
||||
} catch (error) {
|
||||
emailBusy = "idle";
|
||||
emailMessage = emailFailure(error, "emailInvalid");
|
||||
emailField = emailMessage === "emailInvalid" ? "address" : null;
|
||||
// A failed resend keeps the code step; the old code stays usable until it expires.
|
||||
renderEmail();
|
||||
if (emailStep === "address") focusEmailField();
|
||||
}
|
||||
}
|
||||
async function submitCode() {
|
||||
if (emailBusy !== "idle") return;
|
||||
if (!/^[0-9]{8}$/.test(emailCode)) {
|
||||
emailMessage = "emailCodeShape";
|
||||
emailField = "code";
|
||||
renderEmail();
|
||||
focusEmailField();
|
||||
return;
|
||||
}
|
||||
emailBusy = "verifying";
|
||||
emailMessage = null;
|
||||
emailField = null;
|
||||
renderEmail();
|
||||
try {
|
||||
currentSession = await verifyEmailCode(emailAddress, emailCode, {
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
emailStep = "address";
|
||||
emailAddress = "";
|
||||
emailCode = "";
|
||||
emailBusy = "idle";
|
||||
emailMessage = null;
|
||||
logoutState = "idle";
|
||||
renderAccount();
|
||||
} catch (error) {
|
||||
emailBusy = "idle";
|
||||
emailCode = "";
|
||||
emailMessage = emailFailure(error, "emailInvalidCode");
|
||||
emailField = emailMessage === "emailInvalidCode" ? "code" : null;
|
||||
renderEmail();
|
||||
focusEmailField();
|
||||
}
|
||||
}
|
||||
async function logout() {
|
||||
if (!currentSession?.authenticated || logoutState === "pending") return;
|
||||
|
|
@ -290,11 +465,13 @@ async function refresh() {
|
|||
if (controller !== currentController) return;
|
||||
if (!isInfo(value)) throw new Error("invalid_info");
|
||||
githubEnabled = value.capabilities.github_auth === "enabled";
|
||||
emailEnabled = value.capabilities.email_auth === "enabled";
|
||||
infoState = "ready";
|
||||
})
|
||||
.catch(() => {
|
||||
if (!currentController.signal.aborted) {
|
||||
githubEnabled = false;
|
||||
emailEnabled = false;
|
||||
infoState = "error";
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue