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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 157 additions & 9 deletions cloudflare_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,15 @@ def repository_preference_key(provider: str, account_id: str | int) -> str:
return f'{provider}:{digest}'


def github_app_install_url(env) -> str:
if not env:
return ""
slug = getattr(env, "GITHUB_APP_SLUG", "") or getattr(env, "MCP_GITHUB_APP_SLUG", "")
if isinstance(slug, str) and re.fullmatch(r"[A-Za-z0-9-]{1,100}", slug):
return f"https://github.com/apps/{slug}/installations/new"
return ""


@app.get("/api/auth/config")
async def auth_config(request: Request):
env = environment(request)
Expand All @@ -153,6 +162,7 @@ async def auth_config(request: Request):
"required": auth_required(request),
"github_enabled": bool(env and getattr(env, 'GITHUB_OAUTH_CLIENT_ID', '')
and getattr(env, 'GITHUB_OAUTH_CLIENT_SECRET', '') and getattr(env, 'GITHUB_OAUTH_REDIRECT_URI', '')),
"github_app_install_url": github_app_install_url(env),
}


Expand Down Expand Up @@ -259,7 +269,13 @@ async def delete_account(request: Request):
return response


async def public_repo_exists(repo: str, token: str | None, *, allow_private=False) -> dict:
async def public_repo_exists(
repo: str,
token: str | None,
*,
allow_private: bool = False,
github_login: str | None = None,
) -> dict:
headers = {"Accept": "application/vnd.github+json", "User-Agent": "github-flow-analytics/0.1"}
if token:
headers["Authorization"] = f"Bearer {token}"
Expand All @@ -269,7 +285,17 @@ async def public_repo_exists(repo: str, token: str | None, *, allow_private=Fals
except (TimeoutError, httpx.HTTPError) as exc:
raise HTTPException(502, 'GitHub could not be reached. Please try again.') from exc
if status == 404:
raise HTTPException(status_code=404, detail="Repository not found or unavailable to the connected GitHub identity.")
if github_login:
detail = (
f"Repository not found or the GitHub App is not installed on this repository for @{github_login}. "
"Grant repository access in GitHub App settings and try again."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Advisory in Standard mode · Authenticated 404 guidance incorrectly assumes a GitHub App credential

public_repo_exists selects GitHub App installation advice solely from the presence of github_login. However, browser authentication supports OAuth credentials with configurable scopes, and bearer authentication also accepts PATs. A valid token lacking access to a private repository can therefore receive a 404 and be told to grant access in GitHub App settings, which does not change that token's permissions. The new guidance sends these supported users to the wrong recovery path. The explanation must remain valid for the actual credential type, or avoid assuming that App installation controls its access.

Maintainability And Code Quality

)
else:
detail = (
"Repository not found. If it is private, connect GitHub, install the GitHub App on the repository, "
"and allow private analysis."
)
raise HTTPException(status_code=404, detail=detail)
if status == 403:
raise HTTPException(status_code=429,
detail="GitHub is currently refusing analysis requests from this service. Please try again later.")
Expand All @@ -282,6 +308,105 @@ async def public_repo_exists(repo: str, token: str | None, *, allow_private=Fals
return data


async def list_accessible_repositories(identity, *, include_private: bool = True) -> dict[str, Any]:
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {identity.token}",
"User-Agent": "github-flow-analytics/0.1",
"X-GitHub-Api-Version": "2022-11-28",
}
try:
status, _, payload = await asyncio.wait_for(
request_json("https://api.github.com/user/installations?per_page=100", headers=headers, timeout=10), 10
)
except (TimeoutError, httpx.HTTPError) as exc:
raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc
if status == 401:
raise HTTPException(401, "Your GitHub credential expired or was revoked. Sign in again.")

repos_by_key: dict[str, dict[str, Any]] = {}
truncated = False
installation_count = 0
source = "github_app"

def collect(items: list[Any]) -> None:
for item in items:
if not isinstance(item, dict):
continue
full_name = item.get("full_name")
if not isinstance(full_name, str) or "/" not in full_name:
continue
is_private = bool(item.get("private"))
if is_private and not include_private:
continue
repos_by_key[full_name.lower()] = {
"full_name": full_name,
"private": is_private,
"pushed_at": item.get("pushed_at") if isinstance(item.get("pushed_at"), str) else "",
}

if status == 200 and isinstance(payload, dict) and isinstance(payload.get("installations"), list):
installations = payload["installations"]
installation_count = len(installations)
if installation_count > 10:
truncated = True
for inst in installations[:10]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Advisory in Standard mode · Sequential discovery can exceed the browser deadline even when GitHub requests succeed

The listing performs the installation lookup and up to ten repository lookups sequentially, each with its own ten-second timeout, after authentication has already performed an identity lookup. The browser aborts the entire request after twelve seconds. For an identity with ten installations, successful upstream calls taking roughly 1.1 seconds each are enough to lose the entire discovery result. The catch is silent and there is no automatic retry, so autocomplete and the repository count remain unavailable, although manual entry still works. End-to-end discovery latency must be compatible with the consumer deadline rather than bounded only per upstream request.

Scale And Resilience

inst_id = inst.get("id") if isinstance(inst, dict) else None
if type(inst_id) is not int or inst_id <= 0:
continue
try:
r_status, _, r_payload = await asyncio.wait_for(
request_json(
f"https://api.github.com/user/installations/{inst_id}/repositories?per_page=100",
headers=headers,
timeout=10,
),
10,
)
except (TimeoutError, httpx.HTTPError) as exc:
raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc
if r_status == 200 and isinstance(r_payload, dict) and isinstance(r_payload.get("repositories"), list):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Should fix · Failed installation reads are reported as complete repository lists

In cloudflare_app.py:368, a per-installation response is collected only when its status and payload shape match expectations; all other responses are silently skipped without marking the result incomplete. With one installation returning 403 or 5xx, discovery succeeds with an empty list and truncated=false. The browser then reports “0 repositories granted to GitHub App,” and MCP reports no accessible repositories despite discovery having failed. Partial failures must remain distinguishable from genuinely empty access in both consumers.

Correctness And Data Integrity · Maintainability And Code Quality · Scale And Resilience

items = r_payload["repositories"]
collect(items)
total = r_payload.get("total_count")
if isinstance(total, int) and total > len(items):
truncated = True
elif status == 403:
source = "oauth_or_pat"
try:
r_status, _, r_payload = await asyncio.wait_for(
request_json("https://api.github.com/user/repos?per_page=100&sort=pushed", headers=headers, timeout=10),
10,
)
except (TimeoutError, httpx.HTTPError) as exc:
raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc
if r_status == 401:
raise HTTPException(401, "Your GitHub credential expired or was revoked. Sign in again.")
if r_status != 200 or not isinstance(r_payload, list):
raise HTTPException(502, "GitHub could not list accessible repositories. Please try again.")
collect(r_payload)
if len(r_payload) >= 100:
truncated = True
else:
raise HTTPException(502, "GitHub could not list accessible repositories. Please try again.")

repositories = sorted(
repos_by_key.values(),
key=lambda item: (item["pushed_at"], item["full_name"].lower()),
reverse=True,
)
if len(repositories) > 200:
repositories = repositories[:200]
truncated = True
return {
"login": identity.login,
"source": source,
"installation_count": installation_count,
"repositories": repositories,
"truncated": truncated,
}


async def caller_github(request):
if request.headers.get('authorization') is not None or getattr(request, 'cookies', {}).get(github_auth.GITHUB_SESSION_COOKIE):
try:
Expand All @@ -307,15 +432,17 @@ async def authorize_analysis(request, *, expected_account=None):

async def repository_access(repo, request, identity, allow_private):
token = identity.token if identity else getattr(environment(request), 'GITHUB_TOKEN', None)
metadata = await public_repo_exists(repo, token, allow_private=allow_private)
metadata = await public_repo_exists(
repo, token, allow_private=allow_private, github_login=identity.login if identity else None
)
if metadata['private'] and not identity:
raise HTTPException(401, 'Connect your GitHub identity or supply its bearer credential for private analysis.')
# Anonymous content reads cannot cross a later public-to-private transition.
return token if metadata['private'] else None, metadata['private']


async def mcp_repository_access(repo, token, allow_private):
metadata = await public_repo_exists(repo, token, allow_private=allow_private)
async def mcp_repository_access(repo, token, allow_private, *, github_login=None):
metadata = await public_repo_exists(repo, token, allow_private=allow_private, github_login=github_login)
repository_id = metadata.get('id')
if type(repository_id) is not int or repository_id < 1:
raise HTTPException(502, 'GitHub returned unreadable repository access information.')
Expand All @@ -342,6 +469,16 @@ async def health():
return {"ok": True}


@app.get("/api/github/repos")
async def github_repos(request: Request):
identity = await caller_github(request)
if not identity:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Advisory in Standard mode · Repository discovery has no admission bound on repeated upstream enumeration

Neither GET /api/github/repos nor the MCP listing branch applies an enumeration limiter or reuses previous discovery results. Authentication and MCP grant validation do not impose one either. An identity with ten installations generates twelve GitHub requests per invocation, including identity verification, and changing an MCP query repeats the entire fan-out because filtering happens afterward. Repeated or concurrent discovery therefore consumes the credential's GitHub quota without the admission controls used for analysis; sufficiently repeated calls can also leave subsequent analysis and identity verification rate-limited. Admitted discovery load needs a bound covering both entry points, not merely the number of installations within one invocation.

Scale And Resilience

raise HTTPException(401, "Connect your GitHub identity to list accessible repositories.")
result = await list_accessible_repositories(identity, include_private=True)
result["install_url"] = github_app_install_url(environment(request))
return result


@app.post("/api/analyze")
async def analyze_repo(req: AnalyzeRequest, request: Request):
identity = await authorize_analysis(request, expected_account=request.headers.get('X-Analysis-Account'))
Expand All @@ -353,7 +490,9 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
repo = parse_repo(req.repo_url)
env = request.scope.get("env")
if full_dashboard:
repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private)
repo, private, repository_id = await mcp_repository_access(
repo, identity.token, req.allow_private, github_login=identity.login
)
token = identity.token if private else None
else:
token, private = await repository_access(repo, request, identity, req.allow_private)
Expand Down Expand Up @@ -446,7 +585,9 @@ async def issue_value_for_identity(req, request, identity, *, mcp=False):
await enforce_limit(request, 'analyze', 10, identity=identity if mcp else None)
repo = parse_repo(req.repo_url)
if mcp:
repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private)
repo, private, repository_id = await mcp_repository_access(
repo, identity.token, req.allow_private, github_login=identity.login
)
token = identity.token if private else None
else:
token, private = await repository_access(repo, request, identity, req.allow_private)
Expand Down Expand Up @@ -581,7 +722,7 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False):
if full_dashboard:
if private and not req.allow_private:
raise HTTPException(403, 'Allow private analysis to coach against this snapshot.')
metadata = await public_repo_exists(repo, identity.token, allow_private=private)
metadata = await public_repo_exists(repo, identity.token, allow_private=private, github_login=identity.login)
if metadata['private'] != private or metadata.get('id') != metrics.get('repository_id'):
raise HTTPException(403, 'Repository access changed. Analyze it again.')
if private:
Expand Down Expand Up @@ -618,7 +759,14 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False):
raise HTTPException(status_code=502, detail="AI service is temporarily unavailable.") from exc


