Swadhin Biswas Feature/ai code reviewer (#80) · 8/17/2026
9740d3d
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
/**
* SSH Git Server
* Handles SSH connections for git push/pull operations
*/
import { logger } from "@/lib/logger";
import { spawn } from "child_process";
import { generateKeyPairSync } from "crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import ssh2 from "ssh2";
const { Server } = ssh2;
const GIT_PROCESS_TIMEOUT_MS =
parseInt(process.env.GIT_PROCESS_TIMEOUT_SECS || "3600", 10) * 1000;
/**
* Per-IP SSH authentication rate limiter.
* Tracks failed attempts and blocks IPs that exceed the threshold.
*/
const SSH_RATE_LIMIT: {
maxFailures: number;
windowMs: number;
blockMs: number;
maxEntries: number;
map: Map<
string,
{ failures: number; firstFailure: number; blockedUntil: number }
>;
} = {
maxFailures: 5,
windowMs: 60_000, // 1-minute window
blockMs: 5 * 60_000, // 5-minute block after threshold
maxEntries: 10_000, // Max tracked IPs to prevent memory leak
map: new Map(),
};
function checkSshRateLimit(ip: string): {
allowed: boolean;
retryAfterMs?: number;
} {
const now = Date.now();
const entry = SSH_RATE_LIMIT.map.get(ip);
if (entry) {
// Currently blocked?
if (entry.blockedUntil > now) {
return { allowed: false, retryAfterMs: entry.blockedUntil - now };
}
// Window expired — reset
if (now - entry.firstFailure > SSH_RATE_LIMIT.windowMs) {
SSH_RATE_LIMIT.map.delete(ip);
}
}
return { allowed: true };
}
function recordSshFailure(ip: string): void {
const now = Date.now();
const entry = SSH_RATE_LIMIT.map.get(ip);
if (!entry || now - entry.firstFailure > SSH_RATE_LIMIT.windowMs) {
// Evict oldest entries if map is full
if (SSH_RATE_LIMIT.map.size >= SSH_RATE_LIMIT.maxEntries) {
let oldestKey = "";
let oldestTime = Infinity;
for (const [key, val] of SSH_RATE_LIMIT.map) {
if (val.firstFailure < oldestTime) {
oldestTime = val.firstFailure;
oldestKey = key;
}
}
if (oldestKey) SSH_RATE_LIMIT.map.delete(oldestKey);
}
SSH_RATE_LIMIT.map.set(ip, {
failures: 1,
firstFailure: now,
blockedUntil: 0,
});
return;
}
entry.failures += 1;
if (entry.failures >= SSH_RATE_LIMIT.maxFailures) {
entry.blockedUntil = now + SSH_RATE_LIMIT.blockMs;
logger.warn(
{ ip, failures: entry.failures },
"SSH IP blocked due to repeated auth failures",
);
}
}
// Periodic cleanup of stale entries (every 5 minutes)
setInterval(() => {
const now = Date.now();
for (const [ip, entry] of SSH_RATE_LIMIT.map) {
if (
now - entry.firstFailure > SSH_RATE_LIMIT.windowMs &&
entry.blockedUntil < now
) {
SSH_RATE_LIMIT.map.delete(ip);
}
}
}, 5 * 60_000).unref();
export interface SSHServerConfig {
port: number;
hostKeyPath: string;
reposPath: string;
authenticateUser: (
username: string,
key: Buffer,
) => Promise<{
valid: boolean;
userId?: string;
canRead?: boolean;
canWrite?: boolean;
}>;
authorizeRepo: (
userId: string,
repoPath: string,
operation: "read" | "write",
) => Promise<boolean>;
onPush?: (userId: string, repoPath: string, refs: string[]) => Promise<void>;
}
export function createSSHServer(
config: SSHServerConfig,
): InstanceType<typeof Server> {
const {
port,
hostKeyPath,
reposPath,
authenticateUser,
authorizeRepo,
onPush,
} = config;
// Generate or load host key
const hostKey = loadOrGenerateHostKey(hostKeyPath);
const server = new Server(
{
hostKeys: [hostKey],
},
(client, info) => {
let userId: string | undefined;
let username: string | undefined;
let canWrite = false;
const clientIp = info?.ip || info?.header?.identRaw || "unknown";
client.on("authentication", async (ctx) => {
// Rate-limit check
const rl = checkSshRateLimit(clientIp);
if (!rl.allowed) {
logger.warn({ ip: clientIp }, "SSH auth rejected — IP rate-limited");
ctx.reject(["publickey"]);
return;
}
if (ctx.method === "publickey") {
try {
const result = await authenticateUser(ctx.username, ctx.key.data);
if (result.valid) {
userId = result.userId;
username = ctx.username;
canWrite = result.canWrite ?? false;
ctx.accept();
return;
}
} catch (error) {
logger.error({ err: error }, "SSH auth error");
}
}
recordSshFailure(clientIp);
ctx.reject(["publickey"]);
});
client.on("ready", () => {
logger.info({ username }, "SSH client connected");
client.on("session", (accept, reject) => {
const session = accept();
session.on("exec", async (accept, reject, info) => {
const command = info.command;
logger.debug({ command }, "SSH exec");
// Parse git command
const gitCommand = parseGitCommand(command);
if (!gitCommand) {
reject();
return;
}
const { operation, repoPath: requestedPath } = gitCommand;
// Normalize and validate repo path
const normalizedPath = normalizeRepoPath(requestedPath);
const fullRepoPath = join(reposPath, normalizedPath);
// Check authorization
const isWrite = operation === "git-receive-pack";
const authorized = userId
? await authorizeRepo(
userId,
normalizedPath,
isWrite ? "write" : "read",
)
: false;
if (!authorized) {
const channel = accept();
channel.stderr.write("Permission denied\n");
channel.exit(1);
channel.close();
return;
}
if (isWrite && !canWrite) {
const channel = accept();
channel.stderr.write("Write access denied\n");
channel.exit(1);
channel.close();
return;
}
// Ensure repo exists
if (!existsSync(fullRepoPath)) {
const channel = accept();
channel.stderr.write("Repository not found\n");
channel.exit(1);
channel.close();
return;
}
// Execute git command
const channel = accept();
const gitProcess = spawn(operation, [fullRepoPath], {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
REMOTE_USER: userId || "anonymous",
GL_ID: userId || "anonymous", // GitLab compatibility
},
});
// Kill git process if it runs too long
const gitTimer = setTimeout(() => {
logger.warn({ fullRepoPath, operation }, "SSH git process timed out, killing");
gitProcess.kill("SIGKILL");
}, GIT_PROCESS_TIMEOUT_MS);
gitProcess.on("close", () => clearTimeout(gitTimer));
gitProcess.on("error", () => clearTimeout(gitTimer));
// Track refs for push hook
let receivedRefs: string[] = [];
channel.pipe(gitProcess.stdin);
gitProcess.stdout.pipe(channel);
gitProcess.stderr.pipe(channel.stderr);
// Capture refs on push
if (isWrite) {
gitProcess.stdin.on("data", (data: Buffer) => {
const lines = data.toString().split("\n");
for (const line of lines) {
// Format: oldsha newsha refname
const match = line.match(
/^([a-f0-9]+)\s+([a-f0-9]+)\s+(.+)$/,
);
if (match) {
receivedRefs.push(match[3]);
}
}
});
}
gitProcess.on("close", async (code) => {
// Call push hook on successful push
if (
isWrite &&
code === 0 &&
userId &&
receivedRefs.length > 0 &&
onPush
) {
try {
await onPush(userId, normalizedPath, receivedRefs);
} catch (error) {
logger.error({ err: error }, "Push hook error");
}
}
channel.exit(code || 0);
channel.close();
});
gitProcess.on("error", (error) => {
logger.error({ err: error }, "Git process error");
channel.stderr.write(`Error: ${error.message}\n`);
channel.exit(1);
channel.close();
});
});
session.on("shell", (accept, reject) => {
// Don't allow shell access
reject();
});
});
});
client.on("error", (error) => {
logger.error({ err: error }, "SSH client error");
});
client.on("end", () => {
logger.info({ username }, "SSH client disconnected");
});
},
);
return server;
}
/**
* Parse a git SSH command
*/
function parseGitCommand(
command: string,
): { operation: string; repoPath: string } | null {
// Format: git-upload-pack '/path/to/repo.git' or git-receive-pack '/path/to/repo.git'
const match = command.match(
/^(git-upload-pack|git-receive-pack)\s+'?([^']+)'?$/,
);
if (!match) return null;
return {
operation: match[1],
repoPath: match[2],
};
}
/**
* Normalize repository path (remove leading slash, ensure .git suffix)
*/
function normalizeRepoPath(path: string): string {
let normalized = path.replace(/^\/+/, "");
if (!normalized.endsWith(".git")) {
normalized += ".git";
}
return normalized;
}
/**
* Load or generate SSH host key
*/
function loadOrGenerateHostKey(keyPath: string): string {
if (existsSync(keyPath)) {
return readFileSync(keyPath, "utf8");
}
// Ensure directory exists
const dir = dirname(keyPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
// Generate new key pair
const { privateKey } = generateKeyPairSync("rsa", {
modulusLength: 4096,
privateKeyEncoding: {
type: "pkcs1",
format: "pem",
},
publicKeyEncoding: {
type: "pkcs1",
format: "pem",
},
});
writeFileSync(keyPath, privateKey, { mode: 0o600 });
logger.info({ keyPath }, "Generated new SSH host key");
return privateKey;
}
/**
* Start the SSH server
*/
export async function startSSHServer(config: SSHServerConfig): Promise<void> {
const server = createSSHServer(config);
return new Promise((resolve, reject) => {
server.listen(config.port, "0.0.0.0", () => {
logger.info({ port: config.port }, "SSH Git server listening");
resolve();
});
server.on("error", (error: Error) => {
logger.error({ err: error }, "SSH server error");
reject(error);
});
});
}
/**
* Validate SSH public key format
*/
export function validateSSHPublicKey(key: string): boolean {
const keyTypes = [
"ssh-rsa",
"ssh-ed25519",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
];
const parts = key.trim().split(" ");
if (parts.length < 2) return false;
if (!keyTypes.includes(parts[0])) return false;
// Check if base64 part is valid
try {
Buffer.from(parts[1], "base64");
return true;
} catch {
return false;
}
}
/**
* Parse SSH public key to get type and fingerprint
*/
export async function parseSSHPublicKey(key: string): Promise<{
type: string;
fingerprint: string;
comment?: string;
} | null> {
const parts = key.trim().split(" ");
if (parts.length < 2) return null;
const type = parts[0];
const data = parts[1];
const comment = parts.slice(2).join(" ") || undefined;
// Generate fingerprint
const nodeCrypto = await import("crypto");
const buffer = Buffer.from(data, "base64");
const hash = nodeCrypto.createHash("sha256").update(buffer).digest("base64");
const fingerprint = `SHA256:${hash.replace(/=+$/, "")}`;
return { type, fingerprint, comment };
}