Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(project-icons): github org avatar resolver + shared fetch core + IPC
enesdc16a04bc19d
diff --git a/src/core/github/avatar-fetcher.ts b/src/core/github/avatar-fetcher.tsindex c2157e0d2..e8b4c2b73 100644--- a/src/core/github/avatar-fetcher.ts+++ b/src/core/github/avatar-fetcher.ts@@ -32,6 +32,35 @@ async function boundedBytes(response: Response): Promise<Uint8Array | null> {return bytes}+/** The SSRF-hardened URL→dataURL core, shared by issue-user avatars and project org avatars.+ * Locked to avatars.githubusercontent.com over https, no credentials in the URL, redirect:'manual',+ * a MIME allowlist, and the 128 KB `boundedBytes` cap. Returns null on any rejection — never throws.+ * This is `GitHubAvatarFetcher.fetchOne` minus the per-user cache; do NOT fork the guard. */+export async function fetchAvatarDataUrl(+ url: string,+ fetchImpl: typeof fetch = fetch+): Promise<{ dataUrl: string; bytes: number } | null> {+ let parsed: URL+ try { parsed = new URL(url) } catch { return null }+ if (parsed.protocol !== 'https:' || parsed.hostname !== 'avatars.githubusercontent.com' ||+ parsed.username || parsed.password) return null+ let response: Response+ try {+ response = await fetchImpl(parsed, { method: 'GET', redirect: 'manual' })+ } catch {+ return null+ }+ if (!response.ok || response.status >= 300) return null+ const mime = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase()+ if (!mime || !MIME.has(mime)) return null+ const bytes = await boundedBytes(response)+ if (!bytes) return null+ return {+ dataUrl: `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`,+ bytes: bytes.byteLength+ }+}+export class GitHubAvatarFetcher {private readonly fetcher: typeof fetchprivate readonly cache = new Map<number, CacheEntry>()@@ -71,25 +100,10 @@ export class GitHubAvatarFetcher {private async fetchOne(user: GitHubIssueUser): Promise<CacheEntry | null> {let url: URLtry { url = new URL(user.avatarUrl) } catch { return null }- if (url.protocol !== 'https:' || url.hostname !== 'avatars.githubusercontent.com' ||- url.username || url.password) return nullurl.searchParams.set('size', '64')- let response: Response- try {- response = await this.fetcher(url, { method: 'GET', redirect: 'manual' })- } catch {- return null- }- if (!response.ok || response.status >= 300) return null- const mime = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase()- if (!mime || !MIME.has(mime)) return null- const bytes = await boundedBytes(response)- if (!bytes) return null- const entry = {- dataUrl: `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`,- bytes: bytes.byteLength,- expiresAt: this.now() + this.ttl- }+ const loaded = await fetchAvatarDataUrl(url.toString(), this.fetcher)+ if (!loaded) return null+ const entry = { ...loaded, expiresAt: this.now() + this.ttl }this.cache.set(user.id, entry)if (this.cache.size > 500) this.cache.delete(this.cache.keys().next().value!)return entrydiff --git a/src/core/github/integration.ts b/src/core/github/integration.tsindex 237187c9e..b2ddb697c 100644--- a/src/core/github/integration.ts+++ b/src/core/github/integration.ts@@ -7,6 +7,7 @@ import { GitHubIssuesClient } from './client'import { GitHubIssueCache } from './cache'import { GitHubRequestCoordinator } from './request-coordinator'import { GitHubAvatarFetcher } from './avatar-fetcher'+import { resolveProjectAvatarForProject } from './project-avatar'import { GitHubHostController } from './host'import { GitHubIssueService } from './service'import { registerGitHubIssueHandlers } from './handlers'@@ -66,5 +67,26 @@ export function registerGitHubIntegration(dependencies: Dependencies): {dependencies.platform.sendTo(uiId, IPC.githubIssuesChanged(projectId), changedIssueNumbers)})registerGitHubIssueHandlers(dependencies.platform, service)++ // Project org/user avatar. The handler receives only a projectId: it derives the owner host-side+ // from the project's own GitHub origin (a renderer never supplies a slug/owner) and resolves a+ // token via the shared credential resolver. Independent of kanban approval — an avatar is public —+ // and never throws: any failure (no origin, no auth, fetch failed, SSH host unreachable) is null.+ dependencies.platform.handle(IPC.githubProjectAvatar, async (projectId: string) => {+ try {+ const record = await dependencies.project(projectId)+ if (!record) return null+ const state = await controls.load()+ const credential = await resolver.resolve(state.authProvider)+ return await resolveProjectAvatarForProject({+ project: record.project,+ detectRepository: dependencies.detectRepository,+ token: credential?.token+ })+ } catch {+ return null+ }+ })+return { controller, service }}diff --git a/src/core/github/project-avatar.test.ts b/src/core/github/project-avatar.test.tsnew file mode 100644index 000000000..1462bead5--- /dev/null+++ b/src/core/github/project-avatar.test.ts@@ -0,0 +1,184 @@+import { describe, expect, it } from 'vitest'+import type { Project } from '../../shared/types'+import { fetchAvatarDataUrl } from './avatar-fetcher'+import { resolveProjectAvatarDataUrl, resolveProjectAvatarForProject } from './project-avatar'++const AVATAR = 'https://avatars.githubusercontent.com/u/1?v=4'++describe('fetchAvatarDataUrl', () => {+ it('fetches the validated avatar host with redirect:manual and returns a data URL', async () => {+ const calls: Array<{ url: string; init: RequestInit }> = []+ const result = await fetchAvatarDataUrl(AVATAR, async (url, init) => {+ calls.push({ url: String(url), init: init ?? {} })+ return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } })+ })+ expect(result).toEqual({ dataUrl: 'data:image/png;base64,AQID', bytes: 3 })+ expect(calls[0].init.redirect).toBe('manual')+ expect(new URL(calls[0].url).hostname).toBe('avatars.githubusercontent.com')+ })++ it('rejects a non-avatar host (SSRF guard)', async () => {+ let called = false+ const result = await fetchAvatarDataUrl('https://example.com/a.png', async () => {+ called = true+ return new Response(new Uint8Array([1]), { headers: { 'content-type': 'image/png' } })+ })+ expect(result).toBeNull()+ expect(called).toBe(false)+ })++ it('rejects credentials embedded in the URL', async () => {+ const result = await fetchAvatarDataUrl(+ 'https://user:[email protected]/u/1',+ async () => new Response(new Uint8Array([1]), { headers: { 'content-type': 'image/png' } })+ )+ expect(result).toBeNull()+ })++ it('rejects redirects, unsupported MIME types, and images above 128 KiB', async () => {+ const redirect = await fetchAvatarDataUrl(AVATAR, async () =>+ new Response(null, { status: 302, headers: { location: 'https://avatars.githubusercontent.com/x' } }))+ expect(redirect).toBeNull()+ const svg = await fetchAvatarDataUrl(AVATAR, async () =>+ new Response(new Uint8Array([1]), { headers: { 'content-type': 'image/svg+xml' } }))+ expect(svg).toBeNull()+ const oversized = await fetchAvatarDataUrl(AVATAR, async () =>+ new Response(new Uint8Array(128 * 1024 + 1), { headers: { 'content-type': 'image/png' } }))+ expect(oversized).toBeNull()+ })++ it('returns null when the fetch itself throws', async () => {+ const result = await fetchAvatarDataUrl(AVATAR, async () => { throw new Error('network') })+ expect(result).toBeNull()+ })+})++describe('resolveProjectAvatarDataUrl', () => {+ const userJson = (avatarUrl: unknown) =>+ new Response(JSON.stringify({ login: 'acme', avatar_url: avatarUrl }), {+ headers: { 'content-type': 'application/json' }+ })++ it('resolves owner -> avatar_url -> data URL', async () => {+ const seen: string[] = []+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: 'acme',+ token: 'tkn',+ fetchImpl: async (url, init) => {+ const href = String(url)+ seen.push(href)+ if (href === 'https://api.github.com/users/acme') {+ expect((init?.headers as Record<string, string>).authorization).toBe('Bearer tkn')+ expect(init?.redirect).toBe('manual')+ return userJson(AVATAR)+ }+ return new Response(new Uint8Array([9, 9]), { headers: { 'content-type': 'image/png' } })+ }+ })+ expect(dataUrl).toBe('data:image/png;base64,CQk=')+ expect(seen[0]).toBe('https://api.github.com/users/acme')+ })++ it('works without a token (unauthenticated)', async () => {+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: 'acme',+ fetchImpl: async (url) => {+ if (String(url) === 'https://api.github.com/users/acme') {+ return userJson(AVATAR)+ }+ return new Response(new Uint8Array([1]), { headers: { 'content-type': 'image/png' } })+ }+ })+ expect(dataUrl).toBe('data:image/png;base64,AQ==')+ })++ it('returns null when avatar_url is missing', async () => {+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: 'acme',+ fetchImpl: async () => userJson(undefined)+ })+ expect(dataUrl).toBeNull()+ })++ it('returns null when the user request is not ok', async () => {+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: 'acme',+ fetchImpl: async () => new Response('nope', { status: 404 })+ })+ expect(dataUrl).toBeNull()+ })++ it('never throws and returns null on a rejecting fetch', async () => {+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: 'acme',+ fetchImpl: async () => { throw new Error('boom') }+ })+ expect(dataUrl).toBeNull()+ })++ it('rejects an owner that would escape the users path', async () => {+ let called = false+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner: '../repos/secret',+ fetchImpl: async () => { called = true; return userJson(AVATAR) }+ })+ expect(dataUrl).toBeNull()+ expect(called).toBe(false)+ })+})++describe('resolveProjectAvatarForProject', () => {+ const project = (overrides: Partial<Project> = {}): Project =>+ ({ id: 'p1', name: 'p', ...overrides }) as unknown as Project++ it('derives the owner from the detected git origin (never a caller slug)', async () => {+ const result = await resolveProjectAvatarForProject({+ project: project(),+ detectRepository: async () => 'https://github.com/acme/widgets.git',+ fetchImpl: async (url) => {+ if (String(url) === 'https://api.github.com/users/acme') {+ return new Response(JSON.stringify({ avatar_url: AVATAR }), {+ headers: { 'content-type': 'application/json' }+ })+ }+ return new Response(new Uint8Array([7]), { headers: { 'content-type': 'image/png' } })+ }+ })+ expect(result).toEqual({ dataUrl: 'data:image/png;base64,Bw==' })+ })++ it('prefers the configured kanban repository owner over the detected origin', async () => {+ const owners: string[] = []+ await resolveProjectAvatarForProject({+ project: project({ kanban: { columns: [], github: { repository: 'configured-org/app' } } } as unknown as Partial<Project>),+ detectRepository: async () => 'https://github.com/detected-org/app',+ fetchImpl: async (url) => {+ owners.push(new URL(String(url)).pathname)+ return new Response(JSON.stringify({ avatar_url: null }), {+ headers: { 'content-type': 'application/json' }+ })+ }+ })+ expect(owners[0]).toBe('/users/configured-org')+ })++ it('returns null when the project has no GitHub origin', async () => {+ let called = false+ const result = await resolveProjectAvatarForProject({+ project: project(),+ detectRepository: async () => null,+ fetchImpl: async () => { called = true; return new Response('') }+ })+ expect(result).toBeNull()+ expect(called).toBe(false)+ })++ it('returns null (does not block) when origin detection throws', async () => {+ const result = await resolveProjectAvatarForProject({+ project: project(),+ detectRepository: async () => { throw new Error('ssh unreachable') },+ fetchImpl: async () => new Response('')+ })+ expect(result).toBeNull()+ })+})diff --git a/src/core/github/project-avatar.ts b/src/core/github/project-avatar.tsnew file mode 100644index 000000000..404542ab3--- /dev/null+++ b/src/core/github/project-avatar.ts@@ -0,0 +1,100 @@+import type { Project } from '../../shared/types'+import { fetchAvatarDataUrl } from './avatar-fetcher'+import { parseGitHubRepository } from './config'++const API_ORIGIN = 'https://api.github.com'+const API_VERSION = '2022-11-28'+const MAX_USER_JSON_BYTES = 64 * 1024+// A GitHub login: same shape as config's OWNER. Validated before it ever reaches the URL path so a+// hostile project.json owner cannot escape `/users/{owner}` into another api.github.com route.+const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/++async function boundedJson(response: Response): Promise<Record<string, unknown> | null> {+ const length = Number(response.headers.get('content-length'))+ if (Number.isFinite(length) && length > MAX_USER_JSON_BYTES) return null+ if (!response.body) return null+ const reader = response.body.getReader()+ const chunks: Uint8Array[] = []+ let total = 0+ while (true) {+ const next = await reader.read()+ if (next.done) break+ total += next.value.byteLength+ if (total > MAX_USER_JSON_BYTES) { await reader.cancel(); return null }+ chunks.push(next.value)+ }+ const bytes = new Uint8Array(total)+ let offset = 0+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }+ try {+ const value = JSON.parse(new TextDecoder().decode(bytes)) as unknown+ return value !== null && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null+ } catch {+ return null+ }+}++/** GET api.github.com/users/{owner} (fixed host, https, no creds in URL, redirect:'manual', bounded+ * JSON) → `.avatar_url` → the locked avatars.githubusercontent.com fetch. Null on missing avatar,+ * a non-ok response, or any fetch failure. NEVER throws. */+export async function resolveProjectAvatarDataUrl(deps: {+ owner: string+ token?: string+ fetchImpl?: typeof fetch+}): Promise<string | null> {+ const fetchImpl = deps.fetchImpl ?? fetch+ if (!OWNER.test(deps.owner)) return null+ const url = new URL(`/users/${deps.owner}`, API_ORIGIN)+ if (url.origin !== API_ORIGIN) return null+ try {+ const response = await fetchImpl(url, {+ method: 'GET',+ redirect: 'manual',+ headers: {+ accept: 'application/vnd.github+json',+ 'x-github-api-version': API_VERSION,+ ...(deps.token ? { authorization: `Bearer ${deps.token}` } : {})+ }+ })+ if (!response.ok || response.status >= 300) return null+ const body = await boundedJson(response)+ const avatarUrl = body?.avatar_url+ if (typeof avatarUrl !== 'string') return null+ const loaded = await fetchAvatarDataUrl(avatarUrl, fetchImpl)+ return loaded?.dataUrl ?? null+ } catch {+ return null+ }+}++/** Host-side resolution keyed on a trusted project: derive the owner from the project's own GitHub+ * origin (configured kanban repository, else the detected git origin — which for an SSH project is+ * its remoteCwd via the same originUrl path) and hand it to the resolver. A caller never supplies a+ * slug/owner. Null when the project has no GitHub origin or origin detection is unreachable. */+export async function resolveProjectAvatarForProject(deps: {+ project: Project+ detectRepository(project: Project): Promise<string | null>+ token?: string+ fetchImpl?: typeof fetch+}): Promise<{ dataUrl: string } | null> {+ const configured = deps.project.kanban?.github?.repository+ ? parseGitHubRepository(deps.project.kanban.github.repository)+ : null+ let detected: string | null = null+ try {+ detected = parseGitHubRepository(await deps.detectRepository(deps.project))+ } catch {+ detected = null+ }+ const repository = configured ?? detected+ if (!repository) return null+ const owner = repository.split('/')[0]+ const dataUrl = await resolveProjectAvatarDataUrl({+ owner,+ token: deps.token,+ fetchImpl: deps.fetchImpl+ })+ return dataUrl ? { dataUrl } : null+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex f699e0637..60e96d4c9 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -210,6 +210,7 @@ const api: NodeTerminalApi = {moveIssue: (request) => ipcRenderer.invoke(IPC.githubIssuesMove, request),createMissingLabels: (projectId) => ipcRenderer.invoke(IPC.githubIssuesCreateLabels, projectId),clearCache: (projectId) => ipcRenderer.invoke(IPC.githubIssuesClearCache, projectId),+ projectAvatar: (projectId) => ipcRenderer.invoke(IPC.githubProjectAvatar, projectId),onChanged: (projectId, listener) => {const channel = IPC.githubIssuesChanged(projectId)const handler = (_event: unknown, changed: number[]) => listener(changed)diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 200a30c5c..88cb8cbd2 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -419,6 +419,10 @@ export function buildGitHubApi(>,clearCache: (projectId) =>client.request(IPC.githubIssuesClearCache, projectId) as Promise<void>,+ projectAvatar: (projectId) =>+ client.request(IPC.githubProjectAvatar, projectId) as ReturnType<+ GitHubIssuesApi['projectAvatar']+ >,onChanged: (projectId, listener) =>client.subscribe(IPC.githubIssuesChanged(projectId), listener as Listener)}diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.tsindex 036f29232..10dee26ec 100644--- a/src/renderer/state/githubIssues.test.ts+++ b/src/renderer/state/githubIssues.test.ts@@ -25,6 +25,7 @@ function api(): GitHubIssuesApi {moveIssue: vi.fn(async () => ({ status: 'configuration-changed' as const })),createMissingLabels: vi.fn(async () => ({ status: 'confirmed' as const, created: [], remaining: [] })),clearCache: vi.fn(async () => {}),+ projectAvatar: vi.fn(async () => null),onChanged: vi.fn(() => () => {})}}diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.tsindex 2b49e7a0e..7f3e5782a 100644--- a/src/shared/github-issues.ts+++ b/src/shared/github-issues.ts@@ -190,6 +190,10 @@ export interface GitHubIssuesApi {createMissingLabels(projectId: string): Promise<CreateMappedLabelsResult>clearCache(projectId: string): Promise<void>onChanged(projectId: string, listener: (changedIssueNumbers: number[]) => void): () => void+ /** Resolve the project's GitHub org/user avatar (owner derived host-side from the project's own+ * origin — never a caller-supplied slug). Null when the project has no GitHub origin or the+ * avatar cannot be fetched. */+ projectAvatar(projectId: string): Promise<{ dataUrl: string } | null>}export interface GitHubControlApi {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex fdbbb0270..ac65f43be 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -325,6 +325,7 @@ export const IPC = {githubIssuesCreateLabels: 'githubIssues:create-labels',githubIssuesClearCache: 'githubIssues:clear-cache',githubIssuesChanged: (projectId: string) => `githubIssues:changed:${projectId}`,+ githubProjectAvatar: 'github:projectAvatar',githubControlStatus: 'githubControl:status',githubControlApprove: 'githubControl:approve',githubControlRevoke: 'githubControl:revoke',