@hex4c59/pi-ext-config-sync 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/github.ts ADDED
@@ -0,0 +1,664 @@
1
+ import { isRecord, normalizeRelativePath } from "./files.ts";
2
+ import { sha256Hex } from "./hash.ts";
3
+ import {
4
+ AGENT_PATH_PREFIX,
5
+ MANIFEST_PATH,
6
+ MANIFEST_TOOL,
7
+ SECRETS_PATH,
8
+ SyncError,
9
+ } from "./types.ts";
10
+ import type { RemoteFile, RemoteSnapshot, SyncManifest } from "./types.ts";
11
+
12
+ const GITHUB_API = "https://api.github.com";
13
+ const GITHUB_WEB = "https://github.com";
14
+ const USER_AGENT = "pi-config-sync";
15
+ const REQUEST_TIMEOUT_MS = 30_000;
16
+ const MAX_BLOB_BYTES = 10 * 1024 * 1024;
17
+ const MAX_SNAPSHOT_BYTES = 60 * 1024 * 1024;
18
+ const MAX_MANIFEST_FILES = 2000;
19
+ const BLOB_UPLOAD_CONCURRENCY = 4;
20
+
21
+ export class GithubError extends SyncError {
22
+ readonly status: number | undefined;
23
+
24
+ constructor(message: string, status?: number) {
25
+ super(message);
26
+ this.name = "GithubError";
27
+ this.status = status;
28
+ }
29
+ }
30
+
31
+ export interface DeviceCodeInfo {
32
+ deviceCode: string;
33
+ userCode: string;
34
+ verificationUri: string;
35
+ expiresIn: number;
36
+ interval: number;
37
+ }
38
+
39
+ export interface ViewerInfo {
40
+ login: string;
41
+ scopes: string[];
42
+ }
43
+
44
+ export interface RepoInfo {
45
+ owner: string;
46
+ name: string;
47
+ fullName: string;
48
+ private: boolean;
49
+ defaultBranch: string;
50
+ }
51
+
52
+ export interface PushSnapshotOptions {
53
+ token: string;
54
+ owner: string;
55
+ name: string;
56
+ branch: string;
57
+ expectedCommit: string | null;
58
+ message: string;
59
+ files: Array<{ path: string; bytes: Buffer }>;
60
+ signal?: AbortSignal;
61
+ }
62
+
63
+ export async function requestDeviceCode(
64
+ clientId: string,
65
+ signal?: AbortSignal,
66
+ ): Promise<DeviceCodeInfo> {
67
+ const data = await postForm(
68
+ `${GITHUB_WEB}/login/device/code`,
69
+ { client_id: clientId, scope: "repo" },
70
+ signal,
71
+ );
72
+ if (!isRecord(data)) throw new GithubError("GitHub returned an unreadable device code response.");
73
+ if (typeof data.error === "string") throw new GithubError(deviceFlowError(data.error), 400);
74
+ const deviceCode = data.device_code;
75
+ const userCode = data.user_code;
76
+ const verificationUri = data.verification_uri;
77
+ const expiresIn = data.expires_in;
78
+ const interval = data.interval;
79
+ if (
80
+ typeof deviceCode !== "string"
81
+ || typeof userCode !== "string"
82
+ || typeof verificationUri !== "string"
83
+ || typeof expiresIn !== "number"
84
+ || !Number.isFinite(expiresIn)
85
+ || typeof interval !== "number"
86
+ || !Number.isFinite(interval)
87
+ ) {
88
+ throw new GithubError("GitHub returned an incomplete device code response.");
89
+ }
90
+ return {
91
+ deviceCode,
92
+ userCode,
93
+ verificationUri,
94
+ expiresIn,
95
+ interval: Math.max(5, Math.floor(interval)),
96
+ };
97
+ }
98
+
99
+ export async function pollDeviceToken(
100
+ clientId: string,
101
+ device: DeviceCodeInfo,
102
+ onPending: () => void,
103
+ signal?: AbortSignal,
104
+ ): Promise<string> {
105
+ let interval = device.interval;
106
+ const deadline = Date.now() + device.expiresIn * 1000;
107
+ while (true) {
108
+ if (Date.now() >= deadline) throw new GithubError(expiredLoginMessage());
109
+ await delay(interval * 1000, signal);
110
+ if (Date.now() >= deadline) throw new GithubError(expiredLoginMessage());
111
+ const data = await postForm(
112
+ `${GITHUB_WEB}/login/oauth/access_token`,
113
+ {
114
+ client_id: clientId,
115
+ device_code: device.deviceCode,
116
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
117
+ },
118
+ signal,
119
+ );
120
+ if (!isRecord(data)) throw new GithubError("GitHub returned an unreadable token response.");
121
+ if (typeof data.access_token === "string" && data.access_token.length > 0) {
122
+ return data.access_token;
123
+ }
124
+ const error = typeof data.error === "string" ? data.error : "";
125
+ if (error === "authorization_pending") {
126
+ onPending();
127
+ continue;
128
+ }
129
+ if (error === "slow_down") {
130
+ interval += 5;
131
+ onPending();
132
+ continue;
133
+ }
134
+ if (error === "expired_token") throw new GithubError(expiredLoginMessage());
135
+ if (error === "access_denied") throw new GithubError("GitHub login was denied.");
136
+ throw new GithubError(deviceFlowError(error), 400);
137
+ }
138
+ }
139
+
140
+ export async function getViewer(token: string, signal?: AbortSignal): Promise<ViewerInfo> {
141
+ const { data, headers } = await apiRequest(token, "GET", "/user", undefined, signal);
142
+ if (!isRecord(data) || typeof data.login !== "string") {
143
+ throw new GithubError("GitHub did not return a login name.", 500);
144
+ }
145
+ const scopeHeader = headers.get("x-oauth-scopes");
146
+ const scopes = scopeHeader === null
147
+ ? []
148
+ : scopeHeader.split(",").map((scope) => scope.trim()).filter((scope) => scope.length > 0);
149
+ return { login: data.login, scopes };
150
+ }
151
+
152
+ export async function getRepo(
153
+ token: string,
154
+ owner: string,
155
+ name: string,
156
+ signal?: AbortSignal,
157
+ ): Promise<RepoInfo | null> {
158
+ try {
159
+ const { data } = await apiRequest(token, "GET", repoPath(owner, name), undefined, signal);
160
+ return parseRepo(data, owner, name);
161
+ } catch (error) {
162
+ if (isNotFound(error)) return null;
163
+ throw error;
164
+ }
165
+ }
166
+
167
+ export async function createRepo(
168
+ token: string,
169
+ name: string,
170
+ signal?: AbortSignal,
171
+ ): Promise<RepoInfo> {
172
+ const { data } = await apiRequest(token, "POST", "/user/repos", {
173
+ name,
174
+ private: true,
175
+ auto_init: false,
176
+ description: "Pi configuration synced by pi-config-sync",
177
+ }, signal);
178
+ return parseRepo(data, "", name);
179
+ }
180
+
181
+ // Git Data API 在空仓库上返回 409,先用 Contents API 建立首个提交。
182
+ export async function initializeRepo(
183
+ token: string,
184
+ owner: string,
185
+ name: string,
186
+ branch: string,
187
+ signal?: AbortSignal,
188
+ ): Promise<void> {
189
+ await apiRequest(token, "PUT", `${repoPath(owner, name)}/contents/.pi-config-sync-init`, {
190
+ message: "Initialize Pi configuration sync",
191
+ content: Buffer.from("pi-config-sync\n", "utf8").toString("base64"),
192
+ branch,
193
+ }, signal);
194
+ }
195
+
196
+ export async function fetchSnapshot(
197
+ token: string,
198
+ owner: string,
199
+ name: string,
200
+ branch: string,
201
+ signal?: AbortSignal,
202
+ ): Promise<RemoteSnapshot> {
203
+ const commit = await getBranchCommit(token, owner, name, branch, signal);
204
+ if (commit === null) {
205
+ return { commit: "", branch, manifest: null, files: new Map(), foreign: false };
206
+ }
207
+ const treeSha = await getCommitTree(token, owner, name, commit, signal);
208
+ const tree = await getTree(token, owner, name, treeSha, signal);
209
+ if (tree.truncated) {
210
+ throw new GithubError("The repository tree is too large for config-sync.", 413);
211
+ }
212
+ const blobs = tree.entries.filter((entry) => entry.type === "blob");
213
+ const manifestEntry = blobs.find((entry) => entry.path === MANIFEST_PATH);
214
+ if (manifestEntry === undefined) {
215
+ return { commit, branch, manifest: null, files: new Map(), foreign: blobs.length > 0 };
216
+ }
217
+ const manifestBytes = await fetchBlob(token, owner, name, manifestEntry.sha, signal);
218
+ const manifest = parseManifest(manifestBytes);
219
+ const files = new Map<string, RemoteFile>();
220
+ let totalBytes = 0;
221
+ for (const path of Object.keys(manifest.files).sort()) {
222
+ if (!isAllowedRemotePath(path)) {
223
+ throw new GithubError(`Remote manifest lists an unexpected path: ${path}`);
224
+ }
225
+ const entry = blobs.find((candidate) => candidate.path === path);
226
+ if (entry === undefined) {
227
+ throw new GithubError(`Remote manifest lists a missing file: ${path}`);
228
+ }
229
+ if (entry.size !== undefined && entry.size > MAX_BLOB_BYTES) {
230
+ throw new GithubError(`Remote file is too large: ${path}`, 413);
231
+ }
232
+ const bytes = await fetchBlob(token, owner, name, entry.sha, signal);
233
+ totalBytes += bytes.length;
234
+ if (totalBytes > MAX_SNAPSHOT_BYTES) {
235
+ throw new GithubError("Remote configuration is too large for config-sync.", 413);
236
+ }
237
+ const hash = sha256Hex(bytes);
238
+ if (hash !== manifest.files[path]) {
239
+ throw new GithubError(`Remote file hash mismatch: ${path}`, 409);
240
+ }
241
+ files.set(path, { path, bytes, sha256: hash });
242
+ }
243
+ return { commit, branch, manifest, files, foreign: false };
244
+ }
245
+
246
+ export async function pushSnapshot(options: PushSnapshotOptions): Promise<string> {
247
+ const { token, owner, name, branch, expectedCommit, message, files, signal } = options;
248
+ for (const file of files) {
249
+ if (!isAllowedPushPath(file.path)) {
250
+ throw new GithubError(`Refusing to push unexpected path: ${file.path}`);
251
+ }
252
+ }
253
+ const entries = await mapLimit(files, BLOB_UPLOAD_CONCURRENCY, async (file) => {
254
+ const { data } = await apiRequest(token, "POST", `${repoPath(owner, name)}/git/blobs`, {
255
+ content: file.bytes.toString("base64"),
256
+ encoding: "base64",
257
+ }, signal);
258
+ if (!isRecord(data) || typeof data.sha !== "string") {
259
+ throw new GithubError("GitHub did not return a blob hash.", 500);
260
+ }
261
+ return { path: file.path, mode: "100644", type: "blob", sha: data.sha };
262
+ });
263
+ entries.sort((left, right) => left.path.localeCompare(right.path));
264
+ const treeResponse = await apiRequest(token, "POST", `${repoPath(owner, name)}/git/trees`, {
265
+ tree: entries,
266
+ }, signal);
267
+ if (!isRecord(treeResponse.data) || typeof treeResponse.data.sha !== "string") {
268
+ throw new GithubError("GitHub did not return a tree hash.", 500);
269
+ }
270
+ const parents = expectedCommit === null || expectedCommit.length === 0 ? [] : [expectedCommit];
271
+ const commitResponse = await apiRequest(token, "POST", `${repoPath(owner, name)}/git/commits`, {
272
+ message,
273
+ tree: treeResponse.data.sha,
274
+ parents,
275
+ }, signal);
276
+ if (!isRecord(commitResponse.data) || typeof commitResponse.data.sha !== "string") {
277
+ throw new GithubError("GitHub did not return a commit hash.", 500);
278
+ }
279
+ const commit = commitResponse.data.sha;
280
+ if (parents.length === 0) {
281
+ try {
282
+ await apiRequest(token, "POST", `${repoPath(owner, name)}/git/refs`, {
283
+ ref: `refs/heads/${branch}`,
284
+ sha: commit,
285
+ }, signal);
286
+ } catch (error) {
287
+ if (error instanceof GithubError && (error.status === 422 || error.status === 409)) {
288
+ throw new GithubError("The remote branch changed during push. Run /sync pull first.", 409);
289
+ }
290
+ throw error;
291
+ }
292
+ } else {
293
+ try {
294
+ await apiRequest(token, "PATCH", `${repoPath(owner, name)}/git/refs/heads/${branch}`, {
295
+ sha: commit,
296
+ force: false,
297
+ }, signal);
298
+ } catch (error) {
299
+ if (error instanceof GithubError && (error.status === 422 || error.status === 409)) {
300
+ throw new GithubError("The remote branch changed during push. Run /sync pull first.", 409);
301
+ }
302
+ throw error;
303
+ }
304
+ }
305
+ return commit;
306
+ }
307
+
308
+ export function splitRepo(fullName: string): { owner: string; name: string } {
309
+ const parts = fullName.split("/");
310
+ if (parts.length !== 2) throw new SyncError("Repository must be written as owner/name.");
311
+ const owner = parts[0] ?? "";
312
+ const name = parts[1] ?? "";
313
+ if (owner.length === 0 || name.length === 0) {
314
+ throw new SyncError("Repository must be written as owner/name.");
315
+ }
316
+ return { owner, name };
317
+ }
318
+
319
+ export function assertSafeBranch(branch: string): string {
320
+ if (branch.length === 0) return branch;
321
+ if (
322
+ !/^[A-Za-z0-9._/-]+$/.test(branch)
323
+ || branch.startsWith("/")
324
+ || branch.endsWith("/")
325
+ || branch.includes("//")
326
+ || branch.includes("..")
327
+ || branch.endsWith(".lock")
328
+ ) {
329
+ throw new SyncError(`Unsafe branch name: ${branch}`);
330
+ }
331
+ return branch;
332
+ }
333
+
334
+ export function isNotFound(error: unknown): boolean {
335
+ return error instanceof GithubError && error.status === 404;
336
+ }
337
+
338
+ function repoPath(owner: string, name: string): string {
339
+ return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`;
340
+ }
341
+
342
+ function isAllowedRemotePath(path: string): boolean {
343
+ if (path === SECRETS_PATH) return true;
344
+ if (!path.startsWith(AGENT_PATH_PREFIX)) return false;
345
+ try {
346
+ normalizeRelativePath(path.slice(AGENT_PATH_PREFIX.length));
347
+ return true;
348
+ } catch {
349
+ return false;
350
+ }
351
+ }
352
+
353
+ function isAllowedPushPath(path: string): boolean {
354
+ return path === MANIFEST_PATH || isAllowedRemotePath(path);
355
+ }
356
+
357
+ async function getBranchCommit(
358
+ token: string,
359
+ owner: string,
360
+ name: string,
361
+ branch: string,
362
+ signal?: AbortSignal,
363
+ ): Promise<string | null> {
364
+ try {
365
+ const { data } = await apiRequest(
366
+ token,
367
+ "GET",
368
+ `${repoPath(owner, name)}/git/ref/heads/${branch}`,
369
+ undefined,
370
+ signal,
371
+ );
372
+ if (isRecord(data) && isRecord(data.object) && typeof data.object.sha === "string") {
373
+ return data.object.sha;
374
+ }
375
+ throw new GithubError("GitHub returned an unreadable branch reference.", 500);
376
+ } catch (error) {
377
+ // 新建的空仓库在 branch ref 端点返回 409,而不是 404。
378
+ if (isMissingBranch(error)) return null;
379
+ throw error;
380
+ }
381
+ }
382
+
383
+ function isMissingBranch(error: unknown): boolean {
384
+ if (isNotFound(error)) return true;
385
+ return error instanceof GithubError
386
+ && error.status === 409
387
+ && /repository is empty/i.test(error.message);
388
+ }
389
+
390
+ async function getCommitTree(
391
+ token: string,
392
+ owner: string,
393
+ name: string,
394
+ commit: string,
395
+ signal?: AbortSignal,
396
+ ): Promise<string> {
397
+ const { data } = await apiRequest(
398
+ token,
399
+ "GET",
400
+ `${repoPath(owner, name)}/git/commits/${commit}`,
401
+ undefined,
402
+ signal,
403
+ );
404
+ if (!isRecord(data) || !isRecord(data.tree) || typeof data.tree.sha !== "string") {
405
+ throw new GithubError("GitHub returned an unreadable commit.", 500);
406
+ }
407
+ return data.tree.sha;
408
+ }
409
+
410
+ async function getTree(
411
+ token: string,
412
+ owner: string,
413
+ name: string,
414
+ treeSha: string,
415
+ signal?: AbortSignal,
416
+ ): Promise<{ entries: Array<{ path: string; type: string; sha: string; size?: number }>; truncated: boolean }> {
417
+ const { data } = await apiRequest(
418
+ token,
419
+ "GET",
420
+ `${repoPath(owner, name)}/git/trees/${treeSha}?recursive=1`,
421
+ undefined,
422
+ signal,
423
+ );
424
+ if (!isRecord(data) || !Array.isArray(data.tree)) {
425
+ throw new GithubError("GitHub returned an unreadable tree.", 500);
426
+ }
427
+ const entries: Array<{ path: string; type: string; sha: string; size?: number }> = [];
428
+ for (const entry of data.tree) {
429
+ if (!isRecord(entry)) continue;
430
+ if (typeof entry.path !== "string" || typeof entry.type !== "string" || typeof entry.sha !== "string") {
431
+ continue;
432
+ }
433
+ entries.push({
434
+ path: entry.path,
435
+ type: entry.type,
436
+ sha: entry.sha,
437
+ size: typeof entry.size === "number" ? entry.size : undefined,
438
+ });
439
+ }
440
+ return { entries, truncated: data.truncated === true };
441
+ }
442
+
443
+ async function fetchBlob(
444
+ token: string,
445
+ owner: string,
446
+ name: string,
447
+ sha: string,
448
+ signal?: AbortSignal,
449
+ ): Promise<Buffer> {
450
+ const { data } = await apiRequest(
451
+ token,
452
+ "GET",
453
+ `${repoPath(owner, name)}/git/blobs/${sha}`,
454
+ undefined,
455
+ signal,
456
+ );
457
+ if (!isRecord(data) || typeof data.content !== "string") {
458
+ throw new GithubError("GitHub returned an unreadable blob.", 500);
459
+ }
460
+ const bytes = Buffer.from(data.content.replace(/\s+/g, ""), "base64");
461
+ if (bytes.length > MAX_BLOB_BYTES) {
462
+ throw new GithubError("A remote file is too large for config-sync.", 413);
463
+ }
464
+ return bytes;
465
+ }
466
+
467
+ function parseManifest(bytes: Buffer): SyncManifest {
468
+ let parsed: unknown;
469
+ try {
470
+ parsed = JSON.parse(bytes.toString("utf8"));
471
+ } catch {
472
+ throw new GithubError("Remote manifest.json is not valid JSON.", 422);
473
+ }
474
+ if (!isRecord(parsed) || parsed.version !== 1 || parsed.tool !== MANIFEST_TOOL) {
475
+ throw new GithubError("The repository is not a pi-config-sync repository.", 422);
476
+ }
477
+ if (typeof parsed.deviceId !== "string" || typeof parsed.pushedAt !== "string") {
478
+ throw new GithubError("Remote manifest is incomplete.", 422);
479
+ }
480
+ if (!isRecord(parsed.files)) throw new GithubError("Remote manifest has no file list.", 422);
481
+ const files: Record<string, string> = {};
482
+ const paths = Object.keys(parsed.files);
483
+ if (paths.length > MAX_MANIFEST_FILES) {
484
+ throw new GithubError("Remote manifest lists too many files.", 413);
485
+ }
486
+ for (const path of paths) {
487
+ const hash = parsed.files[path];
488
+ if (typeof hash !== "string" || !/^[0-9a-f]{64}$/.test(hash)) {
489
+ throw new GithubError(`Remote manifest has an invalid hash for ${path}.`, 422);
490
+ }
491
+ files[path] = hash;
492
+ }
493
+ return {
494
+ version: 1,
495
+ tool: MANIFEST_TOOL,
496
+ deviceId: parsed.deviceId,
497
+ pushedAt: parsed.pushedAt,
498
+ files,
499
+ };
500
+ }
501
+
502
+ function parseRepo(data: unknown, owner: string, name: string): RepoInfo {
503
+ if (!isRecord(data)) throw new GithubError("GitHub returned an unreadable repository.", 500);
504
+ const fullName = typeof data.full_name === "string" ? data.full_name : `${owner}/${name}`;
505
+ const defaultBranch = typeof data.default_branch === "string" && data.default_branch.length > 0
506
+ ? data.default_branch
507
+ : "main";
508
+ return {
509
+ owner,
510
+ name,
511
+ fullName,
512
+ private: data.private === true,
513
+ defaultBranch,
514
+ };
515
+ }
516
+
517
+ async function apiRequest(
518
+ token: string,
519
+ method: string,
520
+ path: string,
521
+ body: unknown,
522
+ signal?: AbortSignal,
523
+ ): Promise<{ data: unknown; headers: Headers }> {
524
+ const headers: Record<string, string> = {
525
+ Accept: "application/vnd.github+json",
526
+ Authorization: `Bearer ${token}`,
527
+ "X-GitHub-Api-Version": "2022-11-28",
528
+ "User-Agent": USER_AGENT,
529
+ };
530
+ if (body !== undefined) headers["Content-Type"] = "application/json";
531
+ let response: Response;
532
+ try {
533
+ response = await fetch(`${GITHUB_API}${path}`, {
534
+ method,
535
+ headers,
536
+ body: body === undefined ? undefined : JSON.stringify(body),
537
+ signal: requestSignal(signal),
538
+ });
539
+ } catch (error) {
540
+ if (isTimeoutError(error)) throw new GithubError("GitHub request timed out.", 408);
541
+ throw error;
542
+ }
543
+ const text = await response.text();
544
+ let data: unknown;
545
+ try {
546
+ data = text.length === 0 ? undefined : JSON.parse(text);
547
+ } catch {
548
+ data = undefined;
549
+ }
550
+ if (!response.ok) {
551
+ throw apiError(response, data);
552
+ }
553
+ return { data, headers: response.headers };
554
+ }
555
+
556
+ function apiError(response: Response, data: unknown): GithubError {
557
+ if (response.status === 401) {
558
+ return new GithubError("GitHub token is invalid or expired. Run /sync login.", 401);
559
+ }
560
+ if (response.headers.get("x-ratelimit-remaining") === "0") {
561
+ const reset = response.headers.get("x-ratelimit-reset");
562
+ const when = reset === null ? "later" : new Date(Number(reset) * 1000).toISOString();
563
+ return new GithubError(`GitHub API rate limit reached; resets at ${when}.`, response.status);
564
+ }
565
+ const message = isRecord(data) && typeof data.message === "string"
566
+ ? data.message
567
+ : response.statusText;
568
+ return new GithubError(`GitHub request failed (${response.status}): ${message}`, response.status);
569
+ }
570
+
571
+ function requestSignal(signal?: AbortSignal): AbortSignal {
572
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
573
+ return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
574
+ }
575
+
576
+ async function postForm(
577
+ url: string,
578
+ fields: Record<string, string>,
579
+ signal?: AbortSignal,
580
+ ): Promise<unknown> {
581
+ let response: Response;
582
+ try {
583
+ response = await fetch(url, {
584
+ method: "POST",
585
+ headers: {
586
+ Accept: "application/json",
587
+ "Content-Type": "application/x-www-form-urlencoded",
588
+ "User-Agent": USER_AGENT,
589
+ },
590
+ body: new URLSearchParams(fields),
591
+ signal: requestSignal(signal),
592
+ });
593
+ } catch (error) {
594
+ if (isTimeoutError(error)) throw new GithubError("GitHub request timed out.", 408);
595
+ throw error;
596
+ }
597
+ const text = await response.text();
598
+ let data: unknown;
599
+ try {
600
+ data = text.length === 0 ? undefined : JSON.parse(text);
601
+ } catch {
602
+ throw new GithubError("GitHub returned an unreadable response.", response.status);
603
+ }
604
+ if (!response.ok) throw apiError(response, data);
605
+ return data;
606
+ }
607
+
608
+ function deviceFlowError(code: string): string {
609
+ if (code === "device_flow_disabled") {
610
+ return "Device flow is disabled for this OAuth App. Enable it in the GitHub App settings.";
611
+ }
612
+ if (code === "incorrect_client_credentials") {
613
+ return "GitHub rejected the OAuth client ID. Run /sync setup to set the correct client ID.";
614
+ }
615
+ if (code === "unsupported_grant_type") return "GitHub does not support device flow for this App.";
616
+ return code.length > 0 ? `GitHub login failed: ${code}` : "GitHub login failed.";
617
+ }
618
+
619
+ function expiredLoginMessage(): string {
620
+ return "The GitHub login code expired. Run /sync login again.";
621
+ }
622
+
623
+ function isTimeoutError(error: unknown): boolean {
624
+ return typeof error === "object"
625
+ && error !== null
626
+ && "name" in error
627
+ && error.name === "TimeoutError";
628
+ }
629
+
630
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
631
+ return new Promise((resolve, reject) => {
632
+ if (signal?.aborted === true) {
633
+ reject(signal.reason);
634
+ return;
635
+ }
636
+ const timer = setTimeout(() => {
637
+ signal?.removeEventListener("abort", onAbort);
638
+ resolve();
639
+ }, ms);
640
+ const onAbort = () => {
641
+ clearTimeout(timer);
642
+ reject(signal?.reason);
643
+ };
644
+ signal?.addEventListener("abort", onAbort, { once: true });
645
+ });
646
+ }
647
+
648
+ async function mapLimit<T, R>(
649
+ items: T[],
650
+ limit: number,
651
+ fn: (item: T) => Promise<R>,
652
+ ): Promise<R[]> {
653
+ const results = new Array<R>(items.length);
654
+ let next = 0;
655
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
656
+ while (true) {
657
+ const index = next++;
658
+ if (index >= items.length) return;
659
+ results[index] = await fn(items[index]);
660
+ }
661
+ });
662
+ await Promise.all(workers);
663
+ return results;
664
+ }
package/src/hash.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export function sha256Hex(bytes: Buffer | string): string {
4
+ return createHash("sha256").update(bytes).digest("hex");
5
+ }
6
+
7
+ export function stableStringify(value: unknown): string {
8
+ return JSON.stringify(sortValue(value));
9
+ }
10
+
11
+ function sortValue(value: unknown): unknown {
12
+ if (Array.isArray(value)) return value.map(sortValue);
13
+ if (typeof value === "object" && value !== null) {
14
+ const source = value as Record<string, unknown>;
15
+ const sorted: Record<string, unknown> = {};
16
+ for (const key of Object.keys(source).sort()) {
17
+ sorted[key] = sortValue(source[key]);
18
+ }
19
+ return sorted;
20
+ }
21
+ return value;
22
+ }