fix(whatsapp): wait for creds update and fix config path (#38)

This commit is contained in:
paisley
2026-02-10 19:07:44 +08:00
committed by GitHub
Unverified
parent f950c37a73
commit 29d0db706f
5 changed files with 147 additions and 22 deletions

View File

@@ -6,17 +6,27 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSy
import { join } from 'path';
import { homedir } from 'os';
import { getOpenClawResolvedDir } from './paths';
import * as logger from './logger';
const OPENCLAW_DIR = join(homedir(), '.openclaw');
const CONFIG_FILE = join(OPENCLAW_DIR, 'openclaw.json');
// Channels that are managed as plugins (config goes under plugins.entries, not channels)
const PLUGIN_CHANNELS = ['whatsapp'];
export interface ChannelConfigData {
enabled?: boolean;
[key: string]: unknown;
}
export interface PluginsConfig {
entries?: Record<string, ChannelConfigData>;
[key: string]: unknown;
}
export interface OpenClawConfig {
channels?: Record<string, ChannelConfigData>;
plugins?: PluginsConfig;
[key: string]: unknown;
}
@@ -43,6 +53,7 @@ export function readOpenClawConfig(): OpenClawConfig {
const content = readFileSync(CONFIG_FILE, 'utf-8');
return JSON.parse(content) as OpenClawConfig;
} catch (error) {
logger.error('Failed to read OpenClaw config', error);
console.error('Failed to read OpenClaw config:', error);
return {};
}
@@ -57,6 +68,7 @@ export function writeOpenClawConfig(config: OpenClawConfig): void {
try {
writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
} catch (error) {
logger.error('Failed to write OpenClaw config', error);
console.error('Failed to write OpenClaw config:', error);
throw error;
}
@@ -73,6 +85,28 @@ export function saveChannelConfig(
): void {
const currentConfig = readOpenClawConfig();
// Plugin-based channels (e.g. WhatsApp) go under plugins.entries, not channels
if (PLUGIN_CHANNELS.includes(channelType)) {
if (!currentConfig.plugins) {
currentConfig.plugins = {};
}
if (!currentConfig.plugins.entries) {
currentConfig.plugins.entries = {};
}
currentConfig.plugins.entries[channelType] = {
...currentConfig.plugins.entries[channelType],
enabled: config.enabled ?? true,
};
writeOpenClawConfig(currentConfig);
logger.info('Plugin channel config saved', {
channelType,
configFile: CONFIG_FILE,
path: `plugins.entries.${channelType}`,
});
console.log(`Saved plugin channel config for ${channelType}`);
return;
}
if (!currentConfig.channels) {
currentConfig.channels = {};
}
@@ -146,6 +180,13 @@ export function saveChannelConfig(
};
writeOpenClawConfig(currentConfig);
logger.info('Channel config saved', {
channelType,
configFile: CONFIG_FILE,
rawKeys: Object.keys(config),
transformedKeys: Object.keys(transformedConfig),
enabled: currentConfig.channels[channelType]?.enabled,
});
console.log(`Saved channel config for ${channelType}`);
}
@@ -289,6 +330,23 @@ export function listConfiguredChannels(): string[] {
export function setChannelEnabled(channelType: string, enabled: boolean): void {
const currentConfig = readOpenClawConfig();
// Plugin-based channels go under plugins.entries
if (PLUGIN_CHANNELS.includes(channelType)) {
if (!currentConfig.plugins) {
currentConfig.plugins = {};
}
if (!currentConfig.plugins.entries) {
currentConfig.plugins.entries = {};
}
if (!currentConfig.plugins.entries[channelType]) {
currentConfig.plugins.entries[channelType] = {};
}
currentConfig.plugins.entries[channelType].enabled = enabled;
writeOpenClawConfig(currentConfig);
console.log(`Set plugin channel ${channelType} enabled: ${enabled}`);
return;
}
if (!currentConfig.channels) {
currentConfig.channels = {};
}
@@ -457,10 +515,16 @@ async function validateTelegramCredentials(
): Promise<CredentialValidationResult> {
const botToken = config.botToken?.trim();
const allowedUsers = config.allowedUsers?.trim();
if (!botToken) {
return { valid: false, errors: ['Bot token is required'], warnings: [] };
}
if (!allowedUsers) {
return { valid: false, errors: ['At least one allowed user ID is required'], warnings: [] };
}
try {
const response = await fetch(`https://api.telegram.org/bot${botToken}/getMe`);
const data = (await response.json()) as { ok?: boolean; description?: string; result?: { username?: string } };
@@ -553,6 +617,12 @@ export async function validateChannelConfig(channelType: string): Promise<Valida
result.errors.push('Telegram: Bot token is required');
result.valid = false;
}
// Check allowed users (stored as allowFrom array)
const allowedUsers = telegramConfig?.allowFrom as string[] | undefined;
if (!allowedUsers || allowedUsers.length === 0) {
result.errors.push('Telegram: Allowed User IDs are required');
result.valid = false;
}
}
if (result.errors.length === 0 && result.warnings.length === 0) {

View File

@@ -43,7 +43,10 @@ const QRCodeModule = require(join(qrcodeTerminalPath, 'vendor', 'QRCode', 'index
const QRErrorCorrectLevelModule = require(join(qrcodeTerminalPath, 'vendor', 'QRCode', 'QRErrorCorrectLevel.js'));
// Types from Baileys (approximate since we don't have types for dynamic require)
type BaileysSocket = any;
interface BaileysError extends Error {
output?: { statusCode?: number };
}
type BaileysSocket = ReturnType<typeof makeWASocket>;
type ConnectionState = {
connection: 'close' | 'open' | 'connecting';
lastDisconnect?: {
@@ -186,6 +189,18 @@ export class WhatsAppLoginManager extends EventEmitter {
super();
}
/**
* Finish login: close socket and emit success after credentials are saved
*/
private async finishLogin(accountId: string): Promise<void> {
if (!this.active) return;
console.log('[WhatsAppLogin] Finishing login, closing socket to hand over to Gateway...');
await this.stop();
// Delay to ensure socket is fully released before Gateway connects
await new Promise(resolve => setTimeout(resolve, 2000));
this.emit('success', { accountId });
}
/**
* Start WhatsApp pairing process
*/
@@ -226,7 +241,8 @@ export class WhatsAppLoginManager extends EventEmitter {
console.log(`[WhatsAppLogin] Connecting for ${accountId} at ${authDir} (Attempt ${this.retryCount + 1})`);
let pino: any;
let pino: (...args: unknown[]) => Record<string, unknown>;
try {
// Try to resolve pino from baileys context since it's a dependency of baileys
const baileysRequire = createRequire(join(baileysPath, 'package.json'));
@@ -268,7 +284,21 @@ export class WhatsAppLoginManager extends EventEmitter {
// browser: ['ClawX', 'Chrome', '1.0.0'],
});
this.socket.ev.on('creds.update', saveCreds);
let connectionOpened = false;
let credsReceived = false;
let credsTimeout: ReturnType<typeof setTimeout> | null = null;
this.socket.ev.on('creds.update', async () => {
await saveCreds();
if (connectionOpened && !credsReceived) {
credsReceived = true;
if (credsTimeout) clearTimeout(credsTimeout);
console.log('[WhatsAppLogin] Credentials saved after connection open, finishing login...');
// Small delay to ensure file writes are fully flushed
await new Promise(resolve => setTimeout(resolve, 3000));
await this.finishLogin(accountId);
}
});
this.socket.ev.on('connection.update', async (update: ConnectionState) => {
try {
@@ -282,7 +312,7 @@ export class WhatsAppLoginManager extends EventEmitter {
}
if (connection === 'close') {
const error = (lastDisconnect?.error as any);
const error = lastDisconnect?.error as BaileysError | undefined;
const shouldReconnect = error?.output?.statusCode !== DisconnectReason.loggedOut;
console.log('[WhatsAppLogin] Connection closed.',
'Reconnect:', shouldReconnect,
@@ -317,17 +347,17 @@ export class WhatsAppLoginManager extends EventEmitter {
this.emit('error', 'Logged out');
}
} else if (connection === 'open') {
console.log('[WhatsAppLogin] Connection opened! Closing socket to hand over to Gateway...');
console.log('[WhatsAppLogin] Connection opened! Waiting for credentials to be saved...');
this.retryCount = 0;
connectionOpened = true;
// Close socket gracefully to avoid conflict with Gateway
await this.stop();
// Add a small delay to ensure socket is fully closed and released
// This prevents "401 Conflict" when Gateway tries to connect immediately
await new Promise(resolve => setTimeout(resolve, 2000));
this.emit('success', { accountId });
// Safety timeout: if creds don't update within 15s, proceed anyway
credsTimeout = setTimeout(async () => {
if (!credsReceived && this.active) {
console.warn('[WhatsAppLogin] Timed out waiting for creds.update after connection open, proceeding...');
await this.finishLogin(accountId);
}
}, 15000);
}
} catch (innerErr) {
console.error('[WhatsAppLogin] Error in connection update:', innerErr);