@teamclaws/teamclaw 2026.7.1 → 2026.8.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.
Files changed (60) hide show
  1. package/README.md +8 -0
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +381 -0
  5. package/dist/src/controller/controller-capacity.js +14 -0
  6. package/dist/src/controller/controller-service.js +393 -0
  7. package/dist/src/controller/controller-tools.js +582 -0
  8. package/dist/src/controller/delivery-report.js +458 -0
  9. package/dist/src/controller/github-auth.js +564 -0
  10. package/dist/src/controller/http-server.js +6032 -0
  11. package/dist/src/controller/kickoff-orchestrator.js +220 -0
  12. package/dist/src/controller/managed-gateway-process.js +286 -0
  13. package/dist/src/controller/message-router.js +38 -0
  14. package/dist/src/controller/orchestration-manifest.js +173 -0
  15. package/dist/src/controller/preview-manager.js +586 -0
  16. package/dist/src/controller/prompt-injector.js +187 -0
  17. package/dist/src/controller/role-inference.js +35 -0
  18. package/dist/src/controller/task-router.js +67 -0
  19. package/dist/src/controller/tunnel-manager.js +548 -0
  20. package/dist/src/controller/websocket.js +42 -0
  21. package/dist/src/controller/worker-provisioning.js +1648 -0
  22. package/dist/src/discovery.js +86 -0
  23. package/dist/src/git-collaboration.js +694 -0
  24. package/dist/src/identity.js +131 -0
  25. package/dist/src/install-defaults.js +1 -0
  26. package/dist/src/interaction-contracts.js +531 -0
  27. package/dist/src/networking.js +91 -0
  28. package/dist/src/openclaw-workspace.js +903 -0
  29. package/dist/src/prompt-policy.js +373 -0
  30. package/dist/src/protocol.js +58 -0
  31. package/dist/src/roles.js +349 -0
  32. package/dist/src/state.js +183 -0
  33. package/dist/src/task-executor.js +1033 -0
  34. package/dist/src/teamauto/github-client.js +192 -0
  35. package/dist/src/teamauto/norms.js +85 -0
  36. package/dist/src/teamauto/repo-sync.js +201 -0
  37. package/dist/src/teamauto/scanner.js +179 -0
  38. package/dist/src/teamauto/schedule.js +123 -0
  39. package/dist/src/teamauto/scheduler.js +688 -0
  40. package/dist/src/teamauto/store.js +133 -0
  41. package/dist/src/types.js +243 -0
  42. package/dist/src/ui/app.js +4292 -0
  43. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  44. package/dist/src/ui/github-login.html +296 -0
  45. package/dist/src/ui/index.html +414 -0
  46. package/dist/src/ui/style.css +2611 -0
  47. package/dist/src/worker/http-handler.js +146 -0
  48. package/dist/src/worker/message-queue.js +24 -0
  49. package/dist/src/worker/prompt-injector.js +42 -0
  50. package/dist/src/worker/skill-installer.js +253 -0
  51. package/dist/src/worker/tools.js +541 -0
  52. package/dist/src/worker/worker-service.js +234 -0
  53. package/dist/src/workspace-browser.js +269 -0
  54. package/openclaw.plugin.json +1 -1
  55. package/package.json +9 -7
  56. package/src/controller/http-server.ts +26 -1
  57. package/src/controller/tunnel-manager.ts +139 -15
  58. package/src/ui/app.js +97 -20
  59. package/src/ui/index.html +16 -4
  60. package/src/ui/style.css +49 -0
