Skip to content

A full-featured download manager.

feat(build): stage standalone Server runtime (#1839)

Dr_rOot24e327d0fbd3
diff --git a/.dockerignore b/.dockerignore
index 3c3d3f13..68340baa 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,6 +1,21 @@
-node_modules
-dist
-.vite
.git
+.agents
+.claude
+.codex
+.vite
+dist
+release
+node_modules
docs
+e2e
*.log
+**/*.test.ts
+**/*.test.tsx
+!tests/check-third-party-notices.test.ts
+!tests/generate-third-party-notices.test.ts
+AGENTS.md
+CLAUDE.md
+obsidian-docs.config.json
+scripts/obsidian-docs-lib.mjs
+scripts/obsidian-docs.mjs
+tests/scripts/obsidian-docs.test.ts
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3b81e921..9d82e8d8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -143,7 +143,13 @@ jobs:
tests/scripts/snap-project.test.ts
tests/scripts/snap-store-channel.test.ts
tests/scripts/stage-electron-app.test.ts
+ tests/scripts/audit-server-runtime.test.ts
+ tests/scripts/docker-server-runtime.test.ts
+ tests/scripts/server-runtime-workflow.test.ts
+ tests/scripts/smoke-server-package.test.ts
+ tests/scripts/stage-server-app.test.ts
tests/scripts/verify-electron-package.test.ts
+ tests/scripts/verify-server-package.test.ts
tests/scripts/verify-update-artifacts.test.ts
tests/scripts/workflow-release-matrix.test.ts
tests/scripts/workflow-snap.test.ts
@@ -161,6 +167,55 @@ jobs:
continue-on-error: true
run: pnpm test
+ server-runtime:
+ name: Server runtime / ${{ matrix.target }}
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: linux-x64-musl
+ os: ubuntu-22.04
+ docker_arch: amd64
+ - target: linux-arm64-musl
+ os: ubuntu-22.04-arm
+ docker_arch: arm64
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 24
+
+ - name: Build staged Server image
+ run: >-
+ docker build
+ --platform linux/${{ matrix.docker_arch }}
+ --tag motrix-server-ci:${{ matrix.target }}
+ .
+
+ - name: Export Server size report
+ run: >-
+ docker build
+ --platform linux/${{ matrix.docker_arch }}
+ --target server-size-report
+ --output type=local,dest=release/size-reports
+ .
+
+ - name: Smoke staged Server image
+ run: >-
+ node scripts/smoke-server-image.mjs
+ --image motrix-server-ci:${{ matrix.target }}
+
+ - name: Upload Server size report
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: server-size-report-${{ matrix.target }}
+ path: release/size-reports/server-${{ matrix.target }}.json
+ if-no-files-found: error
+ retention-days: 14
+
rust-quality:
name: Rust / fmt, clippy, test
runs-on: ubuntu-24.04
diff --git a/Dockerfile b/Dockerfile
index 3d5f6e89..5adb1c3d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,44 +1,101 @@
# syntax=docker/dockerfile:1.7
-FROM node:22-alpine AS deps
+FROM node:24-alpine AS deps
RUN apk add --no-cache python3 make g++
WORKDIR /app
-COPY package.json pnpm-lock.yaml .npmrc ./
+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
+COPY packages/native-host/package.json ./packages/native-host/package.json
COPY scripts/postinstall.mjs ./scripts/postinstall.mjs
COPY scripts/fetch-engine.mjs ./scripts/fetch-engine.mjs
-# Server/Node image: no Electron rebuild, and no bundled aria2 either — the
-# runtime stage installs system aria2 (apk) and points MOTRIX_ARIA2_BIN at it,
-# so postinstall must skip BOTH stages (keeps the deps layer offline/hermetic).
+# The Server image uses system aria2 and never rebuilds for Electron. Electron's
+# locked install script is invoked explicitly in the build stage because the
+# legal inventory requires its license payload.
ENV MOTRIX_SKIP_ELECTRON_REBUILD=1 \
MOTRIX_SKIP_ENGINE_FETCH=1
-RUN corepack enable \
+RUN --mount=type=cache,id=motrix-pnpm-store,target=/pnpm/store \
+ corepack enable \
&& corepack prepare [email protected] --activate \
+ && pnpm config set store-dir /pnpm/store \
&& pnpm install --frozen-lockfile
+FROM node:24-alpine AS full-root-production-deps
+RUN apk add --no-cache python3 make g++
+WORKDIR /app
+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
+COPY packages/native-host/package.json ./packages/native-host/package.json
+COPY scripts/postinstall.mjs ./scripts/postinstall.mjs
+COPY scripts/fetch-engine.mjs ./scripts/fetch-engine.mjs
+ENV CI=true \
+ MOTRIX_SKIP_ELECTRON_REBUILD=1 \
+ MOTRIX_SKIP_ENGINE_FETCH=1
+RUN --mount=type=cache,id=motrix-pnpm-store,target=/pnpm/store \
+ corepack enable \
+ && corepack prepare [email protected] --activate \
+ && pnpm config set store-dir /pnpm/store \
+ && pnpm install --prod --frozen-lockfile --ignore-scripts
+
FROM deps AS build
+ARG TARGETARCH
WORKDIR /app
COPY . .
-RUN pnpm rebuild better-sqlite3 \
- && pnpm run check:third-party-notices \
- && pnpm build:server
+RUN node node_modules/electron/install.js
+RUN --mount=type=cache,id=motrix-builtins,target=/app/node_modules/.cache/motrix-builtins \
+ pnpm run check:third-party-notices \
+ && pnpm run build:server \
+ && node scripts/stage-server-app.mjs --platform linux --arch "${TARGETARCH}" --libc musl --strict \
+ && node scripts/verify-server-package.mjs --app-dir dist/server-app --platform linux --arch "${TARGETARCH}" --libc musl
-FROM build AS runtime-deps
-RUN pnpm prune --prod --ignore-scripts
+FROM scratch AS server-size-report
+COPY --from=build /app/release/size-reports/ /
+
+FROM node:24-alpine AS server-full-root-baseline
+RUN apk add --no-cache aria2 ca-certificates \
+ && rm -rf /usr/local/lib/node_modules/npm \
+ /usr/local/lib/node_modules/corepack \
+ /opt/yarn-v1.22.22 \
+ && rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
+ /usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \
+ && mkdir -p /data \
+ && chown node:node /data
+WORKDIR /app
+COPY --from=build --chown=node:node /app/package.json ./package.json
+COPY --from=build --chown=node:node /app/dist/server ./dist/server
+COPY --from=build --chown=node:node /app/dist/core/plugin/host ./dist/core/plugin/host
+COPY --from=build --chown=node:node /app/dist/renderer-web ./dist/renderer-web
+COPY --from=full-root-production-deps --chown=node:node /app/node_modules ./node_modules
+COPY --from=build --chown=node:node /app/extra/aria2.conf ./extra/aria2.conf
+COPY --from=build --chown=node:node /app/dist/builtin-plugins ./builtin-plugins
+COPY --from=build --chown=node:node /app/THIRD_PARTY_NOTICES.md ./THIRD_PARTY_NOTICES.md
+COPY --from=build --chown=node:node /app/THIRD_PARTY_NOTICES.zh-CN.md ./THIRD_PARTY_NOTICES.zh-CN.md
+COPY --from=build --chown=node:node /app/THIRD_PARTY_LICENSES ./THIRD_PARTY_LICENSES
+COPY --from=build --chown=node:node /app/build/legal/THIRD_PARTY_DEPENDENCIES.md ./legal/THIRD_PARTY_DEPENDENCIES.md
+COPY --from=build --chown=node:node /app/build/legal/THIRD_PARTY_LICENSES.txt ./legal/THIRD_PARTY_LICENSES.txt
+COPY --from=build --chown=node:node /app/build/legal/sbom.spdx.json ./legal/sbom.spdx.json
+ENV YARN_VERSION= \
+ NODE_ENV=production \
+ MOTRIX_DATA_DIR=/data \
+ MOTRIX_EXTRA_DIR=/app/extra \
+ MOTRIX_ARIA2_BIN=/usr/bin/aria2c \
+ MOTRIX_RENDERER_DIR=/app/dist/renderer-web \
+ MOTRIX_BUILTIN_PLUGIN_DIR=/app/builtin-plugins \
+ PORT=8080
+VOLUME /data
+EXPOSE 8080
+USER node
+CMD ["node", "dist/server/index.mjs"]
-FROM node:22-alpine AS runtime
-RUN apk add --no-cache aria2 ca-certificates
+FROM node:24-alpine AS runtime
+RUN apk add --no-cache aria2 ca-certificates \
+ && rm -rf /usr/local/lib/node_modules/npm \
+ /usr/local/lib/node_modules/corepack \
+ /opt/yarn-v1.22.22 \
+ && rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
+ /usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \
+ && mkdir -p /data \
+ && chown node:node /data
WORKDIR /app
-COPY --from=build /app/dist/server ./dist/server
-COPY --from=build /app/dist/renderer-web ./dist/renderer-web
-COPY --from=runtime-deps /app/node_modules ./node_modules
-COPY --from=build /app/extra/aria2.conf ./extra/aria2.conf
-COPY --from=build /app/dist/builtin-plugins ./builtin-plugins
-COPY --from=build /app/THIRD_PARTY_NOTICES.md ./THIRD_PARTY_NOTICES.md
-COPY --from=build /app/THIRD_PARTY_NOTICES.zh-CN.md ./THIRD_PARTY_NOTICES.zh-CN.md
-COPY --from=build /app/THIRD_PARTY_LICENSES ./THIRD_PARTY_LICENSES
-COPY --from=build /app/build/legal/THIRD_PARTY_DEPENDENCIES.md ./legal/THIRD_PARTY_DEPENDENCIES.md
-COPY --from=build /app/build/legal/THIRD_PARTY_LICENSES.txt ./legal/THIRD_PARTY_LICENSES.txt
-COPY --from=build /app/build/legal/sbom.spdx.json ./legal/sbom.spdx.json
-ENV NODE_ENV=production \
+COPY --from=build --chown=node:node /app/dist/server-app/ ./
+ENV YARN_VERSION= \
+ NODE_ENV=production \
MOTRIX_DATA_DIR=/data \
MOTRIX_EXTRA_DIR=/app/extra \
MOTRIX_ARIA2_BIN=/usr/bin/aria2c \
@@ -47,4 +104,5 @@ ENV NODE_ENV=production \
PORT=8080
VOLUME /data
EXPOSE 8080
+USER node
CMD ["node", "dist/server/index.mjs"]
diff --git a/package.json b/package.json
index d122f6e3..d41fc2dd 100644
--- a/package.json
+++ b/package.json
@@ -23,6 +23,11 @@
"verify:electron-package": "node scripts/verify-electron-package.mjs",
"smoke:electron-package": "node scripts/smoke-electron-package.mjs",
"build:server": "pnpm run build:builtin && pnpm run build:legal && vite build --config vite.server.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.web.config.ts",
+ "stage:server": "node scripts/stage-server-app.mjs",
+ "verify:server-package": "node scripts/verify-server-package.mjs",
+ "smoke:server-package": "node scripts/smoke-server-package.mjs",
+ "smoke:server-image": "node scripts/smoke-server-image.mjs",
+ "measure:server-images": "node scripts/measure-server-images.mjs",
"build:builtin": "node scripts/fetch-builtins.mjs",
"build:native-host": "node packages/native-host/build.mjs",
"build:legal": "node scripts/generate-third-party-notices.mjs",
diff --git a/scripts/audit-server-runtime.mjs b/scripts/audit-server-runtime.mjs
new file mode 100644
index 00000000..c0a45064
--- /dev/null
+++ b/scripts/audit-server-runtime.mjs
@@ -0,0 +1,275 @@
+import {
+ lstat,
+ readdir,
+ readFile,
+ realpath,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ externalPackageRoots,
+ normalizeRelativePath,
+ scanStaticModuleSpecifiers,
+ stringifySortedJson,
+ validateServerRuntimeContract,
+ validateServerSizeBudgets,
+} from './server-package-utils.mjs'
+
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..'
+)
+
+async function readJson(filePath, label) {
+ try {
+ return JSON.parse(await readFile(filePath, 'utf8'))
+ } catch (error) {
+ throw new Error(`${label} is unreadable: ${filePath}`, { cause: error })
+ }
+}
+
+function isInside(root, candidate) {
+ const relative = path.relative(root, candidate)
+ return (
+ relative.length > 0 &&
+ relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative)
+ )
+}
+
+async function inventoryTree(target, options = {}) {
+ const info = await stat(target)
+ if (info.isFile()) return { bytes: info.size, files: 1 }
+ let bytes = 0
+ let files = 0
+ async function walk(directory) {
+ const entries = await readdir(directory, { withFileTypes: true })
+ entries.sort((left, right) => left.name.localeCompare(right.name))
+ for (const entry of entries) {
+ if (options.skipNodeModules && entry.name === 'node_modules') continue
+ const entryPath = path.join(directory, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else if (entry.isFile()) {
+ const entryInfo = await stat(entryPath)
+ bytes += entryInfo.size
+ files += 1
+ } else {
+ throw new Error(`audit input contains a non-file entry: ${entryPath}`)
+ }
+ }
+ }
+ await walk(target)
+ return { bytes, files }
+}
+
+async function auditInputs(repoRoot, inputs, collectExternals) {
+ const records = []
+ const specifiers = new Set()
+ for (const input of inputs) {
+ const source = path.join(repoRoot, input.source)
+ const info = await lstat(source).catch(() => null)
+ if (info?.isSymbolicLink()) {
+ throw new Error(`top-level audit input is a symlink: ${input.source}`)
+ }
+ if (
+ !info ||
+ (input.type === 'file' ? !info.isFile() : !info.isDirectory())
+ ) {
+ throw new Error(`missing ${input.type} input: ${input.source}`)
+ }
+ if (collectExternals) {
+ const entry =
+ input.type === 'file' ? source : path.join(source, input.entry)
+ if (input.type === 'directory') {
+ if (!(await stat(entry).catch(() => null))?.isFile()) {
+ throw new Error(`missing build entry: ${input.source}/${input.entry}`)
+ }
+ }
+ if (input.scanExternals) {
+ const sourceText = await readFile(entry, 'utf8')
+ for (const specifier of scanStaticModuleSpecifiers(sourceText)) {
+ specifiers.add(specifier)
+ }
+ }
+ }
+ records.push({
+ source: input.source,
+ destination: input.destination,
+ type: input.type,
+ ...(input.entry ? { entry: input.entry } : {}),
+ ...(input.scanExternals !== undefined
+ ? { scanExternals: input.scanExternals }
+ : {}),
+ inventory: await inventoryTree(source),
+ })
+ }
+ return { records, specifiers: [...specifiers].sort() }
+}
+
+async function resolvePackageRoot(repoRoot, name) {
+ const require = createRequire(path.join(repoRoot, 'package.json'))
+ const candidates = [path.join(repoRoot, 'node_modules', name, 'package.json')]
+ try {
+ candidates.push(require.resolve(`${name}/package.json`))
+ } catch {
+ try {
+ let current = path.dirname(require.resolve(name))
+ while (current !== path.dirname(current)) {
+ candidates.push(path.join(current, 'package.json'))
+ current = path.dirname(current)
+ }
+ } catch {
+ // The caller reports the missing runtime root below.
+ }
+ }
+ for (const candidate of candidates) {
+ const info = await stat(candidate).catch(() => null)
+ if (!info?.isFile()) continue
+ const manifest = await readJson(candidate, `package ${name}`)
+ if (manifest.name !== name || typeof manifest.version !== 'string') continue
+ const root = await realpath(path.dirname(candidate))
+ if (root !== repoRoot && !isInside(repoRoot, root)) {
+ throw new Error(`resolved package ${name} escapes repository root`)
+ }
+ return { manifest, root }
+ }
+ throw new Error(`runtime root ${name} is not installed`)
+}
+
+function sumInventory(records) {
+ return records.reduce(
+ (total, record) => ({
+ bytes: total.bytes + record.inventory.bytes,
+ files: total.files + record.inventory.files,
+ }),
+ { bytes: 0, files: 0 }
+ )
+}
+
+export async function auditServerRuntime(options = {}) {
+ const repoRoot = await realpath(
+ path.resolve(options.repoRoot ?? REPOSITORY_ROOT)
+ )
+ const contract = validateServerRuntimeContract(
+ options.contract ??
+ (await readJson(
+ path.join(repoRoot, 'scripts/server-runtime-dependencies.json'),
+ 'server runtime contract'
+ ))
+ )
+ validateServerSizeBudgets(
+ options.budgets ??
+ (await readJson(
+ path.join(repoRoot, 'scripts/server-package-size-budgets.json'),
+ 'server size budgets'
+ ))
+ )
+ const rootManifest = await readJson(
+ path.join(repoRoot, 'package.json'),
+ 'root package manifest'
+ )
+ const build = await auditInputs(repoRoot, contract.buildInputs, true)
+ const resources = await auditInputs(repoRoot, contract.resourceInputs, false)
+ const observedRoots = externalPackageRoots(build.specifiers)
+ const unexpectedRoots = observedRoots.filter(
+ (name) => !contract.runtimeRoots.includes(name)
+ )
+ const staleRoots = contract.runtimeRoots.filter(
+ (name) => !observedRoots.includes(name)
+ )
+ if (unexpectedRoots.length > 0 || staleRoots.length > 0) {
+ throw new Error(
+ [
+ unexpectedRoots.length > 0
+ ? `unexpected runtime roots: ${unexpectedRoots.join(', ')}`
+ : undefined,
+ staleRoots.length > 0
+ ? `stale runtime roots: ${staleRoots.join(', ')}`
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join('; ')
+ )
+ }
+
+ const packages = []
+ for (const name of contract.runtimeRoots) {
+ const declaredVersion = rootManifest.dependencies?.[name]
+ if (typeof declaredVersion !== 'string') {
+ throw new Error(`runtime root ${name} is not a root dependency`)
+ }
+ const resolved = await resolvePackageRoot(repoRoot, name)
+ packages.push({
+ name,
+ declaredVersion,
+ version: resolved.manifest.version,
+ inventory: await inventoryTree(resolved.root, { skipNodeModules: true }),
+ source: normalizeRelativePath(
+ path.relative(repoRoot, resolved.root),
+ `source for ${name}`
+ ),
+ })
+ }
+
+ return {
+ schemaVersion: 1,
+ rootVersion: rootManifest.version,
+ rootProductionDeclarations: {
+ dependencies: Object.keys(rootManifest.dependencies ?? {}).length,
+ optionalDependencies: Object.keys(rootManifest.optionalDependencies ?? {})
+ .length,
+ },
+ externals: {
+ specifiers: build.specifiers,
+ roots: observedRoots,
+ },
+ buildInputs: build.records,
+ resourceInputs: resources.records,
+ controlledInputs: {
+ build: sumInventory(build.records),
+ resources: sumInventory(resources.records),
+ },
+ runtimeRoots: packages,
+ }
+}
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (argument === '--') continue
+ if (!['--report', '--root'].includes(argument)) {
+ throw new Error(`unknown argument: ${argument}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for ${argument}`)
+ }
+ options[argument.slice(2)] = value
+ index += 1
+ }
+ return options
+}
+
+async function main() {
+ const args = parseArguments(process.argv.slice(2))
+ const report = await auditServerRuntime({ repoRoot: args.root })
+ const output = stringifySortedJson(report)
+ if (args.report) {
+ const reportPath = path.resolve(args.report)
+ await writeFile(reportPath, output)
+ }
+ process.stdout.write(output)
+}
+
+const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : undefined
+if (invokedPath === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ console.error(error instanceof Error ? error.message : String(error))
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/measure-server-images.mjs b/scripts/measure-server-images.mjs
new file mode 100644
index 00000000..d5c9a38d
--- /dev/null
+++ b/scripts/measure-server-images.mjs
@@ -0,0 +1,284 @@
+import { execFile } from 'node:child_process'
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+import { stringifySortedJson } from './server-package-utils.mjs'
+
+const execFileAsync = promisify(execFile)
+const MAX_BUFFER = 4 * 1024 * 1024
+
+async function docker(args) {
+ const result = await execFileAsync('docker', args, {
+ encoding: 'utf8',
+ maxBuffer: MAX_BUFFER,
+ })
+ return result.stdout.trim()
+}
+
+const INVENTORY_SCRIPT = [
+ "import { lstat, readdir, readFile } from 'node:fs/promises'",
+ "import path from 'node:path'",
+ "const root = '/app'",
+ 'let appBytes = 0',
+ 'let dependencyBytes = 0',
+ 'let files = 0',
+ 'let symlinks = 0',
+ 'const packages = []',
+ 'const nativeBinaries = []',
+ 'function packageRecord(relative) {',
+ " const parts = relative.split('/')",
+ " if (parts.at(-1) !== 'package.json') return undefined",
+ " const index = parts.lastIndexOf('node_modules')",
+ ' if (index < 0) return undefined',
+ ' const first = parts[index + 1]',
+ ' if (!first) return undefined',
+ " const manifestIndex = first.startsWith('@') ? index + 3 : index + 2",
+ ' if (manifestIndex !== parts.length - 1) return undefined',
+ " const name = first.startsWith('@') ? first + '/' + parts[index + 2] : first",
+ " return { destination: parts.slice(0, manifestIndex).join('/'), name }",
+ '}',
+ 'async function walk(directory, relativeDirectory) {',
+ ' const entries = await readdir(directory, { withFileTypes: true })',
+ ' entries.sort((left, right) => left.name.localeCompare(right.name))',
+ ' for (const entry of entries) {',
+ ' const absolute = path.join(directory, entry.name)',
+ " const relative = relativeDirectory ? relativeDirectory + '/' + entry.name : entry.name",
+ ' const info = await lstat(absolute)',
+ ' if (info.isSymbolicLink()) { symlinks += 1; appBytes += info.size; continue }',
+ ' if (info.isDirectory()) { await walk(absolute, relative); continue }',
+ ' if (!info.isFile()) continue',
+ ' files += 1',
+ ' appBytes += info.size',
+ " if (relative.startsWith('node_modules/')) dependencyBytes += info.size",
+ " if (relative.endsWith('.node')) nativeBinaries.push({ path: relative, bytes: info.size })",
+ ' const record = packageRecord(relative)',
+ ' if (record) {',
+ " const manifest = JSON.parse(await readFile(absolute, 'utf8'))",
+ ' packages.push({ ...record, version: manifest.version })',
+ ' }',
+ ' }',
+ '}',
+ 'await walk(root, "")',
+ "const manifest = JSON.parse(await readFile('/app/package.json', 'utf8'))",
+ 'packages.sort((left, right) => left.destination.localeCompare(right.destination))',
+ 'nativeBinaries.sort((left, right) => left.path.localeCompare(right.path))',
+ 'const packageNames = [...new Set(packages.map((entry) => entry.name))].sort()',
+ 'console.log(JSON.stringify({',
+ ' appBytes,',
+ ' dependencyBytes,',
+ ' files,',
+ ' symlinks,',
+ ' packageInstances: packages.length,',
+ ' packageNames,',
+ ' directRoots: Object.keys(manifest.dependencies ?? {}).sort(),',
+ ' optionalRoots: Object.keys(manifest.optionalDependencies ?? {}).sort(),',
+ ' nativeBinaries,',
+ '}))',
+].join('\n')
+
+function reduction(baseline, optimized) {
+ const bytes = baseline - optimized
+ return {
+ bytes,
+ percent: baseline === 0 ? 0 : Number(((bytes / baseline) * 100).toFixed(2)),
+ }
+}
+
+export function buildServerImageComparison({
+ target,
+ samples,
+ baseline,
+ optimized,
+ stageReport,
+ dockerVersion,
+}) {
+ const baselineStable = samples.baseline.every(
+ (sample) => JSON.stringify(sample) === JSON.stringify(samples.baseline[0])
+ )
+ const optimizedStable = samples.optimized.every(
+ (sample) => JSON.stringify(sample) === JSON.stringify(samples.optimized[0])
+ )
+ const imageReduction = reduction(baseline.imageBytes, optimized.imageBytes)
+ const appReduction = reduction(baseline.appBytes, optimized.appBytes)
+ const dependencyReduction = reduction(
+ baseline.dependencyBytes,
+ optimized.dependencyBytes
+ )
+ const packageInstanceReduction =
+ baseline.packageInstances - optimized.packageInstances
+ const passed = Boolean(
+ baselineStable &&
+ optimizedStable &&
+ imageReduction.bytes > 0 &&
+ appReduction.bytes > 0 &&
+ dependencyReduction.bytes > 0 &&
+ packageInstanceReduction > 0 &&
+ stageReport?.passed === true
+ )
+ return {
+ schemaVersion: 1,
+ target,
+ passed,
+ sampleCount: samples.baseline.length,
+ samplesStable: { baseline: baselineStable, optimized: optimizedStable },
+ baseline,
+ optimized,
+ reduction: {
+ image: imageReduction,
+ app: appReduction,
+ dependencies: dependencyReduction,
+ packageInstances: packageInstanceReduction,
+ },
+ controlledStage: {
+ passed: stageReport?.passed === true,
+ budgets: stageReport?.budgets,
+ metrics: stageReport?.metrics,
+ },
+ toolVersions: {
+ docker: dockerVersion,
+ node: process.versions.node,
+ },
+ }
+}
+
+async function inspectImage(image) {
+ const metadata = JSON.parse(await docker(['image', 'inspect', image]))[0]
+ return {
+ image,
+ imageId: metadata.Id,
+ imageBytes: metadata.Size,
+ architecture: metadata.Architecture,
+ }
+}
+
+async function inventoryImage(image) {
+ const output = await docker([
+ 'run',
+ '--rm',
+ '--entrypoint',
+ 'node',
+ image,
+ '--input-type=module',
+ '--eval',
+ INVENTORY_SCRIPT,
+ ])
+ return JSON.parse(output)
+}
+
+async function measureImage(image, sampleCount) {
+ const metadata = await inspectImage(image)
+ const samples = []
+ for (let index = 0; index < sampleCount; index += 1) {
+ samples.push(await inventoryImage(image))
+ }
+ return {
+ summary: { ...metadata, ...samples[0] },
+ samples,
+ }
+}
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (index === 0 && argument === '--') continue
+ if (!argument.startsWith('--'))
+ throw new Error(`unknown argument: ${argument}`)
+ const key = argument.slice(2)
+ if (
+ ![
+ 'baseline-image',
+ 'optimized-image',
+ 'report',
+ 'samples',
+ 'stage-report',
+ 'target',
+ ].includes(key)
+ ) {
+ throw new Error(`unknown option: --${key}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for --${key}`)
+ }
+ options[key] = value
+ index += 1
+ }
+ for (const key of [
+ 'baseline-image',
+ 'optimized-image',
+ 'report',
+ 'stage-report',
+ 'target',
+ ]) {
+ if (!options[key]) throw new Error(`--${key} is required`)
+ }
+ return options
+}
+
+export async function measureServerImages(options) {
+ const sampleCount = options.samples ?? 3
+ if (
+ !Number.isSafeInteger(sampleCount) ||
+ sampleCount < 2 ||
+ sampleCount > 10
+ ) {
+ throw new Error('image measurement samples must be an integer from 2 to 10')
+ }
+ const stageReport = JSON.parse(await readFile(options.stageReport, 'utf8'))
+ if (stageReport.target?.key !== options.target) {
+ throw new Error(
+ 'controlled stage report target does not match image target'
+ )
+ }
+ const [baselineMeasurement, optimizedMeasurement, dockerVersion] =
+ await Promise.all([
+ measureImage(options.baselineImage, sampleCount),
+ measureImage(options.optimizedImage, sampleCount),
+ docker(['version', '--format', '{{.Server.Version}}']),
+ ])
+ const report = buildServerImageComparison({
+ target: options.target,
+ samples: {
+ baseline: baselineMeasurement.samples,
+ optimized: optimizedMeasurement.samples,
+ },
+ baseline: baselineMeasurement.summary,
+ optimized: optimizedMeasurement.summary,
+ stageReport,
+ dockerVersion,
+ })
+ await mkdir(path.dirname(path.resolve(options.report)), { recursive: true })
+ await writeFile(options.report, stringifySortedJson(report), { mode: 0o644 })
+ if (!report.passed) {
+ throw new Error(
+ 'Server image comparison did not pass material-reduction gates'
+ )
+ }
+ return report
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ const raw = parseArguments(process.argv.slice(2))
+ measureServerImages({
+ baselineImage: raw['baseline-image'],
+ optimizedImage: raw['optimized-image'],
+ report: raw.report,
+ samples: raw.samples ? Number.parseInt(raw.samples, 10) : undefined,
+ stageReport: raw['stage-report'],
+ target: raw.target,
+ })
+ .then((report) => {
+ console.log(
+ `Server image comparison passed: ${report.reduction.image.bytes} bytes (${report.reduction.image.percent}%)`
+ )
+ })
+ .catch((error) => {
+ console.error(error instanceof Error ? error.message : error)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/server-package-size-budgets.json b/scripts/server-package-size-budgets.json
new file mode 100644
index 00000000..8b90e918
--- /dev/null
+++ b/scripts/server-package-size-budgets.json
@@ -0,0 +1,10 @@
+{
+ "schemaVersion": 1,
+ "artifactBytes": 83886080,
+ "dependencyBytes": 54525952,
+ "packageInstances": 130,
+ "unexpectedRuntimeRoots": 0,
+ "unresolvedExternals": 0,
+ "foreignNativeBinaries": 0,
+ "betterSqlite3Prebuilds": 1
+}
diff --git a/scripts/server-package-utils.mjs b/scripts/server-package-utils.mjs
new file mode 100644
index 00000000..771f2ab9
--- /dev/null
+++ b/scripts/server-package-utils.mjs
@@ -0,0 +1,406 @@
+import { builtinModules } from 'node:module'
+import path from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+
+const CONTRACT_KEYS = [
+ 'buildInputs',
+ 'resourceInputs',
+ 'runtimeRoots',
+ 'schemaVersion',
+ 'supportedTargets',
+]
+const BUILD_INPUT_KEYS = [
+ 'destination',
+ 'entry',
+ 'scanExternals',
+ 'source',
+ 'type',
+]
+const RESOURCE_INPUT_KEYS = ['destination', 'source', 'type']
+const BUDGET_KEYS = [
+ 'artifactBytes',
+ 'betterSqlite3Prebuilds',
+ 'dependencyBytes',
+ 'foreignNativeBinaries',
+ 'packageInstances',
+ 'schemaVersion',
+ 'unexpectedRuntimeRoots',
+ 'unresolvedExternals',
+]
+const SUPPORTED_TARGETS = [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64-gnu',
+ 'linux-arm64-musl',
+ 'linux-x64-gnu',
+ 'linux-x64-musl',
+ 'win32-x64',
+]
+const SUPPORTED_PLATFORMS = new Set(['darwin', 'linux', 'win32'])
+const SUPPORTED_ARCHES = new Set(['arm64', 'x64'])
+const SUPPORTED_LIBCS = new Set(['gnu', 'musl'])
+const BUILTIN_MODULES = new Set([
+ ...builtinModules,
+ ...builtinModules.map((name) => `node:${name}`),
+])
+
+function assertRecord(value, label) {
+ if (value === null || Array.isArray(value) || typeof value !== 'object') {
+ throw new Error(`${label} must be an object`)
+ }
+ return value
+}
+
+function assertExactKeys(value, expected, label) {
+ const actual = Object.keys(value).sort()
+ if (isDeepStrictEqual(actual, [...expected].sort())) return
+ const unknown = actual.filter((key) => !expected.includes(key))
+ const missing = expected.filter((key) => !actual.includes(key))
+ if (unknown.length > 0) {
+ throw new Error(`${label} has unknown key: ${unknown.join(', ')}`)
+ }
+ throw new Error(`${label} is missing key: ${missing.join(', ')}`)
+}
+
+function assertInteger(value, label) {
+ if (!Number.isSafeInteger(value) || value < 0) {
+ throw new Error(`${label} must be a non-negative safe integer`)
+ }
+ return value
+}
+
+function assertSortedUniqueStrings(value, label) {
+ if (
+ !Array.isArray(value) ||
+ value.some((entry) => typeof entry !== 'string' || entry.length === 0)
+ ) {
+ throw new Error(`${label} must be an array of non-empty strings`)
+ }
+ const normalized = [...new Set(value)].sort()
+ if (!isDeepStrictEqual(value, normalized)) {
+ throw new Error(`${label} must contain unique strings in sorted order`)
+ }
+ return value
+}
+
+export function normalizeRelativePath(value, label = 'path') {
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(`${label} must be a non-empty string`)
+ }
+ const normalized = path.posix.normalize(value.replaceAll('\\', '/'))
+ if (
+ path.posix.isAbsolute(normalized) ||
+ normalized === '..' ||
+ normalized.startsWith('../')
+ ) {
+ throw new Error(`${label} must stay within its root: ${value}`)
+ }
+ return normalized.replace(/^\.\//, '')
+}
+
+function validateInputList(value, keys, label, withEntry) {
+ if (!Array.isArray(value) || value.length === 0) {
+ throw new Error(`${label} must be a non-empty array`)
+ }
+ const sources = []
+ const destinations = new Set()
+ for (const [index, rawInput] of value.entries()) {
+ const input = assertRecord(rawInput, `${label}[${index}]`)
+ assertExactKeys(input, keys, `${label}[${index}]`)
+ input.source = normalizeRelativePath(
+ input.source,
+ `${label}[${index}].source`
+ )
+ input.destination = normalizeRelativePath(
+ input.destination,
+ `${label}[${index}].destination`
+ )
+ if (!['directory', 'file'].includes(input.type)) {
+ throw new Error(`${label}[${index}].type must be directory or file`)
+ }
+ if (destinations.has(input.destination)) {
+ throw new Error(
+ `${label} has duplicate destination: ${input.destination}`
+ )
+ }
+ destinations.add(input.destination)
+ sources.push(input.source)
+ if (withEntry) {
+ if (input.type === 'directory') {
+ input.entry = normalizeRelativePath(
+ input.entry,
+ `${label}[${index}].entry`
+ )
+ } else if (input.entry !== null) {
+ throw new Error(`${label}[${index}].entry must be null for a file`)
+ }
+ if (typeof input.scanExternals !== 'boolean') {
+ throw new Error(`${label}[${index}].scanExternals must be a boolean`)
+ }
+ }
+ }
+ if (!isDeepStrictEqual(sources, [...sources].sort())) {
+ throw new Error(`${label} must be sorted by source`)
+ }
+ return value
+}
+
+export function validateServerRuntimeContract(value) {
+ const contract = assertRecord(value, 'server runtime contract')
+ assertExactKeys(contract, CONTRACT_KEYS, 'server runtime contract')
+ if (contract.schemaVersion !== 1) {
+ throw new Error('server runtime contract schemaVersion must be 1')
+ }
+ assertSortedUniqueStrings(contract.supportedTargets, 'supportedTargets')
+ if (!isDeepStrictEqual(contract.supportedTargets, SUPPORTED_TARGETS)) {
+ throw new Error(
+ `supportedTargets must be exactly: ${SUPPORTED_TARGETS.join(', ')}`
+ )
+ }
+ assertSortedUniqueStrings(contract.runtimeRoots, 'runtimeRoots')
+ validateInputList(contract.buildInputs, BUILD_INPUT_KEYS, 'buildInputs', true)
+ validateInputList(
+ contract.resourceInputs,
+ RESOURCE_INPUT_KEYS,
+ 'resourceInputs',
+ false
+ )
+ const destinations = [
+ ...contract.buildInputs.map((input) => input.destination),
+ ...contract.resourceInputs.map((input) => input.destination),
+ ]
+ if (new Set(destinations).size !== destinations.length) {
+ throw new Error('server runtime contract has duplicate input destinations')
+ }
+ return contract
+}
+
+export function validateServerSizeBudgets(value) {
+ const budgets = assertRecord(value, 'server size budgets')
+ assertExactKeys(budgets, BUDGET_KEYS, 'server size budgets')
+ if (budgets.schemaVersion !== 1) {
+ throw new Error('server size budgets schemaVersion must be 1')
+ }
+ for (const key of BUDGET_KEYS.filter((entry) => entry !== 'schemaVersion')) {
+ assertInteger(budgets[key], `server size budgets.${key}`)
+ }
+ if (budgets.betterSqlite3Prebuilds !== 1) {
+ throw new Error('server size budgets.betterSqlite3Prebuilds must be 1')
+ }
+ return budgets
+}
+
+function inferLinuxLibc() {
+ const report = process.report?.getReport?.()
+ return report?.header?.glibcVersionRuntime ? 'gnu' : 'musl'
+}
+
+export function serverTargetKey(platform, arch, libc) {
+ return platform === 'linux'
+ ? `${platform}-${arch}-${libc}`
+ : `${platform}-${arch}`
+}
+
+export function betterSqlite3PrebuildName(target) {
+ if (!target || typeof target !== 'object') {
+ throw new Error('Server package target is required')
+ }
+ if (target.platform === 'linux') {
+ if (
+ !SUPPORTED_ARCHES.has(target.arch) ||
+ !SUPPORTED_LIBCS.has(target.libc)
+ ) {
+ throw new Error('invalid Linux target for better-sqlite3')
+ }
+ const prefix = target.libc === 'musl' ? 'linuxmusl' : 'linux'
+ return `${prefix}-${target.arch}.node`
+ }
+ if (
+ !SUPPORTED_PLATFORMS.has(target.platform) ||
+ !SUPPORTED_ARCHES.has(target.arch)
+ ) {
+ throw new Error('invalid target for better-sqlite3')
+ }
+ return `${target.platform}-${target.arch}.node`
+}
+
+export function parseServerTarget(options = {}) {
+ const strict = options.strict === true || options.ci === true
+ const platform = options.platform ?? (strict ? undefined : process.platform)
+ const rawArch = options.arch ?? (strict ? undefined : process.arch)
+ const arch = rawArch === 'amd64' ? 'x64' : rawArch
+
+ if (!platform || !rawArch) {
+ throw new Error('Server package target requires --platform and --arch')
+ }
+ if (!SUPPORTED_PLATFORMS.has(platform) || !SUPPORTED_ARCHES.has(arch)) {
+ throw new Error(
+ `unsupported Server package platform/arch: ${platform}-${arch}`
+ )
+ }
+
+ let libc = options.libc
+ if (platform === 'linux') {
+ libc ??= strict ? undefined : inferLinuxLibc()
+ if (!libc || !SUPPORTED_LIBCS.has(libc)) {
+ throw new Error('Linux Server package target requires --libc gnu or musl')
+ }
+ } else if (libc !== undefined) {
+ throw new Error(`--libc is only valid for Linux Server package targets`)
+ }
+
+ const key = serverTargetKey(platform, arch, libc)
+ if (!SUPPORTED_TARGETS.includes(key)) {
+ throw new Error(
+ `unsupported Server package target ${key}; expected one of: ${SUPPORTED_TARGETS.join(', ')}`
+ )
+ }
+ return { platform, arch, ...(libc ? { libc } : {}), key }
+}
+
+export function packageNameFromSpecifier(specifier) {
+ if (
+ typeof specifier !== 'string' ||
+ specifier.length === 0 ||
+ specifier.startsWith('.') ||
+ specifier.startsWith('/') ||
+ specifier.startsWith('node:') ||
+ specifier.startsWith('#')
+ ) {
+ return undefined
+ }
+ const parts = specifier.split('/')
+ if (specifier.startsWith('@')) {
+ return parts.length >= 2 && parts[1] ? `${parts[0]}/${parts[1]}` : undefined
+ }
+ return parts[0] || undefined
+}
+
+function readStringToken(source, start) {
+ const quote = source[start]
+ let value = ''
+ for (let index = start + 1; index < source.length; index += 1) {
+ const character = source[index]
+ if (character === quote) return { value, end: index + 1 }
+ if (character === '\\') {
+ index += 1
+ if (index >= source.length) return undefined
+ value += source[index]
+ } else {
+ value += character
+ }
+ }
+ return undefined
+}
+
+function tokenizeJavaScript(source) {
+ const tokens = []
+ let index = 0
+ while (index < source.length) {
+ const character = source[index]
+ const next = source[index + 1]
+ if (/\s/.test(character)) {
+ index += 1
+ continue
+ }
+ if (character === '/' && next === '/') {
+ const end = source.indexOf('\n', index + 2)
+ index = end === -1 ? source.length : end + 1
+ continue
+ }
+ if (character === '/' && next === '*') {
+ const end = source.indexOf('*/', index + 2)
+ index = end === -1 ? source.length : end + 2
+ continue
+ }
+ if (character === '"' || character === "'" || character === '`') {
+ const token = readStringToken(source, index)
+ if (!token) break
+ tokens.push({ type: 'string', value: token.value })
+ index = token.end
+ continue
+ }
+ if (/[A-Za-z_$]/.test(character)) {
+ let end = index + 1
+ while (/[\w$]/.test(source[end] ?? '')) end += 1
+ tokens.push({ type: 'identifier', value: source.slice(index, end) })
+ index = end
+ continue
+ }
+ tokens.push({ type: 'punctuation', value: character })
+ index += 1
+ }
+ return tokens
+}
+
+export function scanStaticModuleSpecifiers(source) {
+ if (typeof source !== 'string') {
+ throw new Error('JavaScript source must be a string')
+ }
+ const tokens = tokenizeJavaScript(source)
+ const specifiers = new Set()
+ for (let index = 0; index < tokens.length; index += 1) {
+ const token = tokens[index]
+ if (token.type !== 'identifier') continue
+ if (token.value === 'require' || token.value === 'import') {
+ if (
+ tokens[index + 1]?.value === '(' &&
+ tokens[index + 2]?.type === 'string'
+ ) {
+ specifiers.add(tokens[index + 2].value)
+ continue
+ }
+ }
+ if (token.value !== 'import' && token.value !== 'export') continue
+ if (tokens[index + 1]?.type === 'string') {
+ specifiers.add(tokens[index + 1].value)
+ continue
+ }
+ for (let cursor = index + 1; cursor < tokens.length; cursor += 1) {
+ const candidate = tokens[cursor]
+ if (candidate.value === ';') break
+ if (
+ candidate.type === 'identifier' &&
+ candidate.value === 'from' &&
+ tokens[cursor + 1]?.type === 'string'
+ ) {
+ specifiers.add(tokens[cursor + 1].value)
+ break
+ }
+ }
+ }
+ return [...specifiers].sort()
+}
+
+export function externalPackageRoots(specifiers) {
+ const roots = new Set()
+ for (const specifier of specifiers) {
+ if (BUILTIN_MODULES.has(specifier)) continue
+ const root = packageNameFromSpecifier(specifier)
+ if (root) roots.add(root)
+ }
+ return [...roots].sort()
+}
+
+export function sortJson(value) {
+ if (Array.isArray(value)) return value.map((entry) => sortJson(entry))
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map((key) => [key, sortJson(value[key])])
+ )
+ }
+ return value
+}
+
+export function stringifySortedJson(value) {
+ return `${JSON.stringify(sortJson(value), null, 2)}\n`
+}
+
+export const serverPackageTargets = Object.freeze({
+ arches: [...SUPPORTED_ARCHES].sort(),
+ libcs: [...SUPPORTED_LIBCS].sort(),
+ platforms: [...SUPPORTED_PLATFORMS].sort(),
+ targets: [...SUPPORTED_TARGETS],
+})
diff --git a/scripts/server-runtime-dependencies.json b/scripts/server-runtime-dependencies.json
new file mode 100644
index 00000000..d5f449db
--- /dev/null
+++ b/scripts/server-runtime-dependencies.json
@@ -0,0 +1,99 @@
+{
+ "schemaVersion": 1,
+ "supportedTargets": [
+ "darwin-arm64",
+ "darwin-x64",
+ "linux-arm64-gnu",
+ "linux-arm64-musl",
+ "linux-x64-gnu",
+ "linux-x64-musl",
+ "win32-x64"
+ ],
+ "runtimeRoots": [
+ "@fastify/static",
+ "@fastify/websocket",
+ "@motrix/mdxp",
+ "@motrix/plugin-manifest-schema",
+ "ajv",
+ "better-sqlite3",
+ "bittorrent-peerid",
+ "chokidar",
+ "fastify",
+ "libsodium-wrappers",
+ "parse-torrent",
+ "pino",
+ "quickjs-emscripten",
+ "undici",
+ "uuid",
+ "vscode-jsonrpc",
+ "write-file-atomic",
+ "ws",
+ "yauzl",
+ "zod"
+ ],
+ "buildInputs": [
+ {
+ "source": "dist/core/plugin/host/quick-js-worker.cjs",
+ "destination": "dist/core/plugin/host/quick-js-worker.cjs",
+ "type": "file",
+ "entry": null,
+ "scanExternals": true
+ },
+ {
+ "source": "dist/renderer-web",
+ "destination": "dist/renderer-web",
+ "type": "directory",
+ "entry": "index.html",
+ "scanExternals": false
+ },
+ {
+ "source": "dist/server",
+ "destination": "dist/server",
+ "type": "directory",
+ "entry": "index.mjs",
+ "scanExternals": true
+ }
+ ],
+ "resourceInputs": [
+ {
+ "source": "THIRD_PARTY_LICENSES",
+ "destination": "THIRD_PARTY_LICENSES",
+ "type": "directory"
+ },
+ {
+ "source": "THIRD_PARTY_NOTICES.md",
+ "destination": "THIRD_PARTY_NOTICES.md",
+ "type": "file"
+ },
+ {
+ "source": "THIRD_PARTY_NOTICES.zh-CN.md",
+ "destination": "THIRD_PARTY_NOTICES.zh-CN.md",
+ "type": "file"
+ },
+ {
+ "source": "build/legal/THIRD_PARTY_DEPENDENCIES.md",
+ "destination": "legal/THIRD_PARTY_DEPENDENCIES.md",
+ "type": "file"
+ },
+ {
+ "source": "build/legal/THIRD_PARTY_LICENSES.txt",
+ "destination": "legal/THIRD_PARTY_LICENSES.txt",
+ "type": "file"
+ },
+ {
+ "source": "build/legal/sbom.spdx.json",
+ "destination": "legal/sbom.spdx.json",
+ "type": "file"
+ },
+ {
+ "source": "dist/builtin-plugins",
+ "destination": "builtin-plugins",
+ "type": "directory"
+ },
+ {
+ "source": "extra/aria2.conf",
+ "destination": "extra/aria2.conf",
+ "type": "file"
+ }
+ ]
+}
diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjs
new file mode 100644
index 00000000..2ba5f2d4
--- /dev/null
+++ b/scripts/smoke-server-image.mjs
@@ -0,0 +1,242 @@
+import { execFile } from 'node:child_process'
+import { pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+
+const execFileAsync = promisify(execFile)
+const DEFAULT_TIMEOUT_MS = 45_000
+const MAX_LOG_BYTES = 256 * 1024
+
+async function docker(args, options = {}) {
+ const result = await execFileAsync('docker', args, {
+ encoding: 'utf8',
+ maxBuffer: MAX_LOG_BYTES,
+ ...options,
+ })
+ return result.stdout.trim()
+}
+
+function delay(milliseconds) {
+ return new Promise((resolve) => setTimeout(resolve, milliseconds))
+}
+
+async function containerPort(name, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const output = await docker(['port', name, '8080/tcp']).catch(() => '')
+ const match = /^127\.0\.0\.1:(\d+)$/m.exec(output)
+ if (match) return Number(match[1])
+ await delay(100)
+ }
+ throw new Error('Docker did not publish the Server HTTP port')
+}
+
+async function containerExited(name) {
+ const state = await docker([
+ 'inspect',
+ '--format',
+ '{{json .State}}',
+ name,
+ ]).catch(() => '')
+ if (!state) return undefined
+ const parsed = JSON.parse(state)
+ return parsed.Running ? undefined : parsed
+}
+
+async function waitForHealth(name, url, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const exited = await containerExited(name)
+ if (exited) {
+ throw new Error(
+ `Server image exited before health check: code=${exited.ExitCode}`
+ )
+ }
+ try {
+ const response = await fetch(`${url}/healthz`)
+ if (response.ok && (await response.json()).ok === true) return
+ } catch {
+ // Container startup is still in progress.
+ }
+ await delay(100)
+ }
+ throw new Error(`Server image did not become healthy within ${timeoutMs}ms`)
+}
+
+async function assertOperatorAuth(url, token) {
+ const unauthenticated = await fetch(`${url}/rpc/query/image-smoke`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ args: [] }),
+ })
+ if (unauthenticated.status !== 401) {
+ throw new Error(
+ `unauthenticated image request returned ${unauthenticated.status}`
+ )
+ }
+ const status = await fetch(`${url}/rpc/auth/status`, {
+ headers: { authorization: `Bearer ${token}` },
+ })
+ if (!status.ok || (await status.json()).authed !== true) {
+ throw new Error('Docker image operator authentication failed')
+ }
+ const authenticated = await fetch(`${url}/rpc/query/image-smoke`, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ args: [] }),
+ })
+ if (authenticated.status !== 404) {
+ throw new Error(
+ `authenticated image request returned ${authenticated.status}`
+ )
+ }
+}
+
+const RUNTIME_PROBE = [
+ "import { createRequire } from 'node:module'",
+ "const require = createRequire('/app/package.json')",
+ "const manifest = require('/app/package.json')",
+ 'for (const name of Object.keys(manifest.dependencies).sort()) import.meta.resolve(name)',
+ "const Database = require('better-sqlite3')",
+ "const memory = new Database(':memory:')",
+ "memory.exec('CREATE TABLE smoke(value TEXT)')",
+ "memory.prepare('INSERT INTO smoke(value) VALUES (?)').run('memory-ok')",
+ "if (memory.prepare('SELECT value FROM smoke').get().value !== 'memory-ok') process.exit(2)",
+ 'memory.close()',
+ "const file = '/data/image-smoke.db'",
+ 'const disk = new Database(file)',
+ "disk.exec('CREATE TABLE smoke(value TEXT)')",
+ "disk.prepare('INSERT INTO smoke(value) VALUES (?)').run('disk-ok')",
+ 'disk.close()',
+ 'const reopened = new Database(file)',
+ "if (reopened.prepare('SELECT value FROM smoke').get().value !== 'disk-ok') process.exit(3)",
+ 'reopened.close()',
+].join(';')
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (index === 0 && argument === '--') continue
+ if (!argument.startsWith('--'))
+ throw new Error(`unknown argument: ${argument}`)
+ const key = argument.slice(2)
+ if (!['image', 'timeout-ms'].includes(key)) {
+ throw new Error(`unknown option: --${key}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for --${key}`)
+ }
+ options[key] = value
+ index += 1
+ }
+ if (!options.image) throw new Error('--image is required')
+ return options
+}
+
+export async function smokeServerImage(options) {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000) {
+ throw new Error('Server image smoke timeout must be at least 1000ms')
+ }
+ const image = options.image
+ const name = `motrix-server-smoke-${process.pid}-${Date.now()}`
+ const operatorToken = 'motrix-image-smoke-operator-token'
+ const startedAt = Date.now()
+ let created = false
+ try {
+ await docker([
+ 'run',
+ '--detach',
+ '--name',
+ name,
+ '--env',
+ `MOTRIX_OPERATOR_TOKEN=${operatorToken}`,
+ '--env',
+ 'MOTRIX_MDXP_PORT=0',
+ '--publish',
+ '127.0.0.1::8080',
+ image,
+ ])
+ created = true
+ const port = await containerPort(name, timeoutMs)
+ const url = `http://127.0.0.1:${port}`
+ await waitForHealth(name, url, timeoutMs)
+ await assertOperatorAuth(url, operatorToken)
+ await docker([
+ 'exec',
+ name,
+ 'sh',
+ '-ec',
+ 'test -s /data/motrix.db; pidof aria2c',
+ ])
+ await docker([
+ 'exec',
+ name,
+ 'node',
+ '--input-type=module',
+ '--eval',
+ RUNTIME_PROBE,
+ ])
+ await docker(['stop', '--time', String(Math.ceil(timeoutMs / 1000)), name])
+ const state = JSON.parse(
+ await docker(['inspect', '--format', '{{json .State}}', name])
+ )
+ if (state.Running || state.ExitCode !== 0 || state.OOMKilled) {
+ throw new Error(
+ `Server image shutdown failed: running=${state.Running} code=${state.ExitCode} oom=${state.OOMKilled}`
+ )
+ }
+ const metadata = JSON.parse(await docker(['image', 'inspect', image]))[0]
+ return {
+ imageId: metadata.Id,
+ imageBytes: metadata.Size,
+ architecture: metadata.Architecture,
+ node: metadata.Config.Env.find((entry) =>
+ entry.startsWith('NODE_VERSION=')
+ )?.slice('NODE_VERSION='.length),
+ health: true,
+ operatorAuth: true,
+ sqlite: true,
+ systemAria2: true,
+ shutdown: 'SIGTERM',
+ durationMs: Date.now() - startedAt,
+ }
+ } catch (error) {
+ const logs = created
+ ? await docker(['logs', '--tail', '200', name]).catch(() => '')
+ : ''
+ const message = error instanceof Error ? error.message : String(error)
+ throw new Error(
+ logs
+ ? `${message}\nContainer logs:\n${logs.slice(-MAX_LOG_BYTES)}`
+ : message,
+ { cause: error }
+ )
+ } finally {
+ if (created) await docker(['rm', '--force', name]).catch(() => undefined)
+ }
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ const raw = parseArguments(process.argv.slice(2))
+ smokeServerImage({
+ image: raw.image,
+ timeoutMs: raw['timeout-ms']
+ ? Number.parseInt(raw['timeout-ms'], 10)
+ : undefined,
+ })
+ .then((result) => {
+ console.log(`Server image smoke passed: ${JSON.stringify(result)}`)
+ })
+ .catch((error) => {
+ console.error(error instanceof Error ? error.message : error)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/smoke-server-package.mjs b/scripts/smoke-server-package.mjs
new file mode 100644
index 00000000..30b83fac
--- /dev/null
+++ b/scripts/smoke-server-package.mjs
@@ -0,0 +1,420 @@
+import { spawn } from 'node:child_process'
+import {
+ chmod,
+ copyFile,
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ stat,
+} from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { Worker } from 'node:worker_threads'
+
+const DEFAULT_TIMEOUT_MS = 30_000
+const MAX_LOG_BYTES = 256 * 1024
+
+function withTimeout(promise, timeoutMs, label) {
+ let timer
+ return Promise.race([
+ promise,
+ new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
+ timeoutMs
+ )
+ }),
+ ]).finally(() => clearTimeout(timer))
+}
+
+async function availablePort() {
+ const server = net.createServer()
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const address = server.address()
+ const port = typeof address === 'object' && address ? address.port : 0
+ await new Promise((resolve, reject) => {
+ server.close((error) => (error ? reject(error) : resolve()))
+ })
+ if (port === 0) throw new Error('failed to allocate a Server smoke port')
+ return port
+}
+
+async function assertDirectRootsResolve(stageRoot, dependencies) {
+ const canonicalStageRoot = await realpath(stageRoot)
+ const script = [
+ "import path from 'node:path'",
+ "import { fileURLToPath } from 'node:url'",
+ `const root = ${JSON.stringify(canonicalStageRoot)}`,
+ `const dependencies = ${JSON.stringify(dependencies)}`,
+ 'for (const dependency of dependencies) {',
+ ' const resolved = fileURLToPath(import.meta.resolve(dependency))',
+ ' const relative = path.relative(root, resolved)',
+ " if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {",
+ " throw new Error(dependency + ' resolved outside staged Server app')",
+ ' }',
+ '}',
+ ].join('\n')
+ await withTimeout(
+ new Promise((resolve, reject) => {
+ const child = spawn(
+ process.execPath,
+ ['--input-type=module', '--eval', script],
+ {
+ cwd: stageRoot,
+ env: { ...process.env, NODE_PATH: undefined },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+ )
+ let stderr = ''
+ child.stderr.on('data', (chunk) => {
+ stderr = `${stderr}${chunk}`.slice(-MAX_LOG_BYTES)
+ })
+ child.once('error', reject)
+ child.once('exit', (code) => {
+ if (code === 0) resolve()
+ else
+ reject(new Error(`direct-root resolution failed: ${stderr.trim()}`))
+ })
+ }),
+ 10_000,
+ 'direct-root resolution'
+ )
+}
+
+function assertSqlite(stageRoot, scratchRoot) {
+ const require = createRequire(path.join(stageRoot, 'package.json'))
+ const Database = require('better-sqlite3')
+ const memory = new Database(':memory:')
+ memory.exec('CREATE TABLE smoke (value TEXT NOT NULL)')
+ memory.prepare('INSERT INTO smoke (value) VALUES (?)').run('memory-ok')
+ const memoryValue = memory.prepare('SELECT value FROM smoke').get()?.value
+ memory.close()
+ if (memoryValue !== 'memory-ok') {
+ throw new Error('in-memory better-sqlite3 read/write failed')
+ }
+
+ const databasePath = path.join(scratchRoot, 'sqlite-smoke.db')
+ const disk = new Database(databasePath)
+ disk.exec('CREATE TABLE smoke (value TEXT NOT NULL)')
+ disk.prepare('INSERT INTO smoke (value) VALUES (?)').run('disk-ok')
+ disk.close()
+ const reopened = new Database(databasePath)
+ const diskValue = reopened.prepare('SELECT value FROM smoke').get()?.value
+ reopened.close()
+ if (diskValue !== 'disk-ok') {
+ throw new Error('on-disk better-sqlite3 reopen failed')
+ }
+}
+
+async function assertQuickJsWorker(stageRoot, timeoutMs) {
+ const workerPath = path.join(
+ stageRoot,
+ 'dist/core/plugin/host/quick-js-worker.cjs'
+ )
+ const worker = new Worker(workerPath, {
+ resourceLimits: { maxOldGenerationSizeMb: 32, stackSizeMb: 1 },
+ })
+ try {
+ await withTimeout(
+ new Promise((resolve, reject) => {
+ worker.on('message', (message) => {
+ if (message?.type === 'ready') resolve()
+ else if (message?.type === 'fatal') {
+ reject(
+ new Error(
+ `QuickJS worker failed: ${message.code}: ${message.message}`
+ )
+ )
+ }
+ })
+ worker.once('error', reject)
+ worker.postMessage({
+ type: 'init',
+ pluginId: 'motrix.runtime-smoke',
+ manifest: {
+ manifestVersion: 1,
+ id: 'motrix.runtime-smoke',
+ name: 'Runtime smoke',
+ version: '1.0.0',
+ description: 'Staged Server runtime smoke',
+ categories: ['other'],
+ engines: { motrix: '>=2.0.0 <3.0.0' },
+ main: 'smoke.mjs',
+ requestedHeapMB: 32,
+ permissions: [],
+ hostPermissions: [],
+ activationEvents: [],
+ contributes: {},
+ },
+ bundleSource: 'export const ready = true',
+ app: {
+ version: '2.0.0',
+ platform: process.platform,
+ runtime: 'server',
+ locale: 'en-US',
+ arch: process.arch,
+ },
+ i18n: {
+ language: 'en-US',
+ dir: 'ltr',
+ currentDict: {},
+ fallbackDict: {},
+ },
+ limits: { heapMB: 32, stackKB: 256 },
+ })
+ }),
+ timeoutMs,
+ 'QuickJS worker startup'
+ )
+ const exit = new Promise((resolve, reject) => {
+ worker.once('error', reject)
+ worker.once('exit', resolve)
+ })
+ worker.postMessage({ type: 'event', event: 'shutdown' })
+ const code = await withTimeout(exit, timeoutMs, 'QuickJS worker shutdown')
+ if (code !== 0) throw new Error(`QuickJS worker exited with code ${code}`)
+ } finally {
+ await worker.terminate().catch(() => undefined)
+ }
+}
+
+async function waitForHealth(url, childState, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ if (childState.exit) {
+ throw new Error(
+ `staged Server exited before health check: ${childState.exit}; logs:\n${childState.logs}`
+ )
+ }
+ try {
+ const response = await fetch(`${url}/healthz`)
+ if (response.ok && (await response.json()).ok === true) return
+ } catch {
+ // Startup is still in progress.
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ throw new Error(
+ `staged Server did not become healthy within ${timeoutMs}ms; logs:\n${childState.logs}`
+ )
+}
+
+async function assertOperatorAuth(url, token) {
+ const unauthenticated = await fetch(`${url}/rpc/query/runtime-smoke`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ args: [] }),
+ })
+ if (unauthenticated.status !== 401) {
+ throw new Error(
+ `unauthenticated operator request returned ${unauthenticated.status}, expected 401`
+ )
+ }
+ const status = await fetch(`${url}/rpc/auth/status`, {
+ headers: { authorization: `Bearer ${token}` },
+ })
+ if (!status.ok || (await status.json()).authed !== true) {
+ throw new Error('Bearer operator authentication failed')
+ }
+ const authenticated = await fetch(`${url}/rpc/query/runtime-smoke`, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ args: [] }),
+ })
+ if (authenticated.status !== 404) {
+ throw new Error(
+ `authenticated operator request returned ${authenticated.status}, expected route-level 404`
+ )
+ }
+}
+
+async function stopServer(child, childState, timeoutMs) {
+ if (childState.exit) return childState.exit
+ const exited = new Promise((resolve) => child.once('exit', resolve))
+ child.kill('SIGTERM')
+ try {
+ return await withTimeout(
+ exited,
+ timeoutMs,
+ 'staged Server SIGTERM shutdown'
+ )
+ } catch (error) {
+ child.kill('SIGKILL')
+ await exited
+ throw error
+ }
+}
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (index === 0 && argument === '--') continue
+ if (!argument.startsWith('--'))
+ throw new Error(`unknown argument: ${argument}`)
+ const key = argument.slice(2)
+ if (!['app-dir', 'aria2-bin', 'timeout-ms'].includes(key)) {
+ throw new Error(`unknown option: --${key}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for --${key}`)
+ }
+ options[key] = value
+ index += 1
+ }
+ if (!options['app-dir']) throw new Error('--app-dir is required')
+ return options
+}
+
+export async function smokeServerPackage(options) {
+ const nodeMajor = Number(process.versions.node.split('.')[0])
+ if (nodeMajor !== 24) {
+ throw new Error(
+ `Server runtime smoke requires Node 24, found ${process.versions.node}`
+ )
+ }
+ const stageRoot = path.resolve(options.appDir)
+ const aria2Source = path.resolve(
+ options.aria2Bin ?? process.env.MOTRIX_ARIA2_BIN ?? ''
+ )
+ if (!options.aria2Bin && !process.env.MOTRIX_ARIA2_BIN) {
+ throw new Error('--aria2-bin or MOTRIX_ARIA2_BIN is required')
+ }
+ if (!(await stat(stageRoot)).isDirectory()) {
+ throw new Error('staged Server app is not a directory')
+ }
+ if (!(await stat(aria2Source).catch(() => null))?.isFile()) {
+ throw new Error('aria2 binary is not a file')
+ }
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000) {
+ throw new Error(
+ 'Server smoke timeout must be an integer of at least 1000ms'
+ )
+ }
+ const manifest = JSON.parse(
+ await readFile(path.join(stageRoot, 'package.json'), 'utf8')
+ )
+ const dependencies = Object.keys(manifest.dependencies ?? {}).sort()
+ const scratchRoot = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-server-smoke-')
+ )
+ const startedAt = Date.now()
+ let child
+ const childState = { exit: null, logs: '' }
+ try {
+ await assertDirectRootsResolve(stageRoot, dependencies)
+ assertSqlite(stageRoot, scratchRoot)
+ await assertQuickJsWorker(stageRoot, timeoutMs)
+
+ const port = await availablePort()
+ const systemRoot = path.join(scratchRoot, 'system')
+ const aria2Bin = path.join(systemRoot, 'aria2c')
+ const dataDir = path.join(scratchRoot, 'data')
+ const homeDir = path.join(scratchRoot, 'home')
+ await Promise.all([
+ mkdir(systemRoot, { recursive: true }),
+ mkdir(dataDir, { recursive: true }),
+ mkdir(path.join(homeDir, 'Downloads'), { recursive: true }),
+ ])
+ await copyFile(aria2Source, aria2Bin)
+ await chmod(aria2Bin, 0o755)
+ const operatorToken = 'motrix-runtime-smoke-operator-token'
+ child = spawn(process.execPath, [manifest.main], {
+ cwd: stageRoot,
+ env: {
+ ...process.env,
+ HOME: homeDir,
+ LOG_LEVEL: 'info',
+ MOTRIX_ARIA2_BIN: aria2Bin,
+ MOTRIX_BUILTIN_PLUGIN_DIR: path.join(stageRoot, 'builtin-plugins'),
+ MOTRIX_DATA_DIR: dataDir,
+ MOTRIX_EXTRA_DIR: path.join(stageRoot, 'extra'),
+ MOTRIX_MDXP_PORT: '0',
+ MOTRIX_OPERATOR_TOKEN: operatorToken,
+ MOTRIX_PLUGIN_DIR: path.join(dataDir, 'plugins'),
+ MOTRIX_RENDERER_DIR: path.join(stageRoot, 'dist/renderer-web'),
+ NODE_ENV: 'production',
+ NODE_PATH: undefined,
+ PORT: String(port),
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ const collectLogs = (chunk) => {
+ childState.logs = `${childState.logs}${chunk}`.slice(-MAX_LOG_BYTES)
+ }
+ child.stdout.on('data', collectLogs)
+ child.stderr.on('data', collectLogs)
+ child.once('error', (error) => {
+ childState.exit = `spawn error: ${error.message}`
+ })
+ child.once('exit', (code, signal) => {
+ childState.exit = `code=${code} signal=${signal}`
+ })
+
+ const url = `http://127.0.0.1:${port}`
+ await waitForHealth(url, childState, timeoutMs)
+ await assertOperatorAuth(url, operatorToken)
+ const database = await stat(path.join(dataDir, 'motrix.db'))
+ if (!database.isFile() || database.size === 0) {
+ throw new Error('Server did not create its isolated Motrix database')
+ }
+ const exit = await stopServer(child, childState, timeoutMs)
+ if (exit !== 0) {
+ throw new Error(`staged Server shutdown exited with code ${exit}`)
+ }
+ child = undefined
+ return {
+ node: process.versions.node,
+ directRoots: dependencies.length,
+ sqlite: true,
+ quickJsWorker: true,
+ health: true,
+ operatorAuth: true,
+ databaseBytes: database.size,
+ shutdown: 'SIGTERM',
+ durationMs: Date.now() - startedAt,
+ }
+ } finally {
+ if (child && child.exitCode === null && child.signalCode === null) {
+ const exited = new Promise((resolve) => child.once('exit', resolve))
+ child.kill('SIGKILL')
+ await exited.catch(() => undefined)
+ }
+ await rm(scratchRoot, { recursive: true }).catch(() => undefined)
+ }
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ const raw = parseArguments(process.argv.slice(2))
+ const timeoutMs = raw['timeout-ms']
+ ? Number.parseInt(raw['timeout-ms'], 10)
+ : undefined
+ smokeServerPackage({
+ appDir: raw['app-dir'],
+ aria2Bin: raw['aria2-bin'],
+ timeoutMs,
+ })
+ .then((result) => {
+ console.log(`Server runtime smoke passed: ${JSON.stringify(result)}`)
+ })
+ .catch((error) => {
+ console.error(error instanceof Error ? error.message : error)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/stage-server-app.mjs b/scripts/stage-server-app.mjs
new file mode 100644
index 00000000..40e07727
--- /dev/null
+++ b/scripts/stage-server-app.mjs
@@ -0,0 +1,663 @@
+import { execFile } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import {
+ chmod,
+ cp,
+ lstat,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { promisify } from 'node:util'
+import { auditServerRuntime } from './audit-server-runtime.mjs'
+import { assertNativeBinaryTarget } from './native-binary-target.mjs'
+import {
+ betterSqlite3PrebuildName,
+ normalizeRelativePath,
+ parseServerTarget,
+ stringifySortedJson,
+ validateServerRuntimeContract,
+ validateServerSizeBudgets,
+} from './server-package-utils.mjs'
+
+const execFileAsync = promisify(execFile)
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..'
+)
+const GENERATED_MANIFEST_FIELDS = [
+ 'author',
+ 'description',
+ 'homepage',
+ 'license',
+ 'productName',
+ 'version',
+]
+
+function isInside(root, candidate) {
+ const relative = path.relative(root, candidate)
+ return (
+ relative.length > 0 &&
+ relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative)
+ )
+}
+
+async function readJson(filePath, label) {
+ try {
+ return JSON.parse(await readFile(filePath, 'utf8'))
+ } catch (error) {
+ throw new Error(`${label} is unreadable: ${filePath}`, { cause: error })
+ }
+}
+
+function generatedManifest(rootManifest, contract) {
+ const manifest = {
+ name: '@motrix/server-runtime',
+ }
+ for (const field of GENERATED_MANIFEST_FIELDS) {
+ if (rootManifest[field] !== undefined) manifest[field] = rootManifest[field]
+ }
+ manifest.private = true
+ manifest.type = 'module'
+ manifest.main = 'dist/server/index.mjs'
+ manifest.engines = { node: '>=24' }
+ manifest.dependencies = Object.fromEntries(
+ contract.runtimeRoots.map((name) => {
+ const version = rootManifest.dependencies?.[name]
+ if (typeof version !== 'string') {
+ throw new Error(`runtime root ${name} is not in root dependencies`)
+ }
+ return [name, version]
+ })
+ )
+ return manifest
+}
+
+function packageAppliesToTarget(manifest, target) {
+ function matches(values, actual) {
+ if (!Array.isArray(values) || values.length === 0) return true
+ const denied = values.includes(`!${actual}`)
+ const positive = values.filter((entry) => !entry.startsWith('!'))
+ return !denied && (positive.length === 0 || positive.includes(actual))
+ }
+ return (
+ matches(manifest.os, target.platform) && matches(manifest.cpu, target.arch)
+ )
+}
+
+async function resolvePackageInstance(name, fromRoot, canonicalRepoRoot) {
+ const require = createRequire(path.join(fromRoot, 'package.json'))
+ const candidates = []
+ try {
+ candidates.push(require.resolve(`${name}/package.json`))
+ } catch {
+ for (const searchPath of require.resolve.paths(name) ?? []) {
+ candidates.push(path.join(searchPath, name, 'package.json'))
+ }
+ try {
+ let current = path.dirname(require.resolve(name))
+ while (current !== path.dirname(current)) {
+ candidates.push(path.join(current, 'package.json'))
+ current = path.dirname(current)
+ }
+ } catch {
+ // The caller decides whether a missing dependency is optional.
+ }
+ }
+
+ for (const candidate of candidates) {
+ const info = await stat(candidate).catch(() => null)
+ if (!info?.isFile()) continue
+ const manifest = await readJson(candidate, `package ${name}`)
+ if (manifest.name !== name || typeof manifest.version !== 'string') continue
+ const sourceRoot = await realpath(path.dirname(candidate))
+ if (
+ sourceRoot !== canonicalRepoRoot &&
+ !isInside(canonicalRepoRoot, sourceRoot)
+ ) {
+ throw new Error(`resolved package ${name} escapes repository root`)
+ }
+ return { manifest, sourceRoot }
+ }
+ return undefined
+}
+
+function nodeLookupDestinations(consumerDestination, name) {
+ const destinations = []
+ let current = consumerDestination
+ while (true) {
+ if (path.posix.basename(current) !== 'node_modules') {
+ destinations.push(path.posix.join(current, 'node_modules', name))
+ }
+ const parent = path.posix.dirname(current)
+ if (parent === current || current === '.') break
+ current = parent
+ }
+ destinations.push(path.posix.join('node_modules', name))
+ return [...new Set(destinations.map((entry) => entry.replace(/^\.\//, '')))]
+}
+
+async function isRootHoisted(repoRoot, name, sourceRoot) {
+ const candidate = await realpath(
+ path.join(repoRoot, 'node_modules', name)
+ ).catch(() => null)
+ return candidate === sourceRoot
+}
+
+async function assertSafeDirectory(
+ sourceRoot,
+ canonicalRepoRoot,
+ options = {}
+) {
+ const visited = new Set()
+ async function walk(directory) {
+ const canonical = await realpath(directory)
+ if (visited.has(canonical)) return
+ visited.add(canonical)
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ if (options.skipNodeModules && entry.name === 'node_modules') continue
+ const entryPath = path.join(directory, entry.name)
+ if (entry.isSymbolicLink()) {
+ const target = await realpath(entryPath).catch(() => null)
+ if (
+ !target ||
+ (target !== canonicalRepoRoot && !isInside(canonicalRepoRoot, target))
+ ) {
+ throw new Error(
+ `source symlink escapes repository root: ${entryPath}`
+ )
+ }
+ const targetInfo = await stat(target)
+ if (targetInfo.isDirectory()) await walk(target)
+ } else if (entry.isDirectory()) {
+ await walk(entryPath)
+ }
+ }
+ }
+ await walk(sourceRoot)
+}
+
+async function normalizeDirectoryModes(directory) {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const entryPath = path.join(directory, entry.name)
+ if (entry.isDirectory()) {
+ await chmod(entryPath, 0o755)
+ await normalizeDirectoryModes(entryPath)
+ } else {
+ const info = await lstat(entryPath)
+ if (info.isSymbolicLink()) {
+ throw new Error(`staging emitted a symlink: ${entryPath}`)
+ }
+ await chmod(entryPath, (info.mode & 0o111) === 0 ? 0o644 : 0o755)
+ }
+ }
+}
+
+async function copyPath(source, destination, canonicalRepoRoot, options = {}) {
+ const sourceInfo = await lstat(source)
+ if (sourceInfo.isSymbolicLink()) {
+ throw new Error(`top-level staging input is a symlink: ${source}`)
+ }
+ await mkdir(path.dirname(destination), { recursive: true })
+ if (sourceInfo.isFile()) {
+ await cp(source, destination)
+ await chmod(destination, (sourceInfo.mode & 0o111) === 0 ? 0o644 : 0o755)
+ return
+ }
+ if (!sourceInfo.isDirectory()) {
+ throw new Error(`staging input is not a file or directory: ${source}`)
+ }
+ await assertSafeDirectory(source, canonicalRepoRoot, options)
+ await cp(source, destination, {
+ recursive: true,
+ dereference: true,
+ filter: (candidate) => {
+ const relative = path.relative(source, candidate)
+ if (
+ options.skipNodeModules &&
+ (relative === 'node_modules' ||
+ relative.startsWith(`node_modules${path.sep}`))
+ ) {
+ return false
+ }
+ return options.filter ? options.filter(relative) : true
+ },
+ })
+ await chmod(destination, 0o755)
+ await normalizeDirectoryModes(destination)
+}
+
+function packageCopyFilter(name, target) {
+ if (name !== 'better-sqlite3') return undefined
+ const selected = `prebuilds/${betterSqlite3PrebuildName(target)}`
+ return (relative) => {
+ if (relative.length === 0) return true
+ const portable = relative.replaceAll(path.sep, '/')
+ return (
+ portable === 'package.json' ||
+ /^LICENSE(?:\..*)?$/i.test(portable) ||
+ portable === 'lib' ||
+ portable.startsWith('lib/') ||
+ portable === 'prebuilds' ||
+ portable === selected
+ )
+ }
+}
+
+async function collectNativeModules(directory) {
+ const files = []
+ async function walk(current) {
+ for (const entry of await readdir(current, { withFileTypes: true })) {
+ const entryPath = path.join(current, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else if (entry.name.endsWith('.node')) files.push(entryPath)
+ }
+ }
+ await walk(directory)
+ return files.sort()
+}
+
+async function validateStagedNativeModules(directory, target, packageName) {
+ const nativeModules = await collectNativeModules(directory)
+ for (const file of nativeModules) {
+ await assertNativeBinaryTarget(file, target.platform, target.arch, {
+ label: `${packageName} native module`,
+ })
+ }
+ if (packageName === 'better-sqlite3') {
+ const expected = path.join(
+ directory,
+ 'prebuilds',
+ betterSqlite3PrebuildName(target)
+ )
+ if (nativeModules.length !== 1 || nativeModules[0] !== expected) {
+ throw new Error(
+ `better-sqlite3 must stage exactly one ${target.key} prebuild`
+ )
+ }
+ }
+}
+
+async function fingerprintInput(repoRoot, input) {
+ const source = path.join(repoRoot, input.source)
+ const records = []
+ async function addFile(filePath, relativePath) {
+ const bytes = await readFile(filePath)
+ records.push({
+ path: relativePath,
+ bytes: bytes.length,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ })
+ }
+ if (input.type === 'file') {
+ await addFile(source, input.source)
+ } else {
+ async function walk(directory, relativeDirectory) {
+ const entries = await readdir(directory, { withFileTypes: true })
+ entries.sort((left, right) => left.name.localeCompare(right.name))
+ for (const entry of entries) {
+ const entryPath = path.join(directory, entry.name)
+ const relativePath = path.posix.join(relativeDirectory, entry.name)
+ if (entry.isDirectory()) await walk(entryPath, relativePath)
+ else if (entry.isFile()) await addFile(entryPath, relativePath)
+ else
+ throw new Error(`fingerprint input contains a symlink: ${entryPath}`)
+ }
+ }
+ await walk(source, input.source)
+ }
+ return {
+ source: input.source,
+ destination: input.destination,
+ files: records,
+ }
+}
+
+async function inventoryTree(directory) {
+ let bytes = 0
+ let files = 0
+ async function walk(current) {
+ const entries = await readdir(current, { withFileTypes: true })
+ entries.sort((left, right) => left.name.localeCompare(right.name))
+ for (const entry of entries) {
+ const entryPath = path.join(current, entry.name)
+ if (entry.isDirectory()) await walk(entryPath)
+ else if (entry.isFile()) {
+ bytes += (await stat(entryPath)).size
+ files += 1
+ } else {
+ throw new Error(`staged application contains a symlink: ${entryPath}`)
+ }
+ }
+ }
+ await walk(directory)
+ return { bytes, files }
+}
+
+export async function assertServerExternalsResolve(stageRoot, specifiers) {
+ const script = [
+ `const specifiers = ${JSON.stringify(specifiers)}`,
+ 'for (const specifier of specifiers) {',
+ ' try { import.meta.resolve(specifier) }',
+ ' catch (error) {',
+ ' console.error(specifier + ": " + error.message)',
+ ' process.exitCode = 1',
+ ' }',
+ '}',
+ ].join('\n')
+ try {
+ await execFileAsync(
+ process.execPath,
+ ['--input-type=module', '--eval', script],
+ {
+ cwd: stageRoot,
+ encoding: 'utf8',
+ }
+ )
+ } catch (error) {
+ throw new Error(
+ `staged Server cannot resolve built externals: ${error.stderr?.trim() ?? error.message}`,
+ { cause: error }
+ )
+ }
+}
+
+async function replaceStageAtomically(stageRoot, temporaryRoot) {
+ const backup = `${stageRoot}.previous-${process.pid}-${Date.now()}`
+ let hadPrevious = false
+ try {
+ await rename(stageRoot, backup)
+ hadPrevious = true
+ } catch (error) {
+ if (error?.code !== 'ENOENT') throw error
+ }
+ try {
+ await rename(temporaryRoot, stageRoot)
+ } catch (error) {
+ if (hadPrevious) await rename(backup, stageRoot)
+ throw error
+ }
+ if (hadPrevious) await rm(backup, { recursive: true })
+}
+
+export async function stageServerApp(options = {}) {
+ const repoRoot = path.resolve(options.repoRoot ?? REPOSITORY_ROOT)
+ const canonicalRepoRoot = await realpath(repoRoot)
+ const target = parseServerTarget({
+ platform: options.platform,
+ arch: options.arch,
+ libc: options.libc,
+ strict: options.strict,
+ ci: options.ci,
+ })
+ const contract = validateServerRuntimeContract(
+ options.contract ??
+ (await readJson(
+ path.join(repoRoot, 'scripts/server-runtime-dependencies.json'),
+ 'server runtime contract'
+ ))
+ )
+ const budgets = validateServerSizeBudgets(
+ options.budgets ??
+ (await readJson(
+ path.join(repoRoot, 'scripts/server-package-size-budgets.json'),
+ 'server size budgets'
+ ))
+ )
+ if (!contract.supportedTargets.includes(target.key)) {
+ throw new Error(`unsupported Server package target ${target.key}`)
+ }
+
+ const requestedStageRoot = path.resolve(
+ options.outputDir ?? path.join(repoRoot, 'dist/server-app')
+ )
+ const stageRelative = path.relative(repoRoot, requestedStageRoot)
+ if (
+ stageRelative.length === 0 ||
+ stageRelative === '..' ||
+ stageRelative.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(stageRelative)
+ ) {
+ throw new Error(`stage output must stay within repository root`)
+ }
+ const stageRoot = path.join(canonicalRepoRoot, stageRelative)
+ await mkdir(path.dirname(stageRoot), { recursive: true })
+
+ const audit = await auditServerRuntime({
+ repoRoot,
+ contract,
+ budgets,
+ })
+ const rootManifest = await readJson(
+ path.join(repoRoot, 'package.json'),
+ 'root package manifest'
+ )
+ const appManifest = generatedManifest(rootManifest, contract)
+ const inputs = [...contract.buildInputs, ...contract.resourceInputs]
+ const inputFingerprints = []
+ for (const input of inputs) {
+ inputFingerprints.push(await fingerprintInput(repoRoot, input))
+ }
+
+ const temporaryRoot = await mkdtemp(
+ path.join(path.dirname(stageRoot), `.${path.basename(stageRoot)}-`)
+ )
+ try {
+ for (const input of inputs) {
+ await copyPath(
+ path.join(repoRoot, input.source),
+ path.join(temporaryRoot, input.destination),
+ canonicalRepoRoot
+ )
+ }
+ await writeFile(
+ path.join(temporaryRoot, 'package.json'),
+ stringifySortedJson(appManifest),
+ { mode: 0o644 }
+ )
+
+ const placements = new Map()
+ const queue = []
+ const optionalOmissions = []
+
+ async function addDependency(name, consumer, optional) {
+ const instance = await resolvePackageInstance(
+ name,
+ consumer.sourceRoot,
+ canonicalRepoRoot
+ )
+ if (!instance) {
+ if (optional) {
+ optionalOmissions.push({
+ name,
+ requestedBy: `${consumer.manifest.name}@${consumer.manifest.version}`,
+ })
+ return
+ }
+ throw new Error(
+ `required dependency ${name} requested by ${consumer.manifest.name}@${consumer.manifest.version} is missing`
+ )
+ }
+ if (!packageAppliesToTarget(instance.manifest, target)) {
+ if (optional) {
+ optionalOmissions.push({
+ name,
+ requestedBy: `${consumer.manifest.name}@${consumer.manifest.version}`,
+ })
+ return
+ }
+ throw new Error(
+ `required dependency ${name} is incompatible with ${target.key}`
+ )
+ }
+
+ for (const candidate of nodeLookupDestinations(
+ consumer.destination,
+ name
+ )) {
+ const existing = placements.get(candidate)
+ if (existing?.sourceRoot === instance.sourceRoot) return
+ }
+
+ let destination = path.posix.join(
+ consumer.destination,
+ 'node_modules',
+ name
+ )
+ if (await isRootHoisted(repoRoot, name, instance.sourceRoot)) {
+ destination = path.posix.join('node_modules', name)
+ }
+ destination = normalizeRelativePath(
+ destination,
+ `destination for ${name}`
+ )
+ const conflict = placements.get(destination)
+ if (conflict) {
+ if (conflict.sourceRoot === instance.sourceRoot) return
+ throw new Error(
+ `dependency placement conflict at ${destination}: ${conflict.manifest.version} vs ${instance.manifest.version}`
+ )
+ }
+ const placement = { ...instance, destination }
+ placements.set(destination, placement)
+ queue.push(placement)
+ }
+
+ const rootConsumer = {
+ destination: '.',
+ manifest: rootManifest,
+ sourceRoot: canonicalRepoRoot,
+ }
+ for (const name of contract.runtimeRoots) {
+ await addDependency(name, rootConsumer, false)
+ }
+ for (let index = 0; index < queue.length; index += 1) {
+ const placement = queue[index]
+ for (const name of Object.keys(
+ placement.manifest.dependencies ?? {}
+ ).sort()) {
+ await addDependency(name, placement, false)
+ }
+ for (const name of Object.keys(
+ placement.manifest.optionalDependencies ?? {}
+ ).sort()) {
+ await addDependency(name, placement, true)
+ }
+ }
+
+ const sortedPlacements = [...placements.values()].sort((left, right) =>
+ left.destination.localeCompare(right.destination)
+ )
+ const packageRecords = sortedPlacements.map((placement) => ({
+ destination: placement.destination,
+ name: placement.manifest.name,
+ source: normalizeRelativePath(
+ path.relative(canonicalRepoRoot, placement.sourceRoot),
+ `source for ${placement.manifest.name}`
+ ),
+ version: placement.manifest.version,
+ }))
+ for (const placement of sortedPlacements) {
+ const destination = path.join(temporaryRoot, placement.destination)
+ await copyPath(placement.sourceRoot, destination, canonicalRepoRoot, {
+ filter: packageCopyFilter(placement.manifest.name, target),
+ skipNodeModules: true,
+ })
+ await validateStagedNativeModules(
+ destination,
+ target,
+ placement.manifest.name
+ )
+ }
+
+ await assertServerExternalsResolve(
+ temporaryRoot,
+ audit.externals.specifiers
+ )
+ optionalOmissions.sort((left, right) =>
+ `${left.name}\0${left.requestedBy}`.localeCompare(
+ `${right.name}\0${right.requestedBy}`
+ )
+ )
+ const inventory = await inventoryTree(temporaryRoot)
+ const stageManifest = {
+ schemaVersion: 1,
+ target,
+ rootVersion: rootManifest.version,
+ externals: audit.externals,
+ inputFingerprints,
+ packages: packageRecords,
+ optionalOmissions,
+ inventory,
+ }
+ await writeFile(
+ path.join(temporaryRoot, '.motrix-server-stage.json'),
+ stringifySortedJson(stageManifest),
+ { mode: 0o644 }
+ )
+ await replaceStageAtomically(stageRoot, temporaryRoot)
+ return { manifest: stageManifest, stageRoot }
+ } catch (error) {
+ await rm(temporaryRoot, { recursive: true }).catch(() => undefined)
+ throw error
+ }
+}
+
+function parseArguments(argv) {
+ const values = new Map()
+ for (let index = 0; index < argv.length; index += 1) {
+ const option = argv[index]
+ if (option === '--' && index === 0) continue
+ if (option === '--strict') {
+ values.set(option, true)
+ continue
+ }
+ if (!['--arch', '--libc', '--platform'].includes(option)) {
+ throw new Error(`unknown staging argument: ${option}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for staging argument: ${option}`)
+ }
+ if (values.has(option))
+ throw new Error(`duplicate staging argument: ${option}`)
+ values.set(option, value)
+ index += 1
+ }
+ return values
+}
+
+export async function main(argv = process.argv.slice(2)) {
+ const args = parseArguments(argv)
+ const result = await stageServerApp({
+ platform: args.get('--platform'),
+ arch: args.get('--arch'),
+ libc: args.get('--libc'),
+ strict: args.has('--strict') || Boolean(process.env.CI),
+ })
+ console.log(
+ `Staged ${result.manifest.target.key} Server app at ${result.stageRoot}`
+ )
+ return result
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ main().catch((error) => {
+ console.error(error instanceof Error ? error.message : String(error))
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/verify-server-package.mjs b/scripts/verify-server-package.mjs
new file mode 100644
index 00000000..7df1412d
--- /dev/null
+++ b/scripts/verify-server-package.mjs
@@ -0,0 +1,522 @@
+import { createHash } from 'node:crypto'
+import {
+ lstat,
+ mkdir,
+ readdir,
+ readFile,
+ stat,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { detectNativeBinaryTarget } from './native-binary-target.mjs'
+import {
+ betterSqlite3PrebuildName,
+ normalizeRelativePath,
+ parseServerTarget,
+ stringifySortedJson,
+ validateServerRuntimeContract,
+ validateServerSizeBudgets,
+} from './server-package-utils.mjs'
+import { assertServerExternalsResolve } from './stage-server-app.mjs'
+
+const REPOSITORY_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '..'
+)
+const FORMAT_BY_PLATFORM = {
+ darwin: 'mach-o',
+ linux: 'elf',
+ win32: 'pe',
+}
+const FORBIDDEN_ROOT_PATHS = [
+ '.git',
+ '.github',
+ '.pnpm-store',
+ 'dist/main',
+ 'dist/preload',
+ 'dist/renderer',
+ 'docs',
+ 'pnpm-lock.yaml',
+ 'pnpm-workspace.yaml',
+ 'scripts',
+ 'src',
+]
+const EXPECTED_MANIFEST = {
+ name: '@motrix/server-runtime',
+ private: true,
+ type: 'module',
+ main: 'dist/server/index.mjs',
+ engines: { node: '>=24' },
+}
+
+function sha256(bytes) {
+ return createHash('sha256').update(bytes).digest('hex')
+}
+
+function packageRecordFromManifestPath(relativePath) {
+ const parts = relativePath.split('/')
+ if (parts.at(-1) !== 'package.json') return undefined
+ const nodeModulesIndex = parts.lastIndexOf('node_modules')
+ if (nodeModulesIndex < 0) return undefined
+ const firstNamePart = parts[nodeModulesIndex + 1]
+ if (!firstNamePart) return undefined
+ const manifestIndex = firstNamePart.startsWith('@')
+ ? nodeModulesIndex + 3
+ : nodeModulesIndex + 2
+ if (manifestIndex !== parts.length - 1) return undefined
+ const name = firstNamePart.startsWith('@')
+ ? `${firstNamePart}/${parts[nodeModulesIndex + 2]}`
+ : firstNamePart
+ return {
+ destination: parts.slice(0, manifestIndex).join('/'),
+ name,
+ }
+}
+
+async function walkStage(stageRoot) {
+ const files = []
+ const symlinks = []
+ async function walk(directory, relativeDirectory) {
+ const entries = await readdir(directory, { withFileTypes: true })
+ entries.sort((left, right) => left.name.localeCompare(right.name))
+ for (const entry of entries) {
+ const absolute = path.join(directory, entry.name)
+ const relative = relativeDirectory
+ ? `${relativeDirectory}/${entry.name}`
+ : entry.name
+ const info = await lstat(absolute)
+ if (info.isSymbolicLink()) symlinks.push(relative)
+ else if (info.isDirectory()) await walk(absolute, relative)
+ else if (info.isFile())
+ files.push({ absolute, path: relative, bytes: info.size })
+ else throw new Error(`unsupported staged path type: ${relative}`)
+ }
+ }
+ await walk(stageRoot, '')
+ return { files, symlinks }
+}
+
+function expectedInputFiles(fingerprint) {
+ const source = normalizeRelativePath(fingerprint.source, 'fingerprint source')
+ const destination = normalizeRelativePath(
+ fingerprint.destination,
+ 'fingerprint destination'
+ )
+ if (!Array.isArray(fingerprint.files) || fingerprint.files.length === 0) {
+ throw new Error(`fingerprint ${source} has no files`)
+ }
+ return fingerprint.files.map((record) => {
+ const sourcePath = normalizeRelativePath(record.path, 'fingerprint file')
+ const relative = path.posix.relative(source, sourcePath)
+ if (relative === '..' || relative.startsWith('../')) {
+ throw new Error(`fingerprint file escapes ${source}: ${sourcePath}`)
+ }
+ if (
+ !Number.isSafeInteger(record.bytes) ||
+ record.bytes < 0 ||
+ !/^[a-f0-9]{64}$/.test(record.sha256)
+ ) {
+ throw new Error(`fingerprint record is invalid: ${sourcePath}`)
+ }
+ return {
+ path:
+ relative.length === 0
+ ? destination
+ : path.posix.join(destination, relative),
+ bytes: record.bytes,
+ sha256: record.sha256,
+ }
+ })
+}
+
+function sanitizeReport(value, replacements) {
+ if (Array.isArray(value)) {
+ return value.map((entry) => sanitizeReport(entry, replacements))
+ }
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, entry]) => [
+ key,
+ sanitizeReport(entry, replacements),
+ ])
+ )
+ }
+ if (typeof value !== 'string') return value
+ let sanitized = value
+ for (const [root, label] of replacements) {
+ if (root) sanitized = sanitized.replaceAll(root, label)
+ }
+ return sanitized
+}
+
+function parseArguments(argv) {
+ const options = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index]
+ if (index === 0 && argument === '--') continue
+ if (!argument.startsWith('--'))
+ throw new Error(`unknown argument: ${argument}`)
+ const key = argument.slice(2)
+ if (!['app-dir', 'arch', 'libc', 'platform', 'report'].includes(key)) {
+ throw new Error(`unknown option: --${key}`)
+ }
+ const value = argv[index + 1]
+ if (!value || value.startsWith('--')) {
+ throw new Error(`missing value for --${key}`)
+ }
+ options[key] = value
+ index += 1
+ }
+ if (!options['app-dir']) throw new Error('--app-dir is required')
+ return options
+}
+
+export async function verifyServerPackage(options) {
+ const stageRoot = path.resolve(options.appDir)
+ const target = parseServerTarget({
+ platform: options.platform,
+ arch: options.arch,
+ libc: options.libc,
+ strict: true,
+ })
+ const reportPath = path.resolve(
+ options.reportPath ??
+ path.join(
+ REPOSITORY_ROOT,
+ 'release/size-reports',
+ `server-${target.key}.json`
+ )
+ )
+ const contract = validateServerRuntimeContract(
+ options.contract ??
+ JSON.parse(
+ await readFile(
+ path.join(
+ REPOSITORY_ROOT,
+ 'scripts/server-runtime-dependencies.json'
+ ),
+ 'utf8'
+ )
+ )
+ )
+ const budgets = validateServerSizeBudgets(
+ options.budgets ??
+ JSON.parse(
+ await readFile(
+ path.join(
+ REPOSITORY_ROOT,
+ 'scripts/server-package-size-budgets.json'
+ ),
+ 'utf8'
+ )
+ )
+ )
+ const checks = []
+ const errors = []
+ let stageManifest
+ let appManifest
+ let tree = { files: [], symlinks: [] }
+ const packageRecords = []
+ const nativeBinaries = []
+ let unexpectedRuntimeRoots = contract.runtimeRoots.length
+ let unresolvedExternals = 0
+ let foreignNativeBinaries = 0
+ let betterSqlite3Prebuilds = 0
+
+ async function check(id, operation) {
+ try {
+ const message = await operation()
+ checks.push({ id, passed: true, message: message ?? 'passed' })
+ return true
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ checks.push({ id, passed: false, message })
+ errors.push(`${id}: ${message}`)
+ return false
+ }
+ }
+
+ await check('stage-directory', async () => {
+ if (!(await stat(stageRoot)).isDirectory()) {
+ throw new Error('staged Server app is not a directory')
+ }
+ return 'staged Server app directory exists'
+ })
+ await check('stage-manifest', async () => {
+ stageManifest = JSON.parse(
+ await readFile(path.join(stageRoot, '.motrix-server-stage.json'), 'utf8')
+ )
+ if (
+ stageManifest?.schemaVersion !== 1 ||
+ !Array.isArray(stageManifest.packages) ||
+ !Array.isArray(stageManifest.inputFingerprints) ||
+ !Array.isArray(stageManifest.externals?.specifiers)
+ ) {
+ throw new Error('stage manifest does not match schema version 1')
+ }
+ return 'stage manifest matches schema version 1'
+ })
+ await check('target', () => {
+ if (stageManifest?.target?.key !== target.key) {
+ throw new Error(
+ `stage target ${stageManifest?.target?.key ?? 'missing'} does not match ${target.key}`
+ )
+ }
+ return `stage target is ${target.key}`
+ })
+ await check('application-manifest', async () => {
+ appManifest = JSON.parse(
+ await readFile(path.join(stageRoot, 'package.json'), 'utf8')
+ )
+ for (const [key, expected] of Object.entries(EXPECTED_MANIFEST)) {
+ if (JSON.stringify(appManifest[key]) !== JSON.stringify(expected)) {
+ throw new Error(`generated package.json has invalid ${key}`)
+ }
+ }
+ const actualRoots = Object.keys(appManifest.dependencies ?? {}).sort()
+ const expectedRoots = [...contract.runtimeRoots].sort()
+ const missing = expectedRoots.filter((name) => !actualRoots.includes(name))
+ const extra = actualRoots.filter((name) => !expectedRoots.includes(name))
+ unexpectedRuntimeRoots = missing.length + extra.length
+ if (unexpectedRuntimeRoots > 0) {
+ throw new Error(
+ `runtime roots differ; missing=${missing.join(',') || 'none'} extra=${extra.join(',') || 'none'}`
+ )
+ }
+ return `${actualRoots.length} runtime roots match the contract`
+ })
+ await check('artifact-tree', async () => {
+ tree = await walkStage(stageRoot)
+ if (tree.symlinks.length > 0) {
+ throw new Error(
+ `staged Server app contains symlinks: ${tree.symlinks.join(', ')}`
+ )
+ }
+ return `${tree.files.length} regular files and no symlinks`
+ })
+ await check('forbidden-payloads', () => {
+ const paths = tree.files.map((entry) => entry.path)
+ const forbidden = FORBIDDEN_ROOT_PATHS.filter((candidate) =>
+ paths.some(
+ (entry) => entry === candidate || entry.startsWith(`${candidate}/`)
+ )
+ )
+ const sqliteBuildPayload = paths.filter(
+ (entry) =>
+ entry.startsWith('node_modules/better-sqlite3/src/') ||
+ entry.startsWith('node_modules/better-sqlite3/deps/') ||
+ entry.startsWith('node_modules/better-sqlite3/build/') ||
+ entry === 'node_modules/better-sqlite3/binding.gyp'
+ )
+ if (forbidden.length > 0 || sqliteBuildPayload.length > 0) {
+ throw new Error(
+ `forbidden payloads found: ${[...forbidden, ...sqliteBuildPayload].join(', ')}`
+ )
+ }
+ return 'source, package-manager, Electron, and native build payloads are absent'
+ })
+ await check('input-fingerprints', async () => {
+ if (!stageManifest) throw new Error('stage manifest is unavailable')
+ const expected = stageManifest.inputFingerprints
+ .flatMap((fingerprint) => expectedInputFiles(fingerprint))
+ .sort((left, right) => left.path.localeCompare(right.path))
+ const expectedPaths = new Set(expected.map((entry) => entry.path))
+ for (const record of expected) {
+ const absolute = path.join(stageRoot, ...record.path.split('/'))
+ const bytes = await readFile(absolute)
+ if (bytes.length !== record.bytes || sha256(bytes) !== record.sha256) {
+ throw new Error(`staged input fingerprint mismatch: ${record.path}`)
+ }
+ }
+ for (const fingerprint of stageManifest.inputFingerprints) {
+ const destination = normalizeRelativePath(
+ fingerprint.destination,
+ 'fingerprint destination'
+ )
+ const destinationFiles = tree.files.filter(
+ (entry) =>
+ entry.path === destination || entry.path.startsWith(`${destination}/`)
+ )
+ const unexpected = destinationFiles.filter(
+ (entry) => !expectedPaths.has(entry.path)
+ )
+ if (unexpected.length > 0) {
+ throw new Error(`unexpected staged input file: ${unexpected[0].path}`)
+ }
+ }
+ return `${expected.length} staged input fingerprints match`
+ })
+ await check('stage-inventory', () => {
+ if (!stageManifest) throw new Error('stage manifest is unavailable')
+ const inventoryFiles = tree.files.filter(
+ (entry) => entry.path !== '.motrix-server-stage.json'
+ )
+ const bytes = inventoryFiles.reduce(
+ (total, entry) => total + entry.bytes,
+ 0
+ )
+ if (
+ stageManifest.inventory?.files !== inventoryFiles.length ||
+ stageManifest.inventory?.bytes !== bytes
+ ) {
+ throw new Error('stage inventory does not match artifact contents')
+ }
+ return `${inventoryFiles.length} files match the stage inventory`
+ })
+ await check('package-closure', async () => {
+ for (const file of tree.files) {
+ const record = packageRecordFromManifestPath(file.path)
+ if (!record) continue
+ const manifest = JSON.parse(await readFile(file.absolute, 'utf8'))
+ packageRecords.push({
+ destination: record.destination,
+ name: record.name,
+ version: manifest.version,
+ })
+ }
+ packageRecords.sort((left, right) =>
+ left.destination.localeCompare(right.destination)
+ )
+ const expected = (stageManifest?.packages ?? [])
+ .map(({ destination, name, version }) => ({ destination, name, version }))
+ .sort((left, right) => left.destination.localeCompare(right.destination))
+ if (JSON.stringify(packageRecords) !== JSON.stringify(expected)) {
+ throw new Error('staged package closure differs from the stage manifest')
+ }
+ return `${packageRecords.length} package instances match the closure`
+ })
+ await check('external-resolution', async () => {
+ if (!stageManifest) throw new Error('stage manifest is unavailable')
+ try {
+ await assertServerExternalsResolve(
+ stageRoot,
+ stageManifest.externals.specifiers
+ )
+ } catch (error) {
+ unresolvedExternals = 1
+ throw error
+ }
+ return `${stageManifest.externals.specifiers.length} external specifiers resolve`
+ })
+ await check('native-binaries', async () => {
+ const expectedFormat = FORMAT_BY_PLATFORM[target.platform]
+ const selectedPrebuild = `node_modules/better-sqlite3/prebuilds/${betterSqlite3PrebuildName(target)}`
+ const nativeFiles = tree.files.filter((entry) =>
+ entry.path.endsWith('.node')
+ )
+ betterSqlite3Prebuilds = nativeFiles.filter((entry) =>
+ entry.path.startsWith('node_modules/better-sqlite3/prebuilds/')
+ ).length
+ for (const file of nativeFiles) {
+ const detected = detectNativeBinaryTarget(await readFile(file.absolute))
+ const matches = Boolean(
+ detected &&
+ detected.format === expectedFormat &&
+ detected.arches.length === 1 &&
+ detected.arches[0] === target.arch
+ )
+ if (!matches) foreignNativeBinaries += 1
+ nativeBinaries.push({
+ path: file.path,
+ format: detected?.format ?? 'unknown',
+ arches: detected?.arches ?? [],
+ bytes: file.bytes,
+ matchesTarget: matches,
+ })
+ }
+ if (
+ betterSqlite3Prebuilds !== 1 ||
+ !nativeFiles.some((entry) => entry.path === selectedPrebuild) ||
+ foreignNativeBinaries > 0
+ ) {
+ throw new Error(
+ `native payload mismatch; selected=${selectedPrebuild} betterSqlite3=${betterSqlite3Prebuilds} foreign=${foreignNativeBinaries}`
+ )
+ }
+ return `${nativeFiles.length} native binaries match ${target.key}`
+ })
+
+ const metrics = {
+ artifactBytes: tree.files.reduce((total, entry) => total + entry.bytes, 0),
+ dependencyBytes: tree.files
+ .filter((entry) => entry.path.startsWith('node_modules/'))
+ .reduce((total, entry) => total + entry.bytes, 0),
+ packageInstances: packageRecords.length,
+ unexpectedRuntimeRoots,
+ unresolvedExternals,
+ foreignNativeBinaries,
+ betterSqlite3Prebuilds,
+ }
+ await check('size-budgets', () => {
+ const failures = []
+ for (const [key, actual] of Object.entries(metrics)) {
+ const expected = budgets[key]
+ const passes =
+ key === 'betterSqlite3Prebuilds'
+ ? actual === expected
+ : actual <= expected
+ if (!passes) failures.push(`${key}=${actual} budget=${expected}`)
+ }
+ if (failures.length > 0) {
+ throw new Error(
+ `Server package size budget exceeded: ${failures.join(', ')}`
+ )
+ }
+ return 'all Server package size budgets pass'
+ })
+
+ const report = sanitizeReport(
+ {
+ schemaVersion: 1,
+ target,
+ passed: errors.length === 0,
+ budgets,
+ metrics,
+ checks,
+ errors,
+ packages: packageRecords,
+ nativeBinaries,
+ toolVersions: { node: process.versions.node },
+ },
+ [
+ [stageRoot, '<app-dir>'],
+ [REPOSITORY_ROOT, '<repository>'],
+ [os.homedir(), '<home>'],
+ ]
+ )
+ await mkdir(path.dirname(reportPath), { recursive: true })
+ await writeFile(reportPath, stringifySortedJson(report), { mode: 0o644 })
+ if (errors.length > 0) {
+ const error = new Error(
+ `Server package verification failed:\n${errors.join('\n')}`
+ )
+ error.report = report
+ throw error
+ }
+ return report
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ const raw = parseArguments(process.argv.slice(2))
+ verifyServerPackage({
+ appDir: raw['app-dir'],
+ platform: raw.platform,
+ arch: raw.arch,
+ libc: raw.libc,
+ reportPath: raw.report,
+ })
+ .then((report) => {
+ console.log(
+ `Verified Server ${report.target.key}: ${report.metrics.artifactBytes} bytes, ${report.metrics.packageInstances} packages`
+ )
+ })
+ .catch((error) => {
+ console.error(error instanceof Error ? error.message : error)
+ process.exitCode = 1
+ })
+}
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index 9773a59c..de166069 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -344,32 +344,50 @@ describe('third-party graph dependency notices', () => {
).toBe(true)
})
- it('copies notices, licenses, and generated compliance files into the Docker runtime image', async () => {
+ it('delivers the verified staged legal payload into the Docker runtime image', async () => {
const dockerfile = await readFile(path.join(ROOT, 'Dockerfile'), 'utf8')
expect(dockerfile).toContain(
- 'COPY --from=build /app/THIRD_PARTY_NOTICES.md ./THIRD_PARTY_NOTICES.md'
+ 'COPY --from=build --chown=node:node /app/dist/server-app/ ./'
)
+ for (const artifact of LEGAL_ARTIFACTS) {
+ const contract = JSON.parse(
+ await readFile(
+ path.join(ROOT, 'scripts/server-runtime-dependencies.json'),
+ 'utf8'
+ )
+ ) as { resourceInputs?: Array<{ destination?: string }> }
+ expect(
+ contract.resourceInputs?.map((input) => input.destination)
+ ).toContain(`legal/${artifact}`)
+ }
+ for (const destination of [
+ 'THIRD_PARTY_NOTICES.md',
+ 'THIRD_PARTY_NOTICES.zh-CN.md',
+ 'THIRD_PARTY_LICENSES',
+ ]) {
+ const contract = JSON.parse(
+ await readFile(
+ path.join(ROOT, 'scripts/server-runtime-dependencies.json'),
+ 'utf8'
+ )
+ ) as { resourceInputs?: Array<{ destination?: string }> }
+ expect(
+ contract.resourceInputs?.map((input) => input.destination)
+ ).toContain(destination)
+ }
expect(dockerfile).toContain(
- 'COPY --from=build /app/THIRD_PARTY_NOTICES.zh-CN.md ./THIRD_PARTY_NOTICES.zh-CN.md'
+ 'node scripts/verify-server-package.mjs --app-dir dist/server-app'
)
- expect(dockerfile).toContain(
- 'COPY --from=build /app/THIRD_PARTY_LICENSES ./THIRD_PARTY_LICENSES'
+ expect(dockerfile).not.toMatch(
+ /COPY --from=build \/app\/(?:THIRD_PARTY|build\/legal)/
)
- for (const artifact of LEGAL_ARTIFACTS) {
- expect(dockerfile).toContain(
- `COPY --from=build /app/build/legal/${artifact} ./legal/${artifact}`
- )
- }
expect(dockerfile).not.toContain(
- 'COPY --from=build /app/build/legal ./legal'
- )
- expect(dockerfile).toContain(
'COPY --from=runtime-deps /app/node_modules ./node_modules'
)
})
- it('gates the canonical Docker build before build:server', async () => {
+ it('gates and stages the canonical Docker build before runtime delivery', async () => {
const [dockerfile, manifestSource] = await Promise.all([
readFile(path.join(ROOT, 'Dockerfile'), 'utf8'),
readFile(path.join(ROOT, 'package.json'), 'utf8'),
@@ -379,30 +397,48 @@ describe('third-party graph dependency notices', () => {
}
const depsCommands = dockerStageRunCommands(dockerfile, 'deps')
const buildCommands = dockerStageRunCommands(dockerfile, 'build')
- const runtimeDependencyCommands = dockerStageRunCommands(
- dockerfile,
- 'runtime-deps'
- )
const installCommand = depsCommands.find((command) =>
/^pnpm install(?:\s|$)/.test(command)
)
- const gateIndex = buildCommands.indexOf(NOTICE_GATE_COMMAND)
+ const electronInstallIndex = buildCommands.indexOf(
+ 'node node_modules/electron/install.js'
+ )
+ const gateIndex = buildCommands.findIndex((command) =>
+ command.endsWith(NOTICE_GATE_COMMAND)
+ )
const buildIndex = buildCommands.findIndex((command) =>
/^pnpm (?:run )?build:server(?:\s|$)/.test(command)
)
+ const stageIndex = buildCommands.findIndex((command) =>
+ command.startsWith('node scripts/stage-server-app.mjs ')
+ )
+ const verifyIndex = buildCommands.findIndex((command) =>
+ command.startsWith('node scripts/verify-server-package.mjs ')
+ )
expect(manifest.devDependencies?.vitest).toBeDefined()
expect(installCommand).toBeDefined()
expect(isProductionOnlyInstall(installCommand ?? '')).toBe(false)
- expect(
- dockerfile.slice(0, dockerfile.indexOf('FROM node:22-alpine AS runtime'))
- ).not.toMatch(/ENV\s+NODE_ENV=production/)
- expect(gateIndex).toBeGreaterThanOrEqual(0)
+ expect(dockerfile).toContain('FROM node:24-alpine AS deps')
+ expect(dockerfile).toContain('FROM node:24-alpine AS runtime')
+ expect(electronInstallIndex).toBeGreaterThanOrEqual(0)
+ expect(gateIndex).toBeGreaterThan(electronInstallIndex)
expect(buildIndex).toBeGreaterThan(gateIndex)
- expect(dockerfile).toContain('FROM build AS runtime-deps')
- expect(runtimeDependencyCommands).toContain(
- 'pnpm prune --prod --ignore-scripts'
+ expect(stageIndex).toBeGreaterThan(buildIndex)
+ expect(verifyIndex).toBeGreaterThan(stageIndex)
+ expect(dockerfile).not.toContain('pnpm prune --prod')
+ expect(dockerfile).not.toContain('FROM build AS runtime-deps')
+ expect(dockerfile).toContain(
+ 'COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./'
+ )
+ expect(dockerfile).toContain(
+ 'COPY packages/native-host/package.json ./packages/native-host/package.json'
+ )
+ expect(dockerfile).toContain(
+ 'node scripts/stage-server-app.mjs --platform linux --arch "${' +
+ 'TARGETARCH}" --libc musl --strict'
)
+ expect(dockerfile).toContain('USER node')
})
it('gates the canonical Flatpak build before rebuild and packaging', async () => {
diff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.ts
new file mode 100644
index 00000000..33dc0309
--- /dev/null
+++ b/tests/scripts/audit-server-runtime.test.ts
@@ -0,0 +1,328 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { auditServerRuntime } from '../../scripts/audit-server-runtime.mjs'
+import {
+ externalPackageRoots,
+ parseServerTarget,
+ scanStaticModuleSpecifiers,
+ validateServerRuntimeContract,
+ validateServerSizeBudgets,
+} from '../../scripts/server-package-utils.mjs'
+
+const ROOT = path.resolve(import.meta.dirname, '../..')
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+async function writeFixtureFile(
+ root: string,
+ relativePath: string,
+ content = relativePath
+): Promise<void> {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+}
+
+function fixtureContract() {
+ return {
+ schemaVersion: 1,
+ supportedTargets: [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64-gnu',
+ 'linux-arm64-musl',
+ 'linux-x64-gnu',
+ 'linux-x64-musl',
+ 'win32-x64',
+ ],
+ runtimeRoots: ['alpha', 'beta'],
+ buildInputs: [
+ {
+ source: 'dist/core/plugin/host/quick-js-worker.cjs',
+ destination: 'dist/core/plugin/host/quick-js-worker.cjs',
+ type: 'file',
+ entry: null,
+ scanExternals: true,
+ },
+ {
+ source: 'dist/renderer-web',
+ destination: 'dist/renderer-web',
+ type: 'directory',
+ entry: 'index.html',
+ scanExternals: false,
+ },
+ {
+ source: 'dist/server',
+ destination: 'dist/server',
+ type: 'directory',
+ entry: 'index.mjs',
+ scanExternals: true,
+ },
+ ],
+ resourceInputs: [
+ {
+ source: 'extra/aria2.conf',
+ destination: 'extra/aria2.conf',
+ type: 'file',
+ },
+ ],
+ }
+}
+
+function fixtureBudgets() {
+ return {
+ schemaVersion: 1,
+ artifactBytes: 100,
+ dependencyBytes: 80,
+ packageInstances: 10,
+ unexpectedRuntimeRoots: 0,
+ unresolvedExternals: 0,
+ foreignNativeBinaries: 0,
+ betterSqlite3Prebuilds: 1,
+ }
+}
+
+async function createFixture(): Promise<string> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-audit-'))
+ temporaryRoots.push(root)
+ await writeFixtureFile(
+ root,
+ 'package.json',
+ `${JSON.stringify(
+ {
+ name: 'server-audit-fixture',
+ version: '1.2.3',
+ dependencies: { alpha: '1.0.0', beta: '2.0.0', extra: '3.0.0' },
+ optionalDependencies: { optional: '1.0.0' },
+ },
+ null,
+ 2
+ )}\n`
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/server/index.mjs',
+ [
+ 'import fs from "node:fs";',
+ 'import alpha from "alpha/subpath";',
+ '// import ignored from "ignored-comment";',
+ 'const ignored = "require(\\"ignored-string\\")";',
+ 'export { alpha, ignored };',
+ ].join('\n')
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'module.exports = require("beta")\n'
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/renderer-web/index.html',
+ '<main>ok</main>'
+ )
+ await writeFixtureFile(root, 'extra/aria2.conf', 'continue=true\n')
+ for (const [name, version] of [
+ ['alpha', '1.0.0'],
+ ['beta', '2.0.0'],
+ ]) {
+ await writeFixtureFile(
+ root,
+ `node_modules/${name}/package.json`,
+ `${JSON.stringify({ name, version, main: 'index.js' })}\n`
+ )
+ await writeFixtureFile(
+ root,
+ `node_modules/${name}/index.js`,
+ 'module.exports = true\n'
+ )
+ }
+ await writeFixtureFile(
+ root,
+ 'node_modules/alpha/subpath.js',
+ 'module.exports = true\n'
+ )
+ return root
+}
+
+describe('Server package contracts', () => {
+ it('accepts the canonical target matrix and normalizes Docker arch aliases', () => {
+ expect(
+ parseServerTarget({
+ platform: 'linux',
+ arch: 'amd64',
+ libc: 'musl',
+ strict: true,
+ })
+ ).toEqual({
+ platform: 'linux',
+ arch: 'x64',
+ libc: 'musl',
+ key: 'linux-x64-musl',
+ })
+ expect(
+ parseServerTarget({ platform: 'darwin', arch: 'arm64', strict: true })
+ ).toEqual({ platform: 'darwin', arch: 'arm64', key: 'darwin-arm64' })
+ })
+
+ it('rejects ambiguous libc and unsupported targets', () => {
+ expect(() =>
+ parseServerTarget({ platform: 'linux', arch: 'arm64', strict: true })
+ ).toThrow('requires --libc')
+ expect(() =>
+ parseServerTarget({
+ platform: 'darwin',
+ arch: 'arm64',
+ libc: 'musl',
+ strict: true,
+ })
+ ).toThrow('--libc is only valid')
+ expect(() =>
+ parseServerTarget({ platform: 'win32', arch: 'arm64', strict: true })
+ ).toThrow('unsupported Server package target')
+ })
+
+ it('rejects unknown, unsorted, and unsafe contract data', () => {
+ expect(validateServerRuntimeContract(fixtureContract())).toBeTruthy()
+ expect(() =>
+ validateServerRuntimeContract({ ...fixtureContract(), unknown: true })
+ ).toThrow('unknown key')
+ expect(() =>
+ validateServerRuntimeContract({
+ ...fixtureContract(),
+ runtimeRoots: ['beta', 'alpha'],
+ })
+ ).toThrow('sorted order')
+ const unsafe = fixtureContract()
+ unsafe.resourceInputs[0].source = '../secret'
+ expect(() => validateServerRuntimeContract(unsafe)).toThrow(
+ 'must stay within its root'
+ )
+ const duplicateDestination = fixtureContract()
+ duplicateDestination.resourceInputs[0].destination =
+ duplicateDestination.buildInputs[0].destination
+ expect(() => validateServerRuntimeContract(duplicateDestination)).toThrow(
+ 'duplicate input destinations'
+ )
+ })
+
+ it('requires exact non-negative size budgets', () => {
+ expect(validateServerSizeBudgets(fixtureBudgets())).toBeTruthy()
+ expect(() =>
+ validateServerSizeBudgets({
+ ...fixtureBudgets(),
+ artifactBytes: -1,
+ })
+ ).toThrow('non-negative safe integer')
+ expect(() =>
+ validateServerSizeBudgets({
+ ...fixtureBudgets(),
+ betterSqlite3Prebuilds: 2,
+ })
+ ).toThrow('must be 1')
+ })
+
+ it('freezes the reviewed build, resource, and runtime-root allowlists', async () => {
+ const contract = validateServerRuntimeContract(
+ JSON.parse(
+ await readFile(
+ path.join(ROOT, 'scripts/server-runtime-dependencies.json'),
+ 'utf8'
+ )
+ )
+ )
+ expect(contract.buildInputs.map((entry) => entry.source)).toEqual([
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'dist/renderer-web',
+ 'dist/server',
+ ])
+ expect(contract.resourceInputs.map((entry) => entry.source)).toEqual([
+ 'THIRD_PARTY_LICENSES',
+ 'THIRD_PARTY_NOTICES.md',
+ 'THIRD_PARTY_NOTICES.zh-CN.md',
+ 'build/legal/THIRD_PARTY_DEPENDENCIES.md',
+ 'build/legal/THIRD_PARTY_LICENSES.txt',
+ 'build/legal/sbom.spdx.json',
+ 'dist/builtin-plugins',
+ 'extra/aria2.conf',
+ ])
+ expect(contract.runtimeRoots).toHaveLength(20)
+ expect(contract.runtimeRoots).not.toContain('electron-updater')
+ expect(contract.runtimeRoots).not.toContain('@motrix/nat')
+ })
+})
+
+describe('Server built external audit', () => {
+ it('scans static ESM, side-effect, dynamic, export-from, and CJS imports', () => {
+ const source = [
+ 'import value from "alpha/subpath";',
+ 'import "beta/register";',
+ 'export { thing } from "@scope/gamma/export";',
+ 'const delta = require("delta")',
+ 'const epsilon = import("epsilon")',
+ '// require("ignored-comment")',
+ 'const ignored = "import(\\"ignored-string\\")"',
+ ].join('\n')
+ expect(scanStaticModuleSpecifiers(source)).toEqual([
+ '@scope/gamma/export',
+ 'alpha/subpath',
+ 'beta/register',
+ 'delta',
+ 'epsilon',
+ ])
+ expect(
+ externalPackageRoots([...scanStaticModuleSpecifiers(source), 'node:fs'])
+ ).toEqual(['@scope/gamma', 'alpha', 'beta', 'delta', 'epsilon'])
+ })
+
+ it('measures reviewed inputs and rejects root drift', async () => {
+ const root = await createFixture()
+ const report = await auditServerRuntime({
+ repoRoot: root,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ expect(report.rootVersion).toBe('1.2.3')
+ expect(report.rootProductionDeclarations).toEqual({
+ dependencies: 3,
+ optionalDependencies: 1,
+ })
+ expect(report.externals.roots).toEqual(['alpha', 'beta'])
+ expect(
+ report.runtimeRoots.map((entry: { name: string }) => entry.name)
+ ).toEqual(['alpha', 'beta'])
+ expect(report.controlledInputs.build.files).toBe(3)
+ expect(report.controlledInputs.resources.files).toBe(1)
+
+ await writeFixtureFile(
+ root,
+ 'dist/server/index.mjs',
+ 'import alpha from "alpha"; import gamma from "gamma";'
+ )
+ await expect(
+ auditServerRuntime({
+ repoRoot: root,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ ).rejects.toThrow('unexpected runtime roots: gamma')
+ })
+
+ it('fails when an allowlisted build entry is missing', async () => {
+ const root = await createFixture()
+ await rm(path.join(root, 'dist/server/index.mjs'))
+ await expect(
+ auditServerRuntime({
+ repoRoot: root,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ ).rejects.toThrow('missing build entry: dist/server/index.mjs')
+ })
+})
diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.ts
new file mode 100644
index 00000000..858e3605
--- /dev/null
+++ b/tests/scripts/docker-server-runtime.test.ts
@@ -0,0 +1,82 @@
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+const ROOT = process.cwd()
+
+describe('Docker Server runtime staging contract', () => {
+ it('copies only the verified stage into a non-root Node 24 runtime', async () => {
+ const dockerfile = await readFile(path.join(ROOT, 'Dockerfile'), 'utf8')
+ const runtime = dockerfile.slice(
+ dockerfile.indexOf('FROM node:24-alpine AS runtime')
+ )
+
+ expect(runtime).toContain(
+ 'COPY --from=build --chown=node:node /app/dist/server-app/ ./'
+ )
+ expect(runtime.match(/^COPY /gm)).toHaveLength(1)
+ expect(runtime).toContain('apk add --no-cache aria2 ca-certificates')
+ expect(runtime).toContain('MOTRIX_ARIA2_BIN=/usr/bin/aria2c')
+ expect(runtime).toContain('MOTRIX_DATA_DIR=/data')
+ expect(runtime).toContain('USER node')
+ expect(runtime).toContain('CMD ["node", "dist/server/index.mjs"]')
+ expect(runtime).toContain('rm -rf /usr/local/lib/node_modules/npm')
+ expect(runtime).toContain('/usr/local/lib/node_modules/corepack')
+ expect(runtime).toContain('/opt/yarn-v1.22.22')
+ expect(runtime).not.toMatch(/\bpnpm (?:exec|install|run)\b/)
+ expect(runtime).not.toContain('/app/src')
+ })
+
+ it('keeps required build inputs and excludes local-only context', async () => {
+ const dockerignore = await readFile(
+ path.join(ROOT, '.dockerignore'),
+ 'utf8'
+ )
+
+ for (const entry of [
+ '.git',
+ '.claude',
+ '.codex',
+ 'dist',
+ 'release',
+ 'node_modules',
+ 'docs',
+ 'e2e',
+ '**/*.test.ts',
+ '**/*.test.tsx',
+ 'obsidian-docs.config.json',
+ ]) {
+ expect(dockerignore.split('\n')).toContain(entry)
+ }
+ expect(dockerignore).toContain('!tests/check-third-party-notices.test.ts')
+ expect(dockerignore).toContain(
+ '!tests/generate-third-party-notices.test.ts'
+ )
+ })
+
+ it('keeps a corrected full-root comparison target without changing the final target', async () => {
+ const dockerfile = await readFile(path.join(ROOT, 'Dockerfile'), 'utf8')
+ const baselineStart = dockerfile.indexOf(
+ 'FROM node:24-alpine AS server-full-root-baseline'
+ )
+ const runtimeStart = dockerfile.indexOf('FROM node:24-alpine AS runtime')
+ const baseline = dockerfile.slice(baselineStart, runtimeStart)
+
+ expect(baselineStart).toBeGreaterThanOrEqual(0)
+ expect(runtimeStart).toBeGreaterThan(baselineStart)
+ expect(dockerfile).toContain(
+ 'FROM node:24-alpine AS full-root-production-deps'
+ )
+ expect(dockerfile).toContain(
+ 'pnpm install --prod --frozen-lockfile --ignore-scripts'
+ )
+ expect(baseline).toContain(
+ 'COPY --from=full-root-production-deps --chown=node:node /app/node_modules ./node_modules'
+ )
+ expect(baseline).toContain('/app/dist/core/plugin/host')
+ expect(baseline).toContain('/app/build/legal/sbom.spdx.json')
+ expect(
+ dockerfile.trimEnd().endsWith('CMD ["node", "dist/server/index.mjs"]')
+ ).toBe(true)
+ })
+})
diff --git a/tests/scripts/measure-server-images.test.ts b/tests/scripts/measure-server-images.test.ts
new file mode 100644
index 00000000..173f671f
--- /dev/null
+++ b/tests/scripts/measure-server-images.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest'
+import { buildServerImageComparison } from '../../scripts/measure-server-images.mjs'
+
+function inventory(overrides: Record<string, unknown> = {}) {
+ return {
+ appBytes: 100,
+ dependencyBytes: 80,
+ files: 10,
+ symlinks: 0,
+ packageInstances: 8,
+ packageNames: ['a', 'b'],
+ directRoots: ['a'],
+ optionalRoots: [],
+ nativeBinaries: [{ path: 'node_modules/a/a.node', bytes: 10 }],
+ ...overrides,
+ }
+}
+
+function comparison(
+ baselineSample = inventory(),
+ optimizedSample = inventory({
+ appBytes: 50,
+ dependencyBytes: 30,
+ packageInstances: 3,
+ packageNames: ['a'],
+ })
+) {
+ return buildServerImageComparison({
+ target: 'linux-arm64-musl',
+ samples: {
+ baseline: [baselineSample, structuredClone(baselineSample)],
+ optimized: [optimizedSample, structuredClone(optimizedSample)],
+ },
+ baseline: { imageBytes: 200, ...baselineSample },
+ optimized: { imageBytes: 120, ...optimizedSample },
+ stageReport: {
+ passed: true,
+ budgets: { artifactBytes: 96 * 1024 * 1024 },
+ metrics: { artifactBytes: 50 },
+ },
+ dockerVersion: '29.4.0',
+ })
+}
+
+describe('buildServerImageComparison', () => {
+ it('reports stable material reductions and controlled stage evidence', () => {
+ const report = comparison()
+
+ expect(report.passed).toBe(true)
+ expect(report.samplesStable).toEqual({ baseline: true, optimized: true })
+ expect(report.reduction).toEqual({
+ image: { bytes: 80, percent: 40 },
+ app: { bytes: 50, percent: 50 },
+ dependencies: { bytes: 50, percent: 62.5 },
+ packageInstances: 5,
+ })
+ expect(report.controlledStage.passed).toBe(true)
+ })
+
+ it('fails comparison when repeated samples drift', () => {
+ const baseline = inventory()
+ const optimized = inventory({
+ appBytes: 50,
+ dependencyBytes: 30,
+ packageInstances: 3,
+ })
+ const report = buildServerImageComparison({
+ target: 'linux-arm64-musl',
+ samples: {
+ baseline: [baseline, { ...baseline, files: 11 }],
+ optimized: [optimized, structuredClone(optimized)],
+ },
+ baseline: { imageBytes: 200, ...baseline },
+ optimized: { imageBytes: 120, ...optimized },
+ stageReport: { passed: true, budgets: {}, metrics: {} },
+ dockerVersion: '29.4.0',
+ })
+
+ expect(report.passed).toBe(false)
+ expect(report.samplesStable.baseline).toBe(false)
+ })
+})
diff --git a/tests/scripts/server-runtime-workflow.test.ts b/tests/scripts/server-runtime-workflow.test.ts
new file mode 100644
index 00000000..35be167d
--- /dev/null
+++ b/tests/scripts/server-runtime-workflow.test.ts
@@ -0,0 +1,109 @@
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+const ROOT = process.cwd()
+const require = createRequire(import.meta.url)
+const parseYaml = require('js-yaml').load as (source: string) => unknown
+const MATRIX_ARCH_EXPRESSION = '--platform linux/${' + '{ matrix.docker_arch }}'
+const MATRIX_TARGET_EXPRESSION = '${' + '{ matrix.target }}'
+
+interface Step {
+ name?: string
+ run?: string
+ uses?: string
+ with?: Record<string, unknown>
+}
+
+interface ServerRuntimeJob {
+ name?: string
+ 'runs-on'?: string
+ strategy?: {
+ matrix?: {
+ include?: Array<Record<string, string>>
+ }
+ }
+ steps?: Step[]
+}
+
+describe('Server runtime CI pipeline', () => {
+ const source = readFileSync(
+ path.join(ROOT, '.github/workflows/ci.yml'),
+ 'utf8'
+ )
+ const workflow = parseYaml(source) as {
+ jobs?: Record<string, ServerRuntimeJob>
+ }
+ const job = workflow.jobs?.['server-runtime']
+ const steps = job?.steps ?? []
+
+ it('runs native x64 and arm64 Node 24 Docker jobs', () => {
+ expect(job).toBeDefined()
+ expect(job?.strategy?.matrix?.include).toEqual([
+ {
+ target: 'linux-x64-musl',
+ os: 'ubuntu-22.04',
+ docker_arch: 'amd64',
+ },
+ {
+ target: 'linux-arm64-musl',
+ os: 'ubuntu-22.04-arm',
+ docker_arch: 'arm64',
+ },
+ ])
+ expect(
+ steps.find((step) => step.uses?.startsWith('actions/setup-node@'))?.with
+ ).toEqual({ 'node-version': 24 })
+ })
+
+ it('orders build, report export, runtime smoke, and artifact upload', () => {
+ const names = steps.map((step) => step.name)
+ const build = names.indexOf('Build staged Server image')
+ const report = names.indexOf('Export Server size report')
+ const smoke = names.indexOf('Smoke staged Server image')
+ const upload = names.indexOf('Upload Server size report')
+ expect(build).toBeGreaterThanOrEqual(0)
+ expect(report).toBeGreaterThan(build)
+ expect(smoke).toBeGreaterThan(report)
+ expect(upload).toBeGreaterThan(smoke)
+
+ expect(steps[build]?.run).toContain(MATRIX_ARCH_EXPRESSION)
+ expect(steps[report]?.run).toContain('--target server-size-report')
+ expect(steps[report]?.run).toContain(
+ '--output type=local,dest=release/size-reports'
+ )
+ expect(steps[smoke]?.run).toContain('scripts/smoke-server-image.mjs')
+ expect(steps[upload]?.with).toEqual(
+ expect.objectContaining({
+ name: `server-size-report-${MATRIX_TARGET_EXPRESSION}`,
+ path: `release/size-reports/server-${MATRIX_TARGET_EXPRESSION}.json`,
+ 'if-no-files-found': 'error',
+ })
+ )
+ })
+
+ it('keeps package scripts and Docker regression assertions in CI', () => {
+ const manifest = JSON.parse(
+ readFileSync(path.join(ROOT, 'package.json'), 'utf8')
+ ) as { scripts?: Record<string, string> }
+ expect(manifest.scripts).toEqual(
+ expect.objectContaining({
+ 'stage:server': 'node scripts/stage-server-app.mjs',
+ 'verify:server-package': 'node scripts/verify-server-package.mjs',
+ 'smoke:server-package': 'node scripts/smoke-server-package.mjs',
+ 'smoke:server-image': 'node scripts/smoke-server-image.mjs',
+ })
+ )
+ const ciSteps = workflow.jobs?.ci?.steps ?? []
+ const releaseContract = ciSteps.find(
+ (step) => step.name === 'Release and packaging contracts'
+ )
+ expect(releaseContract?.run).toContain(
+ 'tests/scripts/docker-server-runtime.test.ts'
+ )
+ expect(releaseContract?.run).toContain(
+ 'tests/scripts/verify-server-package.test.ts'
+ )
+ })
+})
diff --git a/tests/scripts/smoke-server-package.test.ts b/tests/scripts/smoke-server-package.test.ts
new file mode 100644
index 00000000..49807555
--- /dev/null
+++ b/tests/scripts/smoke-server-package.test.ts
@@ -0,0 +1,141 @@
+import {
+ chmod,
+ cp,
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { smokeServerPackage } from '../../scripts/smoke-server-package.mjs'
+
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+async function writeFixtureFile(
+ root: string,
+ relativePath: string,
+ content: string
+): Promise<string> {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+ return target
+}
+
+async function createFixture(): Promise<{
+ stageRoot: string
+ aria2Bin: string
+}> {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-server-smoke-test-')
+ )
+ temporaryRoots.push(root)
+ const stageRoot = path.join(root, 'server-app')
+ await writeFixtureFile(
+ stageRoot,
+ 'package.json',
+ `${JSON.stringify(
+ {
+ name: '@motrix/server-runtime-fixture',
+ private: true,
+ type: 'module',
+ main: 'dist/server/index.cjs',
+ dependencies: { 'better-sqlite3': '13.0.3' },
+ },
+ null,
+ 2
+ )}\n`
+ )
+ const sourcePackage = await realpath(
+ path.resolve('node_modules/better-sqlite3')
+ )
+ await cp(sourcePackage, path.join(stageRoot, 'node_modules/better-sqlite3'), {
+ dereference: true,
+ recursive: true,
+ })
+ await writeFixtureFile(
+ stageRoot,
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ [
+ "const { parentPort } = require('node:worker_threads')",
+ "parentPort.on('message', (message) => {",
+ " if (message.type === 'init') parentPort.postMessage({ type: 'ready' })",
+ " if (message.type === 'event' && message.event === 'shutdown') process.exit(0)",
+ '})',
+ ].join('\n')
+ )
+ await writeFixtureFile(
+ stageRoot,
+ 'dist/server/index.cjs',
+ [
+ "const http = require('node:http')",
+ "const fs = require('node:fs')",
+ "const path = require('node:path')",
+ 'const token = process.env.MOTRIX_OPERATOR_TOKEN',
+ 'fs.mkdirSync(process.env.MOTRIX_DATA_DIR, { recursive: true })',
+ "fs.writeFileSync(path.join(process.env.MOTRIX_DATA_DIR, 'motrix.db'), Buffer.alloc(64, 1))",
+ 'const server = http.createServer((request, response) => {',
+ " response.setHeader('content-type', 'application/json')",
+ " if (request.url === '/healthz') { response.end('{\"ok\":true}'); return }",
+ " const authed = request.headers.authorization === 'Bearer ' + token",
+ " if (request.url === '/rpc/auth/status') { response.end(JSON.stringify({ authed })); return }",
+ ' if (!authed) { response.statusCode = 401; response.end(\'{"error":"unauthorized"}\'); return }',
+ ' response.statusCode = 404; response.end(\'{"error":"unknown channel"}\')',
+ '})',
+ "server.listen(Number(process.env.PORT), '0.0.0.0')",
+ "process.once('SIGTERM', () => server.close(() => process.exit(0)))",
+ ].join('\n')
+ )
+ await writeFixtureFile(
+ stageRoot,
+ 'dist/renderer-web/index.html',
+ '<main>ok</main>'
+ )
+ await writeFixtureFile(stageRoot, 'extra/aria2.conf', '')
+ await mkdir(path.join(stageRoot, 'builtin-plugins'), { recursive: true })
+ const aria2Bin = await writeFixtureFile(root, 'aria2c', '#!/bin/sh\nexit 0\n')
+ await chmod(aria2Bin, 0o755)
+ return { stageRoot, aria2Bin }
+}
+
+describe('smokeServerPackage', () => {
+ it('orchestrates staged roots, SQLite, worker, HTTP auth, and SIGTERM', async () => {
+ const fixture = await createFixture()
+ const result = await smokeServerPackage({
+ appDir: fixture.stageRoot,
+ aria2Bin: fixture.aria2Bin,
+ timeoutMs: 10_000,
+ })
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ directRoots: 1,
+ sqlite: true,
+ quickJsWorker: true,
+ health: true,
+ operatorAuth: true,
+ shutdown: 'SIGTERM',
+ })
+ )
+ expect(result.databaseBytes).toBeGreaterThan(0)
+ }, 20_000)
+
+ it('rejects a missing external aria2 prerequisite before startup', async () => {
+ const fixture = await createFixture()
+ await expect(
+ smokeServerPackage({
+ appDir: fixture.stageRoot,
+ aria2Bin: path.join(fixture.stageRoot, 'missing-aria2c'),
+ })
+ ).rejects.toThrow('aria2 binary is not a file')
+ })
+})
diff --git a/tests/scripts/stage-server-app.test.ts b/tests/scripts/stage-server-app.test.ts
new file mode 100644
index 00000000..7f93ae9f
--- /dev/null
+++ b/tests/scripts/stage-server-app.test.ts
@@ -0,0 +1,538 @@
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { stageServerApp } from '../../scripts/stage-server-app.mjs'
+
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+async function writeFixtureFile(
+ root: string,
+ relativePath: string,
+ content: string | Buffer = relativePath
+): Promise<void> {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+}
+
+function nativeHeader(platform: string, arch: string): Buffer {
+ if (platform === 'win32') {
+ const header = Buffer.alloc(72)
+ header.write('MZ')
+ header.writeUInt32LE(64, 0x3c)
+ header.set([0x50, 0x45, 0, 0], 64)
+ header.writeUInt16LE(arch === 'arm64' ? 0xaa64 : 0x8664, 68)
+ return header
+ }
+ if (platform === 'linux') {
+ const header = Buffer.alloc(20)
+ header.set([0x7f, 0x45, 0x4c, 0x46])
+ header[4] = 2
+ header[5] = 1
+ header.writeUInt16LE(arch === 'arm64' ? 183 : 62, 18)
+ return header
+ }
+ const header = Buffer.alloc(8)
+ header.set([0xcf, 0xfa, 0xed, 0xfe])
+ header.writeUInt32LE(arch === 'arm64' ? 0x0100000c : 0x01000007, 4)
+ return header
+}
+
+const nativeTargets = [
+ {
+ key: 'darwin-arm64',
+ platform: 'darwin',
+ arch: 'arm64',
+ prebuild: 'darwin-arm64.node',
+ },
+ {
+ key: 'darwin-x64',
+ platform: 'darwin',
+ arch: 'x64',
+ prebuild: 'darwin-x64.node',
+ },
+ {
+ key: 'linux-arm64-gnu',
+ platform: 'linux',
+ arch: 'arm64',
+ libc: 'gnu',
+ prebuild: 'linux-arm64.node',
+ },
+ {
+ key: 'linux-arm64-musl',
+ platform: 'linux',
+ arch: 'arm64',
+ libc: 'musl',
+ prebuild: 'linuxmusl-arm64.node',
+ },
+ {
+ key: 'linux-x64-gnu',
+ platform: 'linux',
+ arch: 'x64',
+ libc: 'gnu',
+ prebuild: 'linux-x64.node',
+ },
+ {
+ key: 'linux-x64-musl',
+ platform: 'linux',
+ arch: 'x64',
+ libc: 'musl',
+ prebuild: 'linuxmusl-x64.node',
+ },
+ {
+ key: 'win32-x64',
+ platform: 'win32',
+ arch: 'x64',
+ prebuild: 'win32-x64.node',
+ },
+] as const
+
+async function writePackage(
+ root: string,
+ relativePath: string,
+ manifest: {
+ name: string
+ version: string
+ type?: string
+ exports?: unknown
+ dependencies?: Record<string, string>
+ optionalDependencies?: Record<string, string>
+ os?: string[]
+ cpu?: string[]
+ }
+): Promise<void> {
+ await writeFixtureFile(
+ root,
+ `${relativePath}/package.json`,
+ `${JSON.stringify({ main: 'index.js', ...manifest }, null, 2)}\n`
+ )
+ await writeFixtureFile(
+ root,
+ `${relativePath}/index.js`,
+ manifest.type === 'module'
+ ? 'export default true\n'
+ : 'module.exports = true\n'
+ )
+}
+
+function fixtureContract() {
+ return {
+ schemaVersion: 1,
+ supportedTargets: [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64-gnu',
+ 'linux-arm64-musl',
+ 'linux-x64-gnu',
+ 'linux-x64-musl',
+ 'win32-x64',
+ ],
+ runtimeRoots: ['@scope/pkg', 'alpha', 'gamma'],
+ buildInputs: [
+ {
+ source: 'dist/core/plugin/host/quick-js-worker.cjs',
+ destination: 'dist/core/plugin/host/quick-js-worker.cjs',
+ type: 'file',
+ entry: null,
+ scanExternals: true,
+ },
+ {
+ source: 'dist/renderer-web',
+ destination: 'dist/renderer-web',
+ type: 'directory',
+ entry: 'index.html',
+ scanExternals: false,
+ },
+ {
+ source: 'dist/server',
+ destination: 'dist/server',
+ type: 'directory',
+ entry: 'index.mjs',
+ scanExternals: true,
+ },
+ ],
+ resourceInputs: [
+ {
+ source: 'legal/notice.txt',
+ destination: 'legal/notice.txt',
+ type: 'file',
+ },
+ ],
+ }
+}
+
+function fixtureBudgets() {
+ return {
+ schemaVersion: 1,
+ artifactBytes: 100_000_000,
+ dependencyBytes: 80_000_000,
+ packageInstances: 100,
+ unexpectedRuntimeRoots: 0,
+ unresolvedExternals: 0,
+ foreignNativeBinaries: 0,
+ betterSqlite3Prebuilds: 1,
+ }
+}
+
+async function createFixture(): Promise<string> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-stage-'))
+ temporaryRoots.push(root)
+ await writeFixtureFile(
+ root,
+ 'package.json',
+ `${JSON.stringify(
+ {
+ name: 'motrix-source-fixture',
+ productName: 'Motrix Fixture',
+ version: '1.2.3',
+ description: 'fixture',
+ homepage: 'https://example.test',
+ author: { name: 'Motrix' },
+ license: 'MIT',
+ private: true,
+ scripts: { forbidden: 'true' },
+ devDependencies: { forbidden: '1.0.0' },
+ dependencies: {
+ '@scope/pkg': '1.0.0',
+ alpha: '1.0.0',
+ gamma: '1.0.0',
+ unrelated: '1.0.0',
+ },
+ },
+ null,
+ 2
+ )}\n`
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/server/index.mjs',
+ [
+ 'import alpha from "alpha/subpath";',
+ 'import gamma from "gamma";',
+ 'export { alpha, gamma };',
+ ].join('\n')
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'module.exports = require("@scope/pkg")\n'
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/renderer-web/index.html',
+ '<main>ok</main>'
+ )
+ await writeFixtureFile(root, 'legal/notice.txt', 'legal')
+ await writeFixtureFile(root, 'dist/main/forbidden.cjs', 'forbidden')
+
+ await writePackage(root, 'node_modules/alpha', {
+ name: 'alpha',
+ version: '1.0.0',
+ type: 'module',
+ exports: {
+ '.': { import: './index.js' },
+ './subpath': { import: './subpath.js' },
+ },
+ dependencies: { beta: '1.0.0', shared: '1.0.0' },
+ optionalDependencies: {
+ 'linux-only': '1.0.0',
+ 'missing-native': '1.0.0',
+ },
+ })
+ await writeFixtureFile(
+ root,
+ 'node_modules/alpha/subpath.js',
+ 'export default true\n'
+ )
+ await writePackage(root, 'node_modules/beta', {
+ name: 'beta',
+ version: '1.0.0',
+ dependencies: { alpha: '1.0.0' },
+ })
+ await writePackage(root, 'node_modules/shared', {
+ name: 'shared',
+ version: '1.0.0',
+ })
+ await writePackage(root, 'node_modules/gamma', {
+ name: 'gamma',
+ version: '1.0.0',
+ dependencies: { shared: '2.0.0' },
+ })
+ await writePackage(root, 'node_modules/gamma/node_modules/shared', {
+ name: 'shared',
+ version: '2.0.0',
+ })
+ await writePackage(root, 'node_modules/@scope/pkg', {
+ name: '@scope/pkg',
+ version: '1.0.0',
+ })
+ await writePackage(root, 'node_modules/linux-only', {
+ name: 'linux-only',
+ version: '1.0.0',
+ os: ['linux'],
+ })
+ return root
+}
+
+async function addBetterSqliteFixture(root: string): Promise<void> {
+ const rootManifestPath = path.join(root, 'package.json')
+ const rootManifest = JSON.parse(await readFile(rootManifestPath, 'utf8'))
+ rootManifest.dependencies['better-sqlite3'] = '13.0.3'
+ await writeFile(
+ rootManifestPath,
+ `${JSON.stringify(rootManifest, null, 2)}\n`
+ )
+ await writePackage(root, 'node_modules/better-sqlite3', {
+ name: 'better-sqlite3',
+ version: '13.0.3',
+ })
+ const packageManifestPath = path.join(
+ root,
+ 'node_modules/better-sqlite3/package.json'
+ )
+ const packageManifest = JSON.parse(
+ await readFile(packageManifestPath, 'utf8')
+ )
+ packageManifest.main = 'lib/index.js'
+ await writeFile(
+ packageManifestPath,
+ `${JSON.stringify(packageManifest, null, 2)}\n`
+ )
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/LICENSE', 'MIT')
+ await writeFixtureFile(
+ root,
+ 'node_modules/better-sqlite3/lib/index.js',
+ 'module.exports = true\n'
+ )
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/src/leak.cc')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/deps/leak.c')
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/binding.gyp')
+ for (const target of nativeTargets) {
+ await writeFixtureFile(
+ root,
+ `node_modules/better-sqlite3/prebuilds/${target.prebuild}`,
+ nativeHeader(target.platform, target.arch)
+ )
+ }
+ await writeFixtureFile(
+ root,
+ 'dist/server/index.mjs',
+ [
+ 'import alpha from "alpha/subpath";',
+ 'import Database from "better-sqlite3";',
+ 'import gamma from "gamma";',
+ 'export { alpha, Database, gamma };',
+ ].join('\n')
+ )
+}
+
+async function listSymlinks(root: string): Promise<string[]> {
+ const result: string[] = []
+ async function walk(directory: string): Promise<void> {
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
+ const entryPath = path.join(directory, entry.name)
+ const info = await lstat(entryPath)
+ if (info.isSymbolicLink()) result.push(entryPath)
+ else if (info.isDirectory()) await walk(entryPath)
+ }
+ }
+ await walk(root)
+ return result
+}
+
+describe('stageServerApp', () => {
+ it.each(nativeTargets)(
+ 'keeps only the $key better-sqlite3 prebuild',
+ async (target) => {
+ const root = await createFixture()
+ await addBetterSqliteFixture(root)
+ const contract = fixtureContract()
+ contract.runtimeRoots.splice(2, 0, 'better-sqlite3')
+ await stageServerApp({
+ repoRoot: root,
+ platform: target.platform,
+ arch: target.arch,
+ ...('libc' in target ? { libc: target.libc } : {}),
+ strict: true,
+ contract,
+ budgets: fixtureBudgets(),
+ })
+
+ const packageRoot = path.join(
+ root,
+ 'dist/server-app/node_modules/better-sqlite3'
+ )
+ expect(await readdir(path.join(packageRoot, 'prebuilds'))).toEqual([
+ target.prebuild,
+ ])
+ await expect(stat(path.join(packageRoot, 'src'))).rejects.toThrow()
+ await expect(stat(path.join(packageRoot, 'deps'))).rejects.toThrow()
+ await expect(
+ stat(path.join(packageRoot, 'binding.gyp'))
+ ).rejects.toThrow()
+ }
+ )
+
+ it('creates an atomic minimal Server app with the exact dependency closure', async () => {
+ const root = await createFixture()
+ const sourceTimestamp = (await stat(path.join(root, 'node_modules/alpha')))
+ .mtimeMs
+ const result = await stageServerApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ const stageRoot = path.join(root, 'dist/server-app')
+ const stage = JSON.parse(
+ await readFile(path.join(stageRoot, '.motrix-server-stage.json'), 'utf8')
+ )
+ const manifest = JSON.parse(
+ await readFile(path.join(stageRoot, 'package.json'), 'utf8')
+ )
+ expect(result.manifest).toEqual(stage)
+ expect(manifest).toEqual({
+ name: '@motrix/server-runtime',
+ productName: 'Motrix Fixture',
+ version: '1.2.3',
+ description: 'fixture',
+ homepage: 'https://example.test',
+ author: { name: 'Motrix' },
+ license: 'MIT',
+ private: true,
+ type: 'module',
+ main: 'dist/server/index.mjs',
+ engines: { node: '>=24' },
+ dependencies: {
+ '@scope/pkg': '1.0.0',
+ alpha: '1.0.0',
+ gamma: '1.0.0',
+ },
+ })
+ expect(stage.target).toEqual({
+ platform: 'darwin',
+ arch: 'arm64',
+ key: 'darwin-arm64',
+ })
+ expect(stage.externals.roots).toEqual(['@scope/pkg', 'alpha', 'gamma'])
+ expect(stage.optionalOmissions).toEqual([
+ { name: 'linux-only', requestedBy: '[email protected]' },
+ { name: 'missing-native', requestedBy: '[email protected]' },
+ ])
+ expect(
+ stage.packages.map(
+ (entry: { name: string; version: string }) =>
+ `${entry.name}@${entry.version}`
+ )
+ ).toEqual(
+ expect.arrayContaining([
+ '@scope/[email protected]',
+ ])
+ )
+ expect(stage.inputFingerprints).toHaveLength(4)
+ expect(
+ await readFile(path.join(stageRoot, 'legal/notice.txt'), 'utf8')
+ ).toBe('legal')
+ await expect(stat(path.join(stageRoot, 'dist/main'))).rejects.toThrow()
+ await expect(
+ stat(path.join(stageRoot, 'node_modules/unrelated'))
+ ).rejects.toThrow()
+ expect(await listSymlinks(stageRoot)).toEqual([])
+ expect((await stat(path.join(root, 'node_modules/alpha'))).mtimeMs).toBe(
+ sourceTimestamp
+ )
+ })
+
+ it('preserves the last valid stage after an input failure', async () => {
+ const root = await createFixture()
+ const options = {
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ }
+ await stageServerApp(options)
+ await writeFixtureFile(root, 'dist/server-app/previous.txt', 'preserved')
+ await rm(path.join(root, 'dist/server/index.mjs'))
+ await expect(stageServerApp(options)).rejects.toThrow('missing build entry')
+ expect(
+ await readFile(path.join(root, 'dist/server-app/previous.txt'), 'utf8')
+ ).toBe('preserved')
+ })
+
+ it('rejects a top-level symlink input and an output escape', async () => {
+ const root = await createFixture()
+ const external = await mkdtemp(path.join(os.tmpdir(), 'motrix-external-'))
+ temporaryRoots.push(external)
+ await writeFixtureFile(external, 'notice.txt', 'outside')
+ await rm(path.join(root, 'legal/notice.txt'))
+ await symlink(
+ path.join(external, 'notice.txt'),
+ path.join(root, 'legal/notice.txt')
+ )
+ await expect(
+ stageServerApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ ).rejects.toThrow('symlink')
+
+ await expect(
+ stageServerApp({
+ repoRoot: root,
+ outputDir: path.join(path.dirname(root), 'escaped-stage'),
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ ).rejects.toThrow('must stay within repository root')
+ })
+
+ it('rejects a missing required dependency without emitting a stage', async () => {
+ const root = await createFixture()
+ await rm(path.join(root, 'node_modules/gamma'), { recursive: true })
+ await expect(
+ stageServerApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ ).rejects.toThrow('runtime root gamma is not installed')
+ await expect(stat(path.join(root, 'dist/server-app'))).rejects.toThrow()
+ })
+})
diff --git a/tests/scripts/verify-server-package.test.ts b/tests/scripts/verify-server-package.test.ts
new file mode 100644
index 00000000..9b889c80
--- /dev/null
+++ b/tests/scripts/verify-server-package.test.ts
@@ -0,0 +1,303 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { stageServerApp } from '../../scripts/stage-server-app.mjs'
+import { verifyServerPackage } from '../../scripts/verify-server-package.mjs'
+
+const temporaryRoots: string[] = []
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))
+ )
+})
+
+async function writeFixtureFile(
+ root: string,
+ relativePath: string,
+ content: string | Buffer = relativePath
+): Promise<void> {
+ const target = path.join(root, relativePath)
+ await mkdir(path.dirname(target), { recursive: true })
+ await writeFile(target, content)
+}
+
+function nativeHeader(platform: string, arch: string): Buffer {
+ if (platform === 'win32') {
+ const header = Buffer.alloc(72)
+ header.write('MZ')
+ header.writeUInt32LE(64, 0x3c)
+ header.set([0x50, 0x45, 0, 0], 64)
+ header.writeUInt16LE(arch === 'arm64' ? 0xaa64 : 0x8664, 68)
+ return header
+ }
+ if (platform === 'linux') {
+ const header = Buffer.alloc(20)
+ header.set([0x7f, 0x45, 0x4c, 0x46])
+ header[4] = 2
+ header[5] = 1
+ header.writeUInt16LE(arch === 'arm64' ? 183 : 62, 18)
+ return header
+ }
+ const header = Buffer.alloc(8)
+ header.set([0xcf, 0xfa, 0xed, 0xfe])
+ header.writeUInt32LE(arch === 'arm64' ? 0x0100000c : 0x01000007, 4)
+ return header
+}
+
+function fixtureContract() {
+ return {
+ schemaVersion: 1,
+ supportedTargets: [
+ 'darwin-arm64',
+ 'darwin-x64',
+ 'linux-arm64-gnu',
+ 'linux-arm64-musl',
+ 'linux-x64-gnu',
+ 'linux-x64-musl',
+ 'win32-x64',
+ ],
+ runtimeRoots: ['better-sqlite3'],
+ buildInputs: [
+ {
+ source: 'dist/core/plugin/host/quick-js-worker.cjs',
+ destination: 'dist/core/plugin/host/quick-js-worker.cjs',
+ type: 'file',
+ entry: null,
+ scanExternals: true,
+ },
+ {
+ source: 'dist/renderer-web',
+ destination: 'dist/renderer-web',
+ type: 'directory',
+ entry: 'index.html',
+ scanExternals: false,
+ },
+ {
+ source: 'dist/server',
+ destination: 'dist/server',
+ type: 'directory',
+ entry: 'index.mjs',
+ scanExternals: true,
+ },
+ ],
+ resourceInputs: [
+ {
+ source: 'legal/notice.txt',
+ destination: 'legal/notice.txt',
+ type: 'file',
+ },
+ ],
+ }
+}
+
+function fixtureBudgets(overrides: Record<string, number> = {}) {
+ return {
+ schemaVersion: 1,
+ artifactBytes: 1_000_000,
+ dependencyBytes: 1_000_000,
+ packageInstances: 10,
+ unexpectedRuntimeRoots: 0,
+ unresolvedExternals: 0,
+ foreignNativeBinaries: 0,
+ betterSqlite3Prebuilds: 1,
+ ...overrides,
+ }
+}
+
+async function createStagedFixture(): Promise<{
+ root: string
+ stageRoot: string
+ reportPath: string
+}> {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-verify-'))
+ temporaryRoots.push(root)
+ await writeFixtureFile(
+ root,
+ 'package.json',
+ `${JSON.stringify(
+ {
+ name: 'motrix-server-fixture',
+ version: '1.0.0',
+ license: 'MIT',
+ dependencies: { 'better-sqlite3': '13.0.3' },
+ },
+ null,
+ 2
+ )}\n`
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/server/index.mjs',
+ 'import Database from "better-sqlite3"; export default Database\n'
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/core/plugin/host/quick-js-worker.cjs',
+ 'module.exports = require("node:path")\n'
+ )
+ await writeFixtureFile(
+ root,
+ 'dist/renderer-web/index.html',
+ '<main>ok</main>'
+ )
+ await writeFixtureFile(root, 'legal/notice.txt', 'legal')
+ await writeFixtureFile(
+ root,
+ 'node_modules/better-sqlite3/package.json',
+ `${JSON.stringify(
+ {
+ name: 'better-sqlite3',
+ version: '13.0.3',
+ main: 'lib/index.js',
+ },
+ null,
+ 2
+ )}\n`
+ )
+ await writeFixtureFile(
+ root,
+ 'node_modules/better-sqlite3/lib/index.js',
+ 'module.exports = true\n'
+ )
+ await writeFixtureFile(root, 'node_modules/better-sqlite3/LICENSE', 'MIT')
+ for (const [name, platform, arch] of [
+ ['darwin-arm64.node', 'darwin', 'arm64'],
+ ['darwin-x64.node', 'darwin', 'x64'],
+ ['linux-arm64.node', 'linux', 'arm64'],
+ ['linux-x64.node', 'linux', 'x64'],
+ ['linuxmusl-arm64.node', 'linux', 'arm64'],
+ ['linuxmusl-x64.node', 'linux', 'x64'],
+ ['win32-x64.node', 'win32', 'x64'],
+ ]) {
+ await writeFixtureFile(
+ root,
+ `node_modules/better-sqlite3/prebuilds/${name}`,
+ nativeHeader(platform, arch)
+ )
+ }
+ await stageServerApp({
+ repoRoot: root,
+ platform: 'darwin',
+ arch: 'arm64',
+ strict: true,
+ contract: fixtureContract(),
+ budgets: fixtureBudgets(),
+ })
+ return {
+ root,
+ stageRoot: path.join(root, 'dist/server-app'),
+ reportPath: path.join(root, 'reports/server-darwin-arm64.json'),
+ }
+}
+
+async function verifyFixture(
+ fixture: Awaited<ReturnType<typeof createStagedFixture>>,
+ budgets = fixtureBudgets()
+) {
+ return verifyServerPackage({
+ appDir: fixture.stageRoot,
+ platform: 'darwin',
+ arch: 'arm64',
+ contract: fixtureContract(),
+ budgets,
+ reportPath: fixture.reportPath,
+ })
+}
+
+describe('verifyServerPackage', () => {
+ it('accepts an intact staged Server artifact and emits a sanitized report', async () => {
+ const fixture = await createStagedFixture()
+ const report = await verifyFixture(fixture)
+
+ expect(report.passed).toBe(true)
+ expect(report.metrics.packageInstances).toBe(1)
+ expect(report.metrics.betterSqlite3Prebuilds).toBe(1)
+ expect(report.metrics.foreignNativeBinaries).toBe(0)
+ const reportJson = await readFile(fixture.reportPath, 'utf8')
+ expect(reportJson).not.toContain(fixture.root)
+ expect(JSON.parse(reportJson)).toEqual(report)
+ })
+
+ it('fails closed on content drift and still writes the JSON report', async () => {
+ const fixture = await createStagedFixture()
+ await writeFixtureFile(
+ fixture.stageRoot,
+ 'dist/server/index.mjs',
+ 'export default "tampered"\n'
+ )
+
+ await expect(verifyFixture(fixture)).rejects.toThrow('input-fingerprints')
+ const report = JSON.parse(await readFile(fixture.reportPath, 'utf8'))
+ expect(report.passed).toBe(false)
+ expect(report.checks).toContainEqual(
+ expect.objectContaining({ id: 'input-fingerprints', passed: false })
+ )
+ })
+
+ it('rejects target drift and foreign native binaries', async () => {
+ const fixture = await createStagedFixture()
+ const stageManifestPath = path.join(
+ fixture.stageRoot,
+ '.motrix-server-stage.json'
+ )
+ const stageManifest = JSON.parse(await readFile(stageManifestPath, 'utf8'))
+ stageManifest.target.key = 'darwin-x64'
+ await writeFile(stageManifestPath, `${JSON.stringify(stageManifest)}\n`)
+ await writeFixtureFile(
+ fixture.stageRoot,
+ 'node_modules/better-sqlite3/prebuilds/win32-x64.node',
+ nativeHeader('win32', 'x64')
+ )
+
+ await expect(verifyFixture(fixture)).rejects.toThrow('target')
+ const report = JSON.parse(await readFile(fixture.reportPath, 'utf8'))
+ expect(report.metrics.foreignNativeBinaries).toBe(1)
+ expect(report.metrics.betterSqlite3Prebuilds).toBe(2)
+ })
+
+ it('rejects manifest roots, package closure drift, and tight budgets', async () => {
+ const fixture = await createStagedFixture()
+ const appManifestPath = path.join(fixture.stageRoot, 'package.json')
+ const appManifest = JSON.parse(await readFile(appManifestPath, 'utf8'))
+ appManifest.dependencies.unexpected = '1.0.0'
+ await writeFile(appManifestPath, `${JSON.stringify(appManifest)}\n`)
+ await writeFixtureFile(
+ fixture.stageRoot,
+ 'node_modules/unexpected/package.json',
+ '{"name":"unexpected","version":"1.0.0"}\n'
+ )
+
+ await expect(
+ verifyFixture(fixture, fixtureBudgets({ artifactBytes: 1 }))
+ ).rejects.toThrow('application-manifest')
+ const report = JSON.parse(await readFile(fixture.reportPath, 'utf8'))
+ expect(report.metrics.unexpectedRuntimeRoots).toBe(1)
+ expect(report.checks).toContainEqual(
+ expect.objectContaining({ id: 'package-closure', passed: false })
+ )
+ expect(report.checks).toContainEqual(
+ expect.objectContaining({ id: 'size-budgets', passed: false })
+ )
+ })
+
+ it('rejects symlinks in the staged artifact', async () => {
+ const fixture = await createStagedFixture()
+ await symlink(
+ path.join(fixture.stageRoot, 'legal/notice.txt'),
+ path.join(fixture.stageRoot, 'legal/notice-link.txt')
+ )
+
+ await expect(verifyFixture(fixture)).rejects.toThrow('symlinks')
+ const report = JSON.parse(await readFile(fixture.reportPath, 'utf8'))
+ expect(report.passed).toBe(false)
+ })
+})