The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): authenticate the update check's GitHub API calls
DaxLee998844af26851390
diff --git a/apps/desktop/electron/github-api-auth.test.ts b/apps/desktop/electron/github-api-auth.test.tsnew file mode 100644index 00000000000..76782ae7770--- /dev/null+++ b/apps/desktop/electron/github-api-auth.test.ts@@ -0,0 +1,71 @@+import assert from 'node:assert/strict'++import { test } from 'vitest'++import { githubApiHeaders, githubTokenFromEnv, resolveGithubToken } from './github-api-auth'++// The exact headers the anonymous update check sends today; the change must+// leave this shape byte-identical when no token is configured.+const UPDATE_CHECK_HEADERS = {+ Accept: 'application/vnd.github.sha',+ 'User-Agent': 'hermes-desktop-update-check'+}++test('GITHUB_TOKEN wins over GH_TOKEN', () => {+ assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: 'pat-a', GH_TOKEN: 'pat-b' }), 'pat-a')+})++test('a blank env token falls through to the next var, and the value is trimmed', () => {+ assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: ' ', GH_TOKEN: ' pat-b ' }), 'pat-b')+ assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: '', GH_TOKEN: '' }), null)+ assert.equal(githubTokenFromEnv({}), null)+})++test('the anonymous path sends no Authorization key at all', () => {+ const headers = githubApiHeaders(UPDATE_CHECK_HEADERS, null)++ assert.deepEqual(headers, UPDATE_CHECK_HEADERS)+ assert.equal('Authorization' in headers, false)+})++test('a token adds the `token`-scheme Authorization header without disturbing the base headers', () => {+ const headers = githubApiHeaders(UPDATE_CHECK_HEADERS, 'pat-a')++ assert.equal(headers.Authorization, 'token pat-a')+ assert.equal(headers['User-Agent'], 'hermes-desktop-update-check')+ // The caller's base object is a constant; mutating it would leak the token+ // into every later request that builds from it.+ assert.equal('Authorization' in UPDATE_CHECK_HEADERS, false)+})++test('the gh CLI is consulted only when the env rung is empty', async () => {+ let ghCalls = 0++ const readGhCliToken = async () => {+ ghCalls += 1++ return 'gh-token'+ }++ assert.deepEqual(await resolveGithubToken({ env: { GH_TOKEN: 'pat-a' }, readGhCliToken }), {+ token: 'pat-a',+ source: 'env'+ })+ assert.equal(ghCalls, 0)++ assert.deepEqual(await resolveGithubToken({ env: {}, readGhCliToken }), { token: 'gh-token', source: 'gh-cli' })+ assert.equal(ghCalls, 1)+})++test('a missing, blank or failing gh degrades to the anonymous path instead of throwing', async () => {+ const missing = async () => null+ const blank = async () => ' '++ const failing = async () => {+ throw new Error('spawn gh ENOENT')+ }++ assert.deepEqual(await resolveGithubToken({ readGhCliToken: missing }), { token: null, source: 'none' })+ assert.deepEqual(await resolveGithubToken({ readGhCliToken: blank }), { token: null, source: 'none' })+ assert.deepEqual(await resolveGithubToken({ readGhCliToken: failing }), { token: null, source: 'none' })+})diff --git a/apps/desktop/electron/github-api-auth.ts b/apps/desktop/electron/github-api-auth.tsnew file mode 100644index 00000000000..7b23c0916d0--- /dev/null+++ b/apps/desktop/electron/github-api-auth.ts@@ -0,0 +1,83 @@+// Credentials for the self-update check's api.github.com calls.+//+// The passive check asks the REST API for the branch tip SHA. Unauthenticated+// that budget is 60 requests/hour keyed on the *client IP*, so a shared exit —+// office NAT, VPN, a proxy node many users sit behind — exhausts the bucket for+// everyone on it and the check reports a rate limit that reads as "Hermes can't+// reach the update server". Authenticating moves the caller onto the token's+// 5,000/hour budget.+//+// Precedence mirrors the Python client (tools/skills_hub_github.py::GitHubAuth):+// GITHUB_TOKEN / GH_TOKEN first, then the `gh` CLI's own keyring token. The+// ladder itself stays subprocess-free and pure; the `gh` lookup is injected by+// the caller (main.ts owns the binary resolution and the child process).++export type GithubTokenSource = 'env' | 'gh-cli' | 'none'++export interface GithubTokenResolution {+ token: string | null+ source: GithubTokenSource+}++/** Env vars consulted, in precedence order. */+export const GITHUB_TOKEN_ENV_VARS = ['GITHUB_TOKEN', 'GH_TOKEN'] as const++/** First non-blank env token, trimmed. A blank value falls through to the next. */+export function githubTokenFromEnv(env: Record<string, string | undefined> = {}): string | null {+ for (const name of GITHUB_TOKEN_ENV_VARS) {+ const value = env[name]++ if (typeof value === 'string' && value.trim()) {+ return value.trim()+ }+ }++ return null+}++/**+ * Headers for api.github.com. The `token` scheme (not `Bearer`) matches the+ * Python client. Anonymous callers get the base headers untouched: an empty+ * `Authorization` header is a 401, so it must be absent, not blank.+ */+export function githubApiHeaders(base: Record<string, string>, token?: string | null): Record<string, string> {+ const headers = { ...base }++ if (token) {+ headers.Authorization = `token ${token}`+ }++ return headers+}++/**+ * Resolve a token for api.github.com. `gh` runs only when the env rung is+ * empty, and a missing / unauthenticated / slow `gh` resolves to+ * `{ token: null, source: 'none' }` rather than throwing: the anonymous+ * 60/hour budget is a legitimate fallback rung, not an error.+ */+export async function resolveGithubToken({+ env = {},+ readGhCliToken+}: {+ env?: Record<string, string | undefined>+ readGhCliToken?: () => Promise<string | null>+} = {}): Promise<GithubTokenResolution> {+ const fromEnv = githubTokenFromEnv(env)++ if (fromEnv) {+ return { token: fromEnv, source: 'env' }+ }++ if (!readGhCliToken) {+ return { token: null, source: 'none' }+ }++ try {+ const token = (await readGhCliToken())?.trim()++ return token ? { token, source: 'gh-cli' } : { token: null, source: 'none' }+ } catch {+ return { token: null, source: 'none' }+ }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex fc471b7ea09..6d02638e232 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -1,4 +1,4 @@-import { execFileSync, spawn } from 'node:child_process'+import { execFile, execFileSync, spawn } from 'node:child_process'import crypto from 'node:crypto'import fs from 'node:fs'import http from 'node:http'@@ -217,6 +217,7 @@ import {import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'import { probeGatewayWebSocket } from './gateway-ws-probe'import { registerGitIpc } from './git-ipc'+import { githubApiHeaders, resolveGithubToken } from './github-api-auth'import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'import { readAndConsumeHandoffResult } from './handoff-result'import {@@ -2993,6 +2994,45 @@ function resolveGhBinary() {return _ghBinaryCache}+// Credentials for the update check's api.github.com calls: env first (an+// explicit GITHUB_TOKEN / GH_TOKEN wins), then the `gh` CLI's keyring token —+// the same ladder the Python client uses (tools/skills_hub_github.py). A shared+// exit IP (proxy/VPN/office NAT) exhausts the anonymous 60/hour budget for+// everyone behind it, which is what makes an update check report a rate limit.+//+// Resolved once per process: a token cannot change under a running app, and+// re-shelling `gh` on every check would be pure work. Anonymous stays a valid+// rung — a missing `gh` is not an error.+let _githubApiTokenCache = null+let _githubApiTokenResolved = false++function readGhCliToken(): Promise<string | null> {+ return new Promise(resolve => {+ execFile(+ resolveGhBinary(),+ ['auth', 'token'],+ { env: process.env, windowsHide: true, timeout: 5_000 },+ (err, stdout) => resolve(err ? null : String(stdout || ''))+ )+ })+}++async function resolveGithubApiToken() {+ if (!_githubApiTokenResolved) {+ const { token, source } = await resolveGithubToken({ env: process.env, readGhCliToken })++ _githubApiTokenCache = token+ _githubApiTokenResolved = true++ if (token) {+ // One line, so a rate-limit report can name the budget the check spent.+ rememberLog(`[updates] api.github.com credentials: ${source}`)+ }+ }++ return _githubApiTokenCache+}+function recentHermesLog() {return hermesLog.slice(-20).join('\n')}@@ -3364,16 +3404,21 @@ function describeUpdateCheckFailure(error) {return `api.github.com: ${error?.message || String(error)}`}-function fetchGitHubApi(url, accept = 'application/vnd.github+json') {+async function fetchGitHubApi(url, accept = 'application/vnd.github+json') {+ const token = await resolveGithubApiToken()+return new Promise((resolve, reject) => {const req = https.get(url,{- headers: {- Accept: accept,- // GitHub requires a UA on api.github.com; requests without one 403.- 'User-Agent': 'hermes-desktop-update-check'- },+ headers: githubApiHeaders(+ {+ Accept: accept,+ // GitHub requires a UA on api.github.com; requests without one 403.+ 'User-Agent': 'hermes-desktop-update-check'+ },+ token+ ),timeout: 10_000},res => {