Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): reuse GitHub login for release checks (#5215)

Chris Zhang277760772460
diff --git a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
index c18475a598..2d7ce1664f 100644
--- a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
@@ -25,6 +25,7 @@ describe('createGhCliTokenSource', () => {
});
expect(await src.readToken()).toBe('gho_abc123');
expect(execFileFn.mock.calls[0][0]).toBe('/opt/homebrew/bin/gh');
+ expect(execFileFn.mock.calls[0][1]).toEqual(['auth', 'token', '--hostname', 'github.com']);
});
it('候选都不存在时退回裸 gh(win32 用 gh.exe)', async () => {
diff --git a/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts b/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts
index 0d7f7d3433..878c7eaa6b 100644
--- a/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts
+++ b/apps/desktop/src/main/agent-binaries/__tests__/pi-self-update.test.ts
@@ -1,14 +1,17 @@
import { createHash } from 'node:crypto';
import { probeBinaryVersion } from '../binary-version-probe.js';
import { extractMakeToolArchive } from '../../cindy-make/toolArchive.js';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { installPiBinaryUpdate, parsePiRelease, piBinaryUpdateFailureStage, renameWithTransientRetry, type PiBinaryUpdateDeps } from '../pi-self-update.js';
+import { installPiBinaryUpdate, parsePiRelease, piBinaryUpdateDefaults, piBinaryUpdateFailureStage, renameWithTransientRetry, type PiBinaryUpdateDeps } from '../pi-self-update.js';
const electronFetch = vi.hoisted(() => vi.fn());
+const readToken = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({ net: { fetch: electronFetch } }));
+vi.mock('../../git-context/ghCliTokenSource.js', () => ({ getSharedGhCliTokenSource: () => ({ readToken }) }));
+beforeEach(() => { readToken.mockReset().mockResolvedValue(null); });
const roots: string[] = [];
afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllGlobals(); electronFetch.mockReset(); await Promise.all(roots.splice(0).map(root => fs.rm(root, { recursive: true, force: true }))); });
@@ -33,6 +36,104 @@ async function fixture(platform: 'darwin' | 'win32' = 'darwin') {
};
return { root, current, deps };
}
+describe('Pi release lookup authentication', () => {
+ const url = 'https://api.github.com/repos/earendil-works/pi/releases/latest';
+ const token = 'fixture-github-token';
+ const headers = { Accept: 'application/vnd.github+json' };
+ const success = () => new Response(JSON.stringify(release()), { status: 200 });
+
+ it('prefers the shared GitHub login and prevents authenticated redirects', async () => {
+ readToken.mockResolvedValue(token);
+ electronFetch.mockResolvedValue(success());
+ const signal = new AbortController().signal;
+ await expect(piBinaryUpdateDefaults.fetchRelease(signal)).resolves.toEqual(release());
+ expect(electronFetch).toHaveBeenCalledExactlyOnceWith(url, {
+ signal, redirect: 'error', headers: { ...headers, Authorization: `Bearer ${token}` },
+ });
+ });
+
+ it.each(['missing', 'unavailable'])('checks anonymously when the login is %s', async reason => {
+ if (reason === 'unavailable') readToken.mockRejectedValue(new Error('credential source unavailable'));
+ electronFetch.mockResolvedValue(success());
+ const signal = new AbortController().signal;
+ await expect(piBinaryUpdateDefaults.fetchRelease(signal)).resolves.toEqual(release());
+ expect(electronFetch).toHaveBeenCalledExactlyOnceWith(url, { signal, redirect: 'error', headers });
+ });
+
+ it.each([401, 403])('retries a rejected login (%s) once without credentials', async status => {
+ readToken.mockResolvedValue(token);
+ const rejected = new Response('rejected login', { status });
+ electronFetch.mockResolvedValueOnce(rejected).mockResolvedValueOnce(success());
+ const signal = new AbortController().signal;
+ await expect(piBinaryUpdateDefaults.fetchRelease(signal)).resolves.toEqual(release());
+ expect(rejected.bodyUsed).toBe(true);
+ expect(electronFetch).toHaveBeenCalledTimes(2);
+ expect(electronFetch).toHaveBeenNthCalledWith(1, url, {
+ signal, redirect: 'error', headers: { ...headers, Authorization: `Bearer ${token}` },
+ });
+ expect(electronFetch).toHaveBeenNthCalledWith(2, url, { signal, redirect: 'error', headers });
+ });
+
+ it.each([401, 403])('still retries anonymously when the rejected response (%s) stream has errored', async status => {
+ readToken.mockResolvedValue(token);
+ const body = new ReadableStream({ start(controller) { controller.error(new Error('network stream failed')); } });
+ electronFetch.mockResolvedValueOnce(new Response(body, { status })).mockResolvedValueOnce(success());
+ const signal = new AbortController().signal;
+ await expect(piBinaryUpdateDefaults.fetchRelease(signal)).resolves.toEqual(release());
+ expect(electronFetch).toHaveBeenCalledTimes(2);
+ expect(electronFetch).toHaveBeenNthCalledWith(2, url, { signal, redirect: 'error', headers });
+ });
+
+ it('keeps caller cancellation authoritative when response cleanup also fails', async () => {
+ readToken.mockResolvedValue(token);
+ const controller = new AbortController();
+ electronFetch.mockImplementationOnce(async () => {
+ controller.abort();
+ return new Response(new ReadableStream({ start(stream) { stream.error(new Error('network stream failed')); } }), { status: 401 });
+ });
+ await expect(piBinaryUpdateDefaults.fetchRelease(controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(electronFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([null, token])('bounds retries when anonymous access is also rate limited (login=%s)', async login => {
+ readToken.mockResolvedValue(login);
+ electronFetch.mockImplementation(async () => new Response('rate limited', { status: 403 }));
+ await expect(piBinaryUpdateDefaults.fetchRelease(new AbortController().signal)).rejects.toThrow('(403)');
+ expect(electronFetch).toHaveBeenCalledTimes(login ? 2 : 1);
+ });
+
+ it('does not retry server failures or expose response bodies in the error', async () => {
+ readToken.mockResolvedValue(token);
+ electronFetch.mockResolvedValue(new Response('private response detail', { status: 503 }));
+ await expect(piBinaryUpdateDefaults.fetchRelease(new AbortController().signal))
+ .rejects.toThrow(/^Pi release lookup failed \(503\)$/);
+ expect(electronFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not query credentials or the network after cancellation', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await expect(piBinaryUpdateDefaults.fetchRelease(controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(readToken).not.toHaveBeenCalled();
+ expect(electronFetch).not.toHaveBeenCalled();
+ });
+
+ it('preserves cancellation while reading credentials and before anonymous fallback', async () => {
+ const controller = new AbortController();
+ readToken.mockImplementationOnce(async () => { controller.abort(); return token; });
+ await expect(piBinaryUpdateDefaults.fetchRelease(controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(electronFetch).not.toHaveBeenCalled();
+
+ const retry = new AbortController();
+ readToken.mockResolvedValue(token);
+ electronFetch.mockImplementationOnce(async () => {
+ retry.abort();
+ return new Response('invalid login', { status: 401 });
+ });
+ await expect(piBinaryUpdateDefaults.fetchRelease(retry.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(electronFetch).toHaveBeenCalledTimes(1);
+ });
+});
describe('Pi standalone core update', () => {
it.each([200, 503])('uses Electron release lookup with the existing timeout and status handling (%s)', async status => {
const { root, current } = await fixture();
@@ -43,7 +144,7 @@ describe('Pi standalone core update', () => {
// Exercise the production defaults, stopping before download/version probes.
const error = await installPiBinaryUpdate(root, current, false, undefined, 'darwin', 'arm64').catch(error => error);
expect(electronFetch).toHaveBeenCalledWith('https://api.github.com/repos/earendil-works/pi/releases/latest', {
- signal: expect.any(AbortSignal), headers: { Accept: 'application/vnd.github+json' },
+ signal: expect.any(AbortSignal), redirect: 'error', headers: { Accept: 'application/vnd.github+json' },
});
expect(nodeFetch).not.toHaveBeenCalled();
expect(piBinaryUpdateFailureStage(error)).toBe(status === 200 ? 'asset-validation' : 'release-lookup');
diff --git a/apps/desktop/src/main/agent-binaries/pi-self-update.ts b/apps/desktop/src/main/agent-binaries/pi-self-update.ts
index 0c436b644c..7166d39965 100644
--- a/apps/desktop/src/main/agent-binaries/pi-self-update.ts
+++ b/apps/desktop/src/main/agent-binaries/pi-self-update.ts
@@ -8,6 +8,7 @@ import { download } from '../downloader/index.js';
import { extractMakeToolArchive } from '../cindy-make/toolArchive.js';
import { isBinaryVersionNotOlder, probeBinaryVersion } from './binary-version-probe.js';
import { createLogger } from '../logger.js';
+import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';
const log = createLogger('pi-self-update');
@@ -31,10 +32,27 @@ export interface PiBinaryUpdateDeps {
}
export const piBinaryUpdateDefaults: PiBinaryUpdateDeps = {
fetchRelease: async signal => {
+ signal.throwIfAborted();
+ // Reuse the host's GitHub login source; a missing/unavailable login must not
+ // prevent checking this public release. Never pass the token to downloads.
+ const token = await getSharedGhCliTokenSource().readToken().catch(() => null);
+ signal.throwIfAborted();
+ const url = 'https://api.github.com/repos/earendil-works/pi/releases/latest';
// Match the Electron downloader's system-proxy/PAC-aware network stack.
- const response = await net.fetch('https://api.github.com/repos/earendil-works/pi/releases/latest', {
- signal, headers: { Accept: 'application/vnd.github+json' },
+ let response = await net.fetch(url, {
+ signal, redirect: 'error',
+ headers: { Accept: 'application/vnd.github+json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
});
+ // A revoked/restricted login must not make public releases less accessible.
+ // Retry once without credentials, within the original caller's deadline.
+ if (token && (response.status === 401 || response.status === 403)) {
+ // Stream cleanup can fail independently of the release lookup.
+ await response.body?.cancel().catch(() => undefined);
+ signal.throwIfAborted();
+ response = await net.fetch(url, {
+ signal, redirect: 'error', headers: { Accept: 'application/vnd.github+json' },
+ });
+ }
if (!response.ok) throw new Error(`Pi release lookup failed (${response.status})`);
return response.json();
},
diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
index afaa4bf4e3..c959f895c5 100644
--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts
+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
@@ -107,7 +107,9 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
const bin = resolveGhBinary();
return new Promise<GhCliTokenReadResult>((resolve) => {
try {
- execFileFn(bin, ['auth', 'token'], { timeout: GH_TIMEOUT_MS }, (err, stdout) => {
+ // All consumers target public GitHub. Do not pick an enterprise token
+ // when GH_HOST or the CLI's default host points elsewhere.
+ execFileFn(bin, ['auth', 'token', '--hostname', 'github.com'], { timeout: GH_TIMEOUT_MS }, (err, stdout) => {
if (err) {
// 失败只 debug 级记录;原因分类留给 UI 决定引导动作。
const reason = classifyExecError(err);