Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,13 @@ Previous SSO-only follow-up checks: **40 regression tests passed**, **3 Playwrig
- TypeScript, production Vite build and Pages Functions compilation passed. `npm audit --audit-level=moderate` reported **0 known vulnerabilities**; `git diff --check` passed.
- The browser mock uses a consent document and fresh navigation because Playwright only intercepts the first request of a server redirect chain. Real callback 303 behavior is covered by server tests. This is not a live OAuth provider test.
- [Administrator documentation](github-oauth.md) includes exact OAuth App URLs, runtime-secret CLI prompts for dashboard-restricted Pages projects, redeploy/config verification, scope limits and revocation. No real credentials were supplied/configured. Live OAuth/SSO/custom-domain and hosted-module acceptance remain required.

## Follow-up: post-consent failure diagnostics (2026-10-24)

A user reported that GitHub consent succeeded but GitPlus did not connect after returning. The live failure's exact cause remains unconfirmed; no production logs, cookies or real credentials were accessed. Code review confirmed that token-exchange failures lost their provider error categories, and the alert was below the PAT form.

- Preserve only allowlisted GitHub failure categories, including JSON errors on non-2xx responses; distinguish malformed responses, transport failures and safe internal runtime failures.
- Show stage and numeric HTTP status in a focused alert above the OAuth/PAT choices. Never reflect provider descriptions/URLs, arbitrary error strings or exception text.
- 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.
2 changes: 2 additions & 0 deletions docs/cloudflare-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ Create/connect a **Pages** project, not a plain Worker application:

No new D1/R2 binding, `JWT_SECRET`, `MAIL_INTERNAL_TOKEN` or user GitHub PAT is required. **GitHub OAuth additionally needs runtime `GITHUB_CLIENT_ID` and encrypted `GITHUB_CLIENT_SECRET`.** These must not be `VITE_*` values. If dashboard runtime editing is disabled, use `npx wrangler pages secret put GITHUB_CLIENT_ID --project-name gitplus` and `npx wrangler pages secret put GITHUB_CLIENT_SECRET --project-name gitplus`, entering each value privately at the prompt. See [exact registration, CLI and redeploy steps](github-oauth.md). PAT remains available without OAuth configuration. Do not copy another product's secrets into this project. Runtime origins are not `VITE_*` variables. In a Wrangler-configured Pages project, keep runtime settings in the config source; use separate reviewed configuration for a dedicated staging project/origin rather than relying on divergent dashboard overrides.

**Dashboard clarification:** Pages credentials go in **Settings → Variables and secrets**. The separate **Runtime** panel is for compatibility/placement, not a second secret-entry screen. Text/Secret bindings there can be read by Pages Functions; do not confuse them with explicitly build-only variables. Save and redeploy. A successful OAuth start shows bindings were present, not that GitHub has validated the pair.

## 3. First-party custom domain (required for real SSO)

1. Add `gitplus.gothwadtech.com` (or your chosen first-party subdomain) through the Pages project's custom domain settings and follow Cloudflare's DNS/TLS instructions.
Expand Down
27 changes: 27 additions & 0 deletions docs/github-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ GitPlus is a Gothwad Tech product. **Gothwad Accounts sign-in is mandatory.** Gi
4. Deploy/redeploy Pages **with Functions included**, then check the custom domain's `/api/github/config`. It should return `enabled: true` and public scopes, never credentials. This only checks that configuration is present and well-formed; it does not validate credentials against GitHub.
5. Test real authorization/cancellation, account switching and disconnect on the first-party custom domain. A separate staging origin requires its own reviewed configuration and matching OAuth App callback.

### Where to enter these in the Pages dashboard

Use **Workers & Pages → gitplus → Settings → Variables and secrets** in the intended production environment. Add the Client ID as Text or Secret and the Client Secret as Secret/encrypted. This is the Pages Functions binding location; there is no separate “runtime secrets” form to find. The separate **Runtime** panel controls compatibility/placement, not secret values. An explicitly build-only variable is not a substitute for a Function binding. Save before deploying/redeploying.

