/ opencodehub / src / lib / external-import.ts
Swadhin Biswas Feat/federation (#82) · 8/19/2026
c0437ed
365 lines · 11.8 KB
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
/**
 * External Repository Import Library
 *
 * Imports a repository from another Git hosting service (GitHub, GitLab,
 * Bitbucket, another OpenCodeHub instance, or any public/private git URL)
 * into the requester's account. Mirrors GitHub's "import repository" flow.
 *
 * Security: all URLs are validated with SSRF protection before any network
 * operation (see validateGitCloneUrl). Optional auth tokens are only ever
 * embedded in the ephemeral clone command and are stored encrypted on the
 * repo row (mirrorToken) so scheduled mirror syncs can re-authenticate.
 */

import { existsSync, mkdirSync, rmSync } from "fs";
import { simpleGit } from "simple-git";
import { eq, and } from "drizzle-orm";
import { z } from "zod";

import { getDatabase, schema } from "@/db";
import { validateFederationSourceUrl } from "@/lib/federation";
import { getDiskPath, initRepoInStorage, finalizeRepoInit, isCloudStorage } from "@/lib/git-storage";
import { getSanitizedGitEnv } from "@/lib/git";
import { logger } from "@/lib/logger";
import { logActivity } from "@/lib/activity";
import { encryptWorkflowSecret } from "@/lib/workflow-secret-crypto";
import { isValidRepoName, slugify } from "@/lib/utils";
import { detectOpenCodeHubInstance, getUrlOrigin } from "@/lib/federation";

export const importRepoSchema = z.object({
  sourceUrl: z.string().min(1).max(500),
  name: z.string().min(1).max(100).optional(),
  description: z.string().max(500).optional(),
  visibility: z.enum(["public", "private", "internal"]).default("public"),
  mirror: z.boolean().default(true),
  authToken: z.string().min(1).max(500).optional(),
  authUsername: z.string().min(1).max(255).optional(),
  hasIssues: z.boolean().default(true),
  hasWiki: z.boolean().default(false),
  hasActions: z.boolean().default(true),
});

export type ImportRepoInput = z.infer<typeof importRepoSchema>;

const KNOWN_PROVIDERS: Record<string, string> = {
  "github.com": "github",
  "gitlab.com": "gitlab",
  "bitbucket.org": "bitbucket",
  "codeberg.org": "codeberg",
  "gitea.com": "gitea",
  "gitee.com": "gitee",
};

/**
 * Normalize a user-supplied git URL into a canonical clone URL.
 * Supports:
 *  - https://host/owner/repo[.git]
 *  - git@host:owner/repo.git        (scp-style)
 *  - ssh://git@host/owner/repo.git
 *  - owner/repo shorthand           (defaults to GitHub)
 */
export function normalizeCloneUrl(raw: string): string {
  let url = raw.trim();

  if (url.startsWith("git@") && url.includes(":") && !url.includes("://")) {
    // scp-style → https for https-capable hosts, else leave as-is
    const [userAndHost, pathPart] = url.split(":");
    const host = userAndHost.split("@")[1];
    if (host && KNOWN_PROVIDERS[host] === "github") {
      return `https://github.com/${pathPart}`;
    }
    return url;
  }

  // owner/repo shorthand (no scheme, no host)
  if (!url.includes("://") && !url.includes("@") && /^[^/]+\/[^/]+$/.test(url)) {
    return `https://github.com/${url}`;
  }

  return url;
}

/**
 * Detect the provider from a normalized URL (for display purposes).
 */
export function detectProvider(normalizedUrl: string): string {
  try {
    const parsed = new URL(normalizedUrl);
    return KNOWN_PROVIDERS[parsed.hostname] || "git";
  } catch {
    return "git";
  }
}

/**
 * Derive a valid repo name from a URL's last path segment.
 */
export function deriveRepoName(normalizedUrl: string): string | null {
  try {
    const parsed = new URL(normalizedUrl);
    const segment = parsed.pathname.replace(/\.git$/, "").split("/").filter(Boolean).pop() || "";
    if (!isValidRepoName(segment.toLowerCase())) return null;
    return segment.toLowerCase();
  } catch {
    return null;
  }
}

/**
 * Build a clone URL with an embedded token for https remotes.
 * For ssh/git remotes the token cannot be embedded — callers should reject
 * token+ssh combos before reaching here.
 */
function buildAuthenticatedCloneUrl(normalizedUrl: string, token: string, username?: string): string {
  if (!normalizedUrl.startsWith("https://")) return normalizedUrl;
  const parsed = new URL(normalizedUrl);
  const host = parsed.hostname;
  // Provider-specific username conventions for token auth
  let user = username || "oauth2"; // explicit username (federation) or gitlab default
  if (host === "github.com" || host === "bitbucket.org") {
    user = "x-access-token";
  }
  parsed.username = user;
  parsed.password = token;
  return parsed.toString();
}

/**
 * Detect the default branch of a freshly-cloned bare repo.
 */
async function detectDefaultBranch(localRepoPath: string): Promise<string> {
  const git = simpleGit(localRepoPath);
  try {
    const head = await git.raw(["symbolic-ref", "HEAD"]);
    return head.trim().replace(/^refs\/heads\//, "") || "main";
  } catch {
    return "main";
  }
}

export interface ImportRepoResult {
  success: boolean;
  repositoryId?: string;
  owner?: string;
  name?: string;
  url?: string;
  defaultBranch?: string;
  error?: string;
}

/**
 * Import an external repository into the given user's account.
 */
export async function importExternalRepository(
  userId: string,
  input: ImportRepoInput,
): Promise<ImportRepoResult> {
  const db = getDatabase();

  const user = await db.query.users.findFirst({
    where: eq(schema.users.id, userId),
  });
  if (!user) return { success: false, error: "User not found" };

  const normalized = normalizeCloneUrl(input.sourceUrl);
  if (!normalized) {
    return { success: false, error: "Invalid source URL" };
  }

  // SSRF protection: reject private/internal/link-local targets before cloning.
  // Federation-aware: localhost is allowed only when FEDERATION_ALLOW_LOCALHOST=true
  // (needed to fork from a peer instance on the same host / private network).
  const urlCheck = await validateFederationSourceUrl(normalized);
  if (!urlCheck.valid) {
    return { success: false, error: urlCheck.reason };
  }

  // If a token is supplied, the remote must be https so we can embed it safely.
  // Exception: localhost federation testing (FEDERATION_ALLOW_LOCALHOST=true),
  // where http on the loopback interface is trusted.
  const allowLocalhost = process.env.FEDERATION_ALLOW_LOCALHOST === "true";
  if (input.authToken && !normalized.startsWith("https://") && !allowLocalhost) {
    return {
      success: false,
      error: "An auth token can only be used with an https:// source URL",
    };
  }

  // Detect whether the source is another OpenCodeHub instance (federation).
  // If so, record the fork relationship so this instance can push back to it.
  const sourceOrigin = getUrlOrigin(normalized);
  const peerInstance = sourceOrigin
    ? await detectOpenCodeHubInstance(sourceOrigin)
    : null;
  const isExternalFork = peerInstance !== null;

  // Derive repo name
  let name = input.name?.trim().toLowerCase() || deriveRepoName(normalized);
  if (!name) {
    return { success: false, error: "Unable to determine a repository name" };
  }
  if (!isValidRepoName(name)) {
    return {
      success: false,
      error: "Invalid repository name. Use only lowercase letters, numbers, dots, hyphens, and underscores.",
    };
  }

  // Name availability
  const slug = slugify(name);
  const existing = await db.query.repositories.findFirst({
    where: and(
      eq(schema.repositories.ownerId, user.id),
      eq(schema.repositories.name, name),
    ),
  });
  if (existing) {
    return { success: false, error: `You already have a repository named "${name}"` };
  }

  const repoId = crypto.randomUUID();
  const timestamp = new Date();
  const siteUrl = process.env.SITE_URL || "http://localhost:4321";
  const sshPort = process.env.GIT_SSH_PORT || "2222";
  const diskPath = await getDiskPath(user.username, slug);
  const sshCloneUrl = `ssh://git@localhost:${sshPort}/${user.username}/${slug}.git`;
  const httpCloneUrl = `${siteUrl}/${user.username}/${slug}.git`;

  const provider = detectProvider(normalized);
  const mirrorUrl = normalized; // clean URL (never embeds the token)

  let localGitPath: string | null = null;
  let cloned = false;
  try {
    // Prepare target path (temp for cloud, direct for local)
    localGitPath = await initRepoInStorage(user.username, slug);
    if (existsSync(localGitPath)) {
      rmSync(localGitPath, { recursive: true, force: true });
    }
    mkdirSync(localGitPath, { recursive: true });

    // Clone from the remote. Embed the token transiently for https remotes.
    // Build authenticated URL: for OpenCodeHub upstreams (federation push-back)
    // the upstream username is used for basic-auth; for third-party hosts the
    // provider-specific username convention applies.
    const cloneUrl = input.authToken
      ? buildAuthenticatedCloneUrl(normalized, input.authToken, input.authUsername)
      : normalized;

    const git = simpleGit({
      binary: "git",
      maxConcurrentProcesses: 1,
      unsafe: {
        allowUnsafePack: true,
        allowUnsafeSshCommand: true,
        allowUnsafeCredentialHelper: true,
        allowUnsafeEditor: true,
      },
    });
    git.env(getSanitizedGitEnv());
    await git.clone(cloneUrl, localGitPath, ["--bare"]);
    cloned = true;

    const defaultBranch = await detectDefaultBranch(localGitPath);

    // Remove the origin remote pointing at the source (avoids leaking the
    // embedded token into the stored config) unless mirroring.
    if (!input.mirror) {
      try {
        const bareGit = simpleGit(localGitPath);
        bareGit.env(getSanitizedGitEnv());
        await bareGit.remote(["remove", "origin"]);
      } catch {
        // Non-fatal
      }
    }

    // Encrypt token (if any) for later mirror syncs.
    let encryptedToken: string | null = null;
    if (input.authToken) {
      encryptedToken = encryptWorkflowSecret(input.authToken);
    }

    // Create DB record
    // @ts-expect-error - Drizzle multi-db union type issue
    await db.insert(schema.repositories).values({
      id: repoId,
      name,
      slug,
      description: input.description ?? null,
      ownerId: user.id,
      ownerType: "user",
      visibility: input.visibility,
      defaultBranch,
      diskPath,
      sshCloneUrl,
      httpCloneUrl,
      isMirror: input.mirror,
      mirrorUrl: input.mirror ? mirrorUrl : null,
      mirrorToken: encryptedToken,
      mirrorUsername: input.authUsername || null,
      mirrorSyncStatus: input.mirror ? "success" : null,
      lastMirrorSyncAt: input.mirror ? timestamp : null,
      isFork: isExternalFork,
      forkedFromUrl: isExternalFork ? mirrorUrl : null,
      hasIssues: input.hasIssues,
      hasWiki: input.hasWiki,
      hasActions: input.hasActions,
      size: 0,
      language: null,
      topics: null,
      createdAt: timestamp,
      updatedAt: timestamp,
    });

    // Upload to cloud storage if needed
    if (await isCloudStorage()) {
      await finalizeRepoInit(user.username, slug);
    }

    logger.info({ userId, repoId, sourceUrl: mirrorUrl, provider }, "External repository imported");

    await logActivity(
      user.id,
      "import_repo",
      "imported",
      "repository",
      repoId,
      repoId,
      { name, sourceUrl: mirrorUrl, provider },
    );

    return {
      success: true,
      repositoryId: repoId,
      owner: user.username,
      name,
      url: `/${user.username}/${slug}`,
      defaultBranch,
    };
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logger.error({ userId, sourceUrl: mirrorUrl, error: message }, "External repo import failed");

    // Cleanup the cloned dir on failure
    if (localGitPath) {
      try {
        if (existsSync(localGitPath)) {
          rmSync(localGitPath, { recursive: true, force: true });
        }
      } catch {
        // Non-fatal
      }
    }
    // Rollback DB row if we got far enough to insert but something after failed
    try {
      // @ts-expect-error - Drizzle multi-db union type issue
      await db.delete(schema.repositories).where(eq(schema.repositories.id, repoId));
    } catch {
      // Non-fatal
    }

    return { success: false, error: message };
  }
}