From 71b9fcb0ec55c7e259d46e8d3d27f3fe47dadee1 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Khalid <172179217+zkaeshjm@users.noreply.github.com> Date: Sun, 18 Oct 2026 10:08:01 +0500 Subject: [PATCH] feat(protocol): add media/formats for mdxp 0.9.0 Adds the media/formats method: a client asks the host which downloadable video/audio qualities a page offers, so a browser-extension quality picker can show real options before the user submits. - MediaFormatsParamsSchema: strict { url, cookies? }; the host fetches the URL itself, so it is restricted to http(s) and the cookie list is bounded to 256 { name, value } pairs. - MediaFormatsResultSchema: non-strict { available, reason?, title?, durationSec?, entries[] } where an entry key is the quality token echoed back as download/submit.meta.qualityLabel - never a raw extractor selector. An unproducible listing is a successful available:false with a machine-readable reason, not a protocol error. - Registered in Methods/Tools as a non-agent-facing client to server method (extension WS only; not exposed on unary HTTP), and gated on the new capabilities.mediaFormats server flag. - Exports HttpUrlSchema from resource.ts so every method that makes the host fetch a caller-supplied URL shares one http(s)-only policy. - README (EN + zh-CN): methods table row, usage example, and the data-sharing/transport-exposure contract. --- README.md | 34 ++++++ README.zh-CN.md | 30 +++++ docs/media-formats.md | 121 +++++++++++++++++++ docs/media-formats.zh-CN.md | 102 ++++++++++++++++ package.json | 5 +- src/__tests__/media-formats.test.ts | 179 ++++++++++++++++++++++++++++ src/connection.ts | 4 + src/methods.ts | 2 + src/schemas/index.ts | 1 + src/schemas/initialize.ts | 6 + src/schemas/media-formats.ts | 68 +++++++++++ src/schemas/resource.ts | 6 +- src/tools.ts | 12 ++ src/types.ts | 6 + 14 files changed, 572 insertions(+), 4 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..e6f2290 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,28 @@ 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 a page's media formats (client → server) + +```ts +// Only after the host advertised mediaFormats support in the handshake. +if (hello.capabilities.mediaFormats ?? false) { + const listing = await conn.sendRequest('media/formats', { + url: 'https://www.youtube.com/watch?v=…', + cookies: [{ name: 'SID', value: '…' }], + }) + + for (const option of listing.entries) { + // option.key ('1080p' | '1440p' | … | 'mp3') is echoed back verbatim as + // download/submit.meta.qualityLabel when the user picks it. + console.log(option.label, option.kind, option.sizeBytes) + } +} +``` + +An extractor that cannot produce a listing answers `available: false` with a +`reason` instead of a protocol error, so a client always gets a shape it can +render. + ### Resolve a page (server → client) The desktop app asks a client whether it can handle a page (`url/probe`), then @@ -370,6 +392,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 the media qualities a page offers (extension quality picker). | | `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. | @@ -474,6 +497,17 @@ 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. +## Media formats (since 0.9.0) + +The optional `mediaFormats` capability adds `media/formats`: a client asks the +host which downloadable video/audio qualities a page offers, so an extension +quality picker can show real options before the user submits. The result is a +successful `available: false` with a machine-readable `reason` when no listing +can be produced, never a protocol error. The method is extension-only and not +agent-facing. See the [media formats v1 contract](docs/media-formats.md) for the +negotiation, data-sharing, resource-limit and transport-exposure requirements a +host must satisfy before advertising it. + ## License [MIT](./LICENSE) © Dr_rOot diff --git a/README.zh-CN.md b/README.zh-CN.md index 0f66b55..7e5d519 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -199,6 +199,27 @@ if (hello.capabilities.taskReveal ?? false) { `taskId`,绝不接受任意本地路径。它会注册在 `Tools` 中以便发现 schema,但不会进入 `toAgentToolCatalog()`;打开文件管理器属于 UI 副作用,必须由用户发起。 +### 列出页面的媒体格式(client → server) + +```ts +// 仅在握手时目标已声明支持媒体格式后才可调用。 +if (hello.capabilities.mediaFormats ?? false) { + const listing = await conn.sendRequest('media/formats', { + url: 'https://www.youtube.com/watch?v=…', + cookies: [{ name: 'SID', value: '…' }], + }) + + for (const option of listing.entries) { + // 用户选中后,option.key('1080p' | '1440p' | … | 'mp3')会原样回填为 + // download/submit.meta.qualityLabel。 + console.log(option.label, option.kind, option.sizeBytes) + } +} +``` + +抽取器无法列出格式时,返回 `available: false` 与 `reason`,而不是抛协议错误, +因此 client 总能拿到可直接渲染的结构。 + ### 解析页面(server → client) 桌面端会先问某个 client 能否处理这个页面(`url/probe`),再请它抽取出可下载的资源 @@ -349,6 +370,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。 | @@ -442,6 +464,14 @@ RPC handler 需要保留错误码和 data 时,应抛出从 `@motrix/mdxp` 导 不返回底层文件系统错误细节。目录校验不是操作系统沙箱,不能防御有权限并发替换 目录的本地进程。 +## 媒体格式(自 0.9.0 起) + +可选的 `mediaFormats` 能力新增了 `media/formats`:client 询问目标该页面提供哪些可下载 +的视频/音频清晰度,以便扩展的画质选择器在用户提交前展示真实选项。无法列出格式时, +返回成功的 `available: false` 与机器可读的 `reason`,而不是抛协议错误。该方法仅供扩展 +使用,不是 agent-facing 接口。目标在声明支持前必须满足的协商、数据共享、资源上限与 +传输暴露要求,见[媒体格式 v1 契约](docs/media-formats.zh-CN.md)。 + ## License [MIT](./LICENSE) © Dr_rOot diff --git a/docs/media-formats.md b/docs/media-formats.md new file mode 100644 index 0000000..381786a --- /dev/null +++ b/docs/media-formats.md @@ -0,0 +1,121 @@ +# Media formats v1 + +This document defines the `media/formats` contract added by this change. The +package provides the wire schemas, the typed RPC entry and the tool registry +entry. It does not implement media-site policy, an extractor, a picker or a +cache. A host must not advertise support until the requirements below are +implemented and tested. Existing `download/submit` behavior is unchanged. + +## Negotiation and scope + +An authenticated extension may call `media/formats` only when initialize +returns `capabilities.mediaFormats === true`. Absence means unsupported, and a +host that has not registered a lister must not advertise it. + +The method lists the downloadable qualities a page offers so a picker can show +real options before the user submits. It does not transfer a download and it +does not authorize one: the later `download/submit` is validated on its own, +including its `meta.qualityLabel`. Listing a page is a HOST-side fetch — the +host runs its own extractor on a caller-supplied URL. + +`media/formats` is extension-only. It is registered in `Tools` for schema +discovery with `agentFacing: false`, must not appear in the agent tool catalog, +and must not be reachable over the unary HTTP transport. `agentFacing: false` +is not authorization: the transport must authenticate the principal as a paired +extension session before dispatch, independently of any caller-supplied +initialize fields. + +## Data sharing + +- Only `http:`/`https:` URLs are accepted. `file:`, `data:` and `javascript:` + are rejected at the contract boundary. A valid URL is not permission to + access it — the host's normal media-site, permission, size and rate policy + still applies, and a URL the submit path would refuse must also be refused + here so the picker can never promise a quality the submit would decline. +- Browser-session cookies are optional and are disclosed to the extractor for + that one URL only. They are never persisted, never returned in the result and + never logged. Only the `{ name, value }` pair needed for a `Cookie:` header + crosses the wire; domain, expiry and other browser data stay in the browser. + The list is bounded to 256 pairs, and each name/value pair is bounded, so a + client cannot force unbounded header growth. +- The result carries a title, a duration and the option list. It must not carry + extractor stderr, filesystem paths, or any other host detail that was not + requested. + +## Methods and results + +Params are strict: unknown keys are rejected instead of silently ignored. + +```ts +{ url: string /* http(s) */, cookies?: { name: string; value: string }[] } +``` + +The result is non-strict so a newer host may add fields an older client +ignores: + +```ts +{ + available: boolean + reason?: string // machine-readable, opaque, non-exhaustive + title?: string + durationSec?: number + entries: Array<{ + key: string // /^(\d{3,4}p|mp3)$/ + kind: 'video' | 'audio' + label: string + height?: number + fps?: number + ext?: string + sizeBytes?: number + }> +} +``` + +`key` is the quality token the client echoes back as +`download/submit.meta.qualityLabel` — never a raw extractor selector, so a +client cannot smuggle arbitrary format syntax into a download. `entries` is +empty when `available` is false. + +## Failure semantics + +A listing that cannot be produced is a SUCCESSFUL result with +`available: false`, a machine-readable `reason` (`disabled`, `not-allowed`, +`binary-missing`, `unsupported`, `failed`, …) and empty `entries`. `reason` is +opaque and its set is not exhaustive: clients must not branch on an exhaustive +list, and must render an unavailable picker rather than an error. Transport and +protocol errors (including `MethodNotFound` from a host that predates this +method) are the only failures; a client that receives one must treat the +desktop as connected-but-unsupported, not as absent. + +## Compatibility and release order + +Neither side may require synchronized installation. Keep `protocolVersion` +`1.0` and the existing initialize, submit, task and pairing contracts. + +| Extension | Motrix | Result | +| --- | --- | --- | +| Existing | Existing | No calls; unchanged | +| New | Existing (no capability, no method) | `MethodNotFound`; keep the legacy picker/no-op path | +| Existing | New (capability absent from the client's point of view) | Capability simply unused | +| New | New, capability `true` | Formats listed | + +A host must keep the capability absent until it also enforces the URL scheme +restriction and the cookie bound above — advertising the capability is a claim +that the constraints in this document are enforced, not just that the lister +exists. + +## Acceptance required before host advertisement + +1. The lister is registered only for authenticated, paired extension sessions, + and is not exposed on the unary HTTP transport or in the agent catalog. +2. Params are validated with the exported schema, so a non-http(s) URL or an + over-long cookie list is rejected before any process is spawned. +3. Refusals (feature disabled, host not allowlisted, extractor missing, extractor + error) all return `available: false` with a reason, never a crash and never a + protocol error, and never a partial option list the submit would reject. +4. Cookies are used for the single extractor invocation and are not persisted or + logged. + +## License + +[MIT](../LICENSE) diff --git a/docs/media-formats.zh-CN.md b/docs/media-formats.zh-CN.md new file mode 100644 index 0000000..dd2856b --- /dev/null +++ b/docs/media-formats.zh-CN.md @@ -0,0 +1,102 @@ +# 媒体格式 v1 + +本文档定义本次变更引入的 `media/formats` 契约。本包只提供 wire schema、类型化的 RPC +条目与工具注册表条目,不实现媒体站点策略、抽取器、选择器 UI 或缓存。目标在实现并 +验证下文要求之前,不得声明支持该能力。既有 `download/submit` 行为保持不变。 + +## 协商与范围 + +已认证的扩展仅在 initialize 返回 `capabilities.mediaFormats === true` 时才可调用 +`media/formats`。能力缺失即表示不支持;没有注册 lister 的目标不得声明该能力。 + +该方法列出页面可下载的清晰度,供选择器在用户提交前展示真实选项。它不传输下载, +也不构成下载授权:随后的 `download/submit`(包括其 `meta.qualityLabel`)仍会独立 +校验。列出格式是由**目标端**抓取:目标对调用方给出的 URL 运行自己的抽取器。 + +`media/formats` 仅供扩展使用。它注册在 `Tools` 中以便发现 schema,并标记 +`agentFacing: false`,不得出现在 agent tool catalog 中,也不得通过 unary HTTP +transport 访问。`agentFacing: false` 不是授权机制:transport 必须在派发前把调用方 +认证为已配对扩展会话,且不依赖调用方自报的 initialize 字段。 + +## 数据共享 + +- 只接受 `http:`/`https:` URL。`file:`、`data:`、`javascript:` 在契约边界即被拒绝。 + 合法 URL 不等于访问许可 —— 目标常规的媒体站点、权限、体积与限流策略仍然生效; + 提交路径会拒绝的 URL,此处也必须拒绝,避免选择器承诺一个提交时会被拒的清晰度。 +- 浏览器会话 cookie 为可选项,且仅对该 URL 的这一次抽取披露。它们绝不持久化、 + 不在结果中回传、也不会写入日志。只有拼装 `Cookie:` 头所需的 `{ name, value }` + 会跨进程传输;domain、过期时间等浏览器数据保留在浏览器内。列表上限 256 组, + 每组名称与值亦各有上限,因此 client 无法制造无界的头增长。 +- 结果只包含标题、时长与选项列表;不得携带抽取器 stderr、文件系统路径或任何未被 + 请求的目标端细节。 + +## 方法与结果 + +参数为严格模式:未知键会被拒绝,而不是静默忽略。 + +```ts +{ url: string /* http(s) */, cookies?: { name: string; value: string }[] } +``` + +结果为非严格模式,便于更新的目标添加字段而旧 client 忽略: + +```ts +{ + available: boolean + reason?: string // 机器可读、不透明、集合不保证穷尽 + title?: string + durationSec?: number + entries: Array<{ + key: string // /^(\d{3,4}p|mp3)$/ + kind: 'video' | 'audio' + label: string + height?: number + fps?: number + ext?: string + sizeBytes?: number + }> +} +``` + +`key` 是 client 原样回填到 `download/submit.meta.qualityLabel` 的清晰度令牌,绝不是 +原始抽取器 selector,因此 client 无法借此把任意格式语法夹带进下载请求。`available` +为 false 时 `entries` 为空数组。 + +## 失败语义 + +无法列出格式时应返回**成功**结果:`available: false`、机器可读的 `reason` +(`disabled`、`not-allowed`、`binary-missing`、`unsupported`、`failed` 等)以及空 +`entries`。`reason` 不透明且取值集合不保证穷尽:client 不得依赖穷尽枚举来分支,也 +必须把不可用渲染成“不可用”而不是错误。传输与协议错误(例如早于本方法的旧目标返回 +`MethodNotFound`)是唯一的失败形式;client 收到这类错误时,应视为目标“已连接但不 +支持”,而不是目标不存在。 + +## 兼容与发布顺序 + +任何一方都不得要求另一方同步安装。保持 `protocolVersion` 为 `1.0`,并保持既有 +initialize、submit、task 与 pairing 契约不变。 + +| 扩展 | Motrix | 结果 | +| --- | --- | --- | +| 旧 | 旧 | 不调用;行为不变 | +| 新 | 旧(无能力、无方法) | `MethodNotFound`;保留旧的 picker/静默路径 | +| 旧 | 新 | 该能力未被使用 | +| 新 | 新且能力为 `true` | 正常列出格式 | + +在同时落实上文 URL scheme 限制与 cookie 上限之前,目标必须保持能力缺失 —— 声明该 +能力意味着“本文档中的约束已被强制执行”,而不仅仅是 lister 存在。 + +## 声明支持前必须满足 + +1. lister 仅对已认证、已配对的扩展会话注册,且不通过 unary HTTP transport 或 agent + catalog 暴露。 +2. 使用导出的 schema 校验参数:非 http(s) URL 或超长的 cookie 列表在派发任何进程 + 之前即被拒绝。 +3. 各类拒绝(功能关闭、站点不在允许列表、抽取器缺失、抽取器报错)一律返回 + `available: false` 与 reason,绝不崩溃、绝不抛协议错误,也绝不返回提交时会被拒的 + 部分选项列表。 +4. cookie 仅用于那一次抽取调用,不被持久化,也不写入日志。 + +## License + +[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__/media-formats.test.ts b/src/__tests__/media-formats.test.ts new file mode 100644 index 0000000..69c8d06 --- /dev/null +++ b/src/__tests__/media-formats.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest' +import { + InitializeResultSchema, + MediaFormatsParamsSchema, + MediaFormatsResultSchema, + Methods, + Tools, + toAgentToolCatalog, +} from '../index.js' + +const entry = { + key: '1080p', + kind: 'video' as const, + label: '1080p', + height: 1080, + fps: 60, + ext: 'mp4', + sizeBytes: 734_003_200, +} + +const serverHello = { + protocolVersion: '1.0', + server: { name: 'motrix', version: '2', runtime: 'electron' }, + capabilities: { + ffmpegAvailable: true, + selectionKinds: ['direct'], + progress: true, + cancellation: true, + }, + serverAdapters: [], +} + +describe('media/formats params', () => { + it('accepts a page url, with or without session cookies', () => { + expect( + MediaFormatsParamsSchema.safeParse({ url: 'https://youtu.be/x' }).success + ).toBe(true) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://www.youtube.com/watch?v=x', + cookies: [{ name: 'SID', value: 'abc' }], + }).success + ).toBe(true) + }) + + it('rejects unknown params (strict)', () => { + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://youtu.be/x', + formatSelector: 'bv*+ba/b', + }).success + ).toBe(false) + }) + + it('rejects non-http(s) urls — the host fetches this url itself', () => { + for (const url of [ + 'file:///etc/passwd', + 'data:text/plain,x', + 'javascript:alert(1)', + 'ftp://host/f', + ]) { + expect(MediaFormatsParamsSchema.safeParse({ url }).success).toBe(false) + } + }) + + it('requires a non-empty cookie name', () => { + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://youtu.be/x', + cookies: [{ name: '', value: 'v' }], + }).success + ).toBe(false) + }) + + it('bounds the cookie list so header growth stays finite', () => { + const cookies = Array.from({ length: 256 }, (_, i) => ({ + name: `c${i}`, + value: 'v', + })) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://youtu.be/x', + cookies, + }).success + ).toBe(true) + expect( + MediaFormatsParamsSchema.safeParse({ + url: 'https://youtu.be/x', + cookies: [...cookies, { name: 'extra', value: 'v' }], + }).success + ).toBe(false) + }) +}) + +describe('media/formats result', () => { + it('accepts an available listing', () => { + const r = MediaFormatsResultSchema.safeParse({ + available: true, + title: 'Sample clip', + durationSec: 372, + entries: [entry, { key: 'mp3', kind: 'audio', label: 'MP3' }], + }) + expect(r.success).toBe(true) + }) + + it('accepts an unavailable listing with empty entries', () => { + expect( + MediaFormatsResultSchema.safeParse({ + available: false, + reason: 'not-allowed', + entries: [], + }).success + ).toBe(true) + }) + + it('rejects a raw extractor selector as a quality key', () => { + for (const key of ['bestvideo+bestaudio', 'bv*+ba/b', '137', '']) { + expect( + MediaFormatsResultSchema.safeParse({ + available: true, + entries: [{ ...entry, key }], + }).success + ).toBe(false) + } + }) + + it('rejects an unknown kind', () => { + expect( + MediaFormatsResultSchema.safeParse({ + available: true, + entries: [{ ...entry, kind: 'subtitle' }], + }).success + ).toBe(false) + }) + + it('strips unknown result fields (forward-compatible)', () => { + const parsed = MediaFormatsResultSchema.parse({ + available: true, + entries: [entry], + addedByANewerServer: 'ignored', + }) + expect(parsed.entries).toHaveLength(1) + expect('addedByANewerServer' in parsed).toBe(false) + }) +}) + +describe('media/formats registration + exposure', () => { + it('is a non-agent-facing client→server method', () => { + expect(Methods.MediaFormats).toBe('media/formats') + const tool = Tools[Methods.MediaFormats] + expect(tool?.method).toBe(Methods.MediaFormats) + expect(tool?.agentFacing).toBe(false) + expect( + tool?.paramsSchema.safeParse({ url: 'https://youtu.be/x' }).success + ).toBe(true) + expect( + tool?.resultSchema.safeParse({ available: true, entries: [entry] }) + .success + ).toBe(true) + }) + + it('stays off the unary agent tool catalog', () => { + expect( + toAgentToolCatalog().some((t) => t.name === Methods.MediaFormats) + ).toBe(false) + }) + + it('requires negotiated support; absent means unsupported', () => { + expect( + InitializeResultSchema.parse(serverHello).capabilities.mediaFormats + ).not.toBe(true) + expect( + InitializeResultSchema.parse({ + ...serverHello, + capabilities: { ...serverHello.capabilities, mediaFormats: true }, + }).capabilities.mediaFormats + ).toBe(true) + }) +}) diff --git a/src/connection.ts b/src/connection.ts index 37c8f84..48a086a 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,8 @@ export interface MdxpRequestMap { 'url/probe': [UrlProbeParams, UrlProbeResult] 'url/resolve': [UrlResolveParams, UrlResolveResult] 'system/ping': [SystemPingParams, SystemPingResult] + // Extension-only media surface (since 0.9.0) + '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..4697879 100644 --- a/src/methods.ts +++ b/src/methods.ts @@ -7,6 +7,8 @@ export const Methods = Object.freeze({ UrlProbe: 'url/probe', UrlResolve: 'url/resolve', SystemPing: 'system/ping', + // Extension-only media surface (since 0.9.0) + 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..4468aba 100644 --- a/src/schemas/initialize.ts +++ b/src/schemas/initialize.ts @@ -74,6 +74,12 @@ const ServerCapabilitiesSchema = z.object({ taskReveal: z.boolean().optional().default(false), /** Enables download/directories AND download/submit.saveDir; absent is false. */ downloadDirectories: z.boolean().optional(), + /** + * Enables media/formats for an authenticated extension session; absent is + * false. The listing runs the host's extractor on a caller-supplied URL, so + * a client MUST NOT call the method unless the host advertised `true`. + */ + 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..d6d5e07 --- /dev/null +++ b/src/schemas/media-formats.ts @@ -0,0 +1,68 @@ +import { z } from 'zod' +import { HttpUrlSchema } from './resource.js' + +// media/formats ------------------------------------------------ + +/** + * A cookie captured from the CALLER's browser session and forwarded verbatim + * to the extractor, exactly like `download/submit`'s resource cookies. Only + * the pair needed for a `Cookie:` header is disclosed — domain/expiry metadata + * stays in the browser. + */ +export const MediaFormatCookieSchema = z.object({ + name: z.string().min(1).max(256), + value: z.string().max(4096), +}) + +export const MediaFormatsParamsSchema = z + .object({ + /** + * Page (watch page or direct media) URL whose formats should be listed. + * http(s) only: the host fetches this URL with its own extractor, so + * local/`file:`/`data:` schemes are rejected at the boundary. + */ + url: HttpUrlSchema, + /** + * Browser-session cookies for member-only media. Optional; the host only + * forwards them to the extractor for this URL and never persists or + * returns them. Bounded so a client cannot force unbounded header growth. + */ + cookies: z.array(MediaFormatCookieSchema).max(256).optional(), + }) + .strict() + +/** + * One selectable option. `key` is the quality token the client echoes back as + * `download/submit.meta.qualityLabel` — never a raw extractor selector, so a + * client cannot smuggle arbitrary format syntax through this schema. + */ +export const MediaFormatEntrySchema = z.object({ + key: z.string().regex(/^(\d{3,4}p|mp3)$/), + kind: z.enum(['video', 'audio']), + /** Display label, e.g. `1080p` or `MP3`. */ + label: z.string().min(1).max(64), + height: z.number().int().positive().optional(), + fps: z.number().positive().optional(), + ext: z.string().min(1).max(16).optional(), + sizeBytes: z.number().int().positive().optional(), +}) + +/** + * Non-strict result: a newer host may add fields (forward-compatible), and an + * unavailable listing is expressed as `available: false` + `reason` with an + * empty `entries` — never as a protocol error. `reason` is an opaque + * machine-readable token (`disabled`, `not-allowed`, `unsupported`, `failed`, + * …); clients must not branch on an exhaustive list. + */ +export const MediaFormatsResultSchema = z.object({ + available: z.boolean(), + reason: z.string().min(1).max(64).optional(), + title: z.string().max(500).optional(), + durationSec: z.number().nonnegative().optional(), + entries: z.array(MediaFormatEntrySchema), +}) + +export type MediaFormatCookie = z.infer +export type MediaFormatEntry = z.infer +export type MediaFormatsParams = z.infer +export type MediaFormatsResult = z.infer diff --git a/src/schemas/resource.ts b/src/schemas/resource.ts index ce322a0..d97b813 100644 --- a/src/schemas/resource.ts +++ b/src/schemas/resource.ts @@ -1,7 +1,9 @@ import { z } from 'zod' // Download hosts may be IP literals or local names; z.httpUrl requires a domain. -const HttpUrl = z.url({ +// Exported so every method that makes the HOST fetch a caller-supplied URL +// enforces the same http(s)-only policy (see `media/formats`). +export const HttpUrlSchema = z.url({ protocol: /^https?$/, message: 'URL must be http: or https:', }) @@ -20,7 +22,7 @@ export const CookieSchema = z.object({ }) export const ResourceSchema = z.object({ - url: HttpUrl, + url: HttpUrlSchema, headers: z.record(z.string(), z.string()).default({}), cookies: z.array(CookieSchema).default([]), refererPolicy: z.string().default('strict-origin-when-cross-origin'), diff --git a/src/tools.ts b/src/tools.ts index 3e18bb0..062ad0a 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 the extractable media formats (video/audio qualities) a page offers, for an extension quality picker.', + 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,