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.

113 lines · 6.3 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/** Paths that never count: health checks, avatars, and the Actions runtime and runners (their own credentials). */
38const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/)/;
39const AUTH = /^\/(?:auth\/passkey\/|invite\/|signin\/|login(?:$|\/)|signup(?:$|\/)|security\/report$|early-access(?:\/confirm|\/remove(?:\/confirm)?)?$|contact(?:\/confirm)?$|-\/cli\/device$|oauth\/register$)/;
40const CREATE: Array<[method: string, path: RegExp]> = [
41 ["POST", /^\/api\/v3\/(?:user|orgs\/[^/]+)\/repos$/],
42 ["POST", /^\/api\/v3\/(?:user\/orgs|admin\/organizations)$/],
43 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls|releases|forks)$/],
44 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:issues|pulls)\/\d+\/(?:comments|reviews)$/],
45 ["POST", /^\/api\/v3\/repos\/[^/]+\/[^/]+\/(?:commits\/[^/]+\/comments|pulls\/\d+\/comments\/\d+\/replies)$/],
46 ["POST", /^\/new(?:\/import)?$/],
47 ["POST", /^\/settings\/orgs$/],
48 ["POST", /^\/[^/]+\/[^/]+\/(?:issues|pulls|releases)$/],
49 ["POST", /^\/[^/]+\/[^/]+\/(?:issues\/\d+\/comment|pull\/\d+\/(?:review|line-comment))$/],
50 // Reports to the site administrators (lib/moderation.ts also caps them per day).
51 ["POST", /^\/api\/v3\/diffinery\/reports$/],
52 ["POST", /^\/-\/report$/],
53];
54
55/** Which buckets a request counts against, with their keys. */
56export function bucketsFor(method: string, path: string, p: Principal, ip: string): Array<[Bucket, string]> {
57 if (EXEMPT.test(path)) return [];
58 if (AUTH.test(path) && method !== "GET") return [["RL_AUTH", `ip:${ip}`]];
59 if (p.type === "anonymous") return [["RL_ANON", `ip:${ip}`]];
60 if (p.type !== "account" && p.type !== "app" && p.type !== "installation") return [];
61 const key = p.type === "account" ? `acct:${p.account.id}` : p.type === "app" ? `app:${p.app.id}` : `inst:${p.auth.installation.id}`;
62 const out: Array<[Bucket, string]> = [["RL_ACCOUNT", key]];
63 // MCP tool calls that change things count in mcp/server.ts, where the tool is known.
64 if (CREATE.some(([m, re]) => m === method && re.test(path))) out.push(["RL_CREATE", key]);
65 return out;
66}
67
68/** The bucket that's over its limit for this request, or null. */
69export async function overLimit(env: Env, buckets: Array<[Bucket, string]>): Promise<Bucket | null> {
70 for (const [b, key] of buckets) {
71 const rl = (env as unknown as Record<string, RateLimiter | undefined>)[b];
72 if (!rl) continue;
73 try {
74 if (!(await rl.limit({ key })).success) return b;
75 } catch (e) {
76 console.error("rate limiter failed", b, e);
77 }
78 }
79 return null;
80}
81
82/**
83 * Model requests through the proxy (/-/model/*), per paying person across all their runs (phase 5a): above the
84 * per-run limits and budgets, it caps how fast a leaked run token or a runaway task can spend a person's key. Kept
85 * out of `bucketsFor` because only the run's ProjectDO knows who pays. Must match RL_MODEL in wrangler.jsonc.
86 */
87export const MODEL_RATE_LIMIT = 600;
88
89/** Whether this person is over their model request rate. A missing (local) or failing binding lets it through. */
90export async function modelRateLimited(env: Env, personId: string): Promise<boolean> {
91 if (!env.RL_MODEL) return false;
92 try {
93 return !(await env.RL_MODEL.limit({ key: `model:${personId}` })).success;
94 } catch (e) {
95 console.error("model rate limiter failed", e);
96 return false;
97 }
98}
99
100const WHAT: Record<Bucket, string> = {
101 RL_AUTH: "sign-in attempts, security reports, early access requests and contact messages from your network",
102 RL_ANON: "requests from your network without signing in",
103 RL_ACCOUNT: "requests from your account",
104 RL_CREATE: "new repositories, issues, pull requests and comments from your account",
105};
106
107/** A 429 that GitHub clients understand (`retry-after`, `x-ratelimit-remaining: 0`). */
108export function tooMany(c: Context, b: Bucket): Response {
109 const message = `Too many ${WHAT[b]}: at most ${RATE_LIMITS[b]} a minute. Try again in a minute.`;
110 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) };
111 const html = (c.req.header("accept") ?? "").includes("text/html");
112 return html ? new Response(message, { status: 429, headers: { ...headers, "content-type": "text/plain; charset=utf-8" } }) : Response.json({ message }, { status: 429, headers });
113}