From e0f1aadc85c2ee50f100330be3664995ea4ed1e3 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 16:05:01 +0000 Subject: [PATCH] Refresh expired Linear access tokens --- packages/app/src/linear.ts | 11 ++++++++ packages/app/src/tenant.ts | 43 ++++++++++++++++++++++++++++---- packages/app/test/linear.test.ts | 19 ++++++++++++-- 3 files changed, 66 insertions(+), 7 deletions(-) diff --git a/packages/app/src/linear.ts b/packages/app/src/linear.ts index 5fdfaac1..5f04b4c1 100644 --- a/packages/app/src/linear.ts +++ b/packages/app/src/linear.ts @@ -9,3 +9,14 @@ export const LINEAR_OPTION_QUERIES = { users: "query { users(first: 100) { nodes { id name } } }", labels: "query { issueLabels(first: 100) { nodes { id name } } }", } as const; + +export const refreshLinearToken = async (refreshToken: string, clientId: string, clientSecret: string): Promise<{ access_token: string; refresh_token?: string }> => { + const response = await fetch("https://api.linear.app/oauth/token", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId, client_secret: clientSecret }), + }); + const tokens = await response.json() as { access_token?: string; refresh_token?: string }; + if (!response.ok || !tokens.access_token) throw new Error("Your Linear connection expired. Reconnect Linear to continue."); + return { access_token: tokens.access_token, refresh_token: tokens.refresh_token }; +}; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 20040cc7..30a2e3f6 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -3,7 +3,7 @@ import Mustache from "mustache"; import { decrypt, encrypt } from "./crypto"; import { agentListCommand, agentOutputCommand, agentStartupBlocked, agentStatusCommand, connectionCheckCommand, defaultAgentCommand, exec, garbageCollectPaneCommand, herdrAgentStatus, herdrCheckCommand, paneGetCommand, paneProcessInfoCommand, replaceForegroundCommand, startAgentCommand, startAgentInPaneCommand, stopAgentCommand, validateWorktreeLeaseCommand, type ExeConnection } from "./exe"; import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; -import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY } from "./linear"; +import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, refreshLinearToken } from "./linear"; import { matchingIssue } from "./matcher"; import type { Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; import { workingDirectoryFor, workspaceNameFor } from "./workspace"; @@ -27,6 +27,8 @@ const text = (value: unknown): string => typeof value === "string" ? value : ""; const linearSource = new LinearSourceAdapter(); export class Tenant extends DurableObject { + private linearRefresh?: Promise; + constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.ctx.storage.sql.exec(` @@ -780,10 +782,41 @@ export class Tenant extends DurableObject { } private async linear(token: string, query: string, variables: Record): Promise { - const response = await fetch("https://api.linear.app/graphql", { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify({ query, variables }) }); - const payload = await response.json() as any; - if (!response.ok || payload.errors?.length) throw new Error(payload.errors?.[0]?.message ?? `Linear request failed (${response.status})`); - return payload.data; + const request = async (accessToken: string) => { + const response = await fetch("https://api.linear.app/graphql", { method: "POST", headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" }, body: JSON.stringify({ query, variables }) }); + const payload = await response.json() as any; + return { response, payload }; + }; + let result = await request(token); + const message = result.payload.errors?.[0]?.message; + if ((result.response.status === 401 || /authentication required|not authenticated/i.test(message ?? ""))) { + const refreshed = await this.refreshLinearAccessToken(token); + result = await request(refreshed); + } + if (!result.response.ok || result.payload.errors?.length) throw new Error(result.payload.errors?.[0]?.message ?? `Linear request failed (${result.response.status})`); + return result.payload.data; + } + + private async refreshLinearAccessToken(staleToken: string): Promise { + if (this.linearRefresh) return this.linearRefresh; + this.linearRefresh = (async () => { + const linear = await this.connection<{ accessToken: string; refreshToken: string; organizationId: string; organizationName?: string }>("linear"); + if (!linear?.refreshToken) throw new Error("Reconnect Linear to continue."); + // Another request may have refreshed the rotating token while this one was in flight. + if (linear.accessToken !== staleToken) return linear.accessToken; + const tokens = await refreshLinearToken(linear.refreshToken, this.env.LINEAR_CLIENT_ID, this.env.LINEAR_CLIENT_SECRET); + await this.putConnection("linear", { + ...linear, + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token ?? linear.refreshToken, + }); + return tokens.access_token; + })(); + try { + return await this.linearRefresh; + } finally { + this.linearRefresh = undefined; + } } private async putConnection(kind: string, value: unknown): Promise { diff --git a/packages/app/test/linear.test.ts b/packages/app/test/linear.test.ts index 5ae1fd55..fa47249a 100644 --- a/packages/app/test/linear.test.ts +++ b/packages/app/test/linear.test.ts @@ -1,5 +1,7 @@ -import { describe, expect, it } from "vitest"; -import { LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY } from "../src/linear"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, refreshLinearToken } from "../src/linear"; + +afterEach(() => vi.restoreAllMocks()); describe("Linear queries", () => { it("keeps the projects lookup small and unnested", () => { @@ -16,4 +18,17 @@ describe("Linear queries", () => { expect(query).not.toContain("projects"); } }); + + it("exchanges a refresh token for a fresh Linear token pair", async () => { + const request = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ access_token: "access-new", refresh_token: "refresh-new" })); + + await expect(refreshLinearToken("refresh-old", "client-id", "client-secret")).resolves.toEqual({ access_token: "access-new", refresh_token: "refresh-new" }); + const [, init] = request.mock.calls[0]; + expect(String(init?.body)).toBe("grant_type=refresh_token&refresh_token=refresh-old&client_id=client-id&client_secret=client-secret"); + }); + + it("asks the user to reconnect when Linear rejects the refresh token", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ error: "invalid_grant" }, { status: 401 })); + await expect(refreshLinearToken("expired", "client-id", "client-secret")).rejects.toThrow("Reconnect Linear"); + }); });