diff --git a/docs/bundled-plugins.md b/docs/bundled-plugins.md index 832f11b6..fe2fbc9b 100644 --- a/docs/bundled-plugins.md +++ b/docs/bundled-plugins.md @@ -199,7 +199,7 @@ A plugin that uses OAuth shows the `codemode auth` command that connects it. See | **shiftWork** | 29 | project, issue, issueView | `apiKey` (`SHIFT_LABS_API_KEY`) | | **shopify** | 10 | order, product | `shopSubdomain` (`SHOPIFY_SUBDOMAIN`), `accessToken` (`SHOPIFY_ACCESS_TOKEN`) | | **signl4** | 2 | alert | `teamSecret` (`SIGNL4_TEAM_SECRET`) | -| **slack** | 38 | message, channel, reaction, user, userGroup, file, star | `accessToken` (`SLACK_ACCESS_TOKEN`) | +| **slack** | 39 | message, channel, reaction, user, userGroup, file, star | `accessToken` (`SLACK_ACCESS_TOKEN`) | | **sms77** | 2 | sms, voice | `apiKey` (`SMS77_API_KEY`) | | **splunk** | 16 | search, alert, report, user | `baseUrl` (`SPLUNK_BASE_URL`), `authToken` (`SPLUNK_AUTH_TOKEN`) | | **spotify** | 30 | player, album, artist, playlist, track, library, myData | `accessToken` (`SPOTIFY_ACCESS_TOKEN`) | diff --git a/packages/codemode-plugins/slack/src/credentials.ts b/packages/codemode-plugins/slack/src/credentials.ts index c95af16d..eb2ad1d4 100644 --- a/packages/codemode-plugins/slack/src/credentials.ts +++ b/packages/codemode-plugins/slack/src/credentials.ts @@ -1,6 +1,9 @@ import { staticCredential } from "@shiftlabs/codemode"; -/** A bot or user token, sent as a bearer to Slack's one API origin. */ +/** + * A bot or user token, sent as a bearer to Slack's API, and to the upload + * URLs `files.getUploadURLExternal` issues on Slack's file host. + */ export const slackCredential = staticCredential({ id: "slack", auth: { kind: "bearer" }, @@ -10,6 +13,11 @@ export const slackCredential = staticCredential({ baseUrl: "https://slack.com/api/", methods: ["GET", "POST"], }, + upload: { + baseUrl: "https://files.slack.com/upload/v1/", + methods: ["POST"], + timeoutMs: 120_000, + }, }, probe: { target: "api", diff --git a/packages/codemode-plugins/slack/src/index.ts b/packages/codemode-plugins/slack/src/index.ts index fd018a86..a79ef4c6 100644 --- a/packages/codemode-plugins/slack/src/index.ts +++ b/packages/codemode-plugins/slack/src/index.ts @@ -1,10 +1,15 @@ +import { basename } from "node:path"; import { type ActionContext, answerFailed, + type CodemodePluginAPI, credentialJson, + credentialOk, type HttpMethod, - type CodemodePluginAPI, + pathWithin, } from "@shiftlabs/codemode"; +import { standardBase64 } from "../../_shared/base64.js"; +import { readLocalFile } from "../../_shared/localFile.js"; import { slackCredential } from "./credentials.js"; async function api( @@ -25,6 +30,76 @@ async function api( return data; } +/** + * A Web API call with a form body. The upload methods + * (`files.getUploadURLExternal`, `files.completeUploadExternal`) read + * their arguments from a form or the query, not from JSON. + */ +async function apiForm( + ctx: ActionContext, + path: string, + form: Record, +): Promise> { + const data = (await credentialJson(ctx, slackCredential, "slack", { + target: "api", + path, + method: "POST", + form, + })) as Record; + if (data.ok === false) throw answerFailed("slack", { code: data.error }); + return data; +} + +/** + * The most one upload carries. Slack accepts up to 1 GB, but the bytes + * are sent in one buffered request, which the credential transport + * bounds at 64 MiB. + */ +const MAX_UPLOAD_BYTES = 64 * 1024 * 1024; +const OVERSIZE = "slack: file.upload content exceeds the 64 MiB upload limit"; + +/** A user ID (`U…`, `W…`), which a file is shared to through its DM. */ +const USER_ID = /^[UW][A-Z0-9]+$/; + +/** The bytes and the name of whichever content source the caller gave. */ +async function uploadContent( + p: Record, +): Promise<{ bytes: Buffer; name?: string }> { + const given = ["contentBase64", "contentPath", "content"].filter( + (key) => p[key] !== undefined, + ); + if (given.length !== 1) + throw new Error( + "slack: file.upload takes exactly one of contentBase64, contentPath or content", + ); + let file: { bytes: Buffer; name?: string }; + if (p.contentBase64 !== undefined) { + const base64 = + typeof p.contentBase64 === "string" + ? standardBase64(p.contentBase64) + : undefined; + if (base64 === undefined) + throw new Error("slack: file.upload contentBase64 is not valid base64"); + file = { bytes: Buffer.from(base64, "base64") }; + } else if (p.contentPath !== undefined) { + const path = String(p.contentPath); + file = { + bytes: await readLocalFile(path, { + subject: "slack: file.upload contentPath", + maxBytes: MAX_UPLOAD_BYTES, + oversize: OVERSIZE, + }), + name: basename(path), + }; + } else { + file = { bytes: Buffer.from(String(p.content), "utf8") }; + } + if (file.bytes.length === 0) + throw new Error("slack: file.upload content is empty"); + if (file.bytes.length > MAX_UPLOAD_BYTES) throw new Error(OVERSIZE); + return file; +} + export default function slack(rl: CodemodePluginAPI) { rl.setName("slack"); rl.setVersion("0.1.0"); @@ -621,6 +696,97 @@ export default function slack(rl: CodemodePluginAPI) { // ── File ──────────────────────────────────────────── + rl.registerAction("file.upload", { + access: "write", + description: + "Upload a file and optionally share it to a channel, a DM or a thread. Give exactly one of contentBase64, contentPath (a file on the codemode host) or content (UTF-8 text). `channel` takes a conversation ID, or a user ID to share in a DM with that user (needs the im:write scope). Without `channel` the file stays private to the uploader. Up to 64 MiB. Returns the uploaded files ({ id, title }).", + inputSchema: { + channel: { + type: "string", + required: false, + description: + "Conversation ID (C…, G…, D…) or user ID (U…, W…) to share in a DM", + }, + filename: { + type: "string", + required: false, + description: + "File name, with extension; defaults to contentPath's name, else 'file'", + }, + title: { type: "string", required: false }, + contentBase64: { type: "string", required: false }, + contentPath: { type: "string", required: false }, + content: { type: "string", required: false }, + initialComment: { + type: "string", + required: false, + description: "Message text posted with the file", + }, + threadTs: { + type: "string", + required: false, + description: "Share as a reply in this thread (needs channel)", + }, + altText: { + type: "string", + required: false, + description: "Description of an image, for screen readers", + }, + snippetType: { + type: "string", + required: false, + description: "Syntax type of a snippet, e.g. python or javascript", + }, + }, + async execute(input, ctx) { + const p = (input ?? {}) as Record; + if (p.threadTs !== undefined && p.channel === undefined) + throw new Error("slack: file.upload threadTs needs a channel"); + const file = await uploadContent(p); + const filename = String(p.filename ?? file.name ?? "file"); + + let channel = p.channel === undefined ? undefined : String(p.channel); + if (channel !== undefined && USER_ID.test(channel)) { + const opened = (await api(ctx, "POST", "conversations.open", { + users: channel, + })) as { channel?: { id?: unknown } }; + if (typeof opened.channel?.id !== "string") + throw new Error("slack: conversations.open returned no channel"); + channel = opened.channel.id; + } + + const ticket = await apiForm(ctx, "files.getUploadURLExternal", { + filename, + length: file.bytes.length, + alt_text: p.altText, + snippet_type: p.snippetType, + }); + if ( + typeof ticket.upload_url !== "string" || + typeof ticket.file_id !== "string" + ) + throw new Error("slack: files.getUploadURLExternal returned no upload"); + + await credentialOk(ctx, slackCredential, "slack", { + target: "upload", + path: pathWithin(ctx, slackCredential, "upload", ticket.upload_url), + method: "POST", + headers: { "Content-Type": "application/octet-stream" }, + body: new Uint8Array(file.bytes), + }); + + const done = await apiForm(ctx, "files.completeUploadExternal", { + files: JSON.stringify([ + { id: ticket.file_id, title: p.title ?? filename }, + ]), + channel_id: channel, + initial_comment: p.initialComment, + thread_ts: p.threadTs, + }); + return done.files; + }, + }); + rl.registerAction("file.get", { access: "read", description: "Get file info", diff --git a/packages/codemode/src/tests/slack-plugin.test.ts b/packages/codemode/src/tests/slack-plugin.test.ts new file mode 100644 index 00000000..1f1a31e1 --- /dev/null +++ b/packages/codemode/src/tests/slack-plugin.test.ts @@ -0,0 +1,198 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, it } from "node:test"; +import slack from "../../../codemode-plugins/slack/src/index.js"; +import { createPluginAPI } from "../plugin/api.js"; +import type { ActionContext } from "../plugin/types.js"; +import { getAction, stubFetch } from "./helpers/plugin.js"; + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +const UPLOAD_URL = "https://files.slack.com/upload/v1/CwABAAAAXAoAAZnoN2Iv"; + +function upload() { + const { api, resolve } = createPluginAPI("slack"); + slack(api); + return getAction(resolve(), "file.upload"); +} + +const ctx: ActionContext = { + connection: { + name: "slack", + plugin: "slack", + config: { accessToken: "xoxb-secret" }, + }, + log: { info() {}, warn() {}, error() {} }, + async updateConnection() {}, +}; + +interface Seen { + url: string; + method: string; + auth: string | null; + type: string | null; + body: string; +} + +/** Slack's three upload steps, answered in order, every request recorded. */ +function stubSlack(seen: Seen[]) { + stubFetch(async (url, init) => { + const headers = new Headers(init?.headers); + const body = init?.body; + seen.push({ + url: String(url), + method: init?.method ?? "GET", + auth: headers.get("authorization"), + type: headers.get("content-type"), + body: + body === undefined || body === null + ? "" + : typeof body === "string" + ? body + : Buffer.from(body as Uint8Array).toString("utf8"), + }); + const json = (value: unknown) => + new Response(JSON.stringify(value), { + headers: { "content-type": "application/json" }, + }); + const path = new URL(String(url)).pathname; + if (path === "/api/conversations.open") + return json({ ok: true, channel: { id: "D42" } }); + if (path === "/api/files.getUploadURLExternal") + return json({ ok: true, upload_url: UPLOAD_URL, file_id: "F1" }); + if (path.startsWith("/upload/v1/")) + return new Response("OK - 5", { + headers: { "content-type": "text/plain" }, + }); + if (path === "/api/files.completeUploadExternal") + return json({ ok: true, files: [{ id: "F1", title: "notes.txt" }] }); + return new Response("unexpected", { status: 404 }); + }); +} + +describe("slack file.upload", () => { + it("uploads text in Slack's three steps and shares it to the channel", async () => { + const seen: Seen[] = []; + stubSlack(seen); + const files = await upload().execute( + { + channel: "C123", + filename: "notes.txt", + content: "hello", + initialComment: "see attached", + threadTs: "1700000000.000100", + }, + ctx, + ); + assert.deepEqual(files, [{ id: "F1", title: "notes.txt" }]); + assert.equal(seen.length, 3); + + const [ticket, bytes, done] = seen; + assert.equal( + ticket.url, + "https://slack.com/api/files.getUploadURLExternal", + ); + assert.equal(ticket.auth, "Bearer xoxb-secret"); + assert.match(ticket.type ?? "", /application\/x-www-form-urlencoded/); + assert.deepEqual(Object.fromEntries(new URLSearchParams(ticket.body)), { + filename: "notes.txt", + length: "5", + }); + + assert.equal(bytes.url, UPLOAD_URL); + assert.equal(bytes.method, "POST"); + assert.equal(bytes.body, "hello"); + + assert.equal( + done.url, + "https://slack.com/api/files.completeUploadExternal", + ); + const form = Object.fromEntries(new URLSearchParams(done.body)); + assert.deepEqual(JSON.parse(form.files), [ + { id: "F1", title: "notes.txt" }, + ]); + assert.equal(form.channel_id, "C123"); + assert.equal(form.initial_comment, "see attached"); + assert.equal(form.thread_ts, "1700000000.000100"); + }); + + it("opens the DM when the channel is a user ID", async () => { + const seen: Seen[] = []; + stubSlack(seen); + await upload().execute( + { + channel: "U0ABC", + contentBase64: Buffer.from("hello").toString("base64"), + }, + ctx, + ); + assert.equal(seen[0].url, "https://slack.com/api/conversations.open"); + assert.deepEqual(JSON.parse(seen[0].body), { users: "U0ABC" }); + const form = Object.fromEntries(new URLSearchParams(seen[3].body)); + assert.equal(form.channel_id, "D42"); + assert.deepEqual(JSON.parse(form.files), [{ id: "F1", title: "file" }]); + }); + + it("names a local file for its path", async () => { + const dir = await mkdtemp(join(tmpdir(), "slack-upload-")); + try { + const path = join(dir, "report.csv"); + await writeFile(path, "a,b\n1,2\n"); + const seen: Seen[] = []; + stubSlack(seen); + await upload().execute({ contentPath: path }, ctx); + const ticket = Object.fromEntries(new URLSearchParams(seen[0].body)); + assert.deepEqual(ticket, { filename: "report.csv", length: "8" }); + assert.equal(seen[1].body, "a,b\n1,2\n"); + const done = Object.fromEntries(new URLSearchParams(seen[2].body)); + assert.equal(done.channel_id, undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); + + it("refuses an upload URL off Slack's file host before sending the bytes", async () => { + const seen: string[] = []; + stubFetch(async (url) => { + seen.push(String(url)); + return new Response( + JSON.stringify({ + ok: true, + upload_url: "https://evil.example.com/upload/v1/x", + file_id: "F1", + }), + { headers: { "content-type": "application/json" } }, + ); + }); + await assert.rejects( + upload().execute({ channel: "C1", content: "hello" }, ctx), + ); + assert.deepEqual(seen, [ + "https://slack.com/api/files.getUploadURLExternal", + ]); + }); + + it("refuses ambiguous or missing content before any request", async () => { + stubFetch(async () => { + throw new Error("no request expected"); + }); + await assert.rejects( + upload().execute({ content: "a", contentBase64: "YQ==" }, ctx), + /exactly one of/, + ); + await assert.rejects(upload().execute({}, ctx), /exactly one of/); + await assert.rejects( + upload().execute({ contentBase64: "not base64!" }, ctx), + /not valid base64/, + ); + await assert.rejects( + upload().execute({ content: "a", threadTs: "1.2" }, ctx), + /needs a channel/, + ); + }); +});