install_mcp(app, analyze_for_identity, issue_value_for_identity, chat_for_identity)
install_mcp(
app,
analyze_for_identity,
issue_value_for_identity,
chat_for_identity,
list_repos=list_accessible_repositories,
install_url_for_env=github_app_install_url,
)


@app.api_route("/{path:path}", methods=["GET", "HEAD"])
Expand Down
62 changes: 60 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@
}
.btn-ghost:hover{border-color:var(--violet);color:var(--text);}
#repo-setup a{color:#c4b5fd;}
.github-access-bar:not([hidden]){display:flex;flex-wrap:wrap;align-items:center;gap:.4rem 1rem;font-size:.875rem;color:var(--text-dim);}
#github-status{color:#6ee7b7;font-weight:500;}
#github-repos-summary{color:var(--text-dim);}
#repo-setup details{color:var(--text-dim);font-size:.875rem;}
#repo-setup summary{cursor:pointer;}
.provider-keys{display:grid;gap:.5rem;margin-top:.75rem;}
Expand Down Expand Up @@ -512,17 +515,24 @@ <h1>⚡ GitHub Flow Analytics</h1>
<input
id="repo-input"
type="text"
list="accessible-repos"
aria-label="GitHub repository URL"
placeholder="github.com/owner/repo or owner/repo"
autocomplete="off"
spellcheck="false"
/>
<datalist id="accessible-repos"></datalist>
<button id="analyze-btn" class="btn btn-primary" type="submit" aria-label="Analyze" disabled>
<span class="spinner" aria-hidden="true"></span>
<span class="btn-label">Analyze</span>
</button>
</div>
<a id="github-connect" href="/api/auth/github/start" hidden>Connect GitHub</a>
<div id="github-access-bar" class="github-access-bar" hidden>
<span id="github-status" hidden></span>
<a id="github-connect" href="/api/auth/github/start" hidden>Connect GitHub</a>
<span id="github-repos-summary" hidden></span>
<a id="github-app-install" href="#" target="_blank" rel="noopener" hidden>Manage repository access (GitHub App)</a>
</div>
<label class="settings-consent"><input id="allow-private" type="checkbox"> Allow private analysis using my connected GitHub identity. Send bounded repository context and descriptions to Gemini and Jev, including when this browser reopens the repository.</label>
<details>
<summary>AI assessment API keys (optional)</summary>
Expand Down Expand Up @@ -741,6 +751,52 @@ <h3>Flowy AI Coach</h3>
let repositoryPreferenceKey;
let restoredPrivateRepository;

