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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions gateway/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,11 @@ def load_gateway_config() -> GatewayConfig:
if isinstance(gaf, list):
gaf = ",".join(str(v) for v in gaf)
os.environ["WHATSAPP_GROUP_ALLOWED_USERS"] = str(gaf)
gac = whatsapp_cfg.get("group_allowed_users")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not add group_allowed_users as a second WhatsApp config key. Current main uses canonical whatsapp.group_allow_from, and plugins/platforms/whatsapp/adapter.py:1738-1742 already exports it to WHATSAPP_GROUP_ALLOWED_USERS; port the behavior through that existing path.

if gac is not None and not os.getenv("WHATSAPP_GROUP_ALLOWED_USERS"):
if isinstance(gac, list):
gac = ",".join(str(v) for v in gac)
os.environ["WHATSAPP_GROUP_ALLOWED_USERS"] = str(gac)

# DingTalk settings β†’ env vars (env vars take precedence)
dingtalk_cfg = yaml_cfg.get("dingtalk", {})
Expand Down
33 changes: 33 additions & 0 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3404,6 +3404,7 @@ async def start(self) -> bool:
_builtin_allowed_vars = (
"TELEGRAM_ALLOWED_USERS", "DISCORD_ALLOWED_USERS",
"WHATSAPP_ALLOWED_USERS", "SLACK_ALLOWED_USERS",
"WHATSAPP_GROUP_ALLOWED_USERS",
"SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
"TELEGRAM_GROUP_ALLOWED_USERS",
"TELEGRAM_GROUP_ALLOWED_CHATS",
Expand Down Expand Up @@ -5586,6 +5587,37 @@ def _is_user_authorized(self, source: SessionSource) -> bool:
if self.pairing_store.is_approved(platform_name, user_id):
return True

# WhatsApp group allowlist: when configured, any member in an allowed
# group can chat with Hermes. "*" allows all groups.
if source.platform == Platform.WHATSAPP and source.chat_type == "group":
group_allowlist = os.getenv("WHATSAPP_GROUP_ALLOWED_USERS", "").strip()
if group_allowlist:
allowed_groups = {
group_id.strip()
for group_id in group_allowlist.split(",")
if group_id.strip()
}
if "*" in allowed_groups:
return True

normalized_allowed_groups = set()
for group_id in allowed_groups:
normalized_allowed_groups.add(group_id)
normalized_group_id = _normalize_whatsapp_identifier(group_id)
if normalized_group_id:
normalized_allowed_groups.add(normalized_group_id)

chat_id_candidates = set()
raw_chat_id = str(source.chat_id or "").strip()
if raw_chat_id:
chat_id_candidates.add(raw_chat_id)
normalized_chat_id = _normalize_whatsapp_identifier(raw_chat_id)
if normalized_chat_id:
chat_id_candidates.add(normalized_chat_id)

if chat_id_candidates & normalized_allowed_groups:
return True

# Check platform-specific and global allowlists
platform_allowlist = os.getenv(platform_env_map.get(source.platform, ""), "").strip()
group_user_allowlist = ""
Expand Down Expand Up @@ -5730,6 +5762,7 @@ def _get_unauthorized_dm_behavior(self, platform: Optional[Platform]) -> str:
"TELEGRAM_GROUP_ALLOWED_USERS",
"TELEGRAM_GROUP_ALLOWED_CHATS",
),
Platform.WHATSAPP: ("WHATSAPP_GROUP_ALLOWED_USERS",),
Platform.QQBOT: ("QQ_GROUP_ALLOWED_USERS",),
}
if os.getenv(platform_env_map.get(platform, ""), "").strip():
Expand Down
2 changes: 1 addition & 1 deletion hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def _warn_config_parse_failure(config_path: Path, exc: Exception) -> None:
"IRC_SERVER", "IRC_PORT", "IRC_NICKNAME", "IRC_CHANNEL",
"IRC_USE_TLS", "IRC_SERVER_PASSWORD", "IRC_NICKSERV_PASSWORD",
"TERMINAL_ENV", "TERMINAL_SSH_KEY", "TERMINAL_SSH_PORT",
"WHATSAPP_MODE", "WHATSAPP_ENABLED",
"WHATSAPP_MODE", "WHATSAPP_ENABLED", "WHATSAPP_GROUP_ALLOWED_USERS",
"MATTERMOST_HOME_CHANNEL", "MATTERMOST_HOME_CHANNEL_NAME", "MATTERMOST_REPLY_MODE",
"MATRIX_PASSWORD", "MATRIX_ENCRYPTION", "MATRIX_DEVICE_ID", "MATRIX_HOME_ROOM",
"MATRIX_REQUIRE_MENTION", "MATRIX_FREE_RESPONSE_ROOMS", "MATRIX_AUTO_THREAD", "MATRIX_DM_AUTO_THREAD",
Expand Down
58 changes: 58 additions & 0 deletions scripts/whatsapp-bridge/allowlist.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,34 @@ export function parseAllowedUsers(rawValue) {
);
}

