The Open Framework for Building Agents
fix(teams): show sign-in links only to the person signing in (#4846)
Ben Pankowa1c18f5cc313
diff --git a/.changeset/teams-private-sign-in.md b/.changeset/teams-private-sign-in.mdnew file mode 100644index 000000000..fda9d699c--- /dev/null+++ b/.changeset/teams-private-sign-in.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Teams group chats and channels no longer show connection sign-in links or confirmation codes in the shared thread. The card now has a **Sign in** button, and Teams shows the link only to the person who has to sign in, so another member can't connect their own account under the requester's identity.diff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdxindex c7b4fc61b..5aef35892 100644--- a/docs/channels/teams.mdx+++ b/docs/channels/teams.mdx@@ -87,6 +87,12 @@ By default, submissions use the Teams identity of the user who clicked the card.When a tool approval settles, eve replaces its Adaptive Card with the outcome and responder name. A response rejected by an approval policy leaves the shared card unchanged.+### Connection sign-ins++When a connection needs the person to sign in, eve's `authorization.required` handler posts an Adaptive Card. In a personal chat, the card includes the sign-in link and any confirmation code. In group chats and channels, the shared card only says who has to sign in and has a **Sign in** button (`Action.Execute`). When someone presses it, eve resolves who they are the same way it does for HITL submissions (`onInputResponse`). If that's the person who needs to sign in, eve sends back a card with the link and code, and Teams shows that card only to them. Anyone else is told they can't open it. That way another member can't finish the sign-in with their own account and have it saved under the requester's identity.++If you customize `onMessage` without also setting `onInputResponse`, nobody can open a sign-in from a group chat or channel, because eve rejects every press.+For invokes that aren't HITL, handle them in `onInvoke(ctx, activity)`.### Proactive sessionsdiff --git a/packages/eve/src/channel/pending-authorization.ts b/packages/eve/src/channel/pending-authorization.tsnew file mode 100644index 000000000..d79e51d25--- /dev/null+++ b/packages/eve/src/channel/pending-authorization.ts@@ -0,0 +1,47 @@+import type { Session } from "#channel/session.js";+import type { AuthorizationRequiredStreamEvent } from "#protocol/message.js";++type AuthorizationRequired = AuthorizationRequiredStreamEvent["data"];++/**+ * How many recent events a lookup reads. A pending sign-in holds its turn, so+ * it sits near the tail; reading a bounded window keeps a press in a+ * long-lived thread from replaying the whole session.+ */+const PENDING_AUTHORIZATION_WINDOW = 500;++/**+ * The newest sign-in that `matches` and hasn't completed yet, from the+ * session's recent events. Attempts are keyed by connection name and+ * `attemptId`, so one attempt completing never hides another still pending.+ */+export async function findPendingAuthorization(+ session: Pick<Session, "getEventStream">,+ matches: (event: AuthorizationRequired) => boolean,+): Promise<AuthorizationRequired | undefined> {+ const pending = new Map<string, AuthorizationRequired>();+ const reader = (+ await session.getEventStream({ follow: false, startIndex: -PENDING_AUTHORIZATION_WINDOW })+ ).getReader();+ try {+ for (;;) {+ const next = await reader.read();+ if (next.done) break;+ const event = next.value;+ if (event.type === "authorization.required" && matches(event.data)) {+ const key = attemptKey(event.data);+ pending.delete(key);+ pending.set(key, event.data);+ } else if (event.type === "authorization.completed") {+ pending.delete(attemptKey(event.data));+ }+ }+ } finally {+ await reader.cancel().catch(() => {});+ }+ return [...pending.values()].at(-1);+}++function attemptKey(event: { readonly attemptId?: string; readonly name: string }): string {+ return JSON.stringify([event.name, event.attemptId ?? null]);+}diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.mdindex 4a5aebd4e..fa6de976e 100644--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md@@ -84,7 +84,8 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: || a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ || a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ |-| only the person signing in sees the sign-in link and code | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ❌<sup>[19](#note-19)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ❌<sup>[20](#note-20)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |+| only the person signing in sees the sign-in link and code | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ❌<sup>[19](#note-19)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |+| someone else pressing a sign-in isn't shown its link or code | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[20](#note-20)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[20](#note-20)</sup> | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> || a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ || after signing in, the agent carries on with the request | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ || completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | ✅ | ✅ | ✅ |@@ -102,10 +103,10 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` || --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| an image a person sends reaches the agent with its bytes and type | —<sup>[21](#note-21)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[21](#note-21)</sup> | ✅ | ✅ | ✅ |-| a PDF a person sends reaches the agent with its bytes and type | —<sup>[21](#note-21)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[21](#note-21)</sup> | ✅ | ✅ | ✅ |-| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[21](#note-21)</sup> | —<sup>[22](#note-22)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[21](#note-21)</sup> | ✅ | ✅ | ✅ |-| a file sent earlier in the conversation is still there on a later message | —<sup>[21](#note-21)</sup> | ✅ | ✅ | | ✅ | —<sup>[23](#note-23)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[21](#note-21)</sup> | ✅ | ✅ | ✅ |+| an image a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |+| a PDF a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |+| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[22](#note-22)</sup> | —<sup>[23](#note-23)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |+| a file sent earlier in the conversation is still there on a later message | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |## Notes@@ -127,8 +128,9 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform16. <a id="note-16"></a>Linq's openDM needs the person's phone handle, but a message names its sender by an opaque handle id, so the bot can only say to continue in a direct message17. <a id="note-17"></a>the rule applies only where the conversation is shared or private, and this one is public18. <a id="note-18"></a>the rule applies only where the conversation is public or shared, and this one is private-19. <a id="note-19"></a>the sign-in prompt, link included, is posted to the whole thread-20. <a id="note-20"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified-21. <a id="note-21"></a>the platform has no files a person can send-22. <a id="note-22"></a>the browser sends a file's bytes with the message, so there is no download to fail-23. <a id="note-23"></a>each slash command starts its own session, so no later message shares one with the file+19. <a id="note-19"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified+20. <a id="note-20"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press+21. <a id="note-21"></a>the channel shows no sign-in, so there's nothing to press+22. <a id="note-22"></a>the platform has no files a person can send+23. <a id="note-23"></a>the browser sends a file's bytes with the message, so there is no download to fail+24. <a id="note-24"></a>each slash command starts its own session, so no later message shares one with the filediff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.tsindex a0fe0c222..7a223bf35 100644--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts@@ -157,7 +157,16 @@ const DISCORD_BROKEN = {),};+const SIGN_IN_PRESS_RULE = "someone else pressing a sign-in isn't shown its link or code";++/** The challenge goes privately to the person signing in, so the thread has no sign-in to press. */+const SIGN_IN_SENT_PRIVATELY = {+ [SIGN_IN_PRESS_RULE]:+ "the sign-in goes privately to the person signing in, so the thread shows nothing to press",+} satisfies Partial<Record<ContractRuleName, string>>;+const DISCORD_UNSUPPORTED = {+ [SIGN_IN_PRESS_RULE]: "the channel shows no sign-in, so there's nothing to press","a file sent earlier in the conversation is still there on a later message":"each slash command starts its own session, so no later message shares one with the file",} satisfies Partial<Record<ContractRuleName, string>>;@@ -178,14 +187,6 @@ const TEAMS_BROKEN = {...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalText", "questionPress", "questionText"]),} satisfies Partial<Record<ContractRuleName, BrokenCell>>;-/** The sign-in prompt, link included, goes to the whole thread. */-const SIGN_IN_LINK_POSTED_TO_THREAD = {- "only the person signing in sees the sign-in link and code": {- reason: "the sign-in prompt, link included, is posted to the whole thread",- symptom: /a message everyone sees carried the sign-in (link|code)/u,- },-} satisfies Partial<Record<ContractRuleName, BrokenCell>>;-const TELEGRAM_BROKEN = {...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalPress",@@ -216,7 +217,10 @@ const WEB_CHAT_SINGLE_PERSON =* failure (such as harness breakage) both turn it red.*/const channelConformance = {- "chat-sdk": [{ driver: chatSdkDriver, broken: CHAT_SDK_BROKEN }, { driver: chatSdkTextDriver }],+ "chat-sdk": [+ { driver: chatSdkDriver, broken: CHAT_SDK_BROKEN, unsupported: SIGN_IN_SENT_PRIVATELY },+ { driver: chatSdkTextDriver },+ ],"chat-sdk-dm": [{ dm: true, driver: () => chatSdkDriver("private"), broken: CHAT_SDK_BROKEN }],discord: [{ driver: discordDriver, broken: DISCORD_BROKEN, unsupported: DISCORD_UNSUPPORTED }],"discord-dm": [@@ -254,9 +258,9 @@ const channelConformance = {linq: [{ driver: linqDriver, broken: LINQ_SIGN_IN_NOT_PRIVATE }],"linq-dm": [{ dm: true, driver: () => linqDriver("private") }],photon: [{ driver: photonDriver }],- slack: [{ driver: slackDriver, broken: SLACK_BROKEN }],+ slack: [{ driver: slackDriver, broken: SLACK_BROKEN, unsupported: SIGN_IN_SENT_PRIVATELY }],"slack-dm": [{ dm: true, driver: () => slackDriver("private"), broken: SLACK_BROKEN }],- teams: [{ driver: teamsDriver, broken: { ...TEAMS_BROKEN, ...SIGN_IN_LINK_POSTED_TO_THREAD } }],+ teams: [{ driver: teamsDriver, broken: TEAMS_BROKEN }],"teams-dm": [{ dm: true, driver: () => teamsDriver("private"), broken: TEAMS_BROKEN }],telegram: [{ driver: telegramDriver, broken: TELEGRAM_BROKEN }],"telegram-dm": [{ dm: true, driver: () => telegramDriver("private"), broken: TELEGRAM_BROKEN }],diff --git a/packages/eve/src/internal/testing/channel-conformance/contract.ts b/packages/eve/src/internal/testing/channel-conformance/contract.tsindex aaad5eac0..e1bef9b9c 100644--- a/packages/eve/src/internal/testing/channel-conformance/contract.ts+++ b/packages/eve/src/internal/testing/channel-conformance/contract.ts@@ -886,6 +886,31 @@ const signInRules = [);},},+ {+ rule: "someone else pressing a sign-in isn't shown its link or code",+ source:+ "docs/channels/slack.mdx#render-and-decode-hitl-controls-yourself (a sign-in challenge is a credential)",+ requires: ["another-person", "buttons"],+ variesByConversation: true,+ surfaces: ["shared"],+ async run(conversation) {+ await conversation.say(READ_CALENDAR);+ await conversation.waitForSignIn();+ await conversation.waitForRest();+ const challenges = async () =>+ (await conversation.shownTexts()).filter(+ (text) => text.includes(CALENDAR.url) || text.includes(CALENDAR.userCode),+ ).length;+ const before = await challenges();+ const open = (await conversation.shownOptions()).find((option) =>+ SIGN_IN_OPENERS.test(option.label),+ );+ expect(open, "a Sign in button for Bob to press").toBeDefined();+ await conversation.press(open!, "bob");+ await conversation.waitForRest();+ expect(await challenges(), "Bob's press showed him the sign-in link or code").toBe(before);+ },+ },{rule: "a sign-in without a link shows its instructions",source: "docs/connections/overview.mdx#self-hosted-interactive-oauth",diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.tsindex 4837f4180..d366166d0 100644--- a/packages/eve/src/internal/testing/channel-conformance/harness.ts+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts@@ -163,6 +163,11 @@ export interface ChannelDriver {* {@link postedText}.*/shownMessage?(call: PlatformCall): ShownMessage | undefined;+ /**+ * The message a webhook's JSON answer shows the person who sent it, such as+ * the card Teams shows only whoever pressed an `Action.Execute` button.+ */+ shownReply?(body: unknown): ShownMessage | undefined;/** How the person driving the conversation appears in the platform's text, in any form. */readonly personShownAs?: readonly string[];/**@@ -226,6 +231,8 @@ export interface ChannelConversation {waitForShown(pattern: string | RegExp): Promise<string>;/** Everything the bot has shown that everyone in the conversation sees, joined. */sharedText(): Promise<string>;+ /** Every message the bot has shown anyone, privately or not. */+ shownTexts(): Promise<readonly string[]>;/** Every choice the bot's messages let a person press now, newest message first. */shownOptions(): Promise<readonly RenderedOption[]>;/** Waits for the turn to hold for a sign-in, however the channel shows it. */@@ -507,12 +514,25 @@ function webhookView(dispatch: Dispatch,wait: Wait,): ClientView {+ /** What webhook answers showed the person who sent each request. */+ const answered: ShownMessage[] = [];+ const describe = () =>+ `Platform calls:\n${JSON.stringify(calls, null, 2)}\nWebhook answers:\n${JSON.stringify(answered, null, 2)}`;async function post(request: Request): Promise<void> {const { response, settled } = await dispatch(request);await settled;if (!response.ok) throw new Error(`${driver.name} webhook answered ${response.status}.`);+ if (driver.shownReply === undefined) return;+ const text = await response.text();+ let body: unknown;+ try {+ body = JSON.parse(text);+ } catch {+ return;+ }+ const shown = driver.shownReply(body);+ if (shown !== undefined) answered.push(shown);}- const describe = () => `Platform calls:\n${JSON.stringify(calls, null, 2)}`;/** Where each prompt may next appear: after the call it was last found in. */const promptsFrom = new Map<string, number>();@@ -558,21 +578,25 @@ function webhookView(personShownAs: driver.personShownAs ?? [],personId: driver.personId,nextAddress: driver.nextAddress?.bind(driver),- shown: () =>- calls.flatMap((call) => {+ shown: () => [+ ...calls.flatMap((call) => {const shown = driver.shownMessage?.(call);- if (shown !== undefined) {- const text = [shown.text, ...(shown.links ?? [])].join("\n");- return [{ onlyPerson: shown.onlyPerson === true, options: shown.options, text }];- }+ if (shown !== undefined) return [shownText(shown)];const text = driver.postedText(call);return text === undefined ? [] : [{ onlyPerson: false, options: [], text }];}),+ ...answered.map(shownText),+ ],describe,close: async () => {},};}+function shownText(shown: ShownMessage): ShownText {+ const text = [shown.text, ...(shown.links ?? [])].join("\n");+ return { onlyPerson: shown.onlyPerson === true, options: shown.options, text };+}+/** Starts `driver`'s client with the client host's `fetch` routed to the channel until it closes. */async function openClient(driver: ClientDriver,@@ -911,6 +935,7 @@ async function converse(view.describe,),shownOptions: async () => (await view.shown()).toReversed().flatMap(({ options }) => options),+ shownTexts: async () => (await view.shown()).map(({ text }) => text),sharedText: async () =>(await view.shown()).filter((shown) => !shown.onlyPerson)diff --git a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts b/packages/eve/src/internal/testing/channel-conformance/teams-driver.tsindex 69e04beff..202d0cf52 100644--- a/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/teams-driver.ts@@ -176,14 +176,27 @@ export function teamsDriver(surface: Exclude<Surface, "public"> = "shared"): ChashownMessage(call) {const body = call.body as ActivityBody;if (body.type !== "message") return undefined;- const texts = (adaptiveCard(body)?.body ?? []).flatMap((element) =>- element.type === "TextBlock" && element.text !== undefined ? [element.text] : [],- );return {id: activityIdOf(call),links: linkTargets(adaptiveCard(body)?.actions),options: cardOptions(call),- text: [body.text ?? "", ...texts].join("\n"),+ text: [body.text ?? "", cardText(adaptiveCard(body))].join("\n"),+ };+ },+ shownReply(body) {+ // Teams shows an `Action.Execute` invoke's answer card to the presser alone.+ const reply = body as { readonly type?: string; readonly value?: unknown };+ if (reply.type === "application/vnd.microsoft.activity.message") {+ return { id: "", onlyPerson: true, options: [], text: String(reply.value ?? "") };+ }+ if (reply.type !== "application/vnd.microsoft.card.adaptive") return undefined;+ const card = reply.value as AdaptiveCard;+ return {+ id: "",+ links: linkTargets(card.actions),+ onlyPerson: true,+ options: [],+ text: cardText(card),};},personShownAs: [PERSON.name],@@ -216,12 +229,22 @@ function adaptiveCard(body: ActivityBody): AdaptiveCard | undefined {)?.content;}+function cardText(card: AdaptiveCard | undefined): string {+ return (card?.body ?? [])+ .flatMap((element) =>+ element.type === "TextBlock" && element.text !== undefined ? [element.text] : [],+ )+ .join("\n");+}+function cardOptions(call: PlatformCall): RenderedOption[] {const card = adaptiveCard(call.body as ActivityBody);const activityId = activityIdOf(call);const choiceSet = card?.body?.find((element) => element.type === "Input.ChoiceSet");const submits = (card?.actions ?? []).filter(- (action) => action.type === "Action.Submit" && action.data !== undefined,+ (action) =>+ (action.type === "Action.Submit" || action.type === "Action.Execute") &&+ action.data !== undefined,);// A select renders one ChoiceSet and a single Submit; other choices are one Submit each.if (choiceSet?.choices !== undefined) {diff --git a/packages/eve/src/public/channels/teams/authorization.ts b/packages/eve/src/public/channels/teams/authorization.tsnew file mode 100644index 000000000..0d6d4ae31--- /dev/null+++ b/packages/eve/src/public/channels/teams/authorization.ts@@ -0,0 +1,206 @@+/**+ * Teams connection sign-in cards. A sign-in link is a credential: whoever+ * completes it binds their account to the person who asked. Outside personal+ * chats the shared card carries no link or code, only an `Action.Execute`+ * button; Teams shows the invoke's response card to the presser alone, and+ * eve answers with the challenge only when the presser is that person.+ */++import { findPendingAuthorization } from "#channel/pending-authorization.js";+import type { Session } from "#channel/session.js";+import type { SessionAuthContext } from "#channel/types.js";+import type { AuthorizationRequiredStreamEvent } from "#protocol/message.js";+import type { TeamsChannelAccount, TeamsMessageBody } from "#public/channels/teams/api.js";+import {+ TEAMS_ADAPTIVE_CARD_CONTENT_TYPE,+ teamsInvokeResponse,+} from "#public/channels/teams/hitl.js";+import type { TeamsInvokeActivity } from "#public/channels/teams/inbound.js";+import { createLogger } from "#internal/logging.js";+import { displayProperName } from "#shared/display-name.js";+import { isObject } from "#shared/guards.js";+import { parseJsonObject, type JsonObject } from "#shared/json.js";++const log = createLogger("teams.authorization");++type AuthorizationRequired = AuthorizationRequiredStreamEvent["data"];++const NOT_YOURS = "Only the person who needs to sign in can open this sign-in.";++/** Hidden data property carried by the shared sign-in card's button. */+const TEAMS_AUTHORIZATION_DATA_KEY = "eve_authorization";++/** Identifies one sign-in attempt from the shared card's button press. */+export interface TeamsAuthorizationReveal {+ readonly attemptId?: string;+ readonly name: string;+ readonly replyToActivityId?: string;+}++/** A connection's display name for its sign-in cards (`linear` → `Linear`). */+export function teamsAuthorizationDisplayName(event: {+ readonly authorization?: { readonly displayName?: string };+ readonly name: string;+}): string {+ return event.authorization?.displayName ?? displayProperName(event.name);+}++/** The full sign-in card, link and code included, for the person signing in alone. */+export function renderTeamsAuthorizationPrompt(+ event: AuthorizationRequired,+ options: { readonly adaptiveCardVersion: string; readonly requester: string | undefined },+): TeamsMessageBody {+ const displayName = teamsAuthorizationDisplayName(event);+ const url = event.authorization?.url;+ const instructions = event.authorization?.instructions;+ const userCode = event.authorization?.userCode;+ const codeHint = userCode+ ? `If ${displayName} asks for a confirmation code, enter ${userCode}.`+ : undefined;+ const text = [+ url+ ? `Authorization required for ${displayName}: ${url}`+ : `Authorization required for ${displayName}.`,+ instructions,+ codeHint,+ ]+ .filter(Boolean)+ .join(" ");+ return {+ attachments: [+ adaptiveCard(options.adaptiveCardVersion, {+ actions: url ? [{ title: `Sign in with ${displayName}`, type: "Action.OpenUrl", url }] : [],+ body: [+ heading(`Authorization required for ${displayName}`),+ textBlock(+ options.requester+ ? `Requested by ${options.requester}.`+ : "No triggering user is available for a private prompt.",+ ),+ ...[instructions, codeHint]+ .filter((line): line is string => Boolean(line))+ .map((line) => textBlock(line)),+ ],+ }),+ ],+ text,+ };+}++/** The shared sign-in card: who must sign in, and a button that shows them the challenge. */+export function renderTeamsAuthorizationStatus(+ event: AuthorizationRequired,+ options: {+ readonly adaptiveCardVersion: string;+ readonly replyToActivityId: string | undefined;+ readonly requester: string | undefined;+ },+): TeamsMessageBody {+ const displayName = teamsAuthorizationDisplayName(event);+ const notice = options.requester+ ? `${options.requester} must sign in to continue. Only they can open the sign-in.`+ : "Only the person who needs to sign in can open it.";+ const reveal: TeamsAuthorizationReveal = {+ attemptId: event.attemptId,+ name: event.name,+ replyToActivityId: options.replyToActivityId,+ };+ const text = `Authorization required for ${displayName}. ${notice}`;+ return {+ attachments: [+ adaptiveCard(options.adaptiveCardVersion, {+ actions: [+ {+ data: { [TEAMS_AUTHORIZATION_DATA_KEY]: reveal },+ title: "Sign in",+ type: "Action.Execute",+ verb: "eve.authorization.reveal",+ },+ ],+ body: [heading(`Authorization required for ${displayName}`), textBlock(notice)],+ }),+ ],+ text,+ };+}++/** Reads the sign-in attempt a shared card's button names, or `null` for other invokes. */+export function readTeamsAuthorizationReveal(+ activity: TeamsInvokeActivity,+): TeamsAuthorizationReveal | null {+ const action = isObject(activity.value?.action) ? activity.value.action : null;+ const data = action && isObject(action.data) ? action.data : null;+ const reveal = data?.[TEAMS_AUTHORIZATION_DATA_KEY];+ if (!isObject(reveal) || typeof reveal.name !== "string") return null;+ return {+ attemptId: typeof reveal.attemptId === "string" ? reveal.attemptId : undefined,+ name: reveal.name,+ replyToActivityId:+ typeof reveal.replyToActivityId === "string" ? reveal.replyToActivityId : undefined,+ };+}++/**+ * Answers a press of the shared card's button. The challenge comes from the+ * session's own stream and goes back only when the presser's principal is the+ * one that must sign in; nothing the card carries is trusted for identity.+ */+export async function answerTeamsAuthorizationReveal(input: {+ readonly adaptiveCardVersion: string;+ readonly auth: SessionAuthContext | null;+ readonly presser: TeamsChannelAccount;+ readonly resolveSession: () => Promise<Session | undefined>;+ readonly reveal: TeamsAuthorizationReveal;+}): Promise<JsonObject> {+ // A press nobody can be identified for needs no lookup.+ if (input.auth === null) return teamsInvokeResponse({ message: NOT_YOURS });+ const { name, attemptId } = input.reveal;+ let event: AuthorizationRequired | undefined;+ try {+ const session = await input.resolveSession();+ event =+ session &&+ (await findPendingAuthorization(+ session,+ (candidate) => candidate.name === name && candidate.attemptId === attemptId,+ ));+ } catch (error) {+ log.error("Teams sign-in lookup failed", { error });+ }+ if (event === undefined)+ return teamsInvokeResponse({ message: "This sign-in is no longer active." });+ if (input.auth.principalId !== event.principalId)+ return teamsInvokeResponse({ message: NOT_YOURS });+ const prompt = renderTeamsAuthorizationPrompt(event, {+ adaptiveCardVersion: input.adaptiveCardVersion,+ requester: input.presser.name ?? input.presser.id,+ });+ return parseJsonObject({+ statusCode: 200,+ type: TEAMS_ADAPTIVE_CARD_CONTENT_TYPE,+ value: prompt.attachments?.[0]?.content,+ });+}++function adaptiveCard(+ version: string,+ card: { readonly actions: readonly object[]; readonly body: readonly object[] },+) {+ return {+ content: parseJsonObject({+ $schema: "http://adaptivecards.io/schemas/adaptive-card.json",+ ...card,+ type: "AdaptiveCard",+ version,+ }),+ contentType: TEAMS_ADAPTIVE_CARD_CONTENT_TYPE,+ };+}++function heading(text: string) {+ return { text, type: "TextBlock", weight: "Bolder", wrap: true };+}++function textBlock(text: string) {+ return { text, type: "TextBlock", wrap: true };+}diff --git a/packages/eve/src/public/channels/teams/defaults.test.ts b/packages/eve/src/public/channels/teams/defaults.test.tsindex e8e1cde07..8de894e76 100644--- a/packages/eve/src/public/channels/teams/defaults.test.ts+++ b/packages/eve/src/public/channels/teams/defaults.test.ts@@ -30,7 +30,7 @@ function buildChannelStub(state: Partial<TeamsChannelState> = {}) {return { channel, post, startTyping, update };}-function authRequiredEvent(overrides: { displayName?: string } = {}) {+function authRequiredEvent(overrides: { displayName?: string; userCode?: string } = {}) {return {authorization: { url: "https://connect.example.com/a/sca_1", ...overrides },description: "Authorization required for notion",@@ -102,6 +102,50 @@ describe("defaultEvents authorization.required", () => {});});+describe("defaultEvents authorization.required outside personal chats", () => {+ it.each([+ {+ case: "the turn's own sign-in names whoever sent the message",+ event: { principalId: "teams:TENANT:ALICE" },+ named: "Alice",+ },+ {+ case: "an approver's sign-in names the approver",+ event: { candidateId: "candidate-1", principalId: "teams:TENANT:BOB" },+ named: "Bob",+ },+ {+ case: "an approver's sign-in with no recorded account names nobody",+ event: { candidateId: "candidate-1", principalId: "teams:TENANT:CAROL" },+ named: undefined,+ },+ ])("$case, and shares no link or code", async ({ event, named }) => {+ const { channel, post } = buildChannelStub({+ approvalResponderAccounts: { "teams:TENANT:BOB": { id: "BOB", name: "Bob" } },+ conversationType: "channel",+ triggeringUser: { id: "ALICE", name: "Alice" },+ });++ await defaultEvents["authorization.required"]!(+ { ...authRequiredEvent({ userCode: "CODE-42" }), ...event },+ channel,+ sessionCtx,+ );++ const posted = JSON.stringify(post.mock.calls[0]?.[0]);+ expect(posted).not.toContain("https://connect.example.com/a/sca_1");+ expect(posted).not.toContain("CODE-42");+ expect(posted).toContain(+ named === undefined+ ? "Only the person who needs to sign in can open it."+ : `${named} must sign in to continue.`,+ );+ for (const other of ["Alice", "Bob"].filter((name) => name !== named)) {+ expect(posted).not.toContain(other);+ }+ });+});+describe("defaultEvents authorization.completed", () => {it("restarts the typing indicator after authorization succeeds", async () => {const { channel, startTyping } = buildChannelStub();diff --git a/packages/eve/src/public/channels/teams/defaults.ts b/packages/eve/src/public/channels/teams/defaults.tsindex c8c781204..b217cc49e 100644--- a/packages/eve/src/public/channels/teams/defaults.ts+++ b/packages/eve/src/public/channels/teams/defaults.ts@@ -3,7 +3,16 @@ import type { SessionAuthContext } from "#channel/types.js";import { resolvedPromptAnswer } from "#channel/resolved-prompt.js";import { extractErrorId, formatErrorHint } from "#internal/logging.js";import type { ConnectionAuthorizationOutcome } from "#protocol/message.js";-import { splitTeamsMessageText, type TeamsMention } from "#public/channels/teams/api.js";+import {+ splitTeamsMessageText,+ type TeamsChannelAccount,+ type TeamsMention,+} from "#public/channels/teams/api.js";+import {+ renderTeamsAuthorizationPrompt,+ renderTeamsAuthorizationStatus,+ teamsAuthorizationDisplayName,+} from "#public/channels/teams/authorization.js";import {renderAnsweredInputRequestMessage,renderInputRequestMessage,@@ -11,11 +20,11 @@ import {import type { TeamsInvokeActivity, TeamsMessageActivity } from "#public/channels/teams/inbound.js";import type {TeamsChannelEvents,+ TeamsChannelState,TeamsContext,TeamsInboundResult,} from "#public/channels/teams/teamsChannel.js";import { displayProperName } from "#shared/display-name.js";-import { parseJsonObject } from "#shared/json.js";/** Default auth projection for Teams message actors. */export function defaultTeamsAuth(@@ -165,62 +174,17 @@ export const defaultEvents: TeamsChannelEvents = {},async "authorization.required"(event, channel, _ctx) {- const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);- const url = event.authorization?.url;- const instructions = event.authorization?.instructions;- const userCode = event.authorization?.userCode;- const codeHint = userCode- ? `If ${displayName} asks for a confirmation code, enter ${userCode}.`- : undefined;- const text = [- url- ? `Authorization required for ${displayName}: ${url}`- : `Authorization required for ${displayName}.`,- instructions,- codeHint,- ]- .filter(Boolean)- .join(" ");- const posted = await channel.thread.post({- attachments: [- {- content: parseJsonObject({- $schema: "http://adaptivecards.io/schemas/adaptive-card.json",- actions: url- ? [- {- title: `Sign in with ${displayName}`,- type: "Action.OpenUrl",- url,- },- ]- : [],- body: [- {- text: `Authorization required for ${displayName}`,- type: "TextBlock",- weight: "Bolder",- wrap: true,- },- {- text: channel.state.triggeringUser- ? `Requested by ${channel.state.triggeringUser.name ?? channel.state.triggeringUser.id}.`- : "No triggering user is available for a private prompt.",- type: "TextBlock",- wrap: true,- },- ...[instructions, codeHint]- .filter((line): line is string => Boolean(line))- .map((line) => ({ text: line, type: "TextBlock", wrap: true })),- ],- type: "AdaptiveCard",- version: channel.adaptiveCardVersion,- }),- contentType: "application/vnd.microsoft.card.adaptive",- },- ],- text,- });+ const user = signInAccount(event, channel.state);+ const options = {+ adaptiveCardVersion: channel.adaptiveCardVersion,+ replyToActivityId: channel.teams.replyToActivityId,+ requester: user ? (user.name ?? user.id) : undefined,+ };+ const posted = await channel.thread.post(+ channel.state.conversationType === "personal"+ ? renderTeamsAuthorizationPrompt(event, options)+ : renderTeamsAuthorizationStatus(event, options),+ );if (posted.id) {channel.state.pendingAuthActivityId = posted.id;}@@ -233,9 +197,8 @@ export const defaultEvents: TeamsChannelEvents = {const activityId = channel.state.pendingAuthActivityId;if (!activityId) return;- const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);const text = buildAuthCompletedText({- displayName,+ displayName: teamsAuthorizationDisplayName(event),outcome: event.outcome as ConnectionAuthorizationOutcome,reason: event.reason,});@@ -244,6 +207,23 @@ export const defaultEvents: TeamsChannelEvents = {},};+/**+ * The Teams account that must sign in. An approver's sign-in names the+ * approver, recorded when they pressed the approval, not whoever sent the+ * turn's message.+ */+function signInAccount(+ event: { readonly candidateId?: string; readonly principalId?: string },+ state: TeamsChannelState,+): TeamsChannelAccount | null {+ const responder =+ event.principalId === undefined+ ? undefined+ : state.approvalResponderAccounts?.[event.principalId];+ if (responder !== undefined) return responder;+ return event.candidateId === undefined ? state.triggeringUser : null;+}+/** A connection name for the Teams auth card (`linear` → `Linear`). */export function formatConnectionDisplayName(connectionName: string): string {return displayProperName(connectionName);diff --git a/packages/eve/src/public/channels/teams/hitl.ts b/packages/eve/src/public/channels/teams/hitl.tsindex 1f09cde73..bbb3fd12c 100644--- a/packages/eve/src/public/channels/teams/hitl.ts+++ b/packages/eve/src/public/channels/teams/hitl.ts@@ -20,7 +20,7 @@ import {TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH,} from "#public/channels/teams/limits.js";import { isObject } from "#shared/guards.js";-import { parseJsonObject } from "#shared/json.js";+import { parseJsonObject, type JsonObject } from "#shared/json.js";/** Adaptive Card attachment content type used by Teams. */export const TEAMS_ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive";@@ -204,7 +204,7 @@ export function teamsInvokeResponse(readonly message?: string;readonly statusCode?: number;} = {},-): Record<string, unknown> {+): JsonObject {return {statusCode: input.statusCode ?? 200,type: "application/vnd.microsoft.activity.message",diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 9025368f9..9c8276bd7 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -615,6 +615,141 @@ function messageActivity(input: { readonly conversationType: string }): Record<s};}+describe("teamsChannel sign-in button", () => {+ const SIGN_IN_URL = "https://connect.example.test/a/attempt-1";+ const required = (data: Record<string, unknown> = {}) =>+ makeEvent("authorization.required", {+ attemptId: "attempt-1",+ authorization: { url: SIGN_IN_URL, userCode: "CODE-42" },+ description: "Sign in to linear",+ name: "linear",+ principalId: "teams:TENANT:USER",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-1",+ ...data,+ });+ const completed = makeEvent("authorization.completed", {+ attemptId: "attempt-1",+ name: "linear",+ outcome: "declined",+ sequence: 1,+ stepIndex: 0,+ turnId: "turn-1",+ });++ function sessionWith(events: readonly UnstampedMessageStreamEvent[]) {+ return {+ getEventStream: async () =>+ new ReadableStream({+ start(controller) {+ for (const event of events) controller.enqueue(event);+ controller.close();+ },+ }),+ getStreamTailIndex: async () => events.length - 1,+ };+ }++ function press(from: Record<string, unknown> = { id: "USER", name: "Ada" }) {+ return {+ ...baseActivity({ conversationType: "channel" }),+ from,+ name: "adaptiveCard/action",+ type: "invoke",+ value: {+ action: {+ data: {+ eve_authorization: {+ attemptId: "attempt-1",+ name: "linear",+ replyToActivityId: "THREAD_ROOT",+ },+ },+ type: "Action.Execute",+ verb: "eve.authorization.reveal",+ },+ },+ };+ }++ it("answers the person signing in with a card only they see, carrying the link and code", async () => {+ const resolveSession = vi.fn(async () => sessionWith([required()]));+ const channel = teamsChannel({ credentials: { webhookVerifier: () => true } });++ const { response } = await firePost(channel, press(), { resolveSession });++ const body = await response.json();+ expect(resolveSession).toHaveBeenCalledWith("TENANT:CONV:THREAD_ROOT");+ expect(body).toMatchObject({ type: "application/vnd.microsoft.card.adaptive" });+ expect(JSON.stringify(body)).toContain(SIGN_IN_URL);+ expect(JSON.stringify(body)).toContain("CODE-42");+ });++ it.each([+ {+ case: "someone else presses it",+ config: {},+ events: [required()],+ from: { id: "USER-BOB", name: "Bob" },+ reply: "Only the person who needs to sign in can open this sign-in.",+ },+ {+ case: "the attempt has no principal",+ config: {},+ events: [required({ principalId: undefined })],+ from: undefined,+ reply: "Only the person who needs to sign in can open this sign-in.",+ },+ {+ case: "onInputResponse rejects the press",+ config: { onInputResponse: () => null },+ events: [required()],+ from: undefined,+ reply: "Only the person who needs to sign in can open this sign-in.",+ },+ {+ case: "onInputResponse throws",+ config: {+ onInputResponse: () => {+ throw new Error("directory lookup failed");+ },+ },+ events: [required()],+ from: undefined,+ reply: "Only the person who needs to sign in can open this sign-in.",+ },+ {+ case: "the attempt already completed",+ config: {},+ events: [required(), completed],+ from: undefined,+ reply: "This sign-in is no longer active.",+ },+ {+ case: "the thread has no session",+ config: {},+ events: undefined,+ from: undefined,+ reply: "This sign-in is no longer active.",+ },+ ])("withholds the sign-in when $case", async ({ config, events, from, reply }) => {+ const channel = teamsChannel({ credentials: { webhookVerifier: () => true }, ...config });++ const { response } = await firePost(channel, press(from), {+ resolveSession: async () => (events === undefined ? undefined : sessionWith(events)),+ });++ const body = await response.json();+ expect(body).toEqual({+ statusCode: 200,+ type: "application/vnd.microsoft.activity.message",+ value: reply,+ });+ expect(JSON.stringify(body)).not.toContain(SIGN_IN_URL);+ });+});+function baseActivity(input: { readonly conversationType: string }): Record<string, unknown> {return {channelData: {diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex 3c0103966..25197f40a 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -34,6 +34,11 @@ import {type TeamsOutboundActivity,type TeamsPostedActivity,} from "#public/channels/teams/api.js";+import {+ answerTeamsAuthorizationReveal,+ readTeamsAuthorizationReveal,+ type TeamsAuthorizationReveal,+} from "#public/channels/teams/authorization.js";import {defaultEvents,defaultOnMessage,@@ -381,6 +386,7 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {activity,config,onInputResponse,+ resolveSession,waitUntil,from,});@@ -677,8 +683,12 @@ async function handleInvoke(input: {readonly from: ChannelFrom<TeamsChannelState>;readonly config: TeamsChannelConfig;readonly onInputResponse: NonNullable<TeamsChannelConfig["onInputResponse"]>;+ readonly resolveSession: ChannelResolveSession;readonly waitUntil: (task: Promise<unknown>) => void;}): Promise<Response> {+ const reveal = readTeamsAuthorizationReveal(input.activity);+ if (reveal !== null) return Response.json(await revealAuthorization({ ...input, reveal }));+if (isTeamsInputResponseActivity(input.activity)) {input.waitUntil(dispatchInputResponses({@@ -699,6 +709,36 @@ async function handleInvoke(input: {return teamsOk();}+/** Identifies the presser the same way a HITL card submission does. */+async function revealAuthorization(input: {+ readonly activity: TeamsInvokeActivity;+ readonly config: TeamsChannelConfig;+ readonly onInputResponse: NonNullable<TeamsChannelConfig["onInputResponse"]>;+ readonly resolveSession: ChannelResolveSession;+ readonly reveal: TeamsAuthorizationReveal;+}): Promise<JsonObject> {+ const state = stateFromActivity(input.activity);+ const ctx = buildTeamsBinding({ config: input.config, state });+ let auth: SessionAuthContext | null = null;+ try {+ auth = (await input.onInputResponse(ctx, input.activity))?.auth ?? null;+ } catch (error) {+ log.error("Teams sign-in press authorization failed", { error });+ }+ const token = cardContinuationToken(+ input.activity,+ state,+ input.reveal.replyToActivityId ?? null,+ );+ return await answerTeamsAuthorizationReveal({+ adaptiveCardVersion: input.config.adaptiveCardVersion ?? "1.5",+ auth,+ presser: input.activity.from,+ resolveSession: () => input.resolveSession(token),+ reveal: input.reveal,+ });+}+async function dispatchInputResponses(input: {readonly activity: TeamsInvokeActivity | TeamsMessageActivity;readonly from: ChannelFrom<TeamsChannelState>;@@ -718,10 +758,18 @@ async function dispatchInputResponses(input: {}if (result === null) return;try {- await input.from(resolveInputContinuationToken(input.activity, state)).respond(inputResponses, {- auth: result.auth,- state: approvalResponseStatePatch(input.activity, result.auth),- });+ await input+ .from(+ cardContinuationToken(+ input.activity,+ state,+ readTeamsInputReplyToActivityId(input.activity),+ ),+ )+ .respond(inputResponses, {+ auth: result.auth,+ state: approvalResponseStatePatch(input.activity, result.auth),+ });} catch (error) {log.error("Teams input response delivery failed", { error });}@@ -748,11 +796,12 @@ function stateFromActivity(};}-function resolveInputContinuationToken(+/** Continues the thread a card recorded when posted, or the activity's own thread. */+function cardContinuationToken(activity: TeamsMessageActivity | TeamsInvokeActivity,state: TeamsChannelState,+ replyToActivityId: string | null,): string {- const replyToActivityId = readTeamsInputReplyToActivityId(activity);if (replyToActivityId === null) return stateToken(state);return teamsContinuationToken({conversationId: activity.conversation.id,diff --git a/packages/eve/src/public/channels/telegram/authorization-callback.ts b/packages/eve/src/public/channels/telegram/authorization-callback.tsindex dd9b9cd23..3341ea769 100644--- a/packages/eve/src/public/channels/telegram/authorization-callback.ts+++ b/packages/eve/src/public/channels/telegram/authorization-callback.ts@@ -1,7 +1,6 @@import type { ChannelResolveSession } from "#channel/channel-operations.js";-import type { Session } from "#channel/session.js";+import { findPendingAuthorization } from "#channel/pending-authorization.js";import { createLogger } from "#internal/logging.js";-import type { AuthorizationRequiredStreamEvent } from "#protocol/message.js";import {TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX,renderTelegramAuthorizationPrompt,@@ -38,7 +37,10 @@ export async function dispatchTelegramAuthorizationCallback(input: {await inactiveAuthorization(input.telegram.telegram, input.query.id);return;}- const authorization = await findPendingAuthorization(session);+ const authorization = await findPendingAuthorization(+ session,+ (event) => event.candidateId === undefined,+ );if (authorization === undefined) {await inactiveAuthorization(input.telegram.telegram, input.query.id);return;@@ -46,7 +48,7 @@ export async function dispatchTelegramAuthorizationCallback(input: {await input.telegram.telegram.postEphemeral(input.query.from.id,- renderTelegramAuthorizationPrompt(authorization.data),+ renderTelegramAuthorizationPrompt(authorization),{ callbackQueryId: input.query.id },);await input.telegram.telegram.answerCallbackQuery({@@ -68,28 +70,3 @@ async function inactiveAuthorization(text: "This authorization request is no longer active.",});}--async function findPendingAuthorization(- session: Session,-): Promise<AuthorizationRequiredStreamEvent | undefined> {- const tailIndex = await session.getStreamTailIndex();- if (tailIndex < 0) return undefined;- const events = await session.getEventStream({ startIndex: 0 });- const reader = events.getReader();- let authorization: AuthorizationRequiredStreamEvent | undefined;- try {- for (let index = 0; index <= tailIndex; index += 1) {- const next = await reader.read();- if (next.done) break;- if (- next.value.type === "authorization.required" &&- next.value.data.candidateId === undefined- ) {- authorization = next.value;- }- }- } finally {- await reader.cancel().catch(() => {});- }- return authorization;-}