| 1 | import test from "node:test"; |
| 2 | import { createHash } from "node:crypto"; |
| 3 | import { createServer } from "node:http"; |
| 4 | import { once } from "node:events"; |
| 5 | import assert from "node:assert/strict"; |
| 6 | import { mkdtemp, readFile, rm } from "node:fs/promises"; |
| 7 | import { tmpdir } from "node:os"; |
| 8 | import path from "node:path"; |
| 9 | import url from "node:url"; |
| 10 | import { |
| 11 | ApprovalOwnershipError, THREAD_NOT_OWNED_MESSAGE, ThreadOwnershipError, ThreadStore, decideApproval, settleStoredApproval, |
| 12 | admitTurn, createRuntimeClient, activeTurnBlock, latestRunningTurn, readThreadEvents, readJsonSafe, compactRuntimeError, observeTurn, turnOutcomeText |
| 13 | } from "../src/lib.mjs"; |
| 14 | import { isAllowed, isGroupChat } from "../../telegram-bridge/src/lib.mjs"; |
| 15 | import { incomingIdentity as wecomIdentity } from "../../wecom-bridge/src/lib.mjs"; |
| 16 | |
| 17 | const root = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..", ".."); |
| 18 | const chatId = "chat-a", threadId = "thread-a", turnId = "turn-a"; |
| 19 | const owner = { chatId, threadId, turnId, actorId: "telegram-user:alice" }; |
| 20 | const identities = { |
| 21 | "telegram-bridge": (userId) => ({ chatId, chatType: "group", userId, isBot: false }), |
| 22 | "feishu-bridge": (openId) => ({ chatId, chatType: "group", openId }), |
| 23 | "wecom-bridge": (userId) => ({ body: { chatid: chatId, chattype: "group", from: { userid: userId } } }), |
| 24 | "weixin-bridge": () => undefined |
| 25 | }; |
| 26 | const actors = { |
| 27 | "telegram-bridge": "telegram-user:alice", "feishu-bridge": "feishu-openId:alice", |
| 28 | "wecom-bridge": "wecom-user:alice", "weixin-bridge": "weixin-account:bot-a:user:chat-a" |
| 29 | }; |
| 30 | async function withStore(fn, options = {}, ownerScope = "") { |
| 31 | const dir = await mkdtemp(path.join(tmpdir(), "bridge-approvals-")); |
| 32 | try { |
| 33 | const store = await ThreadStore.open(path.join(dir, "state.json"), { actions: true, messageLimit: 500, ...options }); |
| 34 | await store.recordThreadOwner(chatId, threadId, ownerScope); |
| 35 | await store.setChat(chatId, { threadId }); |
| 36 | await fn(store); |
| 37 | } finally { await rm(dir, { recursive: true, force: true }); } |
| 38 | } |
| 39 | function extract(source, name) { |
| 40 | const marker = new RegExp(`^(?:async )?function ${name}\\(`, "m"); |
| 41 | const start = source.search(marker); |
| 42 | assert.notEqual(start, -1, name); |
| 43 | const rest = source.slice(start); |
| 44 | const next = rest.search(/\n(?:async )?function \w+\(/); |
| 45 | return next === -1 ? rest : rest.slice(0, next); |
| 46 | } |
| 47 | async function shipping(bridge, names, values) { |
| 48 | const source = await readFile(path.join(root, bridge, "src/index.mjs"), "utf8"); |
| 49 | const functions = [...new Set([ |
| 50 | ...(bridge === "weixin-bridge" && names.includes("turnActor") ? ["accountIdentity", "weixinActorId", "ownsThread"] : []), |
| 51 | ...(bridge === "telegram-bridge" && (names.includes("runPrompt") || names.includes("startPromptTurn")) |
| 52 | ? ["recoveryAllowed", "supportsAdmissionRecovery"] : []), |
| 53 | ...(bridge === "telegram-bridge" && ["runPrompt", "startPromptTurn", "handleCommand"].some((name) => names.includes(name)) |
| 54 | ? ["releaseUnownedRecovery", "clearActiveTurn"] : []), ...names |
| 55 | ])]; |
| 56 | return new Function(...Object.keys(values), functions.map((name) => extract(source, name)).join("\n") + |
| 57 | `\nreturn { ${names.join(", ")} };`)(...Object.values(values)); |
| 58 | } |
| 59 | async function withRuntime(fn) { |
| 60 | const state = { pending: [{ id: "approval-a", turn_id: turnId }], turns: [], posts: [], |
| 61 | startAttempts: 0, accepted: [], operations: new Map(), failStart: false, acceptDecision: true, events: [] }; |
| 62 | const server = createServer(async (request, response) => { |
| 63 | assert.equal(request.headers.authorization, "Bearer bridge-runtime-fixture-token"); |
| 64 | let text = ""; |
| 65 | for await (const chunk of request) text += chunk; |
| 66 | response.setHeader("connection", "close"); |
| 67 | if (request.url.includes("/events?")) { |
| 68 | response.setHeader("content-type", "text/event-stream"); |
| 69 | response.end(state.events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")); |
| 70 | return; |
| 71 | } |
| 72 | response.setHeader("content-type", "application/json"); |
| 73 | if (request.method === "POST" && request.url.endsWith("/turns")) { |
| 74 | state.startAttempts++; |
| 75 | if (state.failStart) { |
| 76 | response.statusCode = 503; |
| 77 | response.end(JSON.stringify({ error: { message: "start rejected" } })); |
| 78 | } else { |
| 79 | const id = `accepted-${state.startAttempts}`; |
| 80 | state.accepted.push(id); |
| 81 | const turn = { id, thread_id: threadId }; |
| 82 | const operationKey = JSON.parse(text).operation_key; |
| 83 | if (operationKey) state.operations.set(operationKey, turn); |
| 84 | response.end(JSON.stringify({ turn })); |
| 85 | } |
| 86 | } else if (request.url.includes("/turn-operations/")) { |
| 87 | const turn = state.operations.get(decodeURIComponent(request.url.split("/").at(-1))); |
| 88 | response.statusCode = turn ? 200 : 404; |
| 89 | response.end(JSON.stringify(turn || { error: { message: "operation not found" } })); |
| 90 | } else if (request.method === "POST") { |
| 91 | state.posts.push({ route: request.url, body: JSON.parse(text) }); |
| 92 | response.statusCode = state.acceptDecision ? 200 : 503; |
| 93 | response.end(JSON.stringify(state.acceptDecision ? { ok: true } : { error: { message: "fixture unavailable" } })); |
| 94 | } else { |
| 95 | response.end(JSON.stringify({ id: threadId, pending_approvals: state.pending, turns: state.turns, latest_seq: 0 })); |
| 96 | } |
| 97 | }); |
| 98 | server.listen(0, "127.0.0.1"); |
| 99 | await once(server, "listening"); |
| 100 | const runtimeUrl = `http://127.0.0.1:${server.address().port}`; |
| 101 | const runtime = createRuntimeClient({ runtimeUrl, runtimeToken: "bridge-runtime-fixture-token" }); |
| 102 | try { await fn({ ...runtime, runtimeUrl, state }); } |
| 103 | finally { await new Promise((resolve) => server.close(resolve)); } |
| 104 | } |
| 105 | function environment(store, runtime, extra = {}) { |
| 106 | return { |
| 107 | threadStore: store, THREAD_NOT_OWNED_MESSAGE, ThreadOwnershipError, runtimeJson: runtime.runtimeJson, decideRuntimeApproval: decideApproval, |
| 108 | settleStoredApproval, ApprovalOwnershipError, incomingIdentity: wecomIdentity, |
| 109 | WECOM_SYSTEM_PROMPT: "fixture prompt", FEISHU_SYSTEM_PROMPT: "fixture prompt", TELEGRAM_SYSTEM_PROMPT: "fixture prompt", |
| 110 | sendText: async () => {}, replyText: async () => {}, sendTurnText: async () => {}, |
| 111 | parseApprovalDecisionArgs: () => { throw new Error("fixture uses actual parsed approval id"); }, |
| 112 | ensureThread: async () => store.getChat(chatId), activeTurnBlock, latestRunningTurn, |
| 113 | admitTurn, createHash, isAllowed, isGroupChat, botAccountId: "fixture-bot", activeTurnTasks: new Map(), |
| 114 | runtimeCapabilities: { turn_operation_idempotency: true, turn_operation_lookup: true }, |
| 115 | startTrackedTurnStream: () => {}, delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), |
| 116 | config: { runtimeUrl: runtime.runtimeUrl, turnTimeoutMs: 1000, maxReplyChars: 10000, allowGroups: true, allowUnlisted: true, allowlist: [] }, |
| 117 | controlKeyboard: () => ({}), activeTurnKeyboard: () => ({}), helpText: () => "", |
| 118 | clearActiveTurn: () => store.patchChat(chatId, { activeTurnId: null }), stopping: false, |
| 119 | streamTurnEvents: async (chat, thread, turn) => { |
| 120 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 121 | assert.ok(reopened.turnOrigin(chat, thread, turn), "origin must be durable before delivery"); |
| 122 | return true; |
| 123 | }, ...extra |
| 124 | }; |
| 125 | } |
| 126 | let incomingNumber = 0; |
| 127 | async function invokeStart(bridge, functions, user = "alice") { |
| 128 | if (bridge === "telegram-bridge") { |
| 129 | await functions.startPromptTurn(chatId, "prompt", { ...identities[bridge](user), messageKey: `message-${++incomingNumber}` }); |
| 130 | return functions.runPrompt(chatId); |
| 131 | } |
| 132 | return functions.runPrompt(chatId, "prompt", identities[bridge](user)); |
| 133 | } |
| 134 | |
| 135 | test("approval tokens retain 128-bit entropy and require their accepted human and turn", async () => { |
| 136 | await withStore(async (store) => { |
| 137 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 138 | const tokens = new Set(await Promise.all(Array.from({ length: 20 }, () => store.putAction({ kind: "approval", approvalId: "approval-a" }, owner)))); |
| 139 | assert.equal(tokens.size, 20); |
| 140 | for (const token of tokens) assert.match(token, /^[a-f0-9]{32}$/); |
| 141 | const token = [...tokens][0]; |
| 142 | for (const wrong of [null, { chatId }, { ...owner, chatId: "other" }, { ...owner, threadId: "other" }, |
| 143 | { ...owner, actorId: "" }, { ...owner, actorId: "telegram-user:bob" }, { ...owner, turnId: "other" }]) { |
| 144 | assert.equal(await store.takeAction(token, wrong), null); |
| 145 | } |
| 146 | assert.equal((await store.takeAction(token, owner)).approvalId, "approval-a"); |
| 147 | assert.equal(await store.getAction(token, owner), null); |
| 148 | await assert.rejects(store.putAction({ kind: "approval" }, { chatId, threadId }), ApprovalOwnershipError); |
| 149 | }); |
| 150 | }); |
| 151 | |
| 152 | test("legacy privileged tokens missing thread, turn or human refuse after reload", async () => { |
| 153 | await withStore(async (store) => { |
| 154 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 155 | for (const binding of [undefined, { chatId }, { chatId, threadId }, { chatId, threadId, turnId }]) { |
| 156 | const token = String(Object.keys(store.data.actions).length); |
| 157 | store.data.actions[token] = { kind: "approval", owner: binding, approvalId: "approval-a", createdAt: new Date().toISOString() }; |
| 158 | } |
| 159 | await store.save(); |
| 160 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 161 | for (const token of Object.keys(reopened.data.actions)) assert.equal(await reopened.getAction(token, owner), null); |
| 162 | }); |
| 163 | }); |
| 164 | |
| 165 | test("origins are immutable, concurrent, bounded and retired tokens never acquire newer humans", async () => { |
| 166 | await withStore(async (store) => { |
| 167 | await Promise.all([ |
| 168 | store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId), |
| 169 | store.recordTurnOrigin(chatId, threadId, "turn-b", "telegram-user:bob") |
| 170 | ]); |
| 171 | assert.equal(store.turnOrigin(chatId, threadId, turnId).actorId, owner.actorId); |
| 172 | assert.equal(store.turnOrigin(chatId, threadId, "turn-b").actorId, "telegram-user:bob"); |
| 173 | const token = await store.putAction({ kind: "approval", approvalId: "approval-a" }, owner); |
| 174 | await assert.rejects(store.recordTurnOrigin(chatId, threadId, turnId, "telegram-user:bob"), ApprovalOwnershipError); |
| 175 | await store.recordTurnOrigin(chatId, threadId, "turn-c", "telegram-user:bob"); |
| 176 | const reopened = await ThreadStore.open(store.filePath, { actions: true, actionLimit: 2 }); |
| 177 | assert.equal((await reopened.getChat(chatId)).turnOrigins.length, 2); |
| 178 | assert.equal(reopened.turnOrigin(chatId, threadId, turnId), null); |
| 179 | assert.equal(await reopened.getAction(token, owner), null); |
| 180 | await reopened.setChat(chatId, { threadId: "other" }); |
| 181 | assert.equal(reopened.turnOrigin(chatId, threadId, "turn-c"), null); |
| 182 | await reopened.setChat(chatId, { threadId }); |
| 183 | assert.equal(reopened.turnOrigin(chatId, threadId, "turn-c"), null); |
| 184 | }, { actionLimit: 2 }); |
| 185 | }); |
| 186 | |
| 187 | test("shared decisions require Runtime pending turn and originating human, not current sender", async () => { |
| 188 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 189 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 190 | const args = { store, chatId, actorId: owner.actorId, approvalId: "approval-a", decision: "allow" }; |
| 191 | for (const override of [{ actorId: "" }, { actorId: "telegram-user:bob" }, { approvalId: "approval-b" }, |
| 192 | { chatId: "other" }, { turnId: "turn-b" }]) { |
| 193 | await assert.rejects(decideApproval(runtime.runtimeJson, { ...args, ...override }), ApprovalOwnershipError); |
| 194 | } |
| 195 | runtime.state.pending = [{ id: "approval-a" }]; |
| 196 | await assert.rejects(decideApproval(runtime.runtimeJson, args), ApprovalOwnershipError); |
| 197 | runtime.state.pending = [{ id: "approval-a", turn_id: "turn-b" }]; |
| 198 | await assert.rejects(decideApproval(runtime.runtimeJson, args), ApprovalOwnershipError); |
| 199 | assert.equal(runtime.state.posts.length, 0); |
| 200 | runtime.state.pending = [{ id: "approval-a", turn_id: turnId }]; |
| 201 | await decideApproval(runtime.runtimeJson, { ...args, decision: "deny", remember: "yes" }); |
| 202 | assert.deepEqual(runtime.state.posts, [{ route: "/v1/approvals/approval-a", body: { decision: "deny", remember: false } }]); |
| 203 | })); |
| 204 | }); |
| 205 | |
| 206 | test("thread switch during Runtime read refuses before the approval POST", async () => { |
| 207 | await withStore(async (store) => { |
| 208 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 209 | const runtimeJson = async (route, options) => { |
| 210 | assert.equal(options, undefined, "must not post after switch"); |
| 211 | await store.setChat(chatId, { threadId: "other" }); |
| 212 | return { pending_approvals: [{ id: "approval-a", turn_id: turnId }] }; |
| 213 | }; |
| 214 | await assert.rejects(decideApproval(runtimeJson, { store, chatId, actorId: owner.actorId, approvalId: "approval-a", decision: "allow" }), ApprovalOwnershipError); |
| 215 | }); |
| 216 | }); |
| 217 | |
| 218 | for (const bridge of Object.keys(identities)) { |
| 219 | test(`${bridge} shipping decision refuses unrelated, missing and other originating human over Runtime HTTP`, async () => { |
| 220 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 221 | await store.recordTurnOrigin(chatId, threadId, turnId, actors[bridge]); |
| 222 | await store.patchChat(chatId, { authorizedIdentity: identities[bridge]("bob"), activeTurnId: "later-turn" }); |
| 223 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 224 | const { decideApproval: consumer } = await shipping(bridge, ["turnActor", "decideApproval"], environment(reopened, runtime, |
| 225 | bridge === "weixin-bridge" ? { botAccount: { accountId: "bot-a" } } : {})); |
| 226 | const action = { decision: "allow", approvalId: "approval-a", remember: true }; |
| 227 | await consumer(chatId, { ...action, approvalId: "approval-b" }, identities[bridge]("alice")); |
| 228 | if (bridge !== "weixin-bridge") { |
| 229 | await consumer(chatId, action, identities[bridge]("bob")); |
| 230 | await consumer(chatId, action, identities[bridge]("")); |
| 231 | } |
| 232 | assert.equal(runtime.state.posts.length, 0); |
| 233 | await consumer(chatId, action, identities[bridge]("alice")); |
| 234 | assert.deepEqual(runtime.state.posts, [{ route: "/v1/approvals/approval-a", body: { decision: "allow", remember: bridge !== "wecom-bridge" } }]); |
| 235 | }, {}, bridge === "weixin-bridge" ? actors[bridge] : "")); |
| 236 | }); |
| 237 | } |
| 238 | |
| 239 | test("Weixin shipping decision rejects replacement or missing account identity without transferring the origin", async () => { |
| 240 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 241 | await store.recordTurnOrigin(chatId, threadId, turnId, actors["weixin-bridge"]); |
| 242 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 243 | const botAccount = { accountId: "bot-a" }; |
| 244 | const { decideApproval: consumer } = await shipping("weixin-bridge", ["turnActor", "decideApproval"], |
| 245 | environment(reopened, runtime, { botAccount })); |
| 246 | const action = { decision: "allow", approvalId: "approval-a", remember: true }; |
| 247 | for (const accountId of ["bot-b", "", null]) { |
| 248 | botAccount.accountId = accountId; |
| 249 | await consumer(chatId, action); |
| 250 | assert.equal(runtime.state.posts.length, 0); |
| 251 | assert.equal(reopened.turnOrigin(chatId, threadId, turnId).actorId, actors["weixin-bridge"]); |
| 252 | } |
| 253 | botAccount.accountId = "bot-a"; |
| 254 | await consumer(chatId, action); |
| 255 | assert.deepEqual(runtime.state.posts, [{ route: "/v1/approvals/approval-a", body: { decision: "allow", remember: true } }]); |
| 256 | }, {}, actors["weixin-bridge"])); |
| 257 | }); |
| 258 | |
| 259 | test("Weixin shipping decision refuses a legacy origin without bot account provenance after reload", async () => { |
| 260 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 261 | await store.recordTurnOrigin(chatId, threadId, turnId, "weixin-user:chat-a"); |
| 262 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 263 | const { decideApproval: consumer } = await shipping("weixin-bridge", ["turnActor", "decideApproval"], |
| 264 | environment(reopened, runtime, { botAccount: { accountId: "bot-a" } })); |
| 265 | await consumer(chatId, { decision: "allow", approvalId: "approval-a", remember: true }); |
| 266 | assert.equal(runtime.state.posts.length, 0); |
| 267 | assert.equal(reopened.turnOrigin(chatId, threadId, turnId).actorId, "weixin-user:chat-a"); |
| 268 | }, {}, actors["weixin-bridge"])); |
| 269 | }); |
| 270 | |
| 271 | for (const bridge of ["telegram-bridge", "feishu-bridge", "wecom-bridge"]) { |
| 272 | test(`${bridge} accepted start binds before delivery; failed, queued and later starts cannot transfer an old approval`, async () => { |
| 273 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 274 | const functions = await shipping(bridge, ["turnActor", "runPrompt", "decideApproval", ...(bridge === "telegram-bridge" ? ["startPromptTurn"] : [])], environment(store, runtime, bridge === "wecom-bridge" ? { |
| 275 | streamTurnEvents: async (chat, frame, thread, turn) => { |
| 276 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 277 | assert.ok(reopened.turnOrigin(chat, thread, turn), "origin must be durable before delivery"); |
| 278 | } |
| 279 | } : {})); |
| 280 | await invokeStart(bridge, functions, "alice"); |
| 281 | const first = runtime.state.accepted[0]; |
| 282 | assert.equal(store.turnOrigin(chatId, threadId, first).actorId, actors[bridge]); |
| 283 | runtime.state.pending = [{ id: "approval-a", turn_id: first }]; |
| 284 | await store.patchChat(chatId, { authorizedIdentity: identities[bridge]("bob") }); |
| 285 | runtime.state.failStart = true; |
| 286 | await assert.rejects(invokeStart(bridge, functions, "bob"), /start rejected/); |
| 287 | assert.equal(store.turnOrigin(chatId, threadId, first).actorId, actors[bridge]); |
| 288 | runtime.state.failStart = false; |
| 289 | runtime.state.turns = [{ id: first, status: "queued" }]; |
| 290 | const before = runtime.state.startAttempts; |
| 291 | await invokeStart(bridge, functions, "bob"); |
| 292 | assert.equal(runtime.state.startAttempts, before); |
| 293 | runtime.state.turns = []; |
| 294 | await invokeStart(bridge, functions, "bob"); |
| 295 | assert.equal(store.turnOrigin(chatId, threadId, first).actorId, actors[bridge]); |
| 296 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 297 | const { decideApproval: consumer } = await shipping(bridge, ["turnActor", "decideApproval"], environment(reopened, runtime)); |
| 298 | // The WeCom bridge steers the still-active turn with the follow-up text, |
| 299 | // so count approval decisions only, not every runtime POST. |
| 300 | const approvalPosts = () => runtime.state.posts.filter((post) => post.route.startsWith("/v1/approvals")); |
| 301 | await consumer(chatId, { decision: "allow", approvalId: "approval-a" }, identities[bridge]("bob")); |
| 302 | assert.equal(approvalPosts().length, 0); |
| 303 | await consumer(chatId, { decision: "allow", approvalId: "approval-a" }, identities[bridge]("alice")); |
| 304 | assert.equal(approvalPosts().length, 1); |
| 305 | })); |
| 306 | }); |
| 307 | } |
| 308 | |
| 309 | test("Telegram shipping SSE mints a bound button and actual callback human controls retry, restart and replay", async () => { |
| 310 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 311 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 312 | runtime.state.events = [{ seq: 1, thread_id: threadId, turn_id: turnId, event: "approval.required", payload: { approval_id: "approval-a" } }, |
| 313 | { event: "stream.end", thread_id: threadId, last_seq: 1, retryable: true, reason: "runtime_shutdown" }]; |
| 314 | const telegram = await import("../../telegram-bridge/src/lib.mjs"); |
| 315 | const env = environment(store, runtime, { |
| 316 | authHeaders: runtime.authHeaders, readThreadEvents, readJsonSafe, compactRuntimeError, |
| 317 | sendTypingAction: async () => {}, TYPING_INTERVAL_MS: 2000, LAST_SEQ_FLUSH_INTERVAL_MS: 2000, |
| 318 | approvalKeyboard: telegram.approvalKeyboard |
| 319 | }); |
| 320 | const { streamTurnEvents } = await shipping("telegram-bridge", ["streamTurnEvents"], env); |
| 321 | await streamTurnEvents(chatId, threadId, turnId, 0); |
| 322 | const [token] = Object.keys(store.data.actions); |
| 323 | assert.ok(token, "actual SSE must mint a token"); |
| 324 | assert.deepEqual(store.data.actions[token].owner, owner); |
| 325 | const invoke = async (current, user) => { |
| 326 | const values = environment(current, runtime, { |
| 327 | ...telegram, config: { ...env.config, allowGroups: true, allowUnlisted: true, allowlist: [] }, |
| 328 | answerCallback: async () => {}, editMessageReplyMarkup: async () => {}, |
| 329 | rememberAuthorizedIdentity: async (identity) => current.patchChat(chatId, { authorizedIdentity: identity }) |
| 330 | }); |
| 331 | const { handleCallbackQuery } = await shipping("telegram-bridge", |
| 332 | ["turnActor", "decideApproval", "handleStoredAction", "handleModalAction", "handleCallbackQuery"], values); |
| 333 | return handleCallbackQuery({ id: "callback-fixture", data: telegram.approvalKeyboard(token).inline_keyboard[0][0].callback_data, |
| 334 | from: { id: user }, message: { message_id: 1, chat: { id: chatId, type: "group" } } }); |
| 335 | }; |
| 336 | await invoke(store, "bob"); |
| 337 | assert.equal(runtime.state.posts.length, 0); |
| 338 | // The same approval id cannot authorize a different accepted turn, even |
| 339 | // when the same human happens to have initiated both turns. |
| 340 | await store.recordTurnOrigin(chatId, threadId, "other-turn", owner.actorId); |
| 341 | runtime.state.pending = [{ id: "approval-a", turn_id: "other-turn" }]; |
| 342 | await invoke(store, "alice"); |
| 343 | assert.equal(runtime.state.posts.length, 0); |
| 344 | runtime.state.pending = [{ id: "approval-a", turn_id: turnId }]; |
| 345 | runtime.state.acceptDecision = false; |
| 346 | await assert.rejects(invoke(store, "alice"), /fixture unavailable/); |
| 347 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 348 | assert.ok(await reopened.getAction(token, owner)); |
| 349 | runtime.state.acceptDecision = true; |
| 350 | await invoke(reopened, "alice"); |
| 351 | const accepted = await ThreadStore.open(store.filePath, { actions: true }); |
| 352 | assert.equal(await accepted.getAction(token, owner), null); |
| 353 | await invoke(accepted, "alice"); |
| 354 | assert.equal(runtime.state.posts.length, 2, "failed then accepted; accepted replay never posts"); |
| 355 | })); |
| 356 | }); |
| 357 | |
| 358 | test("Telegram and Feishu actual dispatch passes the admitted human to prompt and text approval", async () => { |
| 359 | for (const bridge of ["telegram-bridge", "feishu-bridge"]) { |
| 360 | const lib = await import(`../../${bridge}/src/lib.mjs`); |
| 361 | const calls = []; |
| 362 | const identity = identities[bridge]("alice"); |
| 363 | const values = { ...lib, sendText: async () => {}, threadStore: { getChat: async () => null }, |
| 364 | decideApproval: async (...args) => calls.push(args), |
| 365 | startPromptTurn: (...args) => calls.push(args), |
| 366 | runPrompt: async (...args) => calls.push(args) }; |
| 367 | const { handleCommand } = await shipping(bridge, ["handleCommand"], values); |
| 368 | await handleCommand(chatId, lib.parseCommand("/allow approval-a"), identity); |
| 369 | await handleCommand(chatId, lib.parseCommand("hello"), identity); |
| 370 | assert.equal(calls.length, 2, bridge); |
| 371 | assert.equal(calls[0][2], identity, bridge); |
| 372 | assert.equal(calls[1][2], identity, bridge); |
| 373 | } |
| 374 | }); |
| 375 | |
| 376 | |
| 377 | test("Telegram and Feishu shipping inbound events retain the actual admitted human through accepted start", async () => { |
| 378 | for (const bridge of ["telegram-bridge", "feishu-bridge"]) { |
| 379 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 380 | const lib = await import(`../../${bridge}/src/lib.mjs`); |
| 381 | let delivered; |
| 382 | const delivery = new Promise((resolve) => { delivered = resolve; }); |
| 383 | let markCleared; |
| 384 | const activeCleared = new Promise((resolve, reject) => { |
| 385 | const timer = setTimeout(() => reject(new Error(`${bridge} did not durably clear its accepted turn`)), 5000); |
| 386 | markCleared = () => { clearTimeout(timer); resolve(); }; |
| 387 | }); |
| 388 | const patchChat = store.patchChat.bind(store); |
| 389 | store.patchChat = async (chat, patch) => { |
| 390 | const result = await patchChat(chat, patch); |
| 391 | if (patch?.activeTurnId === null && runtime.state.accepted.length) { |
| 392 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 393 | assert.equal((await reopened.getChat(chat)).activeTurnId, null, `${bridge} clear must be durable before fixture cleanup`); |
| 394 | markCleared(); |
| 395 | } |
| 396 | return result; |
| 397 | }; |
| 398 | const values = environment(store, runtime, { |
| 399 | ...lib, activeTurnTasks: new Map(), |
| 400 | config: { allowGroups: true, allowUnlisted: false, allowlist: [chatId], requirePrefixInGroup: false }, |
| 401 | streamTurnEvents: async (chat, thread, turn) => { |
| 402 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 403 | assert.equal((await reopened.getChat(chat)).activeTurnId, turn, `${bridge} must persist the accepted turn before streaming`); |
| 404 | assert.equal(reopened.turnOrigin(chat, thread, turn).actorId, actors[bridge]); |
| 405 | delivered(); |
| 406 | return true; |
| 407 | } |
| 408 | }); |
| 409 | const names = bridge === "telegram-bridge" ? |
| 410 | ["turnActor", "runPrompt", "startPromptTurn", "startTrackedTurnStream", "handleCommand", "rememberAuthorizedIdentity", "handleIncomingUpdate"] : |
| 411 | ["turnActor", "runPrompt", "handleCommand", "handleIncomingMessage"]; |
| 412 | const handlers = await shipping(bridge, names, values); |
| 413 | if (bridge === "telegram-bridge") { |
| 414 | await handlers.handleIncomingUpdate({ update_id: 1, message: { message_id: 1, text: "hello", |
| 415 | chat: { id: chatId, type: "group" }, from: { id: "alice" } } }); |
| 416 | await delivery; |
| 417 | } else { |
| 418 | await handlers.handleIncomingMessage({ sender: { sender_id: { open_id: "alice" } }, |
| 419 | message: { chat_id: chatId, chat_type: "group", message_id: "message-a", message_type: "text", |
| 420 | content: JSON.stringify({ text: "hello" }) } }); |
| 421 | } |
| 422 | await delivery; |
| 423 | await activeCleared; |
| 424 | assert.equal(runtime.state.accepted.length, 1); |
| 425 | assert.equal(store.turnOrigin(chatId, threadId, runtime.state.accepted[0]).actorId, actors[bridge]); |
| 426 | })); |
| 427 | } |
| 428 | }); |
| 429 | |
| 430 | test("WeCom shipping SSE and natural approval callback use durable Runtime-turn origin, not the hint's latest sender", async () => { |
| 431 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 432 | const lib = await import("../../wecom-bridge/src/lib.mjs"); |
| 433 | await store.recordTurnOrigin(chatId, threadId, turnId, actors["wecom-bridge"]); |
| 434 | runtime.state.events = [{ seq: 1, thread_id: threadId, turn_id: turnId, event: "approval.required", payload: { approval_id: "approval-a" } }, |
| 435 | { event: "stream.end", thread_id: threadId, last_seq: 1, retryable: true, reason: "runtime_shutdown" }]; |
| 436 | const pendingApprovals = new Map(); |
| 437 | const values = environment(store, runtime, { |
| 438 | ...lib, authHeaders: runtime.authHeaders, observeTurn, turnOutcomeText, |
| 439 | config: { runtimeUrl: runtime.runtimeUrl, turnTimeoutMs: 1000, approvalTimeoutMs: 10000 }, |
| 440 | pendingApprovals, generateReqId: () => "stream-fixture", client: { replyStream: async () => {} } |
| 441 | }); |
| 442 | const { streamTurnEvents } = await shipping("wecom-bridge", ["streamTurnEvents"], values); |
| 443 | await streamTurnEvents(chatId, identities["wecom-bridge"]("bob"), threadId, turnId, 0); |
| 444 | assert.equal(pendingApprovals.get(chatId).approvalId, "approval-a"); |
| 445 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 446 | const { handleCommand } = await shipping("wecom-bridge", ["turnActor", "decideApproval", "handleCommand"], |
| 447 | { ...values, threadStore: reopened }); |
| 448 | await handleCommand(chatId, lib.parseCommand("允许"), identities["wecom-bridge"]("bob")); |
| 449 | assert.equal(runtime.state.posts.length, 0); |
| 450 | assert.ok(pendingApprovals.has(chatId), "refused member must not retire the legitimate pending hint"); |
| 451 | await handleCommand(chatId, lib.parseCommand("允许"), identities["wecom-bridge"]("alice")); |
| 452 | assert.equal(runtime.state.posts.length, 1); |
| 453 | assert.deepEqual(runtime.state.posts[0].body, { decision: "allow", remember: false }); |
| 454 | assert.equal(pendingApprovals.has(chatId), false); |
| 455 | })); |
| 456 | }); |
| 457 | |
| 458 | |
| 459 | test("retired origin refuses stale pending approval even when newer turns have the same human", async () => { |
| 460 | await withRuntime(async (runtime) => withStore(async (store) => { |
| 461 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 462 | const token = await store.putAction({ kind: "approval", approvalId: "approval-a" }, owner); |
| 463 | await store.recordTurnOrigin(chatId, threadId, "newer-1", owner.actorId); |
| 464 | await store.recordTurnOrigin(chatId, threadId, "newer-2", owner.actorId); |
| 465 | const reopened = await ThreadStore.open(store.filePath, { actions: true, actionLimit: 2 }); |
| 466 | assert.equal(await reopened.getAction(token, owner), null); |
| 467 | await assert.rejects(decideApproval(runtime.runtimeJson, { store: reopened, chatId, actorId: owner.actorId, |
| 468 | approvalId: "approval-a", decision: "allow" }), ApprovalOwnershipError); |
| 469 | assert.equal(runtime.state.posts.length, 0); |
| 470 | }, { actionLimit: 2 })); |
| 471 | }); |
| 472 | |
| 473 | test("existing action TTL is enforced on lookup after restart", async () => { |
| 474 | await withStore(async (store) => { |
| 475 | await store.recordTurnOrigin(chatId, threadId, turnId, owner.actorId); |
| 476 | const token = await store.putAction({ kind: "approval", approvalId: "approval-a" }, owner); |
| 477 | store.data.actions[token].createdAt = new Date(0).toISOString(); |
| 478 | await store.save(); |
| 479 | const reopened = await ThreadStore.open(store.filePath, { actions: true }); |
| 480 | assert.equal(await reopened.getAction(token, owner), null); |
| 481 | }); |
| 482 | }); |
| 483 |