function updateGitHubAccessUI(session) {
const bar = document.getElementById('github-access-bar');
const status = document.getElementById('github-status');
const connect = document.getElementById('github-connect');
const install = document.getElementById('github-app-install');
const enabled = Boolean(authConfig.github_enabled);
bar.hidden = !enabled;
if (!enabled) return;
const isGitHub = session?.provider === 'github' && Boolean(session.login);
status.hidden = !isGitHub;
status.textContent = isGitHub ? `Connected to GitHub as @${session.login}` : '';
connect.hidden = isGitHub;
const installUrl = typeof authConfig.github_app_install_url === 'string' ? authConfig.github_app_install_url : '';
install.hidden = !installUrl;
if (installUrl) install.href = installUrl;
}

async function loadAccessibleRepositories() {
const summaryEl = document.getElementById('github-repos-summary');
const datalist = document.getElementById('accessible-repos');
if (!summaryEl || !datalist) return;
try {
const response = await fetch('/api/github/repos', {credentials:'same-origin', signal: AbortSignal.timeout(12000)});
if (!response.ok) return;
const data = await response.json();
const repos = Array.isArray(data?.repositories) ? data.repositories : [];
datalist.replaceChildren(...repos.map(repo => {
const option = document.createElement('option');
option.value = repo.full_name;
option.label = repo.private ? `${repo.full_name} (private)` : repo.full_name;
return option;
}));
const privateCount = repos.filter(repo => repo.private).length;
if (repos.length === 0) {
summaryEl.textContent = '0 repositories granted to GitHub App';
} else {
const suffix = data.truncated ? '+' : '';
summaryEl.textContent = `${repos.length}${suffix} accessible ${repos.length === 1 ? 'repo' : 'repos'}`
+ (privateCount ? ` (${privateCount} private)` : '');
}
summaryEl.hidden = false;
} catch {
// Non-fatal: manual repository entry still works.
}
}

async function configureAuthentication() {
try {
const signal = AbortSignal.timeout(12000);
Expand All @@ -751,7 +807,7 @@ <h3>Flowy AI Coach</h3>
}
authConfig = await readApiResponse(response);
document.getElementById('github-signin').hidden = !authConfig.github_enabled;
document.getElementById('github-connect').hidden = !authConfig.github_enabled;
updateGitHubAccessUI(null);
document.getElementById('chat-github-help').hidden = !authConfig.github_enabled;
document.getElementById('chat-github-unavailable').hidden = authConfig.github_enabled !== false;
if (authConfig.required) document.getElementById('login-gate').classList.add('visible');
Expand Down Expand Up @@ -804,8 +860,10 @@ <h3>Flowy AI Coach</h3>
document.getElementById('login-gate').classList.remove('visible');
document.getElementById('account-actions').hidden = false;
document.getElementById('account-email').textContent = session.login || session.email;
updateGitHubAccessUI(session);
repositoryPreferenceKey = session.account_key;
document.getElementById('analyze-btn').disabled = false;
if (session?.provider === 'github') loadAccessibleRepositories();
if (repositoryPreferenceKey) restoreLastRepository();
}

Expand Down
Loading
Loading