/* The account screen, for an app that has not written a UI for it. * * * * * That is the whole of it. The element asks `/api/account` what there is to * know, and draws the four things there are to do about it: change the * password, look at what is signed in and revoke any of it, register and * revoke passkeys, and sign out. * * One file, and the styles are in it rather than beside it, because the shadow * root scopes them anyway and a second file is a second route, a second cache * header and a second thing to forget to copy. Themed from outside through the * same `--desk-jobs-*` custom properties `` reads -- set them once * on `desk-jobs, desk-schedules, auth-account` and the queue's elements and * this one look like one application rather than three. * * Failures are said in place, next to the button that caused them, *and* * raised as an `auth-account:error` event carrying the server's own `detail`, * so an app with toasts can show one without this element knowing what a toast * is. Same split as `desk-jobs:notice`. * * Attributes, both optional: * base="/api" prefix for the HTTP calls, if the router is mounted deeper * login="/login" where signing out sends the browser */ const CSS = ` :host { --desk-jobs-bg: #16181d; --desk-jobs-fg: #e7e9ee; --desk-jobs-dim: #9aa1ad; --desk-jobs-accent: #4c8dff; --desk-jobs-error: #ff6b6b; --desk-jobs-radius: 10px; --desk-jobs-font: system-ui, -apple-system, "Segoe UI", sans-serif; --desk-jobs-gap: 8px; display: block; font-family: var(--desk-jobs-font); font-size: 14px; color: var(--desk-jobs-fg); } :host([hidden]) { display: none; } .panel { display: flex; flex-direction: column; gap: calc(var(--desk-jobs-gap) * 2); } section { display: flex; flex-direction: column; gap: var(--desk-jobs-gap); } h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--desk-jobs-dim); margin: 0; font-weight: 600; } .said { color: var(--desk-jobs-dim); } .said.bad { color: var(--desk-jobs-error); } .what { font-weight: 600; } .row { display: flex; align-items: baseline; justify-content: space-between; gap: var(--desk-jobs-gap); padding: 6px 0; border-top: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 12%, transparent); } .row:first-of-type { border-top: 0; } .row .lines { display: flex; flex-direction: column; min-width: 0; } .row .acts { display: flex; gap: var(--desk-jobs-gap); flex: none; } form { display: flex; flex-wrap: wrap; gap: var(--desk-jobs-gap); align-items: center; } input { font: inherit; color: inherit; background: transparent; border: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 25%, transparent); border-radius: 6px; padding: 3px 7px; min-width: 11rem; } button { font: inherit; color: var(--desk-jobs-dim); background: none; border: 1px solid currentColor; border-radius: 6px; padding: 2px 9px; cursor: pointer; } button:hover { color: var(--desk-jobs-accent); } button.danger:hover { color: var(--desk-jobs-error); } button[disabled] { opacity: .4; cursor: default; } .badge { font-size: 12px; padding: 0 6px; border-radius: 999px; border: 1px solid currentColor; color: var(--desk-jobs-dim); } `; /** What the server says when this build has no `webauthn` installed. The * element takes the whole passkey section off the screen rather than leaving * buttons that can only ever fail -- and 501 is the status that says "this * route exists and this build cannot do it", which is exactly the case. */ const NOT_BUILT = 501; class AuthAccount extends HTMLElement { #root; #panel; #account = null; #busy = false; /** The one line under the status block: what the last button did, or why it * did not. Kept on the element rather than in the DOM because every action * reloads the account and redraws everything. */ #message = ""; #bad = false; /** Set once the server has answered 501 to a passkey call. `/api/account` * already says `passkeys_available`, and this is the same answer arriving * the other way -- from an app that was restarted without the extra while * this page was open. */ #passkeysGone = false; constructor() { super(); this.#root = this.attachShadow({ mode: "open" }); const style = document.createElement("style"); style.textContent = CSS; this.#panel = document.createElement("div"); this.#panel.className = "panel"; this.#root.append(style, this.#panel); } connectedCallback() { this.#load(); } get #base() { return this.getAttribute("base") ?? ""; } get #login() { return this.getAttribute("login") ?? "/login"; } // ------------------------------------------------------------------ server /** One fetch helper, so every failure surfaces the same way: the server's * own sentence, in place and as an event. A 401 means the session ended * under us, which is a redirect rather than a message. */ async #api(path, options = {}) { const response = await fetch(this.#base + path, { credentials: "same-origin", headers: Object.assign({ Accept: "application/json" }, options.body ? { "Content-Type": "application/json" } : {}), ...options, }); let data = null; const text = await response.text(); if (text) { try { data = JSON.parse(text); } catch { data = null; } } if (!response.ok) { const error = new Error((data && data.detail) || `The server answered ${response.status} and said nothing about why.`); error.status = response.status; throw error; } return data; } async #load() { try { this.#account = await this.#api("/api/account"); this.#render(); } catch (err) { if (err.status === 401) { location.assign(this.#login); return; } this.#fail(err); this.#render(); } } /** Run one button's worth of work: disable the panel, say what went wrong, * and reload the account either way -- the server is the only thing that * knows what the sessions and passkeys are now. */ async #act(work) { if (this.#busy) return; this.#busy = true; this.#message = ""; this.#bad = false; this.#render(); try { await work(); } catch (err) { if (err.status === 401) { location.assign(this.#login); return; } if (err.status === NOT_BUILT) this.#passkeysGone = true; this.#fail(err); } finally { this.#busy = false; } await this.#load(); } #fail(err) { this.#message = String(err.message || err); this.#bad = true; this.dispatchEvent(new CustomEvent("auth-account:error", { detail: { detail: this.#message, status: err.status || 0 }, bubbles: true, composed: true, })); } #say(text) { this.#message = text; this.#bad = false; } // ------------------------------------------------------------------ drawing #render() { const account = this.#account; this.#panel.replaceChildren(); if (!account) { this.#panel.append(this.#note(this.#message || "Loading…", this.#bad)); return; } this.#panel.append(this.#status(account)); if (this.#message) this.#panel.append(this.#note(this.#message, this.#bad)); this.#panel.append(this.#password(account)); if (account.sessions.length) this.#panel.append(this.#sessions(account)); if (this.#showPasskeys(account)) this.#panel.append(this.#passkeys(account)); if (account.locked) this.#panel.append(this.#signOut()); } #showPasskeys(account) { return account.passkeys_available && !this.#passkeysGone; } #status(account) { const section = this.#section("This app"); section.append(this.#line( account.locked ? "Locked. Every request but the login page, the health probe and the static files needs a session." : "Not locked. The bind address is loopback and `auth.enabled` is `auto`, so anyone who can reach this app is already sitting at the machine.")); if (account.password_set_at) { section.append(this.#line(`Password last set ${when(account.password_set_at)}.`)); } else { section.append(this.#line("No password has been set on this database yet.")); } if (account.pinned) { section.append(this.#line( `The password is pinned by ${account.pinned_by || "the environment"}, so it cannot be changed here. Change it there and restart.`)); } if (account.passkeys_blocked && account.passkeys_available) { section.append(this.#line(account.passkeys_blocked)); } return section; } #password(account) { const section = this.#section("Password"); if (account.pinned) { section.append(this.#line( `Set by ${account.pinned_by || "the environment"}. Empty that variable, restart, and this form comes back.`)); return section; } // Nothing to prove when there is nothing set yet, which is what an // unlocked app on a laptop looks like before it is ever deployed. Asking // for a current password there is a field with no right answer, and the // form could only ever be refused -- see `change_password` in router.py. const first = !account.password_set_at; const form = document.createElement("form"); const current = field("password", "Current password"); const next = field("password", first ? "Choose a password" : "New password"); const go = document.createElement("button"); go.textContent = first ? "Set password" : "Change password"; go.disabled = this.#busy; form.append(...(first ? [next, go] : [current, next, go])); form.addEventListener("submit", (event) => { event.preventDefault(); this.#act(async () => { const result = await this.#api("/api/account/password", { method: "POST", body: JSON.stringify({ current: current.value, new: next.value }), }); current.value = next.value = ""; if (first) return this.#say("Password set."); this.#say(result.signed_out ? `Password changed. ${count(result.signed_out, "other session")} signed out.` : "Password changed."); }); }); section.append(form); // Every *other* session goes when the password changes: if the reason you // are changing it is that someone may have it, leaving their session open // makes the change ceremonial. Said here so it is not a surprise. section.append(this.#line(first ? "Nothing asks for it until the app binds an address that is not loopback -- or `auth.enabled: always`. Set it before you deploy, not after." : "Changing it signs out every other session, and keeps this one.")); return section; } #sessions(account) { const section = this.#section("Signed in"); for (const session of account.sessions) { const row = this.#row( session.label || "Unnamed browser", `${session.current ? "This browser · " : ""}last seen ${when(session.last_seen_at)} · started ${when(session.created_at)}`); if (session.current) row.querySelector(".acts").append(badge("this one")); row.querySelector(".acts").append(this.#button("Revoke", "danger", () => this.#act(async () => { await this.#api(`/api/account/sessions/${session.id}`, { method: "DELETE" }); // Revoking your own is allowed -- it is a logout with an extra click // -- and the next request is the one that discovers it. this.#say("Session revoked."); }))); section.append(row); } if (account.sessions.length > 1) { section.append(this.#button("Sign out everywhere else", "", () => this.#act(async () => { const result = await this.#api("/api/account/sessions/close", { method: "POST" }); this.#say(`${count(result.signed_out, "session")} signed out.`); }))); } return section; } #passkeys(account) { const section = this.#section("Passkeys"); for (const key of account.passkeys) { const row = this.#row( key.label || "Passkey", [key.transports.join(", "), `added ${when(key.created_at)}`, key.last_used_at ? `last used ${when(key.last_used_at)}` : "never used", ].filter(Boolean).join(" · ")); const acts = row.querySelector(".acts"); acts.append(this.#button("Rename", "", () => { const label = prompt("Call this passkey what?", key.label || ""); if (label === null) return; this.#act(async () => { await this.#api(`/api/account/passkeys/${key.id}/label`, { method: "POST", body: JSON.stringify({ label }), }); this.#say("Renamed."); }); })); acts.append(this.#button("Revoke", "danger", () => this.#act(async () => { await this.#api(`/api/account/passkeys/${key.id}`, { method: "DELETE" }); // Safe by construction: the password is still there, which is why // revoking a key can never lock anyone out. this.#say("Passkey revoked."); }))); section.append(row); } if (account.passkeys_blocked) { // Registering needs a secure origin; verifying does not. So the list // above is still worth drawing, and only the button goes. section.append(this.#line(account.passkeys_blocked)); return section; } const add = this.#button("Add a passkey", "", () => this.#register()); add.disabled = this.#busy; section.append(add); return section; } async #register() { const passkey = await loadPasskeyHelper(); if (!passkey || !passkey.supported()) { this.#say("This browser will not create a passkey here. It needs HTTPS, or localhost."); this.#render(); return; } // Two round trips: a challenge, then what the authenticator signed. The // browser's own prompt happens between them, and a cancelled prompt is an // exception rather than an error status -- hence `explain`. await this.#act(async () => { const options = await this.#api("/api/account/passkeys/options", { method: "POST" }); let made; try { made = await passkey.create(options); } catch (err) { throw new Error(passkey.explain(err)); } const label = suggest(); await this.#api("/api/account/passkeys", { method: "POST", body: JSON.stringify({ credential: made, label }), }); this.#say(`Registered "${label}". Rename it if that is not what it is.`); }); } #signOut() { const section = this.#section("This session"); section.append(this.#button("Sign out", "danger", async () => { try { await this.#api("/logout", { method: "POST" }); } catch { /* the cookie is going either way */ } location.assign(this.#login); })); return section; } // --------------------------------------------------------------- furniture #section(title) { const section = document.createElement("section"); const head = document.createElement("h3"); head.textContent = title; section.append(head); return section; } #line(text) { const line = document.createElement("div"); line.className = "said"; line.textContent = text; return line; } #note(text, bad) { const line = this.#line(text); if (bad) line.classList.add("bad"); return line; } #row(what, said) { const row = document.createElement("div"); row.className = "row"; const lines = document.createElement("div"); lines.className = "lines"; const name = document.createElement("span"); name.className = "what"; name.textContent = what; const under = document.createElement("span"); under.className = "said"; under.textContent = said; lines.append(name, under); const acts = document.createElement("div"); acts.className = "acts"; row.append(lines, acts); return row; } #button(text, className, onClick) { const button = document.createElement("button"); button.textContent = text; if (className) button.className = className; button.disabled = this.#busy; button.addEventListener("click", onClick); return button; } } /** The WebAuthn helper is a classic script on `window`, shared with the login * page, which is plain HTML served before any of the app's scripts. Loaded on * demand rather than up front, so a screen nobody registers a passkey from * never fetches it. */ let helper = null; function loadPasskeyHelper() { if (window.passkey) return Promise.resolve(window.passkey); helper = helper || new Promise((resolve) => { const script = document.createElement("script"); script.src = "/_auth/passkey.js"; script.onload = () => resolve(window.passkey || null); script.onerror = () => resolve(null); document.head.append(script); }); return helper; } /** A name the authenticator can be told apart by, before anyone renames it. * Better than "Passkey" and worse than what a person would call it, which is * why Rename is beside it. */ function suggest() { const agent = navigator.userAgent || ""; for (const [needle, name] of [["Windows", "Windows"], ["Mac", "Mac"], ["iPhone", "iPhone"], ["iPad", "iPad"], ["Android", "Android"], ["Linux", "Linux"]]) { if (agent.includes(needle)) return `${name} passkey`; } return "Passkey"; } function badge(text) { const span = document.createElement("span"); span.className = "badge"; span.textContent = text; return span; } function field(type, placeholder) { const input = document.createElement("input"); input.type = type; input.placeholder = placeholder; input.setAttribute("aria-label", placeholder); input.required = true; input.autocomplete = type === "password" ? "new-password" : "off"; return input; } function count(n, thing) { return `${n} ${thing}${n === 1 ? "" : "s"}`; } /** An ISO stamp as something to read. Local time, because the person reading * it is at a machine and the server's UTC is nobody's afternoon. */ function when(stamp) { if (!stamp) return "never"; const at = new Date(stamp); if (Number.isNaN(at.getTime())) return stamp; return at.toLocaleString(); } if (!customElements.get("auth-account")) { customElements.define("auth-account", AuthAccount); } export { AuthAccount };