Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: Linear connection routes and OAuth callback (work 037, S5)

Igor Zalutski265e1730da2c
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 4c5956e1..f7fb2b01 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -517,3 +517,58 @@ describe("/api/managed-agents/slack/callback — unauthenticated mount", () => {
);
});
});
+
+describe("/api/managed-agents/linear — public mounts", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ // Linear redirects here with no OpenComputer credentials; the backend puts
+ // this URL in every authorize link, so the mount stays above the API-key
+ // check and forwards the query untouched.
+ it("forwards Linear's redirect to the backend callback without an API key", async () => {
+ const location =
+ "https://app.opencomputer.dev/projects/prj_test/connections?environment=production&linear=connected&connection=lc_1";
+ const fetchSpy = vi.fn(
+ async (_target: URL | RequestInfo, _init?: RequestInit) =>
+ new Response(null, { status: 302, headers: { location } }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const resp = await worker.fetch(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/linear/callback?state=x&code=y",
+ ),
+ { ...env, MANAGED_AGENTS_API_URL: "https://managedagents.test" },
+ ctx,
+ );
+
+ expect(resp.status).toBe(302);
+ expect(resp.headers.get("location")).toBe(location);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy.mock.calls[0][0].toString()).toBe(
+ "https://managedagents.test/v1/linear/oauth/callback?state=x&code=y",
+ );
+ });
+
+ it("requires an API key for the connection routes", async () => {
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const resp = await worker.fetch(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_test/linear/connections",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ name: "Triage", environment: "production", agentId: "triage" }),
+ },
+ ),
+ { ...env, MANAGED_AGENTS_API_URL: "https://managedagents.test" },
+ ctx,
+ );
+
+ expect(resp.status).toBe(401);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 0ffb7a28..32b4bfb4 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -89,6 +89,7 @@ import {
handleAgentWebhookInvocation,
handleManagedGitHubCallback,
handleManagedSlackCallback,
+ handleManagedLinearCallback,
handleManagedAgentChannelConnection,
proxyManagedAgents,
} from "./managed_agents";
@@ -5562,6 +5563,16 @@ export default {
) {
return handleManagedSlackCallback(req, env);
}
+ // Linear's OAuth redirect for a project's Linear agent connection. The
+ // backend puts this exact URL in every authorize link and on the app it
+ // prefills (BLUE_LINEAR_OAUTH_REDIRECT_URI, default: the Slack callback's
+ // sibling); it answers with a redirect into the project's Connections tab.
+ if (
+ path === "/api/managed-agents/linear/callback" &&
+ req.method === "GET"
+ ) {
+ return handleManagedLinearCallback(req, env);
+ }
if (path.startsWith("/api/agent-webhooks/")) {
return handleAgentWebhookInvocation(req, env);
}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 1ce419f9..a66de293 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -4,6 +4,7 @@ import {
handleAgentWebhookInvocation,
handleManagedAgentChannelConnection,
handleManagedGitHubCallback,
+ handleManagedLinearCallback,
handleManagedSlackCallback,
hasBYOKPlanAccess,
mintManagedAgentsAssertion,
@@ -5847,3 +5848,450 @@ describe("managed agents proxy", () => {
).toEqual({ code: "tool_failed", message: "A tool failed." });
});
});
+
+describe("Linear agent connections", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ const env = {
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ };
+ const caller = { orgID: "org_test", userID: "user_test" };
+ const webhookUrl =
+ "https://managedagents.test/v1/webhooks/linear/lc_0123456789abcdef0123456789abcdef/" +
+ "a".repeat(64);
+ const createAppUrl =
+ "https://linear.app/settings/api/applications/new?distribution=private";
+ const backendConnection = {
+ id: "lc_0123456789abcdef0123456789abcdef",
+ projectId: "prj_test",
+ environment: "production",
+ agentId: "triage",
+ name: "Triage",
+ status: "pending",
+ webhookUrl,
+ createAppUrl,
+ revision: 1,
+ createdAt: "2026-10-02T00:00:00.000Z",
+ updatedAt: "2026-10-02T00:00:00.000Z",
+ accountId: "private_org",
+ clientSecret: "never",
+ accessToken: "never",
+ };
+
+ function send(path: string, init?: RequestInit) {
+ return proxyManagedAgents(
+ new Request(`https://app.opencomputer.dev/api/managed-agents${path}`, init),
+ env,
+ caller,
+ "/api/managed-agents",
+ );
+ }
+
+ function forwarded(fetchMock: ReturnType<typeof vi.fn>) {
+ const [target, init] = fetchMock.mock.calls[0] as [URL, RequestInit];
+ const headers = new Headers(init.headers);
+ return { target: target.toString(), init, headers };
+ }
+
+ it("creates a connection for a project and returns its URLs", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json(
+ {
+ connectionId: backendConnection.id,
+ webhookUrl,
+ createAppUrl,
+ connection: backendConnection,
+ },
+ { status: 201 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const response = await send("/projects/prj_test/linear/connections", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ name: "Triage",
+ environment: "production",
+ agentId: "triage",
+ }),
+ });
+
+ expect(response.status).toBe(201);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ const body = (await response.json()) as Record<string, unknown>;
+ expect(body).toMatchObject({
+ connectionId: backendConnection.id,
+ webhookUrl,
+ createAppUrl,
+ connection: {
+ id: backendConnection.id,
+ projectId: "prj_test",
+ environment: "production",
+ agentId: "triage",
+ name: "Triage",
+ status: "pending",
+ webhookUrl,
+ createAppUrl,
+ revision: 1,
+ },
+ });
+ expect(JSON.stringify(body)).not.toContain("private_org");
+ expect(JSON.stringify(body)).not.toContain("never");
+
+ const { target, init, headers } = forwarded(fetchMock);
+ expect(target).toBe(
+ "https://managedagents.test/v1/projects/prj_test/linear/connections",
+ );
+ expect(init.method).toBe("POST");
+ expect(headers.get("content-type")).toBe("application/json");
+ const token = headers.get("x-opencomputer-agent-token") ?? "";
+ expect(decodePayload(token)).toMatchObject({
+ org_id: "org_test",
+ user_id: "user_test",
+ });
+ expect(await new Response(init.body).json()).toEqual({
+ name: "Triage",
+ environment: "production",
+ agentId: "triage",
+ });
+ });
+
+ it("lists a project's connections with health and forwards the environment", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ connections: [
+ {
+ ...backendConnection,
+ status: "connected",
+ clientId: "client-id",
+ appUserId: "app-user",
+ organizationId: "org-linear",
+ verifiedAt: "2026-10-02T00:01:00.000Z",
+ lastEventAt: "2026-10-02T00:02:00.000Z",
+ teams: { allPublic: false, teamIds: ["team_1"], secret: "x" },
+ health: {
+ state: "receiving",
+ message: "First session received",
+ lastEventAt: "2026-10-02T00:02:00.000Z",
+ internal: "x",
+ },
+ },
+ ],
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const response = await send(
+ "/projects/prj_test/linear/connections?environment=production",
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ const body = (await response.json()) as {
+ connections: Record<string, unknown>[];
+ };
+ expect(body.connections).toHaveLength(1);
+ expect(body.connections[0]).toMatchObject({
+ id: backendConnection.id,
+ status: "connected",
+ clientId: "client-id",
+ appUserId: "app-user",
+ organizationId: "org-linear",
+ webhookUrl,
+ teams: { allPublic: false, teamIds: ["team_1"] },
+ health: {
+ state: "receiving",
+ message: "First session received",
+ lastEventAt: "2026-10-02T00:02:00.000Z",
+ },
+ });
+ expect(JSON.stringify(body)).not.toMatch(/private_org|never|internal|secret/);
+ const { target, init, headers } = forwarded(fetchMock);
+ expect(target).toBe(
+ "https://managedagents.test/v1/projects/prj_test/linear/connections?environment=production",
+ );
+ expect(init.method).toBe("GET");
+ expect(init.body).toBeUndefined();
+ expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
+ });
+
+ it("forwards pasted credentials and never echoes them", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ connection: {
+ ...backendConnection,
+ clientId: "client-id",
+ clientSecret: "client-secret",
+ signingSecret: "signing-secret",
+ },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const credentials = {
+ clientId: "client-id",
+ clientSecret: "client-secret",
+ signingSecret: "signing-secret",
+ };
+
+ const response = await send(
+ `/linear/connections/${backendConnection.id}/credentials`,
+ {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(credentials),
+ },
+ );
+
+ expect(response.status).toBe(200);
+ const text = await response.text();
+ expect(text).not.toContain("client-secret");
+ expect(text).not.toContain("signing-secret");
+ expect(JSON.parse(text)).toMatchObject({
+ connection: { id: backendConnection.id, clientId: "client-id" },
+ });
+ const { target, init, headers } = forwarded(fetchMock);
+ expect(target).toBe(
+ `https://managedagents.test/v1/linear/connections/${backendConnection.id}/credentials`,
+ );
+ expect(init.method).toBe("PUT");
+ expect(headers.get("x-opencomputer-agent-token")).toBeTruthy();
+ expect(await new Response(init.body).json()).toEqual(credentials);
+ });
+
+ it("issues the authorization URL", async () => {
+ const authorizeUrl =
+ "https://linear.app/oauth/authorize?client_id=client-id&actor=app&state=opaque&redirect_uri=https%3A%2F%2Fapp.opencomputer.dev%2Fapi%2Fmanaged-agents%2Flinear%2Fcallback";
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ authorizeUrl,
+ expiresAt: "2026-10-02T00:10:00.000Z",
+ nonce: "private",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const response = await send(
+ `/linear/connections/${backendConnection.id}/authorize`,
+ { method: "POST" },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ await expect(response.json()).resolves.toEqual({
+ authorizeUrl,
+ expiresAt: "2026-10-02T00:10:00.000Z",
+ });
+ const { target, init } = forwarded(fetchMock);
+ expect(target).toBe(
+ `https://managedagents.test/v1/linear/connections/${backendConnection.id}/authorize`,
+ );
+ expect(init.method).toBe("POST");
+ });
+
+ it("deletes a connection", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ connection: { ...backendConnection, status: "disconnected" },
+ revoked: true,
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const response = await send(`/linear/connections/${backendConnection.id}`, {
+ method: "DELETE",
+ });
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ connection: { id: backendConnection.id, status: "disconnected" },
+ revoked: true,
+ });
+ const { target, init } = forwarded(fetchMock);
+ expect(target).toBe(
+ `https://managedagents.test/v1/linear/connections/${backendConnection.id}`,
+ );
+ expect(init.method).toBe("DELETE");
+ });
+
+ it("admits only the contract's Linear routes", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ for (const [method, path] of [
+ ["GET", `/linear/connections/${backendConnection.id}`],
+ ["PUT", `/linear/connections/${backendConnection.id}`],
+ ["GET", `/linear/connections/${backendConnection.id}/credentials`],
+ ["GET", `/linear/connections/${backendConnection.id}/authorize`],
+ ["DELETE", "/projects/prj_test/linear/connections"],
+ ["GET", "/linear/oauth/callback?state=x&code=y"],
+ ["POST", `/webhooks/linear/${backendConnection.id}/${"a".repeat(64)}`],
+ ["POST", "/projects/prj_test/linear/connections/extra"],
+ ] as const) {
+ const response = await send(path, { method });
+ expect(response.status, `${method} ${path}`).toBe(404);
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("refuses without project access, keeping the backend's code", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi
+ .fn()
+ .mockResolvedValueOnce(
+ Response.json(
+ { error: { code: "project_not_found", message: "Project not found" } },
+ { status: 404 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ Response.json(
+ {
+ error: {
+ code: "forbidden",
+ message: "Project tokens cannot manage Linear connections",
+ },
+ },
+ { status: 403 },
+ ),
+ ),
+ );
+
+ const listed = await send("/projects/prj_other/linear/connections");
+ expect(listed.status).toBe(404);
+ await expect(listed.json()).resolves.toEqual({
+ error: {
+ code: "project_not_found",
+ message: "The requested agent resource was not found.",
+ },
+ });
+
+ const authorized = await send(
+ `/linear/connections/${backendConnection.id}/authorize`,
+ { method: "POST" },
+ );
+ expect(authorized.status).toBe(403);
+ await expect(authorized.json()).resolves.toEqual({
+ error: {
+ code: "forbidden",
+ message: "The agent request was not authorized.",
+ },
+ });
+ });
+
+ it("maps Linear conflicts to curated messages with the connection id", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ Response.json(
+ {
+ error: {
+ code: "linear_already_connected",
+ message: "backend wording",
+ connectionId: backendConnection.id,
+ accountId: "private_org",
+ },
+ },
+ { status: 409 },
+ ),
+ ),
+ );
+
+ const response = await send("/projects/prj_test/linear/connections", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ name: "Triage", environment: "production", agentId: "triage" }),
+ });
+
+ expect(response.status).toBe(409);
+ await expect(response.json()).resolves.toEqual({
+ error: {
+ code: "linear_already_connected",
+ message:
+ "This agent already has a Linear connection in this environment. Disconnect it before creating another.",
+ connectionId: backendConnection.id,
+ },
+ });
+ });
+
+ it("passes the OAuth callback redirect through with its location", async () => {
+ const location =
+ "https://app.opencomputer.dev/projects/prj_test/connections?environment=production&linear=connected&connection=lc_0123456789abcdef0123456789abcdef";
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(null, {
+ status: 302,
+ headers: { location, "set-cookie": "private=1" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const response = await handleManagedLinearCallback(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/linear/callback?code=oauth-code&state=opaque",
+ ),
+ { MANAGED_AGENTS_API_URL: "https://managedagents.test" },
+ );
+
+ expect(response.status).toBe(302);
+ expect(response.headers.get("location")).toBe(location);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ expect(response.headers.get("set-cookie")).toBeNull();
+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
+ "https://managedagents.test/v1/linear/oauth/callback?code=oauth-code&state=opaque",
+ );
+ expect(fetchMock.mock.calls[0]?.[1]).toEqual({ redirect: "manual" });
+ });
+
+ it("passes the OAuth callback's error page through without a location", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response("<html>Linear connection failed</html>", {
+ status: 400,
+ headers: {
+ "content-type": "text/html; charset=utf-8",
+ location: "https://app.opencomputer.dev/projects/prj_test",
+ },
+ }),
+ ),
+ );
+
+ const response = await handleManagedLinearCallback(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/linear/callback?state=broken",
+ ),
+ { MANAGED_AGENTS_API_URL: "https://managedagents.test" },
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.headers.get("location")).toBeNull();
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ await expect(response.text()).resolves.toContain("Linear connection failed");
+ });
+
+ it("refuses to forward the OAuth callback over plain HTTP or with another method", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ const insecure = await handleManagedLinearCallback(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/linear/callback?code=c&state=s",
+ ),
+ { MANAGED_AGENTS_API_URL: "http://managedagents.test" },
+ );
+ expect(insecure.status).toBe(503);
+
+ const posted = await handleManagedLinearCallback(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/linear/callback",
+ { method: "POST" },
+ ),
+ { MANAGED_AGENTS_API_URL: "https://managedagents.test" },
+ );
+ expect(posted.status).toBe(405);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index 71eb0b92..43f8e609 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -250,8 +250,13 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
)
? SLACK_SETUP_ERROR_MESSAGES[backendCode]
: undefined;
+ const linearMessage = Object.hasOwn(LINEAR_ERROR_MESSAGES, backendCode)
+ ? LINEAR_ERROR_MESSAGES[backendCode]
+ : undefined;
if (slackSetupMessage) {
message = slackSetupMessage;
+ } else if (linearMessage) {
+ message = linearMessage;
} else if (missingTemplateManifest) {
message =
"This is not a valid template: oc-template.toml is missing from the repository root.";
@@ -320,6 +325,15 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
/^[A-Za-z0-9_-]{1,128}$/.test(backendError.setupId)
? { setupId: backendError.setupId }
: {};
+ // A Linear conflict names the connection it concerns, so the caller can
+ // continue from it (disconnect it, or list and resume).
+ const linearConnection =
+ (backendCode === "linear_already_connected" ||
+ backendCode === "linear_connection_changed") &&
+ typeof backendError?.connectionId === "string" &&
+ /^[A-Za-z0-9_-]{1,128}$/.test(backendError.connectionId)
+ ? { connectionId: backendError.connectionId }
+ : {};
// Workspace export refusals say whether the same Idempotency-Key may be
// retried and which export record the refusal was written to.
const exportOutcome: Record<string, unknown> = {};
@@ -337,7 +351,13 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
}
return new Response(
JSON.stringify({
- error: { code: publicCode, message, ...setupId, ...exportOutcome },
+ error: {
+ code: publicCode,
+ message,
+ ...setupId,
+ ...linearConnection,
+ ...exportOutcome,
+ },
}),
{ status: upstream.status, headers },
);
@@ -788,6 +808,91 @@ function publicSlackSetup(value: unknown): Record<string, unknown> {
};
}
+// Linear agent connections (work 037, design 018 "Connection"). One
+// connection per (project, environment, agent); the webhook URL carries the
+// connection's secret token, so every response is no-store.
+const LINEAR_PROJECT_CONNECTIONS_ROUTE =
+ /^\/projects\/[^/]+\/linear\/connections$/;
+const LINEAR_CONNECTION_ROUTE = /^\/linear\/connections\/[^/]+$/;
+const LINEAR_CREDENTIALS_ROUTE = /^\/linear\/connections\/[^/]+\/credentials$/;
+const LINEAR_AUTHORIZE_ROUTE = /^\/linear\/connections\/[^/]+\/authorize$/;
+
+function isLinearConnectionRoute(method: string, suffix: string): boolean {
+ return (
+ ((method === "GET" || method === "POST") &&
+ LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) ||
+ (method === "PUT" && LINEAR_CREDENTIALS_ROUTE.test(suffix)) ||
+ (method === "POST" && LINEAR_AUTHORIZE_ROUTE.test(suffix)) ||
+ (method === "DELETE" && LINEAR_CONNECTION_ROUTE.test(suffix))
+ );
+}
+
+function isLinearRouteSuffix(suffix: string): boolean {
+ return (
+ suffix.startsWith("/linear/") ||
+ /^\/projects\/[^/]+\/linear(?:\/|$)/.test(suffix)
+ );
+}
+
+const LINEAR_ERROR_MESSAGES: Record<string, string> = {
+ linear_connector_unavailable:
+ "Linear connections are not available right now.",
+ linear_connection_not_found: "That Linear connection does not exist.",
+ linear_already_connected:
+ "This agent already has a Linear connection in this environment. Disconnect it before creating another.",
+ linear_connection_changed:
+ "This connection changed while the request was in flight. List the connections and continue from there.",
+ linear_credentials_required:
+ "Paste the app's client ID, client secret and webhook signing secret before authorizing.",
+ invalid_linear_credentials:
+ "Expected clientId, clientSecret and signingSecret as copied from the Linear app.",
+ linear_app_already_connected:
+ "This Linear app is already connected to another agent or environment. Create a separate app for each.",
+ linear_connection_connected:
+ "This connection is authorized with a different Linear app. Disconnect it first.",
+ invalid_linear_app_name: "The Linear app name must be 1 to 64 characters.",
+ linear_app_name_reserved:
+ 'Linear does not allow app names that contain "Linear". Choose another name.',
+};
+
+/** A Linear connection by whitelist: never its credentials or account. */
+function publicLinearConnection(value: unknown): Record<string, unknown> {
+ const connection = record(value) ?? {};
+ const teams = record(connection.teams);
+ const health = record(connection.health);
+ return {
+ id: connection.id,
+ projectId: connection.projectId,
+ environment: connection.environment,
+ agentId: connection.agentId,
+ name: connection.name,
+ status: connection.status,
+ clientId: connection.clientId,
+ appUserId: connection.appUserId,
+ organizationId: connection.organizationId,
+ webhookUrl: connection.webhookUrl,
+ createAppUrl: connection.createAppUrl,
+ verifiedAt: connection.verifiedAt,
+ verificationError: connection.verificationError,
+ lastEventAt: connection.lastEventAt,
+ ...(teams
+ ? { teams: { allPublic: teams.allPublic === true, teamIds: strings(teams.teamIds) } }
+ : {}),
+ ...(health
+ ? {
+ health: {
+ state: health.state,
+ message: health.message,
+ lastEventAt: health.lastEventAt,
+ },
+ }
+ : {}),
+ revision: connection.revision,
+ createdAt: connection.createdAt,
+ updatedAt: connection.updatedAt,
+ };
+}
+
function publicOutboxItem(value: unknown): Record<string, unknown> {
const item = record(value) ?? {};
const content = record(item.contentPreview) ?? {};
@@ -1908,6 +2013,33 @@ function publicSuccessBody(
if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix)) {
return { run: publicScheduleRun(body.run) };
}
+ if (method === "POST" && LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) {
+ return {
+ connectionId: body.connectionId,
+ webhookUrl: body.webhookUrl,
+ createAppUrl: body.createAppUrl,
+ connection: publicLinearConnection(body.connection),
+ };
+ }
+ if (method === "GET" && LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) {
+ return {
+ connections: Array.isArray(body.connections)
+ ? body.connections.map(publicLinearConnection)
+ : [],
+ };
+ }
+ if (method === "PUT" && LINEAR_CREDENTIALS_ROUTE.test(suffix)) {
+ return { connection: publicLinearConnection(body.connection) };
+ }
+ if (method === "POST" && LINEAR_AUTHORIZE_ROUTE.test(suffix)) {
+ return { authorizeUrl: body.authorizeUrl, expiresAt: body.expiresAt };
+ }
+ if (method === "DELETE" && LINEAR_CONNECTION_ROUTE.test(suffix)) {
+ return {
+ connection: publicLinearConnection(body.connection),
+ revoked: body.revoked === true,
+ };
+ }
if (method === "POST" && suffix === "/channels/slack/connections") {
return {
connection: publicChannel(body.connection),
@@ -2204,7 +2336,8 @@ async function publicSuccessResponse(
if (
suffix.includes("/webhooks") ||
suffix.includes("/event-subscriptions") ||
- suffix.startsWith("/channels/slack/setups")
+ suffix.startsWith("/channels/slack/setups") ||
+ isLinearRouteSuffix(suffix)
) {
headers.set("cache-control", "no-store");
}
@@ -2511,6 +2644,8 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if (method === "GET" && suffix === "/schedule-runs") return true;
if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix))
return true;
+ // Linear agent connections: only the contract's routes.
+ if (isLinearRouteSuffix(suffix)) return isLinearConnectionRoute(method, suffix);
// Automated Slack setup: only the contract's routes, before the /channels
// catch-all below can admit anything else under the prefix.
if (suffix.startsWith("/channels/slack/setups")) {
@@ -2637,15 +2772,17 @@ export async function handleManagedGitHubCallback(
}
/**
- * Slack's OAuth redirect for apps created by the automated setup. The exact
- * public URL is registered on every generated app, so it forwards the query
- * verbatim and never reinterprets it. The backend resolves the single-use
+ * A provider's OAuth redirect, forwarded to the backend's callback. The exact
+ * public URL is registered with the provider, so the query goes through
+ * verbatim and is never reinterpreted. The backend resolves the single-use
* state and answers with a redirect into the project's Connections tab, or
* a no-store HTML page for a malformed state; both pass through unchanged.
*/
-export async function handleManagedSlackCallback(
+async function forwardProviderCallback(
request: Request,
env: ManagedAgentsEnv,
+ upstreamPath: string,
+ provider: string,
): Promise<Response> {
if (request.method !== "GET") {
return new Response("Method not allowed", { status: 405 });
@@ -2654,11 +2791,11 @@ export async function handleManagedSlackCallback(
const base = (
env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
).replace(/\/+$/, "");
- const target = new URL(
- `${base}/v1/channels/slack/oauth/callback${requestURL.search}`,
- );
+ const target = new URL(`${base}${upstreamPath}${requestURL.search}`);
if (target.protocol !== "https:" && target.hostname !== "localhost") {
- return new Response("Slack connection is unavailable", { status: 503 });
+ return new Response(`${provider} connection is unavailable`, {
+ status: 503,
+ });
}
try {
const upstream = await fetch(target, { redirect: "manual" });
@@ -2685,13 +2822,43 @@ export async function handleManagedSlackCallback(
headers,
});
} catch {
- return new Response("Slack connection is temporarily unavailable", {
+ return new Response(`${provider} connection is temporarily unavailable`, {
status: 502,
headers: { "content-type": "text/plain; charset=utf-8" },
});
}
}
+/** Slack's OAuth redirect for apps created by the automated setup. */
+export async function handleManagedSlackCallback(
+ request: Request,
+ env: ManagedAgentsEnv,
+): Promise<Response> {
+ return forwardProviderCallback(
+ request,
+ env,
+ "/v1/channels/slack/oauth/callback",
+ "Slack",
+ );
+}
+
+/**
+ * Linear's OAuth redirect for a project's Linear agent connection. The
+ * backend builds this URL into every authorize link (its default is the
+ * Slack callback's sibling, `/api/managed-agents/linear/callback`).
+ */
+export async function handleManagedLinearCallback(
+ request: Request,
+ env: ManagedAgentsEnv,
+): Promise<Response> {
+ return forwardProviderCallback(
+ request,
+ env,
+ "/v1/linear/oauth/callback",
+ "Linear",
+ );
+}
+
function channelConnectionPage(
action: string,
status: number,