Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 71 additions & 2 deletions server/src/providers/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import { tr } from '../i18n.js'
* minute is well inside it.
* - `GET /repos/{owner}/{repo}/actions/runs?per_page=10` — workflow runs, one call per repo
* named in the connection's `repos` field, capped at ten repos.
* - `GET /users/{login}/events?per_page=100` — the authenticated user's recent activity, used
* to order My Scope by what Livio did rather than by what somebody else changed. GitHub's
* event feed can lag and only covers a bounded recent window; it is the closest supported
* account-wide signal, not a real-time audit log.
*
* Every GET goes through a conditional request: the ETag of the previous answer is sent back as
* `If-None-Match`, and a `304 Not Modified` replays the cached body. GitHub does not charge a 304
Expand Down Expand Up @@ -95,6 +99,11 @@ export interface GhRun {
url: string
}

export interface GhRepoActivity {
repo: string
updatedAt: number
}

/**
* Why one source of the snapshot has no fresh rows.
*
Expand All @@ -111,6 +120,7 @@ export type GhSectionError = 'unauthorized' | 'forbidden' | 'fine-grained-token'

/** One entry per source of the snapshot; a missing key means that source is fresh. */
export interface GhSectionErrors {
activity?: GhSectionError
notifications?: GhSectionError
reviews?: GhSectionError
myPrs?: GhSectionError
Expand All @@ -130,6 +140,7 @@ export interface GhSectionErrors {
* at all, therefore still shows its reviews, its pull requests and its workflow runs.
*/
export interface GhSnapshot {
repoActivity: GhRepoActivity[]
notifications: GhNotification[]
reviewRequests: GhPull[]
myPrs: GhPull[]
Expand All @@ -147,6 +158,11 @@ export const isFineGrainedToken = (token: string | undefined): boolean =>
(token ?? '').startsWith(FINE_GRAINED_PREFIX)

const OWNER_REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/
const USER_ACTIVITY_TYPES = new Set([
'CommitCommentEvent', 'CreateEvent', 'DeleteEvent', 'DiscussionEvent', 'ForkEvent',
'IssueCommentEvent', 'IssuesEvent', 'PullRequestEvent', 'PullRequestReviewEvent',
'PullRequestReviewCommentEvent', 'PushEvent', 'ReleaseEvent',
])

/**
* `https://api.github.com/` → `https://api.github.com`, empty → the github.com root.
Expand Down Expand Up @@ -275,6 +291,24 @@ export function normalizePulls(json: unknown): GhPull[] {
return out
}

/** `GET /users/{login}/events` → only the authenticated user's contribution-like repo touches. */
export function normalizeUserRepoActivity(json: unknown, login: string): GhRepoActivity[] {
if (!Array.isArray(json) || !login) return []
const latest = new Map<string, GhRepoActivity>()
for (const raw of json as Record<string, any>[]) {
const repo = String(raw?.repo?.name ?? '')
const actor = String(raw?.actor?.login ?? '')
const updatedAt = epoch(raw?.created_at)
if (!OWNER_REPO_RE.test(repo) || repo.split('/').some(part => part === '.' || part === '..')
|| actor.toLowerCase() !== login.toLowerCase()) continue
if (!USER_ACTIVITY_TYPES.has(String(raw?.type)) || updatedAt === undefined) continue
const key = repo.toLowerCase()
const previous = latest.get(key)
if (!previous || updatedAt > previous.updatedAt) latest.set(key, { repo, updatedAt })
}
return [...latest.values()].sort((a, b) => b.updatedAt - a.updatedAt)
}

function runStatus(status: unknown): GhRunStatus {
switch (status) {
case 'completed': return 'completed'
Expand Down Expand Up @@ -360,6 +394,12 @@ const OpenRowPayload = z.object({
id: z.string().regex(/^\d{1,20}$/),
})

// A widget can ask to open a repository name, but it cannot supply a destination URL.
const OpenRepoPayload = z.strictObject({
repo: z.string().regex(OWNER_REPO_RE),
instanceId: z.string().min(1).max(200).optional(),
})

export interface GithubDeps {
openRunner?: (cmd: string, args: string[]) => Promise<void>
fetchFn?: typeof fetch
Expand Down Expand Up @@ -391,7 +431,7 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu
/** While `now()` is below this the provider does not call at all: the quota is spent. */
let quietUntil = 0
let rateLimit: GhSnapshot['rateLimit']
let last: GhSnapshot = { notifications: [], reviewRequests: [], myPrs: [], runs: [] }
let last: GhSnapshot = { repoActivity: [], notifications: [], reviewRequests: [], myPrs: [], runs: [] }
/**
* Set once a fine-grained token has been refused by `/notifications`. The endpoint only answers
* a classic token, so asking again every minute would spend a request on a certain 403 forever.
Expand Down Expand Up @@ -559,7 +599,9 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu
}
}

const [reviewRequests, myPrs] = await Promise.all([
const [repoActivity, reviewRequests, myPrs] = await Promise.all([
section('activity', last.repoActivity, async () =>
normalizeUserRepoActivity(await get(`${base}/users/${encodeURIComponent(me)}/events?per_page=100`), me)),
section('reviews', last.reviewRequests, async () =>
normalizePulls(await get(searchUrl(`is:pr is:open archived:false review-requested:${me}`)))),
section('myPrs', last.myPrs, async () =>
Expand Down Expand Up @@ -591,6 +633,7 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu
}

last = {
repoActivity,
notifications,
reviewRequests,
myPrs,
Expand Down Expand Up @@ -625,6 +668,32 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu
try { await openRunner('/usr/bin/open', [url.href]); return { ok: true } }
catch { return { ok: false } }
},
/** Opens a repository shown in this connection's current activity snapshot. */
openRepo: async (payload, context) => {
if (!context?.loopback) return { ok: false, error: tr(undefined, 'provider.localOnly') }
const parsed = OpenRepoPayload.safeParse(payload)
if (!parsed.success) throw new Error(tr(undefined, 'github.invalidCommand'))
const { repo } = parsed.data
const visibleRepos = [
...last.repoActivity.map(item => item.repo),
...last.notifications.map(row => row.repo),
...last.reviewRequests.map(row => row.repo),
...last.myPrs.map(row => row.repo),
]
if (!base || !visibleRepos.includes(repo)) return { ok: false }

let host: string
try {
const configured = new URL(base)
// Do not turn an API URL with an unusual port into a different web origin.
if (configured.port) return { ok: false }
host = base === GITHUB_DEFAULT_HOST ? 'github.com' : configured.hostname
if (!host || configured.username || configured.password) return { ok: false }
} catch { return { ok: false } }

try { await openRunner('/usr/bin/open', [`https://${host}/${repo}`]); return { ok: true } }
catch { return { ok: false } }
},
/** Marks one notification thread read — what a tap on an inbox row asks for. */
markRead: async (payload) => {
const parsed = MarkReadPayload.safeParse(payload)
Expand Down
78 changes: 76 additions & 2 deletions server/test/github.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ function responder(options: {
if (url.includes('/user/repos')) return []
if (url.endsWith('/user')) return { login: 'example-user' }
if (url.includes('/notifications')) return NOTIFICATIONS
if (url.includes('/users/') && url.includes('/events')) return []
if (url.includes('review-requested')) return REVIEWS
if (url.includes('/search/issues')) return MINE
if (url.includes('/actions/runs')) return RUNS
Expand Down Expand Up @@ -190,6 +191,30 @@ const context = (fields: Record<string, string> = {}) => ({
})

describe('createGithubProvider', () => {
it('orders repositories from the authenticated account activity endpoint', async () => {
const calls: string[] = []
const fetchFn = (async (url: string) => {
const target = String(url)
calls.push(target)
if (target.endsWith('/user')) return new Response(JSON.stringify({ login: 'example-user' }))
if (target.includes('/users/example-user/events')) return new Response(JSON.stringify([
{ type: 'PushEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/active' }, created_at: '2026-10-19T02:00:00Z' },
{ type: 'PullRequestReviewEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/reviewed' }, created_at: '2026-10-19T01:00:00Z' },
{ type: 'PushEvent', actor: { login: 'someone-else' }, repo: { name: 'example-org/other' }, created_at: '2026-10-19T03:00:00Z' },
{ type: 'WatchEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/watched' }, created_at: '2026-10-19T04:00:00Z' },
{ type: 'IssuesEvent', actor: { login: 'example-user' }, repo: { name: '../unsafe' }, created_at: '2026-10-19T05:00:00Z' },
]))
return new Response('[]')
}) as unknown as typeof fetch
const snapshot = await createGithubProvider(context({ repos: '' }), { fetchFn, now: () => 0 }).poll!() as GhSnapshot

expect(calls).toContain('https://api.github.com/users/example-user/events?per_page=100')
expect(snapshot.repoActivity).toEqual([
{ repo: 'example-org/active', updatedAt: Date.parse('2026-10-19T02:00:00Z') },
{ repo: 'example-org/reviewed', updatedAt: Date.parse('2026-10-19T01:00:00Z') },
])
})

it('reads the login, the inbox, both searches and one run list per repo', async () => {
const { calls, fetchFn } = responder()
const provider = createGithubProvider(context(), { fetchFn, now: () => 1_000_000 })
Expand All @@ -199,6 +224,7 @@ describe('createGithubProvider', () => {
expect(calls.map((c) => c.url)).toEqual([
'https://api.github.com/user',
'https://api.github.com/notifications?all=false&per_page=50',
'https://api.github.com/users/example-user/events?per_page=100',
'https://api.github.com/search/issues?q=is%3Apr%20is%3Aopen%20archived%3Afalse%20review-requested%3Aexample-user&per_page=25&sort=updated&order=desc&advanced_search=true',
'https://api.github.com/search/issues?q=is%3Apr%20is%3Aopen%20archived%3Afalse%20author%3Aexample-user&per_page=25&sort=updated&order=desc&advanced_search=true',
'https://api.github.com/repos/example-org/example-repo/actions/runs?per_page=10',
Expand Down Expand Up @@ -230,7 +256,7 @@ describe('createGithubProvider', () => {
const { calls, fetchFn } = responder()
const ctx = { ...context(), secrets: {} }
expect(await createGithubProvider(ctx, { fetchFn, now: () => 0 }).poll!())
.toEqual({ notifications: [], reviewRequests: [], myPrs: [], runs: [], error: 'unconfigured' })
.toEqual({ repoActivity: [], notifications: [], reviewRequests: [], myPrs: [], runs: [], error: 'unconfigured' })
expect(calls).toHaveLength(0)
})

Expand Down Expand Up @@ -335,7 +361,7 @@ describe('createGithubProvider', () => {
const second = (await provider.poll!()) as GhSnapshot
expect(second.error).toBe('offline')
expect(second.errors)
.toEqual({ notifications: 'offline', reviews: 'offline', myPrs: 'offline', runs: 'offline' })
.toEqual({ notifications: 'offline', activity: 'offline', reviews: 'offline', myPrs: 'offline', runs: 'offline' })
// Every section keeps the rows it last had.
expect(second.notifications.map((n) => n.id)).toEqual(first.notifications.map((n) => n.id))
expect(second.runs).toHaveLength(3)
Expand Down Expand Up @@ -570,4 +596,52 @@ describe('opening GitHub rows', () => {
expect(await provider.commands!.open({ kind: 'run', id: snapshot.runs[0].id, url: 'https://evil.test', futureHostField: true }, { loopback: true })).toEqual({ ok: true })
expect(opened).toEqual([['/usr/bin/open', snapshot.runs[0].url]])
})

it('opens only a repository already present in this connection snapshot', async () => {
const { fetchFn, calls } = responder()
const opened: string[][] = []
const provider = createGithubProvider(context(), { fetchFn, openRunner: async (cmd, args) => { opened.push([cmd, ...args]) } })
const snapshot = await provider.poll!() as GhSnapshot
const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise<unknown> }

expect(await commands.openRepo({ repo: snapshot.reviewRequests[0].repo }, { loopback: true })).toEqual({ ok: true })
expect(opened).toEqual([['/usr/bin/open', `https://github.com/${snapshot.reviewRequests[0].repo}`]])
expect(calls.every((call) => call.method === 'GET')).toBe(true)
})

it('opens a repository that is present only in the authenticated activity snapshot', async () => {
const opened: string[][] = []
const provider = createGithubProvider(context({ repos: '' }), {
fetchFn: (async (url: string) => {
if (url.endsWith('/user')) return new Response(JSON.stringify({ login: 'example-user' }))
if (url.includes('/users/example-user/events')) return new Response(JSON.stringify([
{ type: 'PushEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/activity-only' }, created_at: '2026-10-19T02:00:00Z' },
]))
return new Response('[]')
}) as unknown as typeof fetch,
openRunner: async (cmd, args) => { opened.push([cmd, ...args]) },
})
const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise<unknown> }
const snapshot = await provider.poll!() as GhSnapshot

expect(snapshot.repoActivity).toEqual([{ repo: 'example-org/activity-only', updatedAt: Date.parse('2026-10-19T02:00:00Z') }])
expect(await commands.openRepo({ repo: 'example-org/activity-only' }, { loopback: true })).toEqual({ ok: true })
expect(opened).toEqual([['/usr/bin/open', 'https://github.com/example-org/activity-only']])
})

it('refuses non-loopback, unknown, or malformed repository targets', async () => {
const { fetchFn } = responder()
const opened: string[][] = []
const provider = createGithubProvider(context(), { fetchFn, openRunner: async (cmd, args) => { opened.push([cmd, ...args]) } })
const snapshot = await provider.poll!() as GhSnapshot
const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise<unknown> }
const repo = snapshot.reviewRequests[0].repo

expect(await commands.openRepo({ repo }, { loopback: false })).toEqual({ ok: false, error: tr(undefined, 'provider.localOnly') })
expect(await commands.openRepo({ repo: 'other/repo' }, { loopback: true })).toEqual({ ok: false })
for (const unsafe of ['../etc/passwd', 'example-org/repo/extra', 'https://evil.test/a/b', '']) {
await expect(commands.openRepo({ repo: unsafe }, { loopback: true })).rejects.toThrow()
}
expect(opened).toEqual([])
})
})