caelum0x 784bea9880 fix(RIT-BRD): drop wordy "--" copy and raw scope walls across approvals/export/device-auth
Same Apple-design copy pass as the OAuth consent screen: "Held pushes --
all repos" -> "Held pushes, all repos", dropped redundant "so X is a
single click -- no token to copy or paste" trailers now that the consent
screen itself says that, and the device sign-in page's raw space-
separated scope list is now a one-line summary + an expandable
<details> for the full list (matching grant.tmpl's own pattern).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 18:12:38 +03:00

402 lines
18 KiB
JavaScript

#!/usr/bin/env node
// Rithub real browser sign-in for `rit login` (RIT-ACT, 2026-12-01). Served
// behind Caddy at https://rithub.dev/device* and
// https://rithub.dev/api/rit/device/* (handled before the engine's own
// catch-all reverse_proxy, same pattern as /protect*, /billing*, /mcp*).
// Zero npm dependencies -- plain node:http, matching every sibling
// rithub-* pm2 service on this box.
//
// What this is NOT: a second, parallel identity system. Every token this
// service ever hands out is a real Rithub (engine) OAuth2 access token,
// minted by the engine's own /login/oauth/access_token endpoint for the
// human who is signed into rithub.dev in their own browser right now --
// this service only orchestrates the RFC-8628-shaped device-code
// choreography (code/user_code/polling) on top of that real exchange, it
// never issues, stores long-term, or forges a credential of its own.
import http from "node:http";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveSignedInSession } from "../src/ritSession.mjs";
import { normalizeUserCode } from "../src/userCode.mjs";
import { newVerifier, challengeFor } from "../src/pkce.mjs";
import { buildAuthorizeUrl, exchangeCode, isConfigured, GRANTED_SCOPE } from "../src/ritOAuth.mjs";
import * as store from "../src/store.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const SHELL_HTML = readFileSync(join(__dirname, "..", "src", "shell.html"), "utf8");
const PORT = Number(process.env.PORT || 3357);
const RITHUB_BASE_URL = (process.env.RITHUB_BASE_URL || "https://rithub.dev").replace(/\/+$/, "");
// RIT-ACT "enforced, not opt-in" (2026-12-01): loopback call to
// apps/rithub-approvals, same box, right after a real token is minted --
// see handleCallback below. Best-effort: a brief approvals-service outage
// must never break `rit login` itself, it only means that one token
// misses getting its issuance mark (it still gets `rit`'s own best-effort
// runtime mark on first use, same safety net as before this pass).
const APPROVALS_URL = (process.env.RITHUB_APPROVALS_URL || "http://127.0.0.1:3361").replace(/\/+$/, "");
async function markAgentIdentity({ accessToken, source }) {
try {
const res = await fetch(`${APPROVALS_URL}/approvals/api/agent-identity/mark`, {
method: "POST",
headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
body: JSON.stringify({ source }),
signal: AbortSignal.timeout(5000),
});
if (!res.ok) console.error(`rithub-device-auth: agent-identity mark failed (HTTP ${res.status})`);
} catch (err) {
console.error("rithub-device-auth: agent-identity mark failed:", err.message);
}
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
function renderShell({ title, session, content }) {
return SHELL_HTML.replaceAll("__RITHUB_PAGE_TITLE__", escapeHtml(title))
.replaceAll("__RITHUB_LOGIN__", escapeHtml(session?.login ?? ""))
.replaceAll("__RITHUB_AVATAR__", escapeHtml(session?.avatarUrl || "/assets/img/avatar_default.png"))
.replaceAll("__RITHUB_CSRF__", escapeHtml(session?.csrfToken || ""))
.replace("__RITHUB_CONTENT__", content);
}
function sendHtml(res, status, html) {
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
res.end(html);
}
function sendJson(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(payload) });
res.end(payload);
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", (c) => {
size += c.length;
if (size > 10_000) {
reject(new Error("body too large"));
req.destroy();
return;
}
chunks.push(c);
});
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
if (!raw) {
resolve({});
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(err);
}
});
req.on("error", reject);
});
}
const SCOPE_LIST_HTML = GRANTED_SCOPE.split(" ")
.map((s) => `<code>${escapeHtml(s)}</code>`)
.join(" ");
// RIT-BRD 2026-12-01 (owner: "no walls of text or raw scope names"): a
// one-line plain summary up front, the raw list one click away -- same
// pattern as apps/rithub-server/custom/templates/user/auth/grant.tmpl's
// own restyle the same pass.
const SCOPE_SUMMARY_HTML = `<p class="rithub-device-scopes">Grants the CLI access to read and write your repos, issues and packages.</p>
<details class="rithub-grant-detail"><summary>What this includes</summary><p>${SCOPE_LIST_HTML}</p></details>`;
// ---------------------------------------------------------------------------
// POST /api/rit/device/code -- step 1, called by `rit login` before it has
// a browser session of any kind.
// ---------------------------------------------------------------------------
async function handleDeviceCode(req, res) {
if (!isConfigured()) {
sendJson(res, 503, { error: "device_flow_unavailable", message: "not configured yet" });
return;
}
let body = {};
try {
body = await readJsonBody(req);
} catch {
body = {};
}
const { deviceCode, record, expiresIn, interval } = store.createDevice({ requestedKind: body.kind === "agent" ? "agent" : null });
const verificationUri = `${RITHUB_BASE_URL}/device`;
sendJson(res, 200, {
device_code: deviceCode,
user_code: record.userCode,
verification_uri: verificationUri,
verification_uri_complete: `${verificationUri}?code=${encodeURIComponent(record.userCode)}`,
expires_in: expiresIn,
interval,
});
}
// ---------------------------------------------------------------------------
// GET /device[?code=XXXX-XXXX] -- the human-facing confirmation page.
// ---------------------------------------------------------------------------
async function handleDevicePage(req, res, url) {
const session = await resolveSignedInSession(req);
if (!session) {
const redirectTo = `/device${url.search}`;
res.writeHead(302, { Location: `${RITHUB_BASE_URL}/user/login?redirect_to=${encodeURIComponent(redirectTo)}` });
res.end();
return;
}
const prefilled = (url.searchParams.get("code") || "").trim();
const normalized = normalizeUserCode(prefilled);
const record = normalized ? store.getByUserCode(normalized) : null;
let content;
if (prefilled && !record) {
content = `
<div class="rithub-device-intro">
<div class="rithub-bring-code-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22" aria-hidden="true"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/></svg>
</div>
<h1 class="rithub-bring-code-title">That code doesn't work</h1>
<p class="rithub-device-sub">It may have expired or already been used. Run <code>rit login</code> again for a fresh code.</p>
</div>`;
} else {
// RIT-ACT "enforced, not opt-in" (2026-12-01): every device-flow
// token is agent-identity by default -- a held push for a protected
// branch/delete, same as `rit`'s own agent-session pushes, whether or
// not this ever runs through `rit` again. A human signing in for
// themselves has to say so, explicitly, right here; `rit login
// --agent` (record.requestedKind) removes even that choice, since the
// CLI already told the server this one is for an agent.
const kindChoiceHtml = record?.requestedKind === "agent"
? `<p class="rithub-device-scopes">Signing in an agent (requested by <code>rit login --agent</code>). A force-push, branch delete, or push to a protected branch made with this token will be held for a human to approve.</p>`
: `<label class="tw-cursor-pointer" style="display:flex;gap:8px;align-items:flex-start;">
<input type="checkbox" name="personal" style="margin-top:3px;">
<span>This is me signing in — not an agent. (Unchecked: this token is treated as an agent credential, the safe default — a force-push, branch delete, or push to a protected branch made with it will be held for a human to approve.)</span>
</label>`;
content = `
<div class="rithub-device-intro">
<div class="rithub-bring-code-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22" aria-hidden="true"><path d="M9 12l2 2 4-4"/><circle cx="12" cy="12" r="9"/></svg>
</div>
<h1 class="rithub-bring-code-title">Sign in to the rit CLI</h1>
<p class="rithub-device-sub">Confirm the code shown in your terminal.</p>
</div>
<div class="ui segment">
<div class="rithub-device-code">${escapeHtml(normalized || "")}</div>
${SCOPE_SUMMARY_HTML}
<div class="rithub-device-actions">
${
normalized
? `<form method="get" action="/device/authorize" style="display:flex;flex-direction:column;gap:12px;align-items:flex-start;margin-top:12px;">
<input type="hidden" name="user_code" value="${escapeHtml(normalized)}">
${kindChoiceHtml}
<div style="display:flex;gap:10px;">
<button class="ui primary button" type="submit">Authorize</button>
<a class="ui button" href="/device/deny?user_code=${encodeURIComponent(normalized)}">Cancel</a>
</div>
</form>`
: `<form method="get" action="/device" style="display:flex;gap:10px;align-items:center;">
<input class="rithub-full-width-field" type="text" name="code" placeholder="XXXX-XXXX" autocapitalize="characters" autocomplete="off" required>
<button class="ui primary button" type="submit">Continue</button>
</form>`
}
</div>
</div>`;
}
sendHtml(res, 200, renderShell({ title: "Device sign-in", session, content }));
}
// ---------------------------------------------------------------------------
// GET /device/authorize?user_code=XXXX-XXXX -- redirects into the engine's
// own real OAuth2 consent screen (session-cookie-authenticated, native UI,
// lists the exact scopes being granted).
// ---------------------------------------------------------------------------
async function handleDeviceAuthorize(req, res, url) {
const rawUserCode = url.searchParams.get("user_code") || "";
const session = await resolveSignedInSession(req);
if (!session) {
// Reconstruct the redirect target with the /device page's own `code`
// param name (not this route's `user_code`), so a sign-in round trip
// lands back on a pre-filled confirmation page instead of a blank one.
const redirectTo = `/device?code=${encodeURIComponent(rawUserCode)}`;
res.writeHead(302, { Location: `${RITHUB_BASE_URL}/user/login?redirect_to=${encodeURIComponent(redirectTo)}` });
res.end();
return;
}
const normalized = normalizeUserCode(rawUserCode);
const record = normalized ? store.getByUserCode(normalized) : null;
if (!record || record.status !== "pending") {
res.writeHead(302, { Location: "/device" });
res.end();
return;
}
// "requestedKind: agent" (`rit login --agent`) overrides any checkbox --
// the CLI already told the server this one is for an agent, the page
// never offered a way to override it (see handleDevicePage above).
const personalChecked = url.searchParams.get("personal") === "on";
store.setKind(record, record.requestedKind === "agent" ? "agent" : personalChecked ? "human" : "agent");
const codeVerifier = newVerifier();
const codeChallenge = challengeFor(codeVerifier);
store.markAuthorizing(record, codeVerifier);
const authorizeUrl = buildAuthorizeUrl({ state: record.deviceCodeHash, codeChallenge });
res.writeHead(302, { Location: authorizeUrl });
res.end();
}
// ---------------------------------------------------------------------------
// GET /device/deny?user_code=XXXX-XXXX -- explicit cancel.
// ---------------------------------------------------------------------------
async function handleDeviceDeny(req, res, url) {
const session = await resolveSignedInSession(req);
const normalized = normalizeUserCode(url.searchParams.get("user_code"));
const record = normalized ? store.getByUserCode(normalized) : null;
if (record) store.markDenied(record);
const content = `
<div class="rithub-device-intro">
<div class="rithub-bring-code-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>
</div>
<h1 class="rithub-bring-code-title">Sign-in cancelled</h1>
<p class="rithub-device-sub">You can close this tab.</p>
</div>`;
sendHtml(res, 200, renderShell({ title: "Sign-in cancelled", session, content }));
}
// ---------------------------------------------------------------------------
// GET /api/rit/device/callback -- the engine's own OAuth2 redirect target
// after a human clicks "Authorize Application" on its native consent page.
// ---------------------------------------------------------------------------
async function handleCallback(req, res, url) {
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const oauthError = url.searchParams.get("error");
const record = state ? store.getByHash(state) : null;
const errorContent = (message) => `
<div class="rithub-device-intro">
<div class="rithub-bring-code-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22" aria-hidden="true"><path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/></svg>
</div>
<h1 class="rithub-bring-code-title">Sign-in failed</h1>
<p class="rithub-device-sub">${escapeHtml(message)} Run <code>rit login</code> again.</p>
</div>`;
if (oauthError || !code || !record || record.status !== "authorizing" || !record.codeVerifier) {
sendHtml(res, 400, renderShell({ title: "Sign-in failed", session: null, content: errorContent(oauthError || "That sign-in link is no longer valid.") }));
return;
}
try {
const { accessToken, scope } = await exchangeCode({ code, codeVerifier: record.codeVerifier });
store.markApproved(record, accessToken, scope);
// RIT-ACT "enforced, not opt-in" (2026-12-01): mark at ISSUANCE, right
// here, before the token is ever handed to the CLI -- not when (or
// whether) `rit` later chooses to. `record.kind` was decided on the
// /device page (or forced by `rit login --agent`) in
// handleDeviceAuthorize above; default is "agent" if somehow unset
// (the safe default everywhere else in this pass). A "human"/personal
// choice is a pure no-op here -- that token behaves exactly as before.
if (record.kind !== "human") {
await markAgentIdentity({ accessToken, source: "device-login" });
}
} catch (err) {
store.markDenied(record);
sendHtml(res, 502, renderShell({ title: "Sign-in failed", session: null, content: errorContent(String(err?.message || err)) }));
return;
}
const content = `
<div class="rithub-device-intro">
<div class="rithub-bring-code-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>
</div>
<h1 class="rithub-bring-code-title">You're signed in</h1>
<p class="rithub-device-sub">The rit CLI in your terminal will finish signing in automatically. You can close this tab.</p>
</div>`;
sendHtml(res, 200, renderShell({ title: "Signed in", session: null, content }));
}
// ---------------------------------------------------------------------------
// POST /api/rit/device/token -- polled by `rit login`.
// ---------------------------------------------------------------------------
async function handleDeviceToken(req, res) {
let body;
try {
body = await readJsonBody(req);
} catch {
sendJson(res, 400, { error: "invalid_request" });
return;
}
const deviceCode = typeof body.device_code === "string" ? body.device_code : "";
if (!deviceCode) {
sendJson(res, 400, { error: "invalid_request", message: "device_code is required" });
return;
}
const hash = store.hashDeviceCode(deviceCode);
const record = store.getByHash(hash);
if (!record) {
sendJson(res, 400, { error: "expired_token" });
return;
}
if (store.tooSoon(record)) {
sendJson(res, 400, { error: "slow_down" });
return;
}
if (record.status === "denied") {
store.deleteRecord(record);
sendJson(res, 400, { error: "access_denied" });
return;
}
if (record.status === "approved" && record.accessToken) {
const { accessToken, scope } = record;
store.consumeAndDelete(record); // single-use: the next poll with this device_code is a clean "expired_token"
sendJson(res, 200, { access_token: accessToken, token_type: "bearer", scope });
return;
}
sendJson(res, 400, { error: "authorization_pending" });
}
function handleHealth(res) {
sendJson(res, 200, { ok: true, configured: isConfigured() });
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
if (req.method === "POST" && url.pathname === "/api/rit/device/code") {
await handleDeviceCode(req, res);
} else if (req.method === "POST" && url.pathname === "/api/rit/device/token") {
await handleDeviceToken(req, res);
} else if (req.method === "GET" && url.pathname === "/api/rit/device/callback") {
await handleCallback(req, res, url);
} else if (req.method === "GET" && url.pathname === "/device") {
await handleDevicePage(req, res, url);
} else if (req.method === "GET" && url.pathname === "/device/authorize") {
await handleDeviceAuthorize(req, res, url);
} else if (req.method === "GET" && url.pathname === "/device/deny") {
await handleDeviceDeny(req, res, url);
} else if (req.method === "GET" && url.pathname === "/device/health") {
handleHealth(res);
} else {
sendJson(res, 404, { error: "not found" });
}
} catch (err) {
console.error("unhandled error:", err);
sendJson(res, 500, { error: "internal error" });
}
});
server.listen(PORT, "127.0.0.1", () => {
console.log(`rithub-device-auth listening on 127.0.0.1:${PORT} (configured: ${isConfigured()})`);
});