fix(security): lock down inbound DMs by default

This commit is contained in:
Peter Steinberger
2026-01-06 17:51:38 +01:00
parent 327ad3c9c7
commit 967cef80bc
36 changed files with 2093 additions and 203 deletions

View File

@@ -35,10 +35,18 @@ vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../config/config.js")>();
return {
...actual,
loadConfig: () => ({}),
loadConfig: () => ({ telegram: { dmPolicy: "open", allowFrom: ["*"] } }),
};
});
vi.mock("./pairing-store.js", () => ({
readTelegramAllowFromStore: vi.fn(async () => [] as string[]),
upsertTelegramPairingRequest: vi.fn(async () => ({
code: "PAIRCODE",
created: true,
})),
}));
vi.mock("../auto-reply/reply.js", () => {
const replySpy = vi.fn(async (_ctx, opts) => {
await opts?.onReplyStart?.();

View File

@@ -21,6 +21,21 @@ vi.mock("../config/config.js", async (importOriginal) => {
};
});
const { readTelegramAllowFromStore, upsertTelegramPairingRequest } = vi.hoisted(
() => ({
readTelegramAllowFromStore: vi.fn(async () => [] as string[]),
upsertTelegramPairingRequest: vi.fn(async () => ({
code: "PAIRCODE",
created: true,
})),
}),
);
vi.mock("./pairing-store.js", () => ({
readTelegramAllowFromStore,
upsertTelegramPairingRequest,
}));
const useSpy = vi.fn();
const onSpy = vi.fn();
const stopSpy = vi.fn();
@@ -73,7 +88,9 @@ vi.mock("../auto-reply/reply.js", () => {
describe("createTelegramBot", () => {
beforeEach(() => {
loadConfig.mockReturnValue({});
loadConfig.mockReturnValue({
telegram: { dmPolicy: "open", allowFrom: ["*"] },
});
loadWebMedia.mockReset();
sendAnimationSpy.mockReset();
sendPhotoSpy.mockReset();
@@ -130,6 +147,46 @@ describe("createTelegramBot", () => {
}
});
it("requests pairing by default for unknown DM senders", async () => {
onSpy.mockReset();
sendMessageSpy.mockReset();
const replySpy = replyModule.__replySpy as unknown as ReturnType<
typeof vi.fn
>;
replySpy.mockReset();
loadConfig.mockReturnValue({ telegram: { dmPolicy: "pairing" } });
readTelegramAllowFromStore.mockResolvedValue([]);
upsertTelegramPairingRequest.mockResolvedValue({
code: "PAIRME12",
created: true,
});
createTelegramBot({ token: "tok" });
const handler = onSpy.mock.calls[0][1] as (
ctx: Record<string, unknown>,
) => Promise<void>;
await handler({
message: {
chat: { id: 1234, type: "private" },
text: "hello",
date: 1736380800,
from: { id: 999, username: "random" },
},
me: { username: "clawdbot_bot" },
getFile: async () => ({ download: async () => new Uint8Array() }),
});
expect(replySpy).not.toHaveBeenCalled();
expect(sendMessageSpy).toHaveBeenCalledTimes(1);
expect(sendMessageSpy.mock.calls[0]?.[0]).toBe(1234);
expect(String(sendMessageSpy.mock.calls[0]?.[1])).toContain(
"Pairing code:",
);
expect(String(sendMessageSpy.mock.calls[0]?.[1])).toContain("PAIRME12");
});
it("triggers typing cue via onReplyStart", async () => {
onSpy.mockReset();
sendChatActionSpy.mockReset();
@@ -397,7 +454,10 @@ describe("createTelegramBot", () => {
await opts?.onToolResult?.({ text: "tool result" });
return { text: "final reply" };
});
loadConfig.mockReturnValue({ messages: { responsePrefix: "PFX" } });
loadConfig.mockReturnValue({
telegram: { dmPolicy: "open", allowFrom: ["*"] },
messages: { responsePrefix: "PFX" },
});
createTelegramBot({ token: "tok" });
const handler = onSpy.mock.calls[0][1] as (

View File

@@ -35,6 +35,10 @@ import {
} from "../providers/location.js";
import type { RuntimeEnv } from "../runtime.js";
import { loadWebMedia } from "../web/media.js";
import {
readTelegramAllowFromStore,
upsertTelegramPairingRequest,
} from "./pairing-store.js";
const PARSE_ERR_RE =
/can't parse entities|parse entities|find end of the entity/i;
@@ -111,6 +115,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const cfg = loadConfig();
const textLimit = resolveTextChunkLimit(cfg, "telegram");
const dmPolicy = cfg.telegram?.dmPolicy ?? "pairing";
const allowFrom = opts.allowFrom ?? cfg.telegram?.allowFrom;
const groupAllowFrom =
opts.groupAllowFrom ??
@@ -150,8 +155,6 @@ export function createTelegramBot(opts: TelegramBotOptions) {
(entry) => entry === username || entry === `@${username}`,
);
};
const dmAllow = normalizeAllowFrom(allowFrom);
const groupAllow = normalizeAllowFrom(groupAllowFrom);
const replyToMode = opts.replyToMode ?? cfg.telegram?.replyToMode ?? "off";
const ackReaction = (cfg.messages?.ackReaction ?? "").trim();
const ackReactionScope = cfg.messages?.ackReactionScope ?? "group-mentions";
@@ -177,10 +180,19 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const processMessage = async (
primaryCtx: TelegramContext,
allMedia: Array<{ path: string; contentType?: string }>,
storeAllowFrom: string[],
) => {
const msg = primaryCtx.message;
const chatId = msg.chat.id;
const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
const effectiveDmAllow = normalizeAllowFrom([
...(allowFrom ?? []),
...storeAllowFrom,
]);
const effectiveGroupAllow = normalizeAllowFrom([
...(groupAllowFrom ?? []),
...storeAllowFrom,
]);
const sendTyping = async () => {
try {
@@ -192,14 +204,70 @@ export function createTelegramBot(opts: TelegramBotOptions) {
}
};
// allowFrom for direct chats
if (!isGroup && dmAllow.hasEntries) {
const candidate = String(chatId);
if (!isSenderAllowed({ allow: dmAllow, senderId: candidate })) {
logVerbose(
`Blocked unauthorized telegram sender ${candidate} (not in allowFrom)`,
);
return;
// DM access control (secure defaults): "pairing" (default) / "allowlist" / "open" / "disabled"
if (!isGroup) {
if (dmPolicy === "disabled") return;
if (dmPolicy !== "open") {
const candidate = String(chatId);
const senderUsername = msg.from?.username ?? "";
const allowed =
effectiveDmAllow.hasWildcard ||
(effectiveDmAllow.hasEntries &&
isSenderAllowed({
allow: effectiveDmAllow,
senderId: candidate,
senderUsername,
}));
if (!allowed) {
if (dmPolicy === "pairing") {
try {
const from = msg.from as
| {
first_name?: string;
last_name?: string;
username?: string;
}
| undefined;
const { code } = await upsertTelegramPairingRequest({
chatId: candidate,
username: from?.username,
firstName: from?.first_name,
lastName: from?.last_name,
});
logger.info(
{
chatId: candidate,
username: from?.username,
firstName: from?.first_name,
lastName: from?.last_name,
code,
},
"telegram pairing request",
);
await bot.api.sendMessage(
chatId,
[
"Clawdbot: access not configured.",
"",
`Pairing code: ${code}`,
"",
"Ask the bot owner to approve with:",
"clawdbot telegram pairing approve <code>",
].join("\n"),
);
} catch (err) {
logVerbose(
`telegram pairing reply failed for chat ${chatId}: ${String(err)}`,
);
}
} else {
logVerbose(
`Blocked unauthorized telegram sender ${candidate} (dmPolicy=${dmPolicy})`,
);
}
return;
}
}
}
@@ -207,7 +275,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const senderId = msg.from?.id ? String(msg.from.id) : "";
const senderUsername = msg.from?.username ?? "";
const commandAuthorized = isSenderAllowed({
allow: isGroup ? groupAllow : dmAllow,
allow: isGroup ? effectiveGroupAllow : effectiveDmAllow,
senderId,
senderUsername,
});
@@ -407,6 +475,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const chatId = msg.chat.id;
const isGroup =
msg.chat.type === "group" || msg.chat.type === "supergroup";
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
if (isGroup) {
// Group policy filtering: controls how group messages are handled
@@ -419,6 +488,10 @@ export function createTelegramBot(opts: TelegramBotOptions) {
return;
}
if (groupPolicy === "allowlist") {
const effectiveGroupAllow = normalizeAllowFrom([
...(groupAllowFrom ?? []),
...storeAllowFrom,
]);
// For allowlist mode, the sender (msg.from.id) must be in allowFrom
const senderId = msg.from?.id;
if (senderId == null) {
@@ -427,7 +500,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
);
return;
}
if (!groupAllow.hasEntries) {
if (!effectiveGroupAllow.hasEntries) {
logVerbose(
"Blocked telegram group message (groupPolicy: allowlist, no groupAllowFrom)",
);
@@ -436,7 +509,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const senderUsername = msg.from?.username ?? "";
if (
!isSenderAllowed({
allow: groupAllow,
allow: effectiveGroupAllow,
senderId: String(senderId),
senderUsername,
})
@@ -510,7 +583,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
const allMedia = media
? [{ path: media.path, contentType: media.contentType }]
: [];
await processMessage(ctx, allMedia);
await processMessage(ctx, allMedia, storeAllowFrom);
} catch (err) {
runtime.error?.(danger(`handler failed: ${String(err)}`));
}
@@ -538,7 +611,8 @@ export function createTelegramBot(opts: TelegramBotOptions) {
}
}
await processMessage(primaryEntry.ctx, allMedia);
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
await processMessage(primaryEntry.ctx, allMedia, storeAllowFrom);
} catch (err) {
runtime.error?.(danger(`media group handler failed: ${String(err)}`));
}

View File

@@ -0,0 +1,51 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
approveTelegramPairingCode,
listTelegramPairingRequests,
readTelegramAllowFromStore,
upsertTelegramPairingRequest,
} from "./pairing-store.js";
async function withTempStateDir<T>(fn: (stateDir: string) => Promise<T>) {
const previous = process.env.CLAWDBOT_STATE_DIR;
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-pairing-"));
process.env.CLAWDBOT_STATE_DIR = dir;
try {
return await fn(dir);
} finally {
if (previous === undefined) delete process.env.CLAWDBOT_STATE_DIR;
else process.env.CLAWDBOT_STATE_DIR = previous;
await fs.rm(dir, { recursive: true, force: true });
}
}
describe("telegram pairing store", () => {
it("creates pairing request and approves it into allow store", async () => {
await withTempStateDir(async () => {
const created = await upsertTelegramPairingRequest({
chatId: "123456789",
username: "ada",
});
expect(created.code).toBeTruthy();
const list = await listTelegramPairingRequests();
expect(list).toHaveLength(1);
expect(list[0]?.chatId).toBe("123456789");
expect(list[0]?.code).toBe(created.code);
const approved = await approveTelegramPairingCode({ code: created.code });
expect(approved?.chatId).toBe("123456789");
const listAfter = await listTelegramPairingRequests();
expect(listAfter).toHaveLength(0);
const allow = await readTelegramAllowFromStore();
expect(allow).toContain("123456789");
});
});
});

View File

@@ -0,0 +1,122 @@
import type { ClawdbotConfig } from "../config/config.js";
import {
addProviderAllowFromStoreEntry,
approveProviderPairingCode,
listProviderPairingRequests,
readProviderAllowFromStore,
upsertProviderPairingRequest,
} from "../pairing/pairing-store.js";
export type TelegramPairingListEntry = {
chatId: string;
username?: string;
firstName?: string;
lastName?: string;
code: string;
createdAt: string;
lastSeenAt: string;
};
const PROVIDER = "telegram" as const;
export async function readTelegramAllowFromStore(
env: NodeJS.ProcessEnv = process.env,
): Promise<string[]> {
return readProviderAllowFromStore(PROVIDER, env);
}
export async function addTelegramAllowFromStoreEntry(params: {
entry: string | number;
env?: NodeJS.ProcessEnv;
}): Promise<{ changed: boolean; allowFrom: string[] }> {
return addProviderAllowFromStoreEntry({
provider: PROVIDER,
entry: params.entry,
env: params.env,
});
}
export async function listTelegramPairingRequests(
env: NodeJS.ProcessEnv = process.env,
): Promise<TelegramPairingListEntry[]> {
const list = await listProviderPairingRequests(PROVIDER, env);
return list.map((r) => ({
chatId: r.id,
code: r.code,
createdAt: r.createdAt,
lastSeenAt: r.lastSeenAt,
username: r.meta?.username,
firstName: r.meta?.firstName,
lastName: r.meta?.lastName,
}));
}
export async function upsertTelegramPairingRequest(params: {
chatId: string | number;
username?: string;
firstName?: string;
lastName?: string;
env?: NodeJS.ProcessEnv;
}): Promise<{ code: string; created: boolean }> {
return upsertProviderPairingRequest({
provider: PROVIDER,
id: String(params.chatId),
env: params.env,
meta: {
username: params.username,
firstName: params.firstName,
lastName: params.lastName,
},
});
}
export async function approveTelegramPairingCode(params: {
code: string;
env?: NodeJS.ProcessEnv;
}): Promise<{ chatId: string; entry?: TelegramPairingListEntry } | null> {
const res = await approveProviderPairingCode({
provider: PROVIDER,
code: params.code,
env: params.env,
});
if (!res) return null;
const entry = res.entry
? {
chatId: res.entry.id,
code: res.entry.code,
createdAt: res.entry.createdAt,
lastSeenAt: res.entry.lastSeenAt,
username: res.entry.meta?.username,
firstName: res.entry.meta?.firstName,
lastName: res.entry.meta?.lastName,
}
: undefined;
return { chatId: res.id, entry };
}
export async function resolveTelegramEffectiveAllowFrom(params: {
cfg: ClawdbotConfig;
env?: NodeJS.ProcessEnv;
}): Promise<{ dm: string[]; group: string[] }> {
const env = params.env ?? process.env;
const cfgAllowFrom = (params.cfg.telegram?.allowFrom ?? [])
.map((v) => String(v).trim())
.filter(Boolean)
.map((v) => v.replace(/^(telegram|tg):/i, ""))
.filter((v) => v !== "*");
const cfgGroupAllowFrom = (params.cfg.telegram?.groupAllowFrom ?? [])
.map((v) => String(v).trim())
.filter(Boolean)
.map((v) => v.replace(/^(telegram|tg):/i, ""))
.filter((v) => v !== "*");
const storeAllowFrom = await readTelegramAllowFromStore(env);
const dm = Array.from(new Set([...cfgAllowFrom, ...storeAllowFrom]));
const group = Array.from(
new Set([
...(cfgGroupAllowFrom.length > 0 ? cfgGroupAllowFrom : cfgAllowFrom),
...storeAllowFrom,
]),
);
return { dm, group };
}