diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs index 83a7276..e63d15e 100644 --- a/api/auth/callback.mjs +++ b/api/auth/callback.mjs @@ -1,10 +1,11 @@ +import crypto from 'node:crypto' import { waitUntil } from '@vercel/functions' import { getSession, getUserOctokit, getAppOctokit, configureSessionPersistence } from '../../lib/auth.mjs' import { github, appUrl, sessionLeaseMs } from '../../lib/config.mjs' import { supabase } from '../../lib/db.mjs' import { kickSync, runSync, setUserSync, SYNC_DETAIL_INIT } from '../../lib/sync.mjs' import { createAuthSession, gcAuthSessions, isSessionLive } from '../../lib/sessions.mjs' -import { desktopHandoff, isDesktopFlowId, isDesktopChallenge } from '../../lib/desktop-auth.mjs' +import { desktopHandoff, recoverCompletedDesktopHandoff, isDesktopFlowId, isDesktopChallenge } from '../../lib/desktop-auth.mjs' import { requestQuery } from '../../lib/request-query.mjs' import { securityEvent } from '../../lib/security-events.mjs' @@ -61,16 +62,28 @@ export default async function handler(req, res) { const attempts = Array.isArray(session.oauthAttempts) ? session.oauthAttempts : [] const attempt = attempts.find((entry) => entry && entry.state === state) let stateOk = false - if (code && state && (attempt || state === session.oauthState)) { + let oauthAgeSeconds = null + // Repeated query parameters arrive as arrays. Never coerce a list of + // GitHub codes into a comma-joined string during the token exchange. + // Do not log either the code or its state. + const singleCode = typeof code === 'string' && code.length > 0 && code.length <= 512 + const singleState = typeof state === 'string' && state.length > 0 + if (singleCode && singleState && (attempt || state === session.oauthState)) { try { - const parsed = JSON.parse(Buffer.from(String(state), 'base64url').toString('utf8')) + const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) stateOk = Number.isFinite(parsed.at) && Date.now() - parsed.at >= 0 && Date.now() - parsed.at < 15 * 60 * 1000 + if (stateOk) oauthAgeSeconds = Math.floor((Date.now() - parsed.at) / 1000) } catch { stateOk = false } } + if (!singleCode || !singleState) { + console.warn('github oauth callback query cardinality invalid: code_count=%d state_count=%d', + Array.isArray(code) ? code.length : code === undefined ? 0 : 1, + Array.isArray(state) ? state.length : state === undefined ? 0 : 1) + } if (!stateOk) { securityEvent('auth_callback_failed', { req, reasonCode: 'state_mismatch' }) res.status(400).json({ error: 'Invalid OAuth state' }) @@ -102,6 +115,14 @@ export default async function handler(req, res) { } const redirectUri = `${appUrl}/api/auth/callback` + // GitHub state includes 128 bits of CSPRNG entropy plus a timestamp. + // A bounded SHA-256 fingerprint is therefore safe to correlate within + // short-lived server logs without retaining state, code, cookie or tokens. + // Unlike securityEvent.correlate(), it works without an optional hash key. + // Do not use this on low-entropy user identifiers or access credentials. + const stateFingerprint = typeof state === 'string' && state.length <= 1024 + ? crypto.createHash('sha256').update(state).digest('hex').slice(0, 16) + : 'unavailable' // GitHub's documented web-application flow sends URL-encoded form fields. // Keep redirect_uri identical to the authorization request, and never put // the short-lived OAuth code or client secret in a URL or diagnostic log. @@ -120,22 +141,41 @@ export default async function handler(req, res) { }) const tokenData = await tokenRes.json().catch(() => null) if (!tokenData?.access_token) { + // A duplicated desktop callback can arrive with the same pre-exchange + // cookie while the first request succeeds. GitHub codes are single-use. + // Recover only if the first request independently issued the exact + // HMAC-derived, flow+challenge-bound desktop handoff. Do not reuse the + // rejected GitHub token, skip OAuth state checks or forge a new session. + if (tokenData?.error === 'bad_verification_code' + && await recoverCompletedDesktopHandoff(res, session, code)) { + console.info('github duplicate desktop callback recovered: state_fp=%s', + stateFingerprint) + return + } // Only one Set-Cookie header per callback: the successful path saves // after creating its session. A failed exchange still consumes state // in the browser cookie, preventing a refresh from retrying the code. await session.save() console.error( - 'github token exchange failed: http=%d error=%s desc=%s flow=%s', + 'github token exchange failed: http=%d error=%s desc=%s flow=%s oauth_age_sec=%d state_fp=%s', tokenRes.status, tokenData?.error, tokenData?.error_description, - session.desktopFlow ? 'desktop' : 'web' + session.desktopFlow ? 'desktop' : 'web', + oauthAgeSeconds, + stateFingerprint ) securityEvent('auth_callback_failed', { req, reasonCode: 'token_exchange' }) res.status(400).json({ error: 'GitHub token exchange failed' }) return } + if (session.desktopFlow) { + console.info( + 'github oauth token exchange accepted: flow=desktop oauth_age_sec=%d state_fp=%s', + oauthAgeSeconds, stateFingerprint + ) + } const userOctokit = getUserOctokit(tokenData.access_token) const { data: user } = await userOctokit.rest.users.getAuthenticated() @@ -226,7 +266,7 @@ export default async function handler(req, res) { return } - if (await desktopHandoff(res, session, '/')) return + if (await desktopHandoff(res, session, '/', code)) return res.writeHead(302, { Location: '/' }) res.end() } diff --git a/lib/desktop-auth.mjs b/lib/desktop-auth.mjs index b12b583..8e10027 100644 --- a/lib/desktop-auth.mjs +++ b/lib/desktop-auth.mjs @@ -57,6 +57,28 @@ function newSecret(prefix, bytes) { return `${prefix}_${crypto.randomBytes(bytes).toString('base64url')}` } +// For the ordinary GitHub OAuth callback, derive the short-lived desktop +// handoff code deterministically. Two requests carrying the SAME single-use +// GitHub authorization code must be able to redirect to the SAME handoff. +// HMAC keeps the browser-visible GitHub code and the DB-stored SHA-256 hash +// insufficient to reconstruct the desktop handoff credential. GitHub App +// installation setup hops (no OAuth authorization code) remain randomized. +export function oauthDesktopHandoffCode(oauthCode, flow, challenge) { + const key = process.env.SESSION_SECRET + if (typeof key !== 'string' || key.length < 32 + || typeof oauthCode !== 'string' || !oauthCode || oauthCode.length > 512 + || !isDesktopFlowId(flow) || !isDesktopChallenge(challenge)) return null + const mac = crypto.createHmac('sha256', key) + .update('dev-ledger/desktop-handoff/oauth-v1\0') + .update(oauthCode) + .update('\0') + .update(flow.toLowerCase()) + .update('\0') + .update(challenge.toLowerCase()) + .digest('base64url') + return `dlc_${mac}` +} + // The deep link delivered to the desktop app. Only the single-use code // travels — never a session id, never a token. export function desktopDeepLink(flow, code) { @@ -72,13 +94,22 @@ export function desktopDeepLink(flow, code) { // Returns true when the handoff response was sent. Anything missing — // no flow, no session id, no database — falls back to the normal web // redirect so the browser flow is never broken by desktop plumbing. -export async function desktopHandoff(res, session, webLocation) { +export async function desktopHandoff(res, session, webLocation, oauthCode = null) { const flow = session?.desktopFlow if (!flow || !session?.userId || !session?.sid || !supabase) return false const challenge = session.desktopChallenge delete session.desktopFlow delete session.desktopChallenge - const code = newSecret('dlc', 24) + const code = oauthCode + ? oauthDesktopHandoffCode(oauthCode, flow, challenge) + : newSecret('dlc', 24) + // Never emit an unprotected handoff when the HMAC configuration is absent. + if (!code) { + await session.save() + res.writeHead(302, { Location: webLocation }) + res.end() + return true + } const { error } = await supabase.from(CODES_TABLE).insert({ code_hash: sha256(code), flow, @@ -102,6 +133,50 @@ export async function desktopHandoff(res, session, webLocation) { return true } +// A second browser request can reach the OAuth callback with the ORIGINAL +// sealed cookie while the first request is already using the GitHub code. +// GitHub then says bad_verification_code. Only recover when the first request +// has ACTUALLY issued this precise code, bound to the same flow+challenge. +// Never allow a token rejection on its own to create an authenticated handoff. +// The PKCE verifier remains necessary for the app to redeem the recovered URL. +export async function recoverCompletedDesktopHandoff(res, session, oauthCode, { + attempts = 12, + delayMs = 500, +} = {}) { + const flow = session?.desktopFlow + const challenge = session?.desktopChallenge + const code = oauthDesktopHandoffCode(oauthCode, flow, challenge) + if (!supabase || !code) return false + const codeHash = sha256(code) + const boundedAttempts = Math.max(1, Math.min(16, Math.floor(attempts))) + for (let n = 0; n < boundedAttempts; n++) { + const { data, error } = await supabase.from(CODES_TABLE) + .select('code_hash') + .eq('code_hash', codeHash) + .eq('flow', flow) + .eq('challenge', challenge) + .is('consumed_at', null) + .gt('expires_at', new Date().toISOString()) + .maybeSingle() + if (!error && data?.code_hash === codeHash) { + res.writeHead(302, { + Location: desktopDeepLink(flow, code), + 'Cache-Control': 'private, no-store, max-age=0', + }) + res.end() + return true + } + // Allow the successful callback time to finish provisioning the user, + // creating its server-side session, and inserting the handoff row. + if (n + 1 < boundedAttempts && !error) { + await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(1000, delayMs)))) + } else if (error) { + break + } + } + return false +} + // Atomically consume a handoff code: a single UPDATE ... RETURNING guarded // by consumed_at IS NULL — Postgres serializes the row lock and // re-evaluates the predicate, so concurrent exchanges can never both diff --git a/test/auth-login.test.mjs b/test/auth-login.test.mjs index 6a49efc..f3ebd46 100644 --- a/test/auth-login.test.mjs +++ b/test/auth-login.test.mjs @@ -121,6 +121,131 @@ test('GitHub code exchange uses documented form encoding with matching callback assert.equal(resCb.getHeader('location'), '/') }) +test('a GitHub bad_verification_code failure records only safe OAuth age and consumes state', async (t) => { + const desktop = mockRes() + const flow = '9f5a9d2c-2d46-42ff-8f91-e4c93814e055' + await loginHandler(mockReq({ + query: { desktop_flow: flow, desktop_challenge: 'a'.repeat(64) }, + }), desktop) + const state = authorizeUrl(desktop).searchParams.get('state') + const originalFetch = globalThis.fetch + globalThis.fetch = async (url) => { + assert.equal(String(url), 'https://github.com/login/oauth/access_token') + return new Response(JSON.stringify({ + error: 'bad_verification_code', + error_description: 'The code passed is incorrect or expired.', + }), { headers: { 'Content-Type': 'application/json' } }) + } + t.after(() => { globalThis.fetch = originalFetch }) + const originalError = console.error + const errors = [] + console.error = (...parts) => errors.push(parts) + t.after(() => { console.error = originalError }) + + const callback = mockRes() + await callbackHandler(mockReq({ + headers: { cookie: cookieHeader(desktop) }, + query: { code: 'one-time-placeholder', state }, + }), callback) + + assert.equal(callback.statusCode, 400) + assert.equal(callback.body?.error, 'GitHub token exchange failed') + const detail = errors.find((parts) => String(parts[0]).includes('github token exchange failed:')) + assert.ok(detail, 'diagnostic must emit a bounded, credential-free error') + assert.equal(detail[4], 'desktop') + assert.equal(typeof detail[5], 'number') + assert.ok(detail[5] >= 0 && detail[5] < 900) + assert.match(detail[6], /^(?:[a-f0-9]{16}|unavailable)$/) + assert.ok(!JSON.stringify(errors).includes('one-time-placeholder'), 'OAuth code must never be logged') + assert.ok(!JSON.stringify(errors).includes(state), 'OAuth state must never be logged') + const finalCookie = cookieHeader(callback) + const sealed = await sessionFromCookie(finalCookie) + assert.equal(sealed.oauthAttempts?.length, 0, 'failed exchanges consume their pending attempt') +}) + +test('duplicate desktop callbacks share a one-way fingerprint without logging OAuth secrets', async (t) => { + const flow = '9f5a9d2c-2d46-42ff-8f91-e4c93814e055' + const login = mockRes() + await loginHandler(mockReq({ + query: { desktop_flow: flow, desktop_challenge: 'a'.repeat(64) }, + }), login) + const state = authorizeUrl(login).searchParams.get('state') + const cookie = cookieHeader(login) + const originalFetch = globalThis.fetch + let exchanges = 0 + globalThis.fetch = async (url) => { + const u = String(url) + if (u.includes('login/oauth/access_token')) { + exchanges++ + return new Response(JSON.stringify(exchanges === 1 + ? { access_token: 'fake-test-token' } + : { error: 'bad_verification_code', error_description: 'The code passed is incorrect or expired.' }), + { headers: { 'Content-Type': 'application/json' } }) + } + if (u.includes('api.github.com/user')) { + return new Response(JSON.stringify({ id: 4242, login: 'account-b', node_id: 'n42', avatar_url: '', name: 'B' }), + { headers: { 'Content-Type': 'application/json' } }) + } + if (u.includes('api.github.com/user/installations')) { + return new Response(JSON.stringify({ total_count: 0, installations: [] }), + { headers: { 'Content-Type': 'application/json' } }) + } + return new Response(JSON.stringify({}), { status: 404 }) + } + t.after(() => { globalThis.fetch = originalFetch }) + const priorInfo = console.info + const priorError = console.error + const infos = [] + const errors = [] + console.info = (...parts) => infos.push(parts) + console.error = (...parts) => errors.push(parts) + t.after(() => { console.info = priorInfo; console.error = priorError }) + + // Both requests present the same original cookie. This models concurrent + // browser callback requests, not a replay from the post-success cookie. + const first = mockRes() + await callbackHandler(mockReq({ + headers: { cookie }, query: { code: 'fake-one-use-code', state }, + }), first) + const second = mockRes() + await callbackHandler(mockReq({ + headers: { cookie }, query: { code: 'fake-one-use-code', state }, + }), second) + assert.equal(exchanges, 2) + assert.equal(first.statusCode, 302) + assert.equal(second.statusCode, 400) + const successLog = infos.find((parts) => String(parts[0]).includes('github oauth token exchange accepted:')) + const failureLog = errors.find((parts) => String(parts[0]).includes('github token exchange failed:')) + assert.ok(successLog) + assert.ok(failureLog) + assert.match(successLog[2], /^[a-f0-9]{16}$/) + assert.equal(failureLog[6], successLog[2], 'both callback attempts correlate without exposing raw state') + const logged = JSON.stringify({ infos, errors }) + assert.ok(!logged.includes('fake-one-use-code')) + assert.ok(!logged.includes(state)) +}) + +test('repeated OAuth code query parameters are rejected before any GitHub exchange', async (t) => { + const login = mockRes() + await loginHandler(mockReq(), login) + const state = authorizeUrl(login).searchParams.get('state') + const originalFetch = globalThis.fetch + let exchanged = 0 + globalThis.fetch = async () => { + exchanged++ + return new Response('{}') + } + t.after(() => { globalThis.fetch = originalFetch }) + const res = mockRes() + await callbackHandler(mockReq({ + headers: { cookie: cookieHeader(login) }, + url: '/api/auth/callback?code=first&code=second&state=' + encodeURIComponent(state), + }), res) + assert.equal(res.statusCode, 400) + assert.equal(res.body?.error, 'Invalid OAuth state') + assert.equal(exchanged, 0, 'repeated authorization codes must not reach the token endpoint') +}) + test('web login started during desktop authorization never inherits desktop handoff', async (t) => { const flow = '9f5a9d2c-2d46-42ff-8f91-e4c93814e055' const challenge = 'a'.repeat(64) diff --git a/test/desktop-auth.test.mjs b/test/desktop-auth.test.mjs index a6e6c00..d10a247 100644 --- a/test/desktop-auth.test.mjs +++ b/test/desktop-auth.test.mjs @@ -15,6 +15,8 @@ const { consumeDesktopCode, desktopDeepLink, desktopHandoff, + oauthDesktopHandoffCode, + recoverCompletedDesktopHandoff, isDesktopFlowId, issueDesktopToken, revokeDesktopToken, @@ -147,6 +149,92 @@ test('desktopHandoff insert failure degrades to the normal web redirect', async assert.equal(res.headers.Location, '/') }) +test('OAuth-derived desktop handoff is stable, PKCE-bound and never a raw GitHub code', async () => { + const oauthCode = 'sample-code-123' + const one = oauthDesktopHandoffCode(oauthCode, FLOW, CHALLENGE) + const two = oauthDesktopHandoffCode(oauthCode, FLOW, CHALLENGE) + assert.match(one, /^dlc_[A-Za-z0-9_-]{43}$/) + assert.equal(one, two) + assert.notEqual(one, oauthCode) + assert.notEqual(one, oauthDesktopHandoffCode(oauthCode + '-different', FLOW, CHALLENGE)) + assert.notEqual(one, oauthDesktopHandoffCode(oauthCode, FLOW.slice(0, -1) + '1', CHALLENGE)) + assert.notEqual(one, oauthDesktopHandoffCode(oauthCode, FLOW, 'd'.repeat(64))) + assert.equal(oauthDesktopHandoffCode(oauthCode, FLOW, 'invalid'), null) + assert.equal(oauthDesktopHandoffCode('', FLOW, CHALLENGE), null) + + db = fakeDb({ desktop_auth_codes: { data: null, error: null } }) + __setSupabaseForTests(db) + const res = mockRes() + const session = { + desktopFlow: FLOW, desktopChallenge: CHALLENGE, + userId: USER, sid: SID, save: async () => {}, + } + assert.equal(await desktopHandoff(res, session, '/', oauthCode), true) + assert.equal(res.statusCode, 302) + assert.equal(new URL(res.headers.Location).searchParams.get('code'), one) + const insert = db.queries.find((q) => q.table === 'desktop_auth_codes') + ?.ops.find((o) => o.m === 'insert')?.args[0] + assert.equal(insert.code_hash, await import('node:crypto').then(({ default: crypto }) => + crypto.createHash('sha256').update(one).digest('hex'))) + assert.notEqual(insert.code_hash, one, 'only a hash reaches the database') +}) + +test('replayed desktop callback recovers only the already-issued matching handoff', async () => { + const oauthCode = 'sample-code-123' + const expected = oauthDesktopHandoffCode(oauthCode, FLOW, CHALLENGE) + const { default: crypto } = await import('node:crypto') + const codeHash = crypto.createHash('sha256').update(expected).digest('hex') + let inserted = false + db = fakeDb({ + desktop_auth_codes: (q) => { + if (q.ops.some((o) => o.m === 'insert')) { + inserted = true + return { data: null, error: null } + } + const filters = q.ops.filter((o) => o.m === 'eq') + const sameCode = filters.some((o) => o.args[0] === 'code_hash' && o.args[1] === codeHash) + const sameFlow = filters.some((o) => o.args[0] === 'flow' && o.args[1] === FLOW) + const samePkce = filters.some((o) => o.args[0] === 'challenge' && o.args[1] === CHALLENGE) + return { + data: inserted && sameCode && sameFlow && samePkce ? { code_hash: codeHash } : null, + error: null, + } + }, + }) + __setSupabaseForTests(db) + const first = mockRes() + await desktopHandoff(first, { + desktopFlow: FLOW, desktopChallenge: CHALLENGE, + userId: USER, sid: SID, save: async () => {}, + }, '/', oauthCode) + const retry = mockRes() + assert.equal(await recoverCompletedDesktopHandoff(retry, { + desktopFlow: FLOW, desktopChallenge: CHALLENGE, + }, oauthCode, { attempts: 1, delayMs: 0 }), true) + assert.equal(retry.statusCode, 302) + assert.equal(retry.headers.Location, first.headers.Location) + assert.equal(retry.headers['Cache-Control'], 'private, no-store, max-age=0') + assert.equal(await recoverCompletedDesktopHandoff(mockRes(), { + desktopFlow: FLOW, desktopChallenge: CHALLENGE, + }, 'a-different-github-code', { attempts: 1, delayMs: 0 }), false) + assert.equal(await recoverCompletedDesktopHandoff(mockRes(), { + desktopFlow: FLOW, desktopChallenge: 'd'.repeat(64), + }, oauthCode, { attempts: 1, delayMs: 0 }), false) +}) + +test('GitHub recovery cannot create a handoff on its own', async () => { + db = fakeDb({ desktop_auth_codes: { data: null, error: null } }) + __setSupabaseForTests(db) + const response = mockRes() + const restored = await recoverCompletedDesktopHandoff(response, { + desktopFlow: FLOW, desktopChallenge: CHALLENGE, + }, 'not-previously-exchanged', { attempts: 1, delayMs: 0 }) + assert.equal(restored, false) + assert.equal(response.statusCode, 200) + assert.equal(db.queries.filter((q) => q.table === 'desktop_auth_codes').length, 1) + assert.equal(db.queries.some((q) => q.ops.some((o) => o.m === 'insert')), false) +}) + /* ── code consume (single-use, expiry, binding) ─────────────────────── */ test('consumeDesktopCode rejects malformed input without touching the DB', async () => {