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.

160 lines · 8.5 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, unless RATE_LIMITS=durable:
10 * then the RATE_LIMITER Durable Object counts that bucket instead (rate-limiter.ts), for deployments
11 * without the bindings, such as celld. It fails open too.
12 *
13 * - RL_AUTH: sign-in, passkey registration, invitation and sign-in links, open sign-up, private
14 * security reports (/security/report), early access requests and their confirmations
15 * (/early-access and its confirm and remove pages), contact messages and their confirmations
16 * (/contact and /contact/confirm), CLI sign-ins (starting one, typing or approving a
17 * code), and MCP apps registering themselves for OAuth (/oauth/register), per IP address.
18 * - RL_ANON: everything else from someone who isn't signed in, per IP address.
19 * - RL_ACCOUNT: everything from a signed-in person, agent or personal token, per account; from an
20 * app's JWT, per app; from an app's installation token, per installation.
21 * - RL_CREATE: creating things other people see or that cost storage (repositories,
22 * organizations, issues, pull requests, comments, reviews, releases), and reports to the site
23 * administrators, per account.
24 *
25 * Job, sandbox, runner and import credentials aren't counted here: their work is bounded by
26 * the job, sandbox and import limits.
27 */
28
29export interface RateLimiter {
30 limit(o: { key: string }): Promise<{ success: boolean }>;
31}
32
33export type Bucket = "RL_AUTH" | "RL_ANON" | "RL_ACCOUNT" | "RL_CREATE";
34
35/** The limits each binding is configured with in production (wrangler.jsonc), for messages and docs. */
36export const RATE_LIMITS: Record<Bucket, number> = { RL_AUTH: 20, RL_ANON: 300, RL_ACCOUNT: 2000, RL_CREATE: 60 };
37export const RATE_PERIOD_S = 60;
38
39/**
40 * Paths that never count: health checks, avatars, the Actions runtime and runners (their own credentials), and
41 * the GitHub App's signed webhook, which GitHub sends from a few addresses for every job of every installation.
42 */
43const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/|-\/github\/webhook$)/;
44const AUTH = /^\/(?:auth\/passkey\/|invite\/|signin\/|login(?:$|\/)|signup(?:$|\/)|security\/report$|early-access(?:\/confirm|\/remove(?:\/confirm)?)?$|contact(?:\/confirm)?$|-\/cli\/device$|oauth\/register$)/;
45const CREATE: Array<[method: string, path: RegExp]> = [
46 ["POST", /^\/api\/v3\/(?:user|orgs\/[^/]+)\/repos$/],
47 ["POST", /^\/api\/v3\/(?:user\/orgs|admin\/organizations)$/],
48 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls|releases|forks)$/],
49 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls)\/\d+\/(?:comments|reviews)$/],
50 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:commits\/[^/]+\/comments|pulls\/\d+\/comments\/\d+\/replies)$/],
51 ["POST", /^\/new(?:\/import)?$/],
52 ["POST", /^\/settings\/orgs$/],
53 ["POST", /^\/[^/]+\/[^/]+\/(?:issues|pulls|releases)$/],
54 ["POST", /^\/[^/]+\/[^/]+\/(?:issues\/\d+\/comment|pull\/\d+\/(?:review|line-comment))$/],
55 // Reports to the site administrators (lib/moderation.ts also caps them per day).
56 ["POST", /^\/api\/v3\/diffinery\/reports$/],
57 ["POST", /^\/-\/report$/],
58];
59
60/** Which buckets a request counts against, with their keys. */
61export function bucketsFor(method: string, path: string, p: Principal, ip: string): Array<[Bucket, string]> {
62 if (EXEMPT.test(path)) return [];
63 if (AUTH.test(path) && method !== "GET") return [["RL_AUTH", `ip:${ip}`]];
64 if (p.type === "anonymous") return [["RL_ANON", `ip:${ip}`]];
65 if (p.type !== "account" && p.type !== "app" && p.type !== "installation") return [];
66 const key = p.type === "account" ? `acct:${p.account.id}` : p.type === "app" ? `app:${p.app.id}` : `inst:${p.auth.installation.id}`;
67 const out: Array<[Bucket, string]> = [["RL_ACCOUNT", key]];
68 // MCP tool calls that change things count in mcp/server.ts, where the tool is known.
69 if (CREATE.some(([m, re]) => m === method && re.test(path))) out.push(["RL_CREATE", key]);
70 return out;
71}
72
73/** The bucket that's over its limit for this request, or null. */
74export async function overLimit(env: Env, buckets: Array<[Bucket, string]>): Promise<Bucket | null> {
75 const unbound: Array<[Bucket, string]> = [];
76 for (const [b, key] of buckets) {
77 const rl = (env as unknown as Record<string, RateLimiter | undefined>)[b];
78 if (!rl) {
79 unbound.push([b, key]);
80 continue;
81 }
82 try {
83 if (!(await rl.limit({ key })).success) return b;
84 } catch (e) {
85 console.error("rate limiter failed", b, e);
86 }
87 }
88 return durableOverLimit(env, unbound);
89}
90
91/**
92 * Model requests through the proxy (/-/model/*), per paying person across all their runs (phase 5a): above the
93 * per-run limits and budgets, it caps how fast a leaked run token or a runaway task can spend a person's key. Kept
94 * out of `bucketsFor` because only the run's ProjectDO knows who pays. Must match RL_MODEL in wrangler.jsonc.
95 */
96export const MODEL_RATE_LIMIT = 600;
97
98/** Whether this person is over their model request rate. A missing (local) or failing binding lets it through. */
99export async function modelRateLimited(env: Env, personId: string): Promise<boolean> {
100 if (!env.RL_MODEL) return (await durableOverLimit(env, [["RL_MODEL", `model:${personId}`]])) !== null;
101 try {
102 return !(await env.RL_MODEL.limit({ key: `model:${personId}` })).success;
103 } catch (e) {
104 console.error("model rate limiter failed", e);
105 return false;
106 }
107}
108
109/** Limits per window for the Durable Object fallback: the same as the bindings'. */
110const DURABLE_LIMITS: Record<Bucket | "RL_MODEL", number> = { ...RATE_LIMITS, RL_MODEL: MODEL_RATE_LIMIT };
111
112/**
113 * Objects the fallback spreads keys over. A key always lands on the same one; the requests of one
114 * key (one address, one account) can't be spread anyway, and a fixed set keeps the objects few and
115 * warm instead of one per address.
116 */
117export const RATE_LIMITER_SHARDS = 32;
118
119/** The RATE_LIMITER object that counts `key`: FNV-1a of the key, modulo the shards. */
120export function rateLimiterShard(key: string): string {
121 let h = 0x811c9dc5;
122 for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 0x01000193);
123 return `shard-${(h >>> 0) % RATE_LIMITER_SHARDS}`;
124}
125
126/**
127 * Counts buckets that have no binding in the RATE_LIMITER Durable Object, when RATE_LIMITS=durable.
128 * One call per key, so a request costs one call: its buckets share a key (an account's requests
129 * and its new content). A failing object lets the request through, as a failing binding does.
130 */
131async function durableOverLimit<B extends Bucket | "RL_MODEL">(env: Env, buckets: Array<[B, string]>): Promise<B | null> {
132 const ns = env.RATE_LIMITS === "durable" ? env.RATE_LIMITER : undefined;
133 if (!ns || !buckets.length) return null;
134 const byKey = new Map<string, Array<[B, number]>>();
135 for (const [b, key] of buckets) byKey.set(key, [...(byKey.get(key) ?? []), [b, DURABLE_LIMITS[b]]]);
136 for (const [key, limits] of byKey) {
137 try {
138 const over = await ns.get(ns.idFromName(rateLimiterShard(key))).hit(key, limits);
139 if (over) return over as B;
140 } catch (e) {
141 console.error("rate limiter object failed", e);
142 }
143 }
144 return null;
145}
146
147const WHAT: Record<Bucket, string> = {
148 RL_AUTH: "sign-in attempts, security reports, early access requests and contact messages from your network",
149 RL_ANON: "requests from your network without signing in",
150 RL_ACCOUNT: "requests from your account",
151 RL_CREATE: "new repositories, issues, pull requests and comments from your account",
152};
153
154/** A 429 that GitHub clients understand (`retry-after`, `x-ratelimit-remaining: 0`). */
155export function tooMany(c: Context, b: Bucket): Response {
156 const message = `Too many ${WHAT[b]}: at most ${RATE_LIMITS[b]} a minute. Try again in a minute.`;
157 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) };
158 const html = (c.req.header("accept") ?? "").includes("text/html");
159 return html ? new Response(message, { status: 429, headers: { ...headers, "content-type": "text/plain; charset=utf-8" } }) : Response.json({ message }, { status: 429, headers });
160}