Skip to content

Commit cba77fa

Browse files
fix(owpenbot): lazy WhatsApp onboarding and REST pairing (anomalyco#496)
- Default WhatsApp to disabled unless creds/config enable it\n- Never print QR codes from bridge startup (printQr=false)\n- Lazy-load WhatsApp adapter to avoid Bun ws warnings when disabled\n- Add REST endpoints: GET /whatsapp/qr, GET/POST /config/whatsapp-enabled\n- Only print CLI command hints in interactive TTY mode
1 parent 541d7ff commit cba77fa

4 files changed

Lines changed: 211 additions & 4 deletions

File tree

‎packages/owpenbot/src/bridge.ts‎

Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { setTimeout as delay } from "node:timers/promises";
2+
import fs from "node:fs";
3+
import path from "node:path";
24

35
import type { Logger } from "pino";
46

@@ -11,7 +13,6 @@ import { buildPermissionRules, createClient } from "./opencode.js";
1113
import { chunkText, formatInputSummary, truncateText } from "./text.js";
1214
import { createSlackAdapter } from "./slack.js";
1315
import { createTelegramAdapter } from "./telegram.js";
14-
import { createWhatsAppAdapter } from "./whatsapp.js";
1516

1617
type Adapter = {
1718
name: ChannelName;
@@ -205,9 +206,15 @@ export async function startBridge(config: Config, logger: Logger, reporter?: Bri
205206

206207
if (config.whatsappEnabled) {
207208
logger.debug("whatsapp adapter enabled");
209+
// Lazy-load WhatsApp adapter to avoid Bun WS warnings (Baileys) when the
210+
// channel is disabled.
211+
const { createWhatsAppAdapter } = await import("./whatsapp.js");
208212
adapters.set(
209213
"whatsapp",
210-
createWhatsAppAdapter(config, logger, handleInbound, { printQr: true, onStatus: reportStatus }),
214+
// Never print QR codes from the long-running bridge process.
215+
// Pairing/onboarding should be driven by explicit user action (CLI
216+
// subcommand or REST API) so `openwrk`/desktop startup stays quiet.
217+
createWhatsAppAdapter(config, logger, handleInbound, { printQr: false, onStatus: reportStatus }),
211218
);
212219
} else {
213220
logger.info("whatsapp adapter disabled");
@@ -500,6 +507,111 @@ export async function startBridge(config: Config, logger: Logger, reporter?: Bri
500507
applied: true,
501508
};
502509
},
510+
getWhatsAppEnabled: () => Boolean(config.whatsappEnabled),
511+
setWhatsAppEnabled: async (enabled: boolean) => {
512+
const nextEnabled = Boolean(enabled);
513+
const { config: current } = readConfigFile(config.configPath);
514+
const next: OwpenbotConfigFile = {
515+
...current,
516+
channels: {
517+
...current.channels,
518+
whatsapp: {
519+
...current.channels?.whatsapp,
520+
enabled: nextEnabled,
521+
},
522+
},
523+
};
524+
next.version = next.version ?? 1;
525+
writeConfigFile(config.configPath, next);
526+
config.configFile = next;
527+
config.whatsappEnabled = nextEnabled;
528+
529+
const existing = adapters.get("whatsapp");
530+
if (!nextEnabled) {
531+
if (existing) {
532+
try {
533+
await existing.stop();
534+
} catch (error) {
535+
logger.warn({ error }, "failed to stop existing whatsapp adapter");
536+
}
537+
adapters.delete("whatsapp");
538+
}
539+
return { enabled: false, applied: true };
540+
}
541+
542+
if (existing) {
543+
// Already enabled; no-op.
544+
return { enabled: true, applied: true };
545+
}
546+
547+
const { createWhatsAppAdapter } = await import("./whatsapp.js");
548+
const adapter = createWhatsAppAdapter(config, logger, handleInbound, {
549+
printQr: false,
550+
onStatus: reportStatus,
551+
});
552+
adapters.set("whatsapp", adapter);
553+
554+
const startResult = await startAdapterBounded(adapter, {
555+
timeoutMs: 5_000,
556+
onError: (error) => {
557+
logger.error({ error }, "whatsapp adapter start failed");
558+
adapters.delete("whatsapp");
559+
},
560+
});
561+
562+
if (startResult.status === "timeout") {
563+
logger.warn({ timeoutMs: 5_000 }, "whatsapp adapter start timed out");
564+
return { enabled: true, applied: false, starting: true };
565+
}
566+
567+
if (startResult.status === "error") {
568+
return { enabled: true, applied: false, error: String(startResult.error) };
569+
}
570+
571+
return { enabled: true, applied: true };
572+
},
573+
getWhatsAppQr: async () => {
574+
// Avoid printing the QR to stdout; return the raw QR string so a UI
575+
// can render it.
576+
const credsPath = path.join(config.whatsappAuthDir, "creds.json");
577+
if (fs.existsSync(credsPath)) {
578+
throw new Error("WhatsApp already linked");
579+
}
580+
581+
const { createWhatsAppSocket, closeWhatsAppSocket } = await import("./whatsapp-session.js");
582+
583+
return new Promise<{ qr: string }>((resolve, reject) => {
584+
let resolved = false;
585+
const timeout = setTimeout(() => {
586+
if (resolved) return;
587+
resolved = true;
588+
reject(new Error("Timeout waiting for QR code"));
589+
}, 30_000);
590+
591+
void createWhatsAppSocket({
592+
authDir: config.whatsappAuthDir,
593+
logger,
594+
printQr: false,
595+
onQr: (qr) => {
596+
if (resolved) return;
597+
resolved = true;
598+
clearTimeout(timeout);
599+
resolve({ qr });
600+
},
601+
})
602+
.then((sock) => {
603+
setTimeout(() => {
604+
closeWhatsAppSocket(sock);
605+
}, resolved ? 500 : 30_500);
606+
})
607+
.catch((error) => {
608+
if (resolved) return;
609+
resolved = true;
610+
clearTimeout(timeout);
611+
reject(error);
612+
});
613+
});
614+
},
503615
listBindings: async () => {
504616
const bindings = store.listBindings();
505617
return {

‎packages/owpenbot/src/cli.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,11 @@ async function runStart(pathOverride?: string, options?: { opencodeUrl?: string
163163
process.env.OPENCODE_DIRECTORY = config.opencodeDirectory;
164164
}
165165
const bridge = await startBridge(config, logger, reporter);
166-
reporter.onStatus?.("Commands: owpenwork whatsapp login, owpenwork slack status, owpenwork pairing list, owpenwork status");
166+
// Avoid noisy startup output when running under openwrk/desktop (stdio is
167+
// usually piped). Keep the hint for interactive CLI usage.
168+
if (process.stdout.isTTY) {
169+
reporter.onStatus?.("Commands: owpenwork whatsapp login, owpenwork slack status, owpenwork pairing list, owpenwork status");
170+
}
167171

168172
const shutdown = async () => {
169173
logger.info("shutting down");

‎packages/owpenbot/src/config.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export type OwpenbotConfigFile = {
2121
groupsEnabled?: boolean;
2222
channels?: {
2323
whatsapp?: {
24+
enabled?: boolean;
2425
dmPolicy?: DmPolicy;
2526
allowFrom?: string[];
2627
selfChatMode?: boolean;
@@ -255,6 +256,18 @@ export function loadConfig(
255256
const healthPort = parseInteger(env.OWPENBOT_HEALTH_PORT) ?? 3005;
256257
const model = parseModel(env.OWPENBOT_MODEL);
257258

259+
// Preserve existing installs that are already paired by auto-enabling WhatsApp
260+
// when creds are present, but avoid auto-onboarding (QR printing) on fresh
261+
// installs.
262+
const whatsappCredsPresent = (() => {
263+
try {
264+
return fs.existsSync(path.join(whatsappAuthDir, "creds.json"));
265+
} catch {
266+
return false;
267+
}
268+
})();
269+
const whatsappEnabledDefault = configFile.channels?.whatsapp?.enabled ?? whatsappCredsPresent;
270+
258271
return {
259272
configPath,
260273
configFile,
@@ -279,7 +292,7 @@ export function loadConfig(
279292
whatsappDmPolicy: dmPolicy,
280293
whatsappAllowFrom,
281294
whatsappSelfChatMode: selfChatMode,
282-
whatsappEnabled: parseBoolean(env.WHATSAPP_ENABLED, true),
295+
whatsappEnabled: parseBoolean(env.WHATSAPP_ENABLED, whatsappEnabledDefault),
283296
dataDir,
284297
dbPath,
285298
logFile,

‎packages/owpenbot/src/health.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,17 @@ export type SlackTokensResult = {
3939
error?: string;
4040
};
4141

42+
export type WhatsAppEnabledResult = {
43+
enabled: boolean;
44+
applied?: boolean;
45+
starting?: boolean;
46+
error?: string;
47+
};
48+
49+
export type WhatsAppQrResult = {
50+
qr: string;
51+
};
52+
4253
export type GroupsConfigResult = {
4354
groupsEnabled: boolean;
4455
};
@@ -59,6 +70,9 @@ export type HealthHandlers = {
5970
setSlackTokens?: (tokens: { botToken: string; appToken: string }) => Promise<SlackTokensResult>;
6071
setGroupsEnabled?: (enabled: boolean) => Promise<GroupsConfigResult>;
6172
getGroupsEnabled?: () => boolean;
73+
getWhatsAppEnabled?: () => boolean;
74+
setWhatsAppEnabled?: (enabled: boolean) => Promise<WhatsAppEnabledResult>;
75+
getWhatsAppQr?: () => Promise<WhatsAppQrResult>;
6276
listBindings?: () => Promise<BindingsListResult>;
6377
setBinding?: (input: { channel: string; peerId: string; directory: string }) => Promise<void>;
6478
clearBinding?: (input: { channel: string; peerId: string }) => Promise<void>;
@@ -233,6 +247,70 @@ export function startHealthServer(
233247
}
234248
}
235249

250+
// GET /config/whatsapp-enabled - get current whatsapp enabled setting
251+
if (pathname === "/config/whatsapp-enabled" && req.method === "GET") {
252+
if (!handlers.getWhatsAppEnabled) {
253+
res.writeHead(404, { "Content-Type": "application/json" });
254+
res.end(JSON.stringify({ ok: false, error: "Not supported" }));
255+
return;
256+
}
257+
const enabled = handlers.getWhatsAppEnabled();
258+
res.writeHead(200, { "Content-Type": "application/json" });
259+
res.end(JSON.stringify({ ok: true, enabled }));
260+
return;
261+
}
262+
263+
// POST /config/whatsapp-enabled - enable/disable whatsapp adapter
264+
if (pathname === "/config/whatsapp-enabled" && req.method === "POST") {
265+
if (!handlers.setWhatsAppEnabled) {
266+
res.writeHead(404, { "Content-Type": "application/json" });
267+
res.end(JSON.stringify({ ok: false, error: "Not supported" }));
268+
return;
269+
}
270+
271+
let raw = "";
272+
for await (const chunk of req) {
273+
raw += chunk.toString();
274+
if (raw.length > 1024 * 1024) {
275+
res.writeHead(413, { "Content-Type": "application/json" });
276+
res.end(JSON.stringify({ ok: false, error: "Payload too large" }));
277+
return;
278+
}
279+
}
280+
281+
try {
282+
const payload = JSON.parse(raw || "{}");
283+
const enabled = payload.enabled === true || payload.enabled === "true";
284+
const result = await handlers.setWhatsAppEnabled(enabled);
285+
res.writeHead(200, { "Content-Type": "application/json" });
286+
res.end(JSON.stringify({ ok: true, ...result }));
287+
return;
288+
} catch (error) {
289+
res.writeHead(500, { "Content-Type": "application/json" });
290+
res.end(JSON.stringify({ ok: false, error: String(error) }));
291+
return;
292+
}
293+
}
294+
295+
// GET /whatsapp/qr - get a WhatsApp QR code for pairing (non-interactive)
296+
if (pathname === "/whatsapp/qr" && req.method === "GET") {
297+
if (!handlers.getWhatsAppQr) {
298+
res.writeHead(404, { "Content-Type": "application/json" });
299+
res.end(JSON.stringify({ ok: false, error: "Not supported" }));
300+
return;
301+
}
302+
try {
303+
const result = await handlers.getWhatsAppQr();
304+
res.writeHead(200, { "Content-Type": "application/json" });
305+
res.end(JSON.stringify({ ok: true, ...result }));
306+
return;
307+
} catch (error) {
308+
res.writeHead(500, { "Content-Type": "application/json" });
309+
res.end(JSON.stringify({ ok: false, error: String(error) }));
310+
return;
311+
}
312+
}
313+
236314
if (pathname === "/bindings" && req.method === "GET") {
237315
if (!handlers.listBindings) {
238316
res.writeHead(404, { "Content-Type": "application/json" });

0 commit comments

Comments
 (0)