Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Harden the gateway, mail attachments, and CIMD reuse

Fei2411b57e59858636
diff --git a/docs/plans/2026-11-04-connectors.md b/docs/plans/2026-11-04-connectors.md
index ae704826..93fdba5f 100644
--- a/docs/plans/2026-11-04-connectors.md
+++ b/docs/plans/2026-11-04-connectors.md
@@ -1,25 +1,51 @@
-# 连接器(Connectors)
+# 连接器(Connectors)
-日期:2026-11-04。代码:`ds-bot/src/host/connectors/`(`catalog.js` 目录、`oauth.js` 登录、`gateway.js` 本地网关、`mail/` 邮箱、`index.js` 引擎),客户端 `src/client/connectors.js`,端点在 `src/host/channel.js` 的 `connector-*` / `mail-*`。
+日期:2026-11-04。代码:`ds-bot/src/host/connectors/`(`catalog.js` 目录、`oauth.js` 登录、`gateway.js` 本地网关、`mail/` 邮箱、`index.js` 引擎),客户端 `src/client/connectors.js`,端点在 `src/host/channel.js` 的 `connector-*` / `mail-*`。
-## 行为
+## 目录
-- 设置 → Connectors 一页:已连接列表、目录(搜索 + 分类)、添加菜单(粘贴地址、命令、从 Claude Desktop / Cursor / VS Code 导入)。
-- 每个连接器一行:图标(GitHub 用原标,其他用首字母色块)、名称、状态、操作(Connect / Disconnect / Try again / Sign in again)、展开面板(浏览器登录、设备码、密钥/令牌、client 表单)、只读开关、工具数。
-- 登录方式:免登录直连;MCP OAuth(WWW-Authenticate → 受保护资源元数据 → AS 元数据,旧服务器退回 MCP 源站;CIMD 仅在固定回环端口 38517 可用时;否则 DCR;都不行给 client 表单);GitHub 设备码(`DS_BOT_GITHUB_OAUTH_CLIENT_ID` 或常量为空时只给令牌粘贴);密钥(header / query);令牌粘贴。
-- 令牌全部存 DS Bot 密钥(`GITHUB_TOKEN` 不变;其他 `CONNECTOR_<ID>_TOKEN/REFRESH/CLIENT_SECRET/KEY`),`scope: []` 不进 Bot shell;非密状态在 `state.connectors[id]`。
-- 本地网关:mcp-client 只拿到 `http://127.0.0.1:<port>/c/<id>` 加随机 nonce;网关注入真实凭据、转发 `Mcp-Session-Id` 等头、透传 SSE、401 先刷新一次再重试一次(并发 401 共享一次刷新;`invalid_grant` → needs-sign-in);只读开关过滤 `tools/list` 非 readOnlyHint 工具并拒绝写 `tools/call`。
-- Bot 默认都能用已连接的连接器;Bot 详情 → Connectors 逐项关(`offFor`,按 `mcp__<id>__*` / `mail_` 前缀在 per-agent mask 里 deny,随 `tools/change` 重挂)。
-- Bot 工具:`list_connectors`、`request_connector`(自己会话出卡片,连接或忽略后回话)。
-- 邮箱:QQ / 163 / 126 / Gmail / iCloud / 其他(IMAP+SMTP 应用密码;163/126 登录后发 ID;QQ 复用连接);Google 登录走 Gmail API(`DS_BOT_GOOGLE_OAUTH_CLIENT_ID/SECRET` 缺一则按钮隐藏)。`mail_search / mail_read / mail_draft / mail_send / mail_update`;发送必须经发送卡用户确认;草稿不出卡;附件存 Bot 工作文件夹。
-- 导入:只读扫描 Claude Desktop / Cursor / VS Code 的 MCP 配置,env 值进密钥、配置里留 `$DSH_SECRET_` 引用;自定义 id 唯一且不占目录 id;能力名校验拒绝连接器 id。
+`catalog.js` 是一个纯数据数组,一项一个服务:`{ id, name, category, about, remote?: { url }, auth, headers?, whoami? }`。`about` 是自己写的一句话,不抄官网。`auth` 四种:`none`(免登录)、`oauth`(MCP OAuth,`client` 指定已知的公开客户端,`token: true` 同时接受贴令牌)、`key`(密钥放 header 或 query 参数,`keyUrl` 指路去哪里拿)、自定义项(用户加的地址或命令)。GitHub 保留原来的样子:`mcp__github__*` 工具名不变、`GITHUB_TOKEN` 不变、贴令牌流程不变。行内图标一律自绘:GitHub 用原标,其余用按 id 取色的首字母块。
+
+## 登录
+
+OAuth 登录的顺序是定的:目录里写的客户端 → CIMD → DCR → 让用户填 client。CIMD(client metadata document,`https://dsbot.app/oauth/client.json`)只在回环监听拿到固定端口 38517 时用,因为文档里登记的回调是 `http://127.0.0.1:38517/callback`;拿不到就落到 DCR:按本次的回调地址注册,地址变了或 client secret 过期就重新注册。都不行的(Asana、Box、HubSpot、Slack 这类要先在服务商注册的)显示 client 表单。发现元数据走三段:未认证请求拿 `WWW-Authenticate` → 受保护资源元数据(含 well-known 回退)→ AS 元数据;老服务器(如 Atlassian)没有资源文档时退回 MCP 源站查 AS 元数据。授权请求带 PKCE(S256)、`state` 和 `resource`;贴回的地址校验 `state`,贴裸 code 时用本次的 state。GitHub 走设备码(`client_id` + scope 换 `device_code`,轮询时遵守 `slow_down`);`DS_BOT_GITHUB_OAUTH_CLIENT_ID` 为空时只显示令牌表单,和现在一样。
+
+## 网关
+
+凭据永远不进 mcp-client 的配置,因为 `@deepseek-ai/dsh-mcp-client` 只接受静态 headers,没有 OAuth 也没有刷新。所以每个远程连接器在插件进程里挂的是 `http://127.0.0.1:<port>/c/<id>` 加一次性的随机 nonce;网关在转发时才注入真凭据(Bearer、key header 或 key query、目录里的静态 headers),转发 `Mcp-Session-Id`、`MCP-Protocol-Version`、`Accept` 等头,回传 `Mcp-Session-Id`,SSE 原样透传,下游断开就销毁上游。上游 401 且还没回字节时:刷新一次、重试一次;并发 401 共享一次刷新;刷新轮换时写新 refresh token,写失败留旧的;`invalid_grant` 转「需要重新登录」;只读窗口不刷新、只重读密钥。非 https 的上游一律拒绝(本机回环 http 除外,给本地自定义服务器)。每个远程连接器有「Read-only」开关:打开后网关把 `tools/list` 过滤到 `readOnlyHint` 工具,写 `tools/call` 在本地拒绝(批请求整体拒掉),stdio 连接器不显示这个开关。
+
+## 状态与密钥
+
+密钥在 DS Bot 密钥里,首次写入 `scope: []`(不进任何 Bot shell):GitHub 仍用 `GITHUB_TOKEN`,其他 `CONNECTOR_<ID>_TOKEN / _REFRESH / _CLIENT_SECRET / _KEY`,邮箱 `MAIL_<地址>_PASSWORD / _TOKEN / _REFRESH`。非密状态在 `state.connectors[id]`(账号、连接时间、client 元信息、token 过期、readOnly、offFor、custom)。令牌变化不触发重挂(指纹不含令牌)。
+
+## 每个 Bot 的开关
+
+默认所有 Bot 都能用已连接的连接器。Bot 详情 → Connectors 逐项关(`offFor`):按 `mcp__<id>__*` / `mail_` 前缀在 per-agent 工具遮罩里 deny,`tools/change` 时按需重挂,只有 deny 集合变了才动。关掉后该 Bot 看不到工具,也不能再发起新的连接请求。
+
+## Bot 工具和卡片
+
+`list_connectors` 列目录、连接状态和本 Bot 可用性;`request_connector`(id、purpose)在本 Bot 自己的会话里出卡片,按密钥卡同一套规矩:只在私聊、群聊拒绝、只读窗口拒绝、记录 pending 并 `concludeTurn`、连接或取消后回话。`request_secret` 的笔记机制原样复用(`rt.deliver` 带角色标签)。邮箱发送同样出卡片:显示 from/to/cc/bcc/subject/正文/附件名和大小,Send 才发,Cancel 什么都不发;草稿不出卡。
+
+## 邮箱
+
+按地址域名选预设:QQ(含 foxmail)、163、126、Gmail、iCloud、其他(自填主机端口)。163/126 不发 IMAP `ID` 命令会回 Unsafe Login,所以每个账号都带 `ID`(name/version/vendor)。QQ 限频繁登录,一个账号复用一条连接。加账号先登录验证一次(IMAP + SMTP)再保存,验证码错误只报干净的错。工具:`mail_search / mail_read / mail_draft / mail_send / mail_update`,只在有账号时注册。附件保存进 Bot 的工作文件夹,文件名清理防目录穿越;发送的附件限工作文件夹内(realpath 校验),卡片显示名字和大小。Gmail 也支持 Google 登录(Gmail API,`openid + userinfo.email + gmail.modify`),client 由 `DS_BOT_GOOGLE_OAUTH_CLIENT_ID/SECRET` 提供,缺一则按钮隐藏——应用过 Google 审核前只有测试账号能登。不落任何 Google secret 进仓。
+
+## 导入与自定义
+
+`connector-import-scan` 只读扫 Claude Desktop、Cursor、VS Code 的 MCP 配置(不改源文件),返回名称和 env 名;`connector-import` 把 env 值移进 DS Bot 密钥(`CONNECTOR_<ID>_<ENV>`),配置里留 `$DSH_SECRET_` 引用。自定义 id 从名字派生,唯一、≤32 字符、不占目录 id;能力名校验同样拒绝连接器 id。
## 不做
-- 不加 Google 系 MCP(开发者预览条款)、不存 Google client secret 进仓、不引入厂商 logo、不在 Bot shell 暴露凭据、连接器不改 DSH。
+- 不加 Google 的 Gmail/Drive/Calendar MCP(开发者预览条款),不引入任何厂商 logo。
+- 不把凭据放进 Bot shell 或 mcp-client 配置;不改 DSH。
## 已知限制
-- OAuth 仅在本进程内生效;无图形验证时部分服务仍要手动贴 client。
-- 只读过滤依赖服务的 `readOnlyHint`;没标注的按写处理。
-- 邮箱线程按 References/In-Reply-To 关联;Gmail 「移动」按标签实现。
+- 浏览器登录只在本机回环;远程浏览器用贴回地址兜底。
+- 只读过滤依赖服务的 `readOnlyHint`;没标注的按写处理。
+- 邮箱线程按 References/In-Reply-To 关联;Gmail 的「移动」按标签实现。
+- Google 登录在应用过审前仅限测试账号。
+
+## 变更
+
+- 2026-11-04 重写:修正网关把连接器路径和 query 丢到源站根的问题;下游断开销毁上游;只读模式拒批请求;CIMD 存储客户端只在固定端口复用;邮箱附件路径收紧并显示大小;卡片回话与密钥卡同一机制。
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 3931dc9e..902d838c 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -8523,7 +8523,7 @@ function MailSendCard({ sessionId, bot, request, actions, inline = false }) {
request.cc ? (0, import_react17.createElement)("div", null, (0, import_react17.createElement)("b", null, t("Cc")), " ", request.cc) : null,
request.bcc ? (0, import_react17.createElement)("div", null, (0, import_react17.createElement)("b", null, t("Bcc")), " ", request.bcc) : null,
(0, import_react17.createElement)("div", { className: "bt-mail-body" }, request.body),
- request.attachments?.length ? (0, import_react17.createElement)("div", { className: "bt-q-detail" }, t("Attachments: {names}", { names: request.attachments.join(", ") })) : null
+ request.attachmentDetails?.length ? (0, import_react17.createElement)("div", { className: "bt-q-detail" }, t("Attachments: {names}", { names: request.attachmentDetails.map((a) => a.size !== void 0 ? `${a.name} (${a.size} B)` : a.name).join(", ") })) : null
),
(0, import_react17.createElement)(
"div",
diff --git a/ds-bot/src/client/connectors.js b/ds-bot/src/client/connectors.js
index b926d9a5..1989670f 100644
--- a/ds-bot/src/client/connectors.js
+++ b/ds-bot/src/client/connectors.js
@@ -314,7 +314,7 @@ export function MailSendCard({ sessionId, bot, request, actions, inline = false
request.cc ? h('div', null, h('b', null, t('Cc')), ' ', request.cc) : null,
request.bcc ? h('div', null, h('b', null, t('Bcc')), ' ', request.bcc) : null,
h('div', { className: 'bt-mail-body' }, request.body),
- request.attachments?.length ? h('div', { className: 'bt-q-detail' }, t('Attachments: {names}', { names: request.attachments.join(', ') })) : null),
+ request.attachmentDetails?.length ? h('div', { className: 'bt-q-detail' }, t('Attachments: {names}', { names: request.attachmentDetails.map(a => a.size !== undefined ? `${a.name} (${a.size} B)` : a.name).join(', ') })) : null),
h('div', { className: 'bt-q-foot' },
h('button', { type: 'button', className: 'bt-q-btn', disabled: busy, onClick: () => answer('cancel') }, t('Cancel')),
h('button', { type: 'button', className: 'bt-q-submit', disabled: busy, onClick: () => answer('send') }, t('Send'))))
diff --git a/ds-bot/src/host/connectors/gateway.js b/ds-bot/src/host/connectors/gateway.js
index 146ed1ec..11213b1f 100644
--- a/ds-bot/src/host/connectors/gateway.js
+++ b/ds-bot/src/host/connectors/gateway.js
@@ -73,7 +73,11 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
async function sendUpstream(entry, method, path, headers, body) {
return new Promise((resolve, reject) => {
- const target = new URL(path, entry.url)
+ const target = new URL(entry.url)
+ if (path !== '/' && path !== '') {
+ target.pathname = entry.pathBase + path.replace(/^\//, '')
+ }
+ for (const [key, value] of new URL(path, 'http://x').searchParams) target.searchParams.append(key, value)
const outgoing = { ...entry.headers }
for (const name of FORWARD_HEADERS) if (headers[name] !== undefined) outgoing[name] = headers[name]
if (body !== undefined) outgoing['content-length'] = body.length
@@ -96,13 +100,21 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
res.end(JSON.stringify({ error: 'connector address must be https' }))
return
}
- const path = req.url.slice(`/c/${id}`.length) || '/'
+ const suffix = req.url.slice(`/c/${id}`.length)
+ const path = suffix === '' ? '/' : suffix
+ entry.pathBase = new URL(entry.url).pathname.replace(/\/$/, '') === '' ? '' : `${new URL(entry.url).pathname.replace(/\/$/, '')}/`
const limited = readOnly(id) === true
const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await readAll(req)
// Read-only: a write tools/call never reaches the server.
if (limited && req.method === 'POST' && body !== undefined) {
let rpc
try { rpc = JSON.parse(body.toString('utf8')) } catch { rpc = null }
+ if (Array.isArray(rpc)) {
+ // A batch could hide a write call, so read-only refuses them outright.
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: `The ${id} connector is read-only: batched calls are refused.` } }))
+ return
+ }
if (rpc?.method === 'tools/call' && !toolReadOnly(id, rpc.params?.name)) {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify(refuseCall(id, rpc)))
@@ -164,6 +176,9 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
const heads = {}
for (const name of RETURN_HEADERS) if (upstream.headers[name] !== undefined) heads[name] = upstream.headers[name]
if (!isList || limited) {
+ const close = () => { upstream.destroy() }
+ res.on('close', close)
+ upstream.on('end', () => res.off('close', close))
res.writeHead(upstream.statusCode ?? 502, heads)
upstream.pipe(res)
return
diff --git a/ds-bot/src/host/connectors/index.js b/ds-bot/src/host/connectors/index.js
index fdb795d8..8bc5c051 100644
--- a/ds-bot/src/host/connectors/index.js
+++ b/ds-bot/src/host/connectors/index.js
@@ -85,7 +85,8 @@ export function install(rt) {
const credentialOf = (id) => {
const entry = entryFor(id)
- if (entry === undefined || entry.auth.kind === 'none') return entry?.auth.kind === 'none' && entry.custom === undefined ? {} : {}
+ if (entry === undefined) return undefined
+ if (entry.auth.kind === 'none' || entry.auth.kind === 'custom') return {}
if (entry.auth.kind === 'oauth') {
const token = rt.secretValue(tokenSecretOf(id))
return token === undefined ? undefined : { Authorization: `Bearer ${token}` }
diff --git a/ds-bot/src/host/connectors/mail/index.js b/ds-bot/src/host/connectors/mail/index.js
index d9ccd439..37a15af4 100644
--- a/ds-bot/src/host/connectors/mail/index.js
+++ b/ds-bot/src/host/connectors/mail/index.js
@@ -3,7 +3,8 @@
// send card, and the mail-* endpoints. Transports come from transport.js;
// rt.config.mail.connect injects fakes in tests.
import { randomUUID } from 'node:crypto'
-import { join } from 'node:path'
+import { basename, join, resolve, sep } from 'node:path'
+import { realpathSync, statSync } from 'node:fs'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { PRESETS, presetOf, mailSecretName } from './presets.js'
import { connectImap, connectGmail } from './transport.js'
@@ -139,12 +140,19 @@ export function install(rt, host) {
const saved = []
if (args.save_attachments === true) {
const dir = workDir(exec)
+ const taken = new Set()
+ const safe = (raw) => {
+ let name = basename(String(raw ?? '')).replace(/[\0-\x1f\\]/g, '_').replace(/^\.+/, '') || 'attachment'
+ while (taken.has(name)) name = `_${name}`
+ taken.add(name)
+ return name
+ }
for (const message of messages) {
for (const attachment of message.attachments ?? []) {
if (dir === undefined) break
- const target = join(dir, attachment.filename)
- await session.saveAttachment({ uid: message.uid, folder: message.folder, filename: attachment.filename, to: target })
- saved.push(attachment.filename)
+ const name = safe(attachment.filename)
+ await session.saveAttachment({ uid: message.uid, folder: message.folder, filename: attachment.filename, to: join(dir, name) })
+ saved.push(name)
}
}
}
@@ -196,6 +204,15 @@ export function install(rt, host) {
if (!rt.chatOwners.has(exec.agent?.id)) return 'Send cards only work in your current own chat.'
const readOnly = rt.readOnly()
if (readOnly !== undefined) return `No card can be shown now. ${readOnly}`
+ const dir = workDir(exec)
+ const bad = (args.attachments ?? []).map(String).filter(name => name !== '').filter((name) => {
+ if (dir === undefined) return true
+ try {
+ const inside = realpathSync(resolve(dir, name))
+ return inside !== realpathSync(dir) && !inside.startsWith(realpathSync(dir) + sep)
+ } catch { return true }
+ })
+ if (bad.length > 0) return `Attachments must be files in your working folder: ${bad.join(', ')} is not.`
const list = (state.mailRequests ??= {})[bot.id] ??= []
const request = {
id: randomUUID(),
@@ -204,8 +221,11 @@ export function install(rt, host) {
account: account.id,
to: String(args.to ?? ''), cc: String(args.cc ?? ''), bcc: String(args.bcc ?? ''),
subject: String(args.subject ?? ''), body: String(args.body ?? ''),
- attachments: (Array.isArray(args.attachments) ? args.attachments : []).map(String),
- dir: workDir(exec),
+ attachments: (Array.isArray(args.attachments) ? args.attachments : []).map(String).filter(name => name !== ''),
+ dir,
+ attachmentDetails: (Array.isArray(args.attachments) ? args.attachments : []).map(String).filter(name => name !== '').map((name) => {
+ try { return { name, size: statSync(join(dir, name)).size } } catch { return { name } }
+ }),
replyTo: args.reply_to ? String(args.reply_to) : undefined,
status: 'pending', askedAt: Date.now(),
}
@@ -329,7 +349,11 @@ export function install(rt, host) {
}
try {
const session = await connect(account)
- const attachments = (request.attachments ?? []).map(name => ({ filename: name, path: join(request.dir ?? '', name) }))
+ const attachments = (request.attachments ?? []).map((name) => {
+ const inside = realpathSync(resolve(request.dir ?? '', name))
+ if (request.dir === undefined || inside !== realpathSync(request.dir) && !inside.startsWith(realpathSync(request.dir) + sep)) throw new Error(`Attachment ${name} is outside the working folder`)
+ return { filename: name, path: inside }
+ })
await session.send({ to: request.to, cc: request.cc || undefined, bcc: request.bcc || undefined, subject: request.subject, text: request.body, attachments, ...(request.replyTo ? { inReplyTo: request.replyTo } : {}) })
request.status = 'sent'; request.settledAt = Date.now()
await rt.save()
diff --git a/ds-bot/src/host/connectors/mail/transport.js b/ds-bot/src/host/connectors/mail/transport.js
index 607bd300..74a65e2e 100644
--- a/ds-bot/src/host/connectors/mail/transport.js
+++ b/ds-bot/src/host/connectors/mail/transport.js
@@ -7,16 +7,19 @@ import { IMAP_ID } from './presets.js'
// IMAP + SMTP (imapflow + nodemailer). One live IMAP connection per account is
// kept by the caller (QQ throttles frequent logins); on a dropped connection the
// caller reconnects once.
+export const imapOptions = (account, deps = {}) => ({
+ host: account.imap.host, port: account.imap.port, secure: account.imap.secure !== false,
+ auth: { user: account.address, pass: deps.password },
+ // RFC 2971: 163/126 refuse logins without the client identity.
+ id: IMAP_ID,
+ logger: false,
+ socketTimeout: 60_000,
+})
+
export async function connectImap(account, deps = {}) {
const { ImapFlow } = await import('imapflow')
const nodemailer = await import('nodemailer')
- const imap = new ImapFlow({
- host: account.imap.host, port: account.imap.port, secure: account.imap.secure !== false,
- auth: { user: account.address, pass: deps.password },
- id: IMAP_ID,
- logger: false,
- socketTimeout: 60_000,
- })
+ const imap = new ImapFlow(imapOptions(account, deps))
const smtp = nodemailer.createTransport({
host: account.smtp.host, port: account.smtp.port, secure: account.smtp.secure === true,
requireTLS: account.smtp.starttls === true,
@@ -151,7 +154,7 @@ export async function connectImap(account, deps = {}) {
const strip = ({ _parsed, ...message }) => message
const compose = async (from, { to, cc, bcc, subject, text }) => {
- const MailComposer = (await import('nodemailer/lib/mail-composer.js')).default
+ const MailComposer = (await import('nodemailer/lib/mail-composer')).default
return await new MailComposer({ from, to, cc, bcc, subject, text }).compile().build()
}
@@ -240,7 +243,7 @@ export function connectGmail(account, deps = {}) {
}
const gmailRaw = async (from, { to, cc, bcc, subject, text, inReplyTo, references }) => {
- const MailComposer = (await import('nodemailer/lib/mail-composer.js')).default
+ const MailComposer = (await import('nodemailer/lib/mail-composer')).default
const raw = await new MailComposer({ from, to, cc, bcc, subject, text, ...(inReplyTo ? { inReplyTo, references: references ?? [inReplyTo] } : {}) }).compile().build()
return raw.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
diff --git a/ds-bot/src/host/connectors/oauth.js b/ds-bot/src/host/connectors/oauth.js
index 2a15d6dd..5f8f5588 100644
--- a/ds-bot/src/host/connectors/oauth.js
+++ b/ds-bot/src/host/connectors/oauth.js
@@ -65,7 +65,9 @@ export async function resolveClient(entry, discovery, redirectUri, fixedPort, st
if (stored?.clientId) {
const expired = Number.isFinite(stored.secretExpiresAt) && stored.secretExpiresAt * 1000 <= Date.now()
const uriMissing = Array.isArray(stored.redirectUris) && !stored.redirectUris.includes(redirectUri)
- if (!expired && !uriMissing && stored.via !== 'dcr') return { via: stored.via, clientInformation: { client_id: stored.clientId } }
+ // A stored CIMD client still needs the fixed port its document names.
+ if (!expired && !uriMissing && stored.via === 'cimd' && fixedPort) return { via: 'cimd', clientInformation: { client_id: stored.clientId } }
+ if (!expired && !uriMissing && stored.via !== 'dcr' && stored.via !== 'cimd') return { via: stored.via, clientInformation: { client_id: stored.clientId } }
if (!expired && !uriMissing && stored.via === 'dcr') return { via: 'dcr', clientInformation: { client_id: stored.clientId, ...(stored.clientSecret ? { client_secret: stored.clientSecret } : {}) } }
}
const metadata = discovery.metadata
diff --git a/ds-bot/test/connectors-engine.test.js b/ds-bot/test/connectors-engine.test.js
index a5d7e2d5..2affc75b 100644
--- a/ds-bot/test/connectors-engine.test.js
+++ b/ds-bot/test/connectors-engine.test.js
@@ -454,3 +454,157 @@ test('mail account remove drops the secret and unregisters the tools', async (t)
assert.equal(rt.secretValue(mailSecretName('[email protected]', 'PASSWORD')), undefined)
assert.equal(rt.teamTools.some(d => d.name === 'mail_send'), false)
})
+
+const { imapOptions } = await import('../src/host/connectors/mail/transport.js')
+const { IMAP_ID } = await import('../src/host/connectors/mail/presets.js')
+
+test('163 and 126 presets send the IMAP ID identity', () => {
+ for (const domain of ['163.com', '126.com']) {
+ const options = imapOptions({ address: `me@${domain}`, imap: { host: `imap.${domain}`, port: 993, secure: true } }, { password: 'x' })
+ assert.deepEqual(options.id, IMAP_ID)
+ assert.equal(options.id.vendor, 'DS Bot')
+ }
+})
+
+test('gateway keeps the entry path and merges queries', async (t) => {
+ const seen = []
+ const upstream = createServer((req, res) => { seen.push(req.url); res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}') })
+ const port = await listen(upstream)
+ t.after(() => upstream.close())
+ const gw = createGateway({
+ credential: () => ({ url: `http://127.0.0.1:${port}/mcp?key=K1`, headers: {} }),
+ readOnly: () => false, onUnauthorized: async () => false,
+ })
+ await gw.listen()
+ t.after(() => gw.close())
+ const head = { Authorization: `Bearer ${gw.nonce}`, 'content-type': 'application/json' }
+ await fetch(gw.urlFor('svc'), { method: 'POST', headers: head, body: '{}' })
+ assert.equal(seen.at(-1), '/mcp?key=K1')
+ await fetch(`${gw.urlFor('svc')}?x=1&y=2`, { method: 'POST', headers: head, body: '{}' })
+ assert.match(seen.at(-1), /^\/mcp\?key=K1&x=1&y=2$|x=1.*key=K1/)
+})
+
+test('gateway destroys the upstream stream when the client disconnects', async (t) => {
+ let upstreamDestroyed = false
+ const upstream = createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ res.write('event: message\ndata: {}\n\n')
+ res.on('close', () => { upstreamDestroyed = true })
+ // never ends on its own
+ })
+ const port = await listen(upstream)
+ t.after(() => upstream.close())
+ const gw = createGateway({ credential: () => ({ url: `http://127.0.0.1:${port}`, headers: {} }), readOnly: () => false, onUnauthorized: async () => false })
+ await gw.listen()
+ t.after(() => gw.close())
+ const controller = new AbortController()
+ const pending = fetch(gw.urlFor('svc'), { headers: { Authorization: `Bearer ${gw.nonce}` }, signal: controller.signal })
+ const response = await pending.catch(e => e)
+ // The GET answer headers arrived; abort the body read.
+ const res = await pending
+ controller.abort()
+ await res.body?.cancel().catch(() => {})
+ await new Promise(resolve => setTimeout(resolve, 50))
+ assert.equal(upstreamDestroyed, true)
+})
+
+test('gateway refuses JSON-RPC batches in read-only mode', async (t) => {
+ const upstream = createServer((req, res) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('[]') })
+ const port = await listen(upstream)
+ t.after(() => upstream.close())
+ const gw = createGateway({ credential: () => ({ url: `http://127.0.0.1:${port}`, headers: {} }), readOnly: () => true, onUnauthorized: async () => false })
+ await gw.listen()
+ t.after(() => gw.close())
+ const batch = [{ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'write_thing' } }]
+ const answer = await (await fetch(gw.urlFor('svc'), { method: 'POST', headers: { Authorization: `Bearer ${gw.nonce}`, 'content-type': 'application/json' }, body: JSON.stringify(batch) })).json()
+ assert.match(answer.error.message, /read-only/)
+})
+
+test('a stored CIMD client is reused only with the fixed port', async () => {
+ const discovery = { authorizationServerUrl: 'https://as.test', metadata: { ...AS, client_id_metadata_document_supported: true }, resource: 'r' }
+ const entry = { auth: { kind: 'oauth' } }
+ const stored = { via: 'cimd', clientId: 'https://dsbot.app/oauth/client.json', redirectUris: [] }
+ const fixed = await oauth.resolveClient(entry, discovery, 'http://127.0.0.1:38517/callback', true, stored)
+ assert.equal(fixed.via, 'cimd')
+ const request = async (url, init) => url.toString() === 'https://as.test/register' ? json({ client_id: 'dcr-9', redirect_uris: JSON.parse(init.body).redirect_uris }) : notFound()
+ const random = await oauth.resolveClient(entry, discovery, 'http://127.0.0.1:9/callback', false, stored, { fetch: request })
+ assert.equal(random.via, 'dcr')
+})
+
+test('connector-sign-in-code refuses a wrong state and accepts the pasted URL or bare code', async (t) => {
+ const home = teamHome()
+ const ctx = fakeContext()
+ const rt = createRuntime(ctx, { home, github: false })
+ t.after(async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true }) })
+ await rt.load()
+ const internals = rt.connectorsInternals
+ internals.pendings.set('notion', {
+ kind: 'browser', expectedState: 'STATE1', codeVerifier: 'v', redirectUri: 'http://127.0.0.1:9/callback',
+ discovery: { authorizationServerUrl: 'https://as.test', metadata: AS, resource: 'https://mcp.test/mcp' },
+ clientInformation: { client_id: 'c1' }, timer: setTimeout(() => {}, 60_000), listener: { close: cb => cb?.() },
+ })
+ await assert.rejects(rt.connectorEndpoint('connector-sign-in-code', { id: 'notion', input: 'http://x/?code=C&state=WRONG' }), /state/i)
+ const real = globalThis.fetch
+ globalThis.fetch = async (u) => String(u?.url ?? u) === 'https://as.test/token' ? json({ access_token: 'AT-9', token_type: 'Bearer' }) : notFound()
+ t.after(() => { globalThis.fetch = real })
+ await rt.connectorEndpoint('connector-sign-in-code', { id: 'notion', input: 'http://x/?code=C&state=STATE1' })
+ assert.equal(rt.secretValue('CONNECTOR_NOTION_TOKEN'), 'AT-9')
+})
+
+test('gmail transport: search, read, draft, send, modify, trash, and one refresh on 401', async (t) => {
+ const calls = []
+ let refreshes = 0
+ let authed = false
+ const fakeFetch = async (url, init = {}) => {
+ const u = String(url?.url ?? url)
+ calls.push(u)
+ if (!authed && u.includes('/messages/1?format=full')) {
+ authed = true
+ return new Response('unauth', { status: 401 })
+ }
+ if (u.includes('/messages?') || u.includes('maxResults')) return json({ messages: [{ id: '1' }] })
+ if (u.includes('metadataHeaders')) return json({ id: '1', labelIds: ['UNREAD'], payload: { headers: [{ name: 'Subject', value: 'S' }, { name: 'From', value: 'a@b' }] } })
+ if (u.includes('?format=full')) return json({ id: '1', threadId: 't1', payload: { headers: [{ name: 'Subject', value: 'S' }], parts: [{ mimeType: 'text/plain', body: { data: Buffer.from('hi').toString('base64') } }] } })
+ if (u.includes('/drafts')) return json({ id: 'd1' })
+ if (u.includes('/messages/send')) return json({ id: 's1' })
+ if (u.includes('/modify')) return json({})
+ if (u.includes('/trash')) return json({})
+ return json({})
+ }
+ const { connectGmail } = await import('../src/host/connectors/mail/transport.js')
+ const gmail = connectGmail({ address: '[email protected]' }, { token: () => 'G1', fetch: fakeFetch, refresh: async () => { refreshes += 1; return true } })
+ const rows = await gmail.search({ subject: 'x' })
+ assert.equal(rows.length, 1)
+ assert.equal((await gmail.read({ uid: '1' })).messages[0].text, 'hi')
+ assert.ok((await gmail.draft({ to: 'a@b', subject: 'd', text: 'x' })).folder)
+ await gmail.send({ to: 'a@b', subject: 's', text: 'x' })
+ await gmail.update({ uid: '1', seen: true })
+ await gmail.update({ uid: '1', move: 'trash' })
+ // The 401 on the first read was refreshed exactly once, then retried.
+ assert.equal(refreshes, 1)
+ assert.ok(calls.some(c => c.includes('/drafts')) && calls.some(c => c.includes('/trash')) && calls.some(c => c.includes('/modify')))
+})
+
+test('mail_draft never creates a send card', async (t) => {
+ const home = teamHome()
+ const ctx = fakeContext()
+ const rt = createRuntime(ctx, { home, github: false, mail: { connect: async () => fakeSession() } })
+ t.after(async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true }) })
+ await rt.load()
+ await rt.connectorEndpoint('mail-account-add', { address: '[email protected]', password: 'PASSP' })
+ const draft = rt.teamTools.find(d => d.name === 'mail_draft')
+ await draft.execute({ to: 'x@y', subject: 'S', body: 'B' }, { agent: { id: 'm1' }, callId: 'c1', concludeTurn: () => {} })
+ assert.equal((rt.state.mailRequests?.m1 ?? []).filter(r => r.status === 'pending').length, 0)
+})
+
+test('mail_send refuses attachments outside the working folder', async (t) => {
+ const home = teamHome()
+ const ctx = fakeContext()
+ const rt = createRuntime(ctx, { home, github: false, mail: { connect: async () => fakeSession() } })
+ t.after(async () => { await ctx.dispose(); rmSync(home, { recursive: true, force: true }) })
+ await rt.load()
+ await rt.connectorEndpoint('mail-account-add', { address: '[email protected]', password: 'PASSP' })
+ const send = rt.teamTools.find(d => d.name === 'mail_send')
+ const answer = await send.execute({ to: 'x@y', subject: 'S', body: 'B', attachments: ['../../etc/passwd'] }, { agent: { id: 'm1' }, callId: 'c1', concludeTurn: () => {} })
+ assert.match(String(answer), /working folder/)
+})