diff --git a/lib/manage.js b/lib/manage.js index 130df36..10783bf 100644 --- a/lib/manage.js +++ b/lib/manage.js @@ -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=) 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, `Burrow`, + "text/html; charset=utf-8"); + return; } // back from Discord (lib/discord.js): the state and the nonce must be the diff --git a/public/account.html b/public/account.html index 9638209..ef0ad28 100644 --- a/public/account.html +++ b/public/account.html @@ -215,7 +215,7 @@
-
+

No account yet? Create one · Forgot password or 2FA?

@@ -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(); diff --git a/test/account.js b/test/account.js index 5b3a926..0006105 100644 --- a/test/account.js +++ b/test/account.js @@ -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");