Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
/**
* 预览文档的 CSP:策略内容、注入位置,以及「策略必须挂在渲染载体上」的接线守卫。
*
* 资源透传相关的接线守卫(签名地址不得进页面、OSS 对象回收)在本文件末尾单独一段。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { HTML_PREVIEW_CSP, HTML_SNAPSHOT_CSP, withHtmlPreviewCsp } from '@/session/htmlPreviewCsp';
describe('HTML_PREVIEW_CSP(策略内容)', () => {
it('blocks workers explicitly even when snapshot scripts permit self', () => {
expect(HTML_PREVIEW_CSP).toContain("worker-src 'none'");
expect(HTML_SNAPSHOT_CSP).toContain("worker-src 'none'");
expect(HTML_SNAPSHOT_CSP).toContain("script-src 'self' 'unsafe-inline' data:");
});
it('默认全拒,网络出口关闭', () => {
expect(HTML_PREVIEW_CSP).toContain("default-src 'none'");
expect(HTML_PREVIEW_CSP).toContain("connect-src 'none'");
expect(HTML_PREVIEW_CSP).toContain("form-action 'none'");
expect(HTML_PREVIEW_CSP).toContain("base-uri 'none'");
});
it('资源只放行 data:,不放行任何远端来源', () => {
// 放行 img-src https: 就等于留一条 `new Image().src='…?d=…'` 外传通道,
// 那会让「读到了也送不出去」这条保证形同虚设。
expect(HTML_PREVIEW_CSP).toContain('img-src data:');
expect(HTML_PREVIEW_CSP).not.toMatch(/img-src[^;]*https:/);
expect(HTML_PREVIEW_CSP).not.toMatch(/connect-src[^;]*https:/);
expect(HTML_PREVIEW_CSP).not.toContain('*');
});
it('保留内联样式与脚本(设计稿的交互依赖它)', () => {
expect(HTML_PREVIEW_CSP).toContain("style-src 'unsafe-inline' data:");
expect(HTML_PREVIEW_CSP).toContain("script-src 'unsafe-inline' data:");
});
});
describe('withHtmlPreviewCsp(自带前导段,不定位作者 doctype)', () => {
const cspAt = (out: string) => out.indexOf('<meta http-equiv');
it('总是自己前置 doctype + 策略,原文整份跟在后面不动', () => {
const out = withHtmlPreviewCsp('<html><body>x</body></html>');
expect(out.startsWith('<!doctype html><meta http-equiv')).toBe(true);
expect(out.endsWith('<html><body>x</body></html>')).toBe(true);
});
it('原文自带 doctype 也不去找它 —— 重复的那个按规范在 in-body 被忽略', () => {
const out = withHtmlPreviewCsp('<!DOCTYPE html><html>x</html>');
expect(out.startsWith('<!doctype html><meta http-equiv')).toBe(true);
// 原文一字不动,包括它自己的 doctype。
expect(out).toContain('<!DOCTYPE html><html>x</html>');
});
it('前导注释 / 处理指令 / CDATA 都不再需要认识(整类边界消失)', () => {
// 这三种形态此前各挖过一轮:紧贴开头 → 前导注释 → 处理指令。
for (const prefix of [
'<!-- generated by tool -->',
'<?xml version="1.0" encoding="UTF-8"?>',
'<?php echo 1; ?>',
'<![CDATA[x]]>',
'\n\n <!-- a --> <!-- b --> ',
'<!-- 未闭合注释 ',
]) {
const out = withHtmlPreviewCsp(`${prefix}<!doctype html><html>x</html>`);
// 策略永远在最前(作者内容一律在它之后),不存在"插错位置"这回事。
expect(out.startsWith('<!doctype html><meta http-equiv')).toBe(true);
expect(cspAt(out)).toBeLessThan(out.indexOf(prefix));
expect(out).toContain(prefix);
}
});
it('BOM 必须前移,不能变成文档中间的游离字符', () => {
const out = withHtmlPreviewCsp('\uFEFF<!doctype html><html>x</html>');
expect(out.charCodeAt(0)).toBe(0xfeff);
expect(out.slice(1).startsWith('<!doctype html><meta http-equiv')).toBe(true);
// 只应有一个 BOM。
expect(out.split('\uFEFF')).toHaveLength(2);
});
it('空文档也带策略(不留一条无策略的路径)', () => {
expect(withHtmlPreviewCsp('').startsWith('<!doctype html><meta http-equiv')).toBe(true);
});
it('不去找 <head>:注释里的假标签不得成为锚点', () => {
const out = withHtmlPreviewCsp('<!-- <head> --><html><head><title>t</title></head></html>');
expect(out.startsWith('<!doctype html><meta http-equiv')).toBe(true);
// 策略在假标签与真 head 之前。
expect(cspAt(out)).toBeLessThan(out.indexOf('<!-- <head> -->'));
expect(cspAt(out)).toBeLessThan(out.indexOf('<head>', out.indexOf('<html>')));
});
});
describe('前导段剥离设备与 WebRTC 能力(review P0)', () => {
const prolog = withHtmlPreviewCsp('<html><body>x</body></html>');
const cspSource = readFileSync(
resolve(process.cwd(), '../../packages/maker-shared/src/htmlPreviewCsp.ts'),
'utf8',
).replace(/\r\n/g, '\n');
const OPEN = '<script>';
const CLOSE = '</script>';
// 只取我们这一段:切到**第一个** </script> 为止,否则会把作者内容一起圈进来。
const guard = prolog.slice(prolog.indexOf(OPEN), prolog.indexOf(CLOSE) + CLOSE.length);
it('媒体入口按「名单 × 实例+原型」两处一起盖(结构性,不逐条列举)', () => {
// Android 的 mediaCapturePermissionGrantType setter 是空函数(RNCWebViewManager.java),
// 权限只看 app 级 OS 运行时权限 —— 用户为语音输入授过 RECORD_AUDIO 之后,不可信 HTML
// 就能零提示拿到音视频流。所以能力面直接删掉,不依赖平台权限实现是否正确。
//
// **只盖实例不够**(review P1 实捉):遮蔽 `navigator.x` 只挡住那一种写法,原型方法仍可
// `Navigator.prototype.webkitGetUserMedia.call(navigator, ...)` 取出来直接调。上一版正是
// 只给 mediaDevices / getUserMedia 盖了原型、漏了两个前缀变体。
//
// 断言写成「必须有一个同时作用于实例与原型的 both()」而不是逐个名字对 —— 逐个对的写法
// 就是上一版漏掉一边的成因;结构性保证才挡得住下一次加名字时再漏。
expect(guard).toContain("var both=function(k){freeze(navigator,k)");
expect(guard).toContain("freeze(Navigator.prototype,k)");
for (const name of ['mediaDevices', 'getUserMedia', 'webkitGetUserMedia', 'mozGetUserMedia']) {
expect(guard).toContain(`'${name}'`);
}
// 名单必须整体走 both,不允许某个名字被单独用 freeze(navigator, ...) 处理掉。
expect(guard).toContain('.forEach(both)');
expect(guard).not.toMatch(/freeze\(navigator,'/);
});
it('剥掉 WebRTC:webrtc 指令实测在任何平台都无效,删掉构造器才是唯一实际封锁', () => {
for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'RTCDataChannel']) {
expect(guard).toContain(`'${name}'`);
}
expect(guard).toContain('freeze(window,k)');
});
it('兜底盖 MediaDevices.prototype.getUserMedia(带存在性判断,不炸老引擎)', () => {
expect(guard).toContain("typeof MediaDevices!=='undefined'");
expect(guard).toContain("freeze(MediaDevices.prototype,'getUserMedia')");
});
it('属性定死为不可写不可配置,作者脚本重定义会抛', () => {
expect(guard).toContain('writable:false,configurable:false');
});
it('脚本在 CSP meta 之后、任何作者内容之前(无竞态)', () => {
expect(prolog.indexOf('<meta http-equiv')).toBeLessThan(prolog.indexOf('<script>'));
expect(prolog.indexOf('<script>')).toBeLessThan(prolog.indexOf('<html>'));
});
it('脚本文本不得含提前闭合的 </script>', () => {
const body = guard.slice(OPEN.length, guard.length - CLOSE.length);
expect(body).not.toContain('</script');
// 整份文档里只应有我们这一个 <script>(作者内容为空时)。
expect(prolog.split('<script>')).toHaveLength(2);
});
it('封掉子 realm 的便捷取法(contentWindow / contentDocument 恒 null)', () => {
// 无 src 的 iframe 会同步得到未加固的初始 about:blank realm,
// `iframe.contentWindow.RTCPeerConnection` 绕过上面全部冻结(review P1,已实测)。
for (const n of ['HTMLIFrameElement', 'HTMLFrameElement', 'HTMLObjectElement', 'HTMLEmbedElement']) {
expect(guard).toContain(`'${n}'`);
}
expect(guard).toContain("['contentWindow','contentDocument']");
expect(guard).toContain('get:function(){return null;}');
});
it('不得再声称 frame-src 封掉了干净 realm —— 那个说法是错的', () => {
// `frame-src` 管 frame 的**导航**,不阻止无 src iframe 的初始 about:blank 上下文;
// 实测加固页与裸页拿到的绕过路径完全相同。这条守卫防止该错误结论回归。
expect(cspSource).not.toContain('拿不到干净 realm');
// 残留必须被显式写下来,而不是靠删掉错误说法蒙过去。
expect(cspSource).toContain('子 browsing context');
expect(cspSource).toContain('window[0]');
// CSP 这两条仍在(它们各自有别的作用:阻止 frame 导航与插件),只是不能当 realm 证明。
expect(HTML_PREVIEW_CSP).toContain("frame-src 'none'");
expect(HTML_PREVIEW_CSP).toContain("object-src 'none'");
});
it('不改变「预览保留 JavaScript」这个已定取舍', () => {
// 只删设备与 WebRTC 三样,脚本执行本身照旧放行。
expect(HTML_PREVIEW_CSP).toContain("script-src 'unsafe-inline' data:");
});
it("不得再声称 webrtc 'block' 在 Android/Chromium 那侧封住了 —— 实测两种下发都不拦", () => {
// 上一版这里照着 CSP3 spec 推断「Chromium 111+ 实现 → Android System WebView 覆盖 →
// 那一侧是真封住的」,**没有实测**。实机验(Chrome 150.0.7871.187):经 meta http-equiv
// 与 HTTP Content-Security-Policy 响应头两种下发,顶层 new RTCPeerConnection() 都构造成功。
// 这是第四次同类错误(前三次:「不可伪造」「没有任何出网信道」「拿不到干净 realm」),
// 都是**照规范推出来的安全声明没有实测**,所以照旧用守卫钉死措辞。
expect(cspSource).not.toContain('那一侧是真封住的');
expect(cspSource).not.toContain('实机上基本都覆盖');
// 不许再用「Chromium 111+ 实现」当作它生效的依据。
expect(cspSource).not.toMatch(/Chromium 111\+\s*实现/);
// 必须写明实测结论与被验的引擎版本,否则等于删掉错误说法后留白。
expect(cspSource).toContain('实测');
expect(cspSource).toContain('Chrome 150');
});
it('残留矩阵必须逐平台逐 realm 写明,不许糊成一句「有残留」', () => {
// 放行人要靠这张表做取舍(保留 JS 还是 javaScriptEnabled={false}),缺格子就等于
// 让他在信息不全的情况下签字。四个能力面 × 两个 realm 都要在注释里出现。
expect(cspSource).toContain('实测残留矩阵');
for (const cell of ['fetch / XHR 外传', 'mic / camera · iOS', 'mic / camera · Andr', 'WebRTC 外传 · 两端']) {
expect(cspSource).toContain(cell);
}
// Android 的 mic/camera 必须标成可达,且写明根因是空 setter + onPermissionRequest 同步 grant。
expect(cspSource).toContain('onPermissionRequest');
expect(cspSource).toContain('同步 grant、零提示');
// 「一行代码可达」必须显式说出来 —— 它是「理论残留」与「真实漏洞」的分界。
expect(cspSource).toContain('一行代码可达');
});
});
describe('渲染载体的安全接线(源码级守卫)', () => {
const readerSource = readFileSync(
resolve(process.cwd(), 'src/session/HtmlFileReader.tsx'),
'utf8',
).replace(/\r\n/g, '\n');
const cspSource = readFileSync(
resolve(process.cwd(), '../../packages/maker-shared/src/htmlPreviewCsp.ts'),
'utf8',
).replace(/\r\n/g, '\n');
it('CSP 挂在渲染载体上:任何进 WebView 的 HTML 都带策略', () => {
// 放在载体这一层而不是取件那一层:不管 HTML 从哪条路来、有没有同目录资源,
// 只要进这个 WebView 就必须带策略。
expect(readerSource).toContain('withHtmlPreviewCsp(html)');
expect(readerSource).toContain("source={{ baseUrl: 'about:blank', html: guardedHtml }}");
// 不得把未加固的原文直接喂进去。
expect(readerSource).not.toMatch(/html:\s*html\s*\}/);
});
it('WebRTC 是已知残留面:不得把这套说成「零出网」', () => {
// RTCPeerConnection 的 ICE / STUN / DTLS 不受 CSP 各 *-src 指令管辖,恶意脚本能把内容
// 编码进 STUN 域名外传(review P1)。`webrtc 'block'` 保留是为了等引擎将来实现,但
// **实测在 Chrome 150 上 meta 与 HTTP 头两种下发都不拦** —— 见下一条守卫。
expect(HTML_PREVIEW_CSP).toContain("webrtc 'block'");
// 这三个说法一旦回归,就是在这个值上重建一个不成立的安全假设(同「不可伪造」那次)。
for (const text of [readerSource, cspSource]) {
expect(text).not.toContain('完全离线的沙箱');
expect(text).not.toContain('完全离线的预览沙箱');
expect(text).not.toContain('没有任何出网信道');
}
// 残留面必须被显式写下来,而不是靠删掉过强说法蒙过去。
expect(cspSource).toContain('残留信道');
expect(cspSource).toContain('WebKit');
// 媒体权限拒绝是另一件事,注释必须说明它不是 WebRTC 的解(否则会被当成已修)。
expect(readerSource).toContain('mediaCapturePermissionGrantType="deny"');
expect(readerSource).toContain('不是** WebRTC 外传的解');
});
it('CSP 与导航策略是配套的两半:CSP 管得到的出口必须全关', () => {
// CSP 关子资源与表单,导航回调关顶层跳转。少任何一半都留着一条外传路径
// (review P1:导航回调完全不经过 new Image().src / fetch 这类子资源请求)。
// 导航判定已抽到 htmlNavigationPolicy(纯模块,便于行为级用例);载体只负责接线。
const navPolicy = readFileSync(
resolve(process.cwd(), 'src/session/htmlNavigationPolicy.ts'),
'utf8',
).replace(/\r\n/g, '\n');
expect(readerSource).toContain('onShouldStartLoadWithRequest={interceptNavigation}');
expect(navPolicy).toContain("/^about:blank#/i.test(url)");
expect(readerSource).not.toMatch(/\bLinking\.\w/);
expect(HTML_PREVIEW_CSP).toContain("default-src 'none'");
expect(HTML_PREVIEW_CSP).toContain("connect-src 'none'");
});
});
describe('资源取件的安全接线(源码级守卫)', () => {
const pageSource = readFileSync(
resolve(process.cwd(), 'app/files/preview/[sessionId].tsx'),
'utf8',
);
const snapshotSource = readFileSync(resolve(process.cwd(), 'src/session/mobileHtmlPreview.ts'), 'utf8');
it('downloads signed URLs into private files before publishing every guarded HTML', () => {
expect(snapshotSource).toContain('fetchRemoteAbsFileOnce(');
expect(snapshotSource).toContain('createDownloadResumable(media.url, destination.uri');
expect(snapshotSource).toContain('destination.write(withSnapshotHtmlCsp(text))');
expect(snapshotSource).toContain('return { url, documents: snapshotDocumentPaths(files), close }');
expect(snapshotSource).not.toContain('return media.url');
});
it('checks exact manifest size before and after download and bounds upload on the controlled device', () => {
expect(snapshotSource).toContain('if (media.size !== file.size)');
const legacySnapshot = snapshotSource.slice(snapshotSource.indexOf('export async function prepareMobileHtmlPreview'), snapshotSource.indexOf('async function prepareOnDemand'));
expect(legacySnapshot.indexOf('if (media.size !== file.size)')).toBeLessThan(legacySnapshot.indexOf('createDownloadResumable(media.url'));
expect(snapshotSource).toContain('destination.size !== file.size');
expect(snapshotSource).toContain('baseDir: root, maxBytes: Math.max(1, file.size)');
const gallery = readFileSync(resolve(process.cwd(), 'src/session/fileBrowserGallery.ts'), 'utf8');
expect(gallery).toContain('&baseDir=');
expect(gallery).toContain('&maxBytes=');
});
it('collects every upload key before presigning and cleans successful and failed downloads', () => {
expect(snapshotSource).toContain('const uploaded = new Set<string>()');
expect(snapshotSource).toContain('(key) => uploaded.add(key)');
expect(snapshotSource).toContain('finally { for (const key of uploaded) deps.deleteOssObject(key); }');
expect(pageSource).toContain("method: 'DELETE'");
const media = readFileSync(resolve(process.cwd(), 'src/session/remoteMedia.ts'), 'utf8');
const collected = media.indexOf('opts?.onOssKey?.(fetched.ossKey);');
const presigned = media.indexOf('deps.presignGet(fetched.ossKey)');
expect(collected).toBeGreaterThanOrEqual(0);
expect(presigned).toBeGreaterThan(collected);
});
it('SSH 会话的资源取件必须带会话上下文', () => {
expect(pageSource).toContain('const sshMediaContext = useMemo');
expect(pageSource).toContain('session?.remoteHostId?.trim()');
// 三项必须同时给,缺一即视为本机会话(被控端会拒绝不完整的 SSH 参数)。
expect(pageSource).toContain('if (!remoteHostId || !sessionId || !workdir) return null;');
expect(pageSource).toContain('sshMediaContext,');
});
});