diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..66a9781 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: MDXP CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: mdxp-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + contract: + name: MDXP contract checks + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: pnpm/setup@84cb39b217b10273981911c288cd62326dc7c6d2 # v2.0.2 + with: + runtime: node@24.18.0 + cache: true + install: false + - run: pnpm install --frozen-lockfile + - run: pnpm run lint + - run: pnpm run typecheck + - run: pnpm test + - run: pnpm run build + - name: Verify packaged public entry points + run: pnpm run check:package diff --git a/README.md b/README.md index 0575ea7..12aa09c 100644 --- a/README.md +++ b/README.md @@ -491,6 +491,10 @@ an invalid request. A pre-dispatch directory rejection uses `InvalidParams` with included. Filesystem checks are not an OS sandbox: a local process that can replace directories concurrently is outside this guarantee. +## Download handoff (unreleased contract) + +The optional `downloadHandoff` capability defines prepare/commit/status/abort for extension-owned confirmation. This package adds wire schemas, typed methods and shared payload fingerprint encoding; it does not enable application support. See the [handoff v1 contract](docs/download-handoff.md) for durable ledger, cancellation and recovery requirements. Hosts must keep the capability absent until those integration requirements pass. + ## License [MIT](./LICENSE) © Dr_rOot diff --git a/README.zh-CN.md b/README.zh-CN.md index e4fa990..02096eb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -455,6 +455,10 @@ RPC handler 需要保留错误码和 data 时,应抛出从 `@motrix/mdxp` 导 不返回底层文件系统错误细节。目录校验不是操作系统沙箱,不能防御有权限并发替换 目录的本地进程。 +## 下载交接(尚未发布的契约) + +可选 `downloadHandoff` 能力定义扩展端确认使用的 prepare/commit/status/abort。本包新增传输 schema、强类型方法及共享载荷摘要编码,不直接启用应用支持。持久账本、取消与恢复要求见[交接 v1 契约](docs/download-handoff.zh-CN.md);服务端通过对应集成验收前必须保持该能力缺省。 + ## License [MIT](./LICENSE) © Dr_rOot diff --git a/docs/download-handoff.md b/docs/download-handoff.md new file mode 100644 index 0000000..135f168 --- /dev/null +++ b/docs/download-handoff.md @@ -0,0 +1,243 @@ +# Download handoff v1 + +This document defines the opt-in contract added by this change. The package +provides schemas, typed RPC methods and canonical payload encoding. It does not +implement a durable ledger, browser controller or download engine. A host must +not advertise support until the persistence and fault requirements below are +implemented and tested. Existing `download/submit` behavior is unchanged. + +## Negotiation and scope + +An authenticated extension uses these methods only when initialize returns: + +```json +{ + "capabilities": { + "downloadHandoff": { + "version": 1, + "instanceId": "c2b6a2d2-430c-4bc1-bdb0-c10f35004c90", + "maxPreparedTtlMs": 30000, + "acceptingNew": true + } + } +} +``` + +Absence means unsupported. All four handlers and the durable activation path must +be ready before advertising this capability. These methods are extension-only: +no agent catalog or unary HTTP exposure. `agentFacing: false` is not authorization. +The transport must authenticate the principal before dispatch, independently of +caller-supplied initialize fields. No user confirmation is requested by Motrix; +the extension owns the confirmation UI and freezes its options before prepare. + +V1 supports a direct HTTP(S) GET only. POST, bodies, blob URLs, media resolution, +HLS, DASH, mux and magnet are outside this handoff contract. Strict nested request +schemas reject unknown options instead of silently downgrading them to GET. A +valid URL is not permission to access it; normal host policy still applies. An +already-open browser response cannot be transferred to the engine; accepting a +Motrix handoff still needs another request and cannot guarantee one-use URLs. + +## Independent release and rollback + +Browser-store review delay and disabled automatic updates are normal supported +states, not exceptions. Neither side may require synchronized installation. +Keep protocolVersion `1.0` and the existing initialize, submit, task and pairing +contracts. `download/submit` remains a first-class path with its existing request, +response and error semantics, even after handoff is available. Do not redirect it +to prepare/commit or require an instance/key field that older extensions do not +send. Do not raise the minimum extension version just to enable this feature. + +| Extension | Motrix | New download path | +| --- | --- | --- | +| Existing | Existing | Existing submit | +| Existing | Upgraded | Existing submit, unchanged | +| Upgraded | Existing | Existing submit, unchanged | +| Upgraded | Upgraded, either rollout gate off | Existing submit | +| Upgraded | Upgraded, both gates on and v1 supported | Handoff for eligible requests only | +| Upgraded | Host advertises an unknown/invalid handoff capability | Existing submit for new operations; base handshake still works | + +Capability support and rollout are separate. `acceptingNew` defaults to false; +`canStartDownloadHandoff(advertisement, clientEnabled)` also defaults the client +gate to false. This helper is only for **new operations before any handoff +mutation is sent**. It must never be used to reroute an existing operation. +Invalid/unknown optional capability data is discarded by initialize parsing; +invalid mandatory base-protocol data still fails validation. Supported v1 mutation +params and results remain strict. Client implementations must retain the legacy +adapter/submit path and recover pending handoffs independently of these gates. + +Release order is additive, without a deadline tied to store approval: + +1. Release the SDK and a host retaining all legacy handlers, with new handoffs + disabled. Verify an actual released extension against this host. +2. Ship an extension containing both paths and a disabled client rollout gate. + It must work against hosts without this capability throughout store review. +3. Enable new operations only after both sides meet the integration acceptance + requirements, at their own release cadence. Never infer support from a + version string, store approval date or the presence of one method. + +To stop rollout, set `acceptingNew` false and reject the first prepare of an +absent key with `CapabilityNotSupported`, without effects. Already prepared keys +must still support repeated prepare, commit, status and abort. Capability changes +may require renegotiation, so servers enforce the gate on dispatch, not only in +initialize. A stale client denied before prepare still uses same-key recovery +and must not blindly start legacy submit. It can choose a legacy path for a +fresh operation only before any handoff mutation was transmitted. + +Do not remove handlers, discard the ledger or roll back to a binary without +handoff recovery after any handoff could have been accepted. Use a compatible +rollback build retaining the journal, activation reconciliation and handlers; +new operations use legacy while existing ones finish/recover. A crash, reset or +forced downgrade does not justify replaying unresolved work. Reverting an SDK +version alone is not an application rollback procedure. + +The SDK CI tests use the **published 0.8.1 package**, through an exact dev-only +alias, for old/new initialize and submit round trips. They establish wire +compatibility, not production host route retention, browser-store distribution +or database migration safety. Released extension/host cross-version E2E and +rollback with in-flight operations remain mandatory before enabling rollout. + +## Identity and payload + +Every request carries `{ instanceId, operationId }`, both UUIDs. The operation is +keyed by **durable ledger instance + authenticated principal + operationId**, not +URL, socket, tab or claimed extension ID. Separate clicks get separate operation +IDs. Reconnect/retry uses the original ID and immutable payload. Persist the key, +authenticated backend binding and confirmation state before sending mutations. +Never move a pending operation to another backend or credential identity. + +`instanceId` identifies a durable ledger generation. It survives ordinary server +restarts, but MUST change if records are lost, reset or restored to an older +snapshot. Every handler compares it before any effect, returning +`HandoffInstanceChanged` (-32007) for a mismatch. The client must treat an old +pending operation as unresolved; a new instance is not evidence that the old +engine never started it. Never automatically create a replacement operation. + +Prepare carries `download`: the existing submit source, metadata and optional +`saveDir`, restricted to a direct selection, without a second idempotency key. +`canonicalDownloadHandoffPayload()` parses and normalizes schema defaults, sorts +object keys by UTF-16 code units recursively, preserves array order, and encodes +with JSON string/number escaping. SHA-256 over the resulting UTF-8 bytes is the +lowercase 64-character `payloadHash`. This is an MDXP-specific encoding, not a +claim of general JSON canonicalization. Do not normalize URL queries, header +names or reorder cookies independently. Freeze timestamps and options on retry. + +The host computes this hash itself, stores it with the reserved task ID, and +rejects a reused ID with different content using `HandoffPayloadConflict` +(-32008). Clients verify response key and hash against the frozen operation; +commit includes that same hash. Do not log payloads: they may contain cookies, +authorization headers or signed URLs. Hashes are correlation values, not secrets +or authorization proofs. + +## Methods and results + +| Method | Params | Possible result states | +| --- | --- | --- | +| `download/handoff.prepare` | key + `download` | prepared, committed, aborted, expired | +| `download/handoff.commit` | key + `payloadHash` | committed, aborted, expired, not-found | +| `download/handoff.status` | key | prepared, committed, aborted, expired, not-found | +| `download/handoff.abort` | key | aborted, committed, expired | + +All results echo the key. `prepared` includes reserved `taskId`, `payloadHash` +and `expiresAt` (server Unix milliseconds). `committed` includes the same task ID +and hash. Other results contain only key and state. `committed` means durable +ownership/activation intent, not completed download; later task failures stay +with Motrix and must not cause browser replay. A removed or failed task does not +make its handoff record disappear or reusable. + +Prepare performs only local validation and creates an inactive durable record. +It must not probe/fetch the source, call URL adapters, start the engine, or enqueue +active work. Resolve an omitted default directory to a concrete permitted path +and freeze it in the record, independently of the original payload hash. A later +default change must not redirect the task. Revalidate permissions and the frozen +path before commit; refusal leaves it inactive. Never silently substitute paths. +The host chooses an expiry no later than `maxPreparedTtlMs` after its current +clock. Repeating prepare does not extend that expiry or replace the task ID. + +All operations on a key, including expiry, are serialized in the same durable +transaction domain. At the expiry boundary (`now >= expiresAt`), an uncommitted +record becomes expired and cannot commit. Do not evaluate deadlines only when +receiving RPC bytes; check again while holding the transaction's serialization +boundary. Crash recovery must not grant an expired record a new lifetime. + +| Current state | prepare (same payload) | commit (same hash) | abort | status | +| --- | --- | --- | --- | --- | +| absent | persist prepared | not-found; no effect | persist aborted tombstone | not-found; no effect | +| prepared, not expired | unchanged prepared | persist committed + activation intent | persist aborted | prepared | +| prepared, expired | persist expired | persist expired | persist expired | persist expired | +| committed | committed | committed | committed | committed | +| aborted | aborted | aborted | aborted | aborted | +| expired | expired | expired | expired | expired | + +Conflicting hashes/payloads fail before mutation when a stored hash exists, +including terminal records. A tombstone created before prepare has no payload; +any later prepare returns aborted and must not bind or start a task. Abort of an +absent operation MUST create that tombstone. A status miss is only an observation: +a delayed prepare or commit could still arrive. It is never permission to replay. + +Commit atomically records the ledger transition, task and durable activation +outbox/intent before replying. A recoverable engine dispatcher must reconcile a +stable task/engine identity before retrying an activation after a crash. An +in-memory Promise cache or a database transaction around only the ledger does +not meet this contract. Do not claim exactly-once network transfer from these +requirements: the engine/source boundary and browser cancellation are separate. + +Terminal records may compact to key, state, task ID and hash as applicable, but +must remain deduplicating for the lifetime of the instance. Never evict them by +URL TTL or cache pressure. To reclaim an entire generation, fence its live +sessions and rotate the instance; historical tasks may still exist and clients +must not replay old operations. Capacity exhaustion refuses new prepare/abort +mutations explicitly rather than acknowledging a tombstone that was not stored. + +## Browser ownership and recovery + +1. Keep the original browser request under adapter control while the extension + collects confirmation. Choosing browser continues that original response; + explicit cancel stops it. UI drafts expire when the adapter's hold expires; + a UI timeout is not a promise that the browser can remain held that long. +2. Freeze the chosen options, persist the operation binding, then prepare. + Validate the prepared reply. Do not stop the browser merely because a request + was sent or a transport returned without a schema-valid response. +3. Stop the original browser transfer and verify the adapter's outcome, then + persist that evidence before commit. A failed or unknown browser stop must + not commit; attempt abort. Never replay a browser GET to hide that uncertainty. +4. Once commit might have been sent, timeout/EOF/malformed reply is unknown. + Reconnect only to the same instance/principal and query the same operation. + An abort result of aborted/expired is a durable fence; committed belongs to + Motrix. A lost abort response is also unknown. `not-found` alone is not a fence. +5. Restored drafts must not re-create operations or fabricate ownership of a lost + blocking Promise. Backend/config changes invalidate the live UI operation. + Recovery may query or abort its original authenticated backend; it must never + send that commit to the newly selected backend. + +`$/cancelRequest` cancels RPC waiting/cooperative work; it does not create an abort +tombstone and cannot roll back a committed task. Application task cancellation is +separate. Errors, including InternalError, do not by themselves establish whether +a mutation committed. Use same-key recovery. Do not fall back to legacy +`download/submit` after a possibly transmitted handoff mutation. + +## Acceptance required before host advertisement + +These are integration requirements for the simulator and real host. Schema and +in-memory RPC tests in this package do not establish their persistence guarantees. +Both implementations should exercise the same scenarios with named barriers, +independently observing the ledger, engine activation and source HTTP requests. + +| Fault/scenario | Required observation | +| --- | --- | +| prepare, repeat prepare | one inactive record/task ID; no source request or engine work; unchanged expiry | +| different payload or commit hash | conflict; no additional activation, including after commit | +| same URL, new operation IDs | independent records | +| different authenticated principal | no access to the other principal's record | +| abort arrives before delayed prepare/commit | durable tombstone; later messages cannot activate | +| commit wins abort race | abort returns same committed task; exactly one activation intent | +| reply lost after commit transaction | status/retry returns same task and hash; no browser replay | +| engine accepted activation, crash before acknowledgement | recover by stable identity; no second task | +| status not-found while prepare is in flight | no automatic fallback; abort fences the late prepare | +| expiry exactly at commit boundary, restart after expiry | terminal expired; no activation or TTL renewal | +| reset/restore loses ledger | new instance; old requests refused; old client outcome remains unresolved | +| disk full/transaction rollback | no success acknowledgement without durable record/outbox/tombstone | +| original browser cancellation fails or is unknown | no commit; no replacement GET | +| config/backend change or extension restart | no stale UI submission and no cross-instance replay | + +Until these checks pass in the host and browser integrations, keep the capability +absent. The package contract alone does not enable or certify application support. diff --git a/docs/download-handoff.zh-CN.md b/docs/download-handoff.zh-CN.md new file mode 100644 index 0000000..5bed1c0 --- /dev/null +++ b/docs/download-handoff.zh-CN.md @@ -0,0 +1,124 @@ +# 下载交接 v1 + +本文定义本次新增、需要显式协商的协议。SDK 提供 schema、强类型 RPC 方法和载荷规范编码,不实现持久账本、浏览器控制器或下载引擎。服务端必须实现并验证以下持久化和故障要求后才能宣告支持。已有 `download/submit` 行为保持不变。 + +## 协商与范围 + +已认证扩展只有在 initialize 返回以下能力时才能调用: + +```json +{ + "capabilities": { + "downloadHandoff": { + "version": 1, + "instanceId": "c2b6a2d2-430c-4bc1-bdb0-c10f35004c90", + "maxPreparedTtlMs": 30000, + "acceptingNew": true + } + } +} +``` + +缺省表示不支持。四个处理器及持久激活路径都就绪后才能宣告能力。这些方法仅供扩展使用,不进入 agent 工具目录,不通过 unary HTTP 暴露。`agentFacing: false` 不构成鉴权;传输层须独立认证主体,不能信任 initialize 中自报的身份字段。下载前询问由扩展负责,prepare 前冻结用户选择,Motrix 不重复询问。 + +v1 仅支持直接 HTTP(S) GET。POST、请求体、blob URL、媒体解析、HLS、DASH、mux 和 magnet 不在交接范围。嵌套请求 schema 严格拒绝未知选项,不能悄悄把请求降级为 GET。合法 URL 不代表有访问权限,仍须遵守宿主策略。浏览器已打开的响应无法转交引擎;交给 Motrix 后仍需另一次请求,不能保证一次性链接可重放。 + +## 独立发布与回滚 + +浏览器商店审核延迟、用户关闭自动更新都是正常受支持状态,不能要求两端同步安装。保持 protocolVersion `1.0` 及已有 initialize、submit、任务和配对契约。即使启用了新交接,`download/submit` 也必须作为完整路径继续维护原有参数、结果和错误语义;不能在内部偷换成 prepare/commit,也不能要求旧扩展发送实例字段或新操作标识。不得仅为此功能提高扩展最低版本要求。 + +| 扩展 | Motrix | 新下载路径 | +| --- | --- | --- | +| 旧版 | 旧版 | 原 submit | +| 旧版 | 新版 | 原 submit,行为不变 | +| 新版 | 旧版 | 原 submit,行为不变 | +| 新版 | 新版,任一启用开关关闭 | 原 submit | +| 新版 | 新版,两端启用且支持 v1 | 符合条件的请求使用新交接 | +| 新版 | 宣告未知或无效交接能力 | 新操作使用原 submit,基础握手仍正常 | + +支持能力与启用功能是两件事。`acceptingNew` 默认 false;`canStartDownloadHandoff(advertisement, clientEnabled)` 的客户端开关也默认 false。此函数仅用于**尚未发送任何交接修改的新操作**,不得用于给已有操作改道。initialize 解析忽略未知或无效的可选交接能力,但基础协议必填字段无效仍然报错。已支持的 v1 修改参数及结果保持严格校验。客户端必须保留原适配器/submit 路径,并独立于启用开关恢复未决交接。 + +按增量方式发布,不把时限绑定到商店审核: + +1. 发布 SDK 和保留全部旧处理器的 Motrix,新交接默认关闭;使用实际已发布扩展验证新 Motrix。 +2. 发布同时包含两条路径且客户端启用开关关闭的扩展;审核期间也必须能连接没有新能力的旧 Motrix。 +3. 两端完成集成验收后,按各自发布节奏启用新操作;不能仅凭版本号、审核日期或单个方法存在判断支持。 + +停止推广时将 `acceptingNew` 设为 false;对不存在标识的首次 prepare,服务端返回 `CapabilityNotSupported` 且不产生作用。已准备的操作仍须支持重复 prepare、commit、status、abort。能力变化可能需要重新协商,因此分派处理时也必须检查开关,不能只依赖 initialize。持有旧能力缓存的客户端即使被拒绝,也要按原操作恢复,不能盲目改发旧 submit;只有尚未传输交接修改的新操作才能选旧路径。 + +一旦可能接收过交接,就不能删除处理器、丢弃账本或回滚到不具备交接恢复能力的二进制。应使用保留账本、激活核对和处理器的兼容回滚构建:新操作走旧路径,已有操作继续完成/恢复。崩溃、重置或强制降级都不能成为重放未决下载的理由。仅回退 SDK 版本不是应用回滚方案。 + +SDK CI 通过固定、仅用于开发测试的别名依赖,使用**真实已发布的 0.8.1 包**验证新旧 initialize 和 submit 往返。它证明的是传输兼容,不能代替生产服务端入口保留、商店分发或数据库迁移安全。正式启用前,仍必须跑已发布扩展与 Motrix 的交叉版本 E2E,以及带有在途操作的回滚验收。 + +## 身份与载荷 + +每次请求包含 `{ instanceId, operationId }`,两者均为 UUID。操作按**持久账本实例 + 已认证主体 + operationId** 区分,不按 URL、连接、标签页或自报扩展 ID 区分。同 URL 的两次点击使用不同 ID;重连和重试沿用原 ID 及冻结的载荷。发送变更前先持久化操作标识、已认证后端绑定和确认状态。不得把未决操作迁移到另一个后端或凭据身份。 + +`instanceId` 标识一代持久账本,普通重启保持不变;账本丢失、重置或恢复到旧快照时必须更换。所有方法在产生任何作用前核对它,不匹配时返回 `HandoffInstanceChanged`(-32007)。客户端必须将旧操作保持为未决状态;新实例不能证明旧引擎从未启动任务,不得自动新建替代操作。 + +prepare 的 `download` 复用 submit 的来源、元数据、可选 `saveDir`,仅允许 direct selection,不包含第二个幂等键。`canonicalDownloadHandoffPayload()` 先校验并补齐 schema 默认值,递归按 UTF-16 编码单元排序对象键,保持数组顺序,再按 JSON 字符串/数字规则编码。对结果的 UTF-8 字节计算 SHA-256,得到小写 64 字符 `payloadHash`。这是 MDXP 专用编码,不宣称是通用 JSON 规范化;不能另行归一化 URL 查询、请求头名称或 Cookie 顺序。重试时连同时间戳一起冻结。 + +服务端自行计算摘要,与预留任务 ID 一起保存。同 ID 内容不同则返回 `HandoffPayloadConflict`(-32008)。客户端核对回复中的操作标识及摘要,commit 必须携带同一摘要。载荷可能含 Cookie、认证头或签名 URL,不得记录到日志。摘要是关联值,不是秘密或鉴权凭证。 + +## 方法与结果 + +| 方法 | 参数 | 可能的结果状态 | +| --- | --- | --- | +| `download/handoff.prepare` | 操作标识 + `download` | prepared、committed、aborted、expired | +| `download/handoff.commit` | 操作标识 + `payloadHash` | committed、aborted、expired、not-found | +| `download/handoff.status` | 操作标识 | prepared、committed、aborted、expired、not-found | +| `download/handoff.abort` | 操作标识 | aborted、committed、expired | + +所有结果回传操作标识。prepared 额外包含预留 `taskId`、`payloadHash` 和服务端 Unix 毫秒时间 `expiresAt`;committed 包含相同任务 ID 和摘要;其他结果只包含标识和状态。committed 表示持久接管和激活意图,不能解读为下载完成;之后的任务失败由 Motrix 处理,不能触发浏览器重放。任务删除或失败也不能让交接记录消失或被复用。 + +prepare 只做本地校验并持久化未激活记录,不得探测或请求下载源、调用 URL 解析适配器、启动引擎或排入可执行任务。省略目录时,将当前默认目录解析为具体允许路径,独立于原载荷摘要冻结在记录中;默认目录之后改变不能改写目的地。commit 前再次检查权限和冻结路径,拒绝时保持未激活,不能静默替换目录。服务端选择的有效期不超过当前时间加 `maxPreparedTtlMs`;重复 prepare 不延长有效期、不更换任务 ID。 + +同一操作上的所有方法和到期处理必须在同一个持久事务范围内串行化。达到 `now >= expiresAt` 时,未提交记录变为 expired,不可再提交。不能只在 RPC 接收时检查时间,必须在事务串行化边界内再次检查;崩溃恢复不能赋予过期记录新的有效期。 + +| 当前状态 | prepare(相同载荷) | commit(相同摘要) | abort | status | +| --- | --- | --- | --- | --- | +| 不存在 | 持久化 prepared | not-found,无作用 | 持久化 aborted 终止记录 | not-found,无作用 | +| prepared,未到期 | 原 prepared | 持久化 committed 和激活意图 | 持久化 aborted | prepared | +| prepared,已到期 | 持久化 expired | 持久化 expired | 持久化 expired | 持久化 expired | +| committed | committed | committed | committed | committed | +| aborted | aborted | aborted | aborted | aborted | +| expired | expired | expired | expired | expired | + +只要记录已有摘要,载荷/摘要冲突必须在修改前被拒绝,终态也不例外。在 prepare 之前创建的终止记录没有载荷;后来任何 prepare 都返回 aborted,不能再绑定或启动任务。abort 对不存在的操作也必须建立此持久记录。status 的 not-found 只是当时的观察,仍可能有延迟到达的 prepare 或 commit,不能作为重放许可。 + +commit 必须在回复前原子持久化账本变更、任务和激活 outbox/意图。可恢复的引擎调度器在崩溃后重试激活前,必须通过稳定的任务/引擎身份核对状态。内存 Promise 缓存,或只覆盖账本的数据库事务,都不满足要求。这不等于网络传输“恰好一次”:浏览器取消、引擎与下载源仍是不同的边界。 + +终态可压缩为标识、状态及适用的任务 ID/摘要,但在该实例的整个生命周期内必须继续去重,不能因 URL TTL 或缓存压力而驱逐。回收整代账本时,先阻止旧会话继续写入再轮换实例;历史任务仍可能存在,客户端不得重放旧操作。容量不足必须明确拒绝新的 prepare/abort 修改,不能在终止记录尚未持久化时回复成功。 + +## 浏览器归属与恢复 + +1. 扩展等待用户确认时,由浏览器适配器控制原请求。“用浏览器”继续原响应,明确取消则停止它。适配器失去挂起控制权时草稿同步失效;UI 有效期不能被当成浏览器能一直挂起的保证。 +2. 冻结选项并保存操作绑定,然后 prepare,校验准备回复。不能仅因为已发出请求或传输返回就取消原浏览器下载。 +3. 停止原浏览器传输,核实适配器结果,将证据持久化后再 commit。停止失败或结果不明时不得 commit,应尝试 abort,不能通过重发浏览器 GET 掩盖不确定性。 +4. 一旦 commit 可能已经发出,超时、EOF、无效回复均属于未知结果。只向同实例、同主体重连并查询原操作。abort 返回 aborted/expired 才构成持久阻断;committed 归 Motrix。abort 回复丢失也仍属未知;not-found 本身不足以阻断迟到消息。 +5. 恢复草稿不能新建操作,也不能假装重新获得已丢失的 blocking Promise 控制权。配置/后端切换使当前 UI 操作失效;恢复时可查询或撤销原认证后端的操作,但不得向新选中的后端发送旧 commit。 + +`$/cancelRequest` 仅取消 RPC 等待或协作执行,不建立 abort 终止记录,也不能回滚已提交任务。普通任务取消是另一个动作。包括 InternalError 在内的错误本身不能证明修改是否已提交,必须按原操作恢复。可能已经发送交接修改后,不得降级调用旧 `download/submit`。 + +## 服务端宣告能力前的验收要求 + +以下是模拟器和真实服务端必须满足的集成要求。本包的 schema 和内存 RPC 测试不能证明持久化保证。两者应使用相同场景及命名屏障,独立观察账本、引擎激活和源站 HTTP 请求。 + +| 故障/场景 | 必须观察到的结果 | +| --- | --- | +| prepare、重复 prepare | 一个未激活记录/任务 ID,无源站请求和引擎操作,不续期 | +| 不同载荷或 commit 摘要 | 冲突,无新增激活;已提交后仍如此 | +| 相同 URL,不同操作 ID | 独立记录 | +| 不同认证主体 | 无法访问另一主体的记录 | +| abort 先于延迟 prepare/commit 到达 | 持久终止记录阻止迟到消息激活 | +| commit 在与 abort 的竞争中先完成 | abort 返回同一已提交任务,只有一个激活意图 | +| commit 事务完成后回复丢失 | 查询/重试返回同一任务和摘要,不重放浏览器下载 | +| 引擎已接受激活但确认前崩溃 | 根据稳定身份恢复,无第二个任务 | +| prepare 在途而 status 为 not-found | 不自动回退;abort 阻断迟到 prepare | +| commit 时刚好到期、到期后重启 | expired 终态,无激活、不续期 | +| 重置/恢复导致账本丢失 | 更换实例、拒绝旧请求,旧客户端结果保持未决 | +| 磁盘满/事务回滚 | 记录、outbox、终止记录未持久化就不得回复成功 | +| 浏览器原请求取消失败或不明 | 不 commit,不发替代 GET | +| 配置/后端变化、扩展重启 | 旧 UI 不得提交,不能跨实例重放 | + +服务端和浏览器集成通过上述检查前,保持能力字段缺省。安装本协议包本身不启用也不认证应用支持。 diff --git a/package.json b/package.json index 10b7b06..618e709 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "!src/__tests__", "README.md", "README.zh-CN.md", + "docs/download-handoff*.md", "docs/media-formats*.md" ], "packageManager": "pnpm@11.22.0", @@ -60,7 +61,9 @@ "test:watch": "vitest", "lint": "biome check .", "format": "biome format --write .", - "prepublishOnly": "npm run build" + "prepublishOnly": "npm run build", + "typecheck": "tsc --noEmit -p tsconfig.test.json", + "check:package": "node --conditions=browser scripts/verify-package.mjs" }, "dependencies": { "vscode-jsonrpc": "^9.0.3", @@ -68,6 +71,7 @@ }, "devDependencies": { "@biomejs/biome": "^2.5.14", + "@motrix/mdxp-legacy": "npm:@motrix/mdxp@0.8.1", "@types/node": "^24.19.0", "typescript": "^7.0.2", "vitest": "^5.0.2" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 21a31ea..f543087 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18,6 +18,9 @@ importers: '@biomejs/biome': specifier: ^2.5.14 version: 2.5.14 + '@motrix/mdxp-legacy': + specifier: npm:@motrix/mdxp@0.8.1 + version: '@motrix/mdxp@0.8.1' '@types/node': specifier: ^24.19.0 version: 24.19.0 @@ -106,6 +109,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@motrix/mdxp@0.8.1': + resolution: {integrity: sha512-wafsE7NNhftWufJ6cDNtJ79125lmtd1liUkIKfTanDAW9ywqkmhFDKIyekyd1UPaS2P6H+RmK+DXTYY8i3ijcA==} + '@napi-rs/wasm-runtime@1.1.6': resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} peerDependencies: @@ -692,6 +698,11 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 + '@motrix/mdxp@0.8.1': + dependencies: + vscode-jsonrpc: 9.0.3 + zod: 4.6.5 + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: '@emnapi/core': 1.11.1 diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs new file mode 100644 index 0000000..19427e3 --- /dev/null +++ b/scripts/verify-package.mjs @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { mkdtemp, readFile, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +// Run via check:package: vscode-jsonrpc exposes its browser entry only under +// the browser export condition. This checks packaging, not browser execution. +// Exercise the actual tarball, not imports from the source checkout. +const temporary = await mkdtemp(join(tmpdir(), 'mdxp-package-')) +try { + const [packed] = JSON.parse( + execFileSync( + 'npm', + [ + 'pack', + '--ignore-scripts', + '--cache', + join(temporary, 'npm-cache'), + '--json', + '--pack-destination', + temporary, + ], + { encoding: 'utf8' } + ) + ) + const files = new Set(packed.files.map((file) => file.path)) + assert.ok(files.has('docs/media-formats.md')) + assert.ok(files.has('docs/media-formats.zh-CN.md')) + assert.ok(files.has('docs/download-handoff.md')) + assert.ok(files.has('docs/download-handoff.zh-CN.md')) + assert.ok(files.has('dist/schemas/download-handoff.d.ts')) + assert.ok(![...files].some((file) => file.includes('__tests__'))) + execFileSync('tar', [ + '-xzf', + join(temporary, packed.filename), + '-C', + temporary, + ]) + const root = join(temporary, 'package') + await symlink(resolve('node_modules'), join(root, 'node_modules'), 'dir') + const manifest = JSON.parse( + await readFile(join(root, 'package.json'), 'utf8') + ) + for (const entry of ['.', './node', './browser']) { + const mod = await import( + pathToFileURL(join(root, manifest.exports[entry].import)).href + ) + for (const name of ['Prepare', 'Commit', 'Status', 'Abort']) { + assert.equal( + mod.Methods[`DownloadHandoff${name}`], + `download/handoff.${name.toLowerCase()}` + ) + assert.equal( + mod.Tools[mod.Methods[`DownloadHandoff${name}`]].agentFacing, + false + ) + assert.equal( + typeof mod[`DownloadHandoff${name}ParamsSchema`].parse, + 'function' + ) + assert.equal( + typeof mod[`DownloadHandoff${name}ResultSchema`].parse, + 'function' + ) + } + assert.equal(mod.Methods.MediaFormats, 'media/formats') + assert.equal(typeof mod.MediaFormatsResultSchema.parse, 'function') + assert.equal(typeof mod.canonicalDownloadHandoffPayload, 'function') + assert.equal(mod.canStartDownloadHandoff(undefined), false) + } + console.log('Verified handoff exports from all three packaged entry points') +} finally { + await rm(temporary, { recursive: true, force: true }) +} diff --git a/src/__tests__/connection.test.ts b/src/__tests__/connection.test.ts index 21f2c80..20a0c81 100644 --- a/src/__tests__/connection.test.ts +++ b/src/__tests__/connection.test.ts @@ -273,3 +273,113 @@ describe('createMdxpConnection', () => { expect(observedCancelled).toBe(true) }) }) + +// Contract transport coverage only: these handlers deliberately do not model a +// database, browser cancellation, or the download engine. +describe('typed handoff requests', () => { + it('round-trips prepare/commit/status/abort without changing the operation binding', async () => { + const { Methods, Tools, DownloadHandoffPrepareParamsSchema } = await import( + '../index.js' + ) + const { aToB, bToA } = makePair() + const client = createMdxpConnection(bToA.reader, aToB.writer) + const server = createMdxpConnection(aToB.reader, bToA.writer) + const key = { + instanceId: 'c2b6a2d2-430c-4bc1-bdb0-c10f35004c90', + operationId: '501e03a1-1c59-4c81-8dad-e670218d81b1', + } + const payloadHash = 'a'.repeat(64) + const taskId = 'reserved-task' + server.onRequest(Methods.DownloadHandoffPrepare, (input) => { + const params = DownloadHandoffPrepareParamsSchema.parse(input) + expect(params.download.selection.primary.url).toBe( + 'http://127.0.0.1/file' + ) + return { ...key, state: 'prepared', taskId, payloadHash, expiresAt: 1000 } + }) + server.onRequest(Methods.DownloadHandoffCommit, (params) => { + expect(params).toEqual({ ...key, payloadHash }) + return { ...key, state: 'committed', taskId, payloadHash } + }) + server.onRequest(Methods.DownloadHandoffStatus, (params) => { + expect(params).toEqual(key) + return { ...key, state: 'committed', taskId, payloadHash } + }) + server.onRequest(Methods.DownloadHandoffAbort, (params) => { + expect(params).toEqual(key) + // A losing abort reports the committed task, never a false cancellation. + return { ...key, state: 'committed', taskId, payloadHash } + }) + client.listen() + server.listen() + try { + const prepare = await client.sendRequest( + Methods.DownloadHandoffPrepare, + DownloadHandoffPrepareParamsSchema.parse({ + ...key, + download: { + source: { + pageUrl: 'https://example.test/', + pageTitle: '', + detectedAt: 0, + }, + selection: { + kind: 'direct', + primary: { url: 'http://127.0.0.1/file' }, + }, + meta: { suggestedFilename: '', qualityLabel: '' }, + }, + }) + ) + expect( + Tools[Methods.DownloadHandoffPrepare]!.resultSchema.parse(prepare) + ).toMatchObject({ ...key, state: 'prepared' }) + const commit = await client.sendRequest(Methods.DownloadHandoffCommit, { + ...key, + payloadHash, + }) + const status = await client.sendRequest( + Methods.DownloadHandoffStatus, + key + ) + const abort = await client.sendRequest(Methods.DownloadHandoffAbort, key) + expect(commit).toEqual({ + ...key, + state: 'committed', + taskId, + payloadHash, + }) + expect(status).toEqual(commit) + expect(abort).toEqual(commit) + } finally { + client.dispose() + server.dispose() + } + }) + it.each([ + ErrorCodes.HandoffInstanceChanged, + ErrorCodes.HandoffPayloadConflict, + ])('preserves handoff refusal %s across the connection', async (code) => { + const { Methods } = await import('../index.js') + const { aToB, bToA } = makePair() + const client = createMdxpConnection(bToA.reader, aToB.writer) + const server = createMdxpConnection(aToB.reader, bToA.writer) + server.onRequest(Methods.DownloadHandoffCommit, () => { + throw new ResponseError(code, 'Handoff refused', { retryable: false }) + }) + client.listen() + server.listen() + try { + await expect( + client.sendRequest(Methods.DownloadHandoffCommit, { + instanceId: 'c2b6a2d2-430c-4bc1-bdb0-c10f35004c90', + operationId: '501e03a1-1c59-4c81-8dad-e670218d81b1', + payloadHash: 'a'.repeat(64), + }) + ).rejects.toMatchObject({ code, data: { retryable: false } }) + } finally { + client.dispose() + server.dispose() + } + }) +}) diff --git a/src/__tests__/download-handoff.test.ts b/src/__tests__/download-handoff.test.ts new file mode 100644 index 0000000..9053c3a --- /dev/null +++ b/src/__tests__/download-handoff.test.ts @@ -0,0 +1,342 @@ +import { createHash } from 'node:crypto' +import { describe, expect, it } from 'vitest' +import { + canonicalDownloadHandoffPayload, + DownloadHandoffAbortResultSchema, + DownloadHandoffCapabilitySchema, + DownloadHandoffCommitParamsSchema, + DownloadHandoffCommitResultSchema, + DownloadHandoffPayloadSchema, + DownloadHandoffPrepareParamsSchema, + DownloadHandoffPrepareResultSchema, + DownloadHandoffStatusResultSchema, + DownloadSubmitParamsSchema, + ErrorCodes, + InitializeResultSchema, + Methods, + Tools, + toAgentToolCatalog, +} from '../index.js' + +const key = { + instanceId: 'c2b6a2d2-430c-4bc1-bdb0-c10f35004c90', + operationId: '501e03a1-1c59-4c81-8dad-e670218d81b1', +} +const download = { + source: { + pageUrl: 'https://example.test/', + pageTitle: '下载', + detectedAt: 42, + }, + selection: { + kind: 'direct' as const, + primary: { url: 'http://127.0.0.1/file' }, + }, + meta: { suggestedFilename: '报告.zip', qualityLabel: '' }, +} +const hash = (value: unknown) => + createHash('sha256') + .update(canonicalDownloadHandoffPayload(value)) + .digest('hex') +const prepared = { + ...key, + state: 'prepared', + taskId: 'reserved-1', + payloadHash: hash(download), + expiresAt: 1000, +} +const committed = { + ...key, + state: 'committed', + taskId: prepared.taskId, + payloadHash: prepared.payloadHash, +} +const oldInitialize = { + protocolVersion: '1.0', + server: { name: 'Motrix', version: '2', runtime: 'server' }, + capabilities: { + ffmpegAvailable: false, + selectionKinds: ['direct'], + progress: false, + cancellation: false, + }, + serverAdapters: [], +} + +describe('handoff negotiation and payload', () => { + it('does not enable handoff on existing peers or change legacy submit', () => { + expect( + InitializeResultSchema.parse(oldInitialize).capabilities.downloadHandoff + ).toBeUndefined() + expect( + DownloadSubmitParamsSchema.parse(download).idempotencyKey + ).toBeUndefined() + expect( + DownloadHandoffPrepareParamsSchema.parse({ ...key, download }).download + .selection.kind + ).toBe('direct') + }) + it('requires version, durable instance identity and bounded preparation lifetime', () => { + const capability = { + version: 1, + instanceId: key.instanceId, + maxPreparedTtlMs: 30_000, + } + const parse = (value: unknown) => + InitializeResultSchema.safeParse({ + ...oldInitialize, + capabilities: { ...oldInitialize.capabilities, downloadHandoff: value }, + }) + expect(parse(capability).success).toBe(true) + for (const value of [ + true, + {}, + { ...capability, version: 2 }, + { ...capability, instanceId: '' }, + { ...capability, maxPreparedTtlMs: 0 }, + { ...capability, maxPreparedTtlMs: 120_001 }, + ]) { + expect(DownloadHandoffCapabilitySchema.safeParse(value).success).toBe( + false + ) + const result = parse(value) + expect(result.success).toBe(true) + if (result.success) + expect(result.data.capabilities.downloadHandoff).toBeUndefined() + } + }) + it.each(['magnet', 'hls', 'dash', 'mux'])( + 'does not silently widen v1 to %s', + (kind) => { + expect( + DownloadHandoffPayloadSchema.safeParse({ + ...download, + selection: { ...download.selection, kind }, + }).success + ).toBe(false) + } + ) + it.each([ + 'blob:https://example.test/id', + 'data:text/plain,a', + 'file:///tmp/a', + 'ftp://example.test/a', + ])('leaves unsupported source %s outside handoff', (url) => { + expect( + DownloadHandoffPayloadSchema.safeParse({ + ...download, + selection: { ...download.selection, primary: { url } }, + }).success + ).toBe(false) + }) + it.each(['method', 'body', 'postData'])( + 'rejects %s instead of silently converting a request to GET', + (field) => { + for (const input of [ + { ...download, [field]: 'POST' }, + { ...download, selection: { ...download.selection, [field]: 'POST' } }, + { + ...download, + selection: { + ...download.selection, + primary: { ...download.selection.primary, [field]: 'POST' }, + }, + }, + ]) + expect(DownloadHandoffPayloadSchema.safeParse(input).success).toBe( + false + ) + } + ) + it('has one operation key and no caller-supplied principal', () => { + for (const input of [ + { ...key, clientId: 'other', download }, + { ...key, operationId: '', download }, + { ...key, download: { ...download, idempotencyKey: 'another-key' } }, + ]) + expect(DownloadHandoffPrepareParamsSchema.safeParse(input).success).toBe( + false + ) + }) + it('binds commit to the previously approved payload hash', () => { + expect(DownloadHandoffCommitParamsSchema.safeParse(key).success).toBe(false) + expect( + DownloadHandoffCommitParamsSchema.safeParse({ + ...key, + payloadHash: prepared.payloadHash, + }).success + ).toBe(true) + expect( + DownloadHandoffCommitParamsSchema.safeParse({ + ...key, + payloadHash: 'bad', + }).success + ).toBe(false) + }) +}) + +describe('method-specific outcomes', () => { + it('allows prepared only before commit and requires stable task/hash evidence', () => { + expect(DownloadHandoffPrepareResultSchema.parse(prepared)).toEqual(prepared) + expect(DownloadHandoffStatusResultSchema.parse(prepared)).toEqual(prepared) + expect(DownloadHandoffCommitResultSchema.safeParse(prepared).success).toBe( + false + ) + expect(DownloadHandoffAbortResultSchema.safeParse(prepared).success).toBe( + false + ) + for (const invalid of [ + { ...prepared, taskId: '' }, + { ...prepared, payloadHash: undefined }, + { ...prepared, expiresAt: -1 }, + ]) + expect( + DownloadHandoffPrepareResultSchema.safeParse(invalid).success + ).toBe(false) + }) + it('returns committed from repeated prepare, commit, status, or a losing abort', () => { + for (const schema of [ + DownloadHandoffPrepareResultSchema, + DownloadHandoffCommitResultSchema, + DownloadHandoffStatusResultSchema, + DownloadHandoffAbortResultSchema, + ]) + expect(schema.parse(committed)).toEqual(committed) + }) + it.each(['aborted', 'expired'])( + 'keeps %s terminal across all method results', + (state) => { + for (const schema of [ + DownloadHandoffPrepareResultSchema, + DownloadHandoffCommitResultSchema, + DownloadHandoffStatusResultSchema, + DownloadHandoffAbortResultSchema, + ]) { + expect(schema.parse({ ...key, state })).toEqual({ ...key, state }) + expect( + schema.safeParse({ ...key, state, taskId: 'must-not-activate' }) + .success + ).toBe(false) + } + } + ) + it('distinguishes a status/commit miss from the durable tombstone required by abort', () => { + const miss = { ...key, state: 'not-found' } + expect(DownloadHandoffStatusResultSchema.parse(miss)).toEqual(miss) + expect(DownloadHandoffCommitResultSchema.parse(miss)).toEqual(miss) + expect(DownloadHandoffPrepareResultSchema.safeParse(miss).success).toBe( + false + ) + expect(DownloadHandoffAbortResultSchema.safeParse(miss).success).toBe(false) + }) + it('rejects malformed or ambiguous results instead of silently discarding fields', () => { + for (const result of [ + { ...prepared, state: 'unknown' }, + { ...prepared, instanceId: '' }, + { ...committed, expiresAt: 1000 }, + { ...key, state: 'not-found', taskId: 'task' }, + ]) + expect(DownloadHandoffStatusResultSchema.safeParse(result).success).toBe( + false + ) + }) +}) + +describe('shared immutable payload encoding', () => { + it('normalizes omitted defaults and object insertion order identically', () => { + const normalized = DownloadHandoffPayloadSchema.parse(download) + const reordered = { + meta: normalized.meta, + selection: { + primary: { + cookies: [], + refererPolicy: 'strict-origin-when-cross-origin', + headers: {}, + url: download.selection.primary.url, + }, + kind: 'direct', + }, + source: { + detectedAt: 42, + pageTitle: '下载', + pageUrl: 'https://example.test/', + }, + } + expect(canonicalDownloadHandoffPayload(reordered)).toBe( + canonicalDownloadHandoffPayload(download) + ) + expect(hash(reordered)).toBe(hash(download)) + expect(JSON.parse(canonicalDownloadHandoffPayload(download))).toEqual( + normalized + ) + }) + it('has a stable wire vector for non-ASCII metadata and normalized defaults', () => { + expect(canonicalDownloadHandoffPayload(download)).toBe( + '{"meta":{"qualityLabel":"","suggestedFilename":"报告.zip"},"selection":{"kind":"direct","primary":{"cookies":[],"headers":{},"refererPolicy":"strict-origin-when-cross-origin","url":"http://127.0.0.1/file"}},"source":{"detectedAt":42,"pageTitle":"下载","pageUrl":"https://example.test/"}}' + ) + }) + it('binds filename, directory, request headers, cookies and source URL', () => { + const variants = [ + { ...download, saveDir: '/different' }, + { + ...download, + meta: { ...download.meta, suggestedFilename: 'other.zip' }, + }, + { + ...download, + selection: { + ...download.selection, + primary: { + ...download.selection.primary, + headers: { Authorization: 'synthetic' }, + }, + }, + }, + { + ...download, + selection: { + ...download.selection, + primary: { + ...download.selection.primary, + cookies: [{ name: 'a', value: 'b', domain: 'example.test' }], + }, + }, + }, + { + ...download, + selection: { + ...download.selection, + primary: { url: 'https://example.test/different' }, + }, + }, + ] + for (const value of variants) expect(hash(value)).not.toBe(hash(download)) + }) + it('does not mutate input and rejects unknown options before fingerprinting', () => { + const original = structuredClone(download) + canonicalDownloadHandoffPayload(download) + expect(download).toEqual(original) + expect(() => + canonicalDownloadHandoffPayload({ ...download, overwrite: true }) + ).toThrow() + }) +}) + +it('registers all four methods as extension-only, with distinct error codes', () => { + for (const method of [ + Methods.DownloadHandoffPrepare, + Methods.DownloadHandoffCommit, + Methods.DownloadHandoffStatus, + Methods.DownloadHandoffAbort, + ]) { + expect(Tools[method]?.agentFacing).toBe(false) + expect(Tools[method]?.paramsSchema).toBeDefined() + expect(Tools[method]?.resultSchema).toBeDefined() + expect(toAgentToolCatalog().some((tool) => tool.name === method)).toBe( + false + ) + } + expect(new Set(Object.values(ErrorCodes)).size).toBe( + Object.values(ErrorCodes).length + ) +}) diff --git a/src/__tests__/e2e.test.ts b/src/__tests__/e2e.test.ts index 420367d..ada5e5e 100644 --- a/src/__tests__/e2e.test.ts +++ b/src/__tests__/e2e.test.ts @@ -4,6 +4,7 @@ import 'vscode-jsonrpc/node' import { describe, expect, it } from 'vitest' import type { Message, MessageReader, MessageWriter } from 'vscode-jsonrpc' import { createMdxpConnection } from '../connection.js' +import { InitializeParamsSchema, InitializeResultSchema } from '../index.js' class InMemoryReader implements MessageReader { private listeners: Array<(msg: Message) => void> = [] @@ -59,7 +60,7 @@ describe('e2e: full init + resolve + completion flow', () => { // Motrix handles initialize motrix.onRequest('motrix/initialize', (params) => { expect(params.protocolVersion).toBe('1.0') - return { + return InitializeResultSchema.parse({ protocolVersion: '1.0', server: { name: 'motrix', version: '2.0', runtime: 'electron' }, capabilities: { @@ -70,7 +71,7 @@ describe('e2e: full init + resolve + completion flow', () => { }, serverAdapters: [], pairToken: 'tok-123', - } + }) }) // ext handles url/resolve @@ -114,19 +115,22 @@ describe('e2e: full init + resolve + completion flow', () => { motrix.listen() // ext initiates handshake - const initResult = await ext.sendRequest('motrix/initialize', { - protocolVersion: '1.0', - client: { - name: 'motrix-extension', - version: '0.1', - extensionId: 'ext-id', - browser: 'chromium', - browserVersion: '120', - locale: 'en', - }, - capabilities: { resolveUrl: true, submitDownload: true }, - adapters: [], - }) + const initResult = await ext.sendRequest( + 'motrix/initialize', + InitializeParamsSchema.parse({ + protocolVersion: '1.0', + client: { + name: 'motrix-extension', + version: '0.1', + extensionId: 'ext-id', + browser: 'chromium', + browserVersion: '120', + locale: 'en', + }, + capabilities: { resolveUrl: true, submitDownload: true }, + adapters: [], + }) + ) expect(initResult.pairToken).toBe('tok-123') // Motrix → ext: url/resolve diff --git a/src/__tests__/handoff-compatibility.test.ts b/src/__tests__/handoff-compatibility.test.ts new file mode 100644 index 0000000..8d448c2 --- /dev/null +++ b/src/__tests__/handoff-compatibility.test.ts @@ -0,0 +1,177 @@ +import { PassThrough } from 'node:stream' +import * as legacy from '@motrix/mdxp-legacy/node' +import { describe, expect, it } from 'vitest' +import * as current from '../node.js' + +const advertisement = { + version: 1, + instanceId: 'c2b6a2d2-430c-4bc1-bdb0-c10f35004c90', + maxPreparedTtlMs: 30_000, + acceptingNew: true, +} +const initialize = { + protocolVersion: '1.0', + server: { name: 'Motrix', version: 'test', runtime: 'electron' }, + capabilities: { + ffmpegAvailable: false, + selectionKinds: ['direct'], + progress: true, + cancellation: true, + }, + serverAdapters: [], +} +const download = { + source: { pageUrl: 'https://example.test/', pageTitle: '', detectedAt: 42 }, + selection: { + kind: 'direct', + primary: { url: 'http://127.0.0.1/archive.zip' }, + }, + meta: { suggestedFilename: 'archive.zip', qualityLabel: '' }, + idempotencyKey: 'legacy-operation', +} + +// Wire compatibility with the published 0.8.1 SDK, not a copied legacy schema. +// These peers are fixtures; production server route retention still needs E2E. +describe('independent extension and host upgrades', () => { + it.each([ + { + name: 'old extension / old host', + clientSdk: legacy, + serverSdk: legacy, + capability: undefined, + }, + { + name: 'old extension / upgraded host', + clientSdk: legacy, + serverSdk: current, + capability: advertisement, + }, + { + name: 'new extension / old host', + clientSdk: current, + serverSdk: legacy, + capability: undefined, + }, + { + name: 'new extension / new host with rollout disabled', + clientSdk: current, + serverSdk: current, + capability: { ...advertisement, acceptingNew: false }, + }, + { + name: 'new extension / future handoff host', + clientSdk: current, + serverSdk: current, + capability: { ...advertisement, version: 2 }, + }, + ])( + '$name retains initialize and download/submit', + async ({ clientSdk, serverSdk, capability }) => { + const requests = new PassThrough() + const replies = new PassThrough() + const client = clientSdk.createMdxpConnection( + new clientSdk.StreamMessageReader(replies), + new clientSdk.StreamMessageWriter(requests) + ) + const server = serverSdk.createMdxpConnection( + new serverSdk.StreamMessageReader(requests), + new serverSdk.StreamMessageWriter(replies) + ) + let submits = 0 + server.onRequest('motrix/initialize', (params) => { + expect(serverSdk.InitializeParamsSchema.parse(params).client.kind).toBe( + 'extension' + ) + // Preserve the future capability on the wire to test the client's parser. + return { + ...serverSdk.InitializeResultSchema.parse(initialize), + capabilities: { + ...serverSdk.InitializeResultSchema.parse(initialize).capabilities, + ...(capability ? { downloadHandoff: capability } : {}), + }, + } + }) + server.onRequest('download/submit', (params) => { + expect(serverSdk.DownloadSubmitParamsSchema.parse(params)).toEqual( + current.DownloadSubmitParamsSchema.parse(download) + ) + submits += 1 + return { taskId: 'legacy-task' } + }) + client.listen() + server.listen() + try { + const reply = await client.sendRequest( + 'motrix/initialize', + clientSdk.InitializeParamsSchema.parse({ + protocolVersion: '1.0', + client: { + name: 'extension', + version: 'test', + extensionId: 'synthetic', + browser: 'firefox', + browserVersion: '143', + locale: 'en', + }, + capabilities: { submitDownload: true }, + adapters: [], + }) + ) + const parsed = clientSdk.InitializeResultSchema.parse(reply) + const capability = + 'downloadHandoff' in parsed.capabilities + ? parsed.capabilities.downloadHandoff + : undefined + if (clientSdk === current) + expect(current.canStartDownloadHandoff(capability, true)).toBe(false) + const submitted = await client.sendRequest( + 'download/submit', + clientSdk.DownloadSubmitParamsSchema.parse(download) + ) + expect(clientSdk.DownloadSubmitResultSchema.parse(submitted)).toEqual({ + taskId: 'legacy-task', + }) + expect(submits).toBe(1) + } finally { + client.dispose() + server.dispose() + requests.destroy() + replies.destroy() + } + } + ) + + it('requires both gates for new operations and defaults the server gate off', () => { + expect(current.canStartDownloadHandoff(advertisement)).toBe(false) + expect(current.canStartDownloadHandoff(advertisement, false)).toBe(false) + expect(current.canStartDownloadHandoff(advertisement, true)).toBe(true) + for (const capability of [ + undefined, + {}, + { ...advertisement, acceptingNew: false }, + { ...advertisement, acceptingNew: undefined }, + { ...advertisement, version: 2 }, + { ...advertisement, instanceId: '' }, + ]) + expect(current.canStartDownloadHandoff(capability, true)).toBe(false) + }) + + it('does not turn an invalid base handshake into a valid one', () => { + expect( + current.InitializeResultSchema.safeParse({ + ...initialize, + protocolVersion: '2.0', + capabilities: { + ...initialize.capabilities, + downloadHandoff: advertisement, + }, + }).success + ).toBe(false) + expect( + current.InitializeResultSchema.safeParse({ + ...initialize, + capabilities: { downloadHandoff: advertisement }, + }).success + ).toBe(false) + }) +}) diff --git a/src/__tests__/media-formats.test.ts b/src/__tests__/media-formats.test.ts index 3648fcb..7b849bb 100644 --- a/src/__tests__/media-formats.test.ts +++ b/src/__tests__/media-formats.test.ts @@ -41,7 +41,7 @@ describe('media formats request boundary', () => { const parsed = MediaFormatsParamsSchema.parse({ url, cookies: [cookie] }) expect(parsed.cookies).toEqual([cookie]) expect(CookieSchema.parse(parsed.cookies?.[0])).toEqual(cookie) - expect(parsed.cookies?.[0].expiresAt).toBe(1_900_000_000_123) + expect(parsed.cookies?.[0]?.expiresAt).toBe(1_900_000_000_123) }) it.each([ @@ -168,7 +168,7 @@ describe('media formats request boundary', () => { const parsed = MediaFormatsParamsSchema.parse({ url, cookies: [scoped] }) expect(parsed.url).toBe(url) expect(parsed.cookies).toEqual([scoped]) - expect(parsed.cookies?.[0].domain.endsWith('.')).toBe(true) + expect(parsed.cookies?.[0]?.domain.endsWith('.')).toBe(true) }) it.each([ diff --git a/src/connection.ts b/src/connection.ts index 93cadb8..15c4a7d 100644 --- a/src/connection.ts +++ b/src/connection.ts @@ -13,6 +13,14 @@ import type { DownloadCancelResult, DownloadDirectoriesParams, DownloadDirectoriesResult, + DownloadHandoffAbortParams, + DownloadHandoffAbortResult, + DownloadHandoffCommitParams, + DownloadHandoffCommitResult, + DownloadHandoffPrepareParams, + DownloadHandoffPrepareResult, + DownloadHandoffStatusParams, + DownloadHandoffStatusResult, DownloadSubmitParams, DownloadSubmitResult, EngineStatusParams, @@ -52,6 +60,22 @@ import type { export interface MdxpRequestMap { 'motrix/initialize': [InitializeParams, InitializeResult] 'download/submit': [DownloadSubmitParams, DownloadSubmitResult] + 'download/handoff.prepare': [ + DownloadHandoffPrepareParams, + DownloadHandoffPrepareResult, + ] + 'download/handoff.commit': [ + DownloadHandoffCommitParams, + DownloadHandoffCommitResult, + ] + 'download/handoff.status': [ + DownloadHandoffStatusParams, + DownloadHandoffStatusResult, + ] + 'download/handoff.abort': [ + DownloadHandoffAbortParams, + DownloadHandoffAbortResult, + ] 'download/directories': [DownloadDirectoriesParams, DownloadDirectoriesResult] 'download/cancel': [DownloadCancelParams, DownloadCancelResult] 'url/probe': [UrlProbeParams, UrlProbeResult] diff --git a/src/errors.ts b/src/errors.ts index b879745..a2a52fa 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -16,6 +16,8 @@ export const ErrorCodes = Object.freeze({ RateLimited: -32004, CapabilityNotSupported: -32005, PairRevoked: -32006, + HandoffInstanceChanged: -32007, + HandoffPayloadConflict: -32008, } as const) export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes] diff --git a/src/handoff.ts b/src/handoff.ts new file mode 100644 index 0000000..5c97549 --- /dev/null +++ b/src/handoff.ts @@ -0,0 +1,40 @@ +import { + DownloadHandoffCapabilitySchema, + DownloadHandoffPayloadSchema, +} from './schemas/download-handoff.js' + +/** + * Normalize schema defaults and sort object keys by UTF-16 code units, retaining + * array order. Hash the returned string's UTF-8 bytes with SHA-256. This is an + * MDXP encoding, not a general JSON canonicalization or authorization scheme. + * No IO or platform crypto is needed, so both peers use the same normalization. + */ +export function canonicalDownloadHandoffPayload(input: unknown): string { + const normalized = DownloadHandoffPayloadSchema.parse(input) + return encode(normalized) +} + +function encode(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(encode).join(',')}]` + if (value !== null && typeof value === 'object') { + const fields = Object.entries(value) + .filter(([, item]) => item !== undefined) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + return `{${fields.map(([key, item]) => `${JSON.stringify(key)}:${encode(item)}`).join(',')}}` + } + return JSON.stringify(value) +} + +/** + * Eligibility for a NEW operation only. Both rollout gates default closed. + * Never use this to downgrade a transmitted handoff: recover its persisted key + * through the original instance even while acceptingNew is false. + */ +export function canStartDownloadHandoff( + advertisement: unknown, + clientEnabled = false +): boolean { + if (!clientEnabled) return false + const parsed = DownloadHandoffCapabilitySchema.safeParse(advertisement) + return parsed.success && parsed.data.acceptingNew +} diff --git a/src/index.ts b/src/index.ts index dd7cdc1..be7ff3c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,6 +29,10 @@ export { isProtocolError, makeMdxpError, } from './errors.js' +export { + canonicalDownloadHandoffPayload, + canStartDownloadHandoff, +} from './handoff.js' export type { Method, Notification } from './methods.js' export { Methods, Notifications } from './methods.js' diff --git a/src/methods.ts b/src/methods.ts index e0f5fd0..78c7ef6 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -2,6 +2,10 @@ export const Methods = Object.freeze({ MotrixInitialize: 'motrix/initialize', DownloadSubmit: 'download/submit', + DownloadHandoffPrepare: 'download/handoff.prepare', + DownloadHandoffCommit: 'download/handoff.commit', + DownloadHandoffStatus: 'download/handoff.status', + DownloadHandoffAbort: 'download/handoff.abort', DownloadDirectories: 'download/directories', DownloadCancel: 'download/cancel', UrlProbe: 'url/probe', diff --git a/src/schemas/download-handoff.ts b/src/schemas/download-handoff.ts new file mode 100644 index 0000000..d270a6a --- /dev/null +++ b/src/schemas/download-handoff.ts @@ -0,0 +1,134 @@ +import { z } from 'zod' +import { DownloadSubmitParamsSchema } from './download.js' +import { CookieSchema, ResourceSchema } from './resource.js' +import { SelectionSchema } from './selection.js' + +/** Optional capability. Absence means the server cannot perform handoff v1. */ +export const DownloadHandoffCapabilitySchema = z.object({ + version: z.literal(1), + /** Stable across restart; MUST rotate if the durable ledger is lost/reset. */ + instanceId: z.uuid(), + maxPreparedTtlMs: z.number().int().min(1).max(120_000), + /** False drains existing operations while new downloads use legacy submit. */ + acceptingNew: z.boolean().default(false), +}) + +/** Identity is supplied by the authenticated transport, never these params. */ +export const DownloadHandoffKeySchema = z + .object({ + instanceId: z.uuid(), + operationId: z.uuid(), + }) + .strict() + +// V1 only prepares direct HTTP(S) GET downloads. Strict objects prevent a +// caller's POST/body/options from being silently stripped into a GET request. +export const DownloadHandoffPayloadSchema = DownloadSubmitParamsSchema.omit({ + idempotencyKey: true, +}) + .extend({ + source: DownloadSubmitParamsSchema.shape.source.strict(), + meta: DownloadSubmitParamsSchema.shape.meta.strict(), + selection: SelectionSchema.options[0] + .extend({ + primary: ResourceSchema.extend({ + cookies: z.array(CookieSchema.strict()).default([]), + }).strict(), + }) + .strict(), + }) + .strict() + +export const DownloadHandoffPrepareParamsSchema = + DownloadHandoffKeySchema.extend({ + download: DownloadHandoffPayloadSchema, + }).strict() +export const DownloadHandoffCommitParamsSchema = + DownloadHandoffKeySchema.extend({ + payloadHash: z.string().regex(/^[a-f0-9]{64}$/), + }).strict() +export const DownloadHandoffStatusParamsSchema = DownloadHandoffKeySchema +export const DownloadHandoffAbortParamsSchema = DownloadHandoffKeySchema + +const task = { + taskId: z.string().min(1).max(128), + /** SHA-256 of canonicalDownloadHandoffPayload(download), encoded as UTF-8. */ + payloadHash: z.string().regex(/^[a-f0-9]{64}$/), +} +const prepared = DownloadHandoffKeySchema.extend({ + state: z.literal('prepared'), + ...task, + /** Server Unix milliseconds; expiry is checked inside the ledger transaction. */ + expiresAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), +}).strict() +const committed = DownloadHandoffKeySchema.extend({ + state: z.literal('committed'), + ...task, +}).strict() +const aborted = DownloadHandoffKeySchema.extend({ + state: z.literal('aborted'), +}).strict() +const expired = DownloadHandoffKeySchema.extend({ + state: z.literal('expired'), +}).strict() +const notFound = DownloadHandoffKeySchema.extend({ + /** Observation only: a prepare/commit may still be in flight. */ + state: z.literal('not-found'), +}).strict() + +export const DownloadHandoffPrepareResultSchema = z.discriminatedUnion( + 'state', + [prepared, committed, aborted, expired] +) +export const DownloadHandoffStatusResultSchema = z.discriminatedUnion('state', [ + prepared, + committed, + aborted, + expired, + notFound, +]) +/** A successful commit response never leaves the operation merely prepared. */ +export const DownloadHandoffCommitResultSchema = z.discriminatedUnion('state', [ + committed, + aborted, + expired, + notFound, +]) +/** Aborting an absent operation creates a tombstone; it never returns not-found. */ +export const DownloadHandoffAbortResultSchema = z.discriminatedUnion('state', [ + aborted, + committed, + expired, +]) + +export type DownloadHandoffCapability = z.infer< + typeof DownloadHandoffCapabilitySchema +> +export type DownloadHandoffKey = z.infer +export type DownloadHandoffPayload = z.infer< + typeof DownloadHandoffPayloadSchema +> +export type DownloadHandoffPrepareParams = z.infer< + typeof DownloadHandoffPrepareParamsSchema +> +export type DownloadHandoffPrepareResult = z.infer< + typeof DownloadHandoffPrepareResultSchema +> +export type DownloadHandoffCommitParams = z.infer< + typeof DownloadHandoffCommitParamsSchema +> +export type DownloadHandoffCommitResult = z.infer< + typeof DownloadHandoffCommitResultSchema +> +export type DownloadHandoffStatusParams = z.infer< + typeof DownloadHandoffStatusParamsSchema +> +export type DownloadHandoffStatusResult = z.infer< + typeof DownloadHandoffStatusResultSchema +> +export type DownloadHandoffAbortParams = z.infer< + typeof DownloadHandoffAbortParamsSchema +> +export type DownloadHandoffAbortResult = z.infer< + typeof DownloadHandoffAbortResultSchema +> diff --git a/src/schemas/index.ts b/src/schemas/index.ts index 681d6f6..92e7de6 100644 --- a/src/schemas/index.ts +++ b/src/schemas/index.ts @@ -1,6 +1,7 @@ export * from './download.js' export * from './download-add.js' export * from './download-directories.js' +export * from './download-handoff.js' export * from './engine.js' export * from './events.js' export * from './initialize.js' diff --git a/src/schemas/initialize.ts b/src/schemas/initialize.ts index 74ce3be..38fe1c7 100644 --- a/src/schemas/initialize.ts +++ b/src/schemas/initialize.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { DownloadHandoffCapabilitySchema } from './download-handoff.js' const PROTOCOL_VERSION = '1.0' @@ -74,6 +75,10 @@ const ServerCapabilitiesSchema = z.object({ taskReveal: z.boolean().optional().default(false), /** Enables download/directories AND download/submit.saveDir; absent is false. */ downloadDirectories: z.boolean().optional(), + /** Advertise only with all four methods and a durable, recoverable ledger. */ + // Unknown/invalid optional versions must not break the base handshake. + // This affects new-operation eligibility, never recovery of an existing key. + downloadHandoff: DownloadHandoffCapabilitySchema.optional().catch(undefined), /** Registered, authorized extension format listing; absent/false means no call. */ mediaFormats: z.boolean().optional(), }) diff --git a/src/tools.ts b/src/tools.ts index 82efddb..973258d 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -14,6 +14,16 @@ import { DownloadDirectoriesParamsSchema, DownloadDirectoriesResultSchema, } from './schemas/download-directories.js' +import { + DownloadHandoffAbortParamsSchema, + DownloadHandoffAbortResultSchema, + DownloadHandoffCommitParamsSchema, + DownloadHandoffCommitResultSchema, + DownloadHandoffPrepareParamsSchema, + DownloadHandoffPrepareResultSchema, + DownloadHandoffStatusParamsSchema, + DownloadHandoffStatusResultSchema, +} from './schemas/download-handoff.js' import { EngineStatusParamsSchema, EngineStatusResultSchema, @@ -94,6 +104,38 @@ export const Tools: Readonly> = { resultSchema: DownloadDirectoriesResultSchema, agentFacing: false, }, + [Methods.DownloadHandoffPrepare]: { + method: Methods.DownloadHandoffPrepare, + description: + 'Prepare an inactive direct download without fetching its source.', + paramsSchema: DownloadHandoffPrepareParamsSchema, + resultSchema: DownloadHandoffPrepareResultSchema, + agentFacing: false, + }, + [Methods.DownloadHandoffCommit]: { + method: Methods.DownloadHandoffCommit, + description: + 'Commit a prepared download after the browser confirms its transfer stopped.', + paramsSchema: DownloadHandoffCommitParamsSchema, + resultSchema: DownloadHandoffCommitResultSchema, + agentFacing: false, + }, + [Methods.DownloadHandoffStatus]: { + method: Methods.DownloadHandoffStatus, + description: + 'Read an authenticated operation; not-found never proves no request is in flight.', + paramsSchema: DownloadHandoffStatusParamsSchema, + resultSchema: DownloadHandoffStatusResultSchema, + agentFacing: false, + }, + [Methods.DownloadHandoffAbort]: { + method: Methods.DownloadHandoffAbort, + description: + 'Abort an uncommitted handoff, creating a tombstone even if absent.', + paramsSchema: DownloadHandoffAbortParamsSchema, + resultSchema: DownloadHandoffAbortResultSchema, + agentFacing: false, + }, [Methods.DownloadSubmit]: { method: Methods.DownloadSubmit, description: diff --git a/src/types.ts b/src/types.ts index c2eac41..581a1ed 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,19 @@ export type { DownloadDirectoriesParams, DownloadDirectoriesResult, } from './schemas/download-directories.js' +export type { + DownloadHandoffAbortParams, + DownloadHandoffAbortResult, + DownloadHandoffCapability, + DownloadHandoffCommitParams, + DownloadHandoffCommitResult, + DownloadHandoffKey, + DownloadHandoffPayload, + DownloadHandoffPrepareParams, + DownloadHandoffPrepareResult, + DownloadHandoffStatusParams, + DownloadHandoffStatusResult, +} from './schemas/download-handoff.js' export type { EngineFeatureReport, EngineState, diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..a59adea --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "noEmit": true }, + "include": ["src/**/*"], + "exclude": ["dist"] +}