A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): bind a QQ bot by scanning a QR code (#504)
Yaowei Zhengc2ab8eada29d
diff --git a/changelog/unreleased/2026-08-27-messaging-qq-scan.md b/changelog/unreleased/2026-08-27-messaging-qq-scan.mdnew file mode 100644index 00000000..b3405b90--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-qq-scan.md@@ -0,0 +1,44 @@+# A QQ bot can be bound by scanning a QR code++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#504](https://github.com/Prism-Shadow/penguin-harness/pull/504)++[中文版](2026-08-27-messaging-qq-scan.zh.md)++Binding a QQ bot required copying an App ID and an App Secret out of the developer console+by hand. The QQ binding editor gained a QR code above those fields: scan it in QQ, pick the+bot, and the credentials arrive on the server. The typed fields were kept below it for the+cases a scan cannot reach.++## Details++- The bind protocol was implemented as three calls against `q.qq.com`: a task registered+ under a fresh AES key, a URL encoded into the QR code (opened by the QQ app, never fetched+ by this server), and a poll that returns the App Secret encrypted under that key.+- **The key was kept out of the browser entirely.** It was generated, held, used and dropped+ server-side; the client was given a task handle, a URL and a status, and the credentials it+ produced were written to storage without passing back through it — the same rule that keeps+ a stored secret from round-tripping through the form.+- Bind tasks were held in memory only, scoped to the Session that started them, bounded per+ Session rather than process-wide so one caller's scans cannot evict another's, and claimed+ by the poll that resolves them: both a replay and a second concurrent poll of one task read+ as 404 rather than as a second bind. Cancelling — including leaving the editor, and giving+ up after a run of failed polls — releases the key at once, and a task nobody came back for+ is swept at its ten-minute TTL rather than at whenever the next scan happens.+- A completed scan was made to **save** the binding and stop there. Enabling stayed the+ separate, exclusive act it is on every channel, so a scan cannot take a bot away from+ another conversation holding it. Starting a scan while this Session's own QQ connection was+ enabled was refused with 409 `messaging_disable_before_scan`, and a scan completing onto a+ live connection was given the same account guard the PUT runs.+- Three routes were added — `POST /messaging/qq/scan`, `…/scan/poll` and `…/scan/cancel` —+ all owner-only: the flow ends in a stored credential however little of it the caller types.+- The QR was generated in the browser and inlined as `<svg>`, so no third party learns the+ task handle from an image request. It was drawn dark-on-white in both themes and given the+ four-module quiet zone the QR spec requires — a code inverted for a dark background scans+ unreliably.+- The polling panel was made to ride out transient errors: a few consecutive poll failures+ leave the code on screen, and a code the platform reports expired is replaced a bounded+ number of times before the panel falls back to offering a new scan.+- Added `uqr` (MIT, no dependencies) as the QR encoder.diff --git a/changelog/unreleased/2026-08-27-messaging-qq-scan.zh.md b/changelog/unreleased/2026-08-27-messaging-qq-scan.zh.mdnew file mode 100644index 00000000..3a5d4915--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-qq-scan.zh.md@@ -0,0 +1,35 @@+# QQ 机器人可以扫码绑定++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#504](https://github.com/Prism-Shadow/penguin-harness/pull/504)++[English](2026-08-27-messaging-qq-scan.md)++绑定 QQ 机器人此前必须从开发者后台里逐字抄下 App ID 与 App Secret。QQ 绑定编辑器在这些字段+上方加了一个二维码:用 QQ 扫码、选择机器人,凭据就到了服务端。手动填写的字段保留在下方,用于+扫码覆盖不到的情形。++## 细节++- 绑定协议实现为对 `q.qq.com` 的三次调用:用新生成的 AES 密钥注册一个任务、把返回的 URL 编码+ 进二维码(由 QQ 客户端打开,本服务端从不请求它),以及轮询取回用该密钥加密的 App Secret。+- **密钥完全没有交给浏览器。** 它在服务端生成、持有、使用并丢弃;客户端拿到的只有任务句柄、+ URL 与状态,由此得到的凭据被直接写入存储而不回传——与「已存密钥不回传表单」是同一条规则。+- 绑定任务只保存在内存,归属发起它的 Session,限量按 Session 而非按进程计,因此一个调用方的+ 扫码任务挤不掉另一个调用方的;任务由「解决它的那一次轮询」认领,重放与对同一任务的并发轮询+ 得到的都是 404,而不是第二次绑定。取消(包括离开编辑器,以及连续轮询失败后放弃)会立刻释放+ 密钥,无人回头的任务也会在十分钟 TTL 到期时被清扫,而不是等到下一次有人发起扫码。+- 扫码成功改为只**保存**绑定,到此为止。启用仍是每个渠道上那个独立且互斥的动作,因此扫码不会+ 把机器人从正在持有它的另一个对话手里夺走。该 Session 自身的 QQ 连接处于启用状态时,发起扫码+ 被拒绝并返回 409 `messaging_disable_before_scan`;在连接被启用期间完成的扫码,则加上了与+ PUT 相同的账号占用检查。+- 新增三个路由——`POST /messaging/qq/scan`、`…/scan/poll` 与 `…/scan/cancel`,全部仅限+ Project 所有者:无论调用方实际输入多少,这个流程的终点都是一份存下来的凭据。+- 二维码改为在浏览器本地生成并以 `<svg>` 内联,因此不会有第三方从图片请求里得知任务句柄。它在+ 明暗两种主题下都画成白底黑码,并保留 QR 规范要求的四模块静区——为深色背景反色的二维码扫描+ 成功率并不可靠。+- 轮询面板改为能扛住临时故障:连续若干次轮询失败之前,二维码不会从屏幕上消失;平台报告已过期+ 的二维码会自动更换,但更换次数有上限,超过后面板退回到「重新发起扫码」。+- 二维码编码库选用 `uqr`(MIT,无依赖)。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 15793473..5a3de4cc 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -314,12 +314,17 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th| POST | /messaging/qq/state | Same contract as the other toggles (400 `qq_secret_required` without a stored secret) || DELETE | /messaging/qq | Remove this channel's config entirely (App Secret included). API completeness only || POST | /messaging/qq/test | Credential probe (the app-access-token exchange) → `{ok, latencyMs?, error?}`. No account label: the platform has no call that identifies the bot |+| POST | /messaging/qq/scan | Start scan-to-connect: the server registers a bind task under a fresh AES key it keeps → `{taskId, qrUrl, pollMs}`. Render `qrUrl` as a QR code; it is opened by the QQ app, never fetched. 409 `messaging_disable_before_scan` while this Session's QQ connection is enabled — a scan rewrites both halves of the credential under a live connector; 502 `qq_scan_failed` when the platform refuses |+| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`. `completed` means the server already decrypted the App Secret and **saved** the binding (enabling stays separate); `expired` means start a new task. 404 `qq_scan_task_unknown` for an unknown, foreign or already-resolved task |+| POST | /messaging/qq/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its key is forgotten now rather than at the sweep || POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` is the one saved field that is not a credential: with it set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap); it defaults to false, an omitted value on a PUT keeps the stored one, and it never applies to the notices or the test message. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.+**Scan-to-connect never shows the browser the key.** The AES key that decrypts the App Secret is generated, held, used and dropped on the server; the client is given only a task handle, a URL to draw, and a status. Tasks live in memory, are scoped to the Session that started them, are bounded per Session so one caller's scans cannot evict another's, and are claimed by the poll that resolves them — so both a replay and a second concurrent poll of one task read as 404 rather than as a second bind. Every scan route is owner-only, because the flow ends in a stored credential however little of it the caller types.+### Preview on a separate originBoth the Files panel's rendered HTML view (an iframe) and "open in a new tab" go through `GET /files/preview-redirect?path=`, which authenticates the caller, then mints a short-lived HMAC token and 302s to a **different origin**:diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 649ffffb..44ee8275 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -313,12 +313,17 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr| POST | /messaging/qq/state | 与其他开关同一契约(无已存密钥时返回 400 `qq_secret_required`) || DELETE | /messaging/qq | 整体删除该渠道的配置(含 App Secret)。仅为 API 完整性保留 || POST | /messaging/qq/test | 凭据探测(换取 app access token)→ `{ok, latencyMs?, error?}`。不报出账号名:平台没有能识别机器人身份的接口 |+| POST | /messaging/qq/scan | 发起扫码连接:服务端用新生成、且不外传的 AES 密钥注册一个绑定任务 → `{taskId, qrUrl, pollMs}`。把 `qrUrl` 渲染成二维码;它由 QQ 客户端打开,浏览器不会请求它。该 Session 的 QQ 连接处于启用状态时返回 409 `messaging_disable_before_scan`——扫码会在在线连接器底下换掉整对凭据;平台拒绝时返回 502 `qq_scan_failed` |+| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`。`completed` 表示服务端已解密 App Secret 并**保存**了绑定(启用仍是独立动作);`expired` 表示需重新建任务。未知、属于其他 Session 或已完成的任务返回 404 `qq_scan_task_unknown` |+| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 || POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 是唯一一个不属于凭据的已存字段:开启后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条);默认为 false,PUT 省略该字段则保持已存值,且它不作用于通知与测试消息。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。+**扫码连接不会把密钥交给浏览器。** 解密 App Secret 的 AES 密钥在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放与对同一任务的并发轮询得到的都是 404,而不是第二次绑定。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。+### 独立源预览Files 面板内的 HTML 渲染视图(iframe)与“新页面打开”都走 `GET /files/preview-redirect?path=`:先鉴权,再签发一枚短时效 HMAC 令牌,然后 302 跳转到**另一个源**:diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 5d919a3d..2ddee8ec 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1936,6 +1936,39 @@ export interface QQTestResponse {error?: string;}+/**+ * POST …/messaging/qq/scan — starts a scan-to-connect flow: the server registers a bind+ * task under a fresh AES key it keeps to itself, and answers with what the browser may+ * know. The key is absent from this type on purpose — it decrypts the App Secret, so it+ * never leaves the server (the same rule that keeps a stored secret from round-tripping).+ */+export interface QQScanStartResponse {+ /** Opaque bind-task handle, passed back to the poll endpoint. */+ taskId: string;+ /** The URL to ENCODE into a QR code. It is opened by the QQ app, never fetched by the browser. */+ qrUrl: string;+ /** How often to poll, in milliseconds (the interval the protocol is designed around). */+ pollMs: number;+}++/**+ * POST …/messaging/qq/scan/poll — one step of the scan. `pending` means keep polling,+ * `expired` means start a new task and show a new QR, and `completed` means the server has+ * already decrypted the App Secret and SAVED the binding: `appId` names the bot that landed.+ * Saving is all it does — enabling the connection stays the separate, exclusive act it is on+ * every channel. A task id that is unknown, belongs to another Session, was already+ * resolved, or is being resolved by a poll still in flight answers 404+ * `qq_scan_task_unknown`: the task is claimed by one poll, so a client whose interval fires+ * before the previous request came back binds once rather than once per overlapping poll.+ */+export interface QQScanPollResponse {+ status: "none" | "pending" | "completed" | "expired";+ /** The bound bot's App ID; present only on `completed`. Never the secret. */+ appId?: string;+ /** The saved binding, present on `completed` so the editor refreshes without a second GET. */+ binding?: QQBindingInfo;+}+/*** POST …/messaging/<channel>/test-message — sent to the last known chat (409* `feishu_no_chat` / `telegram_no_chat` / `qq_no_chat` before one exists). On QQ this candiff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 4cf33408..d1bfb1dc 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -83,6 +83,8 @@ import type { TelegramTransport } from "./runtime/messaging/telegram-api.js";import { QQConnector } from "./runtime/messaging/qq-connector.js";import { createQQTransport } from "./runtime/messaging/qq-api.js";import type { QQTransport } from "./runtime/messaging/qq-api.js";+import { QQScanService, createQQScanTransport } from "./runtime/messaging/qq-scan.js";+import type { QQScanTransport } from "./runtime/messaging/qq-scan.js";import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";import { AdminService } from "./services/admin-service.js";import { DesktopService } from "./services/desktop-service.js";@@ -183,6 +185,8 @@ export interface AppDeps {messagingRepo: MessagingBindingsRepo;/** Messaging bridge — channel connectors + event connections (started by the platform next to the scheduler). */messaging: MessagingBridge;+ /** QQ scan-to-connect: the in-flight bind tasks and the AES keys that never leave the server. */+ qqScan: QQScanService;scheduler: Scheduler;channels: ChannelHub;manager: SessionManager;@@ -224,6 +228,8 @@ export interface BuildDepsOverrides {qqTailFlushMs?: number;/** Test hook: the bridge's pace between a per-line reply's messages (tests collapse it to zero). */messagingLineDelayMs?: number;+ /** Test double: the QQ scan-to-connect transport (avoids real q.qq.com requests). */+ qqScanTransport?: QQScanTransport;/*** Test double: scrypt work factor for password hashes written through this app.* Omitted in production, where the KDF runs at full strength.@@ -774,6 +780,11 @@ export function buildAppDeps(? { lineDelayMs: overrides.messagingLineDelayMs }: {}),});+ // Scan-to-connect holds one AES key per in-flight bind task, in memory only: it decrypts+ // an App Secret, and a task lives for the couple of minutes a person spends scanning.+ const qqScan = new QQScanService(overrides.qqScanTransport ?? createQQScanTransport(), {+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ });const sessionService = new SessionService({root: config.root,sessions: sessionsRepo,@@ -838,6 +849,7 @@ export function buildAppDeps(goalsRepo,errorsRepo,messagingRepo,+ qqScan,messaging,scheduler,channels,diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsindex d3f2d060..4ba05065 100644--- a/packages/server/src/http/routes/messaging.ts+++ b/packages/server/src/http/routes/messaging.ts@@ -20,6 +20,12 @@* and run the two tests; the secret-mutating writes — PUT, the state toggle and DELETE —* are Project-owner-only.*+ * QQ additionally offers a scan-to-connect flow (`/qq/scan…`): the server holds the bind+ * task and the AES key that decrypts the App Secret, polls on the browser's behalf, and+ * stores the result. The browser only ever learns the task handle, the URL to render as a QR+ * code, and the App ID that came back — the same never-round-trip-the-secret rule the PUT+ * handlers follow, applied to a secret that arrives from outside instead of from the user.+ ** A PUT also carries `linePerMessage`, the one saved field that is not a credential: whether* a relayed reply is delivered one message per non-blank line. It is an ordinary form field* applied on Save — omitted keeps the stored value — and it never touches the connection.@@ -45,6 +51,8 @@ import type {MessagingTestMessageResponse,QQBindingInfo,QQBindingResponse,+ QQScanPollResponse,+ QQScanStartResponse,QQTestResponse,TelegramBindingInfo,TelegramBindingResponse,@@ -650,6 +658,97 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {const row = resolveSession(c);deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);deps.messaging.unbind(row.sessionId, "qq");+ // A scan still in flight would land on a config that has just been removed.+ deps.qqScan.cancelSession(row.sessionId);+ return c.body(null, 204);+ });++ // —— QQ scan-to-connect ————————————————————————————————————————————————————+ //+ // The alternative to typing an App ID and an App Secret: the server registers a bind task+ // under a fresh AES key, the browser renders the returned URL as a QR code, the user scans+ // it in QQ, and the completed poll hands back the App Secret encrypted under that key.+ //+ // The key never leaves the server, which is what these three routes are shaped around: the+ // browser is given a task handle, a URL and a status, and the credentials it produces go+ // straight into storage without passing back through it. Owner-only throughout, like every+ // other write here — the flow ends in a stored secret, so it is a credential write however+ // little of it the caller types.++ app.post("/:sessionId/messaging/qq/scan", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ // Disable-first is a server rule, not just a greyed-out button: a scan rewrites BOTH+ // halves of the credential and would point a live connector at whatever account was+ // scanned, which the PUT's account guard exists to prevent it doing silently.+ if (deps.messagingRepo.find(row.sessionId, "qq")?.enabled === true) {+ throw new HttpError(+ 409,+ "messaging_disable_before_scan",+ "Disable the connection before rebinding it by scan.",+ );+ }+ let started: { taskId: string; qrUrl: string; pollMs: number };+ try {+ started = await deps.qqScan.start(row.sessionId);+ } catch (err) {+ throw new HttpError(502, "qq_scan_failed", err instanceof Error ? err.message : String(err));+ }+ return c.json(started satisfies QQScanStartResponse);+ });++ app.post("/:sessionId/messaging/qq/scan/poll", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const body = await readJson(c);+ const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });+ let result: Awaited<ReturnType<typeof deps.qqScan.poll>>;+ try {+ result = await deps.qqScan.poll(row.sessionId, taskId);+ } catch (err) {+ throw new HttpError(502, "qq_scan_failed", err instanceof Error ? err.message : String(err));+ }+ // Unknown, another Session's, already resolved, or claimed by a poll still in flight —+ // neither a replay nor an overlapping poll may re-authorize.+ if (result === null) {+ throw new HttpError(+ 404,+ "qq_scan_task_unknown",+ "This scan is no longer in progress: start a new one.",+ );+ }+ if (result.status !== "completed" || result.bot === undefined) {+ return c.json({ status: result.status } satisfies QQScanPollResponse);+ }+ // The scan landed: store it exactly as the PUT would, including the never-diverge+ // restart of an enabled connector. It stores only — enabling stays the separate act it+ // is on every channel, because enabling is what binds the account and is exclusive.+ //+ // The start refused an enabled binding, so this only fires when the connection was+ // switched on WHILE the scan was in flight. Same guard as the PUT then: an enabled+ // binding re-pointed at an account another Session holds would stand two connections on+ // one bot's single gateway without either passing the enable gate.+ const bound = deps.messagingRepo.find(row.sessionId, "qq");+ if (bound !== null && bound.enabled) guardAccountFree(row.sessionId, "qq", result.bot.appId);+ const saved = deps.messagingRepo.upsert({+ sessionId: row.sessionId,+ channel: "qq",+ accountId: result.bot.appId,+ config: { appId: result.bot.appId, appSecret: result.bot.appSecret },+ });+ if (saved.enabled) await deps.messaging.sync(row.sessionId);+ return c.json({+ status: "completed",+ appId: result.bot.appId,+ binding: toQQInfo(saved),+ } satisfies QQScanPollResponse);+ });++ app.post("/:sessionId/messaging/qq/scan/cancel", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const body = await readJson(c);+ deps.qqScan.cancel(row.sessionId, requireString(body, "taskId", { minLen: 1, maxLen: 500 }));return c.body(null, 204);});diff --git a/packages/server/src/runtime/messaging/qq-scan.ts b/packages/server/src/runtime/messaging/qq-scan.tsnew file mode 100644index 00000000..00e455cf--- /dev/null+++ b/packages/server/src/runtime/messaging/qq-scan.ts@@ -0,0 +1,434 @@+/**+ * QQ scan-to-connect: binding a bot by scanning a QR code in the QQ app instead of copying+ * an App ID and an App Secret out of the developer console by hand.+ *+ * The protocol is three calls against `q.qq.com`, and it is not part of the bot OpenAPI —+ * different host, different envelope (`{retcode, msg, data}` rather than+ * `{err_code, message}`), no access token. That is why it lives beside qq-api.ts rather+ * than inside it.+ *+ * 1. `create_bind_task` is handed a fresh 32-byte AES key and returns a `task_id`.+ * 2. The `task_id` goes into a URL which is ENCODED INTO A QR CODE and never fetched.+ * Scanning it in QQ opens the authorization page for the bots the account owns.+ * 3. `poll_bind_result` is polled every couple of seconds until it reports the scan+ * completed, at which point it returns the bot's App ID and its App Secret encrypted+ * under the key from step 1.+ *+ * ## The key is the whole security model+ *+ * The AES key decrypts an App Secret, so it is exactly as sensitive as the secret itself.+ * It is generated here, held here, used here, and dropped here — it is never returned by+ * any route, never rendered, and never reaches a browser. What the browser learns is the+ * QR URL, a status, and (once bound) the App ID, which is not secret. This is the same+ * never-round-trip-the-secret rule the PUT handlers follow, applied to a flow where the+ * secret arrives from outside rather than from the user.+ *+ * Tencent publishes an npm package that implements this (`@tencent-connect/qqbot-connector`).+ * It is deliberately not used: it is `UNLICENSED` with no license text, its dist is+ * machine-obfuscated, and it depends on a terminal QR renderer — three separate reasons a+ * product that distributes its server and maintains THIRD-PARTY-NOTICES.md cannot take it.+ * The protocol is fifty lines and is reimplemented here, behind an injectable seam, in the+ * style of telegram-api.ts.+ */+import { createDecipheriv, randomBytes } from "node:crypto";++/** Host serving the three bind-task calls (not the bot OpenAPI host). */+export const QQ_SCAN_BASE = "https://q.qq.com";++/**+ * The page a scanned QR opens. It always points at the production host, even when the calls+ * above are made against the test one — the QQ app resolves it, not this server.+ */+export const QQ_SCAN_QR_PAGE = "https://q.qq.com/qqbot/openclaw/connect.html";++/** Overall per-request deadline for the three calls. */+const CALL_TIMEOUT_MS = 15_000;++/** How often a client should poll (the interval the protocol is designed around). */+export const QQ_SCAN_POLL_MS = 2000;++/** AES-256 key length, and what `create_bind_task` is handed (base64) as `key`. */+const QQ_SCAN_KEY_BYTES = 32;++/** AES-GCM framing of `bot_encrypt_secret`: a 12-byte IV in front, a 16-byte tag at the end. */+const GCM_IV_BYTES = 12;+const GCM_TAG_BYTES = 16;++/** Where the scan stands, in the protocol's own vocabulary (0 NONE, 1 PENDING, 2 COMPLETED, 3 EXPIRED). */+export type QQBindStatus = "none" | "pending" | "completed" | "expired";++/** One bot a completed scan authorized: its App ID, and its App Secret still encrypted. */+export interface QQBoundBot {+ appId: string;+ /** Base64 AES-256-GCM ciphertext of the App Secret, under the task's key. */+ encryptedSecret: string;+ userOpenid?: string;+}++export interface QQBindPollResult {+ status: QQBindStatus;+ /**+ * The bots a completed scan returned. The wire hands back ONE bot as a bare object; this+ * is a list because the shape is worth normalizing once and because Tencent's own client+ * wraps it in an array, which is where a future multi-bot response would appear.+ */+ bots: QQBoundBot[];+}++/** The three calls, behind a seam so tests substitute a fake and never open a socket. */+export interface QQScanTransport {+ /** Registers a bind task under a base64 AES key; resolves the task id. */+ createBindTask(key: string): Promise<string>;+ pollBindResult(taskId: string): Promise<QQBindPollResult>;+}++/** `{retcode, msg, data}` — the envelope all three calls share (0 = success). */+interface QQScanEnvelope<T> {+ retcode?: number;+ msg?: string;+ data?: T;+}++/** Readable failure text out of fetch's throw shapes (nothing here may echo a request body: it carries the key). */+function fetchErrorText(err: unknown): string {+ if (err instanceof Error) {+ if (err.name === "TimeoutError" || err.name === "AbortError") return "request timed out";+ const cause = (err as { cause?: unknown }).cause;+ if (cause instanceof Error && cause.message !== "") return cause.message;+ return err.message;+ }+ return String(err);+}++/** The protocol's numeric status, widened to a name (an unknown value reads as pending, not as failure). */+function statusOf(raw: unknown): QQBindStatus {+ switch (Number(raw)) {+ case 0:+ return "none";+ case 2:+ return "completed";+ case 3:+ return "expired";+ default:+ return "pending";+ }+}++/** One `data` entry of a completed poll, in the wire's own field names. */+interface QQBindResultData {+ status?: number | string;+ bot_appid?: number | string;+ bot_encrypt_secret?: string;+ user_openid?: string;+}++/** Normalizes the completed payload, which arrives as one object (and is tolerated as a list). */+function botsOf(data: QQBindResultData | QQBindResultData[] | undefined): QQBoundBot[] {+ const entries = data === undefined ? [] : Array.isArray(data) ? data : [data];+ const bots: QQBoundBot[] = [];+ for (const entry of entries) {+ const appId = entry.bot_appid;+ const secret = entry.bot_encrypt_secret;+ if (appId === undefined || appId === "" || typeof secret !== "string" || secret === "") {+ continue;+ }+ bots.push({+ appId: String(appId),+ encryptedSecret: secret,+ ...(typeof entry.user_openid === "string" ? { userOpenid: entry.user_openid } : {}),+ });+ }+ return bots;+}++/** The production factory: plain HTTPS against q.qq.com. */+export function createQQScanTransport(base = QQ_SCAN_BASE): QQScanTransport {+ const post = async <T>(path: string, payload: Record<string, unknown>): Promise<T> => {+ let res: Response;+ try {+ res = await fetch(`${base}${path}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ } catch (err) {+ throw new Error(`QQ scan request failed: ${fetchErrorText(err)}`);+ }+ const body = (await res.json().catch(() => null)) as QQScanEnvelope<T> | null;+ if (body === null || (body.retcode !== undefined && body.retcode !== 0)) {+ const detail = body?.msg ?? `HTTP ${res.status}`;+ const code = body?.retcode !== undefined ? ` (retcode ${body.retcode})` : "";+ throw new Error(`QQ scan request failed: ${detail}${code}`);+ }+ return body.data as T;+ };++ return {+ async createBindTask(key: string): Promise<string> {+ const data = await post<{ task_id?: string }>("/lite/create_bind_task", { key });+ const taskId = data?.task_id;+ if (typeof taskId !== "string" || taskId === "") {+ throw new Error("QQ scan request failed: no task id was returned");+ }+ return taskId;+ },+ async pollBindResult(taskId: string): Promise<QQBindPollResult> {+ const data = await post<QQBindResultData | QQBindResultData[]>("/lite/poll_bind_result", {+ task_id: taskId,+ });+ const first = Array.isArray(data) ? data[0] : data;+ return { status: statusOf(first?.status), bots: botsOf(data) };+ },+ };+}++/** A fresh base64 AES-256 key for one bind task. */+export function newQQScanKey(): string {+ return randomBytes(QQ_SCAN_KEY_BYTES).toString("base64");+}++/**+ * The URL a QR code encodes. It is never fetched by this server — the QQ app opens it, and+ * `_wv=2` is the in-app webview flag that makes it render as a full-screen page there.+ *+ * `source` is left blank, which is what Tencent's own client sends by default; the+ * authorization page then labels the requester generically. The field's accepted values are+ * not documented, and inventing one risks a page that refuses to load.+ */+export function qqScanQrUrl(taskId: string, source = ""): string {+ return `${QQ_SCAN_QR_PAGE}?task_id=${encodeURIComponent(taskId)}&source=${encodeURIComponent(source)}&_wv=2`;+}++/**+ * Decrypts `bot_encrypt_secret` into the App Secret.+ *+ * The framing is not self-describing, so it is stated here rather than inferred at the call+ * site: base64-decode, then the first 12 bytes are the GCM IV, the LAST 16 are the auth+ * tag, and everything between them is the ciphertext. The key is the base64 `key` from+ * `create_bind_task`, decoded — used raw, with no derivation step.+ *+ * A wrong key, a corrupted payload or a truncated one all fail here as an authentication+ * error rather than as plausible-looking garbage, which is the property that makes storing+ * the result safe without a second check.+ */+export function decryptQQBotSecret(keyBase64: string, encryptedBase64: string): string {+ const key = Buffer.from(keyBase64, "base64");+ const payload = Buffer.from(encryptedBase64, "base64");+ if (key.length !== QQ_SCAN_KEY_BYTES) {+ throw new Error("QQ scan key is not a 32-byte AES key");+ }+ if (payload.length <= GCM_IV_BYTES + GCM_TAG_BYTES) {+ throw new Error("QQ scan payload is too short to contain an encrypted secret");+ }+ const iv = payload.subarray(0, GCM_IV_BYTES);+ const tag = payload.subarray(payload.length - GCM_TAG_BYTES);+ const ciphertext = payload.subarray(GCM_IV_BYTES, payload.length - GCM_TAG_BYTES);+ const decipher = createDecipheriv("aes-256-gcm", key, iv);+ decipher.setAuthTag(tag);+ let plaintext: Buffer;+ try {+ plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);+ } catch {+ // The cause is never echoed: it is a crypto failure on a payload derived from a secret.+ throw new Error("QQ scan result could not be decrypted");+ }+ const secret = plaintext.toString("utf8");+ if (secret === "") throw new Error("QQ scan result decrypted to an empty secret");+ return secret;+}++// ---------------------------------------------------------------------------+// The in-flight task table+// ---------------------------------------------------------------------------++/**+ * How long a bind task is kept. The platform expires tasks on its own and reports it, so+ * this is only the bound on remembering a key for a flow nobody finished — a browser tab+ * closed mid-scan leaves a task that will otherwise never be polled again.+ */+export const QQ_SCAN_TASK_TTL_MS = 10 * 60_000;++/**+ * How many bind tasks ONE Session may keep in flight. This is the ceiling that binds, and+ * it is per-Session rather than process-wide on purpose: starting a scan is reachable by+ * anyone who owns a Project, which is every signed-up user, so a table bounded only across+ * all callers lets one of them in a loop evict everybody else's code. Eviction here can+ * only ever drop the caller's OWN oldest task. Four covers a person with a couple of tabs+ * open who reloads a few times.+ */+const QQ_SCAN_MAX_TASKS_PER_SESSION = 4;++/**+ * Absolute bound on remembered tasks across every Session — a memory backstop, not the+ * ceiling a caller runs into. It sits far above any real deployment's concurrent scans+ * precisely because reaching it evicts across tenants, which the per-Session ceiling exists+ * to keep from happening.+ */+const QQ_SCAN_MAX_TASKS = 4096;++/** One in-flight bind task. The key is the reason this table exists at all. */+interface QQScanTask {+ /** Base64 AES key. NEVER leaves this process (see the module doc). */+ key: string;+ /** The Session that started the scan; another Session's poll is not this task's business. */+ sessionId: string;+ createdAt: number;+ /** A poll is in flight and holds the right to resolve this task (see `poll`). */+ claimed: boolean;+}++/** What a poll tells the caller: where the scan stands, and the credentials once it landed. */+export interface QQScanPoll {+ status: QQBindStatus;+ /** Present only on `completed` — the plaintext pair, for the caller to store. */+ bot?: { appId: string; appSecret: string };+}++export interface QQScanServiceOpts {+ now?: () => number;+}++/**+ * Holds the in-flight bind tasks and their keys.+ *+ * Deliberately in memory: a task is alive for the couple of minutes a person spends+ * scanning, and persisting an AES key that decrypts an App Secret would buy nothing except+ * a second place for it to leak from. A server restart mid-scan loses the task, and the+ * user starts another — which is a strictly better failure than a key at rest.+ *+ * A task is consumed by the poll that resolves it: completed or expired, it is gone, so a+ * replayed poll of the same task id reads as unknown rather than re-authorizing anything.+ * "Consumed" is claimed before the upstream request rather than deleted after it, because+ * the client's poll interval fires whether or not the previous request came back.+ */+export class QQScanService {+ private readonly tasks = new Map<string, QQScanTask>();+ private readonly now: () => number;+ /** The self-re-arming sweep, alive only while a task is remembered (see `armSweep`). */+ private sweepTimer: ReturnType<typeof setTimeout> | null = null;++ constructor(+ private readonly transport: QQScanTransport,+ opts: QQScanServiceOpts = {},+ ) {+ this.now = opts.now ?? (() => Date.now());+ }++ /** Starts a scan: a fresh key, a task registered under it, and the URL for the QR. */+ async start(sessionId: string): Promise<{ taskId: string; qrUrl: string; pollMs: number }> {+ this.sweep();+ const key = newQQScanKey();+ const taskId = await this.transport.createBindTask(key);+ // Evicted after the create rather than before it: a create that failed must not have+ // cost the caller a live code.+ this.evictOwn(sessionId);+ this.tasks.set(taskId, { key, sessionId, createdAt: this.now(), claimed: false });+ this.armSweep();+ return { taskId, qrUrl: qqScanQrUrl(taskId), pollMs: QQ_SCAN_POLL_MS };+ }++ /**+ * Polls one task. Returns null when the task id is not one this Session started (an+ * unknown id, another Session's, one already consumed, or one another poll is resolving+ * right now) — the caller answers 404, which is also what a replay gets.+ */+ async poll(sessionId: string, taskId: string): Promise<QQScanPoll | null> {+ const task = this.tasks.get(taskId);+ if (task === undefined || task.sessionId !== sessionId || task.claimed) return null;+ // CLAIMED before the await, not deleted after it. The client polls on a fixed interval+ // that fires whether or not the previous request came back, so a slow platform leaves+ // several polls of one task overlapping; without the claim every one of them decrypts+ // the secret and binds again. The claim is released below while the task is unresolved.+ task.claimed = true;+ if (this.now() - task.createdAt > QQ_SCAN_TASK_TTL_MS) {+ this.tasks.delete(taskId);+ return { status: "expired" };+ }+ let result: QQBindPollResult;+ try {+ result = await this.transport.pollBindResult(taskId);+ } catch (err) {+ // A request that failed resolved nothing: the task stays pollable, which is what lets+ // the client ride out a transient platform error without dropping the user's code.+ task.claimed = false;+ throw err;+ }+ if (result.status === "expired") {+ this.tasks.delete(taskId);+ return { status: "expired" };+ }+ if (result.status !== "completed") {+ task.claimed = false;+ return { status: result.status };+ }+ // Past here the task is spent whatever happens. Completed with nothing to store, and a+ // payload that will not decrypt, are both states polling again cannot recover from.+ this.tasks.delete(taskId);+ const bot = result.bots[0];+ if (bot === undefined) {+ throw new Error("QQ reported the scan complete but returned no bot");+ }+ const appSecret = decryptQQBotSecret(task.key, bot.encryptedSecret);+ return { status: "completed", bot: { appId: bot.appId, appSecret } };+ }++ /** Drops a task the user walked away from (the editor's cancel, and its unmount). */+ cancel(sessionId: string, taskId: string): void {+ if (this.tasks.get(taskId)?.sessionId === sessionId) this.tasks.delete(taskId);+ }++ /** Session-delete cascade and bind removal: forget anything this Session had in flight. */+ cancelSession(sessionId: string): void {+ for (const [taskId, task] of this.tasks) {+ if (task.sessionId === sessionId) this.tasks.delete(taskId);+ }+ }++ /**+ * Drops this Session's oldest tasks until one more fits under its own ceiling. Scoped to+ * the caller: the whole point of the per-Session ceiling is that filling it takes a code+ * away from nobody else.+ */+ private evictOwn(sessionId: string): void {+ const own = [...this.tasks].filter(([, task]) => task.sessionId === sessionId);+ if (own.length < QQ_SCAN_MAX_TASKS_PER_SESSION) return;+ own.sort((a, b) => a[1].createdAt - b[1].createdAt);+ for (const [taskId] of own.slice(0, own.length - QQ_SCAN_MAX_TASKS_PER_SESSION + 1)) {+ this.tasks.delete(taskId);+ }+ }++ /** Drops expired tasks, then the oldest ones if the table is still over its backstop. */+ private sweep(): void {+ const cutoff = this.now() - QQ_SCAN_TASK_TTL_MS;+ for (const [taskId, task] of this.tasks) {+ if (task.createdAt <= cutoff) this.tasks.delete(taskId);+ }+ if (this.tasks.size < QQ_SCAN_MAX_TASKS) return;+ // Age comes from createdAt rather than from the Map's insertion order, so the backstop+ // keeps picking the oldest however a task came to sit where it does in the table.+ const byAge = [...this.tasks].sort((a, b) => a[1].createdAt - b[1].createdAt);+ for (const [taskId] of byAge.slice(0, this.tasks.size - QQ_SCAN_MAX_TASKS + 1)) {+ this.tasks.delete(taskId);+ }+ }++ /**+ * Keeps one unref'd timer alive while any task is remembered, so a scan the user walked+ * away from stops holding its key roughly at the TTL instead of at whenever somebody+ * happens to start the next scan — which may be never, and a key at rest is the one+ * outcome this module is shaped to avoid. It re-arms only while the table is non-empty,+ * and unref'd it is never the reason a process stays alive.+ */+ private armSweep(): void {+ if (this.sweepTimer !== null || this.tasks.size === 0) return;+ const timer = setTimeout(() => {+ this.sweepTimer = null;+ this.sweep();+ this.armSweep();+ }, QQ_SCAN_TASK_TTL_MS);+ timer.unref();+ this.sweepTimer = timer;+ }+}diff --git a/packages/server/test/messaging-qq-scan.test.ts b/packages/server/test/messaging-qq-scan.test.tsnew file mode 100644index 00000000..3278c509--- /dev/null+++ b/packages/server/test/messaging-qq-scan.test.ts@@ -0,0 +1,510 @@+/**+ * QQ scan-to-connect tests: the three-call bind protocol, the AES-GCM framing that carries+ * the App Secret out of it, the in-memory task table, and the routes.+ *+ * The framing is what these tests exist for. `bot_encrypt_secret` is base64 with a 12-byte+ * IV in front and a 16-byte auth tag at the end, and nothing in the payload says so — a+ * wrong offset yields an authentication failure rather than a wrong-looking string, so the+ * round-trip here (encrypted by the test with the standard library, decrypted by the+ * module) is the only thing that can prove the layout is the one Tencent actually sends.+ *+ * The second thing pinned throughout: the AES key never leaves the server. Every route+ * assertion checks the whole response body for it.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createCipheriv, randomBytes } from "node:crypto";+import type {+ QQBindingResponse,+ QQScanPollResponse,+ QQScanStartResponse,+} from "../src/api/types.js";+import type { SessionRow } from "../src/db/repos/sessions.js";+import {+ QQ_SCAN_TASK_TTL_MS,+ QQScanService,+ createQQScanTransport,+ decryptQQBotSecret,+ newQQScanKey,+ qqScanQrUrl,+} from "../src/runtime/messaging/qq-scan.js";+import type { QQBindPollResult, QQScanTransport } from "../src/runtime/messaging/qq-scan.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const SID = "session-2026-08-27-11-00-00-q9100001";+const SID2 = "session-2026-08-27-11-00-01-q9100002";+const SCAN = (sid: string) => `/api/sessions/${sid}/messaging/qq/scan`;+const PROJECT = "birder-default_project";+const APP_ID = "102000042";+const APP_SECRET = "scanned-app-secret-XYZ";++/**+ * Encrypts a secret the way the platform does: AES-256-GCM under the task's key, with the+ * IV prepended and the tag appended, base64. This is the mirror image of the module under+ * test, written against node's crypto rather than against it.+ */+function encryptLikeQQ(keyBase64: string, plaintext: string): string {+ const key = Buffer.from(keyBase64, "base64");+ const iv = randomBytes(12);+ const cipher = createCipheriv("aes-256-gcm", key, iv);+ const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);+ return Buffer.concat([iv, body, cipher.getAuthTag()]).toString("base64");+}++/** Fake bind-task transport: hands out task ids and replays whatever the test queued. */+class FakeScanTransport implements QQScanTransport {+ /** The key each task was created under, so a test can encrypt exactly as the platform would. */+ readonly keys = new Map<string, string>();+ /** What the next poll of a task returns; a task with nothing queued reads as pending. */+ readonly results = new Map<string, QQBindPollResult>();+ createCalls = 0;+ pollCalls = 0;+ /** Non-null makes createBindTask throw with this message. */+ failCreate: string | null = null;+ /** Held open for this long, so a test can have two polls of one task in flight at once. */+ pollDelayMs = 0;+ private next = 1;++ async createBindTask(key: string): Promise<string> {+ this.createCalls++;+ if (this.failCreate !== null) throw new Error(this.failCreate);+ const taskId = `task-${this.next++}`;+ this.keys.set(taskId, key);+ return taskId;+ }++ async pollBindResult(taskId: string): Promise<QQBindPollResult> {+ this.pollCalls++;+ if (this.pollDelayMs > 0) {+ await new Promise((resolve) => setTimeout(resolve, this.pollDelayMs));+ }+ return this.results.get(taskId) ?? { status: "pending", bots: [] };+ }++ /** Arms a task to report a completed scan carrying a properly encrypted secret. */+ complete(taskId: string, appId = APP_ID, secret = APP_SECRET): void {+ const key = this.keys.get(taskId);+ if (key === undefined) throw new Error(`no fake task ${taskId}`);+ this.results.set(taskId, {+ status: "completed",+ bots: [{ appId, encryptedSecret: encryptLikeQQ(key, secret), userOpenid: "user_open_x" }],+ });+ }++ lastTaskId(): string {+ const id = [...this.keys.keys()].at(-1);+ if (id === undefined) throw new Error("no fake task was created");+ return id;+ }+}++function sessionRowOf(sessionId: string, projectId: string): SessionRow {+ return {+ sessionId,+ projectId,+ agentId: "default_agent",+ provider: "custom",+ modelId: "m1",+ workspace: "/tmp/w",+ approvalMode: "allow-all",+ title: null,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ };+}++describe("decryptQQBotSecret", () => {+ it("round-trips the platform's framing: IV in front, tag at the end", () => {+ const key = newQQScanKey();+ expect(Buffer.from(key, "base64")).toHaveLength(32);+ expect(decryptQQBotSecret(key, encryptLikeQQ(key, APP_SECRET))).toBe(APP_SECRET);+ // A secret with multi-byte characters must survive as utf8, not as latin1.+ const unicode = "密钥-secret-✓";+ expect(decryptQQBotSecret(key, encryptLikeQQ(key, unicode))).toBe(unicode);+ });++ it("fails loudly on a wrong key, a tampered payload, or a truncated one", () => {+ const key = newQQScanKey();+ const payload = encryptLikeQQ(key, APP_SECRET);+ // GCM authenticates, so a wrong key cannot yield plausible-looking garbage — which is+ // what makes storing the result safe without a second check.+ expect(() => decryptQQBotSecret(newQQScanKey(), payload)).toThrow(/could not be decrypted/);++ const bytes = Buffer.from(payload, "base64");+ bytes[20] = (bytes[20]! + 1) % 256;+ expect(() => decryptQQBotSecret(key, bytes.toString("base64"))).toThrow(+ /could not be decrypted/,+ );++ // Shorter than IV + tag: rejected before crypto is asked anything.+ expect(() => decryptQQBotSecret(key, Buffer.alloc(20).toString("base64"))).toThrow(/too short/);+ // A key that is not 32 bytes is a programming error, not a crypto failure.+ expect(() => decryptQQBotSecret(Buffer.alloc(16).toString("base64"), payload)).toThrow(+ /32-byte AES key/,+ );+ });+});++describe("qqScanQrUrl", () => {+ it("builds the page URL the QQ app opens, with both values encoded", () => {+ expect(qqScanQrUrl("task/1 2")).toBe(+ "https://q.qq.com/qqbot/openclaw/connect.html?task_id=task%2F1%202&source=&_wv=2",+ );+ expect(qqScanQrUrl("t", "a b")).toContain("source=a%20b");+ });+});++describe("createQQScanTransport", () => {+ const originalFetch = globalThis.fetch;+ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it("reads the {retcode, msg, data} envelope and turns a non-zero retcode into a throw", async () => {+ const calls: Array<{ url: string; body: unknown }> = [];+ globalThis.fetch = (async (url: string, init: { body: string }) => {+ calls.push({ url, body: JSON.parse(init.body) as unknown });+ if (url.endsWith("/lite/create_bind_task")) {+ return new Response(JSON.stringify({ retcode: 0, data: { task_id: "T1" } }));+ }+ return new Response(JSON.stringify({ retcode: 42, msg: "task not found" }));+ }) as unknown as typeof globalThis.fetch;++ const transport = createQQScanTransport();+ expect(await transport.createBindTask("KEY")).toBe("T1");+ expect(calls[0]!.url).toBe("https://q.qq.com/lite/create_bind_task");+ expect(calls[0]!.body).toEqual({ key: "KEY" });++ await expect(transport.pollBindResult("T1")).rejects.toThrow(/task not found \(retcode 42\)/);+ expect(calls[1]!.body).toEqual({ task_id: "T1" });+ });++ it("normalizes the completed payload, which arrives as a bare object", async () => {+ globalThis.fetch = (async () =>+ new Response(+ JSON.stringify({+ retcode: 0,+ data: { status: 2, bot_appid: 102000042, bot_encrypt_secret: "AAAA", user_openid: "u1" },+ }),+ )) as unknown as typeof globalThis.fetch;+ const res = await createQQScanTransport().pollBindResult("T1");+ expect(res.status).toBe("completed");+ // The App ID arrives as a NUMBER on the wire and is stored as text everywhere else.+ expect(res.bots).toEqual([{ appId: "102000042", encryptedSecret: "AAAA", userOpenid: "u1" }]);+ });++ it("maps the status enum, treating an unknown value as still pending", async () => {+ for (const [wire, expected] of [+ [0, "none"],+ [1, "pending"],+ [2, "completed"],+ [3, "expired"],+ [99, "pending"],+ ] as const) {+ globalThis.fetch = (async () =>+ new Response(+ JSON.stringify({ retcode: 0, data: { status: wire } }),+ )) as unknown as typeof globalThis.fetch;+ expect((await createQQScanTransport().pollBindResult("T")).status).toBe(expected);+ }+ });+});++describe("QQScanService", () => {+ it("keeps the key to itself and consumes the task on the poll that resolves it", async () => {+ const transport = new FakeScanTransport();+ const service = new QQScanService(transport);+ const started = await service.start(SID);+ expect(started.qrUrl).toContain(encodeURIComponent(started.taskId));+ // The key exists and is 32 bytes — and is not in anything the caller was handed.+ const key = transport.keys.get(started.taskId)!;+ expect(Buffer.from(key, "base64")).toHaveLength(32);+ expect(JSON.stringify(started)).not.toContain(key);++ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });+ transport.complete(started.taskId);+ expect(await service.poll(SID, started.taskId)).toEqual({+ status: "completed",+ bot: { appId: APP_ID, appSecret: APP_SECRET },+ });+ // Consumed: a replayed poll must not re-authorize anything.+ expect(await service.poll(SID, started.taskId)).toBeNull();+ });++ it("refuses a task another Session started, and an id it never issued", async () => {+ const service = new QQScanService(new FakeScanTransport());+ const started = await service.start(SID);+ expect(await service.poll(SID2, started.taskId)).toBeNull();+ expect(await service.poll(SID, "made-up")).toBeNull();+ });++ it("expires a task by its own clock as well as by the platform's answer", async () => {+ let now = 1_000_000;+ const transport = new FakeScanTransport();+ const service = new QQScanService(transport, { now: () => now });+ const stale = await service.start(SID);+ now += 11 * 60_000;+ expect(await service.poll(SID, stale.taskId)).toEqual({ status: "expired" });+ // Expired locally means gone, without a request to the platform.+ expect(transport.pollCalls).toBe(0);+ expect(await service.poll(SID, stale.taskId)).toBeNull();++ const live = await service.start(SID);+ transport.results.set(live.taskId, { status: "expired", bots: [] });+ expect(await service.poll(SID, live.taskId)).toEqual({ status: "expired" });+ expect(await service.poll(SID, live.taskId)).toBeNull();+ });++ it("hands one of two concurrent polls the result and the other nothing", async () => {+ const transport = new FakeScanTransport();+ const service = new QQScanService(transport);+ const started = await service.start(SID);+ transport.complete(started.taskId);+ // The client polls on a fixed interval that fires whether or not the previous request+ // came back, so a slow platform leaves several polls of one task overlapping. Exactly+ // one of them may decrypt the secret and bind; the rest read as unknown.+ transport.pollDelayMs = 30;+ const [a, b] = await Promise.all([+ service.poll(SID, started.taskId),+ service.poll(SID, started.taskId),+ ]);+ expect([a, b].filter((r) => r?.status === "completed")).toHaveLength(1);+ expect([a, b].filter((r) => r === null)).toHaveLength(1);+ // And the loser did not cost a request either.+ expect(transport.pollCalls).toBe(1);+ });++ it("puts a task back when the platform request itself failed", async () => {+ const transport = new FakeScanTransport();+ const service = new QQScanService(transport);+ const started = await service.start(SID);+ transport.results.set(started.taskId, { status: "pending", bots: [] });+ // A failed request resolved nothing, so the code on screen stays pollable — which is+ // what lets the panel ride out a transient platform error.+ const boom = new Error("bad gateway");+ transport.pollBindResult = async () => {+ throw boom;+ };+ await expect(service.poll(SID, started.taskId)).rejects.toThrow(boom);+ transport.pollBindResult = async () => ({ status: "pending", bots: [] });+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });+ });++ it("bounds tasks per Session, so one caller cannot evict another's code", async () => {+ const transport = new FakeScanTransport();+ const service = new QQScanService(transport);+ const victim = await service.start(SID);+ // A caller in a loop on its own Session. Whatever the ceiling is, it is reached here.+ const attacker: string[] = [];+ for (let i = 0; i < 40; i += 1) attacker.push((await service.start(SID2)).taskId);++ // The eviction stayed inside the attacker's own tasks: its oldest is gone, its newest+ // is not, and the other Session's single code is untouched.+ expect(await service.poll(SID2, attacker[0]!)).toBeNull();+ expect(await service.poll(SID2, attacker.at(-1)!)).toEqual({ status: "pending" });+ expect(await service.poll(SID, victim.taskId)).toEqual({ status: "pending" });+ });++ it("sweeps a task nobody came back for without waiting for the next scan", async () => {+ vi.useFakeTimers();+ try {+ let now = 1_000_000;+ const service = new QQScanService(new FakeScanTransport(), { now: () => now });+ const abandoned = await service.start(SID);+ now += QQ_SCAN_TASK_TTL_MS + 1;+ await vi.advanceTimersByTimeAsync(QQ_SCAN_TASK_TTL_MS + 1);+ // Gone, not merely lapsed: a task still in the table answers "expired" when polled,+ // and only one the sweep already dropped reads as unknown. Nothing else ran — no+ // second scan, no other poll — which is the whole point of the timer.+ expect(await service.poll(SID, abandoned.taskId)).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it("cancelling forgets the key immediately rather than waiting for the sweep", async () => {+ const service = new QQScanService(new FakeScanTransport());+ const started = await service.start(SID);+ // Another Session's cancel is not this task's business.+ service.cancel(SID2, started.taskId);+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });+ service.cancel(SID, started.taskId);+ expect(await service.poll(SID, started.taskId)).toBeNull();++ const second = await service.start(SID);+ service.cancelSession(SID);+ expect(await service.poll(SID, second.taskId)).toBeNull();+ });+});++describe("qq scan routes", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let transport: FakeScanTransport;++ beforeEach(async () => {+ transport = new FakeScanTransport();+ t = await createTestApp({ qqScanTransport: transport });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ t.deps.sessionsRepo.insert(sessionRowOf(SID, PROJECT));+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("starts a scan and hands the browser a task, a URL and a poll interval — never the key", async () => {+ const res = await api.post(SCAN(SID), {});+ expect(res.status).toBe(200);+ const body = (await res.json()) as QQScanStartResponse;+ expect(body.taskId).toBe(transport.lastTaskId());+ expect(body.qrUrl).toContain("https://q.qq.com/qqbot/openclaw/connect.html?task_id=");+ expect(body.pollMs).toBeGreaterThan(0);+ // The AES key decrypts the App Secret: nothing in this response may carry it.+ expect(JSON.stringify(body)).not.toContain(transport.keys.get(body.taskId)!);+ });++ it("a completed poll saves the binding with the App ID as the account, and returns no secret", async () => {+ const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;+ const pending = (await (+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId })+ ).json()) as QQScanPollResponse;+ expect(pending).toEqual({ status: "pending" });++ transport.complete(start.taskId);+ const res = await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });+ expect(res.status).toBe(200);+ const done = (await res.json()) as QQScanPollResponse;+ expect(done.status).toBe("completed");+ expect(done.appId).toBe(APP_ID);+ expect(done.binding?.appSecretMasked).toBe("scan…-XYZ");+ // The plaintext went to storage without passing back through the browser.+ expect(JSON.stringify(done)).not.toContain(APP_SECRET);+ const stored = t.deps.messagingRepo.find(SID, "qq")!;+ expect(stored.accountId).toBe(APP_ID);+ expect(stored.config.appSecret).toBe(APP_SECRET);+ // Saving is all it does: enabling stays the separate, exclusive act.+ expect(stored.enabled).toBe(false);++ // The task is spent — a replay is a 404, not a second bind.+ const replay = await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });+ expect(replay.status).toBe(404);+ expect(((await replay.json()) as { error: { code: string } }).error.code).toBe(+ "qq_scan_task_unknown",+ );+ });++ it("a scanned binding is editable afterwards exactly like a typed one", async () => {+ const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;+ transport.complete(start.taskId);+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });+ // The delivery flag rides a normal PUT with the secret left blank, which keeps it.+ const put = await api.put(`/api/sessions/${SID}/messaging/qq`, {+ appId: APP_ID,+ linePerMessage: true,+ });+ expect(put.status).toBe(200);+ expect(((await put.json()) as QQBindingResponse).binding?.linePerMessage).toBe(true);+ expect(t.deps.messagingRepo.find(SID, "qq")?.config.appSecret).toBe(APP_SECRET);+ });++ it("surfaces a platform failure as a 502 rather than as a broken flow", async () => {+ transport.failCreate = "service temporarily unavailable";+ const res = await api.post(SCAN(SID), {});+ expect(res.status).toBe(502);+ const body = (await res.json()) as { error: { code: string; message: string } };+ expect(body.error.code).toBe("qq_scan_failed");+ expect(body.error.message).toContain("service temporarily unavailable");+ });++ it("cancelling drops the task, and a task is not pollable through another Session", async () => {+ const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;+ expect((await api.post(`${SCAN(SID)}/cancel`, { taskId: start.taskId })).status).toBe(204);+ expect((await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId })).status).toBe(404);++ // The task id is not the authorization, and it is not a bearer handle either: the same+ // owner polling their OWN second Session with it gets nothing.+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));+ const mine = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;+ const crossed = await api.post(`${SCAN(SID2)}/poll`, { taskId: mine.taskId });+ expect(crossed.status).toBe(404);+ // ...and it is still the first Session's to resolve.+ expect((await api.post(`${SCAN(SID)}/poll`, { taskId: mine.taskId })).status).toBe(200);+ });++ it("every scan route is owner-only: a Project member is refused, an outsider sees nothing", async () => {+ const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;++ // A Project member who is not its owner may read bindings and run the probes, but the+ // scan ends in a stored credential, so it sits on the owner-only side like PUT does.+ const { cookie: member } = await provisionUser(t.app, "guest");+ expect((await api.post(`/api/projects/${PROJECT}/members`, { userId: "guest" })).status).toBe(+ 201,+ );+ const memberApi = apiClient(t.app, member);+ for (const res of [+ await memberApi.post(SCAN(SID), {}),+ await memberApi.post(`${SCAN(SID)}/poll`, { taskId: start.taskId }),+ await memberApi.post(`${SCAN(SID)}/cancel`, { taskId: start.taskId }),+ ]) {+ expect(res.status).toBe(403);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("owner_required");+ }++ // A user with no access at all: 404, without leaking that the Session exists.+ const outsider = apiClient(t.app, (await provisionUser(t.app, "stranger")).cookie);+ expect((await outsider.post(SCAN(SID), {})).status).toBe(404);+ });++ it("refuses to start a scan while this Session's QQ connection is enabled", async () => {+ // Enabled straight in the repo: flipping it through the route would stand up a live+ // connector, and what is under test is the scan route's own refusal.+ t.deps.messagingRepo.upsert({+ sessionId: SID,+ channel: "qq",+ accountId: "102000777",+ config: { appId: "102000777", appSecret: "typed-secret" },+ });+ t.deps.messagingRepo.setEnabled(SID, "qq", true);++ const res = await api.post(SCAN(SID), {});+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(+ "messaging_disable_before_scan",+ );+ // Refused before the platform was asked for anything.+ expect(transport.createCalls).toBe(0);+ });++ it("a scan completing onto a connection enabled meanwhile runs the account guard", async () => {+ const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;++ // Another Session holds the very account this scan is about to land on...+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));+ t.deps.messagingRepo.upsert({+ sessionId: SID2,+ channel: "qq",+ accountId: APP_ID,+ config: { appId: APP_ID, appSecret: "held-elsewhere" },+ });+ t.deps.messagingRepo.setEnabled(SID2, "qq", true);+ // ...and this Session's own connection was switched on while the user was scanning,+ // which is the only way past the refusal on start.+ t.deps.messagingRepo.upsert({+ sessionId: SID,+ channel: "qq",+ accountId: "102000888",+ config: { appId: "102000888", appSecret: "typed-secret" },+ });+ t.deps.messagingRepo.setEnabled(SID, "qq", true);++ transport.complete(start.taskId);+ const res = await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(+ "account_enabled_elsewhere",+ );+ // Nothing was stored: the live connector still points where it did.+ expect(t.deps.messagingRepo.find(SID, "qq")?.accountId).toBe("102000888");+ });+});diff --git a/packages/web/package.json b/packages/web/package.jsonindex 0e5f6309..4103e315 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -28,6 +28,7 @@"remark-gfm": "^4.0.0","remark-math": "^6.0.0","shiki": "^4.3.1",+ "uqr": "^0.1.3","zustand": "^5.0.15"},"devDependencies": {diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 7f6b496d..473bc6b4 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -99,6 +99,8 @@ import type {SkillLibraryResponse,QQBindingPutRequest,QQBindingResponse,+ QQScanPollResponse,+ QQScanStartResponse,QQTestRequest,QQTestResponse,RecalledMessageResponse,@@ -570,6 +572,33 @@ export const testTelegramBinding = (sessionId: string, body: TelegramTestRequest{ method: "POST", body },);+/**+ * Starts a QQ scan-to-connect flow. The response carries the URL to render as a QR code and+ * a task handle — never the AES key that decrypts the App Secret, which stays on the server.+ */+export const startQQScan = (sessionId: string) =>+ apiFetch<QQScanStartResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq/scan`,+ {+ method: "POST",+ body: {},+ },+ );++/** One poll of a scan. `completed` means the server already decrypted and SAVED the credentials. */+export const pollQQScan = (sessionId: string, taskId: string) =>+ apiFetch<QQScanPollResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq/scan/poll`,+ { method: "POST", body: { taskId } },+ );++/** Drops a scan the user walked away from, so its key is forgotten rather than left to expire. */+export const cancelQQScan = (sessionId: string, taskId: string) =>+ apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq/scan/cancel`, {+ method: "POST",+ body: { taskId },+ });+/** QQ credential probe (the access-token exchange); the platform names no account, so success carries no label. */export const testQQBinding = (sessionId: string, body: QQTestRequest) =>apiFetch<QQTestResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq/test`, {diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex 2f22c449..e8b287b2 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -30,6 +30,10 @@* screen: the switch carries it as its tooltip and the "what binding does" fold states it* in full. Deleting a stored credential remains a separate act — the per-field clear.*+ * QQ additionally leads its section with scan-to-connect (`qq-scan-connect.tsx`): a QR code+ * scanned in the QQ app, after which the server holds the credentials without them ever+ * passing through this browser. The typed fields stay below it as the fallback.+ ** The GET is re-polled while the host shows the editor (the hook's `poll` flag) so* connect/error flips show up live.*/@@ -56,6 +60,7 @@ import { PasswordInput } from "../../components/ui/password-input";import { Segmented } from "../../components/ui/segmented";import { Switch } from "../../components/ui/switch";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";+import { QQScanConnect } from "./qq-scan-connect";import {bindingsToForm,emptyMessagingForm,@@ -168,6 +173,8 @@ function factsFromList(res: MessagingBindingsResponse): ChannelFactsMap {/** Everything a host renders the editor from: state + handlers, one instance per session. */export interface MessagingBindingEditorState {+ /** The Session being edited (flows that talk to the API from inside the body need it). */+ sessionId: string;/** null until the stored bindings have been loaded (hosts show nothing until then). */form: MessagingFormState | null;patchForm(patch: Partial<MessagingFormState>): void;@@ -188,6 +195,12 @@ export interface MessagingBindingEditorState {toggleBlocked: boolean;/** Why the switch is gated, when a reason is worth showing (null otherwise). */toggleHint: string | null;+ /**+ * A flow OUTSIDE the form saved this channel's binding — QQ's scan-to-connect, whose+ * credentials never pass through the browser. Folds the result into that channel's facts+ * and the form baseline, exactly as a Save would.+ */+ adoptBinding(binding: MessagingBindingInfo): void;save(): Promise<void>;toggleEnabled(next: boolean): Promise<void>;testConnection(): Promise<void>;@@ -440,6 +453,7 @@ export function useMessagingBinding(: null;return {+ sessionId,form,patchForm,selectChannel,@@ -453,6 +467,8 @@ export function useMessagingBinding(testable: form !== null && formTestable(form, facts.secretConfigured),toggleBlocked: enableBlocked || toggling || busy,toggleHint,+ adoptBinding: (binding) =>+ applyChannel(binding.channel, binding, channels[binding.channel].status),save,toggleEnabled,testConnection,@@ -757,6 +773,15 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })</>) : channel === "qq" ? (<>+ {/* The easy path leads: scanning is what most people will do, and the fields below+ are the fallback for a bot the scan cannot reach. Both are inside this channel's+ branch, so nothing above the fields moves when the QR opens. */}+ <QQScanConnect+ sessionId={b.sessionId}+ enabled={facts.enabled}+ onBound={(binding) => b.adoptBinding(binding)}+ />+ <p className="text-xs text-gray-400 dark:text-gray-500">{S.qq.scanOrManual}</p><CornerLinkedFieldlabel={S.qq.appId}required@@ -913,6 +938,10 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })<li key={step}>{step}</li>))}</ol>+ {/* What the QR button spares the reader: the last two steps of the list above.+ Disclosed here rather than parked beside the button, which is a control and so+ cannot be the title a standing sentence would need. */}+ {channel === "qq" && <p className="mt-1.5">{S.qq.scanHint}</p>}<p className="mt-1.5"><ExternalLink href={links.tutorial} label={S.messaging.tutorial} /></p>diff --git a/packages/web/src/features/messaging/qq-scan-connect.tsx b/packages/web/src/features/messaging/qq-scan-connect.tsxnew file mode 100644index 00000000..d7e09b45--- /dev/null+++ b/packages/web/src/features/messaging/qq-scan-connect.tsx@@ -0,0 +1,304 @@+/**+ * QQ scan-to-connect — the alternative to copying an App ID and an App Secret out of the QQ+ * developer console by hand: a QR code, scanned in the QQ app, that hands the credentials+ * straight to the server.+ *+ * What this component may and may not know is the whole design. The server registers a bind+ * task under an AES key it keeps, and this component receives a task handle, a URL, and a+ * status. It never sees the key, and it never sees the App Secret — a completed poll returns+ * the App ID and the saved binding, because the credentials went into storage server-side+ * without passing back through the browser. That is the same rule that keeps a stored secret+ * from round-tripping through the form above it.+ *+ * The QR is rendered from the URL locally rather than fetched as an image: the URL is short,+ * a generated `<svg>` stays crisp at any size, and an image request would put the task handle+ * into a third party's logs.+ *+ * Dark-on-white in both themes, deliberately. A QR inverted for a dark background is read+ * unreliably by phone cameras that assume dark modules on a light field, and a scan that+ * silently fails on half the machines is worse than a white plate in a dark panel.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import { encode } from "uqr";+import type {+ MessagingBindingInfo,+ QQBindingInfo,+ QQScanPollResponse,+} from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { apiErrorText } from "../../lib/api-error";+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { toastError, toastSuccess } from "../../components/ui/toast";++/** Modules of quiet zone around the code — four is what the QR spec asks for. */+const QUIET_ZONE = 4;++/** Rendered edge of the code, in CSS pixels. */+const QR_SIZE_PX = 168;++/** One QR code as an inline SVG: one `<rect>` per dark module, on a white plate. Exported for tests. */+export function QrCode({ value, label }: { value: string; label: string }) {+ const { size, data } = encode(value);+ const span = size + QUIET_ZONE * 2;+ const modules: React.ReactElement[] = [];+ for (let y = 0; y < size; y += 1) {+ for (let x = 0; x < size; x += 1) {+ if (data[y]?.[x] !== true) continue;+ modules.push(+ // Modules are drawn 1.02 wide so neighbours meet: a hairline gap between them at+ // fractional device pixel ratios is what makes a rendered code hard to scan.+ <rect key={`${x}-${y}`} x={x + QUIET_ZONE} y={y + QUIET_ZONE} width={1.02} height={1.02} />,+ );+ }+ }+ return (+ <svg+ viewBox={`0 0 ${span} ${span}`}+ width={QR_SIZE_PX}+ height={QR_SIZE_PX}+ role="img"+ aria-label={label}+ className="shrink-0 rounded-md"+ shapeRendering="crispEdges"+ >+ <rect width={span} height={span} fill="#ffffff" />+ <g fill="#000000">{modules}</g>+ </svg>+ );+}++/**+ * Consecutive poll failures ridden out before the code comes down. The interval fires+ * whether or not the previous request came back, so a single 502 from a busy platform must+ * not take the QR off the screen while the user is still walking to their phone — their+ * scan would then bind nothing and they would never learn why.+ */+const POLL_FAILURES_TOLERATED = 3;++/** How many lapsed codes are replaced automatically before the panel stops asking for another. */+const AUTO_REFRESH_LIMIT = 3;++/** One poll attempt's outcome, as the loop hands it to the classifier. */+export type QQScanAttempt = { ok: true; res: QQScanPollResponse } | { ok: false; error: unknown };++/** What the loop has seen so far, NOT counting the attempt being classified. */+export interface QQScanTally {+ /** Consecutive attempts that failed; any attempt that came back resets it. */+ failures: number;+ /** Codes already replaced automatically after the platform reported one expired. */+ refreshes: number;+}++/** What one attempt tells the panel to do next. */+export type QQScanStep =+ | { kind: "wait" }+ | { kind: "refresh" }+ | { kind: "bound"; appId: string; binding: QQBindingInfo | undefined }+ | {+ kind: "stop";+ notice: string;+ /**+ * The task is still the server's to forget: true when the panel gave up on a task+ * nothing has resolved, false when the platform already reported it expired and the+ * server consumed it on that poll.+ */+ releaseTask: boolean;+ };++/**+ * Classifies one poll attempt — the `updateCheckOutcome` idiom: the decision is a pure+ * function, and the loop around it only carries the tally and performs the effects.+ *+ * Two of the four answers are why this is a function at all. A failed attempt is `wait`+ * until it has failed several times running, so a transient error does not abandon a scan+ * mid-flight. And `refresh` is capped: a platform answering `expired` to tasks it has just+ * created — clock skew, throttling, an outage returning one fixed code — would otherwise+ * loop create/poll for as long as the panel stays open, two requests every couple of+ * seconds, against both this server and QQ.+ */+export function qqScanStep(attempt: QQScanAttempt, tally: QQScanTally): QQScanStep {+ if (!attempt.ok) {+ return tally.failures + 1 < POLL_FAILURES_TOLERATED+ ? { kind: "wait" }+ : {+ kind: "stop",+ notice: S.qq.scanFailed(apiErrorText(attempt.error)),+ releaseTask: true,+ };+ }+ const { res } = attempt;+ if (res.status === "completed") {+ return { kind: "bound", appId: res.appId ?? "", binding: res.binding };+ }+ if (res.status !== "expired") return { kind: "wait" };+ return tally.refreshes + 1 > AUTO_REFRESH_LIMIT+ ? { kind: "stop", notice: S.qq.scanExpiredRepeatedly, releaseTask: false }+ : { kind: "refresh" };+}++/** Where the flow stands, as the panel shows it. */+type ScanPhase =+ | { kind: "idle" }+ | { kind: "starting" }+ | { kind: "waiting"; taskId: string; qrUrl: string; pollMs: number; refreshed: boolean };++export function QQScanConnect({+ sessionId,+ /** The channel's connection is enabled: a scan would rebind a live connector, so it is gated. */+ enabled,+ /** Fired when a scan stored a binding, so the editor refreshes its facts and baseline. */+ onBound,+}: {+ sessionId: string;+ enabled: boolean;+ onBound: (binding: MessagingBindingInfo) => void;+}) {+ const [phase, setPhase] = useState<ScanPhase>({ kind: "idle" });+ /** The task the effects act on, read by the unmount cleanup without re-running it. */+ const taskRef = useRef<string | null>(null);+ /** Set once the component is going away, so an in-flight poll stops writing state. */+ const goneRef = useRef(false);+ /** What `qqScanStep` classifies each attempt against; lives outside React state, like taskRef. */+ const tallyRef = useRef<QQScanTally>({ failures: 0, refreshes: 0 });++ const start = useCallback(+ async (refreshed: boolean) => {+ setPhase({ kind: "starting" });+ // A new task starts a fresh failure count; only a scan the USER asked for starts a+ // fresh refresh count, or the cap on automatic replacement would never be reached.+ tallyRef.current = { failures: 0, refreshes: refreshed ? tallyRef.current.refreshes : 0 };+ try {+ const res = await api.startQQScan(sessionId);+ if (goneRef.current) {+ // Started into a component that is already gone: drop the task rather than leave+ // the server holding a key nobody will ever poll for.+ void api.cancelQQScan(sessionId, res.taskId).catch(() => {});+ return;+ }+ taskRef.current = res.taskId;+ setPhase({+ kind: "waiting",+ taskId: res.taskId,+ qrUrl: res.qrUrl,+ pollMs: res.pollMs,+ refreshed,+ });+ } catch (e) {+ if (goneRef.current) return;+ taskRef.current = null;+ setPhase({ kind: "idle" });+ toastError(S.qq.scanFailed(apiErrorText(e)));+ }+ },+ [sessionId],+ );++ const stop = useCallback(() => {+ const taskId = taskRef.current;+ taskRef.current = null;+ setPhase({ kind: "idle" });+ if (taskId !== null) void api.cancelQQScan(sessionId, taskId).catch(() => {});+ }, [sessionId]);++ // The poll loop. Restarted whenever the task changes and torn down with it; what each+ // answer means is `qqScanStep`'s, so this only carries the tally and does the effects —+ // an expired code is replaced rather than stranding the user in front of a dead one, and+ // giving up releases the task instead of leaving the server holding its key.+ useEffect(() => {+ if (phase.kind !== "waiting") return;+ const { taskId, pollMs } = phase;+ let cancelled = false;+ const timer = setInterval(() => {+ void (async () => {+ if (cancelled) return;+ let attempt: QQScanAttempt;+ try {+ attempt = { ok: true, res: await api.pollQQScan(sessionId, taskId) };+ } catch (error) {+ attempt = { ok: false, error };+ }+ if (cancelled) return;+ const step = qqScanStep(attempt, tallyRef.current);+ tallyRef.current = {+ failures: attempt.ok ? 0 : tallyRef.current.failures + 1,+ refreshes: tallyRef.current.refreshes,+ };+ if (step.kind === "wait") return;+ taskRef.current = null;+ if (step.kind === "refresh") {+ tallyRef.current = { failures: 0, refreshes: tallyRef.current.refreshes + 1 };+ void start(true);+ return;+ }+ setPhase({ kind: "idle" });+ if (step.kind === "bound") {+ toastSuccess(S.qq.scanDone(step.appId));+ if (step.binding !== undefined) onBound(step.binding);+ return;+ }+ // A run of failed polls says nothing about the server, so the task may well still be+ // live: it is released here the way cancel and unmount release one, rather than left+ // holding its key until the sweep.+ if (step.releaseTask) void api.cancelQQScan(sessionId, taskId).catch(() => {});+ toastError(step.notice);+ })();+ }, pollMs);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ // `start` and `onBound` are stable enough for this to key on the task alone; re-running+ // on their identity would restart the poll on every render of the host.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [phase.kind === "waiting" ? phase.taskId : null, sessionId]);++ // Leaving the editor drops the task: the server then forgets its key immediately instead+ // of holding it until the TTL sweep.+ useEffect(() => {+ goneRef.current = false;+ return () => {+ goneRef.current = true;+ const taskId = taskRef.current;+ taskRef.current = null;+ if (taskId !== null) void api.cancelQQScan(sessionId, taskId).catch(() => {});+ };+ }, [sessionId]);++ if (phase.kind !== "waiting") {+ // Just the control. What scanning is and what it spares the user is semantics — read+ // once, then in the way forever — so it is disclosed in the setup fold rather than+ // standing beside the button: a control is not a title for a sentence.+ return (+ <div>+ <Button+ size="sm"+ disabled={phase.kind === "starting" || enabled}+ {...(enabled ? { title: S.qq.scanDisableFirst } : {})}+ onClick={() => void start(false)}+ >+ {phase.kind === "starting" ? S.qq.scanStarting : S.qq.scanStart}+ </Button>+ </div>+ );+ }++ return (+ <div className="flex flex-wrap items-start gap-3 rounded-md border border-gray-200 p-3 dark:border-gray-800">+ <QrCode value={phase.qrUrl} label={S.qq.scanQrLabel} />+ <div className="min-w-0 flex-1 space-y-1.5 text-xs text-gray-500 dark:text-gray-400">+ <p className="text-sm text-gray-700 dark:text-gray-300">{S.qq.scanWaiting}</p>+ <p>{S.qq.scanSteps}</p>+ {/* Only shown once a code has actually lapsed: a standing note that codes expire is+ noise until one does. */}+ {phase.refreshed && (+ <p className="text-gray-400 dark:text-gray-500">{S.qq.scanRefreshed}</p>+ )}+ <p className="text-gray-400 dark:text-gray-500">{S.qq.scanPrivacy}</p>+ <Button size="sm" variant="ghost" onClick={stop}>+ {S.common.cancel}+ </Button>+ </div>+ </div>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 9e0e352a..78f0780c 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1837,6 +1837,31 @@ Scenarios:/** The passive-reply budget, in the terms a user experiences it. */replyBudget:"One QQ message can receive at most 4 replies (5 in a group). When a run produces more than that, the last one carries the rest combined — nothing is lost, it just arrives as a single message.",+ /** Scan-to-connect: the button, and the states it moves through. */+ scanStart: "Connect by QR",+ scanStarting: "Generating code…",+ /** In the setup fold: what scanning saves the user, in one line. */+ scanHint:+ "Or connect by QR: authorize in QQ by scanning, with no App ID or App Secret to copy by hand.",+ scanQrLabel: "QQ bot authorization QR code",+ scanWaiting: "Waiting to be scanned in QQ…",+ scanSteps:+ "Scan the code with QQ on your phone, then pick the bot to authorize on the page it opens and confirm.",+ /** Shown only after a code has actually lapsed and been replaced. */+ scanRefreshed: "The previous code expired; this is a new one.",+ /** Why the secret is safe to obtain this way — the question a careful user will ask. */+ scanPrivacy:+ "The credentials are received and stored by the server; the decryption key never reaches this browser.",+ scanDone: (appId: string): string =>+ `Saved the credentials for bot ${appId} — the connection can be enabled now`,+ scanFailed: (reason: string): string => `Scan-to-connect failed: ${reason}`,+ /** Shown when replacing lapsed codes stopped being worth another round trip. */+ scanExpiredRepeatedly:+ "The code kept expiring before it could be scanned. Try starting a new scan in a moment.",+ /** Why the scan button is gated while this channel holds the connection. */+ scanDisableFirst: "Disable the connection before rebinding by scan",+ /** Separates the scan path from the manual one; the fields below are the fallback, not the default. */+ scanOrManual: "Or enter them by hand",/** The setup FAQ fold's steps. */setupSteps: ["Register as a developer on the QQ open platform and create a bot",@@ -2194,6 +2219,8 @@ Scenarios:"This bot's connection is enabled on another conversation: turn it off there first.",messaging_disable_before_clear:"Disable this channel's connection before clearing its credential.",+ messaging_disable_before_scan:+ "Disable this channel's connection before rebinding it by scan.",},},};diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 52b82381..68831d63 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1799,6 +1799,26 @@ Benchmark:/** The passive-reply budget, in the terms a user experiences it. */replyBudget:"同一条 QQ 消息最多能收到 4 条回复(群聊 5 条)。一次运行产生的消息更多时,最后一条会把余下内容合并发出——内容不会丢失,只是合并成一条。",+ /** Scan-to-connect: the button, and the states it moves through. */+ scanStart: "扫码连接",+ scanStarting: "生成二维码…",+ /** In the setup fold: what scanning saves the user, in one line. */+ scanHint: "也可以扫码连接:用 QQ 扫码授权,无需手动填写 App ID 与 App Secret。",+ scanQrLabel: "QQ 机器人授权二维码",+ scanWaiting: "等待在 QQ 中扫码…",+ scanSteps: "用手机 QQ 扫描二维码,在打开的页面里选择要授权的机器人并确认。",+ /** Shown only after a code has actually lapsed and been replaced. */+ scanRefreshed: "上一个二维码已过期,这是新的。",+ /** Why the secret is safe to obtain this way — the question a careful user will ask. */+ scanPrivacy: "凭据由服务端直接接收并保存,解密密钥不会进入浏览器。",+ scanDone: (appId: string): string => `已保存机器人 ${appId} 的凭据,可以启用连接了`,+ scanFailed: (reason: string): string => `扫码连接失败:${reason}`,+ /** Shown when replacing lapsed codes stopped being worth another round trip. */+ scanExpiredRepeatedly: "二维码多次在扫描前就已过期。请稍后重新发起扫码。",+ /** Why the scan button is gated while this channel holds the connection. */+ scanDisableFirst: "先停用连接,再重新扫码绑定",+ /** Separates the scan path from the manual one; the fields below are the fallback, not the default. */+ scanOrManual: "或手动填写",/** The setup FAQ fold's steps. */setupSteps: ["在 QQ 开放平台注册开发者,创建一个机器人",@@ -2148,6 +2168,7 @@ Benchmark:// this user cannot see, and the remedy does not depend on knowing which one it is.account_enabled_elsewhere: "该机器人的连接已在另一个会话中启用:先在那边停用,再在此启用。",messaging_disable_before_clear: "先停用该渠道的连接,才能清除其凭证。",+ messaging_disable_before_scan: "先停用该渠道的连接,才能重新扫码绑定。",},},};diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex 9d421027..45452e26 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -47,6 +47,7 @@ function stateOf(): MessagingBindingEditorState {const noop = async () => {};return {+ sessionId: "session-under-test",form: emptyMessagingForm(channel),patchForm: () => {},selectChannel: () => {},@@ -60,6 +61,7 @@ function stateOf(testable: false,toggleBlocked: false,toggleHint: null,+ adoptBinding: () => {},save: noop,toggleEnabled: noop,testConnection: noop,@@ -456,6 +458,9 @@ describe("MessagingBindingHelp", () => {// bot and looking for its credentials.expect(qq).toContain('href="https://bot.q.qq.com/wiki/"');expect(qq).toContain(S.qq.setupSteps[0]);+ // What the QR button spares the reader belongs beside those steps, not beside the+ // button: it is semantics, and a control is not a title for a standing sentence.+ expect(qq).toContain(S.qq.scanHint);// The reply budget is how this channel delivers a long answer, not a fault: it rides the// "what binding does" fold, while the passive-reply failure rides troubleshooting.expect(qq).toContain(S.qq.replyBudget);diff --git a/packages/web/test/qq-scan-connect.test.ts b/packages/web/test/qq-scan-connect.test.tsnew file mode 100644index 00000000..3179b584--- /dev/null+++ b/packages/web/test/qq-scan-connect.test.ts@@ -0,0 +1,153 @@+/**+ * The QQ scan-to-connect block: the shape it renders, and the decision the poll loop makes+ * on each answer.+ *+ * Three rendered rules that a type checker cannot see. The QR is generated locally and+ * inlined as `<svg>`, so no third party ever learns the task handle from an image request.+ * It is drawn dark-on-white in BOTH themes rather than inheriting the panel's colours,+ * because a code inverted for a dark background is read unreliably by phone cameras. And it+ * carries the four-module quiet zone the QR spec requires, without which scanners lose the+ * finder patterns against a busy page.+ *+ * The fourth is the one that matters most and is asserted here as well as server-side: the+ * copy tells the reader the decryption key stays on the server, because "why is it safe to+ * let a web page fetch my App Secret" is the question this flow has to answer.+ *+ * The loop itself is tested by value rather than by mounting: this package's vitest runs in+ * `node`, deliberately, so the classification lives in a pure function (`qqScanStep`, the+ * `updateCheckOutcome` idiom) and the effects around it stay a thin shell.+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { encode } from "uqr";+import type { QQBindingInfo, QQScanPollResponse } from "@prismshadow/penguin-server/api";+import { ApiError } from "../src/api/client";+import { QQScanConnect, QrCode, qqScanStep } from "../src/features/messaging/qq-scan-connect";+import type { QQScanTally } from "../src/features/messaging/qq-scan-connect";+import { S, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++const QR_URL = "https://q.qq.com/qqbot/openclaw/connect.html?task_id=t-1&source=&_wv=2";++describe("QrCode", () => {+ it("inlines the code as SVG, with the spec's quiet zone around it", () => {+ const html = renderToStaticMarkup(+ createElement(QrCode, { value: QR_URL, label: S.qq.scanQrLabel }),+ );+ // Four modules of margin on each side: the viewBox is the code plus eight.+ const { size } = encode(QR_URL);+ expect(html).toContain(`viewBox="0 0 ${size + 8} ${size + 8}"`);+ // Generated here, not fetched: nothing in the markup requests an image.+ expect(html).not.toContain("<img");+ expect(html).not.toContain("http");+ expect(html).toContain(`aria-label="${S.qq.scanQrLabel}"`);+ expect(html).toContain('role="img"');+ });++ it("is dark-on-white in both themes rather than inheriting the panel's colours", () => {+ const html = renderToStaticMarkup(+ createElement(QrCode, { value: QR_URL, label: S.qq.scanQrLabel }),+ );+ // Explicit, unconditional colours: a theme-following code is a code that fails to scan+ // for half the people who try it.+ expect(html).toContain('fill="#ffffff"');+ expect(html).toContain('fill="#000000"');+ expect(html).not.toContain("currentColor");+ expect(html).not.toContain("dark:");+ // Crisp module edges, and enough of them to be a real code rather than a blank plate.+ expect(html).toContain('shape-rendering="crispEdges"');+ expect((html.match(/<rect/g) ?? []).length).toBeGreaterThan(100);+ });+});++describe("QQScanConnect", () => {+ const render = (enabled: boolean) =>+ renderToStaticMarkup(+ createElement(QQScanConnect, { sessionId: "session-1", enabled, onBound: () => {} }),+ );++ it("offers the scan as a control alone, with its explanation disclosed elsewhere", () => {+ const html = render(false);+ expect(html).toContain(S.qq.scanStart);+ // What scanning is and what it spares the user is semantics, so it is disclosed in the+ // setup fold. A neighbouring button is not a title for a standing sentence.+ expect(html).not.toContain(S.qq.scanHint);+ // Nothing is requested until the user asks for it: no task exists on first render.+ expect(html).not.toContain(S.qq.scanWaiting);+ });++ it("gates the scan while the connection is enabled, and says why", () => {+ const html = render(true);+ expect(html).toContain("disabled=");+ // A rebind would swap the credentials under a live connector, so it is refused with a+ // reason rather than silently doing it.+ expect(html).toContain(`title="${S.qq.scanDisableFirst}"`);+ expect(render(false)).not.toContain(`title="${S.qq.scanDisableFirst}"`);+ });+});++describe("qqScanStep", () => {+ const fresh: QQScanTally = { failures: 0, refreshes: 0 };+ const ok = (res: QQScanPollResponse) => ({ ok: true, res }) as const;+ const failed = (error: unknown) => ({ ok: false, error }) as const;++ it("keeps waiting while the scan has not happened yet", () => {+ expect(qqScanStep(ok({ status: "pending" }), fresh)).toEqual({ kind: "wait" });+ expect(qqScanStep(ok({ status: "none" }), fresh)).toEqual({ kind: "wait" });+ });++ it("hands the binding on, so the editor adopts it without a second GET", () => {+ const binding = { channel: "qq", appId: "102000042" } as QQBindingInfo;+ expect(qqScanStep(ok({ status: "completed", appId: "102000042", binding }), fresh)).toEqual({+ kind: "bound",+ appId: "102000042",+ binding,+ });+ });++ it("rides out a transient failure rather than taking the code off the screen", () => {+ // The user is walking to their phone when one poll 502s. Tearing the panel down there+ // means their scan lands on a task the panel already abandoned and binds nothing.+ const error = new ApiError(502, "qq_scan_failed", "bad gateway");+ expect(qqScanStep(failed(error), fresh)).toEqual({ kind: "wait" });+ expect(qqScanStep(failed(error), { failures: 1, refreshes: 0 })).toEqual({ kind: "wait" });+ // Failing over and over is not transient any more.+ // Giving up releases the task: nothing resolved it, so the server would otherwise hold+ // its key until the sweep — the "key at rest" outcome this flow is shaped to avoid.+ const step = qqScanStep(failed(error), { failures: 2, refreshes: 0 });+ expect(step).toEqual({+ kind: "stop",+ notice: S.qq.scanFailed("bad gateway"),+ releaseTask: true,+ });+ // One answer that came back resets the run — the loop passes failures: 0 again.+ expect(qqScanStep(ok({ status: "pending" }), { failures: 2, refreshes: 0 })).toEqual({+ kind: "wait",+ });+ });++ it("replaces a lapsed code, but a bounded number of times", () => {+ expect(qqScanStep(ok({ status: "expired" }), fresh)).toEqual({ kind: "refresh" });+ expect(qqScanStep(ok({ status: "expired" }), { failures: 0, refreshes: 2 })).toEqual({+ kind: "refresh",+ });+ // A platform that reports tasks it just created as expired — clock skew, throttling, an+ // outage returning one fixed code — would otherwise loop create/poll forever.+ expect(qqScanStep(ok({ status: "expired" }), { failures: 0, refreshes: 3 })).toEqual({+ kind: "stop",+ notice: S.qq.scanExpiredRepeatedly,+ // The platform reported it expired, so the server already consumed the task on that+ // poll: cancelling it would be a request that can only 404.+ releaseTask: false,+ });+ });++ it("names no position for the code, which wraps above the text in a narrow panel", () => {+ // The waiting panel is `flex flex-wrap`: in the dock or on a phone the steps sit BELOW+ // the QR, so copy that says "the code on the left" is wrong exactly where it is read.+ for (const dict of [zh, en]) {+ expect(dict.qq.scanSteps).not.toMatch(/左侧|右侧|left|right/);+ }+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4c794b6a..ff01b249 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -395,6 +395,9 @@ importers:shiki:specifier: ^4.3.1version: 4.3.1+ uqr:+ specifier: ^0.1.3+ version: 0.1.3zustand:specifier: ^5.0.15version: 5.0.15(@types/[email protected])([email protected])@@ -3660,6 +3663,9 @@ packages:peerDependencies:browserslist: '>= 4.21.0'+ resolution: {integrity: sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==}+resolution: {integrity: sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==}@@ -7903,6 +7909,8 @@ snapshots:escalade: 3.2.0picocolors: 1.1.1+ [email protected]: {}+