Under multiplex, a thread-scoped route only matches a source carrying the
thread_id (profile_routing.RouteRule.matches); without it the attachment gate
consulted a different profile's pairing store than dispatch. Compute
session_thread_id first (unchanged, still one thread-count increment) and forward it.
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
signal-cli's daemon downloads received attachments into its data dir unless
started with --ignore-attachments (signal-cli(1)); getAttachment returns those
bytes. The gate prevents Hermes' cache copy, the ffmpeg remux and the agent seeing it.
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
rcvFileDescrReady and the deferred voice-note path told the daemon to fetch
every sender-chosen XFTP file before the runner's authorization ran, and
auto_accept is on by default, so any stranger could make the host download
files. Gate both on _is_sender_authorized(...) is True, the same rule the
other adapters use; the message still dispatches so deny/pairing runs.
Refs #123231
A bot peer admitted via MATTERMOST_ALLOW_BOTS is authorized on the message
path but got False from the callback (is_bot defaulted), so its attachments
were silently dropped. Compute is_bot once and use it for both.
Refs #123231
Same defect as Mattermost/Signal: each adapter downloaded and cached a sender's
attachments with its own credentials before the runner's authorization ran.
Gate the fetch on the runner-wired _is_sender_authorized, fetching only on an
explicit True; the message still dispatches so the runner can deny or pair.
Refs #123231, #143977
dm_allow_from is the raw SIGNAL_ALLOWED_USERS ("*" when unset), so it admitted
every stranger on an unset allowlist, missed pairing-approved and
GATEWAY_ALLOWED_USERS senders, and waved through any member of an allowed group.
Use the runner-wired _is_sender_authorized callback, as Mattermost and Buzz do,
and fetch only on an explicit True.
Fixes#143977
Co-authored-by: liuhao1024 <liuhao1024@users.noreply.github.com>
The inbound post handler fetched and cached every attachment (file info plus
body, up to 10 per post) before the runner authorized the sender, so anyone
able to DM the bot spent its token, bandwidth and disk without being on the
allowlist. The body was read with resp.read(), bypassing
gateway.max_inbound_media_bytes, and documents were cached at any size.
Fetch attachments only when the gateway's authorization check returns an
explicit True (the Buzz adapter's rule); the post still dispatches so the
runner applies denial or pairing. Stream the body through
_read_httpx_body_with_limit, which now takes an aiohttp chunk iterator.
When register(ctx) adds tools without registering the memory provider, subclass discovery returns the provider but leaves the collector without it. The PR's guard then bypasses the claim and exposes the owning profile's rows. Bind the discovered provider to its collector in both user-dir and entry-point loaders and add a focused multiplex regression.
Builds on c2h5oh's PR #154606.
A provider refused for a profile (claim_instance: another profile already
bound this same instance) was only dropped from that profile's
MemoryManager. Tools its register(ctx) put in the tool registry still
dispatched to the shared instance, so a refused profile's read returned
the owning profile's rows (mnemosyne-hermes 0.7.1's process-wide
singleton). _ProviderCollector.register_tool now wraps the handler so it
refuses any caller whose profile is not the one the instance is bound to.
Fixes#147659
_download_bytes' callers already vet the first URL (is_safe_url for reply
URLs, the CDN allowlist or the operator's cdn_base_url for inbound media),
which is all main did; DNS-checking it again drops every inbound image on a
fake-ip proxy host (198.18.0.0/15). Redirect hops stay checked.
Mattermost's 4xx text fallback now runs after the download loop, outside the
chain timeout, so a late error cannot cancel the post and retry. Drop the
stray trailing blank line in tools/url_safety.py.
Refs #126294
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
The Connect resolver prefers authorizations[0].team_id, which Slack documents
as "one installation of your app that the event is visible to" — on a gateway
with two installs in one Grid org it can name the sibling install, so the
external-DM and file_shared sharer gates refused members of an authenticated
workspace. An author is foreign only when their T… team is outside every
install. A reaction in a channel handed off to a D… reaction_trigger_target
now also stamps the reactor's team so the external-DM gate can judge it.
Refs #143792
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Slack file_shared events may carry the receiving install as event.team.
Verify the actual sharer's workspace with users.info before treating that
routing hint as the author; otherwise an external-org video DM synthesizes
a host-team message and escapes the external-DM gate (#143792).
Test: file_shared host event.team with foreign users.info is refused.
Credits: original PR author c2h5oh; reporter doudoujay.
The synthetic reaction event stamps the install team and carried no
user_team, so the external-org DM gate in _prefilter_inbound never fired
for reaction_triggers: an allowlisted external user reacting in a DM got
a turn with the refused DM thread hydrated. Resolve the reactor's T… team
via cached users.info (shared with the file_shared sharer lookup) and
stamp it as user_team, so the single prefilter gate covers both synthetic
paths; a reaction handoff target keeps the DM source in scope. Lookup
failure stays the gate's documented empty-author fail-open.
Fixes#143792
The authenticated-install resolver correctly returns an empty team for
foreign-only events on multi-install gateways, but the prefilter still
accepted those events with an empty scope. Drop them before deduplication
and the external-DM guard; pin the bypass with one regression test.
Salvage for guvengursel's PR #151460. Original report: doudoujay;
production evidence: KCAYAAI; resolver contribution: liuhao1024.
_event_team_id now collects candidates in Bolt's shared-channel order
(authorizations[0].team_id, envelope team_id, inner event.team) and, when the
authenticated install set (_team_clients) is available, only a candidate
inside it may win: with exactly one authenticated workspace that install wins
outright (a Connect pair collapses even when every Slack field names the
partner org), otherwise empty — a foreign team never scopes a session or a
dedupe id (#143792). Callers without an install set keep the field order.
The DM gate now compares only T… workspace ids (user_team can be an
enterprise E… id), and _handle_slack_file_shared refuses an external-org
file-share DM before building the synthetic host-team message that would
slip past that gate.
Tests: contract rows (foreign envelope + single install, Grid
authorizations-vs-envelope example, multi-install no-match, legacy order),
enterprise user_team fallback, allowlisted-external-user refusal, and the
file_shared DM pair (external refused / host synthesizes).
Co-authored-by: liuhao1024 <liuhao1024@users.noreply.github.com>
In a Slack Connect channel, one external @mention arrives as two same-ts
events (message + app_mention) whose inner event.team differs (sender's
org vs host workspace) while the envelope team_id is the installing
workspace on both. _event_team_id checked the inner event first, so the
dedup key and session scope split across two teams: the user got two
replies and one session was keyed to a workspace the app is not
installed in (#143792). Resolve the envelope first.
External-org users can also DM the bot; refuse those DMs at intake when
the event's sender team does not match the installing workspace,
regardless of allowlists.
Matrix docs now say a notice sender gets one reply per exchange under the
bot loop guard's reply_to_reply rule, and how to allow back-and-forth.
The Slack early-auth comment no longer promises a cache hit: the team key
can differ from _drop_bot_sender's. A Discord test pins
SessionSource.is_bot for a webhook post without author.bot.
Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
Reading _user_is_bot_cache directly broke adapters built without
__init__ (test_slack_mention fixtures) and diverged from the probe
condition _drop_bot_sender uses. Call _resolve_user_is_bot under the
same client_msg_id condition; it is a cache hit for the same event.
Refs #143370
Avoid rejecting users.info-detected bot peers as unlisted humans before
SLACK_ALLOW_BOTS can apply. Preserve the cached bot verdict at the early
authorization seam and pin the bot-only grant with a regression test.
PR #154561 by c2h5oh; issue #143370.
msgtype is chosen by the sender, so any Matrix user (federated strangers in
DMs included) can send m.notice. With MATRIX_ALLOW_BOTS=mentions|all and
process_notices on, that let an unlisted sender skip MATRIX_ALLOWED_USERS,
and 'mentions' was never enforced by the Matrix adapter anyway.
Keep m.notice -> is_bot (loop guard, no pairing reply), but don't declare
allow_bots_env until Matrix has an unspoofable bot identity; notice senders
still need a human rung.
Refs #143370
A peer agent posting as a bot user (no bot_id/subtype/app_id markers) was
recognised as a bot by the drop gates via the cached users.info verdict,
but the SessionSource only used the payload markers, so under
allow_bots=mentions|all it reached the gateway as a person: the bot loop
guard never counted it. Reuse the same cached verdict for is_bot.
Also document that processed Matrix notices are flagged as bots.
Refs #143370
A Matrix notice author reached the gateway as a person: only Discord,
Slack, Telegram and Feishu stamped SessionSource.is_bot, so the bot
loop guard and the no-pairing-DM rule never saw a notice-writing bot
(#143370).
Flag msgtype=m.notice sources in _resolve_message_context. The flag only
narrows: a notice sender still needs a human authorization rung.
Discord only guarantees `webhook_id` on webhook posts: the author object is the
webhook's id/name/avatar and the `bot` flag is optional (discord.py reports
author.bot=False when it is missing). The adapter read only author.bot, so a
flagless webhook post went down the human path: under an allow-all rung it was
admitted even with DISCORD_ALLOW_BOTS=none, it reached the session as a person
(is_bot=False, so the bot loop guard never counted it), and under
DISCORD_ALLOW_BOTS=mentions a webhook @mentioning Hermes was refused as an
unknown user. One `is_automated_message` predicate now feeds every site that
classified authors (admission, edit/delete events, bot-tag continuation,
history filter, SessionSource.is_bot), matching session.py's documented
"bot/webhook" meaning of is_bot.
The Mattermost and Weixin plugins imported tools.url_safety.ssrf_checked_aiohttp_get,
a core name outside the published plugin API, which raised two new module_to_core
crossings in scripts/boundary_lint.py. Move the helper next to platform_http_client
in gateway.platforms.helpers (already published), keep tools.url_safety's
async_is_safe_url as the per-hop check, and document it under the platform-adapter
public helpers. No baseline change.
Route _download_bytes through ssrf_checked_aiohttp_get so the CDN-allowlisted
full_url / encrypted_query_param fetch can no longer 302 to loopback or
metadata; _download_remote_media goes back through it and keeps the media
size cap the salvaged change dropped. Test imports follow the plugin move.
Fixes#126294
Refs #138362 (media-redirect half only)
Mattermost send_image / batch images and Weixin send_image fetched a
remote URL through aiohttp after a single is_safe_url() pre-flight.
aiohttp follows redirects by default, so a public URL that 302s to
loopback, RFC 1918 or cloud metadata was fetched and its body uploaded
into the chat, although the security guide says redirect chains are
re-validated at each hop.
Add ssrf_checked_aiohttp_get() to tools.url_safety (allow_redirects=False,
async_is_safe_url on every hop, same shape as the Discord and Matrix loops) and
use it on the three call sites.
Co-authored-by: binhnt92 <84617813+binhnt92@users.noreply.github.com>
Co-authored-by: zapabob <130830376+zapabob@users.noreply.github.com>
The adapter handles /setup-files itself and returns before
handle_message, so the gateway allowlist never saw these messages.
Any user who could message the bot could get replies, start the
OAuth flow, write token files under HERMES_HOME and make the host
install dependencies.
Run the command only when the runner's authorization check accepts
the sender. Everyone else goes on to handle_message, where the
runner's normal deny or pairing path answers them.
Review M1 (Mark S.): inside a flood window longer than the inline cap,
Telegram's delete_message hands the delete to a background task and returns
True at once. The fallback read that as "fragment gone" and sent the whole
answer; a later refused delete left the fragment beside a full copy.
Fragment replacement now uses delete_message_confirmed: True only once the
message is deleted, and on a long window False with nothing queued (a queued
delete would later remove the prefix the tail-only send relies on). Ordinary
best-effort cleanup keeps its deferred behaviour.
Co-authored-by: Mark S. <theoldwizard123@pm.me>
Review M1 (Mark S.): a voice memo recognised by its CAF UTI kept its
application/octet-stream MIME, so the fresh-turn classifier (which reads the
per-item MIME) never treated the admitted memo as audio and its spoken request
was lost. Record such a memo as audio/x-caf, as Photon already does.
Co-authored-by: Mark S. <theoldwizard123@pm.me>
Re-review P2s "Filter BlueBubbles gate inputs to voice attachments" and "Keep speech-admitted
BlueBubbles envelopes eligible for turn STT": the spoken gate passed every downloaded attachment
to transcribe_audio, and the admitted event kept _collect_attachments' last-attachment type, so a
memo followed by a PDF became DOCUMENT and the turn never transcribed the request speech admitted.
The gate now gets the voice paths only (a rejected envelope's other files are deleted, as on
Photon), and a speech-admitted envelope is VOICE.
Re-review P1 "Threaded stop/approve/deny waits behind gate STT": _on_inbound_line read the
escape-hatch command from the top-level content only, so a /stop sent as an iMessage threaded
reply ({type: reply, content: {type: text}}) queued behind the chat's pending gate transcription.
The lane choice now unwraps the reply once (_reply_inner), the same unwrap _gate_stt_chat uses.
Delta review Should fix 3: an attachment named .caf with MIME application/octet-stream passed
_is_voice_payload and was cached as audio, but kept the generic MIME as its media type, so the
gate's audio filter dropped it (0 STT calls, note rejected). A voice payload's media type now
says audio (audio/x-caf for a .caf, audio/mp4 otherwise), so classification and STT input agree.
Bot finding "Voice checks delay control commands" (also the review's minor item 4): on
Photon and WhatsApp, a message in a chat whose earlier voice note was still at gate STT
queued behind it, so a same-group /stop or /deny waited for the STT. A slash command the
base adapter dispatches mid-run (should_bypass_active_session) now skips that wait;
ordinary messages keep their order. Telegram's per-chat update processor predates
this PR and is unchanged.
Bot finding "Mixed messages lose spoken requests": _normalize_group_content keeps the
first attachment's type, and the runner never sends DOCUMENT audio to STT, so a group
envelope of a PDF then a voice note woke the bot without its transcript. A note the
spoken wake word admitted is dispatched as VOICE.
Bot finding "CAF notes cannot wake Hermes": iMessage voice notes also arrive as
`attachment` payloads named .caf / audio/x-caf, which normalisation already treats as
voice but the gate did not. Both now read _is_voice_payload().
Photon normalizes a `group` envelope holding a voice item, but the gate (and the
off-reader FIFO check) only recognised a top-level `voice` payload, so a spoken wake word
in a grouped message was dropped before STT. Both now use _carries_voice(); a typed
wake word in the envelope keeps the text path, only the envelope's audio is transcribed,
and a rejected envelope's other cached files are deleted with it.
Reported and first fixed by kvnloo (kvnloo/hermes-agent@86fc181e, review comment on
#153207); rebuilt on the current head.
Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com>
Review findings on #153207 (Greptile):
- Wake checks use wrong profile: the gate's STT now runs inside the routed profile's runtime
scope (runner._async_profile_scope_for_source), the scope the turn enters.
- Disabled STT still runs: stt.enabled: false in that profile skips gate transcription, so the
local fallback never runs either.
- Rejected notes lose quoted audio: WhatsApp bridge-cached clips are never deleted on a
rejection; the bridge's quotedMediaCache still points at them.
- One note delays every chat: Photon and WhatsApp run a group voice note that may transcribe
(and anything after it in that chat) off their single reader, FIFO per chat, at most 4 gate
transcriptions at once.
In a group with require_mention + mention_patterns, a captionless voice
note was dropped before speech-to-text ran: the mention gate only reads
text, and STT happens later in the runner, so saying the wake word could
never match (#102330). Typing it worked; saying it did not.
With the new opt-in `voice_mention_patterns: true`, a group voice note
that only a wake word could admit is transcribed at the gate and admitted
when the transcript matches. It is off by default because every
unaddressed voice note in the group would then go to the STT provider.
- One shared helper (gateway.platforms.helpers.spoken_mention_clips) and
one transcriber (run_inbound_transcription.transcribe_one_clip, the
runner's own per-clip STT + local fallback).
- Each gate takes a `spoken_mention` flag, so every other rule
(allowed_chats, topics, exclusive mentions, bot loop breaker,
free-response) still applies exactly as before.
- Wired on every adapter whose group gate reads mention_patterns from
text and receives voice: Telegram (new telegram_voice_mention sibling),
WhatsApp (Baileys), Photon and BlueBubbles.
- The turn reuses the gate's transcript by clip content (native admission
re-captures the clip under a new path), so STT runs once per note. A
note that does not match has its clip deleted.
Live on the Telegram stand-in with a real gateway and a local_command
STT: base drops the voice note (0 STT calls, no turn); head transcribes
once, admits it, and the model receives the spoken words. Non-matching
speech and the not-opted-in case stay dropped.
Based on #102369 by @astraltrekkin; not cherry-picked because its commits
conflict with current main on 5 files, and it turned the check on by
default.
Fixes#102330
Co-authored-by: astraltrekkin <164521089+rainbowgits@users.noreply.github.com>
Review M1 (Mark S.): the capture ran only on connect, so a short description
edited in BotFather while Hermes was online was overwritten by the clean
disconnect's Offline write, and turning the indicator off later restored the
older text. Re-read and save the live text before Offline too, in a run whose
first capture succeeded; a failed re-read still skips the destructive write.
Co-authored-by: Mark S. <theoldwizard123@pm.me>
Review fixes on #153096:
- A run whose capture failed (description read or snapshot save) writes
no Online/Offline text: it would overwrite the only copy.
- The snapshot keeps every status text Hermes wrote (capped at 120), so a
renamed status_online/status_offline or an over-long label is still
recognised as ours on the next boot and never saved as the original.
- Turning the indicator off reads the live text first and restores only
when it is still a status Hermes wrote; a newer BotFather text is kept.
extra.status_indicator wrote "Online"/"Offline" into the bot's short
description (its profile text and share-link text) on every connect and
clean disconnect, and never kept what the operator had set in BotFather,
so the real text was lost for good, even after the indicator was turned
off (#78784).
The operator's text is now read before the first "Online" write and saved
per bot in the profile home (telegram_status_description.json), so a
crash, which leaves the status text up, never gets read back as the
original. It is refreshed on each connect, so BotFather edits made while
the gateway was down replace it. With the indicator on, Online/Offline
behave as documented. Turning it off puts the saved text back on the next
connect, once. Live on the Bot API stand-in: base ends at "Offline" after
the indicator is switched off; head ends at the operator's text.
Moved into telegram_status_indicator.py (adapter.py shrinks).
Co-authored-by: Tranquil-Flow <66773372+Tranquil-Flow@users.noreply.github.com>