export function parseAllowedGroups(rawValue) {
const groups = new Set();
const normalizedGroups = new Set();

for (const entry of String(rawValue || '').split(',')) {
const value = String(entry || '').trim();
if (!value) {
continue;
}

groups.add(value);

if (value !== '*') {
const normalized = normalizeWhatsAppIdentifier(value);
if (normalized) {
normalizedGroups.add(normalized);
}
}
}

return { groups, normalizedGroups };
}

export function parseAllowAllFlag(rawValue) {
const value = String(rawValue || '').trim().toLowerCase();
return value === '1' || value === 'true' || value === 'yes';
}

function readMappingFile(sessionDir, identifier, suffix = '') {
const filePath = path.join(sessionDir, `lid-mapping-${identifier}${suffix}.json`);
if (!existsSync(filePath)) {
Expand Down Expand Up @@ -86,3 +114,33 @@ export function matchesAllowedUser(senderId, allowedUsers, sessionDir) {

return false;
}

export function isSenderAllowed({
senderId,
chatId,
isGroup,
allowedUsers,
allowedGroups,
normalizedAllowedGroups,
allowAllUsers,
sessionDir,
}) {
if (allowAllUsers) {
return true;
}

if (isGroup) {
if (allowedGroups?.has('*')) {
return true;
}

const rawChatId = String(chatId || '').trim();
const normalizedChatId = normalizeWhatsAppIdentifier(rawChatId);

if ((rawChatId && allowedGroups?.has(rawChatId)) || (normalizedChatId && normalizedAllowedGroups?.has(normalizedChatId))) {
return true;
}
}

return matchesAllowedUser(senderId, allowedUsers, sessionDir);
}
65 changes: 65 additions & 0 deletions scripts/whatsapp-bridge/allowlist.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';

import {
expandWhatsAppIdentifiers,
isSenderAllowed,
parseAllowAllFlag,
parseAllowedGroups,
matchesAllowedUser,
normalizeWhatsAppIdentifier,
parseAllowedUsers,
Expand Down Expand Up @@ -78,3 +81,65 @@ test('matchesAllowedUser rejects everyone when allowlist is empty (#8389)', () =
rmSync(sessionDir, { recursive: true, force: true });
}
});

test('parseAllowedGroups keeps raw group ids and normalized aliases', () => {
const { groups, normalizedGroups } = parseAllowedGroups('1203630@g.us, +1203631@g.us, *');
assert.equal(groups.has('1203630@g.us'), true);
assert.equal(groups.has('+1203631@g.us'), true);
assert.equal(groups.has('*'), true);
assert.equal(normalizedGroups.has('1203630'), true);
assert.equal(normalizedGroups.has('1203631'), true);
});

test('parseAllowAllFlag accepts gateway-compatible truthy values', () => {
assert.equal(parseAllowAllFlag('true'), true);
assert.equal(parseAllowAllFlag('YES'), true);
assert.equal(parseAllowAllFlag('1'), true);
assert.equal(parseAllowAllFlag('on'), false);
assert.equal(parseAllowAllFlag('0'), false);
assert.equal(parseAllowAllFlag(''), false);
});

test('isSenderAllowed allows non-allowlisted group member in allowlisted group', () => {
const sessionDir = mkdtempSync(path.join(os.tmpdir(), 'hermes-wa-allowlist-'));

try {
const allowedUsers = parseAllowedUsers('+19175395595');
const { groups, normalizedGroups } = parseAllowedGroups('1203630@g.us');

assert.equal(isSenderAllowed({
senderId: '188012763865257@lid',
chatId: '1203630@g.us',
isGroup: true,
allowedUsers,
allowedGroups: groups,
normalizedAllowedGroups: normalizedGroups,
allowAllUsers: false,
sessionDir,
}), true);
} finally {
rmSync(sessionDir, { recursive: true, force: true });
}
});

test('isSenderAllowed still blocks DMs not in allowed users when group allowlist is set', () => {
const sessionDir = mkdtempSync(path.join(os.tmpdir(), 'hermes-wa-allowlist-'));

try {
const allowedUsers = parseAllowedUsers('+19175395595');
const { groups, normalizedGroups } = parseAllowedGroups('1203630@g.us');

assert.equal(isSenderAllowed({
senderId: '188012763865257@lid',
chatId: '188012763865257@s.whatsapp.net',
isGroup: false,
allowedUsers,
allowedGroups: groups,
normalizedAllowedGroups: normalizedGroups,
allowAllUsers: false,
sessionDir,
}), false);
} finally {
rmSync(sessionDir, { recursive: true, force: true });
}
});
21 changes: 19 additions & 2 deletions scripts/whatsapp-bridge/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { randomBytes } from 'crypto';
import { execSync } from 'child_process';
import { tmpdir } from 'os';
import qrcode from 'qrcode-terminal';
import { matchesAllowedUser, parseAllowedUsers } from './allowlist.js';
import { isSenderAllowed, parseAllowAllFlag, parseAllowedGroups, parseAllowedUsers } from './allowlist.js';

// Parse CLI args
const args = process.argv.slice(2);
Expand All @@ -51,6 +51,8 @@ const AUDIO_CACHE_DIR = path.join(process.env.HOME || '~', '.hermes', 'audio_cac
const PAIR_ONLY = args.includes('--pair-only');
const WHATSAPP_MODE = getArg('mode', process.env.WHATSAPP_MODE || 'self-chat'); // "bot" or "self-chat"
const ALLOWED_USERS = parseAllowedUsers(process.env.WHATSAPP_ALLOWED_USERS || '');
const { groups: GROUP_ALLOWED_USERS, normalizedGroups: NORMALIZED_GROUP_ALLOWED_USERS } = parseAllowedGroups(process.env.WHATSAPP_GROUP_ALLOWED_USERS || '');
const ALLOW_ALL_USERS = parseAllowAllFlag(process.env.WHATSAPP_ALLOW_ALL_USERS || '');
const DEFAULT_REPLY_PREFIX = 'βš• *Hermes Agent*\n────────────\n';
const REPLY_PREFIX = process.env.WHATSAPP_REPLY_PREFIX === undefined
? DEFAULT_REPLY_PREFIX
Expand Down Expand Up @@ -301,7 +303,16 @@ async function startSocket() {
} catch {}
continue;
}
if (!matchesAllowedUser(senderId, ALLOWED_USERS, SESSION_DIR)) {
if (!isSenderAllowed({
senderId,
chatId,
isGroup,
allowedUsers: ALLOWED_USERS,
allowedGroups: GROUP_ALLOWED_USERS,
normalizedAllowedGroups: NORMALIZED_GROUP_ALLOWED_USERS,
allowAllUsers: ALLOW_ALL_USERS,
sessionDir: SESSION_DIR,
})) {
try {
console.log(JSON.stringify({
event: 'ignored',
Expand Down Expand Up @@ -723,6 +734,12 @@ if (PAIR_ONLY) {
console.log(` Set WHATSAPP_ALLOWED_USERS=<phone> to authorize specific users,`);
console.log(` or WHATSAPP_ALLOWED_USERS=* for an explicit open bot.`);
}
if (GROUP_ALLOWED_USERS.size > 0) {
console.log(`πŸ‘₯ Allowed groups: ${Array.from(GROUP_ALLOWED_USERS).join(', ')}`);
}
if (ALLOW_ALL_USERS) {
console.log(`⚠️ WHATSAPP_ALLOW_ALL_USERS enabled β€” all senders are allowed`);
}
console.log();
startSocket();
});
Expand Down
5 changes: 5 additions & 0 deletions tests/gateway/test_allowlist_startup_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ def _would_warn():
os.getenv(v)
for v in ("TELEGRAM_ALLOWED_USERS", "DISCORD_ALLOWED_USERS",
"WHATSAPP_ALLOWED_USERS", "SLACK_ALLOWED_USERS",
"WHATSAPP_GROUP_ALLOWED_USERS",
"SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
"EMAIL_ALLOWED_USERS",
"SMS_ALLOWED_USERS", "MATTERMOST_ALLOWED_USERS",
Expand Down Expand Up @@ -37,6 +38,10 @@ def test_signal_group_allowed_users_suppresses_warning(self):
with patch.dict(os.environ, {"SIGNAL_GROUP_ALLOWED_USERS": "user1"}, clear=True):
assert _would_warn() is False

def test_whatsapp_group_allowed_users_suppresses_warning(self):
with patch.dict(os.environ, {"WHATSAPP_GROUP_ALLOWED_USERS": "120363001234567890@g.us"}, clear=True):
assert _would_warn() is False

def test_telegram_allow_all_users_suppresses_warning(self):
with patch.dict(os.environ, {"TELEGRAM_ALLOW_ALL_USERS": "true"}, clear=True):
assert _would_warn() is False
Expand Down
75 changes: 75 additions & 0 deletions tests/gateway/test_unauthorized_dm_behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def _clear_auth_env(monkeypatch) -> None:
"TELEGRAM_GROUP_ALLOWED_USERS",
"DISCORD_ALLOWED_USERS",
"WHATSAPP_ALLOWED_USERS",
"WHATSAPP_GROUP_ALLOWED_USERS",
"SLACK_ALLOWED_USERS",
"SIGNAL_ALLOWED_USERS",
"SIGNAL_GROUP_ALLOWED_USERS",
Expand Down Expand Up @@ -120,6 +121,66 @@ def test_star_wildcard_in_allowlist_authorizes_any_user(monkeypatch):
assert runner._is_user_authorized(source) is True


def test_whatsapp_group_allowlist_authorizes_any_group_member(monkeypatch):
_clear_auth_env(monkeypatch)
monkeypatch.setenv("WHATSAPP_GROUP_ALLOWED_USERS", "120363001234567890")

runner, _adapter = _make_runner(
Platform.WHATSAPP,
GatewayConfig(platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)}),
)

source = SessionSource(
platform=Platform.WHATSAPP,
user_id="99998887776@s.whatsapp.net",
chat_id="120363001234567890@g.us",
user_name="group-member",
chat_type="group",
)

assert runner._is_user_authorized(source) is True


def test_whatsapp_group_allowlist_supports_star_wildcard(monkeypatch):
_clear_auth_env(monkeypatch)
monkeypatch.setenv("WHATSAPP_GROUP_ALLOWED_USERS", "*")

runner, _adapter = _make_runner(
Platform.WHATSAPP,
GatewayConfig(platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)}),
)

source = SessionSource(
platform=Platform.WHATSAPP,
user_id="99998887776@s.whatsapp.net",
chat_id="120363009999999999@g.us",
user_name="group-member",
chat_type="group",
)

assert runner._is_user_authorized(source) is True


def test_whatsapp_group_allowlist_does_not_authorize_dm(monkeypatch):
_clear_auth_env(monkeypatch)
monkeypatch.setenv("WHATSAPP_GROUP_ALLOWED_USERS", "120363001234567890@g.us")

runner, _adapter = _make_runner(
Platform.WHATSAPP,
GatewayConfig(platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)}),
)

