From cf492c30d840d87d6d95046377376fea1637272f Mon Sep 17 00:00:00 2001 From: Hyo Date: Fri, 20 Nov 2026 19:40:03 +0900 Subject: [PATCH] feat: verify GitHub installation access outside sign-in Recording which GitHub App installations a user can reach no longer depends on the sign-in library, which @convex-dev/auth 2.0 needs because its GitHub sign-in keeps the user token to itself. - "Verify GitHub access": an authenticated action starts a GitHub App user authorization (state stored only as a hash, PKCE S256, 10-minute expiry); the /github/access/callback route exchanges the code, records the installations only for the GitHub account linked to that user, revokes the token and returns to a path on Gitdog's site. - The redirect URI uses the same host as the sign-in callback (CUSTOM_AUTH_SITE_URL or CONVEX_SITE_URL); both callbacks are documented for the GitHub App. - The connect page starts it and reports cancelled, failed or mismatched accounts; the consent page's sign-in re-authorization path is removed. - CLI: new github verify command; github recover points to it. - Sign-in and the new flow share one attestation save and linked-account lookup. --- convex/_generated/api.d.ts | 4 + convex/github/accessVerification.ts | 246 +++++++++++++++++ convex/github/accessVerificationResult.ts | 14 + convex/github/action.ts | 50 ++++ convex/github/internalMutation.ts | 85 ++++++ convex/github/oauthInstallationAttestation.ts | 81 ++++-- convex/http.ts | 9 + convex/schema.ts | 14 + docs/github-app-setup.md | 13 +- packages/cli/README.md | 2 +- packages/cli/docs/REFERENCE.md | 3 +- packages/cli/src/api-catalog.json | 5 + packages/cli/src/commands.ts | 22 +- packages/cli/test/commands.test.mjs | 38 ++- src/i18n/locales/en.json | 5 + src/i18n/locales/ja.json | 5 + src/i18n/locales/ko.json | 5 + src/pages/legal/consent.tsx | 85 +----- src/pages/repositories/connect.tsx | 52 +++- src/utils/legalConsent.ts | 35 +-- test/convex/github/accessVerification.test.ts | 250 ++++++++++++++++++ test/pages/legalAgeCompliance.test.ts | 15 -- test/pages/legalConsentPage.test.ts | 19 -- test/utils/legalConsentView.test.ts | 34 +-- 24 files changed, 883 insertions(+), 208 deletions(-) create mode 100644 convex/github/accessVerification.ts create mode 100644 convex/github/accessVerificationResult.ts create mode 100644 test/convex/github/accessVerification.test.ts diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index a8faa68..722320f 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -61,6 +61,8 @@ import type * as apiKeys_query from "../apiKeys/query.js"; import type * as apiKeys_security from "../apiKeys/security.js"; import type * as auth from "../auth.js"; import type * as crons from "../crons.js"; +import type * as github_accessVerification from "../github/accessVerification.js"; +import type * as github_accessVerificationResult from "../github/accessVerificationResult.js"; import type * as github_action from "../github/action.js"; import type * as github_botIdentity from "../github/botIdentity.js"; import type * as github_helpers from "../github/helpers.js"; @@ -234,6 +236,8 @@ declare const fullApi: ApiFromModules<{ "apiKeys/security": typeof apiKeys_security; auth: typeof auth; crons: typeof crons; + "github/accessVerification": typeof github_accessVerification; + "github/accessVerificationResult": typeof github_accessVerificationResult; "github/action": typeof github_action; "github/botIdentity": typeof github_botIdentity; "github/helpers": typeof github_helpers; diff --git a/convex/github/accessVerification.ts b/convex/github/accessVerification.ts new file mode 100644 index 0000000..9a387e5 --- /dev/null +++ b/convex/github/accessVerification.ts @@ -0,0 +1,246 @@ +import { httpAction } from "../_generated/server"; +import { internal } from "../_generated/api"; +import { + fetchAccessibleGitHubInstallationIds, + GITHUB_INSTALLATION_ATTESTATION_REQUEST_TIMEOUT_MS, + githubApiHeaders, +} from "./oauthInstallationAttestation"; +import { + ACCESS_VERIFICATION_RESULT_PARAM, + type AccessVerificationResult, +} from "./accessVerificationResult"; + +/** + * "Verify GitHub access": a GitHub App user authorization, separate from + * sign-in, that records which installations the signed-in user can reach. + * The user token lives only for the callback request and is revoked after. + */ +export const ACCESS_VERIFICATION_CALLBACK_PATH = "/github/access/callback"; +export const ACCESS_VERIFICATION_TTL_MS = 10 * 60 * 1_000; +const DEFAULT_RETURN_PATH = "/repositories/connect"; + +/** + * Where GitHub sends the user back: the same site as sign-in's OAuth + * callback, so one GitHub App lists both under one host. + */ +export function accessVerificationRedirectUri(): string | null { + const site = + process.env.CUSTOM_AUTH_SITE_URL || process.env.CONVEX_SITE_URL || null; + return site && `${site}${ACCESS_VERIFICATION_CALLBACK_PATH}`; +} + +function base64Url(bytes: Uint8Array): string { + return btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +async function sha256(value: string): Promise { + return new Uint8Array( + await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)), + ); +} + +/** A random secret for the OAuth state or the PKCE verifier. */ +export function generateSecret(): string { + return base64Url(crypto.getRandomValues(new Uint8Array(32))); +} + +export async function hashState(state: string): Promise { + return Array.from(await sha256(state), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} + +/** A path on Gitdog's site to return to; anything else is refused. */ +export function readReturnPath(value: string): string | null { + if (!value.startsWith("/") || value.includes("\\")) return null; + const base = "https://gitdog.invalid"; + try { + const url = new URL(value, base); + // Check the normalized path: "/..//evil.example" becomes "//evil.example", + // which a browser reads as another host. + if (url.origin !== base || url.pathname.startsWith("//")) return null; + return `${url.pathname}${url.search}`; + } catch { + return null; + } +} + +export async function buildAuthorizeUrl(args: { + clientId: string; + redirectUri: string; + state: string; + codeVerifier: string; +}): Promise { + const url = new URL("https://github.com/login/oauth/authorize"); + url.searchParams.set("client_id", args.clientId); + url.searchParams.set("redirect_uri", args.redirectUri); + url.searchParams.set("state", args.state); + url.searchParams.set( + "code_challenge", + base64Url(await sha256(args.codeVerifier)), + ); + url.searchParams.set("code_challenge_method", "S256"); + url.searchParams.set("allow_signup", "false"); + return url.toString(); +} + +async function requestJson( + url: string, + init: RequestInit, +): Promise> { + const response = await fetch(url, { + ...init, + signal: AbortSignal.timeout( + GITHUB_INSTALLATION_ATTESTATION_REQUEST_TIMEOUT_MS, + ), + }); + if (!response.ok) throw new Error(`GitHub returned ${response.status}`); + const payload = (await response.json()) as unknown; + if (payload === null || typeof payload !== "object" || Array.isArray(payload)) + throw new Error("GitHub returned an invalid response"); + return payload as Record; +} + +async function exchangeCode(args: { + code: string; + codeVerifier: string; + clientId: string; + clientSecret: string; + redirectUri: string; +}): Promise { + const payload = await requestJson( + "https://github.com/login/oauth/access_token", + { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/json", + }, + body: JSON.stringify({ + client_id: args.clientId, + client_secret: args.clientSecret, + code: args.code, + code_verifier: args.codeVerifier, + redirect_uri: args.redirectUri, + }), + }, + ); + const token = payload.access_token; + if (typeof token !== "string" || token === "") + throw new Error("GitHub did not grant user authorization"); + return token; +} + +async function fetchGitHubAccountId(token: string): Promise { + const user = await requestJson("https://api.github.com/user", { + headers: githubApiHeaders(`Bearer ${token}`), + }); + if (typeof user.id !== "number" || !Number.isSafeInteger(user.id)) + throw new Error("GitHub returned an invalid user"); + return user.id.toString(); +} + +/** Best effort: the token is never stored, and GitHub expires it anyway. */ +async function revokeToken(args: { + token: string; + clientId: string; + clientSecret: string; +}): Promise { + try { + await fetch(`https://api.github.com/applications/${args.clientId}/token`, { + method: "DELETE", + headers: githubApiHeaders( + `Basic ${btoa(`${args.clientId}:${args.clientSecret}`)}`, + ), + body: JSON.stringify({ access_token: args.token }), + signal: AbortSignal.timeout( + GITHUB_INSTALLATION_ATTESTATION_REQUEST_TIMEOUT_MS, + ), + }); + } catch { + // The token expires on GitHub's side regardless. + } +} + +function returnTo( + siteUrl: string, + returnPath: string, + result: AccessVerificationResult, +): Response { + let url = new URL(returnPath, siteUrl); + // Never leave Gitdog's site, whatever the stored path says. + if (url.origin !== new URL(siteUrl).origin) + url = new URL(DEFAULT_RETURN_PATH, siteUrl); + url.searchParams.set(ACCESS_VERIFICATION_RESULT_PARAM, result); + return new Response(null, { + status: 302, + headers: { Location: url.toString(), "Cache-Control": "no-store" }, + }); +} + +export const accessVerificationCallback = httpAction(async (ctx, request) => { + const siteUrl = process.env.SITE_URL; + const clientId = process.env.GITHUB_APP_CLIENT_ID; + const clientSecret = process.env.GITHUB_APP_CLIENT_SECRET; + const redirectUri = accessVerificationRedirectUri(); + if (!siteUrl || !clientId || !clientSecret || !redirectUri) + return new Response("GitHub access verification is not configured", { + status: 503, + }); + + const params = new URL(request.url).searchParams; + const state = params.get("state"); + if (!state) return returnTo(siteUrl, DEFAULT_RETURN_PATH, "failed"); + const pending = await ctx.runMutation( + internal.github.internalMutation.consumeAccessVerification, + { stateHash: await hashState(state), now: Date.now() }, + ); + if (!pending) return returnTo(siteUrl, DEFAULT_RETURN_PATH, "failed"); + if (pending.expired) return returnTo(siteUrl, pending.returnPath, "failed"); + + const code = params.get("code"); + if (!code) { + // Only the user declining is a cancellation; GitHub reports setup + // problems such as a redirect_uri mismatch the same way. + const declined = params.get("error") === "access_denied"; + if (!declined) + console.error("GitHub access verification error:", params.get("error")); + return returnTo( + siteUrl, + pending.returnPath, + declined ? "cancelled" : "failed", + ); + } + + let token: string | null = null; + try { + token = await exchangeCode({ + code, + codeVerifier: pending.codeVerifier, + clientId, + clientSecret, + redirectUri, + }); + const [githubAccountId, installationIds] = await Promise.all([ + fetchGitHubAccountId(token), + fetchAccessibleGitHubInstallationIds(token), + ]); + const result = await ctx.runMutation( + internal.github.internalMutation.saveVerifiedInstallationAccess, + { userId: pending.userId, githubAccountId, installationIds }, + ); + return returnTo(siteUrl, pending.returnPath, result); + } catch (error) { + // Messages never include the token. + console.error( + "GitHub access verification failed:", + error instanceof Error ? error.message : "unknown error", + ); + return returnTo(siteUrl, pending.returnPath, "failed"); + } finally { + if (token) await revokeToken({ token, clientId, clientSecret }); + } +}); diff --git a/convex/github/accessVerificationResult.ts b/convex/github/accessVerificationResult.ts new file mode 100644 index 0000000..f89e8d8 --- /dev/null +++ b/convex/github/accessVerificationResult.ts @@ -0,0 +1,14 @@ +// Shared with the web app, so this module imports nothing. + +/** The query parameter the return page reads to show how verification ended. */ +export const ACCESS_VERIFICATION_RESULT_PARAM = "githubAccess"; + +/** The outcomes other than success, each with its own message. */ +export const ACCESS_VERIFICATION_PROBLEMS = [ + "account_mismatch", + "cancelled", + "failed", +] as const; + +export type AccessVerificationResult = + "verified" | (typeof ACCESS_VERIFICATION_PROBLEMS)[number]; diff --git a/convex/github/action.ts b/convex/github/action.ts index 100b9fb..f276574 100644 --- a/convex/github/action.ts +++ b/convex/github/action.ts @@ -18,6 +18,14 @@ import { } from "./repositoryIdentity"; import { INSTALLATION_WEBHOOK_STATE_MAX_RETRY_COUNT } from "./webhookAccessStateAttestation"; import { REPOSITORY_ACCESS_RECONCILIATION_MAX_RETRY_COUNT } from "./repositoryAccessReconciliation"; +import { + ACCESS_VERIFICATION_TTL_MS, + accessVerificationRedirectUri, + buildAuthorizeUrl, + generateSecret, + hashState, + readReturnPath, +} from "./accessVerification"; const RECONCILIATION_PAGE_SIZE = 50; const RECONCILIATION_STALE_AFTER_MS = 10 * 60 * 1_000; @@ -1324,3 +1332,45 @@ export const recoverOAuthInstallation = action({ } }, }); + +/** + * Start "Verify GitHub access": returns the GitHub authorization URL that + * records which installations the signed-in user can reach, then returns to + * `returnPath` on Gitdog's site. + */ +export const startAccessVerification = action({ + args: { returnPath: v.string() }, + returns: v.object({ url: v.string() }), + handler: async (ctx, args) => { + const userId = await getAuthUserId(ctx); + if (!userId) throw new Error("Not authenticated"); + const returnPath = readReturnPath(args.returnPath); + if (returnPath === null) throw new Error("Invalid return path"); + const clientId = process.env.GITHUB_APP_CLIENT_ID; + const redirectUri = accessVerificationRedirectUri(); + if (!clientId || !redirectUri) + throw new Error("GitHub access verification is not configured"); + + const state = generateSecret(); + const codeVerifier = generateSecret(); + await ctx.runMutation( + internal.github.internalMutation.createAccessVerification, + { + userId, + stateHash: await hashState(state), + codeVerifier, + returnPath, + now: Date.now(), + ttlMs: ACCESS_VERIFICATION_TTL_MS, + }, + ); + return { + url: await buildAuthorizeUrl({ + clientId, + redirectUri, + state, + codeVerifier, + }), + }; + }, +}); diff --git a/convex/github/internalMutation.ts b/convex/github/internalMutation.ts index 742f9f9..ccbfa17 100644 --- a/convex/github/internalMutation.ts +++ b/convex/github/internalMutation.ts @@ -2,6 +2,10 @@ import { internalMutation, type MutationCtx } from "../_generated/server"; import { v } from "convex/values"; import { internal } from "../_generated/api"; import { getExactGitHubInstallation } from "./installationAccess"; +import { + readLinkedGitHubAccountId, + saveInstallationAttestation, +} from "./oauthInstallationAttestation"; import { getInstallationWebhookStateRetryDelayMs, INSTALLATION_WEBHOOK_STATE_ATTEMPT_LEASE_MS, @@ -1210,3 +1214,84 @@ export const markInstallationActiveAfterReconciliation = internalMutation({ return true; }, }); + +/** + * Record a pending "Verify GitHub access" authorization. A user has at most + * one; starting another replaces it. + */ +export const createAccessVerification = internalMutation({ + args: { + userId: v.id("users"), + stateHash: v.string(), + codeVerifier: v.string(), + returnPath: v.string(), + now: v.number(), + ttlMs: v.number(), + }, + returns: v.null(), + handler: async (ctx, args) => { + const previous = await ctx.db + .query("githubAccessVerifications") + .withIndex("by_user", (q) => q.eq("userId", args.userId)) + .first(); + if (previous) await ctx.db.delete(previous._id); + await ctx.db.insert("githubAccessVerifications", { + userId: args.userId, + stateHash: args.stateHash, + codeVerifier: args.codeVerifier, + returnPath: args.returnPath, + createdAt: args.now, + expiresAt: args.now + args.ttlMs, + }); + return null; + }, +}); + +/** Take a pending verification by its state; each state works once. */ +export const consumeAccessVerification = internalMutation({ + args: { stateHash: v.string(), now: v.number() }, + returns: v.union( + v.null(), + v.object({ + userId: v.id("users"), + codeVerifier: v.string(), + returnPath: v.string(), + expired: v.boolean(), + }), + ), + handler: async (ctx, args) => { + const row = await ctx.db + .query("githubAccessVerifications") + .withIndex("by_state_hash", (q) => q.eq("stateHash", args.stateHash)) + .unique(); + if (!row) return null; + await ctx.db.delete(row._id); + return { + userId: row.userId, + codeVerifier: row.codeVerifier, + returnPath: row.returnPath, + expired: row.expiresAt <= args.now, + }; + }, +}); + +/** + * Save the installations GitHub reported for the user who started the + * verification, only when the authorizing GitHub account is the one linked + * to that user. + */ +export const saveVerifiedInstallationAccess = internalMutation({ + args: { + userId: v.id("users"), + githubAccountId: v.string(), + installationIds: v.array(v.number()), + }, + returns: v.union(v.literal("verified"), v.literal("account_mismatch")), + handler: async (ctx, args) => { + const linked = await readLinkedGitHubAccountId(ctx, args.userId); + if (linked === null || linked !== args.githubAccountId) + return "account_mismatch" as const; + await saveInstallationAttestation(ctx, { ...args, now: Date.now() }); + return "verified" as const; + }, +}); diff --git a/convex/github/oauthInstallationAttestation.ts b/convex/github/oauthInstallationAttestation.ts index 7cb6cfb..20da29d 100644 --- a/convex/github/oauthInstallationAttestation.ts +++ b/convex/github/oauthInstallationAttestation.ts @@ -56,6 +56,16 @@ function readOptionalProfileString(value: unknown): string | undefined { return typeof value === "string" && value.trim() !== "" ? value : undefined; } +/** Headers for GitHub's REST API with the given Authorization value. */ +export function githubApiHeaders(authorization: string): HeadersInit { + return { + Accept: "application/vnd.github+json", + Authorization: authorization, + "User-Agent": "Gitdog", + "X-GitHub-Api-Version": "2022-11-28", + }; +} + /** * Resolve every GitHub App installation currently associated with one user * access token. The token remains local to this request and is never returned. @@ -94,12 +104,7 @@ export async function fetchAccessibleGitHubInstallationIds( ); try { const response = await request(url, { - headers: { - Accept: "application/vnd.github+json", - Authorization: `Bearer ${accessToken}`, - "User-Agent": "Gitdog", - "X-GitHub-Api-Version": "2022-11-28", - }, + headers: githubApiHeaders(`Bearer ${accessToken}`), signal: abortController.signal, }); if (!response.ok) { @@ -187,25 +192,64 @@ export async function persistGitHubInstallationAttestation( if (userId === null) { userId = await ctx.db.insert("users", userFields); } else { - const [user, accounts] = await Promise.all([ + const [user, linkedAccountId] = await Promise.all([ ctx.db.get(userId), - ctx.db - .query("authAccounts") - .withIndex("userIdAndProvider", (q) => - q.eq("userId", userId!).eq("provider", "github"), - ) - .take(2), + readLinkedGitHubAccountId(ctx, userId), ]); - if ( - !user || - accounts.length !== 1 || - accounts[0].providerAccountId !== githubAccountId - ) { + if (!user || linkedAccountId !== githubAccountId) { throw new Error("GitHub account identity changed during sign-in"); } await ctx.db.patch(userId, userFields); } + await saveInstallationAttestation(ctx, { + userId, + githubAccountId, + installationIds, + now, + }); + return userId; +} + +/** + * The GitHub account id linked to a Gitdog user, or null when the user has + * none or more than one. Installation access is attested against it. + */ +export async function readLinkedGitHubAccountId( + ctx: Pick, + userId: Id<"users">, +): Promise { + const accounts = await ctx.db + .query("authAccounts") + .withIndex("userIdAndProvider", (q) => + q.eq("userId", userId).eq("provider", "github"), + ) + .take(2); + return accounts.length === 1 + ? readGitHubAccountId(accounts[0].providerAccountId) + : null; +} + +/** + * Replace the user's short-lived installation snapshot. One snapshot exists + * per user and per GitHub account, and they must be the same row. + */ +export async function saveInstallationAttestation( + ctx: MutationCtx, + args: { + userId: Id<"users">; + githubAccountId: string; + installationIds: unknown; + now: number; + }, +): Promise { + const { userId, now } = args; + const githubAccountId = readGitHubAccountId(args.githubAccountId); + const installationIds = normalizeInstallationIds(args.installationIds); + if (githubAccountId === null || installationIds === null) { + throw new Error("GitHub installation attestation is invalid"); + } + const [byUser, byAccount] = await Promise.all([ ctx.db .query("githubOAuthInstallationAttestations") @@ -243,5 +287,4 @@ export async function persistGitHubInstallationAttestation( } else { await ctx.db.insert("githubOAuthInstallationAttestations", snapshot); } - return userId; } diff --git a/convex/http.ts b/convex/http.ts index cc9a569..a29dd3b 100644 --- a/convex/http.ts +++ b/convex/http.ts @@ -15,6 +15,10 @@ import { } from "./github/webhook"; import { handleLemonSqueezyWebhook } from "./lemonSqueezy/webhook"; import { getWorkloadJwks, WORKLOAD_JWKS_PATH } from "./_ai/federation"; +import { + ACCESS_VERIFICATION_CALLBACK_PATH, + accessVerificationCallback, +} from "./github/accessVerification"; import { handlePullRequestEvent } from "./pullRequests/webhook"; @@ -22,6 +26,11 @@ const http = httpRouter(); auth.addHttpRoutes(http); http.route({ path: "/v1/cli", method: "POST", handler: projectApi }); +http.route({ + path: ACCESS_VERIFICATION_CALLBACK_PATH, + method: "GET", + handler: accessVerificationCallback, +}); http.route({ path: WORKLOAD_JWKS_PATH, diff --git a/convex/schema.ts b/convex/schema.ts index 991db42..8733448 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -1118,6 +1118,20 @@ const applicationTables = { .index("by_user", ["userId"]) .index("by_github_account", ["githubAccountId"]), + // Pending "Verify GitHub access" authorizations, keyed by a hash of the + // OAuth state so the state itself is never stored. + githubAccessVerifications: defineTable({ + userId: v.id("users"), + stateHash: v.string(), + // The PKCE verifier GitHub checks when the code is exchanged. + codeVerifier: v.string(), + returnPath: v.string(), + createdAt: v.number(), + expiresAt: v.number(), + }) + .index("by_state_hash", ["stateHash"]) + .index("by_user", ["userId"]), + githubInstallations: defineTable({ userId: v.id("users"), installationId: v.number(), diff --git a/docs/github-app-setup.md b/docs/github-app-setup.md index 7632701..8ba0dd6 100644 --- a/docs/github-app-setup.md +++ b/docs/github-app-setup.md @@ -24,12 +24,16 @@ Go to: - **GitHub App name**: Choose a unique name whose slug matches `VITE_GITHUB_APP_SLUG` (the local default slug is `gitdogbot-dev`) - **Homepage URL**: `http://localhost:5173` (production: `https://gitdog.dev`) -- **Callback URL**: - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github` +- **Callback URLs** (add both): + - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github`, the + sign-in callback + - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/github/access/callback`, the + "Verify GitHub access" callback that records which installations a + signed-in user can reach - Use the concrete `CUSTOM_AUTH_SITE_URL` when it is configured; otherwise, use the target deployment's concrete `CONVEX_SITE_URL`, such as `https://example-deployment.convex.site` - - This is the OAuth authentication callback; it is not the frontend Setup URL + - These are OAuth callbacks; they are not the frontend Setup URL - **Setup URL**: `http://localhost:5173/repositories/connect` - ✅ Check "Redirect on update" @@ -233,7 +237,8 @@ For production deployment: 1. Update GitHub App settings: - Homepage URL: `https://gitdog.dev` - Callback URL: - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github`, + `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github` and + `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/github/access/callback`, using the concrete production custom auth site URL when configured and the concrete production Convex site URL otherwise - Setup URL: `https://gitdog.dev/repositories/connect` diff --git a/packages/cli/README.md b/packages/cli/README.md index 85568e9..d14de75 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -39,7 +39,7 @@ npx gitdog@latest --help ```sh npx gitdog@latest login npx gitdog@latest github install -npx gitdog@latest github recover +npx gitdog@latest github recover # if asked, run github verify first npx gitdog@latest init owner/repo npx gitdog@latest config set requireApproval true npx gitdog@latest config set pullRequestReviewsEnabled true diff --git a/packages/cli/docs/REFERENCE.md b/packages/cli/docs/REFERENCE.md index e77aa20..bdbc622 100644 --- a/packages/cli/docs/REFERENCE.md +++ b/packages/cli/docs/REFERENCE.md @@ -22,6 +22,7 @@ new GitHub repository. GitHub App permissions remain controlled by GitHub. ```sh gitdog github install +gitdog github verify gitdog github recover gitdog projects available gitdog projects create owner/repo @@ -212,7 +213,7 @@ are excluded. All authorization is enforced by the backend. | Usage and quota | `usage summary/projects/estimate/quota` | | Plans and token packs | `billing status/pricing/checkout` | | Account | `account profile/sync/consent` | -| GitHub App access | `github install/installations/recover/bind/retry` | +| GitHub App access | `github install/installations/verify/recover/bind/retry` | | Complete public API | `api list/describe/call` | `repos` is an alias for `projects`. Firebase-style colon commands work too: diff --git a/packages/cli/src/api-catalog.json b/packages/cli/src/api-catalog.json index 8e31575..52a4c20 100644 --- a/packages/cli/src/api-catalog.json +++ b/packages/cli/src/api-catalog.json @@ -139,6 +139,11 @@ "kind": "action", "args": "{\n installationId: v.number(),\n }" }, + { + "path": "github/action:startAccessVerification", + "kind": "action", + "args": "{ returnPath: v.string() }" + }, { "path": "github/query:getInstallation", "kind": "query", diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 22622db..332be55 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -1439,6 +1439,26 @@ export function createProgram( "gitdogai", ) .option("--print", "Print the installation URL"); + command( + github, + "verify", + "Open GitHub to verify which installations you can access", + async ({ api, ui }, _args, opts) => { + const result = asRecord( + await api.call("action", "github/action:startAccessVerification", { + returnPath: "/repositories/connect", + }), + ); + const url = typeof result?.url === "string" ? result.url : undefined; + if (!url?.startsWith("https://github.com/")) + throw new Error("Gitdog returned an invalid GitHub authorization URL."); + if (!ui.json && !flag(opts.print)) await openBrowser(url); + ui.output({ + url, + next: "After GitHub returns you to Gitdog, run npx gitdog@latest github recover.", + }); + }, + ).option("--print", "Print the GitHub authorization URL"); command( github, "recover", @@ -1452,7 +1472,7 @@ export function createProgram( ui.output({ ...result, recoveredCount: count }); if (result?.status === "reauth_required") throw new Error( - "Refresh GitHub authorization with npx gitdog@latest login, then run github recover again.", + "Verify GitHub access with npx gitdog@latest github verify, then run github recover again.", ); return; } diff --git a/packages/cli/test/commands.test.mjs b/packages/cli/test/commands.test.mjs index 1f1fef1..f607112 100644 --- a/packages/cli/test/commands.test.mjs +++ b/packages/cli/test/commands.test.mjs @@ -292,6 +292,42 @@ for (const [input, expectedKind, expectedPath, expectedArgs] of scenarios) { }); } +test("github verify starts access verification and accepts only GitHub URLs", async () => { + const run = async (url) => { + const calls = []; + const api = { + async call(kind, path, args = {}) { + calls.push({ kind, path, args }); + return { url }; + }, + }; + const ui = new CaptureUi(); + await createProgram({ api, ui }).parseAsync(["github", "verify"], { + from: "user", + }); + return { calls, ui }; + }; + + const { calls, ui } = await run( + "https://github.com/login/oauth/authorize?state=x", + ); + assert.deepEqual(calls, [ + { + kind: "action", + path: "github/action:startAccessVerification", + args: { returnPath: "/repositories/connect" }, + }, + ]); + assert.equal( + ui.values[0].url, + "https://github.com/login/oauth/authorize?state=x", + ); + await assert.rejects( + run("https://evil.example/login"), + /invalid GitHub authorization URL/, + ); +}); + test("mutation confirmation happens before a GitHub action executes", async () => { let called = false; const api = { @@ -418,7 +454,7 @@ test("all catalog paths are unique public functions and version matches the npm new Set(API_CATALOG.map((entry) => entry.path)).size, API_CATALOG.length, ); - assert.equal(API_CATALOG.length, 97); + assert.equal(API_CATALOG.length, 98); assert.equal( API_CATALOG.every( (entry) => diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index c5c2178..80160af 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -261,6 +261,11 @@ "recoveryUnavailable": "GitHub installation recovery is temporarily unavailable. Refresh the page and try again.", "recoveryLimitExceeded": "GitHub installation recovery exceeded the supported limit. Contact support to continue.", "reconnectTargetUnavailable": "This repository is no longer available to reconnect." + }, + "accessVerification": { + "failed": "GitHub access could not be verified. Try again.", + "cancelled": "GitHub access verification was cancelled.", + "account_mismatch": "That GitHub account is not the one you signed in with. Verify with the same account." } }, "settings": { diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 63cfbf4..dfa169a 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -261,6 +261,11 @@ "recoveryUnavailable": "GitHubインストールの復旧を一時的に利用できません。ページを更新してもう一度お試しください。", "recoveryLimitExceeded": "GitHubインストールの復旧がサポート上限を超えました。続行するにはサポートへお問い合わせください。", "reconnectTargetUnavailable": "このリポジトリは再接続できなくなりました。" + }, + "accessVerification": { + "failed": "GitHub のアクセスを確認できませんでした。もう一度お試しください。", + "cancelled": "GitHub のアクセス確認がキャンセルされました。", + "account_mismatch": "サインインした GitHub アカウントと異なります。同じアカウントで確認してください。" } }, "settings": { diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index ec946bd..d6b5b56 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -261,6 +261,11 @@ "recoveryUnavailable": "GitHub 설치 복구를 일시적으로 사용할 수 없습니다. 페이지를 새로고침한 후 다시 시도하세요.", "recoveryLimitExceeded": "GitHub 설치 복구가 지원 한도를 초과했습니다. 계속하려면 지원팀에 문의하세요.", "reconnectTargetUnavailable": "이 저장소를 더 이상 다시 연결할 수 없습니다." + }, + "accessVerification": { + "failed": "GitHub 접근을 확인하지 못했습니다. 다시 시도하세요.", + "cancelled": "GitHub 접근 확인이 취소되었습니다.", + "account_mismatch": "로그인한 GitHub 계정과 다른 계정입니다. 같은 계정으로 확인하세요." } }, "settings": { diff --git a/src/pages/legal/consent.tsx b/src/pages/legal/consent.tsx index d54d610..e70eaa9 100644 --- a/src/pages/legal/consent.tsx +++ b/src/pages/legal/consent.tsx @@ -17,7 +17,6 @@ import { getLegalConsentReturnPath, hasPendingLegalConsent, isLegalPolicyVersionMismatch, - isGitHubReauthorizationRequested, markPendingLegalConsent, resolveLegalConsentView, shouldAutoAttestAfterSignIn, @@ -62,11 +61,7 @@ export function LegalConsentPage() { const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); const automaticAttestationAttempted = useRef(false); - const authorizationRefreshAttempted = useRef(false); const returnPath = getLegalConsentReturnPath(location.search); - const refreshGitHubAuthorizationRequested = isGitHubReauthorizationRequested( - location.search, - ); const completeAuthenticatedAttestation = useCallback(async () => { setIsSubmitting(true); @@ -141,37 +136,10 @@ export function LegalConsentPage() { } }, [isAuthResolving, isAuthenticated, returningFromConsentedSignIn]); - const refreshGitHubAuthorization = useCallback(async () => { - authorizationRefreshAttempted.current = true; - setIsSubmitting(true); - setError(null); - try { - await signIn("github", { redirectTo: returnPath }); - } catch { - setError(t("auth.legalConsent.signInError")); - setIsSubmitting(false); - } - }, [returnPath, signIn, t]); - - useEffect(() => { - if ( - currentUser?.hasCurrentLegalAttestation && - refreshGitHubAuthorizationRequested && - !authorizationRefreshAttempted.current - ) { - void refreshGitHubAuthorization(); - } - }, [ - currentUser, - refreshGitHubAuthorization, - refreshGitHubAuthorizationRequested, - ]); - const view = resolveLegalConsentView({ currentUserLoaded: currentUser !== undefined, hasCurrentLegalAttestation: currentUser?.hasCurrentLegalAttestation ?? false, - refreshGitHubAuthorizationRequested, returningFromConsentedSignIn, signInCompletionFailed, }); @@ -190,58 +158,7 @@ export function LegalConsentPage() { ); } - if (view === "reauthorize" || view === "redirectToReturnPath") { - if (view === "reauthorize") { - return ( -
-
- -

- {t("repositories.connect.verificationPending.reauthorize")} -

-

- {error ?? - t("repositories.connect.verificationPending.reauthDescription")} -

- -
-
- ); - } + if (view === "redirectToReturnPath") { return ; } diff --git a/src/pages/repositories/connect.tsx b/src/pages/repositories/connect.tsx index f117a37..f22e6b4 100644 --- a/src/pages/repositories/connect.tsx +++ b/src/pages/repositories/connect.tsx @@ -9,7 +9,10 @@ import { LoadingIndicator } from "../../components/uis/LoadingIndicator"; import { showToast } from "../../utils/signals/toast"; import { useTranslation } from "react-i18next"; import { cn } from "../../utils/cn"; -import { createGitHubReauthorizationConsentUrl } from "../../utils/legalConsent"; +import { + ACCESS_VERIFICATION_PROBLEMS, + ACCESS_VERIFICATION_RESULT_PARAM, +} from "../../../convex/github/accessVerificationResult"; import { clearPendingReconnectMapping, consumePendingReconnectMapping, @@ -66,6 +69,10 @@ export function RepositoryConnect() { ); const ensureProfile = useMutation(api.users.mutation.ensureProfileFromAuth); const refreshInstallation = useAction(api.github.action.saveInstallation); + const startAccessVerification = useAction( + api.github.action.startAccessVerification, + ); + const [isStartingVerification, setIsStartingVerification] = useState(false); const recoverOAuthInstallation = useAction( api.github.action.recoverOAuthInstallation, ); @@ -451,12 +458,34 @@ export function RepositoryConnect() { } }; - const handleRefreshGitHubAuthorization = () => { - navigate( - createGitHubReauthorizationConsentUrl( - `${window.location.pathname}${window.location.search}`, - ), + // "Verify GitHub access" returns here with its outcome; report it once. + useEffect(() => { + const url = new URL(window.location.href); + const result = url.searchParams.get(ACCESS_VERIFICATION_RESULT_PARAM); + if (result === null) return; + url.searchParams.delete(ACCESS_VERIFICATION_RESULT_PARAM); + window.history.replaceState({}, "", `${url.pathname}${url.search}`); + const problem = ACCESS_VERIFICATION_PROBLEMS.find( + (known) => known === result, ); + if (result !== "verified") + showToast( + t(`repositories.connect.accessVerification.${problem ?? "failed"}`), + "error", + ); + }, [t]); + + const handleRefreshGitHubAuthorization = async () => { + setIsStartingVerification(true); + try { + const { url } = await startAccessVerification({ + returnPath: `${window.location.pathname}${window.location.search}`, + }); + window.location.assign(url); + } catch { + setIsStartingVerification(false); + showToast(t("repositories.connect.accessVerification.failed"), "error"); + } }; const handleRetryReconciliation = async (installationId: number) => { @@ -595,7 +624,8 @@ export function RepositoryConnect() {
{installationVerificationRequiresReauth ? ( ) : null}