From fc512c1e379e074f80cee35263884533359ef25c Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:41:37 +0400 Subject: [PATCH 1/7] fix(auth): reject duplicate OAuth query fields and log safe code-exchange timing --- api/auth/callback.mjs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs index 83a7276..cd1a969 100644 --- a/api/auth/callback.mjs +++ b/api/auth/callback.mjs @@ -61,16 +61,27 @@ 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')) - stateOk = Number.isFinite(parsed.at) - && Date.now() - parsed.at >= 0 - && Date.now() - parsed.at < 15 * 60 * 1000 + const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) + const age = Date.now() - parsed.at + stateOk = Number.isFinite(parsed.at) && age >= 0 && age < 15 * 60 * 1000 + if (stateOk) oauthAgeSeconds = Math.floor(age / 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' }) @@ -125,11 +136,12 @@ export default async function handler(req, res) { // 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', tokenRes.status, tokenData?.error, tokenData?.error_description, - session.desktopFlow ? 'desktop' : 'web' + session.desktopFlow ? 'desktop' : 'web', + oauthAgeSeconds ) securityEvent('auth_callback_failed', { req, reasonCode: 'token_exchange' }) res.status(400).json({ error: 'GitHub token exchange failed' }) From c028bd8055de5f20f4928ece1879a0c20b6a0112 Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:41:52 +0400 Subject: [PATCH 2/7] test(auth): cover GitHub code rejection telemetry and duplicated callback parameters --- test/auth-login.test.mjs | 62 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/test/auth-login.test.mjs b/test/auth-login.test.mjs index 6a49efc..6d820ff 100644 --- a/test/auth-login.test.mjs +++ b/test/auth-login.test.mjs @@ -121,6 +121,68 @@ 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.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('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) From bfc1875688238b3a115c06c9bfeab49eef66fd3f Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:42:40 +0400 Subject: [PATCH 3/7] test(auth): retain explicit OAuth freshness predicate required by existing audits --- api/auth/callback.mjs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs index cd1a969..a5d1071 100644 --- a/api/auth/callback.mjs +++ b/api/auth/callback.mjs @@ -70,9 +70,10 @@ export default async function handler(req, res) { if (singleCode && singleState && (attempt || state === session.oauthState)) { try { const parsed = JSON.parse(Buffer.from(state, 'base64url').toString('utf8')) - const age = Date.now() - parsed.at - stateOk = Number.isFinite(parsed.at) && age >= 0 && age < 15 * 60 * 1000 - if (stateOk) oauthAgeSeconds = Math.floor(age / 1000) + 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 } From 18384695508f2c2821a03dcfa8f2f6dd514b2603 Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:06:53 +0400 Subject: [PATCH 4/7] diagnostics(auth): correlate successful and rejected desktop OAuth callback attempts with keyed HMAC --- api/auth/callback.mjs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs index a5d1071..95c787f 100644 --- a/api/auth/callback.mjs +++ b/api/auth/callback.mjs @@ -6,7 +6,7 @@ import { kickSync, runSync, setUserSync, SYNC_DETAIL_INIT } from '../../lib/sync import { createAuthSession, gcAuthSessions, isSessionLive } from '../../lib/sessions.mjs' import { desktopHandoff, isDesktopFlowId, isDesktopChallenge } from '../../lib/desktop-auth.mjs' import { requestQuery } from '../../lib/request-query.mjs' -import { securityEvent } from '../../lib/security-events.mjs' +import { securityEvent, correlate } from '../../lib/security-events.mjs' export default async function handler(req, res) { const { code, state, installation_id: installationId, setup_action: setupAction } = requestQuery(req) @@ -114,6 +114,11 @@ export default async function handler(req, res) { } const redirectUri = `${appUrl}/api/auth/callback` + // Authenticated correlation only: the state is random/short-lived and the + // HMAC key is server-held. Never log state, code, token, cookie or query URL. + // Matching fingerprints across an accepted and rejected callback show + // whether the *same* authorization attempt was processed more than once. + const stateFingerprint = correlate(state)?.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. @@ -137,18 +142,25 @@ export default async function handler(req, res) { // 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 oauth_age_sec=%d', + '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', - oauthAgeSeconds + 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() From 6981b18a045d0d6a0e7e425b9a2857f249830308 Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:07:15 +0400 Subject: [PATCH 5/7] test(auth): correlate duplicate callback success/failure without recording OAuth credentials --- test/auth-login.test.mjs | 70 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/test/auth-login.test.mjs b/test/auth-login.test.mjs index 6d820ff..edc292e 100644 --- a/test/auth-login.test.mjs +++ b/test/auth-login.test.mjs @@ -155,6 +155,7 @@ test('a GitHub bad_verification_code failure records only safe OAuth age and con 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) @@ -162,6 +163,75 @@ test('a GitHub bad_verification_code failure records only safe OAuth age and con assert.equal(sealed.oauthAttempts?.length, 0, 'failed exchanges consume their pending attempt') }) +test('duplicate desktop callback attempts yield matching keyed fingerprints but never log OAuth code', async (t) => { + const prevKey = process.env.SECURITY_EVENT_HASH_KEY + process.env.SECURITY_EVENT_HASH_KEY = 'local-test-only-correlator-32-plus-characters' + t.after(() => { + if (prevKey === undefined) delete process.env.SECURITY_EVENT_HASH_KEY + else process.env.SECURITY_EVENT_HASH_KEY = prevKey + }) + + 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) From 9c147e0fc9eb9a40e344a3ec448d034f7221db53 Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:08:02 +0400 Subject: [PATCH 6/7] diagnostics(auth): correlate random OAuth attempts without requiring an unset env key --- api/auth/callback.mjs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/api/auth/callback.mjs b/api/auth/callback.mjs index 95c787f..74445c8 100644 --- a/api/auth/callback.mjs +++ b/api/auth/callback.mjs @@ -1,3 +1,4 @@ +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' @@ -6,7 +7,7 @@ import { kickSync, runSync, setUserSync, SYNC_DETAIL_INIT } from '../../lib/sync import { createAuthSession, gcAuthSessions, isSessionLive } from '../../lib/sessions.mjs' import { desktopHandoff, isDesktopFlowId, isDesktopChallenge } from '../../lib/desktop-auth.mjs' import { requestQuery } from '../../lib/request-query.mjs' -import { securityEvent, correlate } from '../../lib/security-events.mjs' +import { securityEvent } from '../../lib/security-events.mjs' export default async function handler(req, res) { const { code, state, installation_id: installationId, setup_action: setupAction } = requestQuery(req) @@ -114,11 +115,14 @@ export default async function handler(req, res) { } const redirectUri = `${appUrl}/api/auth/callback` - // Authenticated correlation only: the state is random/short-lived and the - // HMAC key is server-held. Never log state, code, token, cookie or query URL. - // Matching fingerprints across an accepted and rejected callback show - // whether the *same* authorization attempt was processed more than once. - const stateFingerprint = correlate(state)?.slice(0, 16) || 'unavailable' + // 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. From b4fa062a7101c9cb348d9a457e0865a849ec6a9e Mon Sep 17 00:00:00 2001 From: aliferous3 <94698925+Aliferous3@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:08:14 +0400 Subject: [PATCH 7/7] test(auth): verify fingerprint correlation independent of optional telemetry key --- test/auth-login.test.mjs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/auth-login.test.mjs b/test/auth-login.test.mjs index edc292e..f3ebd46 100644 --- a/test/auth-login.test.mjs +++ b/test/auth-login.test.mjs @@ -163,14 +163,7 @@ test('a GitHub bad_verification_code failure records only safe OAuth age and con assert.equal(sealed.oauthAttempts?.length, 0, 'failed exchanges consume their pending attempt') }) -test('duplicate desktop callback attempts yield matching keyed fingerprints but never log OAuth code', async (t) => { - const prevKey = process.env.SECURITY_EVENT_HASH_KEY - process.env.SECURITY_EVENT_HASH_KEY = 'local-test-only-correlator-32-plus-characters' - t.after(() => { - if (prevKey === undefined) delete process.env.SECURITY_EVENT_HASH_KEY - else process.env.SECURITY_EVENT_HASH_KEY = prevKey - }) - +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({