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
import-bulk.tsx15.8 KB · 467 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
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
/**
 * Bulk GitHub import — "paste my org + token → import everything".
 *
 * Owner flow for migrating many products at once. Reuses the single-repo
 * import logic from `src/lib/import-helper.ts` so the clone + DB insert
 * code path is identical to `/import`.
 *
 * Token never leaves this process: it's read from the form body, passed
 * to GitHub's API via `Authorization` header, and embedded in the git
 * clone URL only at the moment of spawning `git`. Results never contain
 * the token — `scrubSecrets()` in the helper redacts it before display.
 */

import { Hono } from "hono";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import {
  sanitizeRepoName,
  importOneRepo,
  type ImportOneRepoResult,
} from "../lib/import-helper";

const importBulkRoutes = new Hono<AuthEnv>();

importBulkRoutes.use("*", softAuth);

// Hard limits to keep a single request bounded.
const MAX_REPOS = 200;
const MAX_REPO_SIZE_KB = 500 * 1024; // 500 MB in KB (GitHub reports size in KB)
const GITHUB_PER_PAGE = 100;

interface GitHubRepo {
  name: string;
  full_name: string;
  description: string | null;
  private: boolean;
  clone_url: string;
  default_branch: string;
  fork: boolean;
  size: number; // KB
}

type Visibility = "public" | "private" | "both";

/**
 * Paginate the GitHub "list org repos" endpoint. Caps at MAX_REPOS so a
 * single request can't fan out indefinitely. Throws on non-2xx so the
 * caller can surface a friendly error.
 */
async function fetchOrgRepos(
  org: string,
  token: string
): Promise<GitHubRepo[]> {
  const headers: Record<string, string> = {
    Accept: "application/vnd.github.v3+json",
    "User-Agent": "gluecron/1.0",
    Authorization: `Bearer ${token}`,
  };

  const repos: GitHubRepo[] = [];
  let page = 1;
  while (repos.length < MAX_REPOS) {
    const url = `https://api.github.com/orgs/${encodeURIComponent(
      org
    )}/repos?per_page=${GITHUB_PER_PAGE}&page=${page}&type=all`;
    const res = await fetch(url, { headers });
    if (!res.ok) {
      // Never echo the token. Include only the status + first slice of body.
      const errBody = (await res.text()).slice(0, 200);
      throw new Error(`GitHub API error (${res.status}): ${errBody}`);
    }
    const batch = (await res.json()) as GitHubRepo[];
    if (!Array.isArray(batch) || batch.length === 0) break;
    repos.push(...batch);
    if (batch.length < GITHUB_PER_PAGE) break;
    page++;
    if (page > 10) break; // hard page ceiling: 1000 entries, we cap earlier anyway
  }
  return repos.slice(0, MAX_REPOS);
}

function matchesVisibility(repo: GitHubRepo, v: Visibility): boolean {
  if (v === "both") return true;
  if (v === "public") return repo.private === false;
  if (v === "private") return repo.private === true;
  return true;
}

// ─── FORM PAGE ───────────────────────────────────────────────

importBulkRoutes.get("/import/bulk", requireAuth, async (c) => {
  const user = c.get("user")!;
  const error = c.req.query("error");

  return c.html(
    <Layout title="Bulk import from GitHub" user={user}>
      <div style="max-width: 720px">
        <h2 style="margin-bottom: 4px">Bulk import from GitHub</h2>
        <p style="color: var(--text-muted); font-size: 14px; margin-bottom: 20px">
          Paste a GitHub org + personal access token. Gluecron will clone
          every repo into your namespace as a mirror.
        </p>

        {error && <div class="auth-error">{decodeURIComponent(error)}</div>}

        <div style="background: var(--bg-secondary); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 20px; font-size: 13px; color: var(--text-muted)">
          <strong style="color: var(--text)">What this does</strong>
          <ul style="margin: 8px 0 0 18px; line-height: 1.6">
            <li>
              Lists every repo in the org via the GitHub API
              (<code>/orgs/{"{org}"}/repos</code>, paginated).
            </li>
            <li>
              Clones each one as a bare mirror into your gluecron account
              (<code>{user.username}/{"{repo}"}</code>).
            </li>
            <li>
              Reports per-repo success / failure / skipped-if-exists at
              the end. One failure does not abort the batch.
            </li>
            <li>
              Hard caps: {MAX_REPOS} repos per run, 500MB per repo.
            </li>
          </ul>
        </div>

        <form method="post" action="/import/bulk">
          <div class="form-group">
            <label style="display:block; margin-bottom:4px; font-size:13px">
              GitHub org
            </label>
            <input
              type="text"
              name="githubOrg"
              required
              placeholder="my-company"
              aria-label="GitHub org"
              style="padding: 8px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text); font-size: 14px; width: 100%"
            />
          </div>

          <div class="form-group">
            <label style="display:block; margin-bottom:4px; font-size:13px">
              GitHub personal access token (<code>repo:read</code> scope)
            </label>
            <input
              type="password"
              name="githubToken"
              required
              placeholder="ghp_xxxxxxxxxxxx"
              autocomplete="off"
              aria-label="GitHub personal access token"
              style="padding: 8px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text); font-size: 14px; font-family: var(--font-mono); width: 100%"
            />
          </div>

          <div class="form-group">
            <label style="display:block; margin-bottom:4px; font-size:13px">
              Visibility filter
            </label>
            <select
              name="visibility"
              aria-label="Visibility filter"
              style="padding: 8px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text); font-size: 14px; width: 100%"
            >
              <option value="both" selected>Both (public + private)</option>
              <option value="public">Public only</option>
              <option value="private">Private only</option>
            </select>
          </div>

          <div class="form-group" style="margin: 12px 0">
            <label style="display:flex; align-items:center; gap:8px; font-size:13px">
              <input type="checkbox" name="dryRun" value="1" checked />
              Dry run — preview the list without cloning
            </label>
          </div>

          <button type="submit" class="btn btn-primary">
            Run bulk import
          </button>
          <a href="/import" class="btn" style="margin-left: 8px">
            Back to /import
          </a>
        </form>
      </div>
    </Layout>
  );
});

