Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Swarm projects' GitHub access: shown and approved in the app; tokens only for approved repositories

bitcoinbuilder491c23ad45ad
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
index 6e24e2275..31664f53b 100644
--- a/backend/integration/superTabGithub.test.ts
+++ b/backend/integration/superTabGithub.test.ts
@@ -10,6 +10,7 @@ import Fastify, { type FastifyInstance } from 'fastify'
import type { AuthUser } from '../src/lib/ssoAuth.js'
import { SuperTabStore } from '../src/superTabs/store.js'
import { superTabRoutes } from '../src/routes/superTabs.js'
+import type { Approvals, GitHubSignIn } from '../src/github/approvals.js'
import { errorHandler } from '../src/middlewares/errorHandler.js'
import type { Command } from '../src/superTabs/commands.js'
import { GitHubTokens, MemoryTokenCache } from '../src/github/tokens.js'
@@ -49,7 +50,7 @@ afterAll(async () => {
})
/** One control API with the app configured against a fresh fake GitHub, its store revoking as tasks end. */
-async function fresh(options: { github?: boolean } = {}) {
+async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?: GitHubSignIn | null } = {}) {
const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242' })
github.installed.set('example/app', 91)
const log = { warn: vi.fn() }
@@ -59,16 +60,25 @@ async function fresh(options: { github?: boolean } = {}) {
const app: FastifyInstance = Fastify()
app.setErrorHandler(errorHandler)
app.addHook('onRequest', async (request, reply) => {
+ // GitHub sends a person back here without a Harness token, as the server's own gate lets it (authMiddleware.ts).
+ if (request.url.startsWith('/api/github/callback')) return
const user = users.find(u => `Bearer ${u.sub}` === request.headers.authorization)
if (!user) return reply.code(401).send({ success: false })
request.user = user
})
- await app.register(superTabRoutes, { store, github: options.github === false ? null : tokens })
+ // Every project approved unless a test says otherwise (github/approvals.ts); what was approved, kept here.
+ const approved: Array<{ tabId: string; projectId: string; repository: string; scope: string; login: string }> = []
+ const approvals: Approvals = {
+ approved: async (_env, tabId, projectId, repository) => options.approveAll !== false
+ || approved.some(a => a.tabId === tabId && a.repository === repository.toLowerCase() && (a.scope === 'swarm' || a.projectId === projectId)),
+ approve: async (request, login) => { approved.push({ ...request, login }) },
+ }
+ await app.register(superTabRoutes, { store, github: options.github === false ? null : tokens, approvals, signIn: options.signIn ?? null })
await app.ready()
const run = (tab: string, command: Command, user = owner, asAgentId?: string) =>
store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
const settled = async () => { await Promise.all(releases.splice(0)) }
- return { github, log, tokens, store, app, run, settled }
+ return { github, log, tokens, store, app, run, settled, approved }
}
type Env = Awaited<ReturnType<typeof fresh>>
@@ -227,6 +237,53 @@ describe('a queued start\'s preparation token', () => {
expect(minted.body).toEqual({ repositories: ['app'], permissions: { contents: 'read', metadata: 'read' } })
})
+ it('gives no token for a repository nobody who can push to it approved for the project', async () => {
+ const env = await fresh({ approveAll: false })
+ const { tab, startId } = await queued(env)
+ const response = await prepare(env, tab, startId)
+ expect(response.statusCode).toBe(403)
+ expect(response.json().error).toMatchObject({ code: 'GITHUB_REPOSITORY_NOT_APPROVED' })
+ expect(env.github.calls.some(c => c.path.endsWith('/access_tokens'))).toBe(false)
+ })
+
+ it('approves a repository through the app\'s sign-in, for someone who can push to it, and gives the token after', async () => {
+ let push = true
+ const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,
+ permission: async () => ({ login: 'olive', push }) } as unknown as GitHubSignIn
+ const env = await fresh({ approveAll: false, signIn })
+ const { tab, startId } = await queued(env)
+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/lead/github/approve`,
+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'project' } })
+ expect(asked.statusCode, asked.body).toBe(200)
+ const { authorizeUrl, installUrl } = asked.json().data as { authorizeUrl: string; installUrl: string }
+ expect(installUrl).toMatch(/\/installations\/new\?state=/)
+ const state = new URL(authorizeUrl).searchParams.get('state')!
+ // Someone who cannot push is told so, and nothing is approved.
+ push = false
+ const refused = await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })
+ expect(refused.statusCode).toBe(403)
+ expect(refused.body).toContain('can&#39;t push to example/app')
+ push = true
+ const done = await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })
+ expect(done.statusCode).toBe(200)
+ expect(done.body).toContain('example/app approved')
+ expect(env.approved).toEqual([expect.objectContaining({ tabId: tab, projectId: 'lead', repository: 'example/app', scope: 'project', login: 'olive' })])
+ expect((await prepare(env, tab, startId)).statusCode).toBe(200)
+ // A forged or missing state, or an installation without a sign-in, approves nothing.
+ expect((await env.app.inject({ method: 'GET', url: '/api/github/callback?code=c&state=forged.state' })).statusCode).toBe(400)
+ const installed = await env.app.inject({ method: 'GET', url: `/api/github/callback?installation_id=9&setup_action=install&state=${encodeURIComponent(state)}` })
+ expect(installed.body).toContain('Harness is installed')
+ expect(env.approved).toHaveLength(1)
+ })
+
+ it('says when the server cannot approve, and refuses a project not on GitHub', async () => {
+ const env = await fresh({ approveAll: false })
+ const { tab } = await queued(env)
+ const none = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/lead/github/approve`,
+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'swarm' } })
+ expect(none.json().error).toMatchObject({ code: 'GITHUB_APPROVAL_NOT_CONFIGURED' })
+ })
+
it('answers no token for the machine owner\'s own project, unless its host asks for one anyway', async () => {
const env = await fresh()
const { tab, startId } = await queued(env, 'owner-pool', owner)
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index 19b57c953..ad0009fea 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -455,6 +455,19 @@ describe('a teammate\'s work and the machines that take it', () => {
// One machine (docs/plans/2026-10-24-swarm-team-account.md): the person's Mac and its Harness Team account are one
// machine. Its team account joins where the Mac is added, through the Mac's own daemon, and takes the teammates' work
// started on the Mac.
+describe('a project\'s repository, for its GitHub access', () => {
+ it('is read by those who may open the project, and by nobody else', async () => {
+ const f = await fixture()
+ expect(await store.projectRepository(owner, f.tab, 'lead')).toBeNull()
+ await run(f.tab, { type: 'tab.project', machineId: 'owner-host', project: { cwd: '/work', repositoryUrl: 'https://github.com/acme/app' } })
+ expect(await store.projectRepository(owner, f.tab, 'lead')).toBe('https://github.com/acme/app')
+ expect(await store.projectRepository(person, f.tab, 'lead')).toBe('https://github.com/acme/app')
+ const secret = String((await run(f.tab, { type: 'project.create', name: 'Secret', visibility: 'private', brief: '' })).result.projectId)
+ await expect(store.projectRepository(person, f.tab, secret)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(store.projectRepository(owner, f.tab, 'nope')).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+})
+
describe('one machine: a Mac and its Harness Team account', () => {
it('with no GitHub App on the server, the team account is never asked to join', async () => {
await db.machine.update({ where: { machineId: 'team-mac' }, data: { hostMachineId: 'personal-mac' } })
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index d0c90f1fd..4c92ea471 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1687,3 +1687,22 @@ model ConnectorApp {
@@map("connector_apps")
}
+
+/// A Swarm's approval to use a GitHub repository for teammates' work (docs/plans/2026-10-28-swarm-project-github-access.md):
+/// someone GitHub says can push to it approved it, signed in to GitHub through the Harness GitHub App. Without one, the
+/// app gives no token for the repository, so a project cannot name a repository its people cannot push to and borrow the
+/// app's access to it. `projectId` "*": every project of the Swarm.
+model GitHubRepositoryApproval {
+ id String @id @map("_id")
+ autonomousEnv String
+ tabId String
+ projectId String
+ /// owner/name, lower case, as the project names it.
+ repository String
+ approvedBy String
+ githubLogin String
+ createdAt DateTime @default(now())
+
+ @@unique([autonomousEnv, tabId, repository, projectId])
+ @@index([tabId])
+}
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 99fcfde83..06c1fb84a 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -245,6 +245,10 @@ const envSchema = z.object({
GITHUB_APP_PRIVATE_KEY: z.string().default(''),
// The app's name in github.com/apps/NAME, for the install link a refusal gives. Optional.
GITHUB_APP_SLUG: z.string().default(''),
+ // The app's own GitHub sign-in (its Client ID and a client secret), with which a person who can push to a repository
+ // approves it for a Swarm (github/approvals.ts). Unset, no repository can be approved and the app gives no token.
+ GITHUB_APP_CLIENT_ID: z.string().default(''),
+ GITHUB_APP_CLIENT_SECRET: z.string().default(''),
// TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path
// (avoids a Mongo lookup per request). Bounds staleness after a cross-instance app teardown.
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index 87b0f8d34..90c433c7e 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -70,6 +70,8 @@ export interface DefaultBranch { branch: string | null; protection: BranchProtec
const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')
const INSTALLATION_TTL_MS = 10 * 60_000
const NOT_INSTALLED_TTL_MS = 60_000
+/** How often a person's "check again" may make the server ask GitHub again about one repository. */
+const REFRESH_MS = 15_000
const BRANCH_TTL_MS = 10 * 60_000
const REQUEST_TIMEOUT_MS = 10_000
@@ -89,6 +91,8 @@ export class GitHubApp {
private readonly branches = new Map<string, { value: DefaultBranch; until: number }>()
/** A repository's name now, by the name asked for (lower case): null when it was not renamed. */
private readonly renames = new Map<string, { repository: GitHubRepository | null; until: number }>()
+ /** When each repository's "not installed" was last forgotten on request ([forget]). */
+ private readonly forgotten = new Map<string, number>()
constructor(readonly config: GitHubAppConfig, options: GitHubAppOptions = {}) {
this.fetch = options.fetch ?? fetch
@@ -218,6 +222,17 @@ export class GitHubApp {
return null
}
+ /** Forgets that the app was not on [repository] (and its rename), so the next lookup asks GitHub: a person just
+ * installed it. At most once every REFRESH_MS per repository, so a refresh cannot become a stream of lookups. */
+ forget(repository: GitHubRepository): void {
+ const key = repository.fullName.toLowerCase()
+ const last = this.forgotten.get(key)
+ if (last !== undefined && this.now() - last < REFRESH_MS) return
+ this.forgotten.set(key, this.now())
+ if (this.installations.get(key)?.id === null) this.installations.delete(key)
+ if (this.renames.get(key)?.repository === null) this.renames.delete(key)
+ }
+
/** A token for [repository] alone, with TOKEN_PERMISSIONS alone. */
async createToken(installationId: number, repository: GitHubRepository, permissions: TokenPermissions = TOKEN_PERMISSIONS): Promise<{ token: string; expiresAt: string }> {
const answer = await this.call('POST', `/app/installations/${installationId}/access_tokens`, `Bearer ${this.jwt()}`,
diff --git a/backend/src/github/approvals.test.ts b/backend/src/github/approvals.test.ts
new file mode 100644
index 000000000..d975218cd
--- /dev/null
+++ b/backend/src/github/approvals.test.ts
@@ -0,0 +1,92 @@
+import { createHmac, randomBytes } from 'node:crypto'
+import { describe, expect, it, vi } from 'vitest'
+import { GitHubSignIn, githubSignIn, PrismaApprovals, readState, signState, STATE_TTL_MS, stateSecret, WHOLE_SWARM, type ApprovalRequest } from './approvals.js'
+import { throwawayKey } from './fakeGitHub.js'
+import { githubRepository } from './repository.js'
+
+const request: ApprovalRequest = { userId: 'alice', autonomousEnv: 'prod', tabId: 'tab', projectId: 'p1', repository: 'alice/a', scope: 'project' }
+const repo = githubRepository('https://github.com/alice/a')!
+
+describe('a sign-in\'s state', () => {
+ it('comes back as it was signed, within ten minutes, and never changed or from elsewhere', () => {
+ const secret = randomBytes(32), now = 1_000_000
+ const state = signState(secret, request, now)
+ expect(readState(secret, state, now + STATE_TTL_MS - 1)).toEqual(request)
+ expect(readState(secret, state, now + STATE_TTL_MS + 1)).toBeNull()
+ expect(readState(randomBytes(32), state, now)).toBeNull()
+ const [body, signature] = state.split('.')
+ const forged = Buffer.from(JSON.stringify({ ...request, projectId: 'other', exp: now + 1000 })).toString('base64url')
+ for (const bad of [`${forged}.${signature}`, `${body}`, `${body}.${signature}.x`, `${body}.short`, '']) expect(readState(secret, bad, now)).toBeNull()
+ const sealed = (body: string) => `${body}.${createHmac('sha256', secret).update(body).digest('base64url')}`
+ const sign = (value: unknown) => sealed(Buffer.from(JSON.stringify(value)).toString('base64url'))
+ expect(readState(secret, sign({ ...request, scope: 'everything', exp: now + 1000 }), now)).toBeNull()
+ expect(readState(secret, sign({ ...request, tabId: '', exp: now + 1000 }), now)).toBeNull()
+ expect(readState(secret, sealed(Buffer.from('{').toString('base64url')), now)).toBeNull()
+ })
+
+ it('is signed with a key of the app\'s own, the same each time', () => {
+ const config = { appId: '1', privateKey: throwawayKey().privateKey, slug: null }
+ expect(stateSecret(config)).toEqual(stateSecret(config))
+ expect(stateSecret(config)).toHaveLength(32)
+ })
+})
+
+describe('the app\'s GitHub sign-in', () => {
+ const fake = (repoStatus = 200, permissions: Record<string, boolean> = { push: true }, tokenOk = true) => {
+ const calls: Array<{ url: string; method: string }> = []
+ const fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const u = String(url), method = init?.method ?? 'GET'
+ calls.push({ url: u, method })
+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status })
+ if (u.endsWith('/login/oauth/access_token')) return tokenOk ? json(200, { access_token: 'ghu_fixture' }) : json(200, { error: 'bad_verification_code' })
+ if (u.endsWith('/user')) return json(200, { login: 'alice' })
+ if (u.includes('/repos/')) return json(repoStatus, repoStatus === 200 ? { permissions } : { message: 'Not Found' })
+ if (method === 'DELETE') return new Response(null, { status: 204 })
+ return json(404, {})
+ }) as unknown as typeof globalThis.fetch
+ return { signIn: new GitHubSignIn({ clientId: 'Iv23client', clientSecret: 'secret', fetch, webUrl: 'https://gh.test', apiUrl: 'https://api.gh.test' }), calls }
+ }
+
+ it('sends the person to GitHub with the state', () => {
+ expect(fake().signIn.authorizeUrl('a.b')).toBe('https://gh.test/login/oauth/authorize?client_id=Iv23client&state=a.b')
+ })
+
+ it('says whether the person can push, and revokes their token at once whatever it found', async () => {
+ const pusher = fake()
+ expect(await pusher.signIn.permission('code', repo)).toEqual({ login: 'alice', push: true })
+ expect(pusher.calls.at(-1)).toEqual({ url: 'https://api.gh.test/applications/Iv23client/token', method: 'DELETE' })
+ for (const permissions of [{ maintain: true }, { admin: true }] as Array<Record<string, boolean>>) expect((await fake(200, permissions).signIn.permission('c', repo))?.push).toBe(true)
+ expect(await fake(200, { pull: true }).signIn.permission('c', repo)).toEqual({ login: 'alice', push: false })
+ const hidden = fake(404)
+ expect(await hidden.signIn.permission('c', repo)).toEqual({ login: 'alice', push: false })
+ expect(hidden.calls.some(c => c.method === 'DELETE')).toBe(true)
+ expect(await fake(200, {}, false).signIn.permission('c', repo)).toBeNull()
+ })
+
+ it('is on with both its client id and secret, off with neither, and refuses one alone', () => {
+ expect(githubSignIn({ GITHUB_APP_CLIENT_ID: '', GITHUB_APP_CLIENT_SECRET: '' })).toBeNull()
+ expect(githubSignIn({ GITHUB_APP_CLIENT_ID: 'Iv23', GITHUB_APP_CLIENT_SECRET: 's' })).toBeInstanceOf(GitHubSignIn)
+ expect(() => githubSignIn({ GITHUB_APP_CLIENT_ID: 'Iv23', GITHUB_APP_CLIENT_SECRET: '' })).toThrow('or neither')
+ })
+})
+
+describe('approvals', () => {
+ it('cover the project approved, or every project of the Swarm, for that repository alone', async () => {
+ const rows: Array<Record<string, string>> = []
+ const db = { gitHubRepositoryApproval: {
+ findFirst: vi.fn(async ({ where }: { where: { autonomousEnv: string; tabId: string; repository: string; projectId: { in: string[] } } }) =>
+ rows.find(r => r.autonomousEnv === where.autonomousEnv && r.tabId === where.tabId && r.repository === where.repository && where.projectId.in.includes(r.projectId!)) ?? null),
+ upsert: vi.fn(async ({ create }: { create: Record<string, string> }) => { rows.push(create); return create }),
+ } }
+ const approvals = new PrismaApprovals(db as never)
+ expect(await approvals.approved('prod', 'tab', 'p1', 'alice/a')).toBe(false)
+ await approvals.approve(request, 'alice')
+ expect(await approvals.approved('prod', 'tab', 'p1', 'Alice/A')).toBe(true)
+ expect(await approvals.approved('prod', 'tab', 'p2', 'alice/a')).toBe(false)
+ expect(await approvals.approved('prod', 'tab', 'p1', 'bob/b')).toBe(false)
+ await approvals.approve({ ...request, scope: 'swarm' }, 'alice')
+ expect(rows.at(-1)!.projectId).toBe(WHOLE_SWARM)
+ expect(await approvals.approved('prod', 'tab', 'p2', 'alice/a')).toBe(true)
+ expect(await approvals.approved('prod', 'other-tab', 'p2', 'alice/a')).toBe(false)
+ })
+})
diff --git a/backend/src/github/approvals.ts b/backend/src/github/approvals.ts
new file mode 100644
index 000000000..ba68070a0
--- /dev/null
+++ b/backend/src/github/approvals.ts
@@ -0,0 +1,134 @@
+/**
+ * Which repositories a Swarm may use the Harness GitHub App on (docs/plans/2026-10-28-swarm-project-github-access.md).
+ *
+ * A project's repository address is text its owner types, and the app is installed on many people's repositories: without
+ * this, anyone could name a repository the app is on as their project's and have the backend mint write tokens for it
+ * (found 2026-10-28, with the app on autonomous-ai/openharness). Now a token goes to a project only once someone GitHub
+ * says can push to the repository approved it, for that project or for every project of the Swarm. They approve by
+ * signing in to GitHub through the app's own sign-in (its Client ID and secret): their short-lived token reads their
+ * permission on the repository, is revoked at once, and is never stored.
+ */
+import { createHmac, hkdfSync, randomUUID, timingSafeEqual } from 'node:crypto'
+import type { PrismaClient } from '@prisma/client'
+import type { GitHubAppConfig } from './app.js'
+import type { GitHubRepository } from './repository.js'
+
+/** Every project of the Swarm, in an approval's `projectId`. */
+export const WHOLE_SWARM = '*'
+/** How long a sign-in may take, from the app asking to GitHub sending the person back. */
+export const STATE_TTL_MS = 10 * 60_000
+
+/** What a sign-in is for: who asked, in which Swarm and project, for which repository, and how widely. */
+export interface ApprovalRequest {
+ userId: string
+ autonomousEnv: string
+ tabId: string
+ projectId: string
+ /** owner/name, lower case. */
+ repository: string
+ scope: 'project' | 'swarm'
+}
+
+/** The key that signs a sign-in's state, derived from the app's private key: nothing further to configure. */
+export function stateSecret(config: GitHubAppConfig): Buffer {
+ const der = config.privateKey.export({ type: 'pkcs8', format: 'der' })
+ return Buffer.from(hkdfSync('sha256', der, 'harness-github-approval-state', config.appId, 32))
+}
+
+export function signState(secret: Buffer, request: ApprovalRequest, now: number): string {
+ const body = Buffer.from(JSON.stringify({ ...request, exp: now + STATE_TTL_MS })).toString('base64url')
+ return `${body}.${createHmac('sha256', secret).update(body).digest('base64url')}`
+}
+
+/** The request a state was signed for, or null when it was not signed here, was changed, or is too old. */
+export function readState(secret: Buffer, state: string, now: number): ApprovalRequest | null {
+ const [body, signature, extra] = state.split('.')
+ if (!body || !signature || extra !== undefined) return null
+ const expected = createHmac('sha256', secret).update(body).digest()
+ const given = Buffer.from(signature, 'base64url')
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null
+ try {
+ const value = JSON.parse(Buffer.from(body, 'base64url').toString()) as ApprovalRequest & { exp: number }
+ if (typeof value.exp !== 'number' || value.exp < now || (value.scope !== 'project' && value.scope !== 'swarm')) return null
+ for (const key of ['userId', 'autonomousEnv', 'tabId', 'projectId', 'repository'] as const) if (typeof value[key] !== 'string' || !value[key]) return null
+ return { userId: value.userId, autonomousEnv: value.autonomousEnv, tabId: value.tabId, projectId: value.projectId, repository: value.repository, scope: value.scope }
+ } catch { return null }
+}
+
+export interface GitHubSignInDeps { clientId: string; clientSecret: string; fetch?: typeof fetch; webUrl?: string; apiUrl?: string }
+
+/** The Harness GitHub App's sign-in (GitHub's web application flow for an app's user access token). */
+export class GitHubSignIn {
+ private readonly fetch: typeof fetch
+ private readonly webUrl: string
+ private readonly apiUrl: string
+ constructor(private readonly deps: GitHubSignInDeps) {
+ this.fetch = deps.fetch ?? fetch
+ this.webUrl = deps.webUrl ?? 'https://github.com'
+ this.apiUrl = deps.apiUrl ?? 'https://api.github.com'
+ }
+
+ authorizeUrl(state: string): string {
+ return `${this.webUrl}/login/oauth/authorize?client_id=${encodeURIComponent(this.deps.clientId)}&state=${encodeURIComponent(state)}`
+ }
+
+ /** What GitHub says [code]'s person may do on [repository]: their login, and whether they can push. The person's token
+ * is revoked before this answers, whatever it found. */
+ async permission(code: string, repository: GitHubRepository): Promise<{ login: string; push: boolean } | null> {
+ const exchanged = await this.fetch(`${this.webUrl}/login/oauth/access_token`, {
+ method: 'POST', signal: AbortSignal.timeout(15_000),
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
+ body: JSON.stringify({ client_id: this.deps.clientId, client_secret: this.deps.clientSecret, code }),
+ })
+ const token = ((await exchanged.json().catch(() => ({}))) as { access_token?: unknown }).access_token
+ if (!exchanged.ok || typeof token !== 'string' || !token) return null
+ try {
+ const headers = { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'harness-backend' }
+ const user = await this.fetch(`${this.apiUrl}/user`, { headers, signal: AbortSignal.timeout(15_000) })
+ const login = ((await user.json().catch(() => ({}))) as { login?: unknown }).login
+ if (!user.ok || typeof login !== 'string') return null
+ // A renamed repository answers by redirect, which fetch follows; one the person cannot see answers 404.
+ const repo = await this.fetch(`${this.apiUrl}/repos/${repository.owner}/${repository.name}`, { headers, signal: AbortSignal.timeout(15_000) })
+ const permissions = ((await repo.json().catch(() => ({}))) as { permissions?: Record<string, unknown> }).permissions ?? {}
+ return { login, push: repo.ok && (permissions.push === true || permissions.maintain === true || permissions.admin === true) }
+ } finally {
+ await this.fetch(`${this.apiUrl}/applications/${encodeURIComponent(this.deps.clientId)}/token`, {
+ method: 'DELETE', signal: AbortSignal.timeout(15_000),
+ headers: { Accept: 'application/vnd.github+json', Authorization: `Basic ${Buffer.from(`${this.deps.clientId}:${this.deps.clientSecret}`).toString('base64')}`,
+ 'Content-Type': 'application/json' },
+ body: JSON.stringify({ access_token: token }),
+ }).catch(() => undefined)
+ }
+ }
+}
+
+export function githubSignIn(env: { GITHUB_APP_CLIENT_ID: string; GITHUB_APP_CLIENT_SECRET: string }): GitHubSignIn | null {
+ const clientId = env.GITHUB_APP_CLIENT_ID.trim(), clientSecret = env.GITHUB_APP_CLIENT_SECRET.trim()
+ if (!clientId && !clientSecret) return null
+ if (!clientId || !clientSecret) throw new Error('Set both GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET for the Harness GitHub App\'s sign-in, or neither.')
+ return new GitHubSignIn({ clientId, clientSecret })
+}
+
+/** Where approvals are kept. */
+export interface Approvals {
+ approved(autonomousEnv: string, tabId: string, projectId: string, repository: string): Promise<boolean>
+ approve(request: ApprovalRequest, githubLogin: string): Promise<void>
+}
+
+export class PrismaApprovals implements Approvals {
+ constructor(private readonly db: Pick<PrismaClient, 'gitHubRepositoryApproval'>) {}
+
+ async approved(autonomousEnv: string, tabId: string, projectId: string, repository: string): Promise<boolean> {
+ return !!await this.db.gitHubRepositoryApproval.findFirst({ where: { autonomousEnv, tabId, repository: repository.toLowerCase(),
+ projectId: { in: [projectId, WHOLE_SWARM] } }, select: { id: true } })
+ }
+
+ async approve(request: ApprovalRequest, githubLogin: string): Promise<void> {
+ const projectId = request.scope === 'swarm' ? WHOLE_SWARM : request.projectId
+ const where = { autonomousEnv_tabId_repository_projectId: { autonomousEnv: request.autonomousEnv, tabId: request.tabId,
+ repository: request.repository, projectId } }
+ await this.db.gitHubRepositoryApproval.upsert({ where, update: { approvedBy: request.userId, githubLogin },
+ create: { id: randomUUID(), autonomousEnv: request.autonomousEnv, tabId: request.tabId, projectId, repository: request.repository,
+ approvedBy: request.userId, githubLogin } })
+ }
+}
diff --git a/backend/src/github/projectAccess.test.ts b/backend/src/github/projectAccess.test.ts
new file mode 100644
index 000000000..85e87371e
--- /dev/null
+++ b/backend/src/github/projectAccess.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest'
+import { fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
+import { projectGitHubAccess } from './projectAccess.js'
+
+/** Approved or not, and whether this server can approve. */
+const approval = (approved = true, canApprove = true) => ({ approved: async () => approved, canApprove })
+
+const key = throwawayKey()
+const setup = (slug: string | null = 'harness-fixture') => {
+ let t = Date.parse('2026-10-28T12:00:00Z')
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now: () => t })
+ return { github, app: fakeApp(key.privateKey, github, { now: () => t, slug }), advance: (ms: number) => { t += ms } }
+}
+
+describe('a Swarm project\'s GitHub access', () => {
+ it('says whether teammates\' agents can push there, and how to let them', async () => {
+ const { github, app } = setup()
+ expect(await projectGitHubAccess(null, 'https://github.com/acme/app', approval())).toEqual({ state: 'unavailable' })
+ expect(await projectGitHubAccess(app, null, approval())).toEqual({ state: 'no-repository' })
+ expect(await projectGitHubAccess(app, 'https://gitlab.com/acme/web', approval())).toEqual({ state: 'not-github', repositoryUrl: 'https://gitlab.com/acme/web' })
+ expect(await projectGitHubAccess(app, '[email protected]:acme/app.git', approval()))
+ .toEqual({ state: 'not-installed', repository: 'acme/app', installUrl: 'https://github.com/apps/harness-fixture/installations/new', canApprove: true })
+ github.installed.set('acme/app', 77)
+ // A remembered "not installed" holds a minute; checking again asks GitHub at once.
+ expect((await projectGitHubAccess(app, '[email protected]:acme/app.git', approval())).state).toBe('not-installed')
+ expect(await projectGitHubAccess(app, '[email protected]:acme/app.git', approval(), true)).toEqual({ state: 'covered', repository: 'acme/app' })
+ expect(await projectGitHubAccess(setup(null).app, 'https://github.com/acme/app', approval())).toMatchObject({ state: 'not-installed', installUrl: null })
+ })
+
+ it('is covered only once someone who can push to the repository approved it for the project', async () => {
+ const { github, app } = setup()
+ github.installed.set('acme/app', 77)
+ expect(await projectGitHubAccess(app, 'https://github.com/acme/app', approval(false)))
+ .toEqual({ state: 'not-approved', repository: 'acme/app', canApprove: true })
+ expect(await projectGitHubAccess(app, 'https://github.com/acme/app', approval(false, false)))
+ .toMatchObject({ state: 'not-approved', canApprove: false })
+ let asked = ''
+ await projectGitHubAccess(app, 'https://github.com/Acme/App', { approved: async (repository) => { asked = repository; return true }, canApprove: true })
+ expect(asked).toBe('acme/app')
+ })
+
+ it('reads GitHub not answering as unknown, never as covered, and says when the app\'s credentials are wrong', async () => {
+ const { github, app } = setup()
+ github.control.down = true
+ expect(await projectGitHubAccess(app, 'https://github.com/acme/app', approval())).toEqual({ state: 'unknown', repository: 'acme/app' })
+ github.control.down = false
+ const wrong = fakeApp(throwawayKey().privateKey, github)
+ await expect(projectGitHubAccess(wrong, 'https://github.com/acme/app', approval())).rejects.toMatchObject({ code: 'GITHUB_APP_MISCONFIGURED' })
+ })
+
+ it('asks GitHub again on request at most every 15 seconds per repository', async () => {
+ const { github, app, advance } = setup()
+ const lookups = () => github.calls.filter(c => c.path === '/repos/acme/app/installation').length
+ await projectGitHubAccess(app, 'https://github.com/acme/app', approval())
+ await projectGitHubAccess(app, 'https://github.com/acme/app', approval(), true)
+ await projectGitHubAccess(app, 'https://github.com/acme/app', approval(), true)
+ expect(lookups()).toBe(2)
+ advance(15_000)
+ await projectGitHubAccess(app, 'https://github.com/acme/app', approval(), true)
+ expect(lookups()).toBe(3)
+ })
+})
diff --git a/backend/src/github/projectAccess.ts b/backend/src/github/projectAccess.ts
new file mode 100644
index 000000000..afa48a489
--- /dev/null
+++ b/backend/src/github/projectAccess.ts
@@ -0,0 +1,39 @@
+/**
+ * Whether teammates' agents can push and open pull requests on a Swarm project's repository: the Harness GitHub App is
+ * installed there (docs/plans/2026-10-28-swarm-project-github-access.md). Read by the app to show it where the project
+ * is, before a start fails on it. Holds the repository's name and the public install link, never a token.
+ */
+import { GitHubAppError, type GitHubApp } from './app.js'
+import { githubRepository } from './repository.js'
+
+export type ProjectGitHubAccess =
+ | { state: 'unavailable' }
+ | { state: 'no-repository' }
+ | { state: 'not-github'; repositoryUrl: string }
+ | { state: 'covered'; repository: string }
+ | { state: 'not-installed'; repository: string; installUrl: string | null; canApprove: boolean }
+ | { state: 'not-approved'; repository: string; canApprove: boolean }
+ | { state: 'unknown'; repository: string }
+
+/** [app]: this server's GitHub App, null when it has none. [approved]: whether someone who can push to the repository
+ * approved it for this project (github/approvals.ts). [canApprove]: this server has the app's sign-in to approve with.
+ * [refresh]: a person asked to check again. */
+export async function projectGitHubAccess(app: Pick<GitHubApp, 'resolve' | 'forget' | 'installUrl'> | null, repositoryUrl: string | null,
+ approval: { approved: (repository: string) => Promise<boolean>; canApprove: boolean }, refresh = false): Promise<ProjectGitHubAccess> {
+ if (!app) return { state: 'unavailable' }
+ if (!repositoryUrl) return { state: 'no-repository' }
+ const repository = githubRepository(repositoryUrl)
+ if (!repository) return { state: 'not-github', repositoryUrl }
+ if (refresh) app.forget(repository)
+ try {
+ if (!await app.resolve(repository)) {
+ return { state: 'not-installed', repository: repository.fullName, installUrl: app.installUrl(), canApprove: approval.canApprove }
+ }
+ return await approval.approved(repository.fullName.toLowerCase()) ? { state: 'covered', repository: repository.fullName }
+ : { state: 'not-approved', repository: repository.fullName, canApprove: approval.canApprove }
+ } catch (error) {
+ // Wrong app credentials are the server's to fix and say so; GitHub not answering is never read as covered.
+ if (error instanceof GitHubAppError && error.code === 'GITHUB_APP_MISCONFIGURED') throw error
+ return { state: 'unknown', repository: repository.fullName }
+ }
+}
diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.ts
index b60fbe6a6..95a61f55a 100644
--- a/backend/src/middlewares/authMiddleware.ts
+++ b/backend/src/middlewares/authMiddleware.ts
@@ -70,6 +70,11 @@ export function shouldSkipAuth(url: string): boolean {
// `start` returns codes it just minted, and `poll` needs the 32-byte device code and answers once.
// The approve/deny/lookup half is NOT listed and stays SSO-gated — that is where the user's identity
// and their machine list are involved. Listed one by one, like the cursor pair above.
+ // GitHub sends a person back here after they signed in to the Harness GitHub App (or installed it), with no Harness
+ // token: the `state` the backend signed for that person, project and scope, ten minutes long, is what it trusts
+ // (routes/superTabs.ts, github/approvals.ts). It only records that someone GitHub says can push to a repository
+ // approved it.
+ path === '/api/github/callback' ||
path === '/api/device-auth/start' ||
path === '/api/device-auth/poll' ||
// The connector gateway's callback (routes/connectors.ts), posted by the Autonomous web callback
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 9756bd2a0..ab3e1b5f2 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -15,6 +15,9 @@ import { machineObservationSchema } from '../superTabs/machines.js'
import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superTabs/sharing.js'
import { holdReason } from '../superTabs/holdReason.js'
import { GitHubAppError } from '../github/app.js'
+import { projectGitHubAccess } from '../github/projectAccess.js'
+import { githubSignIn, PrismaApprovals, readState, signState, stateSecret, type Approvals, type GitHubSignIn } from '../github/approvals.js'
+import type { GitHubRepository } from '../github/repository.js'
import { githubRepository } from '../github/repository.js'
import { attribution } from '../github/attribution.js'
import { githubTokensFromEnv, type GitHubTokens } from '../github/tokens.js'
@@ -52,6 +55,21 @@ const terminalParams = tabParams.extend({ requestId: id })
const hostParams = z.object({ machineId: id })
const hostStartParams = hostParams.extend({ tabId: id, startId: id })
const machineParams = hostParams.extend({ tabId: id })
+const projectParams = tabParams.extend({ projectId: id })
+const refreshQuery = z.object({ refresh: z.literal('1').optional() })
+const approveBody = z.object({ scope: z.enum(['project', 'swarm']) }).strict()
+// What GitHub sends back: a sign-in's code and our state, and after an installation its id and action.
+const callbackQuery = z.object({ code: z.string().max(512).optional(), state: z.string().max(4096).optional(),
+ installation_id: z.string().max(32).optional(), setup_action: z.string().max(32).optional() })
+
+const escapeHtml = (text: string) => text.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!)
+/** The page a person sees in their browser after GitHub sends them back. */
+function githubPage(title: string, text: string): string {
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">`
+ + `<title>${escapeHtml(title)}</title><style>body{font:16px/1.5 -apple-system,system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;`
+ + `color:#1f2328;background:#fff}@media(prefers-color-scheme:dark){body{color:#e6edf3;background:#0d1117}}h1{font-size:1.4rem}</style></head>`
+ + `<body><h1>${escapeHtml(title)}</h1><p>${escapeHtml(text)}</p></body></html>`
+}
const deliveryParams = tabParams.extend({ agentId: id })
const deliveryActionParams = deliveryParams.extend({ deliveryId: id })
const deliveryAction = z.discriminatedUnion('type', [
@@ -81,8 +99,20 @@ async function respond(reply: FastifyReply, action: () => Promise<unknown>) {
* before or right after any action, so it meets this at once. */
const updateRequired = (_req: unknown, reply: FastifyReply) => sendError(reply, UPDATE_REQUIRED.message, UPDATE_REQUIRED.code, UPDATE_REQUIRED.status)
-export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore; github?: GitHubTokens | null; reads?: SwarmReads; hosts?: HostReads } = {}) {
+export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore; github?: GitHubTokens | null; reads?: SwarmReads; hosts?: HostReads;
+ approvals?: Approvals; signIn?: GitHubSignIn | null } = {}) {
const github = options.github !== undefined ? options.github : await githubTokensFromEnv(env)
+ // Which repositories each Swarm may use the app on, and the app's sign-in that approves one (github/approvals.ts).
+ const approvals = options.approvals ?? new PrismaApprovals(prisma)
+ const signIn = options.signIn !== undefined ? options.signIn : githubSignIn(env)
+ const approvalSecret = github ? stateSecret(github.app.config) : null
+ // No token for a repository nobody who can push to it approved for this project: a project names its repository as
+ // text, and the app is on other people's repositories too.
+ const requireApproval = async (user: { autonomousEnv: string }, tabId: string, projectId: string, repository: GitHubRepository) => {
+ if (await approvals.approved(user.autonomousEnv, tabId, projectId, repository.fullName)) return
+ throw new SuperTabError('GITHUB_REPOSITORY_NOT_APPROVED', `Nobody who can push to ${repository.fullName} has approved it for this project yet, `
+ + 'so teammates\' agents get no access to it. Someone who can push to it approves it in Harness: Project details, GitHub access.', 403)
+ }
// A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.
const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
{ workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },
@@ -117,6 +147,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
? 'This project\'s repository is not on github.com, so the Harness GitHub App cannot give a token for it.'
: 'This project has no repository address yet. Its owner or Lead can share it (project.repository).', 409)
}
+ await requireApproval(req.user!, grant.tabId, grant.projectId, repository)
return { github: true, ...await github.prepare(repository), requestedBy: grant.requester }
}))
app.get<{ Params: z.infer<typeof hostStartParams> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', { preHandler: validateParams(hostStartParams) },
@@ -126,6 +157,44 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
if (!('startId' in req.body.command) || req.body.command.startId !== req.params.startId) throw new SuperTabError('FORBIDDEN', 'The host request must name this start.', 403)
return store.execute(req.user!, req.params.tabId, req.body, undefined, req.params.machineId)
}))
+ // Whether teammates' agents can push to a project's repository: the Harness GitHub App installed there
+ // (github/projectAccess.ts). `refresh=1`: a person installed it just now and checks again.
+ app.get<{ Params: z.infer<typeof projectParams>; Querystring: z.infer<typeof refreshQuery> }>('/api/super-tabs/:tabId/projects/:projectId/github',
+ { preHandler: [validateParams(projectParams), validateQuery(refreshQuery)] },
+ (req, reply) => respond(reply, async () => projectGitHubAccess(github?.app ?? null,
+ await store.projectRepository(req.user!, req.params.tabId, req.params.projectId),
+ { approved: repository => approvals.approved(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository), canApprove: !!signIn },
+ req.query.refresh === '1')))
+ // Approving a project's repository: the person signs in to GitHub through the app (or installs it, which signs them in
+ // too), and GitHub sends them back to /api/github/callback with the state signed here for them, this project and scope.
+ app.post<{ Params: z.infer<typeof projectParams>; Body: z.infer<typeof approveBody> }>('/api/super-tabs/:tabId/projects/:projectId/github/approve',
+ { preHandler: [validateParams(projectParams), validateBody(approveBody)] }, (req, reply) => respond(reply, async () => {
+ if (!github || !approvalSecret) throw new GitHubAppError('GITHUB_APP_NOT_CONFIGURED', 'This Harness server has no GitHub App configured.', 503)
+ if (!signIn) throw new GitHubAppError('GITHUB_APPROVAL_NOT_CONFIGURED', 'This Harness server cannot approve repositories yet: its administrator sets GITHUB_APP_CLIENT_ID and GITHUB_APP_CLIENT_SECRET.', 503)
+ const repositoryUrl = await store.projectRepository(req.user!, req.params.tabId, req.params.projectId)
+ const repository = githubRepository(repositoryUrl) ?? fail('REPOSITORY_NOT_GITHUB', 'This project\'s repository is not on github.com.', 409)
+ const state = signState(approvalSecret, { userId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv, tabId: req.params.tabId,
+ projectId: req.params.projectId, repository: repository.fullName.toLowerCase(), scope: req.body.scope }, Date.now())
+ const install = github.app.installUrl()
+ return { authorizeUrl: signIn.authorizeUrl(state), installUrl: install ? `${install}?state=${encodeURIComponent(state)}` : null }
+ }))
+ app.get<{ Querystring: z.infer<typeof callbackQuery> }>('/api/github/callback', { preHandler: validateQuery(callbackQuery) }, async (req, reply) => {
+ const page = (title: string, text: string, status = 200) => reply.status(status).type('text/html; charset=utf-8').send(githubPage(title, text))
+ const request = approvalSecret && req.query.state ? readState(approvalSecret, req.query.state, Date.now()) : null
+ if (!request) return page('This link has expired', 'Go back to Harness and choose Approve again.', 400)
+ const named = githubRepository(`https://github.com/${request.repository}`)
+ if (!req.query.code || !signIn || !named) {
+ return page('Harness is installed', 'Go back to Harness and choose Approve, so this project can use it.')
+ }
+ const seen = await signIn.permission(req.query.code, named).catch(() => null)
+ if (!seen) return page('GitHub could not confirm your access', 'Go back to Harness and choose Approve again.', 502)
+ if (!seen.push) {
+ return page(`You can't push to ${named.fullName}`, 'So you can\'t approve it for this Swarm. Someone who can push to it can.', 403)
+ }
+ await approvals.approve(request, seen.login)
+ return page(`${named.fullName} approved`, request.scope === 'swarm'
+ ? 'Every project in this Swarm can now use it. You can go back to Harness.' : 'This project can now use it. You can go back to Harness.')
+ })
app.get<{ Params: z.infer<typeof machineParams> }>('/api/super-tabs/:tabId/machines/:machineId/removal', { preHandler: validateParams(machineParams) },
(req, reply) => respond(reply, () => store.machineRemoval(req.user!, req.params.tabId, req.params.machineId)))
app.post<{ Params: z.infer<typeof machineParams>; Body: z.infer<typeof machineObservationSchema> }>('/api/super-tabs/:tabId/machines/:machineId',
@@ -204,6 +273,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
? 'This project\'s repository is not on github.com, so the Harness GitHub App cannot give a token for it.'
: 'This project has no repository address yet. Its owner or Lead can share it (project.repository).', 409)
}
+ await requireApproval(req.user!, grant.tabId, grant.projectId, repository)
const issued = await github.issue({ tabId: grant.tabId, agentId: grant.agentId, assignmentId: grant.assignmentId, repository })
return { ...issued, ...attribution(grant) }
}))
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index c7b043072..e016d66ba 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1005,7 +1005,7 @@ export class SuperTabStore {
const contributed = state.machines?.find(m => m.machineId === target.machineId)?.name
const machineName = contributed ?? await tx.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId },
select: { name: true, hostname: true } }).then(m => m?.name ?? m?.hostname ?? null)
- return { tabId, agentId: target.id, assignmentId: group.assignment!.id, repositoryUrl: project.repository?.repositoryUrl ?? null,
+ return { tabId, projectId: project.id, agentId: target.id, assignmentId: group.assignment!.id, repositoryUrl: project.repository?.repositoryUrl ?? null,
requester: { name: requester.name?.trim() || null, email: requester.email },
agentName: agentDisplayName(state.agents, target.id) ?? target.displayName ?? target.name, machineName: machineName?.trim() || null }
})
@@ -1033,7 +1033,7 @@ export class SuperTabStore {
const project = groupProject(state, group)
const owner = await tx.user.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } })
const email = owner?.email ?? state.people.find(p => p.id === project.ownerId)?.email ?? ''
- return { tabId, startId, repositoryUrl: project.repository?.repositoryUrl ?? null, own: project.ownerId === start.machineOwnerId,
+ return { tabId, projectId: project.id, repositoryUrl: project.repository?.repositoryUrl ?? null, startId, own: project.ownerId === start.machineOwnerId,
requester: { name: owner?.name?.trim() || null, email } }
})
}
@@ -1415,6 +1415,18 @@ export class SuperTabStore {
}
/** What removing a machine would do, for its owner's confirmation (machines.ts removalPreview). */
+ /** A project's repository address, for a person who may open the project (routes/superTabs.ts, its GitHub access):
+ * a private project's members only. Null when it has none yet. */
+ async projectRepository(user: AuthUser, tabId: string, projectId: string): Promise<string | null> {
+ return transaction(this.db, async tx => {
+ const { state } = await this.load(tx, user, tabId)
+ const actor = await this.actor(tx, user, state)
+ const project = visibleState(state, actor, this.now()).projects?.find(p => p.id === projectId)
+ ?? fail('NOT_FOUND', 'This project is unavailable.', 404)
+ return project.repository?.repositoryUrl ?? null
+ })
+ }
+
async machineRemoval(user: AuthUser, tabId: string, machineId: string) {
return transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId)
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index aa3c616ed..17fb75716 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -11,6 +11,7 @@ import 'attachment_upload.dart';
import 'identity.dart';
import 'model.dart';
import 'pm_chat.dart';
+import 'project_github.dart';
import 'parts.dart';
import 'reading.dart';
import 'review_verdict.dart';
@@ -412,6 +413,67 @@ class SuperTabController extends ChangeNotifier {
return null;
}
+ /// What the backend last said of each project's GitHub access (backend github/projectAccess.ts), and when.
+ final Map<String, ({SuperTabProjectGitHub value, DateTime at})> _github = {};
+ final Set<String> _githubReading = {};
+
+ /// When each project's GitHub access was last asked for, answered or not: a failed read is not asked again on every
+ /// rebuild either.
+ final Map<String, DateTime> _githubAsked = {};
+
+ /// Whether teammates' agents can push to [projectId]'s repository, as last read; null before a read, or from a
+ /// server too old to say.
+ SuperTabProjectGitHub? githubAccessOf(String projectId) =>
+ _github[projectId]?.value;
+
+ /// Reads [projectId]'s GitHub access, at most every 5 minutes; [refresh]: a person checks again (the server asks
+ /// GitHub at once, at most every 15 seconds per repository). An older server has no such read: nothing is shown.
+ Future<void> readGitHubAccess(String projectId, {bool refresh = false}) async {
+ final asked = _githubAsked[projectId];
+ if (_disposed ||
+ accessRevoked ||
+ (!refresh &&
+ asked != null &&
+ clock.now().difference(asked) < const Duration(minutes: 5))) {
+ return;
+ }
+ if (!_githubReading.add(projectId)) return;
+ _githubAsked[projectId] = clock.now();
+ try {
+ final answer = await request(
+ 'GET',
+ '$_path/projects/${Uri.encodeComponent(projectId)}/github${refresh ? '?refresh=1' : ''}',
+ );
+ _github[projectId] = (
+ value: SuperTabProjectGitHub.fromJson(answer),
+ at: clock.now(),
+ );
+ _changed();
+ } catch (error) {
+ appLog.debug('super-tabs', 'project GitHub access not read: $error');
+ } finally {
+ _githubReading.remove(projectId);
+ }
+ }
+
+ /// Starts approving [projectId]'s repository for teammates' agents ([scope] `project`, or `swarm` for every project):
+ /// the links that sign the person in to GitHub through the Harness GitHub App, or install it there first. GitHub sends
+ /// them back to the backend, which checks they can push to the repository (backend github/approvals.ts).
+ Future<({String authorizeUrl, String? installUrl})> approveGitHub(
+ String projectId,
+ String scope,
+ ) async {
+ final answer = await request(
+ 'POST',
+ '$_path/projects/${Uri.encodeComponent(projectId)}/github/approve',
+ body: {'scope': scope},
+ );
+ return (
+ authorizeUrl: answer['authorizeUrl'] as String,
+ installUrl: answer['installUrl'] as String?,
+ );
+ }
+
/// Reads one message of [id] only: the backend checks the reader may read
/// that conversation, as for its pages. A failed read leaves the quote
/// saying the original isn't loaded.
diff --git a/desktop/lib/super_tabs/project_github.dart b/desktop/lib/super_tabs/project_github.dart
new file mode 100644
index 000000000..0261cabb1
--- /dev/null
+++ b/desktop/lib/super_tabs/project_github.dart
@@ -0,0 +1,327 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'model.dart';
+
+/// Whether teammates' agents can push and open pull requests on a Swarm project's repository: the Harness GitHub App is
+/// installed there (backend github/projectAccess.ts, docs/plans/2026-10-28-swarm-project-github-access.md). Before this,
+/// nothing said so until a start failed and the Lead relayed it.
+class SuperTabProjectGitHub {
+ SuperTabProjectGitHub.fromJson(Map<String, dynamic> row)
+ : state = row['state'] is String ? row['state'] as String : 'unavailable',
+ repository = row['repository'] is String
+ ? row['repository'] as String
+ : null,
+ installUrl = row['installUrl'] is String
+ ? row['installUrl'] as String
+ : null,
+ canApprove = row['canApprove'] == true;
+
+ /// `covered`, `not-installed`, `not-approved` (installed, but nobody who can push to it approved it for this project:
+ /// backend github/approvals.ts), `not-github`, `no-repository`, `unknown` (GitHub did not answer), or `unavailable`
+ /// (the server has no GitHub App: nothing is shown).
+ final String state;
+ final String? repository;
+ final String? installUrl;
+
+ /// This server has the app's GitHub sign-in to approve a repository with.
+ final bool canApprove;
+
+ /// What stops teammates' agents here, in the sidebar's one line; null when nothing does or it cannot be said.
+ String? get problem => switch (state) {
+ 'not-installed' || 'not-approved' => "Teammates can't push here yet",
+ 'not-github' => "Teammates can't work here: not on GitHub",
+ _ => null,
+ };
+}
+
+/// The project's GitHub access in full, with what to do about it: Project details, and the dialog the sidebar line
+/// opens. Read when shown; [SuperTabController.readGitHubAccess] keeps it at most 5 minutes.
+class ProjectGitHubAccess extends StatefulWidget {
+ const ProjectGitHubAccess({
+ super.key,
+ required this.controller,
+ required this.projectId,
+ });
+
+ final SuperTabController controller;
+ final String projectId;
+
+ @override
+ State<ProjectGitHubAccess> createState() => _ProjectGitHubAccessState();
+}
+
+class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>
+ with WidgetsBindingObserver {
+ bool _checking = false;
+ bool _copied = false;
+ bool _busy = false;
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addObserver(this);
+ widget.controller.readGitHubAccess(widget.projectId);
+ }
+
+ @override
+ void didUpdateWidget(ProjectGitHubAccess old) {
+ super.didUpdateWidget(old);
+ if (old.controller != widget.controller ||
+ old.projectId != widget.projectId) {
+ widget.controller.readGitHubAccess(widget.projectId);
+ }
+ }
+
+ @override
+ void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ super.dispose();
+ }
+
+ // Back from GitHub's install page: asked again at once.
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ final known = widget.controller.githubAccessOf(widget.projectId);
+ if (state == AppLifecycleState.resumed &&
+ known != null &&
+ known.state != 'covered') {
+ _check();
+ }
+ }
+
+ Future<void> _check() async {
+ setState(() => _checking = true);
+ await widget.controller.readGitHubAccess(widget.projectId, refresh: true);
+ if (mounted) setState(() => _checking = false);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return ListenableBuilder(
+ listenable: widget.controller,
+ builder: (context, _) {
+ final access = widget.controller.githubAccessOf(widget.projectId);
+ if (access == null || access.state == 'unavailable') {
+ return const SizedBox.shrink();
+ }
+ final repository = access.repository ?? 'its repository';
+ final text = switch (access.state) {
+ 'covered' =>
+ "GitHub ✓ Teammates' agents can push and open pull requests on $repository.",
+ 'not-installed' =>
+ "Teammates' agents can't push to $repository yet. Install Harness on GitHub there: "
+ "an owner of ${repository.split('/').first}, or the repository's owner, can.",
+ 'not-approved' =>
+ access.canApprove
+ ? "Teammates' agents can't use $repository in this project yet. Someone who can push to it "
+ 'approves it, signing in to GitHub.'
+ : "Teammates' agents can't use $repository in this project yet. This Harness server can't approve "
+ 'repositories yet.',
+ 'not-github' => "Teammates' agents can't work on this project: its repository isn't on GitHub.",
+ 'no-repository' => 'This project has no repository address yet. Its owner or Lead sets it.',
+ _ => "Couldn't reach GitHub to check $repository.",
+ };
+ final install = access.installUrl;
+ final approve = access.state == 'not-approved' && access.canApprove;
+ return Column(
+ key: ValueKey('super-project-github-${widget.projectId}'),
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('GitHub access', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 4),
+ Text(
+ text,
+ key: ValueKey('super-project-github-text-${widget.projectId}'),
+ style: DesktopChrome.text(),
+ ),
+ if (_error != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text(
+ _error!,
+ key: const Key('super-project-github-error'),
+ style: DesktopChrome.text().copyWith(
+ color: grid.AppPalette.warn,
+ ),
+ ),
+ ),
+ if (access.state == 'not-installed' ||
+ access.state == 'not-approved' ||
+ access.state == 'unknown')
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ children: [
+ if (install != null && access.state == 'not-installed') ...[
+ FilledButton(
+ key: const Key('super-project-github-install'),
+ onPressed: _busy ? null : () => _install(install),
+ child: const Text('Install on GitHub'),
+ ),
+ TextButton(
+ key: const Key('super-project-github-copy'),
+ onPressed: () async {
+ await Clipboard.setData(ClipboardData(text: install));
+ if (mounted) setState(() => _copied = true);
+ },
+ child: Text(_copied ? 'Link copied' : 'Copy link'),
+ ),
+ ],
+ if (approve) ...[
+ FilledButton(
+ key: const Key('super-project-github-approve'),
+ onPressed: _busy ? null : () => _approve('project'),
+ child: const Text('Approve for this project'),
+ ),
+ TextButton(
+ key: const Key('super-project-github-approve-swarm'),
+ onPressed: _busy ? null : () => _approve('swarm'),
+ child: const Text('Approve for every project here'),
+ ),
+ ],
+ TextButton(
+ key: const Key('super-project-github-check'),
+ onPressed: _checking ? null : _check,
+ child: Text(_checking ? 'Checking…' : 'Check again'),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ /// Installs Harness on GitHub with a link that also approves the repository for this project once installed (GitHub
+ /// signs the installer in and sends them back); an older server's plain link otherwise.
+ Future<void> _install(String plain) async {
+ setState(() => _busy = true);
+ String link = plain;
+ try {
+ link =
+ (await widget.controller.approveGitHub(
+ widget.projectId,
+ 'project',
+ )).installUrl ??
+ plain;
+ } catch (_) {
+ // The plain link still installs; approving is then a step of its own.
+ }
+ await launchUrl(Uri.parse(link), mode: LaunchMode.externalApplication);
+ if (mounted) setState(() => _busy = false);
+ }
+
+ /// Signs the person in to GitHub through the app, which approves the repository if they can push to it.
+ Future<void> _approve(String scope) async {
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ try {
+ final links = await widget.controller.approveGitHub(
+ widget.projectId,
+ scope,
+ );
+ await launchUrl(
+ Uri.parse(links.authorizeUrl),
+ mode: LaunchMode.externalApplication,
+ );
+ } on SuperTabFailure catch (failure) {
+ if (mounted) setState(() => _error = failure.message);
+ } catch (_) {
+ if (mounted) {
+ setState(() => _error = "Couldn't start approving. Try again.");
+ }
+ }
+ if (mounted) setState(() => _busy = false);
+ }
+}
+
+/// The sidebar's one line under a project whose teammates' agents cannot push there, in a Swarm with another person
+/// in it; clicking it shows [ProjectGitHubAccess].
+class ProjectGitHubLine extends StatefulWidget {
+ const ProjectGitHubLine({
+ super.key,
+ required this.controller,
+ required this.project,
+ });
+
+ final SuperTabController controller;
+ final SuperTabProject project;
+
+ @override
+ State<ProjectGitHubLine> createState() => _ProjectGitHubLineState();
+}
+
+class _ProjectGitHubLineState extends State<ProjectGitHubLine> {
+ @override
+ void initState() {
+ super.initState();
+ if (widget.controller.snapshot?.hasTeammates == true) {
+ widget.controller.readGitHubAccess(widget.project.id);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final c = widget.controller;
+ return ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ if (c.snapshot?.hasTeammates != true) return const SizedBox.shrink();
+ // A Swarm that gained a person since: read now (at most every 5 minutes, answered or not).
+ c.readGitHubAccess(widget.project.id);
+ final problem = c.githubAccessOf(widget.project.id)?.problem;
+ if (problem == null) return const SizedBox.shrink();
+ return InkWell(
+ key: ValueKey('super-project-github-line-${widget.project.id}'),
+ onTap: () => showProjectGitHubAccess(context, c, widget.project),
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Text(
+ problem,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata().copyWith(
+ color: grid.AppPalette.warn,
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
+
+Future<void> showProjectGitHubAccess(
+ BuildContext context,
+ SuperTabController c,
+ SuperTabProject project,
+) => showAppDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ key: const Key('super-project-github-dialog'),
+ title: Text(project.name),
+ content: SizedBox(
+ width: 400,
+ child: ProjectGitHubAccess(controller: c, projectId: project.id),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ ),
+);
diff --git a/desktop/lib/super_tabs/project_options.dart b/desktop/lib/super_tabs/project_options.dart
index 2b1695262..95e2631d7 100644
--- a/desktop/lib/super_tabs/project_options.dart
+++ b/desktop/lib/super_tabs/project_options.dart
@@ -6,6 +6,7 @@ import '../widgets/desktop_chrome.dart';
import 'controller.dart';
import 'dialog_scope.dart';
import 'model.dart';
+import 'project_github.dart';
import 'project_visibility.dart';
import 'roles_editor.dart';
@@ -56,6 +57,11 @@ Future<void> showProjectAction(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
+ // Whether teammates' agents can push to its repository, and what to do about it.
+ if (action == 'details') ...[
+ ProjectGitHubAccess(controller: c, projectId: project.id),
+ const SizedBox(height: 16),
+ ],
if (action == 'rename')
TextFormField(
autofocus: true,
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index de314bdea..f0009ad9e 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -16,6 +16,7 @@ import 'model.dart';
import 'pm_chat_rows.dart';
import 'section_heading.dart';
import 'workgroup_name.dart';
+import 'project_github.dart';
/// The Swarm's Product Managers' conversation, listed as a channel among the projects.
const kProductManagersChannel = 'product-managers';
@@ -233,11 +234,24 @@ class ProjectSidebar extends StatelessWidget {
Expanded(
child: label == null && project == null
? SuperTabWorkgroupName(group, style: style)
- : Text(
- label ?? project!.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: style,
+ : Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ label ?? project!.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style,
+ ),
+ // Teammates' agents cannot push to its repository yet (project_github.dart).
+ if (project != null)
+ ProjectGitHubLine(
+ controller: controller,
+ project: project,
+ ),
+ ],
),
),
if (project?.isPrivate == true) ...[
diff --git a/desktop/test/super_tab_project_github_test.dart b/desktop/test/super_tab_project_github_test.dart
new file mode 100644
index 000000000..2666f8f23
--- /dev/null
+++ b/desktop/test/super_tab_project_github_test.dart
@@ -0,0 +1,253 @@
+// A Swarm project's GitHub access (docs/plans/2026-10-28-swarm-project-github-access.md): whether teammates' agents can
+// push to its repository, shown where the project is, with how to let them.
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/project_github.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ late ConversationServer server;
+ late List<String> asked;
+ late Map<String, dynamic> answer;
+ late List<String> launched;
+ var refuseApprove = false;
+
+ SuperTabController controllerFor({bool teammates = true}) {
+ if (teammates) {
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ }
+ return SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: (method, path, {body}) async {
+ if (path.endsWith('/github/approve')) {
+ asked.add('$method $path ${body?['scope']}');
+ if (refuseApprove) {
+ throw const SuperTabFailure(
+ 'GITHUB_APPROVAL_NOT_CONFIGURED',
+ 'This Harness server cannot approve repositories yet.',
+ );
+ }
+ return {
+ 'authorizeUrl': 'https://github.com/login/oauth/authorize?state=s',
+ 'installUrl':
+ 'https://github.com/apps/harness/installations/new?state=s',
+ };
+ }
+ if (path.contains('/github')) {
+ asked.add(path);
+ return answer;
+ }
+ return server.request(method, path, body: body);
+ },
+ save: server.save,
+ upload: server.upload,
+ initial: const {},
+ pollInterval: Duration.zero,
+ );
+ }
+
+ setUp(() {
+ // Copy link writes the clipboard: answered here, as the platform would.
+ TestWidgetsFlutterBinding.ensureInitialized();
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async => null,
+ );
+ launched = [];
+ refuseApprove = false;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(
+ const MethodChannel('plugins.flutter.io/url_launcher'),
+ (call) async {
+ if (call.method == 'launch') {
+ launched.add((call.arguments as Map)['url'] as String);
+ }
+ return true;
+ },
+ );
+ server = ConversationServer();
+ asked = [];
+ answer = {
+ 'state': 'not-installed',
+ 'repository': 'acme/app',
+ 'installUrl': 'https://github.com/apps/harness/installations/new',
+ };
+ });
+
+ Future<SuperTabController> mount(
+ WidgetTester tester,
+ Widget Function(SuperTabController c, SuperTabProject p) child, {
+ bool teammates = true,
+ }) async {
+ final c = controllerFor(teammates: teammates);
+ await c.refresh();
+ final project = c.snapshot!.projects.first;
+ await tester.pumpWidget(
+ MaterialApp(home: Scaffold(body: child(c, project))),
+ );
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ testWidgets(
+ 'the sidebar says when teammates cannot push there, once the Swarm has another person in it',
+ (tester) async {
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubLine(controller: c, project: p),
+ );
+ expect(find.text("Teammates can't push here yet"), findsOneWidget);
+ expect(asked, hasLength(1));
+ // Read again only after 5 minutes, whatever rebuilds meanwhile.
+ await tester.pump();
+ expect(asked, hasLength(1));
+ c.dispose();
+ },
+ );
+
+ testWidgets('nothing is asked or shown in a Swarm of one, or when covered', (
+ tester,
+ ) async {
+ final alone = await mount(
+ tester,
+ (c, p) => ProjectGitHubLine(controller: c, project: p),
+ teammates: false,
+ );
+ expect(asked, isEmpty);
+ expect(find.byType(InkWell), findsNothing);
+ alone.dispose();
+ answer = {'state': 'covered', 'repository': 'acme/app'};
+ final covered = await mount(
+ tester,
+ (c, p) => ProjectGitHubLine(controller: c, project: p),
+ );
+ expect(find.byType(InkWell), findsNothing);
+ covered.dispose();
+ });
+
+ testWidgets(
+ 'Project details explains it, links to GitHub\'s install page, copies the link, and checks again',
+ (tester) async {
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(find.textContaining("can't push to acme/app yet"), findsOneWidget);
+ expect(
+ find.byKey(const Key('super-project-github-install')),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('super-project-github-copy')));
+ await tester.pumpAndSettle();
+ expect(find.text('Link copied'), findsOneWidget);
+ answer = {'state': 'covered', 'repository': 'acme/app'};
+ await tester.tap(find.byKey(const Key('super-project-github-check')));
+ await tester.pumpAndSettle();
+ expect(asked.last, endsWith('/github?refresh=1'));
+ expect(find.textContaining("GitHub ✓"), findsOneWidget);
+ expect(
+ find.byKey(const Key('super-project-github-install')),
+ findsNothing,
+ );
+ c.dispose();
+ },
+ );
+
+ testWidgets(
+ 'says plainly when a project is not on GitHub, has no repository, or GitHub did not answer',
+ (tester) async {
+ for (final (state, words) in [
+ ('not-github', "isn't on GitHub"),
+ ('no-repository', 'no repository address yet'),
+ ('unknown', "Couldn't reach GitHub"),
+ ]) {
+ answer = {'state': state, 'repository': 'acme/app'};
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(find.textContaining(words), findsOneWidget, reason: state);
+ c.dispose();
+ }
+ answer = {'state': 'unavailable'};
+ final none = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(find.text('GitHub access'), findsNothing);
+ none.dispose();
+ },
+ );
+
+ testWidgets(
+ 'installs with a link that also approves, and asks someone who can push to approve an installed repository',
+ (tester) async {
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ await tester.tap(find.byKey(const Key('super-project-github-install')));
+ await tester.pumpAndSettle();
+ expect(asked.last, endsWith('/github/approve project'));
+ expect(launched.last, contains('/installations/new?state='));
+ c.dispose();
+ answer = {
+ 'state': 'not-approved',
+ 'repository': 'acme/app',
+ 'canApprove': true,
+ };
+ final approving = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(
+ find.textContaining("can't use acme/app in this project yet"),
+ findsOneWidget,
+ );
+ await tester.tap(
+ find.byKey(const Key('super-project-github-approve-swarm')),
+ );
+ await tester.pumpAndSettle();
+ expect(asked.last, endsWith('/github/approve swarm'));
+ expect(launched.last, contains('/login/oauth/authorize'));
+ refuseApprove = true;
+ await tester.tap(find.byKey(const Key('super-project-github-approve')));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('This Harness server cannot approve repositories yet.'),
+ findsOneWidget,
+ );
+ approving.dispose();
+ },
+ );
+
+ testWidgets('says so when the server cannot approve, without the buttons', (
+ tester,
+ ) async {
+ answer = {
+ 'state': 'not-approved',
+ 'repository': 'acme/app',
+ 'canApprove': false,
+ };
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(
+ find.textContaining("can't approve repositories yet"),
+ findsOneWidget,
+ );
+ expect(find.byKey(const Key('super-project-github-approve')), findsNothing);
+ c.dispose();
+ });
+}
diff --git a/docs/plans/2026-10-28-swarm-project-github-access.md b/docs/plans/2026-10-28-swarm-project-github-access.md
new file mode 100644
index 000000000..f9d4b219c
--- /dev/null
+++ b/docs/plans/2026-10-28-swarm-project-github-access.md
@@ -0,0 +1,79 @@
+# A Swarm project's GitHub access, set up from the app
+
+2026-10-28. Follows [the Swarm team account](2026-10-24-swarm-team-account.md), Task 4 (the Harness GitHub App).
+
+## The problem
+
+A teammate's agent works on a project in a Harness Team account, which has no git login: it fetches, pushes and opens
+pull requests only with the Harness GitHub App (`docs/swarm-github-app.md`). The app does that only on repositories
+where it is installed. Nothing in the app said so before a start failed: the Lead relayed "The Harness GitHub App is not
+installed on owner/repo" after the fact, and only an organization owner on github.com could fix it. With the app made
+installable by any account, a developer outside autonomous-ai can use it on their own repositories, public or private,
+once they install it there.
+
+## The experience
+
+- The Swarm owner, or anyone in the Swarm, sees each project's GitHub access where the project is: in Project details,
+ and as one line under the project in the sidebar when teammates' agents cannot push there. The line shows only once
+ the Swarm has another person in it, since only teammates' work needs the app.
+- States, in plain words:
+ - **Covered**: "GitHub ✓ Teammates' agents can push and open pull requests on owner/repo."
+ - **Not installed**: "Teammates' agents can't push to owner/repo yet." with **Install on GitHub** (opens GitHub's
+ install page for the app), **Copy link** (for the person who may install it: an owner of the repository's
+ organization, or the repository's owner) and **Check again**. Coming back to the app checks again by itself.
+ - **Not on GitHub** (a GitLab address, say): "Teammates' agents can't work on this project: its repository isn't on
+ GitHub."
+ - **No repository yet**: "This project has no repository address yet." The Lead or the owner sets it
+ (`project.repository`).
+ - **Unavailable**: the server has no GitHub App; nothing is shown.
+- Private and public repositories work the same: the installer chooses which repositories the app covers.
+
+## Approval: who may use a repository
+
+A project's repository address is text its owner types, and once the app is public it is installed on many people's
+repositories: anyone could name one as their project's and borrow the app's write access to it (found 2026-10-28, with
+the app already on autonomous-ai/openharness). So a project gets tokens for a repository only once someone GitHub says
+can push to it approved it, for that project or for every project of the Swarm:
+
+- **Approve for this project** / **Approve for every project here** sign the person in to GitHub through the app (its
+ Client ID and secret). The backend reads, with their own short-lived token, whether they can push (`push`, `maintain`
+ or `admin`), revokes that token at once and stores only the approval: Swarm, project or `*`, repository, who, their
+ GitHub login. **Install on GitHub** carries the same signed state, so installing approves too.
+- Both token routes (a start's preparation and a task's own token) refuse an unapproved project with
+ `GITHUB_REPOSITORY_NOT_APPROVED`. The status says `not-approved`, with the buttons, until then.
+- The signed state names the person, Swarm, project, repository and scope, lasts ten minutes, and is signed with a key
+ derived from the app's private key. The callback trusts nothing else.
+
+## Build
+
+1. **Backend** `GET /api/super-tabs/:tabId/projects/:projectId/github[?refresh=1]` → `{ state, repository?,
+ installUrl? }` for any person who may open the project. It uses `GitHubApp.resolve` (a renamed repository included)
+ and its caches; `refresh=1` (Check again, the app coming back to the front) forgets a remembered "not installed" for
+ that repository, at most once every 15 seconds per repository.
+2. **Desktop** `super_tabs/project_github.dart`: the status and its actions, in Project details, and the sidebar line
+ from the controller's per-project cache (read when the Swarm has another person in it, again after 5 minutes, and on
+ Check again).
+3. **GitHub, once**: the app is made installable by any account (its settings, Advanced → Make public), and optionally
+ its Setup URL points at a Harness page so GitHub sends the installer back.
+
+## Design
+
+- **Approvals (stored):** one row per Swarm, repository and project (or `*`); deleted with nothing yet, so at most
+ projects × repositories per Swarm, a few hundred. A unique index makes approving again an update. Reads are one
+ indexed lookup per token request. Old clients never approve: their teammates' starts get `GITHUB_REPOSITORY_NOT_APPROVED`
+ until someone approves in a new one. Rolling back leaves the rows unused.
+- **Growth:** nothing else stored. The backend keeps its existing in-memory lookup caches (ten minutes for an installation,
+ one minute for none), bounded by the projects asked about.
+- **Concurrency:** a read only; no lock. Two reads at once may both ask GitHub; the cache keeps that to one per minute.
+- **Read cost:** one GitHub lookup per repository per cache window; Desktop reads per project at most every 5 minutes
+ and on Check again, and only in a Swarm with another person in it.
+- **Scale:** 10x projects is 10x lookups per window, each one GitHub call; GitHub's app rate limit (5,000 an hour per
+ installation, more for larger ones) is the metric that warns first. `refresh` is held to once per 15 s per repository.
+- **Compatibility:** an older backend answers 404 for the route: Desktop shows nothing, as before. An older Desktop
+ never asks. The Lead's refusal stays the fallback either way.
+- **Migration and rollback:** nothing to migrate; rolling back removes the line.
+- **Audience:** the server checks the reader may open the project (a private project's members only); the answer holds
+ only the repository's name and the public install link, never a token.
+- **Identity:** no one's login is used; the app's own credentials read whether it is installed, as for a token.
+- **Failure:** GitHub not answering reads as "Couldn't reach GitHub. Check again", never as covered.
+- **Platforms:** the backend and every Desktop; the install page is GitHub's, in the browser.
diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.md
index 78bd50154..d2fccc720 100644
--- a/docs/swarm-github-app.md
+++ b/docs/swarm-github-app.md
@@ -94,6 +94,18 @@ Set these on the backend and deploy it:
| `GITHUB_APP_PRIVATE_KEY` | The `.pem` file's contents. You can paste them as they are, with line breaks written as `\n`, or as base64: `base64 < key.pem \| tr -d '\n'`. |
| `GITHUB_APP_SLUG` | The app's name from `https://github.com/apps/NAME`. Optional; it adds the install link to refusals. |
+| `GITHUB_APP_CLIENT_ID` | The app's Client ID (`Iv23…`), for its sign-in. |
+| `GITHUB_APP_CLIENT_SECRET` | A client secret: the app's page, **Client secrets → Generate a new client secret**. Keep it with the private key. |
+
+The last two let a person approve a repository for a Swarm project (below). Set both or neither: one alone stops the
+backend at startup. Without them, no repository can be approved, so the app gives no tokens.
+
+On the app's settings page on GitHub, so that GitHub sends people back to Harness:
+
+- **Callback URL** and **Setup URL**: `https://harness-api.autonomous.ai/api/github/callback` (your server's address).
+- **Request user authorization (OAuth) during installation**: on. Installing then also approves the repository.
+- **Redirect on update**: on.
+
If both of the first two are empty, the feature is off and nothing changes. If only
one of them is set, or the key cannot be read, the backend stops at startup with a
message that never shows the key. Once the key is configured, delete the downloaded
@@ -104,6 +116,16 @@ whose repository has the app installed. When it has a task, `git push` and
`gh pr create` work in its terminal. `git log -1` shows the trailers, and on GitHub
the push and pull request appear as the app.
+## Approving a repository for a project
+
+A project's repository address is text its owner types, and the app is installed on other people's repositories too.
+So the app gives a project tokens only once someone GitHub says can push to the repository approved it, for that
+project or for every project of the Swarm (`backend/src/github/approvals.ts`). In Harness: Project details, **GitHub
+access**, **Approve for this project** (or **for every project here**). The person signs in to GitHub through the app;
+their own short-lived token reads whether they can push, is revoked at once and is never stored. **Install on GitHub**
+in the same place approves too, once installed. A project without an approval gets
+`GITHUB_REPOSITORY_NOT_APPROVED`.
+
## Which agents use it
Harness wires the app into an agent when the start meets all of these conditions: