收紧文本导出 MIME 边界
将文本导出 MIME 收窄到共享 HostBridge 文本 MIME 清单 让 Expo 和 Tauri 壳拒绝非文本 MIME 的 file.exportText 请求 增加移动端和桌面端门禁反查文本导出 MIME 边界 补充宿主壳协议文档和共享决策记录
This commit is contained in:
@@ -840,6 +840,19 @@ function extractRustSomeStringValues(source, functionName) {
|
||||
);
|
||||
}
|
||||
|
||||
function extractRustGuardedMimeValues(source, functionName) {
|
||||
const match = source.match(
|
||||
new RegExp(`(?:pub\\(crate\\)\\s+)?fn ${functionName}[^\\{]*\\{([\\s\\S]*?)\\n\\}`),
|
||||
);
|
||||
if (!match) {
|
||||
throw new Error(`unable to read Rust function ${functionName}`);
|
||||
}
|
||||
|
||||
return [...match[1].matchAll(/if mime_type == "([^"]+)"/g)].map(
|
||||
(entry) => entry[1],
|
||||
);
|
||||
}
|
||||
|
||||
function extractDesktopCapabilities(source) {
|
||||
const match = source.match(/fn capabilities\(\)[^{]*\{[\s\S]*?vec!\[([\s\S]*?)\]\s*\}/);
|
||||
if (!match) {
|
||||
@@ -1353,6 +1366,11 @@ assertSameList(
|
||||
sharedTextMimeTypes,
|
||||
'desktop shell text MIME types',
|
||||
);
|
||||
assertSameList(
|
||||
extractRustGuardedMimeValues(rustHostSource, 'normalize_export_text_mime_type'),
|
||||
sharedTextMimeTypes,
|
||||
'desktop shell export text MIME types',
|
||||
);
|
||||
assertSameList(
|
||||
extractRustStringMatchArms(rustHostSource, 'export_image_extension'),
|
||||
sharedImageMimeTypes,
|
||||
|
||||
@@ -76,6 +76,13 @@ pub(crate) fn export_text_payload(
|
||||
.get("content")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "content is required"))?;
|
||||
if normalize_export_text_mime_type(payload.get("mimeType").and_then(Value::as_str)).is_none() {
|
||||
return Err(failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"mimeType must be an allowed text type",
|
||||
));
|
||||
}
|
||||
|
||||
if content.len() > EXPORT_TEXT_MAX_BYTES {
|
||||
return Err(failed(
|
||||
@@ -108,6 +115,17 @@ fn import_text_mime_type(path: &Path) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_export_text_mime_type(value: Option<&str>) -> Option<&'static str> {
|
||||
match value.map(|mime_type| mime_type.to_ascii_lowercase()) {
|
||||
None => Some("text/plain"),
|
||||
Some(mime_type) if mime_type == "text/plain" => Some("text/plain"),
|
||||
Some(mime_type) if mime_type == "text/markdown" => Some("text/markdown"),
|
||||
Some(mime_type) if mime_type == "text/csv" => Some("text/csv"),
|
||||
Some(mime_type) if mime_type == "application/json" => Some("application/json"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_document_mime_type(path: &Path) -> Option<&'static str> {
|
||||
match path
|
||||
.extension()
|
||||
@@ -631,6 +649,23 @@ mod tests {
|
||||
assert_eq!(error.message, "content exceeds file export size limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_text_payload_rejects_non_text_mime_type() {
|
||||
let mut invalid = request("file.exportText");
|
||||
invalid.payload = Some(json!({
|
||||
"fileName": "作品记录.txt",
|
||||
"content": "暖灯猫街",
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
|
||||
let response = export_text_payload(&invalid).expect_err("invalid MIME");
|
||||
|
||||
assert!(!response.ok);
|
||||
let error = response.error.expect("error");
|
||||
assert_eq!(error.code, "invalid_request");
|
||||
assert_eq!(error.message, "mimeType must be an allowed text type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_export_text_file_persists_utf8_content() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
|
||||
@@ -647,6 +647,15 @@ for (const boundaryImport of sharedPayloadBoundaryImports) {
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
!hostBridgeSource.includes(
|
||||
'HOST_BRIDGE_TEXT_MIME_TYPE_SET.has(mimeType as HostBridgeTextMimeType)',
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'mobile shell file.exportText must validate MIME against the shared text MIME set',
|
||||
);
|
||||
}
|
||||
|
||||
const forbiddenLocalPayloadBoundaryDeclarations = [
|
||||
'EXPORT_TEXT_MAX_BYTES',
|
||||
|
||||
@@ -1021,6 +1021,22 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('file.exportText 拒绝非文本 MIME', async () => {
|
||||
const response = await send(
|
||||
request('file.exportText', {
|
||||
fileName: '作品记录.txt',
|
||||
content: '暖灯猫街',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
);
|
||||
|
||||
const failedResponse = expectFailed(response);
|
||||
|
||||
expect(failedResponse.error.code).toBe('invalid_request');
|
||||
expect(writtenFiles).toEqual([]);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('file.importText 调起系统文档选择器并返回受控文本数据', async () => {
|
||||
fileTexts.set('file:///private/mobile/story.md', '暖灯猫街');
|
||||
vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValue({
|
||||
|
||||
@@ -261,7 +261,14 @@ export async function exportTextFile(
|
||||
}
|
||||
|
||||
const fileName = normalizeHostBridgeExportFileName(exportPayload?.fileName);
|
||||
const mimeType = exportPayload?.mimeType || 'text/plain';
|
||||
const rawMimeType = exportPayload?.mimeType;
|
||||
const mimeType =
|
||||
typeof rawMimeType === 'string'
|
||||
? rawMimeType.toLowerCase()
|
||||
: 'text/plain';
|
||||
if (!HOST_BRIDGE_TEXT_MIME_TYPE_SET.has(mimeType as HostBridgeTextMimeType)) {
|
||||
throw invalidRequest('mimeType must be an allowed text type');
|
||||
}
|
||||
const file = new File(Paths.cache, fileName);
|
||||
file.write(content);
|
||||
await Sharing.shareAsync(file.uri, {
|
||||
|
||||
@@ -2571,7 +2571,7 @@
|
||||
## 2026-06-19 HostBridge 载荷边界单一来源
|
||||
|
||||
- 背景:文件导入导出、剪贴板、角标、本地通知和 request id 都已经在 Expo 与 Tauri 两套壳里有运行时校验;如果 MIME 清单、字节上限或文本长度只靠人工同步,新增文件类型或调整上限时会出现 H5 契约、移动壳和桌面壳互相漂移。
|
||||
- 决策:`packages/shared/src/contracts/hostBridge.ts` 是 HostBridge 载荷边界的声明来源,导出文本 / 图片 / 音频 MIME 清单、文档导入 MIME 清单、导入 / 导出字节上限、导出文件名 fallback / 长度上限、request id 长度、角标上限、剪贴板文本长度和本地通知标题 / 正文长度。Expo 移动壳必须直接导入这些共享常量,`apps/mobile-shell/scripts/check-config.mjs` 会拒绝移动壳重新本地声明文件大小或 MIME 清单;移动壳 `file.importText` / `file.importDocument` / `file.importAudio` 必须在读取文本内容或 base64 前,通过 picker `size` 或 Expo `File.size` 拿到可信 byte count 并完成上限校验,无法拿到可信大小时直接拒绝导入。Tauri 桌面壳按 Rust 运行时代码镜像实现,`apps/desktop-shell/scripts/check-config.mjs` 必须反查共享契约并拒绝漂移。
|
||||
- 决策:`packages/shared/src/contracts/hostBridge.ts` 是 HostBridge 载荷边界的声明来源,导出文本 / 图片 / 音频 MIME 清单、文档导入 MIME 清单、导入 / 导出字节上限、导出文件名 fallback / 长度上限、request id 长度、角标上限、剪贴板文本长度和本地通知标题 / 正文长度。Expo 移动壳必须直接导入这些共享常量,`apps/mobile-shell/scripts/check-config.mjs` 会拒绝移动壳重新本地声明文件大小或 MIME 清单;移动壳 `file.importText` / `file.importDocument` / `file.importAudio` 必须在读取文本内容或 base64 前,通过 picker `size` 或 Expo `File.size` 拿到可信 byte count 并完成上限校验,无法拿到可信大小时直接拒绝导入。`file.exportText` 的可选 `mimeType` 只能来自 `HOST_BRIDGE_TEXT_MIME_TYPES`,缺省为 `text/plain`,Expo 与 Tauri 都必须拒绝图片、音频或二进制 MIME,避免 H5 通过文本导出通道伪装落盘;两端 config check 必须反查该边界。Tauri 桌面壳按 Rust 运行时代码镜像实现,`apps/desktop-shell/scripts/check-config.mjs` 必须反查共享契约并拒绝漂移。
|
||||
- 影响范围:`packages/shared/src/contracts/hostBridge.ts`、`apps/mobile-shell/src/host-bridge/files.ts`、`apps/mobile-shell/scripts/check-config.mjs`、`apps/desktop-shell/src-tauri/src/host_bridge/`、`apps/desktop-shell/scripts/check-config.mjs`、Expo / Tauri HostBridge 方案文档。
|
||||
- 验证方式:`npm run mobile-shell:typecheck`、`npm run desktop-shell:typecheck`、`npm run test -- packages/shared/src/contracts/hostBridge.test.ts`、`npm run check:native-shells`、`npm run check:encoding`、`git diff --check`。
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ Tauri 桌面壳启动时必须按 `label="main"` 解析 `tauri.conf.json` 主窗
|
||||
- `reloadHostWebView()`:原生 App 宿主的受控 WebView 刷新入口。H5 只能请求刷新当前承载主站的宿主 WebView;Expo 移动壳调用当前 `react-native-webview` 的 `reload()`,Tauri 桌面壳调用主 `WebviewWindow.reload()`。该能力不接受 payload,不开放任意 URL 导航、脚本执行、Tauri guest API 或 RN WebView ref;成功只表示宿主已发起刷新,刷新后当前 H5 上下文会卸载。`AuthGate` 在登录态从未登录变为已登录、或从已登录变为未登录时优先调用该能力刷新当前容器;宿主未声明、返回失败或不可用时再回退浏览器 `window.location.reload()`。
|
||||
- `openHostExternalUrl()`:原生 App 宿主的受控外链入口。H5 中需要离开主站的外链在 `native_app` 下先通过 `app.openExternalUrl` 请求宿主系统浏览器打开;只允许 `http:`、`https:`、`mailto:`、`tel:`,相对路径会先归一化到当前站点绝对 URL。宿主不可用或拒绝时回退浏览器外链行为,普通浏览器和小程序保持原有 `<a>` 语义。H5 支付链接和微信 OAuth 登录授权 URL 也走该入口:原生壳未声明真实 `payment.request` / `auth.requestLogin` 前,微信 H5 支付 URL 和后端返回的微信登录授权 URL 优先交给宿主系统浏览器,宿主未处理时才回退当前 WebView 跳转;不得把 H5 支付或网页登录伪装成已完成的原生支付 / 原生登录。
|
||||
- `navigateHostNativePage()`:受控跳转宿主页,供订阅授权、支付、登录和内置独立 H5 体验入口等 adapter 复用。Expo 移动壳首版只接受同源 H5 route 并切换 WebView URL;Tauri 桌面壳同样只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内跳转。平台首页的儿童动作热身 Demo 入口在 `native_app` 且宿主声明 `navigation.openNativePage` 时必须优先走该 facade 跳转 `/child-motion-demo`,普通浏览器、小程序和未声明能力的裁剪壳才回退浏览器跳转。真正原生页面、登录和支付能力必须等对应 SDK / 页面接入后再声明支持。
|
||||
- `exportHostTextFile()`:原生 App 宿主的受控文本导出入口。Expo 移动壳通过 `file.exportText` 写入缓存文本文件并交给系统分享 / 保存面板;Tauri 桌面壳通过 `file.exportText` 打开系统保存对话框并写入用户选择的文件。文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数,不把本机绝对路径暴露给 H5;系统分享不可用或用户取消时返回明确错误,由 H5 fallback 承接。创作 Agent 工作台在 `native_app` 且声明该能力时提供会话 Markdown 导出入口,导出内容只来自当前 H5 已持有的会话标题、摘要、进度、锚点、消息、流式回复和输入草稿,并在 H5 侧先按同一 5 MiB 上限做 UTF-8 byte 校验;普通浏览器、小程序和未声明能力的裁剪壳不展示该入口。
|
||||
- `exportHostTextFile()`:原生 App 宿主的受控文本导出入口。Expo 移动壳通过 `file.exportText` 写入缓存文本文件并交给系统分享 / 保存面板;Tauri 桌面壳通过 `file.exportText` 打开系统保存对话框并写入用户选择的文件。文件名必须清洗,单次文本不超过 5 MiB,可选 MIME 只能来自共享契约 `HOST_BRIDGE_TEXT_MIME_TYPES`,未传时默认为 `text/plain`,非文本 MIME 必须拒绝,不能借文本导出通道伪装成图片、音频或二进制文件;成功只返回文件名和字节数,不把本机绝对路径暴露给 H5;系统分享不可用或用户取消时返回明确错误,由 H5 fallback 承接。创作 Agent 工作台在 `native_app` 且声明该能力时提供会话 Markdown 导出入口,导出内容只来自当前 H5 已持有的会话标题、摘要、进度、锚点、消息、流式回复和输入草稿,并在 H5 侧先按同一 5 MiB 上限做 UTF-8 byte 校验;普通浏览器、小程序和未声明能力的裁剪壳不展示该入口。
|
||||
- `importHostTextFile()`:原生 App 宿主的受控文本导入入口。Expo 移动壳通过 Expo DocumentPicker 打开系统文档选择器,Tauri 桌面壳通过系统文件选择框读取用户选择的文本文件;两端都只接受 `text/plain`、`text/markdown`、`text/csv`、`application/json` 或对应扩展名,单次不超过 5 MiB,成功只返回清洗后的文件名、MIME、UTF-8 文本内容和字节数,不暴露设备本地 URI 或本机绝对路径,也不开放通用文件系统能力;宿主必须在读取文本内容前拿到可信 byte count 并完成上限校验,移动壳在 picker 缺少 `size` 时改用 Expo `File.size`,仍拿不到可信大小时直接拒绝导入;用户取消时由 H5 facade 归为 `false`。创作 Agent 工作台在 `native_app` 且声明该能力时优先调用宿主文本导入,并把结果转换成现有浏览器 `File` 后继续复用后端 `/api/runtime/creation-agent/document-inputs/parse` 解析链路;普通浏览器、小程序和未声明能力的裁剪壳继续使用原文件输入。
|
||||
- `importHostDocumentFile()`:原生 App 宿主的受控文档导入入口。Expo 移动壳通过 Expo DocumentPicker,Tauri 桌面壳通过系统文件选择框读取用户选择的文档副本;两端都只接受 `text/plain`、`text/markdown`、`text/csv`、`application/json`、`application/vnd.openxmlformats-officedocument.wordprocessingml.document` 或对应 `.txt` / `.md` / `.markdown` / `.csv` / `.json` / `.docx` 扩展名,单次不超过 5 MiB。成功只返回清洗后的文件名、MIME、base64 内容和字节数,不暴露设备本地 URI、本机绝对路径或通用文件系统能力;宿主必须在读取 base64 前拿到可信 byte count 并完成上限校验,移动壳在 picker 缺少 `size` 时改用 Expo `File.size`,仍拿不到可信大小时直接拒绝导入。创作 Agent 工作台在 `native_app` 且声明该能力时优先调用宿主文档导入,把返回 base64 转换成现有浏览器 `File` 后继续调用 `/api/runtime/creation-agent/document-inputs/parse`;旧壳只声明 `file.importText` 时才回退到文本导入,普通浏览器、小程序和未声明能力的裁剪壳继续使用原文件输入。该能力不在前端解析 DOCX,也不绕过后端文档解析、大小校验或错误口径。
|
||||
- `exportHostImageFile()`:原生 App 宿主的受控图片导出入口。H5 只传自己生成的图片 `base64Data`、清洗后的文件名和允许的 `image/png` / `image/jpeg` / `image/webp` MIME;Expo 移动壳写入缓存图片后交给系统分享 / 保存面板,Tauri 桌面壳打开系统保存对话框并写入图片字节。单次图片不超过 5 MiB,成功只返回文件名和字节数,不回传本机绝对路径。当前分享卡下载在 native app 中优先走 `file.exportImage`,宿主未声明时保留浏览器下载路径。
|
||||
|
||||
@@ -479,7 +479,7 @@ export function normalizeHostBridgeClipboardText(
|
||||
export type FileExportTextPayload = {
|
||||
fileName: string;
|
||||
content: string;
|
||||
mimeType?: string;
|
||||
mimeType?: HostBridgeTextMimeType;
|
||||
};
|
||||
|
||||
export type FileExportTextResult = {
|
||||
|
||||
Reference in New Issue
Block a user