Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

116 lines · 6.4 KBRaw History
1import type { Context } from "hono";
2import type { Env } from "../env.js";
3import type { Principal } from "../auth/principal.js";
4
5/**
6 * Request rate limits (Workers rate limiting bindings, configured in wrangler.jsonc). Each
7 * binding counts per key over 60 seconds in the Cloudflare location that serves the request, so
8 * the limits stop floods and scripted abuse rather than meter use exactly. A binding that isn't
9 * configured (local development) or that fails lets the request through.
10 *
11 * - RL_AUTH: sign-in, passkey registration, invitation and sign-in links, open sign-up, private
12 * security reports (/security/report), early access requests and their confirmations
13 * (/early-access and its confirm and remove pages), contact messages and their confirmations
14 * (/contact and /contact/confirm), CLI sign-ins (starting one, typing or approving a
15 * code), and MCP apps registering themselves for OAuth (/oauth/register), per IP address.
16 * - RL_ANON: everything else from someone who isn't signed in, per IP address.
17 * - RL_ACCOUNT: everything from a signed-in person, agent or personal token, per account; from an
18 * app's JWT, per app; from an app's installation token, per installation.
19 * - RL_CREATE: creating things other people see or that cost storage (repositories,
20 * organizations, issues, pull requests, comments, reviews, releases), and reports to the site
21 * administrators, per account.
22 *
23 * Job, sandbox, runner and import credentials aren't counted here: their work is bounded by
24 * the job, sandbox and import limits.
25 */
26
27export interface RateLimiter {
28 limit(o: { key: string }): Promise<{ success: boolean }>;
29}
30
31export type Bucket = "RL_AUTH" | "RL_ANON" | "RL_ACCOUNT" | "RL_CREATE";
32
33/** The limits each binding is configured with in production (wrangler.jsonc), for messages and docs. */
34export const RATE_LIMITS: Record<Bucket, number> = { RL_AUTH: 20, RL_ANON: 300, RL_ACCOUNT: 2000, RL_CREATE: 60 };
35export const RATE_PERIOD_S = 60;
36
37/**
38 * Paths that never count: health checks, avatars, the Actions runtime and runners (their own credentials), and
39 * the GitHub App's signed webhook, which GitHub sends from a few addresses for every job of every installation.
40 */
41const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/|-\/github\/webhook$)/;
42const AUTH = /^\/(?:auth\/passkey\/|invite\/|signin\/|login(?:$|\/)|signup(?:$|\/)|security\/report$|early-access(?:\/confirm|\/remove(?:\/confirm)?)?$|contact(?:\/confirm)?$|-\/cli\/device$|oauth\/register$)/;
43const CREATE: Array<[method: string, path: RegExp]> = [
44 ["POST", /^\/api\/v3\/(?:user|orgs\/[^/]+)\/repos$/],
45 ["POST", /^\/api\/v3\/(?:user\/orgs|admin\/organizations)$/],
46 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls|releases|forks)$/],
47 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls)\/\d+\/(?:comments|reviews)$/],
48 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:commits\/[^/]+\/comments|pulls\/\d+\/comments\/\d+\/replies)$/],
49 ["POST", /^\/new(?:\/import)?$/],
50 ["POST", /^\/settings\/orgs$/],
51 ["POST", /^\/[^/]+\/[^/]+\/(?:issues|pulls|releases)$/],
52 ["POST", /^\/[^/]+\/[^/]+\/(?:issues\/\d+\/comment|pull\/\d+\/(?:review|line-comment))$/],
53 // Reports to the site administrators (lib/moderation.ts also caps them per day).
54 ["POST", /^\/api\/v3\/diffinery\/reports$/],
55 ["POST", /^\/-\/report$/],
56];
57
58/** Which buckets a request counts against, with their keys. */
59export function bucketsFor(method: string, path: string, p: Principal, ip: string): Array<[Bucket, string]> {
60 if (EXEMPT.test(path)) return [];
61 if (AUTH.test(path) && method !== "GET") return [["RL_AUTH", `ip:${ip}`]];
62 if (p.type === "anonymous") return [["RL_ANON", `ip:${ip}`]];
63 if (p.type !== "account" && p.type !== "app" && p.type !== "installation") return [];
64 const key = p.type === "account" ? `acct:${p.account.id}` : p.type === "app" ? `app:${p.app.id}` : `inst:${p.auth.installation.id}`;
65 const out: Array<[Bucket, string]> = [["RL_ACCOUNT", key]];
66 // MCP tool calls that change things count in mcp/server.ts, where the tool is known.
67 if (CREATE.some(([m, re]) => m === method && re.test(path))) out.push(["RL_CREATE", key]);
68 return out;
69}
70
71/** The bucket that's over its limit for this request, or null. */
72export async function overLimit(env: Env, buckets: Array<[Bucket, string]>): Promise<Bucket | null> {
73 for (const [b, key] of buckets) {
74 const rl = (env as unknown as Record<string, RateLimiter | undefined>)[b];
75 if (!rl) continue;
76 try {
77 if (!(await rl.limit({ key })).success) return b;
78 } catch (e) {
79 console.error("rate limiter failed", b, e);
80 }
81 }
82 return null;
83}
84
85/**
86 * Model requests through the proxy (/-/model/*), per paying person across all their runs (phase 5a): above the
87 * per-run limits and budgets, it caps how fast a leaked run token or a runaway task can spend a person's key. Kept
88 * out of `bucketsFor` because only the run's ProjectDO knows who pays. Must match RL_MODEL in wrangler.jsonc.
89 */
90export const MODEL_RATE_LIMIT = 600;
91
92/** Whether this person is over their model request rate. A missing (local) or failing binding lets it through. */
93export async function modelRateLimited(env: Env, personId: string): Promise<boolean> {
94 if (!env.RL_MODEL) return false;
95 try {
96 return !(await env.RL_MODEL.limit({ key: `model:${personId}` })).success;
97 } catch (e) {
98 console.error("model rate limiter failed", e);
99 return false;
100 }
101}
102
103const WHAT: Record<Bucket, string> = {
104 RL_AUTH: "sign-in attempts, security reports, early access requests and contact messages from your network",
105 RL_ANON: "requests from your network without signing in",
106 RL_ACCOUNT: "requests from your account",
107 RL_CREATE: "new repositories, issues, pull requests and comments from your account",
108};
109
110/** A 429 that GitHub clients understand (`retry-after`, `x-ratelimit-remaining: 0`). */
111export function tooMany(c: Context, b: Bucket): Response {
112 const message = `Too many ${WHAT[b]}: at most ${RATE_LIMITS[b]} a minute. Try again in a minute.`;
113 const headers = { "retry-after": String(RATE_PERIOD_S), "x-ratelimit-limit": String(RATE_LIMITS[b]), "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + RATE_PERIOD_S) };
114 const html = (c.req.header("accept") ?? "").includes("text/html");
115 return html ? new Response(message, { status: 429, headers: { ...headers, "content-type": "text/plain; charset=utf-8" } }) : Response.json({ message }, { status: 429, headers });
116}