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
|
import { and, eq } from "drizzle-orm";
import { config } from "../lib/config";
import { db } from "../db";
import {
activityFeed,
deployments,
repoSettings,
repositories,
users,
} from "../db/schema";
import {
runGateTestScan,
runSecretAndSecurityScan,
} from "../lib/gate";
import { getOrCreateSettings } from "../lib/repo-bootstrap";
import { getBlob, getDefaultBranch } from "../git/repository";
import { parseCodeowners, syncCodeowners } from "../lib/codeowners";
import { notify } from "../lib/notify";
interface PushRef {
oldSha: string;
newSha: string;
refName: string;
}
export async function onPostReceive(
owner: string,
repo: string,
refs: PushRef[]
): Promise<void> {
const [ownerRow] = await db
.select()
.from(users)
.where(eq(users.username, owner))
.limit(1);
const repoRow = ownerRow
? (
await db
.select()
.from(repositories)
.where(
and(
eq(repositories.ownerId, ownerRow.id),
eq(repositories.name, repo)
)
)
.limit(1)
)[0]
: null;
const defaultBranch =
(await getDefaultBranch(owner, repo)) || repoRow?.defaultBranch || "main";
if (repoRow) {
try {
await db
.update(repositories)
.set({ pushedAt: new Date(), updatedAt: new Date() })
.where(eq(repositories.id, repoRow.id));
for (const ref of refs) {
if (!ref.newSha.startsWith("0000")) {
await db.insert(activityFeed).values({
repositoryId: repoRow.id,
userId: ownerRow?.id || null,
action: "push",
targetType: "commit",
targetId: ref.newSha,
metadata: JSON.stringify({ ref: ref.refName }),
});
}
}
} catch (err) {
console.error("[post-receive] activity/pushedAt:", err);
}
}
const mainRef = refs.find(
(r) =>
r.refName === `refs/heads/${defaultBranch}` &&
!r.newSha.startsWith("0000")
);
if (mainRef && repoRow) {
try {
const paths = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"];
for (const p of paths) {
const blob = await getBlob(owner, repo, defaultBranch, p);
if (blob && !blob.isBinary) {
const rules = parseCodeowners(blob.content);
await syncCodeowners(repoRow.id, rules);
break;
}
}
} catch (err) {
console.error("[post-receive] codeowners sync:", err);
}
}
const settings = repoRow ? await getOrCreateSettings(repoRow.id) : null;
const promises: Promise<void>[] = [];
for (const ref of refs) {
if (ref.newSha.startsWith("0000")) continue;
if (settings?.gateTestEnabled !== false) {
promises.push(
runGateTestScan(owner, repo, ref.refName, ref.newSha)
.then((result) => {
console.log(
`[gatetest] ${owner}/${repo} ${ref.refName}: ${result.passed ? "PASSED" : "FAILED"} — ${result.details}`
);
})
.catch((err) => {
console.error(`[gatetest] scan error for ${owner}/${repo}:`, err);
})
);
}
if (
settings?.secretScanEnabled !== false ||
settings?.securityScanEnabled !== false
) {
promises.push(
runSecretAndSecurityScan(owner, repo, ref.refName, ref.newSha, {
scanSecrets: settings?.secretScanEnabled !== false,
scanSecurity: false,
})
.then((result) => {
if (
!result.secretResult.passed &&
ownerRow &&
repoRow &&
result.secrets.length > 0
) {
void notify(ownerRow.id, {
kind: "security_alert",
title: `Secret detected in ${owner}/${repo}`,
body: result.secretResult.details,
url: `/${owner}/${repo}/gates`,
repositoryId: repoRow.id,
});
}
})
.catch((err) => {
console.error(`[secret-scan] error for ${owner}/${repo}:`, err);
})
);
}
}
if (mainRef && settings?.autoDeployEnabled !== false && repoRow) {
promises.push(triggerCrontechDeploy(owner, repo, mainRef.newSha, repoRow.id));
}
if (repoRow) {
promises.push(fanoutWebhooks(repoRow.id, owner, repo, refs));
}
await Promise.allSettled(promises);
}
async function triggerCrontechDeploy(
owner: string,
repo: string,
sha: string,
repositoryId: string
): Promise<void> {
let deployId = "";
try {
const [row] = await db
.insert(deployments)
.values({
repositoryId,
environment: "production",
commitSha: sha,
ref: "refs/heads/main",
status: "pending",
target: "crontech",
})
.returning();
deployId = row?.id || "";
} catch {
}
try {
const response = await fetch(config.crontechDeployUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
repository: `${owner}/${repo}`,
sha,
branch: "main",
source: "gluecron",
}),
});
console.log(
`[crontech] deploy triggered for ${owner}/${repo}@${sha.slice(0, 7)}: ${response.status}`
);
if (deployId) {
await db
.update(deployments)
.set({
status: response.ok ? "success" : "failed",
completedAt: new Date(),
})
.where(eq(deployments.id, deployId));
}
} catch (err) {
console.error(`[crontech] failed to trigger deploy:`, err);
if (deployId) {
await db
.update(deployments)
.set({
status: "failed",
blockedReason: (err as Error).message,
completedAt: new Date(),
})
.where(eq(deployments.id, deployId));
}
}
}
async function fanoutWebhooks(
repositoryId: string,
owner: string,
repo: string,
refs: PushRef[]
): Promise<void> {
try {
const { fireWebhooks } = await import("../routes/webhooks");
await fireWebhooks(repositoryId, "push", {
repository: `${owner}/${repo}`,
refs: refs.map((r) => ({
ref: r.refName,
before: r.oldSha,
after: r.newSha,
})),
});
} catch {
}
}
|