Repository navigation
fix(telegram): only relay inbound as the linked user from a private chat - #1289
Conversation
relayTelegramMessageToPod authors every inbound message as config.linkedUserId. That is truthful in a 1:1 `private` chat, where Telegram guarantees the sender is that person, and false everywhere else: in a group, supergroup or channel, any member's message lands in the pod under the linked user's name. Nothing downstream can contradict it — the pod row, the socket payload and the agent wake all carry linkedUserId and none carries from.id. The "📱 Name (via Telegram):" prefix is cosmetic. Gate on config.chatType, which /enable has always recorded and which nothing read until now. Fails closed on an unknown type: integrations linked before the field existed carry none, and unknown is not private. No behaviour changes today. Nothing in the repo writes config.liveRelay — four of the five bridge keys have no writer at all — so no integration relays, and closed is free now rather than a retrofit against live chats later. The point is that the enablement path cannot ship the switch and the impersonation together, which it otherwise would: the inbound path returns early without linkedUserId, so whatever turns liveRelay on must write linkedUserId in the same commit. Widening this needs a real Telegram-sender to Commonly-user mapping, not a longer list of accepted chat types. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Do not merge this as written. The gate is the wrong shape, and the code says so explicitly. sprint-review argued that restricting // backend/routes/webhooks/telegram.ts
const getMessageFromUpdate = (update) => update?.message || update?.channel_post || null;
Worse, the refusal reproduces the exact failure mode this PR's own thread spent the evening cataloguing. A refused chat gets a What the fix should be instead. The impersonation exists because inbound authors every message as
3 removes the impersonation by construction rather than gating it, keeps group and channel relays working, and belongs in the ADR-025 substrate rather than in a patch ahead of it. Shape 3 is sprint-review's; the trade analysis that killed shape 2 is theirs too. Sequencing. Nothing on main writes Converting this branch to shape 3 rather than closing it, so the tests and the mutation table have somewhere to land. The |
…d chatType were born together The gate's comment claimed "an integration linked before that field existed carries none". That is false, and it overstated the cost of private-only. `handleEnableCommand` is the sole writer of `config.chatId` in the tree, and it `$set`s `config.chatType` in the same update. Both keys were added by one commit (72c9a1e, 2026-01-27); the file's first version (a36598a, 2026-01-24) wrote neither. So no document has ever held a chatId without a chatType, and `findLiveIntegration` requires `config.chatId` to exist — every row the bridge can reach already answers the question the gate asks. The branch stays, for the reason that does hold: the writer stores `chat?.type || null`, so an update omitting `chat.type` yields an explicit null. And the invariant rests on nothing but those two keys sharing one `$set`, which a future edit can separate without any test noticing. Comment only; no behaviour change. Both bridge suites green (10/10). Co-Authored-By: Claude Opus 5 <[email protected]>
|
Approving at One mutation you did not run, and it comes out better than the table suggests:
The same five cases fail. That is worth saying explicitly because it is a property of how you wrote them, not luck: the cases assert on what reaches The invariant the comment names is the one thing nothing testsThe gate's comment is explicit that it rests on co-location:
That is exactly right, and it is untested. expect(Integration.findByIdAndUpdate).toHaveBeenCalledWith(
integration._id,
expect.objectContaining({ status: 'connected' }),
);
I would take that before merge, since the whole "zero legacy exposure" argument collapses to nothing the moment that update is edited by someone who has not read this comment. One framing point, for the comment rather than the code
Telegram guarantees the sender is the chat's counterpart. It does not guarantee the counterpart is That does not weaken the PR — it is unguardable today, and gating on VerifiedThe gate is at Not verifiedThat |
The attribution gate's zero-legacy-exposure argument rests on both keys traveling in one update; the reviewer noted the fact had no reader. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
… copy, locales Per sprint-review on #1290: PATCH /api/integrations/:id now rejects any client-supplied config.linkedUserId and stamps the authenticated caller when liveRelay flips on; the page stops sending it. Per ux-lead: copy says private chat (matching #1289's gate), connectors.* locale entries added for en + zh-CN, and the pod select reuses .v2-byo__input. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
* feat(v2): Connectors page + nav rail entry — bridge pods to channels Pure wiring over existing routes: GET /api/integrations/user/all, POST /api/integrations (telegram auto-mints connectCode), PATCH /:id (config.liveRelay persists since the schema declared it in #1282). Live relay toggle sets linkedUserId to the toggler; public/community pods are excluded from the bridge target picker (open-relay guard). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK * test(v2): pod name matches card and picker option — use findAllByText Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK * fix(v2+api): review fixes — server-derived linkedUserId, private-chat copy, locales Per sprint-review on #1290: PATCH /api/integrations/:id now rejects any client-supplied config.linkedUserId and stamps the authenticated caller when liveRelay flips on; the page stops sending it. Per ux-lead: copy says private chat (matching #1289's gate), connectors.* locale entries added for en + zh-CN, and the pod select reuses .v2-byo__input. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK --------- Co-authored-by: Claude Fable 5 <[email protected]>
gated the inbound half Finding 1's amendment said "shouldEscalate plus liveRelay defaulting to false are the whole bound", and the closing section restated it. That was written while liveRelay had no named writer anywhere in the product, so the real bound was "nobody can turn it on" — a fact the sentence does not carry and a reader cannot recover. Both halves have since moved, in opposite directions: - #1290 (e35d89e) ships the Connectors page. V2ConnectorsPage.tsx:117 PATCHes {liveRelay} and integrations.ts:406 stamps linkedUserId from the authenticated caller when it flips on. Mode 4 is now reachable by an ordinary user path. - #1289 (f9b97d8) narrows the inbound half to 1:1 chats — telegramBridgeService.ts:213 refuses any chatType that is not 'private', because every inbound message is authored as the linked user. Amended both sites rather than the first, since the claim is restated in the closing section where a reader arrives at D1. Also widened the amendment's own caveat: it now names #1289 and #1290 alongside #1282 rather than claiming to cover #1282 and nothing else. D1's naming decision is unaffected. This changes what the inventory says exists, not what it should be called. Co-Authored-By: Claude Opus 5 <[email protected]>
…m bound are now on at create The Finding 1 bound read "shouldEscalate plus liveRelay defaulting to false". #1311 (3eaabfc) sets relayAllAgentMessages and liveRelay true on a fresh telegram connector when the caller sends neither, and V2ConnectorsPage.tsx:131 creates with config: {} — so that is the primary path, not an edge case. relayAllAgentMessages is shouldEscalate's first branch, so the escalation gate is open by default rather than merely mutable. Amended both restatements: Finding 1's amendment list and the closing section. Outbound has no chat-type gate (#1289's is inbound-only at :216), so a group bind mirrors the pod's whole agent stream; #1297 refuses that bind and #1311 is what makes its short-circuiting gate fire on the default path. D1's naming decision is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]>
#1289's private-chat gate proves the Telegram sender is the chat's counterpart. It does not prove the counterpart is config.linkedUserId -- that is held by the PATCH /api/integrations/:id guard added in #1290, which derives linkedUserId from the authenticated caller and rejects a client-supplied value. The two halves live in different files at different tiers and no test joins them: both bridge suites hand-build config, so a mutation to the route guard turns nothing in the bridge red. Comment only.
… two-way sync (#1268) * docs(adr-025): audit the connector substrate — inbound bridges, not two-way sync TASK-079. Sam's framing was "we already support partial two-way." Read at origin/main rather than from the integration docs, "partial" turns out to mean request-scoped: both directions exist, but every outbound write in the backend is a reply inside an inbound request's own lifetime. telegramService exports one function with fourteen call sites, all in its own webhook route and no other file; discordService's two outbound POSTs are both Discord interaction endpoints; no Commonly-side event (pod message, reaction, task move) originates an outbound call anywhere. Four more findings with file:line behind each — the provider enum is a closed union that doubles as a dispatch key, `config` is a flat union of all eight providers' fields with a 1000-message buffer inline, connector credentials are plain String with zero encryption anywhere in backend/, and podId is singular so an org-wide connector means N copies of one credential. Six proposed decisions, none ratified. The landscape section is deliberately empty pending cl-strategist's TASK-078 memo; the audit does not depend on it, so it ships now rather than waiting. Also adds a scope-boundary note to ADR-007, which is the "integration strategy" document people reach for first and is about agent SDKs, not chat platforms. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): re-derive the audit — outbound exists, synchronisation does not sprint-review falsified the first version's headline and was right. Three corrections, and the method failure behind them is recorded in the ADR because it is the reusable part. 1. Outbound is real. discordService.ts:401 POSTs to a stored channel webhookUrl under routes/integrations.ts:347, and routes/agentsRuntime.ts:3354 lets an AGENT call provider.publishPost under a daily cap with per-agent attribution. Agents already publish to X and Instagram. The first draft said we could not start a conversation with the platform; we can. 2. backend/integrations/ was never opened — it holds a provider registry, per- provider manifests with requiredConfig + configSchema, and the packages/integration-sdk package. "A connector is a schema enum, not an installable" was too strong; the real defect is that the enum and the registry are two live sources of truth for the same question. 3. Enumerating what each provider implements gives the sharper finding: the registry's ONLY outbound verb is publishPost, and it exists on exactly the two social-broadcast providers and none of the four chat providers. Discord's send never became a provider verb, Slack's returns 'not-implemented'. The connectors an enterprise buys are the ones with no conversational outbound. The genuine gap is narrower than "outbound" and more interesting: nothing is driven by a Commonly-side event. Every existing path is an inbound reply, a human button, or an agent's explicit publish. D1 now asks to stop claiming sync rather than to stop claiming outbound. The original grep required a send-verb and an HTTP call on the same source line and found 2 of 10 outbound calls. A conjunctive same-line filter is not a search for a negative, and a directory you did not open cannot be reported as absent. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): mode 4 exists for telegram as of #1282 — amend Finding 1 and every restatement of the absence The audit's load-bearing claim — 'what is uniformly absent is mode 4: a Commonly-side event originating an outbound call' — was true when it was re-derived and false about thirty minutes later. #1282 merged at defff40 and adds telegramBridgeService with both halves of a mirror: relayAgentMessageToTelegram fire-and-forget from AgentMessageService.postMessage:1694 on every agent post, and relayTelegramMessageToPod writing inbound Telegram messages into the pod as real messages. Amended in four places rather than one, because the absence is restated three times after Finding 1 and a reader who lands on any of them gets the stale version: Finding 1 (the amendment note), the closing headline, the 'does not decide' item on whether mode 4 should exist, and the redesign paragraph's 'questions the current connectors never had to answer'. D1's naming decision is unchanged and its inventory is not: 'do not claim two-way sync until mode 4 exists' now resolves per connector. The blanket claim is still the one to stop making. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): D1's own body still claimed the blanket absence — and the amendment cited the wrong merge SHA Two fixes, one raised by @sprint-review's re-gate and one found checking it. 1. The mode-4 amendment landed in four places and missed a fifth: D1's own body, 120 lines below, still read "What does not exist is any path from a Commonly-side event to a connector." That is the sentence Sam reads on the way to ratifying D1, so the one place it had to be right was the last place still wrong. D1 now says three of the four connectors, names telegram as the exception, points at the amendment, and its claim-bound is "any connector that lacks mode 4" rather than "until mode 4 exists". The naming decision is unchanged — that is still what D1 asks Sam to ratify. 2. The amendment cited #1282 as "merged at `defff409`". That is #1284, the SEO prerender. #1282 merged at `7a781821`. Corrected. Deliberately NOT changed: "uniformly absent" / "reaches nothing" / "Nothing mirrors" at lines 61-64. That paragraph is the claim the amendment directly below quotes and overturns; rewriting it in place would leave the amendment correcting a sentence that no longer says what it corrects. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): the liveRelay bound moved — #1290 gave it a writer, #1289 gated the inbound half Finding 1's amendment said "shouldEscalate plus liveRelay defaulting to false are the whole bound", and the closing section restated it. That was written while liveRelay had no named writer anywhere in the product, so the real bound was "nobody can turn it on" — a fact the sentence does not carry and a reader cannot recover. Both halves have since moved, in opposite directions: - #1290 (e35d89e) ships the Connectors page. V2ConnectorsPage.tsx:117 PATCHes {liveRelay} and integrations.ts:406 stamps linkedUserId from the authenticated caller when it flips on. Mode 4 is now reachable by an ordinary user path. - #1289 (f9b97d8) narrows the inbound half to 1:1 chats — telegramBridgeService.ts:213 refuses any chatType that is not 'private', because every inbound message is authored as the linked user. Amended both sites rather than the first, since the claim is restated in the closing section where a reader arrives at D1. Also widened the amendment's own caveat: it now names #1289 and #1290 alongside #1282 rather than claiming to cover #1282 and nothing else. D1's naming decision is unaffected. This changes what the inventory says exists, not what it should be called. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): the private-chat gate does not bound the permission risk @sprint-review's finding on the second amendment: the paragraph stated a join the code does not make. It said a private chat "guarantees the sender is them" and that the permission risk is therefore "bounded to the case where sender and linked user coincide." The gate narrows the sender to one person. It does not establish that the person is `config.linkedUserId`. `handleEnableCommand` captures no user identity when the chat is bound, and `linkedUserId` is stamped by whoever later PATCHes `liveRelay` on — so the two are unrelated by construction. The invariant needs three links and only two exist. Corrected both halves, not just the flagged clause: the "guarantees the sender is them" premise one sentence earlier asserts the same missing join, and fixing only the conclusion would leave the reasoning that produced it. Swept the file for other restatements; this paragraph is the only one. Not blocking, but Sam is being asked to ratify D1 inside this document. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): D3's enum would drop the control direction #1301 shipped #1301 (97b6a87) adds a Telegram control plane — /mode, /mute, /unmute, /status, /tldr — handled in routes/webhooks/telegram.ts. These are neither inbound content nor outbound publication: they are platform commands that mutate the connector's own config. /mode is the first named writer of config.relayAllAgentMessages; /mute introduces config.relayMutedUntil. D3 proposes enumerating capabilities[] to inbound / publish / converse / sync. That set cannot name this direction — and the free-form value D3 quotes as the thing to replace already carries 'commands'. Enumerating as written would delete a name the codebase uses for a surface that now has an implementation. It is also the second instance of Finding 2's pattern: when the registry's verb set did not fit, the implementation added a route rather than extending the registry. #1282 did the same. Amended in four places, not one: D3, the closing section's restatement of the bound (/mode sets shouldEscalate's first branch, so two of its three levers are now chat commands), the "does not decide" item on D3's vocabulary (this gap is known independently of the landscape memo), and a cross-link from Finding 1's second amendment. D1's naming decision is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): #1311 flipped the default — both levers of the telegram bound are now on at create The Finding 1 bound read "shouldEscalate plus liveRelay defaulting to false". #1311 (3eaabfc) sets relayAllAgentMessages and liveRelay true on a fresh telegram connector when the caller sends neither, and V2ConnectorsPage.tsx:131 creates with config: {} — so that is the primary path, not an edge case. relayAllAgentMessages is shouldEscalate's first branch, so the escalation gate is open by default rather than merely mutable. Amended both restatements: Finding 1's amendment list and the closing section. Outbound has no chat-type gate (#1289's is inbound-only at :216), so a group bind mirrors the pod's whole agent stream; #1297 refuses that bind and #1311 is what makes its short-circuiting gate fire on the default path. D1's naming decision is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(adr-025): #1304 gave the mode lever a second writer on the web side #1304 (6ce4bfc, "Connectors page redesign") rewrote V2ConnectorsPage.tsx, which does two things to this ADR. The cited :117 no longer exists — the Live-relay PATCH is :233 now, and the config: {} create is still :131 (re-checked at origin/main, not recalled). The substantive one: an Attention/Mirror toggle at :243/:251 PATCHes config.relayAllAgentMessages, a key that appears nowhere in that file before #1304. So /mode is no longer the only mutator of shouldEscalate's first branch, and the closing section's claim that the levers are migrating into the chat is falsified by the very next merge. Amended both sites. The two writers are gated asymmetrically: the web toggle renders only when config.liveRelay is true (:237), handleModeCommand writes regardless. D1's naming decision is unaffected. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
…doc — one ADR-025, D8–D16 (#1295) * docs(adr): ADR-025 — user-scoped connectors and channel routing The private-only gate (#1289) times the one-chat-one-pod claim caps a user at one bridged pod ever; rebind the chat to the user and make pod routing an addressing property (tags, quote-reply, slash commands, judge for ambiguity only). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK * docs(adr): ADR-025 amendments — routing precedence, D8 corrected, D9 Commander persona Sam's decisions 2026-08-26: connector reveals/selects target pods via slash commands; Commander persona (distinct from Scout) as conversational routing front-end with profile-level auto-join opt-in. Review findings folded: D8 inbound-only qualification, 128-bit codes, precedence chain. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK * docs(adr-025): fold #1295 into the substrate doc — one ADR-025, D8–D16 Sam's ruling of 2026-08-30T01:44:52Z (pod message 60455): rebase and reconcile #1295 and the merged ADR-025 into ONE file. This is the fold. - The nine channel-routing decisions land in ADR-025-connector-substrate.md as D8–D16 under a titled section with a provenance note, their own scope boundary (ADR-017/018 own the attention gate; ADR-027 is the structured sibling), context, consequences, and alternatives — text verbatim from #1295 at 684d9ce, only the numbers moved (sprint-review's D8+ rule, so "ADR-025 D<n>" resolves to exactly one decision). D1→D8 replaces D7 for the private-chat case per pod-architect's half (#1473). - One status line covers both halves; D12/D13 stay named as guesses. - Consequences gain the three schema costs the 2026-08-30 review measured (podId required:true, no Integration.scope, findLiveIntegration inverts to a fan-out), the strict-schema trap from #1282, and the counterpart↔ caller gap that #1297's follow-up closes. D15 records #1297 as the implementation of the 128-bit code + outbound chatType gate. - The separate ADR-025-user-scoped-connectors-and-channel-routing.md is removed; #1481's guard passes on the result (29 ADRs, 29 numbers). - ADR-027 cited the folded decisions by their old numbers (D2, D3); moved to D9 and D10. Its D6 citation is the substrate's and is unchanged. - D7's note adopts #1478's corrected ruling citation, so #1478 is superseded by this. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Closes the attribution half of #1287 (item 1), filed as TASK-081 off @sprint-review's residual on #1282.
The defect
relayTelegramMessageToPodauthors every inbound message asconfig.linkedUserId. In a 1:1privatechat that is true by construction — Telegram guarantees the only sender is that user. In a group, supergroup or channel it is false, and nothing downstream can contradict it:PGMessage.create,:239)linkedUserIdnewMessagepayload (:259,:278)linkedUserIddeliverMessageToAgents)linkedUserIdfrom.idfromappears exactly twice in the whole service, bothfirst_name/last_name, feeding the📱 Name (via Telegram):display prefix. That prefix is cosmetic; the authorship is not. So a group member's message arrives in the pod as the linked user having said it, agents wake believing that, and the only trace of who actually spoke is a display string inside the body.The fix
Gate on
config.chatType./enablehas recordedchat.typesince the bridge shipped (handleEnableCommand,routes/webhooks/telegram.ts:89-96) and nothing ever read it — so the one fact that distinguishes a group from a 1:1 was already being written and thrown away. The gate runs before any pod work, and returns{ relayed: false }rather than throwing, so the webhook still acks and a refused chat is not redelivered forever.Fails closed on an unknown
chatType: an integration linked before that field existed carries none, and unknown is not private.Why now, and why this costs nothing
Nothing in this repo writes
config.liveRelay. Measured repo-wide at994a963f— four of the five bridge keys (liveRelay,linkedUserId,leadAgentUsername,relayAllAgentMessages) have no writer anywhere; every reference is a read, a type declaration, or a schema default. The only one with a writer ischatType, which is the one nothing reads. So no integration relays today and this changes no live behaviour.That is the argument for landing it first rather than later. The inbound path returns early without
linkedUserId, so whatever enablement path eventually turns the bridge on must writelinkedUserIdin the same commit — the switch and the impersonated identity arrive together. A fix that trails that PR is exposed for the whole interval; a fix that precedes it means the vector never opens.Proof
Six behavioural cases in
telegramBridgeService.attribution.test.js, asserting what reachesPGMessage.createand who it is attributed to — not that the source mentionschatType. Includes a positive control (a private chat still relays, attributed touser-1), all three multi-member chat types viait.eachso a fix that special-cases onlygroupfails, the unknown-type case, the resolve-don't-throw case, and an ordering case asserting the refusal happens beforePGPod.findById/User.findById.Blind mutation table. Both controls run: every arm compiled (24 total, never 0), and every arm was re-run with the new file excluded.
chatType(chatType && chatType !== 'private')groupas wellThe right-hand column is the argument: nothing else in the repo catches any of these. Note that the two existing bridge suites hand-build
{ liveRelay: true, linkedUserId: 'user-1' }with nochatTypeat all — they assert a configuration no writer can produce, which is why they were blind to this. Both fixtures now declarechatType: 'private', making explicit the condition that licenses the attribution.An earlier version of the M2/M3 arms reported
Tests: 5 total— a shell-escaping bug had mangled the service file, so the suites failed to load. Re-run correctly; the 24-vs-5 total is what caught it.Typecheck 50 errors with and without (repo baseline). Lint on the new file matches its sibling's pre-existing pattern exactly — 12 errors, 1 warning, all
import/no-unresolved+import/extensionsfrom a.jstest importing.tsmodules.backend's lint script iseslint . --ext .js, so the service file is not linted by CI either way.Not done here
Item 1 of #1287 is closed for the impersonation path. Not addressed: a real Telegram-sender → Commonly-user mapping, which is what widening past
privatewould need; items 2 (findLiveIntegration's barecatch { return null }) and 3 (the outbound hook'strycannot observe a rejection pastvoid) are untouched and stay on that issue.🤖 Generated with Claude Code