If the GitPlus button successfully starts authorization, the `/api/github/start` Function already found both values in its environment. This does **not** prove GitHub accepts the credential pair, but missing bindings should not be assumed to explain a later callback failure. Do not move or regenerate working secrets merely because the dashboard does not label them “runtime”.

### If dashboard runtime editing is disabled

A Wrangler-managed Pages project may lock parts of dashboard configuration. A screen saying “Variables and secrets” / “Bindings” does not by itself establish that all variables are build-only. Keep non-secret origins in `wrangler.jsonc`; do not work around the UI by exposing credentials in the Vite bundle.
Expand Down Expand Up @@ -67,3 +73,24 @@ One OAuth transaction cookie exists per browser origin: simultaneous connection
## Verification limits

Unit tests cover state/PKCE/owner/origin checks, tampering, expiry, secret rotation, exchange failure and replay rejection. Browser tests mock GitHub consent/completion and Accounts responses, using real built assets and pinned real universal-menu fixtures. They do not prove live GitHub authorization, Cloudflare runtime-secret configuration or cross-product cookie behavior. Complete the deployment checklist before declaring the live integration ready.

## Diagnosing a return that does not connect

GitHub consent is only one step; the callback must still validate state/Accounts identity and exchange the code for a token. A reported production failure after consent is **not yet reproduced or attributed to a specific cause**. Tests below are not a live credential/provider validation.

The earlier implementation discarded GitHub's specific error categories and placed the message below the PAT form. It now displays a focused alert above both connection options, with a safe stage/error/status such as `[complete:github_client_credentials; HTTP 400; GitHub HTTP 401]`. `start`, `callback` and `complete` identify the failing step; HTTP is the Pages response and “GitHub HTTP” is the upstream exchange response when available.

