The Open Framework for Building Agents
fix(eve): linear - attach authenticated inbound images (#1131)
Andrew Barbafecdaf33acad
diff --git a/.changeset/curly-lions-attach.md b/.changeset/curly-lions-attach.mdnew file mode 100644index 000000000..c077f9a96--- /dev/null+++ b/.changeset/curly-lions-attach.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Attach authenticated `uploads.linear.app` images from inbound Linear Agent Session markdown as multimodal file parts while preserving the text fallback for untrusted, failed, or non-image URLs.diff --git a/docs/channels/linear.mdx b/docs/channels/linear.mdxindex cd2b58a8d..0e7fe6841 100644--- a/docs/channels/linear.mdx+++ b/docs/channels/linear.mdx@@ -88,7 +88,7 @@ Start a session without an inbound webhook with `receive(linear, { target })`. S### Attachments-Inbound file attachments are not supported on this channel today.+Markdown images hosted at `https://uploads.linear.app` in Agent Session prompts are fetched with the resolved Linear access token and included as image file parts. eve sends the bearer token only to that exact HTTPS origin; images from other hosts remain markdown text. If a Linear upload fails or returns non-image content, eve preserves its markdown reference and continues the text turn. Other inbound file attachments are not supported on this channel today.### API handlediff --git a/packages/eve/src/public/channels/linear/inbound-images.test.ts b/packages/eve/src/public/channels/linear/inbound-images.test.tsnew file mode 100644index 000000000..e3eb77bb9--- /dev/null+++ b/packages/eve/src/public/channels/linear/inbound-images.test.ts@@ -0,0 +1,150 @@+import type { FilePart, TextPart } from "ai";+import { describe, expect, it, vi } from "vitest";++import {+ attachLinearInboundImages,+ extractLinearUploadImageReferences,+} from "#public/channels/linear/inbound-images.js";++describe("extractLinearUploadImageReferences", () => {+ it("extracts trusted Linear markdown images and ignores ordinary image hosts", () => {+ const markdown = [+ 'First .',+ "Second .",+ "External .",+ ].join("\n");++ expect(+ extractLinearUploadImageReferences(markdown).map((reference) => ({+ altText: reference.altText,+ url: reference.url.href,+ })),+ ).toEqual([+ {+ altText: "screenshot",+ url: "https://uploads.linear.app/acme/one/image.png?signature=one",+ },+ {+ altText: "diagram",+ url: "https://uploads.linear.app/acme/two/diagram.jpg?signature=two",+ },+ ]);+ });+});++describe("attachLinearInboundImages", () => {+ it("fetches image bytes with the resolved credential and response media type", async () => {+ const token = vi.fn().mockResolvedValue("linear-token");+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(new Uint8Array([1, 2, 3, 4]), {+ headers: { "content-type": "Image/PNG; charset=binary" },+ }),+ );++ const content = await attachLinearInboundImages({+ content:+ "Review .",+ credentials: { accessToken: token },+ fetch: fetchMock,+ });++ expect(token).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe("https://uploads.linear.app/acme/one/image.png?signature=secret");+ expect(init).toMatchObject({ credentials: "omit", redirect: "manual" });+ expect(new Headers(init.headers).get("accept")).toBe("image/*");+ expect(new Headers(init.headers).get("authorization")).toBe("Bearer linear-token");++ expect(content).toHaveLength(2);+ expect(content[0]).toEqual({ text: "Review screenshot.", type: "text" });+ const file = content[1] as FilePart;+ expect(file.type).toBe("file");+ expect(file.mediaType).toBe("image/png");+ expect(Buffer.isBuffer(file.data)).toBe(true);+ expect(file.data).toEqual(Buffer.from([1, 2, 3, 4]));+ });++ it("retains surrounding and fallback markdown in mixed content", async () => {+ const fetchMock = vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {+ if (String(url).includes("/attached.png")) {+ return new Response(new Uint8Array([7, 8]), {+ headers: { "content-type": "image/png" },+ });+ }+ return new Response("not an image", {+ headers: { "content-type": "text/plain" },+ });+ });+ const nonImage = "";+ const hostile = "";++ const content = await attachLinearInboundImages({+ content:+ `Before  ` ++ `between ${nonImage} after ${hostile}.`,+ credentials: { accessToken: "linear-token" },+ fetch: fetchMock,+ });++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(content).toHaveLength(2);+ expect((content[0] as TextPart).text).toBe(+ `Before attached between ${nonImage} after ${hostile}.`,+ );+ expect((content[1] as FilePart).data).toEqual(Buffer.from([7, 8]));+ });++ it("preserves markdown when trusted downloads fail, redirect, or are not images", async () => {+ const markdown = [+ "",+ "",+ "",+ ].join(" ");+ const fetchMock = vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {+ const href = String(url);+ if (href.includes("/failed.png")) throw new Error("network failure");+ if (href.includes("/redirect.png")) {+ return new Response(null, {+ headers: { location: "https://attacker.example/image.png" },+ status: 302,+ });+ }+ return new Response("hello", { headers: { "content-type": "text/plain" } });+ });++ await expect(+ attachLinearInboundImages({+ content: markdown,+ credentials: { accessToken: "linear-token" },+ fetch: fetchMock,+ }),+ ).resolves.toBe(markdown);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ for (const [, init] of fetchMock.mock.calls) {+ expect(init?.redirect).toBe("manual");+ }+ });++ it("never resolves or forwards credentials for hostile lookalike URLs", async () => {+ const markdown = [+ "",+ "",+ "",+ "",+ "",+ ].join(" ");+ const token = vi.fn().mockResolvedValue("linear-token");+ const fetchMock = vi.fn();++ await expect(+ attachLinearInboundImages({+ content: markdown,+ credentials: { accessToken: token },+ fetch: fetchMock,+ }),+ ).resolves.toBe(markdown);+ expect(token).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/public/channels/linear/inbound-images.ts b/packages/eve/src/public/channels/linear/inbound-images.tsnew file mode 100644index 000000000..45efbd48e--- /dev/null+++ b/packages/eve/src/public/channels/linear/inbound-images.ts@@ -0,0 +1,145 @@+import type { FilePart, TextPart, UserContent } from "ai";++import type { LinearFetch } from "#public/channels/linear/api.js";+import {+ resolveLinearAccessToken,+ type LinearChannelCredentials,+} from "#public/channels/linear/auth.js";++const LINEAR_UPLOAD_ORIGIN = "https://uploads.linear.app";+const MARKDOWN_IMAGE_PATTERN =+ /!\[([^\]\r\n]*)\]\(\s*(?:<([^>\r\n]+)>|([^\s)\r\n]+))(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^)\r\n]*\)))?\s*\)/gu;++/** One trusted Linear upload referenced by markdown image syntax. */+export interface LinearUploadImageReference {+ readonly altText: string;+ readonly end: number;+ readonly start: number;+ readonly url: URL;+}++/** Extracts markdown image references that target Linear's exact upload origin. */+export function extractLinearUploadImageReferences(+ markdown: string,+): readonly LinearUploadImageReference[] {+ const references: LinearUploadImageReference[] = [];+ for (const match of markdown.matchAll(MARKDOWN_IMAGE_PATTERN)) {+ const href = match[2] ?? match[3];+ const start = match.index;+ if (href === undefined || start === undefined) continue;++ const url = parseLinearUploadUrl(href);+ if (url === null) continue;++ references.push({+ altText: match[1] ?? "",+ end: start + match[0].length,+ start,+ url,+ });+ }+ return references;+}++/** Adds authenticated Linear upload images to otherwise text-only inbound content. */+export async function attachLinearInboundImages(input: {+ readonly content: UserContent;+ readonly credentials?: LinearChannelCredentials;+ readonly fetch?: LinearFetch;+}): Promise<UserContent> {+ if (typeof input.content !== "string") return input.content;++ const references = extractLinearUploadImageReferences(input.content);+ if (references.length === 0) return input.content;++ let token: string;+ try {+ token = await resolveLinearAccessToken(input.credentials?.accessToken);+ } catch {+ return input.content;+ }++ const fetchImage = input.fetch ?? fetch;+ const files = await Promise.all(+ references.map((reference) => fetchLinearUploadImage(reference.url, token, fetchImage)),+ );+ if (files.every((file) => file === null)) return input.content;++ return buildLinearImageContent(input.content, references, files);+}++function parseLinearUploadUrl(href: string): URL | null {+ let url: URL;+ try {+ url = new URL(href);+ } catch {+ return null;+ }+ if (url.origin !== LINEAR_UPLOAD_ORIGIN || url.username !== "" || url.password !== "") {+ return null;+ }+ return url;+}++async function fetchLinearUploadImage(+ url: URL,+ token: string,+ fetchImage: LinearFetch,+): Promise<FilePart | null> {+ if (parseLinearUploadUrl(url.href) === null) return null;++ try {+ const response = await fetchImage(url.href, {+ credentials: "omit",+ headers: {+ accept: "image/*",+ authorization: `Bearer ${token}`,+ },+ redirect: "manual",+ });+ if (!response.ok) return null;++ const mediaType = readImageMediaType(response.headers.get("content-type"));+ if (mediaType === null) return null;++ return {+ data: Buffer.from(await response.arrayBuffer()),+ mediaType,+ type: "file",+ };+ } catch {+ return null;+ }+}++function readImageMediaType(contentType: string | null): string | null {+ const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();+ return mediaType?.startsWith("image/") === true && mediaType.length > "image/".length+ ? mediaType+ : null;+}++function buildLinearImageContent(+ markdown: string,+ references: readonly LinearUploadImageReference[],+ files: readonly (FilePart | null)[],+): UserContent {+ let cursor = 0;+ let text = "";+ const attached: FilePart[] = [];++ for (const [index, reference] of references.entries()) {+ const file = files[index];+ if (file === null || file === undefined) continue;++ text += markdown.slice(cursor, reference.start);+ text += reference.altText;+ cursor = reference.end;+ attached.push(file);+ }+ text += markdown.slice(cursor);++ if (text.trim().length === 0) return attached;+ const textPart: TextPart = { text, type: "text" };+ return [textPart, ...attached];+}diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 34b7865bf..d91204e49 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -204,6 +204,44 @@ describe("linearChannel inbound Agent Session events", () => {expect(payload.message).toBe("approve");});+ it("attaches authenticated Linear upload images to prompted messages", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(new Uint8Array([1, 2, 3]), {+ headers: { "content-type": "image/webp" },+ }),+ );+ const channel = linearChannel({+ api: { fetch: fetchMock },+ credentials: { accessToken: "linear-token", webhookSecret: SECRET },+ });+ const { send } = await firePost(+ channel,+ signedRequest(+ sessionPayload({+ action: "prompted",+ agentActivity: {+ content: {+ body: "Inspect .",+ type: "prompt",+ },+ id: "activity_prompt",+ user: { id: "user_1" },+ userId: "user_1",+ },+ }),+ ),+ );++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(+ "Bearer linear-token",+ );+ const [payload] = send.mock.calls[0]!;+ expect(payload.message[0]).toEqual({ text: "Inspect screenshot.", type: "text" });+ expect(payload.message[1]).toMatchObject({ mediaType: "image/webp", type: "file" });+ expect(payload.message[1].data).toEqual(Buffer.from([1, 2, 3]));+ });+it("acks generic data webhooks without dispatch when no hook is configured", async () => {const body = JSON.stringify({action: "create",diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.tsindex 4539843a8..f0399b8ba 100644--- a/packages/eve/src/public/channels/linear/linearChannel.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.ts@@ -14,6 +14,7 @@ import {import type { LinearChannelCredentials } from "#public/channels/linear/auth.js";import { LINEAR_CHANNEL_DEFAULT_ROUTE } from "#public/channels/linear/constants.js";import { createDefaultEvents, defaultOnAgentSession } from "#public/channels/linear/defaults.js";+import { attachLinearInboundImages } from "#public/channels/linear/inbound-images.js";import {formatLinearContextBlock,linearContinuationToken,@@ -342,6 +343,12 @@ async function dispatchAgentSession(input: {const result = await input.onAgentSession(context, event);if (result === null) return;+ const message = await attachLinearInboundImages({+ content: messageFromLinearAgentSessionEvent(event),+ credentials: input.config.credentials,+ fetch: input.config.api?.fetch,+ });+await input.send({context: [@@ -349,7 +356,7 @@ async function dispatchAgentSession(input: {...event.previousComments,...(result.context ?? []),],- message: messageFromLinearAgentSessionEvent(event),+ message,},{auth: result.auth,