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>
515 lines
26 KiB
JavaScript
515 lines
26 KiB
JavaScript
#!/usr/bin/env node
|
|
// Rithub push-approval service (RIT-ACT, plans/railyard.md queue item 3).
|
|
// Served behind Caddy at https://rithub.dev/approvals* (handled before the
|
|
// engine's own catch-all reverse_proxy, same pattern as /protect*,
|
|
// /billing*, /device*). Zero npm dependencies -- plain node:http, matching
|
|
// every sibling rithub-* pm2 service on this box.
|
|
//
|
|
// What this holds: a push made with an agent-session token that is a
|
|
// force-push, a branch delete, or a push to a protected branch never
|
|
// touches the real branch directly. `rit push`/`rit branch delete` stage
|
|
// it here instead (see packages/rithub-cli/src/push-approval.mjs); a named
|
|
// human with push/admin on the repo lands it with their OWN token
|
|
// (`rit push approve <id>` or this page) or throws it away
|
|
// (`rit push deny <id>`). This service stores no credential of its own --
|
|
// see src/gitOps.mjs's header comment.
|
|
import http from "node:http";
|
|
import crypto from "node:crypto";
|
|
import { readFileSync } from "node:fs";
|
|
import { dirname, join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { resolveSignedInSession } from "../src/ritSession.mjs";
|
|
import {
|
|
ApprovalError,
|
|
createPendingApproval,
|
|
confirmPendingPush,
|
|
cancelPendingApproval,
|
|
approvePendingApproval,
|
|
denyPendingApproval,
|
|
getApprovalView,
|
|
listApprovalsFor,
|
|
listPendingAcrossRepos,
|
|
} from "../src/approvals.mjs";
|
|
import { markAgentToken, listMarksForLogin, revokeMarkForLogin, ISSUANCE_MARK_TTL_MS } from "../src/agentSessionTokens.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";
|
|
|
|
const RITHUB_BASE_URL = (process.env.RITHUB_BASE_URL || "https://rithub.dev").replace(/\/$/, "");
|
|
|
|
// RIT-ACT gap 2 OAuth round trip: `state` -> {codeVerifier, createdAt}.
|
|
// In-memory, short-lived (10 min) -- a restart mid-authorize just fails
|
|
// that one in-flight attempt, same stance as rithub-device-auth's device
|
|
// records (not a security property, just UX).
|
|
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);
|
|
const state = crypto.randomUUID();
|
|
return state;
|
|
}
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
const SHELL_HTML = readFileSync(join(__dirname, "..", "src", "shell.html"), "utf8");
|
|
|
|
const PORT = Number(process.env.PORT || 3361);
|
|
|
|
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);
|
|
}
|
|
|
|
// RIT-ACT gap 2 (2026-12-01): no owner/repo fields, no pasted token. The
|
|
// page itself carries nothing but the real rithub.dev session cookie --
|
|
// every list/approve/deny call below is same-origin `fetch` with no body,
|
|
// authenticated server-side by that cookie (see /approvals/api/mine*
|
|
// below). The one-time "Authorize" link is the engine's own real OAuth2
|
|
// consent screen (not a form this page renders), needed exactly once per
|
|
// browser/account so this service can later act with that human's own
|
|
// permissions -- same non-negotiable safety property the Bearer-token
|
|
// path already had ("an approval can never do more than the approving
|
|
// human could already do by hand").
|
|
function pageBodyNeedsAuthorize() {
|
|
return `
|
|
<div class="rithub-approvals-intro">
|
|
<h1>Held pushes</h1>
|
|
<p>Agent-session pushes that were a force-push, a branch delete, or a push to a protected branch wait here until a named human with push/admin on the repo approves or denies them. Nothing lands until you decide.</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="/approvals/oauth/start">Authorize</a>
|
|
</div>`;
|
|
}
|
|
|
|
function pageBodyInbox() {
|
|
return `
|
|
<div class="rithub-approvals-intro">
|
|
<h1>Held pushes, all repos</h1>
|
|
<p>Agent-session pushes that were a force-push, a branch delete, or a push to a protected branch wait here until a named human with push/admin on the repo approves or denies them. Nothing lands until you decide.</p>
|
|
</div>
|
|
<div id="rit-ap-list"><p class="rithub-approval-empty">Loading…</p></div>
|
|
<script>
|
|
(function () {
|
|
function qs(id) { return document.getElementById(id); }
|
|
function esc(s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }
|
|
function card(a) {
|
|
var badge = '<span class="rithub-approval-badge status-' + esc(a.status) + '">' + esc(a.status) + '</span>';
|
|
var actions = '<div class="rithub-approval-actions"><button class="ui button" data-id="' + esc(a.id) + '" data-decision="approve" title="Approve">✓</button><button class="ui button" data-id="' + esc(a.id) + '" data-decision="deny" title="Deny">✕</button></div>';
|
|
return '<div class="rithub-approval-card">' +
|
|
'<div class="rithub-approval-head"><span class="rithub-approval-repo">' + esc(a.owner) + '/' + esc(a.repo) + ' · ' + esc(a.target_ref.replace('refs/heads/', '')) + '</span>' + badge + '</div>' +
|
|
'<div class="rithub-approval-meta">' + esc(a.action) + (a.forced ? ' (force)' : '') + ' · requested by ' + esc(a.requested_by) + (a.session_id ? ' · session <code>' + esc(a.session_id) + '</code>' : '') + ' · <code>' + esc((a.oldrev || '').slice(0, 10)) + '</code> → <code>' + esc((a.newrev || '').slice(0, 10)) + '</code></div>' +
|
|
(a.reason ? '<div class="rithub-approval-meta">' + esc(a.reason) + '</div>' : '') +
|
|
actions + '</div>';
|
|
}
|
|
async function load() {
|
|
var list = qs('rit-ap-list');
|
|
try {
|
|
var res = await fetch('/approvals/api/mine', { headers: { accept: 'application/json' } });
|
|
var body = await res.json();
|
|
if (res.status === 401 && body.authorize_url) { window.location.href = body.authorize_url; return; }
|
|
if (!res.ok) { list.innerHTML = '<p class="rithub-approval-empty">' + esc(body.error || ('HTTP ' + res.status)) + '</p>'; return; }
|
|
if (!body.approvals.length) { list.innerHTML = '<p class="rithub-approval-empty">No held pushes across your repos.</p>'; return; }
|
|
list.innerHTML = body.approvals.map(card).join('');
|
|
Array.prototype.forEach.call(list.querySelectorAll('button[data-decision]'), function (btn) {
|
|
btn.addEventListener('click', function () { decide(btn.getAttribute('data-id'), btn.getAttribute('data-decision')); });
|
|
});
|
|
} catch (err) {
|
|
list.innerHTML = '<p class="rithub-approval-empty">' + esc(String(err)) + '</p>';
|
|
}
|
|
}
|
|
async function decide(id, decision) {
|
|
try {
|
|
var res = await fetch('/approvals/api/mine/' + encodeURIComponent(id) + '/' + decision, { method: 'POST' });
|
|
var body = await res.json();
|
|
if (!res.ok) { alert(body.error || ('HTTP ' + res.status)); }
|
|
load();
|
|
} catch (err) {
|
|
alert(String(err));
|
|
}
|
|
}
|
|
load();
|
|
})();
|
|
</script>`;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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));
|
|
const content = hasToken ? pageBodyInbox() : pageBodyNeedsAuthorize();
|
|
sendHtml(res, 200, renderShell({ title: "Held pushes", session, content }));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// RIT-ACT gap 2 ("no pasted tokens") -- OAuth round trip that gets this
|
|
// service a real, scoped engine access token for the signed-in human
|
|
// without ever asking them to copy/paste one. Same real "Rit CLI" OAuth2
|
|
// application + PKCE flow as rithub-device-auth's `rit login`, a separate
|
|
// redirect_uri (see src/ritOAuth.mjs).
|
|
// ---------------------------------------------------------------------------
|
|
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 + url.search)}` });
|
|
res.end();
|
|
return;
|
|
}
|
|
if (!oauthConfigured()) {
|
|
sendHtml(res, 503, renderShell({ title: "Not configured", session, content: "<p>Authorize is not configured yet.</p>" }));
|
|
return;
|
|
}
|
|
// Two purposes share this one real OAuth2 round trip (same "Rit CLI"
|
|
// app as `rit login`/`/device`): the default, "authorize", gets THIS
|
|
// service its own acting-as-you token (saved, used for Approve/Deny --
|
|
// unchanged, gap 2 above). "new-agent-token" (RIT-ACT "enforced, not
|
|
// opt-in" pass, 2026-12-01) mints a brand-new, separate token that is
|
|
// immediately marked agent-identity and shown to the human once -- it
|
|
// is never saved into oauthTokenStore, so it never becomes this
|
|
// service's own acting identity.
|
|
const purpose = url.searchParams.get("purpose") === "new-agent-token" ? "new-agent-token" : "authorize";
|
|
const codeVerifier = newVerifier();
|
|
const codeChallenge = challengeFor(codeVerifier);
|
|
const state = newOAuthState();
|
|
pendingOAuth.set(state, { codeVerifier, login: session.login, purpose, createdAt: Date.now() });
|
|
res.writeHead(302, { Location: buildAuthorizeUrl({ state, codeChallenge }) });
|
|
res.end();
|
|
}
|
|
|
|
// Masks everything but a few chars at each end, e.g. "eyJhbGci••••••••WPOl4"
|
|
// -- enough to recognize/compare the token at a glance without the whole
|
|
// ~700-char secret sitting exposed on screen (shoulder-surfing, screenshots,
|
|
// screen-share) by default. The real value never leaves `data-token`;
|
|
// reveal/copy both read from there, never from the masked text node.
|
|
function maskToken(token) {
|
|
if (token.length <= 20) return token;
|
|
return token.slice(0, 8) + "•".repeat(10) + token.slice(-6);
|
|
}
|
|
|
|
function pageBodyNewAgentToken({ token, login }) {
|
|
const masked = escapeHtml(maskToken(token));
|
|
const full = escapeHtml(token);
|
|
return `
|
|
<div class="rithub-approvals-intro">
|
|
<h1>New agent token</h1>
|
|
<p>This is a real Rithub access token for <strong>${escapeHtml(login)}</strong>, already marked as an agent credential. A force-push or a push to a protected branch made with it is held for a human to approve, the same as a <code>rit login</code> device sign-in. Shown once; copy it now.</p>
|
|
</div>
|
|
<div class="ui segment">
|
|
<div class="rithub-token-reveal-wrap">
|
|
<code id="rit-new-token" data-token="${full}" data-masked="${masked}" style="user-select:all;word-break:break-all;">${masked}</code>
|
|
<button class="rithub-token-icon-btn" id="rit-reveal-token" type="button" aria-label="Show token" title="Show token">
|
|
<svg viewBox="0 0 16 16" class="rithub-token-icon-eye" aria-hidden="true" width="16" height="16"><path d="M8 2c1.981 0 3.671.992 4.933 2.078 1.27 1.091 2.187 2.345 2.637 3.023a1.62 1.62 0 0 1 0 1.798c-.45.678-1.367 1.932-2.637 3.023C11.67 13.008 9.981 14 8 14s-3.671-.992-4.933-2.078C1.797 10.83.88 9.576.43 8.898a1.62 1.62 0 0 1 0-1.798c.45-.677 1.367-1.931 2.637-3.022C4.33 2.992 6.019 2 8 2M1.679 7.932a.12.12 0 0 0 0 .136c.411.622 1.241 1.75 2.366 2.717C5.176 11.758 6.527 12.5 8 12.5s2.825-.742 3.955-1.715c1.124-.967 1.954-2.096 2.366-2.717a.12.12 0 0 0 0-.136c-.412-.621-1.242-1.75-2.366-2.717C10.824 4.242 9.473 3.5 8 3.5s-2.825.742-3.955 1.715c-1.124.967-1.954 2.096-2.366 2.717M8 10a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 10"/></svg>
|
|
<svg viewBox="0 0 16 16" class="rithub-token-icon-eye-closed" aria-hidden="true" width="16" height="16"><path d="M.143 2.31a.75.75 0 0 1 1.047-.167l14.5 10.5a.75.75 0 1 1-.88 1.214l-2.248-1.628C11.346 13.19 9.792 14 8 14c-1.981 0-3.67-.992-4.933-2.078C1.797 10.832.88 9.577.43 8.9a1.62 1.62 0 0 1 0-1.797c.353-.533.995-1.42 1.868-2.305L.31 3.357A.75.75 0 0 1 .143 2.31m1.536 5.622A.12.12 0 0 0 1.657 8q-.001.033.022.068c.412.621 1.242 1.75 2.366 2.717C5.175 11.758 6.527 12.5 8 12.5c1.195 0 2.31-.488 3.29-1.191L9.063 9.695A2 2 0 0 1 6.058 7.52L3.529 5.688a14.2 14.2 0 0 0-1.85 2.244M8 3.5c-.516 0-1.017.09-1.499.251a.75.75 0 1 1-.473-1.423A6.2 6.2 0 0 1 8 2c1.981 0 3.67.992 4.933 2.078 1.27 1.091 2.187 2.345 2.637 3.023a1.62 1.62 0 0 1 0 1.798c-.11.166-.248.365-.41.587a.75.75 0 1 1-1.21-.887c.148-.201.272-.382.371-.53a.12.12 0 0 0 0-.137c-.412-.621-1.242-1.75-2.366-2.717C10.825 4.242 9.473 3.5 8 3.5"/></svg>
|
|
</button>
|
|
<button class="rithub-token-icon-btn" id="rit-copy-token" type="button" aria-label="Copy token" title="Copy token">
|
|
<svg viewBox="0 0 16 16" aria-hidden="true" width="16" height="16"><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"/><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"/></svg>
|
|
</button>
|
|
</div>
|
|
<div class="rithub-approval-actions" style="margin-top:12px;">
|
|
<a class="ui button" href="/user/settings/applications">Back to token settings</a>
|
|
</div>
|
|
</div>
|
|
<script>
|
|
(function () {
|
|
var code = document.getElementById('rit-new-token');
|
|
var revealBtn = document.getElementById('rit-reveal-token');
|
|
var copyBtn = document.getElementById('rit-copy-token');
|
|
if (!code || !revealBtn || !copyBtn) return;
|
|
var revealed = false;
|
|
revealBtn.addEventListener('click', function () {
|
|
revealed = !revealed;
|
|
code.textContent = revealed ? code.getAttribute('data-token') : code.getAttribute('data-masked');
|
|
revealBtn.classList.toggle('is-revealed', revealed);
|
|
revealBtn.setAttribute('aria-label', revealed ? 'Hide token' : 'Show token');
|
|
revealBtn.setAttribute('title', revealed ? 'Hide token' : 'Show token');
|
|
});
|
|
copyBtn.addEventListener('click', function () {
|
|
navigator.clipboard.writeText(code.getAttribute('data-token') || '').then(function () {
|
|
copyBtn.classList.add('is-copied');
|
|
setTimeout(function () { copyBtn.classList.remove('is-copied'); }, 1500);
|
|
});
|
|
});
|
|
})();
|
|
</script>`;
|
|
}
|
|
|
|
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); // single-use
|
|
|
|
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="/approvals/oauth/start">Try again</a>.</p>` }));
|
|
return;
|
|
}
|
|
let accessToken;
|
|
try {
|
|
const exchanged = await exchangeCode({ code, codeVerifier: record.codeVerifier });
|
|
accessToken = exchanged.accessToken;
|
|
if (record.purpose === "new-agent-token") {
|
|
await markAgentToken({ token: accessToken, login: record.login, source: "new-agent-token", ttlMs: ISSUANCE_MARK_TTL_MS });
|
|
} else {
|
|
await saveTokenForLogin(record.login, { accessToken, scope: exchanged.scope });
|
|
}
|
|
} catch (err) {
|
|
sendHtml(res, 502, renderShell({ title: "Authorize failed", session: null, content: `<p>${escapeHtml(String(err?.message || err))} <a href="/approvals/oauth/start">Try again</a>.</p>` }));
|
|
return;
|
|
}
|
|
if (record.purpose === "new-agent-token") {
|
|
sendHtml(res, 200, renderShell({ title: "New agent token", session: { login: record.login }, content: pageBodyNewAgentToken({ token: accessToken, login: record.login }) }));
|
|
return;
|
|
}
|
|
res.writeHead(302, { Location: "/approvals" });
|
|
res.end();
|
|
}
|
|
|
|
/** Resolves a token for a mutating `/approvals/api/mine*` route purely
|
|
* from the signed-in cookie session -- never from a header/body the
|
|
* browser sends, so there is no form field anywhere on this page. */
|
|
async function requireOwnToken(req) {
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) return { error: 401, body: { error: "not signed in" } };
|
|
const token = tokenForLogin(session.login);
|
|
if (!token) return { error: 401, body: { error: "not authorized yet", authorize_url: "/approvals/oauth/start" } };
|
|
return { token, login: session.login };
|
|
}
|
|
|
|
async function withErrors(res, fn) {
|
|
try {
|
|
await fn();
|
|
} catch (err) {
|
|
if (err instanceof ApprovalError) {
|
|
sendJson(res, err.status, { error: err.message });
|
|
return;
|
|
}
|
|
console.error("unhandled error:", err);
|
|
sendJson(res, 500, { error: "internal error" });
|
|
}
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
|
|
const token = bearerToken(req);
|
|
|
|
if (req.method === "GET" && url.pathname === "/approvals/health") {
|
|
sendJson(res, 200, { ok: true });
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/approvals") {
|
|
await handlePage(req, res, url);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/approvals/oauth/start") {
|
|
await handleOAuthStart(req, res, url);
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/approvals/oauth/callback") {
|
|
await handleOAuthCallback(req, res, url);
|
|
return;
|
|
}
|
|
// "New agent token" button (token-settings panel, apps/gitea's
|
|
// applications.tmpl override) -- a plain link to the real OAuth2
|
|
// consent screen, purpose locked to "new-agent-token" so the callback
|
|
// above marks (never saves-as-mine) the resulting token.
|
|
if (req.method === "GET" && url.pathname === "/approvals/agent-tokens/new") {
|
|
res.writeHead(302, { Location: "/approvals/oauth/start?purpose=new-agent-token" });
|
|
res.end();
|
|
return;
|
|
}
|
|
// Cookie-session only (same stance as /approvals/api/mine* below) --
|
|
// lists the signed-in human's own agent-identity marks for the
|
|
// token-settings panel. No token, hash, or raw credential is ever in
|
|
// this response, only a 10-hex-char, per-login-scoped short id.
|
|
if (req.method === "GET" && url.pathname === "/approvals/api/agent-tokens") {
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) {
|
|
sendJson(res, 401, { error: "not signed in" });
|
|
return;
|
|
}
|
|
sendJson(res, 200, { tokens: listMarksForLogin(session.login) });
|
|
return;
|
|
}
|
|
const revokeMatch = /^\/approvals\/api\/agent-tokens\/([0-9a-f]{4,64})\/revoke$/.exec(url.pathname);
|
|
if (req.method === "POST" && revokeMatch) {
|
|
const session = await resolveSignedInSession(req);
|
|
if (!session) {
|
|
sendJson(res, 401, { error: "not signed in" });
|
|
return;
|
|
}
|
|
const revoked = await revokeMarkForLogin({ login: session.login, shortId: revokeMatch[1] });
|
|
if (!revoked) {
|
|
sendJson(res, 404, { error: "no such (unrevoked) agent token" });
|
|
return;
|
|
}
|
|
sendJson(res, 200, { revoked: true });
|
|
return;
|
|
}
|
|
// Service-to-service issuance mark (RIT-ACT "enforced, not opt-in"
|
|
// pass): called by apps/rithub-device-auth right after it mints a real
|
|
// access token via the device/browser sign-in flow, with THAT SAME
|
|
// token as the bearer -- same trust rule as every mark route here,
|
|
// "there is no way to mark a token you do not already possess".
|
|
if (req.method === "POST" && url.pathname === "/approvals/api/agent-identity/mark") {
|
|
await withErrors(res, async () => {
|
|
if (!token) throw new ApprovalError("a bearer token is required.", 401);
|
|
const body = await readJsonBody(req);
|
|
const source = body.source === "new-agent-token" ? "new-agent-token" : "device-login";
|
|
const login = await resolveCallerLogin({ baseUrl: RITHUB_BASE_URL, token });
|
|
if (!login) throw new ApprovalError("could not resolve the calling token (not signed in?).", 401);
|
|
const result = await markAgentToken({ token, login, source, ttlMs: ISSUANCE_MARK_TTL_MS });
|
|
sendJson(res, 201, result);
|
|
});
|
|
return;
|
|
}
|
|
// RIT-ACT gap 1 (server-side enforcement): `rit` marks its own bearer
|
|
// token as agent-session-attributed the first time any command runs
|
|
// with RITHUB_AGENT_SESSION_ID set (packages/rithub-cli/src/cli.mjs).
|
|
// apps/rithub-agent-gateway reads this same mark (shared
|
|
// RITHUB_APPROVALS_DATA_DIR) to hold a RAW git push/delete made with
|
|
// that same token, even when `rit push`'s own client-side staging is
|
|
// bypassed entirely.
|
|
if (req.method === "POST" && url.pathname === "/approvals/api/agent-session/mark") {
|
|
await withErrors(res, async () => {
|
|
if (!token) throw new ApprovalError("a bearer token is required.", 401);
|
|
const body = await readJsonBody(req);
|
|
if (!body.session_id) throw new ApprovalError("session_id is required.", 400);
|
|
const login = await resolveCallerLogin({ baseUrl: RITHUB_BASE_URL, token });
|
|
if (!login) throw new ApprovalError("could not resolve the calling token (not signed in?).", 401);
|
|
const result = await markAgentToken({ token, sessionId: body.session_id, login });
|
|
sendJson(res, 201, result);
|
|
});
|
|
return;
|
|
}
|
|
// RIT-ACT gap 2 ("no pasted tokens") -- cross-repo inbox + one-click
|
|
// decide, cookie-session only (see requireOwnToken above).
|
|
if (req.method === "GET" && url.pathname === "/approvals/api/mine") {
|
|
const resolved = await requireOwnToken(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
await withErrors(res, async () => {
|
|
const approvals = await listPendingAcrossRepos({ token: resolved.token });
|
|
sendJson(res, 200, { approvals });
|
|
});
|
|
return;
|
|
}
|
|
const mineIdMatch = /^\/approvals\/api\/mine\/([^/]+)\/(approve|deny)$/.exec(url.pathname);
|
|
if (req.method === "POST" && mineIdMatch) {
|
|
const resolved = await requireOwnToken(req);
|
|
if (resolved.error) {
|
|
sendJson(res, resolved.error, resolved.body);
|
|
return;
|
|
}
|
|
await withErrors(res, async () => {
|
|
const [, id, verb] = mineIdMatch;
|
|
const result = verb === "approve" ? await approvePendingApproval({ token: resolved.token, id }) : await denyPendingApproval({ token: resolved.token, id });
|
|
sendJson(res, 200, result);
|
|
});
|
|
return;
|
|
}
|
|
if (req.method === "GET" && url.pathname === "/approvals/api/list") {
|
|
await withErrors(res, async () => {
|
|
const approvals = await listApprovalsFor({ token, owner: url.searchParams.get("owner"), repo: url.searchParams.get("repo"), status: url.searchParams.get("status") || undefined });
|
|
sendJson(res, 200, { approvals });
|
|
});
|
|
return;
|
|
}
|
|
if (req.method === "POST" && url.pathname === "/approvals/api/create") {
|
|
await withErrors(res, async () => {
|
|
const body = await readJsonBody(req);
|
|
const approval = await createPendingApproval({ token, owner: body.owner, repo: body.repo, action: body.action, branch: body.branch, forced: body.forced, reason: body.reason, sessionId: body.session_id, newrevHint: body.newrev });
|
|
sendJson(res, 201, approval);
|
|
});
|
|
return;
|
|
}
|
|
const idMatch = /^\/approvals\/api\/([^/]+)\/(confirm|cancel|approve|deny)$/.exec(url.pathname);
|
|
if (req.method === "POST" && idMatch) {
|
|
await withErrors(res, async () => {
|
|
const [, id, verb] = idMatch;
|
|
const body = await readJsonBody(req).catch(() => ({}));
|
|
let result;
|
|
if (verb === "confirm") result = await confirmPendingPush({ token, id, newrev: body.newrev });
|
|
else if (verb === "cancel") result = await cancelPendingApproval({ token, id });
|
|
else if (verb === "approve") result = await approvePendingApproval({ token, id });
|
|
else result = await denyPendingApproval({ token, id });
|
|
sendJson(res, 200, result);
|
|
});
|
|
return;
|
|
}
|
|
const getIdMatch = /^\/approvals\/api\/([^/]+)$/.exec(url.pathname);
|
|
if (req.method === "GET" && getIdMatch) {
|
|
await withErrors(res, async () => {
|
|
const approval = await getApprovalView({ token, id: getIdMatch[1] });
|
|
sendJson(res, 200, approval);
|
|
});
|
|
return;
|
|
}
|
|
|
|
sendJson(res, 404, { error: "not found" });
|
|
});
|
|
|
|
server.listen(PORT, "127.0.0.1", () => {
|
|
console.log(`rithub-approvals listening on 127.0.0.1:${PORT}`);
|
|
});
|