| Diagnostic code | Meaning / next investigation |
| --- | --- |
| `github_client_credentials` | GitHub explicitly rejected the client credential pair; verify the deployed pair belongs to one OAuth App. |
| `github_redirect_mismatch` | GitHub explicitly rejected the callback URI. |
| `github_bad_code` | GitHub rejected an invalid, expired or already-used code; begin a fresh attempt. |
| `github_pkce_rejected` | GitHub rejected the verifier; investigate same-tab attempt handling. |
| `github_email_unverified` | GitHub requires primary-email verification. |
| `invalid_state` / `invalid_transaction` | Callback cookie/state or completion proof could not be validated; investigate expiry, lost cookies, multiple attempts/tabs. |
| `origin_not_allowed` | The protected request origin check failed; investigate the actual browser origin, without weakening CSRF checks. |
| `account_unavailable` / `account_changed` | Accounts verification did not permit completion. |
| `github_http_error` / `github_invalid_response` | Upstream failed or did not provide a valid token response; not enough evidence to blame credentials. |
| `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.
35 changes: 31 additions & 4 deletions server/githubOAuth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
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 type { SessionEnv } from './accountsSession';
Expand Down Expand Up @@ -50,6 +51,13 @@ 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<Response> {
try { return 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()]);
}
}
async function oauthRequest(request: Request, env: GitHubOAuthEnv, fetcher: typeof fetch): Promise<Response> {
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 });
Expand Down Expand Up @@ -101,12 +109,31 @@ export async function handleGitHubOAuth(request: Request, env: GitHubOAuthEnv, f
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: env.GITHUB_CLIENT_ID, client_secret: env.GITHUB_CLIENT_SECRET, code: txn.code, redirect_uri: `${appOrigin(env)}/api/github/callback`, code_verifier: body.verifier }),
});
if (!response.ok || !response.headers.get('Content-Type')?.includes('application/json')) return jsonResponse({ error: 'github_exchange_failed', message: 'GitHub could not complete authorization. Start a new connection attempt.' }, 502, cookies);
const result = record(await response.json());
if (!result || result.error || typeof result.access_token !== 'string' || !/^[A-Za-z0-9_-]{10,1024}$/.test(result.access_token) || String(result.token_type).toLowerCase() !== 'bearer') return jsonResponse({ error: 'github_exchange_failed', message: 'GitHub rejected this authorization code. Start a new connection attempt.' }, 400, cookies);
const failed = (error: OAuthErrorCode, status = 502) => jsonResponse({ error, message: OAUTH_ERRORS[error], providerStatus: response.status }, status, cookies);
// GitHub can report OAuth errors as JSON even with non-2xx statuses. Retain
// only known error categories; never relay its description, body or URLs.
let result: Record<string, unknown> | null = null;
if (response.headers.get('Content-Type')?.toLowerCase().includes('application/json')) {
try { result = record(await response.json()); } catch { /* Report a safe category below. */ }
}
const providerErrors: Record<string, OAuthErrorCode> = {
incorrect_client_credentials: 'github_client_credentials',
redirect_uri_mismatch: 'github_redirect_mismatch',
bad_verification_code: 'github_bad_code',
incorrect_code_verifier: 'github_pkce_rejected',
unverified_user_email: 'github_email_unverified',
};
const providerError = result?.error;
if (typeof providerError === 'string' && Object.prototype.hasOwnProperty.call(providerErrors, providerError)) return failed(providerErrors[providerError], 400);
if (!response.ok) return failed('github_http_error');
if (providerError) return failed('github_exchange_rejected', 400);
if (!result || typeof result.access_token !== 'string' || !/^[A-Za-z0-9_-]{10,1024}$/.test(result.access_token) || String(result.token_type).toLowerCase() !== 'bearer') return failed('github_invalid_response');
// Deliberately no offline_access, refresh-token persistence, database or token vault.
// GitHub itself consumes the code once; frontend single-flight prevents duplicate exchanges.
return jsonResponse({ token: result.access_token, ownerId: txn.owner, scope: typeof result.scope === 'string' ? result.scope : '' }, 200, cookies);
} catch { return jsonResponse({ error: 'github_unavailable', message: 'GitHub authorization timed out or failed. Start again or use a PAT.' }, 502, cookies); }
} catch {
const error = controller.signal.aborted ? 'github_timeout' : 'github_unavailable';
return jsonResponse({ error, message: OAUTH_ERRORS[error] }, 502, cookies);
}
finally { clearTimeout(timer); }
}
39 changes: 39 additions & 0 deletions shared/githubOAuthErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 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 = {
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.',
method_not_allowed: 'The OAuth request reached an endpoint with an unsupported method. Check the deployed Functions routing.',
json_required: 'The OAuth endpoint did not receive the expected JSON request.',
invalid_request: 'The OAuth request was incomplete or malformed. Start a new connection attempt.',
invalid_transaction: 'The OAuth transaction cookie or same-tab verification could not be validated. Start again in the same tab; do not run concurrent connection attempts.',
invalid_state: 'The GitHub callback cookie/state could not be validated. The attempt may have expired or been replaced. Start again in the same browser tab.',
invalid_callback: 'GitHub returned without a usable authorization code. Start a new connection attempt.',
denied: 'GitHub authorization was cancelled. Try again or connect with a PAT.',
account_changed: 'Your Gothwad account changed during GitHub authorization. Start again.',
account_unavailable: 'Your Gothwad session could not be verified during authorization. Retry your connection.',
github_client_credentials: 'GitHub rejected the OAuth App Client ID / Client Secret pair. Check that the deployed Pages secrets belong to the same OAuth App, then redeploy.',
github_redirect_mismatch: 'GitHub rejected the callback URL. The OAuth App callback must exactly match the GitPlus custom-domain /api/github/callback URL.',
github_bad_code: 'GitHub rejected an expired, already-used or invalid authorization code. Start a fresh connection; do not reload the callback.',
github_pkce_rejected: 'GitHub rejected the PKCE verifier. Start again in the same tab and finish only one connection attempt at a time.',
github_email_unverified: 'GitHub requires a verified primary email address before completing authorization. Verify it on GitHub, then reconnect.',
github_exchange_rejected: 'GitHub rejected the token exchange with an unrecognized error. No GitHub connection was saved.',
github_http_error: 'GitHub returned an unsuccessful HTTP response during token exchange. No GitHub connection was saved.',
github_invalid_response: 'GitHub returned an unexpected token-exchange response. No GitHub connection was saved.',
github_timeout: 'The Pages Function timed out while exchanging the authorization code with GitHub. Start a new connection attempt.',
github_unavailable: 'The Pages Function could not reach GitHub for the token exchange. Start again or use a PAT.',
github_internal_error: 'The Pages Function could not finish the OAuth request because of an internal error. The deployment needs investigation.',
network_error: 'The browser could not reach the OAuth endpoint. Check connectivity and start a new connection attempt.',
response_not_json: 'The OAuth endpoint returned a non-JSON or unreadable response. Check Pages Functions deployment/routing; this is not a completed connection.',
unknown_error: 'GitHub authorization could not be completed. No usable failure code was returned.',
} as const;
export type OAuthErrorCode = keyof typeof OAUTH_ERRORS;
export function knownOAuthError(value: unknown): OAuthErrorCode {
return typeof value === 'string' && Object.prototype.hasOwnProperty.call(OAUTH_ERRORS, value) ? value as OAuthErrorCode : 'unknown_error';
}
export function oauthFailure(stage: 'start' | 'complete' | 'callback', code: unknown, status?: number, providerStatus?: unknown): string {
const safe = knownOAuthError(code);
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}]`;
}
16 changes: 10 additions & 6 deletions src/components/AuthScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export const AuthScreen: React.FC<AuthScreenProps> = ({ onSuccess, initialError
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(initialError || null);
const [showGuide, setShowGuide] = useState(false);
useEffect(() => {
if (error) document.getElementById('github-connection-error')?.focus();
}, [error]);

const { state: accountState } = useAccounts();
const [oauthEnabled, setOauthEnabled] = useState<boolean | null>(null);
Expand Down Expand Up @@ -167,6 +170,12 @@ export const AuthScreen: React.FC<AuthScreenProps> = ({ onSuccess, initialError
<p className="text-sm text-[#5f6368] dark:text-[#9aa0a6]">
You are signed in with Gothwad Accounts. GitHub access is a separate connection; your Gothwad password is never requested here.
</p>
{error && (
<div id="github-connection-error" role="alert" tabIndex={-1} className="p-3 bg-[#ea4335]/10 border border-[#ea4335]/30 rounded-xl text-xs text-[#ea4335] flex items-start gap-2">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<span className="leading-relaxed break-words min-w-0">{error}</span>
</div>
)}
<section className="space-y-3" aria-label="GitHub OAuth connection">
<h2 className="text-lg font-bold">Connect your GitHub account</h2>
<p className="text-xs leading-relaxed text-[#5f6368] dark:text-[#9aa0a6]">Authorize on GitHub—no PAT to create or paste. Requests broad repository, workflow, gist, profile, email and organization-read access, subject to your GitHub permissions.</p>
Expand Down Expand Up @@ -246,12 +255,7 @@ export const AuthScreen: React.FC<AuthScreenProps> = ({ onSuccess, initialError
</div>
</div>

{error && (
<div className="p-3 bg-[#ea4335]/10 border border-[#ea4335]/30 rounded-xl text-xs text-[#ea4335] flex items-start gap-2">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<span className="leading-relaxed">{error}</span>
</div>
)}


<button
id="connect-github-btn"
Expand Down
Loading
Loading