diff --git a/.kiro/specs/accounts/design.md b/.kiro/specs/accounts/design.md index 503e1c2..9910cd2 100644 --- a/.kiro/specs/accounts/design.md +++ b/.kiro/specs/accounts/design.md @@ -86,6 +86,10 @@ Limits that `/privacy` states plainly: - The repo name is the store key and appears in request URLs, so it is visible in Vercel request logs and the Upstash key list. To hide it as well, key private entries by `repoId` instead; this is optional task 21. - A private badge URL works for anyone who has it. Keepers rotate the key if a README is copied somewhere public. +## Sign-in host + +Chrome's Safe Browsing flagged the OAuth callback on the young custom domain as phishing-like (a page on `lumelo.my.id` receiving a GitHub `code`). Sign in therefore runs on `AUTH_ORIGIN` (`gitgochi.vercel.app`): `/api/auth/login` on the app host redirects there, GitHub calls back there, the callback creates the session and redirects to `APP_ORIGIN/api/auth/handoff?t=`. The ticket is 32 random bytes, stored only as a hash for 60 seconds, and works once; the handoff sets the session cookie on the app host and answers with `Referrer-Policy: no-referrer`. No session cookie is set on the sign-in host. `next.config.ts` redirects every other path on the sign-in host to the app host. + ## Environment variables (new) | Variable | Purpose | diff --git a/README.md b/README.md index 6c9b689..eab2ca7 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,8 @@ Copy [`.env.example`](.env.example) to `.env.local`. All variables are optional | `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID`, `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_APP_WEBHOOK_SECRET` | `src/lib/github-app.ts`, `src/lib/session.ts`, `/api/github-app/webhook` | The GitGotchi App: sign in, keepers, private repos, live webhooks. Without them, pets are public and read-only | | `SESSION_SECRET` | `src/lib/session.ts` | Encrypts sessions and user tokens | | `DATA_ENCRYPTION_KEY` | `src/lib/pet-store.ts` | Encrypts private pets before they reach the store | -| `APP_ORIGIN` | `src/lib/auth-flow.ts`, `src/lib/access.ts` | Public origin, for the sign-in callback and the same-origin check on writes | +| `APP_ORIGIN` | `src/lib/auth-flow.ts`, `src/lib/access.ts` | Public origin, for the same-origin check on writes and the end of sign in | +| `AUTH_ORIGIN` | `src/lib/auth-flow.ts`, `next.config.ts` | Optional second host where GitHub sign in runs (production: `gitgochi.vercel.app`). The OAuth callback lands there and hands the session to `APP_ORIGIN` with a one-time ticket, so the custom domain never serves an OAuth callback. Every other path on that host redirects to `APP_ORIGIN` | | `SETUP_TOKEN` | `/setup/github-app` | Unlocks the one-time app registration page. Remove it afterwards | | `GITGOTCHI_URL` | `scripts/poop-detector.mjs`, `mcp-server/index.mjs` | App URL for the hook and the MCP server (default `http://localhost:3000`) | | `GITGOTCHI_PUBLIC_URL` | `mcp-server/index.mjs` (`add_badge`) | Public deployment written into README badges (default: `GITGOTCHI_URL`; localhost is refused) | @@ -241,6 +242,7 @@ GitHub Actions (`.github/workflows/ci.yml`) runs lint, the type check and the un ## Known limits - **Without a KV store, pets live in memory.** When neither the `UPSTASH_REDIS_REST_*` nor the `KV_REST_API_*` pair is set, `src/lib/pet-store.ts` keeps pets in a `Map` in the server process, and a restart, redeploy or serverless cold start loses poop, the resurrection count and webhook effects. Set a KV pair in production (see [docs/DEPLOY.md](docs/DEPLOY.md)). +- **Reads are cached for 30 seconds per server instance.** To stay inside the Upstash free plan, a pet read is reused for 30 seconds. A change made on another instance (for example a webhook) can take up to 30 seconds to show. - **Resync replaces webhook effects.** Once the 5-minute cache has expired, the next request re-seeds a real repo's stats from GitHub. Effects the snapshot does not count, such as the bonus from a merged pull request, are replaced at that point. Poop, the resurrection count, the rising state and the NECROMANCER streak are kept. Webhooks that arrive before the first snapshot are replayed once onto it. - **Per-file poop has a window.** Cleaning a file removes only that file's poop, but only while its poop event is among the 50 logged events. Poop is capped at 5; the CLEAN button always clears everything. - **The operator can read what is stored.** Private pets are encrypted against a leaked copy of the store, but whoever runs the deployment holds the keys and sees repo names in request logs. `/privacy` says so. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 815ece0..5842b8a 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -18,7 +18,8 @@ Before pushing, run `npm run build` locally once to catch type or build errors. |---|---|---| | `GITHUB_TOKEN` | **Yes, required** | Fine-grained token, public repositories read-only, no scopes. Unauthenticated GitHub allows 60 requests per hour per IP; one adoption costs about 4. Vercel shares IPs, so without a token real repos fail with `github rate limit reached` (503). With it the limit is 5000 per hour. Demo repos work without it | | `SESSION_SECRET`, `DATA_ENCRYPTION_KEY` | Yes, sensitive | 32 random bytes each. Sessions and private pets are encrypted with them. Losing `DATA_ENCRYPTION_KEY` makes stored private pets unreadable (they re-seed from GitHub) | -| `APP_ORIGIN` | Yes | `https://gitgochi.lumelo.my.id`. Sign-in callback and same-origin check | +| `APP_ORIGIN` | Yes | `https://gitgochi.lumelo.my.id`. Same-origin check, end of sign in | +| `AUTH_ORIGIN` | Optional | `https://gitgochi.vercel.app`. Sign in runs there; needs `https://gitgochi.vercel.app/api/auth/callback` as the GitHub App's callback URL and no Vercel domain redirect on that host (the app redirects every other path itself, `next.config.ts`). Set it before the build, because `next.config.ts` reads it | | `GITHUB_APP_*` (6 variables) | Yes, after [registering the app](#github-app) | Sign in, keepers, private repos, live webhooks | | `SETUP_TOKEN` | Only while registering the app | Unlocks `/setup/github-app`; delete it afterwards | | `GITHUB_WEBHOOK_SECRET` | Only for manual webhooks | Random string, same value in the GitHub webhook. When unset, anyone can post events | diff --git a/next.config.ts b/next.config.ts new file mode 100644 index 0000000..de8c1e4 --- /dev/null +++ b/next.config.ts @@ -0,0 +1,23 @@ +import type { NextConfig } from 'next'; + +// Sign in runs on AUTH_ORIGIN (gitgochi.vercel.app) so the GitHub OAuth callback never lands on the custom +// domain; everything else on that host goes back to APP_ORIGIN (accounts design, "Sign-in host"). +const app = process.env.APP_ORIGIN; +const auth = process.env.AUTH_ORIGIN; +const authHost = auth ? new URL(auth).host : null; + +const nextConfig: NextConfig = { + async redirects() { + if (!app || !authHost || authHost === new URL(app).host) return []; + return [ + { + source: '/:path((?!api/auth/(?:login|callback)$).*)', + has: [{ type: 'host', value: authHost }], + destination: `${app}/:path`, + permanent: true, + }, + ]; + }, +}; + +export default nextConfig; diff --git a/src/app/api/auth/callback/route.ts b/src/app/api/auth/callback/route.ts index e3b023d..a4b436b 100644 --- a/src/app/api/auth/callback/route.ts +++ b/src/app/api/auth/callback/route.ts @@ -1,7 +1,7 @@ -import { STATE_COOKIE, callbackUrl, redirect, safeNext, stateCookie } from '@/lib/auth-flow'; +import { STATE_COOKIE, appOrigin, callbackUrl, redirect, safeNext, splitAuth, stateCookie } from '@/lib/auth-flow'; import { safeEqual } from '@/lib/crypto'; import { githubRequest } from '@/lib/github'; -import { createSession, exchangeCode, readCookie, sessionCookie } from '@/lib/session'; +import { createSession, createTicket, exchangeCode, readCookie, sessionCookie } from '@/lib/session'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; @@ -34,5 +34,11 @@ export async function GET(req: Request) { if (!user?.id || !user.login) return failPage('GitHub did not return the account'); const { sid } = await createSession({ id: user.id, login: user.login, avatar_url: user.avatar_url ?? '' }, tokens); + if (splitAuth(req)) { + // Sign-in host: hand the session to the app host with a one-time ticket; no cookie is left here. + const ticket = await createTicket(sid); + const to = `${appOrigin(req)}/api/auth/handoff?t=${ticket}&next=${encodeURIComponent(next)}`; + return redirect(to, [stateCookie('', 0)]); + } return redirect(next, [sessionCookie(sid), stateCookie('', 0)]); } diff --git a/src/app/api/auth/handoff/route.ts b/src/app/api/auth/handoff/route.ts new file mode 100644 index 0000000..7424906 --- /dev/null +++ b/src/app/api/auth/handoff/route.ts @@ -0,0 +1,17 @@ +import { redirect, safeNext } from '@/lib/auth-flow'; +import { redeemTicket, sessionCookie } from '@/lib/session'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +/** App host: turns the one-time ticket from the sign-in host into this host's session cookie. */ +export async function GET(req: Request) { + const q = new URL(req.url).searchParams; + const next = safeNext(q.get('next')); + const sid = await redeemTicket(q.get('t') ?? '').catch(() => null); + if (!sid) return redirect('/?signin=expired'); + const res = redirect(next, [sessionCookie(sid)]); + // The ticket is spent, but keep it out of Referer headers anyway. + res.headers.set('Referrer-Policy', 'no-referrer'); + return res; +} diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts index 3c2c139..0fe9053 100644 --- a/src/app/api/auth/login/route.ts +++ b/src/app/api/auth/login/route.ts @@ -1,4 +1,4 @@ -import { callbackUrl, redirect, safeNext, stateCookie } from '@/lib/auth-flow'; +import { authOrigin, callbackUrl, onAuthHost, redirect, safeNext, stateCookie } from '@/lib/auth-flow'; import { randomToken } from '@/lib/crypto'; import { appConfig } from '@/lib/github-app'; @@ -10,6 +10,8 @@ export async function GET(req: Request) { 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')); + // Start on the sign-in host, so the state cookie lives where the callback will read it. + if (!onAuthHost(req)) return redirect(`${authOrigin(req)}/api/auth/login?next=${encodeURIComponent(next)}`); const state = randomToken(24); const url = new URL('https://github.com/login/oauth/authorize'); url.searchParams.set('client_id', cfg.clientId); diff --git a/src/lib/__tests__/auth-handoff.test.ts b/src/lib/__tests__/auth-handoff.test.ts new file mode 100644 index 0000000..9bdde51 --- /dev/null +++ b/src/lib/__tests__/auth-handoff.test.ts @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { GET as login } from '@/app/api/auth/login/route'; +import { GET as callback } from '@/app/api/auth/callback/route'; +import { GET as handoff } from '@/app/api/auth/handoff/route'; +import { resetMemoryKv } from '../kv'; +import { loadSession } from '../session'; + +const APP = 'https://gitgochi.lumelo.my.id'; +const AUTH = 'https://gitgochi.vercel.app'; + +beforeEach(() => { + resetMemoryKv(); + vi.stubEnv('APP_ORIGIN', APP); + vi.stubEnv('AUTH_ORIGIN', AUTH); + vi.stubEnv('SESSION_SECRET', 'test-session-secret-0123456789abcdef012345'); + 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'); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +const setCookies = (r: Response) => r.headers.getSetCookie(); + +describe('sign in on the Vercel host, session on the custom domain', () => { + it('SIGN IN on the app host moves to the sign-in host first', async () => { + const r = await login(new Request(`${APP}/api/auth/login?next=/pet/a/b`)); + expect(r.status).toBe(302); + expect(r.headers.get('location')).toBe(`${AUTH}/api/auth/login?next=%2Fpet%2Fa%2Fb`); + expect(setCookies(r)).toEqual([]); + }); + + it('the sign-in host sends GitHub a callback on its own domain', async () => { + const r = await login(new Request(`${AUTH}/api/auth/login?next=/me`)); + const to = new URL(r.headers.get('location')!); + expect(to.origin).toBe('https://github.com'); + expect(to.searchParams.get('redirect_uri')).toBe(`${AUTH}/api/auth/callback`); + }); + + it('the callback hands over a one-time ticket; the custom domain sets the cookie; the ticket works once', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (u: string | URL | Request) => + String(u).includes('login/oauth/access_token') + ? Response.json({ access_token: 'ghu_X', expires_in: 28800 }) + : Response.json({ id: 7, login: 'kim', avatar_url: '' }) + ) + ); + const start = await login(new Request(`${AUTH}/api/auth/login?next=/me`)); + const state = new URL(start.headers.get('location')!).searchParams.get('state')!; + const cookie = setCookies(start)[0].split(';')[0]; + + const cb = await callback(new Request(`${AUTH}/api/auth/callback?code=c&state=${state}`, { headers: { cookie } })); + const to = new URL(cb.headers.get('location')!); + expect(to.origin + to.pathname).toBe(`${APP}/api/auth/handoff`); + expect(to.searchParams.get('next')).toBe('/me'); + // No session cookie is left on the sign-in host. + expect(setCookies(cb).some((c) => c.startsWith('gg_session='))).toBe(false); + + const h = await handoff(new Request(to.toString())); + expect(h.headers.get('location')).toBe('/me'); + expect(h.headers.get('referrer-policy')).toBe('no-referrer'); + const sid = setCookies(h).find((c) => c.startsWith('gg_session='))!.split(';')[0].split('=')[1]; + expect((await loadSession(sid))?.login).toBe('kim'); + + const again = await handoff(new Request(to.toString())); + expect(again.headers.get('location')).toBe('/?signin=expired'); + expect(setCookies(again)).toEqual([]); + }); + + it('a made-up ticket is refused', async () => { + const r = await handoff(new Request(`${APP}/api/auth/handoff?t=${'x'.repeat(43)}&next=/me`)); + expect(r.headers.get('location')).toBe('/?signin=expired'); + }); +}); diff --git a/src/lib/__tests__/pet-store.test.ts b/src/lib/__tests__/pet-store.test.ts index f5e5159..bec4ce4 100644 --- a/src/lib/__tests__/pet-store.test.ts +++ b/src/lib/__tests__/pet-store.test.ts @@ -139,3 +139,30 @@ describe('KV store', () => { expect(String(err)).not.toMatch(/SECRET|upstash/); }); }); + +describe('read cache (free-plan budget)', () => { + it('a second read within 30 s skips the store; a write updates it; after 30 s it reads again', async () => { + useKv(); + const { fn } = fakeKv(); + const { resetPetCache, READ_CACHE_MS } = await import('../pet-store'); + resetPetCache(); + vi.useFakeTimers(); + try { + const key = 'test/cache'; + await setEntry(key, { pet: createPet(key, 0), events: [], snapshotAt: 1, source: 'github' }); + const before = fn.mock.calls.length; + expect((await getEntry(key))?.snapshotAt).toBe(1); + expect((await getEntry(key))?.snapshotAt).toBe(1); + expect(fn.mock.calls.length).toBe(before); + + await setEntry(key, { pet: createPet(key, 0), events: [], snapshotAt: 2, source: 'github' }); + expect((await getEntry(key))?.snapshotAt).toBe(2); + + vi.advanceTimersByTime(READ_CACHE_MS + 1); + await getEntry(key); + expect(fn.mock.calls.length).toBe(before + 2); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/src/lib/auth-flow.ts b/src/lib/auth-flow.ts index 63235e9..5afd71c 100644 --- a/src/lib/auth-flow.ts +++ b/src/lib/auth-flow.ts @@ -3,7 +3,14 @@ export const STATE_COOKIE = 'gg_oauth'; export const appOrigin = (req: Request) => process.env.APP_ORIGIN || new URL(req.url).origin; -export const callbackUrl = (req: Request) => `${appOrigin(req)}/api/auth/callback`; +/** + * Where GitHub sign in runs. When AUTH_ORIGIN is set (gitgochi.vercel.app), the OAuth callback lands there and + * hands the session to APP_ORIGIN with a one-time ticket, so the custom domain never serves an OAuth callback. + */ +export const authOrigin = (req: Request) => process.env.AUTH_ORIGIN || appOrigin(req); +export const callbackUrl = (req: Request) => `${authOrigin(req)}/api/auth/callback`; +export const splitAuth = (req: Request) => authOrigin(req) !== appOrigin(req); +export const onAuthHost = (req: Request) => new URL(req.url).host === new URL(authOrigin(req)).host; /** Only same-site relative paths, so `next` cannot send the user to another site after sign in. */ export function safeNext(v: string | null | undefined): string { diff --git a/src/lib/pet-store.ts b/src/lib/pet-store.ts index cdeaf1c..091049e 100644 --- a/src/lib/pet-store.ts +++ b/src/lib/pet-store.ts @@ -1,5 +1,5 @@ import { deriveKey, open, seal } from './crypto'; -import { StoreError, kvDel, kvGet, kvSet } from './kv'; +import { StoreError, kvConfig, kvDel, kvGet, kvSet } from './kv'; import type { PetEvent, PetState } from './types'; export { StoreError, kvConfig } from './kv'; @@ -47,6 +47,27 @@ export function normalizeRepoKey(owner: string, repo: string): string { export const isPrivate = (e: PetEntry | undefined) => e?.visibility === 'private'; +/** + * Reads are kept in function memory for 30 seconds, so polling pages and badges do not read Upstash every time + * (free plan budget). Writes from this instance update the copy at once; a write on another instance shows up + * here within 30 seconds. Only used with a real store: the local in-memory store needs no cache. + */ +export const READ_CACHE_MS = 30_000; +const g = globalThis as unknown as { __ggPetCache?: Map }; +const cache = (g.__ggPetCache ??= new Map()); +const MAX_CACHED = 500; + +/** Test hook. */ +export function resetPetCache(): void { + cache.clear(); +} + +function remember(key: string, entry: PetEntry | undefined): void { + if (!kvConfig()) return; + if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value as string); + cache.set(key, { entry, at: Date.now() }); +} + /** Key for private entries (accounts R9.3). Missing key: private pets cannot be stored. */ function dataKey(): Buffer { const secret = process.env.DATA_ENCRYPTION_KEY; @@ -77,7 +98,11 @@ function parseEntry(raw: string | null): PetEntry | undefined { } export async function getEntry(key: string): Promise { - return parseEntry(await kvGet(KEY_PREFIX + key)); + const hit = kvConfig() ? cache.get(key) : undefined; + if (hit && Date.now() - hit.at < READ_CACHE_MS) return hit.entry && structuredClone(hit.entry); + const entry = parseEntry(await kvGet(KEY_PREFIX + key)); + remember(key, entry); + return entry && structuredClone(entry); } export async function setEntry(key: string, entry: PetEntry): Promise { @@ -85,10 +110,12 @@ export async function setEntry(key: string, entry: PetEntry): Promise const json = JSON.stringify(stored); // Private entries are sealed before they leave the process, so a copy of the store alone reveals nothing. await kvSet(KEY_PREFIX + key, stored.visibility === 'private' ? JSON.stringify({ enc: seal(json, dataKey()) }) : json); + remember(key, structuredClone(stored)); return stored; } export async function deleteEntry(key: string): Promise { + cache.delete(key); await kvDel(KEY_PREFIX + key); } diff --git a/src/lib/session.ts b/src/lib/session.ts index 9a3f1b0..92a0759 100644 --- a/src/lib/session.ts +++ b/src/lib/session.ts @@ -165,3 +165,25 @@ export async function freshToken(sid: string, s: Session, now = Date.now()): Pro await saveSession(sid, s); return t.token; } + +// ---------- one-time ticket from the sign-in host to the app host ---------- + +const TICKET_PREFIX = 'gitgotchi:ticket:'; +const TICKET_TTL_S = 60; + +/** A single-use ticket for `sid`, valid 60 seconds. Only its hash is stored. */ +export async function createTicket(sid: string): Promise { + const ticket = randomToken(32); + await kvSet(TICKET_PREFIX + sha256(ticket), sid, TICKET_TTL_S); + return ticket; +} + +/** The session id behind a ticket, or null. A ticket works once. */ +export async function redeemTicket(ticket: string): Promise { + if (!/^[A-Za-z0-9_-]{40,64}$/.test(ticket)) return null; + const key = TICKET_PREFIX + sha256(ticket); + const sid = await kvGet(key); + if (!sid) return null; + await kvDel(key); + return sid; +}