Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

app.tsx

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

app.tsxBlame1110 lines · 6 contributors
79136bbClaude1import { Hono } from "hono";
4abf6f1ccantynz-alt2import type { Context } from "hono";
79136bbClaude3import { logger } from "hono/logger";
4import { cors } from "hono/cors";
05b973eClaude5import { compress } from "hono/compress";
f1ffd50Claude6import { etag } from "hono/etag";
c63b860Claude7// BLOCK O2 — shared error-page surface (404 / 500 / 403).
8import { NotFoundPage, ServerErrorPage } from "./views/error-page";
80bed05Claude9import { reportError } from "./lib/observability";
3ef4c9dClaude10import { requestContext } from "./middleware/request-context";
11import { rateLimit } from "./middleware/rate-limit";
79136bbClaude12import gitRoutes from "./routes/git";
13import apiRoutes from "./routes/api";
45e31d0Claude14import apiV2Routes from "./routes/api-v2";
15import apiDocsRoutes from "./routes/api-docs";
4a80519Claude16import buildAgentSpecRoutes from "./routes/build-agent-spec";
a6ff0f2Claude17import pullsDashboardRoutes from "./routes/pulls-dashboard";
e9aa4d8Claude18import issuesDashboardRoutes from "./routes/issues-dashboard";
19import inboxRoutes from "./routes/inbox";
cc34156Claude20import digestRoutes from "./routes/digest";
e9aa4d8Claude21import activityRoutes from "./routes/activity";
79136bbClaude22import authRoutes from "./routes/auth";
c63b860Claude23import passwordResetRoutes from "./routes/password-reset";
24import emailVerificationRoutes from "./routes/email-verification";
cd4f63bTest User25import magicLinkRoutes from "./routes/magic-link";
79136bbClaude26import settingsRoutes from "./routes/settings";
7298a17Claude27import settings2faRoutes from "./routes/settings-2fa";
e75eddcClaude28import settingsAgentsRoutes from "./routes/settings-agents";
1d4ff60Claude29import settingsIntegrationsRoutes from "./routes/settings-integrations";
30import integrationsChatRoutes from "./routes/integrations-chat";
e75eddcClaude31import agentsRoutes from "./routes/agents";
ef3fd93Claude32import agentPipelinesRoutes from "./routes/agent-pipelines";
79136bbClaude33import issueRoutes from "./routes/issues";
85c4e13Claude34import milestonesRoutes from "./routes/milestones";
f928118Claude35import shipAgentRoutes from "./routes/ship-agent";
cb5a796Claude36import commentModerationRoutes from "./routes/comment-moderation";
79136bbClaude37import repoSettings from "./routes/repo-settings";
479dcd9Claude38import automationSettingsRoutes from "./routes/automation-settings";
23d1a81Claude39import collaboratorRoutes from "./routes/collaborators";
04f6b7fClaude40import teamCollaboratorRoutes from "./routes/team-collaborators";
41import invitesRoutes from "./routes/invites";
42import liveEventsRoutes from "./routes/live-events";
3c03977Claude43import prLiveRoutes from "./routes/pr-live";
79136bbClaude44import compareRoutes from "./routes/compare";
0074234Claude45import pullRoutes from "./routes/pulls";
79ed944Claude46import prSandboxRoutes from "./routes/pr-sandbox";
9b3a183Claude47import devEnvRoutes from "./routes/dev-env";
0074234Claude48import editorRoutes from "./routes/editor";
6f2809fClaude49import aiEditorRoutes from "./routes/ai-editor";
c81ab7aClaude50import forkRoutes from "./routes/fork";
51import webhookRoutes from "./routes/webhooks";
52import exploreRoutes from "./routes/explore";
53import tokenRoutes from "./routes/tokens";
43de941Claude54import contributorRoutes from "./routes/contributors";
699e5c7Claude55import healthRoutes from "./routes/health-probe";
56import healthDashboardRoutes from "./routes/health";
2316be6Claude57import statusRoutes from "./routes/status";
b1be050CC LABS App58import adminStatusRoutes from "./routes/admin-status";
80bed05Claude59import helpRoutes from "./routes/help";
e1fc7dbClaude60import changelogRoutes from "./routes/changelog";
e0e4219Claude61import docsRoutes from "./routes/docs";
b0148e9Claude62import marketingRoutes from "./routes/marketing";
5f2e749Claude63import pricingRoutes from "./routes/pricing";
9f29b65Claude64import enterpriseRoutes from "./routes/enterprise";
5618f9aClaude65import seoRoutes from "./routes/seo";
05cdb85Claude66import versionRoutes from "./routes/version";
f295f78Dictation App67import { platformStatus } from "./routes/platform-status";
52ad8b1Claude68import publicStatsRoutes from "./routes/public-stats";
69import demoRoutes from "./routes/demo";
16b325cClaude70import insightRoutes from "./routes/insights";
8286942Claude71import engineeringInsightsRoutes from "./routes/engineering-insights";
8d1483cClaude72import doraRoutes from "./routes/dora";
f1ab587Claude73import dashboardRoutes from "./routes/dashboard";
36b4cbdClaude74import legalRoutes from "./routes/legal";
4b66018Claude75import legalDmcaRoutes from "./routes/legal/dmca";
76import legalTermsRoutes from "./routes/legal/terms";
77import legalPrivacyRoutes from "./routes/legal/privacy";
78import legalAcceptableUseRoutes from "./routes/legal/acceptable-use";
bdbd0deClaude79import importRoutes from "./routes/import";
14c3cc8Claude80import importBulkRoutes from "./routes/import-bulk";
f390cfaCC LABS App81import importSecretsRoutes from "./routes/import-secrets";
bb2dea9Claude82import actionsImporterRoutes from "./routes/actions-importer";
14c3cc8Claude83import migrationRoutes from "./routes/migrations";
ba23fe2Claude84import migrationAssistantRoutes from "./routes/migration-assistant";
9a8b8deClaude85import migrateRoutes from "./routes/migrate";
14c3cc8Claude86import specsRoutes from "./routes/specs";
23d0abfClaude87import refactorRoutes from "./routes/refactors";
b665cacClaude88import codebaseMigratorRoutes from "./routes/codebase-migrator";
79136bbClaude89import webRoutes from "./routes/web";
0316dbbClaude90import hookRoutes from "./routes/hooks";
91import eventsRoutes from "./routes/events";
92import passkeyRoutes from "./routes/passkeys";
93import oauthRoutes from "./routes/oauth";
369ad65ccanty labs94import wellKnownRoutes from "./routes/well-known";
0316dbbClaude95import developerAppsRoutes from "./routes/developer-apps";
96import themeRoutes from "./routes/theme";
97import auditRoutes from "./routes/audit";
98import reactionRoutes from "./routes/reactions";
99import savedReplyRoutes from "./routes/saved-replies";
100import deploymentRoutes from "./routes/deployments";
2c61840Claude101import pipelineRoutes from "./routes/pipeline";
0316dbbClaude102import orgRoutes from "./routes/orgs";
103import notificationRoutes from "./routes/notifications";
104import onboardingRoutes from "./routes/onboarding";
105import adminRoutes from "./routes/admin";
7293c67Claude106import adminDeletionsRoutes from "./routes/admin-deletions";
107import adminStripeRoutes from "./routes/admin-stripe";
f764c07Claude108import adminDeploysRoutes from "./routes/admin-deploys";
109import adminDeploysPageRoutes from "./routes/admin-deploys-page";
783dd46Claude110import adminServerTargetsRoutes from "./routes/admin-server-targets";
9aaa128Claude111import deployTargetsRoutes from "./routes/deploy-targets";
90c7531Claude112import claudeWebRoutes from "./routes/claude-web";
9dd96b9Test User113import adminOpsRoutes from "./routes/admin-ops";
f2c00b4CC LABS App114import adminSelfHostRoutes from "./routes/admin-self-host";
826eccfTest User115import adminDiagnoseRoutes from "./routes/admin-diagnose";
f9814d2Claude116import adminCommandRoutes from "./routes/admin-command";
509c376Claude117import adminIntegrationsRoutes from "./routes/admin-integrations";
bc519aeClaude118import adminEnvHealthRoutes from "./routes/admin-env-health";
79ed944Claude119import adminAdvancementRoutes from "./routes/admin-advancement";
ba9e143Claude120import adminSecurityRoutes from "./routes/admin-security";
121import settingsSessionsRoutes from "./routes/settings-sessions";
0316dbbClaude122import advisoriesRoutes from "./routes/advisories";
123import aiChangelogRoutes from "./routes/ai-changelog";
0a69faaClaude124import explainRoutes from "./routes/explain";
0316dbbClaude125import aiExplainRoutes from "./routes/ai-explain";
2be65d0Claude126import archaeologyRoutes from "./routes/ai-archaeology";
0316dbbClaude127import aiTestsRoutes from "./routes/ai-tests";
128import askRoutes from "./routes/ask";
38d31d3Claude129import repoChatRoutes from "./routes/repo-chat";
ee7e577Claude130import personalChatRoutes from "./routes/personal-chat";
0316dbbClaude131import billingRoutes from "./routes/billing";
8809b87Claude132import billingUsageRoutes from "./routes/billing-usage";
6778ad2Claude133import stripeWebhookRoutes from "./routes/stripe-webhook";
0316dbbClaude134import codeScanningRoutes from "./routes/code-scanning";
da3fc18Claude135import securityRoutes from "./routes/security";
0316dbbClaude136import commitStatusesRoutes from "./routes/commit-statuses";
137import copilotRoutes from "./routes/copilot";
f5d020fClaude138import { pairProgrammerRoutes } from "./routes/pair-programmer";
0316dbbClaude139import depUpdaterRoutes from "./routes/dep-updater";
140import depsRoutes from "./routes/deps";
141import discussionsRoutes from "./routes/discussions";
142import environmentsRoutes from "./routes/environments";
4bbacbeClaude143import previewsRoutes from "./routes/previews";
79ed944Claude144import docsTrackingRoutes from "./routes/docs-tracking";
0316dbbClaude145import followsRoutes from "./routes/follows";
146import gatesRoutes from "./routes/gates";
147import gistsRoutes from "./routes/gists";
148import graphqlRoutes from "./routes/graphql";
2c2163eClaude149import mcpRoutes from "./routes/mcp";
0316dbbClaude150import marketplaceRoutes from "./routes/marketplace";
5ca514aClaude151import marketplaceAgentsRoutes from "./routes/marketplace-agents";
0316dbbClaude152import mergeQueueRoutes from "./routes/merge-queue";
153import mirrorsRoutes from "./routes/mirrors";
154import orgInsightsRoutes from "./routes/org-insights";
2be65d0Claude155import orgHealthRoutes from "./routes/org-health";
0316dbbClaude156import packagesRoutes from "./routes/packages";
157import packagesApiRoutes from "./routes/packages-api";
845fd8aClaude158import ociRegistryRoutes from "./routes/oci-registry";
0316dbbClaude159import pagesRoutes from "./routes/pages";
160import projectsRoutes from "./routes/projects";
161import protectedTagsRoutes from "./routes/protected-tags";
162import pwaRoutes from "./routes/pwa";
46d6165Claude163import installRoutes from "./routes/install";
cd4f63bTest User164import dxtRoutes from "./routes/dxt";
662ce86Claude165import connectClaudeRoutes from "./routes/connect-claude";
ebbb527Claude166import claudeDeployRoutes from "./routes/claude-deploy";
f5b9ef5Claude167import claudeIntegration from "./routes/claude-integration";
168import connectRoutes from "./routes/connect";
05ab9b1Claude169import pushWatchRoutes from "./routes/push-watch";
170import orgSecretsRoutes from "./routes/org-secrets";
0316dbbClaude171import releasesRoutes from "./routes/releases";
172import requiredChecksRoutes from "./routes/required-checks";
173import rulesetsRoutes from "./routes/rulesets";
174import searchRoutes from "./routes/search";
175import semanticSearchRoutes from "./routes/semantic-search";
77cf834Claude176import nlSearchRoutes from "./routes/nl-search";
0316dbbClaude177import signingKeysRoutes from "./routes/signing-keys";
178import sponsorsRoutes from "./routes/sponsors";
179import ssoRoutes from "./routes/sso";
3a845e4Claude180import samlSsoRoutes from "./routes/saml-sso";
181import scimRoutes from "./routes/scim";
182import orgSsoSettingsRoutes from "./routes/org-sso-settings";
46d6165Claude183import githubOauthRoutes from "./routes/github-oauth";
582cdacClaude184import googleOauthRoutes from "./routes/google-oauth";
0316dbbClaude185import symbolsRoutes from "./routes/symbols";
186import templatesRoutes from "./routes/templates";
187import trafficRoutes from "./routes/traffic";
188import wikisRoutes from "./routes/wikis";
189import workflowsRoutes from "./routes/workflows";
5ff9cc2Claude190import workflowArtifactsRoutes from "./routes/workflow-artifacts";
191import workflowSecretsRoutes from "./routes/workflow-secrets";
46d6165Claude192import sleepModeRoutes from "./routes/sleep-mode";
56801e1Claude193import standupRoutes from "./routes/standups";
52ad8b1Claude194import vsGithubRoutes from "./routes/vs-github";
45f3b73Claude195import voiceRoutes from "./routes/voice-to-pr";
3122762Claude196import blogRoutes from "./routes/blog";
cd4f63bTest User197import playgroundRoutes from "./routes/playground";
a2b3e99Claude198import crossRepoSearchRoutes from "./routes/cross-repo-search";
199import pushNotifRoutes from "./routes/push-notifications";
9fbe6cdClaude200import velocityRoutes from "./routes/velocity";
201import { staleBranchRoutes } from "./routes/stale-branches";
22f43f3Claude202import pulseRoutes from "./routes/pulse";
74d8c4dClaude203import healthScoreRoutes from "./routes/health-score";
77cf834Claude204import repoHealthRoutes from "./routes/repo-health";
74d8c4dClaude205import hotFilesRoutes from "./routes/hot-files";
bcc4020Claude206import debtMapRoutes from "./routes/debt-map";
1d6db4dClaude207import busFactorRoutes from "./routes/bus-factor";
2be65d0Claude208import testGapsRoutes from "./routes/test-gaps";
f5d020fClaude209import crossRepoImpactRoutes from "./routes/cross-repo-impact";
adf5e18Claude210import developerProgramRoutes from "./routes/developer-program";
891efbeClaude211import shareRoutes from "./routes/share";
70e3293Claude212import incidentHookRoutes from "./routes/incident-hooks";
77cf834Claude213import workspaceRoutes from "./routes/ai-workspace";
2c61840Claude214import workspaceHubRoutes from "./routes/workspace-hub";
4d4bd4bccantynz-alt215import { apiRateLimit, authRateLimit, gitRateLimit, searchRateLimit } from "./middleware/rate-limit";
59b6fb2Claude216import { csrfToken, csrfProtect } from "./middleware/csrf";
f5b9ef5Claude217import { noCache } from "./middleware/no-cache";
79136bbClaude218
2316901Claude219import type { AuthEnv } from "./middleware/auth";
bf19c50Test User220import { softAuth } from "./middleware/auth";
2316901Claude221
222const app = new Hono<AuthEnv>();
79136bbClaude223
3ef4c9dClaude224// Request context (request ID, start time) runs before everything else
225app.use("*", requestContext);
05b973eClaude226// Middleware — compression first (wraps all responses)
227app.use("*", compress());
f1ffd50Claude228
229// ETag middleware — returns 304 Not Modified on unchanged responses.
230// Saves ~95% bandwidth on repeat visits. Skipped on git protocol +
231// SSE + the API surface where it would interfere with streaming.
232app.use("*", async (c, next) => {
233 const p = c.req.path;
234 if (
235 p.includes(".git/") ||
236 p.startsWith("/live-events") ||
237 p.startsWith("/api/events/deploy") ||
3c03977Claude238 p.startsWith("/admin/status") ||
239 // PR live co-editing SSE stream — never etag streaming responses.
240 /^\/api\/v2\/pulls\/[^/]+\/live(\/|$)/.test(p)
f1ffd50Claude241 ) {
242 return next();
243 }
244 return etag()(c, next);
245});
246
247// Cache-Control middleware — sets sensible defaults on public, anonymous
9ecf5a4Claude248// requests. Vapron (when wired as our edge layer) and downstream
f1ffd50Claude249// browsers will honor these. Auth'd users get private,no-store
250// automatically — we never cache responses tied to a session.
251app.use("*", async (c, next) => {
252 await next();
253 // Don't overwrite explicit headers set by route handlers — BUT the
254 // ETag middleware unconditionally sets "private, no-cache, must-
255 // revalidate" so we have to treat that specific value as "no
256 // policy chosen yet" and apply ours. Any route that explicitly set
257 // a different cache-control wins.
258 const existing = c.res.headers.get("cache-control");
259 const etagDefault =
260 existing === "private, no-cache, must-revalidate" ||
261 existing === "no-cache";
262 if (existing && !etagDefault) return;
263 // Anything past auth: private + no-store (avoid leaking session
264 // content into shared caches). softAuth runs before this on the
265 // request, but the response side is what we're stamping.
266 const hasSession = c.req.header("cookie")?.includes("session=") ?? false;
267 const p = c.req.path;
268 // Always private for known-authed paths regardless of cookie.
269 if (
270 p.startsWith("/admin") ||
271 p.startsWith("/settings") ||
272 p.startsWith("/dashboard") ||
273 p.startsWith("/notifications") ||
274 p.startsWith("/connect/") ||
275 hasSession
276 ) {
277 c.res.headers.set("cache-control", "private, no-store");
278 return;
279 }
280 // Public marketing surfaces — short edge cache, longer browser cache,
281 // stale-while-revalidate so the user never waits on a stale fetch.
282 const isMarketing =
283 p === "/" ||
284 p === "/features" ||
285 p === "/pricing" ||
286 p === "/about" ||
287 p === "/vs-github" ||
288 p === "/explore" ||
289 p === "/help" ||
290 p === "/changelog" ||
9f29b65Claude291 p === "/enterprise" ||
f1ffd50Claude292 p.startsWith("/legal/") ||
293 p === "/terms" ||
294 p === "/privacy" ||
295 p === "/acceptable-use" ||
296 p.startsWith("/docs/");
297 if (isMarketing) {
298 c.res.headers.set(
299 "cache-control",
300 "public, max-age=60, s-maxage=300, stale-while-revalidate=86400"
301 );
302 return;
303 }
304 // Public repo browse pages — cache aggressively. Edge invalidates
9ecf5a4Claude305 // on push via the post-receive hook (future Vapron surge purge).
f1ffd50Claude306 if (/^\/[^/]+\/[^/]+(\/.*)?$/.test(p) && c.req.method === "GET") {
307 c.res.headers.set(
308 "cache-control",
309 "public, max-age=30, s-maxage=120, stale-while-revalidate=600"
310 );
311 return;
312 }
313 // Default: don't cache anything we haven't explicitly opted in.
314 c.res.headers.set("cache-control", "private, no-store");
315});
05b973eClaude316// Logger only on non-git routes to avoid overhead on clone/push
317app.use("*", async (c, next) => {
318 if (c.req.path.includes(".git/")) return next();
319 return logger()(c, next);
320});
79136bbClaude321app.use("/api/*", cors());
bf19c50Test User322// Global softAuth — populates c.get("user") for every downstream middleware
323// + route. This was previously per-route, which meant rate-limit middleware
324// (and anything else inspecting auth state) always saw a null user. Keep
325// individual routes free to add requireAuth on top for hard gating; this
326// just establishes the user object cheaply.
327app.use("*", softAuth);
290ea77Claude328
36cc17aClaude329// Force-revalidate HTML on every request — kills browser cache holding stale
290ea77Claude330// pre-redesign markup. JSON / static assets keep their own cache rules; only
331// text/html responses get the no-cache stamp. Without this, every push to
332// main left users staring at cached 80s-looking pages from before the design
333// landed.
36cc17aClaude334//
335// We deliberately use `private, no-cache, must-revalidate` rather than
336// `no-store`. `no-store` disables Safari/Chrome's back-forward cache (bfcache),
337// which makes every Back/Forward press a cold server round-trip — that
338// contributed to the "every nav feels like a fresh login" UX complaint.
339// `no-cache` still revalidates on direct fetch but lets bfcache hold the
340// page in memory between navigations.
290ea77Claude341app.use("*", async (c, next) => {
342 await next();
343 const ct = c.res.headers.get("content-type") || "";
344 if (ct.startsWith("text/html")) {
36cc17aClaude345 c.header("cache-control", "private, no-cache, must-revalidate");
290ea77Claude346 }
347});
826eccfTest User348// Rate-limit API + auth endpoints.
349//
a41e675Test User350// `/api/*`: 1000/min per IP — generous so an admin clicking around the
351// operator console (or a CDN/proxy concentrating multiple users behind one
352// IP) doesn't hit the wall. Bot-resistant headroom comes from the auth
353// rate limits below, not this one.
354//
355// `authedMultiplier` is set but only fires when an upstream middleware has
356// already populated c.get("user") — most app.use() chains apply softAuth
357// per-route, so the multiplier is best-effort. Keep the anonymous base
358// high enough that humans never feel it.
359//
360// Skip-paths: dashboard plumbing endpoints that the layout polls on a
361// fixed cadence and that we don't want consuming any bucket:
362// /api/version — layout polls every 15s
826eccfTest User363// /api/notifications/count — nav bell unread-count fetcher
364// /pwa/vapid-public-key — fetched once per push-notification opt-in
365app.use(
366 "/api/*",
a41e675Test User367 rateLimit(1000, 60_000, "api", {
826eccfTest User368 authedMultiplier: 4,
369 skipPaths: ["/api/version", "/api/notifications/count", "/pwa/vapid-public-key"],
370 })
371);
0316dbbClaude372app.use("/login", rateLimit(20, 60_000, "login"));
373app.use("/register", rateLimit(10, 60_000, "register"));
c63b860Claude374// BLOCK P1 — throttle forgot-password to deter enumeration + mail spam.
375app.use("/forgot-password", rateLimit(5, 60_000, "forgot-password"));
cd4f63bTest User376// BLOCK Q2 — throttle magic-link sign-in for the same reason.
377app.use("/login/magic", rateLimit(5, 60_000, "magic-link"));
1d3a220ccantynz-alt378// The second factor was the one auth endpoint with NO limit, which made it
379// the cheapest thing on the platform to attack: an attacker who already has
380// the password reaches /login/2fa holding a valid half-authenticated session
381// and can grind a 6-digit TOTP (10^6) or a recovery code unthrottled. Tighter
382// than /login deliberately — a real person types one code from their phone,
383// occasionally mistypes it, and never needs ten attempts a minute.
384app.use("/login/2fa", rateLimit(5, 60_000, "login-2fa"));
79136bbClaude385
59b6fb2Claude386// CSRF protection — set token on all requests, validate on mutations
387app.use("*", csrfToken);
388app.use("*", csrfProtect);
389
45e31d0Claude390// Rate limit auth routes
391app.use("/login", authRateLimit);
392app.use("/register", authRateLimit);
393
59b6fb2Claude394// Rate limit git operations
395app.use("/:owner/:repo.git/*", gitRateLimit);
396
397// Rate limit search
398app.use("/:owner/:repo/search", searchRateLimit);
399app.use("/explore", searchRateLimit);
79136bbClaude400
4d4bd4bccantynz-alt401// Rate limit the v1 REST API and the MCP surface. api-v2 already applies its
402// own apiRateLimit internally (this stacks harmlessly for /api/v2/*); v1
403// (src/routes/api.ts) and /mcp had NO rate limiting at all despite /mcp
404// being the primary, anonymously-reachable AI-agent interface and able to
405// trigger expensive per-call work (e.g. gluecron_repo_health scans every
406// file in a repo). softAuth already runs on both, so the existing
407// authedMultiplier (4x for a signed-in caller) applies automatically.
408app.use("/api/*", apiRateLimit);
409app.use("/mcp", apiRateLimit);
410
f5b9ef5Claude411// No-cache for HTML — ensures browsers and proxies never serve stale pages.
412// The middleware only stamps text/html responses so static assets keep
413// their own cache policies unchanged.
414app.use("*", noCache);
415
8ed1b31ccantynz-alt416/**
417 * Platform-wide private-repository gate for `/:owner/:repo/...` pages.
418 *
419 * Every repo subpage was responsible for its own privacy check, and that
420 * drifted badly: a live probe of a private repo found 24 subpages rendering
421 * 200 to an anonymous visitor — /actions, /deployments, /discussions,
422 * /packages, /projects, /wiki, /insights, /contributors, /gates, /queue,
423 * /previews, /pushes, /health, /coupling, /dependencies, /explain,
424 * /archaeology, /cloud-deployments, /ai/changelog, /ai/tests, /docs/tracking,
425 * /search/nl, /search/semantic, /insights/engineering — while the repo root
426 * correctly 404'd. Each leaked names, history, CI logs or dependency data.
427 *
428 * Gating centrally is the point: ~20 route files each re-implementing the
429 * check is what produced the drift, and a subpage added tomorrow inherits
430 * this automatically.
431 *
432 * Safe against false positives. Paths like /settings/tokens or /orgs/new also
433 * match `/:owner/:repo`, but loadRepoByPath returns null for them and the
434 * request falls straight through — exactly as it does for a repo that does
435 * not exist, so each handler keeps emitting its own 404. `/:owner/:repo.git/*`
436 * (git Smart HTTP) resolves `:repo` as "name.git", also null, so the git
437 * protocol's own auth is untouched.
438 *
439 * Registered before every repo router and after softAuth, so c.get("user")
440 * is populated and owners/collaborators are unaffected.
441 */
442app.use("/:owner/:repo/*", async (c, next) => {
443 const owner = c.req.param("owner");
444 const repo = c.req.param("repo");
445 if (!owner || !repo) return next();
446
447 let row: { id: string; isPrivate: boolean } | null = null;
448 try {
449 const { loadRepoByPath } = await import("./lib/namespace");
450 const found = await loadRepoByPath(owner, repo);
451 row = found ? { id: found.id, isPrivate: found.isPrivate } : null;
452 } catch {
453 // Namespace resolution failed (DB blip) — do not invent a denial for
454 // public content; the handler below will surface its own error.
455 return next();
456 }
457 if (!row || !row.isPrivate) return next();
458
459 const viewer = c.get("user");
460 const { resolveRepoAccess } = await import("./middleware/repo-access");
461 const access = await resolveRepoAccess({
462 repoId: row.id,
463 userId: viewer?.id ?? null,
464 isPublic: false,
465 });
466 if (access !== "none") return next();
467
468 // 404, not 403 — a private repo must not confirm its own existence. Matches
469 // what the repo root already does.
470 const accepts = c.req.header("accept") ?? "";
471 if (accepts.includes("application/json") && !accepts.includes("text/html")) {
472 return c.json({ error: "Not found" }, 404);
473 }
474 return c.html(<NotFoundPage user={viewer ?? null} method={c.req.method} path={c.req.path} />, 404);
475});
476
79136bbClaude477// Git Smart HTTP protocol routes (must be before web routes)
478app.route("/", gitRoutes);
479
45e31d0Claude480// REST API v1 (legacy)
79136bbClaude481app.route("/", apiRoutes);
482
52ad8b1Claude483// Block L3 — /demo + /api/v2/demo/* live demo endpoints. Mounted BEFORE
484// apiV2Routes so the /api/v2/demo/* JSON endpoints win over the v2 base
485// router's catch-shape, and BEFORE adminRoutes so the live /demo page
486// wins over the legacy /demo redirect in src/routes/admin.tsx.
487app.route("/", demoRoutes);
488
0316dbbClaude489// REST API v2 (basePath /api/v2)
490app.route("/", apiV2Routes);
491
e75eddcClaude492// Agent multiplayer v1 — /api/v2/agents/* (sessions, leases, usage).
493// Mounted alongside apiV2Routes (its own basePath, no path conflict).
494app.route("/", agentsRoutes);
495
ef3fd93Claude496// Multi-agent pipeline UI — /:owner/:repo/agents (list, new, live view).
497// Must be before webRoutes (the catch-all) so the /agents sub-paths are
498// resolved before the generic tree/blob route takes over.
499app.route("/", agentPipelinesRoutes);
500
ad6d4adClaude501// Inbound API hooks (GateTest callback + backup PAT-authed /api/v1/gate-runs)
502app.route("/", hookRoutes);
21f8dbdClaude503app.route("/api/events", eventsRoutes);
ad6d4adClaude504
45e31d0Claude505// API documentation
506app.route("/", apiDocsRoutes);
4a80519Claude507app.route("/", buildAgentSpecRoutes);
a6ff0f2Claude508// PR command center — global PR dashboard with AI/GateTest/auto-merge signal
509app.route("/", pullsDashboardRoutes);
e9aa4d8Claude510// Issue command center — global issue dashboard with AI-triage + autopilot signal
511app.route("/", issuesDashboardRoutes);
512// Personal activity timeline — every event across the user's repos, with
513// AI-driven events surfaced separately (the Gluecron differentiator).
514app.route("/", activityRoutes);
515// Unified inbox — mentions + review requests + CI failures + AI events in one timeline
516app.route("/", inboxRoutes);
56801e1Claude517// AI standup feed — daily / weekly Claude-generated team brief
518app.route("/", standupRoutes);
cc34156Claude519// Smart morning digest — AI-curated daily developer queue (/digest)
520app.route("/", digestRoutes);
79136bbClaude521
522// Auth routes (register, login, logout)
523app.route("/", authRoutes);
524
c63b860Claude525// BLOCK P1 — Password reset (forgot-password + reset-password)
526app.route("/", passwordResetRoutes);
527
528// BLOCK P2 — Email verification (verify-email + resend)
529app.route("/", emailVerificationRoutes);
530
cd4f63bTest User531// BLOCK Q2 — Magic-link sign-in (/login/magic + callback)
532app.route("/", magicLinkRoutes);
533
79136bbClaude534// Settings routes (profile, SSH keys)
535app.route("/", settingsRoutes);
536
ba9e143Claude537// Session management (SOC 2 CC6.1 — /settings/sessions)
538app.route("/", settingsSessionsRoutes);
539
7298a17Claude540// 2FA / TOTP settings (Block B4)
541app.route("/", settings2faRoutes);
542
e75eddcClaude543// Agent multiplayer — /settings/agents management UI
544app.route("/", settingsAgentsRoutes);
545
1d4ff60Claude546// Chat integrations — Slack / Discord / Teams (/settings/integrations
547// + /api/v2/integrations/{slack,discord}/*). See src/lib/chat-bot.ts.
548app.route("/", settingsIntegrationsRoutes);
549app.route("/", integrationsChatRoutes);
4cd6791ccantynz-alt550// Incident hooks — /settings/incident-hooks (page) + the inbound incident
551// webhook receivers. Was imported but NEVER mounted, so the whole file was
552// dead and /settings/incident-hooks (linked from the settings nav) 404'd.
553app.route("/", incidentHookRoutes);
1d4ff60Claude554
2df1f8cClaude555// WebAuthn / passkey routes (Block B5)
556app.route("/", passkeyRoutes);
557
058d752Claude558// OAuth 2.0 provider (Block B6)
559app.route("/", oauthRoutes);
560app.route("/", developerAppsRoutes);
369ad65ccanty labs561// OAuth / agent discovery metadata (RFC 8414 + RFC 9728) — lets claude.ai,
562// Cursor, Copilot, etc. auto-discover how to authenticate.
563app.route("/", wellKnownRoutes);
058d752Claude564
6fc53bdClaude565// Theme toggle (dark/light cookie)
566app.route("/", themeRoutes);
567
568// Audit log UI
569app.route("/", auditRoutes);
570
571// Reactions API (issues, PRs, comments)
572app.route("/", reactionRoutes);
573
24cf2caClaude574// Saved replies (per-user canned comment templates)
575app.route("/", savedReplyRoutes);
576
577// Environments + deployment history UI
578app.route("/", deploymentRoutes);
2c61840Claude579// Unified CI/CD pipeline timeline
580app.route("/", pipelineRoutes);
24cf2caClaude581
6563f0aClaude582// Organizations + teams (Block B1)
583app.route("/", orgRoutes);
584
c81ab7aClaude585// API tokens
586app.route("/", tokenRoutes);
587
59b6fb2Claude588// Notifications
3ef4c9dClaude589app.route("/", notificationRoutes);
590
79136bbClaude591// Repo settings (description, visibility, delete)
592app.route("/", repoSettings);
479dcd9Claude593// Per-repo automation settings (off / suggest / auto) — migration 0106
594app.route("/", automationSettingsRoutes);
79136bbClaude595
23d1a81Claude596// Repo collaborators (add/list/remove)
597app.route("/", collaboratorRoutes);
598
04f6b7fClaude599// Team-based repo collaborators (invite a whole team)
600app.route("/", teamCollaboratorRoutes);
601
602// Collaborator invite accept flow (token-based)
603app.route("/", invitesRoutes);
604
605// Real-time SSE endpoint (topic-based live updates)
606app.route("/", liveEventsRoutes);
607
3c03977Claude608// PR live co-editing — presence + cursors + content sync via SSE.
609app.route("/", prLiveRoutes);
610
c81ab7aClaude611// Webhooks management
612app.route("/", webhookRoutes);
613
79136bbClaude614// Compare view (branch diffs)
615app.route("/", compareRoutes);
616
617// Issue tracker
618app.route("/", issueRoutes);
619
85c4e13Claude620// Milestones — group issues + PRs toward a shared goal with due dates + progress tracking.
621// Mounted after issueRoutes so /:owner/:repo/issues/* paths win before the milestone patterns.
622app.route("/", milestonesRoutes);
623
f928118Claude624// Ship Agent — autonomous AI feature implementation
625app.route("/", shipAgentRoutes);
626
77cf834Claude627// AI Copilot Workspace — issue-to-PR autonomous agent
628app.route("/", workspaceRoutes);
2c61840Claude629app.route("/", workspaceHubRoutes);
77cf834Claude630
cb5a796Claude631// Comment moderation queue — owner-only `/:owner/:repo/comments/pending`
632// + per-row approve/reject/spam actions. Mounted before `pullRoutes` so
633// the `/:owner/:repo/comments/*` paths resolve before the broader PR
634// patterns kick in.
635app.route("/", commentModerationRoutes);
636
0074234Claude637// Pull requests
638app.route("/", pullRoutes);
09d5f39Claude639
2be65d0Claude640// Streaming PR review — SSE stream + embeddable widget
641// Mounted immediately after pullRoutes so /:owner/:repo/pulls/:number/review/*
642// resolves before the webRoutes catch-all takes over.
643import streamingReviewRoutes from "./routes/streaming-review";
644app.route("/", streamingReviewRoutes);
645
09d5f39Claude646// /stage PR preview — serve built static files from .stage-previews/{jobId}/
647// Registered immediately after pullRoutes so the path `/preview/:id/*` is
648// specific enough to never clash with repo browse routes (`/:owner/:repo/*`).
649app.get("/preview/:stageJobId/*", async (c) => {
650 const { stageJobId } = c.req.param();
651 // Validate job ID format (UUID)
652 if (!/^[0-9a-f-]{32,}$/i.test(stageJobId)) {
653 return c.text("Not found", 404);
654 }
655 const { getPreviewDir, isPreviewExpired } = await import("./lib/pr-stage");
656 if (isPreviewExpired(stageJobId)) {
657 return c.html(
658 "<html><body style='font-family:sans-serif;padding:40px;color:#888'>" +
659 "<h2>Preview expired</h2><p>This stage preview has expired (48h TTL). " +
660 "Comment <code>/stage</code> on the PR to redeploy.</p></body></html>",
661 410
662 );
663 }
664 const { join } = await import("path");
665 const previewDir = getPreviewDir(stageJobId);
666 // Extract the wildcard path after /preview/:id/
667 const rawPath = c.req.path.replace(/^\/preview\/[^/]+/, "") || "/";
668 const filePath = rawPath === "/" || rawPath === "" ? "/index.html" : rawPath;
669 const fullPath = join(previewDir, filePath);
670 const file = Bun.file(fullPath);
671 if (!(await file.exists())) {
672 // Try index.html fallback (SPA behaviour)
673 const indexFile = Bun.file(join(previewDir, "index.html"));
674 if (await indexFile.exists()) {
675 const html = await indexFile.text();
676 return c.html(html);
677 }
678 return c.text("Not found", 404);
679 }
680 const content = await file.arrayBuffer();
681 const ext = fullPath.split(".").pop()?.toLowerCase() ?? "";
682 const contentTypeMap: Record<string, string> = {
683 html: "text/html; charset=utf-8",
684 htm: "text/html; charset=utf-8",
685 css: "text/css; charset=utf-8",
686 js: "application/javascript; charset=utf-8",
687 mjs: "application/javascript; charset=utf-8",
688 json: "application/json; charset=utf-8",
689 png: "image/png",
690 jpg: "image/jpeg",
691 jpeg: "image/jpeg",
692 gif: "image/gif",
693 svg: "image/svg+xml",
694 ico: "image/x-icon",
695 webp: "image/webp",
696 woff: "font/woff",
697 woff2: "font/woff2",
698 ttf: "font/ttf",
699 txt: "text/plain; charset=utf-8",
700 xml: "application/xml",
701 webmanifest: "application/manifest+json",
702 };
703 const ct = contentTypeMap[ext] ?? "application/octet-stream";
704 return c.body(content, 200, {
705 "content-type": ct,
706 "cache-control": "public, max-age=300",
707 "x-stage-job-id": stageJobId,
708 });
709});
710
79ed944Claude711// PR sandboxes — runnable per-PR environments. Migration 0067.
712app.route("/", prSandboxRoutes);
0074234Claude713
9b3a183Claude714// Cloud dev environments — hosted VS Code in the browser. Migration 0072.
715app.route("/", devEnvRoutes);
716
c81ab7aClaude717// Fork
718app.route("/", forkRoutes);
719
0074234Claude720// Web file editor
721app.route("/", editorRoutes);
722
6f2809fClaude723// AI editor API routes (inline suggestions, explain, fix)
724app.route("/", aiEditorRoutes);
725
43de941Claude726// Contributors
727app.route("/", contributorRoutes);
728
699e5c7Claude729// Health liveness + metrics endpoints
2c34075Claude730app.route("/", healthRoutes);
731
f295f78Dictation App732// Cross-product platform status (public, CORS-open — see docs/PLATFORM_STATUS.md)
733app.route("/api/platform-status", platformStatus);
734
52ad8b1Claude735// Block L4 — Public stats counters (powers landing-page social proof)
736app.route("/", publicStatsRoutes);
737
738// Block L3 — Live /demo page + /api/v2/demo/* endpoints
739app.route("/", demoRoutes);
740
2316be6Claude741// Public /status — human-readable platform health page
742app.route("/", statusRoutes);
743
b1be050CC LABS App744// BLOCK S4 — Site-admin synthetic-monitor dashboard (/admin/status).
745// Mounted near the public status route so the two surfaces are visible
746// side-by-side; routes are gated by isSiteAdmin internally.
747app.route("/", adminStatusRoutes);
748
80bed05Claude749// /help — quickstart + API cheatsheet
750app.route("/", helpRoutes);
751
e0e4219Claude752// /docs — expanded documentation site (getting started, workflow YAML, MCP, API, agents)
753app.route("/", docsRoutes);
754
5f2e749Claude755// L8 — public /pricing page (free-tier polish). Mounted BEFORE marketing
756// so the new editorial pricing layout wins the route; the legacy marketing
757// pricing remains as a safety net but is shadowed at the router.
758app.route("/", pricingRoutes);
759
e1fc7dbClaude760// /changelog — manually curated platform release history
761app.route("/", changelogRoutes);
762
9f29b65Claude763// Enterprise sales page + contact form lead capture.
764app.route("/", enterpriseRoutes);
765
b0148e9Claude766// /pricing, /features, /about — marketing surface
767app.route("/", marketingRoutes);
768
adf5e18Claude769// /developer-program — partner + marketplace revenue-share page
770app.route("/", developerProgramRoutes);
771
5618f9aClaude772// SEO: robots.txt + sitemap.xml
773app.route("/", seoRoutes);
774
05cdb85Claude775// /api/version — live build SHA + uptime; client poller uses this to
776// surface 'New version available — reload' banners on deploy.
777app.route("/", versionRoutes);
778
ad189d6ccantynz-alt779// Site-admin console (admin.tsx). MUST be mounted BEFORE healthDashboardRoutes
780// — its generic GET `/:owner/:repo/health` (matching :owner=admin :repo=autopilot)
781// was shadowing `/admin/autopilot/health`, returning a real "repo not found"
782// 404 for a route that exists and works fine once actually reached. Same bug
783// class as the adminOpsRoutes/insightRoutes note below; found via a live
784// production HTTP sweep (curled all 201 static page routes) — the health
785// dashboard existing didn't stop this specific admin page being unreachable.
786app.route("/", adminRoutes);
787
76ee7bcccantynz-alt788// Org health — MUST be mounted BEFORE healthDashboardRoutes. Its literal
789// `/orgs/:slug/health` was shadowed by healthDashboardRoutes' generic
790// `/:owner/:repo/health` (matching :owner=orgs :repo=<slug>), so every
791// org-health page 404'd and the whole feature was dead. Mirrors the
792// orgInsightsRoutes-before-insightRoutes fix below. org-health only matches
793// the literal `/orgs/...` prefix, so mounting it first is safe.
794app.route("/", orgHealthRoutes);
795
699e5c7Claude796// Health dashboard (per-repo health page)
797app.route("/", healthDashboardRoutes);
798
9dd96b9Test User799// Block R1 — site-admin operations console. MUST be mounted BEFORE
800// insightRoutes because its POST `/:owner/:repo/rollback` catch-all would
801// otherwise intercept `/admin/ops/rollback` (matching :owner=admin :repo=ops).
802app.route("/", adminOpsRoutes);
f2c00b4CC LABS App803// BLOCK W — Self-host status + bootstrap dashboard.
804app.route("/", adminSelfHostRoutes);
826eccfTest User805// BLOCK X — AI health-scan diagnose page (/admin/diagnose).
806app.route("/", adminDiagnoseRoutes);
f9814d2Claude807// Unified admin command center — /admin/command
808app.route("/", adminCommandRoutes);
9dd96b9Test User809
6a645f0ccantynz-alt810// Org insights — MUST be mounted BEFORE insightRoutes. insightRoutes' repo
811// insights hub (GET /:owner/:repo/insights) would otherwise match
812// /orgs/:slug/insights (owner="orgs") and 404 it before the org router runs.
813// Same route-shadowing class as the adminOps/insights note above. org-insights
814// only matches the literal "/orgs/..." prefix, so mounting it first is safe.
815app.route("/", orgInsightsRoutes);
816
817// Insights (repo insights hub, time-travel, dependencies, rollback)
16b325cClaude818app.route("/", insightRoutes);
819
8286942Claude820// Engineering Intelligence Dashboard — /insights + /:owner/:repo/insights/engineering
821app.route("/", engineeringInsightsRoutes);
822
8d1483cClaude823// DORA metrics page (/:owner/:repo/insights/dora)
824app.route("/", doraRoutes);
825
f1ab587Claude826// Command center dashboard
827app.route("/", dashboardRoutes);
828
36b4cbdClaude829// Legal pages (terms, privacy, AUP)
830app.route("/", legalRoutes);
4b66018Claude831// Long-form legal sub-pages — /legal/{terms,privacy,acceptable-use,dmca}.
832// The main `legal.tsx` serves the short canonical paths (/terms, /privacy,
833// /acceptable-use); these are the formal versions that the legal pages
834// internally link to each other.
835app.route("/", legalTermsRoutes);
836app.route("/", legalPrivacyRoutes);
837app.route("/", legalAcceptableUseRoutes);
838app.route("/", legalDmcaRoutes);
36b4cbdClaude839
bdbd0deClaude840// GitHub import / migration
841app.route("/", importRoutes);
14c3cc8Claude842app.route("/", importBulkRoutes);
f390cfaCC LABS App843app.route("/", importSecretsRoutes);
bb2dea9Claude844// GitHub Actions → Gluecron gates.yml importer (stateless converter)
845app.route("/", actionsImporterRoutes);
14c3cc8Claude846app.route("/", migrationRoutes);
ba23fe2Claude847app.route("/", migrationAssistantRoutes);
9a8b8deClaude848// GitHub Org Migration Wizard — live progress bulk importer
849app.route("/", migrateRoutes);
14c3cc8Claude850
851// Spec-to-PR (experimental AI-generated draft PRs)
852app.route("/", specsRoutes);
23d0abfClaude853app.route("/", refactorRoutes);
b665cacClaude854app.route("/", codebaseMigratorRoutes);
bdbd0deClaude855
c81ab7aClaude856// Explore page
857app.route("/", exploreRoutes);
858
59b6fb2Claude859// Onboarding
860app.route("/", onboardingRoutes);
861
ad189d6ccantynz-alt862// Admin + feature routes (adminRoutes itself is mounted earlier — see the
863// comment above healthDashboardRoutes)
7293c67Claude864app.route("/", adminDeletionsRoutes);
865app.route("/", adminStripeRoutes);
ba9e143Claude866
867// SOC 2 security dashboard + readiness checklist (/admin/security, /admin/soc2)
868app.route("/", adminSecurityRoutes);
509c376Claude869app.route("/", adminIntegrationsRoutes);
bc519aeClaude870app.route("/", adminEnvHealthRoutes);
79ed944Claude871app.route("/", adminAdvancementRoutes);
f764c07Claude872app.route("/", adminDeploysRoutes);
873app.route("/", adminDeploysPageRoutes);
783dd46Claude874app.route("/", adminServerTargetsRoutes);
9aaa128Claude875app.route("/", deployTargetsRoutes);
90c7531Claude876app.route("/", claudeWebRoutes);
9dd96b9Test User877// Note: adminOpsRoutes is mounted earlier (before insightRoutes) — see comment above.
0316dbbClaude878app.route("/", advisoriesRoutes);
879app.route("/", aiChangelogRoutes);
0a69faaClaude880// "Explain This Repo" — rich structured AI analysis dashboard (mounted before
881// the simpler aiExplainRoutes so the new routes win on /:owner/:repo/explain).
882app.route("/", explainRoutes);
0316dbbClaude883app.route("/", aiExplainRoutes);
2be65d0Claude884app.route("/", archaeologyRoutes);
0316dbbClaude885app.route("/", aiTestsRoutes);
886app.route("/", askRoutes);
38d31d3Claude887app.route("/", repoChatRoutes);
ee7e577Claude888// Personal cross-repo chat — `/chat` (user-scoped). Mounted alongside
889// repoChatRoutes so the two surfaces share the catch-all priority.
890app.route("/", personalChatRoutes);
0316dbbClaude891app.route("/", billingRoutes);
8809b87Claude892app.route("/", billingUsageRoutes);
6778ad2Claude893app.route("/", stripeWebhookRoutes);
0316dbbClaude894app.route("/", codeScanningRoutes);
da3fc18Claude895// Dependency CVE scanner findings page — /:owner/:repo/security/vulnerabilities
896app.route("/", securityRoutes);
0316dbbClaude897app.route("/", commitStatusesRoutes);
898app.route("/", copilotRoutes);
f5d020fClaude899app.route("/", pairProgrammerRoutes);
0316dbbClaude900app.route("/", depUpdaterRoutes);
901app.route("/", depsRoutes);
902app.route("/", discussionsRoutes);
903app.route("/", environmentsRoutes);
4bbacbeClaude904app.route("/", previewsRoutes);
79ed944Claude905app.route("/", docsTrackingRoutes);
0316dbbClaude906app.route("/", followsRoutes);
907app.route("/", gatesRoutes);
908app.route("/", gistsRoutes);
909app.route("/", graphqlRoutes);
2c2163eClaude910app.route("/", mcpRoutes);
8102dd4ccantynz-alt911// marketplaceAgentsRoutes MUST precede marketplaceRoutes: the latter defines
912// the generic `/marketplace/:slug`, which otherwise swallows the literal
913// `/marketplace/agents` (and `/marketplace/agents/publish`) and 404s them as
914// unknown app slugs.
5ca514aClaude915app.route("/", marketplaceAgentsRoutes);
8102dd4ccantynz-alt916app.route("/", marketplaceRoutes);
0316dbbClaude917app.route("/", mergeQueueRoutes);
918app.route("/", mirrorsRoutes);
76ee7bcccantynz-alt919// orgInsightsRoutes + orgHealthRoutes are mounted earlier (before the generic
920// repo routes) — see the notes there.
0316dbbClaude921app.route("/", packagesRoutes);
922app.route("/", packagesApiRoutes);
845fd8aClaude923// OCI / Docker container registry — /v2/* (OCI Distribution Spec v1.0)
924app.route("/", ociRegistryRoutes);
0316dbbClaude925app.route("/", pagesRoutes);
926app.route("/", projectsRoutes);
927app.route("/", protectedTagsRoutes);
928app.route("/", pwaRoutes);
46d6165Claude929app.route("/", installRoutes);
cd4f63bTest User930// BLOCK Q1 — /gluecron.dxt download (Claude Desktop one-click extension)
931app.route("/", dxtRoutes);
662ce86Claude932// Connect Claude — user-facing one-click MCP setup (/connect/claude). Mounted
933// next to the other one-click flows (install.sh + .dxt) for surface symmetry.
934app.route("/", connectClaudeRoutes);
f5b9ef5Claude935// Claude Code Integration Receiver — /api/claude/connect + /api/claude/session.
936app.route("/", claudeIntegration);
937// Connect guide — public onboarding page (/connect/claude-guide).
938app.route("/", connectRoutes);
05ab9b1Claude939// Push Watch — per-commit live status (gates + deploy + latency) at /:owner/:repo/push/:sha
940app.route("/", pushWatchRoutes);
941// Org Secrets Manager — BLOCK M2 — /orgs/:slug/settings/secrets
942app.route("/", orgSecretsRoutes);
a2b3e99Claude943// Cross-repo code search — BLOCK M3 — /search/code + /api/search/code
944app.route("/", crossRepoSearchRoutes);
945// Browser push notifications — BLOCK M4 — /settings/notifications/push + /api/push/*
946app.route("/", pushNotifRoutes);
9fbe6cdClaude947// Developer Velocity Dashboard — BLOCK M9 — /:owner/:repo/insights/velocity
948app.route("/", velocityRoutes);
949// Stale Branch Cleanup — BLOCK M10 — /:owner/:repo/branches/stale
950app.route("/", staleBranchRoutes);
22f43f3Claude951// Repository Pulse — BLOCK M12 — /:owner/:repo/pulse
952app.route("/", pulseRoutes);
74d8c4dClaude953// Repository Health Score — BLOCK M14 — /:owner/:repo/insights/health
954app.route("/", healthScoreRoutes);
77cf834Claude955// Repository Health Score breakdown page — /:owner/:repo/health
956app.route("/", repoHealthRoutes);
74d8c4dClaude957// Hot Files Heatmap — BLOCK M16 — /:owner/:repo/insights/hotfiles
958app.route("/", hotFilesRoutes);
bcc4020Claude959// AI Technical Debt Map — /:owner/:repo/debt-map (visual debt graph + Claude analysis)
960app.route("/", debtMapRoutes);
1d6db4dClaude961// Bus Factor Analysis — /:owner/:repo/insights/bus-factor
962app.route("/", busFactorRoutes);
b02ce30Claude963// Test Gap Detector — /:owner/:repo/insights/test-gaps
964app.route("/", testGapsRoutes);
f5d020fClaude965// Cross-Repo Dependency Impact Detection — /:owner/:repo/pulls/:number/cross-repo-impact
966app.route("/", crossRepoImpactRoutes);
ebbb527Claude967// Hosted Claude tool-use loops — paste loop, get endpoint, billing meter.
968// See src/routes/claude-deploy.tsx + src/lib/hosted-claude-loop.ts.
969app.route("/", claudeDeployRoutes);
0316dbbClaude970app.route("/", releasesRoutes);
971app.route("/", requiredChecksRoutes);
972app.route("/", rulesetsRoutes);
973app.route("/", searchRoutes);
974app.route("/", semanticSearchRoutes);
77cf834Claude975app.route("/", nlSearchRoutes);
0316dbbClaude976app.route("/", signingKeysRoutes);
977app.route("/", sponsorsRoutes);
978app.route("/", ssoRoutes);
3a845e4Claude979// Enterprise per-org SAML 2.0 + OIDC SSO routes
980app.route("/", samlSsoRoutes);
981// SCIM 2.0 user provisioning endpoints
982app.route("/", scimRoutes);
983// Per-org SSO + SCIM admin settings UI
984app.route("/", orgSsoSettingsRoutes);
46d6165Claude985app.route("/", githubOauthRoutes);
582cdacClaude986app.route("/", googleOauthRoutes);
0316dbbClaude987app.route("/", symbolsRoutes);
988app.route("/", templatesRoutes);
989app.route("/", trafficRoutes);
990app.route("/", wikisRoutes);
991app.route("/", workflowsRoutes);
5ff9cc2Claude992app.route("/", workflowArtifactsRoutes);
993app.route("/", workflowSecretsRoutes);
46d6165Claude994app.route("/", sleepModeRoutes);
52ad8b1Claude995app.route("/", vsGithubRoutes);
0316dbbClaude996
45f3b73Claude997// Voice-to-PR — phone-first dictation → spec or issue
998app.route("/", voiceRoutes);
999
3122762Claude1000// Blog / Devlog — public posts, no DB
1001app.route("/", blogRoutes);
1002
cd4f63bTest User1003// Block Q3 — Anonymous playground (`/play`, `/play/claim`). Mounted
1004// before the web catch-all so the bare `/play` literal wins over the
1005// `/:owner` user-profile route.
1006app.route("/", playgroundRoutes);
1007
891efbeClaude1008// Shareable AI hours-saved OG image card + landing page.
1009// /share/hours-saved?user=:username → 1200×630 SVG (og:image)
1010// /share/:username → HTML page with og:image meta + Twitter share
1011// Mounted BEFORE webRoutes so /share/* doesn't fall through to the /:owner profile route.
1012app.route("/", shareRoutes);
1013
4abf6f1ccantynz-alt1014// Machine surfaces must fail in the format their clients parse. An
1015// unmatched /api/* path used to fall through to the HTML 404 page, so a
1016// REST/MCP/registry client asking for JSON got a full HTML document and
1017// blew up on JSON.parse instead of seeing a readable error. Decided by
1018// path root (these mounts are JSON-only by contract) or by an Accept
1019// header that asks for JSON and not HTML.
1020const JSON_ROOTS = [
1021 "/api",
1022 "/mcp",
1023 "/graphql",
1024 "/v2", // OCI registry — the spec mandates a JSON error envelope
1025 "/npm",
1026 "/scim",
1027 "/.well-known",
1028];
1029
1030function wantsJson(c: {
1031 req: { path: string; header: (n: string) => string | undefined };
1032}) {
1033 const path = c.req.path;
1034 // Match the root exactly or as a path segment — "/mcp" and "/mcp/x" are
1035 // machine surfaces, "/mcpanything" is not.
1036 if (JSON_ROOTS.some((r) => path === r || path.startsWith(r + "/"))) return true;
1037 const accept = c.req.header("accept") ?? "";
1038 return accept.includes("application/json") && !accept.includes("text/html");
1039}
1040
1041function jsonNotFound(c: Context) {
1042 return c.json(
1043 { error: "Not found", path: c.req.path, method: c.req.method },
1044 404
1045 );
1046}
1047
1048// Machine-surface 404 fallback — MUST be registered before webRoutes.
1049// webRoutes owns the `/:owner/:repo` catch-all, so an unmatched two-segment
1050// path like `/api/nope` was being read as owner="api", repo="nope" and
1051// answered with the HTML "repository not found" page. REST/MCP/OCI clients
1052// then choked on HTML where they expected a JSON envelope. Terminating the
1053// machine roots here keeps them JSON-only by contract.
1054for (const root of JSON_ROOTS) {
1055 app.all(root, (c) => jsonNotFound(c));
1056 app.all(`${root}/*`, (c) => jsonNotFound(c));
1057}
1058
79136bbClaude1059// Web UI (catch-all, must be last)
1060app.route("/", webRoutes);
1061
c63b860Claude1062// Global 404 — BLOCK O2 routes the shared `NotFoundPage` view so
1063// the markup stays consistent with /500 and the admin /403 page.
79136bbClaude1064app.notFound((c) => {
4abf6f1ccantynz-alt1065 if (wantsJson(c)) {
1066 return c.json(
1067 { error: "Not found", path: c.req.path, method: c.req.method },
1068 404
1069 );
1070 }
36cc17aClaude1071 const user = c.get("user") ?? null;
79136bbClaude1072 return c.html(
c63b860Claude1073 <NotFoundPage user={user} method={c.req.method} path={c.req.path} />,
79136bbClaude1074 404
1075 );
1076});
1077
c63b860Claude1078// Global error handler — BLOCK O2 uses the shared `ServerErrorPage`
1079// view. Trace block only shown outside production.
79136bbClaude1080app.onError((err, c) => {
80bed05Claude1081 reportError(err, {
1082 requestId: c.get("requestId"),
1083 path: c.req.path,
1084 method: c.req.method,
1085 });
c63b860Claude1086 // Prefer the inbound `x-request-id` header (LB-supplied) and fall
1087 // back to the context value set by request-context middleware.
1088 const requestId =
1089 c.req.header("x-request-id") ||
1090 ((c.get("requestId" as never) as string | undefined) ?? undefined);
36cc17aClaude1091 const user = c.get("user") ?? null;
c63b860Claude1092 const trace =
1093 process.env.NODE_ENV !== "production" && err && err.message
1094 ? err.message
1095 : undefined;
4abf6f1ccantynz-alt1096 // Same reasoning as the 404 above: an API/MCP client must get a JSON
1097 // envelope it can parse, not the HTML error page.
1098 if (wantsJson(c)) {
1099 return c.json(
1100 { error: "Internal server error", requestId, ...(trace ? { trace } : {}) },
1101 500
1102 );
1103 }
79136bbClaude1104 return c.html(
c63b860Claude1105 <ServerErrorPage user={user} requestId={requestId} trace={trace} />,
79136bbClaude1106 500
1107 );
1108});
1109
1110export default app;