Skip to content
Merged
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
11 changes: 11 additions & 0 deletions packages/app/src/linear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
};
43 changes: 38 additions & 5 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -27,6 +27,8 @@ const text = (value: unknown): string => typeof value === "string" ? value : "";
const linearSource = new LinearSourceAdapter();

export class Tenant extends DurableObject<Env> {
private linearRefresh?: Promise<string>;

constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.ctx.storage.sql.exec(`
Expand Down Expand Up @@ -780,10 +782,41 @@ export class Tenant extends DurableObject<Env> {
}

private async linear(token: string, query: string, variables: Record<string, unknown>): Promise<any> {
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<string> {
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<void> {
Expand Down
19 changes: 17 additions & 2 deletions packages/app/test/linear.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand All @@ -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");
});
});