Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"@streamdown/code": "^1.0.1",
"@streamdown/math": "^1.0.1",
"@streamdown/mermaid": "^1.0.1",
"@wecom/aibot-node-sdk": "^1.0.1",
"ai": "^6.0.73",
"ansi-to-react": "^6.2.6",
"better-sqlite3": "^12.6.2",
Expand Down
62 changes: 62 additions & 0 deletions src/__tests__/unit/wecom-bridge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* Unit tests for WeCom bridge markdown/card helpers.
*
* Run with: npx tsx --test src/__tests__/unit/wecom-bridge.test.ts
*/

import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import {
buildMarkdownMessage,
buildPermissionCard,
buildPermissionCommandText,
hasComplexMarkdown,
htmlToWecomMarkdown,
preprocessWecomMarkdown,
} from '../../lib/bridge/markdown/wecom';

describe('WeCom markdown helpers', () => {
it('detects fenced code blocks as complex markdown', () => {
assert.equal(hasComplexMarkdown('hello\n```ts\nconst x = 1;\n```'), true);
});

it('detects tables as complex markdown', () => {
assert.equal(hasComplexMarkdown('| a | b |\n| - | - |\n| 1 | 2 |'), true);
});

it('adds a newline before code fences when needed', () => {
assert.equal(preprocessWecomMarkdown('Intro```ts\nconst x = 1;\n```'), 'Intro\n```ts\nconst x = 1;\n```');
});

it('converts simple html to markdown', () => {
assert.equal(htmlToWecomMarkdown('<b>bold</b><br><code>x</code>'), '**bold**\n`x`');
});

it('builds markdown message payloads', () => {
assert.deepEqual(buildMarkdownMessage('hello'), {
msgtype: 'markdown',
markdown: { content: 'hello' },
});
});
});

describe('WeCom permission helpers', () => {
const buttons = [[
{ text: 'Allow once', callbackData: 'perm:allow:req-1' },
{ text: 'Deny', callbackData: 'perm:deny:req-1' },
]];

it('renders /perm fallback text', () => {
const text = buildPermissionCommandText('Need approval', buttons);
assert.ok(text.includes('/perm allow req-1'));
assert.ok(text.includes('/perm deny req-1'));
});

it('builds clickable permission cards', () => {
const card = buildPermissionCard(buttons, 'perm_fixed');
assert.equal(card.msgtype, 'template_card');
assert.equal(card.template_card.card_type, 'button_interaction');
assert.equal(card.template_card.task_id, 'perm_fixed');
assert.equal(card.template_card.button_list?.[0]?.key, 'perm:allow:req-1');
});
});
6 changes: 6 additions & 0 deletions src/app/api/bridge/settings/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ const BRIDGE_SETTING_KEYS = [
'bridge_feishu_group_policy',
'bridge_feishu_group_allow_from',
'bridge_feishu_require_mention',
'bridge_wecom_enabled',
'bridge_wecom_bot_id',
'bridge_wecom_secret',
'bridge_wecom_allowed_users',
'bridge_wecom_group_policy',
'bridge_wecom_group_allow_from',
'bridge_discord_enabled',
'bridge_discord_bot_token',
'bridge_discord_allowed_users',
Expand Down
59 changes: 59 additions & 0 deletions src/app/api/settings/wecom/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSetting, setSetting } from '@/lib/db';

const WECOM_KEYS = [
'bridge_wecom_enabled',
'bridge_wecom_bot_id',
'bridge_wecom_secret',
'bridge_wecom_allowed_users',
'bridge_wecom_group_policy',
'bridge_wecom_group_allow_from',
] as const;

export async function GET() {
try {
const result: Record<string, string> = {};
for (const key of WECOM_KEYS) {
const value = getSetting(key);
if (value === undefined) continue;

if (key === 'bridge_wecom_secret' && value.length > 8) {
result[key] = '***' + value.slice(-8);
} else {
result[key] = value;
}
}

return NextResponse.json({ settings: result });
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to read WeCom settings';
return NextResponse.json({ error: message }, { status: 500 });
}
}

export async function PUT(request: NextRequest) {
try {
const body = await request.json();
const { settings } = body;

if (!settings || typeof settings !== 'object') {
return NextResponse.json({ error: 'Invalid settings data' }, { status: 400 });
}

for (const [key, value] of Object.entries(settings)) {
if (!WECOM_KEYS.includes(key as typeof WECOM_KEYS[number])) continue;
const strValue = String(value ?? '').trim();

if (key === 'bridge_wecom_secret' && strValue.startsWith('***')) {
continue;
}

setSetting(key, strValue);
}

return NextResponse.json({ success: true });
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to save WeCom settings';
return NextResponse.json({ error: message }, { status: 500 });
}
}
89 changes: 89 additions & 0 deletions src/app/api/settings/wecom/verify/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server';
import { WSClient } from '@wecom/aibot-node-sdk';
import { getSetting } from '@/lib/db';

