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
|
import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { repositories, users } from "../db/schema";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
verifyInstallToken,
hasPermission,
type Permission,
} from "../lib/marketplace";
import { audit } from "../lib/notify";
import {
_getProdSignalsTable,
dismissSignal,
isValidSha,
listOpenSignalsForRepo,
listSignalsForCommit,
recordSignal,
resolveSignal,
sanitiseKind,
sanitiseSeverity,
sanitiseSource,
} from "../lib/prod-signals";
const signals = new Hono<AuthEnv>();
type AuthPrincipal =
| { kind: "user"; userId: string; scopes: string[] }
| { kind: "install"; permissions: Permission[]; botUsername: string };
async function resolveAuth(c: any): Promise<AuthPrincipal | null> {
const authHeader = c.req.header("authorization") || "";
if (authHeader.toLowerCase().startsWith("bearer ")) {
const bearer = authHeader.slice(7).trim();
if (bearer.startsWith("ghi_")) {
const install = await verifyInstallToken(bearer);
if (!install) return null;
return {
kind: "install",
permissions: install.permissions,
botUsername: install.botUsername,
};
}
}
const user = c.get("user");
if (user) {
const scopes = (c.get("oauthScopes") as string[] | undefined) || [];
return { kind: "user", userId: user.id, scopes };
}
return null;
}
async function resolveRepoByName(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 };
}
function parseRepoSlug(raw: unknown): { owner: string; name: string } | null {
if (typeof raw !== "string") return null;
const parts = raw.trim().split("/");
if (parts.length !== 2) return null;
const [owner, name] = parts;
if (!owner || !name) return null;
return { owner, name };
}
function canWriteRepo(
principal: AuthPrincipal,
repoOwnerId: string
): boolean {
if (principal.kind === "user") return principal.userId === repoOwnerId;
return hasPermission(principal.permissions, "contents:read");
}
signals.post("/api/v1/signals/error", softAuth, async (c) => {
const principal = await resolveAuth(c);
if (!principal) {
return c.json({ error: "Authentication required" }, 401);
}
let body: any = {};
try {
body = await c.req.json();
} catch {
return c.json({ error: "Invalid JSON body" }, 400);
}
const slug = parseRepoSlug(body.repo ?? body.repository);
if (!slug) {
return c.json(
{ error: "Missing or malformed 'repo' (expected 'owner/name')" },
400
);
}
const sha = String(body.commit_sha ?? body.commitSha ?? "").toLowerCase();
if (!isValidSha(sha)) {
return c.json({ error: "Invalid commit_sha" }, 400);
}
const message = String(body.message ?? "");
if (!message.trim()) {
return c.json({ error: "'message' is required" }, 400);
}
const resolved = await resolveRepoByName(slug.owner, slug.name);
if (!resolved) return c.json({ error: "Repository not found" }, 404);
if (!canWriteRepo(principal, resolved.owner.id)) {
return c.json({ error: "Forbidden" }, 403);
}
const result = await recordSignal({
repositoryId: resolved.repo.id,
commitSha: sha,
source: sanitiseSource(body.source),
kind: sanitiseKind(body.kind),
severity: sanitiseSeverity(body.severity),
message,
stackTrace:
typeof body.stack_trace === "string"
? body.stack_trace
: typeof body.stackTrace === "string"
? body.stackTrace
: null,
deployId:
typeof body.deploy_id === "string"
? body.deploy_id
: typeof body.deployId === "string"
? body.deployId
: null,
environment:
typeof body.environment === "string" ? body.environment : null,
samplePayload:
typeof body.sample_payload === "string"
? body.sample_payload
: typeof body.samplePayload === "string"
? body.samplePayload
: null,
});
if (!result) {
return c.json({ error: "Could not record signal" }, 500);
}
return c.json({
id: result.id,
status: result.status,
count: result.count,
});
});
signals.get("/api/v1/repos/:owner/:repo/signals", softAuth, async (c) => {
const { owner: ownerName, repo: repoName } = c.req.param();
const resolved = await resolveRepoByName(ownerName, repoName);
if (!resolved) return c.json({ error: "Repository not found" }, 404);
const user = c.get("user");
if (resolved.repo.isPrivate && (!user || user.id !== resolved.owner.id)) {
return c.json({ error: "Forbidden" }, 403);
}
const rows = await listOpenSignalsForRepo(resolved.repo.id);
return c.json({ total: rows.length, signals: rows });
});
signals.get(
"/api/v1/repos/:owner/:repo/commits/:sha/signals",
softAuth,
async (c) => {
const { owner: ownerName, repo: repoName, sha } = c.req.param();
if (!isValidSha(sha)) return c.json({ error: "Invalid sha" }, 400);
const resolved = await resolveRepoByName(ownerName, repoName);
if (!resolved) return c.json({ error: "Repository not found" }, 404);
const user = c.get("user");
if (resolved.repo.isPrivate && (!user || user.id !== resolved.owner.id)) {
return c.json({ error: "Forbidden" }, 403);
}
const rows = await listSignalsForCommit(resolved.repo.id, sha);
return c.json({ total: rows.length, signals: rows });
}
);
signals.post("/api/v1/signals/:id/dismiss", softAuth, async (c) => {
const principal = await resolveAuth(c);
if (!principal) return c.json({ error: "Authentication required" }, 401);
if (principal.kind !== "user") {
return c.json({ error: "Only repo owners can dismiss" }, 403);
}
const id = c.req.param("id");
const prodSignals = await _getProdSignalsTable();
const [row] = await db
.select()
.from(prodSignals)
.where(eq(prodSignals.id, id))
.limit(1);
if (!row) return c.json({ error: "Signal not found" }, 404);
const [repo] = await db
.select()
.from(repositories)
.where(eq(repositories.id, row.repositoryId))
.limit(1);
if (!repo) return c.json({ error: "Signal not found" }, 404);
if (repo.ownerId !== principal.userId) {
return c.json({ error: "Forbidden" }, 403);
}
const ok = await dismissSignal(id);
if (!ok) return c.json({ error: "Could not dismiss" }, 500);
await audit({
userId: principal.userId,
repositoryId: repo.id,
action: "signal.dismiss",
targetType: "prod_signal",
targetId: id,
});
return c.json({ ok: true });
});
signals.post("/api/v1/signals/:id/resolve", softAuth, async (c) => {
const principal = await resolveAuth(c);
if (!principal) return c.json({ error: "Authentication required" }, 401);
if (principal.kind !== "user") {
return c.json({ error: "Only repo owners can resolve" }, 403);
}
const id = c.req.param("id");
let body: any = {};
try {
body = await c.req.json();
} catch {
body = {};
}
const [row] = await db
.select()
.from(prodSignals)
.where(eq(prodSignals.id, id))
.limit(1);
if (!row) return c.json({ error: "Signal not found" }, 404);
const [repo] = await db
.select()
.from(repositories)
.where(eq(repositories.id, row.repositoryId))
.limit(1);
if (!repo) return c.json({ error: "Signal not found" }, 404);
if (repo.ownerId !== principal.userId) {
return c.json({ error: "Forbidden" }, 403);
}
const resolvedByCommit =
typeof body.resolved_by_commit === "string"
? body.resolved_by_commit
: typeof body.resolvedByCommit === "string"
? body.resolvedByCommit
: null;
const ok = await resolveSignal(id, resolvedByCommit);
if (!ok) return c.json({ error: "Could not resolve" }, 500);
await audit({
userId: principal.userId,
repositoryId: repo.id,
action: "signal.resolve",
targetType: "prod_signal",
targetId: id,
metadata: resolvedByCommit ? { resolvedByCommit } : undefined,
});
return c.json({ ok: true });
});
export default signals;
|