From 8ebf191f3fda61af733f7607ee32a9765d449082 Mon Sep 17 00:00:00 2001 From: gempir Date: Sun, 8 Feb 2026 13:24:57 +0100 Subject: [PATCH] oauth flow --- .env.example | 1 + AGENTS.md | 4 +- dummy.patch | 48 --------------- src/lib/bitbucket-oauth.ts | 111 ++++++++++++++++++++++++++++++++++ src/lib/pr-context.tsx | 42 +++++++++++-- src/routeTree.gen.ts | 24 +++++++- src/routes/__root.tsx | 53 +++++++++------- src/routes/oauth/callback.tsx | 50 +++++++++++++++ 8 files changed, 253 insertions(+), 80 deletions(-) create mode 100644 .env.example delete mode 100644 dummy.patch create mode 100644 src/lib/bitbucket-oauth.ts create mode 100644 src/routes/oauth/callback.tsx diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..86fe125 --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +VITE_BITBUCKET_CLIENT_ID=CdujMQ8Bqyb8j75XdB diff --git a/AGENTS.md b/AGENTS.md index cd2ba25..2fa4587 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Always run after changes: - `bun run build` ## Key flows -- Onboarding + auth + repo selection: `src/lib/pr-context.tsx`, `src/routes/__root.tsx` +- OAuth + repo selection: `src/lib/bitbucket-oauth.ts`, `src/lib/pr-context.tsx`, `src/routes/__root.tsx`, `src/routes/oauth/callback.tsx` - PR input + PR list landing: `src/routes/index.tsx` - Bitbucket API fetch + diff parsing: `src/routes/index.tsx` - File tree data model: `src/lib/file-tree-context.tsx` @@ -26,7 +26,7 @@ Always run after changes: - Fetches: - `GET https://api.bitbucket.org/2.0/repositories///pullrequests//diff` - `GET https://api.bitbucket.org/2.0/repositories///pullrequests//diffstat?pagelen=100` -- Optional Bearer auth via API token (set in onboarding UI). +- OAuth app required. Set env:\n - `VITE_BITBUCKET_CLIENT_ID` (client/public)\n - `BITBUCKET_CLIENT_ID` and `BITBUCKET_CLIENT_SECRET` (server)\n+- OAuth endpoints:\n - `https://bitbucket.org/site/oauth2/authorize`\n - `https://bitbucket.org/site/oauth2/access_token`\n - Repository listing: `GET https://api.bitbucket.org/2.0/repositories?role=member&pagelen=100` - Repository listing: `GET https://api.bitbucket.org/2.0/repositories?role=member&pagelen=100` ## File tree + diff linking diff --git a/dummy.patch b/dummy.patch deleted file mode 100644 index bb69dfd..0000000 --- a/dummy.patch +++ /dev/null @@ -1,48 +0,0 @@ -From 7d9c824863cfe140a17dbfc0b805e725c57c8681 Mon Sep 17 00:00:00 2001 From: gempir - Date: Sat, 27 Dec 2025 18:25:30 +0100 Subject: [PATCH 1/2] color --- - web/app/components/Sidebar/Sidebar.tsx | 3 +-- web/app/styles/globals.css | 4 ++-- - web/app/theme.ts | 22 +++++++++++----------- 3 files changed, 14 insertions(+), 15 - deletions(-) -diff --git a/web/app/components/Sidebar/Sidebar.tsx b/web/app/components/Sidebar/Sidebar.tsx -index 8dd2e82..784deac 100644 --- a/web/app/components/Sidebar/Sidebar.tsx +++ -b/web/app/components/Sidebar/Sidebar.tsx @@ -64,7 +64,7 @@ export function Sidebar() { - letterSpacing: "0.1em", - }} - > - {">"} gempbot + gempbot - v2.0 {"// twitch bot"} @@ -110,7 +110,6 @@ export function Sidebar() { - to={link.href} label={ - - {isActive ? "> " : " "} - {link.label} - - } diff --git a/web/app/styles/globals.css b/web/app/styles/globals.css -index 289a6c4..26f97da 100644 --- a/web/app/styles/globals.css +++ -b/web/app/styles/globals.css @@ -5,8 +5,8 @@ - -:root {minal color palette */minal-green: #00ff99;minal-green-dim: #00cc7a;minal-green: -#28c88c;minal-green-dim: #20a070;minal-blue: #339af0;minal-red: #ff6b6b;minal-yellow: -#ffd43b; p/theme.ts b/web/app/theme.ts index ff3e71f..6133f91 100644 --- a/web/app/theme.ts -+++ b/web/app/theme.ts @@ -1,17 +1,17 @@ - import { createTheme, type MantineColorsTuple } from "@mantine/core"; - --// Terminal green - high contrast, technical feel +// Muted green - darker, more readable - const terminal: MantineColorsTuple = [ - "#e6fff5", - "#ccffeb", - "#99ffd6", - "#66ffc2", -- "#33ffad", - "#00ff99", // Primary terminal green - "#00e689", - "#00cc7a", - "#00b36b", - -"#00995c", + "#d4f4e8", + "#a9e9d1", + "#7edeba", + "#53d3a3", + "#28c88c", // Primary muted -green + "#20a070", + "#187854", + "#105038", + "#08281c", + "#000000", - ]; - - // Steel gray - mechanical, industrial -From 6b0f7839f35a3e892ec793d33bd0a188f4dc5b56 Mon Sep 17 00:00:00 2001 From: gempir - Date: Sat, 27 Dec 2025 18:28:12 +0100 Subject: [PATCH 2/2] fix case ---- - web/app/components/Sidebar/Login.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) -diff --git a/web/app/components/Sidebar/Login.tsx b/web/app/components/Sidebar/Login.tsx -index 10947ca..073f711 100644 --- a/web/app/components/Sidebar/Login.tsx +++ -b/web/app/components/Sidebar/Login.tsx @@ -26,7 +26,7 @@ export function Login() { - - logged in as{" "} - {scTokenContent?.login || -"user"} + {scTokenContent?.Login || "user"} - - - diff --git a/src/lib/bitbucket-oauth.ts b/src/lib/bitbucket-oauth.ts new file mode 100644 index 0000000..c078284 --- /dev/null +++ b/src/lib/bitbucket-oauth.ts @@ -0,0 +1,111 @@ +import { createServerFn } from "@tanstack/react-start"; + +export interface OAuthTokenResult { + accessToken: string; + refreshToken?: string; + expiresAt?: number; +} + +interface OAuthTokenResponse { + access_token: string; + refresh_token?: string; + expires_in?: number; +} + +function encodeBasicAuth(clientId: string, clientSecret: string) { + return Buffer.from(`${clientId}:${clientSecret}`).toString("base64"); +} + +export function buildAuthorizeUrl(params: { + clientId: string; + redirectUri: string; + state: string; + scope?: string; +}) { + const url = new URL("https://bitbucket.org/site/oauth2/authorize"); + url.searchParams.set("client_id", params.clientId); + url.searchParams.set("response_type", "code"); + url.searchParams.set("redirect_uri", params.redirectUri); + url.searchParams.set("state", params.state); + if (params.scope) { + url.searchParams.set("scope", params.scope); + } + return url.toString(); +} + +export const exchangeOAuthCode = createServerFn({ + method: "POST", +}).handler(async ({ data }: { data: { code: string; redirectUri: string } }) => { + const clientId = + process.env.BITBUCKET_CLIENT_ID ?? + process.env.VITE_BITBUCKET_CLIENT_ID ?? + ""; + const clientSecret = process.env.BITBUCKET_CLIENT_SECRET ?? ""; + if (!clientId || !clientSecret) { + throw new Error("Missing BITBUCKET_CLIENT_ID or BITBUCKET_CLIENT_SECRET"); + } + + const body = new URLSearchParams({ + grant_type: "authorization_code", + code: data.code, + redirect_uri: data.redirectUri, + }); + + const res = await fetch("https://bitbucket.org/site/oauth2/access_token", { + method: "POST", + headers: { + Authorization: `Basic ${encodeBasicAuth(clientId, clientSecret)}`, + "Content-Type": "application/x-www-form-urlencoded", + }, + body, + }); + + if (!res.ok) { + throw new Error(`OAuth token exchange failed: ${res.status} ${res.statusText}`); + } + + const payload = (await res.json()) as OAuthTokenResponse; + return { + accessToken: payload.access_token, + refreshToken: payload.refresh_token, + expiresAt: payload.expires_in ? Date.now() + payload.expires_in * 1000 : undefined, + } as OAuthTokenResult; +}); + +export const refreshOAuthToken = createServerFn({ + method: "POST", +}).handler(async ({ data }: { data: { refreshToken: string } }) => { + const clientId = + process.env.BITBUCKET_CLIENT_ID ?? + process.env.VITE_BITBUCKET_CLIENT_ID ?? + ""; + const clientSecret = process.env.BITBUCKET_CLIENT_SECRET ?? ""; + if (!clientId || !clientSecret) { + throw new Error("Missing BITBUCKET_CLIENT_ID or BITBUCKET_CLIENT_SECRET"); + } + + const body = new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: data.refreshToken, + }); + + const res = await fetch("https://bitbucket.org/site/oauth2/access_token", { + method: "POST", + headers: { + Authorization: `Basic ${encodeBasicAuth(clientId, clientSecret)}`, + "Content-Type": "application/x-www-form-urlencoded", + }, + body, + }); + + if (!res.ok) { + throw new Error(`OAuth refresh failed: ${res.status} ${res.statusText}`); + } + + const payload = (await res.json()) as OAuthTokenResponse; + return { + accessToken: payload.access_token, + refreshToken: payload.refresh_token, + expiresAt: payload.expires_in ? Date.now() + payload.expires_in * 1000 : undefined, + } as OAuthTokenResult; +}); diff --git a/src/lib/pr-context.tsx b/src/lib/pr-context.tsx index 2ead8a4..d6dd5ac 100644 --- a/src/lib/pr-context.tsx +++ b/src/lib/pr-context.tsx @@ -1,7 +1,10 @@ import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; +import { refreshOAuthToken } from "@/lib/bitbucket-oauth"; interface BitbucketAuth { accessToken: string; + refreshToken?: string; + expiresAt?: number; } export interface BitbucketRepo { @@ -29,13 +32,21 @@ export function PrProvider({ children }: { children: ReactNode }) { const [auth, setAuth] = useState(null); const [repos, setRepos] = useState([]); const [hydrated, setHydrated] = useState(false); + const [refreshing, setRefreshing] = useState(false); useEffect(() => { if (typeof window === "undefined") return; - const stored = window.localStorage.getItem("bitbucket_access_token"); + const stored = window.localStorage.getItem("bitbucket_oauth"); const storedRepos = window.localStorage.getItem("bitbucket_repos"); if (stored) { - setAuth({ accessToken: stored }); + try { + const parsed = JSON.parse(stored) as BitbucketAuth; + if (parsed?.accessToken) { + setAuth(parsed); + } + } catch { + window.localStorage.removeItem("bitbucket_oauth"); + } } if (storedRepos) { try { @@ -51,9 +62,9 @@ export function PrProvider({ children }: { children: ReactNode }) { useEffect(() => { if (!hydrated || typeof window === "undefined") return; if (auth?.accessToken) { - window.localStorage.setItem("bitbucket_access_token", auth.accessToken); + window.localStorage.setItem("bitbucket_oauth", JSON.stringify(auth)); } else { - window.localStorage.removeItem("bitbucket_access_token"); + window.localStorage.removeItem("bitbucket_oauth"); } }, [auth, hydrated]); @@ -69,7 +80,7 @@ export function PrProvider({ children }: { children: ReactNode }) { const clearAuth = () => { setAuth(null); if (typeof window !== "undefined") { - window.localStorage.removeItem("bitbucket_access_token"); + window.localStorage.removeItem("bitbucket_oauth"); } }; @@ -80,6 +91,27 @@ export function PrProvider({ children }: { children: ReactNode }) { } }; + useEffect(() => { + if (!hydrated || refreshing) return; + if (!auth?.refreshToken || !auth.expiresAt) return; + const now = Date.now(); + if (now < auth.expiresAt - 60_000) return; + + setRefreshing(true); + refreshOAuthToken({ data: { refreshToken: auth.refreshToken } }) + .then((next) => { + setAuth({ + accessToken: next.accessToken, + refreshToken: next.refreshToken ?? auth.refreshToken, + expiresAt: next.expiresAt, + }); + }) + .catch(() => { + clearAuth(); + }) + .finally(() => setRefreshing(false)); + }, [auth, clearAuth, hydrated, refreshing]); + return ( rootRouteImport, } as any) +const OauthCallbackRoute = OauthCallbackRouteImport.update({ + id: '/oauth/callback', + path: '/oauth/callback', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/oauth/callback': typeof OauthCallbackRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/oauth/callback': typeof OauthCallbackRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/oauth/callback': typeof OauthCallbackRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' + fullPaths: '/' | '/oauth/callback' fileRoutesByTo: FileRoutesByTo - to: '/' - id: '__root__' | '/' + to: '/' | '/oauth/callback' + id: '__root__' | '/' | '/oauth/callback' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + OauthCallbackRoute: typeof OauthCallbackRoute } declare module '@tanstack/react-router' { @@ -48,11 +58,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/oauth/callback': { + id: '/oauth/callback' + path: '/oauth/callback' + fullPath: '/oauth/callback' + preLoaderRoute: typeof OauthCallbackRouteImport + parentRoute: typeof rootRouteImport + } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + OauthCallbackRoute: OauthCallbackRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index c6fac29..357b33f 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -5,6 +5,7 @@ import { Link, Outlet, Scripts, + useRouterState, } from "@tanstack/react-router"; import type { ReactNode } from "react"; import { createServerFn } from "@tanstack/react-start"; @@ -20,6 +21,7 @@ import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { useState } from "react"; import { fileAnchorId } from "@/lib/file-anchors"; +import { buildAuthorizeUrl } from "@/lib/bitbucket-oauth"; import appCss from "../../styles.css?url"; @@ -113,8 +115,7 @@ function RootComponent() { } function OnboardingScreen() { - const { setAuth, auth, setRepos, clearAuth, clearRepos } = usePrContext(); - const [accessToken, setAccessToken] = useState(""); + const { auth, setRepos, clearAuth, clearRepos } = usePrContext(); const [query, setQuery] = useState(""); const [selected, setSelected] = useState>(new Set()); @@ -125,12 +126,6 @@ function OnboardingScreen() { enabled: Boolean(auth?.accessToken), }); - const handleContinue = () => { - const token = accessToken.trim(); - if (!token) return; - setAuth({ accessToken: token }); - }; - if (auth?.accessToken) { const entries = reposQuery.data ?? []; const filtered = entries.filter((repo) => { @@ -250,33 +245,42 @@ function OnboardingScreen() { ); } + const clientId = import.meta.env.VITE_BITBUCKET_CLIENT_ID as string | undefined; + return (

