feat: 内置 HTML 预览器 + 沙箱浏览器 tab(v0.5.0)
- html viewer:.html/.htm 沙箱 iframe 预览(相对资源经 /sidebar/html 路径编码路由加载,CSP sandbox + 信任围栏 + cwd 边界),预览/编辑切换 - browser tab:+ 菜单多开(browser:<n>),地址栏后退/前进/刷新/在浏览器中打开(15px 图标),URL 与标题按会话持久化(patchTab + nextBrowser) - 安全:iframe 一律不透明源沙箱(无 allow-same-origin/top-navigation、no-referrer、权限策略全禁、禁 srcdoc);地址栏仅 http(s)、拒绝 localhost 等本机地址;界面实时沙箱状态(关闭红色警示)+ 临时解锁/恢复 - 设置:htmlViewerNoSandbox / htmlViewerDefaultUnsafe / browserNoSandbox / browserInterceptLinks 四个声明式二级设置(默认安全) - 外链拦截:聊天/界面 http(s) 外链默认在侧边栏打开(openTab seed.url),Ctrl/Cmd 点击放行 - 嵌入拒绝面板:browser.probe 路由探测 X-Frame-Options/frame-ancestors,被拒站点显示原因 + 在浏览器中打开/仍然加载 - 设置页可滚动;内置 7 tab + 9 viewer;新增设计文档;268 个测试全绿
This commit is contained in:
@@ -124,7 +124,7 @@ interface TabDescriptor {
|
||||
*/
|
||||
settings?: {
|
||||
toggles?: readonly {
|
||||
/** SidebarPrefs 字段名(内置键:'autoOpenSubagent' / 'agentTerminalTools') */
|
||||
/** SidebarPrefs 字段名(内置键:'autoOpenSubagent' / 'agentTerminalTools' / 'htmlViewerNoSandbox' / 'htmlViewerDefaultUnsafe' / 'browserNoSandbox' / 'browserInterceptLinks') */
|
||||
key: string
|
||||
title: string | (() => string)
|
||||
desc?: string | (() => string)
|
||||
@@ -210,6 +210,7 @@ ctx.effect(() =>
|
||||
| `git` | 20 | 是 | 否 | Git 面板 |
|
||||
| `subagent` | 30 | 是 | 否 | 子代理拓扑 |
|
||||
| `terminal` | 40 | 否 | 否 | 终端(nextTerminal 自增) |
|
||||
| `browser` | 50 | 否(createTab 铸造 browser:`<n>`,nextBrowser 自增) | 否 | 内嵌网页浏览器(沙箱 iframe;可设置关闭沙箱) |
|
||||
| `diff` | -1 | 否(按 id 去重) | 是 | 差异查看(由 GitView 触发) |
|
||||
|
||||
你的 `id` 不可与上述重复,否则 `registerTab` 抛 `"tab type \"X\" already registered"`。
|
||||
@@ -283,7 +284,7 @@ interface FileViewerProps {
|
||||
|
||||
> **head 字节从哪来**:第一次匹配(纯扩展名)没有 head。`fsRead` 策略读取后若文件为二进制,host 的 `fs.read` 响应会带 `head` 字段(base64,前 4KB),编辑器会用它对 `detect` viewer **重匹配一次**——所以 detect 型 viewer 的实际触发场景是"扩展名匹配落空/二进制文件"。文本文件的 detect 嗅探不在内置流程内(用 `exts` 或 `custom` 策略替代)。
|
||||
|
||||
> **内置 viewer**(不可重复注册,全部 8 个):image(0) / pdf(0) / docx(0) / xlsx(0) / pptx(0) / markdown(0, fsRead) / code(-100, catch-all, fsRead) / binary-download(-50, exts doc/xls/ppt + NUL detect)。
|
||||
> **内置 viewer**(不可重复注册,全部 9 个):image(0) / pdf(0) / docx(0) / xlsx(0) / pptx(0) / markdown(0, fsRead) / html(0, fsRead, 沙箱 iframe 预览) / code(-100, catch-all, fsRead) / binary-download(-50, exts doc/xls/ppt + NUL detect)。
|
||||
> code 是兜底 viewer:任何其他 viewer 未认领的文件都会落到 code(CodeMirror 文本编辑);二进制文件经 head 重匹配被 binary-download 的 NUL detect 认领(下载按钮)。外部 viewer 注册同扩展名 + 更高 priority 即可覆盖。
|
||||
|
||||
### 4.5 注册示例
|
||||
@@ -360,9 +361,11 @@ interface BetterSidebarService {
|
||||
* 打开一个 tab(+ 菜单和外部触发都用它;走 descriptor.dedupeKey 去重)。
|
||||
* title 可选:给出时优先于 descriptor.title(editor 显示文件名);
|
||||
* 有 createTab 的 descriptor(terminal)会忽略 title/path/id。
|
||||
* url 可选:落地后把 tab 的 path 预填为 URL(侧边栏浏览器导航种子,
|
||||
* 通常配合 hostname title;对 createTab 铸造的 tab 同样生效)。
|
||||
* 被设置禁用的类型是 no-op(console.warn 提示)。
|
||||
*/
|
||||
openTab(seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string }): void
|
||||
openTab(seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string; url?: string }): void
|
||||
/** 关闭一个 tab */
|
||||
closeTab(tabId: string): void
|
||||
/** 订阅注册表变化(register/dispose 时触发) */
|
||||
@@ -370,7 +373,7 @@ interface BetterSidebarService {
|
||||
}
|
||||
```
|
||||
|
||||
> **声明式设置(v0.4.1+)**:每个注册的 tab/viewer 自动出现在 DSH 设置页「侧边卡片」分区的清单里——响应式网格中的**小卡片**(图标 + 标题 + 类型 id + **高亮 = 启用**,勾选徽标钉在卡片最右端,viewer 卡片还显示扩展名),开关持久化到 `SidebarPrefs.tabsEnabled / viewersEnabled`(开放 map,缺省 = 启用)。关闭语义:tab 从 `+` 菜单消失、`openTab` 拒绝新开、子代理自动展开 / agent 终端自动补 tab 等派生流程停止,**已打开的 tab 保留**;viewer 被 `matchFileViewer` 跳过,文件落到下一个匹配。`settings.toggles` 声明的相关设置(如子代理的 `autoOpenSubagent`)通过卡片右下角的齿轮按钮在**原生弹窗**中编辑(复选框行),父级卡片关闭时齿轮隐藏;**key 必须是宿主 PrefsSchema 的字段**(内置键:`autoOpenSubagent` / `agentTerminalTools`),外部插件的自定义键会被 settings seam 丢弃。
|
||||
> **声明式设置(v0.4.1+)**:每个注册的 tab/viewer 自动出现在 DSH 设置页「侧边卡片」分区的清单里——响应式网格中的**小卡片**(图标 + 标题 + 类型 id + **高亮 = 启用**,勾选徽标钉在卡片最右端,viewer 卡片还显示扩展名),开关持久化到 `SidebarPrefs.tabsEnabled / viewersEnabled`(开放 map,缺省 = 启用)。关闭语义:tab 从 `+` 菜单消失、`openTab` 拒绝新开、子代理自动展开 / agent 终端自动补 tab 等派生流程停止,**已打开的 tab 保留**;viewer 被 `matchFileViewer` 跳过,文件落到下一个匹配。`settings.toggles` 声明的相关设置(如子代理的 `autoOpenSubagent`)通过卡片右下角的齿轮按钮在**原生弹窗**中编辑(复选框行),父级卡片关闭时齿轮隐藏;**key 必须是宿主 PrefsSchema 的字段**(内置键:`autoOpenSubagent` / `agentTerminalTools` / `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` / `browserNoSandbox` / `browserInterceptLinks`),外部插件的自定义键会被 settings seam 丢弃。
|
||||
|
||||
---
|
||||
|
||||
@@ -476,11 +479,11 @@ function parseCsv(text: string): string[][] { /* ... */ }
|
||||
|
||||
better-sidebar 自己的内置 tab 和 viewer 就是参考实现("吃狗粮"):
|
||||
|
||||
- **`src/client/builtins/`**:6 个内置 tab(explorer/git/subagent/terminal/editor/diff)+ 8 个内置 viewer(image/pdf/docx/xlsx/pptx/markdown/code/binary-download)的注册代码(tabs.tsx / viewers.tsx / index.ts)
|
||||
- **`src/client/builtins/`**:7 个内置 tab(explorer/git/subagent/terminal/browser/editor/diff)+ 9 个内置 viewer(image/pdf/docx/xlsx/pptx/markdown/html/code/binary-download)的注册代码(tabs.tsx / viewers.tsx / index.ts)
|
||||
- **`src/client/service.ts`**:`BetterSidebarService` 接口 + `createBetterSidebarService` 工厂实现
|
||||
- **`src/client/SideCardSection.tsx`**:声明式设置页(注册表驱动清单 + `settings.toggles` 嵌套开关 + 开关持久化)
|
||||
- **`tests/service.spec.ts`**:注册表生命周期 / 匹配算法 / dedupe / createTab / 启用态 gating 测试
|
||||
- **`tests/builtins.spec.ts`**:内置注册清单断言(6 tab + 8 viewer + 声明式元数据)
|
||||
- **`tests/builtins.spec.ts`**:内置注册清单断言(7 tab + 9 viewer + 声明式元数据)
|
||||
- **`docs/plans/2026-08-11-service-registry-design.md`** / **`docs/plans/2026-08-11-declarative-sidebar-settings-design.md`**:设计文档(含实施偏差记录)
|
||||
|
||||
调试时直接读这些文件即可看到所有 API 的真实用法。
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# 内置 HTML 预览器 + 内嵌网页浏览器(沙箱化)设计
|
||||
|
||||
**日期**:2026-08-11
|
||||
**状态**:已批准,已实施
|
||||
**作者**:opencode + 用户
|
||||
**当前版本**:v0.4.3(main `35cde82`)
|
||||
**目标版本**:v0.5.0
|
||||
|
||||
## 1. 目标
|
||||
|
||||
在 `dsh-better-sidebar` 内按既有 builtins 模式新增两个内置能力:
|
||||
|
||||
1. **`html` 文件预览器**:`.html`/`.htm` 文件在侧边栏编辑器中默认以真实渲染预览(相对资源可加载),可切换代码编辑(CodeMirror HTML 高亮 + 保存)。
|
||||
2. **`browser` 浏览器 tab**:`+` 菜单新增「浏览器」页面,地址栏输入 URL 在沙箱 iframe 中浏览,支持后退/前进/刷新,URL 与标题按 tab 持久化。
|
||||
|
||||
安全问题为第一优先级(用户显式要求"注意安全问题"):所有渲染走**不透明源沙箱 iframe**,host 侧新增 `/sidebar/html` 路由带 CSP + 信任围栏 + cwd 边界。另按用户追加要求提供**关闭沙箱的子设置**(默认关闭该设置;开启需明确勾选,设置项与界面都带安全警告文案)。
|
||||
|
||||
## 2. 复用门(dsh-reuse-first)
|
||||
|
||||
`NO EXISTING CAPABILITY`:已搜索 DSH checkout(docs/*-catalog、apps/web、packages 源码——sidecar/iframe/webview/html preview/CSP 均无等价物;`WorkspaceBrowser` 只是目录树)与 dsh-external org hub 目录(browser/html/webview/iframe/sidecar/viewer/preview 均 0 命中)。全新实现,落点为本仓库 builtins(用户已确认)。
|
||||
|
||||
## 3. 威胁模型与安全基线
|
||||
|
||||
| 威胁 | 对策 |
|
||||
|---|---|
|
||||
| 恶意 HTML/网页读取 GUI 数据(localStorage、`/sidebar/api`、同源 cookie) | iframe 一律 `sandbox` 且**不含 `allow-same-origin`** → 文档源为不透明源(null)。**禁止 srcdoc**(srcdoc 在无沙箱时继承父源),一律 route-src |
|
||||
| 预览/浏览内容劫持 GUI 页面(top 导航) | 不含 `allow-top-navigation` / `allow-top-navigation-by-user-activation` |
|
||||
| 表单 CSRF 打到本地服务 | html 预览器 iframe **不含 `allow-forms`**;浏览器 tab 含 `allow-forms`(登录流必需,残余风险见 §9) |
|
||||
| 浏览器 tab 访问内部地址(GUI 自身、localhost、127.0.0.0/8) | 地址栏导航前客户端阻断(`browser.ts` 纯函数);`javascript:`/`data:`/`file:` 等非 http(s) 一律拒绝 |
|
||||
| 预览页脚本请求 `/sidebar/api` | 三层:不透明源 fetch 被 CORS 拒读;信任围栏拒 `sec-fetch-site: cross-site`;`Origin: null` 无法伪造同源 |
|
||||
| 敏感信息泄露给被浏览站点 | iframe `referrerPolicy="no-referrer"`;权限策略 `allow=""`(拒绝 camera/mic/geolocation 等一切策略特性) |
|
||||
| 直接顶层打开 `/sidebar/html/*` URL(弹窗等) | 路由响应带 `Content-Security-Policy: sandbox ...; object-src 'none'`,顶层同样被沙箱化 |
|
||||
| 路径逃逸 | 路由复用 `requireAbsolute` + `isWithin(cwd, path)` + `mediaLimit` 上限 + 信任围栏 |
|
||||
| 关闭沙箱(用户主动选择) | 每功能独立子设置(`htmlViewerNoSandbox` / `browserNoSandbox`,默认 false);设置文案 + 渲染时持久警告条双警告 |
|
||||
|
||||
## 4. 变更清单
|
||||
|
||||
### 4.1 host:`/sidebar/html` 路由(src/html-route.ts 新 + src/index.ts)
|
||||
|
||||
URL 采用**路径编码**(无 query)——WHATSG URL 解析对纯路径相对引用会丢弃 base 的 query,query 式 URL 下 `./style.css` 会丢失 session 作用域:
|
||||
|
||||
```
|
||||
/sidebar/html/<sessionId>/<绝对路径逐段 encodeURIComponent>
|
||||
例:/sidebar/html/S/Users/me/proj/index.html
|
||||
./style.css → /sidebar/html/S/Users/me/proj/style.css ✓
|
||||
Windows: C:\Users\me\a.html → /sidebar/html/S/C%3A/Users/me/a.html
|
||||
```
|
||||
|
||||
- `src/html-route.ts`(无依赖纯模块,client 可导入不触发纯度门):`encodeHtmlUrl(sessionId, path)`、`decodeHtmlUrl(pathname)`(404 错前缀;400 空路径/双斜杠/畸形编码/缺 sessionId 或文件路径/空段)。
|
||||
- `src/index.ts`:注册 `/sidebar/html` prefix 路由(fence → GET 校验 → decode → `requireAbsolute` → `isWithin(cwd)` → stat isFile + `mediaLimit` → 读文件),响应头:
|
||||
`content-type`(新增 `.html`/`.htm` → `text/html` 到 MEDIA_TYPES)、`cache-control: no-cache`、`X-Content-Type-Options: nosniff`、`Referrer-Policy: no-referrer`、`Content-Security-Policy: sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'`。
|
||||
- cwd 语义与媒体路由一致:session store 权威;会话附着前的首请求回退 `process.cwd()`,通常被 `isWithin` 拒绝(可接受)。
|
||||
|
||||
### 4.2 client:`html` 预览器(TextEditor.tsx 扩展 + builtins/viewers.tsx)
|
||||
|
||||
- descriptor:`{ id:'html', exts:['html','htm'], priority:0, fetchStrategy:'fsRead', settings.toggles:[htmlViewerNoSandbox] }`。
|
||||
- TextEditor:`markdown || html` 都显示预览/编辑切换;html 预览分支渲染:
|
||||
`<iframe src={htmlUrl(scope,path)} sandbox="allow-scripts allow-popups allow-downloads allow-modals" referrerPolicy="no-referrer" allow="" />`
|
||||
- 导出 `HTML_IFRAME_SANDBOX` 常量(测试钉死);沙箱关闭时 `sandbox` 属性整体移除 + 渲染 `sandboxWarning` 警告条。
|
||||
- 预览显示**已保存文件**(route-src),不反映未保存草稿(有意取舍,文档化)。
|
||||
|
||||
### 4.3 client:`browser` tab(BrowserView.tsx 新 + browser.ts 新 + builtins/tabs.tsx + state.ts)
|
||||
|
||||
- state.ts:`SidebarState.nextBrowser`(默认 1;sanitize 对缺失/畸形值回退 1,旧持久化布局继续加载);新 reducer `patchTab(state, tabId, {title?, path?})`。
|
||||
- tabs.tsx:`{ id:'browser', order:50, settings.toggles:[browserNoSandbox], createTab: 铸造 browser:<n> + nextBrowser 递增 }`。
|
||||
- browser.ts(无依赖纯模块):`isLoopbackHostname`(localhost/::1/0.0.0.0/127/8);`normalizeBrowserUrl(input, selfOrigin)`:
|
||||
- 无 scheme → 补 `https://`;`://` 完整 URL 走解析后协议兜底;已知危险 scheme 前缀(javascript/data/file/about/...)直接拒绝;`host:port` 形态(如 `example.com:8080`)不被误判为 scheme。
|
||||
- 拒绝顺序:协议 → 自身 origin **放行**(GUI 自身可在侧边栏打开,沙箱不透明源兜底;须先于 loopback 判定,因其主机通常就是 loopback)→ loopback 阻止 → ok。
|
||||
- BrowserView:地址栏(后退/前进/刷新/输入/前往)+ iframe + 状态行;URL 经 `patchTab` 持久化到 `tab.path`/`tab.title`(hostname);历史栈仅记录地址栏导航(iframe 内部跳转跨域不可见,已知限制);无 URL 时显示起始页(不自动加载任何站点)。
|
||||
- iframe:`sandbox="allow-scripts allow-forms allow-popups allow-downloads allow-modals allow-popups-to-escape-sandbox"`(导出 `BROWSER_IFRAME_SANDBOX`;无 allow-same-origin / allow-top-navigation;allow-popups-to-escape-sandbox 供 OAuth 弹窗);沙箱关闭时移除属性 + 警告条。
|
||||
- 常驻底部小字沙箱说明(`browserHint`)。
|
||||
|
||||
### 4.4 设置(prefs-shared.ts + config.ts + SideCardSection 声明式渲染)
|
||||
|
||||
- `SidebarPrefs` 新增 `htmlViewerNoSandbox` / `browserNoSandbox`(boolean,默认 false);`SIDEBAR_PREFS_DEFAULTS` 与 `PrefsSchema` 同步;`parsePrefs` 按字段校验回退。
|
||||
- 声明式设置:html viewer 行与 browser tab 行各自 `settings.toggles`,设置页自动渲染(父级关闭时隐藏),文案含「(不安全)」+ 后果说明。
|
||||
|
||||
### 4.5 其他
|
||||
|
||||
- `api.ts`:`htmlUrl(scope, path)` = `encodeHtmlUrl(sessionId, path)`。
|
||||
- `icons.tsx`:`IconHtmlOutline16`(文件 + `‹/›`)、`IconGlobeOutline16`(地球)。
|
||||
- `locales.ts`:zh/en 双份新键(viewerHtml/browser/浏览器栏/阻止原因/沙箱提示/设置文案)。
|
||||
- `sidebar.module.css`:`sandboxWarning`、`editorHtml`、`.browser*` 系列。
|
||||
|
||||
## 5. 测试
|
||||
|
||||
| 文件 | 覆盖 |
|
||||
|---|---|
|
||||
| tests/html-route.spec.ts(新) | 编码/解码往返(POSIX/Windows/特殊字符)、相对解析保持同路由同 session、404/400 拒绝、遍历段留给 isWithin |
|
||||
| tests/browser.spec.ts(新) | 补 https、host:port 不误判、危险 scheme/loopback 拒绝、自身 origin 放行、invalid |
|
||||
| tests/sandbox-views.spec.tsx(新) | iframe sandbox 常量钉死(无 allow-same-origin/top-navigation)、route-src 非 srcdoc、referrer/allow 属性、沙箱关闭 → 无 sandbox 属性 + 警告条、markdown 分支回归、浏览器起始页不自动加载 |
|
||||
| tests/builtins.spec.ts | 7 tab / 9 viewer 清单、html 扩展名匹配、browser createTab 铸造与 nextBrowser、两个 toggles 声明 |
|
||||
| tests/unit.spec.ts | nextBrowser sanitize(缺失/畸形回退 1)、patchTab 更新/无操作、parsePrefs 新字段默认与校验 |
|
||||
| tests/smoke.spec.ts | fenced routes 清单 + `/sidebar/html` |
|
||||
|
||||
## 6. 版本与文档
|
||||
|
||||
- 版本 0.4.3 → 0.5.0(package.json + dsh.plugin.json 同步,manifest-consistency 守卫)。
|
||||
- README/AGENTS 内置清单更新为 7 tab + 9 viewer。
|
||||
|
||||
## 7. 验收标准
|
||||
|
||||
1. `pnpm typecheck && pnpm build && pnpm test` 全绿(245 用例)。
|
||||
2. 手动:打开 `.html` 默认预览渲染(相对资源可加载),可切编辑/保存;`+` 菜单浏览器 tab 多开、地址栏浏览、后退/前进/刷新、刷新页面恢复 URL 与标题。
|
||||
3. 安全:预览/浏览 iframe 无 allow-same-origin/top-navigation;`javascript:`/`data:`/`file:`/localhost/127.x 均被阻止并提示(自身 origin 允许);`/sidebar/html` 越界 403、超限 400、跨站 403;预览页 fetch `/sidebar/api` 读不到(CORS),预览器表单被沙箱禁(无 allow-forms)。
|
||||
4. 关闭沙箱开关:设置页勾选后界面出现持久警告条,iframe 无 sandbox 属性。
|
||||
|
||||
## 8. 实施偏差记录
|
||||
|
||||
- 设计初期考虑过 srcdoc + `<base>` 注入以实现"预览反映未保存草稿",因 srcdoc 无沙箱时继承父源的致命风险与 base 注入的脆弱性,改采 route-src(预览 = 已保存文件);相对资源经路径编码 URL 天然解析,无需内容改写。
|
||||
- `normalizeBrowserUrl` 的 scheme 判别:朴素正则会把 `example.com:8080` 误判为 scheme,最终采用「`://` 完整 URL + 危险 scheme 黑名单 + 解析后协议兜底」三段式。
|
||||
- `nextBrowser` 在 sanitize 中为宽松字段(缺失/畸形回退 1),避免旧持久化布局整体失效(与严格校验的 `nextTerminal` 不同)。
|
||||
|
||||
## 8.1 追加需求(2026-08-11,v0.5.0 内)
|
||||
|
||||
1. **设置页滚动**:`SideCardSection.module.css` 的 `.section` 填满设置壳 options 区并内部滚动(`height:100% + min-height:0 + overflow-y:auto`),7 tab + 9 viewer 卡片再多也不会被裁切。
|
||||
2. **沙箱状态实时显示 + 临时解锁**:新增 `SandboxStatusBar`(HTML 预览与浏览器 tab 共用)——沙箱开启显示绿色状态 + 「临时解锁(不安全)」按钮;关闭(全局设置或本页临时解锁)显示**红色警示**(`state-error-primary` 色系 + 危险文案)与「恢复沙箱」按钮(仅临时态)。临时解锁是组件内 state,不写回全局设置,随页面/标签卸载失效;iframe 随沙箱翻转重挂载。
|
||||
3. **聊天/界面外链在侧边栏打开**:新设置 `browserInterceptLinks`(默认开,受浏览器 tab 启用开关 gate)——`link-intercept.ts` 在 document capture 阶段拦截 http(s) **外部**链接点击(同源/非 http(s)/修饰键点击一律放行),经 `openTab({type:'browser', url, title: hostname})`(openTab seed 新增 `url` 字段:落地后 patchTab 预填 path)在侧边栏打开。浏览器 tab 地址栏新增「在浏览器中打开」按钮(`window.open(url,'_blank','noopener')`,用户手势触发,等价真实浏览器新标签)。
|
||||
|
||||
## 8.2 追加需求(2026-08-11 二轮,v0.5.0 内)
|
||||
|
||||
1. **HTML「默认非安全」二级设置**:`htmlViewerDefaultUnsafe`(默认 false)——打开 HTML 文件时预览**初始**处于非沙箱状态(localUnlock 初始值取自该 pref),状态行仍可一键「恢复沙箱」;与 `htmlViewerNoSandbox`(全局强制关闭,不可界面恢复)语义区分。
|
||||
2. **沙箱状态行单行化并取代底部说明**:浏览器 tab 底部常驻 `browserHint` 条移除,说明并入 `SandboxStatusBar` 开启态文案(「沙箱模式:已启用 · 页面无法访问界面数据与本地文件,登录态与第三方 Cookie 可能不可用」),状态行 `nowrap + ellipsis + title` 恒为一行;关闭态同样单行红色警示。
|
||||
3. **「在浏览器中打开」图标放大**:`IconRightUpOutline14` → `IconRightUpOutline16`(15px 渲染)。
|
||||
|
||||
## 8.3 追加需求(2026-08-11 三轮,v0.5.0 内)
|
||||
|
||||
1. **图标改 15px**:`<IconRightUpOutline16 size={15} />`。
|
||||
2. **嵌入拒绝面板**:站点通过 `X-Frame-Options` / CSP `frame-ancestors` 禁止嵌入时,浏览器 tab 不再显示空白拒绝框,而是显示 `BrowserEmbedBlocked` 面板——「{host} 拒绝了嵌入请求」+ 原因说明 + 「在浏览器中打开」(`window.open`)+ 「仍然加载」两个按钮。检测:新增 host 路由 `browser.probe`(HEAD→GET 兜底,8s 超时,仅 http(s) 非 loopback,返回目标响应头的 `x-frame-options`/`frame-ancestors`,受信任围栏保护)+ 客户端 `embeddabilityOf` 判定(XFO DENY/SAMEORIGIN 或 frame-ancestors 不含 `*` → blocked;探测失败 → unknown 保持普通 iframe)。探测在每次导航(含恢复的 path)时经 `useEffect(url)` 触发;「仍然加载」以 `forceEmbed` 保留普通 iframe。
|
||||
|
||||
## 9. 已知限制与残余风险
|
||||
|
||||
- 浏览器沙箱无登录态/第三方 Cookie 受限(SameSite=Lax 在跨站 iframe 不发送),部分站点登录需走弹窗(allow-popups-to-escape-sandbox 已开)。
|
||||
- iframe 内部链接跳转不进后退栈(跨域不可见);被 `X-Frame-Options`/`frame-ancestors` 拒绝的站点显示空白(站点策略,无法绕过)。
|
||||
- 用户主动浏览的恶意站点仍可在沙箱内发起盲 GET(无法读取响应)到本地服务;站点重定向链可把 iframe 带到 localhost(内容仍沙箱化、受围栏保护)。
|
||||
- 关闭沙箱后预览/浏览内容获得 GUI 同源权限(可读会话文件/本地存储/调内部接口)——仅建议对完全可信内容开启,设置与界面双重警告。
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"id": "dsh-external/dsh-better-sidebar",
|
||||
"version": "0.4.3",
|
||||
"version": "0.5.0",
|
||||
"main": "./lib/index.js",
|
||||
"description": "VSCode 风格右侧侧边栏:文件资源管理器 / 编辑器 / 终端 / Git,按会话隔离。暴露服务供其他插件注册侧边栏页面和文件预览器",
|
||||
"description": "VSCode 风格右侧侧边栏:文件资源管理器 / 编辑器 / 终端 / Git / 浏览器,按会话隔离。暴露服务供其他插件注册侧边栏页面和文件预览器",
|
||||
"engines": {
|
||||
"dsh": ">=0.0.1"
|
||||
},
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "dsh-better-sidebar",
|
||||
"version": "0.4.3",
|
||||
"description": "DSH web plugin: a VSCode-like right sidebar (explorer / editor / terminal / git), isolated per conversation session. Exposes a service for other plugins to register sidebar tabs and file viewers.",
|
||||
"version": "0.5.0",
|
||||
"description": "DSH web plugin: a VSCode-like right sidebar (explorer / editor / terminal / git / browser), isolated per conversation session. Exposes a service for other plugins to register sidebar tabs and file viewers.",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Pure helpers for the `browser.probe` route (sidebar browser): the host
|
||||
* fetches the response HEADERS of a URL the user is browsing and the client
|
||||
* decides whether the target site forbids being embedded (X-Frame-Options /
|
||||
* CSP frame-ancestors are exactly the signals the browser enforces when it
|
||||
* refuses an iframe load). Kept dependency-free so the parser is
|
||||
* unit-testable.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Extract the `frame-ancestors` source list of a Content-Security-Policy
|
||||
* header, or undefined when the directive is absent (or empty). The
|
||||
* directive is the only one with a source list; sources are space-separated
|
||||
* tokens (`'none'`, `'self'`, `*`, or origins).
|
||||
*/
|
||||
export function extractFrameAncestors(csp: string | null): string[] | undefined {
|
||||
if (csp === null) return undefined
|
||||
for (const directive of csp.split(';')) {
|
||||
const parts = directive.trim().split(/\s+/)
|
||||
if (parts[0] === 'frame-ancestors') {
|
||||
const sources = parts.slice(1).filter(source => source !== '')
|
||||
return sources.length === 0 ? undefined : sources
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* The built-in browser tab: an address bar plus a sandboxed iframe.
|
||||
*
|
||||
* Security model (see browser.ts + the sandbox tokens below): the iframe is
|
||||
* ALWAYS sandboxed without `allow-same-origin` (opaque origin — the visited
|
||||
* page can never sit on the GUI's origin, read its storage, or reach
|
||||
* /sidebar/api) and without `allow-top-navigation` (a page must not hijack
|
||||
* the GUI). The address bar only accepts http(s) and refuses loopback /
|
||||
* the GUI's own origin. The side card setting "关闭浏览器沙箱" drops the
|
||||
* sandbox attribute entirely for fully trusted sites — the visited page then
|
||||
* runs with the GUI's own origin and full session access, so a persistent
|
||||
* warning bar renders while it is off.
|
||||
*
|
||||
* The URL is persisted onto the tab (path/title via the patchTab reducer)
|
||||
* so a reload restores the visited page; the back/forward stack only tracks
|
||||
* address-bar navigations (in-frame link clicks are cross-origin and
|
||||
* invisible — a documented limitation).
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
IconChevronLeftOutline14,
|
||||
IconChevronRightOutline14,
|
||||
IconLinkOutline14,
|
||||
IconRefreshOutline14,
|
||||
IconRightUpOutline16,
|
||||
IconWarningOutline16,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { api } from './api.ts'
|
||||
import { embeddabilityOf, normalizeBrowserUrl } from './browser.ts'
|
||||
import { patchTab } from './state.ts'
|
||||
import { SandboxStatusBar } from './SandboxStatusBar.tsx'
|
||||
import { t } from './locales.ts'
|
||||
import type { TabComponentProps } from './service.ts'
|
||||
import css from './sidebar.module.css'
|
||||
|
||||
/**
|
||||
* The browser iframe sandbox tokens. NO allow-same-origin (opaque origin —
|
||||
* no GUI storage/API access), NO allow-top-navigation (a browsed page must
|
||||
* not hijack the GUI). allow-forms/allow-popups/allow-downloads/allow-modals
|
||||
* keep login flows working; allow-popups-to-escape-sandbox lets OAuth
|
||||
* popups open as normal tabs (they are cross-origin to the GUI either way).
|
||||
*/
|
||||
export const BROWSER_IFRAME_SANDBOX =
|
||||
'allow-scripts allow-forms allow-popups allow-downloads allow-modals allow-popups-to-escape-sandbox'
|
||||
|
||||
export function BrowserView(props: TabComponentProps) {
|
||||
const { store, tab } = props
|
||||
// The current address (initialized from the persisted tab.path so a
|
||||
// reload restores the visited page).
|
||||
const [url, setUrl] = useState<string | undefined>(tab.path)
|
||||
const [input, setInput] = useState<string>(tab.path ?? '')
|
||||
/** Blocked/invalid hint shown under the address bar (null = none). */
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
/** Address-bar navigation history (in-frame clicks are not tracked). */
|
||||
const [history, setHistory] = useState<string[]>(tab.path !== undefined ? [tab.path] : [])
|
||||
const [cursor, setCursor] = useState<number>(tab.path !== undefined ? 0 : -1)
|
||||
/** Bumped on reload to remount the iframe (also remounts on sandbox flip). */
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
/** TEMPORARY sandbox unlock for THIS surface only (never writes the global
|
||||
* side card setting; lasts until the tab unmounts or the user restores). */
|
||||
const [localUnlock, setLocalUnlock] = useState(false)
|
||||
const noSandbox = store.getPrefs().browserNoSandbox === true || localUnlock
|
||||
/** A site that refuses to be embedded (X-Frame-Options / frame-ancestors):
|
||||
* the probe verdict shown instead of the blank iframe. */
|
||||
const [embedBlocked, setEmbedBlocked] = useState<string | null>(null)
|
||||
/** The user asked to load the refused site anyway (keeps the plain iframe). */
|
||||
const [forceEmbed, setForceEmbed] = useState(false)
|
||||
|
||||
// Probe every navigation (address bar, history, restored path): when the
|
||||
// target forbids embedding, show the reason + open-in-browser instead of
|
||||
// the browser's cryptic "refused to connect" blank frame. A failed probe
|
||||
// (unreachable) keeps the plain iframe.
|
||||
useEffect(() => {
|
||||
if (url === undefined) return
|
||||
let cancelled = false
|
||||
setEmbedBlocked(null)
|
||||
setForceEmbed(false)
|
||||
void api.browserProbe(url).then((probe) => {
|
||||
if (!cancelled && embeddabilityOf(probe) === 'blocked') setEmbedBlocked(url)
|
||||
}).catch(() => { /* unreachable: keep the plain iframe */ })
|
||||
return () => { cancelled = true }
|
||||
}, [url])
|
||||
|
||||
const persist = (nextUrl: string): void => {
|
||||
let host = nextUrl
|
||||
try { host = new URL(nextUrl).hostname } catch { /* keep the URL as title */ }
|
||||
store.reduce(state => patchTab(state, tab.id, { path: nextUrl, title: host }))
|
||||
}
|
||||
|
||||
const navigateTo = (raw: string): void => {
|
||||
const result = normalizeBrowserUrl(raw, window.location.origin)
|
||||
if (result.kind === 'ok') {
|
||||
const next = result.url
|
||||
setUrl(next)
|
||||
setInput(next)
|
||||
setMessage(null)
|
||||
// Push onto the stack, dropping any stale forward entries.
|
||||
setHistory(previous => [...previous.slice(0, cursor + 1), next])
|
||||
setCursor(previous => previous + 1)
|
||||
setReloadKey(key => key + 1)
|
||||
persist(next)
|
||||
return
|
||||
}
|
||||
setMessage(result.kind === 'invalid'
|
||||
? t('browserInvalid')
|
||||
: result.reason === 'scheme' ? t('browserBlockedScheme')
|
||||
: t('browserBlockedLoopback'))
|
||||
}
|
||||
|
||||
const goBack = (): void => {
|
||||
if (cursor <= 0) return
|
||||
const next = history[cursor - 1]!
|
||||
setCursor(cursor - 1)
|
||||
setUrl(next)
|
||||
setInput(next)
|
||||
setReloadKey(key => key + 1)
|
||||
}
|
||||
|
||||
const goForward = (): void => {
|
||||
if (cursor >= history.length - 1) return
|
||||
const next = history[cursor + 1]!
|
||||
setCursor(cursor + 1)
|
||||
setUrl(next)
|
||||
setInput(next)
|
||||
setReloadKey(key => key + 1)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={css.browser}>
|
||||
<div className={css.browserBar}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
aria-label={t('browserBack')}
|
||||
title={t('browserBack')}
|
||||
disabled={cursor <= 0}
|
||||
onClick={goBack}
|
||||
>
|
||||
<IconChevronLeftOutline14 />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
aria-label={t('browserForward')}
|
||||
title={t('browserForward')}
|
||||
disabled={cursor >= history.length - 1}
|
||||
onClick={goForward}
|
||||
>
|
||||
<IconChevronRightOutline14 />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
aria-label={t('refresh')}
|
||||
title={t('refresh')}
|
||||
onClick={() => { setReloadKey(key => key + 1) }}
|
||||
>
|
||||
<IconRefreshOutline14 />
|
||||
</button>
|
||||
<input
|
||||
className={css.browserInput}
|
||||
value={input}
|
||||
placeholder={t('browserPlaceholder')}
|
||||
spellCheck={false}
|
||||
onChange={event => { setInput(event.target.value) }}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') navigateTo(input)
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
aria-label={t('browserGo')}
|
||||
title={t('browserGo')}
|
||||
onClick={() => { navigateTo(input) }}
|
||||
>
|
||||
<IconLinkOutline14 />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
aria-label={t('browserOpenExternal')}
|
||||
title={t('browserOpenExternal')}
|
||||
disabled={url === undefined}
|
||||
onClick={() => {
|
||||
if (url !== undefined) window.open(url, '_blank', 'noopener')
|
||||
}}
|
||||
>
|
||||
<IconRightUpOutline16 size={15} />
|
||||
</button>
|
||||
</div>
|
||||
{message !== null && <div className={css.browserMessage}>{message}</div>}
|
||||
<SandboxStatusBar
|
||||
sandboxed={!noSandbox}
|
||||
local={localUnlock}
|
||||
dangerCopy={t('browserNoSandboxWarning')}
|
||||
onUnlock={() => { setLocalUnlock(true) }}
|
||||
onRestore={() => { setLocalUnlock(false) }}
|
||||
/>
|
||||
{url === undefined ? (
|
||||
<div className={css.browserStart}>{t('browserStart')}</div>
|
||||
) : embedBlocked !== null && !forceEmbed ? (
|
||||
<BrowserEmbedBlocked
|
||||
url={embedBlocked}
|
||||
onOpenInBrowser={() => { window.open(embedBlocked, '_blank', 'noopener') }}
|
||||
onLoadAnyway={() => { setForceEmbed(true) }}
|
||||
/>
|
||||
) : (
|
||||
<iframe
|
||||
key={`${reloadKey}:${noSandbox ? 'ns' : 'sb'}`}
|
||||
className={css.browserFrame}
|
||||
src={url}
|
||||
sandbox={noSandbox ? undefined : BROWSER_IFRAME_SANDBOX}
|
||||
referrerPolicy="no-referrer"
|
||||
allow=""
|
||||
title={url}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The embed-refusal panel: shown when the probed site forbids being
|
||||
* displayed inside other pages (X-Frame-Options / frame-ancestors) — the
|
||||
* iframe would only show the browser's "refused to connect" blank. Explains
|
||||
* the reason and offers the real-browser open plus a load-anyway escape.
|
||||
* Exported so the copy and the actions are testable without a DOM.
|
||||
*/
|
||||
export function BrowserEmbedBlocked(props: {
|
||||
url: string
|
||||
onOpenInBrowser: () => void
|
||||
onLoadAnyway: () => void
|
||||
}) {
|
||||
const { url, onOpenInBrowser, onLoadAnyway } = props
|
||||
let host = url
|
||||
try { host = new URL(url).hostname } catch { /* keep the raw URL */ }
|
||||
return (
|
||||
<div className={css.browserBlocked}>
|
||||
<IconWarningOutline16 size={16} />
|
||||
<div className={css.browserBlockedTitle}>{t('browserEmbedBlocked', { host })}</div>
|
||||
<div className={css.browserBlockedDesc}>{t('browserEmbedBlockedDesc')}</div>
|
||||
<div className={css.browserBlockedActions}>
|
||||
<button type="button" className={css.browserBlockedButton} onClick={onOpenInBrowser}>
|
||||
{t('browserOpenExternal')}
|
||||
</button>
|
||||
<button type="button" className={css.browserBlockedButton} onClick={onLoadAnyway}>
|
||||
{t('browserEmbedAnyway')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* The live sandbox status row of the two built-in web surfaces (HTML
|
||||
* preview and the browser tab): a green "sandbox on" state with a one-tap
|
||||
* TEMPORARY unlock, or a RED "sandbox off" state (global setting or the
|
||||
* temporary unlock) with a restore action.
|
||||
*
|
||||
* The temporary unlock is component state only — it never writes the
|
||||
* global side card setting (`htmlViewerNoSandbox` / `browserNoSandbox`);
|
||||
* it lasts until the surface unmounts (tab switch / file switch) or the
|
||||
* user restores the sandbox from the row. When the global setting already
|
||||
* drops the sandbox, no unlock/restore action is offered (changing the
|
||||
* global setting is the settings page's job) — the red warning stands.
|
||||
*/
|
||||
import clsx from 'clsx'
|
||||
import { t } from './locales.ts'
|
||||
import css from './sidebar.module.css'
|
||||
|
||||
export function SandboxStatusBar(props: {
|
||||
/** The effective sandbox state (global pref OR the local temporary unlock). */
|
||||
sandboxed: boolean
|
||||
/** Whether the sandbox is off due to the LOCAL temporary unlock (shows the restore action). */
|
||||
local: boolean
|
||||
/** The red-state explanation (e.g. "the page runs with full GUI privileges"). */
|
||||
dangerCopy: string
|
||||
onUnlock: () => void
|
||||
onRestore: () => void
|
||||
}) {
|
||||
const { sandboxed, local, dangerCopy, onUnlock, onRestore } = props
|
||||
if (sandboxed) {
|
||||
const copy = t('sandboxStatusOn')
|
||||
return (
|
||||
<div className={clsx(css.sandboxStatus, css.sandboxStatusOn)}>
|
||||
<span className={css.sandboxDot} />
|
||||
<span className={css.sandboxStatusText} title={copy}>{copy}</span>
|
||||
<button
|
||||
type="button"
|
||||
className={css.sandboxAction}
|
||||
onClick={onUnlock}
|
||||
>
|
||||
{t('sandboxUnlock')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className={clsx(css.sandboxStatus, css.sandboxStatusOff)}>
|
||||
<span className={css.sandboxDot} />
|
||||
<span className={css.sandboxStatusText} title={dangerCopy}>{dangerCopy}</span>
|
||||
{local && (
|
||||
<button
|
||||
type="button"
|
||||
className={css.sandboxAction}
|
||||
onClick={onRestore}
|
||||
>
|
||||
{t('sandboxRestore')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -16,6 +16,12 @@
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
/* Tall inventories (7 tab cards + 9 viewer cards + general rows) must
|
||||
never be clipped by the settings shell: fill the shell's options area
|
||||
and scroll inside the section when the content outgrows the panel. */
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.section > :last-child {
|
||||
|
||||
@@ -15,10 +15,11 @@ import { EditorState } from '@codemirror/state'
|
||||
import { EditorView as CodeMirrorView, keymap, lineNumbers } from '@codemirror/view'
|
||||
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands'
|
||||
import { IconCheckOutline16, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { api } from './api.ts'
|
||||
import { api, htmlUrl } from './api.ts'
|
||||
import { languageForPath } from './lang.ts'
|
||||
import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts'
|
||||
import { isDarkScheme, subscribeColorScheme } from './theme.ts'
|
||||
import { SandboxStatusBar } from './SandboxStatusBar.tsx'
|
||||
import { t } from './locales.ts'
|
||||
import type { FileViewerProps } from './service.ts'
|
||||
import css from './sidebar.module.css'
|
||||
@@ -26,6 +27,15 @@ import css from './sidebar.module.css'
|
||||
/** Previewable files (rendered output vs source editing). */
|
||||
type ViewMode = 'preview' | 'edit'
|
||||
|
||||
/**
|
||||
* The sandbox tokens of the HTML preview iframe. NO allow-same-origin (the
|
||||
* preview must stay in an opaque origin — with the route's own origin it
|
||||
* could read session data) and NO allow-top-navigation (a previewed page
|
||||
* must not hijack the GUI). The user can disable the sandbox per-feature
|
||||
* in the side card settings (warned); the toggle below reflects it.
|
||||
*/
|
||||
export const HTML_IFRAME_SANDBOX = 'allow-scripts allow-popups allow-downloads allow-modals'
|
||||
|
||||
export function TextEditor(props: FileViewerProps) {
|
||||
const { scope, path, viewerId, content, truncated } = props
|
||||
const [mode, setMode] = useState<ViewMode>('preview')
|
||||
@@ -136,13 +146,23 @@ export function TextEditor(props: FileViewerProps) {
|
||||
}
|
||||
|
||||
const markdown = viewerId === 'markdown'
|
||||
const html = viewerId === 'html'
|
||||
const editable = content !== undefined
|
||||
const saveLabel = saveState === 'saving' ? t('loading') : saveState === 'saved' ? t('saved') : saveState === 'failed' ? t('saveFailed') : ''
|
||||
// Per-feature sandbox escape hatch: the global side card setting (warned)
|
||||
// plus a per-surface temporary unlock. The unlock state starts at the
|
||||
// "default unsafe" pref so a preview can open straight into the red
|
||||
// unsandboxed state (still restorable from the status row). With the
|
||||
// sandbox OFF the preview iframe drops its sandbox attribute entirely —
|
||||
// the previewed page then runs on the GUI's own origin with full session
|
||||
// access.
|
||||
const [localUnlock, setLocalUnlock] = useState(() => props.store?.getPrefs().htmlViewerDefaultUnsafe === true)
|
||||
const htmlNoSandbox = props.store?.getPrefs().htmlViewerNoSandbox === true || localUnlock
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={css.editorHeader}>
|
||||
{markdown && (
|
||||
{(markdown || html) && (
|
||||
<div className={css.editorModeToggle}>
|
||||
<button
|
||||
type="button"
|
||||
@@ -178,7 +198,7 @@ export function TextEditor(props: FileViewerProps) {
|
||||
<>
|
||||
{truncated === true && mode === 'edit' && <div className={css.editorBanner}>{t('truncation')}</div>}
|
||||
<div
|
||||
className={clsx(css.editorCm, markdown && mode === 'preview' && css.editorCmHidden)}
|
||||
className={clsx(css.editorCm, (markdown || html) && mode === 'preview' && css.editorCmHidden)}
|
||||
ref={hostRef}
|
||||
/>
|
||||
</>
|
||||
@@ -188,6 +208,29 @@ export function TextEditor(props: FileViewerProps) {
|
||||
<MarkdownText text={draft ?? content ?? ''} />
|
||||
</div>
|
||||
)}
|
||||
{html && mode === 'preview' && (
|
||||
<>
|
||||
<SandboxStatusBar
|
||||
sandboxed={!htmlNoSandbox}
|
||||
local={localUnlock}
|
||||
dangerCopy={t('htmlNoSandboxWarning')}
|
||||
onUnlock={() => { setLocalUnlock(true) }}
|
||||
onRestore={() => { setLocalUnlock(false) }}
|
||||
/>
|
||||
{/* Route-src (never srcdoc — a srcdoc frame inherits the parent
|
||||
origin when unsandboxed; the route URL keeps the frame
|
||||
cross-origin by construction). The preview shows the SAVED
|
||||
file; the draft is only visible in edit mode. */}
|
||||
<iframe
|
||||
className={css.editorHtml}
|
||||
src={htmlUrl(scope, path)}
|
||||
sandbox={htmlNoSandbox ? undefined : HTML_IFRAME_SANDBOX}
|
||||
referrerPolicy="no-referrer"
|
||||
allow=""
|
||||
title={path}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* hydrating at page load (a detached session would otherwise fail the
|
||||
* request). Failures surface as {@link SidebarApiError} with the wire code.
|
||||
*/
|
||||
import { encodeHtmlUrl } from '../html-route.ts'
|
||||
import type { BrowserProbeResult } from './browser.ts'
|
||||
|
||||
/** One wire failure. */
|
||||
export class SidebarApiError extends Error {
|
||||
@@ -152,6 +154,10 @@ export const api = {
|
||||
patch,
|
||||
...(expectedRevision !== undefined ? { expectedRevision } : {}),
|
||||
}),
|
||||
/** Probe a URL's response headers (the sidebar browser's embeddability
|
||||
* check; see the host's browser.probe route). */
|
||||
browserProbe: (url: string, signal?: AbortSignal) =>
|
||||
call<BrowserProbeResult>('browser.probe', { url }, signal),
|
||||
}
|
||||
|
||||
/** Absolute URL of the media route for one path (images only). */
|
||||
@@ -172,3 +178,10 @@ function fileUrl(scope: SessionScope, path: string, download: boolean): string {
|
||||
if (download) params.set('download', '1')
|
||||
return `/sidebar/file?${params.toString()}`
|
||||
}
|
||||
|
||||
/** Absolute URL of the HTML preview route (see html-route.ts): the path is
|
||||
* fully encoded so the previewed page's relative assets resolve back into
|
||||
* the same route with the session scope intact. */
|
||||
export function htmlUrl(scope: SessionScope, path: string): string {
|
||||
return encodeHtmlUrl(scope.sessionId, path)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Pure URL policy for the built-in browser tab: normalize user input into
|
||||
* an http(s) URL, and refuse destinations that would be dangerous to embed
|
||||
* in the sidebar iframe. Kept dependency-free so it is unit-testable.
|
||||
*
|
||||
* The iframe sandbox (opaque origin, no allow-same-origin / top-navigation)
|
||||
* is the primary security boundary; this module is the address-bar gate on
|
||||
* top of it: only http/https may be navigated, and loopback addresses are
|
||||
* refused so a browsed page cannot probe local services by user action.
|
||||
* The GUI's OWN origin is explicitly ALLOWED — the user may open the GUI
|
||||
* itself in the sidebar (debugging, mirroring); the sandbox still renders
|
||||
* it in an opaque origin with no same-origin privileges, exactly like any
|
||||
* other site.
|
||||
*/
|
||||
|
||||
/** Why a navigation attempt was refused. */
|
||||
export type BrowserBlockReason = 'scheme' | 'loopback'
|
||||
|
||||
/** Result of normalizing one address-bar input. */
|
||||
export type BrowserNavigateResult =
|
||||
| { kind: 'ok'; url: string }
|
||||
| { kind: 'blocked'; reason: BrowserBlockReason }
|
||||
| { kind: 'invalid' }
|
||||
|
||||
/** One browser.probe wire result (host fetch of the target's headers). */
|
||||
export interface BrowserProbeResult {
|
||||
reachable: boolean
|
||||
/** The final (post-redirect) URL; present when reachable. */
|
||||
url?: string
|
||||
status?: number
|
||||
xFrameOptions?: string
|
||||
/** The CSP frame-ancestors source list; present when the directive exists. */
|
||||
frameAncestors?: string[]
|
||||
}
|
||||
|
||||
/** Embeddability verdict of one probe. */
|
||||
export type Embeddability = 'embeddable' | 'blocked' | 'unknown'
|
||||
|
||||
/**
|
||||
* Decide whether a site can render inside the sidebar iframe. The signals
|
||||
* are exactly the ones the BROWSER enforces when it refuses an iframe load:
|
||||
* X-Frame-Options DENY/SAMEORIGIN, or a frame-ancestors directive that does
|
||||
* not allow `*` ('self' here means the SITE's own origin — never ours, so
|
||||
* it also blocks the sidebar). A site we could not reach yields 'unknown'
|
||||
* and the plain iframe stays.
|
||||
*/
|
||||
export function embeddabilityOf(probe: BrowserProbeResult): Embeddability {
|
||||
if (probe.reachable !== true) return 'unknown'
|
||||
const xfo = probe.xFrameOptions?.trim().toUpperCase()
|
||||
if (xfo === 'DENY' || xfo === 'SAMEORIGIN') return 'blocked'
|
||||
if (probe.frameAncestors !== undefined && !probe.frameAncestors.some(source => source === '*')) return 'blocked'
|
||||
return 'embeddable'
|
||||
}
|
||||
|
||||
/** A loopback hostname (localhost, IPv6 ::1, 127.0.0.0/8, 0.0.0.0). */
|
||||
export function isLoopbackHostname(hostname: string): boolean {
|
||||
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
|
||||
if (host === 'localhost' || host === '::1' || host === '0.0.0.0') return true
|
||||
const parts = host.split('.')
|
||||
return parts.length === 4
|
||||
&& parts[0] === '127'
|
||||
&& parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one address-bar input against the navigation policy.
|
||||
* @param input - raw user text.
|
||||
* @param selfOrigin - the GUI's own origin (window.location.origin). The GUI
|
||||
* itself may be browsed in the sidebar (the sandbox keeps it opaque), so it
|
||||
* is let through BEFORE the loopback check — its host is normally loopback.
|
||||
*/
|
||||
/** Schemes that must never reach the iframe, even without `//` (javascript:,
|
||||
* data:, file:, ...). Host:port lookalikes (example.com:8080) are NOT here —
|
||||
* they parse as hosts below. */
|
||||
const FORBIDDEN_SCHEMES = new Set([
|
||||
'javascript', 'data', 'file', 'about', 'vbscript', 'blob',
|
||||
'mailto', 'tel', 'ftp', 'ftps', 'ws', 'wss', 'sftp', 'ssh',
|
||||
'chrome', 'chrome-extension', 'moz-extension', 'edge', 'opera', 'resource', 'view-source',
|
||||
])
|
||||
|
||||
export function normalizeBrowserUrl(input: string, selfOrigin: string): BrowserNavigateResult {
|
||||
const trimmed = input.trim()
|
||||
if (trimmed === '') return { kind: 'invalid' }
|
||||
// Distinguish an explicit scheme from a bare host:port. "example.com:8080"
|
||||
// would match a naive scheme regex (dots are legal in schemes), so a
|
||||
// scheme prefix is only honored when it is http(s) or a known-forbidden
|
||||
// scheme; anything else is treated as a host and gets https://.
|
||||
const schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(trimmed)
|
||||
let withScheme: string
|
||||
if (schemeMatch === null) {
|
||||
withScheme = `https://${trimmed}`
|
||||
} else {
|
||||
const scheme = schemeMatch[1]!.toLowerCase()
|
||||
if (scheme === 'http' || scheme === 'https') withScheme = trimmed
|
||||
else if (FORBIDDEN_SCHEMES.has(scheme)) return { kind: 'blocked', reason: 'scheme' }
|
||||
else withScheme = `https://${trimmed}`
|
||||
}
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(withScheme)
|
||||
} catch {
|
||||
return { kind: 'invalid' }
|
||||
}
|
||||
// The protocol backstop: any URL that still parses to a non-http(s)
|
||||
// scheme (e.g. ftp://, ws:// — which carry `//` and skip the list) is
|
||||
// refused here.
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return { kind: 'blocked', reason: 'scheme' }
|
||||
// The GUI's own origin is ALLOWED (the user may browse the GUI itself in
|
||||
// the sidebar; the sandbox renders it in an opaque origin like any other
|
||||
// site). It must be checked before the loopback gate because its host is
|
||||
// normally loopback.
|
||||
try {
|
||||
if (url.origin === new URL(selfOrigin).origin) return { kind: 'ok', url: url.href }
|
||||
} catch {
|
||||
// Unparsable selfOrigin (never in practice): fall through to the loopback gate.
|
||||
}
|
||||
if (isLoopbackHostname(url.hostname)) return { kind: 'blocked', reason: 'loopback' }
|
||||
return { kind: 'ok', url: url.href }
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* The 6 built-in tab descriptors: the plugin registers its own pages
|
||||
* (explorer / git / terminal / subagent / editor / diff) through the same
|
||||
* {@link BetterSidebarService} external plugins use — eating its own
|
||||
* dogfood. The terminal descriptor owns its quota (`TERMINAL_LIMIT`) and
|
||||
* mints `terminal:<n>` ids through `createTab`.
|
||||
* The 7 built-in tab descriptors: the plugin registers its own pages
|
||||
* (explorer / git / terminal / browser / subagent / editor / diff) through
|
||||
* the same {@link BetterSidebarService} external plugins use — eating its
|
||||
* own dogfood. The terminal descriptor owns its quota (`TERMINAL_LIMIT`)
|
||||
* and mints `terminal:<n>` ids through `createTab`; the browser mints
|
||||
* `browser:<n>` the same way (no quota).
|
||||
*/
|
||||
import { IconBranchOutline16, IconCodeOutline16, IconFolderOpen16, IconThinkOutline16 } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { Context } from '../../context-types.ts'
|
||||
@@ -16,7 +17,8 @@ import { TerminalView } from '../TerminalView.tsx'
|
||||
import { GitView } from '../GitView.tsx'
|
||||
import { DiffTab } from '../DiffTab.tsx'
|
||||
import { SubagentView } from '../SubagentView.tsx'
|
||||
import { IconTerminalOutline16, IconDiffOutline16 } from '../icons.tsx'
|
||||
import { BrowserView } from '../BrowserView.tsx'
|
||||
import { IconTerminalOutline16, IconDiffOutline16, IconGlobeOutline16 } from '../icons.tsx'
|
||||
import type { TabDescriptor } from '../service.ts'
|
||||
|
||||
/** How many UI-owned terminals may be open at once (agent-owned ones are uncapped). */
|
||||
@@ -29,7 +31,7 @@ function uiTerminalCount(state: SidebarState): number {
|
||||
.filter(tab => tab.type === 'terminal' && !isAgentTabId(tab.id)).length
|
||||
}
|
||||
|
||||
/** The 6 built-in tab descriptors. */
|
||||
/** The 7 built-in tab descriptors. */
|
||||
export function builtinTabs(ctx: Context): readonly TabDescriptor[] {
|
||||
return [
|
||||
{
|
||||
@@ -130,6 +132,35 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] {
|
||||
<TerminalView scope={scope} tabId={tab.id} store={store} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'browser',
|
||||
title: () => t('browser'),
|
||||
icon: (size: number) => <IconGlobeOutline16 size={size} />,
|
||||
order: 50,
|
||||
// Declarative settings: the sandbox escape hatch and the link
|
||||
// takeover render under this tab's row in the Side card settings
|
||||
// page (the sandbox one is warned on).
|
||||
settings: {
|
||||
toggles: [{
|
||||
key: 'browserNoSandbox',
|
||||
title: () => t('settingsBrowserSandboxTitle'),
|
||||
desc: () => t('settingsBrowserSandboxDesc'),
|
||||
}, {
|
||||
key: 'browserInterceptLinks',
|
||||
title: () => t('settingsBrowserLinksTitle'),
|
||||
desc: () => t('settingsBrowserLinksDesc'),
|
||||
}],
|
||||
},
|
||||
createTab: (state) => ({
|
||||
tab: {
|
||||
id: `browser:${state.nextBrowser}`,
|
||||
type: 'browser',
|
||||
title: t('browser'),
|
||||
},
|
||||
patch: { nextBrowser: state.nextBrowser + 1 },
|
||||
}),
|
||||
component: (props) => <BrowserView {...props} />,
|
||||
},
|
||||
{
|
||||
id: 'diff',
|
||||
title: () => t('git'),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* The 8 built-in file viewer descriptors: every preview surface is a
|
||||
* registered viewer (image / pdf / docx / xlsx / pptx / markdown / code /
|
||||
* binary-download), exactly like external plugins register theirs. The
|
||||
* `binary-download` viewer sniffs NUL bytes via `detect` for unknown
|
||||
* The 9 built-in file viewer descriptors: every preview surface is a
|
||||
* registered viewer (image / pdf / docx / xlsx / pptx / markdown / html /
|
||||
* code / binary-download), exactly like external plugins register theirs.
|
||||
* The `binary-download` viewer sniffs NUL bytes via `detect` for unknown
|
||||
* binaries and serves doc/xls/ppt by extension; `code` is the catch-all
|
||||
* (`exts: []`, lowest priority) that claims any file no other viewer did.
|
||||
*
|
||||
@@ -23,12 +23,13 @@ import {
|
||||
IconDocxOutline16,
|
||||
IconXlsxOutline16,
|
||||
IconPptxOutline16,
|
||||
IconHtmlOutline16,
|
||||
} from '../icons.tsx'
|
||||
import type { FileViewerDescriptor } from '../service.ts'
|
||||
import { t } from '../locales.ts'
|
||||
import css from '../sidebar.module.css'
|
||||
|
||||
/** The 8 built-in file viewer descriptors. */
|
||||
/** The 9 built-in file viewer descriptors. */
|
||||
export function builtinViewers(): readonly FileViewerDescriptor[] {
|
||||
return [
|
||||
{
|
||||
@@ -91,6 +92,28 @@ export function builtinViewers(): readonly FileViewerDescriptor[] {
|
||||
fetchStrategy: 'fsRead',
|
||||
component: (props) => <TextEditor {...props} />,
|
||||
},
|
||||
{
|
||||
id: 'html',
|
||||
title: () => t('viewerHtml'),
|
||||
icon: (size: number) => <IconHtmlOutline16 size={size} />,
|
||||
exts: ['html', 'htm'],
|
||||
fetchStrategy: 'fsRead',
|
||||
// Declarative settings: the sandbox escape hatch and the default-unsafe
|
||||
// start state render under this viewer's row in the Side card settings
|
||||
// page (both warned on).
|
||||
settings: {
|
||||
toggles: [{
|
||||
key: 'htmlViewerNoSandbox',
|
||||
title: () => t('settingsHtmlSandboxTitle'),
|
||||
desc: () => t('settingsHtmlSandboxDesc'),
|
||||
}, {
|
||||
key: 'htmlViewerDefaultUnsafe',
|
||||
title: () => t('settingsHtmlDefaultUnsafeTitle'),
|
||||
desc: () => t('settingsHtmlDefaultUnsafeDesc'),
|
||||
}],
|
||||
},
|
||||
component: (props) => <TextEditor {...props} />,
|
||||
},
|
||||
{
|
||||
id: 'code',
|
||||
title: () => t('viewerCode'),
|
||||
|
||||
@@ -83,3 +83,21 @@ export const IconMarkdownOutline16 = ({ size = 16, className }: IconProps) => (
|
||||
<path d="M4 10.5V5.5l2 2.5 2-2.5v5M9.5 10.5v-5l2 2.5 2-2.5v5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
/** HTML viewer glyph: a document frame with a "‹/›" tag pair. */
|
||||
export const IconHtmlOutline16 = ({ size = 16, className }: IconProps) => (
|
||||
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3.5 1.5h6.5L13.5 5v9.5h-10z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M9.5 1.5V5h4" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M5.6 13.2 4.2 10l1.4-3.2M7.4 6.8 8.8 10l-1.4 3.2" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
/** Browser tab glyph: a globe with meridians. */
|
||||
export const IconGlobeOutline16 = ({ size = 16, className }: IconProps) => (
|
||||
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="8" cy="8" r="6.5" stroke="currentColor" strokeWidth="1.5" />
|
||||
<ellipse cx="8" cy="8" rx="2.8" ry="6.5" stroke="currentColor" strokeWidth="1.5" />
|
||||
<path d="M1.5 8h13M8 1.5c-2.4 1.8-2.4 11.2 0 13M8 1.5c2.4 1.8 2.4 11.2 0 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
@@ -16,6 +16,7 @@ import { createBetterSidebarService } from './service.ts'
|
||||
import { registerBuiltins } from './builtins/index.ts'
|
||||
import { Sidebar } from './Sidebar.tsx'
|
||||
import { registerOpenPathInterception, registerTurnTailInterception } from './intercept.tsx'
|
||||
import { registerLinkInterception } from './link-intercept.ts'
|
||||
import { loadPrefs } from './prefs.ts'
|
||||
import { SideCardSection } from './SideCardSection.tsx'
|
||||
import { api } from './api.ts'
|
||||
@@ -158,6 +159,30 @@ export function apply(ctx: Context): void {
|
||||
'dsh-better-sidebar: open-path interception',
|
||||
)
|
||||
|
||||
ctx.effect(
|
||||
() => {
|
||||
try {
|
||||
// External http(s) links in the chat/GUI open the sidebar browser
|
||||
// instead of a new window (gated on the browserInterceptLinks pref
|
||||
// AND the browser tab's enable switch; Ctrl/Cmd+click bypasses).
|
||||
return registerLinkInterception({
|
||||
takeoverEnabled: () => sidebarStore.getPrefs().browserInterceptLinks !== false
|
||||
&& sidebarStore.getPrefs().tabsEnabled['browser'] !== false,
|
||||
openInSidebar: (url) => {
|
||||
let title: string | undefined
|
||||
try { title = new URL(url).hostname } catch { /* keep the default title */ }
|
||||
ctx.betterSidebar?.openTab({ type: 'browser', url, title })
|
||||
},
|
||||
selfOrigin: window.location.origin,
|
||||
})
|
||||
} catch (error) {
|
||||
fail('interception', error)
|
||||
return undefined
|
||||
}
|
||||
},
|
||||
'dsh-better-sidebar: link interception',
|
||||
)
|
||||
|
||||
// The "Side card" settings section: appears in the DSH Settings shell
|
||||
// once the shell's declaration is on the ledger (slots.inject waits for
|
||||
// it); the section reads/writes the prefs through the plugin's own
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Chat/GUI external-link interception: clicking an http(s) link that points
|
||||
* OUTSIDE the GUI (chat messages, tool rows, prose mentions) opens the
|
||||
* sidebar browser instead of a new browser tab. Gated by BOTH the
|
||||
* `browserInterceptLinks` pref and the browser tab's enable switch; a
|
||||
* Ctrl/Cmd/Shift/Alt-modified click always bypasses the takeover so the
|
||||
* user can still force a real browser tab.
|
||||
*
|
||||
* Only the GUI's OWN document is watched — links inside the browser tab's
|
||||
* sandboxed iframe live in another document and never bubble here (and
|
||||
* their clicks must keep working inside the sidebar).
|
||||
*/
|
||||
|
||||
/** The pure decision: the URL to open in the sidebar, or null to let the
|
||||
* click fall through. Extracted so the policy is unit-testable without a
|
||||
* DOM. `anchorHref` must be the ABSOLUTE href (`<a>.href` already is). */
|
||||
export function shouldInterceptLink(anchorHref: string, selfOrigin: string): string | null {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(anchorHref)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
|
||||
// Same-origin links are GUI-internal navigation (settings pages, tool
|
||||
// docs) — never routed into the sidebar browser.
|
||||
try {
|
||||
if (url.origin === new URL(selfOrigin).origin) return null
|
||||
} catch {
|
||||
// Unparsable selfOrigin (never in practice): intercept defensively.
|
||||
}
|
||||
return url.href
|
||||
}
|
||||
|
||||
/** Whether a left-click may be taken over (unmodified left click only). */
|
||||
export function isPlainLeftClick(event: { button: number; metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean }): boolean {
|
||||
return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the document-level click capture that funnels external links
|
||||
* into the sidebar browser. Returns the disposer (HMR-safe).
|
||||
*/
|
||||
export function registerLinkInterception(opts: {
|
||||
takeoverEnabled: () => boolean
|
||||
/** Open the sidebar browser tab at `url` (the caller resolves the session). */
|
||||
openInSidebar: (url: string) => void
|
||||
/** The GUI's own origin (window.location.origin at registration). */
|
||||
selfOrigin: string
|
||||
}): () => void {
|
||||
const onClick = (event: MouseEvent): void => {
|
||||
if (!isPlainLeftClick(event)) return
|
||||
if (event.defaultPrevented) return
|
||||
if (!opts.takeoverEnabled()) return
|
||||
const target = event.target
|
||||
if (target === null || typeof (target as Element).closest !== 'function') return
|
||||
const anchor = (target as Element).closest('a[href]') as HTMLAnchorElement | null
|
||||
if (anchor === null) return
|
||||
const url = shouldInterceptLink(anchor.href, opts.selfOrigin)
|
||||
if (url === null) return
|
||||
event.preventDefault()
|
||||
opts.openInSidebar(url)
|
||||
}
|
||||
document.addEventListener('click', onClick, true)
|
||||
return () => { document.removeEventListener('click', onClick, true) }
|
||||
}
|
||||
@@ -136,6 +136,33 @@ const zh = {
|
||||
viewerMarkdown: 'Markdown',
|
||||
viewerCode: '代码',
|
||||
viewerBinary: '二进制下载',
|
||||
viewerHtml: 'HTML',
|
||||
browser: '浏览器',
|
||||
browserPlaceholder: '输入网址,例如 example.com',
|
||||
browserGo: '前往',
|
||||
browserBack: '后退',
|
||||
browserForward: '前进',
|
||||
browserStart: '输入网址开始浏览(沙箱模式)',
|
||||
browserBlockedScheme: '已阻止:仅支持 http/https 链接',
|
||||
browserBlockedLoopback: '已阻止:不允许在浏览器中访问本机或内部地址',
|
||||
browserInvalid: '无效的网址',
|
||||
browserNoSandboxWarning: '沙箱已关闭:当前页面与界面同源,拥有完整会话权限(可在设置中恢复)',
|
||||
htmlNoSandboxWarning: '沙箱已关闭:此 HTML 与界面同源,可读取会话文件与内部接口(可在设置中恢复)',
|
||||
sandboxStatusOn: '沙箱模式:已启用 · 页面无法访问界面数据与本地文件,登录态与第三方 Cookie 可能不可用',
|
||||
sandboxUnlock: '临时解锁(不安全)',
|
||||
sandboxRestore: '恢复沙箱',
|
||||
settingsHtmlDefaultUnsafeTitle: 'HTML 预览默认以非沙箱模式打开(不安全)',
|
||||
settingsHtmlDefaultUnsafeDesc: '开启后,每次打开 HTML 文件时预览默认处于非沙箱状态(与界面同源,可读取会话文件与内部接口);可在状态行临时恢复沙箱',
|
||||
settingsHtmlSandboxTitle: '关闭 HTML 预览沙箱(不安全)',
|
||||
settingsHtmlSandboxDesc: '关闭后,预览的 HTML 将与界面同源运行,可读取会话文件、本地存储并调用内部接口。仅对完全可信的文件开启',
|
||||
settingsBrowserSandboxTitle: '关闭浏览器沙箱(不安全)',
|
||||
settingsBrowserSandboxDesc: '关闭后,访问的任何网站都将与界面同源运行,可读取会话数据并冒充你的登录状态。仅对完全可信的站点开启',
|
||||
settingsBrowserLinksTitle: '聊天区外链在侧边栏打开',
|
||||
settingsBrowserLinksDesc: '开启后,点击聊天或界面中的 http/https 外链时在侧边栏浏览器中打开,不再弹出新窗口;Ctrl/Cmd 点击可临时放行',
|
||||
browserOpenExternal: '在浏览器中打开',
|
||||
browserEmbedBlocked: '{host} 拒绝了嵌入请求',
|
||||
browserEmbedBlockedDesc: '该站点通过 X-Frame-Options / frame-ancestors 禁止在其它页面中显示,无法在侧边栏内加载。可在浏览器中直接打开',
|
||||
browserEmbedAnyway: '仍然加载',
|
||||
subagent: '子代理',
|
||||
openSubagent: '子代理',
|
||||
subagentMainAgent: '主代理',
|
||||
@@ -284,6 +311,33 @@ const en: Record<keyof typeof zh, string> = {
|
||||
viewerMarkdown: 'Markdown',
|
||||
viewerCode: 'Code',
|
||||
viewerBinary: 'Binary download',
|
||||
viewerHtml: 'HTML',
|
||||
browser: 'Browser',
|
||||
browserPlaceholder: 'Enter a URL, e.g. example.com',
|
||||
browserGo: 'Go',
|
||||
browserBack: 'Back',
|
||||
browserForward: 'Forward',
|
||||
browserStart: 'Enter a URL to start browsing (sandbox mode)',
|
||||
browserBlockedScheme: 'Blocked: only http/https URLs are allowed',
|
||||
browserBlockedLoopback: 'Blocked: local and internal addresses cannot be browsed here',
|
||||
browserInvalid: 'Invalid URL',
|
||||
browserNoSandboxWarning: 'Sandbox off: the current page runs with full GUI privileges (re-enable in settings)',
|
||||
htmlNoSandboxWarning: 'Sandbox off: this HTML runs with full GUI privileges (re-enable in settings)',
|
||||
sandboxStatusOn: 'Sandbox mode: on · pages cannot access the GUI\'s data or local files; logins and third-party cookies may not work',
|
||||
sandboxUnlock: 'Temporarily disable (unsafe)',
|
||||
sandboxRestore: 'Restore sandbox',
|
||||
settingsHtmlDefaultUnsafeTitle: 'Open HTML previews unsandboxed by default (unsafe)',
|
||||
settingsHtmlDefaultUnsafeDesc: 'When on, every newly opened HTML preview starts in the unsandboxed state (same origin as the GUI — it can read session files and internal APIs); the status row still offers a one-tap restore',
|
||||
settingsHtmlSandboxTitle: 'Disable HTML preview sandbox (unsafe)',
|
||||
settingsHtmlSandboxDesc: 'With the sandbox off, previewed HTML runs with the same origin as the GUI: it can read session files, local storage and call internal APIs. Only enable for fully trusted files',
|
||||
settingsBrowserSandboxTitle: 'Disable browser sandbox (unsafe)',
|
||||
settingsBrowserSandboxDesc: 'With the sandbox off, any visited site runs with the same origin as the GUI: it can read session data and act as your logged-in session. Only enable for fully trusted sites',
|
||||
settingsBrowserLinksTitle: 'Open chat external links in the sidebar',
|
||||
settingsBrowserLinksDesc: 'When on, clicking an http/https external link in the chat or GUI opens the sidebar browser instead of a new window; Ctrl/Cmd+click always bypasses',
|
||||
browserOpenExternal: 'Open in browser',
|
||||
browserEmbedBlocked: '{host} refused to be embedded',
|
||||
browserEmbedBlockedDesc: 'The site forbids being displayed inside other pages (X-Frame-Options / frame-ancestors), so it cannot load in the sidebar. Open it directly in your browser instead.',
|
||||
browserEmbedAnyway: 'Load anyway',
|
||||
subagent: 'Subagents',
|
||||
openSubagent: 'Subagents',
|
||||
subagentMainAgent: 'Main agent',
|
||||
|
||||
@@ -46,6 +46,18 @@ export function parsePrefs(value: unknown): SidebarPrefs {
|
||||
interceptOpenPath: typeof record.interceptOpenPath === 'boolean'
|
||||
? record.interceptOpenPath
|
||||
: SIDEBAR_PREFS_DEFAULTS.interceptOpenPath,
|
||||
htmlViewerNoSandbox: typeof record.htmlViewerNoSandbox === 'boolean'
|
||||
? record.htmlViewerNoSandbox
|
||||
: SIDEBAR_PREFS_DEFAULTS.htmlViewerNoSandbox,
|
||||
htmlViewerDefaultUnsafe: typeof record.htmlViewerDefaultUnsafe === 'boolean'
|
||||
? record.htmlViewerDefaultUnsafe
|
||||
: SIDEBAR_PREFS_DEFAULTS.htmlViewerDefaultUnsafe,
|
||||
browserNoSandbox: typeof record.browserNoSandbox === 'boolean'
|
||||
? record.browserNoSandbox
|
||||
: SIDEBAR_PREFS_DEFAULTS.browserNoSandbox,
|
||||
browserInterceptLinks: typeof record.browserInterceptLinks === 'boolean'
|
||||
? record.browserInterceptLinks
|
||||
: SIDEBAR_PREFS_DEFAULTS.browserInterceptLinks,
|
||||
tabsEnabled: booleanMapOf(record.tabsEnabled),
|
||||
viewersEnabled: booleanMapOf(record.viewersEnabled),
|
||||
}
|
||||
|
||||
+26
-9
@@ -22,7 +22,7 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { Context } from '../context-types.ts'
|
||||
import {
|
||||
activateTab, allLeaves, closeTab as closeTabReducer, openTabInActivePane,
|
||||
activateTab, allLeaves, closeTab as closeTabReducer, openTabInActivePane, patchTab,
|
||||
type SidebarState, type SidebarStore, type SidebarTab,
|
||||
} from './state.ts'
|
||||
import type { SessionScope } from './api.ts'
|
||||
@@ -194,9 +194,12 @@ export interface BetterSidebarService {
|
||||
* Open a tab (used by external tabs and the + menu). `title` overrides
|
||||
* the descriptor's title when given (the editor tab shows the file name);
|
||||
* when the descriptor provides `createTab` it mints the tab itself and
|
||||
* `title`/`path`/`id` are ignored. A disabled tab type is a no-op.
|
||||
* `title`/`path`/`id` are ignored. `url` lands the tab with its `path`
|
||||
* pre-set to the URL (the browser tab's navigation seed; the caller
|
||||
* usually pairs it with a hostname `title`). A disabled tab type is a
|
||||
* no-op.
|
||||
*/
|
||||
openTab(seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string }): void
|
||||
openTab(seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string; url?: string }): void
|
||||
/** Close a tab by id. */
|
||||
closeTab(tabId: string): void
|
||||
/** Subscribe to registry changes (register/dispose). */
|
||||
@@ -297,7 +300,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
return undefined
|
||||
}
|
||||
|
||||
const openTab = (seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string }): void => {
|
||||
const openTab = (seed: { type: string; title?: string; path?: string; diff?: SidebarTab['diff']; id?: string; url?: string }): void => {
|
||||
// A type the user disabled in settings never opens — neither from the
|
||||
// + menu nor from derived flows (file opens, subagent auto-open,
|
||||
// external plugins). Already-open tabs keep rendering.
|
||||
@@ -309,13 +312,16 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
const descriptor = tabs.get(seed.type)
|
||||
if (descriptor === undefined) return state
|
||||
// Let the descriptor mint the tab (terminal's nextTerminal bump, etc.).
|
||||
let tab: SidebarTab
|
||||
let next: SidebarState
|
||||
if (descriptor.createTab !== undefined) {
|
||||
const result = descriptor.createTab(state)
|
||||
if (result === null) return state
|
||||
const next = applyDedupe(state, result.tab, descriptor)
|
||||
return result.patch !== undefined ? { ...next, ...result.patch } : next
|
||||
}
|
||||
const tab: SidebarTab = {
|
||||
tab = result.tab
|
||||
next = applyDedupe(state, result.tab, descriptor)
|
||||
if (result.patch !== undefined) next = { ...next, ...result.patch }
|
||||
} else {
|
||||
tab = {
|
||||
id: seed.id ?? seed.type,
|
||||
type: seed.type,
|
||||
// A caller-provided title wins (the editor shows the file name);
|
||||
@@ -324,7 +330,18 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
...(seed.path !== undefined ? { path: seed.path } : {}),
|
||||
...(seed.diff !== undefined ? { diff: seed.diff } : {}),
|
||||
}
|
||||
return applyDedupe(state, tab, descriptor)
|
||||
next = applyDedupe(state, tab, descriptor)
|
||||
}
|
||||
// A URL seed pre-fills the tab's path (the browser tab navigates to it
|
||||
// on mount). An explicit seed.title also wins over a createTab-minted
|
||||
// default title (e.g. the sidebar-browser's hostname title).
|
||||
if (seed.url !== undefined) {
|
||||
return patchTab(next, tab.id, {
|
||||
path: seed.url,
|
||||
...(seed.title !== undefined ? { title: seed.title } : {}),
|
||||
})
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -703,6 +703,186 @@
|
||||
background: var(--dsw-alias-state-warn-tertiary);
|
||||
}
|
||||
|
||||
/* Live sandbox status row (HTML preview / browser tab): GREEN while the
|
||||
sandbox is on (with the one-tap temporary unlock), RED while it is off
|
||||
(global setting or temporary unlock) — the red state is the persistent
|
||||
warning that the page runs on the GUI's own origin. */
|
||||
.sandboxStatus {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 10px;
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
}
|
||||
|
||||
.sandboxStatusOn {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||
}
|
||||
|
||||
.sandboxStatusOff {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent);
|
||||
}
|
||||
|
||||
.sandboxDot {
|
||||
flex: none;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--dsw-alias-state-success-primary);
|
||||
}
|
||||
|
||||
.sandboxStatusOff .sandboxDot {
|
||||
background: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.sandboxStatusText {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sandboxAction {
|
||||
flex: none;
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sandboxAction:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
/* The HTML preview iframe: fills the editor body. Route-src (never srcdoc)
|
||||
so the frame is cross-origin by construction even if the sandbox
|
||||
attribute is ever dropped; sandboxed by default (see TextEditor). */
|
||||
.editorHtml {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: none;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
/* ── Browser tab ──────────────────────────────────────────────────────── */
|
||||
|
||||
.browser {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.browserBar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||
}
|
||||
|
||||
.browserInput {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
border-radius: 6px;
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font: var(--dsw-font-xxs-12);
|
||||
}
|
||||
|
||||
.browserInput:focus {
|
||||
outline: none;
|
||||
border-color: var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
.browserMessage {
|
||||
flex: none;
|
||||
padding: 4px 12px;
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
color: var(--dsw-alias-state-warn-label);
|
||||
background: var(--dsw-alias-state-warn-tertiary);
|
||||
}
|
||||
|
||||
.browserFrame {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: none;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
.browserStart {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
font: var(--dsw-font-xs-13);
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* Embed-refusal panel (X-Frame-Options / frame-ancestors): replaces the
|
||||
blank refused iframe with the reason + open-in-browser actions. */
|
||||
.browserBlocked {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
color: var(--dsw-alias-state-warn-primary);
|
||||
}
|
||||
|
||||
.browserBlockedTitle {
|
||||
font: var(--dsw-font-xxs-strong-12);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.browserBlockedDesc {
|
||||
max-width: 280px;
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.browserBlockedActions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.browserBlockedButton {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 6px;
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.browserBlockedButton:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.editorCm {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface SidebarState {
|
||||
activePane: string | null
|
||||
/** Monotonic terminal tab counter (ids survive reloads). */
|
||||
nextTerminal: number
|
||||
/** Monotonic browser tab counter (ids survive reloads; mirrors nextTerminal). */
|
||||
nextBrowser: number
|
||||
/** Explorer expansion set (absolute directory paths). */
|
||||
expanded: string[]
|
||||
splits: SplitNode
|
||||
@@ -129,6 +131,7 @@ export function makeDefaultState(width = PANEL_DEFAULT, panelOpen = true, seedEx
|
||||
width,
|
||||
activePane: leaf.id,
|
||||
nextTerminal: 1,
|
||||
nextBrowser: 1,
|
||||
expanded: [],
|
||||
splits: leaf,
|
||||
}
|
||||
@@ -308,6 +311,36 @@ export function activateTab(state: SidebarState, paneId: string, tabId: string):
|
||||
}
|
||||
}
|
||||
|
||||
/** Update the display fields of one open tab (title / path) without
|
||||
* re-opening it. The browser tab persists its current URL and hostname
|
||||
* title through this reducer so a reload restores the visited page. A
|
||||
* missing tab id is a no-op. */
|
||||
export function patchTab(
|
||||
state: SidebarState,
|
||||
tabId: string,
|
||||
patch: { title?: string; path?: string },
|
||||
): SidebarState {
|
||||
let changed = false
|
||||
const walk = (node: SplitNode): SplitNode => {
|
||||
if (node.kind === 'leaf') {
|
||||
const tabs = node.tabs.map(tab => {
|
||||
if (tab.id !== tabId) return tab
|
||||
changed = true
|
||||
return {
|
||||
...tab,
|
||||
...(patch.title !== undefined ? { title: patch.title } : {}),
|
||||
...(patch.path !== undefined ? { path: patch.path } : {}),
|
||||
}
|
||||
})
|
||||
return tabs === node.tabs ? node : { ...node, tabs }
|
||||
}
|
||||
const children = node.children.map(walk)
|
||||
return children === node.children ? node : { ...node, children }
|
||||
}
|
||||
const splits = walk(state.splits)
|
||||
return changed ? { ...state, splits } : state
|
||||
}
|
||||
|
||||
/**
|
||||
* Land a tab in the active pane (or focus its existing instance by id).
|
||||
* Dedup strategies (single-instance, per-path, per-change) are owned by the
|
||||
@@ -572,6 +605,12 @@ export function sanitizeState(parsed: unknown): SidebarState | undefined {
|
||||
if (typeof record.nextTerminal !== 'number' || !Number.isInteger(record.nextTerminal) || record.nextTerminal < 1) {
|
||||
return undefined
|
||||
}
|
||||
// nextBrowser arrived in a later build; a missing or malformed value on an
|
||||
// OLDER persisted state defaults to 1 so existing layouts keep loading
|
||||
// (unlike nextTerminal, which is strict — it predates the v1 shape).
|
||||
const nextBrowser = typeof record.nextBrowser === 'number' && Number.isInteger(record.nextBrowser) && record.nextBrowser >= 1
|
||||
? record.nextBrowser
|
||||
: 1
|
||||
if (typeof record.activePane !== 'string' && record.activePane !== null) return undefined
|
||||
if (!Array.isArray(record.expanded) || record.expanded.some(item => typeof item !== 'string')) return undefined
|
||||
const reid = new Map<string, string>()
|
||||
@@ -585,6 +624,7 @@ export function sanitizeState(parsed: unknown): SidebarState | undefined {
|
||||
// new tabs still land in the pane the user was using.
|
||||
activePane: typeof record.activePane === 'string' ? (reid.get(record.activePane) ?? record.activePane) : null,
|
||||
nextTerminal: record.nextTerminal,
|
||||
nextBrowser,
|
||||
expanded: record.expanded as string[],
|
||||
splits,
|
||||
}
|
||||
|
||||
@@ -81,6 +81,10 @@ export const PrefsSchema: z<SidebarPrefs> = z.object({
|
||||
autoOpenSubagent: z.boolean().default(true),
|
||||
agentTerminalTools: z.boolean().default(false),
|
||||
interceptOpenPath: z.boolean().default(true),
|
||||
htmlViewerNoSandbox: z.boolean().default(false),
|
||||
htmlViewerDefaultUnsafe: z.boolean().default(false),
|
||||
browserNoSandbox: z.boolean().default(false),
|
||||
browserInterceptLinks: z.boolean().default(true),
|
||||
// Per-feature enable switches are OPEN maps (any tab/viewer id, built-in or
|
||||
// external): an absent key means enabled, so old documents resolve to {}
|
||||
// (everything on) with no migration. Non-boolean values fail validation.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Pure URL vocabulary of the /sidebar/html route (HTML previewer).
|
||||
*
|
||||
* Why path-encoded parameters instead of a query string: the previewed
|
||||
* page resolves its relative assets (./style.css, img/x.png) against the
|
||||
* document URL, and the WHATWG URL algorithm DROPS the query of a
|
||||
* path-relative reference — `/sidebar/html?a=1&path=/a/b/` + `./style.css`
|
||||
* would lose the session scope and the route would reject the asset.
|
||||
* Encoding everything into the URL path keeps relative resolution inside
|
||||
* the same route with every request self-contained:
|
||||
*
|
||||
* /sidebar/html/<sessionId>/<absolute-path segments, encodeURIComponent'd>
|
||||
* /sidebar/html/S/Users/me/proj/index.html
|
||||
* + ./style.css → /sidebar/html/S/Users/me/proj/style.css
|
||||
* Windows: C:\Users\me\a.html → /sidebar/html/S/C%3A/Users/me/a.html
|
||||
*
|
||||
* This module is intentionally dependency-free (no node imports, no wire
|
||||
* helpers) so the client bundle can import `encodeHtmlUrl` without tripping
|
||||
* the build-time purity gate; the host converts decode failures into
|
||||
* SidebarError responses at the route boundary.
|
||||
*/
|
||||
|
||||
/** One decoded route reference. */
|
||||
export interface HtmlRouteRef {
|
||||
sessionId: string
|
||||
/** Absolute file path (leading slash; Windows drives keep their colon). */
|
||||
path: string
|
||||
}
|
||||
|
||||
/** Decode outcome: the reference, or a client-error description. */
|
||||
export type HtmlDecodeResult =
|
||||
| { ok: true; ref: HtmlRouteRef }
|
||||
| { ok: false; status: 400 | 404; message: string }
|
||||
|
||||
/** The route prefix both encoders/decoders agree on. */
|
||||
export const HTML_ROUTE_PREFIX = '/sidebar/html/'
|
||||
|
||||
/** Build the route URL for one absolute file path (client + tests). */
|
||||
export function encodeHtmlUrl(sessionId: string, path: string): string {
|
||||
const segments = path.split(/[\\/]+/).filter(segment => segment !== '')
|
||||
return `${HTML_ROUTE_PREFIX}${encodeURIComponent(sessionId)}/${segments.map(encodeURIComponent).join('/')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a route pathname into the session + absolute file path. Rejects
|
||||
* a wrong prefix (404), an empty or double-slash path, malformed percent
|
||||
* encoding, and a missing sessionId or file path (400). The caller still
|
||||
* must bound the decoded path with requireAbsolute + isWithin(cwd) — a
|
||||
* decoded `..` segment resolves outside the cwd and is refused there.
|
||||
*/
|
||||
export function decodeHtmlUrl(pathname: string): HtmlDecodeResult {
|
||||
if (!pathname.startsWith(HTML_ROUTE_PREFIX)) {
|
||||
return { ok: false, status: 404, message: 'not an html route' }
|
||||
}
|
||||
const rest = pathname.slice(HTML_ROUTE_PREFIX.length)
|
||||
if (rest === '' || rest.includes('//')) {
|
||||
return { ok: false, status: 400, message: 'invalid html route path' }
|
||||
}
|
||||
let segments: string[]
|
||||
try {
|
||||
segments = rest.split('/').map(segment => decodeURIComponent(segment))
|
||||
} catch {
|
||||
return { ok: false, status: 400, message: 'malformed URL encoding' }
|
||||
}
|
||||
const [sessionId, ...pathSegments] = segments
|
||||
if (sessionId === undefined || sessionId === '' || pathSegments.length === 0 || pathSegments.some(segment => segment === '')) {
|
||||
return { ok: false, status: 400, message: 'sessionId and file path are required' }
|
||||
}
|
||||
return { ok: true, ref: { sessionId, path: `/${pathSegments.join('/')}` } }
|
||||
}
|
||||
+118
-1
@@ -26,7 +26,9 @@ import {
|
||||
type SidebarPrefs,
|
||||
} from './config.ts'
|
||||
import { isWithin, parentOf, requireAbsolute, listDirectory, rootLabel } from './fs-tree.ts'
|
||||
import { isTrustedApiRequest } from './trust-fence.ts'
|
||||
import { decodeHtmlUrl } from './html-route.ts'
|
||||
import { extractFrameAncestors } from './browser-probe.ts'
|
||||
import { isTrustedApiRequest, isLoopbackHostname } from './trust-fence.ts'
|
||||
import * as git from './git.ts'
|
||||
import { SettingsConflictError, settingsNamespace, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
|
||||
import { defaultShell, ensureSpawnHelper, PtyManager } from './pty-manager.ts'
|
||||
@@ -68,6 +70,8 @@ const MEDIA_TYPES: Record<string, string> = {
|
||||
'.ico': 'image/x-icon',
|
||||
'.avif': 'image/avif',
|
||||
'.pdf': 'application/pdf',
|
||||
'.html': 'text/html',
|
||||
'.htm': 'text/html',
|
||||
}
|
||||
|
||||
/** Content type served by /sidebar/file (binary-safe fallback for unknowns). */
|
||||
@@ -350,6 +354,55 @@ function buildApi(
|
||||
throw new SidebarError('settings-rejected', error instanceof Error ? error.message : String(error), 400)
|
||||
}
|
||||
},
|
||||
// Probe a URL's RESPONSE HEADERS so the sidebar browser can explain an
|
||||
// iframe refusal: X-Frame-Options / CSP frame-ancestors are exactly the
|
||||
// signals the browser enforces when it refuses to embed a site. The
|
||||
// probe is display-only (headers back to the caller), restricted to
|
||||
// http(s) non-loopback URLs with a hard timeout, and gated by the same
|
||||
// trust fence as every other route — a cross-site page cannot reach it.
|
||||
'browser.probe': async (payload) => {
|
||||
const raw = requireString(payload, 'url')
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(raw)
|
||||
} catch {
|
||||
throw new SidebarError('bad-request', 'invalid url', 400)
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new SidebarError('bad-request', 'only http/https urls can be probed', 400)
|
||||
}
|
||||
// Mirror the browser tab's address-bar policy: loopback stays unreachable
|
||||
// from the sidebar, so probing it would leak nothing the tab could use.
|
||||
if (isLoopbackHostname(parsed.hostname)) {
|
||||
throw new SidebarError('bad-request', 'local addresses are not probed', 400)
|
||||
}
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), 8000)
|
||||
try {
|
||||
let response = await fetch(parsed, { method: 'HEAD', redirect: 'follow', signal: controller.signal })
|
||||
// Some servers answer HEAD with 405/501; retry once as GET (the
|
||||
// body is discarded — only the headers matter).
|
||||
if (response.status === 405 || response.status === 501) {
|
||||
response = await fetch(parsed, { method: 'GET', redirect: 'follow', signal: controller.signal })
|
||||
}
|
||||
const csp = response.headers.get('content-security-policy')
|
||||
const frameAncestors = extractFrameAncestors(csp)
|
||||
const xFrameOptions = response.headers.get('x-frame-options')
|
||||
return {
|
||||
reachable: true,
|
||||
url: response.url,
|
||||
status: response.status,
|
||||
...(xFrameOptions !== null ? { xFrameOptions } : {}),
|
||||
...(frameAncestors !== undefined ? { frameAncestors } : {}),
|
||||
}
|
||||
} catch {
|
||||
// DNS / TLS / connection / timeout: nothing to judge — the client
|
||||
// keeps the plain iframe.
|
||||
return { reachable: false }
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,6 +566,70 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
|
||||
},
|
||||
}), 'dsh-better-sidebar: /sidebar/file media route')
|
||||
|
||||
// ── HTML preview route (sandboxed HTML + its relative assets) ───────────
|
||||
// Serves files under the session cwd for the built-in HTML previewer. The
|
||||
// URL is path-encoded (see html-route.ts) so the previewed page's relative
|
||||
// assets (./style.css, img/x.png) resolve back into this route with the
|
||||
// session scope intact — a query-encoded URL would drop the scope when the
|
||||
// browser resolves relatives. Every response carries the CSP `sandbox`
|
||||
// directive: inside the editor's iframe the sandbox ATTRIBUTE is the
|
||||
// boundary, this header is defense-in-depth so even a top-level load of
|
||||
// the URL (e.g. a popup opened by a previewed page) stays in an opaque
|
||||
// origin with no same-origin access to the GUI.
|
||||
ctx.effect(() => ctx.httpServer.register({
|
||||
kind: 'prefix',
|
||||
path: '/sidebar/html',
|
||||
handler: async (req, res) => {
|
||||
if (!fence(req)) {
|
||||
res.writeHead(403)
|
||||
res.end('forbidden')
|
||||
return
|
||||
}
|
||||
if (req.method !== 'GET') {
|
||||
res.writeHead(405)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
try {
|
||||
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
||||
const decoded = decodeHtmlUrl(url.pathname)
|
||||
if (!decoded.ok) {
|
||||
writeError(res, new SidebarError('bad-request', decoded.message, decoded.status))
|
||||
return
|
||||
}
|
||||
const { sessionId, path } = decoded.ref
|
||||
// The session's authoritative cwd (client cwd cannot ride in the URL
|
||||
// — the path encoding has no query; a detached first request falls
|
||||
// back to the process cwd and is normally refused by isWithin, same
|
||||
// semantics as the media route's fallback).
|
||||
const cwd = sessionCwdOf(ctx, sessionId)
|
||||
const absolute = requireAbsolute(path)
|
||||
if (!isWithin(cwd, absolute)) {
|
||||
throw new SidebarError('fs-error', 'html path outside the session working directory', 403)
|
||||
}
|
||||
const info = await stat(absolute)
|
||||
if (!info.isFile() || info.size > resolved.mediaLimit) {
|
||||
throw new SidebarError('fs-error', 'not a file or too large', 400)
|
||||
}
|
||||
const type = mediaTypeForPath(absolute)
|
||||
const body = await readFile(absolute)
|
||||
res.writeHead(200, {
|
||||
'content-type': type,
|
||||
'cache-control': 'no-cache',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'referrer-policy': 'no-referrer',
|
||||
// The sandbox directive (no allow-same-origin → opaque origin) is
|
||||
// the previewer's security boundary even for top-level loads;
|
||||
// object-src 'none' blocks plugin embeds.
|
||||
'content-security-policy': "sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'",
|
||||
})
|
||||
res.end(body)
|
||||
} catch (error) {
|
||||
writeError(res, error)
|
||||
}
|
||||
},
|
||||
}), 'dsh-better-sidebar: /sidebar/html preview route')
|
||||
|
||||
// ── Terminal WebSocket ──────────────────────────────────────────────────
|
||||
// One upgrade endpoint serves both UI-tab terminals (?tab=...) and
|
||||
// agent-owned terminals (?uuid=...). The two paths attach to different
|
||||
|
||||
@@ -35,6 +35,38 @@ export interface SidebarPrefs {
|
||||
* own enable switch gates it too (both must be on for the takeover).
|
||||
*/
|
||||
interceptOpenPath: boolean
|
||||
/**
|
||||
* Whether the HTML previewer drops its sandboxed iframe. Sandbox ON (the
|
||||
* default) renders previewed HTML in an opaque-origin iframe that cannot
|
||||
* touch the GUI; turning it OFF runs the previewed page with the GUI's
|
||||
* own origin — full read/write access to session files and internal
|
||||
* APIs. Only for trusted local content; the setting copy warns.
|
||||
*/
|
||||
htmlViewerNoSandbox: boolean
|
||||
/**
|
||||
* Whether a newly opened HTML preview starts UNSANDBOXED (the per-surface
|
||||
* temporary unlock pre-applied). Off by default: previews open sandboxed
|
||||
* and the status row offers the one-tap unlock; when on, previews open
|
||||
* in the red unsandboxed state and the status row offers a one-tap
|
||||
* restore for the current file.
|
||||
*/
|
||||
htmlViewerDefaultUnsafe: boolean
|
||||
/**
|
||||
* Whether the browser tab drops its sandboxed iframe. Sandbox ON (the
|
||||
* default) keeps browsed sites in an opaque origin with no GUI access;
|
||||
* turning it OFF runs any visited site with the GUI's own origin — it
|
||||
* can read session data and act as the logged-in GUI. Only for trusted
|
||||
* sites; the setting copy warns.
|
||||
*/
|
||||
browserNoSandbox: boolean
|
||||
/**
|
||||
* Whether clicking an http(s) EXTERNAL link in the GUI (chat messages,
|
||||
* tool rows, prose mentions) opens the sidebar browser instead of a new
|
||||
* browser tab. On by default; gated on the browser tab's own enable
|
||||
* switch (both must be on for the takeover). Ctrl/Cmd+click always
|
||||
* bypasses the takeover.
|
||||
*/
|
||||
browserInterceptLinks: boolean
|
||||
/**
|
||||
* Per-tab enable switches, keyed by tab descriptor id (`'explorer'`,
|
||||
* `'my-plugin:db'`). An ABSENT key means enabled — only an explicit
|
||||
@@ -66,6 +98,10 @@ export const SIDEBAR_PREFS_DEFAULTS: SidebarPrefs = {
|
||||
autoOpenSubagent: true,
|
||||
agentTerminalTools: false,
|
||||
interceptOpenPath: true,
|
||||
htmlViewerNoSandbox: false,
|
||||
htmlViewerDefaultUnsafe: false,
|
||||
browserNoSandbox: false,
|
||||
browserInterceptLinks: true,
|
||||
tabsEnabled: {},
|
||||
viewersEnabled: {},
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ const elementStub = (): Record<string, unknown> => ({
|
||||
classList: { add: () => {}, remove: () => {}, contains: () => false },
|
||||
setAttribute: () => {},
|
||||
getAttribute: () => null,
|
||||
hasAttribute: () => false,
|
||||
appendChild: () => {},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* browser.probe helpers: the CSP frame-ancestors parser (host side) and the
|
||||
* embeddability verdict (client side). Together they turn the target's
|
||||
* response headers into the "refused to be embedded" explanation the
|
||||
* sidebar browser shows instead of the browser's cryptic blank frame.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractFrameAncestors } from '../src/browser-probe.ts'
|
||||
import { embeddabilityOf } from '../src/client/browser.ts'
|
||||
|
||||
describe('extractFrameAncestors', () => {
|
||||
it('extracts a frame-ancestors source list from a CSP header', () => {
|
||||
expect(extractFrameAncestors("default-src 'self'; frame-ancestors 'none'"))
|
||||
.toEqual(["'none'"])
|
||||
expect(extractFrameAncestors("frame-ancestors 'self' https://example.com"))
|
||||
.toEqual(["'self'", 'https://example.com'])
|
||||
expect(extractFrameAncestors('frame-ancestors *')).toEqual(['*'])
|
||||
})
|
||||
|
||||
it('is undefined when the directive is absent or empty', () => {
|
||||
expect(extractFrameAncestors(null)).toBeUndefined()
|
||||
expect(extractFrameAncestors("default-src 'self'")).toBeUndefined()
|
||||
expect(extractFrameAncestors('frame-ancestors')).toBeUndefined()
|
||||
expect(extractFrameAncestors('frame-ancestors ; default-src *')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('embeddabilityOf', () => {
|
||||
it('blocks X-Frame-Options DENY / SAMEORIGIN', () => {
|
||||
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'DENY' })).toBe('blocked')
|
||||
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'SAMEORIGIN' })).toBe('blocked')
|
||||
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'sameorigin' })).toBe('blocked')
|
||||
})
|
||||
|
||||
it('blocks a frame-ancestors list that does not allow * ("self" means the SITE origin, never ours)', () => {
|
||||
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'none'"] })).toBe('blocked')
|
||||
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'self'"] })).toBe('blocked')
|
||||
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'self'", 'https://x.dev'] })).toBe('blocked')
|
||||
})
|
||||
|
||||
it('allows a wildcard frame-ancestors and absent anti-framing headers', () => {
|
||||
expect(embeddabilityOf({ reachable: true, status: 200, frameAncestors: ['*'] })).toBe('embeddable')
|
||||
expect(embeddabilityOf({ reachable: true, status: 200 })).toBe('embeddable')
|
||||
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'ALLOW-FROM https://x' })).toBe('embeddable')
|
||||
})
|
||||
|
||||
it('is unknown when the target is unreachable (plain iframe stays)', () => {
|
||||
expect(embeddabilityOf({ reachable: false })).toBe('unknown')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Browser address-bar policy tests: only http(s) URLs may be navigated,
|
||||
* loopback addresses and the GUI's own origin are refused outright. The
|
||||
* iframe sandbox (opaque origin) is the primary security boundary; this
|
||||
* policy is the address-bar gate on top of it.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isLoopbackHostname, normalizeBrowserUrl } from '../src/client/browser.ts'
|
||||
|
||||
const SELF = 'http://127.0.0.1:3080'
|
||||
|
||||
describe('normalizeBrowserUrl', () => {
|
||||
it('normalizes a bare domain to https', () => {
|
||||
expect(normalizeBrowserUrl('example.com', SELF)).toEqual({ kind: 'ok', url: 'https://example.com/' })
|
||||
})
|
||||
|
||||
it('normalizes a host with a port to https', () => {
|
||||
expect(normalizeBrowserUrl('example.com:8080/path', SELF)).toEqual({ kind: 'ok', url: 'https://example.com:8080/path' })
|
||||
})
|
||||
|
||||
it('keeps an explicit http:// scheme', () => {
|
||||
expect(normalizeBrowserUrl('http://example.com/a?b=1', SELF)).toEqual({ kind: 'ok', url: 'http://example.com/a?b=1' })
|
||||
})
|
||||
|
||||
it('accepts a non-loopback IP literal', () => {
|
||||
expect(normalizeBrowserUrl('https://8.8.8.8/dns', SELF)?.kind).toBe('ok')
|
||||
})
|
||||
|
||||
it('refuses non-http(s) schemes', () => {
|
||||
expect(normalizeBrowserUrl('javascript:alert(1)', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
|
||||
expect(normalizeBrowserUrl('data:text/html,<b>x</b>', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
|
||||
expect(normalizeBrowserUrl('file:///etc/passwd', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
|
||||
expect(normalizeBrowserUrl('about:blank', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
|
||||
})
|
||||
|
||||
it('refuses loopback hostnames in every spelling', () => {
|
||||
for (const input of [
|
||||
'http://localhost/', 'https://localhost:3080/', 'http://LOCALHOST/',
|
||||
'http://127.0.0.1/', 'http://127.255.255.255/',
|
||||
'http://[::1]/', 'http://0.0.0.0/',
|
||||
]) {
|
||||
expect(normalizeBrowserUrl(input, SELF), input).toEqual({ kind: 'blocked', reason: 'loopback' })
|
||||
}
|
||||
})
|
||||
|
||||
it('allows the GUI\'s own origin (the sandbox keeps it opaque like any site)', () => {
|
||||
// The user may browse the GUI itself in the sidebar; its host is
|
||||
// loopback, so the self check must win BEFORE the loopback gate.
|
||||
expect(normalizeBrowserUrl('http://127.0.0.1:3080/sidebar', SELF)).toEqual({
|
||||
kind: 'ok', url: 'http://127.0.0.1:3080/sidebar',
|
||||
})
|
||||
expect(normalizeBrowserUrl('http://127.0.0.1:3080/', SELF)).toEqual({
|
||||
kind: 'ok', url: 'http://127.0.0.1:3080/',
|
||||
})
|
||||
// A different port of the same loopback host is NOT the GUI origin and
|
||||
// stays blocked.
|
||||
expect(normalizeBrowserUrl('http://127.0.0.1:9999/', SELF)).toEqual({ kind: 'blocked', reason: 'loopback' })
|
||||
})
|
||||
|
||||
it('reports invalid input', () => {
|
||||
expect(normalizeBrowserUrl('', SELF)).toEqual({ kind: 'invalid' })
|
||||
expect(normalizeBrowserUrl(' ', SELF)).toEqual({ kind: 'invalid' })
|
||||
expect(normalizeBrowserUrl('ht tp://x', SELF)).toEqual({ kind: 'invalid' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLoopbackHostname', () => {
|
||||
it('flags localhost, IPv6 loopback, and the 127/8 block', () => {
|
||||
expect(isLoopbackHostname('localhost')).toBe(true)
|
||||
expect(isLoopbackHostname('::1')).toBe(true)
|
||||
expect(isLoopbackHostname('[::1]')).toBe(true)
|
||||
expect(isLoopbackHostname('127.0.0.1')).toBe(true)
|
||||
expect(isLoopbackHostname('127.8.9.10')).toBe(true)
|
||||
expect(isLoopbackHostname('0.0.0.0')).toBe(true)
|
||||
expect(isLoopbackHostname('example.com')).toBe(false)
|
||||
expect(isLoopbackHostname('128.0.0.1')).toBe(false)
|
||||
expect(isLoopbackHostname('192.168.1.1')).toBe(false)
|
||||
})
|
||||
})
|
||||
+51
-9
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Built-in registration tests: the plugin registers 6 tabs and 8 file
|
||||
* Built-in registration tests: the plugin registers 7 tabs and 9 file
|
||||
* viewers through the same service external plugins use (dogfooding);
|
||||
* the catch-all `code` viewer and the NUL-sniffing `binary-download`
|
||||
* viewer pin the registry's matching behavior.
|
||||
* the catch-all `code` viewer, the NUL-sniffing `binary-download` viewer,
|
||||
* and the html/browser sandbox settings pin the registry's behavior.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
// First import: browser globals before the xterm-carrying builtin graph loads.
|
||||
@@ -11,20 +11,21 @@ import './browser-globals.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import { createBetterSidebarService } from '../src/client/service.ts'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
import { allLeaves } from '../src/client/state.ts'
|
||||
import { registerBuiltins } from '../src/client/builtins/index.ts'
|
||||
|
||||
function setup(): { service: ReturnType<typeof createBetterSidebarService>; dispose: () => void } {
|
||||
function setup(): { service: ReturnType<typeof createBetterSidebarService>; store: ReturnType<typeof createSidebarStore>; dispose: () => void } {
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
const dispose = registerBuiltins({} as Context, service)
|
||||
return { service, dispose }
|
||||
return { service, store, dispose }
|
||||
}
|
||||
|
||||
describe('built-in tab registrations', () => {
|
||||
it('registers the 6 built-in tabs', () => {
|
||||
it('registers the 7 built-in tabs', () => {
|
||||
const { service } = setup()
|
||||
expect(service.getTabs().map(t => t.id).sort()).toEqual(
|
||||
['diff', 'editor', 'explorer', 'git', 'subagent', 'terminal'],
|
||||
['browser', 'diff', 'editor', 'explorer', 'git', 'subagent', 'terminal'],
|
||||
)
|
||||
})
|
||||
|
||||
@@ -52,6 +53,29 @@ describe('built-in tab registrations', () => {
|
||||
expect(toggles.map(t => t.key)).toEqual(['agentTerminalTools'])
|
||||
})
|
||||
|
||||
it('the browser tab declares its sandbox and link-takeover related settings', () => {
|
||||
const { service } = setup()
|
||||
const toggles = service.getTab('browser')?.settings?.toggles ?? []
|
||||
expect(toggles.map(t => t.key)).toEqual(['browserNoSandbox', 'browserInterceptLinks'])
|
||||
expect(toggles[0]?.title).toBeDefined()
|
||||
expect(toggles[0]?.desc).toBeDefined()
|
||||
expect(toggles[1]?.title).toBeDefined()
|
||||
expect(toggles[1]?.desc).toBeDefined()
|
||||
})
|
||||
|
||||
it('the browser createTab mints browser:<n> ids and bumps nextBrowser', () => {
|
||||
const { service, store } = setup()
|
||||
store.setSession('s1')
|
||||
service.openTab({ type: 'browser' })
|
||||
service.openTab({ type: 'browser' })
|
||||
const state = store.getSnapshot().state!
|
||||
const tabs = allLeaves(state.splits).flatMap(leaf => leaf.tabs).filter(t => t.type === 'browser')
|
||||
expect(tabs).toHaveLength(2)
|
||||
expect(tabs[0]!.id).toBe('browser:1')
|
||||
expect(tabs[1]!.id).toBe('browser:2')
|
||||
expect(state.nextBrowser).toBe(3)
|
||||
})
|
||||
|
||||
it('every built-in tab carries the settings-surface icon', () => {
|
||||
const { service } = setup()
|
||||
for (const tab of service.getTabs()) {
|
||||
@@ -61,10 +85,10 @@ describe('built-in tab registrations', () => {
|
||||
})
|
||||
|
||||
describe('built-in file viewer registrations', () => {
|
||||
it('registers the 8 built-in file viewers', () => {
|
||||
it('registers the 9 built-in file viewers', () => {
|
||||
const { service } = setup()
|
||||
expect(service.getFileViewers().map(v => v.id).sort()).toEqual(
|
||||
['binary-download', 'code', 'docx', 'image', 'markdown', 'pdf', 'pptx', 'xlsx'],
|
||||
['binary-download', 'code', 'docx', 'html', 'image', 'markdown', 'pdf', 'pptx', 'xlsx'],
|
||||
)
|
||||
})
|
||||
|
||||
@@ -84,6 +108,24 @@ describe('built-in file viewer registrations', () => {
|
||||
expect(service.matchFileViewer('readme.md', new Uint8Array([0x61]))?.id).toBe('markdown')
|
||||
})
|
||||
|
||||
it('html claims html/htm before the catch-all', () => {
|
||||
const { service } = setup()
|
||||
expect(service.matchFileViewer('index.html')?.id).toBe('html')
|
||||
expect(service.matchFileViewer('page.htm')?.id).toBe('html')
|
||||
expect(service.matchFileViewer('index.html', new Uint8Array([0x3c, 0x21]))?.id).toBe('html')
|
||||
expect(service.matchFileViewer('index.HTML')?.id).toBe('html')
|
||||
})
|
||||
|
||||
it('the html viewer declares its sandbox and default-unsafe related settings', () => {
|
||||
const { service } = setup()
|
||||
const toggles = service.getFileViewers().find(v => v.id === 'html')?.settings?.toggles ?? []
|
||||
expect(toggles.map(t => t.key)).toEqual(['htmlViewerNoSandbox', 'htmlViewerDefaultUnsafe'])
|
||||
expect(toggles[0]?.title).toBeDefined()
|
||||
expect(toggles[0]?.desc).toBeDefined()
|
||||
expect(toggles[1]?.title).toBeDefined()
|
||||
expect(toggles[1]?.desc).toBeDefined()
|
||||
})
|
||||
|
||||
it('binary-download claims legacy office by extension', () => {
|
||||
const { service } = setup()
|
||||
expect(service.matchFileViewer('old.doc')?.id).toBe('binary-download')
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* /sidebar/html route vocabulary tests: the path-encoded URL scheme must
|
||||
* round-trip absolute paths (POSIX and Windows), survive special characters,
|
||||
* and refuse malformed input — and crucially, a relative asset reference
|
||||
* resolved against an encoded document URL stays inside the same route with
|
||||
* the session scope intact (the WHY of the path-encoding design).
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeHtmlUrl, encodeHtmlUrl } from '../src/html-route.ts'
|
||||
|
||||
describe('encodeHtmlUrl', () => {
|
||||
it('encodes a POSIX absolute path into route segments', () => {
|
||||
expect(encodeHtmlUrl('sess-1', '/Users/me/proj/index.html'))
|
||||
.toBe('/sidebar/html/sess-1/Users/me/proj/index.html')
|
||||
})
|
||||
|
||||
it('encodes a Windows absolute path (drive colon percent-encoded)', () => {
|
||||
expect(encodeHtmlUrl('sess-1', 'C:\\Users\\me\\a.html'))
|
||||
.toBe('/sidebar/html/sess-1/C%3A/Users/me/a.html')
|
||||
})
|
||||
|
||||
it('percent-encodes special characters in segments', () => {
|
||||
expect(encodeHtmlUrl('s-1', '/a b/中文/100%.html'))
|
||||
.toBe('/sidebar/html/s-1/a%20b/%E4%B8%AD%E6%96%87/100%25.html')
|
||||
})
|
||||
|
||||
it('ignores leading/trailing slashes (files only)', () => {
|
||||
expect(encodeHtmlUrl('s', '/a//b/x.html')).toBe('/sidebar/html/s/a/b/x.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('decodeHtmlUrl', () => {
|
||||
it('decodes a POSIX round-trip', () => {
|
||||
const url = encodeHtmlUrl('sess-1', '/Users/me/proj/index.html')
|
||||
expect(decodeHtmlUrl(url)).toEqual({
|
||||
ok: true,
|
||||
ref: { sessionId: 'sess-1', path: '/Users/me/proj/index.html' },
|
||||
})
|
||||
})
|
||||
|
||||
it('decodes a Windows round-trip', () => {
|
||||
const url = encodeHtmlUrl('sess-1', 'C:\\Users\\me\\a.html')
|
||||
expect(decodeHtmlUrl(url)).toEqual({
|
||||
ok: true,
|
||||
ref: { sessionId: 'sess-1', path: '/C:/Users/me/a.html' },
|
||||
})
|
||||
})
|
||||
|
||||
it('decodes special characters round-trip', () => {
|
||||
const url = encodeHtmlUrl('s-1', '/a b/中文/100%.html')
|
||||
const result = decodeHtmlUrl(url)
|
||||
expect(result.ok).toBe(true)
|
||||
if (result.ok) expect(result.ref.path).toBe('/a b/中文/100%.html')
|
||||
})
|
||||
|
||||
it('refuses a wrong prefix (404)', () => {
|
||||
expect(decodeHtmlUrl('/sidebar/api/fs.read')).toEqual({
|
||||
ok: false, status: 404, message: 'not an html route',
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses an empty or double-slash path (400)', () => {
|
||||
expect(decodeHtmlUrl('/sidebar/html/').ok).toBe(false)
|
||||
expect(decodeHtmlUrl('/sidebar/html//s/a.html').ok).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses malformed percent encoding (400)', () => {
|
||||
expect(decodeHtmlUrl('/sidebar/html/s/%E0%A4%A').ok).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses a missing sessionId or file path (400)', () => {
|
||||
expect(decodeHtmlUrl('/sidebar/html//a.html')).toEqual({
|
||||
ok: false, status: 400, message: 'sessionId and file path are required',
|
||||
})
|
||||
expect(decodeHtmlUrl('/sidebar/html/s/')).toEqual({
|
||||
ok: false, status: 400, message: 'sessionId and file path are required',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps encoded traversal segments for the isWithin fence to bound', () => {
|
||||
// The decoder is not a security boundary by itself: an encoded `..`
|
||||
// decodes to `..` and the HOST refuses it via requireAbsolute +
|
||||
// isWithin(cwd) (the decoded path resolves outside the cwd).
|
||||
const result = decodeHtmlUrl('/sidebar/html/s/Users/me/../../etc/passwd')
|
||||
expect(result.ok).toBe(true)
|
||||
if (result.ok) expect(result.ref.path).toBe('/Users/me/../../etc/passwd')
|
||||
})
|
||||
})
|
||||
|
||||
describe('relative asset resolution stays in-route', () => {
|
||||
it('a relative reference against an encoded document URL keeps the session scope', () => {
|
||||
// WHATWG URL resolution drops the QUERY of a path-relative reference,
|
||||
// which is why the route is path-encoded: resolving ./style.css against
|
||||
// the document URL must land back on the same route with the same
|
||||
// session prefix.
|
||||
const doc = encodeHtmlUrl('sess-1', '/Users/me/proj/index.html')
|
||||
const asset = new URL('./style.css', `http://h${doc}`).pathname
|
||||
expect(asset).toBe('/sidebar/html/sess-1/Users/me/proj/style.css')
|
||||
expect(decodeHtmlUrl(asset)).toEqual({
|
||||
ok: true,
|
||||
ref: { sessionId: 'sess-1', path: '/Users/me/proj/style.css' },
|
||||
})
|
||||
})
|
||||
|
||||
it('deeper and parent-relative references resolve inside the route', () => {
|
||||
const doc = `http://h${encodeHtmlUrl('s', '/a/b/index.html')}`
|
||||
expect(new URL('img/x.png', doc).pathname).toBe('/sidebar/html/s/a/b/img/x.png')
|
||||
expect(new URL('../c.css', doc).pathname).toBe('/sidebar/html/s/a/c.css')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* External-link interception policy tests: the pure decision (which http(s)
|
||||
* external links are taken over into the sidebar browser) and the click
|
||||
* shape (plain left clicks only — modified clicks always bypass).
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isPlainLeftClick, shouldInterceptLink } from '../src/client/link-intercept.ts'
|
||||
|
||||
const SELF = 'http://127.0.0.1:3080'
|
||||
|
||||
describe('shouldInterceptLink', () => {
|
||||
it('takes over http(s) external links', () => {
|
||||
expect(shouldInterceptLink('https://example.com/page?a=1', SELF)).toBe('https://example.com/page?a=1')
|
||||
expect(shouldInterceptLink('http://example.com/', SELF)).toBe('http://example.com/')
|
||||
})
|
||||
|
||||
it('ignores non-http(s) links (mailto:, javascript:, file:)', () => {
|
||||
expect(shouldInterceptLink('mailto:a@b.c', SELF)).toBeNull()
|
||||
expect(shouldInterceptLink('javascript:void(0)', SELF)).toBeNull()
|
||||
expect(shouldInterceptLink('file:///tmp/x.html', SELF)).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores unparsable hrefs', () => {
|
||||
expect(shouldInterceptLink('not a url', SELF)).toBeNull()
|
||||
})
|
||||
|
||||
it('never takes over same-origin (GUI-internal) links', () => {
|
||||
expect(shouldInterceptLink('http://127.0.0.1:3080/settings', SELF)).toBeNull()
|
||||
expect(shouldInterceptLink('http://127.0.0.1:3080/chat/session-x', SELF)).toBeNull()
|
||||
// A different port of the same host is external.
|
||||
expect(shouldInterceptLink('http://127.0.0.1:9999/', SELF)).toBe('http://127.0.0.1:9999/')
|
||||
})
|
||||
|
||||
it("takes over LAN hosts (the browser's own blocklist, not the link policy)", () => {
|
||||
// The link takeover funnels into the sidebar browser, which then applies
|
||||
// its own loopback/self address-bar policy on render — the interception
|
||||
// itself must not silently drop links the browser will surface as blocked.
|
||||
expect(shouldInterceptLink('http://192.168.1.1/', SELF)).toBe('http://192.168.1.1/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isPlainLeftClick', () => {
|
||||
const plain = { button: 0, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false }
|
||||
|
||||
it('accepts a plain left click', () => {
|
||||
expect(isPlainLeftClick(plain)).toBe(true)
|
||||
})
|
||||
|
||||
it('bypasses modified clicks (Ctrl/Cmd/Shift/Alt) and non-left buttons', () => {
|
||||
expect(isPlainLeftClick({ ...plain, metaKey: true })).toBe(false)
|
||||
expect(isPlainLeftClick({ ...plain, ctrlKey: true })).toBe(false)
|
||||
expect(isPlainLeftClick({ ...plain, shiftKey: true })).toBe(false)
|
||||
expect(isPlainLeftClick({ ...plain, altKey: true })).toBe(false)
|
||||
expect(isPlainLeftClick({ ...plain, button: 1 })).toBe(false)
|
||||
expect(isPlainLeftClick({ ...plain, button: 2 })).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -57,6 +57,6 @@ describe('dsh-better-sidebar plugin export shape', () => {
|
||||
const overridden = (PrefsSchema as unknown as {
|
||||
(input: Record<string, unknown> | undefined): Record<string, unknown>
|
||||
})({ openByDefault: false, defaultWidthPercent: 45 })
|
||||
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Sandbox-contract tests for the two built-in web surfaces (HTML preview
|
||||
* iframe and the browser tab iframe). The iframe sandbox — opaque origin,
|
||||
* no allow-same-origin, no top-navigation — is the PRIMARY security
|
||||
* boundary of both features; these tests pin the exact attribute so a
|
||||
* refactor cannot silently widen it. The side card settings can drop the
|
||||
* sandbox per-feature (warned); those paths render the warning bar and no
|
||||
* sandbox attribute.
|
||||
*/
|
||||
import { describe, expect, it, beforeEach } from 'vitest'
|
||||
import { renderToString } from 'react-dom/server'
|
||||
import { createElement } from 'react'
|
||||
import './browser-globals.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import { TextEditor, HTML_IFRAME_SANDBOX } from '../src/client/TextEditor.tsx'
|
||||
import { BrowserView, BrowserEmbedBlocked, BROWSER_IFRAME_SANDBOX } from '../src/client/BrowserView.tsx'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
import type { FileViewerProps } from '../src/client/service.ts'
|
||||
|
||||
const CTX = {} as Context
|
||||
|
||||
// The copy assertions below pin the zh strings: force the zh locale (the
|
||||
// test environment's navigator may be the real Node one with an en locale).
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true })
|
||||
})
|
||||
|
||||
function viewerProps(store: ReturnType<typeof createSidebarStore>, overrides: Partial<FileViewerProps> = {}): FileViewerProps {
|
||||
return {
|
||||
ctx: CTX,
|
||||
store,
|
||||
scope: { sessionId: 's1', cwd: '/p' },
|
||||
path: '/p/a/index.html',
|
||||
title: 'index.html',
|
||||
viewerId: 'html',
|
||||
content: '<h1>hi</h1>',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('HTML preview iframe sandbox', () => {
|
||||
it('renders the preview iframe with the exact sandbox tokens and no same-origin / top-navigation', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(TextEditor, viewerProps(store)))
|
||||
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
|
||||
expect(iframe).toBeDefined()
|
||||
// The sandbox tokens are exactly the exported constant...
|
||||
expect(iframe).toContain(`sandbox="${HTML_IFRAME_SANDBOX}"`)
|
||||
// ...which must never contain the dangerous tokens.
|
||||
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-same-origin')
|
||||
expect(HTML_IFRAME_SANDBOX).not.toContain('allow-top-navigation')
|
||||
// Cross-origin framing by construction: route-src (never srcdoc).
|
||||
expect(iframe).toContain('src="/sidebar/html/s1/p/a/index.html"')
|
||||
expect(iframe).not.toContain('srcdoc=')
|
||||
// Referrer + permissions policy stay locked even when sandboxed.
|
||||
// (React SSR renders the referrerPolicy prop camelCase as written.)
|
||||
expect(iframe).toContain('referrerPolicy="no-referrer"')
|
||||
expect(iframe).toContain('allow=""')
|
||||
})
|
||||
|
||||
it('renders the live sandbox status row (green on + temporary unlock action)', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(TextEditor, viewerProps(store)))
|
||||
// Sandbox ON: the green status + the one-tap temporary unlock button.
|
||||
expect(html).toContain('沙箱模式:已启用')
|
||||
expect(html).toContain('临时解锁(不安全)')
|
||||
// No restore action while the sandbox is on.
|
||||
expect(html).not.toContain('恢复沙箱')
|
||||
})
|
||||
|
||||
it('drops the sandbox attribute with the red warning when the setting is on (no restore action — the global setting owns it)', () => {
|
||||
const store = createSidebarStore()
|
||||
store.setPrefs({ ...store.getPrefs(), htmlViewerNoSandbox: true })
|
||||
const html = renderToString(createElement(TextEditor, viewerProps(store)))
|
||||
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
|
||||
expect(iframe).toBeDefined()
|
||||
expect(iframe).not.toContain('sandbox=')
|
||||
// The red persistent warning copy is rendered; the temporary-unlock
|
||||
// action is NOT offered (re-enabling is the settings page's job).
|
||||
expect(html).toContain('沙箱已关闭')
|
||||
expect(html).not.toContain('临时解锁(不安全)')
|
||||
expect(html).not.toContain('恢复沙箱')
|
||||
})
|
||||
|
||||
it('starts unsandboxed (red, restorable) when the default-unsafe pref is on', () => {
|
||||
const store = createSidebarStore()
|
||||
store.setPrefs({ ...store.getPrefs(), htmlViewerDefaultUnsafe: true })
|
||||
const html = renderToString(createElement(TextEditor, viewerProps(store)))
|
||||
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
|
||||
expect(iframe).toBeDefined()
|
||||
expect(iframe).not.toContain('sandbox=')
|
||||
// The red warning + the one-tap restore (this is the LOCAL state).
|
||||
expect(html).toContain('沙箱已关闭')
|
||||
expect(html).toContain('恢复沙箱')
|
||||
expect(html).not.toContain('临时解锁(不安全)')
|
||||
})
|
||||
|
||||
it('markdown preview keeps rendering markdown, not an iframe', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(TextEditor, viewerProps(store, {
|
||||
viewerId: 'markdown',
|
||||
path: '/p/readme.md',
|
||||
content: '# hi',
|
||||
})))
|
||||
expect(html).not.toContain('<iframe')
|
||||
expect(html).not.toContain('/sidebar/html/')
|
||||
// The markdown is rendered into markup, not framed.
|
||||
expect(html).toContain('<h1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('browser tab iframe sandbox', () => {
|
||||
function tabProps(store: ReturnType<typeof createSidebarStore>, path?: string) {
|
||||
return {
|
||||
ctx: CTX,
|
||||
store,
|
||||
scope: { sessionId: 's1', cwd: '/p' },
|
||||
tab: { id: 'browser:1', type: 'browser', title: 'Browser', ...(path !== undefined ? { path } : {}) },
|
||||
visible: true,
|
||||
}
|
||||
}
|
||||
|
||||
it('renders the start page before any navigation (no iframe, no auto-load)', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(BrowserView, tabProps(store)))
|
||||
expect(html).not.toContain('<iframe')
|
||||
expect(html).toContain('输入网址开始浏览')
|
||||
})
|
||||
|
||||
it('sandboxes the iframe without same-origin / top-navigation', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
|
||||
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
|
||||
expect(iframe).toBeDefined()
|
||||
expect(iframe).toContain(`sandbox="${BROWSER_IFRAME_SANDBOX}"`)
|
||||
expect(BROWSER_IFRAME_SANDBOX).not.toContain('allow-same-origin')
|
||||
expect(BROWSER_IFRAME_SANDBOX).not.toContain('allow-top-navigation')
|
||||
expect(iframe).toContain('src="https://example.com/"')
|
||||
expect(iframe).toContain('referrerPolicy="no-referrer"')
|
||||
expect(iframe).toContain('allow=""')
|
||||
})
|
||||
|
||||
it('renders the live sandbox status row with the temporary unlock action', () => {
|
||||
const store = createSidebarStore()
|
||||
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
|
||||
expect(html).toContain('沙箱模式:已启用')
|
||||
expect(html).toContain('临时解锁(不安全)')
|
||||
})
|
||||
|
||||
it('offers the open-in-browser action once a URL is loaded (disabled before navigation)', () => {
|
||||
const store = createSidebarStore()
|
||||
// No URL yet: the external-open action is disabled.
|
||||
const start = renderToString(createElement(BrowserView, tabProps(store)))
|
||||
expect(start).toContain('aria-label="在浏览器中打开"')
|
||||
expect(start).toContain('title="在浏览器中打开" disabled=""')
|
||||
// With a URL: enabled.
|
||||
const loaded = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
|
||||
expect(loaded).toContain('aria-label="在浏览器中打开"')
|
||||
expect(loaded).not.toContain('title="在浏览器中打开" disabled=""')
|
||||
})
|
||||
|
||||
it('drops the sandbox attribute with the red warning when the setting is on (no restore action — the global setting owns it)', () => {
|
||||
const store = createSidebarStore()
|
||||
store.setPrefs({ ...store.getPrefs(), browserNoSandbox: true })
|
||||
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
|
||||
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
|
||||
expect(iframe).toBeDefined()
|
||||
expect(iframe).not.toContain('sandbox=')
|
||||
expect(html).toContain('沙箱已关闭')
|
||||
expect(html).not.toContain('临时解锁(不安全)')
|
||||
expect(html).not.toContain('恢复沙箱')
|
||||
})
|
||||
})
|
||||
|
||||
describe('browser embed-refusal panel', () => {
|
||||
it('explains the refusal with the host, the reason, and both actions', () => {
|
||||
const html = renderToString(createElement(BrowserEmbedBlocked, {
|
||||
url: 'https://arxiv.org/abs/2401.10001',
|
||||
onOpenInBrowser: () => {},
|
||||
onLoadAnyway: () => {},
|
||||
}))
|
||||
expect(html).toContain('arxiv.org 拒绝了嵌入请求')
|
||||
expect(html).toContain('X-Frame-Options / frame-ancestors')
|
||||
expect(html).toContain('在浏览器中打开')
|
||||
expect(html).toContain('仍然加载')
|
||||
})
|
||||
})
|
||||
@@ -307,6 +307,28 @@ describe('service.openTab dedupe', () => {
|
||||
expect(tab?.title).toBe('main.ts')
|
||||
})
|
||||
|
||||
it('a url seed lands the tab with its path pre-set (the sidebar-browser navigation seed)', () => {
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
service.registerTab({
|
||||
id: 'browser',
|
||||
title: () => 'Browser',
|
||||
createTab: (state) => ({
|
||||
tab: { id: `browser:${state.nextBrowser}`, type: 'browser', title: 'Browser' },
|
||||
patch: { nextBrowser: state.nextBrowser + 1 },
|
||||
}),
|
||||
component: () => null,
|
||||
})
|
||||
store.setSession('s1')
|
||||
service.openTab({ type: 'browser', url: 'https://example.com/x', title: 'example.com' })
|
||||
const state = store.getSnapshot().state!
|
||||
const tab = allLeaves(state.splits).flatMap(l => l.tabs).find(t => t.type === 'browser')
|
||||
expect(tab?.id).toBe('browser:1')
|
||||
expect(tab?.path).toBe('https://example.com/x')
|
||||
expect(tab?.title).toBe('example.com')
|
||||
expect(state.nextBrowser).toBe(2)
|
||||
})
|
||||
|
||||
it('the descriptor title is the default when no title is given', () => {
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
|
||||
+70
-2
@@ -3,7 +3,7 @@
|
||||
* exercises the real integrations — route registration, git against the
|
||||
* actual repository, and a real directory listing. Runs with `pnpm test`.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
@@ -58,7 +58,7 @@ describe('host plugin smoke', () => {
|
||||
inject: () => () => {},
|
||||
}
|
||||
apply(ctx as never)
|
||||
expect(routes.map(route => route.path)).toEqual(['/sidebar/api', '/sidebar/file'])
|
||||
expect(routes.map(route => route.path)).toEqual(['/sidebar/api', '/sidebar/file', '/sidebar/html'])
|
||||
expect(upgrades.map(route => route.path)).toEqual(['/sidebar/ws/terminal', '/sidebar/ws/agent-terminals'])
|
||||
// Teardown runs without throwing (pty manager has nothing open).
|
||||
for (const cleanup of effects) cleanup()
|
||||
@@ -508,6 +508,10 @@ describe('side card settings routes', () => {
|
||||
autoOpenSubagent: true,
|
||||
agentTerminalTools: false,
|
||||
interceptOpenPath: true,
|
||||
htmlViewerNoSandbox: false,
|
||||
htmlViewerDefaultUnsafe: false,
|
||||
browserNoSandbox: false,
|
||||
browserInterceptLinks: true,
|
||||
// The enable-switch maps default to {} (everything on).
|
||||
tabsEnabled: {},
|
||||
viewersEnabled: {},
|
||||
@@ -542,7 +546,69 @@ describe('side card settings routes', () => {
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error?.message).toMatch(/plain object/)
|
||||
})
|
||||
/** Fake fetch responses shaped like what the route consumes. */
|
||||
const respond = (status: number, headers: Record<string, string>): Response =>
|
||||
({ status, url: 'https://site.example/', headers: new Headers(headers) }) as unknown as Response
|
||||
|
||||
it('reports X-Frame-Options and frame-ancestors from the target headers', async () => {
|
||||
const route = mountWithSettings(undefined)
|
||||
vi.stubGlobal('fetch', vi.fn(async () => respond(200, {
|
||||
'x-frame-options': 'SAMEORIGIN',
|
||||
'content-security-policy': "default-src 'self'; frame-ancestors 'none'",
|
||||
})))
|
||||
try {
|
||||
const result = await invoke(route, 'browser.probe', { url: 'https://arxiv.org/' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.value).toEqual({
|
||||
reachable: true,
|
||||
url: 'https://site.example/',
|
||||
status: 200,
|
||||
xFrameOptions: 'SAMEORIGIN',
|
||||
frameAncestors: ["'none'"],
|
||||
})
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('retries a 405 HEAD as GET', async () => {
|
||||
const route = mountWithSettings(undefined)
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(respond(405, {}))
|
||||
.mockResolvedValueOnce(respond(200, {}))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
try {
|
||||
const result = await invoke(route, 'browser.probe', { url: 'https://example.com/' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(result.value).toMatchObject({ reachable: true, status: 200 })
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports an unreachable target as reachable:false', async () => {
|
||||
const route = mountWithSettings(undefined)
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ENOTFOUND') }))
|
||||
try {
|
||||
const result = await invoke(route, 'browser.probe', { url: 'https://example.com/' })
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.value).toEqual({ reachable: false })
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses non-http(s) and loopback URLs', async () => {
|
||||
const route = mountWithSettings(undefined)
|
||||
for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'http://127.0.0.1:8080/', 'http://localhost/']) {
|
||||
const result = await invoke(route, 'browser.probe', { url })
|
||||
expect(result.ok, url).toBe(false)
|
||||
expect(result.error?.code, url).toBe('bad-request')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('agent terminal tool gating', () => {
|
||||
it('injects the eight tools only when the side-card setting is enabled (default off)', () => {
|
||||
@@ -601,4 +667,6 @@ describe('agent terminal tool gating', () => {
|
||||
expect(live()).toBe(8)
|
||||
expect(registered).toBe(16)
|
||||
})
|
||||
|
||||
|
||||
})
|
||||
|
||||
+63
-5
@@ -4,7 +4,7 @@ import { parseLogLines, parsePorcelainZ } from '../src/git.ts'
|
||||
import { parseUnifiedDiff } from '../src/client/DiffView.tsx'
|
||||
import {
|
||||
activateTab, allLeaves, closeTab, createSidebarStore, defaultWidthFor, insertLeafAt, makeDefaultState,
|
||||
moveTab, moveTabToEdge, openDiffTab, openTabInActivePane, reconcileAgentTerminals, resizeSplit, sanitizeState, splitPane, tabOpenIn, toggleExpanded,
|
||||
moveTab, moveTabToEdge, openDiffTab, openTabInActivePane, patchTab, reconcileAgentTerminals, resizeSplit, sanitizeState, splitPane, tabOpenIn, toggleExpanded,
|
||||
type SidebarState, type SidebarTab, type SplitNode,
|
||||
} from '../src/client/state.ts'
|
||||
import { loadPrefs, type SidebarSettingsClient } from '../src/client/prefs.ts'
|
||||
@@ -454,6 +454,52 @@ describe('sidebar state', () => {
|
||||
expect((after.splits as { active: string | null }).active).toBe(tabId)
|
||||
})
|
||||
|
||||
it('patchTab updates the title and path of one open tab (browser persistence)', () => {
|
||||
let s = state()
|
||||
const leaf = s.splits as { id: string; tabs: { id: string; type: string; title: string; path?: string }[] }
|
||||
s = openTabInActivePane(s, { id: 'browser:1', type: 'browser', title: 'Browser' })
|
||||
const browserId = 'browser:1'
|
||||
s = patchTab(s, browserId, { path: 'https://example.com/', title: 'example.com' })
|
||||
const tab = (s.splits as { tabs: { id: string; title: string; path?: string }[] }).tabs.find(t => t.id === browserId)
|
||||
expect(tab).toMatchObject({ title: 'example.com', path: 'https://example.com/' })
|
||||
// A partial patch leaves the other field untouched.
|
||||
s = patchTab(s, browserId, { title: 'example.org' })
|
||||
const again = (s.splits as { tabs: { id: string; title: string; path?: string }[] }).tabs.find(t => t.id === browserId)
|
||||
expect(again).toMatchObject({ title: 'example.org', path: 'https://example.com/' })
|
||||
// Other tabs are untouched.
|
||||
expect(leaf.tabs[0]).toBeDefined()
|
||||
})
|
||||
|
||||
it('patchTab is a no-op for a missing tab id', () => {
|
||||
const s = state()
|
||||
const after = patchTab(s, 'nope', { title: 'X', path: 'https://x/' })
|
||||
expect(after).toBe(s)
|
||||
})
|
||||
|
||||
it('sanitize accepts nextBrowser (defaulting a missing/malformed one to 1)', () => {
|
||||
const base = {
|
||||
panelOpen: true,
|
||||
width: 400,
|
||||
nextTerminal: 1,
|
||||
activePane: 'pane:1',
|
||||
expanded: [],
|
||||
splits: {
|
||||
kind: 'leaf',
|
||||
id: 'pane:1',
|
||||
active: null,
|
||||
tabs: [{ id: 't', type: 'explorer', title: 'Explorer' }],
|
||||
},
|
||||
}
|
||||
// Older persisted states lack the field: they must keep loading.
|
||||
expect(sanitizeState(base)?.nextBrowser).toBe(1)
|
||||
// A present valid value survives; a malformed one falls back to 1.
|
||||
expect(sanitizeState({ ...base, nextBrowser: 7 })?.nextBrowser).toBe(7)
|
||||
expect(sanitizeState({ ...base, nextBrowser: 'x' })?.nextBrowser).toBe(1)
|
||||
expect(sanitizeState({ ...base, nextBrowser: 0 })?.nextBrowser).toBe(1)
|
||||
// The default state seeds 1.
|
||||
expect(makeDefaultState().nextBrowser).toBe(1)
|
||||
})
|
||||
|
||||
it('tabOpenIn: a tab is open until it is truly closed, wherever it lives', () => {
|
||||
let s = state()
|
||||
const leaf = s.splits as { id: string; tabs: { id: string }[] }
|
||||
@@ -838,6 +884,10 @@ describe('side card preferences', () => {
|
||||
autoOpenSubagent: false,
|
||||
agentTerminalTools: true,
|
||||
interceptOpenPath: true,
|
||||
htmlViewerNoSandbox: false,
|
||||
htmlViewerDefaultUnsafe: false,
|
||||
browserNoSandbox: false,
|
||||
browserInterceptLinks: true,
|
||||
tabsEnabled: {},
|
||||
viewersEnabled: {},
|
||||
})
|
||||
@@ -851,6 +901,10 @@ describe('side card preferences', () => {
|
||||
autoOpenSubagent: true,
|
||||
agentTerminalTools: false,
|
||||
interceptOpenPath: true,
|
||||
htmlViewerNoSandbox: false,
|
||||
htmlViewerDefaultUnsafe: false,
|
||||
browserNoSandbox: false,
|
||||
browserInterceptLinks: true,
|
||||
tabsEnabled: {},
|
||||
viewersEnabled: {},
|
||||
})
|
||||
@@ -864,6 +918,10 @@ describe('side card preferences', () => {
|
||||
autoOpenSubagent: true,
|
||||
agentTerminalTools: false,
|
||||
interceptOpenPath: true,
|
||||
htmlViewerNoSandbox: false,
|
||||
htmlViewerDefaultUnsafe: false,
|
||||
browserNoSandbox: false,
|
||||
browserInterceptLinks: true,
|
||||
tabsEnabled: {},
|
||||
viewersEnabled: {},
|
||||
})
|
||||
@@ -905,9 +963,9 @@ describe('side card preferences', () => {
|
||||
const store = createSidebarStore()
|
||||
// Node environment: no window → the width falls back to PANEL_DEFAULT,
|
||||
// while the open flag still follows the preference.
|
||||
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
store.setSession('fresh-session')
|
||||
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
const snapshot = store.getSnapshot()
|
||||
expect(snapshot.sessionId).toBe('fresh-session')
|
||||
expect(snapshot.state?.panelOpen).toBe(false)
|
||||
@@ -920,7 +978,7 @@ describe('side card preferences', () => {
|
||||
|
||||
it('skips the default explorer tab when the explorer type is disabled', () => {
|
||||
const store = createSidebarStore()
|
||||
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, tabsEnabled: { explorer: false }, viewersEnabled: {} })
|
||||
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, tabsEnabled: { explorer: false }, viewersEnabled: {} })
|
||||
store.setSession('no-explorer')
|
||||
const state = store.getSnapshot().state!
|
||||
const tabs = allLeaves(state.splits).flatMap(leaf => leaf.tabs)
|
||||
@@ -928,7 +986,7 @@ describe('side card preferences', () => {
|
||||
expect(state.splits.kind).toBe('leaf')
|
||||
// Re-enabling seeds the explorer tab again.
|
||||
const openStore = createSidebarStore()
|
||||
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, agentTerminalTools: false, interceptOpenPath: true, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, tabsEnabled: {}, viewersEnabled: {} })
|
||||
openStore.setSession('with-explorer')
|
||||
const openTabs = allLeaves(openStore.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
|
||||
expect(openTabs.map(tab => tab.type)).toEqual(['explorer'])
|
||||
|
||||
Reference in New Issue
Block a user