export const runtime = 'nodejs';

/**
* POST /api/settings/wecom/verify
*
* Verifies WeCom AI Bot credentials by establishing a short-lived WebSocket
* connection and waiting for the SDK authenticated event.
* If secret starts with *** (masked), falls back to the stored secret.
*/
export async function POST(request: NextRequest) {
let client: WSClient | null = null;

try {
const body = await request.json();
let { bot_id, secret } = body;

if (!bot_id) {
bot_id = getSetting('bridge_wecom_bot_id') || '';
}
if (!secret || secret.startsWith('***')) {
secret = getSetting('bridge_wecom_secret') || '';
}

if (!bot_id || !secret) {
return NextResponse.json(
{ verified: false, error: 'Bot ID and Secret are required' },
{ status: 400 },
);
}

client = new WSClient({
botId: bot_id,
secret,
requestTimeout: 10_000,
reconnectInterval: 1_000,
maxReconnectAttempts: 0,
});
const verifyClient = client;

await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
cleanup();
reject(new Error('Timed out while waiting for WeCom authentication'));
}, 10_000);

const cleanup = () => {
clearTimeout(timeout);
verifyClient.off('authenticated', onAuthenticated);
verifyClient.off('error', onError);
verifyClient.off('disconnected', onDisconnected);
};

const onAuthenticated = () => {
cleanup();
resolve();
};

const onError = (error: Error) => {
cleanup();
reject(error);
};

const onDisconnected = (reason: string) => {
cleanup();
reject(new Error(reason || 'WeCom connection disconnected before authentication'));
};

verifyClient.once('authenticated', onAuthenticated);
verifyClient.once('error', onError);
verifyClient.once('disconnected', onDisconnected);
verifyClient.connect();
});

return NextResponse.json({ verified: true, botId: bot_id });
} catch (error) {
const message = error instanceof Error ? error.message : 'Verification failed';
return NextResponse.json({ verified: false, error: message }, { status: 500 });
} finally {
try {
client?.disconnect();
} catch {
// ignore cleanup failure
}
}
}
7 changes: 6 additions & 1 deletion src/components/bridge/BridgeLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import { Button } from "@/components/ui/button";
import { BridgeSection } from "./BridgeSection";
import { TelegramBridgeSection } from "./TelegramBridgeSection";
import { FeishuBridgeSection } from "./FeishuBridgeSection";
import { WecomBridgeSection } from "./WecomBridgeSection";
import { DiscordBridgeSection } from "./DiscordBridgeSection";
import { QqBridgeSection } from "./QqBridgeSection";
import { useTranslation } from "@/hooks/useTranslation";
import type { TranslationKey } from "@/i18n";

type Section = "bridge" | "telegram" | "feishu" | "discord" | "qq";
type Section = "bridge" | "telegram" | "feishu" | "wecom" | "discord" | "qq";

interface SidebarItem {
id: Section;
Expand All @@ -24,10 +25,12 @@ const sidebarItems: SidebarItem[] = [
{ id: "bridge", label: "Bridge", icon: WifiHigh },
{ id: "telegram", label: "Telegram", icon: TelegramLogo },
{ id: "feishu", label: "Feishu", icon: ChatTeardrop },
{ id: "wecom", label: "WeCom", icon: ChatTeardrop },
{ id: "discord", label: "Discord", icon: GameController },
{ id: "qq", label: "QQ", icon: ChatsCircle },
];


function getSectionFromHash(): Section {
if (typeof window === "undefined") return "bridge";
const hash = window.location.hash.replace("#", "");
Expand All @@ -53,6 +56,7 @@ export function BridgeLayout() {
'Bridge': 'bridge.title',
'Telegram': 'bridge.telegramSettings',
'Feishu': 'bridge.feishuSettings',
'WeCom': 'bridge.wecomSettings',
'Discord': 'bridge.discordSettings',
'QQ': 'bridge.qqSettings',
};
Expand Down Expand Up @@ -96,6 +100,7 @@ export function BridgeLayout() {
{activeSection === "bridge" && <BridgeSection />}
{activeSection === "telegram" && <TelegramBridgeSection />}
{activeSection === "feishu" && <FeishuBridgeSection />}
{activeSection === "wecom" && <WecomBridgeSection />}
{activeSection === "discord" && <DiscordBridgeSection />}
{activeSection === "qq" && <QqBridgeSection />}
</div>
Expand Down
Loading