Swadhin Biswas Feat/federation (#82) · 8/19/2026
c0437ed
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
import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { logger } from "@/lib/logger";
import { triggerRepoWorkflows } from "@/lib/workflows";
import type { APIRoute } from "astro";
import { eq } from "drizzle-orm";
export const POST: APIRoute = async ({ request, url }) => {
// Verify internal hook secret for security
const hookSecret = process.env.INTERNAL_HOOK_SECRET;
if (!hookSecret) {
return new Response("Server misconfigured", { status: 500 });
}
const providedSecret = request.headers.get("X-Hook-Secret");
if (providedSecret !== hookSecret) {
return new Response("Unauthorized", { status: 401 });
}
const repoPath = url.searchParams.get("repo");
if (!repoPath) {
return new Response("Missing repo path", { status: 400 });
}
let body: { oldrev: string; newrev: string; refname: string };
try {
body = await request.json();
} catch (e) {
return new Response("Invalid JSON", { status: 400 });
}
logger.info({ repoPath, ref: body.refname, oldrev: body.oldrev, newrev: body.newrev }, "Post-receive hook");
const db = getDatabase() as NodePgDatabase<typeof schema>;
// Extract owner and repo name from path for flexible lookup
// Path formats:
// - local: /path/to/data/repos/owner/repo.git
// - cloud diskPath: repos/owner/repo.git
// - temp path: /path/to/.tmp/repos/owner/repo.git
const pathParts = repoPath.split('/');
const repoGit = pathParts.pop() || '';
const repoName = repoGit.replace('.git', '');
const owner = pathParts.pop() || '';
// Try finding by exact diskPath first
let repo = await db.query.repositories.findFirst({
where: eq(schema.repositories.diskPath, repoPath),
with: { owner: true }
});
// If not found, try cloud storage path format
if (!repo && owner && repoName) {
const cloudPath = `repos/${owner}/${repoName}.git`;
repo = await db.query.repositories.findFirst({
where: eq(schema.repositories.diskPath, cloudPath),
with: { owner: true }
});
}
if (!repo) {
logger.error({ repoPath }, "Repo not found in DB");
return new Response("Repo not found", { status: 404 });
}
// Update repo updatedAt
await db
.update(schema.repositories)
.set({ updatedAt: new Date() })
.where(eq(schema.repositories.id, repo.id));
// Trigger CI/CD Workflows (fire and forget)
// refname arrives as "refs/heads/main\0capabilities..." — strip the caps
const cleanRef = body.refname.split("\0")[0];
if (repo.hasActions && cleanRef.startsWith("refs/heads/")) {
try {
triggerRepoWorkflows(
repo.id,
body.newrev,
cleanRef,
repo.ownerId
);
logger.info({ repoId: repo.id }, "CI/CD workflows triggered");
} catch (err) {
logger.error({ err }, "Failed to trigger workflows");
}
}
// Resolve repo path for git operations
// ... existing code ...
// Fetch commits
let commits: any[] = [];
try {
const { resolveRepoPath } = await import("@/lib/git-storage");
const { getGit } = await import("@/lib/git");
const localRepoPath = await resolveRepoPath(repo.diskPath);
const git = getGit(localRepoPath);
// If new branch (oldrev is 000...), show from newrev
const range = body.oldrev === "0000000000000000000000000000000000000000"
? body.newrev
: `${body.oldrev}..${body.newrev}`;
const log = await git.raw([
"log",
"--pretty=format:%H|%s|%an|%ae",
"-n", "20", // Limit to 20 commits
range
]);
if (log) {
commits = log.split("\n").filter(Boolean).map(line => {
const [sha, message, authorName, authorEmail] = line.split("|");
return {
id: sha,
message,
url: `${process.env.SITE_URL || 'http://localhost:3000'}/${owner}/${repoName}/commit/${sha}`,
author: {
name: authorName,
email: authorEmail
}
};
});
}
} catch (err) {
logger.error({ err }, "Failed to parse commits");
}
// Log push activity so real git commits count as contributions
try {
const { logActivity } = await import("@/lib/activity");
const pusher = (body as any).pusher;
let pusherUser = null;
if (pusher && pusher !== "system" && pusher !== "internal-bot" && pusher !== "git-user") {
pusherUser = await db.query.users.findFirst({
where: eq(schema.users.id, pusher),
columns: { id: true },
});
if (!pusherUser) {
pusherUser = await db.query.users.findFirst({
where: eq(schema.users.username, pusher),
columns: { id: true },
});
}
}
if (pusherUser?.id) {
await logActivity(
pusherUser.id,
"push",
"pushed",
"commit",
body.newrev,
repo.id,
{
repoName: repo.name,
refName: cleanRef,
commitCount: commits.length,
messages: commits.slice(0, 5).map((c) => c.message),
},
"branch",
cleanRef.replace("refs/heads/", ""),
);
logger.info({ userId: pusherUser.id, repoId: repo.id, commits: commits.length }, "Push activity logged");
} else {
logger.warn({ pusher }, "Could not resolve pusher user for activity logging");
}
} catch (err) {
logger.error({ err }, "Failed to log push activity");
}
// Trigger Webhooks
try {
const { triggerWebhooks } = await import("@/lib/webhooks");
// Get pusher from body (passed by hook script) or default
const pusherName = (body as any).pusher || "git-user";
await triggerWebhooks(repo.id, "push", {
ref: body.refname,
before: body.oldrev,
after: body.newrev,
repository: {
id: repo.id,
name: repo.name,
full_name: `${repo.owner.username}/${repo.name}`,
owner: {
name: repo.owner.username,
email: repo.owner.email,
},
html_url: `${process.env.SITE_URL || 'http://localhost:3000'}/${repo.owner.username}/${repo.name}`,
},
pusher: {
name: pusherName,
},
commits: commits,
});
logger.info({ repoId: repo.id }, "Webhooks triggered");
} catch (err) {
logger.error({ err }, "Failed to trigger webhooks");
}
return new Response("OK", { status: 200 });
};