Compare commits

..

5 Commits

Author SHA1 Message Date
Kenneth Lien
1636fedbd4 Sanitize user-controlled filenames and download path components
- safeName() strips <>[]\r\n; from file_name/title before they hit the
  <channel> notification — delimiter chars would let an uploader break
  out of the tag or forge meta entries
- download_attachment strips ext/uniqueId to alphanumeric before join()
  — defense-in-depth against path traversal (file_unique_id is
  Telegram-controlled so this is belt-and-braces)
2026-03-20 11:56:57 -07:00
Kenneth Lien
a9bc23da6f telegram: handle all inbound file types + download_attachment tool 2026-03-20 11:51:42 -07:00
Tobin South
90accf6fd2 add(plugin): mcp-server-dev — skills for building MCP servers (#731) 2026-03-20 17:51:32 +00:00
Kenneth Lien
562a27feec Merge pull request #811 from anthropics/kenneth/chmod-env-files
Lock telegram/discord .env files to owner (chmod 600)
2026-03-20 10:48:05 -07:00
Kenneth Lien
8140fbad22 Lock telegram/discord .env files to owner (chmod 600)
The bot token is a credential. Tighten perms on load so hand-written
or pre-existing .env files get locked down, and update the configure
skill to chmod after writing. No-op on Windows.
2026-03-20 10:37:13 -07:00
4 changed files with 131 additions and 5 deletions

View File

@@ -25,7 +25,7 @@ import {
type Attachment,
} from 'discord.js'
import { randomBytes } from 'crypto'
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync } from 'fs'
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync, chmodSync } from 'fs'
import { homedir } from 'os'
import { join, sep } from 'path'
@@ -37,6 +37,8 @@ const ENV_FILE = join(STATE_DIR, '.env')
// Load ~/.claude/channels/discord/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
if (m && process.env[m[1]] === undefined) process.env[m[1]] = m[2]

View File

@@ -80,7 +80,8 @@ as the correct long-term choice. Don't skip the lockdown offer.
2. `mkdir -p ~/.claude/channels/discord`
3. Read existing `.env` if present; update/add the `DISCORD_BOT_TOKEN=` line,
preserve other keys. Write back, no quotes around the value.
4. Confirm, then show the no-args status so the user sees where they stand.
4. `chmod 600 ~/.claude/channels/discord/.env` — the token is a credential.
5. Confirm, then show the no-args status so the user sees where they stand.
### `clear` — remove the token

View File

