Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
mirrors.ts11.3 KB · 410 lines
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
/**
 * Block I9 — Repository mirroring.
 *
 * Pull-style mirroring: a mirrored repo has an upstream URL that we
 * periodically `git fetch` from. We run it as `git remote update` into
 * the bare repo so refs/heads/* are kept in sync with upstream's.
 *
 * SECURITY: only http(s) and git:// URLs are accepted. We refuse any URL
 * with shell metacharacters, `file://`, `ssh://`, or paths that could
 * escape the bare repo. Credentials embedded in URLs are allowed (the
 * caller decides whether to persist them) but stripped from logs.
 */

import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
  repoMirrors,
  repoMirrorRuns,
  repositories,
  users,
} from "../db/schema";
import { getRepoPath } from "../git/repository";
import { assertPublicUrl } from "./ssrf-guard";

const MIRROR_REMOTE_NAME = "gluecron-mirror";

/** Mirror upstreams may use git:// in addition to http(s). */
const MIRROR_SCHEMES = ["http:", "https:", "git:"];
const FETCH_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes

export interface ValidationResult {
  ok: boolean;
  error?: string;
}

/** Pure — validates an upstream URL for use as a mirror. */
export function validateUpstreamUrl(url: string): ValidationResult {
  if (!url || typeof url !== "string") {
    return { ok: false, error: "URL is required" };
  }
  const trimmed = url.trim();
  if (trimmed.length === 0) {
    return { ok: false, error: "URL is required" };
  }
  if (trimmed.length > 2048) {
    return { ok: false, error: "URL too long" };
  }
  // Reject shell metacharacters that Bun.spawn would pass through safely,
  // but which should never appear in a legitimate git URL.
  if (/[\s;&|`$\\<>]/.test(trimmed)) {
    return { ok: false, error: "URL contains invalid characters" };
  }
  // Accept only https/http/git schemes. Reject ssh/file/local paths —
  // ssh needs key management we don't have yet, file:// lets the user
  // escape into the server's filesystem.
  const allowed = /^(https?:\/\/|git:\/\/)/i;
  if (!allowed.test(trimmed)) {
    return { ok: false, error: "URL must start with https://, http://, or git://" };
  }
  // SSRF guard (BUILD_BIBLE §7): refuse upstreams that point at private/
  // internal address space (localhost, RFC1918, link-local metadata, etc).
  // SSRF_ALLOW_PRIVATE=1 opts out for self-hosted setups mirroring
  // internal git servers.
  const guard = assertPublicUrl(trimmed, { schemes: MIRROR_SCHEMES });
  if (!guard.ok) {
    return { ok: false, error: `blocked: ${guard.reason} (SSRF protection)` };
  }
  return { ok: true };
}

/** Strip credentials from a URL for safe logging. */
export function safeUrlForLog(url: string): string {
  try {
    const u = new URL(url);
    if (u.username || u.password) {
      u.username = "***";
      u.password = "";
      return u.toString();
    }
    return url;
  } catch {
    return url;
  }
}

export interface UpsertMirrorInput {
  repositoryId: string;
  upstreamUrl: string;
  intervalMinutes?: number;
  isEnabled?: boolean;
}

/** Create or update the mirror config for a repository. */
export async function upsertMirror(
  input: UpsertMirrorInput
): Promise<{ ok: true; id: string } | { ok: false; error: string }> {
  const v = validateUpstreamUrl(input.upstreamUrl);
  if (!v.ok) return { ok: false, error: v.error! };

  try {
    const [existing] = await db
      .select()
      .from(repoMirrors)
      .where(eq(repoMirrors.repositoryId, input.repositoryId))
      .limit(1);

    if (existing) {
      await db
        .update(repoMirrors)
        .set({
          upstreamUrl: input.upstreamUrl.trim(),
          intervalMinutes: input.intervalMinutes ?? existing.intervalMinutes,
          isEnabled: input.isEnabled ?? existing.isEnabled,
          updatedAt: new Date(),
        })
        .where(eq(repoMirrors.id, existing.id));
      return { ok: true, id: existing.id };
    }

    const [row] = await db
      .insert(repoMirrors)
      .values({
        repositoryId: input.repositoryId,
        upstreamUrl: input.upstreamUrl.trim(),
        intervalMinutes: input.intervalMinutes ?? 1440,
        isEnabled: input.isEnabled ?? true,
      })
      .returning({ id: repoMirrors.id });
    return { ok: true, id: row.id };
  } catch (err) {
    console.error("[mirrors] upsertMirror error:", err);
    return { ok: false, error: "Failed to save mirror configuration" };
  }
}

export async function deleteMirror(repositoryId: string): Promise<void> {
  try {
    await db
      .delete(repoMirrors)
      .where(eq(repoMirrors.repositoryId, repositoryId));
  } catch (err) {
    console.error("[mirrors] deleteMirror error:", err);
  }
}

export async function getMirrorForRepo(repositoryId: string) {
  try {
    const [row] = await db
      .select()
      .from(repoMirrors)
      .where(eq(repoMirrors.repositoryId, repositoryId))
      .limit(1);
    return row || null;
  } catch {
    return null;
  }
}

export async function listRecentRuns(
  mirrorId: string,
  limit = 20
): Promise<Array<typeof repoMirrorRuns.$inferSelect>> {
  try {
    return await db
      .select()
      .from(repoMirrorRuns)
      .where(eq(repoMirrorRuns.mirrorId, mirrorId))
      .orderBy(desc(repoMirrorRuns.startedAt))
      .limit(limit);
  } catch {
    return [];
  }
}

/**
 * Execute one sync run for a mirror. Returns the run row after completion.
 * Safe to call concurrently per-repo (we'd still end up fetching serially
 * because git locks `packed-refs` during fetch).
 */
export async function runMirrorSync(
  mirrorId: string
): Promise<{ ok: boolean; message: string; exitCode: number }> {
  // Load mirror + owning repo in one shot.
  const [row] = await db
    .select({
      mirror: repoMirrors,
      repoName: repositories.name,
      ownerName: users.username,
    })
    .from(repoMirrors)
    .innerJoin(repositories, eq(repoMirrors.repositoryId, repositories.id))
    .innerJoin(users, eq(repositories.ownerId, users.id))
    .where(eq(repoMirrors.id, mirrorId))
    .limit(1);

  if (!row) {
    return { ok: false, message: "mirror not found", exitCode: -1 };
  }
  if (!row.mirror.isEnabled) {
    return { ok: false, message: "mirror disabled", exitCode: -1 };
  }

  const repoPath = getRepoPath(row.ownerName, row.repoName);

  const [runRow] = await db
    .insert(repoMirrorRuns)
    .values({ mirrorId, status: "running" })
    .returning();

  const url = row.mirror.upstreamUrl;
  let exitCode = -1;
  let stdout = "";
  let stderr = "";

  try {
    // SSRF guard — re-check at use time: the stored URL may predate the
    // guard or have been saved while SSRF_ALLOW_PRIVATE was set. Throwing
    // here lands in the catch below, which records the run as failed and
    // never throws out.
    const guard = assertPublicUrl(url, { schemes: MIRROR_SCHEMES });
    if (!guard.ok) {
      throw new Error(`blocked: ${guard.reason} (SSRF protection)`);
    }

    // Ensure the remote exists and points at the current URL.
    await runGit(["git", "remote", "remove", MIRROR_REMOTE_NAME], repoPath);
    const addRes = await runGit(
      ["git", "remote", "add", MIRROR_REMOTE_NAME, url],
      repoPath
    );
    if (addRes.exitCode !== 0) {
      throw new Error(`remote add failed: ${addRes.stderr}`);
    }

    const fetchRes = await runGit(
      [
        "git",
        "fetch",
        "--prune",
        "--tags",
        "--no-write-fetch-head",
        MIRROR_REMOTE_NAME,
        "+refs/heads/*:refs/heads/*",
      ],
      repoPath,
      FETCH_TIMEOUT_MS
    );
    exitCode = fetchRes.exitCode;
    stdout = fetchRes.stdout;
    stderr = fetchRes.stderr;
    if (exitCode !== 0) {
      throw new Error(stderr.slice(0, 4000) || "git fetch failed");
    }

    const messageLines: string[] = [];
    if (stdout.trim()) messageLines.push(`stdout:\n${stdout.trim()}`);
    if (stderr.trim()) messageLines.push(`stderr:\n${stderr.trim()}`);
    const message =
      messageLines.join("\n\n").slice(0, 4000) || "Mirror synced (no changes)";

    await db
      .update(repoMirrorRuns)
      .set({
        finishedAt: new Date(),
        status: "ok",
        message,
        exitCode,
      })
      .where(eq(repoMirrorRuns.id, runRow.id));

    await db
      .update(repoMirrors)
      .set({
        lastSyncedAt: new Date(),
        lastStatus: "ok",
        lastError: null,
        updatedAt: new Date(),
      })
      .where(eq(repoMirrors.id, mirrorId));

    return { ok: true, message, exitCode };
  } catch (err: any) {
    const errMsg = String(err?.message || err || "unknown error").slice(0, 4000);
    await db
      .update(repoMirrorRuns)
      .set({
        finishedAt: new Date(),
        status: "error",
        message: errMsg,
        exitCode,
      })
      .where(eq(repoMirrorRuns.id, runRow.id));

    await db
      .update(repoMirrors)
      .set({
        lastSyncedAt: new Date(),
        lastStatus: "error",
        lastError: errMsg,
        updatedAt: new Date(),
      })
      .where(eq(repoMirrors.id, mirrorId));

    return { ok: false, message: errMsg, exitCode };
  }
}

// ---------- Internal ----------

async function runGit(
  cmd: string[],
  cwd: string,
  timeoutMs = 60_000
): Promise<{ exitCode: number; stdout: string; stderr: string }> {
  try {
    const proc = Bun.spawn(cmd, {
      cwd,
      stdout: "pipe",
      stderr: "pipe",
      env: {
        ...process.env,
        GIT_TERMINAL_PROMPT: "0", // never prompt for creds
      },
    });
    const timer = setTimeout(() => {
      try {
        proc.kill("SIGKILL");
      } catch {
        // ignore
      }
    }, timeoutMs);
    const [stdout, stderr] = await Promise.all([
      new Response(proc.stdout).text(),
      new Response(proc.stderr).text(),
    ]);
    const exitCode = await proc.exited;
    clearTimeout(timer);
    return { exitCode, stdout, stderr };
  } catch (err: any) {
    return {
      exitCode: -1,
      stdout: "",
      stderr: String(err?.message || err || "spawn failed"),
    };
  }
}

/** Returns mirrors that are due for a sync (used by admin cron trigger). */
export async function listDueMirrors(
  now: Date = new Date()
): Promise<Array<{ id: string; repositoryId: string; upstreamUrl: string }>> {
  try {
    const rows = await db
      .select()
      .from(repoMirrors)
      .where(eq(repoMirrors.isEnabled, true));
    const due: Array<{
      id: string;
      repositoryId: string;
      upstreamUrl: string;
    }> = [];
    for (const r of rows) {
      if (!r.lastSyncedAt) {
        due.push({
          id: r.id,
          repositoryId: r.repositoryId,
          upstreamUrl: r.upstreamUrl,
        });
        continue;
      }
      const last = new Date(r.lastSyncedAt as any).getTime();
      const elapsedMin = (now.getTime() - last) / 60000;
      if (elapsedMin >= r.intervalMinutes) {
        due.push({
          id: r.id,
          repositoryId: r.repositoryId,
          upstreamUrl: r.upstreamUrl,
        });
      }
    }
    return due;
  } catch {
    return [];
  }
}

/** Run sync for every due mirror. Returns summary counts. */
export async function syncAllDue(): Promise<{
  total: number;
  ok: number;
  failed: number;
}> {
  const due = await listDueMirrors();
  let ok = 0;
  let failed = 0;
  for (const m of due) {
    const r = await runMirrorSync(m.id);
    if (r.ok) ok++;
    else failed++;
  }
  return { total: due.length, ok, failed };
}

// Suppress unused import warning for `and`.
void and;

export const __internal = {
  MIRROR_REMOTE_NAME,
  FETCH_TIMEOUT_MS,
};