CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 | /**
* Comprehensive REST API v2 — full CRUD for all resources.
*
* Authentication: Bearer token (API tokens) or session cookie.
* Rate limited: 100 requests/minute per IP.
* All responses are JSON.
*/
import { Hono } from "hono";
import { eq, and, desc, asc, sql, like, or } from "drizzle-orm";
import { db } from "../db";
import {
users,
repositories,
issues,
issueComments,
pullRequests,
prComments,
stars,
labels,
issueLabels,
activityFeed,
webhooks,
repoTopics,
} from "../db/schema";
import {
listBranches,
getDefaultBranch,
getDefaultBranchFresh,
getTree,
getTreeRecursive,
getBlob,
getCommit,
listCommits,
getDiff,
searchCode,
repoExists,
initBareRepo,
resolveRef,
catBlobBytes,
refExists,
objectExists,
updateRef,
createOrUpdateFileOnBranch,
} from "../git/repository";
import { apiAuth, requireApiAuth, requireScope } from "../middleware/api-auth";
import type { ApiAuthEnv } from "../middleware/api-auth";
import { apiRateLimit, searchRateLimit } from "../middleware/rate-limit";
import { postCommitStatusHandler } from "./commit-statuses";
import { apiTokens } from "../db/schema";
import { audit } from "../lib/notify";
import {
computeAiSavingsForUser,
computeLifetimeAiSavingsForUser,
} from "../lib/ai-hours-saved";
const apiv2 = new Hono<ApiAuthEnv>().basePath("/api/v2");
// Apply auth and rate limiting to all v2 routes
apiv2.use("*", apiRateLimit);
apiv2.use("*", apiAuth);
// ─── Helper ─────────────────────────────────────────────────────────────────
async function resolveRepo(ownerName: string, repoName: string) {
const [owner] = await db
.select()
.from(users)
.where(eq(users.username, ownerName))
.limit(1);
if (!owner) return null;
const [repo] = await db
.select()
.from(repositories)
.where(and(eq(repositories.ownerId, owner.id), eq(repositories.name, repoName)))
.limit(1);
if (!repo) return null;
return { owner, repo };
}
// ─── Auth (install-token) ───────────────────────────────────────────────────
//
// POST /api/v2/auth/install-token
//
// Mint a new personal access token from a one-command install script
// (`scripts/install.sh`). Session-cookie auth ONLY — Bearer tokens are
// explicitly rejected so existing PATs cannot escalate into a fan-out of new
// PATs. The plaintext token value is returned exactly once and never persisted.
//
// Audit-logged as `auth.install_token.created`.
function generateInstallToken(): string {
const bytes = crypto.getRandomValues(new Uint8Array(32));
return (
"glc_" +
Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
);
}
async function hashInstallToken(token: string): Promise<string> {
const data = new TextEncoder().encode(token);
const hash = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hash))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
apiv2.post("/auth/install-token", async (c) => {
// Reject Bearer-token callers outright. The whole point of this endpoint
// is preventing token escalation, so we check the raw header rather than
// relying on whatever the middleware decided.
const authHeader = c.req.header("Authorization");
if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
return c.json(
{
error: "Session authentication required",
hint: "This endpoint refuses Bearer tokens — sign in with a session cookie.",
},
401
);
}
const user = c.get("user");
const authMethod = c.get("authMethod");
if (!user || authMethod !== "session") {
return c.json(
{
error: "Session authentication required",
hint: "Sign in via /login first; install-token mints PATs only over the session cookie.",
},
401
);
}
let body: { name?: unknown; scope?: unknown } = {};
try {
body = await c.req.json();
} catch {
// Empty / unparseable body is allowed — we fall back to defaults.
body = {};
}
const shortStamp = Math.floor(Date.now() / 1000)
.toString(36)
.slice(-6);
const name =
typeof body.name === "string" && body.name.trim().length > 0
? body.name.trim().slice(0, 80)
: `gluecron-install-${shortStamp}`;
const requested = typeof body.scope === "string" ? body.scope : "admin";
const scope = requested === "repo" ? "repo" : "admin";
// Mirror existing PAT semantics: a comma-separated list. `admin` implies
// everything; `repo` keeps it narrow.
const scopes = scope === "admin" ? "admin,repo,user" : "repo";
const token = generateInstallToken();
const tokenHash = await hashInstallToken(token);
const tokenPrefix = token.slice(0, 12);
const [row] = await db
.insert(apiTokens)
.values({
userId: user.id,
name,
tokenHash,
tokenPrefix,
scopes,
})
.returning();
await audit({
userId: user.id,
action: "auth.install_token.created",
targetType: "api_token",
targetId: row?.id,
ip: c.req.header("x-forwarded-for") || c.req.header("x-real-ip") || undefined,
userAgent: c.req.header("user-agent") || undefined,
metadata: { name, scope, prefix: tokenPrefix },
});
return c.json(
{
token,
id: row?.id,
name,
scope,
scopes,
expiresAt: row?.expiresAt ?? null,
},
201
);
});
// ─── Users ──────────────────────────────────────────────────────────────────
apiv2.get("/user", requireApiAuth, (c) => {
const user = c.get("user")!;
return c.json({
id: user.id,
username: user.username,
email: user.email,
displayName: user.displayName,
bio: user.bio,
avatarUrl: user.avatarUrl,
createdAt: user.createdAt,
});
});
apiv2.get("/users/:username", async (c) => {
const { username } = c.req.param();
const [user] = await db
.select({
id: users.id,
username: users.username,
displayName: users.displayName,
bio: users.bio,
avatarUrl: users.avatarUrl,
createdAt: users.createdAt,
})
.from(users)
.where(eq(users.username, username))
.limit(1);
if (!user) return c.json({ error: "User not found" }, 404);
return c.json(user);
});
/**
* Block L9 — AI hours-saved counter, exposed for the dashboard widget,
* VS Code extension, and CLI. Returns the same numbers the web UI shows.
* No special scope — any authenticated token can read its own counter.
*/
apiv2.get("/me/ai-savings", requireApiAuth, async (c) => {
const user = c.get("user")!;
const [window, lifetime] = await Promise.all([
computeAiSavingsForUser(user.id, { windowHours: 168 }),
computeLifetimeAiSavingsForUser(user.id),
]);
return c.json({
window: {
hours: window.windowHours,
hoursSaved: window.hoursSaved,
breakdown: window.breakdown,
},
lifetime: {
hoursSaved: lifetime.hoursSaved,
breakdown: lifetime.breakdown,
sinceCreatedAt: lifetime.sinceCreatedAt.toISOString(),
},
});
});
apiv2.patch("/user", requireApiAuth, requireScope("user"), async (c) => {
const user = c.get("user")!;
const body = await c.req.json<{
displayName?: string;
bio?: string;
avatarUrl?: string;
}>();
const updates: Record<string, any> = { updatedAt: new Date() };
if (body.displayName !== undefined) updates.displayName = body.displayName;
if (body.bio !== undefined) updates.bio = body.bio;
if (body.avatarUrl !== undefined) updates.avatarUrl = body.avatarUrl;
await db.update(users).set(updates).where(eq(users.id, user.id));
return c.json({ ok: true });
});
// ─── Repositories ───────────────────────────────────────────────────────────
apiv2.get("/users/:username/repos", async (c) => {
const { username } = c.req.param();
const sort = c.req.query("sort") || "updated";
const [owner] = await db.select().from(users).where(eq(users.username, username)).limit(1);
if (!owner) return c.json({ error: "User not found" }, 404);
const currentUser = c.get("user");
const orderBy = sort === "stars" ? desc(repositories.starCount) :
sort === "name" ? asc(repositories.name) :
desc(repositories.updatedAt);
let repoList = await db
.select()
.from(repositories)
.where(eq(repositories.ownerId, owner.id))
.orderBy(orderBy);
// Only show private repos to owner
if (!currentUser || currentUser.id !== owner.id) {
repoList = repoList.filter((r: any) => !r.isPrivate);
}
return c.json(repoList);
});
apiv2.post("/repos", requireApiAuth, requireScope("repo"), async (c) => {
const user = c.get("user")!;
const body = await c.req.json<{
name: string;
description?: string;
isPrivate?: boolean;
}>();
if (!body.name || !/^[a-zA-Z0-9._-]+$/.test(body.name)) {
return c.json({ error: "Invalid repository name" }, 400);
}
// P4 — plan-quota gate. 402 Payment Required is the canonical HTTP
// signal that the client should branch on (e.g. show an upgrade CTA).
const { checkRepoCreateAllowed } = await import("../lib/repo-create-gate");
const gate = await checkRepoCreateAllowed(user.id);
if (!gate.ok) {
return c.json({ error: gate.reason, upgrade_url: gate.upgradeUrl }, 402);
}
if (await repoExists(user.username, body.name)) {
return c.json({ error: "Repository already exists" }, 409);
}
const diskPath = await initBareRepo(user.username, body.name);
const result = await db
.insert(repositories)
.values({
name: body.name,
ownerId: user.id,
description: body.description || null,
isPrivate: body.isPrivate || false,
diskPath,
})
.returning();
return c.json(result[0], 201);
});
apiv2.get("/repos/:owner/:repo", async (c) => {
const { owner, repo } = c.req.param();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const currentUser = c.get("user");
if ((resolved.repo as any).isPrivate && (!currentUser || currentUser.id !== resolved.owner.id)) {
return c.json({ error: "Not found" }, 404);
}
// Cache-free fresh read of HEAD's ref — needed by GateTest.
const defaultBranch = await getDefaultBranchFresh(owner, repo);
return c.json({
...(resolved.repo as any),
defaultBranch,
owner: {
id: (resolved.owner as any).id,
login: (resolved.owner as any).username,
},
});
});
apiv2.patch("/repos/:owner/:repo", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const user = c.get("user")!;
if (user.id !== resolved.owner.id) {
return c.json({ error: "Permission denied" }, 403);
}
const body = await c.req.json<{
description?: string;
isPrivate?: boolean;
defaultBranch?: string;
}>();
const updates: Record<string, any> = { updatedAt: new Date() };
if (body.description !== undefined) updates.description = body.description;
if (body.isPrivate !== undefined) updates.isPrivate = body.isPrivate;
if (body.defaultBranch !== undefined) updates.defaultBranch = body.defaultBranch;
await db.update(repositories).set(updates).where(eq(repositories.id, (resolved.repo as any).id));
return c.json({ ok: true });
});
apiv2.delete("/repos/:owner/:repo", requireApiAuth, requireScope("admin"), async (c) => {
const { owner, repo } = c.req.param();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const user = c.get("user")!;
if (user.id !== resolved.owner.id) {
return c.json({ error: "Permission denied" }, 403);
}
await db.delete(repositories).where(eq(repositories.id, (resolved.repo as any).id));
return c.json({ ok: true });
});
// ─── Branches ───────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/branches", async (c) => {
const { owner, repo } = c.req.param();
if (!(await repoExists(owner, repo))) {
return c.json({ error: "Not found" }, 404);
}
const branches = await listBranches(owner, repo);
const defaultBranch = await getDefaultBranch(owner, repo);
return c.json(
branches.map((name) => ({
name,
isDefault: name === defaultBranch,
}))
);
});
// ─── Commits ────────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/commits", async (c) => {
const { owner, repo } = c.req.param();
const ref = c.req.query("ref") || c.req.query("sha") || "HEAD";
const limit = Math.min(parseInt(c.req.query("limit") || "30"), 100);
const offset = parseInt(c.req.query("offset") || "0");
if (!(await repoExists(owner, repo))) {
return c.json({ error: "Not found" }, 404);
}
const commits = await listCommits(owner, repo, ref, limit, offset);
return c.json(commits);
});
apiv2.get("/repos/:owner/:repo/commits/:sha", async (c) => {
const { owner, repo, sha } = c.req.param();
if (!(await repoExists(owner, repo))) {
return c.json({ error: "Not found" }, 404);
}
const commit = await getCommit(owner, repo, sha);
if (!commit) return c.json({ error: "Commit not found" }, 404);
const { files } = await getDiff(owner, repo, sha);
return c.json({ ...commit, files });
});
// ─── Tree & Files ───────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/tree/:ref", async (c) => {
const { owner, repo } = c.req.param();
const ref = c.req.param("ref");
const path = c.req.query("path") || "";
const recursive = c.req.query("recursive");
if (!(await repoExists(owner, repo))) {
return c.json({ error: "Not found" }, 404);
}
if (recursive === "1" || recursive === "true") {
const result = await getTreeRecursive(owner, repo, ref, 50_000);
if (!result) return c.json({ error: "Ref not found" }, 404);
return c.json(result);
}
const tree = await getTree(owner, repo, ref, path);
return c.json(tree);
});
const CONTENTS_MAX_BYTES = 10 * 1024 * 1024;
apiv2.get("/repos/:owner/:repo/contents/:path{.+$}", async (c) => {
const { owner, repo } = c.req.param();
const filePath = c.req.param("path");
const ref = c.req.query("ref") || "HEAD";
const encoding = c.req.query("encoding") || "utf8";
if (!(await repoExists(owner, repo))) {
return c.json({ error: "Not found" }, 404);
}
if (encoding === "base64") {
const got = await catBlobBytes(owner, repo, ref, filePath);
if (!got) return c.json({ error: "File not found" }, 404);
if (got.size > CONTENTS_MAX_BYTES) {
return c.json(
{ error: `File too large (${got.size} bytes, max ${CONTENTS_MAX_BYTES})` },
413
);
}
const content = Buffer.from(got.bytes).toString("base64");
return c.json({
path: filePath,
size: got.size,
sha: got.sha,
encoding: "base64",
content,
});
}
const blob = await getBlob(owner, repo, ref, filePath);
if (!blob) return c.json({ error: "File not found" }, 404);
if (blob.size > CONTENTS_MAX_BYTES) {
return c.json(
{ error: `File too large (${blob.size} bytes, max ${CONTENTS_MAX_BYTES})` },
413
);
}
return c.json({
path: filePath,
size: blob.size,
isBinary: blob.isBinary,
content: blob.isBinary ? null : blob.content,
encoding: blob.isBinary ? null : "utf8",
});
});
// ─── Issues ─────────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/issues", async (c) => {
const { owner, repo } = c.req.param();
const state = c.req.query("state") || "open";
const limit = Math.min(parseInt(c.req.query("limit") || "30"), 100);
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const issueList = await db
.select({
issue: issues,
author: { username: users.username, id: users.id },
})
.from(issues)
.innerJoin(users, eq(issues.authorId, users.id))
.where(and(eq(issues.repositoryId, (resolved.repo as any).id), eq(issues.state, state)))
.orderBy(desc(issues.createdAt))
.limit(limit);
return c.json(issueList.map(({ issue, author }) => ({ ...issue, author })));
});
apiv2.post("/repos/:owner/:repo/issues", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const body = await c.req.json<{ title: string; body?: string }>();
if (!body.title?.trim()) {
return c.json({ error: "Title is required" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const result = await db
.insert(issues)
.values({
repositoryId: (resolved.repo as any).id,
authorId: user.id,
title: body.title.trim(),
body: body.body?.trim() || null,
})
.returning();
return c.json(result[0], 201);
});
apiv2.get("/repos/:owner/:repo/issues/:number", async (c) => {
const { owner, repo } = c.req.param();
const num = parseInt(c.req.param("number"), 10);
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const [issue] = await db
.select()
.from(issues)
.where(and(eq(issues.repositoryId, (resolved.repo as any).id), eq(issues.number, num)))
.limit(1);
if (!issue) return c.json({ error: "Issue not found" }, 404);
const comments = await db
.select({
comment: issueComments,
author: { username: users.username },
})
.from(issueComments)
.innerJoin(users, eq(issueComments.authorId, users.id))
.where(eq(issueComments.issueId, issue.id))
.orderBy(asc(issueComments.createdAt));
return c.json({
...issue,
comments: comments.map(({ comment, author }) => ({ ...comment, author })),
});
});
apiv2.patch("/repos/:owner/:repo/issues/:number", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const num = parseInt(c.req.param("number"), 10);
const body = await c.req.json<{ title?: string; body?: string; state?: "open" | "closed" }>();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const updates: Record<string, any> = { updatedAt: new Date() };
if (body.title !== undefined) updates.title = body.title;
if (body.body !== undefined) updates.body = body.body;
if (body.state === "closed") {
updates.state = "closed";
updates.closedAt = new Date();
} else if (body.state === "open") {
updates.state = "open";
updates.closedAt = null;
}
await db
.update(issues)
.set(updates)
.where(and(eq(issues.repositoryId, (resolved.repo as any).id), eq(issues.number, num)));
return c.json({ ok: true });
});
apiv2.post("/repos/:owner/:repo/issues/:number/comments", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const num = parseInt(c.req.param("number"), 10);
const user = c.get("user")!;
const body = await c.req.json<{ body: string }>();
if (!body.body?.trim()) {
return c.json({ error: "Comment body is required" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const [issue] = await db
.select()
.from(issues)
.where(and(eq(issues.repositoryId, (resolved.repo as any).id), eq(issues.number, num)))
.limit(1);
if (!issue) return c.json({ error: "Issue not found" }, 404);
const result = await db
.insert(issueComments)
.values({
issueId: issue.id,
authorId: user.id,
body: body.body.trim(),
})
.returning();
return c.json(result[0], 201);
});
// ─── Pull Requests ──────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/pulls", async (c) => {
const { owner, repo } = c.req.param();
const state = c.req.query("state") || "open";
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const prList = await db
.select({
pr: pullRequests,
author: { username: users.username },
})
.from(pullRequests)
.innerJoin(users, eq(pullRequests.authorId, users.id))
.where(and(eq(pullRequests.repositoryId, (resolved.repo as any).id), eq(pullRequests.state, state)))
.orderBy(desc(pullRequests.createdAt));
return c.json(prList.map(({ pr, author }) => ({ ...pr, author })));
});
apiv2.post("/repos/:owner/:repo/pulls", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const body = await c.req.json<{
title: string;
body?: string;
baseBranch: string;
headBranch: string;
}>();
if (!body.title?.trim() || !body.baseBranch || !body.headBranch) {
return c.json({ error: "title, baseBranch, and headBranch are required" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const result = await db
.insert(pullRequests)
.values({
repositoryId: (resolved.repo as any).id,
authorId: user.id,
title: body.title.trim(),
body: body.body?.trim() || null,
baseBranch: body.baseBranch,
headBranch: body.headBranch,
})
.returning();
return c.json(result[0], 201);
});
apiv2.get("/repos/:owner/:repo/pulls/:number", async (c) => {
const { owner, repo } = c.req.param();
const num = parseInt(c.req.param("number"), 10);
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const [pr] = await db
.select()
.from(pullRequests)
.where(and(eq(pullRequests.repositoryId, (resolved.repo as any).id), eq(pullRequests.number, num)))
.limit(1);
if (!pr) return c.json({ error: "PR not found" }, 404);
const comments = await db
.select({
comment: prComments,
author: { username: users.username },
})
.from(prComments)
.innerJoin(users, eq(prComments.authorId, users.id))
.where(eq(prComments.pullRequestId, pr.id))
.orderBy(asc(prComments.createdAt));
return c.json({
...pr,
comments: comments.map(({ comment, author }) => ({ ...comment, author })),
});
});
// ─── PR Comments (GateTest integration) ────────────────────────────────────
apiv2.post(
"/repos/:owner/:repo/pulls/:number/comments",
requireApiAuth,
requireScope("repo"),
async (c) => {
const { owner, repo } = c.req.param();
const num = parseInt(c.req.param("number"), 10);
const user = c.get("user")!;
let body: { body?: string } = {};
try {
body = await c.req.json();
} catch {
body = {};
}
if (!body.body?.trim()) {
return c.json({ error: "Comment body is required" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== (resolved.owner as any).id) {
return c.json({ error: "Forbidden" }, 403);
}
const [pr] = await db
.select()
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, (resolved.repo as any).id),
eq(pullRequests.number, num)
)
)
.limit(1);
if (!pr) return c.json({ error: "PR not found" }, 404);
const [comment] = await db
.insert(prComments)
.values({
pullRequestId: pr.id,
authorId: user.id,
body: body.body.trim(),
})
.returning();
return c.json({ ok: true, comment }, 201);
}
);
// ─── Git refs — create branch / tag from sha ────────────────────────────────
apiv2.post(
"/repos/:owner/:repo/git/refs",
requireApiAuth,
requireScope("repo"),
async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
let body: { ref?: string; sha?: string } = {};
try {
body = await c.req.json();
} catch {
body = {};
}
const ref = body.ref?.trim();
const sha = body.sha?.trim();
if (!ref || !/^refs\/(heads|tags)\/.+/.test(ref)) {
return c.json({ error: "ref must be of the form refs/heads/... or refs/tags/..." }, 400);
}
if (!sha || !/^[0-9a-f]{40}$/.test(sha)) {
return c.json({ error: "sha must be a 40-char lowercase hex string" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== (resolved.owner as any).id) {
return c.json({ error: "Forbidden" }, 403);
}
// Verify sha reachable.
if (!(await objectExists(owner, repo, sha))) {
return c.json({ error: "sha not found in repository" }, 400);
}
// Conflict check: if ref already exists, the existing sha must match.
if (await refExists(owner, repo, ref)) {
const existing = await resolveRef(owner, repo, ref);
if (existing !== sha) {
return c.json({ error: "ref already exists", existing }, 409);
}
}
const ok = await updateRef(owner, repo, ref, sha);
if (!ok) return c.json({ error: "Failed to create ref" }, 500);
return c.json({ ok: true, ref, sha }, 201);
}
);
// ─── Contents PUT — create/update a file via git plumbing ────────────────────
apiv2.put(
"/repos/:owner/:repo/contents/:path{.+$}",
requireApiAuth,
requireScope("repo"),
async (c) => {
const { owner, repo } = c.req.param();
const filePath = c.req.param("path");
const user = c.get("user")!;
let body: {
message?: string;
content?: string;
branch?: string;
sha?: string | null;
} = {};
try {
body = await c.req.json();
} catch {
body = {};
}
const message = body.message?.trim();
const branch = body.branch?.trim();
const base64 = body.content;
if (!message) return c.json({ error: "message is required" }, 400);
if (!branch) return c.json({ error: "branch is required" }, 400);
if (typeof base64 !== "string") return c.json({ error: "content (base64) is required" }, 400);
let bytes: Uint8Array;
try {
bytes = new Uint8Array(Buffer.from(base64, "base64"));
} catch {
return c.json({ error: "content is not valid base64" }, 400);
}
if (bytes.length > CONTENTS_MAX_BYTES) {
return c.json({ error: "File too large" }, 413);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== (resolved.owner as any).id) {
return c.json({ error: "Forbidden" }, 403);
}
const result = await createOrUpdateFileOnBranch({
owner,
name: repo,
branch,
filePath,
bytes,
message,
authorName: (user as any).displayName || user.username,
authorEmail: user.email,
expectBlobSha: body.sha ?? null,
});
if ("error" in result) {
if (result.error === "sha-mismatch") {
return c.json({ error: "sha does not match current blob at path" }, 409);
}
return c.json({ error: "Failed to write file" }, 500);
}
return c.json(
{
ok: true,
commit: { sha: result.commitSha, message },
content: { path: filePath, sha: result.blobSha },
},
201
);
}
);
// ─── v2 alias for commit-status POST ─────────────────────────────────────────
// Reuses the handler from src/routes/commit-statuses.ts (v1 mount).
apiv2.post(
"/repos/:owner/:repo/statuses/:sha",
requireApiAuth,
requireScope("repo"),
postCommitStatusHandler
);
// ─── Stars ──────────────────────────────────────────────────────────────────
apiv2.put("/repos/:owner/:repo/star", requireApiAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const repoId = (resolved.repo as any).id;
const [existing] = await db
.select()
.from(stars)
.where(and(eq(stars.userId, user.id), eq(stars.repositoryId, repoId)))
.limit(1);
if (!existing) {
await db.insert(stars).values({ userId: user.id, repositoryId: repoId });
await db
.update(repositories)
.set({ starCount: sql`${repositories.starCount} + 1` })
.where(eq(repositories.id, repoId));
}
return c.json({ starred: true });
});
apiv2.delete("/repos/:owner/:repo/star", requireApiAuth, async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const repoId = (resolved.repo as any).id;
const [existing] = await db
.select()
.from(stars)
.where(and(eq(stars.userId, user.id), eq(stars.repositoryId, repoId)))
.limit(1);
if (existing) {
await db.delete(stars).where(eq(stars.id, existing.id));
await db
.update(repositories)
.set({ starCount: sql`GREATEST(${repositories.starCount} - 1, 0)` })
.where(eq(repositories.id, repoId));
}
return c.json({ starred: false });
});
// ─── Labels ─────────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/labels", async (c) => {
const { owner, repo } = c.req.param();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const labelList = await db
.select()
.from(labels)
.where(eq(labels.repositoryId, (resolved.repo as any).id))
.orderBy(asc(labels.name));
return c.json(labelList);
});
apiv2.post("/repos/:owner/:repo/labels", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const body = await c.req.json<{ name: string; color?: string; description?: string }>();
if (!body.name?.trim()) {
return c.json({ error: "Label name is required" }, 400);
}
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const result = await db
.insert(labels)
.values({
repositoryId: (resolved.repo as any).id,
name: body.name.trim(),
color: body.color || "#8b949e",
description: body.description || null,
})
.returning();
return c.json(result[0], 201);
});
// ─── Search ─────────────────────────────────────────────────────────────────
apiv2.get("/search/repos", searchRateLimit, async (c) => {
const q = c.req.query("q") || "";
const sort = c.req.query("sort") || "stars";
const limit = Math.min(parseInt(c.req.query("limit") || "30"), 100);
if (!q.trim()) {
return c.json({ error: "Query parameter 'q' is required" }, 400);
}
const orderBy = sort === "updated" ? desc(repositories.updatedAt) :
sort === "name" ? asc(repositories.name) :
desc(repositories.starCount);
const results = await db
.select({
repo: repositories,
owner: { username: users.username },
})
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(
and(
eq(repositories.isPrivate, false),
or(
like(repositories.name, `%${q}%`),
like(repositories.description, `%${q}%`)
)
)
)
.orderBy(orderBy)
.limit(limit);
return c.json(results.map(({ repo, owner }) => ({ ...repo, owner })));
});
apiv2.get("/repos/:owner/:repo/search/code", searchRateLimit, async (c) => {
const { owner, repo } = c.req.param();
const q = c.req.query("q") || "";
if (!q.trim()) return c.json({ error: "Query parameter 'q' is required" }, 400);
if (!(await repoExists(owner, repo))) return c.json({ error: "Not found" }, 404);
const defaultBranch = (await getDefaultBranch(owner, repo)) || "main";
const results = await searchCode(owner, repo, defaultBranch, q.trim());
return c.json(results);
});
// ─── Activity Feed ──────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/activity", async (c) => {
const { owner, repo } = c.req.param();
const limit = Math.min(parseInt(c.req.query("limit") || "30"), 100);
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const activity = await db
.select()
.from(activityFeed)
.where(eq(activityFeed.repositoryId, (resolved.repo as any).id))
.orderBy(desc(activityFeed.createdAt))
.limit(limit);
return c.json(activity);
});
// ─── Topics ─────────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/topics", async (c) => {
const { owner, repo } = c.req.param();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
const topicsList = await db
.select()
.from(repoTopics)
.where(eq(repoTopics.repositoryId, (resolved.repo as any).id));
return c.json(topicsList.map((t: any) => t.topic));
});
apiv2.put("/repos/:owner/:repo/topics", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const body = await c.req.json<{ topics: string[] }>();
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== resolved.owner.id) return c.json({ error: "Permission denied" }, 403);
const repoId = (resolved.repo as any).id;
// Clear existing topics and insert new ones
await db.delete(repoTopics).where(eq(repoTopics.repositoryId, repoId));
if (body.topics && body.topics.length > 0) {
await db.insert(repoTopics).values(
body.topics.slice(0, 20).map((topic: string) => ({
repositoryId: repoId,
topic: topic.toLowerCase().trim(),
}))
);
}
return c.json({ ok: true });
});
// ─── Webhooks ───────────────────────────────────────────────────────────────
apiv2.get("/repos/:owner/:repo/webhooks", requireApiAuth, requireScope("repo"), async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== resolved.owner.id) return c.json({ error: "Permission denied" }, 403);
const hookList = await db
.select()
.from(webhooks)
.where(eq(webhooks.repositoryId, (resolved.repo as any).id));
return c.json(hookList);
});
apiv2.post("/repos/:owner/:repo/webhooks", requireApiAuth, requireScope("admin"), async (c) => {
const { owner, repo } = c.req.param();
const user = c.get("user")!;
const body = await c.req.json<{
url: string;
secret?: string;
events?: string;
}>();
if (!body.url) return c.json({ error: "URL is required" }, 400);
const resolved = await resolveRepo(owner, repo);
if (!resolved) return c.json({ error: "Not found" }, 404);
if (user.id !== resolved.owner.id) return c.json({ error: "Permission denied" }, 403);
const result = await db
.insert(webhooks)
.values({
repositoryId: (resolved.repo as any).id,
url: body.url,
secret: body.secret || null,
events: body.events || "push",
})
.returning();
return c.json(result[0], 201);
});
// ─── API Info ───────────────────────────────────────────────────────────────
apiv2.get("/", (c) => {
return c.json({
name: "gluecron API",
version: "2.0",
documentation: "/api/docs",
endpoints: {
auth: {
"POST /api/v2/auth/install-token":
"Mint a PAT for one-command install (session-cookie auth only)",
},
users: {
"GET /api/v2/user": "Get authenticated user",
"GET /api/v2/users/:username": "Get user by username",
"PATCH /api/v2/user": "Update authenticated user profile",
"GET /api/v2/me/ai-savings":
"AI hours-saved counter (window + lifetime, Block L9)",
},
repositories: {
"GET /api/v2/users/:username/repos": "List user repositories",
"POST /api/v2/repos": "Create repository",
"GET /api/v2/repos/:owner/:repo": "Get repository",
"PATCH /api/v2/repos/:owner/:repo": "Update repository",
"DELETE /api/v2/repos/:owner/:repo": "Delete repository",
},
branches: {
"GET /api/v2/repos/:owner/:repo/branches": "List branches",
},
commits: {
"GET /api/v2/repos/:owner/:repo/commits": "List commits",
"GET /api/v2/repos/:owner/:repo/commits/:sha": "Get commit with diff",
},
files: {
"GET /api/v2/repos/:owner/:repo/tree/:ref": "Get file tree (supports ?recursive=1)",
"GET /api/v2/repos/:owner/:repo/contents/:path": "Get file contents (supports ?encoding=base64)",
"PUT /api/v2/repos/:owner/:repo/contents/:path": "Create or update a file on a branch",
},
git: {
"POST /api/v2/repos/:owner/:repo/git/refs": "Create a branch or tag pointing at a sha",
},
statuses: {
"POST /api/v2/repos/:owner/:repo/statuses/:sha": "Post commit status (v2 alias)",
},
issues: {
"GET /api/v2/repos/:owner/:repo/issues": "List issues",
"POST /api/v2/repos/:owner/:repo/issues": "Create issue",
"GET /api/v2/repos/:owner/:repo/issues/:number": "Get issue with comments",
"PATCH /api/v2/repos/:owner/:repo/issues/:number": "Update issue",
"POST /api/v2/repos/:owner/:repo/issues/:number/comments": "Add comment",
},
pullRequests: {
"GET /api/v2/repos/:owner/:repo/pulls": "List pull requests",
"POST /api/v2/repos/:owner/:repo/pulls": "Create pull request",
"GET /api/v2/repos/:owner/:repo/pulls/:number": "Get PR with comments",
"POST /api/v2/repos/:owner/:repo/pulls/:number/comments": "Add PR comment",
},
stars: {
"PUT /api/v2/repos/:owner/:repo/star": "Star repository",
"DELETE /api/v2/repos/:owner/:repo/star": "Unstar repository",
},
labels: {
"GET /api/v2/repos/:owner/:repo/labels": "List labels",
"POST /api/v2/repos/:owner/:repo/labels": "Create label",
},
search: {
"GET /api/v2/search/repos": "Search repositories",
"GET /api/v2/repos/:owner/:repo/search/code": "Search code in repo",
},
topics: {
"GET /api/v2/repos/:owner/:repo/topics": "Get topics",
"PUT /api/v2/repos/:owner/:repo/topics": "Set topics",
},
webhooks: {
"GET /api/v2/repos/:owner/:repo/webhooks": "List webhooks",
"POST /api/v2/repos/:owner/:repo/webhooks": "Create webhook",
},
activity: {
"GET /api/v2/repos/:owner/:repo/activity": "Get activity feed",
},
},
authentication: {
method: "Bearer token",
header: "Authorization: Bearer <your-token>",
createApiKey: "Visit /settings/tokens to create a personal access key",
},
rateLimit: {
api: "100 requests/minute",
search: "30 requests/minute",
auth: "10 requests/minute",
},
});
});
export default apiv2;
|