@@ -18,7 +18,7 @@ import {
import { Bot, InputFile, type Context } from 'grammy'
import type { ReactionTypeEmoji } from 'grammy/types'
import { randomBytes } from 'crypto'
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync } from 'fs'
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync, renameSync, realpathSync, chmodSync } from 'fs'
import { homedir } from 'os'
import { join, extname, sep } from 'path'
@@ -30,6 +30,8 @@ const ENV_FILE = join(STATE_DIR, '.env')
// Load ~/.claude/channels/telegram/.env into process.env. Real env wins.
// Plugin-spawned servers don't get an env block — this is where the token lives.
try {
// Token is a credential — lock to owner. No-op on Windows (would need ACLs).
chmodSync(ENV_FILE, 0o600)
for (const line of readFileSync(ENV_FILE, 'utf8').split('\n')) {
const m = line.match(/^(\w+)=(.*)$/)
if (m && process.env[m[1]] === undefined) process.env[m[1]] = m[2]
@@ -339,7 +341,7 @@ const mcp = new Server(
instructions: [
'The sender reads Telegram, not this session. Anything you want them to see must go through the reply tool — your transcript output never reaches their chat.',
'',
'Messages from Telegram arrive as <channel source="telegram" chat_id="..." message_id="..." user="..." ts="...">. If the tag has an image_path attribute, Read that file — it is a photo the sender attached. Reply with the reply tool — pass chat_id back. Use reply_to (set to a message_id) only when replying to an earlier message; the latest message doesn\'t need a quote-reply, omit reply_to for normal responses.',
'Messages from Telegram arrive as <channel source="telegram" chat_id="..." message_id="..." user="..." ts="...">. If the tag has an image_path attribute, Read that file — it is a photo the sender attached. If the tag has attachment_file_id, call download_attachment with that file_id to fetch the file, then Read the returned path. Reply with the reply tool — pass chat_id back. Use reply_to (set to a message_id) only when replying to an earlier message; the latest message doesn\'t need a quote-reply, omit reply_to for normal responses.',
'',
'reply accepts file paths (files: ["/abs/path.png"]) for attachments. Use react to add emoji reactions, and edit_message to update a message you previously sent (e.g. progress → result).',
'',
@@ -387,6 +389,17 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
required: ['chat_id', 'message_id', 'emoji'],
},
},
{
name: 'download_attachment',
description: 'Download a file attachment from a Telegram message to the local inbox. Use when the inbound <channel> meta shows attachment_file_id. Returns the local file path ready to Read. Telegram caps bot downloads at 20MB.',
inputSchema: {
type: 'object',
properties: {
file_id: { type: 'string', description: 'The attachment_file_id from inbound meta' },
},
required: ['file_id'],
},
},
{
name: 'edit_message',
description: 'Edit a message the bot previously sent. Useful for progress updates (send "working…" then edit to the result).',
@@ -478,6 +491,24 @@ mcp.setRequestHandler(CallToolRequestSchema, async req => {
])
return { content: [{ type: 'text', text: 'reacted' }] }
}
case 'download_attachment': {
const file_id = args.file_id as string
const file = await bot.api.getFile(file_id)
if (!file.file_path) throw new Error('Telegram returned no file_path — file may have expired')
const url = `https://api.telegram.org/file/bot${TOKEN}/${file.file_path}`
const res = await fetch(url)
if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`)
const buf = Buffer.from(await res.arrayBuffer())
// file_path is from Telegram (trusted), but strip to safe chars anyway
// so nothing downstream can be tricked by an unexpected extension.
const rawExt = file.file_path.includes('.') ? file.file_path.split('.').pop()! : 'bin'
const ext = rawExt.replace(/[^a-zA-Z0-9]/g, '') || 'bin'
const uniqueId = (file.file_unique_id ?? '').replace(/[^a-zA-Z0-9_-]/g, '') || 'dl'
const path = join(INBOX_DIR, `${Date.now()}-${uniqueId}.${ext}`)
mkdirSync(INBOX_DIR, { recursive: true })
writeFileSync(path, buf)
return { content: [{ type: 'text', text: path }] }
}
case 'edit_message': {
assertAllowedChat(args.chat_id as string)
const edited = await bot.api.editMessageText(
@@ -535,10 +566,94 @@ bot.on('message:photo', async ctx => {
})
})
bot.on('message:document', async ctx => {
const doc = ctx.message.document
const name = safeName(doc.file_name)
const text = ctx.message.caption ?? `(document: ${name ?? 'file'})`
await handleInbound(ctx, text, undefined, {
kind: 'document',
file_id: doc.file_id,
size: doc.file_size,
mime: doc.mime_type,
name,
})
})
bot.on('message:voice', async ctx => {
const voice = ctx.message.voice
const text = ctx.message.caption ?? '(voice message)'
await handleInbound(ctx, text, undefined, {
kind: 'voice',
file_id: voice.file_id,
size: voice.file_size,
mime: voice.mime_type,
})
})
bot.on('message:audio', async ctx => {
const audio = ctx.message.audio
const name = safeName(audio.file_name)
const text = ctx.message.caption ?? `(audio: ${safeName(audio.title) ?? name ?? 'audio'})`
await handleInbound(ctx, text, undefined, {
kind: 'audio',
file_id: audio.file_id,
size: audio.file_size,
mime: audio.mime_type,
name,
})
})
bot.on('message:video', async ctx => {
const video = ctx.message.video
const text = ctx.message.caption ?? '(video)'
await handleInbound(ctx, text, undefined, {
kind: 'video',
file_id: video.file_id,
size: video.file_size,
mime: video.mime_type,
name: safeName(video.file_name),
})
})
bot.on('message:video_note', async ctx => {
const vn = ctx.message.video_note
await handleInbound(ctx, '(video note)', undefined, {
kind: 'video_note',
file_id: vn.file_id,
size: vn.file_size,
})
})
bot.on('message:sticker', async ctx => {
const sticker = ctx.message.sticker
const emoji = sticker.emoji ? ` ${sticker.emoji}` : ''
await handleInbound(ctx, `(sticker${emoji})`, undefined, {
kind: 'sticker',
file_id: sticker.file_id,
size: sticker.file_size,
})
})
type AttachmentMeta = {
kind: string
file_id: string
size?: number
mime?: string
name?: string
}
// Filenames and titles are uploader-controlled. They land inside the <channel>
// notification — delimiter chars would let the uploader break out of the tag
// or forge a second meta entry.
function safeName(s: string | undefined): string | undefined {
return s?.replace(/[<>\[\]\r\n;]/g, '_')
}
async function handleInbound(
ctx: Context,
text: string,
downloadImage: (() => Promise<string | undefined>) | undefined,
attachment?: AttachmentMeta,
): Promise<void> {
const result = gate(ctx)
@@ -586,6 +701,13 @@ async function handleInbound(
user_id: String(from.id),
ts: new Date((ctx.message?.date ?? 0) * 1000).toISOString(),
...(imagePath ? { image_path: imagePath } : {}),
...(attachment ? {
attachment_kind: attachment.kind,
attachment_file_id: attachment.file_id,
...(attachment.size != null ? { attachment_size: String(attachment.size) } : {}),
...(attachment.mime ? { attachment_mime: attachment.mime } : {}),
...(attachment.name ? { attachment_name: attachment.name } : {}),
} : {}),
},
},
})

View File

@@ -77,7 +77,8 @@ offer.
2. `mkdir -p ~/.claude/channels/telegram`
3. Read existing `.env` if present; update/add the `TELEGRAM_BOT_TOKEN=` line,
preserve other keys. Write back, no quotes around the value.
4. Confirm, then show the no-args status so the user sees where they stand.
4. `chmod 600 ~/.claude/channels/telegram/.env` — the token is a credential.
5. Confirm, then show the no-args status so the user sees where they stand.
### `clear` — remove the token