~james/core

ref: 452f17b75181d62d1d92016edecd38e1d70fecab core/web/src/lib/api/githubImport.ts -rw-r--r-- 12.5 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
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
import { ok } from "@atcute/client";
import { mainSchema as listRecordsSchema } from "@atcute/atproto/types/repo/listRecords";
import { isDid, type Did, type Nsid } from "@atcute/lexicons/syntax";
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import { createClient, serviceDidForHost } from "#lib/auth/agent.ts";
import { validateRepoName } from "#lib/api/repoCreate.ts";
import { createMigrationTask, type MigrationTask } from "#lib/api/migrator.ts";
import { uploadProfileAvatar } from "#lib/api/profile.ts";
import { createRecord, putRecord, readRecord } from "#lib/api/write.ts";
import { createPubKey } from "#lib/api/settings.ts";
import { addEmail, listEmails } from "#lib/api/emails.ts";
import { createDeliberiClient } from "#lib/api/deliberi.ts";
import { nsidOf, recordKeyOf } from "#lib/api/syntax.ts";
import type { GitHubAccount, GitHubRepo } from "#lib/github.ts";
import type { ProfileRecord } from "#lib/api/records.ts";
import type { Fetch } from "#lib/fetch.ts";

const ACCOUNT_CACHE_MS = 30_000;
const accountCache = new WeakMap<Fetch, { account: GitHubAccount; at: number }>();

export const fetchGitHubAccount = async (fetcher: Fetch = fetch): Promise<GitHubAccount | null> => {
	const cached = accountCache.get(fetcher);
	if (cached && Date.now() - cached.at < ACCOUNT_CACHE_MS) return cached.account;
	const response = await fetcher("/_internal/github", { cache: "no-store" });
	if (response.status === 401) {
		accountCache.delete(fetcher);
		return null;
	}
	if (!response.ok) throw new Error("Could not load your GitHub account. Try connecting again.");
	const account = (await response.json()) as GitHubAccount;
	accountCache.set(fetcher, { account, at: Date.now() });
	return account;
};

export const invalidateGitHubAccount = (fetcher: Fetch = fetch) => accountCache.delete(fetcher);

const PROFILE_COLLECTION = nsidOf("org.tangled.actor.profile");
const PUBLIC_KEY_COLLECTION = "org.tangled.key.sshKey" as Nsid;
const SELF_RKEY = recordKeyOf("self");

const GITHUB_REPO_GRAMMAR = /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/;

const messageOf = (cause: unknown): string =>
	cause instanceof Error ? cause.message : String(cause);

// localinfra serves a github stub on its own origin; github.com cannot be hardcoded
const hostOf = (origin: string): string => {
	let parsed: URL;
	try {
		parsed = new URL(origin);
	} catch {
		throw new Error(`Invalid GitHub origin: "${origin}" is not a URL.`);
	}
	if (parsed.protocol !== "https:") {
		throw new Error(`Invalid GitHub origin: protocol must be https.`);
	}
	return parsed.hostname.toLowerCase();
};

export const validateGitHubRepoUrl = (
	urlString: string,
	expectedFullName: string,
	kind: "htmlUrl" | "cloneUrl",
	origin: string
): string => {
	if (!GITHUB_REPO_GRAMMAR.test(expectedFullName)) {
		throw new Error(`Invalid GitHub fullName: "${expectedFullName}".`);
	}
	let parsed: URL;
	try {
		parsed = new URL(urlString);
	} catch {
		throw new Error(`Invalid GitHub ${kind}: malformed URL.`);
	}
	if (parsed.protocol !== "https:") {
		throw new Error(`Invalid GitHub ${kind}: protocol must be https.`);
	}
	const allowedHost = hostOf(origin);
	if (parsed.hostname.toLowerCase() !== allowedHost) {
		throw new Error(`Invalid GitHub ${kind}: host must be ${allowedHost}.`);
	}
	if (parsed.username || parsed.password) {
		throw new Error(`Invalid GitHub ${kind}: credentials are not allowed.`);
	}
	if (parsed.port !== "") {
		throw new Error(`Invalid GitHub ${kind}: non-default port is not allowed.`);
	}
	if (parsed.search !== "") {
		throw new Error(`Invalid GitHub ${kind}: query parameters are not allowed.`);
	}
	if (parsed.hash !== "") {
		throw new Error(`Invalid GitHub ${kind}: hash fragments are not allowed.`);
	}

	const allowedPaths =
		kind === "cloneUrl"
			? [`/${expectedFullName}.git`, `/${expectedFullName}`]
			: [`/${expectedFullName}`];

	if (!allowedPaths.includes(parsed.pathname)) {
		throw new Error(
			`Invalid GitHub ${kind}: pathname must match repository "${expectedFullName}".`
		);
	}

	return parsed.toString();
};

