swadhinbiswas feat: push-mirror, webhook queue, auth-cache, gists/discussions · 8/28/2026
96005fc
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
/**
* Commit Signature Verification Library
* GitHub-style "Verified" commit badges
* Verifies git commit GPG signatures against user-uploaded keys
* in the gpg_keys table using openpgp (no system keyring needed)
*/
import { getDatabase, schema } from "@/db";
import { and, eq, inArray } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import * as openpgp from "openpgp";
import { logger } from "./logger";
// Types
export interface CommitVerification {
/** Commit object contains a gpgsig/gpgsig-sha256 header */
signed: boolean;
/** Signature cryptographically valid AND owned by the committer's account */
verified: boolean;
/** A public key stored in gpg_keys verified the signature */
validKeyInDb: boolean;
/** users.id of the committer matched by committer email, if registered */
signerUserId: string | null;
}
const UNSIGNED_RESULT: CommitVerification = {
signed: false,
verified: false,
validKeyInDb: false,
signerUserId: null,
};
// Cache
const CACHE_TTL_MS = 10 * 60 * 1000;
const CACHE_MAX_ENTRIES = 2000;
interface CacheEntry {
result: CommitVerification;
expiresAt: number;
}
const verificationCache = new Map<string, CacheEntry>();
function cacheGet(key: string): CommitVerification | null {
const entry = verificationCache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
verificationCache.delete(key);
return null;
}
return entry.result;
}
function cacheSet(key: string, result: CommitVerification): void {
while (verificationCache.size >= CACHE_MAX_ENTRIES) {
const oldest = verificationCache.keys().next().value;
if (oldest === undefined) break;
verificationCache.delete(oldest);
}
verificationCache.set(key, { result, expiresAt: Date.now() + CACHE_TTL_MS });
}
// Signature extraction
/**
* Parse the raw output of `git cat-file commit <sha>`.
* Returns the armored signature block and the exact commit bytes with all
* gpgsig/gpgsig-sha256 header lines stripped (this is what Git signs).
*/
export function extractSignatureFromCommit(
rawCommitObject: string,
): { signature: string; signedData: string } | null {
const separatorIndex = rawCommitObject.indexOf("\n\n");
const headerSection =
separatorIndex === -1 ? rawCommitObject : rawCommitObject.slice(0, separatorIndex);
const tail = separatorIndex === -1 ? "" : rawCommitObject.slice(separatorIndex);
const headerLines = headerSection.split("\n");
const keptLines: string[] = [];
let signatureLines: string[] | null = null;
let collecting = false;
for (const line of headerLines) {
if (/^gpgsig(-sha256)?( |$)/.test(line)) {
if (!signatureLines) {
signatureLines = [];
collecting = true;
} else {
collecting = false;
keptLines.push(line);
}
continue;
}
if (collecting && line.startsWith(" ")) {
signatureLines!.push(line.slice(1));
continue;
}
collecting = false;
keptLines.push(line);
}
if (!signatureLines || signatureLines.length === 0) {
return null;
}
const signature = signatureLines.join("\n");
const signedData = `${keptLines.join("\n")}${tail}`;
return { signature, signedData };
}
function parseCommitterEmail(rawCommitObject: string): string | null {
const match = rawCommitObject.match(/^committer [^\n]*<([^>]*)>/m);
return match ? match[1] : null;
}
// Verification
interface VerificationContext {
db: NodePgDatabase<typeof schema>;
repoPath: string;
}
async function loadContext(
owner: string,
repo: string,
): Promise<VerificationContext | null> {
const db = getDatabase() as NodePgDatabase<typeof schema>;
const ownerUser = await db.query.users.findFirst({
where: eq(schema.users.username, owner),
});
if (!ownerUser) return null;
const repoRow = await db.query.repositories.findFirst({
where: and(
eq(schema.repositories.ownerId, ownerUser.id),
eq(schema.repositories.name, repo),
),
});
if (!repoRow) return null;
const { resolveRepoPath } = await import("./git-storage");
const repoPath = await resolveRepoPath(repoRow.diskPath);
return { db, repoPath };
}
async function readRawCommit(repoPath: string, sha: string): Promise<string | null> {
if (!/^[0-9a-f]{7,64}$/i.test(sha)) return null;
const { simpleGit } = await import("simple-git");
try {
return await simpleGit(repoPath).raw(["cat-file", "commit", sha]);
} catch {
return null;
}
}
async function verifyWithKeys(
ctx: VerificationContext,
sha: string,
extracted: { signature: string; signedData: string },
): Promise<CommitVerification> {
const sig = await openpgp.readSignature({ armoredSignature: extracted.signature });
const signingKeyIds = sig
.getSigningKeyIDs()
.map((id) => id.toHex().toLowerCase())
.filter(Boolean);
for (const keyId of signingKeyIds) {
const cached = cacheGet(`${sha}:${keyId}`);
if (cached) return cached;
}
let keyRows = signingKeyIds.length
? await ctx.db.select().from(schema.gpgKeys).where(inArray(schema.gpgKeys.keyId, signingKeyIds))
: [];
if (!keyRows.length) {
keyRows = await ctx.db.select().from(schema.gpgKeys).limit(500);
}
const message = await openpgp.createMessage({ text: extracted.signedData });
for (const row of keyRows) {
try {
const keyObj = await openpgp.readKey({ armoredKey: row.publicKey });
const keyHex = keyObj.getKeyID().toHex().toLowerCase();
const fingerprint = keyObj.getFingerprint().toLowerCase();
if (
signingKeyIds.length &&
!signingKeyIds.some(
(id) => keyHex === id || fingerprint.endsWith(id) || keyHex.endsWith(id),
)
) {
continue;
}
const result = await openpgp.verify({
message,
verificationKeys: keyObj,
signature: sig,
});
const firstSignature = result.signatures[0];
if (!firstSignature) continue;
const isValid = await firstSignature.verified.then(
() => true,
() => false,
);
if (!isValid) continue;
const committerEmail = parseCommitterEmail(extracted.signedData);
const signerUser = committerEmail
? await ctx.db.query.users.findFirst({
where: eq(schema.users.email, committerEmail),
})
: null;
const verification: CommitVerification = {
signed: true,
verified: !!signerUser && row.userId === signerUser.id,
validKeyInDb: true,
signerUserId: signerUser?.id ?? null,
};
cacheSet(`${sha}:${fingerprint}`, verification);
cacheSet(`${sha}:${keyHex}`, verification);
return verification;
} catch {
continue;
}
}
const fallback: CommitVerification = {
signed: true,
verified: false,
validKeyInDb: false,
signerUserId: null,
};
for (const keyId of signingKeyIds) {
cacheSet(`${sha}:${keyId}`, fallback);
}
return fallback;
}
async function verifySha(
ctx: VerificationContext,
sha: string,
): Promise<CommitVerification> {
const raw = await readRawCommit(ctx.repoPath, sha);
if (!raw) return { ...UNSIGNED_RESULT };
const extracted = extractSignatureFromCommit(raw);
if (!extracted) return { ...UNSIGNED_RESULT };
try {
return await verifyWithKeys(ctx, sha, extracted);
} catch (e) {
logger.warn({ err: e, sha }, "Commit signature verification failed");
return { ...UNSIGNED_RESULT };
}
}
/**
* Verify a single commit's GPG signature against user-uploaded public keys.
* Never throws — any failure yields an "unsigned"-shaped result.
*/
export async function verifyCommitSignature(opts: {
owner: string;
repo: string;
sha: string;
}): Promise<CommitVerification> {
try {
const ctx = await loadContext(opts.owner, opts.repo);
if (!ctx) return { ...UNSIGNED_RESULT };
return await verifySha(ctx, opts.sha);
} catch (e) {
logger.warn(
{ err: e, owner: opts.owner, repo: opts.repo, sha: opts.sha },
"Commit signature verification failed",
);
return { ...UNSIGNED_RESULT };
}
}
/**
* Verify a page of commits sequentially (openpgp is CPU-bound).
* Returns a Map keyed by sha. Empty map when disabled via
* COMMIT_SIGNATURE_VERIFICATION=false.
*/
export async function verifyCommitsSignatures(
owner: string,
repo: string,
shas: string[],
maxBatch = 20,
): Promise<Map<string, CommitVerification>> {
const results = new Map<string, CommitVerification>();
if (process.env.COMMIT_SIGNATURE_VERIFICATION === "false") return results;
const batch = shas.filter(Boolean).slice(0, maxBatch);
if (batch.length === 0) return results;
let ctx: VerificationContext | null = null;
try {
ctx = await loadContext(owner, repo);
} catch (e) {
logger.warn({ err: e, owner, repo }, "Commit signature verification context failed");
}
if (!ctx) {
for (const sha of batch) results.set(sha, { ...UNSIGNED_RESULT });
return results;
}
for (const sha of batch) {
results.set(sha, await verifySha(ctx, sha));
}
return results;
}