Skip to content

fix(auth): allow same-principal consecutive turns and continue device-code authorization on the live turn - #1911

Merged
deepcoldy merged 2 commits into
deepcoldy:masterfrom
47seek:47seek/fix/turn-identity-same-principal-20261014
Oct 15, 2026
Merged

deepcoldy merged 2 commits into
deepcoldy:masterfrom
47seek:47seek/fix/turn-identity-same-principal-20261014

Conversation

@47seek

@47seek 47seek commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator

Problem

With triggerUserAuth enabled, the per-turn lark-cli / bytedcli wrapper refuses a command whenever its stamped turn id no longer matches the worker's live turn (turn-mismatch, exit 77):

botmux: 这条命令属于上一轮对话,而凭证已经切换到新消息的发起人;为避免用错人的权限,命令未执行。

The guard compares turn ids only, not principals. The most common trigger is therefore entirely benign: while a turn is still running, the same person sends a follow-up (or taps a device-code authorization link and types "继续" while botmux auth wait is polling). The follow-up opens a new turn, the credential file rotates, and every command in the old turn's tail — including the document read the agent was authorized to do — fails. The device-code flow compounds it: when the turn rotated during approval, the granted token was discarded with auth_turn_changed and never republished, so the next turn hit missing_scope again. Users saw a recurring "this command belongs to the previous turn" loop and could not finish a simple doc read.

Fix

