feat(account): sign in to the account page with the Burrow client

"Sign in with the Burrow client" on the account page's sign-in screen
opens burrow://account?n=<nonce>; the browser asks whether to open
Burrow. The client asks for a ticket with its login token
(POST /account/api/client-ticket) and opens /account/client?ticket= in
the browser, which signs in there. A ticket lasts 2 minutes, is good
once, and signs in only the browser holding the nonce's cookie, so a
burrow:// link from elsewhere signs nobody in and a ticket sent to
someone else opens nothing. The tab that started it follows by itself;
once it has worked in a browser, the page asks for Burrow by itself.
This commit is contained in:
Burrowdev committed 2026-10-23 07:04:45 +03:00
1 parent b22708a4ba
commit 44af83f1c5
3 files changed
+197 -1

No files matched your search

+101
View File
@@ -52,6 +52,29 @@ const discordCookie = (value, maxAgeSeconds) =>
`${DISCORD_COOKIE}=${value}; Path=/account/discord; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const SESSION_HOURS = 12;
const TEN_MINUTES_MS = 600000;
// "Sign in with the Burrow client": the page starts it, and keeps this
// cookie; the link it opens (burrow://account?n=<nonce>) has the client ask
// for a ticket with its own login token, which it then opens in the
// browser at /account/client. the ticket signs in only the browser that
// holds the nonce it was asked for, so a burrow:// link from anywhere else
// signs nobody in, and a ticket sent to someone else opens nothing for them.
const CLIENT_COOKIE = "ajc_clink";
const clientCookie = (value, maxAgeSeconds) =>
`${CLIENT_COOKIE}=${value}; Path=/account/client; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${config.secureCookies ? "; Secure" : ""}`;
const CLIENT_START_MS = 5 * 60 * 1000;
const CLIENT_TICKET_MS = 2 * 60 * 1000;
const MAX_CLIENT_STARTS = 10000;
const clientStarts = new Map(); // SHA-256 of a nonce -> expiry (ms)
const clientTickets = new Map(); // SHA-256 of a ticket -> {id: account id, nonce: SHA-256 of its nonce, expiry: ms}
const clientStartsByAddress = limits.limiter(20, TEN_MINUTES_MS);
const clientTicketsByAccount = limits.limiter(10, TEN_MINUTES_MS);
const dropExpired = map => {
for (const [hash, entry] of map) {
if ((typeof entry === "number" ? entry : entry.expiry) < Date.now()) {
map.delete(hash);
}
}
};
const MAX_NOTE = 120;
const RECOVERY_TOKEN_MS = 30 * 60 * 1000;
const recoveryHash = token => crypto.createHash("sha256").update(token).digest("hex");
@@ -707,6 +730,84 @@ const handle = async (req, res, url, from, web) => {
reply(200, {ok: true});
return;
}
// "Sign in with the Burrow client" (above), from the page: the nonce for
// the burrow:// link, which this browser keeps as a cookie too.
case "POST /account/api/client-start": {
if (!from.local && !clientStartsByAddress.allow(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientStarts);
if (clientStarts.size >= MAX_CLIENT_STARTS) {
reply(503, {error: "Try again in a few minutes."});
return;
}
const nonce = crypto.randomBytes(24).toString("hex");
clientStarts.set(sha256(nonce), Date.now() + CLIENT_START_MS);
res.setHeader("Set-Cookie", clientCookie(nonce, CLIENT_START_MS / 1000));
reply(200, {nonce});
return;
}
// ... from the client, with its login token (no Origin: the client's main
// process): where to send the browser, which signs in there. a token is
// only given after a whole sign-in, 2FA code included (lib/http.js).
case "POST /account/api/client-ticket": {
const nonce = typeof body.nonce === "string" && /^[0-9a-f]{48}$/.test(body.nonce) ? body.nonce : "";
const started = nonce && clientStarts.get(sha256(nonce));
if (!started || started < Date.now()) {
reply(400, {error: "Start again from the account page."});
return;
}
if (!from.local && failuresByAddress.blocked(from.key)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
const account = accounts.byToken(body.token);
if (!account) {
failuresByAddress.record(from.key);
reply(401, {error: "Log in to Burrow again first."});
return;
}
if (!clientTicketsByAccount.allow(account.id)) {
reply(429, {error: "Too many attempts. Try later."});
return;
}
dropExpired(clientTickets);
const ticket = crypto.randomBytes(24).toString("hex");
clientTickets.set(sha256(ticket), {id: account.id, nonce: sha256(nonce), expiry: Date.now() + CLIENT_TICKET_MS});
reply(200, {url: new URL(`/account/client?ticket=${ticket}`, config.siteUrl).href, username: account.username});
return;
}
}
// ... and the ticket, opened by the client in the browser: signed in when
// this browser started it (its cookie). a ticket is good once, whatever
// happens. the page that follows says how it went.
if (route === "GET /account/client") {
const given = String(url.searchParams.get("ticket") || "");
const ticket = /^[0-9a-f]{48}$/.test(given) ? clientTickets.get(sha256(given)) : null;
if (ticket) {
clientTickets.delete(sha256(given));
}
const nonce = (new RegExp(`(?:^|;\\s*)${CLIENT_COOKIE}=([0-9a-f]{48})(?:;|$)`).exec(req.headers.cookie || "") || [])[1];
const account = ticket && ticket.expiry > Date.now() ? accounts.byId(ticket.id) : null;
const result = !account ? "expired" : !nonce || sha256(nonce) !== ticket.nonce ? "elsewhere" : "ok";
const cookies = [clientCookie("", 0)];
if (result === "ok") {
clientStarts.delete(ticket.nonce);
accounts.recordLogin(account, "web", from.address);
accounts.save(account);
signIn(res, account, cookies);
}
else {
res.setHeader("Set-Cookie", cookies);
}
// a page of this site's own that goes on to the account page, rather than
// a redirect: the (SameSite=Strict) cookie then surely goes with it.
res.setHeader("Cache-Control", "no-store");
web.send(res, 200, `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/account?client=${result}"><title>Burrow</title>`,
"text/html; charset=utf-8");
return;
}
// back from Discord (lib/discord.js): the state and the nonce must be the
+63 -1
View File
@@ -215,7 +215,7 @@
<label class="check" style="margin-top:12px"><input id="remember-device" type="checkbox"> Trust this device for 30 days</label>
</div>
<div class="captcha" id="captcha"></div>
<div class="row"><button class="primary" type="submit">Sign in</button></div>
<div class="row"><button class="primary" type="submit">Sign in</button><button id="client-sign-in" type="button">Sign in with the Burrow client</button></div>
</form>
<p class="status" id="gate-status" role="status"></p>
<p class="hint" style="margin:10px 0 0">No account yet? <a href="/register">Create one</a> · <a href="/account/recover">Forgot password or 2FA?</a></p>
@@ -1120,9 +1120,71 @@
}
else {
showGate(result.status === 0 ? result.data.error : "");
if (Object.hasOwn(CLIENT_RESULTS, clientResult || "")) {
setStatus("gate-status", CLIENT_RESULTS[clientResult], true);
}
// never by itself on the way back from it: a browser that would
// not keep the sign-in would open tab after tab.
else if (!clientResult && clientRemembered()) {
signInWithClient();
}
}
if (clientResult) {
if (result.ok && clientResult === "ok") {
try {
localStorage.setItem(CLIENT_KEY, "1");
}
catch (err) {
// not kept: the button stays the way in.
}
}
history.replaceState(null, "", location.pathname + location.hash);
}
};
// "Sign in with the Burrow client" (lib/manage.js): the browser asks
// whether to open Burrow, which opens this page again signed in (in a
// new tab: this one follows). once that has worked in this browser, the
// page asks by itself each time it opens signed out.
const CLIENT_KEY = "burrow-client-sign-in";
const CLIENT_RESULTS = {
ok: "Burrow signed you in, but this browser did not keep it. Sign in with your password.",
expired: "That sign-in took too long. Try again.",
elsewhere: "Burrow opened the page in another browser than the one you started in. Start from this browser again, or sign in with your password.",
};
const clientResult = new URLSearchParams(location.search).get("client");
const clientRemembered = () => {
try {
return localStorage.getItem(CLIENT_KEY) === "1";
}
catch (err) {
return false;
}
};
let clientWait = null;
const signInWithClient = async () => {
const started = await api("client-start", {});
if (!started.ok) {
setStatus("gate-status", started.data.error || "That did not work.", true);
return;
}
setStatus("gate-status", "Opening Burrow… Allow it if your browser asks. Burrow must be logged in, or remember you.");
location.href = `burrow://account?n=${started.data.nonce}`;
clearInterval(clientWait);
const until = Date.now() + 120000;
clientWait = setInterval(async () => {
if (account || Date.now() > until) {
clearInterval(clientWait);
return;
}
if ((await api("me")).ok) {
clearInterval(clientWait);
await load();
}
}, 2000);
};
$("client-sign-in").addEventListener("click", signInWithClient);
$("sign-in").addEventListener("submit", async event => {
event.preventDefault();
const answer = captchaPass ? undefined : await check.answer();
+33
View File
@@ -66,6 +66,39 @@ const run = async () => {
// the wrong password and the sign-in are both in her history, newest first.
assert.deepStrictEqual(me.history.map(login => [login.via, login.ok]), [["web", true], ["web", false]]);
// --- signing in with the Burrow client: the page's nonce, the client's
// token for a ticket, and the ticket only for the browser that started it
const clientStart = async () => {
const started = await mine("client-start", {});
assert.strictEqual(started.status, 200);
assert.match(started.cookie, /^ajc_clink=[0-9a-f]{48}$/);
return {nonce: started.data.nonce, cookie: started.cookie};
};
const openTicket = async (link, cookie) => {
const response = await fetch(`${BASE}${new URL(link).pathname}${new URL(link).search}`, {headers: cookie ? {Cookie: cookie} : {}});
const result = /client=(\w+)/.exec(await response.text())[1];
const session = response.headers.getSetCookie().map(line => line.split(";")[0]).find(line => /^ajc_account=[0-9a-f]{48}$/.test(line));
return {result, session};
};
const annToken = (await (await authenticate("Ann", "KettlePass01")).json()).auth_token;
const browser = await clientStart();
assert.strictEqual((await mine("client-ticket", {token: annToken, nonce: "0".repeat(48)})).status, 400);
assert.strictEqual((await mine("client-ticket", {token: "f".repeat(annToken.length), nonce: browser.nonce})).status, 401);
const ticket = await mine("client-ticket", {token: annToken, nonce: browser.nonce});
assert.deepStrictEqual([ticket.status, ticket.data.username], [200, "Ann"]);
// another browser (no cookie, or another start's) gets nothing from it, and it is then used up
const other = await clientStart();
assert.deepStrictEqual(await openTicket(ticket.data.url, other.cookie), {result: "elsewhere", session: undefined});
assert.deepStrictEqual(await openTicket(ticket.data.url, browser.cookie), {result: "expired", session: undefined});
const second = await mine("client-ticket", {token: annToken, nonce: browser.nonce});
assert.deepStrictEqual(await openTicket(second.data.url), {result: "elsewhere", session: undefined});
const third = await mine("client-ticket", {token: annToken, nonce: browser.nonce});
const opened = await openTicket(third.data.url, browser.cookie);
assert.strictEqual(opened.result, "ok");
assert.strictEqual((await mine("me", undefined, opened.session)).data.username, "Ann");
// the start is used up with the sign-in
assert.strictEqual((await mine("client-ticket", {token: annToken, nonce: browser.nonce})).status, 400);
// --- parts of the game switched off
const {client: a, roomId} = await arrive("Ann", "KettlePass01");
const {client: b} = await arrive("Ben", "KettlePass01");