This commit is contained in:
161
packages/server/src/local/channels/chat-client.ts
Normal file
161
packages/server/src/local/channels/chat-client.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Loopback chat client — runs one agent turn through POST /api/chat on
|
||||
* 127.0.0.1 and collapses the SSE stream into a final result.
|
||||
*
|
||||
* Deliberate design: channel adapters reuse the FULL existing chat path
|
||||
* (injection scan, persona resolution, governance, memory persistence,
|
||||
* audit trail) instead of extracting a service from the 2k-line chat.ts.
|
||||
* The origin guard admits loopback requests without an Origin header by
|
||||
* design (see local/origin-guard.ts — "same-host curl / server inject").
|
||||
*
|
||||
* Approval semantics (founder decision, v1): when the turn stalls on
|
||||
* `approval_required` we do NOT approve over IM — the caller replies with
|
||||
* a "needs approval in the Waggle app" message instead.
|
||||
*/
|
||||
|
||||
export interface ChatTurnResult {
|
||||
content: string;
|
||||
approvalRequired: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ChatTurnRequest {
|
||||
port: number;
|
||||
/** Sidecar session token for the protected loopback API. */
|
||||
sessionToken: string;
|
||||
message: string;
|
||||
workspace: string;
|
||||
/** Persisted session id — one per IM conversation. */
|
||||
session: string;
|
||||
timeoutMs?: number;
|
||||
/** Per-turn persona override (e.g. 'session-reviewer' for the idle watcher). */
|
||||
persona?: string;
|
||||
/**
|
||||
* Headless turn: hold gated proposable tools for human approval instead of
|
||||
* prompting live over an SSE stream nobody is watching. Used by channels and
|
||||
* self-evolution reviews. See the `proposeHeld` field on POST /api/chat.
|
||||
*/
|
||||
proposeHeld?: boolean;
|
||||
/**
|
||||
* Automation-origin marker (#13): set ONLY by headless/automated callers
|
||||
* (e.g. the idle-watcher's review turns) so the chat route skips its
|
||||
* post-response memory write-back. IM channel adapters must NOT set this —
|
||||
* inbound IM messages are real user turns and must keep writing memory.
|
||||
*/
|
||||
origin?: 'automation' | 'router';
|
||||
/**
|
||||
* #17: originating IM channel of this turn (REAL platform + chatId — the
|
||||
* session id normalizes chatId irreversibly). The chat route publishes it
|
||||
* as the request-scoped turn origin so create_schedule can stamp ai_task
|
||||
* delivery targets. Set only by ChannelManager.handleInbound.
|
||||
*/
|
||||
channel?: { platform: string; chatId: string };
|
||||
}
|
||||
|
||||
/** Hard ceiling so a wedged turn can't pin a poll loop forever. */
|
||||
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
interface SseEvent {
|
||||
event: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/** Parse complete SSE frames out of an accumulating buffer. Returns leftover. */
|
||||
export function drainSseBuffer(buffer: string): { events: SseEvent[]; rest: string } {
|
||||
const events: SseEvent[] = [];
|
||||
const frames = buffer.split('\n\n');
|
||||
const rest = frames.pop() ?? '';
|
||||
for (const frame of frames) {
|
||||
let event = 'message';
|
||||
let dataRaw = '';
|
||||
for (const line of frame.split('\n')) {
|
||||
if (line.startsWith('event: ')) event = line.slice(7).trim();
|
||||
else if (line.startsWith('data: ')) dataRaw += line.slice(6);
|
||||
}
|
||||
if (dataRaw === '') continue;
|
||||
try {
|
||||
events.push({ event, data: JSON.parse(dataRaw) });
|
||||
} catch {
|
||||
/* non-JSON data frame — ignore; the chat route always sends JSON */
|
||||
}
|
||||
}
|
||||
return { events, rest };
|
||||
}
|
||||
|
||||
export async function runChannelChatTurn(req: ChatTurnRequest): Promise<ChatTurnResult> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), req.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${req.port}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${req.sessionToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: req.message,
|
||||
workspace: req.workspace,
|
||||
session: req.session,
|
||||
...(req.persona ? { persona: req.persona } : {}),
|
||||
...(req.proposeHeld ? { proposeHeld: true } : {}),
|
||||
...(req.origin ? { origin: req.origin } : {}),
|
||||
...(req.channel ? { channel: req.channel } : {}),
|
||||
}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Pre-SSE JSON errors: validation, injection block, viewer RBAC.
|
||||
let detail = `HTTP ${response.status}`;
|
||||
try {
|
||||
const body = await response.json() as { error?: string; code?: string };
|
||||
if (body?.code === 'INJECTION_DETECTED') {
|
||||
return { content: '', approvalRequired: false, error: 'Message blocked by the security scanner.' };
|
||||
}
|
||||
if (body?.error) detail = body.error;
|
||||
} catch { /* non-JSON error body — keep status text */ }
|
||||
return { content: '', approvalRequired: false, error: detail };
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
return { content: '', approvalRequired: false, error: 'Empty response stream' };
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let content = '';
|
||||
let approvalRequired = false;
|
||||
let error: string | undefined;
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (value) buffer += decoder.decode(value, { stream: true });
|
||||
const drained = drainSseBuffer(buffer);
|
||||
buffer = drained.rest;
|
||||
for (const evt of drained.events) {
|
||||
if (evt.event === 'done') {
|
||||
const d = evt.data as { content?: string };
|
||||
if (typeof d?.content === 'string') content = d.content;
|
||||
} else if (evt.event === 'approval_required') {
|
||||
approvalRequired = true;
|
||||
} else if (evt.event === 'error') {
|
||||
const d = evt.data as { error?: string; message?: string };
|
||||
error = d?.error ?? d?.message ?? 'Agent turn failed';
|
||||
}
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
|
||||
return { content, approvalRequired, error };
|
||||
} catch (e: unknown) {
|
||||
const aborted = e instanceof Error && e.name === 'AbortError';
|
||||
return {
|
||||
content: '',
|
||||
approvalRequired: false,
|
||||
error: aborted ? 'Agent turn timed out' : (e instanceof Error ? e.message : 'Agent turn failed'),
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
268
packages/server/src/local/channels/discord-adapter.ts
Normal file
268
packages/server/src/local/channels/discord-adapter.ts
Normal file
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* Discord channel adapter — raw gateway WebSocket, no discord.js.
|
||||
*
|
||||
* NAT-friendly: the bot dials OUT to Discord's gateway; no public endpoint.
|
||||
* We implement the minimal gateway contract (HELLO → IDENTIFY → heartbeat →
|
||||
* MESSAGE_CREATE dispatches) and reconnect-with-re-IDENTIFY on any drop —
|
||||
* resume (op 6) is deliberately skipped: a desktop assistant tolerates the
|
||||
* occasional replayed-gap far better than it tolerates resume-state bugs.
|
||||
*
|
||||
* Fixed API host (discord.com) — no SSRF surface. Bot needs the
|
||||
* MESSAGE CONTENT privileged intent enabled in the developer portal.
|
||||
*/
|
||||
|
||||
import WebSocket from 'ws';
|
||||
import type {
|
||||
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler, WsFactory, WsLike,
|
||||
} from './types.js';
|
||||
import { chunkText } from './types.js';
|
||||
|
||||
const DISCORD_API = 'https://discord.com/api/v10';
|
||||
export const DISCORD_MAX_TEXT = 2000;
|
||||
// GUILDS + GUILD_MESSAGES + DIRECT_MESSAGES + MESSAGE_CONTENT
|
||||
export const DISCORD_INTENTS = 1 | (1 << 9) | (1 << 12) | (1 << 15);
|
||||
const BACKOFF_START_MS = 1_000;
|
||||
const BACKOFF_CAP_MS = 60_000;
|
||||
|
||||
// Gateway opcodes we handle.
|
||||
const OP_DISPATCH = 0;
|
||||
const OP_HEARTBEAT = 1;
|
||||
const OP_IDENTIFY = 2;
|
||||
const OP_RECONNECT = 7;
|
||||
const OP_INVALID_SESSION = 9;
|
||||
const OP_HELLO = 10;
|
||||
const OP_HEARTBEAT_ACK = 11;
|
||||
|
||||
interface GatewayFrame {
|
||||
op: number;
|
||||
d?: unknown;
|
||||
s?: number | null;
|
||||
t?: string | null;
|
||||
}
|
||||
|
||||
interface DiscordAuthor {
|
||||
id: string;
|
||||
username?: string;
|
||||
bot?: boolean;
|
||||
}
|
||||
|
||||
interface DiscordMessageCreate {
|
||||
id: string;
|
||||
channel_id: string;
|
||||
content?: string;
|
||||
author?: DiscordAuthor;
|
||||
}
|
||||
|
||||
export interface DiscordAdapterOptions {
|
||||
botToken: string;
|
||||
onMessage: InboundHandler;
|
||||
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
||||
/** Test seams. */
|
||||
fetchImpl?: typeof fetch;
|
||||
wsFactory?: WsFactory;
|
||||
/** Test seam — collapses reconnect backoff waits. */
|
||||
backoffCapMs?: number;
|
||||
}
|
||||
|
||||
export class DiscordAdapter implements ChannelAdapter {
|
||||
readonly platform = 'discord' as const;
|
||||
|
||||
private readonly token: string;
|
||||
private readonly onMessage: InboundHandler;
|
||||
private readonly log: DiscordAdapterOptions['log'];
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly wsFactory: WsFactory;
|
||||
private readonly backoffCap: number;
|
||||
|
||||
private running = false;
|
||||
private connected = false;
|
||||
private lastError: string | undefined;
|
||||
private lastActivityAt: number | undefined;
|
||||
private ws: WsLike | null = null;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private backoff: number;
|
||||
private seq: number | null = null;
|
||||
private botUserId: string | null = null;
|
||||
|
||||
constructor(opts: DiscordAdapterOptions) {
|
||||
this.token = opts.botToken;
|
||||
this.onMessage = opts.onMessage;
|
||||
this.log = opts.log;
|
||||
this.fetchImpl = opts.fetchImpl ?? fetch;
|
||||
this.wsFactory = opts.wsFactory ?? ((url: string) => new WebSocket(url) as unknown as WsLike);
|
||||
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.lastError = undefined;
|
||||
await this.connect();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.running = false;
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
getStatus(): ChannelAdapterStatus {
|
||||
return {
|
||||
platform: this.platform,
|
||||
running: this.running,
|
||||
connected: this.connected,
|
||||
lastError: this.lastError,
|
||||
lastActivityAt: this.lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
async send(chatId: string, text: string): Promise<void> {
|
||||
for (const chunk of chunkText(text, DISCORD_MAX_TEXT)) {
|
||||
const r = await this.fetchImpl(`${DISCORD_API}/channels/${encodeURIComponent(chatId)}/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bot ${this.token}`,
|
||||
},
|
||||
body: JSON.stringify({ content: chunk }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
const body = await r.text().catch(() => '');
|
||||
throw new Error(`Discord send failed (HTTP ${r.status}): ${body.slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Gateway lifecycle ────────────────────────────────────────────────
|
||||
|
||||
private async connect(): Promise<void> {
|
||||
try {
|
||||
const r = await this.fetchImpl(`${DISCORD_API}/gateway/bot`, {
|
||||
headers: { Authorization: `Bot ${this.token}` },
|
||||
});
|
||||
if (!r.ok) throw new Error(`gateway/bot HTTP ${r.status}`);
|
||||
const { url } = await r.json() as { url: string };
|
||||
|
||||
const ws = this.wsFactory(`${url}?v=10&encoding=json`);
|
||||
this.ws = ws;
|
||||
ws.on('message', (data: unknown) => this.handleFrame(String(data)));
|
||||
ws.on('close', () => this.handleDrop('gateway closed'));
|
||||
ws.on('error', (err: unknown) => {
|
||||
this.lastError = err instanceof Error ? err.message : String(err);
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
this.handleDrop(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
private handleFrame(raw: string): void {
|
||||
let frame: GatewayFrame;
|
||||
try {
|
||||
frame = JSON.parse(raw) as GatewayFrame;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (typeof frame.s === 'number') this.seq = frame.s;
|
||||
this.lastActivityAt = Date.now();
|
||||
|
||||
switch (frame.op) {
|
||||
case OP_HELLO: {
|
||||
const interval = (frame.d as { heartbeat_interval?: number })?.heartbeat_interval ?? 41_250;
|
||||
this.startHeartbeat(interval);
|
||||
this.sendFrame({
|
||||
op: OP_IDENTIFY,
|
||||
d: {
|
||||
token: this.token,
|
||||
intents: DISCORD_INTENTS,
|
||||
properties: { os: process.platform, browser: 'waggle-os', device: 'waggle-os' },
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
case OP_HEARTBEAT:
|
||||
this.sendFrame({ op: OP_HEARTBEAT, d: this.seq });
|
||||
break;
|
||||
case OP_HEARTBEAT_ACK:
|
||||
break;
|
||||
case OP_RECONNECT:
|
||||
case OP_INVALID_SESSION:
|
||||
this.handleDrop(frame.op === OP_RECONNECT ? 'server requested reconnect' : 'invalid session');
|
||||
break;
|
||||
case OP_DISPATCH:
|
||||
this.handleDispatch(frame);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private handleDispatch(frame: GatewayFrame): void {
|
||||
if (frame.t === 'READY') {
|
||||
this.botUserId = (frame.d as { user?: { id?: string } })?.user?.id ?? null;
|
||||
this.connected = true;
|
||||
this.lastError = undefined;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
this.log.info('[discord] gateway ready');
|
||||
return;
|
||||
}
|
||||
if (frame.t !== 'MESSAGE_CREATE') return;
|
||||
const m = frame.d as DiscordMessageCreate;
|
||||
if (!m?.content || !m.author) return;
|
||||
if (m.author.bot || m.author.id === this.botUserId) return;
|
||||
const msg: ChannelMessage = {
|
||||
platform: 'discord',
|
||||
chatId: m.channel_id,
|
||||
senderId: m.author.id,
|
||||
senderName: m.author.username,
|
||||
text: m.content,
|
||||
messageId: m.id,
|
||||
};
|
||||
void this.onMessage(msg).catch(e => {
|
||||
this.log.warn(`[discord] inbound handler failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
}
|
||||
|
||||
private startHeartbeat(intervalMs: number): void {
|
||||
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
this.sendFrame({ op: OP_HEARTBEAT, d: this.seq });
|
||||
}, intervalMs);
|
||||
// A desktop process must never be kept alive by a bot heartbeat.
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
|
||||
private sendFrame(frame: GatewayFrame): void {
|
||||
try {
|
||||
this.ws?.send(JSON.stringify(frame));
|
||||
} catch (e: unknown) {
|
||||
this.lastError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
|
||||
private handleDrop(reason: string): void {
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
if (!this.running) return;
|
||||
this.lastError = reason;
|
||||
this.log.warn(`[discord] connection dropped (${reason}) — reconnecting in ${this.backoff}ms`);
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
void this.connect();
|
||||
}, this.backoff);
|
||||
this.reconnectTimer.unref?.();
|
||||
this.backoff = Math.min(this.backoff * 2, this.backoffCap);
|
||||
}
|
||||
|
||||
private teardownSocket(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
try {
|
||||
this.ws?.close();
|
||||
} catch { /* already closed */ }
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
367
packages/server/src/local/channels/manager.ts
Normal file
367
packages/server/src/local/channels/manager.ts
Normal file
@@ -0,0 +1,367 @@
|
||||
/**
|
||||
* ChannelManager — owns adapter lifecycle and the inbound message pipeline.
|
||||
*
|
||||
* Pipeline (every inbound message, all platforms):
|
||||
* 1. per-sender rate limit (token bucket, RATE_LIMIT_MAX/min)
|
||||
* 2. `/pair <code>` — the ONLY verb an unpaired sender can use
|
||||
* 3. deny-by-default: unpaired senders get silence (no bot-presence oracle)
|
||||
* 4. commands: /workspace [id], /status
|
||||
* 5. plain text → loopback /api/chat turn (injection scan, persona,
|
||||
* governance, memory all inherited) → chunked reply
|
||||
*
|
||||
* Secrets stay in the vault (read-only here — routes write them);
|
||||
* allowlist/overrides/config live in PairingStore (channels.json).
|
||||
*/
|
||||
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { PairingStore } from './pairing.js';
|
||||
import { runChannelChatTurn } from './chat-client.js';
|
||||
import { TelegramAdapter } from './telegram-adapter.js';
|
||||
import { DiscordAdapter } from './discord-adapter.js';
|
||||
import { SlackAdapter } from './slack-adapter.js';
|
||||
import { WhatsAppAdapter } from './whatsapp-adapter.js';
|
||||
import type { ChannelAdapter, ChannelAdapterStatus, ChannelMessage, ChannelPlatform } from './types.js';
|
||||
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000;
|
||||
const RATE_LIMIT_MAX = 10;
|
||||
const MESSAGE_DEDUP_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const MESSAGE_DEDUP_MAX = 2_000;
|
||||
|
||||
export const APPROVAL_NEEDED_REPLY =
|
||||
'This request needs a tool approval — open the Waggle app to review and approve it.';
|
||||
export const PAIR_OK_REPLY = 'Paired ✓ — this device can now talk to Waggle. Try /status or just say hi.';
|
||||
export const PAIR_FAIL_REPLY = 'Invalid or expired pairing code. Generate a fresh one in Waggle → Settings → Channels.';
|
||||
|
||||
/** Vault keys per platform (telegram reuses the FR-2 digest key on purpose). */
|
||||
export const CHANNEL_VAULT_KEYS: Record<ChannelPlatform, string[]> = {
|
||||
telegram: ['telegram_bot_token'],
|
||||
discord: ['discord_bot_token'],
|
||||
slack: ['slack_app_token', 'slack_bot_token'],
|
||||
whatsapp: [], // No user-entered token; Baileys state uses an encrypted Vault entry.
|
||||
};
|
||||
|
||||
interface ChannelVault {
|
||||
get(key: string): { value: string } | null | undefined;
|
||||
has(key: string): boolean;
|
||||
set(key: string, value: string, metadata?: Record<string, unknown>): void;
|
||||
delete(key: string): boolean;
|
||||
}
|
||||
|
||||
interface ManagerLog {
|
||||
info: (msg: string) => void;
|
||||
warn: (msg: string) => void;
|
||||
}
|
||||
|
||||
export interface ChannelManagerOptions {
|
||||
dataDir: string;
|
||||
/** Sidecar HTTP port for loopback /api/chat calls. */
|
||||
port: number;
|
||||
/** Sidecar bearer token for protected loopback /api/chat calls. */
|
||||
sessionToken: string;
|
||||
vault: ChannelVault;
|
||||
log: ManagerLog;
|
||||
/** For /workspace validation; absent → any id accepted. */
|
||||
listWorkspaceIds?: () => string[];
|
||||
/** Human-friendly workspace names for /workspace name-or-id resolution. */
|
||||
listWorkspaces?: () => Array<{ id: string; name: string }>;
|
||||
/** Audit sink (pair/unpair events — names match AuditEventType). */
|
||||
onAudit?: (event: {
|
||||
type: 'channel_pair' | 'channel_pair_failed' | 'channel_unpair';
|
||||
platform: ChannelPlatform;
|
||||
detail?: string;
|
||||
}) => void;
|
||||
/** Test seam — replaces the loopback chat call. */
|
||||
chatTurnImpl?: typeof runChannelChatTurn;
|
||||
/** Test seam — replaces adapter construction. */
|
||||
adapterFactory?: (platform: ChannelPlatform, manager: ChannelManager) => ChannelAdapter | null;
|
||||
}
|
||||
|
||||
export class ChannelManager {
|
||||
readonly pairing: PairingStore;
|
||||
|
||||
private readonly opts: ChannelManagerOptions;
|
||||
private readonly adapters = new Map<ChannelPlatform, ChannelAdapter>();
|
||||
private readonly rateBuckets = new Map<string, number[]>();
|
||||
private readonly inboundQueues = new Map<string, Promise<void>>();
|
||||
private readonly seenMessageIds = new Map<string, number>();
|
||||
private readonly chatTurn: typeof runChannelChatTurn;
|
||||
|
||||
constructor(opts: ChannelManagerOptions) {
|
||||
this.opts = opts;
|
||||
this.pairing = new PairingStore(opts.dataDir);
|
||||
this.chatTurn = opts.chatTurnImpl ?? runChannelChatTurn;
|
||||
}
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────────────
|
||||
|
||||
/** Start every platform whose persisted config says enabled. */
|
||||
async startEnabled(): Promise<void> {
|
||||
for (const platform of ['telegram', 'discord', 'slack', 'whatsapp'] as ChannelPlatform[]) {
|
||||
if (this.pairing.getConfig(platform).enabled) {
|
||||
await this.start(platform).catch(e => {
|
||||
this.opts.log.warn(`[channels] ${platform} failed to start: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async start(platform: ChannelPlatform): Promise<ChannelAdapterStatus> {
|
||||
let adapter = this.adapters.get(platform);
|
||||
if (!adapter) {
|
||||
const created = this.createAdapter(platform);
|
||||
if (!created) {
|
||||
throw new Error(`${platform} is not configured (missing credentials or unsupported in this build)`);
|
||||
}
|
||||
adapter = created;
|
||||
this.adapters.set(platform, adapter);
|
||||
}
|
||||
await adapter.start();
|
||||
this.opts.log.info(`[channels] ${platform} started`);
|
||||
return adapter.getStatus();
|
||||
}
|
||||
|
||||
async stop(platform: ChannelPlatform): Promise<void> {
|
||||
const adapter = this.adapters.get(platform);
|
||||
if (!adapter) return;
|
||||
await adapter.stop();
|
||||
this.adapters.delete(platform);
|
||||
this.opts.log.info(`[channels] ${platform} stopped`);
|
||||
}
|
||||
|
||||
async stopAll(): Promise<void> {
|
||||
for (const platform of [...this.adapters.keys()]) {
|
||||
await this.stop(platform).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
/** Restart a running platform so config changes take effect. */
|
||||
async restartIfRunning(platform: ChannelPlatform): Promise<void> {
|
||||
if (this.adapters.has(platform)) {
|
||||
await this.stop(platform);
|
||||
await this.start(platform);
|
||||
}
|
||||
}
|
||||
|
||||
getStatuses(): ChannelAdapterStatus[] {
|
||||
return (['telegram', 'discord', 'slack', 'whatsapp'] as ChannelPlatform[]).map(platform =>
|
||||
this.adapters.get(platform)?.getStatus()
|
||||
?? { platform, running: false, connected: false },
|
||||
);
|
||||
}
|
||||
|
||||
private createAdapter(platform: ChannelPlatform): ChannelAdapter | null {
|
||||
if (this.opts.adapterFactory) return this.opts.adapterFactory(platform, this);
|
||||
const onMessage = (msg: ChannelMessage) => this.handleInbound(msg);
|
||||
if (platform === 'telegram') {
|
||||
const token = this.readVault('telegram_bot_token');
|
||||
if (!token) return null;
|
||||
return new TelegramAdapter({ botToken: token, onMessage, log: this.opts.log });
|
||||
}
|
||||
if (platform === 'discord') {
|
||||
const token = this.readVault('discord_bot_token');
|
||||
if (!token) return null;
|
||||
return new DiscordAdapter({ botToken: token, onMessage, log: this.opts.log });
|
||||
}
|
||||
if (platform === 'slack') {
|
||||
const appToken = this.readVault('slack_app_token');
|
||||
const botToken = this.readVault('slack_bot_token');
|
||||
if (!appToken || !botToken) return null;
|
||||
return new SlackAdapter({ appToken, botToken, onMessage, log: this.opts.log });
|
||||
}
|
||||
if (platform === 'whatsapp') {
|
||||
// No user-entered credential: Baileys pairs via QR and persists all
|
||||
// resulting session state through the encrypted Vault adapter.
|
||||
return new WhatsAppAdapter({
|
||||
dataDir: this.opts.dataDir,
|
||||
vault: this.opts.vault,
|
||||
onMessage,
|
||||
log: this.opts.log,
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private readVault(key: string): string | null {
|
||||
try {
|
||||
return this.opts.vault.get(key)?.value ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Inbound pipeline ─────────────────────────────────────────────────
|
||||
|
||||
async handleInbound(msg: ChannelMessage): Promise<void> {
|
||||
const queueKey = `${msg.platform}:${msg.chatId}`;
|
||||
const previous = this.inboundQueues.get(queueKey) ?? Promise.resolve();
|
||||
const queued = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.processInbound(msg));
|
||||
this.inboundQueues.set(queueKey, queued);
|
||||
try {
|
||||
await queued;
|
||||
} finally {
|
||||
if (this.inboundQueues.get(queueKey) === queued) this.inboundQueues.delete(queueKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async processInbound(msg: ChannelMessage): Promise<void> {
|
||||
if (this.isDuplicate(msg)) return;
|
||||
if (!this.allowRate(`${msg.platform}:${msg.senderId}`)) return;
|
||||
|
||||
const text = msg.text.trim();
|
||||
const adapter = this.adapters.get(msg.platform);
|
||||
const reply = async (t: string) => {
|
||||
await adapter?.send(msg.chatId, t).catch(e => {
|
||||
this.opts.log.warn(`[channels] ${msg.platform} reply failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
};
|
||||
|
||||
// 1. Pairing — the only path open to unknown senders.
|
||||
if (/^\/pair\b/i.test(text)) {
|
||||
const code = text.replace(/^\/pair\b/i, '').trim();
|
||||
const ok = this.pairing.consumeCode(msg.platform, code, msg.senderId, msg.senderName);
|
||||
this.opts.onAudit?.({
|
||||
type: ok ? 'channel_pair' : 'channel_pair_failed',
|
||||
platform: msg.platform,
|
||||
detail: ok ? `sender ${msg.senderId} paired` : `bad code from ${msg.senderId}`,
|
||||
});
|
||||
await reply(ok ? PAIR_OK_REPLY : PAIR_FAIL_REPLY);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Deny-by-default: silence toward unpaired senders.
|
||||
if (!this.pairing.isPaired(msg.platform, msg.senderId)) {
|
||||
this.opts.log.info(`[channels] ignored message from unpaired ${msg.platform} sender ${msg.senderId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Commands.
|
||||
if (/^\/workspace\b/i.test(text)) {
|
||||
await reply(this.handleWorkspaceCommand(msg, text));
|
||||
return;
|
||||
}
|
||||
if (/^\/status\b/i.test(text)) {
|
||||
const status = adapter?.getStatus();
|
||||
const ws = this.resolveWorkspace(msg);
|
||||
await reply(`Waggle connected ✓\nWorkspace: ${this.workspaceLabel(ws)}\nTransport: ${status?.connected ? 'healthy' : 'degraded'}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. Agent turn via loopback chat. channel meta (#17) carries the REAL
|
||||
// platform/chatId (sessionIdFor normalizes chatId irreversibly) so a
|
||||
// create_schedule call inside this turn can deliver ai_task results back
|
||||
// to this chat.
|
||||
const result = await this.chatTurn({
|
||||
port: this.opts.port,
|
||||
sessionToken: this.opts.sessionToken,
|
||||
message: msg.text,
|
||||
workspace: this.resolveWorkspace(msg),
|
||||
session: sessionIdFor(msg),
|
||||
proposeHeld: true,
|
||||
channel: { platform: msg.platform, chatId: msg.chatId },
|
||||
});
|
||||
|
||||
if (result.approvalRequired && !result.content) {
|
||||
await reply(APPROVAL_NEEDED_REPLY);
|
||||
return;
|
||||
}
|
||||
if (result.error && !result.content) {
|
||||
await reply(`Something went wrong: ${result.error}`);
|
||||
return;
|
||||
}
|
||||
if (result.content) {
|
||||
await reply(result.content + (result.approvalRequired ? `\n\n${APPROVAL_NEEDED_REPLY}` : ''));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #17: outbound delivery for scheduler ai_task results. Returns false when
|
||||
* the platform adapter is not running (result then falls back to the
|
||||
* desktop notification only). Adapters chunk long text internally.
|
||||
*/
|
||||
async sendTo(platform: ChannelPlatform, chatId: string, text: string): Promise<boolean> {
|
||||
const adapter = this.adapters.get(platform);
|
||||
if (!adapter) return false;
|
||||
await adapter.send(chatId, text);
|
||||
return true;
|
||||
}
|
||||
|
||||
private handleWorkspaceCommand(msg: ChannelMessage, text: string): string {
|
||||
const arg = text.replace(/^\/workspace\b/i, '').trim();
|
||||
if (!arg) {
|
||||
const current = this.resolveWorkspace(msg);
|
||||
return `Current workspace: ${this.workspaceLabel(current)}\nUse "/workspace <name or id>" to switch this chat, "/workspace default" to clear.`;
|
||||
}
|
||||
if (arg === 'default') {
|
||||
this.pairing.setWorkspaceOverride(msg.platform, msg.chatId, null);
|
||||
const defaultWorkspace = this.pairing.getConfig(msg.platform).defaultWorkspace;
|
||||
return `This chat now uses the channel default workspace (${this.workspaceLabel(defaultWorkspace)}).`;
|
||||
}
|
||||
const workspaces = this.opts.listWorkspaces?.()
|
||||
?? this.opts.listWorkspaceIds?.().map(id => ({ id, name: id }));
|
||||
const normalizedArg = arg.toLocaleLowerCase();
|
||||
const match = workspaces?.find(workspace => workspace.id === arg)
|
||||
?? workspaces?.find(workspace => workspace.name.toLocaleLowerCase() === normalizedArg);
|
||||
if (workspaces && !match) {
|
||||
const available = workspaces.slice(0, 20).map(workspace => workspace.name).join(', ') || '(none)';
|
||||
return `Unknown workspace "${arg}". Available: ${available}`;
|
||||
}
|
||||
const workspaceId = match?.id ?? arg;
|
||||
this.pairing.setWorkspaceOverride(msg.platform, msg.chatId, workspaceId);
|
||||
return `This chat is now routed to workspace "${match?.name ?? workspaceId}".`;
|
||||
}
|
||||
|
||||
private resolveWorkspace(msg: ChannelMessage): string {
|
||||
return this.pairing.getWorkspaceOverride(msg.platform, msg.chatId)
|
||||
?? this.pairing.getConfig(msg.platform).defaultWorkspace;
|
||||
}
|
||||
|
||||
private isDuplicate(msg: ChannelMessage): boolean {
|
||||
if (!msg.messageId) return false;
|
||||
const now = Date.now();
|
||||
const key = `${msg.platform}:${msg.chatId}:${msg.messageId}`;
|
||||
const seenAt = this.seenMessageIds.get(key);
|
||||
if (seenAt !== undefined && now - seenAt < MESSAGE_DEDUP_TTL_MS) return true;
|
||||
if (seenAt !== undefined) this.seenMessageIds.delete(key);
|
||||
|
||||
if (this.seenMessageIds.size >= MESSAGE_DEDUP_MAX) {
|
||||
const cutoff = now - MESSAGE_DEDUP_TTL_MS;
|
||||
for (const [seenKey, seenAt] of this.seenMessageIds) {
|
||||
if (seenAt < cutoff) this.seenMessageIds.delete(seenKey);
|
||||
}
|
||||
while (this.seenMessageIds.size >= MESSAGE_DEDUP_MAX) {
|
||||
const oldest = this.seenMessageIds.keys().next().value as string | undefined;
|
||||
if (!oldest) break;
|
||||
this.seenMessageIds.delete(oldest);
|
||||
}
|
||||
}
|
||||
this.seenMessageIds.set(key, now);
|
||||
return false;
|
||||
}
|
||||
|
||||
private workspaceLabel(workspaceId: string): string {
|
||||
const workspace = this.opts.listWorkspaces?.().find(item => item.id === workspaceId);
|
||||
return workspace ? `${workspace.name} (${workspace.id})` : workspaceId;
|
||||
}
|
||||
|
||||
private allowRate(key: string): boolean {
|
||||
const now = Date.now();
|
||||
const recent = (this.rateBuckets.get(key) ?? []).filter(t => now - t < RATE_LIMIT_WINDOW_MS);
|
||||
if (recent.length >= RATE_LIMIT_MAX) {
|
||||
this.rateBuckets.set(key, recent);
|
||||
return false;
|
||||
}
|
||||
this.rateBuckets.set(key, [...recent, now]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable persisted-session id per IM conversation. Base64url keeps the full
|
||||
* transport id unique while staying inside assertSafeSegment's safe charset.
|
||||
*/
|
||||
export function sessionIdFor(msg: Pick<ChannelMessage, 'platform' | 'chatId'>): string {
|
||||
const encodedChat = Buffer.from(msg.chatId, 'utf8').toString('base64url') || 'empty';
|
||||
return `channel-v2-${msg.platform}-${encodedChat}`;
|
||||
}
|
||||
198
packages/server/src/local/channels/pairing.ts
Normal file
198
packages/server/src/local/channels/pairing.ts
Normal file
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* Pairing + per-chat workspace overrides for IM channels.
|
||||
*
|
||||
* Security model (founder-ratified, see docs/plans/CHANNELS-ARC-2026-07-09.md):
|
||||
* deny-by-default. Unknown senders are ignored entirely; the only way in is a
|
||||
* short-lived single-use pairing code the owner generates in Settings and
|
||||
* sends to the bot from their own IM account. Codes live in memory only —
|
||||
* they are 10-minute artifacts of a local desktop process, not durable state.
|
||||
*
|
||||
* The allowlist and per-chat workspace overrides are NOT secrets, so they
|
||||
* persist to <dataDir>/channels/channels.json (atomic tmp+rename writes).
|
||||
* Bot tokens never touch this file — vault only.
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { ChannelConfig, ChannelPlatform } from './types.js';
|
||||
|
||||
export interface PairedSender {
|
||||
senderId: string;
|
||||
senderName?: string;
|
||||
pairedAt: number;
|
||||
}
|
||||
|
||||
interface ChannelsFile {
|
||||
version: 1;
|
||||
allowlist: Partial<Record<ChannelPlatform, PairedSender[]>>;
|
||||
/** chatId → workspaceId override, per platform. */
|
||||
overrides: Partial<Record<ChannelPlatform, Record<string, string>>>;
|
||||
config: Partial<Record<ChannelPlatform, ChannelConfig>>;
|
||||
}
|
||||
|
||||
const EMPTY_FILE: ChannelsFile = { version: 1, allowlist: {}, overrides: {}, config: {} };
|
||||
|
||||
export const PAIRING_CODE_TTL_MS = 10 * 60 * 1000;
|
||||
// Unambiguous alphabet (no 0/O/1/I) — the user retypes this on a phone.
|
||||
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const CODE_LENGTH = 8;
|
||||
|
||||
interface PendingCode {
|
||||
code: string;
|
||||
platform: ChannelPlatform;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
function generateCodeString(): string {
|
||||
const bytes = crypto.randomBytes(CODE_LENGTH);
|
||||
let out = '';
|
||||
for (let i = 0; i < CODE_LENGTH; i++) {
|
||||
out += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export class PairingStore {
|
||||
private readonly filePath: string;
|
||||
private data: ChannelsFile;
|
||||
private pending: PendingCode[] = [];
|
||||
|
||||
constructor(dataDir: string) {
|
||||
this.filePath = path.join(dataDir, 'channels', 'channels.json');
|
||||
this.data = this.load();
|
||||
}
|
||||
|
||||
private load(): ChannelsFile {
|
||||
try {
|
||||
const raw = fs.readFileSync(this.filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw) as ChannelsFile;
|
||||
if (parsed?.version === 1) {
|
||||
return {
|
||||
version: 1,
|
||||
allowlist: parsed.allowlist ?? {},
|
||||
overrides: parsed.overrides ?? {},
|
||||
config: parsed.config ?? {},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
/* missing or corrupt file → start empty; first save recreates it */
|
||||
}
|
||||
return structuredClone(EMPTY_FILE);
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
const dir = path.dirname(this.filePath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const tmp = `${this.filePath}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(this.data, null, 2), 'utf8');
|
||||
fs.renameSync(tmp, this.filePath);
|
||||
}
|
||||
|
||||
// ── Pairing codes ────────────────────────────────────────────────────
|
||||
|
||||
/** Owner-side: mint a single-use code for one platform. */
|
||||
generateCode(platform: ChannelPlatform): { code: string; expiresAt: number } {
|
||||
this.prunePending();
|
||||
const entry: PendingCode = {
|
||||
code: generateCodeString(),
|
||||
platform,
|
||||
expiresAt: Date.now() + PAIRING_CODE_TTL_MS,
|
||||
};
|
||||
this.pending = [...this.pending, entry];
|
||||
return { code: entry.code, expiresAt: entry.expiresAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sender-side: redeem a code. Consumes it on success. Case-insensitive —
|
||||
* phone keyboards autocapitalize unpredictably.
|
||||
*/
|
||||
consumeCode(
|
||||
platform: ChannelPlatform,
|
||||
rawCode: string,
|
||||
senderId: string,
|
||||
senderName?: string,
|
||||
): boolean {
|
||||
this.prunePending();
|
||||
const code = rawCode.trim().toUpperCase();
|
||||
const match = this.pending.find(p => p.platform === platform && p.code === code);
|
||||
if (!match) return false;
|
||||
this.pending = this.pending.filter(p => p !== match);
|
||||
this.addPaired(platform, senderId, senderName);
|
||||
return true;
|
||||
}
|
||||
|
||||
private prunePending(): void {
|
||||
const now = Date.now();
|
||||
this.pending = this.pending.filter(p => p.expiresAt > now);
|
||||
}
|
||||
|
||||
// ── Allowlist ────────────────────────────────────────────────────────
|
||||
|
||||
isPaired(platform: ChannelPlatform, senderId: string): boolean {
|
||||
return (this.data.allowlist[platform] ?? []).some(s => s.senderId === senderId);
|
||||
}
|
||||
|
||||
private addPaired(platform: ChannelPlatform, senderId: string, senderName?: string): void {
|
||||
if (this.isPaired(platform, senderId)) return;
|
||||
const list = this.data.allowlist[platform] ?? [];
|
||||
this.data = {
|
||||
...this.data,
|
||||
allowlist: {
|
||||
...this.data.allowlist,
|
||||
[platform]: [...list, { senderId, senderName, pairedAt: Date.now() }],
|
||||
},
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
|
||||
unpair(platform: ChannelPlatform, senderId: string): boolean {
|
||||
const list = this.data.allowlist[platform] ?? [];
|
||||
const next = list.filter(s => s.senderId !== senderId);
|
||||
if (next.length === list.length) return false;
|
||||
this.data = {
|
||||
...this.data,
|
||||
allowlist: { ...this.data.allowlist, [platform]: next },
|
||||
};
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
listPaired(): Partial<Record<ChannelPlatform, PairedSender[]>> {
|
||||
return this.data.allowlist;
|
||||
}
|
||||
|
||||
// ── Per-chat workspace overrides ─────────────────────────────────────
|
||||
|
||||
getWorkspaceOverride(platform: ChannelPlatform, chatId: string): string | undefined {
|
||||
return this.data.overrides[platform]?.[chatId];
|
||||
}
|
||||
|
||||
setWorkspaceOverride(platform: ChannelPlatform, chatId: string, workspaceId: string | null): void {
|
||||
const current = { ...(this.data.overrides[platform] ?? {}) };
|
||||
if (workspaceId === null) {
|
||||
delete current[chatId];
|
||||
} else {
|
||||
current[chatId] = workspaceId;
|
||||
}
|
||||
this.data = {
|
||||
...this.data,
|
||||
overrides: { ...this.data.overrides, [platform]: current },
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
|
||||
// ── Per-platform config (non-secret) ─────────────────────────────────
|
||||
|
||||
getConfig(platform: ChannelPlatform): ChannelConfig {
|
||||
return this.data.config[platform] ?? { enabled: false, defaultWorkspace: 'default' };
|
||||
}
|
||||
|
||||
setConfig(platform: ChannelPlatform, config: ChannelConfig): void {
|
||||
this.data = {
|
||||
...this.data,
|
||||
config: { ...this.data.config, [platform]: config },
|
||||
};
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
219
packages/server/src/local/channels/routes.ts
Normal file
219
packages/server/src/local/channels/routes.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* /api/channels — IM channel management surface for Settings UI.
|
||||
*
|
||||
* Everything here is local-app-only (isLocalRequest guard): these routes
|
||||
* mint pairing codes and write bot tokens, i.e. they gate who can talk to
|
||||
* an agent with tools. Secrets go to the vault; reads come back masked.
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { createLogger } from '../logger.js';
|
||||
import { isLocalRequest } from '../origin-guard.js';
|
||||
import { emitAuditEvent } from '../routes/events.js';
|
||||
import { CHANNEL_VAULT_KEYS, ChannelManager } from './manager.js';
|
||||
import { isChannelPlatform, type ChannelPlatform } from './types.js';
|
||||
|
||||
const log = createLogger('channels');
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
channelManager?: ChannelManager;
|
||||
}
|
||||
}
|
||||
|
||||
function requireLocal(request: FastifyRequest, reply: FastifyReply): boolean {
|
||||
if (!isLocalRequest(request)) {
|
||||
void reply.status(403).send({ error: 'Local app only' });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function requireManager(server: FastifyInstance, reply: FastifyReply): ChannelManager | null {
|
||||
const manager = server.channelManager;
|
||||
if (!manager) {
|
||||
void reply.status(503).send({ error: 'Channel manager not initialized' });
|
||||
return null;
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
function parsePlatform(raw: string, reply: FastifyReply): ChannelPlatform | null {
|
||||
if (!isChannelPlatform(raw)) {
|
||||
void reply.status(400).send({ error: `Unknown platform: ${raw}` });
|
||||
return null;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
/** Mask a secret for status display: first 4 chars + length hint. */
|
||||
function mask(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
return `${value.slice(0, 4)}…(${value.length})`;
|
||||
}
|
||||
|
||||
export const channelRoutes: FastifyPluginAsync = async (server) => {
|
||||
// ── Status / listing ─────────────────────────────────────────────────
|
||||
server.get('/api/channels', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const statuses = manager.getStatuses();
|
||||
return statuses.map(s => {
|
||||
const config = manager.pairing.getConfig(s.platform);
|
||||
const secrets: Record<string, string | null> = {};
|
||||
for (const key of CHANNEL_VAULT_KEYS[s.platform]) {
|
||||
let v: string | null = null;
|
||||
try { v = server.vault?.get(key)?.value ?? null; } catch { /* vault locked */ }
|
||||
secrets[key] = mask(v);
|
||||
}
|
||||
return { ...s, config, secrets };
|
||||
});
|
||||
});
|
||||
|
||||
// ── Config (non-secret → store, secrets → vault) ─────────────────────
|
||||
server.post<{
|
||||
Params: { platform: string };
|
||||
Body: {
|
||||
enabled?: boolean;
|
||||
defaultWorkspace?: string;
|
||||
/** Vault writes, keyed by CHANNEL_VAULT_KEYS entries. */
|
||||
secrets?: Record<string, string>;
|
||||
};
|
||||
}>('/api/channels/:platform/config', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const platform = parsePlatform(request.params.platform, reply);
|
||||
if (!platform) return;
|
||||
|
||||
const { enabled, defaultWorkspace, secrets } = request.body ?? {};
|
||||
|
||||
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||
return reply.status(400).send({ error: 'enabled must be a boolean' });
|
||||
}
|
||||
|
||||
let validatedWorkspace = defaultWorkspace;
|
||||
if (defaultWorkspace !== undefined) {
|
||||
if (typeof defaultWorkspace !== 'string' || !defaultWorkspace.trim() || defaultWorkspace.length > 200) {
|
||||
return reply.status(400).send({ error: 'defaultWorkspace must be a valid workspace id' });
|
||||
}
|
||||
validatedWorkspace = defaultWorkspace.trim();
|
||||
const workspaceExists = server.workspaceManager?.list()
|
||||
.some(workspace => workspace.id === validatedWorkspace);
|
||||
if (!workspaceExists) {
|
||||
return reply.status(400).send({ error: `Unknown workspace: ${validatedWorkspace}` });
|
||||
}
|
||||
}
|
||||
|
||||
if (secrets !== undefined && (!secrets || typeof secrets !== 'object' || Array.isArray(secrets))) {
|
||||
return reply.status(400).send({ error: 'secrets must be an object' });
|
||||
}
|
||||
|
||||
const secretEntries = Object.entries(secrets ?? {});
|
||||
if (secretEntries.length > 0) {
|
||||
const allowed = new Set(CHANNEL_VAULT_KEYS[platform]);
|
||||
for (const [key, value] of secretEntries) {
|
||||
if (!allowed.has(key)) {
|
||||
return reply.status(400).send({ error: `Unknown secret key for ${platform}: ${key}` });
|
||||
}
|
||||
if (typeof value !== 'string' || value.length === 0 || value.length > 512) {
|
||||
return reply.status(400).send({ error: `Invalid value for ${key}` });
|
||||
}
|
||||
}
|
||||
if (!server.vault) return reply.status(503).send({ error: 'Vault is not available' });
|
||||
}
|
||||
|
||||
for (const [key, value] of secretEntries) {
|
||||
server.vault!.set(key, value, { credentialType: 'api_key' });
|
||||
}
|
||||
|
||||
const current = manager.pairing.getConfig(platform);
|
||||
const next = {
|
||||
enabled: enabled ?? current.enabled,
|
||||
defaultWorkspace: validatedWorkspace ?? current.defaultWorkspace,
|
||||
};
|
||||
manager.pairing.setConfig(platform, next);
|
||||
log.info(`[channels] ${platform} config updated (enabled=${next.enabled})`);
|
||||
emitAuditEvent(server, {
|
||||
workspaceId: next.defaultWorkspace,
|
||||
eventType: 'channel_config_change',
|
||||
input: JSON.stringify({
|
||||
platform,
|
||||
enabled: next.enabled,
|
||||
defaultWorkspace: next.defaultWorkspace,
|
||||
secretKeysUpdated: secretEntries.map(([key]) => key),
|
||||
}),
|
||||
});
|
||||
|
||||
await manager.restartIfRunning(platform).catch(e => {
|
||||
log.warn(`[channels] ${platform} restart after config change failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
return { ok: true, config: next };
|
||||
});
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────────────
|
||||
server.post<{ Params: { platform: string } }>('/api/channels/:platform/start', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const platform = parsePlatform(request.params.platform, reply);
|
||||
if (!platform) return;
|
||||
try {
|
||||
const status = await manager.start(platform);
|
||||
return { ok: true, status };
|
||||
} catch (e: unknown) {
|
||||
return reply.status(400).send({ ok: false, error: e instanceof Error ? e.message : 'start failed' });
|
||||
}
|
||||
});
|
||||
|
||||
server.post<{ Params: { platform: string } }>('/api/channels/:platform/stop', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const platform = parsePlatform(request.params.platform, reply);
|
||||
if (!platform) return;
|
||||
await manager.stop(platform);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// ── Pairing ──────────────────────────────────────────────────────────
|
||||
server.post<{ Body: { platform?: string } }>('/api/channels/pairing-code', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const platform = parsePlatform(request.body?.platform ?? '', reply);
|
||||
if (!platform) return;
|
||||
const { code, expiresAt } = manager.pairing.generateCode(platform);
|
||||
log.info(`[channels] pairing code minted for ${platform}`);
|
||||
return { code, expiresAt };
|
||||
});
|
||||
|
||||
server.get('/api/channels/pairing', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
return manager.pairing.listPaired();
|
||||
});
|
||||
|
||||
server.delete<{
|
||||
Body: { platform?: string; senderId?: string };
|
||||
}>('/api/channels/pairing', async (request, reply) => {
|
||||
if (!requireLocal(request, reply)) return;
|
||||
const manager = requireManager(server, reply);
|
||||
if (!manager) return;
|
||||
const platform = parsePlatform(request.body?.platform ?? '', reply);
|
||||
if (!platform) return;
|
||||
const senderId = request.body?.senderId;
|
||||
if (!senderId) return reply.status(400).send({ error: 'senderId is required' });
|
||||
const removed = manager.pairing.unpair(platform, senderId);
|
||||
if (removed) {
|
||||
emitAuditEvent(server, {
|
||||
workspaceId: 'default',
|
||||
eventType: 'channel_unpair',
|
||||
input: JSON.stringify({ platform, senderId }),
|
||||
});
|
||||
}
|
||||
return { ok: removed };
|
||||
});
|
||||
};
|
||||
231
packages/server/src/local/channels/slack-adapter.ts
Normal file
231
packages/server/src/local/channels/slack-adapter.ts
Normal file
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Slack channel adapter — Socket Mode, no @slack/bolt.
|
||||
*
|
||||
* NAT-friendly: apps.connections.open (app-level xapp- token) hands us a
|
||||
* wss URL we dial OUT to; no public Request URL needed. Events arrive as
|
||||
* envelopes that MUST be acked by envelope_id or Slack redelivers; sends go
|
||||
* through chat.postMessage with the separate bot xoxb- token.
|
||||
*
|
||||
* Slack rotates socket connections routinely (`disconnect` envelope with
|
||||
* reason refresh_requested) — treat every drop as a normal reconnect, not
|
||||
* an error. Fixed API host (slack.com) — no SSRF surface.
|
||||
*
|
||||
* Setup requirements (surfaced in Settings UI copy): Socket Mode enabled,
|
||||
* app token with connections:write, bot token with chat:write, and the
|
||||
* message.im / message.channels event subscriptions.
|
||||
*/
|
||||
|
||||
import WebSocket from 'ws';
|
||||
import type {
|
||||
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler, WsFactory, WsLike,
|
||||
} from './types.js';
|
||||
import { chunkText } from './types.js';
|
||||
|
||||
const SLACK_API = 'https://slack.com/api';
|
||||
/** Slack truncates at 40k but recommends ≤4k for message text. */
|
||||
export const SLACK_MAX_TEXT = 4000;
|
||||
const BACKOFF_START_MS = 1_000;
|
||||
const BACKOFF_CAP_MS = 60_000;
|
||||
|
||||
interface SlackEnvelope {
|
||||
envelope_id?: string;
|
||||
type?: string; // 'hello' | 'disconnect' | 'events_api' | …
|
||||
payload?: {
|
||||
event?: {
|
||||
type?: string;
|
||||
subtype?: string;
|
||||
bot_id?: string;
|
||||
user?: string;
|
||||
channel?: string;
|
||||
text?: string;
|
||||
ts?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface SlackAdapterOptions {
|
||||
/** App-level token (xapp-…) — Socket Mode connections. */
|
||||
appToken: string;
|
||||
/** Bot token (xoxb-…) — chat.postMessage sends. */
|
||||
botToken: string;
|
||||
onMessage: InboundHandler;
|
||||
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
||||
/** Test seams. */
|
||||
fetchImpl?: typeof fetch;
|
||||
wsFactory?: WsFactory;
|
||||
backoffCapMs?: number;
|
||||
}
|
||||
|
||||
export class SlackAdapter implements ChannelAdapter {
|
||||
readonly platform = 'slack' as const;
|
||||
|
||||
private readonly appToken: string;
|
||||
private readonly botToken: string;
|
||||
private readonly onMessage: InboundHandler;
|
||||
private readonly log: SlackAdapterOptions['log'];
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly wsFactory: WsFactory;
|
||||
private readonly backoffCap: number;
|
||||
|
||||
private running = false;
|
||||
private connected = false;
|
||||
private lastError: string | undefined;
|
||||
private lastActivityAt: number | undefined;
|
||||
private ws: WsLike | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private backoff: number;
|
||||
|
||||
constructor(opts: SlackAdapterOptions) {
|
||||
this.appToken = opts.appToken;
|
||||
this.botToken = opts.botToken;
|
||||
this.onMessage = opts.onMessage;
|
||||
this.log = opts.log;
|
||||
this.fetchImpl = opts.fetchImpl ?? fetch;
|
||||
this.wsFactory = opts.wsFactory ?? ((url: string) => new WebSocket(url) as unknown as WsLike);
|
||||
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.lastError = undefined;
|
||||
await this.connect();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.running = false;
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
getStatus(): ChannelAdapterStatus {
|
||||
return {
|
||||
platform: this.platform,
|
||||
running: this.running,
|
||||
connected: this.connected,
|
||||
lastError: this.lastError,
|
||||
lastActivityAt: this.lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
async send(chatId: string, text: string): Promise<void> {
|
||||
for (const chunk of chunkText(text, SLACK_MAX_TEXT)) {
|
||||
const r = await this.fetchImpl(`${SLACK_API}/chat.postMessage`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
Authorization: `Bearer ${this.botToken}`,
|
||||
},
|
||||
body: JSON.stringify({ channel: chatId, text: chunk }),
|
||||
});
|
||||
const body = await r.json() as { ok: boolean; error?: string };
|
||||
if (!body.ok) {
|
||||
throw new Error(`Slack send failed: ${body.error ?? `HTTP ${r.status}`}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Socket Mode lifecycle ────────────────────────────────────────────
|
||||
|
||||
private async connect(): Promise<void> {
|
||||
try {
|
||||
const r = await this.fetchImpl(`${SLACK_API}/apps.connections.open`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${this.appToken}` },
|
||||
});
|
||||
const body = await r.json() as { ok: boolean; url?: string; error?: string };
|
||||
if (!body.ok || !body.url) {
|
||||
throw new Error(`apps.connections.open failed: ${body.error ?? `HTTP ${r.status}`}`);
|
||||
}
|
||||
|
||||
const ws = this.wsFactory(body.url);
|
||||
this.ws = ws;
|
||||
ws.on('message', (data: unknown) => this.handleEnvelope(String(data)));
|
||||
ws.on('close', () => this.handleDrop('socket closed'));
|
||||
ws.on('error', (err: unknown) => {
|
||||
this.lastError = err instanceof Error ? err.message : String(err);
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
this.handleDrop(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
private handleEnvelope(raw: string): void {
|
||||
let envelope: SlackEnvelope;
|
||||
try {
|
||||
envelope = JSON.parse(raw) as SlackEnvelope;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
this.lastActivityAt = Date.now();
|
||||
|
||||
// Ack FIRST — Slack redelivers unacked envelopes, which would double-run
|
||||
// agent turns. An ack for a turn we then fail is the safer failure mode.
|
||||
if (envelope.envelope_id) {
|
||||
this.sendRaw({ envelope_id: envelope.envelope_id });
|
||||
}
|
||||
|
||||
switch (envelope.type) {
|
||||
case 'hello':
|
||||
this.connected = true;
|
||||
this.lastError = undefined;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
this.log.info('[slack] socket mode connected');
|
||||
return;
|
||||
case 'disconnect':
|
||||
// Routine link refresh — reconnect quietly.
|
||||
this.handleDrop('slack requested reconnect');
|
||||
return;
|
||||
case 'events_api':
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
const event = envelope.payload?.event;
|
||||
if (event?.type !== 'message') return;
|
||||
// Skip edits/joins/etc. (subtype), bot echoes, and system messages.
|
||||
if (event.subtype || event.bot_id || !event.user || !event.channel || !event.text) return;
|
||||
|
||||
const msg: ChannelMessage = {
|
||||
platform: 'slack',
|
||||
chatId: event.channel,
|
||||
senderId: event.user,
|
||||
text: event.text,
|
||||
messageId: event.ts,
|
||||
};
|
||||
void this.onMessage(msg).catch(e => {
|
||||
this.log.warn(`[slack] inbound handler failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
}
|
||||
|
||||
private sendRaw(payload: unknown): void {
|
||||
try {
|
||||
this.ws?.send(JSON.stringify(payload));
|
||||
} catch (e: unknown) {
|
||||
this.lastError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
|
||||
private handleDrop(reason: string): void {
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
if (!this.running) return;
|
||||
this.lastError = reason;
|
||||
this.log.warn(`[slack] connection dropped (${reason}) — reconnecting in ${this.backoff}ms`);
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
void this.connect();
|
||||
}, this.backoff);
|
||||
this.reconnectTimer.unref?.();
|
||||
this.backoff = Math.min(this.backoff * 2, this.backoffCap);
|
||||
}
|
||||
|
||||
private teardownSocket(): void {
|
||||
try {
|
||||
this.ws?.close();
|
||||
} catch { /* already closed */ }
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
176
packages/server/src/local/channels/telegram-adapter.ts
Normal file
176
packages/server/src/local/channels/telegram-adapter.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Telegram channel adapter — long-polling getUpdates.
|
||||
*
|
||||
* NAT-friendly by construction: the desktop reaches OUT to api.telegram.org
|
||||
* with a 50s long-poll; no webhook, no public endpoint, no tunnel. The API
|
||||
* host is hard-coded (token interpolated into the path of a fixed host), so
|
||||
* there is no SSRF surface — same posture as routes/telegram.ts, whose
|
||||
* one-way digest push this adapter complements (and shares the vault token
|
||||
* with).
|
||||
*/
|
||||
|
||||
import type {
|
||||
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler,
|
||||
} from './types.js';
|
||||
import { chunkText } from './types.js';
|
||||
|
||||
const TELEGRAM_API_HOST = 'https://api.telegram.org';
|
||||
export const TELEGRAM_MAX_TEXT = 4096;
|
||||
const POLL_TIMEOUT_S = 50;
|
||||
const BACKOFF_START_MS = 1_000;
|
||||
const BACKOFF_CAP_MS = 30_000;
|
||||
|
||||
interface TelegramUpdate {
|
||||
update_id: number;
|
||||
message?: {
|
||||
message_id: number;
|
||||
text?: string;
|
||||
chat: { id: number };
|
||||
from?: { id: number; username?: string; first_name?: string };
|
||||
};
|
||||
}
|
||||
|
||||
interface TelegramApiResponse<T> {
|
||||
ok: boolean;
|
||||
description?: string;
|
||||
result?: T;
|
||||
}
|
||||
|
||||
export interface TelegramAdapterOptions {
|
||||
botToken: string;
|
||||
onMessage: InboundHandler;
|
||||
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
||||
/** Test seam — overrides global fetch. */
|
||||
fetchImpl?: typeof fetch;
|
||||
}
|
||||
|
||||
export class TelegramAdapter implements ChannelAdapter {
|
||||
readonly platform = 'telegram' as const;
|
||||
|
||||
private readonly token: string;
|
||||
private readonly onMessage: InboundHandler;
|
||||
private readonly log: TelegramAdapterOptions['log'];
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
private running = false;
|
||||
private connected = false;
|
||||
private lastError: string | undefined;
|
||||
private lastActivityAt: number | undefined;
|
||||
private offset = 0;
|
||||
private abort: AbortController | null = null;
|
||||
private loopPromise: Promise<void> | null = null;
|
||||
|
||||
constructor(opts: TelegramAdapterOptions) {
|
||||
this.token = opts.botToken;
|
||||
this.onMessage = opts.onMessage;
|
||||
this.log = opts.log;
|
||||
this.fetchImpl = opts.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.lastError = undefined;
|
||||
this.loopPromise = this.pollLoop();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.running = false;
|
||||
this.abort?.abort();
|
||||
// Wait for the in-flight poll to unwind so stop() → start() can't race
|
||||
// two loops onto one getUpdates offset.
|
||||
await this.loopPromise?.catch(() => undefined);
|
||||
this.loopPromise = null;
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
getStatus(): ChannelAdapterStatus {
|
||||
return {
|
||||
platform: this.platform,
|
||||
running: this.running,
|
||||
connected: this.connected,
|
||||
lastError: this.lastError,
|
||||
lastActivityAt: this.lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
async send(chatId: string, text: string): Promise<void> {
|
||||
for (const chunk of chunkText(text, TELEGRAM_MAX_TEXT)) {
|
||||
const res = await this.api<{ message_id: number }>('sendMessage', {
|
||||
chat_id: chatId,
|
||||
text: chunk,
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Telegram sendMessage failed: ${res.description ?? 'unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async pollLoop(): Promise<void> {
|
||||
let backoff = BACKOFF_START_MS;
|
||||
while (this.running) {
|
||||
try {
|
||||
this.abort = new AbortController();
|
||||
const res = await this.api<TelegramUpdate[]>('getUpdates', {
|
||||
timeout: POLL_TIMEOUT_S,
|
||||
offset: this.offset,
|
||||
allowed_updates: ['message'],
|
||||
}, this.abort.signal, (POLL_TIMEOUT_S + 10) * 1000);
|
||||
|
||||
if (!res.ok) throw new Error(res.description ?? 'getUpdates failed');
|
||||
this.connected = true;
|
||||
this.lastError = undefined;
|
||||
this.lastActivityAt = Date.now();
|
||||
backoff = BACKOFF_START_MS;
|
||||
|
||||
for (const update of res.result ?? []) {
|
||||
this.offset = Math.max(this.offset, update.update_id + 1);
|
||||
const msg = this.normalize(update);
|
||||
if (!msg) continue;
|
||||
// Inbound handling must never kill the poll loop.
|
||||
await this.onMessage(msg).catch(e => {
|
||||
this.log.warn(`[telegram] inbound handler failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
if (!this.running) break; // stop() aborted the in-flight poll
|
||||
this.connected = false;
|
||||
this.lastError = e instanceof Error ? e.message : String(e);
|
||||
this.log.warn(`[telegram] poll error, backing off ${backoff}ms: ${this.lastError}`);
|
||||
await new Promise(r => setTimeout(r, backoff));
|
||||
backoff = Math.min(backoff * 2, BACKOFF_CAP_MS);
|
||||
}
|
||||
}
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
private normalize(update: TelegramUpdate): ChannelMessage | null {
|
||||
const m = update.message;
|
||||
if (!m?.text || !m.from) return null;
|
||||
return {
|
||||
platform: 'telegram',
|
||||
chatId: String(m.chat.id),
|
||||
senderId: String(m.from.id),
|
||||
senderName: m.from.username ?? m.from.first_name,
|
||||
text: m.text,
|
||||
messageId: String(m.message_id),
|
||||
};
|
||||
}
|
||||
|
||||
private async api<T>(
|
||||
method: string,
|
||||
body: Record<string, unknown>,
|
||||
signal?: AbortSignal,
|
||||
timeoutMs = 30_000,
|
||||
): Promise<TelegramApiResponse<T>> {
|
||||
const url = `${TELEGRAM_API_HOST}/bot${encodeURIComponent(this.token)}/${method}`;
|
||||
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
||||
const r = await this.fetchImpl(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
signal: signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal,
|
||||
});
|
||||
return await r.json() as TelegramApiResponse<T>;
|
||||
}
|
||||
}
|
||||
91
packages/server/src/local/channels/types.ts
Normal file
91
packages/server/src/local/channels/types.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* IM channel adapter contracts — Slack / Telegram / WhatsApp / Discord.
|
||||
*
|
||||
* A ChannelAdapter owns exactly one platform transport (long-poll, gateway
|
||||
* WebSocket, Socket Mode, Baileys). It normalizes inbound platform payloads
|
||||
* into ChannelMessage and hands them to the ChannelManager's inbound
|
||||
* pipeline; it knows nothing about pairing, workspaces, or the agent loop.
|
||||
* See docs/plans/CHANNELS-ARC-2026-07-09.md for the arc spec.
|
||||
*/
|
||||
|
||||
export type ChannelPlatform = 'telegram' | 'discord' | 'slack' | 'whatsapp';
|
||||
|
||||
export const CHANNEL_PLATFORMS: readonly ChannelPlatform[] = [
|
||||
'telegram', 'discord', 'slack', 'whatsapp',
|
||||
] as const;
|
||||
|
||||
export function isChannelPlatform(v: string): v is ChannelPlatform {
|
||||
return (CHANNEL_PLATFORMS as readonly string[]).includes(v);
|
||||
}
|
||||
|
||||
/** One normalized inbound message from any platform. */
|
||||
export interface ChannelMessage {
|
||||
platform: ChannelPlatform;
|
||||
/** Platform-native conversation id (Telegram chat_id, Discord channel id…). */
|
||||
chatId: string;
|
||||
/** Platform-native sender id — the pairing/allowlist key. */
|
||||
senderId: string;
|
||||
senderName?: string;
|
||||
text: string;
|
||||
messageId?: string;
|
||||
}
|
||||
|
||||
export interface ChannelAdapterStatus {
|
||||
platform: ChannelPlatform;
|
||||
running: boolean;
|
||||
/** Transport-level health (polling loop alive / WS open). */
|
||||
connected: boolean;
|
||||
lastError?: string;
|
||||
/** Epoch ms of the last successful transport activity. */
|
||||
lastActivityAt?: number;
|
||||
}
|
||||
|
||||
/** Inbound sink the manager injects into every adapter. */
|
||||
export type InboundHandler = (msg: ChannelMessage) => Promise<void>;
|
||||
|
||||
export interface ChannelAdapter {
|
||||
readonly platform: ChannelPlatform;
|
||||
start(): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
getStatus(): ChannelAdapterStatus;
|
||||
/** Send plain text to a conversation. Implementations chunk to platform limits. */
|
||||
send(chatId: string, text: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Non-secret per-platform config persisted in channels.json (secrets → vault). */
|
||||
export interface ChannelConfig {
|
||||
enabled: boolean;
|
||||
/** Workspace id handling messages with no per-chat override. */
|
||||
defaultWorkspace: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal structural WebSocket contract shared by the Discord gateway and
|
||||
* Slack Socket Mode adapters. `ws`'s WebSocket satisfies it; tests inject
|
||||
* scripted fakes through the adapters' wsFactory seam.
|
||||
*/
|
||||
export interface WsLike {
|
||||
on(event: 'open' | 'message' | 'close' | 'error', cb: (...args: unknown[]) => void): void;
|
||||
send(data: string): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export type WsFactory = (url: string) => WsLike;
|
||||
|
||||
/** Split a reply into ≤limit chunks, preferring paragraph then line breaks. */
|
||||
export function chunkText(text: string, limit: number): string[] {
|
||||
if (text.length <= limit) return [text];
|
||||
const chunks: string[] = [];
|
||||
let rest = text;
|
||||
while (rest.length > limit) {
|
||||
const slice = rest.slice(0, limit);
|
||||
// Prefer the last blank line, then last newline, then hard cut.
|
||||
let cut = slice.lastIndexOf('\n\n');
|
||||
if (cut < limit * 0.5) cut = slice.lastIndexOf('\n');
|
||||
if (cut < limit * 0.5) cut = limit;
|
||||
chunks.push(rest.slice(0, cut).trimEnd());
|
||||
rest = rest.slice(cut).trimStart();
|
||||
}
|
||||
if (rest.length > 0) chunks.push(rest);
|
||||
return chunks;
|
||||
}
|
||||
479
packages/server/src/local/channels/whatsapp-adapter.ts
Normal file
479
packages/server/src/local/channels/whatsapp-adapter.ts
Normal file
@@ -0,0 +1,479 @@
|
||||
/**
|
||||
* WhatsApp channel adapter — Baileys (unofficial multi-device WebSocket).
|
||||
*
|
||||
* FOUNDER-ACCEPTED RISK (2026-07-09, docs/plans/CHANNELS-ARC-2026-07-09.md):
|
||||
* Baileys is an UNOFFICIAL client that violates WhatsApp's ToS; accounts can
|
||||
* be banned. The Settings UI must show a prominent ban-risk disclosure and
|
||||
* recommend a secondary number. Do not soften or remove that copy.
|
||||
*
|
||||
* NAT-friendly: Baileys dials OUT to WhatsApp's multi-device WS. Pairing is
|
||||
* QR-scan (like WhatsApp Web): the latest QR string is held in memory and
|
||||
* surfaced through getStatus().qr → /api/channels for the UI to render.
|
||||
* Credentials persist as one encrypted Vault entry so pairing survives
|
||||
* restarts without leaving Baileys session keys as plaintext JSON. Existing
|
||||
* <dataDir>/channels/whatsapp-auth data is migrated once and then removed.
|
||||
* DisconnectReason.loggedOut wipes the Vault entry (re-pair needed).
|
||||
*
|
||||
* Baileys is loaded via dynamic import so the sidecar boots without paying
|
||||
* its (heavy: libsignal/protobuf) module cost until WhatsApp is enabled.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type {
|
||||
AuthenticationState, SignalDataSet, SignalDataTypeMap,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import type {
|
||||
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler,
|
||||
} from './types.js';
|
||||
import { chunkText } from './types.js';
|
||||
|
||||
/** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */
|
||||
export const WHATSAPP_MAX_TEXT = 4000;
|
||||
export const WHATSAPP_AUTH_VAULT_KEY = 'channel:whatsapp:auth-state';
|
||||
const BACKOFF_START_MS = 2_000;
|
||||
const BACKOFF_CAP_MS = 60_000;
|
||||
|
||||
export interface WhatsAppAuthVault {
|
||||
get(key: string): { value: string } | null | undefined;
|
||||
has(key: string): boolean;
|
||||
set(key: string, value: string, metadata?: Record<string, unknown>): void;
|
||||
delete(key: string): boolean;
|
||||
}
|
||||
|
||||
interface StoredWhatsAppAuth {
|
||||
version: 1;
|
||||
creds: AuthenticationState['creds'];
|
||||
keys: Array<[string, unknown]>;
|
||||
}
|
||||
|
||||
type BaileysModule = typeof import('@whiskeysockets/baileys');
|
||||
|
||||
const SIGNAL_KEY_TYPES: Array<keyof SignalDataTypeMap> = [
|
||||
'app-state-sync-version',
|
||||
'app-state-sync-key',
|
||||
'sender-key-memory',
|
||||
'sender-key',
|
||||
'identity-key',
|
||||
'lid-mapping',
|
||||
'device-list',
|
||||
'pre-key',
|
||||
'session',
|
||||
'tctoken',
|
||||
];
|
||||
|
||||
function fixLegacyFileName(value: string): string {
|
||||
return value.replace(/\//g, '__').replace(/:/g, '-');
|
||||
}
|
||||
|
||||
function signalStoreKey(type: keyof SignalDataTypeMap, id: string): string {
|
||||
return `${type}:${fixLegacyFileName(id)}`;
|
||||
}
|
||||
|
||||
function parseStoredAuth(raw: string, baileys: BaileysModule): StoredWhatsAppAuth | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw, baileys.BufferJSON.reviver) as Partial<StoredWhatsAppAuth>;
|
||||
if (parsed.version !== 1 || !parsed.creds || !Array.isArray(parsed.keys)) return null;
|
||||
const keys = parsed.keys.filter((entry): entry is [string, unknown] => (
|
||||
Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'
|
||||
));
|
||||
return { version: 1, creds: parsed.creds, keys };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readLegacyAuth(authDir: string, baileys: BaileysModule): StoredWhatsAppAuth | null {
|
||||
const credsPath = path.join(authDir, 'creds.json');
|
||||
if (!fs.existsSync(credsPath)) return null;
|
||||
try {
|
||||
const creds = JSON.parse(
|
||||
fs.readFileSync(credsPath, 'utf8'),
|
||||
baileys.BufferJSON.reviver,
|
||||
) as AuthenticationState['creds'];
|
||||
const keys: Array<[string, unknown]> = [];
|
||||
for (const file of fs.readdirSync(authDir)) {
|
||||
if (file === 'creds.json' || !file.endsWith('.json')) continue;
|
||||
const base = file.slice(0, -'.json'.length);
|
||||
const type = SIGNAL_KEY_TYPES.find(candidate => base.startsWith(`${candidate}-`));
|
||||
if (!type) continue;
|
||||
const id = base.slice(type.length + 1);
|
||||
const value = JSON.parse(
|
||||
fs.readFileSync(path.join(authDir, file), 'utf8'),
|
||||
baileys.BufferJSON.reviver,
|
||||
) as unknown;
|
||||
keys.push([`${type}:${id}`, value]);
|
||||
}
|
||||
return { version: 1, creds, keys };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Baileys AuthenticationState backed entirely by Waggle's encrypted Vault. */
|
||||
export async function useVaultWhatsAppAuthState(
|
||||
vault: WhatsAppAuthVault,
|
||||
legacyAuthDir: string,
|
||||
): Promise<{ state: AuthenticationState; saveCreds: () => void }> {
|
||||
const baileys = await import('@whiskeysockets/baileys');
|
||||
const storedExists = vault.has(WHATSAPP_AUTH_VAULT_KEY);
|
||||
const storedEntry = vault.get(WHATSAPP_AUTH_VAULT_KEY);
|
||||
const stored = storedEntry ? parseStoredAuth(storedEntry.value, baileys) : null;
|
||||
if (storedExists && !stored) {
|
||||
throw new Error('Encrypted WhatsApp auth state is unreadable; pairing state was left untouched');
|
||||
}
|
||||
const legacyExists = fs.existsSync(path.join(legacyAuthDir, 'creds.json'));
|
||||
const legacy = stored ? null : readLegacyAuth(legacyAuthDir, baileys);
|
||||
if (!stored && legacyExists && !legacy) {
|
||||
throw new Error('Legacy WhatsApp auth state could not be migrated; plaintext state was left untouched');
|
||||
}
|
||||
const creds = stored?.creds ?? legacy?.creds ?? baileys.initAuthCreds();
|
||||
const keyStore = new Map<string, unknown>(stored?.keys ?? legacy?.keys ?? []);
|
||||
|
||||
const persist = (): void => {
|
||||
const payload: StoredWhatsAppAuth = {
|
||||
version: 1,
|
||||
creds,
|
||||
keys: [...keyStore.entries()],
|
||||
};
|
||||
vault.set(
|
||||
WHATSAPP_AUTH_VAULT_KEY,
|
||||
JSON.stringify(payload, baileys.BufferJSON.replacer),
|
||||
{ kind: 'whatsapp-auth-state', encryptedAtRest: true },
|
||||
);
|
||||
};
|
||||
|
||||
if (legacy) {
|
||||
// Delete plaintext only after the encrypted write succeeds.
|
||||
persist();
|
||||
fs.rmSync(legacyAuthDir, { recursive: true, force: true });
|
||||
} else if (stored && fs.existsSync(legacyAuthDir)) {
|
||||
// Vault is authoritative; remove any stale plaintext residue.
|
||||
fs.rmSync(legacyAuthDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const state: AuthenticationState = {
|
||||
creds,
|
||||
keys: {
|
||||
get: async <T extends keyof SignalDataTypeMap>(type: T, ids: string[]) => {
|
||||
const result = {} as Record<string, SignalDataTypeMap[T]>;
|
||||
for (const id of ids) {
|
||||
let value = keyStore.get(signalStoreKey(type, id));
|
||||
if (type === 'app-state-sync-key' && value) {
|
||||
value = baileys.proto.Message.AppStateSyncKeyData.fromObject(value as object);
|
||||
}
|
||||
result[id] = value as SignalDataTypeMap[T];
|
||||
}
|
||||
return result;
|
||||
},
|
||||
set: async (data: SignalDataSet) => {
|
||||
const categories = data as Record<string, Record<string, unknown | null> | undefined>;
|
||||
for (const [category, values] of Object.entries(categories)) {
|
||||
if (!values) continue;
|
||||
for (const [id, value] of Object.entries(values)) {
|
||||
const key = signalStoreKey(category as keyof SignalDataTypeMap, id);
|
||||
if (value === null) keyStore.delete(key);
|
||||
else keyStore.set(key, value);
|
||||
}
|
||||
}
|
||||
persist();
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return { state, saveCreds: persist };
|
||||
}
|
||||
|
||||
// This is a server-side state loader, not a React Hook. Use a non-hook alias
|
||||
// internally so the repo-wide React lint rule can distinguish the call site.
|
||||
const loadVaultWhatsAppAuthState = useVaultWhatsAppAuthState;
|
||||
|
||||
/** Status payload extended with the pairing QR (rendered by Settings UI). */
|
||||
export interface WhatsAppStatus extends ChannelAdapterStatus {
|
||||
qr?: string;
|
||||
/** True when registered auth credentials exist in the encrypted Vault. */
|
||||
paired?: boolean;
|
||||
}
|
||||
|
||||
// ── Minimal structural contracts over Baileys (test seam) ──────────────
|
||||
|
||||
interface BaileysEventMap {
|
||||
'connection.update': {
|
||||
connection?: 'close' | 'connecting' | 'open';
|
||||
qr?: string;
|
||||
lastDisconnect?: { error?: unknown };
|
||||
};
|
||||
'messages.upsert': {
|
||||
type: string;
|
||||
messages: Array<{
|
||||
key: { remoteJid?: string | null; fromMe?: boolean | null; id?: string | null; participant?: string | null };
|
||||
pushName?: string | null;
|
||||
message?: {
|
||||
conversation?: string | null;
|
||||
extendedTextMessage?: { text?: string | null } | null;
|
||||
} | null;
|
||||
}>;
|
||||
};
|
||||
'creds.update': unknown;
|
||||
}
|
||||
|
||||
export interface WaSocketLike {
|
||||
ev: {
|
||||
on<E extends keyof BaileysEventMap>(event: E, cb: (arg: BaileysEventMap[E]) => void): void;
|
||||
};
|
||||
sendMessage(jid: string, content: { text: string }): Promise<unknown>;
|
||||
end?(err?: Error): void;
|
||||
}
|
||||
|
||||
export type WaSocketFactory = (
|
||||
vault: WhatsAppAuthVault,
|
||||
legacyAuthDir: string,
|
||||
onAuthError: (error: unknown) => void,
|
||||
) => Promise<WaSocketLike>;
|
||||
|
||||
interface BaileysLogger {
|
||||
level: string;
|
||||
child(fields: Record<string, unknown>): BaileysLogger;
|
||||
trace(value: unknown, message?: string): void;
|
||||
debug(value: unknown, message?: string): void;
|
||||
info(value: unknown, message?: string): void;
|
||||
warn(value: unknown, message?: string): void;
|
||||
error(value: unknown, message?: string): void;
|
||||
}
|
||||
|
||||
const silentBaileysLogger: BaileysLogger = {
|
||||
level: 'silent',
|
||||
child: () => silentBaileysLogger,
|
||||
trace: () => undefined,
|
||||
debug: () => undefined,
|
||||
info: () => undefined,
|
||||
warn: () => undefined,
|
||||
error: () => undefined,
|
||||
};
|
||||
|
||||
/** Production factory — real Baileys, dynamically imported. */
|
||||
async function defaultWaSocketFactory(
|
||||
vault: WhatsAppAuthVault,
|
||||
legacyAuthDir: string,
|
||||
onAuthError: (error: unknown) => void,
|
||||
): Promise<WaSocketLike> {
|
||||
const baileys = await import('@whiskeysockets/baileys');
|
||||
const { state, saveCreds } = await loadVaultWhatsAppAuthState(vault, legacyAuthDir);
|
||||
const sock = baileys.makeWASocket({
|
||||
auth: state,
|
||||
logger: silentBaileysLogger,
|
||||
// No terminal QR — the Settings UI renders it from getStatus().qr.
|
||||
printQRInTerminal: false,
|
||||
syncFullHistory: false,
|
||||
});
|
||||
sock.ev.on('creds.update', () => {
|
||||
try {
|
||||
saveCreds();
|
||||
} catch (error) {
|
||||
onAuthError(error);
|
||||
}
|
||||
});
|
||||
return sock as unknown as WaSocketLike;
|
||||
}
|
||||
|
||||
/** Extract the Baileys disconnect status code (boom-style error). */
|
||||
export function disconnectStatusCode(lastDisconnect?: { error?: unknown }): number | undefined {
|
||||
const err = lastDisconnect?.error as { output?: { statusCode?: number } } | undefined;
|
||||
return err?.output?.statusCode;
|
||||
}
|
||||
|
||||
const LOGGED_OUT = 401; // DisconnectReason.loggedOut
|
||||
|
||||
export interface WhatsAppAdapterOptions {
|
||||
/** Channels data dir, used only to migrate/remove legacy plaintext state. */
|
||||
dataDir: string;
|
||||
/** Encrypted store for all Baileys credentials and signal keys. */
|
||||
vault: WhatsAppAuthVault;
|
||||
onMessage: InboundHandler;
|
||||
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
||||
/** Test seam. */
|
||||
socketFactory?: WaSocketFactory;
|
||||
backoffCapMs?: number;
|
||||
}
|
||||
|
||||
export class WhatsAppAdapter implements ChannelAdapter {
|
||||
readonly platform = 'whatsapp' as const;
|
||||
|
||||
private readonly legacyAuthDir: string;
|
||||
private readonly vault: WhatsAppAuthVault;
|
||||
private readonly onMessage: InboundHandler;
|
||||
private readonly log: WhatsAppAdapterOptions['log'];
|
||||
private readonly socketFactory: WaSocketFactory;
|
||||
private readonly backoffCap: number;
|
||||
|
||||
private running = false;
|
||||
private connected = false;
|
||||
private lastError: string | undefined;
|
||||
private lastActivityAt: number | undefined;
|
||||
private qr: string | undefined;
|
||||
private sock: WaSocketLike | null = null;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private backoff: number;
|
||||
|
||||
constructor(opts: WhatsAppAdapterOptions) {
|
||||
this.legacyAuthDir = path.join(opts.dataDir, 'channels', 'whatsapp-auth');
|
||||
this.vault = opts.vault;
|
||||
this.onMessage = opts.onMessage;
|
||||
this.log = opts.log;
|
||||
this.socketFactory = opts.socketFactory ?? defaultWaSocketFactory;
|
||||
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.lastError = undefined;
|
||||
await this.connect();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.running = false;
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
this.qr = undefined;
|
||||
}
|
||||
|
||||
getStatus(): WhatsAppStatus {
|
||||
return {
|
||||
platform: this.platform,
|
||||
running: this.running,
|
||||
connected: this.connected,
|
||||
lastError: this.lastError,
|
||||
lastActivityAt: this.lastActivityAt,
|
||||
qr: this.qr,
|
||||
paired: this.hasPersistedAuth(),
|
||||
};
|
||||
}
|
||||
|
||||
async send(chatId: string, text: string): Promise<void> {
|
||||
if (!this.sock) throw new Error('WhatsApp is not connected');
|
||||
for (const chunk of chunkText(text, WHATSAPP_MAX_TEXT)) {
|
||||
await this.sock.sendMessage(chatId, { text: chunk });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Connection lifecycle ─────────────────────────────────────────────
|
||||
|
||||
private async connect(): Promise<void> {
|
||||
try {
|
||||
const sock = await this.socketFactory(this.vault, this.legacyAuthDir, error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.lastError = `Could not save encrypted WhatsApp session: ${message}`;
|
||||
this.log.warn(`[whatsapp] ${this.lastError}`);
|
||||
});
|
||||
this.sock = sock;
|
||||
|
||||
sock.ev.on('connection.update', update => {
|
||||
if (update.qr) {
|
||||
this.qr = update.qr;
|
||||
this.log.info('[whatsapp] pairing QR refreshed — scan it from Settings → Channels');
|
||||
}
|
||||
if (update.connection === 'open') {
|
||||
this.connected = true;
|
||||
this.qr = undefined;
|
||||
this.lastError = undefined;
|
||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
||||
this.lastActivityAt = Date.now();
|
||||
this.log.info('[whatsapp] connected');
|
||||
}
|
||||
if (update.connection === 'close') {
|
||||
const code = disconnectStatusCode(update.lastDisconnect);
|
||||
if (code === LOGGED_OUT) {
|
||||
// Device unlinked from the phone — credentials are dead. Wipe so
|
||||
// the next start shows a fresh QR instead of a reconnect loop.
|
||||
this.wipeAuthState();
|
||||
this.handleDrop('logged out — re-pair via QR', false);
|
||||
} else {
|
||||
this.handleDrop(`connection closed (code ${code ?? 'unknown'})`, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
sock.ev.on('messages.upsert', upsert => {
|
||||
if (upsert.type !== 'notify') return;
|
||||
for (const raw of upsert.messages) {
|
||||
const msg = this.normalize(raw);
|
||||
if (!msg) continue;
|
||||
this.lastActivityAt = Date.now();
|
||||
void this.onMessage(msg).catch(e => {
|
||||
this.log.warn(`[whatsapp] inbound handler failed: ${e instanceof Error ? e.message : e}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
this.handleDrop(e instanceof Error ? e.message : String(e), true);
|
||||
}
|
||||
}
|
||||
|
||||
private normalize(raw: BaileysEventMap['messages.upsert']['messages'][number]): ChannelMessage | null {
|
||||
const jid = raw.key.remoteJid;
|
||||
if (!jid || raw.key.fromMe) return null;
|
||||
if (jid === 'status@broadcast') return null;
|
||||
const text = raw.message?.conversation ?? raw.message?.extendedTextMessage?.text;
|
||||
if (!text) return null;
|
||||
// In groups the author is key.participant; in DMs it's the chat jid.
|
||||
const senderId = raw.key.participant ?? jid;
|
||||
return {
|
||||
platform: 'whatsapp',
|
||||
chatId: jid,
|
||||
senderId,
|
||||
senderName: raw.pushName ?? undefined,
|
||||
text,
|
||||
messageId: raw.key.id ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private handleDrop(reason: string, reconnect: boolean): void {
|
||||
this.teardownSocket();
|
||||
this.connected = false;
|
||||
if (!this.running) return;
|
||||
this.lastError = reason;
|
||||
if (!reconnect) {
|
||||
this.log.warn(`[whatsapp] ${reason}`);
|
||||
return;
|
||||
}
|
||||
this.log.warn(`[whatsapp] dropped (${reason}) — reconnecting in ${this.backoff}ms`);
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
void this.connect();
|
||||
}, this.backoff);
|
||||
this.reconnectTimer.unref?.();
|
||||
this.backoff = Math.min(this.backoff * 2, this.backoffCap);
|
||||
}
|
||||
|
||||
private wipeAuthState(): void {
|
||||
try {
|
||||
this.vault.delete(WHATSAPP_AUTH_VAULT_KEY);
|
||||
fs.rmSync(this.legacyAuthDir, { recursive: true, force: true });
|
||||
} catch (e: unknown) {
|
||||
this.log.warn(`[whatsapp] failed to clear auth state: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
|
||||
private hasPersistedAuth(): boolean {
|
||||
const entry = this.vault.get(WHATSAPP_AUTH_VAULT_KEY);
|
||||
if (entry) {
|
||||
try {
|
||||
const parsed = JSON.parse(entry.value) as { creds?: { registered?: boolean } };
|
||||
return parsed.creds?.registered === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Compatibility during the one-time migration window.
|
||||
return fs.existsSync(path.join(this.legacyAuthDir, 'creds.json'));
|
||||
}
|
||||
|
||||
private teardownSocket(): void {
|
||||
try {
|
||||
this.sock?.end?.(undefined);
|
||||
} catch { /* already closed */ }
|
||||
this.sock = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user