source = SessionSource(
platform=Platform.WHATSAPP,
user_id="99998887776@s.whatsapp.net",
chat_id="99998887776@s.whatsapp.net",
user_name="stranger",
chat_type="dm",
)

assert runner._is_user_authorized(source) is False


def test_star_wildcard_works_for_any_platform(monkeypatch):
"""The * wildcard should work generically, not just for WhatsApp."""
_clear_auth_env(monkeypatch)
Expand Down Expand Up @@ -615,6 +676,20 @@ def test_allowlist_authorized_user_returns_ignore_for_unauthorized(monkeypatch):
assert behavior == "ignore"


def test_whatsapp_group_allowlist_returns_ignore_for_unauthorized(monkeypatch):
"""WhatsApp group allowlists should not trigger pairing codes for unknown DMs."""
_clear_auth_env(monkeypatch)
monkeypatch.setenv("WHATSAPP_GROUP_ALLOWED_USERS", "120363001234567890@g.us")

config = GatewayConfig(
platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)},
)
runner, _adapter = _make_runner(Platform.WHATSAPP, config)

behavior = runner._get_unauthorized_dm_behavior(Platform.WHATSAPP)
assert behavior == "ignore"


def test_get_unauthorized_dm_behavior_no_allowlist_returns_pair(monkeypatch):
"""Without any allowlist, 'pair' is still the default."""
_clear_auth_env(monkeypatch)
Expand Down
Loading