@essentialai/cogent-bridge
Version:
Cogent Bridge — cross-agent comms for Claude Code, OpenAI Codex and Slack. Codex users: install with `curl -fsSL https://cogent.tools/install.sh | sh`, then start with `cogent-codex` for real-time peer wake.
227 lines • 11.2 kB
JavaScript
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { BridgeError, BridgeErrorCode } from "../errors.js";
/**
* COG-94 — Slack file attachments, the bridge side.
*
* Operator decisions (2026-11-03): files up to 1 GB; Slack is the store of record; a copy the agent
* fetches is kept 7 days ON THE AGENT'S MACHINE, then deleted; our servers stream and keep nothing.
* The agent never holds a Slack token: the file endpoint on our side (FREE adapter / Business
* control plane) checks this agent's relay Bearer against the channel, then streams from Slack.
*
* Wire contract (both editions):
* GET /api/slack/files/:sessionId/:fileId → bytes; X-Cogent-File-Name (URI-encoded), Content-Type
* POST /api/slack/files/:sessionId ← bytes; X-Cogent-File-Name, Content-Length,
* X-Cogent-From-Peer → 201 {fileId,name,size,mimeType,url}
*/
/** Slack's per-file maximum, "1 GB". Decimal on purpose: never larger than Slack's own limit. */
export const MAX_FILE_BYTES = 1_000_000_000;
/** How long a fetched copy stays on this machine. */
export const FILE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
/** A download that receives nothing for this long is aborted (a stalled 1 GB stream must not hang the tool). */
const IDLE_TIMEOUT_MS = 60_000;
/** Upload ceiling: 1 GB on a slow uplink still fits; a dead connection does not hang forever. */
const UPLOAD_TIMEOUT_MS = 60 * 60 * 1000;
/** Relative reference the Slack side puts in a message's `attachments[].url`. */
const FILE_REF_RE = /^\/api\/slack\/files\/([A-Za-z0-9-]+)\/([A-Za-z0-9]+)$/;
export function isSlackFileRef(url) {
if (!url)
return false;
try {
return FILE_REF_RE.test(new URL(url, "http://x").pathname) && (url.startsWith("/") || /^https?:\/\//.test(url));
}
catch {
return false;
}
}
/** Keep a received file name usable and inside its directory: no separators, no control chars. */
export function safeFileName(name) {
const base = path.basename(String(name ?? "")).replace(/[^\p{L}\p{N}_.\-() ]+/gu, "_").replace(/^\.+/, "").trim();
return (base || "file").slice(0, 200);
}
export function filesRoot(stateDir) {
return path.join(stateDir, "files");
}
async function errorFrom(resp, what) {
let body = {};
try {
body = (await resp.json());
}
catch {
/* non-JSON (proxy page) — fall through to the status */
}
const code = body.code && body.code in BridgeErrorCode ? body.code : BridgeErrorCode.STARTUP_FAILED;
return new BridgeError(code, `${what} failed: HTTP ${resp.status}${body.message ? ` — ${body.message}` : ""}`, body.suggestion);
}
/** Delete fetched copies older than the retention window; returns how many files were removed. */
export async function cleanupOldFiles(root, now = Date.now(), retentionMs = FILE_RETENTION_MS) {
let removed = 0;
let channels;
try {
channels = await fsp.readdir(root, { withFileTypes: true });
}
catch {
return 0; // nothing fetched yet
}
for (const ch of channels) {
if (!ch.isDirectory())
continue;
const dir = path.join(root, ch.name);
for (const f of await fsp.readdir(dir, { withFileTypes: true }).catch(() => [])) {
if (!f.isFile())
continue;
const p = path.join(dir, f.name);
const st = await fsp.stat(p).catch(() => null);
if (st && now - st.mtimeMs > retentionMs) {
await fsp.rm(p, { force: true });
removed++;
}
}
await fsp.rmdir(dir).catch(() => { }); // only succeeds when empty
}
return removed;
}
/** How often a running bridge re-sweeps: the 7-day promise must hold for a bridge that runs for weeks. */
export const FILE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
/**
* Enforce the 7-day retention WITHOUT waiting for another fetch: sweep once now, then every
* `intervalMs` while the process lives. The timer is unref'd (it never keeps a bridge alive) and a
* failed sweep is ignored (the next one retries). Returns a stop function.
*/
export function startFileSweeper(root, intervalMs = FILE_SWEEP_INTERVAL_MS) {
const sweep = () => void cleanupOldFiles(root).catch(() => { });
sweep();
const timer = setInterval(sweep, intervalMs);
timer.unref();
return () => clearInterval(timer);
}
/** Download one file reference into `<root>/<sessionId>/<fileId>-<name>`. */
export async function downloadSlackFile(http, sessionId, url, root, maxBytes = MAX_FILE_BYTES) {
const ref = new URL(url, http.endpoint);
const m = FILE_REF_RE.exec(ref.pathname);
if (!m) {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Not a Slack file reference: ${url}`, "Pass the url from a message's 📎 Attachments block.");
}
const [, refSession, fileId] = m;
if (refSession !== sessionId) {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, "That file belongs to a different channel than the one this agent is in");
}
const ac = new AbortController();
let idle = setTimeout(() => ac.abort(), IDLE_TIMEOUT_MS);
const resp = await http.streamRequest(ref.toString(), { method: "GET", signal: ac.signal }).catch((e) => {
clearTimeout(idle);
throw e;
});
if (!resp.ok || !resp.body) {
clearTimeout(idle);
throw await errorFrom(resp, "File download");
}
const declared = Number(resp.headers.get("content-length") ?? NaN);
if (Number.isFinite(declared) && declared > maxBytes) {
clearTimeout(idle);
ac.abort();
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `File is ${declared} bytes; the limit is ${maxBytes} (1 GB)`);
}
const name = safeFileName(decodeURIComponent(resp.headers.get("x-cogent-file-name") ?? fileId));
const dir = path.join(root, sessionId);
await fsp.mkdir(dir, { recursive: true, mode: 0o700 });
const dest = path.join(dir, `${fileId}-${name}`);
const part = `${dest}.part`;
let size = 0;
const counter = new Transform({
transform(chunk, _enc, cb) {
size += chunk.length;
clearTimeout(idle);
idle = setTimeout(() => ac.abort(), IDLE_TIMEOUT_MS);
if (size > maxBytes)
return cb(new BridgeError(BridgeErrorCode.INVALID_INPUT, `File exceeds the ${maxBytes}-byte (1 GB) limit`));
cb(null, chunk);
},
});
try {
await pipeline(Readable.fromWeb(resp.body), counter, fs.createWriteStream(part, { mode: 0o600 }));
await fsp.rename(part, dest);
}
catch (e) {
await fsp.rm(part, { force: true });
if (ac.signal.aborted && !(e instanceof BridgeError)) {
throw new BridgeError(BridgeErrorCode.NETWORK_TIMEOUT, `File download stalled: nothing received for ${IDLE_TIMEOUT_MS / 1000}s`);
}
throw e;
}
finally {
clearTimeout(idle);
}
return { path: dest, name, size, mimeType: resp.headers.get("content-type") ?? undefined };
}
/**
* Refuse files an agent must never post into Slack, judged on the REAL path (symlinks resolved):
* anything under a hidden directory or itself hidden (`.ssh/`, `.aws/`, `.env`, `.git/`…), and
* anything inside Cogent's own state directory (its credentials) except THIS channel's fetched
* copies (`files/<sessionId>/` — another channel's copies would leak across channels).
* The tool is reachable from text other people write (a Slack message can ask an agent to "attach
* X"), so this is the line between attaching work and posting secrets into a channel.
*/
export async function assertAttachable(filePath, stateDir, sessionId) {
const real = await fsp.realpath(path.resolve(filePath)).catch(() => {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Not a file: ${path.resolve(filePath)}`);
});
const stateReal = await fsp.realpath(stateDir).catch(() => path.resolve(stateDir));
const inside = (root) => real === root || real.startsWith(root + path.sep);
const ownCopies = path.join(filesRoot(stateReal), sessionId);
if (inside(stateReal) && !inside(ownCopies)) {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Refusing to attach ${real}: it is inside Cogent's state directory (credentials)`);
}
if (!inside(ownCopies) && real.split(path.sep).some((part) => part.startsWith("."))) {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Refusing to attach ${real}: hidden files and folders (.ssh, .env, .aws, .git …) are never posted into Slack`, "Copy what you mean to share into a normal (non-hidden) file and attach that.");
}
return real;
}
/** Upload one local file to the Slack channel mapped to this channel; returns its attachment reference. */
export async function uploadSlackFile(http, sessionId, filePath, fromPeerId, stateDir, maxBytes = MAX_FILE_BYTES) {
const abs = await assertAttachable(filePath, stateDir, sessionId);
// Open ONCE (O_NOFOLLOW: the checked real path has no symlink left to swap in), verify through the
// handle, and stream from the same handle — the path is never re-resolved after the check.
const fh = await fsp.open(abs, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW).catch(() => {
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Not a file: ${abs}`);
});
const st = await fh.stat();
const checked = await fsp.stat(abs).catch(() => null);
if (!st.isFile() || !checked || checked.dev !== st.dev || checked.ino !== st.ino) {
await fh.close();
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `Not a file (or it changed while being checked): ${abs}`);
}
if (st.size > maxBytes) {
await fh.close();
throw new BridgeError(BridgeErrorCode.INVALID_INPUT, `${path.basename(abs)} is ${st.size} bytes; the limit is ${maxBytes} (1 GB)`);
}
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), UPLOAD_TIMEOUT_MS);
try {
const resp = await http.streamRequest(`/api/slack/files/${sessionId}`, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"Content-Length": String(st.size),
"X-Cogent-File-Name": encodeURIComponent(path.basename(abs)),
"X-Cogent-From-Peer": encodeURIComponent(fromPeerId),
},
body: Readable.toWeb(fh.createReadStream()),
// Node's fetch requires this for a streamed request body.
duplex: "half",
signal: ac.signal,
});
if (resp.status !== 201)
throw await errorFrom(resp, `Upload of ${path.basename(abs)}`);
const out = (await resp.json());
return { url: out.url, name: out.name, size: out.size, ...(out.mimeType ? { mimeType: out.mimeType } : {}) };
}
finally {
clearTimeout(timer);
await fh.close().catch(() => { });
}
}
//# sourceMappingURL=slack-files.js.map