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.tsxBlame1103 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"));
79136bbClaude378
59b6fb2Claude379// CSRF protection — set token on all requests, validate on mutations
380app.use("*", csrfToken);
381app.use("*", csrfProtect);
382
45e31d0Claude383// Rate limit auth routes
384app.use("/login", authRateLimit);
385app.use("/register", authRateLimit);
386
59b6fb2Claude387// Rate limit git operations
388app.use("/:owner/:repo.git/*", gitRateLimit);
389
390// Rate limit search
391app.use("/:owner/:repo/search", searchRateLimit);
392app.use("/explore", searchRateLimit);
79136bbClaude393
4d4bd4bccantynz-alt394// Rate limit the v1 REST API and the MCP surface. api-v2 already applies its
395// own apiRateLimit internally (this stacks harmlessly for /api/v2/*); v1
396// (src/routes/api.ts) and /mcp had NO rate limiting at all despite /mcp
397// being the primary, anonymously-reachable AI-agent interface and able to
398// trigger expensive per-call work (e.g. gluecron_repo_health scans every
399// file in a repo). softAuth already runs on both, so the existing
400// authedMultiplier (4x for a signed-in caller) applies automatically.
401app.use("/api/*", apiRateLimit);
402app.use("/mcp", apiRateLimit);
403
f5b9ef5Claude404// No-cache for HTML — ensures browsers and proxies never serve stale pages.
405// The middleware only stamps text/html responses so static assets keep
406// their own cache policies unchanged.
407app.use("*", noCache);
408
8ed1b31ccantynz-alt409/**
410 * Platform-wide private-repository gate for `/:owner/:repo/...` pages.
411 *
412 * Every repo subpage was responsible for its own privacy check, and that
413 * drifted badly: a live probe of a private repo found 24 subpages rendering
414 * 200 to an anonymous visitor — /actions, /deployments, /discussions,
415 * /packages, /projects, /wiki, /insights, /contributors, /gates, /queue,
416 * /previews, /pushes, /health, /coupling, /dependencies, /explain,
417 * /archaeology, /cloud-deployments, /ai/changelog, /ai/tests, /docs/tracking,
418 * /search/nl, /search/semantic, /insights/engineering — while the repo root
419 * correctly 404'd. Each leaked names, history, CI logs or dependency data.
420 *
421 * Gating centrally is the point: ~20 route files each re-implementing the
422 * check is what produced the drift, and a subpage added tomorrow inherits
423 * this automatically.
424 *
425 * Safe against false positives. Paths like /settings/tokens or /orgs/new also
426 * match `/:owner/:repo`, but loadRepoByPath returns null for them and the
427 * request falls straight through — exactly as it does for a repo that does
428 * not exist, so each handler keeps emitting its own 404. `/:owner/:repo.git/*`
429 * (git Smart HTTP) resolves `:repo` as "name.git", also null, so the git
430 * protocol's own auth is untouched.
431 *
432 * Registered before every repo router and after softAuth, so c.get("user")
433 * is populated and owners/collaborators are unaffected.
434 */
435app.use("/:owner/:repo/*", async (c, next) => {
436 const owner = c.req.param("owner");
437 const repo = c.req.param("repo");
438 if (!owner || !repo) return next();
439
440 let row: { id: string; isPrivate: boolean } | null = null;
441 try {
442 const { loadRepoByPath } = await import("./lib/namespace");
443 const found = await loadRepoByPath(owner, repo);
444 row = found ? { id: found.id, isPrivate: found.isPrivate } : null;
445 } catch {
446 // Namespace resolution failed (DB blip) — do not invent a denial for
447 // public content; the handler below will surface its own error.
448 return next();
449 }
450 if (!row || !row.isPrivate) return next();
451
452 const viewer = c.get("user");
453 const { resolveRepoAccess } = await import("./middleware/repo-access");
454 const access = await resolveRepoAccess({
455 repoId: row.id,
456 userId: viewer?.id ?? null,
457 isPublic: false,
458 });
459 if (access !== "none") return next();
460
461 // 404, not 403 — a private repo must not confirm its own existence. Matches
462 // what the repo root already does.
463 const accepts = c.req.header("accept") ?? "";
464 if (accepts.includes("application/json") && !accepts.includes("text/html")) {
465 return c.json({ error: "Not found" }, 404);
466 }
467 return c.html(<NotFoundPage user={viewer ?? null} method={c.req.method} path={c.req.path} />, 404);
468});
469
79136bbClaude470// Git Smart HTTP protocol routes (must be before web routes)
471app.route("/", gitRoutes);
472
45e31d0Claude473// REST API v1 (legacy)
79136bbClaude474app.route("/", apiRoutes);
475
52ad8b1Claude476// Block L3 — /demo + /api/v2/demo/* live demo endpoints. Mounted BEFORE
477// apiV2Routes so the /api/v2/demo/* JSON endpoints win over the v2 base
478// router's catch-shape, and BEFORE adminRoutes so the live /demo page
479// wins over the legacy /demo redirect in src/routes/admin.tsx.
480app.route("/", demoRoutes);
481
0316dbbClaude482// REST API v2 (basePath /api/v2)
483app.route("/", apiV2Routes);
484
e75eddcClaude485// Agent multiplayer v1 — /api/v2/agents/* (sessions, leases, usage).
486// Mounted alongside apiV2Routes (its own basePath, no path conflict).
487app.route("/", agentsRoutes);
488
ef3fd93Claude489// Multi-agent pipeline UI — /:owner/:repo/agents (list, new, live view).
490// Must be before webRoutes (the catch-all) so the /agents sub-paths are
491// resolved before the generic tree/blob route takes over.
492app.route("/", agentPipelinesRoutes);
493
ad6d4adClaude494// Inbound API hooks (GateTest callback + backup PAT-authed /api/v1/gate-runs)
495app.route("/", hookRoutes);
21f8dbdClaude496app.route("/api/events", eventsRoutes);
ad6d4adClaude497
45e31d0Claude498// API documentation
499app.route("/", apiDocsRoutes);
4a80519Claude500app.route("/", buildAgentSpecRoutes);
a6ff0f2Claude501// PR command center — global PR dashboard with AI/GateTest/auto-merge signal
502app.route("/", pullsDashboardRoutes);
e9aa4d8Claude503// Issue command center — global issue dashboard with AI-triage + autopilot signal
504app.route("/", issuesDashboardRoutes);
505// Personal activity timeline — every event across the user's repos, with
506// AI-driven events surfaced separately (the Gluecron differentiator).
507app.route("/", activityRoutes);
508// Unified inbox — mentions + review requests + CI failures + AI events in one timeline
509app.route("/", inboxRoutes);
56801e1Claude510// AI standup feed — daily / weekly Claude-generated team brief
511app.route("/", standupRoutes);
cc34156Claude512// Smart morning digest — AI-curated daily developer queue (/digest)
513app.route("/", digestRoutes);
79136bbClaude514
515// Auth routes (register, login, logout)
516app.route("/", authRoutes);
517
c63b860Claude518// BLOCK P1 — Password reset (forgot-password + reset-password)
519app.route("/", passwordResetRoutes);
520
521// BLOCK P2 — Email verification (verify-email + resend)
522app.route("/", emailVerificationRoutes);
523
cd4f63bTest User524// BLOCK Q2 — Magic-link sign-in (/login/magic + callback)
525app.route("/", magicLinkRoutes);
526
79136bbClaude527// Settings routes (profile, SSH keys)
528app.route("/", settingsRoutes);
529
ba9e143Claude530// Session management (SOC 2 CC6.1 — /settings/sessions)
531app.route("/", settingsSessionsRoutes);
532
7298a17Claude533// 2FA / TOTP settings (Block B4)
534app.route("/", settings2faRoutes);
535
e75eddcClaude536// Agent multiplayer — /settings/agents management UI
537app.route("/", settingsAgentsRoutes);
538
1d4ff60Claude539// Chat integrations — Slack / Discord / Teams (/settings/integrations
540// + /api/v2/integrations/{slack,discord}/*). See src/lib/chat-bot.ts.
541app.route("/", settingsIntegrationsRoutes);
542app.route("/", integrationsChatRoutes);
4cd6791ccantynz-alt543// Incident hooks — /settings/incident-hooks (page) + the inbound incident
544// webhook receivers. Was imported but NEVER mounted, so the whole file was
545// dead and /settings/incident-hooks (linked from the settings nav) 404'd.
546app.route("/", incidentHookRoutes);
1d4ff60Claude547
2df1f8cClaude548// WebAuthn / passkey routes (Block B5)
549app.route("/", passkeyRoutes);
550
058d752Claude551// OAuth 2.0 provider (Block B6)
552app.route("/", oauthRoutes);
553app.route("/", developerAppsRoutes);
369ad65ccanty labs554// OAuth / agent discovery metadata (RFC 8414 + RFC 9728) — lets claude.ai,
555// Cursor, Copilot, etc. auto-discover how to authenticate.
556app.route("/", wellKnownRoutes);
058d752Claude557
6fc53bdClaude558// Theme toggle (dark/light cookie)
559app.route("/", themeRoutes);
560
561// Audit log UI
562app.route("/", auditRoutes);
563
564// Reactions API (issues, PRs, comments)
565app.route("/", reactionRoutes);
566
24cf2caClaude567// Saved replies (per-user canned comment templates)
568app.route("/", savedReplyRoutes);
569
570// Environments + deployment history UI
571app.route("/", deploymentRoutes);
2c61840Claude572// Unified CI/CD pipeline timeline
573app.route("/", pipelineRoutes);
24cf2caClaude574
6563f0aClaude575// Organizations + teams (Block B1)
576app.route("/", orgRoutes);
577
c81ab7aClaude578// API tokens
579app.route("/", tokenRoutes);
580
59b6fb2Claude581// Notifications
3ef4c9dClaude582app.route("/", notificationRoutes);
583
79136bbClaude584// Repo settings (description, visibility, delete)
585app.route("/", repoSettings);
479dcd9Claude586// Per-repo automation settings (off / suggest / auto) — migration 0106
587app.route("/", automationSettingsRoutes);
79136bbClaude588
23d1a81Claude589// Repo collaborators (add/list/remove)
590app.route("/", collaboratorRoutes);
591
04f6b7fClaude592// Team-based repo collaborators (invite a whole team)
593app.route("/", teamCollaboratorRoutes);
594
595// Collaborator invite accept flow (token-based)
596app.route("/", invitesRoutes);
597
598// Real-time SSE endpoint (topic-based live updates)
599app.route("/", liveEventsRoutes);
600
3c03977Claude601// PR live co-editing — presence + cursors + content sync via SSE.
602app.route("/", prLiveRoutes);
603
c81ab7aClaude604// Webhooks management
605app.route("/", webhookRoutes);
606
79136bbClaude607// Compare view (branch diffs)
608app.route("/", compareRoutes);
609
610// Issue tracker
611app.route("/", issueRoutes);
612
85c4e13Claude613// Milestones — group issues + PRs toward a shared goal with due dates + progress tracking.
614// Mounted after issueRoutes so /:owner/:repo/issues/* paths win before the milestone patterns.
615app.route("/", milestonesRoutes);
616
f928118Claude617// Ship Agent — autonomous AI feature implementation
618app.route("/", shipAgentRoutes);
619
77cf834Claude620// AI Copilot Workspace — issue-to-PR autonomous agent
621app.route("/", workspaceRoutes);
2c61840Claude622app.route("/", workspaceHubRoutes);
77cf834Claude623
cb5a796Claude624// Comment moderation queue — owner-only `/:owner/:repo/comments/pending`
625// + per-row approve/reject/spam actions. Mounted before `pullRoutes` so
626// the `/:owner/:repo/comments/*` paths resolve before the broader PR
627// patterns kick in.
628app.route("/", commentModerationRoutes);
629
0074234Claude630// Pull requests
631app.route("/", pullRoutes);
09d5f39Claude632
2be65d0Claude633// Streaming PR review — SSE stream + embeddable widget
634// Mounted immediately after pullRoutes so /:owner/:repo/pulls/:number/review/*
635// resolves before the webRoutes catch-all takes over.
636import streamingReviewRoutes from "./routes/streaming-review";
637app.route("/", streamingReviewRoutes);
638
09d5f39Claude639// /stage PR preview — serve built static files from .stage-previews/{jobId}/
640// Registered immediately after pullRoutes so the path `/preview/:id/*` is
641// specific enough to never clash with repo browse routes (`/:owner/:repo/*`).
642app.get("/preview/:stageJobId/*", async (c) => {
643 const { stageJobId } = c.req.param();
644 // Validate job ID format (UUID)
645 if (!/^[0-9a-f-]{32,}$/i.test(stageJobId)) {
646 return c.text("Not found", 404);
647 }
648 const { getPreviewDir, isPreviewExpired } = await import("./lib/pr-stage");
649 if (isPreviewExpired(stageJobId)) {
650 return c.html(
651 "<html><body style='font-family:sans-serif;padding:40px;color:#888'>" +
652 "<h2>Preview expired</h2><p>This stage preview has expired (48h TTL). " +
653 "Comment <code>/stage</code> on the PR to redeploy.</p></body></html>",
654 410
655 );
656 }
657 const { join } = await import("path");
658 const previewDir = getPreviewDir(stageJobId);
659 // Extract the wildcard path after /preview/:id/
660 const rawPath = c.req.path.replace(/^\/preview\/[^/]+/, "") || "/";
661 const filePath = rawPath === "/" || rawPath === "" ? "/index.html" : rawPath;
662 const fullPath = join(previewDir, filePath);
663 const file = Bun.file(fullPath);
664 if (!(await file.exists())) {
665 // Try index.html fallback (SPA behaviour)
666 const indexFile = Bun.file(join(previewDir, "index.html"));
667 if (await indexFile.exists()) {
668 const html = await indexFile.text();
669 return c.html(html);
670 }
671 return c.text("Not found", 404);
672 }
673 const content = await file.arrayBuffer();
674 const ext = fullPath.split(".").pop()?.toLowerCase() ?? "";
675 const contentTypeMap: Record<string, string> = {
676 html: "text/html; charset=utf-8",
677 htm: "text/html; charset=utf-8",
678 css: "text/css; charset=utf-8",
679 js: "application/javascript; charset=utf-8",
680 mjs: "application/javascript; charset=utf-8",
681 json: "application/json; charset=utf-8",
682 png: "image/png",
683 jpg: "image/jpeg",
684 jpeg: "image/jpeg",
685 gif: "image/gif",
686 svg: "image/svg+xml",
687 ico: "image/x-icon",
688 webp: "image/webp",
689 woff: "font/woff",
690 woff2: "font/woff2",
691 ttf: "font/ttf",
692 txt: "text/plain; charset=utf-8",
693 xml: "application/xml",
694 webmanifest: "application/manifest+json",
695 };
696 const ct = contentTypeMap[ext] ?? "application/octet-stream";
697 return c.body(content, 200, {
698 "content-type": ct,
699 "cache-control": "public, max-age=300",
700 "x-stage-job-id": stageJobId,
701 });
702});
703
79ed944Claude704// PR sandboxes — runnable per-PR environments. Migration 0067.
705app.route("/", prSandboxRoutes);
0074234Claude706
9b3a183Claude707// Cloud dev environments — hosted VS Code in the browser. Migration 0072.
708app.route("/", devEnvRoutes);
709
c81ab7aClaude710// Fork
711app.route("/", forkRoutes);
712
0074234Claude713// Web file editor
714app.route("/", editorRoutes);
715
6f2809fClaude716// AI editor API routes (inline suggestions, explain, fix)
717app.route("/", aiEditorRoutes);
718
43de941Claude719// Contributors
720app.route("/", contributorRoutes);
721
699e5c7Claude722// Health liveness + metrics endpoints
2c34075Claude723app.route("/", healthRoutes);
724
f295f78Dictation App725// Cross-product platform status (public, CORS-open — see docs/PLATFORM_STATUS.md)
726app.route("/api/platform-status", platformStatus);
727
52ad8b1Claude728// Block L4 — Public stats counters (powers landing-page social proof)
729app.route("/", publicStatsRoutes);
730
731// Block L3 — Live /demo page + /api/v2/demo/* endpoints
732app.route("/", demoRoutes);
733
2316be6Claude734// Public /status — human-readable platform health page
735app.route("/", statusRoutes);
736
b1be050CC LABS App737// BLOCK S4 — Site-admin synthetic-monitor dashboard (/admin/status).
738// Mounted near the public status route so the two surfaces are visible
739// side-by-side; routes are gated by isSiteAdmin internally.
740app.route("/", adminStatusRoutes);
741
80bed05Claude742// /help — quickstart + API cheatsheet
743app.route("/", helpRoutes);
744
e0e4219Claude745// /docs — expanded documentation site (getting started, workflow YAML, MCP, API, agents)
746app.route("/", docsRoutes);
747
5f2e749Claude748// L8 — public /pricing page (free-tier polish). Mounted BEFORE marketing
749// so the new editorial pricing layout wins the route; the legacy marketing
750// pricing remains as a safety net but is shadowed at the router.
751app.route("/", pricingRoutes);
752
e1fc7dbClaude753// /changelog — manually curated platform release history
754app.route("/", changelogRoutes);
755
9f29b65Claude756// Enterprise sales page + contact form lead capture.
757app.route("/", enterpriseRoutes);
758
b0148e9Claude759// /pricing, /features, /about — marketing surface
760app.route("/", marketingRoutes);
761
adf5e18Claude762// /developer-program — partner + marketplace revenue-share page
763app.route("/", developerProgramRoutes);
764
5618f9aClaude765// SEO: robots.txt + sitemap.xml
766app.route("/", seoRoutes);
767
05cdb85Claude768// /api/version — live build SHA + uptime; client poller uses this to
769// surface 'New version available — reload' banners on deploy.
770app.route("/", versionRoutes);
771
ad189d6ccantynz-alt772// Site-admin console (admin.tsx). MUST be mounted BEFORE healthDashboardRoutes
773// — its generic GET `/:owner/:repo/health` (matching :owner=admin :repo=autopilot)
774// was shadowing `/admin/autopilot/health`, returning a real "repo not found"
775// 404 for a route that exists and works fine once actually reached. Same bug
776// class as the adminOpsRoutes/insightRoutes note below; found via a live
777// production HTTP sweep (curled all 201 static page routes) — the health
778// dashboard existing didn't stop this specific admin page being unreachable.
779app.route("/", adminRoutes);
780
76ee7bcccantynz-alt781// Org health — MUST be mounted BEFORE healthDashboardRoutes. Its literal
782// `/orgs/:slug/health` was shadowed by healthDashboardRoutes' generic
783// `/:owner/:repo/health` (matching :owner=orgs :repo=<slug>), so every
784// org-health page 404'd and the whole feature was dead. Mirrors the
785// orgInsightsRoutes-before-insightRoutes fix below. org-health only matches
786// the literal `/orgs/...` prefix, so mounting it first is safe.
787app.route("/", orgHealthRoutes);
788
699e5c7Claude789// Health dashboard (per-repo health page)
790app.route("/", healthDashboardRoutes);
791
9dd96b9Test User792// Block R1 — site-admin operations console. MUST be mounted BEFORE
793// insightRoutes because its POST `/:owner/:repo/rollback` catch-all would
794// otherwise intercept `/admin/ops/rollback` (matching :owner=admin :repo=ops).
795app.route("/", adminOpsRoutes);
f2c00b4CC LABS App796// BLOCK W — Self-host status + bootstrap dashboard.
797app.route("/", adminSelfHostRoutes);
826eccfTest User798// BLOCK X — AI health-scan diagnose page (/admin/diagnose).
799app.route("/", adminDiagnoseRoutes);
f9814d2Claude800// Unified admin command center — /admin/command
801app.route("/", adminCommandRoutes);
9dd96b9Test User802
6a645f0ccantynz-alt803// Org insights — MUST be mounted BEFORE insightRoutes. insightRoutes' repo
804// insights hub (GET /:owner/:repo/insights) would otherwise match
805// /orgs/:slug/insights (owner="orgs") and 404 it before the org router runs.
806// Same route-shadowing class as the adminOps/insights note above. org-insights
807// only matches the literal "/orgs/..." prefix, so mounting it first is safe.
808app.route("/", orgInsightsRoutes);
809
810// Insights (repo insights hub, time-travel, dependencies, rollback)
16b325cClaude811app.route("/", insightRoutes);
812
8286942Claude813// Engineering Intelligence Dashboard — /insights + /:owner/:repo/insights/engineering
814app.route("/", engineeringInsightsRoutes);
815
8d1483cClaude816// DORA metrics page (/:owner/:repo/insights/dora)
817app.route("/", doraRoutes);
818
f1ab587Claude819// Command center dashboard
820app.route("/", dashboardRoutes);
821
36b4cbdClaude822// Legal pages (terms, privacy, AUP)
823app.route("/", legalRoutes);
4b66018Claude824// Long-form legal sub-pages — /legal/{terms,privacy,acceptable-use,dmca}.
825// The main `legal.tsx` serves the short canonical paths (/terms, /privacy,
826// /acceptable-use); these are the formal versions that the legal pages
827// internally link to each other.
828app.route("/", legalTermsRoutes);
829app.route("/", legalPrivacyRoutes);
830app.route("/", legalAcceptableUseRoutes);
831app.route("/", legalDmcaRoutes);
36b4cbdClaude832
bdbd0deClaude833// GitHub import / migration
834app.route("/", importRoutes);
14c3cc8Claude835app.route("/", importBulkRoutes);
f390cfaCC LABS App836app.route("/", importSecretsRoutes);
bb2dea9Claude837// GitHub Actions → Gluecron gates.yml importer (stateless converter)
838app.route("/", actionsImporterRoutes);
14c3cc8Claude839app.route("/", migrationRoutes);
ba23fe2Claude840app.route("/", migrationAssistantRoutes);
9a8b8deClaude841// GitHub Org Migration Wizard — live progress bulk importer
842app.route("/", migrateRoutes);
14c3cc8Claude843
844// Spec-to-PR (experimental AI-generated draft PRs)
845app.route("/", specsRoutes);
23d0abfClaude846app.route("/", refactorRoutes);
b665cacClaude847app.route("/", codebaseMigratorRoutes);
bdbd0deClaude848
c81ab7aClaude849// Explore page
850app.route("/", exploreRoutes);
851
59b6fb2Claude852// Onboarding
853app.route("/", onboardingRoutes);
854
ad189d6ccantynz-alt855// Admin + feature routes (adminRoutes itself is mounted earlier — see the
856// comment above healthDashboardRoutes)
7293c67Claude857app.route("/", adminDeletionsRoutes);
858app.route("/", adminStripeRoutes);
ba9e143Claude859
860// SOC 2 security dashboard + readiness checklist (/admin/security, /admin/soc2)
861app.route("/", adminSecurityRoutes);
509c376Claude862app.route("/", adminIntegrationsRoutes);
bc519aeClaude863app.route("/", adminEnvHealthRoutes);
79ed944Claude864app.route("/", adminAdvancementRoutes);
f764c07Claude865app.route("/", adminDeploysRoutes);
866app.route("/", adminDeploysPageRoutes);
783dd46Claude867app.route("/", adminServerTargetsRoutes);
9aaa128Claude868app.route("/", deployTargetsRoutes);
90c7531Claude869app.route("/", claudeWebRoutes);
9dd96b9Test User870// Note: adminOpsRoutes is mounted earlier (before insightRoutes) — see comment above.
0316dbbClaude871app.route("/", advisoriesRoutes);
872app.route("/", aiChangelogRoutes);
0a69faaClaude873// "Explain This Repo" — rich structured AI analysis dashboard (mounted before
874// the simpler aiExplainRoutes so the new routes win on /:owner/:repo/explain).
875app.route("/", explainRoutes);
0316dbbClaude876app.route("/", aiExplainRoutes);
2be65d0Claude877app.route("/", archaeologyRoutes);
0316dbbClaude878app.route("/", aiTestsRoutes);
879app.route("/", askRoutes);
38d31d3Claude880app.route("/", repoChatRoutes);
ee7e577Claude881// Personal cross-repo chat — `/chat` (user-scoped). Mounted alongside
882// repoChatRoutes so the two surfaces share the catch-all priority.
883app.route("/", personalChatRoutes);
0316dbbClaude884app.route("/", billingRoutes);
8809b87Claude885app.route("/", billingUsageRoutes);
6778ad2Claude886app.route("/", stripeWebhookRoutes);
0316dbbClaude887app.route("/", codeScanningRoutes);
da3fc18Claude888// Dependency CVE scanner findings page — /:owner/:repo/security/vulnerabilities
889app.route("/", securityRoutes);
0316dbbClaude890app.route("/", commitStatusesRoutes);
891app.route("/", copilotRoutes);
f5d020fClaude892app.route("/", pairProgrammerRoutes);
0316dbbClaude893app.route("/", depUpdaterRoutes);
894app.route("/", depsRoutes);
895app.route("/", discussionsRoutes);
896app.route("/", environmentsRoutes);
4bbacbeClaude897app.route("/", previewsRoutes);
79ed944Claude898app.route("/", docsTrackingRoutes);
0316dbbClaude899app.route("/", followsRoutes);
900app.route("/", gatesRoutes);
901app.route("/", gistsRoutes);
902app.route("/", graphqlRoutes);
2c2163eClaude903app.route("/", mcpRoutes);
8102dd4ccantynz-alt904// marketplaceAgentsRoutes MUST precede marketplaceRoutes: the latter defines
905// the generic `/marketplace/:slug`, which otherwise swallows the literal
906// `/marketplace/agents` (and `/marketplace/agents/publish`) and 404s them as
907// unknown app slugs.
5ca514aClaude908app.route("/", marketplaceAgentsRoutes);
8102dd4ccantynz-alt909app.route("/", marketplaceRoutes);
0316dbbClaude910app.route("/", mergeQueueRoutes);
911app.route("/", mirrorsRoutes);
76ee7bcccantynz-alt912// orgInsightsRoutes + orgHealthRoutes are mounted earlier (before the generic
913// repo routes) — see the notes there.
0316dbbClaude914app.route("/", packagesRoutes);
915app.route("/", packagesApiRoutes);
845fd8aClaude916// OCI / Docker container registry — /v2/* (OCI Distribution Spec v1.0)
917app.route("/", ociRegistryRoutes);
0316dbbClaude918app.route("/", pagesRoutes);
919app.route("/", projectsRoutes);
920app.route("/", protectedTagsRoutes);
921app.route("/", pwaRoutes);
46d6165Claude922app.route("/", installRoutes);
cd4f63bTest User923// BLOCK Q1 — /gluecron.dxt download (Claude Desktop one-click extension)
924app.route("/", dxtRoutes);
662ce86Claude925// Connect Claude — user-facing one-click MCP setup (/connect/claude). Mounted
926// next to the other one-click flows (install.sh + .dxt) for surface symmetry.
927app.route("/", connectClaudeRoutes);
f5b9ef5Claude928// Claude Code Integration Receiver — /api/claude/connect + /api/claude/session.
929app.route("/", claudeIntegration);
930// Connect guide — public onboarding page (/connect/claude-guide).
931app.route("/", connectRoutes);
05ab9b1Claude932// Push Watch — per-commit live status (gates + deploy + latency) at /:owner/:repo/push/:sha
933app.route("/", pushWatchRoutes);
934// Org Secrets Manager — BLOCK M2 — /orgs/:slug/settings/secrets
935app.route("/", orgSecretsRoutes);
a2b3e99Claude936// Cross-repo code search — BLOCK M3 — /search/code + /api/search/code
937app.route("/", crossRepoSearchRoutes);
938// Browser push notifications — BLOCK M4 — /settings/notifications/push + /api/push/*
939app.route("/", pushNotifRoutes);
9fbe6cdClaude940// Developer Velocity Dashboard — BLOCK M9 — /:owner/:repo/insights/velocity
941app.route("/", velocityRoutes);
942// Stale Branch Cleanup — BLOCK M10 — /:owner/:repo/branches/stale
943app.route("/", staleBranchRoutes);
22f43f3Claude944// Repository Pulse — BLOCK M12 — /:owner/:repo/pulse
945app.route("/", pulseRoutes);
74d8c4dClaude946// Repository Health Score — BLOCK M14 — /:owner/:repo/insights/health
947app.route("/", healthScoreRoutes);
77cf834Claude948// Repository Health Score breakdown page — /:owner/:repo/health
949app.route("/", repoHealthRoutes);
74d8c4dClaude950// Hot Files Heatmap — BLOCK M16 — /:owner/:repo/insights/hotfiles
951app.route("/", hotFilesRoutes);
bcc4020Claude952// AI Technical Debt Map — /:owner/:repo/debt-map (visual debt graph + Claude analysis)
953app.route("/", debtMapRoutes);
1d6db4dClaude954// Bus Factor Analysis — /:owner/:repo/insights/bus-factor
955app.route("/", busFactorRoutes);
b02ce30Claude956// Test Gap Detector — /:owner/:repo/insights/test-gaps
957app.route("/", testGapsRoutes);
f5d020fClaude958// Cross-Repo Dependency Impact Detection — /:owner/:repo/pulls/:number/cross-repo-impact
959app.route("/", crossRepoImpactRoutes);
ebbb527Claude960// Hosted Claude tool-use loops — paste loop, get endpoint, billing meter.
961// See src/routes/claude-deploy.tsx + src/lib/hosted-claude-loop.ts.
962app.route("/", claudeDeployRoutes);
0316dbbClaude963app.route("/", releasesRoutes);
964app.route("/", requiredChecksRoutes);
965app.route("/", rulesetsRoutes);
966app.route("/", searchRoutes);
967app.route("/", semanticSearchRoutes);
77cf834Claude968app.route("/", nlSearchRoutes);
0316dbbClaude969app.route("/", signingKeysRoutes);
970app.route("/", sponsorsRoutes);
971app.route("/", ssoRoutes);
3a845e4Claude972// Enterprise per-org SAML 2.0 + OIDC SSO routes
973app.route("/", samlSsoRoutes);
974// SCIM 2.0 user provisioning endpoints
975app.route("/", scimRoutes);
976// Per-org SSO + SCIM admin settings UI
977app.route("/", orgSsoSettingsRoutes);
46d6165Claude978app.route("/", githubOauthRoutes);
582cdacClaude979app.route("/", googleOauthRoutes);
0316dbbClaude980app.route("/", symbolsRoutes);
981app.route("/", templatesRoutes);
982app.route("/", trafficRoutes);
983app.route("/", wikisRoutes);
984app.route("/", workflowsRoutes);
5ff9cc2Claude985app.route("/", workflowArtifactsRoutes);
986app.route("/", workflowSecretsRoutes);
46d6165Claude987app.route("/", sleepModeRoutes);
52ad8b1Claude988app.route("/", vsGithubRoutes);
0316dbbClaude989
45f3b73Claude990// Voice-to-PR — phone-first dictation → spec or issue
991app.route("/", voiceRoutes);
992
3122762Claude993// Blog / Devlog — public posts, no DB
994app.route("/", blogRoutes);
995
cd4f63bTest User996// Block Q3 — Anonymous playground (`/play`, `/play/claim`). Mounted
997// before the web catch-all so the bare `/play` literal wins over the
998// `/:owner` user-profile route.
999app.route("/", playgroundRoutes);
1000
891efbeClaude1001// Shareable AI hours-saved OG image card + landing page.
1002// /share/hours-saved?user=:username → 1200×630 SVG (og:image)
1003// /share/:username → HTML page with og:image meta + Twitter share
1004// Mounted BEFORE webRoutes so /share/* doesn't fall through to the /:owner profile route.
1005app.route("/", shareRoutes);
1006
4abf6f1ccantynz-alt1007// Machine surfaces must fail in the format their clients parse. An
1008// unmatched /api/* path used to fall through to the HTML 404 page, so a
1009// REST/MCP/registry client asking for JSON got a full HTML document and
1010// blew up on JSON.parse instead of seeing a readable error. Decided by
1011// path root (these mounts are JSON-only by contract) or by an Accept
1012// header that asks for JSON and not HTML.
1013const JSON_ROOTS = [
1014 "/api",
1015 "/mcp",
1016 "/graphql",
1017 "/v2", // OCI registry — the spec mandates a JSON error envelope
1018 "/npm",
1019 "/scim",
1020 "/.well-known",
1021];
1022
1023function wantsJson(c: {
1024 req: { path: string; header: (n: string) => string | undefined };
1025}) {
1026 const path = c.req.path;
1027 // Match the root exactly or as a path segment — "/mcp" and "/mcp/x" are
1028 // machine surfaces, "/mcpanything" is not.
1029 if (JSON_ROOTS.some((r) => path === r || path.startsWith(r + "/"))) return true;
1030 const accept = c.req.header("accept") ?? "";
1031 return accept.includes("application/json") && !accept.includes("text/html");
1032}
1033
1034function jsonNotFound(c: Context) {
1035 return c.json(
1036 { error: "Not found", path: c.req.path, method: c.req.method },
1037 404
1038 );
1039}
1040
1041// Machine-surface 404 fallback — MUST be registered before webRoutes.
1042// webRoutes owns the `/:owner/:repo` catch-all, so an unmatched two-segment
1043// path like `/api/nope` was being read as owner="api", repo="nope" and
1044// answered with the HTML "repository not found" page. REST/MCP/OCI clients
1045// then choked on HTML where they expected a JSON envelope. Terminating the
1046// machine roots here keeps them JSON-only by contract.
1047for (const root of JSON_ROOTS) {
1048 app.all(root, (c) => jsonNotFound(c));
1049 app.all(`${root}/*`, (c) => jsonNotFound(c));
1050}
1051
79136bbClaude1052// Web UI (catch-all, must be last)
1053app.route("/", webRoutes);
1054
c63b860Claude1055// Global 404 — BLOCK O2 routes the shared `NotFoundPage` view so
1056// the markup stays consistent with /500 and the admin /403 page.
79136bbClaude1057app.notFound((c) => {
4abf6f1ccantynz-alt1058 if (wantsJson(c)) {
1059 return c.json(
1060 { error: "Not found", path: c.req.path, method: c.req.method },
1061 404
1062 );
1063 }
36cc17aClaude1064 const user = c.get("user") ?? null;
79136bbClaude1065 return c.html(
c63b860Claude1066 <NotFoundPage user={user} method={c.req.method} path={c.req.path} />,
79136bbClaude1067 404
1068 );
1069});
1070
c63b860Claude1071// Global error handler — BLOCK O2 uses the shared `ServerErrorPage`
1072// view. Trace block only shown outside production.
79136bbClaude1073app.onError((err, c) => {
80bed05Claude1074 reportError(err, {
1075 requestId: c.get("requestId"),
1076 path: c.req.path,
1077 method: c.req.method,
1078 });
c63b860Claude1079 // Prefer the inbound `x-request-id` header (LB-supplied) and fall
1080 // back to the context value set by request-context middleware.
1081 const requestId =
1082 c.req.header("x-request-id") ||
1083 ((c.get("requestId" as never) as string | undefined) ?? undefined);
36cc17aClaude1084 const user = c.get("user") ?? null;
c63b860Claude1085 const trace =
1086 process.env.NODE_ENV !== "production" && err && err.message
1087 ? err.message
1088 : undefined;
4abf6f1ccantynz-alt1089 // Same reasoning as the 404 above: an API/MCP client must get a JSON
1090 // envelope it can parse, not the HTML error page.
1091 if (wantsJson(c)) {
1092 return c.json(
1093 { error: "Internal server error", requestId, ...(trace ? { trace } : {}) },
1094 500
1095 );
1096 }
79136bbClaude1097 return c.html(
c63b860Claude1098 <ServerErrorPage user={user} requestId={requestId} trace={trace} />,
79136bbClaude1099 500
1100 );
1101});
1102
1103export default app;