@@ -0,0 +1,564 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ /**
6
+ * GitHub (GitHub App) user login for the TeamClaw controller.
7
+ *
8
+ * Flow: OAuth authorization code + PKCE (S256) + `state` CSRF guard, with a
9
+ * localhost redirect handled by the controller HTTP server. See GITHUB_AUTH.md
10
+ * for the full design.
11
+ *
12
+ * Persistence: a single JSON file under the plugin state directory
13
+ * (`auth/github.json`, mode 0600, atomic tmp+rename writes).
14
+ */
15
+ export const DEFAULT_GITHUB_CLIENT_ID = "Iv23liqWmzrS3swGiIvK";
16
+ export const GITHUB_AUTH_CALLBACK_PATH = "/api/v1/auth/github/callback";
17
+ export const GITHUB_CLIENT_SECRET_ENV = "TEAMCLAW_GITHUB_CLIENT_SECRET";
18
+ const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
19
+ const GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
20
+ const GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code";
21
+ const GITHUB_DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
22
+ const GITHUB_API_BASE = "https://api.github.com";
23
+ const GITHUB_API_VERSION = "2026-03-10";
24
+ const GITHUB_USER_AGENT = "teamclaw-github-auth";
25
+ const STORE_VERSION = 1;
26
+ /** Pending authorize flows older than this are discarded (CSRF window). */
27
+ const PENDING_FLOW_TTL_MS = 10 * 60 * 1000;
28
+ /** Refresh this long before the access token actually expires. */
29
+ const REFRESH_EARLY_MS = 5 * 60 * 1000;
30
+ const HTTP_TIMEOUT_MS = 15 * 1000;
31
+ export class GithubAuthError extends Error {
32
+ code;
33
+ constructor(message, code) {
34
+ super(message);
35
+ this.name = "GithubAuthError";
36
+ this.code = code;
37
+ }
38
+ }
39
+ const defaultFetch = (url, init) => fetch(url, init);
40
+ /** Location of the persisted token file, mirroring state.ts state-dir resolution. */
41
+ export function resolveGithubAuthFilePath() {
42
+ const explicitStateDir = process.env.OPENCLAW_STATE_DIR?.trim();
43
+ if (explicitStateDir) {
44
+ return path.join(path.resolve(explicitStateDir), "plugins", "teamclaw", "auth", "github.json");
45
+ }
46
+ const explicitHome = process.env.OPENCLAW_HOME?.trim() || process.env.HOME?.trim();
47
+ const homeDir = explicitHome ? path.resolve(explicitHome) : os.homedir();
48
+ return path.join(homeDir, ".openclaw", "plugins", "teamclaw", "auth", "github.json");
49
+ }
50
+ const storeWriteQueues = new Map();
51
+ async function writeStoreAtomically(filePath, contents) {
52
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
53
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
54
+ await fs.writeFile(tmpPath, contents, { encoding: "utf8", mode: 0o600 });
55
+ try {
56
+ await fs.chmod(tmpPath, 0o600);
57
+ }
58
+ catch {
59
+ // Best-effort: the write itself already requested mode 0600; some
60
+ // filesystems (e.g. network mounts) reject explicit chmod.
61
+ }
62
+ await fs.rename(tmpPath, filePath);
63
+ }
64
+ function enqueueStoreWrite(filePath, record) {
65
+ const contents = JSON.stringify(record, null, 2) + "\n";
66
+ const previous = storeWriteQueues.get(filePath) ?? Promise.resolve();
67
+ const next = previous
68
+ .catch(() => { })
69
+ .then(() => writeStoreAtomically(filePath, contents));
70
+ storeWriteQueues.set(filePath, next);
71
+ return next.finally(() => {
72
+ if (storeWriteQueues.get(filePath) === next) {
73
+ storeWriteQueues.delete(filePath);
74
+ }
75
+ });
76
+ }
77
+ async function postTokenRequest(fetchImpl, params, options = {}) {
78
+ const response = await fetchImpl(GITHUB_TOKEN_URL, {
79
+ method: "POST",
80
+ headers: {
81
+ "Accept": "application/json",
82
+ "Content-Type": "application/x-www-form-urlencoded",
83
+ "User-Agent": GITHUB_USER_AGENT,
84
+ },
85
+ body: new URLSearchParams(params).toString(),
86
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
87
+ });
88
+ let payload = {};
89
+ try {
90
+ payload = (await response.json());
91
+ }
92
+ catch {
93
+ payload = {};
94
+ }
95
+ // Device-flow polling reports authorization_pending / slow_down as an
96
+ // `error` field on HTTP 200; callers opt in to receiving those payloads.
97
+ if (!options.tolerateError && (!response.ok || typeof payload.error === "string")) {
98
+ const errorName = typeof payload.error === "string" ? payload.error : `http_${response.status}`;
99
+ const description = typeof payload.error_description === "string" ? payload.error_description : "";
100
+ throw new GithubAuthError(`GitHub token endpoint rejected the request (${errorName})${description ? `: ${description}` : ""}`, errorName);
101
+ }
102
+ return payload;
103
+ }
104
+ export function createGithubAuthManager(options = {}) {
105
+ const clientId = options.clientId?.trim() || DEFAULT_GITHUB_CLIENT_ID;
106
+ // The environment variable wins so operators can keep the secret out of the
107
+ // plugin config file.
108
+ const clientSecret = process.env[GITHUB_CLIENT_SECRET_ENV]?.trim() || options.clientSecret?.trim() || "";
109
+ const logger = options.logger;
110
+ const fetchImpl = options.fetchImpl ?? defaultFetch;
111
+ const now = options.now ?? Date.now;
112
+ const filePath = resolveGithubAuthFilePath();
113
+ const pendingFlows = new Map();
114
+ let inFlightRefresh = null;
115
+ let activeDeviceFlow = null;
116
+ let devicePollTimer = null;
117
+ function requireSecret() {
118
+ if (!clientSecret) {
119
+ throw new GithubAuthError(`GitHub client secret is not configured. Generate one in the GitHub App settings and provide it via the ${GITHUB_CLIENT_SECRET_ENV} environment variable or the githubClientSecret plugin config.`, "missing_client_secret");
120
+ }
121
+ }
122
+ function beginLogin(origin) {
123
+ requireSecret();
124
+ const base = origin.trim().replace(/\/+$/, "");
125
+ if (!/^https?:\/\/.+/.test(base)) {
126
+ throw new GithubAuthError("Invalid controller origin for the GitHub login redirect.", "invalid_origin");
127
+ }
128
+ const callbackUrl = base + GITHUB_AUTH_CALLBACK_PATH;
129
+ const state = crypto.randomBytes(24).toString("base64url");
130
+ const codeVerifier = crypto.randomBytes(32).toString("base64url");
131
+ const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
132
+ const cutoff = now() - PENDING_FLOW_TTL_MS;
133
+ for (const [key, flow] of pendingFlows) {
134
+ if (flow.createdAt < cutoff) {
135
+ pendingFlows.delete(key);
136
+ }
137
+ }
138
+ pendingFlows.set(state, { createdAt: now(), codeVerifier, redirectUri: callbackUrl });
139
+ const authorizeUrl = `${GITHUB_AUTHORIZE_URL}?${new URLSearchParams({
140
+ client_id: clientId,
141
+ redirect_uri: callbackUrl,
142
+ // For GitHub Apps, offline_access is the only supported scope and is
143
+ // what yields an expiring access token plus a refresh token.
144
+ scope: "offline_access",
145
+ state,
146
+ code_challenge: codeChallenge,
147
+ code_challenge_method: "S256",
148
+ }).toString()}`;
149
+ return { authorizeUrl, state, callbackUrl };
150
+ }
151
+ function stopDeviceFlow() {
152
+ if (devicePollTimer) {
153
+ clearTimeout(devicePollTimer);
154
+ devicePollTimer = null;
155
+ }
156
+ activeDeviceFlow = null;
157
+ }
158
+ function scheduleDevicePoll(delayMs) {
159
+ if (devicePollTimer) {
160
+ clearTimeout(devicePollTimer);
161
+ }
162
+ devicePollTimer = setTimeout(() => {
163
+ void pollDeviceFlowTick();
164
+ }, Math.max(0, delayMs));
165
+ devicePollTimer.unref?.();
166
+ }
167
+ /**
168
+ * Start a device-flow login. No client secret is required: the device code
169
+ * request and the token polling both send only the client id, and GitHub
170
+ * allows refreshing device-flow tokens without a secret as well.
171
+ */
172
+ async function beginDeviceLogin() {
173
+ stopDeviceFlow();
174
+ const response = await fetchImpl(GITHUB_DEVICE_CODE_URL, {
175
+ method: "POST",
176
+ headers: {
177
+ "Accept": "application/json",
178
+ "Content-Type": "application/x-www-form-urlencoded",
179
+ "User-Agent": GITHUB_USER_AGENT,
180
+ },
181
+ body: new URLSearchParams({
182
+ client_id: clientId,
183
+ // Yields an expiring access token plus a refresh token; refresh of
184
+ // device-flow tokens stays secretless.
185
+ scope: "offline_access",
186
+ }).toString(),
187
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
188
+ });
189
+ let data = {};
190
+ try {
191
+ data = (await response.json());
192
+ }
193
+ catch {
194
+ data = {};
195
+ }
196
+ if (!response.ok || typeof data.error === "string") {
197
+ const errorName = typeof data.error === "string" ? data.error : `http_${response.status}`;
198
+ const hint = errorName === "device_flow_disabled"
199
+ ? "Device flow is disabled for this GitHub App. Open the GitHub App settings and check 'Enable Device Flow'."
200
+ : "";
201
+ throw new GithubAuthError(`GitHub device authorization failed (${errorName})${hint ? `: ${hint}` : ""}`, errorName);
202
+ }
203
+ const deviceCode = typeof data.device_code === "string" ? data.device_code : "";
204
+ const userCode = typeof data.user_code === "string" ? data.user_code : "";
205
+ const verificationUri = typeof data.verification_uri === "string"
206
+ ? data.verification_uri
207
+ : "https://github.com/login/device";
208
+ if (!deviceCode || !userCode) {
209
+ throw new GithubAuthError("GitHub device authorization response was missing device_code/user_code.", "device_code_invalid");
210
+ }
211
+ const expiresInSeconds = typeof data.expires_in === "number" && data.expires_in > 0 ? data.expires_in : 900;
212
+ const intervalMs = (typeof data.interval === "number" && data.interval > 0 ? data.interval : 5) * 1000;
213
+ activeDeviceFlow = {
214
+ userCode,
215
+ deviceCode,
216
+ verificationUri,
217
+ expiresAt: now() + expiresInSeconds * 1000,
218
+ intervalMs,
219
+ };
220
+ logger?.info(`Controller: GitHub device login started (code ${userCode})`);
221
+ scheduleDevicePoll(intervalMs);
222
+ const { deviceCode: _omit, ...info } = activeDeviceFlow;
223
+ return info;
224
+ }
225
+ async function pollDeviceFlowTick() {
226
+ const flow = activeDeviceFlow;
227
+ if (!flow) {
228
+ return;
229
+ }
230
+ if (now() >= flow.expiresAt) {
231
+ logger?.warn("Controller: GitHub device login expired before authorization");
232
+ stopDeviceFlow();
233
+ return;
234
+ }
235
+ let payload;
236
+ try {
237
+ payload = await postTokenRequest(fetchImpl, {
238
+ client_id: clientId,
239
+ device_code: flow.deviceCode,
240
+ grant_type: GITHUB_DEVICE_GRANT_TYPE,
241
+ }, { tolerateError: true });
242
+ }
243
+ catch (err) {
244
+ logger?.warn(`Controller: GitHub device poll failed (${err instanceof Error ? err.message : String(err)}); retrying`);
245
+ scheduleDevicePoll(flow.intervalMs);
246
+ return;
247
+ }
248
+ const errorCode = typeof payload.error === "string" ? payload.error : "";
249
+ if (errorCode === "authorization_pending") {
250
+ scheduleDevicePoll(flow.intervalMs);
251
+ return;
252
+ }
253
+ if (errorCode === "slow_down") {
254
+ flow.intervalMs += 5000;
255
+ scheduleDevicePoll(flow.intervalMs);
256
+ return;
257
+ }
258
+ if (errorCode) {
259
+ // expired_token / access_denied / incorrect_device_code / device_flow_disabled
260
+ logger?.warn(`Controller: GitHub device login ended (${errorCode})`);
261
+ stopDeviceFlow();
262
+ return;
263
+ }
264
+ try {
265
+ await persistTokenExchange(payload, "device");
266
+ }
267
+ catch (err) {
268
+ logger?.warn(`Controller: GitHub device login completion failed (${err instanceof Error ? err.message : String(err)})`);
269
+ }
270
+ finally {
271
+ stopDeviceFlow();
272
+ }
273
+ }
274
+ async function fetchAccount(accessToken) {
275
+ const response = await fetchImpl(`${GITHUB_API_BASE}/user`, {
276
+ method: "GET",
277
+ headers: {
278
+ "Accept": "application/vnd.github+json",
279
+ "Authorization": `Bearer ${accessToken}`,
280
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
281
+ "User-Agent": GITHUB_USER_AGENT,
282
+ },
283
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
284
+ });
285
+ if (!response.ok) {
286
+ throw new GithubAuthError(`Failed to load the GitHub user profile (HTTP ${response.status}).`, "user_profile_failed");
287
+ }
288
+ const payload = (await response.json());
289
+ const id = typeof payload.id === "number" ? payload.id : Number(payload.id);
290
+ const login = typeof payload.login === "string" ? payload.login : "";
291
+ if (!Number.isFinite(id) || !login) {
292
+ throw new GithubAuthError("GitHub user profile response was missing id/login.", "user_profile_invalid");
293
+ }
294
+ return {
295
+ id,
296
+ login,
297
+ name: typeof payload.name === "string" ? payload.name : null,
298
+ avatarUrl: typeof payload.avatar_url === "string" ? payload.avatar_url : null,
299
+ htmlUrl: typeof payload.html_url === "string" ? payload.html_url : null,
300
+ };
301
+ }
302
+ async function loadStore() {
303
+ try {
304
+ const raw = await fs.readFile(filePath, "utf8");
305
+ const parsed = JSON.parse(raw);
306
+ if (typeof parsed.accessToken !== "string" || !parsed.accessToken) {
307
+ return null;
308
+ }
309
+ const account = parsed.account && typeof parsed.account === "object" && !Array.isArray(parsed.account)
310
+ ? parsed.account
311
+ : null;
312
+ return {
313
+ version: typeof parsed.version === "number" ? parsed.version : STORE_VERSION,
314
+ clientId: typeof parsed.clientId === "string" ? parsed.clientId : clientId,
315
+ flowOrigin: parsed.flowOrigin === "device" ? "device" : "web",
316
+ account: account && typeof account.login === "string"
317
+ ? {
318
+ id: typeof account.id === "number" ? account.id : 0,
319
+ login: account.login,
320
+ name: typeof account.name === "string" ? account.name : null,
321
+ avatarUrl: typeof account.avatarUrl === "string" ? account.avatarUrl : null,
322
+ htmlUrl: typeof account.htmlUrl === "string" ? account.htmlUrl : null,
323
+ }
324
+ : null,
325
+ accessToken: parsed.accessToken,
326
+ refreshToken: typeof parsed.refreshToken === "string" ? parsed.refreshToken : null,
327
+ obtainedAt: typeof parsed.obtainedAt === "number" ? parsed.obtainedAt : 0,
328
+ expiresAt: typeof parsed.expiresAt === "number" ? parsed.expiresAt : null,
329
+ refreshExpiresAt: typeof parsed.refreshExpiresAt === "number" ? parsed.refreshExpiresAt : null,
330
+ updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : 0,
331
+ };
332
+ }
333
+ catch {
334
+ // Missing or unreadable file simply means "not signed in yet".
335
+ return null;
336
+ }
337
+ }
338
+ async function clearStore() {
339
+ try {
340
+ await fs.unlink(filePath);
341
+ }
342
+ catch {
343
+ // Already absent — nothing to clear.
344
+ }
345
+ }
346
+ async function performRefresh(store) {
347
+ if (!store.refreshToken) {
348
+ await clearStore();
349
+ throw new GithubAuthError("GitHub login has no refresh token; sign in again.", "refresh_unavailable");
350
+ }
351
+ const refreshParams = {
352
+ client_id: clientId,
353
+ grant_type: "refresh_token",
354
+ refresh_token: store.refreshToken,
355
+ };
356
+ if (clientSecret) {
357
+ refreshParams.client_secret = clientSecret;
358
+ }
359
+ else if (store.flowOrigin !== "device") {
360
+ // GitHub: client_secret is required for refresh UNLESS the token came
361
+ // from the device flow. Secretless installs must therefore log in via
362
+ // the device flow (the default).
363
+ await clearStore();
364
+ throw new GithubAuthError(`Refreshing this GitHub login requires the client secret. Sign in again using the device flow (default), which refreshes without a secret, or configure ${GITHUB_CLIENT_SECRET_ENV}.`, "missing_client_secret");
365
+ }
366
+ let payload;
367
+ try {
368
+ payload = await postTokenRequest(fetchImpl, refreshParams);
369
+ }
370
+ catch (err) {
371
+ if (err instanceof GithubAuthError && err.code === "bad_refresh_token") {
372
+ // The refresh token is dead (expired or revoked): drop the stored
373
+ // credentials so the UI falls back to "not signed in".
374
+ await clearStore();
375
+ throw new GithubAuthError("GitHub login has expired; sign in again.", "refresh_expired");
376
+ }
377
+ throw err;
378
+ }
379
+ const accessToken = typeof payload.access_token === "string" ? payload.access_token : "";
380
+ if (!accessToken) {
381
+ throw new GithubAuthError("GitHub refresh response did not include an access token.", "missing_access_token");
382
+ }
383
+ const refreshedAt = now();
384
+ const next = {
385
+ ...store,
386
+ accessToken,
387
+ // Refresh tokens rotate: always prefer the newly issued one.
388
+ refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : store.refreshToken,
389
+ expiresAt: typeof payload.expires_in === "number" ? refreshedAt + payload.expires_in * 1000 : null,
390
+ refreshExpiresAt: typeof payload.refresh_token_expires_in === "number"
391
+ ? refreshedAt + payload.refresh_token_expires_in * 1000
392
+ : store.refreshExpiresAt,
393
+ updatedAt: refreshedAt,
394
+ };
395
+ await enqueueStoreWrite(filePath, next);
396
+ logger?.info("Controller: GitHub access token refreshed");
397
+ return next;
398
+ }
399
+ async function persistTokenExchange(payload, flowOrigin) {
400
+ const accessToken = typeof payload.access_token === "string" ? payload.access_token : "";
401
+ if (!accessToken) {
402
+ throw new GithubAuthError("GitHub token response did not include an access token.", "missing_access_token");
403
+ }
404
+ const account = await fetchAccount(accessToken);
405
+ const fetchedAt = now();
406
+ await enqueueStoreWrite(filePath, {
407
+ version: STORE_VERSION,
408
+ clientId,
409
+ flowOrigin,
410
+ account,
411
+ accessToken,
412
+ refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : null,
413
+ obtainedAt: fetchedAt,
414
+ expiresAt: typeof payload.expires_in === "number" ? fetchedAt + payload.expires_in * 1000 : null,
415
+ refreshExpiresAt: typeof payload.refresh_token_expires_in === "number"
416
+ ? fetchedAt + payload.refresh_token_expires_in * 1000
417
+ : null,
418
+ updatedAt: fetchedAt,
419
+ });
420
+ logger?.info(`Controller: GitHub login stored for @${account.login}`);
421
+ return account;
422
+ }
423
+ async function completeLogin(params) {
424
+ if (params.error) {
425
+ throw new GithubAuthError(`GitHub authorization was not granted (${params.error}${params.errorDescription ? `: ${params.errorDescription}` : ""}).`, params.error);
426
+ }
427
+ const state = params.state ?? "";
428
+ const code = params.code ?? "";
429
+ const flow = pendingFlows.get(state);
430
+ // One-shot: a state value can only ever be consumed once.
431
+ pendingFlows.delete(state);
432
+ if (!flow) {
433
+ throw new GithubAuthError("Unknown or already-used GitHub login state. Please start the login again.", "invalid_state");
434
+ }
435
+ if (now() - flow.createdAt > PENDING_FLOW_TTL_MS) {
436
+ throw new GithubAuthError("GitHub login state expired. Please start the login again.", "state_expired");
437
+ }
438
+ if (!code) {
439
+ throw new GithubAuthError("GitHub login callback is missing the authorization code.", "missing_code");
440
+ }
441
+ requireSecret();
442
+ const payload = await postTokenRequest(fetchImpl, {
443
+ client_id: clientId,
444
+ client_secret: clientSecret,
445
+ code,
446
+ redirect_uri: flow.redirectUri,
447
+ code_verifier: flow.codeVerifier,
448
+ });
449
+ return persistTokenExchange(payload, "web");
450
+ }
451
+ async function getAccessToken() {
452
+ const store = await loadStore();
453
+ if (!store) {
454
+ throw new GithubAuthError("Not signed in to GitHub.", "not_authenticated");
455
+ }
456
+ if (store.expiresAt === null || now() < store.expiresAt - REFRESH_EARLY_MS) {
457
+ return store.accessToken;
458
+ }
459
+ // Single-flight: concurrent callers share one refresh round-trip.
460
+ const refreshed = inFlightRefresh ?? (inFlightRefresh = performRefresh(store).finally(() => {
461
+ inFlightRefresh = null;
462
+ }));
463
+ return (await refreshed).accessToken;
464
+ }
465
+ async function forceRefresh() {
466
+ const store = await loadStore();
467
+ if (!store) {
468
+ throw new GithubAuthError("Not signed in to GitHub.", "not_authenticated");
469
+ }
470
+ return performRefresh(store);
471
+ }
472
+ async function logout() {
473
+ const store = await loadStore();
474
+ if (store && clientSecret) {
475
+ try {
476
+ const basic = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");
477
+ await fetchImpl(`${GITHUB_API_BASE}/applications/${clientId}/token`, {
478
+ method: "DELETE",
479
+ headers: {
480
+ "Accept": "application/vnd.github+json",
481
+ "Authorization": `Basic ${basic}`,
482
+ "Content-Type": "application/json",
483
+ "User-Agent": GITHUB_USER_AGENT,
484
+ },
485
+ body: JSON.stringify({ access_token: store.accessToken }),
486
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
487
+ });
488
+ }
489
+ catch (err) {
490
+ logger?.warn(`Controller: GitHub token revocation skipped (${err instanceof Error ? err.message : String(err)})`);
491
+ }
492
+ }
493
+ await clearStore();
494
+ pendingFlows.clear();
495
+ stopDeviceFlow();
496
+ }
497
+ async function getStatus(origin) {
498
+ const store = await loadStore();
499
+ return {
500
+ authenticated: store !== null,
501
+ account: store?.account ?? null,
502
+ clientId,
503
+ clientSecretConfigured: Boolean(clientSecret),
504
+ expiresAt: store?.expiresAt ?? null,
505
+ refreshExpiresAt: store?.refreshExpiresAt ?? null,
506
+ callbackPath: GITHUB_AUTH_CALLBACK_PATH,
507
+ callbackUrl: origin
508
+ ? origin.trim().replace(/\/+$/, "") + GITHUB_AUTH_CALLBACK_PATH
509
+ : null,
510
+ loginPageUrl: origin
511
+ ? origin.trim().replace(/\/+$/, "") + "/ui/auth/github"
512
+ : null,
513
+ device: activeDeviceFlow
514
+ ? {
515
+ userCode: activeDeviceFlow.userCode,
516
+ verificationUri: activeDeviceFlow.verificationUri,
517
+ expiresAt: activeDeviceFlow.expiresAt,
518
+ intervalMs: activeDeviceFlow.intervalMs,
519
+ }
520
+ : null,
521
+ };
522
+ }
523
+ /** Ready-to-use GitHub API headers for internal consumers of the stored token. */
524
+ async function getAuthHeaders() {
525
+ const token = await getAccessToken();
526
+ return {
527
+ "Authorization": `Bearer ${token}`,
528
+ "Accept": "application/vnd.github+json",
529
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
530
+ "User-Agent": GITHUB_USER_AGENT,
531
+ };
532
+ }
533
+ return {
534
+ beginLogin,
535
+ beginDeviceLogin,
536
+ completeLogin,
537
+ getAccessToken,
538
+ getAuthHeaders,
539
+ getStatus,
540
+ forceRefresh,
541
+ logout,
542
+ };
543
+ }
544
+ const managerCache = new Map();
545
+ /**
546
+ * Cached manager keyed by client id, secret, and token file location so the
547
+ * controller's in-memory pending-flow state survives across requests.
548
+ */
549
+ export function getGithubAuthManager(config, logger) {
550
+ const clientId = config.githubClientId?.trim() || DEFAULT_GITHUB_CLIENT_ID;
551
+ const clientSecret = config.githubClientSecret ?? "";
552
+ const cacheKey = [
553
+ clientId,
554
+ crypto.createHash("sha256").update(clientSecret).digest("hex").slice(0, 16),
555
+ resolveGithubAuthFilePath(),
556
+ ].join("|");
557
+ const cached = managerCache.get(cacheKey);
558
+ if (cached) {
559
+ return cached;
560
+ }
561
+ const manager = createGithubAuthManager({ clientId, clientSecret, logger });
562
+ managerCache.set(cacheKey, manager);
563
+ return manager;
564
+ }