Skip to content

A full-featured download manager.

fix(server): support Docker extension bridge startup (#2055)

Dr_rOot2712720d45c6
diff --git a/.claude/rules/bridge.md b/.claude/rules/bridge.md
index 83b6d3eb..d10191c9 100644
--- a/.claude/rules/bridge.md
+++ b/.claude/rules/bridge.md
@@ -72,6 +72,14 @@ that is not `127.0.0.1`, `localhost`, or `[::1]` with the bound port — the §4
DNS-rebinding guard. It is inert for a non-loopback bind, which keeps its
existing token + reverse-proxy model.
+The Server's documented Docker path deliberately binds MDXP to `0.0.0.0`
+inside the container so Docker can publish port 16801. Remote Extension routes
+may use that non-loopback listener only behind a parser-issued, all-or-nothing
+remote configuration; `RemoteExtensionSurfacePolicy` then enforces the exact
+public Host and raw route prefix plus the admission limits before MBP1 runs.
+Do not reintroduce a loopback-only bootstrap guard: container loopback is not
+reachable through Docker's published-port path.
+
`GET /discovery` additionally reports unauthenticated compatibility hints:
`runtime`, `extensionPairing: { protocol: 'mbp1', versions: [1] }`, and
`applicationProtocols: { mdxp: ['1.0'] }`. They may drive an upgrade message,
diff --git a/.dockerignore b/.dockerignore
index cf829e43..cc192984 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,8 +1,10 @@
.git
+.worktrees
.agents
.claude
.codex
.vite
+**/target
dist
release
node_modules
diff --git a/Dockerfile b/Dockerfile
index b8eb0c7b..6204ec88 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -113,7 +113,7 @@ ENV YARN_VERSION= \
TMPDIR=/data/tmp \
PORT=8080
VOLUME ["/data", "/downloads"]
-EXPOSE 8080
+EXPOSE 8080 16801
USER node
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'8080')+'/healthz').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
@@ -160,7 +160,7 @@ ENV YARN_VERSION= \
TMPDIR=/data/tmp \
PORT=8080
VOLUME ["/data", "/downloads"]
-EXPOSE 8080
+EXPOSE 8080 16801
USER node
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'8080')+'/healthz').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
diff --git a/docs/docker-server.md b/docs/docker-server.md
index bd922683..899a8c9e 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -506,12 +506,47 @@ detection.
| `no matching manifest` | Confirm the NAS is 64-bit `amd64` or `arm64` with `docker info`; 32-bit ARM is unsupported. |
| Startup reports `EACCES`, read-only, or a path failure | Compare `docker inspect ... .Config.User` with numeric ownership of both mounts. Correct ownership/ACLs; do not run privileged or as root. |
| Port is already allocated | Change `MOTRIX_HTTP_PORT` or `MOTRIX_MDXP_PUBLIC_PORT`, and update `MOTRIX_PUBLIC_URL` if the Web port changes. |
+| Web UI is healthy but port 16801 refuses connections | Look for `bridge data ownership unavailable` and inspect its `stage` and `reason` fields. If ownership is ready, verify the MDXP publish address and all four remote Extension variables. |
| External aria2 RPC client cannot connect | Confirm `MOTRIX_ARIA2_RPC_LISTEN_ALL=true`, a non-empty matching RPC secret, the correct 16800 mapping (or configured RPC port), and the host firewall. The standard Compose files do not publish this port. |
| Web UI opens but unlock fails | Read the current persistent `/data/operator-token`; do not use a token copied from another deployment. Verify the file is regular, base64url text, and mode `0600`. |
| Download directory is rejected or files are missing from the NAS share | Use an absolute container path below `MOTRIX_ALLOWED_SAVE_DIRS`; verify the intended host directory is mounted at that exact path and writable by the runtime UID/GID. |
| Plugin install fails | Inspect `/api/diagnostics` and logs, retain `/data`, confirm package/source trust and network/TLS access, and mount any `MOTRIX_PLUGIN_IMPORT_DIRS` explicitly. Do not enable unmanaged plugins for a normal `.moext`, URL, or registry install. |
| Container is unhealthy after an upgrade | Inspect logs and diagnostics, verify both mounts, then roll back to the recorded immutable image and matching `/data` backup. |
+### Recover an invalid bridge ownership record
+
+The Server logs a fixed `reason` when
+`/data/.motrix-server-bridge-owner.json` cannot establish process ownership.
+Reasons distinguish inaccessible metadata, a non-regular or multiply linked
+file, owner or write-permission problems, malformed/non-canonical content, and
+stale port or bridge-directory values. The record contains no credential, but
+its integrity authorizes safe recovery of a stale bridge lock, so Motrix never
+silently replaces a conflicting record.
+
+First stop every container that uses the same `/data` mount:
+
+```bash
+docker compose down
+```
+
+Inspect the record on the Docker host. It must be owned by the configured
+runtime UID, must not be writable by group or other users, and normally has
+mode `0600`. Read-only group/other access inherited from a NAS ACL is accepted.
+For `binding-owner-mismatch` or `binding-insecure-mode`, correct the host
+ownership or remove group/other write access. For a stale or malformed record,
+retain it as a backup before restarting:
+
+```bash
+mv ./motrix-data/.motrix-server-bridge-owner.json \
+ ./motrix-data/.motrix-server-bridge-owner.json.bak
+docker compose up -d --wait
+```
+
+Motrix creates a new `0600` record after it owns the Web control-plane port.
+Keep the backup until both `/healthz` and the MDXP `/discovery` endpoint work.
+Do not manually remove files below `/data/bridge/`; stale bridge-lock recovery
+uses this ownership record and the already-bound Web listener as one proof.
+
## Environment reference
| Variable | Image default | Notes |
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index 3c45cd6e..21de3044 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -450,12 +450,42 @@ secret-store 状态和 FFmpeg 探测结果。
| `no matching manifest` | 用 `docker info` 确认 NAS 是 64 位 `amd64` 或 `arm64`;不支持 32 位 ARM。 |
| 启动报告 `EACCES`、只读或路径失败 | 对比 `docker inspect ... .Config.User` 与两个挂载的数字 owner。修正 owner/ACL;不要改用 privileged 或 root。 |
| 端口已分配 | 修改 `MOTRIX_HTTP_PORT` 或 `MOTRIX_MDXP_PUBLIC_PORT`;Web 端口变化时同步更新 `MOTRIX_PUBLIC_URL`。 |
+| Web 界面健康但连接 16801 被拒绝 | 查找 `bridge data ownership unavailable`,检查日志中的 `stage` 和 `reason` 字段。ownership 就绪时,再核对 MDXP 发布地址和四个远程 Extension 变量。 |
| 外部 aria2 RPC 客户端无法连接 | 确认 `MOTRIX_ARIA2_RPC_LISTEN_ALL=true`、RPC secret 非空且匹配、16800(或自定义 RPC 端口)映射正确,并检查宿主 firewall。标准 Compose 文件不会发布该端口。 |
| Web 能打开但无法解锁 | 读取当前持久化 `/data/operator-token`,不要使用另一套部署的 token。确认它是普通文件、内容为 base64url 文本且权限为 `0600`。 |
| 下载目录被拒绝或 NAS 共享目录中没有文件 | 使用 `MOTRIX_ALLOWED_SAVE_DIRS` 下的绝对容器路径;确认目标宿主目录正好挂载到该路径,并允许 runtime UID/GID 写入。 |
| 插件安装失败 | 检查 `/api/diagnostics` 与日志,保留 `/data`,核实包/来源可信且网络/TLS 可达;显式挂载所有 `MOTRIX_PLUGIN_IMPORT_DIRS`。正常 `.moext`、URL 或 registry 安装不要开启 unmanaged plugins。 |
| 升级后容器 unhealthy | 检查日志、诊断和两个挂载,然后回滚到已记录的不可变镜像及其配套 `/data` 备份。 |
+### 恢复无效的 bridge ownership 记录
+
+当 `/data/.motrix-server-bridge-owner.json` 无法建立进程 ownership 时,Server
+会在日志中输出固定的 `reason`。不同 reason 可区分元数据不可访问、文件不是普通文件或有
+多个硬链接、owner/写权限不安全、内容损坏或非规范,以及端口或 bridge 目录记录过期。
+该文件不含凭据,但其完整性用于授权安全恢复遗留的 bridge lock,因此 Motrix 不会静默覆盖
+存在冲突的记录。
+
+首先停止所有使用同一 `/data` 挂载的容器:
+
+```bash
+docker compose down
+```
+
+然后在 Docker 宿主上检查该文件。它必须属于配置的 runtime UID,group 和 other 不得有
+写权限,通常应为 `0600`。NAS ACL 继承的 group/other 只读权限可以保留。若 reason 是
+`binding-owner-mismatch` 或 `binding-insecure-mode`,应修正宿主 owner 或去掉 group/other
+写权限。若记录过期或损坏,重启前先将其保留为备份:
+
+```bash
+mv ./motrix-data/.motrix-server-bridge-owner.json \
+ ./motrix-data/.motrix-server-bridge-owner.json.bak
+docker compose up -d --wait
+```
+
+Motrix 在持有 Web 控制面端口后会创建新的 `0600` 记录。在 `/healthz` 和 MDXP
+`/discovery` endpoint 都正常前请保留备份。不要手动删除 `/data/bridge/` 下的文件;遗留
+bridge lock 的恢复会把该 ownership 记录与已绑定的 Web listener 共同作为证明。
+
## 环境变量参考
| 变量 | 镜像默认值 | 说明 |
diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjs
index 6ca7ea7d..5fb94b9f 100644
--- a/scripts/smoke-server-image.mjs
+++ b/scripts/smoke-server-image.mjs
@@ -11,7 +11,7 @@ import {
stat,
writeFile,
} from 'node:fs/promises'
-import { createServer } from 'node:http'
+import { createServer, request as httpRequest } from 'node:http'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
@@ -102,15 +102,17 @@ async function pathExists(target) {
}
}
-async function containerPort(name, timeoutMs) {
+async function containerPort(name, internalPort, label, timeoutMs) {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
- const output = await docker(['port', name, '8080/tcp']).catch(() => '')
+ const output = await docker(['port', name, `${internalPort}/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')
+ throw new Error(`Docker did not publish the Server ${label} port`)
}
async function containerExited(name) {
@@ -271,6 +273,90 @@ async function requestJson(url, options = {}, expectedStatus) {
return body
}
+function requestPublishedBridge({ port, path, method = 'GET', host }) {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest(
+ {
+ host: '127.0.0.1',
+ port,
+ path,
+ method,
+ headers: {
+ host,
+ connection: 'close',
+ ...(method === 'POST'
+ ? {
+ 'content-length': '0',
+ 'x-motrix-bridge': '1',
+ }
+ : {}),
+ },
+ },
+ (response) => {
+ let body = ''
+ response.setEncoding('utf8')
+ response.on('data', (chunk) => {
+ body += chunk
+ })
+ response.once('end', () => {
+ let parsed = null
+ try {
+ parsed = body === '' ? null : JSON.parse(body)
+ } catch {
+ parsed = body
+ }
+ resolve({ status: response.statusCode ?? 0, body: parsed })
+ })
+ }
+ )
+ request.once('error', reject)
+ request.end()
+ })
+}
+
+async function assertRemoteExtensionSurface(name, timeoutMs) {
+ const port = await containerPort(name, 16801, 'MDXP', timeoutMs)
+ const publicAuthority = `${name}:16801`
+ const deadline = Date.now() + timeoutMs
+ let lastResult = 'not ready'
+ while (Date.now() < deadline) {
+ try {
+ const discovery = await requestPublishedBridge({
+ port,
+ path: '/discovery',
+ host: publicAuthority,
+ })
+ lastResult = JSON.stringify(discovery)
+ if (
+ discovery.status === 200 &&
+ discovery.body?.runtime === 'server' &&
+ discovery.body?.extensionPairing?.protocol === 'mbp1'
+ ) {
+ const nonce = await requestPublishedBridge({
+ port,
+ path: '/nonce',
+ method: 'POST',
+ host: publicAuthority,
+ })
+ if (
+ nonce.status === 200 &&
+ typeof nonce.body?.nonce === 'string' &&
+ /^[A-Za-z0-9_-]+$/.test(nonce.body.nonce)
+ ) {
+ return port
+ }
+ lastResult = JSON.stringify(nonce)
+ }
+ } catch (error) {
+ lastResult = error instanceof Error ? error.message : String(error)
+ }
+ await delay(150)
+ }
+ throw new Error(
+ `remote Extension routes did not become ready through the published MDXP port: ${lastResult}`
+ )
+}
+
async function rpc(url, token, kind, channel, ...args) {
return requestJson(`${url}/rpc/${kind}/${encodeURIComponent(channel)}`, {
method: 'POST',
@@ -525,16 +611,28 @@ async function startServerContainer(options) {
'--env',
`MOTRIX_OPERATOR_TOKEN=${operatorToken}`,
'--env',
- 'MOTRIX_MDXP_PORT=0',
+ 'MOTRIX_MDXP_HOST=0.0.0.0',
+ '--env',
+ 'MOTRIX_MDXP_PORT=16801',
+ '--env',
+ `MOTRIX_PUBLIC_URL=http://${name}:8080`,
+ '--env',
+ 'MOTRIX_REMOTE_EXTENSION_ENABLED=true',
+ '--env',
+ `MOTRIX_REMOTE_EXTENSION_PUBLIC_URL=ws://${name}:16801`,
+ '--env',
+ 'MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true',
'--mount',
`type=bind,source=${dataDir},target=/data`,
'--mount',
`type=bind,source=${downloadsDir},target=/downloads`,
'--publish',
'127.0.0.1::8080',
+ '--publish',
+ '127.0.0.1::16801',
image,
])
- const port = await containerPort(name, options.timeoutMs)
+ const port = await containerPort(name, 8080, 'HTTP', options.timeoutMs)
const url = `http://127.0.0.1:${port}`
await waitForHealth(name, url, options.timeoutMs)
return url
@@ -821,6 +919,7 @@ function imageSmokeSummary(metadata, diagnostics, identity, startedAt) {
sqlite: true,
motrixAria2Fork: true,
defaultSaveDir: '/downloads',
+ remoteExtensionDirectLan: true,
shutdown: 'SIGTERM',
durationMs: Date.now() - startedAt,
}
@@ -864,6 +963,9 @@ export async function smokeServerImage(options) {
if (!metadata.Config.Healthcheck) {
throw new Error('Server image has no Docker HEALTHCHECK')
}
+ if (!metadata.Config.ExposedPorts?.['16801/tcp']) {
+ throw new Error('Server image does not expose the MDXP port')
+ }
if (platform && metadata.Architecture !== platform.split('/')[1]) {
throw new Error(
`Server image architecture is ${metadata.Architecture}, expected ${platform}`
@@ -941,6 +1043,7 @@ export async function smokeServerImage(options) {
timeoutMs,
})
appCreated = true
+ await assertRemoteExtensionSurface(appName, timeoutMs)
const diagnostics = await assertRuntimeContract(
appName,
url,
@@ -1116,6 +1219,7 @@ export async function smokeServerImage(options) {
timeoutMs,
})
appCreated = true
+ await assertRemoteExtensionSurface(appName, timeoutMs)
const restoredTasks = await rpc(
url,
operatorToken,
diff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.ts
index d5658ddb..703e95e5 100644
--- a/src/server/bridge/bootstrap.test.ts
+++ b/src/server/bridge/bootstrap.test.ts
@@ -6,6 +6,7 @@ import {
exchangeCredential,
initializeParams,
mdxpOverChannel,
+ reconnect,
runPake,
startPair,
} from '@core/bridge/__tests__/mbp1-client'
@@ -311,7 +312,7 @@ describe('bootstrapBridgeForServer', () => {
await reacquired.release()
})
- it('opens an explicit WS public route bundle with stable Server identity', async () => {
+ it('serves the direct-LAN Extension routes across a persistent restart', async () => {
const remoteExtensionConfig = parseRemoteExtensionConfig({
MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',
MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://motrix.example/bridge',
@@ -320,7 +321,7 @@ describe('bootstrapBridgeForServer', () => {
const firstReceiver = extensionReceiver()
runtime = await bootstrapBridgeForServer({
userDataDir,
- host: '127.0.0.1',
+ host: '0.0.0.0',
port: 0,
motrixVersion: '2.0',
eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
@@ -400,7 +401,7 @@ describe('bootstrapBridgeForServer', () => {
const code = pending[0]?.code
if (code === undefined) throw new Error('extension pairing code missing')
const { channel } = await runPake(handshake, code)
- await exchangeCredential(handshake, channel)
+ const credential = await exchangeCredential(handshake, channel)
const connection = mdxpOverChannel(handshake.wire, channel)
await connection.sendRequest(
'motrix/initialize',
@@ -444,7 +445,7 @@ describe('bootstrapBridgeForServer', () => {
const secondReceiver = extensionReceiver()
runtime = await bootstrapBridgeForServer({
userDataDir,
- host: '127.0.0.1',
+ host: '0.0.0.0',
port: 0,
motrixVersion: '2.0',
eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
@@ -456,6 +457,26 @@ describe('bootstrapBridgeForServer', () => {
await expect(
readFile(join(userDataDir, 'bridge', 'server-instance-id'), 'utf8')
).resolves.toBe(firstInstanceId)
+
+ const reconnected = await reconnect({
+ port: runtime.port,
+ origin: `chrome-extension://${extensionId}`,
+ instanceId: firstInstanceId.trim(),
+ credential,
+ routePrefix: '/bridge',
+ hostHeader: 'motrix.example',
+ })
+ const reconnectedMdxp = mdxpOverChannel(
+ reconnected.wire,
+ reconnected.channel
+ )
+ await expect(
+ reconnectedMdxp.sendRequest(
+ 'motrix/initialize',
+ initializeParams(extensionId)
+ )
+ ).resolves.toMatchObject({ protocolVersion: '1.0' })
+ reconnectedMdxp.dispose()
})
it('quarantines a committed Extension when projection persistence fails and repairs it on restart', async () => {
diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.ts
index d8dce5d2..e7f61d18 100644
--- a/src/server/bridge/bootstrap.ts
+++ b/src/server/bridge/bootstrap.ts
@@ -156,14 +156,11 @@ export async function bootstrapBridgeForServer(
opts.remoteExtensionConfig !== undefined &&
isIssuedRemoteExtensionConfig(opts.remoteExtensionConfig) &&
opts.remoteExtensionConfig.status === 'enabled'
- if (
- remoteExtensionEnabled &&
- opts.host !== '127.0.0.1' &&
- opts.host !== '::1' &&
- opts.host !== 'localhost'
- ) {
- throw new Error('remote Extension bridge must bind to loopback')
- }
+ // Docker must bind the listener to the container interface for host port
+ // publication to work. The explicit remote opt-in, canonical public URLs,
+ // exact raw Host/path checks, admission limits, and MBP1 authentication are
+ // the public-surface boundary; container loopback is not reachable through
+ // Docker's published-port path.
if (remoteExtensionEnabled) {
await recoverExtensionPairingProjectionWriterLock(
join(dataDir, 'extension-pairings.json'),
diff --git a/src/server/bridge/server-process-ownership-authority.test.ts b/src/server/bridge/server-process-ownership-authority.test.ts
index 62c39ab7..ca91ef70 100644
--- a/src/server/bridge/server-process-ownership-authority.test.ts
+++ b/src/server/bridge/server-process-ownership-authority.test.ts
@@ -2,7 +2,10 @@ import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { establishServerProcessOwnershipAuthority } from './server-process-ownership-authority'
+import {
+ establishServerProcessOwnershipAuthority,
+ ServerProcessOwnershipFailureReason,
+} from './server-process-ownership-authority'
const roots: string[] = []
@@ -31,6 +34,17 @@ describe('server process ownership authority', () => {
expect(first.ownershipEpoch).toMatch(/^[A-Za-z0-9_-]{43}$/u)
await expect(first.assertExclusiveProcessOwnership()).resolves.toBe(true)
+ const bindingPath = path.join(
+ userDataDir,
+ '.motrix-server-bridge-owner.json'
+ )
+ if (process.platform !== 'win32') {
+ expect((await fs.stat(bindingPath)).mode & 0o777).toBe(0o600)
+ // NAS ACLs commonly retain read-only group/other access. The record has
+ // no secret and remains an integrity-safe ownership pin in this mode.
+ await fs.chmod(bindingPath, 0o644)
+ }
+
const restarted = await establishServerProcessOwnershipAuthority({
userDataDir,
port: 8080,
@@ -58,7 +72,9 @@ describe('server process ownership authority', () => {
port: 8081,
assertControlPlaneOwnership: () => true,
})
- ).rejects.toThrow('server bridge process ownership unavailable')
+ ).rejects.toMatchObject({
+ reason: ServerProcessOwnershipFailureReason.BindingPortMismatch,
+ })
})
it('requires the control-plane listener before creating the binding', async () => {
@@ -69,7 +85,9 @@ describe('server process ownership authority', () => {
port: 8080,
assertControlPlaneOwnership: () => false,
})
- ).rejects.toThrow('server bridge process ownership unavailable')
+ ).rejects.toMatchObject({
+ reason: ServerProcessOwnershipFailureReason.ControlPlaneUnavailable,
+ })
await expect(
fs.stat(path.join(userDataDir, '.motrix-server-bridge-owner.json'))
@@ -111,6 +129,80 @@ describe('server process ownership authority', () => {
port: 8080,
assertControlPlaneOwnership: () => true,
})
- ).rejects.toThrow('server bridge process ownership unavailable')
+ ).rejects.toMatchObject({
+ reason: ServerProcessOwnershipFailureReason.BindingNotRegularFile,
+ })
+ })
+
+ it('reports an insecure writable mode without exposing record contents', async () => {
+ if (process.platform === 'win32') return
+ const userDataDir = await temporaryDataDir()
+ const bindingPath = path.join(
+ userDataDir,
+ '.motrix-server-bridge-owner.json'
+ )
+ await fs.writeFile(
+ bindingPath,
+ `${JSON.stringify({
+ version: 1,
+ transport: 'tcp-control-plane',
+ host: '0.0.0.0',
+ port: 8080,
+ bridgeDataDirectory: path.join(userDataDir, 'bridge'),
+ })}\n`,
+ { mode: 0o660 }
+ )
+ await fs.chmod(bindingPath, 0o660)
+
+ await expect(
+ establishServerProcessOwnershipAuthority({
+ userDataDir,
+ port: 8080,
+ assertControlPlaneOwnership: () => true,
+ })
+ ).rejects.toMatchObject({
+ message:
+ 'server bridge process ownership unavailable: binding-insecure-mode',
+ reason: ServerProcessOwnershipFailureReason.BindingInsecureMode,
+ })
+ })
+
+ it('distinguishes malformed JSON from a stale canonical directory', async () => {
+ const userDataDir = await temporaryDataDir()
+ const bindingPath = path.join(
+ userDataDir,
+ '.motrix-server-bridge-owner.json'
+ )
+ await fs.writeFile(bindingPath, '{\n', { mode: 0o600 })
+ await expect(
+ establishServerProcessOwnershipAuthority({
+ userDataDir,
+ port: 8080,
+ assertControlPlaneOwnership: () => true,
+ })
+ ).rejects.toMatchObject({
+ reason: ServerProcessOwnershipFailureReason.BindingInvalidJson,
+ })
+
+ await fs.writeFile(
+ bindingPath,
+ `${JSON.stringify({
+ version: 1,
+ transport: 'tcp-control-plane',
+ host: '0.0.0.0',
+ port: 8080,
+ bridgeDataDirectory: '/stale/bridge',
+ })}\n`,
+ { mode: 0o600 }
+ )
+ await expect(
+ establishServerProcessOwnershipAuthority({
+ userDataDir,
+ port: 8080,
+ assertControlPlaneOwnership: () => true,
+ })
+ ).rejects.toMatchObject({
+ reason: ServerProcessOwnershipFailureReason.BindingDirectoryMismatch,
+ })
})
})
diff --git a/src/server/bridge/server-process-ownership-authority.ts b/src/server/bridge/server-process-ownership-authority.ts
index c1e6cf72..f54e3a13 100644
--- a/src/server/bridge/server-process-ownership-authority.ts
+++ b/src/server/bridge/server-process-ownership-authority.ts
@@ -9,6 +9,40 @@ const BINDING_FILE_NAME = '.motrix-server-bridge-owner.json'
const MAX_BINDING_BYTES = 1024
const NO_FOLLOW = constants.O_NOFOLLOW ?? 0
+export const ServerProcessOwnershipFailureReason = {
+ ControlPlaneUnavailable: 'control-plane-unavailable',
+ BindingMetadataUnavailable: 'binding-metadata-unavailable',
+ BindingNotRegularFile: 'binding-not-regular-file',
+ BindingLinkCountMismatch: 'binding-link-count-mismatch',
+ BindingOwnerMismatch: 'binding-owner-mismatch',
+ BindingInsecureMode: 'binding-insecure-mode',
+ BindingOpenFailed: 'binding-open-failed',
+ BindingStatFailed: 'binding-stat-failed',
+ BindingChanged: 'binding-changed',
+ BindingTooLarge: 'binding-too-large',
+ BindingReadFailed: 'binding-read-failed',
+ BindingEmpty: 'binding-empty',
+ BindingInvalidJson: 'binding-invalid-json',
+ BindingSchemaMismatch: 'binding-schema-mismatch',
+ BindingSerializationMismatch: 'binding-serialization-mismatch',
+ BindingCreateFailed: 'binding-create-failed',
+ BindingWriteFailed: 'binding-write-failed',
+ BindingPortMismatch: 'binding-port-mismatch',
+ BindingHostMismatch: 'binding-host-mismatch',
+ BindingTransportMismatch: 'binding-transport-mismatch',
+ BindingDirectoryMismatch: 'binding-directory-mismatch',
+} as const
+
+export type ServerProcessOwnershipFailureReason =
+ (typeof ServerProcessOwnershipFailureReason)[keyof typeof ServerProcessOwnershipFailureReason]
+
+export class ServerProcessOwnershipError extends Error {
+ constructor(readonly reason: ServerProcessOwnershipFailureReason) {
+ super(`server bridge process ownership unavailable: ${reason}`)
+ this.name = 'ServerProcessOwnershipError'
+ }
+}
+
interface BindingDocument {
readonly version: typeof BINDING_VERSION
readonly transport: 'tcp-control-plane'
@@ -24,8 +58,10 @@ export interface ServerProcessOwnershipAuthorityOptions {
readonly assertControlPlaneOwnership: () => boolean
}
-function fail(): Error {
- return new Error('server bridge process ownership unavailable')
+function fail(
+ reason: ServerProcessOwnershipFailureReason
+): ServerProcessOwnershipError {
+ return new ServerProcessOwnershipError(reason)
}
function serialize(document: BindingDocument): Buffer {
@@ -66,58 +102,151 @@ function sameFile(
async function readExactBinding(filePath: string): Promise<BindingDocument> {
let handle: fs.FileHandle | null = null
try {
- const before = await fs.lstat(filePath, { bigint: true })
- if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n) {
- throw fail()
+ let before: Awaited<ReturnType<typeof fs.lstat>>
+ try {
+ before = await fs.lstat(filePath, { bigint: true })
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingMetadataUnavailable)
}
- if (process.platform !== 'win32' && (before.mode & 0o777n) !== 0o600n) {
- throw fail()
+ if (!before.isFile() || before.isSymbolicLink()) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingNotRegularFile)
+ }
+ if (before.nlink !== 1n) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingLinkCountMismatch)
+ }
+ if (process.platform !== 'win32') {
+ if (
+ typeof process.geteuid === 'function' &&
+ before.uid !== BigInt(process.geteuid())
+ ) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingOwnerMismatch)
+ }
+ // The record contains no secret. Integrity requires that the owning UID
+ // is the only identity able to modify it; read-only group/other access is
+ // harmless and is common on NAS bind mounts with inherited ACLs.
+ if ((before.mode & 0o022n) !== 0n) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingInsecureMode)
+ }
}
const flags = constants.O_RDONLY | NO_FOLLOW
- handle = await fs.open(filePath, flags)
- const during = await handle.stat({ bigint: true })
- if (!sameFile(before, during) || during.size > BigInt(MAX_BINDING_BYTES)) {
- throw fail()
- }
- const bytes = await handle.readFile()
- if (bytes.length === 0 || bytes.length > MAX_BINDING_BYTES) throw fail()
- const parsed: unknown = JSON.parse(bytes.toString('utf8'))
- if (!isExactBinding(parsed) || !bytes.equals(serialize(parsed)))
- throw fail()
- const after = await fs.lstat(filePath, { bigint: true })
- if (!sameFile(during, after)) throw fail()
+ try {
+ handle = await fs.open(filePath, flags)
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingOpenFailed)
+ }
+ let during: Awaited<ReturnType<fs.FileHandle['stat']>>
+ try {
+ during = await handle.stat({ bigint: true })
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingStatFailed)
+ }
+ if (!sameFile(before, during)) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingChanged)
+ }
+ if (during.size > BigInt(MAX_BINDING_BYTES)) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingTooLarge)
+ }
+ let bytes: Buffer
+ try {
+ bytes = await handle.readFile()
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingReadFailed)
+ }
+ if (bytes.length === 0) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingEmpty)
+ }
+ if (bytes.length > MAX_BINDING_BYTES) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingTooLarge)
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(bytes.toString('utf8'))
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingInvalidJson)
+ }
+ if (!isExactBinding(parsed)) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingSchemaMismatch)
+ }
+ if (!bytes.equals(serialize(parsed))) {
+ throw fail(
+ ServerProcessOwnershipFailureReason.BindingSerializationMismatch
+ )
+ }
+ let after: Awaited<ReturnType<typeof fs.lstat>>
+ try {
+ after = await fs.lstat(filePath, { bigint: true })
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingChanged)
+ }
+ if (!sameFile(during, after)) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingChanged)
+ }
return parsed
- } catch {
- throw fail()
} finally {
await handle?.close().catch(() => undefined)
}
}
+async function tightenNewBindingMode(handle: fs.FileHandle): Promise<void> {
+ if (process.platform === 'win32') return
+ try {
+ await handle.chmod(0o600)
+ } catch {
+ // Some mounted filesystems reject chmod even though create(0600) already
+ // produced a safe file. Continue only when the handle proves that case.
+ let info: Awaited<ReturnType<fs.FileHandle['stat']>>
+ try {
+ info = await handle.stat({ bigint: true })
+ } catch {
+ throw fail(ServerProcessOwnershipFailureReason.BindingStatFailed)
+ }
+ if (
+ (typeof process.geteuid === 'function' &&
+ info.uid !== BigInt(process.geteuid())) ||
+ (info.mode & 0o022n) !== 0n
+ ) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingInsecureMode)
+ }
+ }
+}
+
async function persistBinding(
filePath: string,
expected: BindingDocument
): Promise<void> {
+ let handle: fs.FileHandle | null = null
try {
- const handle = await fs.open(filePath, 'wx', 0o600)
+ handle = await fs.open(filePath, 'wx', 0o600)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
+ throw fail(ServerProcessOwnershipFailureReason.BindingCreateFailed)
+ }
+ }
+ if (handle !== null) {
try {
+ await tightenNewBindingMode(handle)
await handle.writeFile(serialize(expected))
await handle.sync()
+ } catch (error) {
+ if (error instanceof ServerProcessOwnershipError) throw error
+ throw fail(ServerProcessOwnershipFailureReason.BindingWriteFailed)
} finally {
- await handle.close()
+ await handle.close().catch(() => undefined)
}
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw fail()
}
const actual = await readExactBinding(filePath)
- if (
- actual.port !== expected.port ||
- actual.host !== expected.host ||
- actual.transport !== expected.transport ||
- actual.bridgeDataDirectory !== expected.bridgeDataDirectory
- ) {
- throw fail()
+ if (actual.port !== expected.port) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingPortMismatch)
+ }
+ if (actual.host !== expected.host) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingHostMismatch)
+ }
+ if (actual.transport !== expected.transport) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingTransportMismatch)
+ }
+ if (actual.bridgeDataDirectory !== expected.bridgeDataDirectory) {
+ throw fail(ServerProcessOwnershipFailureReason.BindingDirectoryMismatch)
}
}
@@ -137,7 +266,7 @@ export async function establishServerProcessOwnershipAuthority(
options.port > 65535 ||
!options.assertControlPlaneOwnership()
) {
- throw fail()
+ throw fail(ServerProcessOwnershipFailureReason.ControlPlaneUnavailable)
}
await fs.mkdir(options.userDataDir, { recursive: true })
diff --git a/src/server/index.ts b/src/server/index.ts
index 91dcb243..4ae02d44 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -137,7 +137,10 @@ import {
import { diagnoseMdxpPublicUrl } from './bridge/public-url-diagnostic'
import { parseRemoteExtensionConfig } from './bridge/remote-extension-config'
import { logRemoteExtensionPairingReady } from './bridge/remote-extension-startup-log'
-import { establishServerProcessOwnershipAuthority } from './bridge/server-process-ownership-authority'
+import {
+ establishServerProcessOwnershipAuthority,
+ ServerProcessOwnershipError,
+} from './bridge/server-process-ownership-authority'
import {
createServerDownloadPathPolicy,
resolveServerDefaultSaveDir,
@@ -1596,6 +1599,10 @@ async function main() {
const serverUrl = `http://localhost:${port}`
log.info({ port, url: serverUrl }, `server listening at ${serverUrl}`)
+ let bridgeSetupStage:
+ | 'process-ownership'
+ | 'bridge-data-lock'
+ | 'trusted-extension-registry' = 'process-ownership'
bridgeOwnershipSetup = (async () => {
bridgeDataDirLockRecoveryAuthority =
await establishServerProcessOwnershipAuthority({
@@ -1611,6 +1618,7 @@ async function main() {
)
},
})
+ bridgeSetupStage = 'bridge-data-lock'
const dataDirLock = await acquireBridgeDataDirLock(bridgeDataDir, {
recoverExisting: bridgeDataDirLockRecoveryAuthority,
})
@@ -1619,6 +1627,7 @@ async function main() {
return
}
bridgeProcessDataDirLock = dataDirLock
+ bridgeSetupStage = 'trusted-extension-registry'
try {
await trustedExtensionRegistry.load()
} catch (error) {
@@ -1634,7 +1643,12 @@ async function main() {
bridgeRegistryReady = true
})().catch((err) => {
log.error(
- { err },
+ {
+ err,
+ stage: bridgeSetupStage,
+ reason:
+ err instanceof ServerProcessOwnershipError ? err.reason : undefined,
+ },
'bridge data ownership unavailable — trusted registry and MDXP bridge disabled'
)
})
diff --git a/tests/scripts/docker-server-docs.test.ts b/tests/scripts/docker-server-docs.test.ts
index 1c366e95..67bb44e9 100644
--- a/tests/scripts/docker-server-docs.test.ts
+++ b/tests/scripts/docker-server-docs.test.ts
@@ -38,6 +38,9 @@ describe('public Docker Server documentation', () => {
'MOTRIX_MDXP_BIND_IP',
'MOTRIX_BIND_IP',
'MOTRIX_ARIA2_RPC_LISTEN_ALL',
+ '.motrix-server-bridge-owner.json',
+ 'binding-insecure-mode',
+ 'docker compose down',
'16800',
'/mdxp/events',
'/healthz',
diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.ts
index 3e15845d..09774685 100644
--- a/tests/scripts/docker-server-runtime.test.ts
+++ b/tests/scripts/docker-server-runtime.test.ts
@@ -96,6 +96,7 @@ describe('Docker Server runtime staging contract', () => {
expect(runtime).toContain('TMPDIR=/data/tmp')
expect(runtime).toContain('HOME=/data/home')
expect(runtime).toContain('USER node')
+ expect(runtime).toContain('EXPOSE 8080 16801')
expect(runtime).toContain('STOPSIGNAL SIGTERM')
expect(runtime).toContain('HEALTHCHECK --interval=30s')
expect(runtime).toContain('CMD ["node", "dist/server/index.mjs"]')
@@ -196,6 +197,16 @@ describe('Docker Server runtime staging contract', () => {
expect(imageSmoke).toContain('totalBytes: lastTask.totalBytes')
expect(imageSmoke).toContain('Fixture tracker: announces=')
expect(imageSmoke).toContain('identity.user')
+ expect(imageSmoke).toContain("'MOTRIX_MDXP_HOST=0.0.0.0'")
+ expect(imageSmoke).toContain("'MOTRIX_REMOTE_EXTENSION_ENABLED=true'")
+ expect(imageSmoke).toContain("'127.0.0.1::16801'")
+ expect(imageSmoke).toContain("metadata.Config.ExposedPorts?.['16801/tcp']")
+ expect(
+ imageSmoke.match(
+ /await assertRemoteExtensionSurface\(appName, timeoutMs\)/g
+ )
+ ).toHaveLength(2)
+ expect(imageSmoke).toContain('remoteExtensionDirectLan: true')
expect(imageSmoke).toContain("'command:createTask'")
expect(imageSmoke).toContain("'command:setTaskBtTracker'")
expect(imageSmoke).toContain("'command:installPlugin'")