forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·9812 lines (9710 loc) · 313 KB
/
main.js
File metadata and controls
executable file
·9812 lines (9710 loc) · 313 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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
import { PATHS, closeDb, configPath, countActiveAdminKeys, countActiveDebugKeys, createKey, ensurePaths, findKeyByHash, findKeyById, getDb, initDb, isDebugActive, listKeys, revokeKey, setDebugEnabled, tracesDir, updateKeyScope } from "./keys-BntVlM1P.js";
import { defineCommand, runMain } from "citty";
import consola, { consola as consola$1 } from "consola";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import crypto$1, { randomUUID } from "node:crypto";
import fs$1 from "node:fs";
import { z } from "zod";
import clipboard from "clipboardy";
import { serve } from "srvx";
import invariant from "tiny-invariant";
import { getProxyForUrl } from "proxy-from-env";
import { Agent, ProxyAgent, setGlobalDispatcher } from "undici";
import { execSync, spawnSync } from "node:child_process";
import process$1 from "node:process";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import { Fragment, jsx, jsxs } from "hono/jsx/jsx-runtime";
import { streamSSE } from "hono/streaming";
import { events } from "fetch-event-stream";
//#region src/lib/state.ts
const state = {
accountType: "individual",
manualApprove: false,
rateLimitWait: false,
showToken: false
};
//#endregion
//#region src/services/version-cache.ts
const VERSION_CACHE_TTL_MS = 1440 * 60 * 1e3;
//#endregion
//#region src/services/get-copilot-chat-version.ts
/**
* Hard-coded fallback used when both the Marketplace API and the
* vscode-copilot-release GitHub releases are unreachable.
*
* Bump this periodically. Last bumped 2026-05-19 based on Marketplace
* extension query returning 0.48.1 for GitHub.copilot-chat.
*/
const FALLBACK = "0.48.1";
let cache$1;
async function fetchFromMarketplace() {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 5e3);
try {
const parsed = (await (await fetch("https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json;api-version=3.0-preview.1"
},
body: JSON.stringify({
filters: [{ criteria: [{
filterType: 7,
value: "GitHub.copilot-chat"
}] }],
flags: 529
}),
signal: controller.signal
})).json())?.results?.[0]?.extensions?.[0]?.versions?.[0]?.version;
if (typeof parsed !== "string" || !parsed) throw new Error("Unexpected response shape");
return parsed;
} finally {
clearTimeout(timeout);
}
}
async function getCopilotChatVersion() {
if (cache$1 && Date.now() - cache$1.fetchedAt < VERSION_CACHE_TTL_MS) return cache$1.version;
let fetched = null;
try {
fetched = await fetchFromMarketplace();
} catch {
consola.warn("Failed to fetch Copilot Chat version from Marketplace, using fallback");
}
const isValid = fetched !== null && /^\d+\.\d+\.\d+$/.test(fetched);
const version = isValid ? fetched : FALLBACK;
if (isValid) cache$1 = {
version,
fetchedAt: Date.now()
};
else if (fetched !== null) {
const safeVersion = fetched.slice(0, 40).replaceAll(/[^\x20-\x7E]/g, "?");
consola.warn(`Invalid version format received: ${safeVersion}, using fallback`);
}
return version;
}
//#endregion
//#region src/services/get-vscode-version.ts
/**
* Hard-coded fallback used when both the official VSCode update API and the
* AUR PKGBUILD mirror are unreachable (offline / firewall / DNS issue).
*
* Bump this periodically — Copilot's upstream is lenient about
* `editor-version` header values but a wildly stale string could in theory
* trip future anti-abuse heuristics. Last bumped 2026-05-19 based on
* `update.code.visualstudio.com/api/releases/stable` returning 1.120.0.
*/
const FALLBACK$1 = "1.120.0";
let cache;
async function fetchFromOfficialApi() {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 5e3);
try {
const versions = await (await fetch("https://update.code.visualstudio.com/api/releases/stable", { signal: controller.signal })).json();
if (Array.isArray(versions) && versions.length > 0 && versions[0]) return versions[0];
throw new Error("Unexpected response shape");
} finally {
clearTimeout(timeout);
}
}
async function fetchFromAur() {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 5e3);
try {
const match = (await (await fetch("https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=visual-studio-code-bin", { signal: controller.signal })).text()).match(/pkgver=(\d+\.\d+\.\d+)/);
if (match?.[1]) return match[1];
throw new Error("Version not found in PKGBUILD");
} finally {
clearTimeout(timeout);
}
}
async function getVSCodeVersion() {
if (cache && Date.now() - cache.fetchedAt < VERSION_CACHE_TTL_MS) return cache.version;
let fetched = null;
try {
fetched = await fetchFromOfficialApi();
} catch {
try {
fetched = await fetchFromAur();
} catch {
consola.warn("Failed to fetch VS Code version from all sources, using fallback");
}
}
const isValid = fetched !== null && /^\d+\.\d+\.\d+$/.test(fetched);
const version = isValid ? fetched : FALLBACK$1;
if (isValid) cache = {
version,
fetchedAt: Date.now()
};
else if (fetched !== null) {
const safeVersion = fetched.slice(0, 40).replaceAll(/[^\x20-\x7E]/g, "?");
consola.warn(`Invalid version format received: ${safeVersion}, using fallback`);
}
return version;
}
//#endregion
//#region src/lib/api-config.ts
const standardHeaders = () => ({
"content-type": "application/json",
accept: "application/json"
});
const API_VERSION = "2025-04-01";
const copilotBaseUrl = (state$1) => state$1.accountType === "individual" ? "https://api.githubcopilot.com" : `https://api.${state$1.accountType}.githubcopilot.com`;
/**
* Headers sent with every upstream request to mimic VS Code Copilot Chat traffic.
*
* Header sources:
* - Authorization — Copilot token from GitHub OAuth flow
* - editor-version — Auto-detected VS Code stable release (update.code.visualstudio.com)
* - editor-plugin-version — Auto-detected GitHub.copilot-chat Marketplace version
* - user-agent — Same as editor-plugin-version, GitHubCopilotChat/<version>
* - copilot-integration-id — Fixed "vscode-chat"
* - openai-intent — Fixed "conversation-panel"
* - x-github-api-version — Fixed "2025-04-01" (verify periodically against VS Code source)
* - x-request-id — Per-request UUID via crypto.randomUUID()
* - x-vscode-user-agent-library-version — Fixed "electron-fetch"
* - copilot-vision-request — Added when request includes image content
*/
const copilotHeaders = (state$1, vision = false) => {
const copilotVersion = state$1.copilotChatVersion ?? FALLBACK;
const headers = {
Authorization: `Bearer ${state$1.copilotToken}`,
"content-type": standardHeaders()["content-type"],
"copilot-integration-id": "vscode-chat",
"editor-version": `vscode/${state$1.vsCodeVersion ?? FALLBACK$1}`,
"editor-plugin-version": `copilot-chat/${copilotVersion}`,
"user-agent": `GitHubCopilotChat/${copilotVersion}`,
"openai-intent": "conversation-panel",
"x-github-api-version": API_VERSION,
"x-request-id": randomUUID(),
"x-vscode-user-agent-library-version": "electron-fetch"
};
if (vision) headers["copilot-vision-request"] = "true";
return headers;
};
const GITHUB_API_BASE_URL = "https://api.github.com";
const githubHeaders = (state$1) => {
const copilotVersion = state$1.copilotChatVersion ?? FALLBACK;
return {
...standardHeaders(),
authorization: `token ${state$1.githubToken}`,
"editor-version": `vscode/${state$1.vsCodeVersion ?? FALLBACK$1}`,
"editor-plugin-version": `copilot-chat/${copilotVersion}`,
"user-agent": `GitHubCopilotChat/${copilotVersion}`,
"x-github-api-version": API_VERSION,
"x-vscode-user-agent-library-version": "electron-fetch"
};
};
const GITHUB_BASE_URL = "https://github.com";
const GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98";
const GITHUB_APP_SCOPES = ["read:user"].join(" ");
//#endregion
//#region src/lib/error.ts
var HTTPError = class extends Error {
response;
constructor(message, response) {
super(message);
this.response = response;
}
};
async function forwardError(c, error) {
consola.error("Error occurred:", error);
if (error instanceof HTTPError) {
const errorText = await error.response.text();
let errorJson;
try {
errorJson = JSON.parse(errorText);
} catch {
errorJson = errorText;
}
consola.error("HTTP error:", errorJson);
return c.json({ error: {
message: errorText,
type: "error"
} }, error.response.status);
}
return c.json({ error: {
message: error.message,
type: "error"
} }, 500);
}
//#endregion
//#region src/services/github/get-copilot-token.ts
const getCopilotToken = async () => {
const response = await fetch(`${GITHUB_API_BASE_URL}/copilot_internal/v2/token`, { headers: githubHeaders(state) });
if (!response.ok) throw new HTTPError("Failed to get Copilot token", response);
return await response.json();
};
//#endregion
//#region src/services/github/get-device-code.ts
async function getDeviceCode() {
const response = await fetch(`${GITHUB_BASE_URL}/login/device/code`, {
method: "POST",
headers: standardHeaders(),
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
scope: GITHUB_APP_SCOPES
})
});
if (!response.ok) throw new HTTPError("Failed to get device code", response);
return await response.json();
}
//#endregion
//#region src/services/github/get-user.ts
async function getGitHubUser() {
const response = await fetch(`${GITHUB_API_BASE_URL}/user`, { headers: {
authorization: `token ${state.githubToken}`,
...standardHeaders()
} });
if (!response.ok) throw new HTTPError("Failed to get GitHub user", response);
return await response.json();
}
//#endregion
//#region src/services/copilot/get-models.ts
const getModels = async () => {
const response = await fetch(`${copilotBaseUrl(state)}/models`, { headers: copilotHeaders(state) });
if (!response.ok) throw new HTTPError("Failed to get models", response);
return await response.json();
};
//#endregion
//#region src/lib/utils.ts
const sleep = (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
const isNullish = (value) => value === null || value === void 0;
async function cacheModels() {
state.models = await getModels();
}
//#endregion
//#region src/services/github/poll-access-token.ts
async function pollAccessToken(deviceCode) {
const sleepDuration = (deviceCode.interval + 1) * 1e3;
consola.debug(`Polling access token with interval of ${sleepDuration}ms`);
while (true) {
const response = await fetch(`${GITHUB_BASE_URL}/login/oauth/access_token`, {
method: "POST",
headers: standardHeaders(),
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
device_code: deviceCode.device_code,
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
})
});
if (!response.ok) {
await sleep(sleepDuration);
consola.error("Failed to poll access token:", await response.text());
continue;
}
const json = await response.json();
consola.debug("Polling access token response:", json);
const { access_token } = json;
if (access_token) return access_token;
else await sleep(sleepDuration);
}
}
//#endregion
//#region src/lib/token.ts
const readGithubToken = () => fs.readFile(PATHS.GITHUB_TOKEN_PATH, "utf8");
const writeGithubToken = (token) => fs.writeFile(PATHS.GITHUB_TOKEN_PATH, token);
/**
* Handle for the Copilot-token refresh timer. Stored module-level so the
* shutdown hook in start.ts can stop it cleanly, AND so a re-entry into
* setupCopilotToken (e.g. from tests) doesn't leak a previous interval.
*/
let copilotTokenRefreshTimer;
/** Cancel handle for stopCopilotTokenRefresh(). */
function stopCopilotTokenRefresh() {
if (copilotTokenRefreshTimer !== void 0) {
clearInterval(copilotTokenRefreshTimer);
copilotTokenRefreshTimer = void 0;
}
}
const setupCopilotToken = async () => {
const { token, refresh_in } = await getCopilotToken();
state.copilotToken = token;
consola.debug("GitHub Copilot Token fetched successfully!");
if (state.showToken) consola.info("Copilot token:", token);
stopCopilotTokenRefresh();
const refreshInterval = (refresh_in - 60) * 1e3;
copilotTokenRefreshTimer = setInterval(() => {
consola.debug("Refreshing Copilot token");
(async () => {
try {
const { token: refreshed } = await getCopilotToken();
state.copilotToken = refreshed;
consola.debug("Copilot token refreshed");
if (state.showToken) consola.info("Refreshed Copilot token:", refreshed);
} catch (error) {
consola.error("Failed to refresh Copilot token (continuing with existing token until next attempt):", error);
}
})();
}, refreshInterval);
};
async function setupGitHubToken(options) {
try {
const githubToken = await readGithubToken();
if (githubToken && !options?.force) {
state.githubToken = githubToken;
if (state.showToken) consola.info("GitHub token:", githubToken);
await logUser();
return;
}
consola.info("Not logged in, getting new access token");
const response = await getDeviceCode();
consola.debug("Device code response:", response);
consola.info(`Please enter the code "${response.user_code}" in ${response.verification_uri}`);
const token = await pollAccessToken(response);
await writeGithubToken(token);
state.githubToken = token;
if (state.showToken) consola.info("GitHub token:", token);
await logUser();
} catch (error) {
if (error instanceof HTTPError) {
consola.error("Failed to get GitHub token:", await error.response.json());
throw error;
}
consola.error("Failed to get GitHub token:", error);
throw error;
}
}
async function logUser() {
const user = await getGitHubUser();
consola.info(`Logged in as ${user.login}`);
}
//#endregion
//#region src/auth.ts
async function runAuth(options) {
if (options.verbose) {
consola.level = 5;
consola.info("Verbose logging enabled");
}
state.showToken = options.showToken;
await ensurePaths();
await setupGitHubToken({ force: true });
consola.success("GitHub token written to", PATHS.GITHUB_TOKEN_PATH);
}
const auth = defineCommand({
meta: {
name: "auth",
description: "Run GitHub auth flow without running the server"
},
args: {
verbose: {
alias: "v",
type: "boolean",
default: false,
description: "Enable verbose logging"
},
"show-token": {
type: "boolean",
default: false,
description: "Show GitHub token on auth"
}
},
run({ args }) {
return runAuth({
verbose: args.verbose,
showToken: args["show-token"]
});
}
});
//#endregion
//#region src/services/github/get-copilot-usage.ts
const getCopilotUsage = async () => {
const response = await fetch(`${GITHUB_API_BASE_URL}/copilot_internal/user`, { headers: githubHeaders(state) });
if (!response.ok) throw new HTTPError("Failed to get Copilot usage", response);
return await response.json();
};
//#endregion
//#region src/check-usage.ts
const checkUsage = defineCommand({
meta: {
name: "check-usage",
description: "Show current GitHub Copilot usage/quota information"
},
async run() {
await ensurePaths();
await setupGitHubToken();
try {
const usage = await getCopilotUsage();
const premium = usage.quota_snapshots.premium_interactions;
const premiumTotal = premium.entitlement;
const premiumUsed = premiumTotal - premium.remaining;
const premiumPercentUsed = premiumTotal > 0 ? premiumUsed / premiumTotal * 100 : 0;
const premiumPercentRemaining = premium.percent_remaining;
function summarizeQuota(name, snap) {
if (!snap) return `${name}: N/A`;
const total = snap.entitlement;
const used = total - snap.remaining;
const percentUsed = total > 0 ? used / total * 100 : 0;
const percentRemaining = snap.percent_remaining;
return `${name}: ${used}/${total} used (${percentUsed.toFixed(1)}% used, ${percentRemaining.toFixed(1)}% remaining)`;
}
const premiumLine = `Premium: ${premiumUsed}/${premiumTotal} used (${premiumPercentUsed.toFixed(1)}% used, ${premiumPercentRemaining.toFixed(1)}% remaining)`;
const chatLine = summarizeQuota("Chat", usage.quota_snapshots.chat);
const completionsLine = summarizeQuota("Completions", usage.quota_snapshots.completions);
consola.box(`Copilot Usage (plan: ${usage.copilot_plan})\nQuota resets: ${usage.quota_reset_date}\n\nQuotas:\n ${premiumLine}\n ${chatLine}\n ${completionsLine}`);
} catch (err) {
consola.error("Failed to fetch Copilot usage:", err);
process.exit(1);
}
}
});
//#endregion
//#region src/lib/config-store.ts
const ModelEntrySchema = z.object({
upstream: z.string().regex(/^\w[\w.:-]*$/, "upstream must be a model ID (e.g. 'gpt-4o'), not a URL"),
enabled: z.boolean().default(true),
allowed_keys: z.array(z.string()).default(["*"]),
default_effort: z.enum([
"low",
"medium",
"high",
"xhigh",
""
]).default("")
});
const RetentionSchema = z.object({
events_days: z.number().int().min(0).default(90),
traces_days: z.number().int().min(0).default(0),
traces_max_bytes: z.number().int().min(0).default(104857600),
audit_days: z.number().int().min(0).default(365)
});
const FeaturesSchema = z.object({
auth: z.boolean().default(true),
telemetry: z.boolean().default(false),
debug: z.boolean().default(false)
});
const ConfigSchema = z.object({
version: z.literal(1),
models: z.preprocess((v) => v ?? {}, z.record(z.string(), ModelEntrySchema)),
retention: z.preprocess((v) => v ?? {}, RetentionSchema),
features: z.preprocess((v) => v ?? {}, FeaturesSchema),
default_model_alias: z.string().default("")
}).superRefine((cfg, ctx) => {
if (cfg.default_model_alias && !Object.hasOwn(cfg.models, cfg.default_model_alias)) ctx.addIssue({
code: "custom",
path: ["default_model_alias"],
message: `default_model_alias "${cfg.default_model_alias}" is not defined in models. Add the alias to models first, or clear this field.`
});
});
const DEFAULT_CONFIG = ConfigSchema.parse({ version: 1 });
let _currentConfig = DEFAULT_CONFIG;
function fsyncPath(targetPath) {
if (os.platform() === "win32") return;
const fd = fs$1.openSync(targetPath, "r");
try {
fs$1.fsyncSync(fd);
} finally {
fs$1.closeSync(fd);
}
}
function saveConfig(config, filePath = configPath()) {
const parsed = ConfigSchema.parse(config);
const json = JSON.stringify(parsed, null, 2);
const tmpPath = `${filePath}.${process.pid}.${crypto$1.randomBytes(4).toString("hex")}.tmp`;
const dir = path.dirname(filePath);
fs$1.mkdirSync(dir, {
recursive: true,
mode: 448
});
const fd = fs$1.openSync(tmpPath, "w", 384);
try {
fs$1.writeSync(fd, json);
fs$1.fsyncSync(fd);
} finally {
fs$1.closeSync(fd);
}
fs$1.chmodSync(tmpPath, 384);
fs$1.renameSync(tmpPath, filePath);
fsyncPath(dir);
_currentConfig = parsed;
}
async function loadConfig(filePath = configPath()) {
const dir = path.dirname(filePath);
await fs.mkdir(dir, {
recursive: true,
mode: 448
});
let raw;
try {
raw = await Bun.file(filePath).text();
} catch {
consola$1.info(`config.json not found, writing defaults to ${filePath}`);
saveConfig(DEFAULT_CONFIG, filePath);
_currentConfig = DEFAULT_CONFIG;
return DEFAULT_CONFIG;
}
try {
const mode = fs$1.statSync(filePath).mode & 511;
if (mode !== 384) consola$1.warn(`config.json has mode 0${mode.toString(8)}, expected 0600. Consider running: chmod 600 ${filePath}`);
} catch {}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (err) {
throw new Error(`config.json is not valid JSON: ${String(err)}`);
}
const result = ConfigSchema.safeParse(parsed);
if (!result.success) throw new Error(`config.json schema validation failed: ${result.error.message}`);
_currentConfig = result.data;
return result.data;
}
let _overrides = {};
/** Set a runtime override that wins over the persisted config until cleared. */
function setRuntimeAuthOverride(value) {
if (value === void 0) delete _overrides.authEnabled;
else _overrides.authEnabled = value;
}
function applyOverrides(cfg) {
if (_overrides.authEnabled === void 0) return cfg;
return {
...cfg,
features: {
...cfg.features,
auth: _overrides.authEnabled
}
};
}
function deepFreeze(obj) {
if (obj === null || typeof obj !== "object") return obj;
Object.freeze(obj);
for (const key of Object.keys(obj)) deepFreeze(obj[key]);
return obj;
}
function getConfig() {
return deepFreeze(applyOverrides(structuredClone(_currentConfig)));
}
function watchConfig(onChange, filePath = configPath()) {
const dir = path.dirname(filePath);
const filename = path.basename(filePath);
let debounceTimer = null;
const watcher = fs$1.watch(dir, (_eventType, changedFile) => {
if (!changedFile || changedFile !== filename) return;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debounceTimer = null;
(async () => {
let raw;
try {
raw = await Bun.file(filePath).text();
} catch (err) {
consola$1.warn(`config.json reload failed (file unreadable), keeping previous config: ${String(err)}`);
return;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (err) {
consola$1.warn(`config.json reload failed (invalid JSON), keeping previous config: ${String(err)}`);
return;
}
const result = ConfigSchema.safeParse(parsed);
if (!result.success) {
consola$1.warn(`config.json reload failed schema validation, keeping previous config: ${result.error.message}`);
return;
}
_currentConfig = result.data;
onChange(deepFreeze(applyOverrides(structuredClone(result.data))));
})().catch((err) => {
consola$1.error(`config.json reload: unexpected error in onChange callback: ${String(err)}`);
});
}, 250);
});
return () => {
if (debounceTimer) clearTimeout(debounceTimer);
watcher.close();
};
}
async function initConfig(onChange, filePath = configPath()) {
await loadConfig(filePath);
return watchConfig(onChange ?? (() => {}), filePath);
}
//#endregion
//#region src/services/audit.ts
/** Returns the audit JSONL file path for a given date string (YYYY-MM-DD). */
function auditFilePath(dateStr) {
return path.join(PATHS.APP_DIR, `audit-${dateStr}.jsonl`);
}
/** Returns today's date string in YYYY-MM-DD format (local time). */
function todayDateStr$1() {
const d = /* @__PURE__ */ new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
/**
* Append a single AuditEvent as a JSONL line.
* Opens the file with O_APPEND | O_CREAT, mode 0600 — atomically appends on
* POSIX systems (write(2) on O_APPEND is atomic for writes ≤ PIPE_BUF).
* Creates parent directory (0700) if needed.
*/
function appendAudit(event) {
const filePath = auditFilePath(todayDateStr$1());
const dir = path.dirname(filePath);
fs$1.mkdirSync(dir, {
recursive: true,
mode: 448
});
const line = JSON.stringify(event) + os.EOL;
const fd = fs$1.openSync(filePath, fs$1.constants.O_WRONLY | fs$1.constants.O_CREAT | fs$1.constants.O_APPEND, 384);
try {
fs$1.writeSync(fd, line);
} finally {
fs$1.closeSync(fd);
}
}
/** Append an audit event, automatically setting ts = Date.now(). */
function audit(event) {
appendAudit({
ts: Date.now(),
...event
});
}
/**
* Delete audit JSONL files older than retention.audit_days.
* Files matching the pattern audit-YYYY-MM-DD.jsonl in APP_DIR are examined;
* any whose date is strictly older than (today − audit_days) are removed.
* Files that do not match the pattern are left untouched.
*/
function initAudit() {
const retentionDays = getConfig().retention.audit_days;
if (retentionDays === 0) return;
const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1e3;
const dir = PATHS.APP_DIR;
let entries;
try {
entries = fs$1.readdirSync(dir);
} catch {
return;
}
for (const entry of entries) {
const match = /^audit-(\d{4}-\d{2}-\d{2})\.jsonl$/.exec(entry);
if (!match) continue;
const dateStr = match[1];
if ((/* @__PURE__ */ new Date(`${dateStr}T00:00:00`)).getTime() < cutoffMs) try {
fs$1.unlinkSync(path.join(dir, entry));
} catch {}
}
}
//#endregion
//#region src/lib/bootstrap.ts
const ADMIN_KEY_FILE = path.join(PATHS.APP_DIR, "admin.key.txt");
/**
* Returns true if the admin bootstrap file exists (operator hasn't read it yet).
*/
function bootstrapFilePending() {
return fs$1.existsSync(ADMIN_KEY_FILE);
}
/**
* Run bootstrap: if auth is enabled and no admin keys exist, generate one.
* Called during startup AFTER initDb() and BEFORE HTTP listener binds.
*
* Logic:
* 1. If auth is disabled → no-op.
* 2. If admin keys already exist in DB → warn if file still present, return.
* 3. Otherwise → create first admin key and write to ADMIN_KEY_FILE.
*/
function runBootstrap() {
const { features } = getConfig();
if (!features.auth) return;
if (countActiveAdminKeys() > 0) {
if (bootstrapFilePending()) consola.warn(`Admin key file still present at ${ADMIN_KEY_FILE}. Delete it after reading:\n rm ${ADMIN_KEY_FILE}`);
return;
}
fs$1.mkdirSync(PATHS.APP_DIR, {
recursive: true,
mode: 448
});
const { plain } = createKey({
tier: "admin",
label: "bootstrap-admin"
});
try {
fs$1.writeFileSync(ADMIN_KEY_FILE, plain + "\n", {
mode: 384,
flag: "wx"
});
} catch (err) {
if (err.code === "EEXIST") {
consola.warn(`Bootstrap key file already exists at ${ADMIN_KEY_FILE} (parallel start?). Using existing file.`);
return;
}
consola.error(`Admin key created in DB but file write failed. Run 'copilot-api admin recover' to retrieve it. Error: ${String(err)}`);
throw err;
}
audit({
actor_key_id: "__system__",
actor_tier: "system",
action: "auth.bootstrap",
after: { label: "bootstrap-admin" }
});
if (process.stdout.isTTY) {
consola.success(`Admin key generated: ${plain}`);
consola.info(`Also written to ${ADMIN_KEY_FILE} (delete after reading)`);
} else consola.info(`Admin key written to ${ADMIN_KEY_FILE}. Read it and delete the file before restarting.`);
}
//#endregion
//#region src/cli/admin-recover.ts
const ADMIN_KEY_FILE_RECOVER = path.join(PATHS.APP_DIR, "admin.key.txt");
const adminRecover = defineCommand({
meta: {
name: "recover",
description: "Mint a new admin key (requires local data-dir access as proof of operator identity)"
},
args: { force: {
type: "boolean",
description: "Create a new admin key even if active admin keys exist",
default: false
} },
run({ args }) {
try {
fs$1.statSync(PATHS.APP_DIR);
} catch {
consola.error(`Cannot access data directory ${PATHS.APP_DIR}. Are you running as the correct user?`);
process.exit(1);
}
initDb();
const existing = countActiveAdminKeys();
if (existing > 0 && !args.force) {
consola.warn(`${existing} active admin key(s) already exist. Pass --force to create a new one anyway.`);
process.exit(1);
}
if (fs$1.existsSync(ADMIN_KEY_FILE_RECOVER)) {
consola.error(`${ADMIN_KEY_FILE_RECOVER} already exists. Read and delete it first:\n cat ${ADMIN_KEY_FILE_RECOVER} && rm ${ADMIN_KEY_FILE_RECOVER}`);
process.exit(1);
}
const { plain } = createKey({
tier: "admin",
label: "recovery-admin"
});
try {
fs$1.writeFileSync(ADMIN_KEY_FILE_RECOVER, plain + "\n", {
mode: 384,
flag: "wx"
});
} catch (err) {
consola.error(`Failed to write recovery key file: ${String(err)}`);
process.exit(1);
}
if (process.stdout.isTTY) consola.success(`Recovery admin key generated: ${plain}`);
else consola.info(`Recovery admin key written to ${ADMIN_KEY_FILE_RECOVER}. Read and delete the file.`);
consola.info(`Also written to ${ADMIN_KEY_FILE_RECOVER}`);
}
});
//#endregion
//#region src/debug.ts
async function getPackageVersion() {
try {
const packageJsonPath = new URL("../package.json", import.meta.url).pathname;
return JSON.parse(await fs.readFile(packageJsonPath)).version;
} catch {
return "unknown";
}
}
function getRuntimeInfo() {
const isBun = typeof Bun !== "undefined";
return {
name: isBun ? "bun" : "node",
version: isBun ? Bun.version : process.version.slice(1),
platform: os.platform(),
arch: os.arch()
};
}
async function checkTokenExists() {
try {
if (!(await fs.stat(PATHS.GITHUB_TOKEN_PATH)).isFile()) return false;
return (await fs.readFile(PATHS.GITHUB_TOKEN_PATH, "utf8")).trim().length > 0;
} catch {
return false;
}
}
async function getDebugInfo() {
const [version, tokenExists] = await Promise.all([getPackageVersion(), checkTokenExists()]);
return {
version,
runtime: getRuntimeInfo(),
paths: {
APP_DIR: PATHS.APP_DIR,
GITHUB_TOKEN_PATH: PATHS.GITHUB_TOKEN_PATH
},
tokenExists
};
}
function printDebugInfoPlain(info) {
consola.info(`copilot-api debug
Version: ${info.version}
Runtime: ${info.runtime.name} ${info.runtime.version} (${info.runtime.platform} ${info.runtime.arch})
Paths:
- APP_DIR: ${info.paths.APP_DIR}
- GITHUB_TOKEN_PATH: ${info.paths.GITHUB_TOKEN_PATH}
Token exists: ${info.tokenExists ? "Yes" : "No"}`);
}
function printDebugInfoJson(info) {
console.log(JSON.stringify(info, null, 2));
}
async function runDebug(options) {
const debugInfo = await getDebugInfo();
if (options.json) printDebugInfoJson(debugInfo);
else printDebugInfoPlain(debugInfo);
}
const debug = defineCommand({
meta: {
name: "debug",
description: "Print debug information about the application"
},
args: { json: {
type: "boolean",
default: false,
description: "Output debug information as JSON"
} },
run({ args }) {
return runDebug({ json: args.json });
}
});
//#endregion
//#region src/admin/csrf.ts
const CSRF_SECRET = crypto$1.randomBytes(32);
function generateCsrfToken(sessionId) {
return crypto$1.createHmac("sha256", CSRF_SECRET).update(sessionId).digest("base64url");
}
function verifyCsrfToken(sessionId, token) {
const expected = generateCsrfToken(sessionId);
if (expected.length !== token.length) return false;
return crypto$1.timingSafeEqual(Buffer.from(expected), Buffer.from(token));
}
const CSRF_COOKIE = "csrf";
const CSRF_HEADER = "x-csrf-token";
/** Build Set-Cookie value for the CSRF token cookie */
function csrfCookieValue(token) {
const secure = process.env.ADMIN_INSECURE_HTTP === "true" ? "" : "; Secure";
return `${CSRF_COOKIE}=${token}; SameSite=Strict${secure}; Path=/admin`;
}
/** Extract CSRF token from cookie string */
function extractCsrfCookie(cookieHeader) {
if (!cookieHeader) return void 0;
for (const part of cookieHeader.split(";")) {
const [name, ...rest] = part.trim().split("=");
if (name.trim() === CSRF_COOKIE) return rest.join("=").trim();
}
}
//#endregion
//#region src/admin/session.ts
/** Session lifetime: 8 hours in milliseconds */
const SESSION_LIFETIME_MS = 480 * 60 * 1e3;
const SESSION_COOKIE = "sid";
function newSessionId() {
return crypto$1.randomBytes(32).toString("hex");
}
/** Create a new session for the given key and return the session row. */
function createSession(keyId) {
const db = getDb();
const id = newSessionId();
const now = Date.now();
const expiresAt = now + SESSION_LIFETIME_MS;
const csrfToken = generateCsrfToken(id);
db.run(`INSERT INTO sessions (id, key_id, csrf_token, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)`, [
id,
keyId,
csrfToken,
now,
expiresAt
]);
return {
id,
key_id: keyId,
csrf_token: csrfToken,
created_at: now,
expires_at: expiresAt
};
}
/** Look up an active session by id, sliding its expiry. Returns null if not found or expired. */
function getSession(sessionId) {
const db = getDb();
const now = Date.now();
const row = db.query(`SELECT id, key_id, csrf_token, created_at, expires_at
FROM sessions WHERE id = ? AND expires_at > ?`).get(sessionId, now);
if (!row) return null;
const newExpiry = now + SESSION_LIFETIME_MS;
db.run(`UPDATE sessions SET expires_at = ? WHERE id = ?`, [newExpiry, sessionId]);
return {
...row,
expires_at: newExpiry
};
}
/** Destroy a session (logout). */
function deleteSession(sessionId) {
getDb().run(`DELETE FROM sessions WHERE id = ?`, [sessionId]);
}
/** Sweep expired sessions (called on startup / periodically). */
function purgeExpiredSessions() {
getDb().run(`DELETE FROM sessions WHERE expires_at <= ?`, [Date.now()]);
}
/**
* Whether session cookies should be flagged `Secure` (HTTPS-only). Defaults
* to true. When ADMIN_INSECURE_HTTP=true is set, the operator has opted into
* plain-HTTP admin access on LAN, and `Secure` must be dropped — browsers
* silently discard Secure cookies received over HTTP, which would manifest
* as a "login loop" (server sets cookies, browser drops them, next request
* has no session → redirect back to login).
*/
function cookieSecureFlag() {
return process.env.ADMIN_INSECURE_HTTP === "true" ? "" : "; Secure";
}
/** Build the Set-Cookie header value for the session cookie. */
function sessionCookieValue(sessionId) {
return `${SESSION_COOKIE}=${sessionId}; HttpOnly${cookieSecureFlag()}; SameSite=Strict; Path=/admin; Max-Age=${SESSION_LIFETIME_MS / 1e3}`;
}
/** Build a Set-Cookie value that clears the session cookie. */
function clearSessionCookieValue() {
return `${SESSION_COOKIE}=; HttpOnly${cookieSecureFlag()}; SameSite=Strict; Path=/admin; Max-Age=0`;
}
/** Extract the session id from the Cookie header. */