Relax the turn binding only when both sides name the same human; cross-principal protection is unchanged.

  1. Principal alongside the turn marker. The worker now also publishes turn.caller (one line, next to the existing turn file) carrying the live turn's open id; published identities stamp BOTMUX_IDENTITY_OPEN_ID into their env file. The wrapper clears turn-mismatch only when both open ids are present and equal. Missing either side still denies (fail closed); a different human still exits 77.
  2. Caller threaded over IPC. turnCallerOpenId is carried on daemon→worker init / message / raw_input (resolved from the accepted turn's reply target / active interactive turn), through the type-ahead queue, adopt/replacement paths and follow-ups, into setCaptureIdentity and publishActiveTurn.
  3. Device-code authorization survives a same-principal turn rotation. auth-status freezes the approver in the request record, keeps polling while the session's live caller is that same human, and on approval republishes the token for the live turn (with the open-id stamp). A different caller, a dead worker, or a live-turn marker that has not flipped yet keeps the strict auth_turn_changed. Bound lark tools (new --as user tool-binding path) self-resolve identity and simply return ready.

Verification

  • bun run build and tsc clean on top of current master.
  • Full unit suite: ~30k tests, no new failures vs a pristine baseline checkout run in the same environment (remaining failures are pre-existing environment-sensitive git/bwrap/pm2 flake, confirmed by running the unmodified base in parallel).
  • New/updated tests:
    • wrapper: same-principal rotated turn runs (token + user-home modes), different human refused, missing either open id refused;
    • IPC auth route: token handed to the same human's live follow-up turn; refused for a different human's turn; queued identity preserved when the live-turn marker has not flipped;
    • updated source-order/IPC-snapshot pins for the new third setCaptureIdentity argument and turnCallerOpenId field.
  • Deployed on a multi-bot fleet from this branch: the regenerated on-disk wrapper black-box verified all four cases (same principal allow / different principal deny / unknown deny / same turn allow), and a full fleet restart came up healthy.

Co-Authored-By: Claude [email protected]

triggerUserAuth 的 lark-cli/bytedcli wrapper 在 turn id 不一致时一律 exit 77,
即使用户只是自己发了跟进消息(旧轮尾部命令、auth wait 期间的新一轮)也被拦,
表现为「这条命令属于上一轮对话」反复出现、文档一直读不到。

- 凭证与 live-turn 标记各盖 openId(turn.caller / .env 新增 BOTMUX_IDENTITY_OPEN_ID),
  wrapper 仅在双方都指名且为同一人时放行,缺任一侧仍 fail closed,跨人安全语义不变
- worker 经 IPC 透传 turnCallerOpenId(init/message/raw_input/排队/接管全路径)
- auth-status 设备码授权在轮次轮转到同一人时把新 token 回灌当前轮;
  发起人冻结在授权请求记录里,异人仍严格 auth_turn_changed

Co-Authored-By: Claude <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Owner

你好 @47seek,PR 的评审群已建好,自动评审(首审 + 交叉复审)已在群里开始,结论稍后会同步到本 PR。

你目前不在我们的自动拉群名单里,机器人暂时无法直接把你拉进群,请点击下面的链接自行加入(一年有效):
https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=c99qdb45-183e-4939-ad22-64cb87dce3df

也欢迎把你的 GitHub 账号和飞书信息补进这份名单文档,补好后后续评审群会自动把你拉进去:
https://bytedance.larkoffice.com/wiki/WJ1nwWbtxi89erkNGNbcgkt9nUe

(本条为自动流程发出,最终评审结论以维护者审阅为准。)

@deepcoldy

Copy link
Copy Markdown
Owner

初步自动评审意见(最终以维护者审阅为准)。

整体方向认可:仅在双方都具名同一人时放宽 turn 绑定、跨人仍然 exit 77(fail closed);设备码轮询冻结 approver、批准后改发到 live turn、marker 未翻转时保持 409 让 CLI 重试的设计都正确。wrapper 四态测试与 IPC 同人/异人用例齐备,本地 tsc / build / 相关测试及 CI 10 腿均绿,关键分支做变异核验有牙。

但发现 1 个会让主要场景在自然时序下间歇性失败的问题,建议修改:

P2|refreshSessionIdentity 的 CAS 后缀与新增的 OPEN_ID 行不兼容(src/core/cli-identity.ts:370)

renderIdentityEnv 现在按 TURN → OPEN_ID 顺序写文件,带 openId 戳的常规身份(user / user-home / bytedcli,本 PR 合入后 publishOne 的默认产物)最后一行是 BOTMUX_IDENTITY_OPEN_ID=...;而 refreshSessionIdentity 仍要求现有文件 endsWith(BOTMUX_IDENTITY_TURN='<turn>'),对盖戳文件恒为 false(已用真实模块探针验证:同轮与换轮 refresh 均返回 false)。

触发链路:设备码批准后 token 已落库 → 用户的跟进消息 t2 被 accept,publishOne 此刻已能取到 token,于是 t2 的 env 是「盖了 openId 戳」的 user 身份 → 等待中的 CLI poll auth-status(isCurrent 分支与同人换轮分支都一样)→ CAS 失败 → 409 auth_turn_changed,一直重试到请求 TTL。也就是本 PR 要修的「点链接 + 发『继续』」场景,在「批准先于跟进消息的身份重写」这个很常见的时序下仍然失败(token 实际已入库,下一轮会自愈,但当前轮卡死)。而「首次授权时 env 是无 openId 的 denied 文件」的时序恰好能通过,所以黑盒自测与现有测试没有暴露:新 IPC 测试 mock 了 refreshSessionIdentity,单元测试里的身份文件也都没有盖 openId 戳。

建议:

  • CAS 改为按行匹配 TURN(例如 content.split('\n').includes(\${TURN_VAR}=...`)`,可顺带校验 openId 一致),不要依赖最后一行;
  • isCurrent 分支(dashboard-ipc-server.ts:2607)的 refresh 也补上 openId: callerOpenId,避免刷新后的 env 丢戳、后续同人换轮又退化为严格拒绝;
  • 补一条「env 已盖 openId 戳时 refresh 成功」的真实文件测试,锁住这个时序。

P3 备忘(不阻塞)

  1. wrapper 在 source 身份文件前没有清空继承的 BOTMUX_IDENTITY_OPEN_ID(TURN 也一样):会话内进程理论上可经父环境变量影响判定(真实 sh 探针可复现)。按当前 daemon 在 accept 时已把 env 换成当轮凭证的顺序,拿不到跨人收益,但建议像 MODE/DENY_MSG 一样在脚本开头置空,做纵深防御。
  2. publishActiveTurn 两个文件非原子(先写 turn 后写 turn.caller),存在「新 turn + 旧 caller」的交错窗口;调换为先 caller 后 turn 在各时序下都严格更安全。
  3. PID marker JSON 没有持久化 callerOpenId,adoptInitialActiveTurn 也没有 trustedCaller?.requestUserOpenId 兜底(对比 syncQueuedTurnsFromMarkerDisk 里的 parsed.callerOpenId ?? advancedRecord.turnCallerOpenId);崩溃恢复 reconcile 时可能发布空 caller,只朝 fail-closed 方向失效(多拒绝,不会错人)。
  4. src/core/worker-pool.ts:9861 原有 /** Route user input through the transfer fence ... */ 文档注释悬空落在了 turnCallerOpenIdFor 上方,建议归位。

验证记录:评审基于最新 master(20e5f32cf,PR 0 behind、无冲突);本地 tsc、bun run build、8 个相关测试文件 357 个用例全绿,CI 10 腿全绿;3 处变异(wrapper 相等条件取反、删除两侧非空守卫、IPC 同人判定取反)均被测试杀死;P2 与 P3-1 均用真实模块 / 真实 /bin/sh 探针实证,非纯静态推断。

@deepcoldy

Copy link
Copy Markdown
Owner

补充一条勘误与双审收敛后的修改清单(接续上条初步意见,仍以维护者审阅为准)。

勘误:请撤回上条 P3-2 的「调换两个文件的写入顺序」建议——那个改法会更不安全。

复审用真实 wrapper 对两种顺序各自的单文件交错窗口做了实测(我也独立复现一致):两次 atomicWriteFileSync 之间天然存在微秒级混合态,而读侧也是两次独立的 read,调换写入顺序只是把窗口从一种混合态换成另一种:

  • 当前顺序(先 turn 后 turn.caller)的混合态是「新 turn + 旧 caller」,要错放需要 accept 序列 t1(A)→t2(B)→t3(A) 这种首尾同人的 ABA 交替;
  • 调换顺序(先 caller 后 turn)的混合态是「旧 turn + 新 caller」,t1(A)→t2(B)→t3(B) 即可错放——也就是「异人之后同一人连发两条」,恰好是本 PR 要支持的高频跟进形态,窗口更宽。

实测两种一致态(turn/caller 同人同轮)都正确拒绝;只有各自的混合态放行。所以请勿调换顺序。若要彻底消掉这个竞态(可作为本 PR 或后续 followup),正解是把 turn 与 caller 放进同一次原子写:例如 turn 文件一次写两行(turn 一行、caller 一行),wrapper 一次 read 拿到一致快照(读不到两行就按缺名拒绝),而不是两个文件各写各读。

双审收敛后的修改清单

必修(P2,双审均用真实代码实证;复审还穿过真实 HTTP 路由端到端复现):

  1. refreshSessionIdentity 的 CAS 不能再用 endsWith(BOTMUX_IDENTITY_TURN=...):renderIdentityEnv 现在行序是 TURN→OPEN_ID,任何盖了 openId 戳的身份(本 PR 后 publishOne 的默认产物)refresh 恒为 false。改为按行匹配 TURN(建议同时校验 openId 一致)。影响面不止设备码:所有走 lark-cli 授权续期、且当前轮 env 已盖戳的会话都会 409;同轮情况下 botmux auth wait 会一直轮询到 5min 超时。
  2. refresh 写入时透传 openId:两处调用(isCurrent 分支与同人换轮分支)都要带,否则刷新成功也会抹掉戳,同一人下一轮又退化回严格拒绝(顺带避免 user-home 身份被刷新覆写成 token 身份的既有口径)。
  3. 补真实文件测试(不要 mock refreshSessionIdentity):盖戳 env 的同轮 refresh 成功、同人换轮 refresh 成功且戳保留、异人 refresh 失败。

P3(不阻塞,建议顺手):

  1. wrapper 开头把继承的 BOTMUX_IDENTITY_OPEN_ID(及既有的 BOTMUX_IDENTITY_TURN)像 MODE/DENY_MSG 一样置空——它是本 PR 新增的唯一能把「异人拒绝」翻转成「同人放行」的输入(真实 sh 可复现),虽然利用窗口很窄,清零无成本。
  2. (替代我上条错误的 P3-2)turn 与 caller 单文件原子写,消除两文件交错窗口。
  3. PID marker JSON 持久化 callerOpenId,adoptInitialActiveTurn 增加 trustedCaller?.requestUserOpenId 兜底(对齐 syncQueuedTurnsFromMarkerDisk 的 parsed.callerOpenId ?? advancedRecord.turnCallerOpenId);崩溃恢复 reconcile 目前只会多拒、不会错人。
  4. promoteQueuedActivationTail(worker-pool.ts:12036)的 caller 在 promote 当刻现查 replyTargets,tail 排久了被 prune(32 条窗口)就会丢 caller → 同人续轮被拒(fail-closed 功能回退)。建议直接从已冻结的 promote 记录取(exactInput.trustedCaller?.requestUserOpenId,与 worker 侧 item.turnCallerOpenId ?? item.trustedCaller?.requestUserOpenId 的兜底一致),或把 caller 随 accept 记录落库。
  5. worker-pool.ts:9861 一处悬空的文档注释归位。

验证基线不变:head bfcfec4 对最新 master 0 behind、CI 10 腿绿。改完我们会重 fetch 新 head 重新核验。

@deepcoldy

Copy link
Copy Markdown
Owner

再补一组「单文件原子写」正解的实现约束(双审用真实 /bin/sh 实测过),避免改出「看着对、实则坏」的版本:

若采纳「turn + caller 合并进 turn 文件两行、wrapper 一次读到一致快照」来消除两文件交错窗口(34 万次并发对跑 0 混合态;对照当前两文件 57 万次观测中 27 万次混合态),有 3 个坑:

  1. 必须一次 open、两次 read:{ read -r t; read -r c; } < "$__botmux_d/turn"。不能写成两个独立重定向 read -r t < f; read -r c < f——每次重定向都从头读,实测第二行读到的是 turn id(turn=t2 caller=t2),于是任何凭证都会被当成「匹配 t2 的人」,同人放宽形同虚设、跨人保护被打开。(缺第二行时正确写法读到 caller=,现有两侧非空守卫自然 fail-closed。)

  2. 与 P2 的 CAS 必须在同一处一起改:refreshSessionIdentity(src/core/cli-identity.ts:373)现在对同一个 sessionActiveTurnPath 做 readFileSync(turnPath, 'utf8').trim() !== identity.turnId。文件变两行后 .trim() 得到 "t2\nou_bob",恒不等于 turnId(实测 false),会把修好的 CAS 又打回原形。该文件在 TS 侧的消费者经全量 grep 只有这一处(另有 wrapper 一处 sh read、写侧 publishActiveTurn、占位 ensureSessionIdentityPlaceholders),这里改成只取首行(如 split('\n')[0] 或抽一个 readActiveTurnLine 小工具)即可,建议与 wrapper 改动同一 commit。

  3. fail-closed 口径保持到首行:caller 非空不能成为绕过空 turn 的理由——首行为空(无 live turn)时现有 [ -n "$__botmux_live" ] 守卫会跳过整段轮次比较,这是既有「无 live turn 无可矛盾」的口径;宽松分支仍应只在 turn 非空、turn 不等、双方 caller 具名相等时进入。

如果觉得单文件改造面偏大,也可以选择本 PR 只修必修 3 条(CAS 按行匹配 + openId 透传 + 真实文件测试),两文件交错窗口(当前顺序需要 A→B→A 交替 accept 的窄窗口)另开 followup 用上面的方案收口——两种范围都可接受,但不要采用「调换两个文件写入顺序」的改法(上一条勘误已说明)。

@deepcoldy

Copy link
Copy Markdown
Owner

补充一份最终实现核对清单(与复审方逐处对齐,供修改时逐项勾):

若本 PR 一并落「单文件原子写」(推荐)——同一 commit 四处同步:

  1. 写侧 publishActiveTurn(cli-identity.ts:139-142):两次 atomicWriteFileSync 合成一次,写 turn\ncaller\n 两行;
  2. 读侧 wrapper sh(:484-489):两个独立 read < f 合成「一次 open 两次 read」{ read -r __botmux_live; read -r __botmux_live_caller; } < "$__botmux_d/turn",删掉 turn.caller 分支;
  3. 读侧 TS refreshSessionIdentity(:370-373):turn 文件读取收成首行(split('\n')[0] 或抽 readActiveTurnLine),同时完成 P2 的 CAS 按行匹配;
  4. 占位 ensureSessionIdentityPlaceholders(:575-576):删掉 sessionActiveTurnCallerPath 占位项,并删除该导出函数及相关 turn.caller 注释,避免留死路径(bare turn 文件全量消费者:TS 仅 :369 一处、wrapper sh 一处、写侧、占位;turn.json 是另一个文件,不要动)。

若本 PR 只修必修 3 条、交错窗口另开 followup: 即使当前 turn 还是单行,P2 修 CAS 时也请直接把 turn 读取写成「取首行」语义(单行文件下与 .trim() 等价、无行为变化),这样将来单文件正解落地时 CAS 不会因读到两行又恒 false 而回潮——请在代码注释或 followup issue 里留一句给下一位。

其余 P3(wrapper 开头清空继承的 OPEN_ID/TURN、PID marker 持久化 caller + adoptInitialActiveTurn 兜底、promoteQueuedActivationTail 的 caller 改取冻结的 trustedCaller、悬空注释归位)不阻塞,可随本 PR 或 followup。

在 deepcoldy#1911 的同一人连续轮次放行基础上,修复双审发现的必修问题,并消除
turn 与 caller 两文件交错读的竞态:

- refreshSessionIdentity 的 CAS 不再用 endsWith(BOTMUX_IDENTITY_TURN=…) 做后缀
  匹配:renderIdentityEnv 的行序是 TURN→OPEN_ID,任何盖了 openId 戳的身份
  (publishOne 的默认产物)refresh 恒为 false,导致批准落库后跟进消息已能取到
  token 的当轮仍 409,`botmux auth wait` 一直轮询到 5min 超时。改为按行匹配
  TURN,并在文件已盖戳时校验 openId 一致;未盖戳(首次授权的 denied 文件)不算
  冲突,保持可通过。
- 两处 auth-status refresh 调用补传 openId,避免刷新成功也把戳抹掉,使同一人
  下一轮又退化回严格拒绝。
- turn 与 caller 合并进同一个 turn 文件(第一行 turn、第二行 caller),由
  publishActiveTurn 一次原子写产出;wrapper 改为一次 open、两次 read 取一致快照,
  删掉 turn.caller 独立文件、sessionActiveTurnCallerPath 导出与占位。原先两次
  独立写/读之间必然存在「新 turn + 旧 caller」或「旧 turn + 新 caller」的混合态,
  两个方向各能错放一次跨人命令,这次一并消除。
- TS 侧新增 readActiveTurnLine(取首行),refreshSessionIdentity 用它将 turn 语义
  收敛到单一处;同样消除两行文件下 .trim() 恒不相等的隐患。
- wrapper 开头把继承的 BOTMUX_IDENTITY_TURN / BOTMUX_IDENTITY_OPEN_ID 像
  MODE/DENY_MSG 一样置空:它们是本 PR 新增的、唯一能把「异人拒绝」翻转成
  「同人放行」的输入,做纵深防御。
- PID marker 持久化 callerOpenId;adoptInitialActiveTurn / adoptDisplacedActiveTurn
  增加 trustedCaller?.requestUserOpenId 兜底;marker 里 queuedTurns 重放回
  queuedTypeAheadTurns 时带上 caller。崩溃恢复 reconcile 缺失 caller 只会多拒,
  不会错人。
- promoteQueuedActivationTail 的 caller 改取已冻结的 promote 记录
  (exactInput.trustedCaller?.requestUserOpenId),不再在 promote 当刻查
  replyTargets:排久被 prune 的 tail 会查空而丢 caller,使同人续轮被误拒。
- 归位 worker-pool.ts 一处悬空的文档注释。

测试:新增真实文件用例锁定盖上戳 env 的同轮 refresh 成功、同人换轮成功且保戳、
异人 refresh 失败、未盖戳文件可通过、两行文件首行语义,以及 wrapper 单次 open
一致快照与继承 env 清零;新增 promote tail 从冻结记录取 caller 的用例,并补
worker 侧 marker/adopt/replay 的 caller 持久化断言。既有 mock 断言同步到新的
openId 契约。

验证(在本 checkout 实测):
- npx tsc --noEmit、bun run build 通过;
- 9 个相关测试文件 585 用例全绿(cli-identity / ipc-auth-request /
  daemon-rename-route / initial-user-turn-opening / raw-input-followup-atomicity /
  transfer-passthrough-gate / worker-durable-expiry-order /
  worker-screenshot-upload-hardening / session-lifecycle-start);
- 10 处变异(CAS 退回后缀匹配、turn 读整段而非首行、wrapper 退回两次独立 read、
  去掉继承 env 清零、publishActiveTurn 丢 caller 行、marker 不存 caller、
  adopt 丢 trustedCaller 兜底、promote 退回 live 查询、queuedTurns 重放丢 caller、
  auth-status refresh 不传 openId)全部被测试杀死;
- 真实 publishActiveTurn 并发写 + 真实渲染 wrapper 的 144420 次单次 open 读,
  两态各 7 万余次、混合态 0 次,确认交错窗口已消除。

影响面:改动集中在 trigger-user-auth 的凭证/turn 绑定(lark-cli 与 bytedcli
共用 wrapper)、auth-status 续期路由与 worker 的 turn 归属发布。非
trigger-user-auth 会话、无授权会话、bytedcli 的 wrapper 行为均不变;turn 文件
由一行变两行,TS 侧唯一消费者 refreshSessionIdentity 已同步取首行;沙盒按目录
绑定 cli-identity/<sid>.bin,无需改 allowlist。

Co-Authored-By: 47Seek <[email protected]>
@deepcoldy
deepcoldy merged commit fdfafa3 into deepcoldy:master Oct 15, 2026
10 checks passed
@github-actions

Copy link
Copy Markdown

🚀 Released in v3.45.0

deepcoldy added a commit to Hyperzsb/botmux that referenced this pull request Oct 20, 2026
合并最新 master(含 deepcoldy#1606/deepcoldy#1911/deepcoldy#1941/deepcoldy#1946/deepcoldy#1961/deepcoldy#2042 等按人鉴权演进)。
语义冲突处理:
- bytedcli 身份同时携带五区域 cloudJwts 与 codeJwt(后者派生 codebase 同伴工具),
  mintByteCloudUserJwts 一次返回,去掉外层重复 mint。
- larkdev 平台凭据源暂不支持:grant client 端拒绝、toIdentity 收窄,platform 模式
  fail-closed、auto 模式回落本地个人 HOME 五区域 mint。
- lark-cli 个人 app 两步授权的拒绝文案按 stage 区分(app-setup vs user-login),
  ByteCloud 家族(bytedcli/larkdev)统一 provider 文案、空 HOME 与 502/409 守卫。
- 沙箱 lark-cli HOME 物化在 publishOne/publishDelegated 叠加 sessionSandbox 透传。
- session-tmp 采用 master 新短路径布局(8 字符 profile+sid hash),根目录强制
  deny 与本 PR 快照 carve 不受布局变化影响(seal 的是整个 session-tmp 根)。
- dashboard scope 加购/auth-status 取 master(绑定会话走 bot 应用,个人 app 首次
  授权走 turn 发布路径,不经此 IPC);删除被 deepcoldy#1946 改名的旧 scope 测试文件。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants