diff --git a/next.config.ts b/next.config.ts index de8c1e4..cb0c047 100644 --- a/next.config.ts +++ b/next.config.ts @@ -6,7 +6,39 @@ const app = process.env.APP_ORIGIN; const auth = process.env.AUTH_ORIGIN; const authHost = auth ? new URL(auth).host : null; +// Production CSP. Next.js streams inline bootstrap scripts, so scripts allow 'unsafe-inline' but only from this +// origin; nothing on the site renders user HTML. The rest is strict: no framing (clickjacking on keeper +// actions), no plugins, no foreign forms, no base-tag tricks. +const CSP = [ + "default-src 'self'", + "script-src 'self' 'unsafe-inline'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data:", + "font-src 'self'", + "connect-src 'self'", + "object-src 'none'", + "base-uri 'self'", + "form-action 'self' https://github.com", + "frame-ancestors 'none'", + 'upgrade-insecure-requests', +].join('; '); + +const SECURITY_HEADERS = [ + { key: 'Content-Security-Policy', value: CSP }, + { key: 'X-Frame-Options', value: 'DENY' }, + { key: 'X-Content-Type-Options', value: 'nosniff' }, + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, + { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), payment=(), usb=()' }, + { key: 'Cross-Origin-Opener-Policy', value: 'same-origin' }, +]; + const nextConfig: NextConfig = { + poweredByHeader: false, + async headers() { + // Dev needs eval for fast refresh, so the policy only ships in production builds. + if (process.env.NODE_ENV !== 'production') return []; + return [{ source: '/:path*', headers: SECURITY_HEADERS }]; + }, async redirects() { if (!app || !authHost || authHost === new URL(app).host) return []; return [ diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 0fe9053..5257d8d 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { authOrigin, callbackUrl, onAuthHost, redirect, safeNext, stateCookie } from '@/lib/auth-flow'; import { randomToken } from '@/lib/crypto'; import { appConfig } from '@/lib/github-app'; @@ -7,6 +8,8 @@ export const dynamic = 'force-dynamic'; /** Starts "Sign in with GitHub" with a random state bound to this browser (accounts R1.1). */ export async function GET(req: Request) { + const slow = limit(req, 'auth'); + if (slow) return slow; const cfg = appConfig(); if (!cfg) return Response.json({ error: 'sign in is not configured on this deployment' }, { status: 503 }); const next = safeNext(new URL(req.url).searchParams.get('next')); diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts index 14dd8eb..d08c4ab 100644 --- a/src/app/api/auth/logout/route.ts +++ b/src/app/api/auth/logout/route.ts @@ -1,6 +1,6 @@ import { sameOrigin } from '@/lib/access'; import { redirect } from '@/lib/auth-flow'; -import { SESSION_COOKIE, clearSessionCookie, deleteSession, readCookie } from '@/lib/session'; +import { SESSION_COOKIE, clearSessionCookie, deleteSession, loadSession, readCookie, revokeGitHubToken } from '@/lib/session'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; @@ -9,6 +9,10 @@ export const dynamic = 'force-dynamic'; export async function POST(req: Request) { if (!sameOrigin(req)) return Response.json({ error: 'cross-origin request refused' }, { status: 403 }); const sid = readCookie(req, SESSION_COOKIE); - if (sid) await deleteSession(sid).catch(() => undefined); + if (sid) { + const s = await loadSession(sid).catch(() => null); + if (s) await revokeGitHubToken(s.token).catch(() => false); + await deleteSession(sid).catch(() => undefined); + } return redirect('/', [clearSessionCookie()], 303); } diff --git a/src/app/api/auto-heal/route.ts b/src/app/api/auto-heal/route.ts index 04a31e5..ce8c472 100644 --- a/src/app/api/auto-heal/route.ts +++ b/src/app/api/auto-heal/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { ANON, resolveCtx } from '@/lib/access'; import { isDemoKey } from '@/lib/demo-fixtures'; import { diagnose } from '@/lib/heal'; @@ -14,6 +15,8 @@ const HEADERS = { 'Cache-Control': 'no-store' }; * A private repo's diagnosis is built for readers and keepers only and never stored (accounts R9.4). */ export async function POST(req: Request) { + const slow = limit(req, 'heal'); + if (slow) return slow; const body = (await req.json().catch(() => null)) as { repo?: unknown } | null; const raw = typeof body?.repo === 'string' ? body.repo : ''; const [owner, repo, ...rest] = raw.split('/'); diff --git a/src/app/api/local-poop/route.ts b/src/app/api/local-poop/route.ts index ba36e32..f8c62cf 100644 --- a/src/app/api/local-poop/route.ts +++ b/src/app/api/local-poop/route.ts @@ -24,6 +24,8 @@ function operatorBearer(bearer: string): boolean { // shortcut: Host is client-supplied, so a remote caller can fake it. Set GITGOTCHI_HOOK_TOKEN when the app is exposed. function isLocal(req: Request): boolean { + // Never on a deployment: Host and X-Forwarded-For are client-supplied there. Use a hook token instead. + if (process.env.NODE_ENV === 'production') return false; const host = (req.headers.get('host') ?? '').replace(/:\d+$/, ''); const hops = (req.headers.get('x-forwarded-for') ?? '').split(',').map((s) => s.trim()).filter(Boolean); return LOOPBACK.test(host) && hops.every((ip) => LOOPBACK.test(ip)); diff --git a/src/app/api/me/pets/route.ts b/src/app/api/me/pets/route.ts index c8011b6..7ef0a0c 100644 --- a/src/app/api/me/pets/route.ts +++ b/src/app/api/me/pets/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { githubRequest } from '@/lib/github'; import { installUrl } from '@/lib/github-app'; import { getEntry, normalizeRepoKey } from '@/lib/pet-store'; @@ -19,6 +20,8 @@ interface RepoJson { /** Installed repos the signed-in user can access, with their pets (accounts R8). */ export async function GET(req: Request) { + const slow = limit(req, 'pet'); + if (slow) return slow; const found = await getSession(req).catch(() => null); // Signed out is a normal state of this page, not an error (no 401 noise in the browser console). if (!found) return Response.json({ signedIn: false }, { headers: HEADERS }); diff --git a/src/app/api/pet/[owner]/[repo]/action/route.ts b/src/app/api/pet/[owner]/[repo]/action/route.ts index 4b0bb88..1841608 100644 --- a/src/app/api/pet/[owner]/[repo]/action/route.ts +++ b/src/app/api/pet/[owner]/[repo]/action/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { ANON, bearerOf, resolveCtx, sameOrigin } from '@/lib/access'; import { isDemoKey } from '@/lib/demo-fixtures'; import { normalizeRepoKey } from '@/lib/pet-store'; @@ -11,6 +12,8 @@ const NO_STORE = { 'Cache-Control': 'no-store' }; const bad = (error: string) => Response.json({ error }, { status: 400, headers: NO_STORE }); export async function POST(req: Request, ctx: { params: Promise<{ owner: string; repo: string }> }) { + const slow = limit(req, 'pet'); + if (slow) return slow; const { owner, repo } = await ctx.params; let key: string; try { diff --git a/src/app/api/pet/[owner]/[repo]/readme/route.ts b/src/app/api/pet/[owner]/[repo]/readme/route.ts index 6722c1f..87b6e37 100644 --- a/src/app/api/pet/[owner]/[repo]/readme/route.ts +++ b/src/app/api/pet/[owner]/[repo]/readme/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { resolveCtx } from '@/lib/access'; import { isDemoKey } from '@/lib/demo-fixtures'; import { githubRequest } from '@/lib/github'; @@ -13,6 +14,8 @@ const HEADERS = { 'Cache-Control': 'private, no-store' }; * (one or two GitHub calls per click). A private repo answers 404 to anyone outside it, like everywhere else. */ export async function GET(req: Request, ctx: { params: Promise<{ owner: string; repo: string }> }) { + const slow = limit(req, 'heal'); + if (slow) return slow; const { owner, repo } = await ctx.params; let key: string; try { diff --git a/src/app/api/pet/[owner]/[repo]/route.ts b/src/app/api/pet/[owner]/[repo]/route.ts index b36ac77..11a6546 100644 --- a/src/app/api/pet/[owner]/[repo]/route.ts +++ b/src/app/api/pet/[owner]/[repo]/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { ANON, resolveCtx } from '@/lib/access'; import { isDemoKey } from '@/lib/demo-fixtures'; import { normalizeRepoKey } from '@/lib/pet-store'; @@ -7,6 +8,8 @@ export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function GET(req: Request, ctx: { params: Promise<{ owner: string; repo: string }> }) { + const slow = limit(req, 'pet'); + if (slow) return slow; const { owner, repo } = await ctx.params; let key: string; try { diff --git a/src/app/api/pet/[owner]/[repo]/settings/route.ts b/src/app/api/pet/[owner]/[repo]/settings/route.ts index 58f3957..4ed1f6f 100644 --- a/src/app/api/pet/[owner]/[repo]/settings/route.ts +++ b/src/app/api/pet/[owner]/[repo]/settings/route.ts @@ -1,3 +1,4 @@ +import { limit } from '@/lib/rate-limit'; import { resolveCtx, sameOrigin } from '@/lib/access'; import { normalizeRepoKey } from '@/lib/pet-store'; import { petErrorResponse } from '@/lib/pet-service'; @@ -11,6 +12,8 @@ const HEADERS = { 'Cache-Control': 'private, no-store', 'X-Robots-Tag': 'noindex /** Keeper-only: badge key, hook tokens, delete pet. Signed-in sessions only, same origin only. */ export async function POST(req: Request, ctx: { params: Promise<{ owner: string; repo: string }> }) { + const slow = limit(req, 'pet'); + if (slow) return slow; const { owner, repo } = await ctx.params; let key: string; try { diff --git a/src/lib/__tests__/security.test.ts b/src/lib/__tests__/security.test.ts new file mode 100644 index 0000000..5a301d7 --- /dev/null +++ b/src/lib/__tests__/security.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { POST as logout } from '@/app/api/auth/logout/route'; +import { POST as localPoop } from '@/app/api/local-poop/route'; +import { GET as petGet } from '@/app/api/pet/[owner]/[repo]/route'; +import { resetMemoryKv } from '../kv'; +import { allow, resetRateLimits } from '../rate-limit'; +import { createSession, loadSession } from '../session'; + +beforeEach(() => { + resetMemoryKv(); + resetRateLimits(); + vi.stubEnv('SESSION_SECRET', 'test-session-secret-0123456789abcdef012345'); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +describe('rate limits', () => { + it('counts per key and window', () => { + for (let i = 0; i < 3; i++) expect(allow('k', 3, 1000, 0)).toBe(true); + expect(allow('k', 3, 1000, 10)).toBe(false); + expect(allow('other', 3, 1000, 10)).toBe(true); + expect(allow('k', 3, 1000, 1001)).toBe(true); + }); + + it('a flood of pet reads from one IP gets 429, another IP is unaffected', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 404 }))); + const get = (ip: string) => + petGet(new Request('http://x/api/pet/acme/rocket', { headers: { 'x-forwarded-for': ip } }), { + params: Promise.resolve({ owner: 'acme', repo: 'rocket' }), + }); + let last = 0; + for (let i = 0; i < 121; i++) last = (await get('203.0.113.1')).status; + expect(last).toBe(429); + expect((await get('203.0.113.2')).status).toBe(404); + }); +}); + +describe('sign out', () => { + it('revokes the GitHub token at GitHub and deletes the session', async () => { + vi.stubEnv('APP_ORIGIN', 'https://g.example'); + vi.stubEnv('GITHUB_APP_ID', '1'); + vi.stubEnv('GITHUB_APP_PRIVATE_KEY', 'unused'); + vi.stubEnv('GITHUB_APP_CLIENT_ID', 'cid'); + vi.stubEnv('GITHUB_APP_CLIENT_SECRET', 'csecret'); + const fetchSpy = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', fetchSpy); + const { sid } = await createSession({ id: 1, login: 'kim', avatar_url: '' }, { token: 'ghu_TOKEN', tokenExpiresAt: null, refreshToken: null, refreshExpiresAt: null }); + + const res = await logout(new Request('https://g.example/api/auth/logout', { method: 'POST', headers: { origin: 'https://g.example', cookie: `gg_session=${sid}` } })); + expect(res.status).toBe(303); + const calls = fetchSpy.mock.calls as unknown as [string, RequestInit][]; + const [url, init] = calls[0]; + expect(url).toBe('https://api.github.com/applications/cid/token'); + expect(init.method).toBe('DELETE'); + expect(String(init.body)).toContain('ghu_TOKEN'); + expect(await loadSession(sid)).toBeNull(); + }); +}); + +describe('hook endpoint on a deployment', () => { + it('never trusts a localhost Host or X-Forwarded-For in production', async () => { + vi.stubEnv('NODE_ENV', 'production'); + const res = await localPoop( + new Request('http://localhost:3000/api/local-poop', { + method: 'POST', + headers: { host: 'localhost:3000', 'x-forwarded-for': '127.0.0.1' }, + body: JSON.stringify({ filePath: 'src/a.ts', hasTodo: true, repo: 'demo/healthy' }), + }) + ); + expect(res.status).toBe(403); + }); +}); diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts new file mode 100644 index 0000000..0acd172 --- /dev/null +++ b/src/lib/rate-limit.ts @@ -0,0 +1,50 @@ +// Best-effort, per-instance request limiter. It keeps one visitor from burning the free Upstash and GitHub +// quotas for everyone; Vercel runs several instances, so the real ceiling is a small multiple of these numbers. + +const g = globalThis as unknown as { __ggRate?: Map }; +const buckets = (g.__ggRate ??= new Map()); +const MAX_BUCKETS = 5000; + +/** The caller's IP as Vercel reports it (first X-Forwarded-For hop), or "unknown". */ +export function clientIp(req: Request): string { + return (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || req.headers.get('x-real-ip') || 'unknown'; +} + +/** True when `key` may make another request in this window. */ +export function allow(key: string, limit: number, windowMs: number, now = Date.now()): boolean { + const b = buckets.get(key); + if (!b || now >= b.reset) { + if (buckets.size >= MAX_BUCKETS) buckets.delete(buckets.keys().next().value as string); + buckets.set(key, { n: 1, reset: now + windowMs }); + return true; + } + b.n++; + return b.n <= limit; +} + +/** Test hook. */ +export function resetRateLimits(): void { + buckets.clear(); +} + +export const LIMITS = { + /** Pet reads, actions and settings: a page polls every 15 s or slower, so this only stops floods. */ + pet: { limit: 120, windowMs: 60_000 }, + /** Summon Kiro reads up to three GitHub endpoints and a log per call. */ + heal: { limit: 10, windowMs: 60_000 }, + /** Starting sign in. */ + auth: { limit: 20, windowMs: 60_000 }, +} as const; + +export function tooMany(retryAfterS: number): Response { + return Response.json( + { error: 'too many requests, slow down' }, + { status: 429, headers: { 'Retry-After': String(retryAfterS), 'Cache-Control': 'no-store' } } + ); +} + +/** Null when allowed, else a 429 response. */ +export function limit(req: Request, kind: keyof typeof LIMITS): Response | null { + const { limit: n, windowMs } = LIMITS[kind]; + return allow(`${kind}:${clientIp(req)}`, n, windowMs) ? null : tooMany(Math.ceil(windowMs / 1000)); +} diff --git a/src/lib/session.ts b/src/lib/session.ts index 92a0759..708f466 100644 --- a/src/lib/session.ts +++ b/src/lib/session.ts @@ -105,6 +105,24 @@ export async function createSession(user: { id: number; login: string; avatar_ur return { sid, session }; } +/** + * Revokes the user's GitHub token at GitHub (accounts R1.5), so a copy of it is useless after sign out. + * Best effort: sign out still completes when GitHub does not answer. + */ +export async function revokeGitHubToken(token: string): Promise { + const cfg = appConfig(); + if (!cfg || !token) return false; + const basic = Buffer.from(`${cfg.clientId}:${cfg.clientSecret}`).toString('base64'); + const res = await fetch(`https://api.github.com/applications/${cfg.clientId}/token`, { + method: 'DELETE', + headers: { Authorization: `Basic ${basic}`, Accept: 'application/vnd.github+json', 'User-Agent': 'gitgotchi', 'Content-Type': 'application/json' }, + body: JSON.stringify({ access_token: token }), + signal: AbortSignal.timeout(5000), + cache: 'no-store', + }).catch(() => null); + return res?.status === 204; +} + export async function deleteSession(sid: string): Promise { memo.delete(sid); await kvDel(storeKey(sid));