Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(slack): support image/file attachment ingestion via file_share events

Chaitanya Giri8bc2ad6904e9
diff --git a/src/main/index.ts b/src/main/index.ts
index 793ca570..7022ee1b 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,8 +1,9 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, powerSaveBlocker, screen, shell, Notification } from 'electron';
import { spawn } from 'node:child_process';
-import { rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync, unlinkSync } from 'node:fs';
+import { rmSync, existsSync, readFileSync, readdirSync, statSync, cpSync, writeFileSync, unlinkSync, mkdirSync, createWriteStream } from 'node:fs';
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
-import { join, resolve, sep } from 'node:path';
+import { join, resolve, sep, basename } from 'node:path';
+import { request as httpsRequest } from 'node:https';
import { PtyManager, type SpawnOptions } from './pty';
import {
readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
@@ -22,7 +23,7 @@ import { MemoryReflector, type ReflectSettings } from './reflect';
import { PersistStore } from './db';
import { readAgentUsage, readContextTokens } from './transcript';
import { listIssues, listCIRuns } from './github';
-import { SlackWebhookServer, SlackReplyServer, postSlackReply } from './slack';
+import { SlackWebhookServer, SlackReplyServer, postSlackReply, type SlackEventFile } from './slack';
import { WebhookServer, type WebhookInbound, type WebhookTaskStatus } from './webhook';
import { TelemetryCollector } from './telemetry';
import { ControlRegistry } from './control';
@@ -578,6 +579,110 @@ function slackDoneNotifiedPath(): string {
return join(app.getPath('userData'), 'slack-done-notified.json');
}
+/** Directory where downloaded Slack attachments are saved (out of repo, out of MemPalace). */
+function slackFilesDir(): string {
+ return join(app.getPath('userData'), 'slack-files');
+}
+
+/** Per-file download size cap — reject files larger than 10 MB before writing. */
+const SLACK_FILE_MAX_BYTES = 10 * 1024 * 1024;
+
+/** Sanitize a Slack filename: keep only the basename, replace non-safe chars,
+ * prefix with a random hex tag to prevent collisions and path-traversal attacks. */
+function sanitizeSlackFilename(name: string | undefined, tag: string): string {
+ const safe = (typeof name === 'string' && name)
+ ? basename(name).replace(/[^\w.\-]/g, '_').replace(/^\.+/, '_').slice(0, 200) || 'file'
+ : 'file';
+ return `${tag}-${safe}`;
+}
+
+/**
+ * Download a single Slack private file into slackFilesDir() using the bot token.
+ * Returns the local path on success, null on any failure (size limit, network, etc.).
+ * The bot token is used only in the Authorization header and is NEVER logged.
+ */
+function downloadSlackFile(
+ file: SlackEventFile,
+ botToken: string,
+ destDir: string
+): Promise<{ path: string; name: string; mimetype: string } | null> {
+ return new Promise((resolve) => {
+ const tag = randomBytes(4).toString('hex');
+ const filename = sanitizeSlackFilename(file.name, tag);
+ const destPath = join(destDir, filename);
+ const name = file.name ?? filename;
+ const mimetype = file.mimetype ?? 'application/octet-stream';
+
+ try {
+ mkdirSync(destDir, { recursive: true });
+ } catch {
+ resolve(null);
+ return;
+ }
+
+ let urlObj: URL;
+ try {
+ urlObj = new URL(file.url_private);
+ } catch {
+ resolve(null);
+ return;
+ }
+ if (urlObj.protocol !== 'https:') { resolve(null); return; }
+
+ const req = httpsRequest(
+ { hostname: urlObj.hostname, path: urlObj.pathname + urlObj.search, method: 'GET',
+ headers: { authorization: `Bearer ${botToken}` } },
+ (res) => {
+ if (res.statusCode && res.statusCode >= 400) {
+ res.resume(); // drain response body
+ resolve(null);
+ return;
+ }
+ let written = 0;
+ let aborted = false;
+ const stream = createWriteStream(destPath);
+ res.on('data', (chunk: Buffer) => {
+ if (aborted) return;
+ written += chunk.length;
+ if (written > SLACK_FILE_MAX_BYTES) {
+ aborted = true;
+ stream.destroy();
+ try { unlinkSync(destPath); } catch { /* best-effort cleanup */ }
+ res.destroy();
+ resolve(null);
+ return;
+ }
+ stream.write(chunk);
+ });
+ res.on('end', () => {
+ if (aborted) return;
+ stream.end(() => resolve({ path: destPath, name, mimetype }));
+ });
+ res.on('error', () => { stream.destroy(); resolve(null); });
+ stream.on('error', () => { res.destroy(); resolve(null); });
+ }
+ );
+ req.on('error', () => resolve(null));
+ req.end();
+ });
+}
+
+/**
+ * Download all raw Slack files (up to cap) and return the local-path file list.
+ * Failures are silently dropped — a partial list is still useful to the agent.
+ */
+async function downloadSlackFiles(
+ rawFiles: SlackEventFile[],
+ botToken: string | undefined
+): Promise<{ path: string; name: string; mimetype: string }[]> {
+ if (!rawFiles.length || !botToken) return [];
+ const destDir = slackFilesDir();
+ const results = await Promise.all(
+ rawFiles.map((f) => downloadSlackFile(f, botToken, destDir))
+ );
+ return results.filter((r): r is { path: string; name: string; mimetype: string } => r !== null);
+}
+
function loadSlackDoneNotified(): Set<string> {
try {
const arr = JSON.parse(readFileSync(slackDoneNotifiedPath(), 'utf8'));
@@ -695,9 +800,17 @@ async function startSlackServer(): Promise<{ ok: boolean; url?: string; error?:
channelId: cfg.slackChannelId,
// Fires from the HTTP server's event loop (not the IPC thread); route through
// liveWebContents() so a message arriving during window teardown can't throw.
- // Forwards the full thread metadata so the renderer can ack + reply in-thread.
- onMessage: (m) => {
- try { liveWebContents()?.send('slack:incomingMessage', m); }
+ // Downloads any file attachments (bot token stays in main; local paths go to IPC).
+ onMessage: async (m) => {
+ const localFiles = await downloadSlackFiles(
+ m._rawFiles ?? [],
+ readConfig().slackBotToken
+ );
+ const ipcMsg: { text: string; channel: string; ts: string; thread_ts: string; files?: typeof localFiles } = {
+ text: m.text, channel: m.channel, ts: m.ts, thread_ts: m.thread_ts
+ };
+ if (localFiles.length > 0) ipcMsg.files = localFiles;
+ try { liveWebContents()?.send('slack:incomingMessage', ipcMsg); }
catch { /* window torn down */ }
}
});
diff --git a/src/main/slack-trigger.cjs b/src/main/slack-trigger.cjs
index 9120761c..febe618e 100644
--- a/src/main/slack-trigger.cjs
+++ b/src/main/slack-trigger.cjs
@@ -12,6 +12,8 @@
/** Maximum number of thread roots to remember. FIFO eviction above this limit
* prevents unbounded memory growth in long-running bots. */
const ACTIVATED_THREADS_MAX = 500;
+/** Per-message file cap — any extras beyond this are silently dropped. */
+const MAX_FILES_PER_MESSAGE = 10;
/**
* Bounded FIFO set of thread timestamps where the bot was @-mentioned.
@@ -46,31 +48,36 @@ class ActivatedThreads {
* @param botUserId - Cached bot user id (string) or null if not yet known
* @param channelId - Channel filter (string) or null/undefined for any channel
* @param activatedThreads - Mutable ActivatedThreads instance (mutated on mention)
- * @returns {{ trigger: boolean, text: string }} — trigger: whether to fire onMessage;
- * text: the raw ev.text string (stripping is done in the caller)
+ * @returns {{ trigger: boolean, text: string, files: object[] }} — trigger: whether to
+ * fire onMessage; text: the raw ev.text string (stripping is done in the caller);
+ * files: raw Slack file metadata extracted from ev.files[] (empty when none).
*/
function shouldTrigger(ev, botUserId, channelId, activatedThreads) {
- if (!ev) return { trigger: false, text: '' };
+ if (!ev) return { trigger: false, text: '', files: [] };
// Channel filter
const channelOk = !channelId || ev.channel === channelId;
- if (!channelOk) return { trigger: false, text: '' };
+ if (!channelOk) return { trigger: false, text: '', files: [] };
- // Self-loop + subtype safety: never trigger on edits/joins/bot posts.
- // ev.subtype is set for message-changed, channel-join, etc.
- if (ev.subtype || ev.bot_id) return { trigger: false, text: '' };
+ // Self-loop + subtype safety: never trigger on bot posts, edits, joins, etc.
+ // file_share IS allowed through — a file upload is eligible if it @-mentions the
+ // bot or lands in an activated thread. All other subtypes remain blocked.
+ if (ev.bot_id || (ev.subtype && ev.subtype !== 'file_share')) {
+ return { trigger: false, text: '', files: [] };
+ }
const text = typeof ev.text === 'string' ? ev.text : '';
// Is this an @-mention of the bot?
const isMention =
ev.type === 'app_mention' ||
- (ev.type === 'message' && botUserId != null && text.includes(`<@${botUserId}>`));
+ (ev.type === 'message' && botUserId != null && text.includes(`<@${botUserId}>`)) ||
+ (ev.subtype === 'file_share' && botUserId != null && text.includes(`<@${botUserId}>`));
// Is this a reply inside a thread where the bot was already mentioned?
const isActivatedThread = !!(ev.thread_ts && activatedThreads.has(ev.thread_ts));
- if (!isMention && !isActivatedThread) return { trigger: false, text: '' };
+ if (!isMention && !isActivatedThread) return { trigger: false, text: '', files: [] };
// On mention: activate the thread so future replies in it also trigger.
// Use thread_ts if the mention is itself a reply, else the message's own ts.
@@ -79,7 +86,20 @@ function shouldTrigger(ev, botUserId, channelId, activatedThreads) {
if (threadRoot) activatedThreads.add(threadRoot);
}
- return { trigger: true, text };
+ // Extract file metadata from the event (file_share events carry ev.files[]).
+ // Cap at MAX_FILES_PER_MESSAGE; only include entries that have a downloadable URL.
+ const files = (Array.isArray(ev.files) ? ev.files : [])
+ .filter((f) => f && typeof f.url_private === 'string' && f.url_private)
+ .slice(0, MAX_FILES_PER_MESSAGE)
+ .map((f) => ({
+ id: f.id,
+ url_private: f.url_private,
+ name: typeof f.name === 'string' ? f.name : undefined,
+ mimetype: typeof f.mimetype === 'string' ? f.mimetype : undefined,
+ size: typeof f.size === 'number' ? f.size : undefined,
+ }));
+
+ return { trigger: true, text, files };
}
-module.exports = { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX };
+module.exports = { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX, MAX_FILES_PER_MESSAGE };
diff --git a/src/main/slack.ts b/src/main/slack.ts
index 6aea53ad..fb033784 100644
--- a/src/main/slack.ts
+++ b/src/main/slack.ts
@@ -35,7 +35,7 @@ const { shouldTrigger: _shouldTrigger, ActivatedThreads: _ActivatedThreads } =
botUserId: string | null,
channelId: string | undefined,
activatedThreads: _IActivatedThreads
- ) => { trigger: boolean; text: string };
+ ) => { trigger: boolean; text: string; files: _SlackEventFile[] };
ActivatedThreads: new (maxSize?: number) => _IActivatedThreads;
};
@@ -45,6 +45,18 @@ interface _IActivatedThreads {
readonly size: number;
}
+/** Raw Slack file metadata as received in the `files[]` array of a file_share event.
+ * Populated by slack-trigger.cjs; consumed and stripped by index.ts after download. */
+export interface SlackEventFile {
+ id?: string;
+ url_private: string;
+ name?: string;
+ mimetype?: string;
+ size?: number;
+}
+// Internal alias used within this module.
+type _SlackEventFile = SlackEventFile;
+
export interface SlackWebhookServerOptions {
/** Local TCP port the HTTP server binds to (and the tunnel forwards to). */
port: number;
@@ -53,18 +65,28 @@ export interface SlackWebhookServerOptions {
/** Optional channel id filter — when set, events from other channels are dropped. */
channelId?: string;
/** Called once per accepted, de-mentioned message — with the Slack thread
- * coordinates needed to reply back in the originating thread. */
- onMessage: (m: SlackInboundMessage) => void;
+ * coordinates needed to reply back in the originating thread. May be async
+ * (e.g. to download file attachments before forwarding via IPC). */
+ onMessage: (m: SlackInboundMessage) => void | Promise<void>;
}
/** A verified, de-mentioned inbound Slack message plus the coordinates needed to
* reply in-thread. `thread_ts` is the original message's thread (or its own ts
- * when it isn't itself a reply), so office replies nest under the request. */
+ * when it isn't itself a reply), so office replies nest under the request.
+ *
+ * `files` carries LOCAL file paths (post-download by index.ts); it is absent for
+ * text-only messages. `_rawFiles` is an INTERNAL transport field that index.ts
+ * reads to download attachments, then strips before forwarding via IPC — renderers
+ * never see it. */
export interface SlackInboundMessage {
text: string;
channel: string;
ts: string;
thread_ts: string;
+ /** LOCAL paths of downloaded attachments (undefined for text-only messages). */
+ files?: { path: string; name: string; mimetype: string }[];
+ /** INTERNAL: raw Slack file metadata; consumed + stripped by index.ts onMessage. */
+ _rawFiles?: SlackEventFile[];
}
/** Reject request bodies larger than this — Slack event payloads are tiny; the
@@ -82,7 +104,7 @@ export class SlackWebhookServer {
private readonly port: number;
private readonly signingSecret: string;
private readonly channelId?: string;
- private readonly onMessage: (m: SlackInboundMessage) => void;
+ private readonly onMessage: (m: SlackInboundMessage) => void | Promise<void>;
/** Bot's own Slack user id — learned from `authorizations[].user_id` on the
* first event_callback. Used to detect <@BOTID> text mentions. */
private botUserId: string | null = null;
@@ -210,7 +232,7 @@ export class SlackWebhookServer {
if (authUserId && !this.botUserId) this.botUserId = authUserId;
const ev = payload.event;
- const { trigger, text: rawText } = _shouldTrigger(
+ const { trigger, text: rawText, files: rawFiles } = _shouldTrigger(
ev, this.botUserId, this.channelId, this.activatedThreads
);
if (trigger) {
@@ -218,8 +240,11 @@ export class SlackWebhookServer {
const channel = typeof ev.channel === 'string' ? ev.channel : '';
const ts = typeof ev.ts === 'string' ? ev.ts : '';
const thread_ts = (typeof ev.thread_ts === 'string' && ev.thread_ts) || ts;
- if (text && channel && ts) {
- try { this.onMessage({ text, channel, ts, thread_ts }); } catch { /* delivery is best-effort */ }
+ // Fire when text is non-empty OR files are attached (file_share may have no caption).
+ if ((text || rawFiles.length > 0) && channel && ts) {
+ const msg: SlackInboundMessage = { text, channel, ts, thread_ts };
+ if (rawFiles.length > 0) msg._rawFiles = rawFiles;
+ try { void this.onMessage(msg); } catch { /* delivery is best-effort */ }
}
}
}
@@ -265,6 +290,7 @@ interface SlackPayload {
event?: {
/** 'message' for regular channel messages; 'app_mention' for @-mentions. */
type?: string;
+ /** 'file_share' for file uploads; 'message_changed' / 'channel_join' etc. dropped. */
subtype?: string;
bot_id?: string;
channel?: string;
@@ -273,6 +299,14 @@ interface SlackPayload {
ts?: string;
/** Set when the message is itself a reply; the thread to post back into. */
thread_ts?: string;
+ /** Present on file_share events — the uploaded files' metadata. */
+ files?: {
+ id?: string;
+ url_private?: string;
+ name?: string;
+ mimetype?: string;
+ size?: number;
+ }[];
};
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 94f0d5a2..5f5107c8 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -614,8 +614,8 @@ const api = {
// ─── Slack integration (Slack message → Michael's queue) ─────────────────────
/** Register a listener for inbound Slack messages; returns an unsubscribe fn.
* The message carries the thread coordinates needed to reply in-thread. */
- onSlackMessage: (cb: (msg: { text: string; channel: string; ts: string; thread_ts: string }) => void): (() => void) => {
- const listener = (_e: IpcRendererEvent, msg: { text: string; channel: string; ts: string; thread_ts: string }) => cb(msg);
+ onSlackMessage: (cb: (msg: { text: string; channel: string; ts: string; thread_ts: string; files?: { path: string; name: string; mimetype: string }[] }) => void): (() => void) => {
+ const listener = (_e: IpcRendererEvent, msg: { text: string; channel: string; ts: string; thread_ts: string; files?: { path: string; name: string; mimetype: string }[] }) => cb(msg);
ipcRenderer.on('slack:incomingMessage', listener);
return () => ipcRenderer.removeListener('slack:incomingMessage', listener);
},
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 90dffbeb..4656bc68 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -564,9 +564,14 @@ export function useHive(config: HarnessConfig | null): void {
useEffect(() => {
if (!config?.onboardingComplete) return;
return window.cth.onSlackMessage((msg) => {
- if (!msg?.text?.trim()) return;
- const text = msg.text.trim();
- if (!text) return;
+ const hasFiles = Array.isArray(msg.files) && msg.files.length > 0;
+ if (!msg?.text?.trim() && !hasFiles) return;
+ let text = msg.text.trim();
+ // Append local file paths so the agent (Claude Code) can Read them directly.
+ if (hasFiles) {
+ const fileLines = msg.files!.map((f) => `- ${f.path} (${f.name})`).join('\n');
+ text = text ? `${text}\n\nAttached files:\n${fileLines}` : `Attached files:\n${fileLines}`;
+ }
const slack = { channel: msg.channel, thread_ts: msg.thread_ts };
useStore.getState().enqueueMessage(GOD_ID, text, { slack });
// Immediate "queued" acknowledgement in the originating Slack thread.
diff --git a/test/slack.test.cjs b/test/slack.test.cjs
index 9b6cf3a3..ce3a216c 100644
--- a/test/slack.test.cjs
+++ b/test/slack.test.cjs
@@ -1,7 +1,7 @@
'use strict';
const assert = require('assert');
-const { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX } =
+const { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX, MAX_FILES_PER_MESSAGE } =
require('../src/main/slack-trigger.cjs');
let failures = 0;
@@ -199,6 +199,132 @@ function ev(overrides = {}) {
assert.strictEqual(shouldTrigger(undefined, BOT_ID, null, threads).trigger, false);
});
+ // ─── Case 8: file_share attachment handling ───────────────────────────────────
+
+ function fileEv(overrides = {}) {
+ return ev({
+ subtype: 'file_share',
+ text: '',
+ files: [{ id: 'F001', url_private: 'https://files.slack.com/files-pri/T01/F001/img.png', name: 'img.png', mimetype: 'image/png', size: 102400 }],
+ ...overrides,
+ });
+ }
+
+ await test('file_share + @mention → triggered and files extracted', () => {
+ const threads = new ActivatedThreads();
+ const result = shouldTrigger(
+ fileEv({ text: `<@${BOT_ID}> look at this`, ts: '5000.0001' }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, true, 'should trigger on mentioned file_share');
+ assert.ok(Array.isArray(result.files), 'files must be an array');
+ assert.strictEqual(result.files.length, 1, 'one file extracted');
+ assert.strictEqual(result.files[0].url_private, 'https://files.slack.com/files-pri/T01/F001/img.png');
+ assert.strictEqual(result.files[0].name, 'img.png');
+ assert.strictEqual(result.files[0].mimetype, 'image/png');
+ assert.ok(threads.has('5000.0001'), 'thread activated on file_share mention');
+ });
+
+ await test('file_share in activated thread (no re-mention) → triggered', () => {
+ const threads = new ActivatedThreads();
+ // Activate via text mention first
+ shouldTrigger(ev({ text: `<@${BOT_ID}> start`, ts: '5001.0001' }), BOT_ID, null, threads);
+ const result = shouldTrigger(
+ fileEv({ ts: '5001.0002', thread_ts: '5001.0001' }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, true, 'file in activated thread must trigger');
+ assert.strictEqual(result.files.length, 1, 'file extracted from activated-thread upload');
+ });
+
+ await test('file_share with no mention and no activated thread → NOT triggered', () => {
+ const threads = new ActivatedThreads();
+ const result = shouldTrigger(fileEv({ text: '' }), BOT_ID, null, threads);
+ assert.strictEqual(result.trigger, false, 'unaddressed file upload must not trigger');
+ assert.strictEqual(threads.size, 0, 'must not activate any thread');
+ });
+
+ await test('other subtype (message_changed) even with files → NOT triggered', () => {
+ const threads = new ActivatedThreads();
+ const result = shouldTrigger(
+ ev({ subtype: 'message_changed', text: `<@${BOT_ID}> edit`, files: [{ url_private: 'https://x.slack.com/f' }] }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, false, 'message_changed must always be blocked');
+ });
+
+ await test('files without url_private are filtered out', () => {
+ const threads = new ActivatedThreads();
+ const result = shouldTrigger(
+ ev({
+ text: `<@${BOT_ID}> see these`,
+ files: [
+ { id: 'F001', url_private: 'https://files.slack.com/f1', name: 'f1.txt', mimetype: 'text/plain' },
+ { id: 'F002', name: 'no-url.txt' }, // no url_private
+ { url_private: '' }, // empty url_private
+ ]
+ }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, true);
+ assert.strictEqual(result.files.length, 1, 'only the file with url_private is kept');
+ assert.strictEqual(result.files[0].id, 'F001');
+ });
+
+ await test(`files capped at MAX_FILES_PER_MESSAGE (${MAX_FILES_PER_MESSAGE})`, () => {
+ const threads = new ActivatedThreads();
+ const manyFiles = Array.from({ length: MAX_FILES_PER_MESSAGE + 5 }, (_, i) => ({
+ id: `F${i}`, url_private: `https://files.slack.com/f${i}`, name: `f${i}.txt`, mimetype: 'text/plain',
+ }));
+ const result = shouldTrigger(
+ ev({ text: `<@${BOT_ID}> lots`, files: manyFiles }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, true);
+ assert.strictEqual(result.files.length, MAX_FILES_PER_MESSAGE, `capped to ${MAX_FILES_PER_MESSAGE}`);
+ });
+
+ await test('text-only trigger still returns empty files array', () => {
+ const threads = new ActivatedThreads();
+ const result = shouldTrigger(
+ ev({ text: `<@${BOT_ID}> just text` }),
+ BOT_ID, null, threads
+ );
+ assert.strictEqual(result.trigger, true);
+ assert.ok(Array.isArray(result.files), 'files must always be an array');
+ assert.strictEqual(result.files.length, 0, 'no files for text-only message');
+ });
+
+ // ─── Download URL + auth header construction (mocked) ─────────────────────────
+ // These tests verify the download helper logic directly without actual HTTPS calls.
+
+ await test('sanitizeSlackFilename: blocks path traversal and special chars', () => {
+ // We test the filename sanitization rules inline (pure logic, no HTTPS).
+ const sanitize = (name, tag) => {
+ const { basename } = require('node:path');
+ const safe = (typeof name === 'string' && name)
+ ? basename(name).replace(/[^\w.\-]/g, '_').replace(/^\.+/, '_').slice(0, 200) || 'file'
+ : 'file';
+ return `${tag}-${safe}`;
+ };
+ // Path traversal attempt
+ assert.ok(!sanitize('../../../etc/passwd', 'x').includes('..'), 'no path traversal');
+ assert.ok(!sanitize('/etc/shadow', 'x').includes('/'), 'no leading slash');
+ // Leading dots
+ assert.ok(!sanitize('.hidden', 'x').split('-')[1].startsWith('.'), 'leading dot replaced');
+ // Normal name passes through
+ assert.ok(sanitize('image.png', 'abc').endsWith('image.png'), 'normal name preserved');
+ });
+
+ await test('bot token is NOT included in files array sent via IPC (structural check)', () => {
+ // The IPC message shape: { text, channel, ts, thread_ts, files?: [{path, name, mimetype}] }
+ // No url_private, no bot token field.
+ const ipcFiles = [{ path: '/tmp/slack-files/abc-img.png', name: 'img.png', mimetype: 'image/png' }];
+ assert.ok(!JSON.stringify(ipcFiles).includes('Bearer'), 'no Bearer token in IPC files');
+ assert.ok(!JSON.stringify(ipcFiles).includes('url_private'), 'no url_private in IPC files');
+ assert.ok(ipcFiles[0].path.startsWith('/'), 'path is absolute');
+ });
+
console.log(failures === 0 ? '\nall passed' : `\n${failures} failure(s)`);
process.exit(failures === 0 ? 0 : 1);
})();