export const canonicalRepoName = (rawName: string): string =>
	validateRepoName(rawName).toLowerCase();

interface RepoCollision<T = string> {
	canonical: string;
	candidates: T[];
	conflictsWithExisting: boolean;
	hasCollision: boolean;
}

export const findRepoCollisions = <T extends string | { name: string }>(
	candidates: Iterable<T>,
	existing: Iterable<string> = []
): Map<string, RepoCollision<T>> => {
	const existingSet = new Set(
		Array.from(existing).flatMap((item) => {
			try {
				return [canonicalRepoName(item)];
			} catch {
				return [];
			}
		})
	);

	const groups = new Map<string, T[]>();
	for (const candidate of candidates) {
		const rawName = typeof candidate === "string" ? candidate : candidate.name;
		const canonical = canonicalRepoName(rawName);
		const bucket = groups.get(canonical);
		if (bucket) {
			bucket.push(candidate);
		} else {
			groups.set(canonical, [candidate]);
		}
	}

	return new Map(
		Array.from(groups, ([canonical, items]) => {
			const conflictsWithExisting = existingSet.has(canonical);
			return [
				canonical,
				{
					canonical,
					candidates: items,
					conflictsWithExisting,
					hasCollision: items.length > 1 || conflictsWithExisting
				}
			];
		})
	);
};

interface ImportGitHubRepoInput {
	ownerDid: Did;
	ownerHandle: string;
	knot: string;
	spindle?: string;
	repo: GitHubRepo;
	name?: string;
	description?: string;
}

interface ImportUrlInput {
	sourceUrl: string;
	name: string;
	description?: string;
	knot: string;
	ownerDid?: Did;
	ownerHandle?: string;
	spindle?: string;
}

const knotDidOf = (knot: string): Did => {
	const did = knot.startsWith("did:") ? knot : serviceDidForHost(knot);
	if (!isDid(did)) throw new Error(`${knot} is not a did`);
	return did;
};

type Uri = `${string}:${string}`;

const validateUrlSource = (raw: string): Uri => {
	let parsed: URL;
	try {
		parsed = new URL(raw.trim());
	} catch {
		throw new Error("That is not a URL.");
	}
	if (parsed.protocol !== "https:") throw new Error("The source URL must be https.");
	if (parsed.username || parsed.password)
		throw new Error("The source URL must not carry credentials.");
	if (parsed.port !== "" && parsed.port !== "443")
		throw new Error("The source URL must not use a custom port.");
	if (parsed.pathname.replace(/\/+$/, "").split("/").filter(Boolean).length === 0)
		throw new Error("The source URL must name a repository.");
	return parsed.toString() as Uri;
};

export interface StartedMigration {
	taskId: string;
	name: string;
	jobId?: string;
}

export const importFromUrl = async (
	agent: OAuthUserAgent,
	migratorUrl: string,
	input: ImportUrlInput,
	options?: { fetch?: Fetch; signal?: AbortSignal; bobbinUrl?: string }
): Promise<StartedMigration> => {
	const sourceUrl = validateUrlSource(input.sourceUrl);
	const name = validateRepoName(input.name);
	const description = input.description?.trim() || undefined;

	const task = await createMigrationTask(
		agent,
		migratorUrl,
		crypto.randomUUID(),
		[
			{
				name,
				knotDid: knotDidOf(input.knot),
				sourceUrl,
				...(description !== undefined ? { description } : {})
			}
		],
		options
	);
	const first = task.jobs[0];
	return { taskId: task.id, name: first?.name ?? name, jobId: first?.id };
};

export const importGitHubRepos = async (
	agent: OAuthUserAgent,
	migratorUrl: string,
	origin: string,
	inputs: ImportGitHubRepoInput[],
	options?: { fetch?: Fetch; signal?: AbortSignal; bobbinUrl?: string }
): Promise<MigrationTask> => {
	if (inputs.length === 0) throw new Error("Select at least one repository to import.");
	const jobs = [];
	for (const input of inputs) {
		const cloneUrl = validateGitHubRepoUrl(
			input.repo.cloneUrl,
			input.repo.fullName,
			"cloneUrl",
			origin
		);
		const name = validateRepoName(input.name ?? input.repo.name);
		const description = input.description?.trim() || undefined;

		jobs.push({
			name,
			knotDid: knotDidOf(input.knot),
			sourceUrl: validateUrlSource(cloneUrl),
			...(input.repo.private === true ? { private: true } : {}),
			...(description !== undefined ? { description } : {})
		});
	}
	return createMigrationTask(agent, migratorUrl, crypto.randomUUID(), jobs, options);
};

const normalizeSshKey = (rawKey: string): string | null => {
	const parts = rawKey.trim().split(/\s+/);
	if (parts.length < 2) return null;
	const [algorithm, base64Blob] = parts;
	if (!/^[a-zA-Z0-9@._-]+$/.test(algorithm)) return null;
	if (!/^[A-Za-z0-9+/=]+$/.test(base64Blob)) return null;
	return `${algorithm} ${base64Blob}`;
};

