fix(desktop): unpack and verify native Office conversion

This commit is contained in:
07akioni committed 2026-09-18 16:25:29 +08:00
1 parent bedcb7b58c
commit 54d46ad4d4
19 files changed
+304 -28

No files matched your search

+2
View File
@@ -9,9 +9,11 @@ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
import * as desktopOffice from './office.ts'
import { installDesktopUpdateTaskControl } from './update-tasks.ts'
import { installOfficeEngineResolution } from './office-engine.ts'
async function main(): Promise<void> {
const runtimeDir = process.argv[2] as string
installOfficeEngineResolution(runtimeDir)
const projectDir = process.argv[3] as string
const installAnchor = join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json')
const profile = loadProfileDirectory('dsh', projectDir, installAnchor)
+26
View File
@@ -0,0 +1,26 @@
/** Resolve packaged Office engine manifests from their complete, unpacked resource directories. */
import { registerHooks, type ModuleHooks } from 'node:module'
import { realpathSync } from 'node:fs'
import { basename, dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
/**
* Keep engine executable and resource paths usable by native child processes outside Electron.
* @param runtimeDir - Prepared or ASAR-contained dsh runtime directory.
* @returns Installed resolver for the Host lifetime, or undefined for a non-ASAR runtime.
*/
export function installOfficeEngineResolution(runtimeDir: string): ModuleHooks | undefined {
if (basename(dirname(runtimeDir)) !== 'app.asar') return undefined
const root = realpathSync(runtimeDir)
const archive = dirname(root)
const source = pathToFileURL(join(root, 'node_modules', '@deepseek-ai', 'libreoffice-kit-')).href
const destination = pathToFileURL(join(`${archive}.unpacked`, 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit-')).href
return registerHooks({
resolve(specifier, context, nextResolve) {
const resolved = nextResolve(specifier, context)
if (!specifier.startsWith('@deepseek-ai/libreoffice-kit-') || !resolved.url.startsWith(source)) return resolved
const physical = realpathSync(fileURLToPath(destination + resolved.url.slice(source.length)))
return { ...resolved, url: pathToFileURL(physical).href }
},
})
}
@@ -0,0 +1,53 @@
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire, type ModuleHooks } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { installOfficeEngineResolution } from '../src/office-engine.ts'
const roots: string[] = []
const hooks: ModuleHooks[] = []
afterEach(() => {
for (const hook of hooks.splice(0)) hook.deregister()
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'desktop-office-resolution-'))
roots.push(root)
const runtime = join(root, 'app.asar', 'dsh')
const manifest = 'node_modules/@deepseek-ai/libreoffice-kit-darwin-arm64/package.json'
for (const base of [runtime, join(root, 'app.asar.unpacked', 'dsh')]) {
const path = join(base, manifest)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, '{"name":"@deepseek-ai/libreoffice-kit-darwin-arm64"}')
}
const api = join(runtime, 'node_modules/@deepseek-ai/libreoffice-kit/package.json')
mkdirSync(dirname(api), { recursive: true })
writeFileSync(api, '{"name":"@deepseek-ai/libreoffice-kit"}')
const require = createRequire(join(runtime, 'package.json'))
const hook = installOfficeEngineResolution(runtime)!
hooks.push(hook)
return { root, runtime, manifest, require }
}
it('resolves engine manifests to physical directories and leaves unrelated modules alone', () => {
const f = fixture()
expect(f.require.resolve('@deepseek-ai/libreoffice-kit-darwin-arm64/package.json'))
.toBe(realpathSync(join(f.root, 'app.asar.unpacked', 'dsh', f.manifest)))
expect(f.require.resolve('node:fs')).toBe('node:fs')
expect(f.require.resolve('@deepseek-ai/libreoffice-kit/package.json'))
.toBe(realpathSync(join(f.runtime, 'node_modules/@deepseek-ai/libreoffice-kit/package.json')))
})
it('rejects an engine missing from the unpacked tree instead of using its archived copy', () => {
const f = fixture()
rmSync(join(f.root, 'app.asar.unpacked'), { recursive: true })
expect(() => f.require.resolve('@deepseek-ai/libreoffice-kit-darwin-arm64/package.json')).toThrow()
})
it('leaves a prepared runtime without an archive unchanged', () => {
const root = mkdtempSync(join(tmpdir(), 'desktop-office-prepared-'))
roots.push(root)
expect(installOfficeEngineResolution(join(root, 'dsh'))).toBeUndefined()
})
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/README.md
README.md: 5de3550de473cb71704025e1d60057611b15987c
README.zh.md: 057094c80e1197e0216f660ea788dabc0d436573
README.md: d6c28e845d639116901463bedc9a0b512d97c78a
README.zh.md: 695c73183e14015b97011027685a2eb3ee9887e1
+2 -2
View File
@@ -144,9 +144,9 @@ Each target owns its packed package inputs, prepared runtime, package set, dsh t
Desktop packs workspace packages locally and installs external dependencies through the target's bundled Node and pnpm. [Desktop's file policy](scripts/runtime-file-policy.ts) then filters the immutable `resources/app.asar/dsh/node_modules` copy before signing and integrity sealing. It omits TypeScript declarations, recognized JavaScript/CSS/TypeScript source maps, TypeScript build caches, Domino's test directory, selected native compiler outputs, and node-pty prebuilds for other platforms. It preserves runtime JavaScript, native modules and their DLL/EXE helpers, WASM, unknown assets, licenses, and notices. Dependency manifests pass through electron-builder's metadata cleanup before integrity sealing, so archiving preserves their recorded bytes. The policy does not alter npm tarballs, the bundled package manager, or user-installed plugin files.
The [Office conversion provider](../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. Engine assets, licenses, and notices remain in the runtime dependency tree.
The [Office conversion provider](../../packages/document/office-to-pdf/README.md) carries the target’s declared native engine, or WASM when the kit declares no matching native target. Preparation rejects a missing target engine before packaging. Complete engine packages, including executables, libraries, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai/`. The Desktop Host resolves engine manifests to these physical directories so native subprocesses can read their resources; the JavaScript API remains in ASAR. On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in).
The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`.
The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python, converts each through the real Office provider, and checks PDF output. Every assembled application, including directory and unsigned Windows builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare file bytes and membership, recorded executable flags for archived files, and physical permissions for unpacked files. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization.
Windows release qualification also runs [directory and replacement checks](scripts/smoke-windows.ps1) manually after the Desktop build. Set `$Makensis`, `$SevenZip`, and `$PluginDir` to the pinned builder’s NSIS compiler, 7-Zip executable, and x86-unicode NSIS plugin directory. From the repository root, run the command below. It verifies directory replacement and rollback, and both locked-file replacement modes; it is not part of the unit-test lane.
+2 -2
View File
@@ -145,9 +145,9 @@ macOS arm64 命令要求 Apple Silicon。macOS x64 命令可以在 Intel macOS
Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安装外部依赖。[Desktop 文件策略](scripts/runtime-file-policy.ts)随后在签名和完整性封装前过滤不可变的 `resources/app.asar/dsh/node_modules` 副本。它排除 TypeScript 声明、已识别的 JavaScript/CSS/TypeScript source map、TypeScript 构建缓存、Domino 测试目录、选定的原生编译器输出和其他平台的 node-pty 预构建文件。它保留运行时 JavaScript、原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。
[Office 转换提供方](../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。引擎资源、许可证和 notices 保留在运行时依赖树中。
[Office 转换提供方](../../packages/document/office-to-pdf/README.zh.md)携带目标已声明的原生引擎;kit 未声明匹配原生目标时携带 WASM 引擎。准备阶段在打包前拒绝缺少目标引擎的情况。完整引擎包(包括可执行文件、库、数据、许可证和 notices)解包到 `resources/app.asar.unpacked/dsh/node_modules/@deepseek-ai/` 下。Desktop Host 将引擎清单解析到这些物理目录,使原生子进程能读取资源;JavaScript API 保留在 ASAR 中。macOS 上的原生辅助程序获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT entitlement。
打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。
打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,通过真实 Office 提供方逐一转换并检查 PDF 输出。每个组装后的应用(包括目录包和 Windows 未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查核对文件内容和文件清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。
Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检查](scripts/smoke-windows.ps1)。将 `$Makensis`、`$SevenZip` 和 `$PluginDir` 分别设为锁定版本构建器的 NSIS 编译器、7-Zip 可执行文件和 x86-unicode NSIS 插件目录。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。
@@ -63,7 +63,8 @@ export function createElectronBuilderConfig(
let primaryRuntimeDestination
let dshDestination
let windowsCode = []
const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep/bin/rg']
const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep/bin/rg',
'**/node_modules/@deepseek-ai/libreoffice-kit-*/**/*']
const windowsSigner = packagesWindows && !unsigned
? createWindowsTokenSigner({
certificateFile: env.DSH_DESKTOP_WINDOWS_CER_FILE,
+3 -2
View File
@@ -32,8 +32,9 @@ export async function signMacOSRuntime(root: string, appId: string, expected: Ma
const path = files[next++]
if (path === undefined) return
const identifier = `${appId}.runtime.${createHash('sha256').update(path).digest('hex')}`
const entitlements = path === 'dependencies/node/bin/node'
? join(import.meta.dirname, 'node-entitlements.plist') : undefined
const needsJit = path === 'dependencies/node/bin/node'
|| /^node_modules\/@deepseek-ai\/libreoffice-kit-darwin-(?:arm64|x64)\/bin\/libreoffice-kit$/u.test(path)
const entitlements = needsJit ? join(import.meta.dirname, 'jit-entitlements.plist') : undefined
await signMacOSRuntimeCode(join(root, path), identifier, expected, entitlements)
verifyMacOSRuntimeCode(join(root, path), expected)
}
+4 -1
View File
@@ -394,6 +394,7 @@ export async function packageTarget(
...desktopElectronBuilderArguments(target, true),
'--config.mac.notarize=false',
], electronBuilderEnv)
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
await packageMacOSArtifacts({
arch: target.arch,
version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'),
@@ -403,7 +404,9 @@ export async function packageTarget(
} else {
await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv))
}
if (signPrimaryRuntime) await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
if (target.platform !== 'darwin' || invocation.directory) {
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts', ...(invocation.unsigned ? ['--unsigned'] : [])], targetEnv)
}
if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)
}
+17 -7
View File
@@ -1,13 +1,23 @@
/** Validate the assembled Windows application before recording release completion. */
/** Validate the assembled application, including native Office conversion outside ASAR. */
import { join } from 'node:path'
import { resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
import { parseArgs } from 'node:util'
import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
import { readDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts'
import { verifyWindowsCode } from './windows-runtime-signature.mjs'
import { smokePreparedRuntime } from './smoke-prepared-runtime.ts'
import { resolveDesktopPackageTarget } from './package-target.ts'
const paths = resolveDesktopTargetBuildPaths()
const application = join(paths.artifacts, 'win-unpacked')
const descriptor = await verifyDesktopRuntime(paths.dsh, readDesktopRuntime(paths.dsh).release.version)
await verifyWindowsCode(application)
await smokePreparedRuntime(join(application, 'resources', 'app.asar', 'dsh'),
join(application, 'DeepSeek Harness.exe'), join(application, 'resources', 'runtime'), descriptor)
const { values } = parseArgs({ options: { unsigned: { type: 'boolean', default: false } }, allowPositionals: false })
const target = resolveDesktopBuildTarget()
const windows = target === 'win-x64'
if (values.unsigned && !windows) throw new Error('desktop smoke: unsigned artifacts require Windows')
const artifacts = values.unsigned ? join(paths.root, 'unsigned-artifacts') : paths.artifacts
const application = windows ? join(artifacts, 'win-unpacked')
: join(artifacts, target === 'mac-arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app', 'Contents')
const resources = join(application, windows ? 'resources' : 'Resources')
const executable = windows ? join(application, 'DeepSeek Harness.exe') : join(application, 'MacOS', 'DeepSeek Harness')
const descriptor = await verifyDesktopRuntime(paths.dsh, readDesktopRuntime(paths.dsh).release.version,
resolveDesktopPackageTarget(target))
if (windows && !values.unsigned) await verifyWindowsCode(application)
await smokePreparedRuntime(join(resources, 'app.asar', 'dsh'), executable, join(resources, 'runtime'), descriptor)
@@ -2,12 +2,13 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { basename, dirname, join, resolve } from 'node:path'
import { promisify } from 'node:util'
import { desktopNodeEnvironment } from '../src/node-environment.ts'
import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts'
import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
import { smokeDesktopRuntime } from './smoke-runtime.ts'
import { verifyRuntimeArchive } from './verify-runtime-archive.ts'
/**
* Exercise real runtime files and Host composition, including an ASAR root when packaged.
@@ -15,7 +16,7 @@ import { smokeDesktopRuntime } from './smoke-runtime.ts'
* @param node Target Electron executable.
* @param resourcesRuntime External runtime directory beside the archive.
* @param descriptor Runtime descriptor already verified against the selected target, which may differ from the build host.
* @returns Resolves after payload checks, Host readiness and teardown.
* @returns Resolves after archive integrity, payload checks, Host startup, Office conversion and teardown.
*/
export async function smokePreparedRuntime(
root: string, node: string, resourcesRuntime: string, descriptor: DesktopRuntimeDescriptor,
@@ -24,6 +25,7 @@ export async function smokePreparedRuntime(
const environment = { ...scrubWindowsSigningEnvironment(process.env), NODE_OPTIONS: '',
NARB_NATIVE_CACHE_DIR: cache, NARB_DISABLE_NATIVE_CACHE: '0' }
try {
if (basename(dirname(root)) === 'app.asar') await verifyRuntimeArchive(dirname(root), descriptor.files)
const { stdout } = await promisify(execFile)(node, [
'--expose-internals', resolve(import.meta.dirname, '../tests/fixtures/runtime-payload-smoke.mjs'), root, resourcesRuntime,
], { timeout: 120_000, windowsHide: true,
+42 -2
View File
@@ -3,17 +3,22 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { fileURLToPath } from 'node:url'
import { readPrimaryRuntime, workspaceDependencyPaths } from '../../desktop-host/src/primary-runtime.ts'
import { DesktopHostProcess } from '../src/host-process.ts'
import { createPluginProfile } from '../src/project-manager.ts'
import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts'
/**
* Prove the final resource tree boots and serves its matching Web frontend.
* Check Host startup, its matching frontend, external plugins and real Office-to-PDF conversion.
* @param root - Materialized dsh resources.
* @param node - Prepared target Electron executable.
* @param runtime - Verified resource descriptor.
* @param environment - Credential-scrubbed build environment and private native cache.
* @param resourcesRuntime - Bundled interpreters outside the application archive.
* @returns Resolves after checks and teardown; rejects on a check or teardown failure.
*/
export async function smokeDesktopRuntime(
root: string, node: string, runtime: DesktopRuntimeDescriptor, environment: NodeJS.ProcessEnv, resourcesRuntime: string,
@@ -29,6 +34,13 @@ export async function smokeDesktopRuntime(
const pluginName = 'desktop-runtime-smoke-plugin'
const plugin = join(profile, 'node_modules', pluginName)
mkdirSync(plugin, { recursive: true })
const primary = join(resourcesRuntime, 'primary-runtime')
const dependencies = workspaceDependencyPaths(primary, await readPrimaryRuntime(primary))
await promisify(execFile)(dependencies.python, ['-I', '-B',
fileURLToPath(new URL('../tests/fixtures/office-conversion-inputs.py', import.meta.url)), home],
{ env: environment, timeout: 120_000, windowsHide: true })
const inputs = ['docx', 'xlsx', 'pptx'].map(extension => ({ extension,
bytes: readFileSync(join(home, `input.${extension}`)).toString('base64') }))
const cordis = runtime.sharedPackages.find(entry => entry.name === '@deepseek-ai/cordis')
if (cordis === undefined) throw new Error('desktop runtime: missing shared Cordis package')
writeFileSync(join(plugin, 'package.json'), JSON.stringify({
@@ -37,13 +49,29 @@ export async function smokeDesktopRuntime(
}))
writeFileSync(join(plugin, 'index.js'), `
import { Context } from '@deepseek-ai/cordis'
import { inspect } from 'node:util'
export function apply(ctx) {
if (!(ctx instanceof Context)) throw new Error('desktop runtime: external plugin loaded another Cordis instance')
ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke',
handler(_request, response) { response.end('plugin route ready') } }))
for (const input of ${JSON.stringify(inputs)}) {
ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke-office/' + input.extension,
async handler(_request, response) {
try {
const bytes = Buffer.from(input.bytes, 'base64')
const result = await ctx.officeToPdf.convert({ extension: input.extension, priority: 'foreground',
source: { key: 'desktop-smoke-' + input.extension, version: 'fixture', bytes: bytes.length,
async read() { return { bytes, version: 'fixture' } } } })
response.end(Buffer.from(result.pdf))
} catch (error) {
response.statusCode = 500
response.end(inspect(error, { depth: 5 }))
}
} }))
}
}
`)
writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n inject: [webServer]\n')
writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n inject: [webServer, officeToPdf]\n')
const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')) as {
dependencies: Record<string, string>
dsh: { profile: { bundles: string[] } }
@@ -64,6 +92,18 @@ export function apply(ctx) {
}
const pluginResponse = await fetch(new URL('/desktop-smoke', ready.url), { headers: { cookie } })
if (await pluginResponse.text() !== 'plugin route ready') throw new Error('desktop runtime: plugin HTTP route failed')
for (const { extension } of inputs) {
const converted = await fetch(new URL(`/desktop-smoke-office/${extension}`, ready.url), {
headers: { cookie }, signal: AbortSignal.timeout(120_000),
})
if (!converted.ok) throw new Error(`desktop runtime: ${extension} conversion failed: ${await converted.text()}`)
const pdf = Buffer.from(await converted.arrayBuffer())
if (!/^%PDF-\d\.\d/u.test(pdf.subarray(0, 8).toString())
|| !pdf.subarray(-1024).toString().trimEnd().endsWith('%%EOF')) {
throw new Error(`desktop runtime: invalid ${extension} PDF output`)
}
}
console.log('desktop runtime: DOCX, XLSX, PPTX to PDF passed')
} finally {
clearTimeout(timer)
await host.stop()
@@ -0,0 +1,36 @@
/** Verify runtime bytes and executable permissions using ASAR records and physical unpacked files. */
import { createHash } from 'node:crypto'
import { lstat } from 'node:fs/promises'
import { join } from 'node:path'
import { readAsar, type Node } from 'app-builder-lib/out/asar/asar.js'
import type { DesktopRuntimeFile } from '../src/runtime-tree.ts'
/**
* Compare the complete archived dsh tree with the sealed preparation inventory.
* @param archivePath - Application ASAR file beside its unpacked directory.
* @param expected - Verified preparation inventory, excluding the descriptor itself.
* @returns Resolves when bytes, file membership and meaningful executable permissions match.
*/
export async function verifyRuntimeArchive(archivePath: string, expected: readonly DesktopRuntimeFile[]): Promise<void> {
const archive = await readAsar(archivePath)
const files: DesktopRuntimeFile[] = []
async function visit(node: Node, path: string): Promise<void> {
if (node.link !== undefined) throw new Error(`desktop runtime: unexpected ASAR link ${path}`)
if (node.files !== undefined) {
for (const [name, child] of Object.entries(node.files)) await visit(child, path === '' ? name : `${path}/${name}`)
return
}
if (path === 'desktop-runtime.json') return
const name = join('dsh', ...path.split('/'))
const physical = node.unpacked === true ? await lstat(join(`${archivePath}.unpacked`, name)) : undefined
if (physical !== undefined && !physical.isFile()) throw new Error(`desktop runtime: unexpected unpacked entry ${path}`)
const body = await archive.readFile(name)
const executable = process.platform !== 'win32' && (physical !== undefined
? (physical.mode & 0o111) !== 0
: node.executable === true)
files.push({ path, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'), executable })
}
await visit(archive.getFile('dsh', false), '')
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
if (JSON.stringify(files) !== JSON.stringify(expected)) throw new Error('desktop runtime: ASAR integrity verification failed')
}
+20
View File
@@ -0,0 +1,20 @@
"""Create one-page Office inputs with the packaged authoring runtime."""
from pathlib import Path
import sys
from docx import Document
from openpyxl import Workbook
from pptx import Presentation
from pptx.util import Inches
root = Path(sys.argv[1])
document = Document()
document.add_paragraph("Desktop Office conversion 42")
document.save(root / "input.docx")
workbook = Workbook()
workbook.active.append(["Desktop Office conversion", 42])
workbook.save(root / "input.xlsx")
workbook.close()
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
slide.shapes.add_textbox(Inches(1), Inches(1), Inches(6), Inches(1)).text = "Desktop Office conversion 42"
presentation.save(root / "input.pptx")
-2
View File
@@ -16,8 +16,6 @@ assert.equal(process.versions.node, descriptor.release.nodeVersion, 'Run with th
assert.equal(process.platform, descriptor.platform)
assert.equal(process.arch, descriptor.arch)
const resourcesRuntime = process.argv[3] ?? join(dirname(root), 'runtime')
const { verifyDesktopRuntime } = await import('../../lib/types/runtime-tree.js')
await verifyDesktopRuntime(root, descriptor.release.version, { platform: process.platform, arch: process.arch })
const requireRuntime = createRequire(join(root, 'package.json'))
const scratch = mkdtempSync(join(tmpdir(), 'dsh-runtime-payload-'))
+8 -4
View File
@@ -47,14 +47,18 @@ it('awaits other signers before rejecting and permitting output cleanup', async
expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'b.node'), identity)
})
it('grants JIT only to the standalone Node interpreter', async () => {
it('grants JIT only to the standalone Node interpreter and native Office helpers', async () => {
const path = root()
mkdirSync(join(path, 'dependencies/node/bin'), { recursive: true })
const node = join(path, 'dependencies/node/bin/node')
const addon = join(path, 'addon.node')
for (const file of [node, addon]) writeFileSync(file, Buffer.from('cffaedfe00000000', 'hex'))
const helpers = ['arm64', 'x64'].map(arch => join(path, 'node_modules/@deepseek-ai', `libreoffice-kit-darwin-${arch}`, 'bin/libreoffice-kit'))
for (const helper of helpers) mkdirSync(join(helper, '..'), { recursive: true })
for (const file of [node, addon, ...helpers]) writeFileSync(file, Buffer.from('cffaedfe00000000', 'hex'))
await signMacOSRuntime(path, 'com.example.app', identity)
expect(signMacOSRuntimeCode).toHaveBeenCalledWith(node, expect.any(String), identity,
join(import.meta.dirname, '../scripts/node-entitlements.plist'))
for (const file of [node, ...helpers]) {
expect(signMacOSRuntimeCode).toHaveBeenCalledWith(file, expect.any(String), identity,
join(import.meta.dirname, '../scripts/jit-entitlements.plist'))
}
expect(signMacOSRuntimeCode).toHaveBeenCalledWith(addon, expect.any(String), identity, undefined)
})
@@ -1,6 +1,7 @@
import { writeFileSync } from 'node:fs'
import { afterEach, expect, it, vi } from 'vitest'
import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts'
import { packageMacOSArtifacts } from '../scripts/package-macos.ts'
import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs'
import { prepareWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs'
@@ -12,6 +13,8 @@ vi.mock('../scripts/windows-signature-cache-directory.mjs', () => ({
resolveWindowsSignatureCacheDirectory: vi.fn(() => 'C:\\fixture-cache'),
}))
vi.mock('../scripts/package-macos.ts', () => ({ packageMacOSArtifacts: vi.fn() }))
// Keep the real orchestration and manifest reads; this suite owns no release directories or subprocesses.
vi.mock('node:fs', async importOriginal => ({
...await importOriginal<typeof import('node:fs')>(),
@@ -84,4 +87,32 @@ it.each(['--unsigned', '--prepare-only'])('keeps %s hardware-free and creates no
expect(withWindowsSigningStage).not.toHaveBeenCalled()
for (const call of run.run.mock.calls) expect(call[3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN')
expect(writeFileSync).not.toHaveBeenCalled()
expect(stages.includes('exec tsx scripts/smoke-packaged-runtime.ts --unsigned')).toBe(mode === '--unsigned')
})
it('checks the assembled macOS runtime before notarizing and recording the release', async () => {
const { run, stages } = supervisor()
vi.mocked(packageMacOSArtifacts).mockImplementationOnce(async () => {
expect(stages.at(-1)).toBe('exec tsx scripts/smoke-packaged-runtime.ts')
expect(writeFileSync).not.toHaveBeenCalled()
})
await packageTarget(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64'), environment, run)
expect(packageMacOSArtifacts).toHaveBeenCalledOnce()
expect(writeFileSync).toHaveBeenCalledOnce()
})
it('refuses macOS notarization and release records after an assembled-runtime failure', async () => {
const { run } = supervisor('exec tsx scripts/smoke-packaged-runtime.ts')
await expect(packageTarget(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64'), environment, run))
.rejects.toThrow('stage refused')
expect(packageMacOSArtifacts).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
})
it('checks macOS directory packages without writing a release record', async () => {
const { run, stages } = supervisor()
await packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--dir'], 'darwin', 'arm64'), environment, run)
expect(stages.at(-1)).toBe('exec tsx scripts/smoke-packaged-runtime.ts')
expect(packageMacOSArtifacts).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
})
+50 -1
View File
@@ -1,4 +1,4 @@
import { lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -10,6 +10,8 @@ import { readAsar } from 'app-builder-lib/out/asar/asar.js'
import { afterEach, expect, it, vi } from 'vitest'
import { prepareWindowsAsarUnpack, verifyWindowsAsarUnpack } from '../scripts/windows-asar-unpack.mjs'
import { createElectronBuilderConfig } from '../scripts/electron-builder-config.mjs'
import { verifyRuntimeArchive } from '../scripts/verify-runtime-archive.ts'
import { inventoryDesktopRuntime } from '../src/runtime-tree.ts'
vi.mock('../scripts/windows-sign.mjs', async importOriginal => ({
...await importOriginal<typeof import('../scripts/windows-sign.mjs')>(),
@@ -183,3 +185,50 @@ it.each([true, false])('validates the real builder hook for unsigned=%s', async
await expect(config.afterSign(input.context)).rejects.toThrow('PE bytes changed')
}
})
it.each([false, true])('keeps the complete Office engine outside ASAR with external source=%s', async (external) => {
const input = await fixture(external)
const engine = join('node_modules', '@deepseek-ai', 'libreoffice-kit-darwin-arm64')
const files = ['package.json', 'prebuilds.json', 'bin/libreoffice-kit', 'program/registry/main.xcd']
for (const file of files) {
const path = join(input.source, engine, file)
await mkdir(dirname(path), { recursive: true })
await writeFile(path, '{}')
}
const config = createElectronBuilderConfig({
DSH_DESKTOP_APP_ID: 'com.example.office', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com',
DSH_DESKTOP_UNSIGNED: '1',
}, 'win32', 'x64', input.source)
input.config.asarUnpack = [...config.asarUnpack]
await config.beforePack(input.context)
await packageFixture(input)
const archive = await readAsar(join(input.resources, 'app.asar'))
for (const file of files) {
expect(archive.getFile(join('dsh', engine, file), false).unpacked).toBe(true)
expect(await readFile(join(input.resources, 'app.asar.unpacked', 'dsh', engine, file), 'utf8')).toBe('{}')
}
})
it('verifies archived bytes and file membership against the preparation inventory', async () => {
const input = await fixture(false)
const expected = inventoryDesktopRuntime(input.source)
await packageFixture(input)
const archive = join(input.resources, 'app.asar')
await expect(verifyRuntimeArchive(archive, expected)).resolves.toBeUndefined()
await expect(verifyRuntimeArchive(archive, expected.slice(1))).rejects.toThrow('ASAR integrity')
await expect(verifyRuntimeArchive(archive, [...expected, { ...expected[0]!, path: 'missing' }])).rejects.toThrow('ASAR integrity')
await writeFile(join(input.resources, 'app.asar.unpacked/dsh/node_modules/foo/native.node'), 'tampered')
await expect(verifyRuntimeArchive(archive, expected)).rejects.toThrow('ASAR integrity')
})
it.skipIf(process.platform === 'win32')('checks packed executable records and physical unpacked permissions', async () => {
const input = await fixture(false)
for (const name of ['extensionless', 'native.node']) await chmod(join(input.source, 'node_modules/foo', name), 0o755)
const expected = inventoryDesktopRuntime(input.source)
await packageFixture(input)
const archive = join(input.resources, 'app.asar')
await expect(verifyRuntimeArchive(archive, expected)).resolves.toBeUndefined()
await expect(verifyRuntimeArchive(archive, expected.map(file => ({ ...file, executable: false })))).rejects.toThrow('ASAR integrity')
await chmod(join(input.resources, 'app.asar.unpacked/dsh/node_modules/foo/native.node'), 0o644)
await expect(verifyRuntimeArchive(archive, expected)).rejects.toThrow('ASAR integrity')
})