From 6e484527ec2a60871bacb8d386fca30b32c180b4 Mon Sep 17 00:00:00 2001 From: GothwadTech <295316515+GothwadTech@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:30:23 +0000 Subject: [PATCH] Add local GitHub OAuth connection and universal Gothwad account menu Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 19 +- docs/README.md | 5 +- docs/architecture.md | 14 +- docs/audit.md | 14 +- docs/cloudflare-pages.md | 17 +- docs/github-oauth.md | 69 ++++ docs/gothwad-accounts.md | 23 +- docs/product-roadmap.md | 9 +- docs/security.md | 14 +- functions/api/[[path]].ts | 14 +- public/_headers | 2 +- server/accountActions.ts | 31 ++ server/githubOAuth.ts | 112 ++++++ server/protectedRequest.ts | 57 +++ shared/githubOAuth.ts | 14 + src/App.tsx | 9 +- src/components/AuthScreen.tsx | 40 +- src/components/accounts/AccountsBar.tsx | 78 ++++ src/components/accounts/AccountsGate.tsx | 25 +- src/context/AccountsContext.tsx | 3 + src/services/accounts/accountWidget.ts | 50 +++ src/services/github.ts | 2 + src/services/githubOAuth.ts | 77 ++++ tests/account-widget.test.ts | 30 ++ tests/browser/accounts.spec.ts | 129 +++++- tests/fixtures/account-widget/README.md | 10 + .../account-widget/account-menu-styles.js | 367 ++++++++++++++++++ .../account-widget/account-menu-template.js | 209 ++++++++++ tests/fixtures/account-widget/account-menu.js | 290 ++++++++++++++ tests/github-oauth.test.ts | 168 ++++++++ 30 files changed, 1826 insertions(+), 75 deletions(-) create mode 100644 docs/github-oauth.md create mode 100644 server/accountActions.ts create mode 100644 server/githubOAuth.ts create mode 100644 server/protectedRequest.ts create mode 100644 shared/githubOAuth.ts create mode 100644 src/components/accounts/AccountsBar.tsx create mode 100644 src/services/accounts/accountWidget.ts create mode 100644 src/services/githubOAuth.ts create mode 100644 tests/account-widget.test.ts create mode 100644 tests/fixtures/account-widget/README.md create mode 100644 tests/fixtures/account-widget/account-menu-styles.js create mode 100644 tests/fixtures/account-widget/account-menu-template.js create mode 100644 tests/fixtures/account-widget/account-menu.js create mode 100644 tests/github-oauth.test.ts diff --git a/README.md b/README.md index dddf090..5ebea01 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A mobile-first GitHub workspace built with React, TypeScript, Vite and Tailwind. ## Two separate connections 1. **Sign in to GitPlus with Gothwad Accounts.** Existing first-party Accounts sessions are recognized automatically. A same-origin Cloudflare Pages Function verifies HttpOnly cookies with the Accounts API and returns only a public profile. -2. **Connect GitHub separately.** Gothwad login does not grant GitHub repository permissions. The current connection uses a user-provided GitHub PAT scoped to the verified Gothwad user ID and this tab. A server-side GitHub App integration is future work, not implemented authentication. +2. **Connect GitHub separately.** Gothwad login does not grant GitHub repository permissions. Use **Connect with GitHub** (OAuth App) or a manually supplied PAT. Either connection is bound to the verified Gothwad user ID and stored only in this tab session. No D1 or cross-device token sync is used. No Gothwad password, Accounts access token or refresh token is stored by the browser app. GitHub PATs still need careful handling: session storage is not an encrypted vault. @@ -17,10 +17,11 @@ This is now **Pages + a small Pages Function**, not a static-only deployment: ```text Browser -> /api/session (Pages Function) -> Gothwad Accounts /api/auth/me - -> GitHub REST API (separate GitHub PAT) + -> /api/github/* (Pages Functions: OAuth state/callback/code exchange) + -> GitHub REST API (local OAuth token or PAT) ``` -No new D1/R2 database, Accounts JWT secret, OAuth client secret or GitHub token is required in Pages environment settings. Accounts continues owning sessions. +No new D1/R2 database or Accounts JWT secret is required. Accounts continues owning sessions. GitHub OAuth requires runtime `GITHUB_CLIENT_ID` and encrypted `GITHUB_CLIENT_SECRET`; PAT works without these. See [OAuth setup and CLI fallback](docs/github-oauth.md) if Pages dashboard runtime editing is disabled. **Silent SSO requires a first-party HTTPS custom domain.** The proposed/default origin is `https://gitplus.gothwadtech.com`; configure that domain in Pages before production use. `pages.dev`, localhost and Arena preview domains cannot receive `.gothwadtech.com` cookies. They deliberately show a setup message, not fake authentication. The custom domain is configured in source but has **not** been provisioned or deployed by this repair. @@ -73,14 +74,15 @@ CI has a separate browser job that installs Chromium and runs these checks. `PLA | Runtime `GITPLUS_ORIGIN` | `https://gitplus.gothwadtech.com` (change if using another first-party subdomain) | | Runtime `ACCOUNTS_API_ORIGIN` | `https://api.gothwadtech.com` | | Functions | Root `functions/` must be deployed with the app | -| Secrets / new database | None for this Accounts-cookie integration | +| OAuth runtime credentials | `GITHUB_CLIENT_ID`, encrypted `GITHUB_CLIENT_SECRET`; never `VITE_*` | +| New database | None | -Values above are non-secret runtime variables, already declared in `wrangler.jsonc`. Do not upload only the static `dist` directory through a method that omits Functions. See [deployment instructions](docs/cloudflare-pages.md). +The two origins are non-secret runtime variables already declared in `wrangler.jsonc`. OAuth credentials must be configured separately; no real secret is checked in. Do not upload only the static `dist` directory through a method that omits Functions. See [deployment instructions](docs/cloudflare-pages.md). ## Project layout ```text -functions/api/[[path]].ts Same-origin session route + JSON API 404s +functions/api/[[path]].ts Session, OAuth and explicit sign-out routes + JSON API 404s server/accountsSession.ts Accounts verification and cookie/public-profile filtering shared/ Product identity and shared Accounts contract src/ @@ -88,7 +90,7 @@ src/ components/accounts/ Gothwad login gate and account menu services/accounts/ Abortable single-flight session client services/github.ts GitHub API and non-forced batch sync - utils/ Owner-bound PAT, ZIP, encoding and storage helpers + utils/ Owner-bound GitHub token, ZIP, encoding and storage helpers public/ _headers, _routes.json, favicon, robots.txt docs/ Product plan, integration research and operations tests/ Regression tests with mocked upstream services @@ -102,7 +104,7 @@ Generated `dist/`, `.wrangler/`, dependencies, `.env*` and `.dev.vars*` are not - Signed-in Accounts identity is rechecked on startup, on visible-tab intervals and focus; no persistent profile acts as authentication. - Switching Gothwad users clears the GitHub connection and invalidates in-flight operations. A late response cannot sign a new user in as the previous one. -- “Disconnect GitHub” and “Sign out of GitPlus (this tab)” are distinct. Global Gothwad sign-out is managed on Accounts; GitPlus does not silently sign Mail/Drive/Store out. +- “Disconnect GitHub” and “Sign out of GitPlus (this tab)” are distinct. The **actual hosted universal Accounts menu** supports explicitly confirmed ecosystem sign-out and local-only sign-out. Read-only checks never silently sign Mail/Drive/Store out. - ZIP paths are preserved by default; optional wrapper removal strips one outer directory only. Review all paths/deletions before syncing. - Batch sync requires an initialized branch, never force-pushes and aborts on partial upload failures. Start with a disposable repository. @@ -111,6 +113,7 @@ Generated `dist/`, `.wrangler/`, dependencies, `.env*` and `.dev.vars*` are not - [Product identity and phased roadmap](docs/product-roadmap.md) - [Accounts research, contract and implementation](docs/gothwad-accounts.md) - [Cloudflare deployment and rollout checklist](docs/cloudflare-pages.md) +- [GitHub OAuth App, scopes and runtime secrets](docs/github-oauth.md) - [Architecture](docs/architecture.md) - [Security and permissions](docs/security.md) - [Audit and remaining limitations](docs/audit.md) diff --git a/docs/README.md b/docs/README.md index 089087b..1f360b7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,8 +7,9 @@ | [Product roadmap](product-roadmap.md) | Canonical naming, phases, completed implementation and remaining work | | [Gothwad Accounts](gothwad-accounts.md) | Source-pinned Accounts/Mail/Store/Drive findings, SSO decisions and API contract | | [Cloudflare Pages](cloudflare-pages.md) | Functions, runtime variables, first-party domain and deployment acceptance tests | +| [GitHub OAuth](github-oauth.md) | OAuth App registration, runtime-secret CLI fallback, local storage, scopes and callback security | | [Architecture](architecture.md) | Runtime boundaries and code ownership | -| [Security](security.md) | Accounts cookies versus GitHub PATs, scopes, ZIP safety and hosting defenses | +| [Security](security.md) | Accounts cookies versus GitHub OAuth/PATs, scopes, ZIP safety and hosting defenses | | [Audit](audit.md) | Initial repository repair, current verification and known limitations | -Deployment is **Pages + Functions**, not static-only. No new database or login secret is needed for first-party Accounts-cookie SSO. Runtime origins are public configuration; never expose credentials through `VITE_*` variables. +Deployment is **Pages + Functions**, not static-only. No new database or login secret is needed for first-party Accounts-cookie SSO. GitHub OAuth separately requires its runtime client credentials (PAT remains available without them). Runtime origins are public configuration; never expose credentials through `VITE_*` variables. diff --git a/docs/architecture.md b/docs/architecture.md index 38fe544..f8854da 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,12 +8,14 @@ GitPlus is a Gothwad Tech product. Its identity provider is Gothwad Accounts; Gi Cloudflare Pages: dist/ static React app /api/* -> root Pages Function /api/session -> verified Accounts cookie session -> public identity only + /api/github/* -> OAuth App state, callback and code exchange (no token vault) + /api/accounts/signout[-all] -> explicit, verified universal-menu mutations other paths -> JSON 404 Browser after verified Accounts identity - -> GitHub REST API using the separately connected GitHub PAT + -> GitHub REST API using the separately connected OAuth token or PAT -> JSZip + Web Crypto for local ZIP comparison - -> sessionStorage: owner-bound GitHub PAT, account selector, local sign-out marker + -> sessionStorage: owner-bound GitHub token, short-lived OAuth verifier, account selector, local sign-out marker -> localStorage: non-secret appearance/editor preferences only ``` @@ -26,6 +28,10 @@ No new database, AI backend, Express server or self-issued Gothwad login token e | `shared/brand.ts` | GitPlus / Gothwad Tech public identity and default first-party domains | | `shared/accounts.ts` | Public identity types, schema normalization, safe return URL and selectors | | `functions/api/[[path]].ts` | Pages route dispatch; no accidental SPA fallback for API requests | +| `server/githubOAuth.ts`, `server/protectedRequest.ts` | Exact-origin JSON/Accounts verification, encrypted transaction cookie, S256 PKCE, fixed provider exchange | +| `server/accountActions.ts` | Narrow, explicit sign-out routes; approved rotations/deletions only | +| `src/services/githubOAuth.ts` | Same-tab verifier, single-flight completion and owner/generation guards | +| `src/services/accounts/accountWidget.ts`, `AccountsBar.tsx` | Real hosted universal menu, sanitized state and guarded callbacks | | `server/accountsSession.ts` | Trusted upstream request, cookie filtering, timeout, public-profile projection, no-store responses | | `src/services/accounts/sessionClient.ts` | Single-flight, selector-keyed, abortable session requests; explicit error states | | `src/context/AccountsContext.tsx` | Automatic session boot/revalidation, account switching, local sign-out pause, generation isolation | @@ -33,7 +39,7 @@ No new database, AI backend, Express server or self-issued Gothwad login token e | `src/App.tsx` | Verified user's GitHub workspace; lazy-loaded tabs and overlays | | `src/components/AuthScreen.tsx` | **Connect GitHub**, not the product identity login | | `src/services/github.ts` | GitHub REST API, cancellable request generations, live trees, pagination, batch commits | -| `src/utils/tokenStorage.ts` | Session-only PAT with verified Gothwad user ID ownership; unbound legacy tokens removed | +| `src/utils/tokenStorage.ts` | Session-only OAuth token/PAT with verified Gothwad user ID ownership; unbound legacy tokens removed | | `src/utils/zipParser.ts`, `paths.ts`, `encoding.ts` | ZIP byte budgets, path safety and byte-exact Git SHA/Base64 | | `src/components/ErrorBoundary.tsx` | Reload recovery on render failure | @@ -54,7 +60,7 @@ No local profile/cookie decoding is considered proof of authentication. The UI h A temporary identity-service outage blocks the workspace and invalidates pending GitHub calls without deliberately deleting the same-owner PAT. Successful revalidation can restore that connection. An identity change or local sign-out deletes the old connection. Unsaved UI/draft state is not durable and can reset when the gate closes. -The implementation does not introduce a global account-menu script or widen CSP to external scripts: its local account menu uses Accounts-derived, sanitized metadata. Global account management stays on Accounts. +The app imports the actual `https://accounts.gothwadtech.com/widget/account-menu.js` ES module and relative template/style modules. CSP permits only that external script directory. Its state is sanitized; callbacks use GitPlus verification/switching and protected sign-out routes instead of raw `/auth/me`. This shared script is trusted app code with access to local GitHub tokens, not a sandbox. Load failure shows a management link, not a cloned menu. See [OAuth protocol](github-oauth.md) and [security](security.md). ## Tooling diff --git a/docs/audit.md b/docs/audit.md index 0b1520e..83f0b6b 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -55,7 +55,7 @@ No real GitHub write/delete/merge operations or Cloudflare account deployment ar ## Current known limitations / next work -- Gothwad Accounts SSO and its read-only backend adapter are now implemented. GitHub authorization remains PAT-based; a server-side GitHub App/OAuth credential flow and vault are not implemented. +- Accounts SSO, OAuth App + PAT and the actual shared account menu are implemented. No token vault/D1 is intended. Runtime OAuth credentials and live first-party/provider acceptance remain operator work; see [setup](github-oauth.md). - GitHub Actions log redirects and private raw-file/image downloads may fail in a browser because of CORS or authorization. Opening the resource on GitHub is the safe fallback; do not paste tokens into raw URLs. - Empty repositories need an initial commit before batch ZIP sync. Large/truncated recursive trees are blocked instead of partially compared. A full subtree traversal workflow is future work. - Repository lists paginate; several other endpoint lists (branches, releases, issues, PR files, jobs, etc.) still return a limited page. Full pagination/UI for all endpoints remains to be implemented. @@ -72,4 +72,14 @@ Run `npm ci && npm run check` for current results. The expanded suite checks the The initial 20-test count above describes the earlier repair, not the expanded suite. Real Accounts cookie acceptance across products, DNS/custom-domain provisioning and live GitHub writes still require the operator's staging checklist. No deployment or modification to Accounts/Mail/Store/Drive was made here. -Latest local follow-up checks: **40 regression tests passed**, **3 Playwright browser tests passed**, TypeScript and production build passed, Pages Functions compiled, and `npm audit --audit-level=moderate` reported **0 known vulnerabilities**. Browser checks cover automatic existing-session recognition, GitHub owner isolation on account switch, local sign-out across reload, return/error behavior without redirect loops, and the real local Functions unsupported-domain/JSON-404 responses. Upstream identity/GitHub responses are mocked in the authenticated browser cases; this does not claim live Accounts SSO is deployed. +Previous SSO-only follow-up checks: **40 regression tests passed**, **3 Playwright browser tests passed**, TypeScript and production build passed, Pages Functions compiled, and `npm audit --audit-level=moderate` reported **0 known vulnerabilities**. Browser checks cover automatic existing-session recognition, GitHub owner isolation on account switch, local sign-out across reload, return/error behavior without redirect loops, and the real local Functions unsupported-domain/JSON-404 responses. Upstream identity/GitHub responses are mocked in the authenticated browser cases; this does not claim live Accounts SSO is deployed. + +## OAuth App + universal menu verification (2026-10-24) + +- Implemented the accepted OAuth App + PAT design: mandatory Accounts identity, base scopes plus explicit optional `delete_repo`, same-tab S256 PKCE, encrypted ten-minute transaction cookie, verified-owner callback/completion and local owner-bound session storage. No D1, refresh-token persistence, GitHub App installation flow or cross-device sync. +- Replaced the local menu with the actual Accounts-hosted universal module. Explicit slot/global sign-out uses narrowly routed, origin-checked, verified mutations; local GitPlus sign-out stays local. CSP and the trusted-script supply-chain boundary are documented. +- **52 unit/regression tests passed**, including state/PKCE/owner rejection, expiry/tampering, secret rotation, one-use exchange failure, sign-out and widget loader contracts. +- **8 Playwright browser tests passed** with real built Pages assets, pinned actual widget modules and mocked Accounts/GitHub: OAuth completion/reload/disconnect, PAT fallback, denial, widget mutation/failure and stale completion after a Gothwad account switch, plus existing SSO/isolation tests. +- 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. diff --git a/docs/cloudflare-pages.md b/docs/cloudflare-pages.md index 50770fb..3c713f6 100644 --- a/docs/cloudflare-pages.md +++ b/docs/cloudflare-pages.md @@ -13,7 +13,7 @@ npm run check This runs regression tests, TypeScript, Vite (`dist/`) and Pages Functions compilation (`.wrangler/functions-build/`). Do not commit either output directory. npm is the only lockfile source of truth. -Current work is on `arena/9559f2f5-gitplus`. A Pages project building `main` will not receive these changes until they are merged/pushed to that release branch. No changes have been pushed or deployed by this implementation. +A Pages project building `main` receives changes after the implementation PR is merged. Verify the deployed commit in Pages rather than assuming a successful local build means production is updated. ## 2. Pages Git integration @@ -33,7 +33,7 @@ Create/connect a **Pages** project, not a plain Worker application: - `GITPLUS_ORIGIN=https://gitplus.gothwadtech.com`: exact trusted HTTPS origin for the app. It must be a subdomain of `gothwadtech.com` with no path/port. This is the **proposed/default host**, not proof of existing DNS. - `ACCOUNTS_API_ORIGIN=https://api.gothwadtech.com`: dedicated API Worker origin for server-to-server requests. Do not accidentally point it at a static Accounts Pages frontend. -No new D1/R2 binding, `JWT_SECRET`, `MAIL_INTERNAL_TOKEN`, OAuth client secret or GitHub PAT is required. 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. +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. ## 3. First-party custom domain (required for real SSO) @@ -71,7 +71,7 @@ Optional second terminal: npm run dev # Vite at 0.0.0.0:3000, /api proxy -> localhost:8788 inside server ``` -Browser code only calls relative `/api/session`; it never calls the user's browser `localhost` for a separate backend. Vite allows Arena `.e2b.app` preview hosts. Local SSO returns `unsupported` by design; unit/browser tests use mocked responses without a runtime bypass. Test real SSO on a first-party staging domain. +Browser code calls relative `/api/session`, `/api/github/*` and `/api/accounts/*`; it never calls the user's browser `localhost` for a separate backend. Vite allows Arena `.e2b.app` preview hosts. Local SSO returns `unsupported` by design; unit/browser tests use mocked responses without a runtime bypass. Test real SSO on a first-party staging domain. `npm run preview` serves only Vite assets and cannot alone validate Functions. `_headers` are interpreted by Pages/Wrangler, not Vite. The local runtime may warn when blocked sandbox internet prevents fetching Cloudflare's optional `Request.cf` placeholder; this does not replace live deployment testing. @@ -102,6 +102,12 @@ Browser code only calls relative `/api/session`; it never calls the user's brows ### GitHub and UI +- [ ] Register the OAuth App with exact `/api/github/callback`, configure runtime credentials, redeploy and verify `/api/github/config` reports `enabled: true` without exposing secrets. +- [ ] Test Connect with GitHub success, cancelled consent, expired state, wrong tab and account switch while completing; the local token must remain owner-bound. +- [ ] Confirm no tokens appear in frontend URLs, permanent storage or server logs. Reconnect separately on another device. +- [ ] Test the optional deletion consent on a disposable repository; base scopes cannot bypass GitHub/org/branch policies. +- [ ] Load the real Accounts-hosted universal menu and its modules with CORS/CSP; test switch, add/manage account, slot/global sign-out, local-only sign-out and blocked-module fallback. + - [ ] Use a disposable repository and an expiring least-privilege PAT. Browse/edit an empty file and refresh the live tree. - [ ] Compare a ZIP containing `README.md`, `docs/`, `public/` and nested `src/`. Paths are preserved; wrapper stripping is opt-in. - [ ] Confirm selected deletions, protected-branch rejection and non-fast-forward errors; do not force overwrite the branch. @@ -117,7 +123,10 @@ Browser code only calls relative `/api/session`; it never calls the user's brows | `accounts_not_json` / `accounts_redirect` | API origin/Worker routing is incorrect; Accounts login frontend is not the API backend. | | Anonymous after Accounts handoff | Inspect cookie domain/Secure/path, chosen slot, exact app origin and provider availability; do not retry by automatic redirects. | | Account no longer available | Provider fell back from a missing selector; GitPlus rejected it. Choose an account again. | -| GitHub 401 / 403 / 404 | Separate from Gothwad login: check PAT expiry, repo access, organization SSO/approval, branch and rate limits. | +| GitHub 401 / 403 / 404 | Separate from Gothwad login: check OAuth/PAT expiry, repo access, organization SSO/approval, branch and rate limits. | +| OAuth unavailable | Check runtime credentials on the deployed Function, not only build-time variables; use the CLI fallback above. | +| OAuth invalid/expired attempt | Start again in the same tab/account; concurrent attempts can replace the shared transaction cookie. | +| Universal menu fails to load | Check canonical Accounts widget availability, module CORS and static CSP; use the visible management link meanwhile. | | Empty-repo ZIP sync fails | Add an initial README commit first. | | Actions logs/raw files fail | Browser CORS or GitHub authorization limitation; use the resource on GitHub. | diff --git a/docs/github-oauth.md b/docs/github-oauth.md new file mode 100644 index 0000000..9838128 --- /dev/null +++ b/docs/github-oauth.md @@ -0,0 +1,69 @@ +# GitHub OAuth App + local connection + +GitPlus is a Gothwad Tech product. **Gothwad Accounts sign-in is mandatory.** GitHub authorization is a separate connection: use **Connect with GitHub** or the existing PAT form. This is an **OAuth App**, not a GitHub App installation/selected-repository flow. + +## Administrator setup on Cloudflare Pages + +1. In GitHub developer settings, register an **OAuth App**: + - Application name: `GitPlus by Gothwad Tech` + - Homepage URL: `https://gitplus.gothwadtech.com` + - Authorization callback URL: **`https://gitplus.gothwadtech.com/api/github/callback`** + - No device flow or webhook is needed. +2. Record the Client ID and generate a Client Secret privately. Do not paste the secret into chat, source, logs or screenshots. +3. Configure **Pages Functions runtime** bindings `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`. The ID is public configuration; the secret must be an encrypted secret. Neither uses a `VITE_` prefix. +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. + +### 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. + +From this checkout on your own Cloudflare-authenticated machine: + +```sh +npm ci +npx wrangler login +npx wrangler pages secret put GITHUB_CLIENT_ID --project-name gitplus +npx wrangler pages secret put GITHUB_CLIENT_SECRET --project-name gitplus +npx wrangler pages secret list --project-name gitplus +``` + +Replace `gitplus` if your actual Pages project name differs. Each `put` prompts for the value locally; do **not** append it as a shell argument. Setting the public Client ID using the secret command is supported and avoids dashboard-editing restrictions. The pinned Wrangler command supports `--project-name`; do not copy a Workers-specific `--env` flag into these Pages commands. + +Redeploy the intended production branch through Pages Git integration after merge (or use the Pages deploy procedure in [the hosting guide](cloudflare-pages.md)). Verify the deployed custom-domain endpoint, not just the build log. Check production/preview scope in your project's configuration; avoid distributing production credentials to untrusted preview code. If Cloudflare reports a permission error, fix your Cloudflare project/account permissions rather than placing the secret in build-time JavaScript. + +Missing runtime credentials disable the OAuth button with an explanation. **PAT remains usable after Gothwad login.** No real OAuth App credentials were configured as part of this implementation. + +## Access and consent + +Requested base scopes: + +```text +repo workflow gist read:user user:email read:org +``` + +The separate, unchecked-by-default deletion checkbox adds `delete_repo`. These are deliberately broad OAuth scopes, as requested; they are not limited to selected repositories. They still cannot bypass repository roles, protected branches, organization OAuth restrictions, SAML SSO, rate limits or unsupported browser API behavior. No unrelated organization/key/admin scopes are requested. + +GitHub may retain previously granted permissions. **Unchecking deletion is not revocation or a guaranteed scope downgrade.** Review/revoke the app under GitHub Settings → Applications → Authorized OAuth Apps, then reconnect if you need to remove an older grant. A fine-grained, expiring PAT remains the narrower-access alternative. + +## Local persistence and revocation + +- OAuth tokens and PATs share the existing owner-bound `gitplus_github_connection` storage: memory plus this tab's `sessionStorage`, never deliberately permanent `localStorage`. +- There is **no D1, central token vault, cross-device connection sync or refresh-token persistence**. Connect separately on another device. If a token expires or is revoked, reconnect. +- Disconnect GitHub removes the local connection; it does not revoke the OAuth App grant or PAT at GitHub. Local GitPlus sign-out and Gothwad ecosystem sign-out are separate actions. +- Browser session restore/duplicated tabs can retain session storage. This is not an encrypted vault. XSS, a compromised deployment or a trusted script can read these tokens; see [security](security.md). +- The access token passes through the Pages completion response once, with private/no-store headers. It is not persisted server-side. Never enable request/response-body logging on these routes. + +## Protocol and security checks + +1. The browser generates a random same-tab verifier and S256 challenge. `POST /api/github/start` requires exact same-origin JSON and a verified Gothwad account. It returns only the authorization URL/state/owner ID. +2. A random state, challenge, stable account ID/slot, client ID and ten-minute expiry are sealed into `__Host-gitplus_oauth` with AES-GCM. Its encryption key is HKDF-derived from the runtime client secret, app origin and a purpose-specific label. The cookie is Secure, HttpOnly, SameSite=Lax, host-only and Path=/. +3. GitHub's callback must match the sealed state and reverified owner. The code is sealed into the short-lived cookie; the 303 redirect uses a fixed frontend origin and status marker, **not an access token or code in the frontend URL**. The incoming provider callback necessarily contains the one-use code; avoid logging callback query strings. +4. The originating tab POSTs its verifier/state to `/api/github/complete`. The Function verifies PKCE, expiry and owner again, then exchanges the code only at GitHub's fixed token endpoint, with a timeout and redirects disabled. GitHub's single-use code is the replay barrier; no database is introduced. +5. The browser validates the response owner and current connection generation before saving the token. Concurrent completion calls are shared; switching/signing out invalidates old results. Callback status parameters and pending verifier state are removed. + +One OAuth transaction cookie exists per browser origin: simultaneous connection attempts in multiple tabs can supersede each other. Finish one at a time; retries are safe. Secret rotation invalidates pending transactions, requiring a new attempt. Blocked session storage prevents OAuth from starting; PAT can still use the existing memory fallback. + +## 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. diff --git a/docs/gothwad-accounts.md b/docs/gothwad-accounts.md index 3f1c465..1ca8bec 100644 --- a/docs/gothwad-accounts.md +++ b/docs/gothwad-accounts.md @@ -20,7 +20,7 @@ No files in those repositories were edited or pushed. GitPlus does not need thei 1. `GET /api/auth/me` returns `authenticated`, `user`, `activeId`, `authuser`, `accounts`. **It may also return raw Accounts access/refresh tokens.** GitPlus must never transparently proxy its JSON body to the browser. Our adapter emits only allowlisted identity fields (ID, username, display name, derived email, public account slots). 2. The API can rotate session credentials during a read. Dropping valid `Set-Cookie` headers can break subsequent login. GitPlus relays only recognized `gothwad_*` cookies with `Secure`, `HttpOnly`, `SameSite=Lax`, `Path=/`, and the exact shared domain. 3. The current `resolveSession` falls back to the first live slot if an explicit selector is missing. **GitPlus rejects a mismatched requested slot/index** rather than silently logging into a different account. After verification it pins stable slot `a`–`f`, not a shifting list index. -4. Accounts' anonymous `/auth/me` path can clear all browser slot cookies. A read-only GitPlus check must not unexpectedly sign out Mail/Store/Drive; those anonymous deletion headers are not propagated. Explicit global logout remains on Accounts. +4. Accounts' anonymous `/auth/me` path can clear all browser slot cookies. A read-only GitPlus check must not unexpectedly sign out Mail/Store/Drive; those anonymous deletion headers are not propagated. Only explicitly confirmed menu mutations may relay deletion cookies; read-only failures still cannot globally log users out. 5. Server-to-server calls use the actual Accounts API Worker custom domain, default `https://api.gothwadtech.com/api/auth/me`, not a static frontend URL that could answer HTML. Redirects are not followed. ## Chosen architecture @@ -37,7 +37,7 @@ GitPlus browser on https://gitplus.gothwadtech.com validate authenticated user + selected slot return sanitized identity + allowlisted HttpOnly cookie rotations - Verified Gothwad user ID -> separate owner-bound GitHub PAT -> api.github.com + Verified Gothwad user ID -> separate owner-bound GitHub OAuth token or PAT -> api.github.com ``` Using a first-party Pages Function avoids browser third-party-cookie/CORS dependencies and avoids exposing the raw Accounts response. It adds **no** new identity database or locally minted login token. @@ -56,12 +56,21 @@ Using a first-party Pages Function avoids browser third-party-cookie/CORS depend | Action | Effect | | --- | --- | -| Disconnect GitHub | Clear the current PAT and GitHub UI; remain signed in to Gothwad Accounts. | +| Disconnect GitHub | Clear the local OAuth token/PAT and GitHub UI (not the GitHub grant); remain signed in to Gothwad Accounts. | | Sign out of GitPlus (this tab) | Clear GitHub connection, gate workspace, persist a tab-local pause marker; no Accounts mutation. “Continue to GitPlus” re-verifies Accounts. | | Switch Gothwad account | Confirm loss of unsaved work, clear GitHub connection, verify the selected stable slot. | -| Manage Gothwad Account / global sign-out | Open Accounts' own account UI. Global logout is explicit and controlled there. Other GitPlus tabs notice on a subsequent session check. | +| Manage Gothwad Account | Open Accounts' own account management UI. | +| Universal menu: sign out one/all accounts | Confirm ecosystem-wide sign-out, then use a same-origin protected route. Other tabs notice on a subsequent session check. | -The local pause is not provider revocation. No automatic sign-out-all POST is implemented or disguised as a local action. +The local pause is not provider revocation. No automatic sign-out-all POST is made or disguised as a local action. + +## Actual universal account menu + +GitPlus imports `https://accounts.gothwadtech.com/widget/account-menu.js`, the same shared widget used by the ecosystem—not a local lookalike. Source research also inspected Mail's `src/services/accountWidget.ts`, Store's `shared/AccountMenu.tsx` and Drive's `lib/accountMenuWidget.ts` at the pinned commits above. The loader shares in-flight imports, validates the exported API and times out after five seconds. Public stable slots map to widget IDs. It updates for theme/account changes and closes on owner changes/unmount. + +All mutation callbacks are overridden: switching uses the existing tab-local verified selector; sign-out POSTs require exact app Origin, JSON, verified identity and an available target slot. The fixed upstream routes are `/api/auth/accounts/{a-f}/signout` and `/api/auth/signout`. No arbitrary proxy or raw identity auto-SSO is exposed. Add-account uses a safe first-party return URL. Load failure offers an honest management link/local sign-out, not another menu implementation. + +The hosted widget executes as trusted app code; CSP explicitly permits its module directory. See the [supply-chain boundary](security.md). Test fixtures pin the actual three upstream modules, but production always imports the canonical hosted widget. ## `/api/session` contract @@ -94,8 +103,8 @@ All Function responses explicitly set private/no-store caching and restrictive J ## Security boundaries / what this does not do - Gothwad authentication is not GitHub authorization. Connecting GitHub still requires consent/permissions from GitHub; no token can be derived from a Gothwad cookie or email. -- The UI gate is not server-side authorization for GitHub writes: those go directly to GitHub and are authorized by GitHub's PAT. Anyone holding a valid PAT can call GitHub independently. Future product APIs must verify Accounts server-side on **every** protected request. -- GitHub PATs remain JavaScript-readable session credentials. The owner tag prevents accidental cross-account reuse; it is not cryptographic proof of ownership or protection against same-origin XSS. +- The UI gate is not server-side authorization for GitHub writes: those go directly to GitHub and are authorized by GitHub's OAuth token/PAT. Anyone holding a valid PAT can call GitHub independently. Future product APIs must verify Accounts server-side on **every** protected request. +- GitHub OAuth tokens/PATs remain JavaScript-readable session credentials. The owner tag prevents accidental cross-account reuse; it is not cryptographic proof of ownership or protection against same-origin XSS. - Aborting a request cannot undo a write GitHub already accepted. Epoch checks stop later steps/retries from continuing under a newly bound account. - Cross-tab refresh races are ultimately owned by Accounts. GitPlus deduplicates its own requests and relays rotations; it cannot guarantee upstream refresh behavior across every ecosystem tab. - `pages.dev`, Arena and localhost do not support this shared-domain cookie flow. An external-domain/native product would need separately registered OAuth + S256 PKCE, exact redirects and a reviewed server session flow. No placeholder OAuth client was invented here. diff --git a/docs/product-roadmap.md b/docs/product-roadmap.md index f1afa8d..ce1b95a 100644 --- a/docs/product-roadmap.md +++ b/docs/product-roadmap.md @@ -18,13 +18,13 @@ | 2. First-party Accounts SSO | Read-only Pages session adapter; HttpOnly cookie verification; public-profile projection; automatic existing-session recognition | Implemented; local unit/runtime tests, live deployment still pending | | 3. Account isolation and lifecycle | Stable slot selector, user-ID-bound GitHub connection, abort/epoch guards, retry and separate local/global sign-out | Implemented; regression-tested | | 4. Deployment verification | Functions bundle, no-store API, visible preview restriction, regression/browser tests | Local checks implemented; operator acceptance on a real staging domain remains required | -| 5. GitHub authorization upgrade | GitHub App (preferred) or server-side OAuth, installation/repo selection, secure callback/state, revocation, encrypted credential storage | Planned; needs GitHub App registration and server-side storage/security design | +| 5. GitHub authorization + universal menu | OAuth App + PAT, broad scopes and optional deletion, state/S256 PKCE, local owner-bound token; actual Accounts-hosted menu | Implemented and tested; runtime OAuth credentials/live operator acceptance remain required | | 6. Workspace reliability | All-endpoint pagination, stale-diff conflict detection, executable/symlink handling, drafts scoped by account/repo, coherent editor preferences | Planned; see current limitations in audit | | 7. Product quality | Keyboard/dialog accessibility, responsive end-to-end coverage, observability without secrets, recovery UX, release checks | Planned | -Phases 2–3 deliberately do **not** add a GitHub token vault, automatic PAT sharing across devices, or a duplicate Gothwad login database. Those would change the security boundary and need a separate reviewed design. +The accepted design deliberately adds **no D1/token vault or cross-device sync**. GitHub App installation/selected-repository selection was rejected in favor of an OAuth App with broad consent. Local session storage remains the connection model; reconnect on each device. PAT remains an alternative. -## Release acceptance before moving to Phase 5 +## Live release acceptance 1. Connect a first-party staging domain to this Pages project and set `GITPLUS_ORIGIN` to that exact origin. 2. Verify sign-in once on Accounts automatically opens GitPlus's GitHub connection screen; no Accounts token appears in JavaScript-readable storage or JSON. @@ -32,6 +32,7 @@ Phases 2–3 deliberately do **not** add a GitHub token vault, automatic PAT sha 4. Verify silent session refresh keeps Accounts cookies working across Mail, Store and Drive. Rejected selectors must not log those products out. 5. Exercise timeout, HTML routing error, 429, expired login and a return without cookies. None may become an automatic redirect loop. 6. Check local sign-out, GitHub-only disconnect, and explicit global Accounts sign-out independently. -7. Complete the disposable-repository write tests in the Pages guide before important repositories are used. +7. Configure OAuth runtime credentials using [the CLI fallback](github-oauth.md) if needed, and verify real consent/cancellation plus the hosted universal menu. +8. Complete the disposable-repository write tests in the Pages guide before important repositories are used. No external deployment, DNS change, Accounts migration or GitHub App registration was performed as part of this source implementation. diff --git a/docs/security.md b/docs/security.md index f446bd8..73c0066 100644 --- a/docs/security.md +++ b/docs/security.md @@ -14,9 +14,9 @@ GitPlus is a Gothwad Tech product. Product sign-in uses the existing first-party ## GitHub credentials (separate connection) -GitHub repository permissions still use a separately supplied PAT. Gothwad login does not authorize a GitHub account or derive a GitHub credential. +GitHub repository permissions use a separately consented OAuth App token or supplied PAT. Gothwad login does not authorize a GitHub account or derive a GitHub credential. -- PATs are sent in Authorization headers only to GitHub's API. The request helper refuses other origins. +- Stored OAuth tokens/PATs are sent in Authorization headers only to GitHub's API. The request helper refuses other origins. - The current connection is stored in memory and tab `sessionStorage` under `gitplus_github_connection`, with the verified Gothwad user ID. It is never deliberately written to permanent `localStorage`. - Legacy unbound PAT copies in local/session storage are removed, not assigned to whichever Gothwad user logs in first. - Switching Gothwad users or locally signing out clears the old connection, aborts pending GitHub requests and invalidates multi-step batch generations. Already accepted upstream writes cannot be undone by aborting. @@ -24,7 +24,13 @@ GitHub repository permissions still use a separately supplied PAT. Gothwad login - Session storage is **not encrypted** and remains accessible to same-origin JavaScript. XSS, extensions or a compromised deployment can steal the PAT. The owner tag prevents accidental credential reuse, not malicious storage tampering or exfiltration. - Browser session restore and duplicated tabs may preserve session storage. Local sign-out affects this tab; it does not revoke the PAT or globally sign out Gothwad. Revoke compromised credentials with their provider. - Never put PATs/Accounts tokens in source, Pages environment variables, `VITE_*`, screenshots or logs. Origin configuration is public; credentials are not. -- Global Accounts logout remains an explicit action in Accounts. A failed GitPlus identity read does not propagate Accounts' sign-out-all cookie deletions to Mail/Store/Drive. +- The real universal menu can explicitly sign out one/all Gothwad accounts through narrow, exact-origin JSON POST routes that verify the current account and target slot. Confirmations distinguish ecosystem logout from local GitPlus sign-out. A failed GitPlus identity read does not propagate Accounts' sign-out-all cookie deletions to Mail/Store/Drive. + +## OAuth App security + +The base OAuth scopes are `repo workflow gist read:user user:email read:org`; `delete_repo` is requested only with the separate checkbox. Previously granted permissions must be revoked at GitHub, not merely unchecked. These broad grants never bypass user roles, organization approval/SSO or protected branches. The PAT alternative offers narrower repository-level control. + +The Pages runtime secret never enters the frontend bundle. Start/complete use exact-origin JSON POSTs and verified Accounts identity. A ten-minute encrypted HttpOnly host-only cookie binds state, S256 PKCE challenge, account owner/slot and client ID; the callback checks state/owner, and completion requires the same-tab verifier. Token exchange uses a fixed GitHub URL with no redirects, timeouts and no-store responses. GitHub consumes the code once. No D1 or refresh-token persistence is added. Never log callback query strings or OAuth bodies. See [protocol, CLI configuration and revocation](github-oauth.md). ## Least privilege @@ -59,6 +65,6 @@ Token support varies by endpoint and organization policy. Organization tokens ma ## Hosting defenses -`public/_headers` defines a restrictive CSP, `nosniff`, no-referrer, disabled camera/microphone/geolocation and caching rules. Production pages cannot be embedded. Inline styles remain allowed for React layout/progress styles; inline scripts and `eval` are not allowed. External script CDNs are not used. Google Fonts and GitHub images/API are narrowly allowed. +`public/_headers` defines a restrictive CSP, `nosniff`, no-referrer, disabled camera/microphone/geolocation and caching rules. Production pages cannot be embedded. Inline styles remain allowed for React layout/progress styles; inline scripts and `eval` are not allowed. The only allowed external script source is the canonical Accounts `/widget/` directory for the **actual universal account menu**. Its ES module and relative imports require CORS. It runs with GitPlus privileges and can read JavaScript-accessible GitHub tokens; trusting it is an explicit first-party supply-chain boundary, not isolation. Production uses the hosted module, not a vendored copy; pinned fixtures are test-only. Google Fonts and GitHub images/API are narrowly allowed. Headers are defense-in-depth, not proof that the app is immune to XSS or dependency attacks. Run `npm audit`, review dependency updates, restrict who can deploy, use HTTPS and test the real Pages headers. Do not cache private API responses in a service worker or add an unauthenticated proxy to work around CORS. diff --git a/functions/api/[[path]].ts b/functions/api/[[path]].ts index 6320302..c035c14 100644 --- a/functions/api/[[path]].ts +++ b/functions/api/[[path]].ts @@ -1,7 +1,11 @@ -import { handleSession, sessionJson, type SessionEnv } from '../../server/accountsSession'; +import { handleSession, sessionJson } from '../../server/accountsSession'; +import { handleGitHubOAuth, type GitHubOAuthEnv } from '../../server/githubOAuth'; +import { handleAccountAction } from '../../server/accountActions'; -// Pages Functions owns only /api/*; unknown API paths must be JSON 404s, never SPA HTML. -export function onRequest(context: { request: Request; env: SessionEnv }): Promise | Response { - if (new URL(context.request.url).pathname !== '/api/session') return sessionJson({ error: 'not_found' }, 404); - return handleSession(context.request, context.env); +export function onRequest(context: { request: Request; env: GitHubOAuthEnv }): Promise | Response { + const path = new URL(context.request.url).pathname; + if (path === '/api/session') return handleSession(context.request, context.env); + if (['/api/github/config', '/api/github/start', '/api/github/callback', '/api/github/complete'].includes(path)) return handleGitHubOAuth(context.request, context.env); + if (['/api/accounts/signout', '/api/accounts/signout-all'].includes(path)) return handleAccountAction(context.request, context.env); + return sessionJson({ error: 'not_found' }, 404); } diff --git a/public/_headers b/public/_headers index e8ce281..1baa814 100644 --- a/public/_headers +++ b/public/_headers @@ -2,7 +2,7 @@ X-Content-Type-Options: nosniff Referrer-Policy: no-referrer Permissions-Policy: camera=(), microphone=(), geolocation=() - Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://*.githubusercontent.com https://github.com; connect-src 'self' https://api.github.com https://*.githubusercontent.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' + Content-Security-Policy: default-src 'self'; script-src 'self' https://accounts.gothwadtech.com/widget/; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://*.githubusercontent.com https://github.com; connect-src 'self' https://api.github.com https://*.githubusercontent.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' / Cache-Control: no-cache diff --git a/server/accountActions.ts b/server/accountActions.ts new file mode 100644 index 0000000..6c0e154 --- /dev/null +++ b/server/accountActions.ts @@ -0,0 +1,31 @@ +import { BRAND } from '../shared/brand'; +import { firstPartyOrigin, record, validSelector } from '../shared/accounts'; +import { rotationCookies, type SessionEnv } from './accountsSession'; +import { clearOAuthCookie } from './githubOAuth'; +import { appOrigin, jsonResponse, postGuard, smallJson, verifiedAccount } from './protectedRequest'; + +/** Narrow, explicit universal-menu mutations, never an arbitrary Accounts proxy. */ +export async function handleAccountAction(request: Request, env: SessionEnv, fetcher: typeof fetch = fetch): Promise { + const guard = postGuard(request, env); + if (guard) return guard; + const body = await smallJson(request); + if (!body || !validSelector(body.selector)) return jsonResponse({ error: 'invalid_request' }, 400); + const path = new URL(request.url).pathname; + if (path !== '/api/accounts/signout' && path !== '/api/accounts/signout-all') return jsonResponse({ error: 'not_found' }, 404); + if (path.endsWith('/signout') && (typeof body.slot !== 'string' || !/^[a-f]$/.test(body.slot))) return jsonResponse({ error: 'invalid_slot' }, 400); + const account = await verifiedAccount(request, env, body.selector, fetcher); + if (!account.ok) return account.response; + if (path.endsWith('/signout') && !account.session.accounts.some((a) => a.slot === body.slot)) return jsonResponse({ error: 'account_not_available' }, 409, account.cookies); + const api = firstPartyOrigin(env.ACCOUNTS_API_ORIGIN || BRAND.accountsApiOrigin)!; + const endpoint = path.endsWith('/signout-all') ? '/api/auth/signout' : `/api/auth/accounts/${body.slot}/signout`; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 7000); + try { + const response = await fetcher(`${api}${endpoint}`, { method: 'POST', redirect: 'error', signal: controller.signal, + headers: { Accept: 'application/json', 'Content-Type': 'application/json', Cookie: account.cookieHeader, Origin: appOrigin(env)! }, body: '{}' }); + if (!response.ok || !response.headers.get('Content-Type')?.includes('application/json') || record(await response.json())?.ok !== true) return jsonResponse({ error: 'signout_failed', message: 'Accounts did not confirm sign-out. Please retry or manage your account on Accounts.' }, 502, account.cookies); + // Explicit user-approved mutations may relay deletion cookies (unlike a read-only probe). + return jsonResponse({ ok: true }, 200, [...account.cookies, ...rotationCookies(response.headers), clearOAuthCookie()]); + } catch { return jsonResponse({ error: 'accounts_unavailable', message: 'Accounts sign-out could not be confirmed. Please retry.' }, 503, account.cookies); } + finally { clearTimeout(timer); } +} diff --git a/server/githubOAuth.ts b/server/githubOAuth.ts new file mode 100644 index 0000000..f77261a --- /dev/null +++ b/server/githubOAuth.ts @@ -0,0 +1,112 @@ +import { record, validSelector } from '../shared/accounts'; +import { base64url, challengeFor, 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 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(); +function configured(env: GitHubOAuthEnv): boolean { + return typeof env.GITHUB_CLIENT_ID === 'string' && /^[A-Za-z0-9_.-]{1,100}$/.test(env.GITHUB_CLIENT_ID) && typeof env.GITHUB_CLIENT_SECRET === 'string' && env.GITHUB_CLIENT_SECRET.length >= 16; +} +function cookie(value: string, age = OAUTH_TTL_SECONDS): string { + return `${TRANSACTION_COOKIE}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${age}`; +} +export const clearOAuthCookie = () => cookie('', 0); +async function key(env: GitHubOAuthEnv): Promise { + const material = await crypto.subtle.importKey('raw', encoder.encode(env.GITHUB_CLIENT_SECRET!), 'HKDF', false, ['deriveKey']); + return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: encoder.encode(appOrigin(env)!), info: encoder.encode('GitPlus OAuth transaction v1') }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']); +} +function decode(value: string): Uint8Array { + const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/')); + return Uint8Array.from(binary, (c) => c.charCodeAt(0)); +} +async function seal(data: Transaction, env: GitHubOAuthEnv): Promise { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await key(env), encoder.encode(JSON.stringify(data))); + return `${base64url(iv)}.${base64url(new Uint8Array(encrypted))}`; +} +async function transaction(request: Request, env: GitHubOAuthEnv): Promise { + try { + const values = (request.headers.get('Cookie') || '').split(';').map((p) => p.trim()).filter((p) => p.startsWith(`${TRANSACTION_COOKIE}=`)); + if (values.length !== 1 || values[0].length > 3000) return null; + const [iv, body, extra] = values[0].slice(TRANSACTION_COOKIE.length + 1).split('.'); + if (!iv || !body || extra) return null; + const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decode(iv) }, await key(env), decode(body)); + const data = record(JSON.parse(new TextDecoder().decode(decrypted))); + if (!data || !validProof(data.state) || !validProof(data.challenge) || typeof data.owner !== 'string' || !validSelector(data.selector) || typeof data.expires !== 'number' || data.expires <= Date.now() || data.expires > Date.now() + OAUTH_TTL_SECONDS * 1000 || data.clientId !== env.GITHUB_CLIENT_ID) return null; + if (data.code !== undefined && (typeof data.code !== 'string' || !/^[A-Za-z0-9_-]{1,256}$/.test(data.code))) return null; + return data as unknown as Transaction; + } catch { return null; } +} +function callbackRedirect(env: GitHubOAuthEnv, status: 'complete' | 'error', reason?: string, cookies: string[] = [], selector?: string): Response { + const target = new URL('/', appOrigin(env)!); + target.searchParams.set('github_oauth', status); + if (reason) target.searchParams.set('oauth_error', reason); + if (selector) target.searchParams.set('authuser', selector); + const headers = jsonResponse({}, 200, cookies).headers; + headers.set('Location', target.toString()); + return new Response(null, { status: 303, headers }); +} +export async function handleGitHubOAuth(request: Request, env: GitHubOAuthEnv, fetcher: typeof fetch = 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 (!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') { + if (request.method !== 'GET') return jsonResponse({ error: 'method_not_allowed' }, 405); + const txn = await transaction(request, env); + const fail = (reason: string, cookies: string[] = []) => callbackRedirect(env, 'error', reason, [...cookies, clearOAuthCookie()]); + if (!txn || txn.code || url.searchParams.getAll('state').length !== 1 || url.searchParams.get('state') !== txn.state) return fail('invalid_state'); + if (url.searchParams.has('error')) return fail('denied'); + const code = url.searchParams.get('code'); + if (url.searchParams.getAll('code').length !== 1 || !code || !/^[A-Za-z0-9_-]{1,256}$/.test(code)) return fail('invalid_callback'); + const account = await verifiedAccount(request, env, txn.selector, fetcher); + if (!account.ok) return fail('account_unavailable', account.response.headers.getSetCookie()); + if (account.session.user.id !== txn.owner) return fail('account_changed', account.cookies); + // Code stays in a short-lived encrypted HttpOnly cookie. No token/code is copied into + // the frontend URL, HTML or a redirect fragment. The originating tab must prove PKCE. + const sealed = await seal({ ...txn, code }, env); + return callbackRedirect(env, 'complete', undefined, [...account.cookies, cookie(sealed, Math.max(1, Math.floor((txn.expires - Date.now()) / 1000)))], txn.selector); + } + + const guard = postGuard(request, env); + if (guard) return guard; + const body = await smallJson(request); + if (!body) return jsonResponse({ error: 'invalid_request' }, 400); + if (url.pathname === '/api/github/start') { + if (!validProof(body.challenge) || !validSelector(body.selector) || (body.allowDelete !== undefined && typeof body.allowDelete !== 'boolean')) return jsonResponse({ error: 'invalid_request' }, 400); + const account = await verifiedAccount(request, env, body.selector, fetcher); + if (!account.ok) return account.response; + const txn: Transaction = { state: randomProof(), challenge: body.challenge, owner: account.session.user.id, selector: account.session.activeSlot || String(account.session.authuser), expires: Date.now() + OAUTH_TTL_SECONDS * 1000, clientId: env.GITHUB_CLIENT_ID! }; + const target = new URL('https://github.com/login/oauth/authorize'); + target.search = new URLSearchParams({ client_id: env.GITHUB_CLIENT_ID!, redirect_uri: `${appOrigin(env)}/api/github/callback`, state: txn.state, scope: [...GITHUB_SCOPES, ...(body.allowDelete ? ['delete_repo'] : [])].join(' '), code_challenge: txn.challenge, code_challenge_method: 'S256', prompt: 'select_account' }).toString(); + return jsonResponse({ authorizeUrl: target.toString(), state: txn.state, ownerId: txn.owner }, 200, [...account.cookies, cookie(await seal(txn, env))]); + } + if (url.pathname !== '/api/github/complete') return jsonResponse({ error: 'not_found' }, 404); + const txn = await transaction(request, env); + const cleared = [clearOAuthCookie()]; + if (!txn?.code || !validProof(body.state) || body.state !== txn.state || !validProof(body.verifier) || await challengeFor(body.verifier) !== txn.challenge) return jsonResponse({ error: 'invalid_transaction', message: 'This GitHub connection attempt expired or belongs to another tab. Start again.' }, 400, cleared); + const account = await verifiedAccount(request, env, txn.selector, fetcher); + if (!account.ok) { account.response.headers.append('Set-Cookie', clearOAuthCookie()); return account.response; } + const cookies = [...account.cookies, ...cleared]; + if (account.session.user.id !== txn.owner) return jsonResponse({ error: 'account_changed', message: 'Your Gothwad account changed. Start the GitHub connection again.' }, 409, cookies); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 10_000); + try { + const response = await fetcher('https://github.com/login/oauth/access_token', { + method: 'POST', redirect: 'error', signal: controller.signal, + 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); + // 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); } + finally { clearTimeout(timer); } +} diff --git a/server/protectedRequest.ts b/server/protectedRequest.ts new file mode 100644 index 0000000..6599871 --- /dev/null +++ b/server/protectedRequest.ts @@ -0,0 +1,57 @@ +import { BRAND } from '../shared/brand'; +import { firstPartyOrigin, record, type AuthenticatedSession } from '../shared/accounts'; +import { accountCookies, handleSession, sessionJson, type SessionEnv } from './accountsSession'; + +export function appOrigin(env: SessionEnv): string | null { + return firstPartyOrigin(env.GITPLUS_ORIGIN || BRAND.productionOrigin); +} +export function jsonResponse(body: unknown, status = 200, cookies: string[] = []): Response { + // Same no-store/security policy as identity responses, including secrets returned by OAuth completion. + const response = sessionJson({ error: '' }, status, cookies); + return new Response(JSON.stringify(body), { status, headers: response.headers }); +} +export function postGuard(request: Request, env: SessionEnv): Response | null { + if (request.method !== 'POST') return jsonResponse({ error: 'method_not_allowed' }, 405); + const origin = appOrigin(env); + if (!origin || new URL(request.url).origin !== origin || request.headers.get('Origin') !== origin || request.headers.get('Sec-Fetch-Site') === 'cross-site') return jsonResponse({ error: 'origin_not_allowed' }, 403); + if (!request.headers.get('Content-Type')?.toLowerCase().startsWith('application/json')) return jsonResponse({ error: 'json_required' }, 415); + return null; +} +export async function smallJson(request: Request): Promise | null> { + const reader = request.body?.getReader(); + if (!reader) return null; + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + const chunk = await reader.read(); + if (chunk.done) break; + size += chunk.value.length; + if (size > 4096) { await reader.cancel(); return null; } + chunks.push(chunk.value); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + return record(JSON.parse(new TextDecoder().decode(bytes))); + } catch { return null; } +} +export async function verifiedAccount(request: Request, env: SessionEnv, selector: string, fetcher: typeof fetch) { + // Only called after route-specific CSRF/state checks. Cross-site OAuth callback navigation + // must not be mistaken for a cross-site session API call. + const url = new URL('/api/session', request.url); + url.searchParams.set('authuser', selector); + const response = await handleSession(new Request(url, { headers: { Cookie: request.headers.get('Cookie') || '' } }), env, fetcher); + const data = await response.clone().json(); + if (!response.ok || data.status !== 'authenticated') return { ok: false as const, response }; + const cookies = response.headers.getSetCookie(); + // /auth/me can rotate credentials. Use the rotated values for any following provider mutation. + const pairs = new Map(accountCookies(request.headers.get('Cookie') || '').split('; ').filter(Boolean).map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)])); + for (const cookie of cookies) { + const pair = cookie.split(';')[0]; + const name = pair.slice(0, pair.indexOf('=')); + if (/;\s*max-age=0(?:;|$)/i.test(cookie)) pairs.delete(name); + else pairs.set(name, pair.slice(pair.indexOf('=') + 1)); + } + return { ok: true as const, session: data as AuthenticatedSession, cookies, cookieHeader: Array.from(pairs, ([k, v]) => `${k}=${v}`).join('; ') }; +} diff --git a/shared/githubOAuth.ts b/shared/githubOAuth.ts new file mode 100644 index 0000000..95b22e9 --- /dev/null +++ b/shared/githubOAuth.ts @@ -0,0 +1,14 @@ +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'; +export const OAUTH_RETURN_PARAM = 'github_oauth'; +export function base64url(bytes: Uint8Array): string { + let text = ''; + for (const byte of bytes) text += String.fromCharCode(byte); + return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +export function randomProof(): string { return base64url(crypto.getRandomValues(new Uint8Array(32))); } +export async function challengeFor(verifier: string): Promise { + return base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))); +} +export function validProof(value: unknown): value is string { return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value); } diff --git a/src/App.tsx b/src/App.tsx index 0e70425..de5f8da 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,5 @@ import React, { useState, useEffect, lazy, Suspense } from 'react'; +import { oauthReturn, completeGitHubOAuth } from './services/githubOAuth'; import { GitHubApiError, githubService } from './services/github'; import { GitHubUser, GitHubRepo, GitHubRateLimit } from './types/github'; import { AuthScreen } from './components/AuthScreen'; @@ -17,6 +18,8 @@ import { AccountsProvider, useAccounts } from './context/AccountsContext'; import { AccountsBar, AccountsGate } from './components/accounts/AccountsGate'; function MainApp() { + const { state: accountState } = useAccounts(); + const [returnedOAuth] = useState(oauthReturn); const [user, setUser] = useState(null); const [appError, setAppError] = useState(null); const [loadingAuth, setLoadingAuth] = useState(true); @@ -42,14 +45,16 @@ function MainApp() { }, []); const checkAuthentication = async () => { - if (!githubService.hasToken()) { + if (!returnedOAuth && !githubService.hasToken()) { setLoadingAuth(false); return; } try { setLoadingAuth(true); - const userData = await githubService.getAuthenticatedUser(); + const userData = returnedOAuth && accountState.status === 'authenticated' + ? await completeGitHubOAuth(accountState.user.id, returnedOAuth) + : await githubService.getAuthenticatedUser(); setUser(userData); await loadInitialData(); } catch (error) { diff --git a/src/components/AuthScreen.tsx b/src/components/AuthScreen.tsx index bf96d15..485191c 100644 --- a/src/components/AuthScreen.tsx +++ b/src/components/AuthScreen.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import { Github, ExternalLink, @@ -18,6 +18,8 @@ import { } from 'lucide-react'; import { githubService } from '../services/github'; import { GitHubUser } from '../types/github'; +import { useAccounts } from '../context/AccountsContext'; +import { startGitHubOAuth } from '../services/githubOAuth'; import { useTheme } from '../context/ThemeContext'; interface AuthScreenProps { @@ -33,6 +35,29 @@ export const AuthScreen: React.FC = ({ onSuccess, initialError const [error, setError] = useState(initialError || null); const [showGuide, setShowGuide] = useState(false); + const { state: accountState } = useAccounts(); + const [oauthEnabled, setOauthEnabled] = useState(null); + const [oauthLoading, setOauthLoading] = useState(false); + const [allowDelete, setAllowDelete] = useState(false); + useEffect(() => { + let disposed = false; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 7000); + fetch('/api/github/config', { cache: 'no-store', credentials: 'same-origin', signal: controller.signal }) + .then(async (response) => response.ok && (await response.json()).enabled === true) + .then((enabled) => { if (!disposed) setOauthEnabled(enabled); }) + .catch(() => { if (!disposed) setOauthEnabled(false); }) + .finally(() => clearTimeout(timer)); + return () => { disposed = true; controller.abort(); clearTimeout(timer); }; + }, []); + const connectOAuth = async () => { + if (accountState.status !== 'authenticated') return; + setOauthLoading(true); + setError(null); + try { window.location.assign(await startGitHubOAuth(accountState, allowDelete)); } + catch (error) { setError(error instanceof Error ? error.message : 'Could not start GitHub authorization.'); setOauthLoading(false); } + }; + // Prefer repository-scoped, expiring tokens instead of broad classic admin scopes. const githubPatUrl = 'https://github.com/settings/personal-access-tokens/new'; @@ -41,7 +66,7 @@ export const AuthScreen: React.FC = ({ onSuccess, initialError if (e) e.preventDefault(); const token = tokenInput.trim(); if (!token) { - setError('Please paste or enter your GitHub GitHub Personal Access Token (PAT).'); + setError('Please paste or enter your GitHub Personal Access Token (PAT).'); return; } @@ -142,6 +167,15 @@ export const AuthScreen: React.FC = ({ onSuccess, initialError