interface ImportGitHubProfileEndpoints {
	bobbinUrl?: string;
	deliberiUrl: string;
	fetch?: Fetch;
}

interface ImportGitHubProfileOptions {
	avatar: boolean;
	keys: boolean;
	email: boolean;
}

interface ImportedGitHubKey {
	rkey: string;
	name: string;
	key: string;
}

interface ImportGitHubProfileResult {
	imported: string[];
	errors: string[];
	keys: ImportedGitHubKey[];
}

export const importGitHubProfile = async (
	agent: OAuthUserAgent,
	endpoints: ImportGitHubProfileEndpoints,
	account: GitHubAccount,
	options: ImportGitHubProfileOptions
): Promise<ImportGitHubProfileResult> => {
	const fetchFn = endpoints.fetch ?? globalThis.fetch;
	const imported: string[] = [];
	const errors: string[] = [];

	if (options.avatar) {
		try {
			const res = await fetchFn("/_internal/github/avatar");
			if (!res.ok) {
				throw new Error(`failed to fetch avatar (${res.status})`);
			}
			const rawBlob = await res.blob();
			const contentType = res.headers.get("content-type")?.split(";")[0]?.trim();
			const image =
				contentType && !rawBlob.type ? new Blob([rawBlob], { type: contentType }) : rawBlob;
			const avatarBlob = await uploadProfileAvatar(agent, image);

			const existing = await readRecord<ProfileRecord>(agent, PROFILE_COLLECTION, SELF_RKEY);
			const existingProfile = existing?.value;
			const existingCid = existing?.written?.cid;

			const record: ProfileRecord = {
				$type: "org.tangled.actor.profile",
				...(existingProfile ?? {}),
				avatar: avatarBlob
			};

			if (existingProfile) {
				await putRecord(agent, PROFILE_COLLECTION, SELF_RKEY, record, existingCid);
			} else {
				await createRecord(agent, PROFILE_COLLECTION, record, SELF_RKEY);
			}
			imported.push("avatar");
		} catch (cause) {
			errors.push(`Failed to import avatar: ${messageOf(cause)}`);
		}
	}

	const writtenKeys: ImportedGitHubKey[] = [];

	if (options.keys) {
		try {
			const rpc = createClient(agent);
			const existingTokens = new Set<string>();
			let cursor: string | undefined;

			do {
				const page = await ok(
					rpc.call(listRecordsSchema, {
						params: {
							repo: agent.sub,
							collection: PUBLIC_KEY_COLLECTION,
							limit: 100,
							...(cursor ? { cursor } : {})
						}
					})
				);
				for (const rec of page.records) {
					const val = rec.value as { publicKey?: unknown };
					if (typeof val?.publicKey === "string") {
						const token = normalizeSshKey(val.publicKey);
						if (token) existingTokens.add(token);
					}
				}
				cursor = page.cursor;
			} while (cursor);

			const seenInBatch = new Set<string>();
			for (const key of account.keys) {
				const rawKey = key.key?.trim() ?? "";
				const token = normalizeSshKey(rawKey);
				if (!token) {
					errors.push(`Invalid SSH key format for key ${key.title || key.id}.`);
					continue;
				}
				if (existingTokens.has(token) || seenInBatch.has(token)) {
					continue;
				}
				seenInBatch.add(token);

				try {
					const title = key.title?.trim() || `github-${key.id}`;
					const written = await createPubKey(agent, title, rawKey);
					writtenKeys.push({ rkey: written.rkey, name: title, key: rawKey });
					existingTokens.add(token);
					imported.push(`key:${key.id}`);
				} catch (cause) {
					errors.push(`Failed to import key ${key.title || key.id}: ${messageOf(cause)}`);
				}
			}
		} catch (cause) {
			errors.push(`Failed to load existing keys: ${messageOf(cause)}`);
		}
	}

	if (options.email) {
		if (!account.email || !account.email.trim()) {
			errors.push("GitHub account does not have an email address.");
		} else {
			const targetEmail = account.email.trim();
			try {
				const deliberi = createDeliberiClient({
					deliberiUrl: endpoints.deliberiUrl,
					agent,
					fetch: fetchFn
				});
				const { emails } = await listEmails(deliberi);
				const normalizedTarget = targetEmail.toLowerCase();
				const exists = emails.some((e) => e.address.toLowerCase() === normalizedTarget);

				if (!exists) {
					await addEmail(deliberi, targetEmail);
					imported.push(`email:${targetEmail} (verification required)`);
				}
			} catch (cause) {
				errors.push(`Failed to import email ${targetEmail}: ${messageOf(cause)}`);
			}
		}
	}

	return { imported, errors, keys: writtenKeys };
};