diff --git a/docs/audit.md b/docs/audit.md index bfc7a8a..6ddd935 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -93,3 +93,12 @@ A user reported that GitHub consent succeeded but GitPlus did not connect after - Correct Pages dashboard guidance: **Settings → Variables and secrets** is the binding entry point; the separate Runtime panel is not where secrets are entered. No build-time secret injection or relaxed OAuth security checks. - Local validation: **56 unit tests, 11 browser tests**, TypeScript, production build and Functions compilation passed; dependency audit reported zero known vulnerabilities. - This repairs failure reporting/visibility; it is **not evidence that the reported live authorization problem has been resolved**. A fresh attempt on the diagnostic deployment is needed to identify the actual failing stage/reason. + +## Follow-up: unrecognized completion 502 (2026-10-24) + +The user supplied `[complete:unknown_error; HTTP 502]`. Review found that all ordinary current-backend 502 paths emit recognized identifiers, while the older `github_exchange_failed` response reproduced the diagnostic compatibility gap. This does not establish that the user's backend is old: a different/intermediary JSON response can also produce that message. + +- Recognize the legacy exchange code without blaming credentials; classify unexpected JSON failures separately and never echo their contents. +- Add a public response-contract marker and optional strictly validated short Pages commit to OAuth config/headers, so the custom-domain backend can be checked without another authorization attempt. +- Keep success behavior, cookie forwarding, state/PKCE/origin/owner protections unchanged; no production secrets accessed and no private diagnostic logging added. +- Local checks: **59 unit tests and 13 browser tests passed**, TypeScript, Vite build and Functions compilation passed. Live failure cause remains unconfirmed; this is compatibility/serving-version diagnostics, not proof of repaired live authorization. diff --git a/docs/github-oauth.md b/docs/github-oauth.md index ef2e7f0..6fd13b8 100644 --- a/docs/github-oauth.md +++ b/docs/github-oauth.md @@ -94,3 +94,22 @@ The earlier implementation discarded GitHub's specific error categories and plac | `response_not_json` / `github_internal_error` | Investigate Pages routing/runtime, rather than asking the user to repeatedly change secrets. | Only fixed allowlisted categories and numeric HTTP statuses are displayed. Provider descriptions, exception text and unknown error strings are not reflected. No diagnostic endpoint exposes secret values, token responses, cookie contents or callback codes, and no request/response logging was added. Share only the visible diagnostic—not a HAR, full callback URL or network response containing credentials. Existing origin/owner/state/PKCE validation remains unchanged. + +### `complete:unknown_error; HTTP 502` and serving-version checks + +This reports a parsed JSON failure from the completion endpoint whose error identifier was not recognized. It is **not** evidence that runtime bindings are missing or the secret is incorrect. The current backend's normal 502 paths use specific recognized identifiers. One reproducible compatibility gap was the previous backend's `github_exchange_failed` code, which the first diagnostic frontend mapped to `unknown_error`. That legacy code is now recognized; unknown bodies are classified as `oauth_response_unrecognized`, not echoed. + +Before asking someone to authorize repeatedly, open the public, no-store endpoint: + +```text +https://gitplus.gothwadtech.com/api/github/config +``` + +It returns only `enabled`, public `scopes`, `protocol` (currently `gitplus-oauth-2`) and `deployment` (a shortened Pages commit SHA, or null if unavailable). No Client ID, secret, cookie, token, verifier or authorization code is returned. OAuth responses, including callbacks/errors, also carry `X-GitPlus-OAuth-Protocol` and, when available, `X-GitPlus-Deployment`. The frontend renders only a fixed contract classification and strictly validated hex revision in error diagnostics, never arbitrary headers. + +- Missing `protocol`: that config response is not the newly instrumented handler. Check the production deployment/custom-domain mapping and any Worker route overriding `/api/*`. +- Config has the current protocol but completion is `backend:unmarked`: investigate the completion route and intermediary responses, rather than assuming the whole backend updated. Missing headers alone do not prove an old deployment; intermediaries may remove them. +- `deployment` differs from the intended production commit: verify which Pages deployment is promoted for the custom domain. A successful GitHub Pages check alone does not prove what every custom-domain path is serving. +- A current, marked completion error has a known provider category: investigate that category. The version fields do not validate credentials or prove live OAuth works. + +No request/response body logging or automatic token-exchange retry was added. State/PKCE/owner checks and local-only persistence remain unchanged. The reported live failure still requires serving-version/response evidence before attributing its cause. diff --git a/server/githubOAuth.ts b/server/githubOAuth.ts index 45838fb..ef70f4d 100644 --- a/server/githubOAuth.ts +++ b/server/githubOAuth.ts @@ -1,10 +1,10 @@ import { OAUTH_ERRORS, type OAuthErrorCode } from '../shared/githubOAuthErrors'; import { record, validSelector } from '../shared/accounts'; -import { base64url, challengeFor, GITHUB_SCOPES, OAUTH_TTL_SECONDS, randomProof, validProof } from '../shared/githubOAuth'; +import { base64url, challengeFor, OAUTH_PROTOCOL, OAUTH_PROTOCOL_HEADER, OAUTH_DEPLOYMENT_HEADER, GITHUB_SCOPES, OAUTH_TTL_SECONDS, randomProof, validProof } from '../shared/githubOAuth'; import type { SessionEnv } from './accountsSession'; import { appOrigin, jsonResponse, postGuard, smallJson, verifiedAccount } from './protectedRequest'; -export interface GitHubOAuthEnv extends SessionEnv { GITHUB_CLIENT_ID?: string; GITHUB_CLIENT_SECRET?: string } +export interface GitHubOAuthEnv extends SessionEnv { GITHUB_CLIENT_ID?: string; GITHUB_CLIENT_SECRET?: string; CF_PAGES_COMMIT_SHA?: string } export const TRANSACTION_COOKIE = '__Host-gitplus_oauth'; interface Transaction { state: string; challenge: string; owner: string; selector: string; expires: number; clientId: string; code?: string } const encoder = new TextEncoder(); @@ -51,16 +51,25 @@ function callbackRedirect(env: GitHubOAuthEnv, status: 'complete' | 'error', rea return new Response(null, { status: 303, headers }); } export async function handleGitHubOAuth(request: Request, env: GitHubOAuthEnv, fetcher: typeof fetch = fetch): Promise { - try { return await oauthRequest(request, env, fetcher); } + let response: Response; + try { response = await oauthRequest(request, env, fetcher); } catch { // Do not leak runtime exception messages (which can contain credentials/URLs). - return jsonResponse({ error: 'github_internal_error', message: OAUTH_ERRORS.github_internal_error }, 500, [clearOAuthCookie()]); + response = jsonResponse({ error: 'github_internal_error', message: OAUTH_ERRORS.github_internal_error }, 500, [clearOAuthCookie()]); } + response.headers.set(OAUTH_PROTOCOL_HEADER, OAUTH_PROTOCOL); + const deployment = deploymentRevision(env); + if (deployment) response.headers.set(OAUTH_DEPLOYMENT_HEADER, deployment); + return response; +} +function deploymentRevision(env: GitHubOAuthEnv): string | null { + const value = env.CF_PAGES_COMMIT_SHA; + return typeof value === 'string' && /^[a-f0-9]{7,40}$/.test(value) ? value.slice(0, 12) : null; } async function oauthRequest(request: Request, env: GitHubOAuthEnv, fetcher: typeof fetch): Promise { const url = new URL(request.url); if (url.origin !== appOrigin(env)) return jsonResponse({ error: 'first_party_domain_required' }, 403); - if (url.pathname === '/api/github/config' && request.method === 'GET') return jsonResponse({ enabled: configured(env), scopes: GITHUB_SCOPES }); + if (url.pathname === '/api/github/config' && request.method === 'GET') return jsonResponse({ enabled: configured(env), scopes: GITHUB_SCOPES, protocol: OAUTH_PROTOCOL, deployment: deploymentRevision(env) }); if (!configured(env)) return jsonResponse({ error: 'oauth_not_configured', message: 'Connect with GitHub is not configured yet. Use a PAT or ask the administrator to configure the OAuth App.' }, 503); if (url.pathname === '/api/github/callback') { diff --git a/shared/githubOAuth.ts b/shared/githubOAuth.ts index 95b22e9..bfb2819 100644 --- a/shared/githubOAuth.ts +++ b/shared/githubOAuth.ts @@ -1,3 +1,7 @@ +// Public response-contract marker, not an authentication credential. +export const OAUTH_PROTOCOL = 'gitplus-oauth-2'; +export const OAUTH_PROTOCOL_HEADER = 'X-GitPlus-OAuth-Protocol'; +export const OAUTH_DEPLOYMENT_HEADER = 'X-GitPlus-Deployment'; export const GITHUB_SCOPES = ['repo', 'workflow', 'gist', 'read:user', 'user:email', 'read:org'] as const; export const OAUTH_TTL_SECONDS = 600; export const OAUTH_PENDING_KEY = 'gitplus_github_oauth_pending'; diff --git a/shared/githubOAuthErrors.ts b/shared/githubOAuthErrors.ts index 8731f66..65469aa 100644 --- a/shared/githubOAuthErrors.ts +++ b/shared/githubOAuthErrors.ts @@ -1,6 +1,10 @@ +import { OAUTH_PROTOCOL, OAUTH_PROTOCOL_HEADER, OAUTH_DEPLOYMENT_HEADER } from './githubOAuth'; + // Only fixed, public diagnostic messages may reach the UI. Never reflect provider // error_description, URLs, response bodies, cookies, codes, verifiers or credentials. export const OAUTH_ERRORS = { + github_exchange_failed: 'An older GitPlus backend reported a GitHub token-exchange failure without a specific reason. Check that the custom domain is serving the latest Pages Functions deployment; do not assume the secret is wrong.', + oauth_response_unrecognized: 'The OAuth endpoint returned JSON that does not match the expected GitPlus error contract. Check the API deployment and any proxy/Worker route on this domain. This response does not establish that the OAuth credentials are wrong.', oauth_not_configured: 'The deployed Pages Function is missing OAuth configuration. Set the two credentials in Pages Settings → Variables and secrets, then redeploy.', first_party_domain_required: 'Open GitPlus on its configured Gothwad Tech custom domain before connecting GitHub.', origin_not_allowed: 'GitPlus rejected the request origin. Open the custom domain directly in the same browser tab and start again.', @@ -37,3 +41,14 @@ export function oauthFailure(stage: 'start' | 'complete' | 'callback', code: unk const upstream = typeof providerStatus === 'number' && Number.isInteger(providerStatus) && providerStatus >= 100 && providerStatus <= 599 ? `; GitHub HTTP ${providerStatus}` : ''; return `${OAUTH_ERRORS[safe]} [${stage}:${safe}${status ? `; HTTP ${status}` : ''}${upstream}]`; } + +export function oauthResponseFailure(stage: 'start' | 'complete', result: Record | null, response: Response): string { + const candidate = result?.error ?? (result?.status === 'anonymous' || result?.status === 'unavailable' ? 'account_unavailable' : 'unknown_error'); + const code = knownOAuthError(candidate) === 'unknown_error' ? 'oauth_response_unrecognized' : candidate; + const protocol = response.headers.get(OAUTH_PROTOCOL_HEADER); + const contract = protocol === OAUTH_PROTOCOL ? 'current' : protocol ? 'different' : 'unmarked'; + const revision = response.headers.get(OAUTH_DEPLOYMENT_HEADER); + // Never render arbitrary headers or unknown JSON fields in a diagnostic. + const deployment = revision && /^[a-f0-9]{7,40}$/.test(revision) ? revision.slice(0, 12) : 'unavailable'; + return `${oauthFailure(stage, code, response.status, result?.providerStatus)} [backend:${contract}; deployment:${deployment}]`; +} diff --git a/src/services/githubOAuth.ts b/src/services/githubOAuth.ts index 9881223..7cea4b0 100644 --- a/src/services/githubOAuth.ts +++ b/src/services/githubOAuth.ts @@ -1,4 +1,4 @@ -import { oauthFailure } from '../../shared/githubOAuthErrors'; +import { oauthFailure, oauthResponseFailure } from '../../shared/githubOAuthErrors'; import { challengeFor, OAUTH_PENDING_KEY, OAUTH_RETURN_PARAM, OAUTH_TTL_SECONDS, randomProof, validProof } from '../../shared/githubOAuth'; import { record, type AuthenticatedSession } from '../../shared/accounts'; import { githubService } from './github'; @@ -21,8 +21,7 @@ async function api(path: string, data: unknown) { if (!response.ok || !result) { // Session verification has its own sanitized messages, but keep OAuth diagnostics // allowlisted: never display arbitrary response bodies or unknown error strings. - const code = result?.error ?? (result?.status === 'anonymous' || result?.status === 'unavailable' ? 'account_unavailable' : 'unknown_error'); - throw new Error(oauthFailure(stage, code, response.status, result?.providerStatus)); + throw new Error(oauthResponseFailure(stage, result, response)); } return result; } diff --git a/tests/browser/accounts.spec.ts b/tests/browser/accounts.spec.ts index 40746dc..96694d0 100644 --- a/tests/browser/accounts.spec.ts +++ b/tests/browser/accounts.spec.ts @@ -236,3 +236,21 @@ for (const failure of ['provider', 'html', 'guard'] as const) { expect(errors).toEqual([]); }); } + +for (const legacy of [true, false]) { + test(`${legacy ? 'legacy' : 'unidentified'} backend 502 is actionable and never claims the OAuth secret is wrong`, async ({ page }) => { + const errors = await mockApp(page, () => ({ status: 200, body: account('alice') })); + await page.addInitScript(() => sessionStorage.setItem('gitplus_github_oauth_pending', JSON.stringify({ ownerId: 'alice-id', state: 'a'.repeat(43), verifier: 'b'.repeat(43), expires: Date.now() + 600000 }))); + await page.route(`${ORIGIN}/api/github/complete`, (route) => route.fulfill({ status: 502, contentType: 'application/json', body: JSON.stringify({ error: legacy ? 'github_exchange_failed' : 'private-error-must-not-display', message: 'private-message-must-not-display' }) })); + await page.goto(`${ORIGIN}/?github_oauth=complete&authuser=a`); + const alert = page.locator('#github-connection-error'); + await expect(alert).toContainText(`[complete:${legacy ? 'github_exchange_failed' : 'oauth_response_unrecognized'}; HTTP 502]`); + await expect(alert).toContainText('[backend:unmarked; deployment:unavailable]'); + await expect(alert).not.toContainText('private-'); + await expect(alert).not.toContainText('unknown_error'); + await expect(alert).toBeInViewport(); + await expect(page.locator('#pat-input')).toBeEnabled(); + expect(await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection'))).toBeNull(); + expect(errors).toEqual([]); + }); +} diff --git a/tests/github-oauth-errors.test.ts b/tests/github-oauth-errors.test.ts index 4752496..e2eae0f 100644 --- a/tests/github-oauth-errors.test.ts +++ b/tests/github-oauth-errors.test.ts @@ -12,3 +12,31 @@ test('OAuth diagnostics include stage and numeric status but never arbitrary pro } assert.ok(!oauthFailure('complete', 'github_http_error', 502, Infinity).includes('Infinity')); }); + +test('legacy 502 exchange failure is recognized rather than being collapsed to unknown_error', async () => { + const { oauthResponseFailure } = await import('../shared/githubOAuthErrors'); + const response = new Response(null, { status: 502 }); + const message = oauthResponseFailure('complete', { error: 'github_exchange_failed', message: 'never-display-provider-body' }, response); + assert.match(message, /\[complete:github_exchange_failed; HTTP 502\]/); + assert.match(message, /backend:unmarked; deployment:unavailable/); + assert.ok(!message.includes('unknown_error')); + assert.ok(!message.includes('never-display-provider-body')); +}); + +test('unrecognized 502 JSON identifies the response contract without echoing private JSON or arbitrary headers', async () => { + const { oauthResponseFailure } = await import('../shared/githubOAuthErrors'); + const { OAUTH_PROTOCOL, OAUTH_PROTOCOL_HEADER, OAUTH_DEPLOYMENT_HEADER } = await import('../shared/githubOAuth'); + for (const protocol of [undefined, OAUTH_PROTOCOL, 'private-header']) { + const response = new Response(null, { status: 502, headers: { + ...(protocol ? { [OAUTH_PROTOCOL_HEADER]: protocol } : {}), + [OAUTH_DEPLOYMENT_HEADER]: protocol === OAUTH_PROTOCOL ? 'b1506461ef205d2ef2629047664aaade6fd51399' : 'private-header', + } }); + for (const data of [null, { error: 'private-token' }, { errors: [{ message: 'private-message' }] }]) { + const text = oauthResponseFailure('complete', data, response); + assert.match(text, /complete:oauth_response_unrecognized; HTTP 502/); + assert.ok(text.includes(`backend:${protocol === undefined ? 'unmarked' : protocol === OAUTH_PROTOCOL ? 'current' : 'different'}`)); + assert.ok(!text.includes('private-')); + if (protocol === OAUTH_PROTOCOL) assert.match(text, /deployment:b1506461ef20/); + } + } +}); diff --git a/tests/github-oauth.test.ts b/tests/github-oauth.test.ts index 3540890..a858bf6 100644 --- a/tests/github-oauth.test.ts +++ b/tests/github-oauth.test.ts @@ -2,7 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { handleGitHubOAuth, TRANSACTION_COOKIE, type GitHubOAuthEnv } from '../server/githubOAuth'; import { handleAccountAction } from '../server/accountActions'; -import { challengeFor, randomProof } from '../shared/githubOAuth'; +import { challengeFor, randomProof, OAUTH_PROTOCOL, OAUTH_PROTOCOL_HEADER, OAUTH_DEPLOYMENT_HEADER } from '../shared/githubOAuth'; const origin = 'https://gitplus.gothwadtech.com'; const env: GitHubOAuthEnv = { GITPLUS_ORIGIN: origin, GITHUB_CLIENT_ID: 'test-client-id', GITHUB_CLIENT_SECRET: 'test-only-secret-not-a-real-github-secret' }; @@ -44,7 +44,7 @@ async function callback(s: Awaited>, fetcher: typeof fe test('unconfigured OAuth reports unavailable without exposing secrets or disabling PAT infrastructure', async () => { const config = await handleGitHubOAuth(makeRequest('/api/github/config'), {}); - assert.deepEqual(await config.json(), { enabled: false, scopes: ['repo', 'workflow', 'gist', 'read:user', 'user:email', 'read:org'] }); + assert.deepEqual(await config.json(), { enabled: false, scopes: ['repo', 'workflow', 'gist', 'read:user', 'user:email', 'read:org'], protocol: OAUTH_PROTOCOL, deployment: null }); assert.equal((await handleGitHubOAuth(makeRequest('/api/github/start', {}), {})).status, 503); assert.equal((await handleGitHubOAuth(new Request('https://gitplus.pages.dev/api/github/config'), env)).status, 403); }); @@ -220,3 +220,27 @@ test('unexpected runtime exceptions produce JSON diagnostics without exposing ex assert.ok(!JSON.stringify(body).includes('private-runtime-secret')); assert.match(response.headers.get('Cache-Control')!, /no-store/); }); + +test('OAuth config and responses identify the serving backend without credentials or arbitrary environment data', async () => { + const deploymentEnv = { ...env, CF_PAGES_COMMIT_SHA: 'b1506461ef205d2ef2629047664aaade6fd51399' }; + const config = await handleGitHubOAuth(makeRequest('/api/github/config'), deploymentEnv); + const body = await config.json(); + assert.equal(body.protocol, OAUTH_PROTOCOL); + assert.equal(body.deployment, 'b1506461ef20'); + assert.equal(config.headers.get(OAUTH_PROTOCOL_HEADER), OAUTH_PROTOCOL); + assert.equal(config.headers.get(OAUTH_DEPLOYMENT_HEADER), 'b1506461ef20'); + assert.ok(!JSON.stringify(body).includes(env.GITHUB_CLIENT_ID!)); + assert.ok(!JSON.stringify(body).includes(env.GITHUB_CLIENT_SECRET!)); + const invalid = await handleGitHubOAuth(makeRequest('/api/github/config'), { ...env, CF_PAGES_COMMIT_SHA: 'private-environment-value' }); + assert.equal((await invalid.json()).deployment, null); + assert.equal(invalid.headers.get(OAUTH_DEPLOYMENT_HEADER), null); + const failure = await handleGitHubOAuth(makeRequest('/api/github/complete', {}), deploymentEnv); + assert.equal(failure.status, 400); + assert.equal(failure.headers.get(OAUTH_PROTOCOL_HEADER), OAUTH_PROTOCOL); + assert.equal(failure.headers.get(OAUTH_DEPLOYMENT_HEADER), 'b1506461ef20'); + const callback = await handleGitHubOAuth(makeRequest('/api/github/callback'), deploymentEnv); + assert.equal(callback.status, 303); + assert.equal(callback.headers.get(OAUTH_PROTOCOL_HEADER), OAUTH_PROTOCOL); + assert.match(callback.headers.getSetCookie().at(-1)!, /Max-Age=0/); + assert.match(callback.headers.get('Cache-Control')!, /no-store/); +});