Connect Bitbucket

- Enter a Bitbucket Cloud access token to continue. It will be saved in - local storage on this device. + Connect your Bitbucket Cloud account to continue.

- setAccessToken(e.target.value)} - onKeyDown={(e) => e.key === "Enter" && handleContinue()} - className="h-9 text-sm" - autoComplete="current-password" - /> + {!clientId && ( +

+ Missing `VITE_BITBUCKET_CLIENT_ID` in your environment. +

+ )}
@@ -285,6 +289,11 @@ function OnboardingScreen() { function AppLayout() { const { auth, clearAuth, clearRepos, repos } = usePrContext(); + const pathname = useRouterState({ select: (state) => state.location.pathname }); + + if (pathname.startsWith("/oauth/callback")) { + return ; + } if (!auth?.accessToken) { return ; diff --git a/src/routes/oauth/callback.tsx b/src/routes/oauth/callback.tsx new file mode 100644 index 0000000..a1f340c --- /dev/null +++ b/src/routes/oauth/callback.tsx @@ -0,0 +1,50 @@ +import { createFileRoute, useNavigate } from "@tanstack/react-router"; +import { useEffect, useState } from "react"; +import { exchangeOAuthCode } from "@/lib/bitbucket-oauth"; +import { usePrContext } from "@/lib/pr-context"; + +export const Route = createFileRoute("/oauth/callback")({ + component: OAuthCallback, +}); + +function OAuthCallback() { + const navigate = useNavigate(); + const { setAuth } = usePrContext(); + const [message, setMessage] = useState("Completing sign-in..."); + + useEffect(() => { + const url = new URL(window.location.href); + const code = url.searchParams.get("code"); + const state = url.searchParams.get("state"); + const storedState = window.localStorage.getItem("bitbucket_oauth_state"); + window.localStorage.removeItem("bitbucket_oauth_state"); + + if (!code || !state || !storedState || state !== storedState) { + setMessage("OAuth state mismatch. Please try again."); + return; + } + + const redirectUri = `${window.location.origin}/oauth/callback`; + exchangeOAuthCode({ data: { code, redirectUri } }) + .then((result) => { + setAuth({ + accessToken: result.accessToken, + refreshToken: result.refreshToken, + expiresAt: result.expiresAt, + }); + navigate({ to: "/" }); + }) + .catch((err) => { + const msg = err instanceof Error ? err.message : "OAuth failed"; + setMessage(msg); + }); + }, [navigate, setAuth]); + + return ( +
+
+ {message} +
+
+ ); +} -- knotmirror 0.0.1