From 7ea565621ce1ea2e17d80b212c3622664488b59a Mon Sep 17 00:00:00 2001 From: Nuomi Date: Sun, 18 Oct 2026 20:06:04 +0800 Subject: [PATCH 1/2] feat(protocol): define bounded media format queries --- README.md | 17 ++ README.zh-CN.md | 13 + docs/media-formats.md | 189 +++++++++++++ docs/media-formats.zh-CN.md | 148 +++++++++++ package.json | 5 +- src/__tests__/connection.test.ts | 82 +++++- src/__tests__/media-formats.test.ts | 395 ++++++++++++++++++++++++++++ src/connection.ts | 3 + src/methods.ts | 1 + src/schemas/index.ts | 1 + src/schemas/initialize.ts | 2 + src/schemas/media-formats.ts | 246 +++++++++++++++++ src/tools.ts | 12 + src/types.ts | 6 + 14 files changed, 1117 insertions(+), 3 deletions(-) create mode 100644 docs/media-formats.md create mode 100644 docs/media-formats.zh-CN.md create mode 100644 src/__tests__/media-formats.test.ts create mode 100644 src/schemas/media-formats.ts diff --git a/README.md b/README.md index 9158799..0575ea7 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,22 @@ path. It is registered in `Tools` for schema discovery but intentionally omitted from `toAgentToolCatalog()` because opening a file-manager window is a UI side effect and must be initiated by the user. +### List media quality choices (client → server) + +`media/formats` (since 0.9.0) is an optional extension-only method for a quality +picker. Call it only after an explicit user action, advertised +`capabilities.mediaFormats === true`, and the current endpoint's data-sharing +authorization. Cookie disclosure additionally requires the separate credential +grant. An old host receives no request. + +Use `MediaFormatsParamsSchema` / `MediaFormatsResultSchema` and send parsed +values. Requests preserve full Cookie scope (expiry in Unix milliseconds), are +bounded to 64 KiB, and do not authorize a later download. Results are either a +nonempty quality list or `{ available: false, reason, entries: [] }`. See the +[media formats contract](docs/media-formats.md) for the mandatory authorization, +extractor, error, and compatibility rules. The connection helper does not grant +permissions or run these checks for an application. + ### Resolve a page (server → client) The desktop app asks a client whether it can handle a page (`url/probe`), then @@ -370,6 +386,7 @@ copy of `vscode-jsonrpc` can cause it to be serialized as an internal error. | `system/ping` | client → server | | Liveness probe; echoes `sentAt` with `recvAt`. | | `download/submit` | client → server | | Submit a browser-detected, page-shaped download. | | `download/cancel` | client → server | | Cancel a submitted download by task id. | +| `media/formats` | client → server | | List explicitly requested media quality choices (extension-only). | | `download/add` | client → server | ✓ | Add a download by URL(s), magnet, or torrent. | | `task/list` | client → server | ✓ | List tasks, filterable + paginated. | | `task/get` | client → server | ✓ | Get one task by id. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 0f66b55..e4fa990 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -199,6 +199,18 @@ if (hello.capabilities.taskReveal ?? false) { `taskId`,绝不接受任意本地路径。它会注册在 `Tools` 中以便发现 schema,但不会进入 `toAgentToolCatalog()`;打开文件管理器属于 UI 副作用,必须由用户发起。 +### 列出媒体画质选项(client → server) + +`media/formats`(自 0.9.0 起)是供扩展画质选择器使用的可选方法。只有用户明确操作、 +目标声明 `capabilities.mediaFormats === true`,且当前端点的数据共享授权有效时才能 +调用;Cookie 披露还需要独立凭据授权。不得向旧目标发送试探请求。 + +使用 `MediaFormatsParamsSchema`/`MediaFormatsResultSchema` 并发送解析后的值。 +请求保留 Cookie 的完整作用域(Unix 毫秒有效期),总大小不超过 64 KiB,也不构成后续 +下载授权。结果为非空画质列表,或 `{ available: false, reason, entries: [] }`。 +必需的授权、抽取器、错误和兼容规则见[媒体格式契约](docs/media-formats.zh-CN.md)。 +连接辅助函数不会替应用授予权限或执行这些检查。 + ### 解析页面(server → client) 桌面端会先问某个 client 能否处理这个页面(`url/probe`),再请它抽取出可下载的资源 @@ -349,6 +361,7 @@ RPC handler 需要保留错误码和 data 时,应抛出从 `@motrix/mdxp` 导 | `system/ping` | client → server | | 存活探测;回显 `sentAt` 与 `recvAt`。 | | `download/submit` | client → server | | 提交浏览器侦测到的 page 形态下载。 | | `download/cancel` | client → server | | 按 task id 取消已提交的下载。 | +| `media/formats` | client → server | | 列出用户明确请求的媒体画质选项(仅供扩展)。 | | `download/add` | client → server | ✓ | 按 URL / magnet / torrent 添加下载。 | | `task/list` | client → server | ✓ | 列出 task,可过滤、可分页。 | | `task/get` | client → server | ✓ | 按 id 取单个 task。 | diff --git a/docs/media-formats.md b/docs/media-formats.md new file mode 100644 index 0000000..435f9b5 --- /dev/null +++ b/docs/media-formats.md @@ -0,0 +1,189 @@ +# Media formats contract (MDXP 0.9.0) + +`media/formats` supplies the quality picker proposed in Motrix PR #2365. It +returns video-height choices and an optional MP3 extraction choice. It does not +submit a task, prove that a download is authorized, or change pairing. The +package supplies schemas and typed RPC registration; the applications enforce +the authorization and extractor requirements below. + +## Negotiation and transport + +- Keep `protocolVersion` at `1.0` and all existing pairing and submit behavior. +- A host advertises `capabilities.mediaFormats: true` only when a lister is + registered and the host implements this contract. Missing or false means the + client MUST NOT send the request, including speculative probes. +- This method is for authenticated, ready extension sessions. It is registered + in `Tools` with `agentFacing: false`, absent from `toAgentToolCatalog()`, and + MUST NOT be exposed through unary `POST /mdxp`. The registry flag and a claimed + `client.kind` are not authentication. Use the transport-verified principal. +- Capability negotiation describes support; it grants no permission to collect + or disclose a page URL or cookies. + +## Client authorization before collection and transmission + +1. Start from an explicit user action requesting qualities for the current page + or selected embedded player. Merely loading a page, observing a video, + polling, or reconnecting MUST NOT trigger a disclosure. +2. Derive the target from the browser's current tab/document/frame identity. + An arbitrary same-origin path is not an authenticated frame URL. Preserve + existing build/site exclusions independently of a quality label or listing. +3. For a remote host, require the existing data-sharing grant for the exact + selected authority and authenticated instance before sending the URL. + Require the separate credential grant before collecting or sending cookies. + In the extension these are `remoteDataBoundaryAcceptedAt` and + `allowRequestCredentials`; pairing alone satisfies neither grant. +4. Capture the endpoint generation, authenticated instance, document identity, + and relevant grants. Revalidate after asynchronous work and immediately + before sending. Revocation, endpoint edits/switches, or document changes + invalidate the operation; do not redirect or replay it against a new host. +5. Collect only cookies applicable to this exact browser document and its + current cookie store/partition. Retain their scope fields. Do not read all + browser cookies or consult another browser profile as a fallback. +6. Parse with `MediaFormatsParamsSchema` and send the parsed value, not the + original object. The generic connection helper does not enforce these + application-owned checks or automatically validate payloads. + +Local pairing also does not authorize background cookie collection. The same +explicit-action and current-document requirements apply to local hosts. + +## Request and cookie scope + +The strict request is `{ url, cookies? }`. URLs are HTTP(S), at most 8,192 +characters, and cannot contain user information or raw control characters. IP literals and local hostnames +remain supported; a valid scheme does not bypass the host's ordinary URL policy. +There are no raw headers, extractor flags, format selectors, or local paths. + +`MediaFormatCookie` preserves the existing `Resource.Cookie` representation: +`name`, `value`, `domain`, `path`, `secure`, `httpOnly`, `sameSite`, and optional +`expiresAt`. Expiry is **Unix milliseconds**. An absent expiry denotes a session +cookie. A domain without a leading dot is host-only; a leading dot permits +domain matching under normal cookie policy. Defaults match `CookieSchema`. + +The new method bounds fields and rejects malformed names, control characters, +cookie delimiters in values, invalid domains, and invalid paths. Its request +schema rejects cookies whose domain/path/Secure scope does not cover the +requested URL. Hosts MUST also discard expired cookies at invocation time and +apply a standard cookie policy, including domain restrictions. Schema validation +does not establish the origin of a cookie or replace browser-side authorization. + +The extractor MUST preserve domain, host-only, path, Secure, and expiry rules +for **every** HTTP request, redirect, and subrequest. Browser-side SameSite and +partition restrictions must already have been respected during collection. +Do not flatten the cookies into a global `Cookie:` header: one extractor +invocation can contact multiple hosts and paths. Do not inherit browser profiles +or ambient extractor credentials/configuration. If the adapter cannot enforce +these constraints, return unavailable (for example, `credentials-unsupported`) +instead of weakening scope or silently exporting credentials another way. + +Cookie values belong to the request lifetime. They MUST NOT be written to +durable storage, process arguments, logs, results, result-cache keys, or shared +caches. Use request-scoped memory/protected process I/O, cancel pending work on +revocation, and release secrets when the request ends. A credential-bearing +listing MUST NOT be shared with another principal or later request. A host may +cache credential-free results only if it rechecks current feature/site policy +before reuse and bounds cache size and lifetime. + +## Results and limits + +The result is one of: + +```ts +{ available: true, title?: string, durationSec?: number, entries: MediaFormatEntry[] } +{ available: false, reason: string, entries: [] } +``` + +An available result has 1–64 entries with unique keys. Video keys are decimal +heights from `100p` through `4320p`; when present, `height` must agree with the +key. Video entries may include `fps`, `ext`, and `sizeBytes`. The audio choice is +`{ kind: 'audio', key: 'mp3', label: 'MP3' }`, with optional `ext`/`sizeBytes`. +Only offer it when the host can actually extract MP3. Labels are display text, +not selectors. The client may echo a key in `download/submit.meta.qualityLabel`, +but the submit path independently validates the URL, authorization, and choice. + +`sizeBytes` is an optional estimate of the total bytes to download for this +choice, not a promise about the final encoded file size. Omit it when unknown; +do not report only the video leg of a two-stream download or label source-audio +bytes as the final MP3 size. + +Unavailable results require a machine-readable reason and empty entries. Reasons +are non-exhaustive lowercase hyphenated tokens, such as `disabled`, `not-allowed`, +`binary-missing`, `unsupported`, `failed`, or `credentials-unsupported`. Do not +return stderr, credentials, host paths, or stack traces in a reason. Unknown +result fields are stripped so additive future fields do not break old clients. + +`MEDIA_FORMATS_LIMITS` is exported for consumers: + +| Limit | Maximum | +| --- | --- | +| Parsed params, UTF-8 JSON | 64 KiB | +| Parsed result, UTF-8 JSON | 64 KiB | +| Cookies | 256, also subject to the aggregate byte limit | +| Cookie name / value / domain / path | 256 / 4096 / 254 / 2048 characters | +| Entries / label / title | 64 / 128 / 500 characters | + +Senders MUST serialize schema-parsed values and apply the aggregate byte limits +before writing to the connection. These budgets leave room for the JSON-RPC +envelope under the existing MBP1 1 MiB plaintext limit; transport limits remain +mandatory. JSON Schema discovery describes structural bounds but cannot encode +every Zod refinement (UTF-8 budgets, scope matching, key uniqueness). Consumers +must use the runtime schemas or equivalent conformance checks, not JSON Schema +alone. Hosts must bound concurrent extractor work and execution time and observe +the existing cancellation token. Unsupported/empty extractor output is an +unavailable result, never an available empty list. + +## Failures and compatibility + +Feature disabled, excluded site, missing executable, unsupported media, or an +ordinary extraction failure return an unavailable result. Authentication or +permission denial uses the existing `PermissionDenied`/`PairRevoked` behavior; +malformed input uses `InvalidParams`, rate admission uses `RateLimited`, and +cancellation uses `RequestCancelled`. None of these grants permission to retry +against another endpoint or to change pairing. + +`MethodNotFound`/`CapabilityNotSupported` on an otherwise live, authorized +connection permits hiding the picker and falling back to existing UI. Actual +connection loss, timeout/recovery exhaustion, or revocation remains owned by +the connection state machine; do not relabel a lost connection as connected. + +| Client / host | Required behavior | +| --- | --- | +| Old client / new host | Optional capability is unused; old methods work | +| New client / old host, capability absent or false | No formats request; existing UI | +| New client / host advertises support, grants valid | Explicit action may request a listing | +| Support advertised but method missing | Handle method mismatch on the still-live connection | +| Support advertised, grant absent/revoked or document changed | Do not collect/send; invalidate pending work | +| Connection lost or pairing revoked | Existing connection/revocation handling | + +## Consumer acceptance and release order + +Publish the reviewed protocol before changing application dependencies. No +`file:`, `link:`, local module augmentation, or mirrored wire schema may ship. +Consumers must pass these checks before advertising/calling the method: + +- No request with a missing/false capability or absent remote data grant; no + cookie lookup or cookie transmission without a credential grant. +- No automatic page-load/poll request, stale frame request, or request after + endpoint switch, instance change, document navigation, or grant revocation. +- Cookie scope/expiry enforced across redirects; credentials absent from argv, + logs, persistent data, and caches. Test with synthetic secrets. +- Unauthenticated, non-extension, and unary HTTP calls rejected before + extractor work; schema-invalid and oversized payloads rejected too. +- Disabled/missing/unsupported extraction, unavailable results, cancellation, + and new/old peer combinations follow the rules above. +- Existing pairing, submit permissions, and store/site exclusions unchanged. + +Motrix PR #2365 must replace its local schemas, advertise the capability from +the registered handler, preserve cookies as scoped records, remove global cookie +headers/raw-cookie cache keys, and parse the result before returning it. Its +current empty-success case must become unavailable. Normalize extractor metadata +first: filter heights outside 100–4320, cap titles, and omit invalid fps/ext/size +fields. The existing lister accepts heights below 100 even though its submit +parser cannot select those keys. Add MP3 only when both a downloadable audio +source and conversion support exist, not merely because FFmpeg is installed. +Gate this new method on `isReady()` as well as authentication, with a rejection +test before `motrix/initialized`; do not change unrelated methods to do so. +Extension PR #56 must use +the published types, gate requests on explicit actions/support/current grants, +and retain its independent site exclusions and browser-verified frame identity. + +[MIT](../LICENSE) diff --git a/docs/media-formats.zh-CN.md b/docs/media-formats.zh-CN.md new file mode 100644 index 0000000..0fc1caa --- /dev/null +++ b/docs/media-formats.zh-CN.md @@ -0,0 +1,148 @@ +# 媒体格式契约(MDXP 0.9.0) + +`media/formats` 为 Motrix PR #2365 的画质选择器提供视频高度选项,以及可选的 MP3 +提取选项。它不提交任务、不构成下载授权,也不改变配对。协议包提供 schema 与类型化 +RPC 注册;下面的授权和抽取器要求由应用实现。 + +## 协商与传输 + +- 保持 `protocolVersion` 为 `1.0`,保留既有配对和提交行为。 +- 目标只有在注册 lister 且实现本契约后,才能声明 `capabilities.mediaFormats: true`。 + 能力缺失或为 false 时,客户端不得发送此请求,也不得试探调用。 +- 方法只对已认证、已就绪的扩展会话开放。`Tools` 将其标为 `agentFacing: false`, + 不进入 `toAgentToolCatalog()`,也不得通过 unary `POST /mdxp` 暴露。注册标记和 + 调用方自报的 `client.kind` 都不是认证,应使用传输层验证的主体。 +- 能力协商只表示支持情况,不授予读取或披露页面 URL、Cookie 的权限。 + +## 客户端读取与发送前的授权 + +1. 请求必须由用户明确要求查看当前页面或选中嵌入播放器画质的操作发起。加载页面、 + 观察到视频、轮询、重连都不得自动触发披露。 +2. 从浏览器当前的标签页、文档、frame 身份取得目标。任意同源路径不能视为经过验证 + 的 frame URL;画质标签或格式列表不得覆盖既有构建版本、站点排除策略。 +3. 对远程目标,在发送 URL 前检查所选 authority 与已认证 instance 的既有数据授权; + 在读取、发送 Cookie 前另行检查凭据授权。扩展中的对应字段是 + `remoteDataBoundaryAcceptedAt` 和 `allowRequestCredentials`,配对不能替代它们。 +4. 捕获端点代次、已认证实例、文档身份及相关授权,在异步操作后和即将发送前重新验证。 + 授权撤销、端点编辑或切换、文档变化均使操作失效,不得转发或重放到另一个目标。 +5. 只读取适用于该准确文档及其当前 Cookie store/partition 的 Cookie,保留作用域 + 字段;不得读取全部浏览器 Cookie,也不得回退到其他浏览器配置。 +6. 使用 `MediaFormatsParamsSchema` 解析,并发送解析后的值,而不是原始对象。 + 通用连接辅助函数不执行这些由应用负责的检查,也不会自动校验载荷。 + +本地配对也不授权后台读取 Cookie。本地目标同样遵守明确操作与当前文档要求。 + +## 请求与 Cookie 作用域 + +严格请求形状为 `{ url, cookies? }`。URL 仅允许 HTTP(S),最多 8,192 个字符,不能 +包含用户信息或原始控制字符;继续支持 IP 和本地主机名。合法 scheme 不会绕过目标的 URL 策略。 +不提供原始请求头、抽取器参数、格式 selector 或本地路径字段。 + +`MediaFormatCookie` 保留现有 `Resource.Cookie` 表示:`name`、`value`、`domain`、 +`path`、`secure`、`httpOnly`、`sameSite`,以及可选的 `expiresAt`。过期时间是 +**Unix 毫秒**,缺失表示会话 Cookie。无前导点的 domain 为 host-only;有前导点的 +domain 按常规 Cookie 策略匹配域名。默认值与 `CookieSchema` 相同。 + +新方法限制字段大小,并拒绝非法名称、控制字符、值中的 Cookie 分隔符、非法 domain +与 path。请求 schema 拒绝 domain/path/Secure 范围不覆盖目标 URL 的 Cookie。 +目标还必须在实际调用时丢弃过期 Cookie,并执行包含域名限制在内的标准 Cookie +策略。schema 无法证明 Cookie 来源,也不能替代浏览器端授权。 + +抽取器必须在**每个** HTTP 请求、重定向及子请求上保留 domain、host-only、path、 +Secure 和有效期限制。浏览器端 SameSite 与 partition 限制应在读取时已经执行。 +不得把 Cookie 平铺为全局 `Cookie:` 请求头:一次抽取可以访问多个主机和路径。 +不得继承其他浏览器配置或抽取器环境中的凭据/配置。适配器无法满足这些限制时,应 +返回不可用(例如 `credentials-unsupported`),不能扩大作用域或换一种方式静默导出。 + +Cookie 值只属于当前请求的生命周期,不得进入持久存储、进程参数、日志、结果、结果 +缓存键或共享缓存。使用请求级内存/受保护的进程 I/O;撤销授权时取消待执行工作, +请求结束后释放秘密。带凭据的查询不得与其他主体或后续请求共享。无凭据结果可缓存, +但每次复用前仍需检查当前功能、站点策略,并限制缓存容量与寿命。 + +## 结果与上限 + +结果只能是以下两种之一: + +```ts +{ available: true, title?: string, durationSec?: number, entries: MediaFormatEntry[] } +{ available: false, reason: string, entries: [] } +``` + +可用结果包含 1–64 个 key 唯一的选项。视频 key 为 `100p` 到 `4320p` 的十进制高度; +若提供 `height`,必须与 key 一致。视频选项可带 `fps`、`ext` 和 `sizeBytes`。 +音频选项是 `{ kind: 'audio', key: 'mp3', label: 'MP3' }`,可带 `ext`/`sizeBytes`; +目标确实能够提取 MP3 时才能提供它。label 是显示文字,不是 selector。客户端可将 +key 回填为 `download/submit.meta.qualityLabel`,但提交路径仍独立检查 URL、权限和 +选项本身。 + +`sizeBytes` 是该选项需要下载的总字节数的可选估计,不保证最终编码文件的大小。 +未知时省略;不能只报告双流下载中的视频部分,也不能把源音频字节数标成最终 MP3 +文件大小。 + +不可用结果必须有机器可读 reason 和空 entries。reason 是不穷尽的小写连字符词元, +例如 `disabled`、`not-allowed`、`binary-missing`、`unsupported`、`failed` 或 +`credentials-unsupported`;不得放入 stderr、凭据、本地路径或堆栈。未知结果字段 +会被剥离,便于未来新增字段与旧客户端兼容。 + +协议导出 `MEDIA_FORMATS_LIMITS` 供消费者使用: + +| 项目 | 上限 | +| --- | --- | +| 解析后参数的 UTF-8 JSON | 64 KiB | +| 解析后结果的 UTF-8 JSON | 64 KiB | +| Cookie 数量 | 256,同时受总字节数限制 | +| Cookie 名称/值/domain/path | 256/4096/254/2048 个字符 | +| 选项数量/label/title | 64/128/500 个字符 | + +发送方必须序列化 schema 解析后的值,在写入连接前执行总字节数检查。这些上限为 +JSON-RPC 封装预留空间,低于现有 MBP1 的 1 MiB 明文上限;传输层限制仍然有效。 +JSON Schema 只能表达结构限制,无法完整表达 Zod refinement(UTF-8 预算、作用域 +匹配、key 唯一性)。消费者必须使用运行时 schema 或等效一致性检查,不能只依赖 +JSON Schema。目标必须限制并发抽取数量与执行时间,并响应既有取消令牌。抽取器无 +支持或没有选项时,应返回不可用,不能返回可用的空列表。 + +## 失败与兼容 + +功能关闭、站点被排除、缺少可执行程序、不支持媒体或一般抽取失败,都返回不可用 +结果。认证或权限拒绝沿用 `PermissionDenied`/`PairRevoked`;非法输入使用 +`InvalidParams`,限流使用 `RateLimited`,取消使用 `RequestCancelled`。这些结果 +都不授权切换端点重试或修改配对。 + +在仍然有效、已授权的连接上收到 `MethodNotFound`/`CapabilityNotSupported` 时, +可以隐藏选择器并保留既有 UI。真正的连接丢失、超时/恢复耗尽、授权撤销,仍由连接 +状态机处理,不能把断线改标为已连接。 + +| 客户端/目标组合 | 必需行为 | +| --- | --- | +| 旧客户端/新目标 | 不使用可选能力,旧方法照常工作 | +| 新客户端/旧目标,能力缺失或为 false | 不发送格式查询,保留旧 UI | +| 新客户端/目标声明支持且授权有效 | 明确操作可发起查询 | +| 声明支持但没有注册方法 | 在仍有效连接上处理方法不匹配 | +| 声明支持但授权缺失/撤销或文档变化 | 不读取、不发送,使待执行工作失效 | +| 连接丢失或配对撤销 | 沿用连接/撤销处理 | + +## 消费者验收与发布顺序 + +先发布审查通过的协议,再更新应用依赖;不能发布 `file:`、`link:`、本地 module +augmentation 或镜像 wire schema。声明/调用能力前,消费者必须验证: + +- 能力缺失/false 或远程数据授权缺失时不发送请求;无凭据授权时不读取、发送 Cookie。 +- 页面加载/轮询不自动查询;拒绝过期 frame,以及端点切换、实例变化、页面导航、 + 授权撤销后的请求。 +- 重定向中执行 Cookie 作用域/有效期;argv、日志、持久化数据和缓存不含凭据。 + 使用合成秘密测试。 +- 未认证、非扩展、unary HTTP 调用均在抽取前被拒绝;非法或超大载荷也被拒绝。 +- 功能关闭、程序缺失、不支持、不可用结果、取消和新旧版本组合遵守上面的规则。 +- 既有配对、提交授权和构建版本/站点排除策略保持不变。 + +Motrix PR #2365 应替换本地 schema,按注册的 handler 声明能力,以带作用域的记录 +传递 Cookie,移除全局 Cookie 头和原文 Cookie 缓存键,并在返回前解析结果;目前 +可用空列表的情况应改为不可用。先规范化抽取器元数据:过滤 100–4320 之外的高度, +限制标题长度,省略不合法的 fps/ext/size。旧 lister 会接受低于 100 的高度,而 +既有提交解析器本来就不能选择这些 key。只有存在可下载音轨且支持转换时才添加 MP3, +不能只检查是否安装 FFmpeg。新方法除了认证,还必须检查 `isReady()`,并测试尚未 +收到 `motrix/initialized` 时的拒绝;无需顺带修改其他方法。 +扩展 PR #56 应使用发布类型,并按明确操作、能力、 +当前授权控制查询,保留独立的站点排除与浏览器验证的 frame 身份。 + +[MIT](../LICENSE) diff --git a/package.json b/package.json index 837a457..10b7b06 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@motrix/mdxp", - "version": "0.8.1", + "version": "0.9.0", "description": "Motrix Download eXchange Protocol — JSON-RPC 2.0 wire types and connection helpers", "license": "MIT", "author": "Motrix", @@ -47,7 +47,8 @@ "src", "!src/__tests__", "README.md", - "README.zh-CN.md" + "README.zh-CN.md", + "docs/media-formats*.md" ], "packageManager": "pnpm@11.22.0", "publishConfig": { diff --git a/src/__tests__/connection.test.ts b/src/__tests__/connection.test.ts index aa1482d..21f2c80 100644 --- a/src/__tests__/connection.test.ts +++ b/src/__tests__/connection.test.ts @@ -4,7 +4,14 @@ import 'vscode-jsonrpc/node' import { describe, expect, it } from 'vitest' import type { Message, MessageReader, MessageWriter } from 'vscode-jsonrpc' import { createMdxpConnection } from '../connection.js' -import { ErrorCodes, ResponseError } from '../index.js' +import { + DownloadSubmitParamsSchema, + ErrorCodes, + MediaFormatsParamsSchema, + MediaFormatsResultSchema, + Methods, + ResponseError, +} from '../index.js' // In-memory message pipe for testing. class InMemoryReader implements MessageReader { @@ -64,6 +71,79 @@ function makePair(): { } describe('createMdxpConnection', () => { + it('round-trips scoped format requests and a picker choice for download/submit', async () => { + const { aToB, bToA } = makePair() + const client = createMdxpConnection(bToA.reader, aToB.writer) + const server = createMdxpConnection(aToB.reader, bToA.writer) + const cookies = [ + { + name: 'member', + value: 'fixture-only', + domain: 'media.example', + path: '/watch', + secure: true, + httpOnly: true, + sameSite: 'lax' as const, + expiresAt: 1_900_000_000_000, + }, + ] + let invocations = 0 + // Runtime validation remains the receiving application's responsibility. + server.onRequest(Methods.MediaFormats, (params) => { + const parsed = MediaFormatsParamsSchema.safeParse(params) + if (!parsed.success) + throw new ResponseError( + ErrorCodes.InvalidParams, + 'Invalid media formats request' + ) + invocations += 1 + expect(parsed.data.cookies).toEqual(cookies) + return MediaFormatsResultSchema.parse({ + available: true, + entries: [ + { kind: 'video', key: '1080p', label: '1080p', height: 1080 }, + { kind: 'audio', key: 'mp3', label: 'MP3' }, + ], + }) + }) + client.listen() + server.listen() + try { + const result = await client.sendRequest(Methods.MediaFormats, { + url: 'https://media.example/watch/1', + cookies, + }) + expect(result.available).toBe(true) + const key = result.entries[0]!.key + const submitted = DownloadSubmitParamsSchema.parse({ + source: { + pageUrl: 'https://media.example/watch/1', + pageTitle: 'Fixture', + detectedAt: 1, + }, + selection: { + kind: 'direct', + primary: { + url: 'https://media.example/watch/1', + cookies, + headers: {}, + }, + }, + meta: { suggestedFilename: 'fixture.mp4', qualityLabel: key }, + }) + expect(submitted.meta.qualityLabel).toBe('1080p') + await expect( + client.sendRequest(Methods.MediaFormats, { + url: 'file:///private/fixture', + cookies, + }) + ).rejects.toMatchObject({ code: ErrorCodes.InvalidParams }) + expect(invocations).toBe(1) + } finally { + client.dispose() + server.dispose() + } + }) it('preserves codes and data from the public ResponseError constructor', async () => { const { aToB, bToA } = makePair() const a = createMdxpConnection(bToA.reader, aToB.writer) diff --git a/src/__tests__/media-formats.test.ts b/src/__tests__/media-formats.test.ts new file mode 100644 index 0000000..aa948a7 --- /dev/null +++ b/src/__tests__/media-formats.test.ts @@ -0,0 +1,395 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { + CookieSchema, + InitializeResultSchema, + MEDIA_FORMATS_LIMITS, + MediaFormatCookieSchema, + MediaFormatEntrySchema, + MediaFormatsParamsSchema, + MediaFormatsResultSchema, + Methods, + Tools, + toAgentToolCatalog, +} from '../index.js' + +// Same shape and units as the extension's capturePageCookies / mapCookies. +const cookie = { + name: 'session', + value: 'test-only', + domain: '.media.example', + path: '/watch', + secure: true, + httpOnly: true, + sameSite: 'lax' as const, + expiresAt: 1_900_000_000_123, +} +const url = 'https://www.media.example/watch/video?id=123' +const video = { + key: '1080p', + kind: 'video' as const, + label: '1080p', + height: 1080, + fps: 60, + ext: 'mp4', + sizeBytes: 123456, +} +const mp3 = { key: 'mp3', kind: 'audio' as const, label: 'MP3' } + +describe('media formats request boundary', () => { + it('preserves browser Cookie metadata and millisecond expiry', () => { + 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) + }) + + it.each([ + 'https://media.example/watch', + 'http://127.0.0.1/video', + 'http://nas/video', + 'http://[::1]/video', + ])('retains existing HTTP URL support: %s', (url) => { + expect(MediaFormatsParamsSchema.parse({ url })).toEqual({ url }) + }) + + it.each([ + 'file:///tmp/video', + 'data:text/plain,video', + 'javascript:alert(1)', + 'ftp://nas/video', + 'https://user:secret@media.example/watch', + 'https://media.example/watch/\nx', + 'https://media.example/watch/\tx', + 'not a URL', + '', + ])('rejects an invalid media URL: %s', (url) => { + expect(MediaFormatsParamsSchema.safeParse({ url }).success).toBe(false) + }) + + it('rejects a raw selector and the old name/value-only cookie draft', () => { + expect( + MediaFormatsParamsSchema.safeParse({ url, formatSelector: 'bv*+ba' }) + .success + ).toBe(false) + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ name: 'session', value: 'test-only' }], + }).success + ).toBe(false) + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, storeId: 'browser-only' }], + }).success + ).toBe(false) + }) + + it.each([ + { name: '' }, + { name: 'bad=name' }, + { name: 'bad name' }, + { value: 'x\r\nHeader: injected' }, + { value: 'a;b=c' }, + { value: 'x\0y' }, + { value: 'x\ty' }, + { domain: '' }, + { domain: '..media.example' }, + { domain: 'https://media.example' }, + { domain: 'media.example:80' }, + { domain: 'media.example/path' }, + { path: 'watch' }, + { path: '/watch\tother' }, + { expiresAt: -1 }, + { expiresAt: Number.POSITIVE_INFINITY }, + ])('rejects malformed cookie fields: %j', (patch) => { + expect( + MediaFormatCookieSchema.safeParse({ ...cookie, ...patch }).success + ).toBe(false) + }) + + it.each([ + { domain: '.other.example' }, + { domain: 'media.example' }, // Host-only does not include www. + { domain: '.notmedia.example' }, + { path: '/account' }, + { path: '/wat' }, // Prefix alone is not a cookie path match. + ])('rejects a cookie not applicable to the requested URL: %j', (patch) => { + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, ...patch }], + }).success + ).toBe(false) + }) + + it('accepts host-only/IP cookies and enforces Secure and path boundaries', () => { + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, domain: 'www.media.example' }], + }).success + ).toBe(true) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'http://www.media.example/watch/video', + cookies: [cookie], + }).success + ).toBe(false) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://www.media.example/watcher', + cookies: [cookie], + }).success + ).toBe(false) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://www.media.example/watch', + cookies: [cookie], + }).success + ).toBe(true) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'http://127.0.0.1/video', + cookies: [{ name: 'local', value: '', domain: '127.0.0.1' }], + }).success + ).toBe(true) + }) + + it('bounds the whole parsed request rather than each cookie in isolation', () => { + const oversized = { + url, + cookies: Array.from({ length: 256 }, (_, index) => ({ + ...cookie, + name: `c${index}`, + value: 'v'.repeat(4096), + })), + } + expect(Buffer.byteLength(JSON.stringify(oversized))).toBeGreaterThan( + 1024 * 1024 + ) + expect(MediaFormatsParamsSchema.safeParse(oversized).success).toBe(false) + const accepted = MediaFormatsParamsSchema.parse({ + url, + cookies: Array.from({ length: 256 }, (_, index) => ({ + ...cookie, + name: `c${index}`, + })), + }) + expect(Buffer.byteLength(JSON.stringify(accepted))).toBeLessThanOrEqual( + MEDIA_FORMATS_LIMITS.paramsBytes + ) + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: Array(257).fill(cookie), + }).success + ).toBe(false) + }) + + it('accepts the exact aggregate byte limit and rejects the next byte', () => { + const request = { + url, + cookies: Array.from({ length: 20 }, (_, index) => ({ + ...cookie, + name: `c${index}`, + value: '', + })), + } + let remaining = + MEDIA_FORMATS_LIMITS.paramsBytes - + Buffer.byteLength(JSON.stringify(MediaFormatsParamsSchema.parse(request))) + for (const item of request.cookies) { + const length = Math.min( + remaining, + MEDIA_FORMATS_LIMITS.cookieValueCharacters + ) + item.value = 'x'.repeat(length) + remaining -= length + } + expect(remaining).toBe(0) + expect( + Buffer.byteLength(JSON.stringify(MediaFormatsParamsSchema.parse(request))) + ).toBe(MEDIA_FORMATS_LIMITS.paramsBytes) + request.cookies.at(-1)!.value += 'x' + expect(MediaFormatsParamsSchema.safeParse(request).success).toBe(false) + }) + + it('counts UTF-8 bytes rather than JavaScript string length', () => { + const request = { + url, + cookies: Array.from({ length: 8 }, (_, index) => ({ + ...cookie, + name: `c${index}`, + value: '界'.repeat(3000), + })), + } + expect(JSON.stringify(request).length).toBeLessThan( + MEDIA_FORMATS_LIMITS.paramsBytes + ) + expect(Buffer.byteLength(JSON.stringify(request))).toBeGreaterThan( + MEDIA_FORMATS_LIMITS.paramsBytes + ) + expect(MediaFormatsParamsSchema.safeParse(request).success).toBe(false) + }) + + it('returns safe validation messages without echoing credentials', () => { + const result = MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, value: 'SECRET_DO_NOT_ECHO\r\n' }], + }) + expect(result.success).toBe(false) + if (!result.success) + expect(result.error.message).not.toContain('SECRET_DO_NOT_ECHO') + }) +}) + +describe('Motrix quality-picker result contract', () => { + it('accepts the desktop lister projection, including MP3 extraction', () => { + const entries = [4320, 2160, 1440, 1080, 720, 480, 360, 240, 144].map( + (height) => ({ + key: `${height}p`, + kind: 'video', + label: `${height}p`, + height, + ext: 'mp4', + }) + ) + const result = MediaFormatsResultSchema.parse({ + available: true, + title: 'Fixture', + durationSec: 120, + entries: [...entries, mp3], + }) + expect(result.entries).toHaveLength(10) + }) + + it.each([ + 'disabled', + 'not-allowed', + 'binary-missing', + 'unsupported', + 'failed', + 'vendor-new-reason', + ])('accepts an extensible unavailable reason: %s', (reason) => { + expect( + MediaFormatsResultSchema.parse({ available: false, reason, entries: [] }) + ).toEqual({ available: false, reason, entries: [] }) + }) + + it('rejects contradictory availability states', () => { + for (const result of [ + { available: false, entries: [] }, + { available: false, reason: 'disabled', entries: [video] }, + { available: true, entries: [] }, + { available: false, reason: '/private/extractor/error.log', entries: [] }, + ]) + expect(MediaFormatsResultSchema.safeParse(result).success).toBe(false) + }) + + it.each([ + { ...video, key: 'bv*+ba/b' }, + { ...video, key: 'mp3' }, + { ...video, height: 720 }, + { ...video, key: '9999p', height: 9999 }, + { ...mp3, key: '1080p' }, + { ...video, fps: Number.POSITIVE_INFINITY }, + { ...video, sizeBytes: 0 }, + ])('rejects an invalid quality option: %j', (entry) => { + expect(MediaFormatEntrySchema.safeParse(entry).success).toBe(false) + }) + + it('bounds options and rejects ambiguous repeated keys', () => { + expect( + MediaFormatsResultSchema.safeParse({ + available: true, + entries: [video, video], + }).success + ).toBe(false) + const entries = Array.from({ length: 65 }, (_, index) => ({ + ...video, + key: `${100 + index}p`, + height: 100 + index, + })) + expect( + MediaFormatsResultSchema.safeParse({ available: true, entries }).success + ).toBe(false) + }) + + it('strips forward-compatible result fields before serialization', () => { + expect( + MediaFormatsResultSchema.parse({ + available: true, + title: 'Fixture', + entries: [{ ...video, futureField: 'ignored' }], + futureField: 'ignored', + }) + ).toEqual({ available: true, title: 'Fixture', entries: [video] }) + expect( + MediaFormatsResultSchema.parse({ + available: false, + reason: 'failed', + entries: [], + stderr: 'not part of contract', + }) + ).toEqual({ available: false, reason: 'failed', entries: [] }) + }) + + it('keeps the maximum supported listing below the message budget', () => { + const entries = Array.from({ length: 64 }, (_, index) => ({ + key: `${100 + index}p`, + kind: 'video', + label: '界'.repeat(128), + height: 100 + index, + fps: 1000, + ext: 'x'.repeat(16), + sizeBytes: Number.MAX_SAFE_INTEGER, + })) + const result = MediaFormatsResultSchema.parse({ + available: true, + title: '界'.repeat(500), + durationSec: Number.MAX_VALUE, + entries, + }) + expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual( + MEDIA_FORMATS_LIMITS.resultBytes + ) + }) +}) + +describe('media formats registration and negotiation', () => { + it('publishes the shared schema without exposing an agent tool', () => { + expect(Methods.MediaFormats).toBe('media/formats') + expect(Tools[Methods.MediaFormats]).toMatchObject({ + agentFacing: false, + paramsSchema: MediaFormatsParamsSchema, + resultSchema: MediaFormatsResultSchema, + }) + expect( + toAgentToolCatalog().some((tool) => tool.name === Methods.MediaFormats) + ).toBe(false) + expect(() => z.toJSONSchema(MediaFormatsParamsSchema)).not.toThrow() + expect(() => z.toJSONSchema(MediaFormatsResultSchema)).not.toThrow() + }) + + it.each([undefined, false, true])( + 'retains optional capability value %s', + (mediaFormats) => { + const hello = InitializeResultSchema.parse({ + protocolVersion: '1.0', + server: { name: 'motrix', version: '2', runtime: 'electron' }, + capabilities: { + ffmpegAvailable: true, + selectionKinds: ['direct'], + progress: true, + cancellation: true, + ...(mediaFormats === undefined ? {} : { mediaFormats }), + }, + serverAdapters: [], + }) + expect(hello.capabilities.mediaFormats).toBe(mediaFormats) + expect(hello.protocolVersion).toBe('1.0') + } + ) +}) diff --git a/src/connection.ts b/src/connection.ts index 37c8f84..93cadb8 100644 --- a/src/connection.ts +++ b/src/connection.ts @@ -19,6 +19,8 @@ import type { EngineStatusResult, InitializeParams, InitializeResult, + MediaFormatsParams, + MediaFormatsResult, PairRevokedParams, StatsGetParams, StatsResult, @@ -55,6 +57,7 @@ export interface MdxpRequestMap { 'url/probe': [UrlProbeParams, UrlProbeResult] 'url/resolve': [UrlResolveParams, UrlResolveResult] 'system/ping': [SystemPingParams, SystemPingResult] + 'media/formats': [MediaFormatsParams, MediaFormatsResult] // v1 control-plane (Spec 2) 'download/add': [DownloadAddParams, DownloadAddResult] 'task/list': [TaskListParams, TaskListResult] diff --git a/src/methods.ts b/src/methods.ts index 521e575..e0f5fd0 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -7,6 +7,7 @@ export const Methods = Object.freeze({ UrlProbe: 'url/probe', UrlResolve: 'url/resolve', SystemPing: 'system/ping', + MediaFormats: 'media/formats', // v1 control-plane (Spec 2) DownloadAdd: 'download/add', TaskList: 'task/list', diff --git a/src/schemas/index.ts b/src/schemas/index.ts index 70e0d9a..681d6f6 100644 --- a/src/schemas/index.ts +++ b/src/schemas/index.ts @@ -4,6 +4,7 @@ export * from './download-directories.js' export * from './engine.js' export * from './events.js' export * from './initialize.js' +export * from './media-formats.js' export * from './resource.js' export * from './selection.js' export * from './stats.js' diff --git a/src/schemas/initialize.ts b/src/schemas/initialize.ts index 9a2bba0..74ce3be 100644 --- a/src/schemas/initialize.ts +++ b/src/schemas/initialize.ts @@ -74,6 +74,8 @@ const ServerCapabilitiesSchema = z.object({ taskReveal: z.boolean().optional().default(false), /** Enables download/directories AND download/submit.saveDir; absent is false. */ downloadDirectories: z.boolean().optional(), + /** Registered, authorized extension format listing; absent/false means no call. */ + mediaFormats: z.boolean().optional(), }) export const InitializeResultSchema = z.object({ diff --git a/src/schemas/media-formats.ts b/src/schemas/media-formats.ts new file mode 100644 index 0000000..9121fbb --- /dev/null +++ b/src/schemas/media-formats.ts @@ -0,0 +1,246 @@ +import { z } from 'zod' +import { CookieSchema, ResourceSchema } from './resource.js' + +/** Bounds apply to schema-parsed values serialized as UTF-8 JSON. */ +export const MEDIA_FORMATS_LIMITS = Object.freeze({ + urlCharacters: 8192, + cookies: 256, + cookieNameCharacters: 256, + cookieValueCharacters: 4096, + cookieDomainCharacters: 254, + cookiePathCharacters: 2048, + paramsBytes: 64 * 1024, + resultBytes: 64 * 1024, + entries: 64, + maxVideoHeight: 4320, +} as const) + +// Cookie names are HTTP tokens. Values must not introduce another cookie or +// a header line; preserve the value instead of silently trimming/rewriting it. +const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ +// biome-ignore lint/suspicious/noControlCharactersInRegex: reject control characters at the wire boundary +const UNSAFE_COOKIE_VALUE = /[\u0000-\u001f\u007f;]/ +// biome-ignore lint/suspicious/noControlCharactersInRegex: Netscape jars and HTTP headers cannot carry these controls +const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/ + +function validCookieDomain(value: string): boolean { + const host = value.startsWith('.') ? value.slice(1) : value + if ( + !host || + host.startsWith('.') || + host.endsWith('.') || + /[\s/\\@?#;]/.test(host) + ) + return false + try { + const url = new URL(`http://${host}`) + return !url.port && url.hostname.toLowerCase() === host.toLowerCase() + } catch { + return false + } +} + +/** Existing Resource cookie metadata, with bounded, header-safe fields. */ +export const MediaFormatCookieSchema = CookieSchema.extend({ + name: z + .string() + .min(1) + .max(MEDIA_FORMATS_LIMITS.cookieNameCharacters) + .regex(COOKIE_NAME), + value: z + .string() + .max(MEDIA_FORMATS_LIMITS.cookieValueCharacters) + .refine( + (value) => !UNSAFE_COOKIE_VALUE.test(value), + 'Invalid cookie value' + ), + domain: z + .string() + .min(1) + .max(MEDIA_FORMATS_LIMITS.cookieDomainCharacters) + .refine(validCookieDomain, 'Invalid cookie domain'), + path: z + .string() + .min(1) + .max(MEDIA_FORMATS_LIMITS.cookiePathCharacters) + .refine( + (value) => value.startsWith('/') && !CONTROL_CHARACTERS.test(value), + 'Invalid cookie path' + ) + .default('/'), + /** Unix milliseconds, matching Resource.Cookie and browser cookie capture. */ + expiresAt: z.number().int().nonnegative().optional(), +}).strict() + +function coversUrl( + cookie: z.infer, + url: URL +): boolean { + const domain = cookie.domain.toLowerCase() + const hostname = url.hostname.toLowerCase() + const domainMatches = domain.startsWith('.') + ? hostname === domain.slice(1) || hostname.endsWith(domain) + : hostname === domain + const pathMatches = + url.pathname === cookie.path || + (url.pathname.startsWith(cookie.path) && + (cookie.path.endsWith('/') || url.pathname[cookie.path.length] === '/')) + return ( + domainMatches && + pathMatches && + (!cookie.secure || url.protocol === 'https:') + ) +} + +function checkJsonBudget( + value: unknown, + maximum: number, + ctx: z.RefinementCtx +) { + if (new TextEncoder().encode(JSON.stringify(value)).byteLength > maximum) { + ctx.addIssue({ + code: 'custom', + message: 'Media formats payload exceeds its byte limit', + }) + } +} + +/** Validation grants no access: the client must check its current data grants. */ +export const MediaFormatsParamsSchema = z + .object({ + url: z + .string() + .max(MEDIA_FORMATS_LIMITS.urlCharacters) + .refine( + (value) => !CONTROL_CHARACTERS.test(value), + 'Media URLs must not contain control characters' + ) + .pipe(ResourceSchema.shape.url.max(MEDIA_FORMATS_LIMITS.urlCharacters)) + .refine((value) => { + try { + const url = new URL(value) + return !url.username && !url.password + } catch { + return false + } + }, 'Media URLs must not contain user information'), + cookies: z + .array(MediaFormatCookieSchema) + .max(MEDIA_FORMATS_LIMITS.cookies) + .optional(), + }) + .strict() + .superRefine((value, ctx) => { + // Parsing failures are already reported by the URL schema. + let url: URL + try { + url = new URL(value.url) + } catch { + return + } + for (const [index, cookie] of (value.cookies ?? []).entries()) { + if (!coversUrl(cookie, url)) { + ctx.addIssue({ + code: 'custom', + path: ['cookies', index], + message: 'Cookie scope does not cover the requested URL', + }) + } + } + checkJsonBudget(value, MEDIA_FORMATS_LIMITS.paramsBytes, ctx) + }) + +const VideoQualityKeySchema = z + .string() + .regex(/^[1-9]\d{2,3}p$/) + .refine( + (value) => Number.parseInt(value, 10) <= MEDIA_FORMATS_LIMITS.maxVideoHeight + ) + +const entryFields = { + label: z.string().min(1).max(128), + ext: z + .string() + .regex(/^[a-zA-Z0-9]{1,16}$/) + .optional(), + sizeBytes: z.number().int().positive().optional(), +} + +/** Tokens are picker choices, never raw extractor format selectors. */ +export const MediaFormatEntrySchema = z + .discriminatedUnion('kind', [ + z.object({ + ...entryFields, + kind: z.literal('video'), + key: VideoQualityKeySchema, + height: z + .number() + .int() + .min(100) + .max(MEDIA_FORMATS_LIMITS.maxVideoHeight) + .optional(), + fps: z.number().positive().max(1000).optional(), + }), + z.object({ + ...entryFields, + kind: z.literal('audio'), + key: z.literal('mp3'), + }), + ]) + .superRefine((value, ctx) => { + if ( + value.kind === 'video' && + value.height !== undefined && + value.key !== `${value.height}p` + ) { + ctx.addIssue({ + code: 'custom', + path: ['height'], + message: 'Height must match the quality key', + }) + } + }) + +/** Reasons are extensible machine tokens, never extractor error text. */ +export const MediaFormatsUnavailableReasonSchema = z + .string() + .min(1) + .max(64) + .regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/) + +/** Unknown result fields are stripped for forward compatibility. */ +export const MediaFormatsResultSchema = z + .discriminatedUnion('available', [ + z.object({ + available: z.literal(true), + title: z.string().max(500).optional(), + durationSec: z.number().nonnegative().optional(), + entries: z + .array(MediaFormatEntrySchema) + .min(1) + .max(MEDIA_FORMATS_LIMITS.entries), + }), + z.object({ + available: z.literal(false), + reason: MediaFormatsUnavailableReasonSchema, + entries: z.array(MediaFormatEntrySchema).length(0), + }), + ]) + .superRefine((value, ctx) => { + if ( + new Set(value.entries.map((entry) => entry.key)).size !== + value.entries.length + ) { + ctx.addIssue({ + code: 'custom', + path: ['entries'], + message: 'Quality keys must be unique', + }) + } + checkJsonBudget(value, MEDIA_FORMATS_LIMITS.resultBytes, ctx) + }) + +export type MediaFormatCookie = z.infer +export type MediaFormatEntry = z.infer +export type MediaFormatsParams = z.infer +export type MediaFormatsResult = z.infer diff --git a/src/tools.ts b/src/tools.ts index 3e18bb0..82efddb 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -22,6 +22,10 @@ import { InitializeParamsSchema, InitializeResultSchema, } from './schemas/initialize.js' +import { + MediaFormatsParamsSchema, + MediaFormatsResultSchema, +} from './schemas/media-formats.js' import { StatsGetParamsSchema, StatsResultSchema } from './schemas/stats.js' import { SystemPingParamsSchema, @@ -105,6 +109,14 @@ export const Tools: Readonly> = { resultSchema: DownloadCancelResultSchema, agentFacing: false, }, + [Methods.MediaFormats]: { + method: Methods.MediaFormats, + description: + 'List media quality options for an explicitly requested page. Requires a paired extension and client-side data-sharing authorization.', + paramsSchema: MediaFormatsParamsSchema, + resultSchema: MediaFormatsResultSchema, + agentFacing: false, + }, [Methods.DownloadAdd]: { method: Methods.DownloadAdd, description: diff --git a/src/types.ts b/src/types.ts index b914b09..c2eac41 100644 --- a/src/types.ts +++ b/src/types.ts @@ -29,6 +29,12 @@ export type { InitializeParams, InitializeResult, } from './schemas/initialize.js' +export type { + MediaFormatCookie, + MediaFormatEntry, + MediaFormatsParams, + MediaFormatsResult, +} from './schemas/media-formats.js' export type { Cookie, Resource, From 0347079ec46b97bafcc8e17c2cbba9ca3ab0db3e Mon Sep 17 00:00:00 2001 From: Nuomi Date: Sun, 18 Oct 2026 21:47:42 +0800 Subject: [PATCH 2/2] fix(protocol): preserve trailing-dot cookie domains --- docs/media-formats.md | 3 ++ docs/media-formats.zh-CN.md | 3 ++ src/__tests__/media-formats.test.ts | 62 +++++++++++++++++++++++++++++ src/schemas/media-formats.ts | 4 +- 4 files changed, 71 insertions(+), 1 deletion(-) diff --git a/docs/media-formats.md b/docs/media-formats.md index 435f9b5..b6202b2 100644 --- a/docs/media-formats.md +++ b/docs/media-formats.md @@ -58,6 +58,9 @@ There are no raw headers, extractor flags, format selectors, or local paths. `expiresAt`. Expiry is **Unix milliseconds**. An absent expiry denotes a session cookie. A domain without a leading dot is host-only; a leading dot permits domain matching under normal cookie policy. Defaults match `CookieSchema`. +DNS cookie domains may retain one trailing dot. Preserve it during validation +and matching: `media.example.` and `media.example` are separate cookie scopes. +Reject multiple trailing dots; do not remove a dot to make a cookie match. The new method bounds fields and rejects malformed names, control characters, cookie delimiters in values, invalid domains, and invalid paths. Its request diff --git a/docs/media-formats.zh-CN.md b/docs/media-formats.zh-CN.md index 0fc1caa..754e75d 100644 --- a/docs/media-formats.zh-CN.md +++ b/docs/media-formats.zh-CN.md @@ -42,6 +42,9 @@ RPC 注册;下面的授权和抽取器要求由应用实现。 `path`、`secure`、`httpOnly`、`sameSite`,以及可选的 `expiresAt`。过期时间是 **Unix 毫秒**,缺失表示会话 Cookie。无前导点的 domain 为 host-only;有前导点的 domain 按常规 Cookie 策略匹配域名。默认值与 `CookieSchema` 相同。 +DNS Cookie 域允许保留一个尾点,校验和匹配时不得删除:`media.example.` 与 +`media.example` 是两个独立的 Cookie 作用域。拒绝多个尾点,不能删除尾点来让 Cookie +匹配另一个域。 新方法限制字段大小,并拒绝非法名称、控制字符、值中的 Cookie 分隔符、非法 domain 与 path。请求 schema 拒绝 domain/path/Secure 范围不覆盖目标 URL 的 Cookie。 diff --git a/src/__tests__/media-formats.test.ts b/src/__tests__/media-formats.test.ts index aa948a7..3648fcb 100644 --- a/src/__tests__/media-formats.test.ts +++ b/src/__tests__/media-formats.test.ts @@ -157,6 +157,68 @@ describe('media formats request boundary', () => { ).toBe(true) }) + it.each([ + ['www.media.example.', 'https://www.media.example./watch'], + ['WWW.MEDIA.EXAMPLE.', 'https://www.media.example./watch'], + ['.media.example.', 'https://media.example./watch'], + ['.media.example.', 'https://www.media.example./watch'], + ['.media.example.', 'https://cdn.www.media.example./watch/video'], + ])('preserves a trailing-dot cookie domain %s for %s', (domain, url) => { + const scoped = { ...cookie, domain } + 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) + }) + + it.each([ + ['www.media.example', 'https://www.media.example./watch'], + ['www.media.example.', 'https://www.media.example/watch'], + ['.media.example', 'https://media.example./watch'], + ['.media.example.', 'https://media.example/watch'], + ['.media.example', 'https://www.media.example./watch'], + ['.media.example.', 'https://www.media.example/watch'], + ['media.example.', 'https://www.media.example./watch'], + ['.media.example.', 'https://notmedia.example./watch'], + ['.media.example.', 'https://media.example.attacker.test./watch'], + ['.media.example.', 'https://www.media.example../watch'], + ])('isolates trailing-dot cookie scope %s from %s', (domain, url) => { + expect( + MediaFormatCookieSchema.safeParse({ ...cookie, domain }).success + ).toBe(true) + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, domain }], + }).success + ).toBe(false) + }) + + it.each(['media.example..', '.media.example..', 'www.media.example...', '.'])( + 'rejects a malformed trailing-dot cookie domain %s', + (domain) => { + expect( + MediaFormatCookieSchema.safeParse({ ...cookie, domain }).success + ).toBe(false) + } + ) + + it.each([ + 'http://www.media.example./watch', + 'https://www.media.example./watcher', + 'https://www.media.example./account', + ])( + 'retains Secure and path boundaries for trailing-dot cookies at %s', + (url) => { + expect( + MediaFormatsParamsSchema.safeParse({ + url, + cookies: [{ ...cookie, domain: '.media.example.' }], + }).success + ).toBe(false) + } + ) + it('bounds the whole parsed request rather than each cookie in isolation', () => { const oversized = { url, diff --git a/src/schemas/media-formats.ts b/src/schemas/media-formats.ts index 9121fbb..36b43bc 100644 --- a/src/schemas/media-formats.ts +++ b/src/schemas/media-formats.ts @@ -28,12 +28,14 @@ function validCookieDomain(value: string): boolean { if ( !host || host.startsWith('.') || - host.endsWith('.') || + host.endsWith('..') || /[\s/\\@?#;]/.test(host) ) return false try { const url = new URL(`http://${host}`) + // Preserve a single DNS root dot: browsers isolate dotted and undotted + // cookie domains. Never strip it before the exact/suffix scope checks. return !url.port && url.hostname.toLowerCase() === host.toLowerCase() } catch { return false