// ─── POST HANDLER ────────────────────────────────────────────

importBulkRoutes.post("/import/bulk", requireAuth, async (c) => {
  const user = c.get("user")!;
  const body = await c.req.parseBody();

  const githubOrg = String(body.githubOrg || "").trim();
  const githubToken = String(body.githubToken || "").trim();
  const visibilityRaw = String(body.visibility || "both").trim();
  const visibility: Visibility =
    visibilityRaw === "public" || visibilityRaw === "private"
      ? (visibilityRaw as Visibility)
      : "both";
  const dryRun = Boolean(body.dryRun); // unchecked box = undefined = false

  if (!githubOrg) {
    return c.redirect("/import/bulk?error=GitHub+org+is+required");
  }
  if (!githubToken) {
    return c.redirect(
      "/import/bulk?error=GitHub+token+is+required+%28repo%3Aread+scope%29"
    );
  }

  // Validate the token has at least read access before we start cloning.
  // `GET /user` is the cheapest call that requires a valid token. We also
  // inspect the `X-OAuth-Scopes` header so we can warn early if the token
  // is missing `repo`/`repo:read`.
  try {
    const userRes = await fetch("https://api.github.com/user", {
      headers: {
        Accept: "application/vnd.github.v3+json",
        "User-Agent": "gluecron/1.0",
        Authorization: `Bearer ${githubToken}`,
      },
    });
    if (!userRes.ok) {
      return c.redirect(
        `/import/bulk?error=${encodeURIComponent(
          `Invalid GitHub token (${userRes.status}). Check scope repo:read.`
        )}`
      );
    }
    const scopes = (userRes.headers.get("x-oauth-scopes") || "").toLowerCase();
    if (
      scopes &&
      !scopes.includes("repo") &&
      !scopes.includes("public_repo")
    ) {
      return c.redirect(
        `/import/bulk?error=${encodeURIComponent(
          "Token is missing repo:read scope. Regenerate with repo (or public_repo) checked."
        )}`
      );
    }
  } catch (err) {
    // Network-level failure talking to GitHub. Don't leak err details.
    return c.redirect(
      "/import/bulk?error=Could+not+reach+GitHub+to+validate+the+token"
    );
  }

  // Pull the repo list.
  let allRepos: GitHubRepo[];
  try {
    allRepos = await fetchOrgRepos(githubOrg, githubToken);
  } catch (err) {
    const msg = (err as Error).message || "Unknown error";
    return c.redirect(
      `/import/bulk?error=${encodeURIComponent(msg).slice(0, 400)}`
    );
  }

  if (allRepos.length === 0) {
    return c.redirect(
      `/import/bulk?error=${encodeURIComponent(
        `No repos visible for org "${githubOrg}" with this token.`
      )}`
    );
  }

  // Apply visibility filter + size cap; track why things were skipped.
  const candidates: GitHubRepo[] = [];
  const oversized: { name: string; sizeKB: number }[] = [];
  for (const r of allRepos) {
    if (!matchesVisibility(r, visibility)) continue;
    if (typeof r.size === "number" && r.size > MAX_REPO_SIZE_KB) {
      oversized.push({ name: r.name, sizeKB: r.size });
      continue;
    }
    candidates.push(r);
  }

  // Dry run: render a preview + counts, never touch disk or DB.
  if (dryRun) {
    return c.html(
      <Layout title="Bulk import preview" user={user}>
        <div style="max-width: 820px">
          <h2 style="margin-bottom: 4px">Bulk import — dry-run preview</h2>
          <p style="color: var(--text-muted); font-size: 14px; margin-bottom: 16px">
            Org <code>{githubOrg}</code> · visibility <code>{visibility}</code>
            {" · "}
            {candidates.length} repo(s) would be imported
            {oversized.length > 0 ? `, ${oversized.length} skipped (>500MB)` : ""}
            .
          </p>

          <ResultsTable
            rows={candidates.map((r) => ({
              name: sanitizeRepoName(r.name),
              status: "dry-run",
              notes: `${r.private ? "private" : "public"} · ${(
                r.size / 1024
              ).toFixed(1)} MB`,
            }))}
          />

          {oversized.length > 0 && (
            <>
              <h3 style="margin-top:24px">Skipped — over 500MB</h3>
              <ResultsTable
                rows={oversized.map((r) => ({
                  name: sanitizeRepoName(r.name),
                  status: "too-large",
                  notes: `${(r.sizeKB / 1024).toFixed(1)} MB`,
                }))}
              />
            </>
          )}

          <div style="margin-top:20px; padding:12px 14px; background:var(--bg-secondary); border:1px solid var(--border); border-radius:var(--radius); font-size:13px">
            Looks good? Go back and uncheck <em>Dry run</em> to actually
            import.
          </div>

          <div style="margin-top:16px">
            <a href="/import/bulk" class="btn btn-primary">
              Back to form
            </a>
          </div>
        </div>
      </Layout>
    );
  }

  // Real run: clone each candidate sequentially. Collect results.
  const results: ImportOneRepoResult[] = [];
  for (const r of candidates) {
    // eslint-disable-next-line no-await-in-loop
    const res = await importOneRepo({
      cloneUrl: r.clone_url,
      targetName: r.name,
      ownerId: user.id,
      ownerUsername: user.username,
      token: githubToken,
      description: r.description,
      isPrivate: r.private,
      defaultBranch: r.default_branch,
    });
    results.push(res);
  }

  for (const o of oversized) {
    results.push({
      status: "failed",
      name: sanitizeRepoName(o.name),
      notes: `Skipped — over 500MB (${(o.sizeKB / 1024).toFixed(1)} MB)`,
    });
  }

  const counts = results.reduce(
    (acc, r) => {
      acc[r.status] = (acc[r.status] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>
  );

  return c.html(
    <Layout title="Bulk import results" user={user}>
      <div style="max-width: 820px">
        <h2 style="margin-bottom: 4px">Bulk import — results</h2>
        <p style="color: var(--text-muted); font-size: 14px; margin-bottom: 16px">
          Org <code>{githubOrg}</code>: {counts["success"] || 0} imported,
          {" "}
          {counts["skipped-exists"] || 0} skipped (exists),
          {" "}
          {counts["failed"] || 0} failed.
        </p>

        <ResultsTable rows={results} />

        <div style="margin-top:20px; display:flex; gap:8px">
          <a href={`/${user.username}`} class="btn btn-primary">
            View my repositories
          </a>
          <a href="/import/bulk" class="btn">
            Run another import
          </a>
        </div>
      </div>
    </Layout>
  );
});

// ─── COMPONENTS ──────────────────────────────────────────────

function ResultsTable({
  rows,
}: {
  rows: { name: string; status: string; notes: string }[];
}) {
  if (rows.length === 0) {
    return (
      <div style="padding:14px; background:var(--bg-secondary); border:1px solid var(--border); border-radius:var(--radius); font-size:13px; color:var(--text-muted)">
        No rows.
      </div>
    );
  }
  return (
    <table
      style="width:100%; border-collapse:collapse; font-size:13px; background:var(--bg-secondary); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden"
    >
      <thead>
        <tr style="background:var(--bg); text-align:left">
          <th style="padding:8px 12px; border-bottom:1px solid var(--border)">
            Name
          </th>
          <th style="padding:8px 12px; border-bottom:1px solid var(--border)">
            Status
          </th>
          <th style="padding:8px 12px; border-bottom:1px solid var(--border)">
            Notes
          </th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r) => (
          <tr>
            <td style="padding:6px 12px; border-bottom:1px solid var(--border); font-family:var(--font-mono)">
              {r.name}
            </td>
            <td style="padding:6px 12px; border-bottom:1px solid var(--border)">
              <StatusBadge status={r.status} />
            </td>
            <td style="padding:6px 12px; border-bottom:1px solid var(--border); color:var(--text-muted)">
              {r.notes}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function StatusBadge({ status }: { status: string }) {
  const color =
    status === "success"
      ? "#3fb950"
      : status === "skipped-exists"
        ? "#f0b429"
        : status === "dry-run"
          ? "#58a6ff"
          : status === "too-large"
            ? "#f0b429"
            : "#f85149";
  return (
    <span
      style={`display:inline-block; padding:2px 8px; border-radius:10px; background:${color}22; color:${color}; font-size:12px; font-weight:600`}
    >
      {status}
    </span>
  );
}

export default importBulkRoutes;