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>
374 lines
15 KiB
JavaScript
374 lines
15 KiB
JavaScript
#!/usr/bin/env node
|
|
// Rithub full account export (RIT-RET, plans/railyard.md queue item 4).
|
|
// Served behind Caddy at https://rithub.dev/export* (handled before the
|
|
// engine's own catch-all reverse_proxy, same pattern as /approvals*,
|
|
// /device*, /protect*). Two ways in, same job underneath:
|
|
// - the web page (cookie session + a one-time real OAuth2 consent, same
|
|
// "no pasted tokens" pattern as apps/rithub-approvals)
|
|
// - `rit export` (a Bearer token the caller already has -- no browser
|
|
// round trip needed for a CLI/agent caller)
|
|
import http from "node:http";
|
|
import crypto from "node:crypto";
|
|
import { createReadStream, existsSync, statSync } from "node:fs";
|
|
import { readFileSync } from "node:fs";
|
|
import { dirname, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { resolveSignedInSession } from "../src/ritSession.mjs";
|
|
import { resolveCallerLogin } from "../src/rithubClient.mjs";
|
|
import { newVerifier, challengeFor } from "../src/pkce.mjs";
|
|
import { buildAuthorizeUrl, exchangeCode, isConfigured as oauthConfigured } from "../src/ritOAuth.mjs";
|
|
import { saveTokenForLogin, tokenForLogin } from "../src/oauthTokenStore.mjs";
|
|
import * as jobStore from "../src/jobStore.mjs";
|
|
import * as runner from "../src/runner.mjs";
|
|
import * as nightly from "../src/nightly.mjs";
|
|
|
|
const RITHUB_BASE_URL = (process.env.RITHUB_BASE_URL || "https://rithub.dev").replace(/\/$/, "");
|
|
const PORT = Number(process.env.PORT || 3365);
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
const SHELL_HTML = readFileSync(join(__dirname, "..", "src", "shell.html"), "utf8");
|
|
|
|
jobStore.reconcileOrphans();
|
|
nightly.startNightlySweepTimer();
|
|
|
|
function escapeHtml(value) {
|
|
return String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[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 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 sendHtml(res, status, html) {
|
|
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
|
|
res.end(html);
|
|
}
|
|
|
|
function readJsonBody(req) {
|
|
return new Promise((resolve, reject) => {
|
|
const chunks = [];
|
|
let size = 0;
|
|
req.on("data", (c) => {
|
|
size += c.length;
|
|
if (size > 1_000_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);
|
|
});
|
|
}
|
|
|
|
function bearerToken(req) {
|
|
const header = req.headers.authorization || "";
|
|
const match = /^Bearer\s+(.+)$/i.exec(header) || /^token\s+(.+)$/i.exec(header);
|
|
return match ? match[1].trim() : null;
|
|
}
|
|
|
|
/** Resolves (login, token) for a mutating call either way: a Bearer token
|
|
* (the `rit export` path -- that token IS the working token, no OAuth
|
|
* needed) or a cookie session + this service's own one-time-authorized,
|
|
* encrypted-at-rest token (the web path, same "no pasted tokens" pattern
|
|
* as apps/rithub-approvals). */
|
|
async function resolveCaller(req) {
|
|
const token = bearerToken(req);
|
|
if (token) {
|
|
const login = await resolveCallerLogin({ token });
|
|
if (!login) return { error: 401, body: { error: "that token did not work" } };
|
|
return { login, token };
|
|
}
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) return { error: 401, body: { error: "not signed in" } };
|
|
const stored = tokenForLogin(session.login);
|
|
if (!stored) return { error: 401, body: { error: "not authorized yet", authorize_url: "/export/oauth/start" } };
|
|
return { login: session.login, token: stored };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// GET /export -- the human-facing page.
|
|
// ---------------------------------------------------------------------------
|
|
function pageBodyNeedsAuthorize() {
|
|
return `
|
|
<div class="rithub-approvals-intro">
|
|
<h1>Export your account</h1>
|
|
<p>One click downloads everything you own: real <code>git</code> bundles, wikis, issues, pull requests, and releases.</p>
|
|
</div>
|
|
<div class="ui segment">
|
|
<p>One-time step: let this page act with your own Rithub permissions.</p>
|
|
<a class="ui primary button" href="/export/oauth/start">Authorize</a>
|
|
</div>`;
|
|
}
|
|
|
|
function pageBodyExport() {
|
|
return `
|
|
<div class="rithub-approvals-intro">
|
|
<h1>Export your account</h1>
|
|
<p>One click downloads everything you own: real <code>git</code> bundles, wikis, issues, pull requests, and releases. Also <code>rit export</code> from the CLI.</p>
|
|
</div>
|
|
<div class="ui segment">
|
|
<button class="ui primary button" id="rit-export-start" type="button">Export now</button>
|
|
<label class="rithub-switch" style="margin-left:16px;">
|
|
<input type="checkbox" id="rit-export-nightly">
|
|
<span class="rithub-switch-track" aria-hidden="true"><span class="rithub-switch-thumb"></span></span>
|
|
<span class="rithub-switch-label">Keep a nightly copy here for 7 days</span>
|
|
</label>
|
|
</div>
|
|
<div id="rit-export-jobs"><p class="tw-my-2">Loading…</p></div>
|
|
<script>
|
|
(function () {
|
|
function esc(s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }
|
|
function fmtBytes(n) { if (n == null) return ""; var u = ["B","KB","MB","GB"]; var i = 0; while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; } return n.toFixed(1) + " " + u[i]; }
|
|
function row(j) {
|
|
var line = esc(j.trigger) + " · " + esc(j.status) + (j.created_at ? " · " + new Date(j.created_at).toLocaleString() : "");
|
|
var action = j.status === "done" ? '<a class="ui button rithub-icon-text-button" href="/export/download/' + esc(j.id) + '"><svg viewBox="0 0 16 16" aria-hidden="true" width="14" height="14"><path d="M2.75 14A1.75 1.75 0 0 1 1 12.25v-2.5a.75.75 0 0 1 1.5 0v2.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25v-2.5a.75.75 0 0 1 1.5 0v2.5A1.75 1.75 0 0 1 13.25 14Z"/><path d="M7.25 7.689V2a.75.75 0 0 1 1.5 0v5.689l1.97-1.969a.749.749 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 6.78a.749.749 0 1 1 1.06-1.06z"/></svg>' + esc(fmtBytes(j.size_bytes)) + '</a>' : (j.status === "failed" ? '<span>' + esc(j.error || "failed") + '</span>' : '<span>in progress…</span>');
|
|
return '<div class="flex-item"><div class="flex-item-main"><span class="flex-item-title">' + line + '</span></div><div class="flex-item-trailing">' + action + '</div></div>';
|
|
}
|
|
function load() {
|
|
fetch('/export/api/jobs', { headers: { accept: 'application/json' } })
|
|
.then(function (r) { return r.json(); })
|
|
.then(function (body) {
|
|
var list = document.getElementById('rit-export-jobs');
|
|
if (!body.jobs || !body.jobs.length) { list.innerHTML = '<p class="tw-my-2">No exports yet.</p>'; return; }
|
|
list.innerHTML = body.jobs.map(row).join('');
|
|
});
|
|
fetch('/export/api/nightly', { headers: { accept: 'application/json' } })
|
|
.then(function (r) { return r.json(); })
|
|
.then(function (body) { document.getElementById('rit-export-nightly').checked = Boolean(body.enabled); });
|
|
}
|
|
document.getElementById('rit-export-start').addEventListener('click', function () {
|
|
fetch('/export/api/start', { method: 'POST' }).then(function () { setTimeout(load, 500); });
|
|
});
|
|
document.getElementById('rit-export-nightly').addEventListener('change', function (e) {
|
|
fetch('/export/api/nightly', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ enabled: e.target.checked }) });
|
|
});
|
|
load();
|
|
setInterval(load, 4000);
|
|
})();
|
|
</script>`;
|
|
}
|
|
|
|
async function handlePage(req, res, url) {
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) {
|
|
res.writeHead(302, { Location: `${RITHUB_BASE_URL}/user/login?redirect_to=${encodeURIComponent(url.pathname + url.search)}` });
|
|
res.end();
|
|
return;
|
|
}
|
|
const hasToken = Boolean(tokenForLogin(session.login));
|
|
sendHtml(res, 200, renderShell({ title: "Export", session, content: hasToken ? pageBodyExport() : pageBodyNeedsAuthorize() }));
|
|
}
|
|
|
|
const pendingOAuth = new Map();
|
|
const OAUTH_STATE_TTL_MS = 10 * 60_000;
|
|
function newOAuthState() {
|
|
for (const [state, rec] of pendingOAuth) if (Date.now() - rec.createdAt > OAUTH_STATE_TTL_MS) pendingOAuth.delete(state);
|
|
return crypto.randomUUID();
|
|
}
|
|
|
|
async function handleOAuthStart(req, res, url) {
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) {
|
|
res.writeHead(302, { Location: `${RITHUB_BASE_URL}/user/login?redirect_to=${encodeURIComponent(url.pathname)}` });
|
|
res.end();
|
|
return;
|
|
}
|
|
if (!oauthConfigured()) {
|
|
sendHtml(res, 503, renderShell({ title: "Not configured", session, content: "<p>Authorize is not configured yet.</p>" }));
|
|
return;
|
|
}
|
|
const codeVerifier = newVerifier();
|
|
const codeChallenge = challengeFor(codeVerifier);
|
|
const state = newOAuthState();
|
|
pendingOAuth.set(state, { codeVerifier, login: session.login, createdAt: Date.now() });
|
|
res.writeHead(302, { Location: buildAuthorizeUrl({ state, codeChallenge }) });
|
|
res.end();
|
|
}
|
|
|
|
async function handleOAuthCallback(req, res, url) {
|
|
const code = url.searchParams.get("code");
|
|
const state = url.searchParams.get("state");
|
|
const oauthError = url.searchParams.get("error");
|
|
const record = state ? pendingOAuth.get(state) : null;
|
|
if (record) pendingOAuth.delete(state);
|
|
if (oauthError || !code || !record) {
|
|
sendHtml(res, 400, renderShell({ title: "Authorize failed", session: null, content: `<p>${escapeHtml(oauthError || "That authorize link is no longer valid.")} <a href="/export/oauth/start">Try again</a>.</p>` }));
|
|
return;
|
|
}
|
|
try {
|
|
const { accessToken, scope } = await exchangeCode({ code, codeVerifier: record.codeVerifier });
|
|
await saveTokenForLogin(record.login, { accessToken, scope });
|
|
} catch (err) {
|
|
sendHtml(res, 502, renderShell({ title: "Authorize failed", session: null, content: `<p>${escapeHtml(String(err?.message || err))} <a href="/export/oauth/start">Try again</a>.</p>` }));
|
|
return;
|
|
}
|
|
res.writeHead(302, { Location: "/export" });
|
|
res.end();
|
|
}
|
|
|
|
async function handleStart(req, res) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
if (jobStore.hasActiveJob() || jobStore.boxTooBusy()) {
|
|
sendJson(res, 503, { error: "an export is already running, or the box is busy right now. Try again shortly" });
|
|
return;
|
|
}
|
|
const job = jobStore.createJob({ login: resolved.login, trigger: "manual" });
|
|
// Fire-and-forget: the caller polls /export/api/jobs/:id (or /export/api/jobs
|
|
// for the page's own list) for status, same pattern as every other
|
|
// long-running job on this box.
|
|
runner.executeJob(job, { token: resolved.token }).catch((err) => console.error("rithub-export: job crashed:", err));
|
|
sendJson(res, 202, { id: job.id, status: job.status });
|
|
}
|
|
|
|
async function handleJobsList(req, res) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
sendJson(res, 200, { jobs: jobStore.jobsForLogin(resolved.login) });
|
|
}
|
|
|
|
async function handleJobGet(req, res, id) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
const job = jobStore.getJob(id);
|
|
if (!job || job.login !== resolved.login) {
|
|
sendJson(res, 404, { error: "not found" });
|
|
return;
|
|
}
|
|
sendJson(res, 200, job);
|
|
}
|
|
|
|
async function handleDownload(req, res, id) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
const job = jobStore.getJob(id);
|
|
if (!job || job.login !== resolved.login || job.status !== "done" || !job.archive_file) {
|
|
sendJson(res, 404, { error: "no finished export with that id" });
|
|
return;
|
|
}
|
|
const full = jobStore.archiveFullPath(job.archive_file);
|
|
if (!existsSync(full)) {
|
|
sendJson(res, 404, { error: "archive file is gone (pruned after the retention window?)" });
|
|
return;
|
|
}
|
|
const size = statSync(full).size;
|
|
res.writeHead(200, {
|
|
"Content-Type": "application/gzip",
|
|
"Content-Length": size,
|
|
"Content-Disposition": `attachment; filename="rithub-export-${job.login}-${job.id}.tar.gz"`,
|
|
});
|
|
createReadStream(full).pipe(res);
|
|
}
|
|
|
|
async function handleNightlyGet(req, res) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
sendJson(res, 200, { enabled: nightly.isOptedIn(resolved.login) });
|
|
}
|
|
|
|
async function handleNightlySet(req, res) {
|
|
const resolved = await resolveCaller(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
const body = await readJsonBody(req).catch(() => ({}));
|
|
const enabled = nightly.setOptIn(resolved.login, Boolean(body.enabled));
|
|
sendJson(res, 200, { enabled });
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
try {
|
|
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
|
|
if (req.method === "GET" && url.pathname === "/export/health") {
|
|
sendJson(res, 200, { ok: true });
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/export") {
|
|
await handlePage(req, res, url);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/export/oauth/start") {
|
|
await handleOAuthStart(req, res, url);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/export/oauth/callback") {
|
|
await handleOAuthCallback(req, res, url);
|
|
return;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/export/api/start") {
|
|
await handleStart(req, res);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/export/api/jobs") {
|
|
await handleJobsList(req, res);
|
|
return;
|
|
}
|
|
const jobMatch = /^\/export\/api\/jobs\/([a-f0-9]+)$/.exec(url.pathname);
|
|
if (req.method === "GET" && jobMatch) {
|
|
await handleJobGet(req, res, jobMatch[1]);
|
|
return;
|
|
}
|
|
const dlMatch = /^\/export\/download\/([a-f0-9]+)$/.exec(url.pathname);
|
|
if (req.method === "GET" && dlMatch) {
|
|
await handleDownload(req, res, dlMatch[1]);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/export/api/nightly") {
|
|
await handleNightlyGet(req, res);
|
|
return;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/export/api/nightly") {
|
|
await handleNightlySet(req, res);
|
|
return;
|
|
}
|
|
sendJson(res, 404, { error: "not found" });
|
|
} catch (err) {
|
|
console.error("rithub-export: unhandled error:", err);
|
|
if (!res.headersSent) sendJson(res, 500, { error: "internal error" });
|
|
}
|
|
});
|
|
|
|
server.listen(PORT, "127.0.0.1", () => {
|
|
console.log(`rithub-export listening on 127.0.0.1:${PORT}`);
|
|
});
|