You are signed in with Gothwad Accounts. GitHub access is a separate connection; your Gothwad password is never requested here.

+
+

Connect your GitHub account

+

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.

+ + + {oauthEnabled !== true &&

{oauthEnabled === null ? 'Checking OAuth availability…' : 'OAuth is unavailable or not configured. The administrator must configure the GitHub OAuth App runtime credentials. You can still use a PAT below.'}

} +

Saved only in this tab session, bound to your Gothwad account. No D1 storage or cross-device sync. Unchecking deletion does not revoke an earlier GitHub grant; revoke it in GitHub settings.

+
+
Or connect manually with a PAT
{/* Quick Create Token Link Banner */}
@@ -222,7 +256,7 @@ export const AuthScreen: React.FC = ({ onSuccess, initialError + {notice &&

{notice}

Manage Gothwad Account
} +
; +} diff --git a/src/components/accounts/AccountsGate.tsx b/src/components/accounts/AccountsGate.tsx index 3dc063a..fd6c54d 100644 --- a/src/components/accounts/AccountsGate.tsx +++ b/src/components/accounts/AccountsGate.tsx @@ -39,27 +39,4 @@ export function AccountsGate({ children }: React.PropsWithChildren) { ); } -export function AccountsBar() { - const { state, switchAccount, signOut } = useAccounts(); - if (state.status !== 'authenticated') return null; - return ( -
- GitPlus Gothwad Tech -
- {state.user.email} -
-

{state.user.name}

Signed in with Gothwad Accounts

- {state.accounts.length > 1 && } - Manage Gothwad Account / global sign-out - Choose or add an account - -

GitHub disconnect only removes the GitHub connection. Signing out here also pauses automatic sign-in for this tab.

-
-
-
- ); -} +export { AccountsBar } from './AccountsBar'; diff --git a/src/context/AccountsContext.tsx b/src/context/AccountsContext.tsx index f409e65..5a55e2e 100644 --- a/src/context/AccountsContext.tsx +++ b/src/context/AccountsContext.tsx @@ -1,6 +1,7 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'; import { type AccountSession, RETURN_MARKER, validSelector } from '../../shared/accounts'; import { sessionClient } from '../services/accounts/sessionClient'; +import { clearPendingOAuth } from '../services/githubOAuth'; import { githubService } from '../services/github'; const SELECTOR_KEY = 'gitplus_account_selector'; @@ -101,6 +102,7 @@ export function AccountsProvider({ children }: React.PropsWithChildren) { const switchAccount = useCallback((value: string) => { if (!validSelector(value)) return; generation.current++; + clearPendingOAuth(); sessionClient.reset(); githubService.bindAccount(null); store(SELECTOR_KEY, value); @@ -113,6 +115,7 @@ export function AccountsProvider({ children }: React.PropsWithChildren) { }, []); const signOut = useCallback(() => { generation.current++; + clearPendingOAuth(); sessionClient.reset(); githubService.bindAccount(null); store(PAUSED_KEY, '1'); diff --git a/src/services/accounts/accountWidget.ts b/src/services/accounts/accountWidget.ts new file mode 100644 index 0000000..66bcd98 --- /dev/null +++ b/src/services/accounts/accountWidget.ts @@ -0,0 +1,50 @@ +import { BRAND } from '../../../shared/brand'; +import type { AuthenticatedSession } from '../../../shared/accounts'; + +export interface MenuAccount { id: string; authuser: number; username: string; name: string; email: string } +export interface MenuState { user: AuthenticatedSession['user']; accounts: MenuAccount[]; activeId: string | null; authuser: number } +export interface MenuOptions { + appDomain: string; accountsWebOrigin: string; accountsApiOrigin: string; ecosystemName: string; + theme: 'light' | 'dark'; anchorEl: HTMLElement | null; nextUrl: string; manageAccountHref: string; + accountHref: (account: MenuAccount) => string; + onSwitchAccount: (account: MenuAccount) => void; + onSignOutAccount: (slot: string) => Promise; + onSignOutAll: () => Promise; + onManageAccount: () => void; + onClose: () => void; + onError: (message: string) => void; + extraActions: { label: string; onClick: () => void }[]; +} +export interface AccountWidget { open(state: MenuState, options: MenuOptions): void; update(state: MenuState, options: MenuOptions): void; close(): void; isOpen(): boolean } +export const WIDGET_URL = `${BRAND.accountsWebOrigin}/widget/account-menu.js`; +export function widgetState(session: AuthenticatedSession): MenuState { + return { user: session.user, activeId: session.activeSlot, authuser: session.authuser, + accounts: session.accounts.map((a) => ({ id: a.slot, authuser: a.authuser, username: a.username, name: a.name, email: `${a.username}@${BRAND.domain}` })) }; +} +function usable(value: unknown): value is AccountWidget { + if (!value || typeof value !== 'object') return false; + return ['open', 'update', 'close', 'isOpen'].every((key) => typeof (value as Record)[key] === 'function'); +} +export function createWidgetLoader(importer: () => Promise, timeoutMs = 5000) { + let loaded: AccountWidget | null = null; + let pending: Promise | null = null; + return { + peek: () => loaded, + load(): Promise { + if (loaded) return Promise.resolve(loaded); + if (pending) return pending; + pending = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('Widget timed out')), timeoutMs); + Promise.resolve().then(importer).then((module) => { clearTimeout(timer); resolve(module); }, (error) => { clearTimeout(timer); reject(error); }); + }).then((module) => { + const widget = (module as { GothwadAccountMenu?: unknown } | null)?.GothwadAccountMenu; + if (!usable(widget)) return null; + loaded = widget; + return widget; + }).catch(() => null).finally(() => { pending = null; }); + return pending; + }, + }; +} +// Use the real Accounts ES module (including its relative template/style modules), not a fork. +export const accountWidget = createWidgetLoader(() => import(/* @vite-ignore */ WIDGET_URL)); diff --git a/src/services/github.ts b/src/services/github.ts index 5f7a4e0..d150e41 100644 --- a/src/services/github.ts +++ b/src/services/github.ts @@ -40,6 +40,8 @@ export class GitHubService { private sessionAbort = new AbortController(); private accessPaused = false; + public getAccountId() { return this.accountId; } + public getGeneration() { return this.epoch; } private invalidateRequests() { diff --git a/src/services/githubOAuth.ts b/src/services/githubOAuth.ts new file mode 100644 index 0000000..e2b5cbd --- /dev/null +++ b/src/services/githubOAuth.ts @@ -0,0 +1,77 @@ +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'; +import type { GitHubUser } from '../types/github'; + +interface Pending { verifier: string; state: string; ownerId: string; expires: number } +export function clearPendingOAuth() { try { sessionStorage.removeItem(OAUTH_PENDING_KEY); } catch { /* PAT memory fallback still works. */ } } +function currentAttempt(ownerId: string, generation: number) { + if (githubService.getAccountId() !== ownerId || githubService.getGeneration() !== generation) throw new Error('Account connection changed. Start GitHub authorization again.'); +} +async function api(path: string, data: unknown) { + const response = await fetch(path, { method: 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(20_000), headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(data) }); + const result = record(await response.json()); + if (!response.ok || !result) throw new Error(typeof result?.message === 'string' ? result.message : 'GitHub authorization could not be completed. Try again or use a PAT.'); + return result; +} +export async function startGitHubOAuth(session: AuthenticatedSession, allowDelete: boolean): Promise { + const epoch = githubService.getGeneration(); + const verifier = randomProof(); + const pending: Pending = { verifier, state: '', ownerId: session.user.id, expires: Date.now() + OAUTH_TTL_SECONDS * 1000 }; + // Test storage before starting an authorization we could not finish in this tab. + try { sessionStorage.setItem(OAUTH_PENDING_KEY, JSON.stringify(pending)); } + catch { throw new Error('OAuth needs session storage in this tab. Enable it or use the PAT option.'); } + try { + const response = await api('/api/github/start', { challenge: await challengeFor(verifier), selector: session.activeSlot || String(session.authuser), allowDelete }); + currentAttempt(session.user.id, epoch); + if (!validProof(response.state) || response.ownerId !== session.user.id || typeof response.authorizeUrl !== 'string') throw new Error('Invalid OAuth start response.'); + const target = new URL(response.authorizeUrl); + if (target.origin !== 'https://github.com' || target.pathname !== '/login/oauth/authorize' || target.searchParams.get('state') !== response.state) throw new Error('Invalid GitHub authorization destination.'); + sessionStorage.setItem(OAUTH_PENDING_KEY, JSON.stringify({ ...pending, state: response.state })); + return target.toString(); + } catch (error) { clearPendingOAuth(); throw error; } +} +export function oauthReturn(): { status: string; error: string | null } | null { + const url = new URL(window.location.href); + const status = url.searchParams.get(OAUTH_RETURN_PARAM); + return status ? { status, error: url.searchParams.get('oauth_error') } : null; +} +function cleanReturnUrl() { + const url = new URL(window.location.href); + url.searchParams.delete(OAUTH_RETURN_PARAM); + url.searchParams.delete('oauth_error'); + history.replaceState(null, '', url); +} +const messages: Record = { + 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.', +}; +let completion: { owner: string; promise: Promise } | null = null; +export function completeGitHubOAuth(ownerId: string, returned: { status: string; error: string | null }): Promise { + if (completion?.owner === ownerId) return completion.promise; + cleanReturnUrl(); + const epoch = githubService.getGeneration(); + const run = async () => { + if (returned.status !== 'complete') throw new Error(messages[returned.error || ''] || 'This GitHub authorization attempt expired or was invalid. Start again.'); + let pending: Pending | null = null; + try { pending = JSON.parse(sessionStorage.getItem(OAUTH_PENDING_KEY) || 'null'); } catch { /* Invalid/missing state is rejected. */ } + if (!pending || pending.ownerId !== ownerId || pending.expires <= Date.now() || !validProof(pending.verifier) || !validProof(pending.state)) throw new Error('GitHub authorization must finish in the same tab and Gothwad account where it started. Please connect again.'); + currentAttempt(ownerId, epoch); + const result = await api('/api/github/complete', { state: pending.state, verifier: pending.verifier }); + currentAttempt(ownerId, epoch); + if (result.ownerId !== ownerId || typeof result.token !== 'string' || !result.token) throw new Error('GitHub returned an invalid connection.'); + githubService.setToken(result.token); + const connectedEpoch = githubService.getGeneration(); + try { return await githubService.getAuthenticatedUser(); } + catch (error) { if (githubService.getGeneration() === connectedEpoch) githubService.setToken(''); throw error; } + }; + const task = { owner: ownerId, promise: undefined as unknown as Promise }; + task.promise = run().finally(() => { + // Do not remove a new user's authorization attempt after an old request settles. + try { if (JSON.parse(sessionStorage.getItem(OAUTH_PENDING_KEY) || 'null')?.ownerId === ownerId) clearPendingOAuth(); } catch { /* Ignore. */ } + if (completion === task) completion = null; + }); + completion = task; + return task.promise; +} diff --git a/tests/account-widget.test.ts b/tests/account-widget.test.ts new file mode 100644 index 0000000..c8917fd --- /dev/null +++ b/tests/account-widget.test.ts @@ -0,0 +1,30 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createWidgetLoader, widgetState, WIDGET_URL } from '../src/services/accounts/accountWidget'; + +test('widget loader shares the real module import and validates the exported controller', async () => { + let calls = 0; + const menu = { open() {}, update() {}, close() {}, isOpen() { return false; } }; + const loader = createWidgetLoader(async () => { calls++; return { GothwadAccountMenu: menu }; }); + const [a, b] = await Promise.all([loader.load(), loader.load()]); + assert.equal(a, menu); assert.equal(b, menu); assert.equal(calls, 1); + assert.equal(await loader.load(), menu); assert.equal(calls, 1); + assert.equal(WIDGET_URL, 'https://accounts.gothwadtech.com/widget/account-menu.js'); +}); + +test('missing or broken widget fails safely and can be retried without a cloned fallback menu', async () => { + let calls = 0; + const loader = createWidgetLoader(async () => { calls++; throw new Error('offline'); }); + assert.equal(await loader.load(), null); + assert.equal(await loader.load(), null); + assert.equal(calls, 2); + assert.equal(await createWidgetLoader(async () => ({ GothwadAccountMenu: { open: 'not-a-function' } })).load(), null); +}); + +test('widget data maps stable slot IDs and only sanitized public identity', () => { + const session = { status: 'authenticated' as const, user: { id: 'user-id', username: 'alice', name: 'Alice', email: 'alice@gothwadtech.com' }, activeSlot: 'b', authuser: 0, accounts: [{ slot: 'b', authuser: 0, username: 'alice', name: 'Alice' }] }; + const result = widgetState(session); + assert.equal(result.activeId, 'b'); + assert.equal(result.accounts[0].id, 'b'); + assert.equal(result.user.id, 'user-id'); +}); diff --git a/tests/browser/accounts.spec.ts b/tests/browser/accounts.spec.ts index 9195910..1c62797 100644 --- a/tests/browser/accounts.spec.ts +++ b/tests/browser/accounts.spec.ts @@ -1,3 +1,5 @@ +import { readFile } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; import { test, expect, type Page } from '@playwright/test'; const ORIGIN = 'https://gitplus.gothwadtech.com'; @@ -14,9 +16,16 @@ async function mockApp(page: Page, session: (url: URL) => { status: number; body page.on('dialog', (dialog) => dialog.accept()); await page.route('https://fonts.googleapis.com/**', (route) => route.abort()); await page.route('https://fonts.gstatic.com/**', (route) => route.abort()); + await page.route('https://accounts.gothwadtech.com/widget/**', async (route) => { + const filename = new URL(route.request().url()).pathname.split('/').pop()!; + if (!['account-menu.js', 'account-menu-template.js', 'account-menu-styles.js'].includes(filename)) return route.abort(); + await route.fulfill({ contentType: 'text/javascript', headers: { 'Access-Control-Allow-Origin': '*' }, body: await readFile(`tests/fixtures/account-widget/${filename}`, 'utf8') }); + }); await page.route(`${ORIGIN}/**`, async (route) => { const url = new URL(route.request().url()); - if (url.pathname === '/api/session') { + if (url.pathname === '/api/github/config') { + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ enabled: true }) }); + } else if (url.pathname === '/api/session') { const response = session(url); await route.fulfill({ status: response.status, contentType: 'application/json', body: JSON.stringify(response.body) }); } else { @@ -49,13 +58,13 @@ test('existing Accounts session automatically opens Connect GitHub, isolates swi await page.locator('#connect-github-btn').click(); await expect(page.locator('#mobile-bottom-navigation')).toBeVisible(); expect(JSON.parse((await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection')))!).ownerId).toBe('alice-id'); - await page.locator('#gothwad-account-bar summary').click(); - await page.locator('#gothwad-account-select').selectOption('b'); + await page.locator('#gothwad-account-menu').click(); + await page.locator('[data-gw-switch="b"]').click(); await expect(page.locator('#gothwad-account-bar')).toContainText('bob@gothwadtech.com'); await expect(page.locator('#pat-input')).toBeVisible(); expect(await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection'))).toBeNull(); - await page.locator('#gothwad-account-bar summary').click(); - await page.locator('#gitplus-signout').click(); + await page.locator('#gothwad-account-menu').click(); + await page.getByRole('button', { name: 'Sign out of GitPlus (this tab)', exact: true }).click(); await expect(page.getByRole('heading', { name: 'Signed out of GitPlus' })).toBeVisible(); const beforeReload = checks; await page.reload(); @@ -95,3 +104,113 @@ test('actual local Pages Function refuses preview SSO and unknown API routes are await expect(page.getByRole('heading', { name: 'Use your GitPlus custom domain' })).toBeVisible(); await expect(page.locator('#pat-input')).toHaveCount(0); }); + + +test('OAuth connect survives the same-tab redirect, saves only an owner-bound local token, and preserves PAT as an alternative', async ({ page }) => { + const errors = await mockApp(page, () => ({ status: 200, body: account('alice') })); + const state = 'a'.repeat(43); + let challenge = ''; + let completions = 0; + await page.route(`${ORIGIN}/api/github/start`, async (route) => { + const body = route.request().postDataJSON(); + expect(body.allowDelete).toBe(true); + expect(body.selector).toBe('a'); + challenge = body.challenge; + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ownerId: 'alice-id', state, authorizeUrl: `https://github.com/login/oauth/authorize?state=${state}` }) }); + }); + // A mocked consent document starts a fresh routed navigation; Playwright only intercepts + // the first request in a server redirect chain. Backend callback/303 behavior is unit-tested. + await page.route('https://github.com/login/oauth/authorize?**', (route) => route.fulfill({ contentType: 'text/html', body: `Approve test app` })); + await page.route(`${ORIGIN}/api/github/complete`, async (route) => { + completions++; + const body = route.request().postDataJSON(); + expect(body.state).toBe(state); + expect(createHash('sha256').update(body.verifier).digest('base64url')).toBe(challenge); + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ownerId: 'alice-id', token: 'gho_mocked_browser_token', scope: 'repo' }) }); + }); + await page.goto(ORIGIN); + await expect(page.locator('#pat-input')).toBeVisible(); + await expect(page.locator('#github-oauth-connect')).toBeEnabled(); + await page.locator('#oauth-allow-delete').check(); + await page.locator('#github-oauth-connect').click(); + await page.getByRole('link', { name: 'Approve test app' }).click(); + await expect(page.locator('#mobile-bottom-navigation')).toBeVisible(); + expect(completions).toBe(1); + expect(page.url()).not.toContain('github_oauth'); + expect(page.url()).not.toContain('gho_'); + expect(await page.evaluate(() => localStorage.getItem('gitplus_github_connection'))).toBeNull(); + expect(await page.evaluate(() => sessionStorage.getItem('gitplus_github_oauth_pending'))).toBeNull(); + expect(JSON.parse((await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection')))!).ownerId).toBe('alice-id'); + await page.reload(); + await expect(page.locator('#mobile-bottom-navigation')).toBeVisible(); + expect(completions).toBe(1); + await page.locator('#header-logout-btn').click(); + await expect(page.locator('#pat-input')).toBeVisible(); + expect(await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection'))).toBeNull(); + expect(errors).toEqual([]); +}); + +test('missing OAuth runtime credentials leaves PAT usable; denied callback does not connect or leak data', async ({ page }) => { + const errors = await mockApp(page, () => ({ status: 200, body: account('alice') })); + await page.route(`${ORIGIN}/api/github/config`, (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ enabled: false }) })); + await page.goto(`${ORIGIN}/?github_oauth=error&oauth_error=denied`); + await expect(page.locator('#github-oauth-connect')).toBeDisabled(); + await expect(page.locator('#oauth-configuration-note')).toContainText('administrator'); + await expect(page.getByText('GitHub authorization was cancelled.', { exact: false })).toBeVisible(); + await expect(page.locator('#pat-input')).toBeEnabled(); + expect(page.url()).not.toContain('github_oauth'); + expect(errors).toEqual([]); +}); + +test('universal widget sign-out uses the same-origin protected action, while load failure has an honest fallback', async ({ page }) => { + const errors = await mockApp(page, () => ({ status: 200, body: account('alice') })); + let called = false; + await page.route(`${ORIGIN}/api/accounts/signout`, async (route) => { + expect(route.request().postDataJSON()).toEqual({ selector: 'a', slot: 'a' }); + called = true; + await route.fulfill({ contentType: 'application/json', body: '{"ok":true}' }); + }); + await page.goto(ORIGIN); + await page.locator('#gothwad-account-menu').click(); + await page.locator('[data-gw-signout-slot="a"]').click(); + await expect(page.getByRole('heading', { name: 'Signed out of GitPlus' })).toBeVisible(); + expect(called).toBe(true); + expect(errors).toEqual([]); +}); + +test('blocked universal widget shows a management link instead of a duplicate menu', async ({ page }) => { + const errors = await mockApp(page, () => ({ status: 200, body: account('alice') })); + await page.route('https://accounts.gothwadtech.com/widget/**', (route) => route.abort()); + await page.goto(ORIGIN); + await page.locator('#gothwad-account-menu').click(); + await expect(page.getByText('The universal Accounts menu could not load.', { exact: false })).toBeVisible(); + await expect(page.getByRole('link', { name: 'Manage Gothwad Account', exact: true })).toBeVisible(); + expect(errors).toEqual([]); +}); + +test('late OAuth completion cannot replace a newly selected Gothwad user connection', async ({ page }) => { + const errors = await mockApp(page, (url) => ({ status: 200, body: account(url.searchParams.get('authuser') === 'b' ? 'bob' : '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 }))); + let release!: () => void; + const held = new Promise((resolve) => { release = resolve; }); + const requested = page.waitForRequest(`${ORIGIN}/api/github/complete`); + await page.route(`${ORIGIN}/api/github/complete`, async (route) => { + await held; + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ownerId: 'alice-id', token: 'gho_late_alice_token', scope: 'repo' }) }); + }); + await page.goto(`${ORIGIN}/?github_oauth=complete&authuser=a`); + await requested; + await page.locator('#gothwad-account-menu').click(); + await page.locator('[data-gw-switch="b"]').click(); + await expect(page.locator('#gothwad-account-bar')).toContainText('bob@gothwadtech.com'); + await page.locator('#pat-input').fill('bob-test-only-token'); + await page.locator('#connect-github-btn').click(); + await expect(page.locator('#mobile-bottom-navigation')).toBeVisible(); + const completed = page.waitForResponse(`${ORIGIN}/api/github/complete`); + release(); + await (await completed).finished(); + await expect(page.locator('#mobile-bottom-navigation')).toBeVisible(); + expect(JSON.parse((await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection')))!).ownerId).toBe('bob-id'); + expect(await page.evaluate(() => sessionStorage.getItem('gitplus_github_connection'))).not.toContain('gho_late_alice_token'); + expect(errors).toEqual([]); +}); diff --git a/tests/fixtures/account-widget/README.md b/tests/fixtures/account-widget/README.md new file mode 100644 index 0000000..cb14b38 --- /dev/null +++ b/tests/fixtures/account-widget/README.md @@ -0,0 +1,10 @@ +# Shared Accounts widget test fixture + +Unmodified browser module/template/styles from GothwadTech/accounts commit +`507eb25b24b2a9fd3d4e99a76579026057a4e761`, `web/widget/`. + +These fixtures let Playwright exercise the real universal menu contract without network access. +They are **not** bundled or served by the production app. Production imports the canonical +`https://accounts.gothwadtech.com/widget/account-menu.js` ES module. + +Update these fixtures only alongside review of the Accounts widget contract. diff --git a/tests/fixtures/account-widget/account-menu-styles.js b/tests/fixtures/account-widget/account-menu-styles.js new file mode 100644 index 0000000..7399ccb --- /dev/null +++ b/tests/fixtures/account-widget/account-menu-styles.js @@ -0,0 +1,367 @@ +/** + * ============================================================================= + * UNIVERSAL ACCOUNT WIDGET STYLES (`Shadow DOM` Encapsulated — Light & Dark) + * Uniform Account Rows + Responsive Sheet/Popover + * ============================================================================= + */ + +export const ACCOUNT_MENU_CSS = ` +:host { + display: inline-flex; + align-items: center; + vertical-align: middle; + font-family: 'Roboto', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + line-height: 1.4; + box-sizing: border-box; +} + +*, *::before, *::after { box-sizing: border-box; } + +.gw-trigger { + position: relative; + display: inline-grid; + place-items: center; + width: var(--gw-avatar-size, 36px); + height: var(--gw-avatar-size, 36px); + padding: 0; + border: 2px solid rgba(11, 87, 208, 0.16); + border-radius: 999px; + background: transparent; + cursor: pointer; + transition: transform 0.14s ease, box-shadow 0.16s ease, border-color 0.16s ease; +} +.gw-trigger:hover { + border-color: rgba(11, 87, 208, 0.45); + box-shadow: 0 0 0 4px rgba(11, 87, 208, 0.10); +} +.gw-trigger:focus-visible { + outline: 2px solid #0b57d0; + outline-offset: 2px; +} + +.gw-signin-pill { + display: inline-flex; + align-items: center; + gap: 8px; + height: 38px; + padding: 0 18px; + border-radius: 999px; + background: #0b57d0; + color: #ffffff; + font-size: 14px; + font-weight: 500; + text-decoration: none; + border: none; + cursor: pointer; + white-space: nowrap; + transition: filter 0.15s ease, transform 0.12s ease; +} +.gw-signin-pill:hover { filter: brightness(1.07); } + +.gw-avatar { + position: relative; + display: inline-grid; + place-items: center; + border-radius: 999px; + overflow: hidden; + color: #ffffff; + font-weight: 500; + user-select: none; + flex-shrink: 0; +} +.gw-avatar img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} + +/* Sheet Overlay & Surface Tokens */ +.gw-layer { + --gw-surface: #eef3f8; + --gw-card: #ffffff; + --gw-card-hover: #f5f8fc; + --gw-text: #1f1f1f; + --gw-subtext: #444746; + --gw-accent: #0b57d0; + --gw-danger: #b3261e; + --gw-danger-bg: #fceeee; + --gw-border: rgba(0, 0, 0, 0.06); + --gw-shadow: 0 12px 36px rgba(15, 23, 42, 0.18), 0 2px 6px rgba(15, 23, 42, 0.08); + position: fixed; + inset: 0; + z-index: 2147483000; + font-family: 'Roboto', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + color: var(--gw-text); +} + +.gw-layer[data-theme="dark"] { + --gw-surface: #212121; + --gw-card: #2c2c2c; + --gw-card-hover: #363636; + --gw-text: #e3e3e3; + --gw-subtext: #c4c7c5; + --gw-accent: #8ab4f8; + --gw-danger: #f28b82; + --gw-danger-bg: #3c2525; + --gw-border: rgba(255, 255, 255, 0.08); + --gw-shadow: 0 16px 42px rgba(0, 0, 0, 0.56), 0 2px 8px rgba(0, 0, 0, 0.35); +} + +.gw-backdrop { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.32); + animation: gwFadeIn 0.16s ease-out; +} + +.gw-sheet { + position: fixed; + inset: 0; + display: flex; + flex-direction: column; + background: var(--gw-surface); + overflow-y: auto; + overscroll-behavior: contain; + padding: 12px 16px max(18px, env(safe-area-inset-bottom)); + animation: gwSlideUp 0.18s cubic-bezier(0.2, 0, 0, 1); +} + +@media (min-width: 640px) { + .gw-backdrop { background: transparent; } + .gw-sheet { + inset: auto; + top: var(--gw-top, 58px); + right: var(--gw-right, 16px); + width: 396px; + max-width: calc(100vw - 24px); + max-height: calc(100dvh - 74px); + min-height: 0; + border-radius: 28px; + border: 1px solid var(--gw-border); + box-shadow: var(--gw-shadow); + animation: gwPopIn 0.15s cubic-bezier(0.2, 0, 0, 1); + } +} + +@keyframes gwFadeIn { from { opacity: 0; } to { opacity: 1; } } +@keyframes gwSlideUp { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } } +@keyframes gwPopIn { from { opacity: 0; transform: scale(0.97) translateY(-6px); } to { opacity: 1; transform: scale(1) translateY(0); } } + +.gw-topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 40px; + margin-bottom: 10px; +} + +.gw-close { + display: inline-grid; + place-items: center; + width: 38px; + height: 38px; + border: none; + border-radius: 999px; + background: transparent; + color: var(--gw-subtext); + cursor: pointer; + transition: background 0.14s ease; +} +.gw-close:hover { background: rgba(127, 127, 127, 0.14); } +.gw-close:focus-visible { outline: 2px solid var(--gw-accent); } + +/* Equal account rows; only the outermost corners form the rounded group. */ +.gw-heading { + margin: 0; + padding-left: 8px; + font-size: 15px; + font-weight: 500; + letter-spacing: 0.1px; +} +.gw-stack { + display: flex; + flex-direction: column; + gap: 2px; + flex-shrink: 0; +} +.gw-account-row { + display: flex; + align-items: center; + background: var(--gw-card); + border-radius: 4px; + overflow: hidden; +} +.gw-account-row:first-child { border-radius: 24px 24px 4px 4px; } +.gw-account-row:last-child { border-radius: 4px 4px 24px 24px; } +.gw-account-row:only-child { border-radius: 24px; } +.gw-account-row .gw-account-link { + flex: 1; + min-width: 0; + min-height: 68px; + padding: 12px 8px 12px 18px; + gap: 12px; + background: transparent; +} +.gw-account-link:hover { background: var(--gw-card-hover); } +.gw-current-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--gw-subtext); + flex-shrink: 0; +} +.gw-slot-signout { + display: grid; + place-items: center; + width: 36px; + height: 40px; + margin-right: 8px; + padding: 0; + border: none; + border-radius: 12px; + background: transparent; + color: var(--gw-subtext); + cursor: pointer; + flex-shrink: 0; +} +.gw-slot-signout:hover { background: var(--gw-danger-bg); color: var(--gw-danger); } + +.gw-row { + display: flex; + align-items: center; + gap: 16px; + width: 100%; + min-height: 60px; + padding: 11px 20px; + border: none; + border-radius: 4px; + background: var(--gw-card); + color: var(--gw-text); + text-align: left; + text-decoration: none; + font-family: inherit; + font-size: 14.5px; + font-weight: 500; + cursor: pointer; + transition: background 0.13s ease; +} +.gw-row:hover { background: var(--gw-card-hover); } +.gw-row:focus-visible { outline: 2px solid var(--gw-accent); outline-offset: -2px; } +.gw-row.is-last { border-radius: 4px 4px 24px 24px; } + +.gw-acct-meta { + flex: 1; + min-width: 0; +} +.gw-acct-name { + display: block; + font-size: 14.5px; + font-weight: 500; + color: var(--gw-text); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.gw-acct-email { + display: block; + font-size: 12.5px; + font-weight: 400; + color: var(--gw-subtext); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.gw-badge { + padding: 2px 8px; + border-radius: 999px; + background: var(--gw-accent); + color: #ffffff; + font-size: 11px; + font-weight: 600; + flex-shrink: 0; +} + +.gw-primary-actions { + display: flex; + flex-direction: column; + gap: 10px; + margin-top: 14px; + flex-shrink: 0; +} +.gw-action-icon { + width: 24px; + height: 24px; + display: grid; + place-items: center; + flex-shrink: 0; +} +.gw-brand-logo { display: block; flex-shrink: 0; border-radius: 50%; } + +.gw-manage-pill { + display: flex; + align-items: center; + gap: 16px; + width: 100%; + min-height: 56px; + margin: 0; + padding: 12px 22px; + border: 1px solid var(--gw-border); + border-radius: 999px; + background: var(--gw-card); + color: var(--gw-text); + text-decoration: none; + font-size: 14.5px; + font-weight: 500; + cursor: pointer; + transition: background 0.14s ease; +} +.gw-manage-pill:hover { background: var(--gw-card-hover); } +.gw-signout-all { + align-self: center; + margin: 14px 0 0; + padding: 9px 14px; + border: none; + border-radius: 999px; + background: transparent; + color: var(--gw-subtext); + font: inherit; + font-size: 12.5px; + cursor: pointer; +} +.gw-signout-all:hover { background: var(--gw-danger-bg); color: var(--gw-danger); } +.gw-slot-signout:focus-visible, .gw-manage-pill:focus-visible, .gw-signout-all:focus-visible { + outline: 2px solid var(--gw-accent); + outline-offset: -3px; +} + +.gw-extra-group { + display: flex; + flex-direction: column; + gap: 2px; + margin-top: 12px; +} +.gw-extra-group .gw-row:first-child { border-radius: 20px 20px 4px 4px; } +.gw-extra-group .gw-row:last-child { border-radius: 4px 4px 20px 20px; } +.gw-extra-group .gw-row:only-child { border-radius: 20px; } + +.gw-footer { + margin-top: auto; + padding-top: 16px; + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + font-size: 12.5px; + color: var(--gw-subtext); +} +.gw-footer a { + color: var(--gw-subtext); + text-decoration: none; + padding: 4px 6px; + border-radius: 6px; +} +.gw-footer a:hover { background: rgba(127, 127, 127, 0.12); } +`; diff --git a/tests/fixtures/account-widget/account-menu-template.js b/tests/fixtures/account-widget/account-menu-template.js new file mode 100644 index 0000000..0dfaba2 --- /dev/null +++ b/tests/fixtures/account-widget/account-menu-template.js @@ -0,0 +1,209 @@ +/** + * ============================================================================= + * UNIVERSAL ACCOUNT WIDGET — PURE DATA NORMALIZERS & HTML TEMPLATE + * ============================================================================= + */ + +export const MAX_BROWSER_ACCOUNTS = 6; + +const AVATAR_PALETTE = [ + '#9334a6', '#0b57d0', '#0d652d', '#c5221f', '#00639b', '#b06000', '#7627bb', '#185abc', +]; + +export function esc(value) { + return String(value ?? '').replace(/[&<>"']/g, (ch) => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', + }[ch])); +} + +export function avatarColorFor(seed) { + const s = String(seed || 'u').toLowerCase(); + let hash = 0; + for (let i = 0; i < s.length; i += 1) { + hash = ((hash << 5) - hash + s.charCodeAt(i)) | 0; + } + return AVATAR_PALETTE[Math.abs(hash) % AVATAR_PALETTE.length]; +} + +export function initialsFrom(item) { + const full = `${item?.firstName || item?.first_name || ''} ${item?.lastName || item?.last_name || ''}`.trim() + || String(item?.name || item?.username || '?').trim(); + const parts = full.split(/[\s._-]+/).filter(Boolean); + if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase(); + return full.slice(0, 1).toUpperCase() || '?'; +} + +export function resolveEndpoints(opts = {}) { + const scriptOrigin = (() => { + try { + const u = new URL(import.meta.url); + return u.protocol === 'http:' || u.protocol === 'https:' ? u.origin : ''; + } catch { + return ''; + } + })(); + const locHost = globalThis.location?.hostname || 'localhost'; + const locOrigin = globalThis.location?.origin || 'http://localhost:3000'; + + const accountsWebOrigin = ( + opts.accountsWebOrigin + || scriptOrigin + || locOrigin + ).replace(/\/+$/, ''); + + const inferredDomain = (() => { + if (opts.appDomain) return String(opts.appDomain).toLowerCase(); + try { + const host = new URL(accountsWebOrigin).hostname.toLowerCase(); + if (host === 'localhost' || host === '127.0.0.1' || host.endsWith('.e2b.app')) { + return 'gothwadtech.com'; + } + return host.startsWith('accounts.') ? host.slice('accounts.'.length) : host; + } catch { + return locHost || 'gothwadtech.com'; + } + })(); + + const accountsApiOrigin = ( + opts.accountsApiOrigin || `${accountsWebOrigin}/api` + ).replace(/\/+$/, ''); + + const ecosystemName = String(opts.ecosystemName || 'Gothwad').trim() || 'Gothwad'; + return { appDomain: inferredDomain, accountsWebOrigin, accountsApiOrigin, ecosystemName }; +} + +export function normalizeMenuAccount(raw, idx = 0, appDomain = 'gothwadtech.com') { + const username = String(raw?.username || '').trim().toLowerCase(); + const firstName = String(raw?.firstName ?? raw?.first_name ?? '').trim(); + const lastName = String(raw?.lastName ?? raw?.last_name ?? '').trim(); + const name = String(raw?.name || `${firstName} ${lastName}`.trim() || username || 'Account').trim(); + const authuser = Number.isInteger(raw?.authuser) ? raw.authuser : idx; + const avatarUrl = raw?.avatarUrl || raw?.avatar_url || raw?.picture || null; + const email = String(raw?.email || (username ? `${username}@${appDomain}` : '')).trim().toLowerCase(); + return { + id: String(raw?.id || raw?.slot || authuser), + authuser, + username, + name, + firstName, + lastName, + email, + avatarUrl: avatarUrl ? String(avatarUrl) : null, + accountUrl: raw?.accountUrl || null, + }; +} + +export function renderAvatarMarkup(acct, sizePx = 40) { + const bg = avatarColorFor(acct?.username || acct?.email || acct?.name); + const label = esc(initialsFrom(acct)); + const fontSize = Math.max(13, Math.round(sizePx * 0.42)); + const url = acct?.avatarUrl || acct?.avatar_url || acct?.picture || ''; + if (url) { + return ` + + `; + } + return `${label}`; +} + +const SVG = { + close: '', + plus: '', + logout: '', +}; + +export function detectHostTheme(explicitTheme) { + if (explicitTheme === 'dark' || explicitTheme === 'light') return explicitTheme; + const docEl = globalThis.document?.documentElement; + if (docEl) { + const attr = docEl.getAttribute?.('data-theme'); + if (attr === 'dark' || attr === 'light') return attr; + if (docEl.classList?.contains('dark')) return 'dark'; + } + return globalThis.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light'; +} + +export function buildAccountSheetHtml(state, opts = {}) { + const { appDomain, accountsWebOrigin, ecosystemName } = resolveEndpoints(opts); + const rawAccounts = Array.isArray(state.accounts) ? state.accounts : []; + const normalized = rawAccounts.map((a, i) => normalizeMenuAccount(a, i, appDomain)); + const activeUser = normalizeMenuAccount( + state.user || normalized.find((a) => a.id === state.activeId) || normalized[0] || {}, + state.authuser ?? 0, + appDomain, + ); + if (normalized.length === 0 && activeUser.username) normalized.push(activeUser); + + const activeIndex = normalized.findIndex((acct) => + acct.id === state.activeId || (activeUser.username && acct.username === activeUser.username)); + // Present the current account first without changing its server authuser index. + const accounts = activeIndex > 0 + ? [normalized[activeIndex], ...normalized.filter((_, index) => index !== activeIndex)] + : normalized; + const authuser = Number.isInteger(state.authuser) ? state.authuser : activeUser.authuser; + const nextUrl = opts.nextUrl || globalThis.location?.href || `${accountsWebOrigin}/u/${authuser}/me`; + const addHref = `${accountsWebOrigin}/signin?choose=1&add=1&next=${encodeURIComponent(nextUrl)}`; + const manageHref = opts.manageAccountHref || `${accountsWebOrigin}/u/${authuser}/me`; + const badges = opts.badges || {}; + const extraActions = Array.isArray(opts.extraActions) ? opts.extraActions : []; + + const accountRowsHtml = accounts.map((acct, index) => { + const current = activeIndex >= 0 ? acct === normalized[activeIndex] : index === 0; + const unread = Number(badges[acct.username] || 0); + const href = typeof opts.accountHref === 'function' + ? opts.accountHref(acct) + : `${accountsWebOrigin}/u/${acct.authuser}/me`; + return ``; + }).join(''); + + const extraHtml = extraActions.length > 0 + ? `
+ ${extraActions.map((act, idx) => (act.href + ? ` + ${esc(act.label)} + ` + : ``)).join('')} +
` + : ''; + + return `
+ `; +} diff --git a/tests/fixtures/account-widget/account-menu.js b/tests/fixtures/account-widget/account-menu.js new file mode 100644 index 0000000..4a868a5 --- /dev/null +++ b/tests/fixtures/account-widget/account-menu.js @@ -0,0 +1,290 @@ +/** + * ============================================================================= + * UNIVERSAL ACCOUNT MENU & SILENT SSO SDK + * Hosted once at `https://accounts./widget/account-menu.js` + * Used across Accounts (`/me`), Mail, Kiwi Store, Console, Admin, Notes & Drive. + * ============================================================================= + */ + +import { ACCOUNT_MENU_CSS } from './account-menu-styles.js'; +import { + MAX_BROWSER_ACCOUNTS, + avatarColorFor, + buildAccountSheetHtml, + detectHostTheme, + esc, + initialsFrom, + normalizeMenuAccount, + renderAvatarMarkup, + resolveEndpoints, +} from './account-menu-template.js'; + +export { + MAX_BROWSER_ACCOUNTS, + avatarColorFor, + buildAccountSheetHtml, + detectHostTheme, + initialsFrom, + normalizeMenuAccount, + renderAvatarMarkup, + resolveEndpoints, +}; + +async function callAccountsApi(opts, path, method = 'GET', body = undefined) { + const { accountsApiOrigin } = resolveEndpoints(opts); + const headers = { Accept: 'application/json' }; + if (Number.isInteger(opts.authuser) && opts.authuser >= 0 && opts.authuser <= 5) { + headers['X-Gothwad-Authuser'] = String(opts.authuser); + } + if (body !== undefined) headers['Content-Type'] = 'application/json'; + const res = await fetch(`${accountsApiOrigin}${path}`, { + method, + credentials: 'include', + headers, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + let data = null; + try { data = await res.json(); } catch { data = null; } + return { ok: res.ok, status: res.status, data }; +} + +class SheetOverlayController { + constructor() { + this.hostEl = null; + this.shadow = null; + this.layerEl = null; + this.state = { user: null, accounts: [], activeId: null, authuser: 0 }; + this.opts = {}; + this._onKeyDown = (e) => { if (e.key === 'Escape') this.close(); }; + } + + isOpen() { + return Boolean(this.hostEl); + } + + ensureMounted() { + if (this.hostEl || !globalThis.document?.body) return; + this.hostEl = document.createElement('div'); + this.hostEl.setAttribute('data-gothwad-account-overlay', '1'); + if (typeof this.hostEl.attachShadow === 'function') { + this.shadow = this.hostEl.attachShadow({ mode: 'open' }); + } else { + this.shadow = this.hostEl; + } + const styleEl = document.createElement('style'); + styleEl.textContent = ACCOUNT_MENU_CSS; + this.layerEl = document.createElement('div'); + this.layerEl.className = 'gw-layer'; + this.shadow.appendChild(styleEl); + this.shadow.appendChild(this.layerEl); + document.body.appendChild(this.hostEl); + globalThis.window?.addEventListener?.('keydown', this._onKeyDown); + } + + open(nextState = {}, nextOpts = {}) { + this.state = { ...this.state, ...nextState }; + this.opts = { ...nextOpts }; + this.ensureMounted(); + this.render(); + } + + update(patchState = {}, patchOpts = null) { + this.state = { ...this.state, ...patchState }; + if (patchOpts) this.opts = { ...this.opts, ...patchOpts }; + if (this.isOpen()) this.render(); + } + + close() { + if (!this.hostEl) return; + this.hostEl.remove(); + this.hostEl = null; + this.shadow = null; + this.layerEl = null; + globalThis.window?.removeEventListener?.('keydown', this._onKeyDown); + this.opts.onClose?.(); + } + + render() { + if (!this.layerEl) return; + this.layerEl.setAttribute('data-theme', detectHostTheme(this.opts.theme)); + const anchorRect = this.opts.anchorEl?.getBoundingClientRect?.(); + if (anchorRect && globalThis.innerWidth) { + const top = Math.max(12, Math.round(anchorRect.bottom + 10)); + const right = Math.max(12, Math.round(globalThis.innerWidth - anchorRect.right)); + this.layerEl.style?.setProperty?.('--gw-top', `${top}px`); + this.layerEl.style?.setProperty?.('--gw-right', `${right}px`); + } + this.layerEl.innerHTML = buildAccountSheetHtml(this.state, this.opts); + this.bindEvents(); + } + + bindEvents() { + if (!this.layerEl?.querySelectorAll) return; + + this.layerEl.querySelectorAll('[data-gw-avatar-img]').forEach((img) => { + img.addEventListener('error', () => { + const parent = img.parentElement; + if (parent) parent.textContent = img.getAttribute('data-gw-avatar-img') || '?'; + }); + }); + + this.layerEl.querySelectorAll('[data-gw-action="close"]').forEach((el) => { + el.addEventListener('click', (e) => { + e.stopPropagation(); + this.close(); + }); + }); + + this.layerEl.querySelector('[data-gw-action="manage-account"]')?.addEventListener('click', (e) => { + if (typeof this.opts.onManageAccount === 'function') { + e.preventDefault(); + this.close(); + this.opts.onManageAccount(); + } + }); + + this.layerEl.querySelector('[data-gw-action="add-account"]')?.addEventListener('click', (e) => { + const count = Array.isArray(this.state.accounts) ? this.state.accounts.length : 0; + if (count >= MAX_BROWSER_ACCOUNTS) { + e.preventDefault(); + this.opts.onError?.(`Maximum ${MAX_BROWSER_ACCOUNTS} accounts can stay signed in on one browser.`); + } + }); + + this.layerEl.querySelectorAll('[data-gw-signout-slot]').forEach((btn) => { + btn.addEventListener('click', async (e) => { + e.preventDefault(); + e.stopPropagation(); + const slotId = btn.getAttribute('data-gw-signout-slot'); + const { appDomain } = resolveEndpoints(this.opts); + const accounts = (this.state.accounts || []).map((a, i) => normalizeMenuAccount(a, i, appDomain)); + const target = accounts.find((a) => a.id === slotId) || null; + this.close(); + if (typeof this.opts.onSignOutAccount === 'function') { + await this.opts.onSignOutAccount(slotId, target); + return; + } + await callAccountsApi(this.opts, `/auth/accounts/${encodeURIComponent(slotId)}/signout`, 'POST', {}); + globalThis.location?.reload?.(); + }); + }); + + this.layerEl.querySelector('[data-gw-action="signout-all"]')?.addEventListener('click', async () => { + this.close(); + if (typeof this.opts.onSignOutAll === 'function') { + await this.opts.onSignOutAll(); + return; + } + await callAccountsApi(this.opts, '/auth/signout', 'POST', {}); + globalThis.location?.reload?.(); + }); + + this.layerEl.querySelectorAll('[data-gw-extra]').forEach((el) => { + el.addEventListener('click', (e) => { + const idx = Number(el.getAttribute('data-gw-extra')); + const action = this.opts.extraActions?.[idx]; + if (action?.href && typeof action.onClick !== 'function') { + if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; + this.close(); + return; + } + if (action?.href) e.preventDefault(); + this.close(); + action?.onClick?.(e); + }); + }); + + this.layerEl.querySelectorAll('[data-gw-switch]').forEach((row) => { + row.addEventListener('click', async (e) => { + if (e.target?.closest?.('[data-gw-signout-slot]')) return; + if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return; + e.preventDefault(); + const slotId = row.getAttribute('data-gw-switch'); + const { appDomain } = resolveEndpoints(this.opts); + const accounts = (this.state.accounts || []).map((a, i) => normalizeMenuAccount(a, i, appDomain)); + const target = accounts.find((a) => a.id === slotId); + if (!target) return; + this.close(); + if (typeof this.opts.onSwitchAccount === 'function') { + await this.opts.onSwitchAccount(target); + return; + } + const sw = await callAccountsApi(this.opts, '/auth/switch', 'POST', { + id: target.id, + authuser: target.authuser, + }); + if (sw.ok) globalThis.location?.reload?.(); + }); + }); + } +} + +export const GothwadAccountMenu = new SheetOverlayController(); + +if (globalThis.window) { + globalThis.window.GothwadAccountMenu = GothwadAccountMenu; +} + +if (typeof globalThis.HTMLElement !== 'undefined' && globalThis.customElements && !globalThis.customElements.get('gothwad-account-menu')) { + class GothwadAccountMenuElement extends globalThis.HTMLElement { + constructor() { + super(); + this._root = this.attachShadow({ mode: 'open' }); + this._session = { authenticated: false, user: null, accounts: [], activeId: null, authuser: 0 }; + this._options = {}; + } + + connectedCallback() { + this.renderButton(); + if (this.hasAttribute('auto-sso')) void this.refreshSession(); + } + + setSession(session, options = {}) { + this._session = { ...this._session, ...session, authenticated: Boolean(session?.user) }; + this._options = { ...this._options, ...options }; + this.renderButton(); + } + + async refreshSession() { + const res = await callAccountsApi(this._options, '/auth/me', 'GET'); + if (res.ok && res.data?.authenticated && res.data.user) { + this._session = { + authenticated: true, + user: res.data.user, + accounts: res.data.accounts || [], + activeId: res.data.activeId || null, + authuser: Number.isInteger(res.data.authuser) ? res.data.authuser : 0, + }; + } else { + this._session = { authenticated: false, user: null, accounts: [], activeId: null, authuser: 0 }; + } + this.renderButton(); + this.dispatchEvent(new CustomEvent('gothwad-session', { detail: this._session, bubbles: true })); + return this._session; + } + + renderButton() { + const size = Number(this.getAttribute('size') || 36); + const { appDomain, accountsWebOrigin } = resolveEndpoints(this._options); + const signInHref = `${accountsWebOrigin}/signin?next=${encodeURIComponent(globalThis.location?.href || accountsWebOrigin)}`; + + if (!this._session.authenticated || !this._session.user) { + this._root.innerHTML = ` + `; + return; + } + + const acct = normalizeMenuAccount(this._session.user, this._session.authuser, appDomain); + this._root.innerHTML = ` + `; + this._root.querySelector('.gw-trigger')?.addEventListener('click', (e) => { + e.stopPropagation(); + if (GothwadAccountMenu.isOpen()) GothwadAccountMenu.close(); + else GothwadAccountMenu.open(this._session, { ...this._options, anchorEl: this }); + }); + } + } + globalThis.customElements.define('gothwad-account-menu', GothwadAccountMenuElement); +} diff --git a/tests/github-oauth.test.ts b/tests/github-oauth.test.ts new file mode 100644 index 0000000..2f6c4ce --- /dev/null +++ b/tests/github-oauth.test.ts @@ -0,0 +1,168 @@ +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'; + +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' }; +const identity = (id = 'alice-id') => ({ authenticated: true, user: { id, username: 'alice', first_name: 'Alice' }, activeId: 'a', authuser: 0, accounts: [{ id: 'a', authuser: 0, username: 'alice', name: 'Alice' }, { id: 'b', authuser: 1, username: 'bobby', name: 'Bob' }] }); +const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); +const makeRequest = (path: string, body?: unknown, txnCookie = '', extraHeaders: Record = {}) => new Request(origin + path, { + method: body === undefined ? 'GET' : 'POST', + headers: { Cookie: `gothwad_sess_a=account-cookie${txnCookie ? '; ' + txnCookie : ''}`, ...(body !== undefined ? { Origin: origin, 'Content-Type': 'application/json' } : {}), ...extraHeaders }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), +}); +const readCookie = (res: Response) => res.headers.getSetCookie().find((v) => v.startsWith(TRANSACTION_COOKIE + '='))!.split(';')[0]; +function provider(owner = 'alice-id') { + let exchangeCount = 0; + const requests: { url: string; init?: RequestInit }[] = []; + const fetcher: typeof fetch = async (input, init) => { + const url = String(input); requests.push({ url, init }); + if (url === 'https://api.gothwadtech.com/api/auth/me') { + assert.ok(!new Headers(init?.headers).get('Cookie')?.includes(TRANSACTION_COOKIE)); + return json(identity(owner)); + } + if (url === 'https://github.com/login/oauth/access_token') { + exchangeCount++; + return exchangeCount === 1 ? json({ access_token: 'gho_test_only_token', token_type: 'bearer', scope: 'repo,gist', refresh_token: 'never-return-or-persist-this' }) : json({ error: 'bad_verification_code' }); + } + throw new Error('Unexpected external request'); + }; + return { fetcher, requests }; +} +async function start(fetcher: typeof fetch = provider().fetcher, allowDelete = false) { + const verifier = randomProof(); + const challenge = await challengeFor(verifier); + const response = await handleGitHubOAuth(makeRequest('/api/github/start', { challenge, selector: 'a', allowDelete }), env, fetcher); + assert.equal(response.status, 200); + return { verifier, challenge, response, body: await response.json(), cookie: readCookie(response) }; +} +async function callback(s: Awaited>, fetcher: typeof fetch) { + return handleGitHubOAuth(makeRequest(`/api/github/callback?state=${s.body.state}&code=test-one-time-code`, undefined, s.cookie, { 'Sec-Fetch-Site': 'cross-site' }), env, fetcher); +} + +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.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); +}); + +test('start is CSRF-protected, verifies Gothwad identity and requests explicit PKCE/scopes', async () => { + for (const originHeader of ['', 'https://evil.example']) { + const res = await handleGitHubOAuth(makeRequest('/api/github/start', {}, '', { Origin: originHeader }), env); + assert.equal(res.status, 403); + } + const s = await start(); + const url = new URL(s.body.authorizeUrl); + assert.equal(url.origin, 'https://github.com'); + assert.equal(url.searchParams.get('code_challenge'), s.challenge); + assert.equal(url.searchParams.get('code_challenge_method'), 'S256'); + assert.equal(url.searchParams.get('redirect_uri'), origin + '/api/github/callback'); + assert.ok(!url.searchParams.get('scope')!.includes('delete_repo')); + assert.ok(!url.searchParams.get('scope')!.includes('offline_access')); + assert.ok(!JSON.stringify(s.body).includes(env.GITHUB_CLIENT_SECRET!)); + assert.ok(!s.cookie.includes('alice-id')); + assert.match(s.response.headers.getSetCookie()[0], /Secure; HttpOnly; SameSite=Lax/); + assert.match(s.response.headers.get('Cache-Control')!, /no-store/); + const destructive = await start(undefined, true); + assert.ok(new URL(destructive.body.authorizeUrl).searchParams.get('scope')!.includes('delete_repo')); +}); + +test('start rejects anonymous Accounts and oversized input before GitHub authorization', async () => { + const anonymous: typeof fetch = async () => json({ authenticated: false }, 401); + const response = await handleGitHubOAuth(makeRequest('/api/github/start', { challenge: randomProof(), selector: 'a' }), env, anonymous); + assert.equal(response.status, 401); + assert.equal(response.headers.getSetCookie().length, 0); + assert.equal((await handleGitHubOAuth(makeRequest('/api/github/start', { challenge: 'x'.repeat(5000) }), env, anonymous)).status, 400); +}); + +test('callback rejects state tampering, modified cookie, denied consent and changed Gothwad owner', async () => { + const s = await start(); + for (const query of [`state=${randomProof()}&code=abc`, `state=${s.body.state}&state=${s.body.state}&code=abc`, `state=${s.body.state}&error=access_denied`]) { + const res = await handleGitHubOAuth(makeRequest('/api/github/callback?' + query, undefined, s.cookie), env, provider().fetcher); + assert.equal(res.status, 303); + assert.equal(new URL(res.headers.get('Location')!).searchParams.get('github_oauth'), 'error'); + assert.match(res.headers.getSetCookie().at(-1)!, /Max-Age=0/); + } + const tampered = { ...s, cookie: s.cookie.replace(/=./, (value) => value === '=X' ? '=Y' : '=X') }; + assert.match((await callback(tampered, provider().fetcher)).headers.get('Location')!, /invalid_state/); + const changed = await callback(s, provider('bob-id').fetcher); + assert.match(changed.headers.get('Location')!, /account_changed/); +}); + +test('expired transaction and rotated client secret cannot complete callback', async (t) => { + const s = await start(); + assert.match((await handleGitHubOAuth(makeRequest(`/api/github/callback?state=${s.body.state}&code=abc`, undefined, s.cookie), { ...env, GITHUB_CLIENT_SECRET: 'different-test-only-secret' }, provider().fetcher)).headers.get('Location')!, /invalid_state/); + const now = Date.now(); + t.mock.method(Date, 'now', () => now + 601_000); + assert.match((await callback(s, provider().fetcher)).headers.get('Location')!, /invalid_state/); +}); + +test('completion requires originating tab PKCE and same verified owner; token never enters redirect URLs', async () => { + const p = provider(); + const s = await start(p.fetcher); + const returned = await callback(s, p.fetcher); + const location = returned.headers.get('Location')!; + assert.equal(new URL(location).searchParams.get('github_oauth'), 'complete'); + assert.ok(!location.includes('test-one-time-code')); + const returnedCookie = readCookie(returned); + const invalid = await handleGitHubOAuth(makeRequest('/api/github/complete', { state: s.body.state, verifier: randomProof() }, returnedCookie), env, p.fetcher); + assert.equal(invalid.status, 400); + assert.equal(p.requests.filter((r) => r.url.includes('github.com/login')).length, 0); + const changed = await handleGitHubOAuth(makeRequest('/api/github/complete', { state: s.body.state, verifier: s.verifier }, returnedCookie), env, provider('other-id').fetcher); + assert.equal(changed.status, 409); + const complete = () => handleGitHubOAuth(makeRequest('/api/github/complete', { state: s.body.state, verifier: s.verifier }, returnedCookie), env, p.fetcher); + const response = await complete(); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { token: 'gho_test_only_token', ownerId: 'alice-id', scope: 'repo,gist' }); + const exchange = p.requests.find((r) => r.url.includes('github.com/login'))!; + assert.equal(JSON.parse(exchange.init!.body as string).code_verifier, s.verifier); + assert.equal(JSON.parse(exchange.init!.body as string).client_secret, env.GITHUB_CLIENT_SECRET); + assert.equal(exchange.init?.redirect, 'error'); + assert.match(response.headers.getSetCookie().at(-1)!, /Max-Age=0/); + assert.match(response.headers.get('Cache-Control')!, /no-store/); + assert.equal((await complete()).status, 400); // GitHub's one-use code is the replay barrier, no D1 required. +}); + +test('failed exchange is generic, clears the transaction and never reflects provider secrets/errors', async () => { + const p = provider(); const s = await start(p.fetcher); const cb = await callback(s, p.fetcher); + const failure: typeof fetch = async (url, options) => String(url).includes('api.gothwadtech.com') ? p.fetcher(url, options) : json({ error: 'bad_code', error_description: env.GITHUB_CLIENT_SECRET }, 500); + const response = await handleGitHubOAuth(makeRequest('/api/github/complete', { state: s.body.state, verifier: s.verifier }, readCookie(cb)), env, failure); + assert.equal(response.status, 502); + assert.ok(!(await response.text()).includes(env.GITHUB_CLIENT_SECRET!)); + assert.match(response.headers.getSetCookie().at(-1)!, /Max-Age=0/); +}); + +test('universal-menu sign-out validates origin/slot and relays only approved cookie deletions', async () => { + assert.equal((await handleAccountAction(makeRequest('/api/accounts/signout-all', { selector: 'a' }, '', { Origin: 'https://evil.example' }), env)).status, 403); + assert.equal((await handleAccountAction(makeRequest('/api/accounts/signout', { selector: 'a', slot: 'z' }), env)).status, 400); + const p = provider(); + const response = await handleAccountAction(makeRequest('/api/accounts/signout', { selector: 'a', slot: 'b' }), env, async (url, init) => { + if (String(url).endsWith('/api/auth/me')) return p.fetcher(url, init); + assert.equal(url, 'https://api.gothwadtech.com/api/auth/accounts/b/signout'); + assert.equal(init?.method, 'POST'); + assert.equal(new Headers(init?.headers).get('Origin'), origin); + const res = json({ ok: true, access_token: 'must-not-expose' }); + res.headers.append('Set-Cookie', 'gothwad_sess_b=; Path=/; HttpOnly; Secure; SameSite=Lax; Domain=.gothwadtech.com; Max-Age=0'); + return res; + }); + assert.deepEqual(await response.json(), { ok: true }); + assert.ok(response.headers.getSetCookie().some((c) => c.startsWith('gothwad_sess_b='))); +}); + +test('global sign-out uses only the fixed Accounts endpoint; failed mutations do not claim logout', async () => { + const p = provider(); + for (const success of [true, false]) { + const response = await handleAccountAction(makeRequest('/api/accounts/signout-all', { selector: 'a' }), env, async (url, init) => { + if (String(url).endsWith('/api/auth/me')) return p.fetcher(url, init); + assert.equal(url, 'https://api.gothwadtech.com/api/auth/signout'); + assert.equal(init?.redirect, 'error'); + assert.equal(init?.body, '{}'); + return json({ ok: success }); + }); + assert.equal(response.status, success ? 200 : 502); + assert.equal((await response.json()).ok === true, success); + } +});