caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

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

248 lines
10 KiB
JavaScript

#!/usr/bin/env node
// Rithub Pro checkout + Dodo Payments webhook (RIT-MON).
// Served behind Caddy at https://rithub.dev/billing/* (handled before the
// the engine catch-all reverse_proxy, same pattern as /mcp* and /agent-tokens*).
// Zero npm dependencies -- plain node:http, matching the rithub-mcp style
// already deployed on this box.
import http from "node:http";
import { createCheckoutSession, verifyWebhook } from "../src/dodo.mjs";
import {
alreadyProcessed,
markProcessed,
appendRawEvent,
upsertEntitlement,
listEntitlements,
} from "../src/store.mjs";
import { getProStatus, listProUsers } from "../src/proStatus.mjs";
import { resolveSignedInLogin } from "../src/ritSession.mjs";
const PORT = Number(process.env.PORT || 3353);
const PUBLIC_BASE = process.env.RITHUB_BILLING_PUBLIC_BASE || "https://rithub.dev";
const DODO_API_KEY = process.env.DODO_API_KEY || "";
const DODO_WEBHOOK_SECRET = process.env.DODO_WEBHOOK_SECRET || "";
const ADMIN_TOKEN = process.env.RITHUB_BILLING_ADMIN_TOKEN || "";
// Allowlisted plan -> product id. Never accept a raw product id from the
// browser (standard Dodo integration mistake); only ever these slugs.
const PLAN_PRODUCTS = {
pro: process.env.DODO_PRODUCT_ID_PRO_MONTH || "",
"pro-year": process.env.DODO_PRODUCT_ID_PRO_YEAR || "",
// Team ($49/mo, 5 seats) and the one-time migration concierge ($149) --
// same checkout/webhook pipeline as Pro above, just a different product
// id and plan label. Real per-seat enforcement is not wired (no quota
// exists to enforce yet, same honest "ships the promise, not an invented
// paywall" rule as Pro) -- this is the real paid checkout + entitlement
// record, same bar RIT-MON already shipped for Pro.
team: process.env.DODO_PRODUCT_ID_TEAM || "",
concierge: process.env.DODO_PRODUCT_ID_CONCIERGE || "",
};
// Plans that are a one-time purchase, not a subscription -- never show a
// "subscription" cancel/change-plan line for these in copy, and the
// lifecycle pass treats them as a service request, not a Pro/Free state.
const ONE_TIME_PLANS = new Set(["concierge"]);
// Reverse lookup (product id -> plan slug), built from PLAN_PRODUCTS once
// env vars are read above. Lets the webhook resolve which of our 4 plans
// an event is about from the product id Dodo actually sends, instead of
// trusting a client-settable metadata field for a security-relevant
// grant decision.
const PRODUCT_TO_PLAN = Object.fromEntries(
Object.entries(PLAN_PRODUCTS)
.filter(([, id]) => id)
.map(([plan, id]) => [id, plan]),
);
/** Resolves which plan a webhook event is about, or undefined if it can't
* be determined (e.g. a cancellation event with no product info) -- in
* that case upsertEntitlement() keeps whatever plan was already on
* record for that customer rather than guessing "pro". */
function resolvePlanFromEvent(data) {
const productId = data.product_cart?.[0]?.product_id ?? data.product_id ?? null;
if (productId && PRODUCT_TO_PLAN[productId]) return PRODUCT_TO_PLAN[productId];
const metaPlan = data.metadata?.plan;
if (metaPlan && Object.prototype.hasOwnProperty.call(PLAN_PRODUCTS, metaPlan)) return metaPlan;
return undefined;
}
const EVENTS_THAT_GRANT = new Set(["payment.succeeded", "subscription.active", "subscription.renewed"]);
const EVENTS_THAT_REVOKE = new Set(["subscription.cancelled", "subscription.expired", "subscription.failed"]);
const EVENTS_THAT_HOLD = new Set(["subscription.on_hold", "payment.failed"]);
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 readRawBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
req.on("error", reject);
});
}
async function handleCheckout(req, res, url) {
const plan = url.searchParams.get("plan") || "pro";
const productId = PLAN_PRODUCTS[plan];
if (!Object.prototype.hasOwnProperty.call(PLAN_PRODUCTS, plan) || !productId) {
sendHtml(res, 400, "<p>Unknown plan.</p>");
return;
}
if (!DODO_API_KEY) {
sendHtml(res, 503, "<p>Billing is not configured yet.</p>");
return;
}
try {
const session = await createCheckoutSession({
apiKey: DODO_API_KEY,
productId,
returnUrl: `${PUBLIC_BASE}/billing/success?plan=${encodeURIComponent(plan)}`,
metadata: { plan, source: "pricing_page" },
});
res.writeHead(302, { Location: session.checkoutUrl });
res.end();
} catch (err) {
console.error("checkout session failed:", err.message);
sendHtml(res, 502, "<p>Could not start checkout. Please try again in a moment.</p>");
}
}
const SUCCESS_COPY = {
pro: "Your Rithub Pro access is applied once we confirm the payment (usually within a minute).",
"pro-year": "Your Rithub Pro access is applied once we confirm the payment (usually within a minute).",
team: "Your Rithub Team plan is applied once we confirm the payment (usually within a minute).",
concierge: "We have your payment. We'll reply by email with next steps for moving your repos, usually within a day.",
};
function handleSuccess(res, url) {
const plan = url.searchParams.get("plan") || "pro";
const copy = SUCCESS_COPY[plan] || SUCCESS_COPY.pro;
sendHtml(
res,
200,
`<!doctype html><meta name=viewport content="width=device-width">
<title>Thanks - Rithub</title>
<body style="font-family:-apple-system,system-ui,sans-serif;display:grid;place-items:center;height:90vh;margin:0">
<div style="text-align:center;max-width:420px">
<h1 style="font-size:20px">Payment received</h1>
<p>${copy} You can close this tab.</p>
<p><a href="/" style="color:#2f6fed">Back to Rithub</a></p>
</div></body>`,
);
}
async function handleWebhook(req, res) {
const rawBody = await readRawBody(req);
if (!DODO_WEBHOOK_SECRET) {
sendJson(res, 503, { error: "webhook secret not configured" });
return;
}
let event;
try {
event = verifyWebhook({
secret: DODO_WEBHOOK_SECRET,
headers: {
"webhook-id": req.headers["webhook-id"],
"webhook-timestamp": req.headers["webhook-timestamp"],
"webhook-signature": req.headers["webhook-signature"],
},
rawBody,
});
} catch (err) {
console.error("webhook verification failed:", err.message);
sendJson(res, 401, { error: "invalid signature" });
return;
}
const webhookId = req.headers["webhook-id"];
appendRawEvent(webhookId, event.type, event.data ?? null);
if (alreadyProcessed(webhookId)) {
sendJson(res, 200, { received: true, duplicate: true });
return;
}
const data = event.data || {};
const customerId = data.customer?.customer_id ?? null;
const email = data.customer?.email ?? null;
const subscriptionId = data.subscription_id ?? data.id ?? null;
const plan = resolvePlanFromEvent(data);
if (EVENTS_THAT_GRANT.has(event.type)) {
upsertEntitlement({ customerId, email, plan, status: "active", eventType: event.type, subscriptionId, raw: data });
} else if (EVENTS_THAT_REVOKE.has(event.type)) {
upsertEntitlement({ customerId, email, plan, status: "revoked", eventType: event.type, subscriptionId, raw: data });
} else if (EVENTS_THAT_HOLD.has(event.type)) {
upsertEntitlement({ customerId, email, plan, status: "on_hold", eventType: event.type, subscriptionId, raw: data });
}
markProcessed(webhookId);
sendJson(res, 200, { received: true });
}
function handleAdmin(req, res, url) {
const token = req.headers["x-admin-token"] || url.searchParams.get("token") || "";
if (!ADMIN_TOKEN || token !== ADMIN_TOKEN) {
sendJson(res, 401, { error: "unauthorized" });
return;
}
// customers = who paid (Dodo's view, keyed by customer/email).
// pro_users = who that resolved to (rithub-lifecycle's view, keyed by
// Rithub login) -- the owner needs both to spot an unlinked payment
// (paid but no login match yet).
sendJson(res, 200, { plan_products: PLAN_PRODUCTS, customers: listEntitlements(), pro_users: listProUsers() });
}
// Real enforcement surface (RIT-MON): the settings-page Pro badge
// (apps/gitea/custom/templates/custom/header.tmpl) calls this for the
// signed-in login. The login is NEVER taken from the query string -- that
// would let anyone probe any other user's Pro/revoked/on_hold state (public
// usernames, zero auth). Instead the request's own session cookie is
// forwarded to Rithub's GET /api/v1/user to prove who is actually signed
// in, and only that login's status is ever returned.
async function handleStatus(req, res) {
const login = await resolveSignedInLogin(req);
if (!login) {
sendJson(res, 401, { error: "not signed in" });
return;
}
sendJson(res, 200, getProStatus(login));
}
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 === "/billing/checkout") {
await handleCheckout(req, res, url);
} else if (req.method === "GET" && url.pathname === "/billing/success") {
handleSuccess(res, url);
} else if (req.method === "POST" && url.pathname === "/billing/webhook") {
await handleWebhook(req, res);
} else if (req.method === "GET" && url.pathname === "/billing/admin") {
handleAdmin(req, res, url);
} else if (req.method === "GET" && url.pathname === "/billing/status") {
await handleStatus(req, res);
} else if (req.method === "GET" && url.pathname === "/billing/health") {
sendJson(res, 200, { ok: true, configured: Boolean(DODO_API_KEY && DODO_WEBHOOK_SECRET) });
} 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-billing listening on 127.0.0.1:${PORT}`);
});