Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 83e965dfeb
commit 244e57ac29
19 files changed
+2288 -214

No files matched your search

+209 -12
View File
@@ -4,9 +4,9 @@
* <auth-account></auth-account>
*
* 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
* know, and draws the five 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.
* revoke passkeys, make and revoke API tokens for scripts, 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
@@ -79,6 +79,18 @@ button {
padding: 2px 9px;
cursor: pointer;
}
select {
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;
}
select option { color: initial; }
label.check { display: flex; align-items: center; gap: 6px; flex: 1 1 100%; }
label.check input { min-width: 0; margin: 0; }
input.token { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; min-width: 20rem; }
.made { display: flex; flex-direction: column; gap: var(--desk-jobs-gap); }
.made .bar { display: flex; flex-wrap: wrap; gap: var(--desk-jobs-gap); align-items: center; }
button:hover { color: var(--desk-jobs-accent); }
button.danger:hover { color: var(--desk-jobs-error); }
button[disabled] { opacity: .4; cursor: default; }
@@ -87,6 +99,25 @@ button[disabled] { opacity: .4; cursor: default; }
font-size: 12px; padding: 0 6px; border-radius: 999px;
border: 1px solid currentColor; color: var(--desk-jobs-dim);
}
/* A finger: every button a thumb's height, and no field under 16px, which
* is where iOS zooms the page in on focus and never back out. Sizes only;
* the layout is the width query below, and neither reads the other. */
@media (pointer: coarse) {
button { min-height: 2.5rem; padding: 4px 12px; }
input, select { font-size: 16px; padding: 7px 9px; }
}
/* A phone: a session's name and its buttons share a line while they fit and
* the buttons drop under it when they do not, still on the right; a form's
* fields take the width and its buttons share what is left. 40rem is
* app.css's number, on purpose. */
@media (max-width: 40rem) {
.row { flex-wrap: wrap; align-items: center; }
.row .acts { margin-left: auto; }
form input:not([type="checkbox"]), form select, .bar input { flex: 1 1 100%; min-width: 0; }
form button, .bar button { flex: 1 1 auto; }
}
`;
/** What the server says when this build has no `webauthn` installed. The
@@ -110,6 +141,11 @@ class AuthAccount extends HTMLElement {
* the other way -- from an app that was restarted without the extra while
* this page was open. */
#passkeysGone = false;
/** The token just made, held until Done: the server shows it once and keeps
* only its hash, so nothing reloaded from `/api/account` can bring it back. */
#made = null;
/** What Copy last did: "", "done" or "failed". */
#copy = "";
constructor() {
super();
@@ -211,6 +247,7 @@ class AuthAccount extends HTMLElement {
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));
this.#panel.append(this.#tokens(account));
if (account.locked) this.#panel.append(this.#signOut());
}
@@ -255,22 +292,30 @@ class AuthAccount extends HTMLElement {
const form = document.createElement("form");
const current = field("password", "Current password");
const next = field("password", first ? "Choose a password" : "New password");
// Tokens and passkeys survive a change unless this is ticked: the cron
// job holding a token is not what a routine change is against, but an
// intruder who had the password may have minted one.
const revoke = document.createElement("input");
revoke.type = "checkbox";
const revokeLabel = document.createElement("label");
revokeLabel.className = "check";
revokeLabel.append(revoke, "Also revoke every API token and passkey");
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.append(...(first ? [next, go] : [current, next, revokeLabel, 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 }),
body: JSON.stringify({
current: current.value, new: next.value, revoke_all: !first && revoke.checked,
}),
});
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.");
this.#say(changed(result));
});
});
section.append(form);
@@ -279,7 +324,7 @@ class AuthAccount extends HTMLElement {
// 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."));
: "Changing it signs out every other session and keeps this one. API tokens and passkeys stay unless you tick the box; tick it if someone else may have had the password."));
return section;
}
@@ -344,13 +389,142 @@ class AuthAccount extends HTMLElement {
section.append(this.#line(account.passkeys_blocked));
return section;
}
const add = this.#button("Add a passkey", "", () => this.#register());
// A passkey outlasts every session, so adding one takes the password --
// see `passkey_options` in router.py. With none set there is nothing to
// confirm, and the server does not ask.
const asks = Boolean(account.password_set_at);
const form = document.createElement("form");
const current = field("password", "Password, to add a passkey");
current.autocomplete = "current-password";
const add = document.createElement("button");
add.textContent = "Add a passkey";
add.disabled = this.#busy;
section.append(add);
form.append(...(asks ? [current, add] : [add]));
form.addEventListener("submit", (event) => {
event.preventDefault();
this.#register(current.value);
});
section.append(form);
return section;
}
async #register() {
#tokens(account) {
const section = this.#section("API tokens");
for (const token of account.tokens || []) {
const row = this.#row(
token.label || "Token",
[`${token.hint}…`,
`added ${when(token.created_at)}`,
token.last_used_at ? `last used ${when(token.last_used_at)}` : "never used",
lifetime(token),
].join(" · "));
const acts = row.querySelector(".acts");
acts.append(this.#button("Rename", "", () => {
const label = prompt("Call this token what?", token.label || "");
if (label === null) return;
this.#act(async () => {
await this.#api(`/api/account/tokens/${token.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/tokens/${token.id}`, { method: "DELETE" });
// The script holding it is locked out on its next request, and
// nothing else changes: the password and the sessions stay.
this.#say("Token revoked.");
})));
section.append(row);
}
// A token outlives every session and a password change, so making one
// takes the password, on the same condition as a passkey -- see
// `create_token` in router.py.
const asks = Boolean(account.password_set_at);
const form = document.createElement("form");
const label = field("text", "Name, e.g. the script that holds it");
label.required = false;
label.maxLength = 100;
const days = document.createElement("select");
days.setAttribute("aria-label", "How long it is valid");
for (const [value, text] of [["", "Does not expire"], ["30", "30 days"],
["90", "90 days"], ["365", "1 year"]]) {
const option = document.createElement("option");
option.value = value;
option.textContent = text;
days.append(option);
}
const current = field("password", "Password, to create a token");
current.autocomplete = "current-password";
const create = document.createElement("button");
create.textContent = "Create a token";
create.disabled = this.#busy;
form.append(label, days, ...(asks ? [current] : []), create);
form.addEventListener("submit", (event) => {
event.preventDefault();
this.#act(async () => {
const made = await this.#api("/api/account/tokens", {
method: "POST",
body: JSON.stringify({
current: current.value, label: label.value.trim(),
days: days.value ? Number(days.value) : null,
}),
});
// In the one answer that made it and nowhere after, so it is kept on
// the element until Done rather than read back from the account.
this.#made = made;
this.#copy = "";
this.#say(`Token "${made.label || "Token"}" created. Copy it below; it is shown only once.`);
});
});
section.append(form);
if (this.#made) section.append(this.#shown(this.#made));
section.append(this.#line(
"A script sends a token as `Authorization: Bearer`. It cannot manage the account, and it is kept through a password change. Revoke it here when the script no longer needs it."));
return section;
}
/** The new token, read-only and selectable, with Copy and a sentence that
* it is the only time. Done drops it from the element, after which the
* page never has it again. */
#shown(made) {
const box = document.createElement("div");
box.className = "made";
const bar = document.createElement("div");
bar.className = "bar";
const value = document.createElement("input");
value.type = "text";
value.readOnly = true;
value.className = "token";
value.value = made.token;
value.setAttribute("aria-label", "The new token");
value.addEventListener("focus", () => value.select());
bar.append(value,
this.#button("Copy", "", async () => {
try {
await navigator.clipboard.writeText(made.token);
this.#copy = "done";
} catch {
// No clipboard on an insecure origin, or the browser refused: the
// field is selectable, so the token is still there to take by hand.
this.#copy = "failed";
}
this.#render();
}),
this.#button("Done", "", () => {
this.#made = null;
this.#copy = "";
this.#render();
}));
box.append(bar, this.#line(
"This is the only time the token is shown. Only a hash is stored, so it cannot be looked up again; if it is lost, revoke it and create another."));
if (this.#copy === "done") box.append(this.#line("Copied."));
if (this.#copy === "failed") box.append(this.#note("Could not copy. Select the token and copy it by hand.", true));
return box;
}
async #register(current) {
const passkey = await loadPasskeyHelper();
if (!passkey || !passkey.supported()) {
this.#say("This browser will not create a passkey here. It needs HTTPS, or localhost.");
@@ -361,7 +535,9 @@ class AuthAccount extends HTMLElement {
// 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" });
const options = await this.#api("/api/account/passkeys/options", {
method: "POST", body: JSON.stringify({ current }),
});
let made;
try {
made = await passkey.create(options);
@@ -485,6 +661,19 @@ function field(type, placeholder) {
return input;
}
/** What a password change closed and what it left, in a sentence or three. */
function changed(result) {
const said = ["Password changed."];
if (result.signed_out) said.push(`${count(result.signed_out, "other session")} signed out.`);
if (result.tokens_revoked || result.passkeys_revoked) {
said.push(`${count(result.tokens_revoked, "API token")} and ${count(result.passkeys_revoked, "passkey")} revoked.`);
}
if (result.tokens_left || result.passkeys_left) {
said.push(`${count(result.tokens_left, "API token")} and ${count(result.passkeys_left, "passkey")} remain; revoke any you do not recognise.`);
}
return said.join(" ");
}
function count(n, thing) {
return `${n} ${thing}${n === 1 ? "" : "s"}`;
}
@@ -498,6 +687,14 @@ function when(stamp) {
return at.toLocaleString();
}
/** What a token's row says about its end: no end, one to come, or one that
* has passed and left the row for the owner to clear. */
function lifetime(token) {
if (!token.expires_at) return "does not expire";
const gone = new Date(token.expires_at).getTime() <= Date.now();
return `${gone ? "expired" : "expires"} ${when(token.expires_at)}`;
}
if (!customElements.get("auth-account")) {
customElements.define("auth-account", AuthAccount);
}