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
|
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import {
issues,
issueLabels,
labels,
repositories,
users,
} from "../db/schema";
import { getRepoPath } from "../git/repository";
const TODO_PATTERN = /^\+.*\b(TODO|FIXME|HACK|XXX|BUG|OPTIMIZE)\b.*$/gm;
const SECRET_PATTERN =
/^\+.*(password|secret|api_key|apikey|token|private_key|privatekey)\s*=\s*["'][^"']{8,}/gim;
const SQL_INJECTION_PATTERN =
/^\+.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/gim;
const CONSOLE_LOG_PATTERN = /^\+.*console\.(log|debug|info)\(/gm;
type FindingType = "todo" | "secret" | "sql-injection" | "console-log";
interface Finding {
type: FindingType;
filePath: string;
lineNumber: number;
matchText: string;
}
const MAX_ISSUES_PER_PUSH = 5;
const MAX_DIFF_BYTES = 500 * 1024;
const LABEL_NAME = "ai-detected";
const LABEL_COLOR = "#e11d48";
async function getDiff(
owner: string,
repo: string,
oldSha: string,
newSha: string
): Promise<string> {
const cwd = getRepoPath(owner, repo);
const allZero = /^0+$/.test(oldSha);
const cmd = allZero
? ["git", "show", "--format=", newSha]
: ["git", "diff", oldSha, newSha];
try {
const proc = Bun.spawn(cmd, {
cwd,
stdout: "pipe",
stderr: "ignore",
});
const reader = proc.stdout.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
if (totalBytes + value.byteLength > MAX_DIFF_BYTES) {
const remaining = MAX_DIFF_BYTES - totalBytes;
if (remaining > 0) {
chunks.push(value.slice(0, remaining));
}
break;
}
chunks.push(value);
totalBytes += value.byteLength;
}
}
reader.cancel();
await proc.exited;
const decoder = new TextDecoder();
return chunks.map((c) => decoder.decode(c)).join("");
} catch {
return "";
}
}
export function parseDiffForFindings(diff: string): Finding[] {
const findings: Finding[] = [];
let currentFile = "";
let currentNewLine = 0;
const lines = diff.split("\n");
for (const line of lines) {
const fileMatch = line.match(/^diff --git a\/.* b\/(.+)$/);
if (fileMatch) {
currentFile = fileMatch[1];
currentNewLine = 0;
continue;
}
const plusHeader = line.match(/^\+\+\+ b\/(.+)$/);
if (plusHeader) {
currentFile = plusHeader[1];
continue;
}
const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (hunkMatch) {
currentNewLine = parseInt(hunkMatch[1], 10) - 1;
continue;
}
if (line.startsWith("+") && !line.startsWith("+++")) {
currentNewLine++;
} else if (line.startsWith("-") && !line.startsWith("---")) {
continue;
} else if (!line.startsWith("\\")) {
if (!line.startsWith("diff") && !line.startsWith("index") &&
!line.startsWith("---") && !line.startsWith("+++")) {
currentNewLine++;
}
continue;
}
if (!line.startsWith("+") || !currentFile) continue;
}
return scanDiffLines(diff);
}
function scanDiffLines(diff: string): Finding[] {
const findings: Finding[] = [];
let currentFile = "";
let currentNewLine = 0;
let lineIdx = 0;
const lines = diff.split("\n");
for (const line of lines) {
lineIdx++;
const fileMatch = line.match(/^diff --git a\/.* b\/(.+)$/);
if (fileMatch) {
currentFile = fileMatch[1];
currentNewLine = 0;
continue;
}
const plusHeader = line.match(/^\+\+\+ b\/(.+)$/);
if (plusHeader) {
currentFile = plusHeader[1];
continue;
}
const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (hunkMatch) {
currentNewLine = parseInt(hunkMatch[1], 10) - 1;
continue;
}
if (line.startsWith("-") && !line.startsWith("---")) {
continue;
}
if (line.startsWith("+") && !line.startsWith("+++")) {
currentNewLine++;
if (!currentFile) continue;
const matchText = line.slice(0, 200);
if (TODO_PATTERN.test(line)) {
findings.push({
type: "todo",
filePath: currentFile,
lineNumber: currentNewLine,
matchText,
});
}
TODO_PATTERN.lastIndex = 0;
if (SECRET_PATTERN.test(line)) {
findings.push({
type: "secret",
filePath: currentFile,
lineNumber: currentNewLine,
matchText: maskSecretValue(matchText),
});
}
SECRET_PATTERN.lastIndex = 0;
if (SQL_INJECTION_PATTERN.test(line)) {
findings.push({
type: "sql-injection",
filePath: currentFile,
lineNumber: currentNewLine,
matchText,
});
}
SQL_INJECTION_PATTERN.lastIndex = 0;
if (CONSOLE_LOG_PATTERN.test(line)) {
findings.push({
type: "console-log",
filePath: currentFile,
lineNumber: currentNewLine,
matchText,
});
}
CONSOLE_LOG_PATTERN.lastIndex = 0;
} else {
currentNewLine++;
}
}
return findings;
}
function maskSecretValue(text: string): string {
return text.replace(
/(password|secret|api_key|apikey|token|private_key|privatekey)\s*=\s*["'][^"']{0,200}/gi,
(m) => {
const eqIdx = m.indexOf("=");
const quoteIdx = m.indexOf('"', eqIdx) !== -1
? m.indexOf('"', eqIdx)
: m.indexOf("'", eqIdx);
return m.slice(0, quoteIdx + 1) + "****";
}
);
}
interface GroupedFinding {
type: FindingType;
filePath: string;
lineNumbers: number[];
sampleText: string;
}
function groupFindings(findings: Finding[]): GroupedFinding[] {
const map = new Map<string, GroupedFinding>();
for (const f of findings) {
const key = `${f.type}::${f.filePath}`;
const existing = map.get(key);
if (existing) {
existing.lineNumbers.push(f.lineNumber);
} else {
map.set(key, {
type: f.type,
filePath: f.filePath,
lineNumbers: [f.lineNumber],
sampleText: f.matchText,
});
}
}
return Array.from(map.values());
}
const FINDING_LABELS: Record<FindingType, string> = {
"todo": "TODO/FIXME",
"secret": "Potential Secret Exposure",
"sql-injection": "SQL Injection Risk",
"console-log": "Debug Console Log",
};
function renderIssueTitle(
group: GroupedFinding,
pusherUsername: string
): string {
const label = FINDING_LABELS[group.type];
const loc = `${group.filePath}`;
return `[AI] ${label} found in ${loc} (pushed by @${pusherUsername})`;
}
function renderIssueBody(
group: GroupedFinding,
owner: string,
repo: string,
commitSha: string,
pusherUsername: string
): string {
const label = FINDING_LABELS[group.type];
const shortSha = commitSha.slice(0, 7);
const lineList = group.lineNumbers.slice(0, 10).join(", ");
const firstLine = group.lineNumbers[0];
const fileLink = `[\`${group.filePath}:${firstLine}\`](/${owner}/${repo}/blob/${commitSha}/${group.filePath}#L${firstLine})`;
const description = findingDescription(group.type);
const lines = [
`**Automated AI scan** detected a **${label}** in commit \`${shortSha}\` pushed by @${pusherUsername}.`,
"",
`**File:** ${fileLink}`,
`**Line(s):** ${lineList}${group.lineNumbers.length > 10 ? ` (and ${group.lineNumbers.length - 10} more)` : ""}`,
"",
"## Matched code",
"```",
group.sampleText.trim(),
"```",
"",
"## Why this matters",
description,
"",
"---",
"_This issue was auto-opened by Gluecron's AI push scanner. Close it if the finding is a false positive._",
];
return lines.join("\n");
}
function findingDescription(type: FindingType): string {
switch (type) {
case "todo":
return "TODO/FIXME/HACK comments indicate incomplete or workaround code that should be tracked as proper issues rather than buried in source files.";
case "secret":
return "Hardcoded credentials or API keys in source code can be extracted from git history even after deletion. Rotate the exposed credential immediately and use environment variables or a secrets manager instead.";
case "sql-injection":
return "Template literals interpolated directly into SQL statements may allow SQL injection if user-controlled data reaches this code path. Use parameterised queries or a query builder instead.";
case "console-log":
return "Debug `console.log` calls left in production code can expose sensitive data in logs and add unnecessary noise. Remove or replace with a proper logging library with log-level controls.";
}
}
function renderSummaryIssueBody(
totalFindings: number,
groups: GroupedFinding[],
owner: string,
repo: string,
commitSha: string,
pusherUsername: string
): string {
const shortSha = commitSha.slice(0, 7);
const lines = [
`**Automated AI scan** detected **${totalFindings} findings** in commit \`${shortSha}\` pushed by @${pusherUsername}.`,
"",
"The push scanner limit was reached — here is a summary of all findings:",
"",
"| Type | File | Lines |",
"| ---- | ---- | ----- |",
...groups.map((g) => {
const label = FINDING_LABELS[g.type];
const fileLink = `[${g.filePath}](/${owner}/${repo}/blob/${commitSha}/${g.filePath})`;
const lineStr = g.lineNumbers.slice(0, 5).join(", ") +
(g.lineNumbers.length > 5 ? ` (+${g.lineNumbers.length - 5})` : "");
return `| ${label} | ${fileLink} | ${lineStr} |`;
}),
"",
"Address the individual findings and re-push to trigger a fresh scan.",
"",
"---",
"_This issue was auto-opened by Gluecron's AI push scanner._",
];
return lines.join("\n");
}
async function ensureAiDetectedLabel(repositoryId: string): Promise<string | null> {
try {
const [existing] = await db
.select({ id: labels.id })
.from(labels)
.where(and(eq(labels.repositoryId, repositoryId), eq(labels.name, LABEL_NAME)))
.limit(1);
if (existing) return existing.id;
const [created] = await db
.insert(labels)
.values({
repositoryId,
name: LABEL_NAME,
color: LABEL_COLOR,
description: "Automatically detected by Gluecron AI push scanner",
})
.onConflictDoNothing()
.returning({ id: labels.id });
return created?.id ?? null;
} catch {
return null;
}
}
async function insertIssue(opts: {
repositoryId: string;
authorId: string;
title: string;
body: string;
labelId: string | null;
currentIssueCount: number;
}): Promise<number | null> {
try {
const [inserted] = await db
.insert(issues)
.values({
repositoryId: opts.repositoryId,
authorId: opts.authorId,
title: opts.title.slice(0, 255),
body: opts.body,
state: "open",
})
.returning({ id: issues.id, number: issues.number });
if (!inserted) return null;
if (opts.labelId) {
await db
.insert(issueLabels)
.values({ issueId: inserted.id, labelId: opts.labelId })
.catch(() => {});
}
await db
.update(repositories)
.set({ issueCount: opts.currentIssueCount + 1 })
.where(eq(repositories.id, opts.repositoryId))
.catch(() => {});
return inserted.number;
} catch {
return null;
}
}
export interface ScanResult {
findingsCount: number;
issuesOpened: number;
skipped: boolean;
}
export async function scanDiffForIssues(
owner: string,
repo: string,
oldSha: string,
newSha: string,
pusherUserId: string
): Promise<ScanResult> {
if (process.env.AI_AUTO_ISSUES !== "1") {
return { findingsCount: 0, issuesOpened: 0, skipped: true };
}
try {
const [repoRow] = await db
.select({
id: repositories.id,
ownerId: repositories.ownerId,
issueCount: repositories.issueCount,
})
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(and(eq(users.username, owner), eq(repositories.name, repo)))
.limit(1);
if (!repoRow) {
return { findingsCount: 0, issuesOpened: 0, skipped: true };
}
let pusherUsername = "unknown";
try {
const [pusherRow] = await db
.select({ username: users.username })
.from(users)
.where(eq(users.id, pusherUserId))
.limit(1);
if (pusherRow) pusherUsername = pusherRow.username;
} catch {
}
const diff = await getDiff(owner, repo, oldSha, newSha);
if (!diff.trim()) {
return { findingsCount: 0, issuesOpened: 0, skipped: false };
}
const rawFindings = scanDiffLines(diff);
const groups = groupFindings(rawFindings);
if (groups.length === 0) {
return { findingsCount: 0, issuesOpened: 0, skipped: false };
}
const labelId = await ensureAiDetectedLabel(repoRow.id);
let issuesOpened = 0;
let currentIssueCount = repoRow.issueCount ?? 0;
if (groups.length <= MAX_ISSUES_PER_PUSH) {
for (const group of groups) {
const title = renderIssueTitle(group, pusherUsername);
const body = renderIssueBody(group, owner, repo, newSha, pusherUsername);
const num = await insertIssue({
repositoryId: repoRow.id,
authorId: repoRow.ownerId,
title,
body,
labelId,
currentIssueCount,
});
if (num !== null) {
issuesOpened++;
currentIssueCount++;
}
}
} else {
const title = `[AI] Multiple issues found in this push (${rawFindings.length} findings) — see details`;
const body = renderSummaryIssueBody(
rawFindings.length,
groups,
owner,
repo,
newSha,
pusherUsername
);
const num = await insertIssue({
repositoryId: repoRow.id,
authorId: repoRow.ownerId,
title,
body,
labelId,
currentIssueCount,
});
if (num !== null) {
issuesOpened++;
}
}
console.log(
`[ai-auto-issues] ${owner}/${repo}@${newSha.slice(0, 7)}: ${rawFindings.length} finding(s), ${issuesOpened} issue(s) opened`
);
return {
findingsCount: rawFindings.length,
issuesOpened,
skipped: false,
};
} catch (err) {
console.warn(
`[ai-auto-issues] error for ${owner}/${repo}@${newSha.slice(0, 7)}:`,
err instanceof Error ? err.message : err
);
return { findingsCount: 0, issuesOpened: 0, skipped: false };
}
}
export const __test = {
scanDiffLines,
groupFindings,
parseDiffForFindings,
renderIssueTitle,
renderIssueBody,
renderSummaryIssueBody,
maskSecretValue,
};
|