Skip to content
Back to search

mcp-video-analyzer

MCP server that turns any video — YouTube, Instagram, TikTok, Loom, X, Vimeo, direct URLs, local files — into transcripts, key frames, OCR text, and metadata for AI agents.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/guimatheus92/mcp-video-analyzer with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/guimatheus92/mcp-video-analyzer'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/guimatheus92--mcp-video-analyzer/badge.svg)](/listings/guimatheus92--mcp-video-analyzer)

HTML

<a href="/listings/guimatheus92--mcp-video-analyzer"><img src="/api/listings/guimatheus92--mcp-video-analyzer/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Prerequisites

- **Node.js 22.12+** — required to run the server via `npx` - **yt-dlp** — **required** for YouTube/Vimeo/TikTok/Instagram/X/Twitch/Dailymotion/Facebook URLs; optional for everything else (improves Loom download quality). Install with `pip install yt-dlp` - **Chrome/Chromium** (optional) — fallback for frame extraction if yt-dlp is unavailable

> Without yt-dlp or Chrome, direct URLs and local files still get frames — the bundled `ffmpeg-static` does the extraction, and Loom falls back to its own CDN download. Platform URLs (YouTube etc.) degrade to a clear "install yt-dlp" warning. Transcripts, metadata, and comments never require either.

There are three ways in: the **`/video` plugin** (Claude Code — slash command + MCP server auto-configured), a plain **MCP server** config (any MCP client), or the **portable skill + CLI** (Codex, Cursor, Copilot, and any agent with a shell — no MCP required).

Claude Code — `/video` plugin (recommended)

/plugin marketplace add guimatheus92/mcp-video-analyzer
/plugin install video@mcp-video-analyzer

This adds the `/video` slash command **and** auto-registers the MCP server — no `claude mcp add` needed:

/video https://youtu.be/jNQXAC9IVRw what happens at 0:10?
/video ~/Movies/screen-recording.mp4 when does the UI break?

Other agents — Codex, Cursor, Copilot, Gemini CLI, …

npx skills add guimatheus92/mcp-video-analyzer

Installs the `video` skill ([Agent Skills](https://github.com/vercel-labs/skills) format) into every agent detected on your machine. Agents without the MCP server configured fall back to the bundled [CLI](#cli-one-shot-no-mcp-client) automatically — zero configuration.

Claude Code (MCP only)

claude mcp add video-analyzer -- npx mcp-video-analyzer@latest

Then restart Claude Code or start a new conversation.

VS Code / Cursor

Add to your MCP settings file:

- **VS Code**: `File → Preferences → Settings → search "MCP"` or edit `~/.vscode/mcp.json` / `%APPDATA%\Code\User\mcp.json` (Windows) - **Cursor**: `Settings → MCP Servers → Add`

{
  "servers": {
    "mcp-video-analyzer": {
      "type": "stdio",
      "command": "npx",
      "args": ["mcp-video-analyzer@latest"]
    }
  }
}

Then reload the window (`Ctrl+Shift+P` → "Developer: Reload Window").

Claude Desktop

Add to your Claude Desktop config file:

- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

{
  "mcpServers": {
    "video-analyzer": {
      "command": "npx",
      "args": ["mcp-video-analyzer@latest"]
    }
  }
}

Then restart Claude Desktop.

CLI (one-shot, no MCP client)

The same engine is exposed as a one-shot command — this is what the `video` skill uses on agents without MCP, and it works standalone in any terminal:

npx -y mcp-video-analyzer@latest analyze "https://youtu.be/jNQXAC9IVRw"

stdout is a single JSON document — `metadata`, `transcript`, `ocrResults`, `timeline`, `warnings`, `frameCount`, and `frames` as `{ time, filePath, mimeType }` entries pointing at JPEG key frames copied to `--out` (default: the per-user cache dir — `%LOCALAPPDATA%` on Windows, `~/Library/Caches` on macOS, `$XDG_CACHE_HOME` or `~/.cache` on Linux — under `mcp-video-analyzer/<url-hash>/`; set `MCP_CACHE_DIR` to an absolute path to relocate it). Unlike the temp dir this used to live in, nothing reaps that location, so frames persist until you delete them — the directories are created `0700`. Progress streams on stderr, so `stdout` can be piped straight into a JSON parser. Partial failures land in `warnings` with exit code 0; only hard failures exit 1.

| Flag | Description | |------|-------------| | `--detail <level>` | `brief` (metadata + transcript, no frames), `standard` (default), `detailed` | | `--max-frames <n>` | Max key frames, 1–60 (default adapts to duration) |

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 18 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "mcp-video-analyzer",
  3. "metadata": {
  4. "description": "Video analysis for AI agents: transcripts, key frames, OCR, and annotated timelines from Loom, YouTube, Instagram, TikTok, direct URLs, and local files."
  5. },
  6. "owner": {
  7. "name": "Guilherme Matheus"
  8. },
  9. "plugins": [
  10. {
  11. "name": "video",
  12. "description": "Watch a video with /video — transcript, key frames, OCR, and timeline from a URL or local file, answered with timestamps.",
  13. "source": "./",
  14. "category": "productivity",
  15. "homepage": "https://github.com/guimatheus92/mcp-video-analyzer"
  16. }
  17. ]
  18. }
README.md · README · 585 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <img src="assets/icon.svg" width="88" height="88" alt="mcp-video-analyzer" />
  3. </p>
  4. <h1 align="center">mcp-video-analyzer</h1>
  5. <p align="center"><em>Turn any video — YouTube, Instagram, TikTok, Loom, X, Vimeo, direct links, local files — into transcripts, key frames, OCR text, and metadata for AI agents.</em></p>
  6. <p align="center">
  7. <a href="https://www.npmjs.com/package/mcp-video-analyzer"><img src="https://img.shields.io/npm/v/mcp-video-analyzer?color=e8468f&labelColor=1e1e2e&logo=npm&logoColor=white" alt="npm" /></a>
  8. <a href="https://github.com/guimatheus92/mcp-video-analyzer/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/mcp-video-analyzer?color=8b5cf6&labelColor=1e1e2e" alt="license" /></a>
  9. <a href="https://github.com/punkpeye/awesome-mcp-servers#-multimedia-process"><img src="https://img.shields.io/badge/awesome--mcp--servers-listed-ff4d6d?labelColor=1e1e2e" alt="awesome-mcp-servers" /></a>
  10. <a href="https://mcpservers.org/servers/guimatheus92/mcp-video-analyzer"><img src="https://img.shields.io/badge/mcpservers.org-listed-38bdf8?labelColor=1e1e2e" alt="mcpservers.org" /></a>
  11. </p>
  12. <p align="center">
  13. <a href="https://glama.ai/mcp/servers/guimatheus92/mcp-video-analyzer"><img width="360" height="190" src="https://glama.ai/mcp/servers/guimatheus92/mcp-video-analyzer/badge" alt="mcp-video-analyzer MCP server" /></a>
  14. </p>
  15. No existing video MCP combines **transcripts + visual frames + metadata** in one tool. This one does — across Loom, the major yt-dlp platforms (YouTube/Vimeo/TikTok/Instagram/X/Twitch/Dailymotion/Facebook), direct video URLs, and local files.
  16. > **Want a full pipeline, not just a tool?** [social-knowledge-base](https://github.com/guimatheus92/social-knowledge-base) is built on top of this server — it downloads whole Instagram creator accounts (reels, stories, highlights), transcribes them, and turns the result into a searchable, RAG-queryable knowledge base with AI-generated notes. Use this MCP when you want per-video analysis inside an agent; use social-knowledge-base when you want to archive and query an entire account.
  17. ## Installation
  18. ### Prerequisites
  19. - **Node.js 22.12+** — required to run the server via `npx`
  20. - **yt-dlp** — **required** for YouTube/Vimeo/TikTok/Instagram/X/Twitch/Dailymotion/Facebook URLs; optional for everything else (improves Loom download quality). Install with `pip install yt-dlp`
  21. - **Chrome/Chromium** (optional) — fallback for frame extraction if yt-dlp is unavailable
  22. > Without yt-dlp or Chrome, direct URLs and local files still get frames — the bundled `ffmpeg-static` does the extraction, and Loom falls back to its own CDN download. Platform URLs (YouTube etc.) degrade to a clear "install yt-dlp" warning. Transcripts, metadata, and comments never require either.
  23. There are three ways in: the **`/video` plugin** (Claude Code — slash command + MCP server auto-configured), a plain **MCP server** config (any MCP client), or the **portable skill + CLI** (Codex, Cursor, Copilot, and any agent with a shell — no MCP required).
  24. ### Claude Code — `/video` plugin (recommended)
  25. ```
  26. /plugin marketplace add guimatheus92/mcp-video-analyzer
  27. /plugin install video@mcp-video-analyzer
  28. ```
  29. This adds the `/video` slash command **and** auto-registers the MCP server — no `claude mcp add` needed:
  30. ```
  31. /video https://youtu.be/jNQXAC9IVRw what happens at 0:10?
  32. /video ~/Movies/screen-recording.mp4 when does the UI break?
  33. ```
  34. ### Other agents — Codex, Cursor, Copilot, Gemini CLI, …
  35. ```bash
  36. npx skills add guimatheus92/mcp-video-analyzer
  37. ```
  38. Installs the `video` skill ([Agent Skills](https://github.com/vercel-labs/skills) format) into every agent detected on your machine. Agents without the MCP server configured fall back to the bundled [CLI](#cli-one-shot-no-mcp-client) automatically — zero configuration.
  39. ### Claude Code (MCP only)
  40. ```bash
  41. claude mcp add video-analyzer -- npx mcp-video-analyzer@latest
  42. ```
  43. Then restart Claude Code or start a new conversation.
  44. ### VS Code / Cursor
  45. Add to your MCP settings file:
  46. - **VS Code**: `File → Preferences → Settings → search "MCP"` or edit `~/.vscode/mcp.json` / `%APPDATA%\Code\User\mcp.json` (Windows)
  47. - **Cursor**: `Settings → MCP Servers → Add`
  48. ```json
  49. {
  50. "servers": {
  51. "mcp-video-analyzer": {
  52. "type": "stdio",
  53. "command": "npx",
  54. "args": ["mcp-video-analyzer@latest"]
  55. }
  56. }
  57. }
  58. ```
  59. Then reload the window (`Ctrl+Shift+P` → "Developer: Reload Window").
  60. ### Claude Desktop
  61. Add to your Claude Desktop config file:
  62. - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
  63. - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
  64. ```json
  65. {
  66. "mcpServers": {
  67. "video-analyzer": {
  68. "command": "npx",
  69. "args": ["mcp-video-analyzer@latest"]
  70. }
  71. }
  72. }
  73. ```
  74. Then restart Claude Desktop.
  75. ### CLI (one-shot, no MCP client)
  76. The same engine is exposed as a one-shot command — this is what the `video` skill uses on agents without MCP, and it works standalone in any terminal:
  77. ```bash
  78. npx -y mcp-video-analyzer@latest analyze "https://youtu.be/jNQXAC9IVRw"
  79. ```
  80. stdout is a single JSON document — `metadata`, `transcript`, `ocrResults`, `timeline`, `warnings`, `frameCount`, and `frames` as `{ time, filePath, mimeType }` entries pointing at JPEG key frames copied to `--out` (default: the per-user cache dir — `%LOCALAPPDATA%` on Windows, `~/Library/Caches` on macOS, `$XDG_CACHE_HOME` or `~/.cache` on Linux — under `mcp-video-analyzer/<url-hash>/`; set `MCP_CACHE_DIR` to an absolute path to relocate it). Unlike the temp dir this used to live in, nothing reaps that location, so frames persist until you delete them — the directories are created `0700`. Progress streams on stderr, so `stdout` can be piped straight into a JSON parser. Partial failures land in `warnings` with exit code 0; only hard failures exit 1.
  81. | Flag | Description |
  82. |------|-------------|
  83. | `--detail <level>` | `brief` (metadata + transcript, no frames), `standard` (default), `detailed` |
  84. | `--max-frames <n>` | Max key frames, 1–60 (default adapts to duration) |
  85. | `--max-width <px>` | Width cap for emitted frames (default `800`, or `MCP_FRAME_MAX_WIDTH`); `0` keeps the source resolution — see [Frame size](#frame-size-dense-ui-captures) |
  86. | `--fields <list>` | Output filter — comma-separated subset: `metadata,transcript,frames,comments,chapters,ocrResults,timeline,aiSummary`. Filters the emitted JSON only; use `--detail brief` to actually skip download/frame extraction |
  87. | `--force-refresh` | Bypass the cache and re-analyze |
  88. | `--ocr-language <codes>` | Tesseract languages (default `eng+por`) |
  89. | `--model <name>` / `--language <code>` | Whisper overrides for the transcription fallback |
  90. | `--out <dir>` | Where frame images are copied |
  91. Run with no arguments (`npx mcp-video-analyzer@latest`) to start the MCP stdio server — the CLI is purely additive.
  92. ### Verify it works
  93. Once installed, ask your AI assistant:
  94. ```
  95. Analyze this video: https://www.youtube.com/watch?v=jNQXAC9IVRw
  96. ```
  97. (also works with an Instagram/TikTok/Loom link, a direct `.mp4` URL, or a local file path). If the server is connected, it will automatically call the `analyze_video` tool.
  98. ## Tools
  99. Eight tools — the AI picks the cheapest one for the job and calls it automatically. Click any tool to expand its parameters and examples.
  100. | Tool | What it does |
  101. |------|--------------|
  102. | **`analyze_video`** | Full analysis: transcript + key frames + OCR + timeline + metadata |
  103. | **`analyze_videos`** | Batch version, one structured result per source (resumable) |
  104. | **`get_transcript`** | Transcript only (native captions or Whisper fallback) |
  105. | **`get_metadata`** | Metadata + comments + chapters, no download |
  106. | **`get_frames`** | Key frames only (scene-change or dense 1 fps) |
  107. | **`analyze_moment`** | Deep-dive on a time range (burst frames + transcript + OCR) |
  108. | **`get_frame_at`** | Single frame at a timestamp |
  109. | **`get_frame_burst`** | N frames across a narrow window (motion/animation) |
  110. <details>
  111. <summary><b><code>analyze_video</code></b> — full video analysis</summary>
  112. <br>
  113. Extracts everything from a video URL in one call:
  114. ```
  115. > Analyze this video: https://www.youtube.com/watch?v=abc123...
  116. ```
  117. Returns:
  118. - **Transcript** with timestamps and speakers
  119. - **Key frames** extracted via scene-change detection (automatically deduplicated). For static clips with no scene cuts — e.g. talking-head Reels/Stories where only an on-screen text overlay changes — it automatically falls back to uniform temporal sampling so you still get frames (and OCR) instead of an empty result.
  120. - **OCR text** extracted from frames (code, error messages, UI text, prices/dates/CTAs visible on screen)
  121. - **Annotated timeline** merging transcript + frames + OCR into a unified "what happened when" view
  122. - **Metadata** (title, duration, platform)
  123. - **Comments** from viewers
  124. - **Chapters** and **AI summary** (when available)
  125. The AI will **automatically** call this tool when it sees a video URL — no need to ask.
  126. Options:
  127. - `detail` — analysis depth: `"brief"` (metadata + truncated transcript, no frames), `"standard"` (default), `"detailed"` (dense sampling, more frames)
  128. - `fields` — array of specific fields to return, e.g. `["metadata", "transcript"]`. Available: `metadata`, `transcript`, `frames`, `comments`, `chapters`, `ocrResults`, `timeline`, `aiSummary`
  129. - `maxFrames` (1-60) — cap on extracted frames. Default scales with video duration at `standard` detail (~12 for ≤30s up to 60 for >10min); fixed 60 at `detailed`, 0 at `brief`. An explicit value always wins
  130. - `threshold` (0.0-1.0, default 0.1) — scene-change sensitivity
  131. - `forceRefresh` — bypass cache and re-analyze
  132. - `skipFrames` — skip frame extraction for transcript-only analysis
  133. - `model` / `language` / `initialPrompt` — per-call Whisper overrides for the transcription fallback (override `WHISPER_MODEL` / `WHISPER_LANGUAGE` / `WHISPER_PROMPT` for this call only — pick a heavier model or a domain glossary for one hard clip without restarting the server)
  134. </details>
  135. <details>
  136. <summary><b><code>analyze_videos</code></b> — batch analysis</summary>
  137. <br>
  138. ```
  139. > Analyze every .mp4 in this folder
  140. ```
  141. Runs `analyze_video` over a list of `sources` with a `concurrency` limit (default 2), returning one **structured result per source** — counts + warnings on success, or a per-item `error` on failure (one bad file never aborts the batch). Frame images are not inlined and full transcript/OCR/timeline are returned only when `fields` is set; otherwise you get counts. Pair with `MCP_WRITE_SIDECARS=1` (below) so each video's result persists to disk and a re-run resumes instead of recomputing.
  142. </details>
  143. <details>
  144. <summary><b><code>get_transcript</code></b> — transcript only</summary>
  145. <br>
  146. ```
  147. > Get the transcript from this video
  148. ```
  149. Quick transcript extraction. Falls back to Whisper transcription when no native transcript is available. Accepts the same per-call `model` / `language` / `initialPrompt` overrides as `analyze_video`.
  150. </details>
  151. <details>
  152. <summary><b><code>get_metadata</code></b> — metadata only</summary>
  153. <br>
  154. ```
  155. > What's this video about?
  156. ```
  157. Returns metadata, comments, chapters, and AI summary without downloading the video.
  158. </details>
  159. <details>
  160. <summary><b><code>get_frames</code></b> — frames only</summary>
  161. <br>
  162. ```
  163. > Extract frames from this video with dense sampling
  164. ```
  165. Two modes:
  166. - **Scene-change detection** (default) — captures visual transitions
  167. - **Dense sampling** (`dense: true`) — 1 frame/sec for full coverage
  168. </details>
  169. <details>
  170. <summary><b><code>analyze_moment</code></b> — deep-dive on a time range</summary>
  171. <br>
  172. ```
  173. > Analyze what happens between 1:30 and 2:00 in this video
  174. ```
  175. Combines burst frame extraction + filtered transcript + OCR + annotated timeline for a focused segment. Use when you need to understand exactly what happens at a specific moment.
  176. </details>
  177. <details>
  178. <summary><b><code>get_frame_at</code></b> — single frame at a timestamp</summary>
  179. <br>
  180. ```
  181. > Show me the frame at 1:23 in this video
  182. ```
  183. The AI reads the transcript, spots a critical moment, and requests the exact frame to see what's on screen.
  184. </details>
  185. <details>
  186. <summary><b><code>get_frame_burst</code></b> — N frames in a time range</summary>
  187. <br>
  188. ```
  189. > Show me 10 frames between 0:15 and 0:17 of this video
  190. ```
  191. For motion, vibration, animations, or fast scrolling — burst mode captures N frames in a narrow window so the AI can see frame-by-frame changes.
  192. </details>
  193. ## Detail Levels
  194. | Level | Frames | Transcript | OCR | Timeline | Use case |
  195. |-------|--------|-----------|-----|----------|----------|
  196. | `brief` | None | First 10 entries | No | No | Quick check — what's this video about? |
  197. | `standard` | Duration-adaptive: ~12 (≤30s) up to 60 (>10min), scene-change | Full | Yes | Yes | Default — full analysis |
  198. | `detailed` | Up to 60 (1fps dense) | Full | Yes | Yes | Deep analysis — every second captured |
  199. ## Caching
  200. Results are cached in memory for 10 minutes. Subsequent calls with the same URL and options return instantly. Use `forceRefresh: true` to bypass the cache. `skipFrames` is part of the cache and sidecar key, so a transcript-only analysis and a framed one of the same URL never answer for each other.
  201. ### Persistent sidecars (resumable bulk processing)
  202. The in-memory cache is lost on restart, which makes reprocessing a large local corpus costly. Set `MCP_WRITE_SIDECARS=1` to also persist results **next to each local video** so the work survives restarts and can resume:
  203. - `<stem>.vtt` — the transcript, **only** when it was generated by the Whisper fallback (an existing `<stem>.vtt` from your own pipeline is never overwritten). A later call reuses it via the normal sidecar reader and skips Whisper entirely.
  204. - `<stem>.analysis.json` + `<stem>.frames/` — the full result (frames + OCR + timeline), keyed by the video's `mtime:size` and the analysis params. On a later call with a matching stamp + params, the result is returned straight from disk (no extraction, no OCR).
  205. This makes `analyze_videos` over thousands of files resumable, and lets an external GPU transcription pipeline and this MCP share results through the filesystem: the pipeline writes `<stem>.vtt`, and the MCP picks it up instead of running Whisper.
  206. ## Supported Sources
  207. | Source | Transcript | Metadata | Comments | Frames | Auth |
  208. |--------|:----------:|:--------:|:--------:|:------:|:----:|
  209. | **Loom** | Yes | Yes | Yes | Yes (usually needs yt-dlp — see note) | None |
  210. | **YouTube / Vimeo / TikTok / Instagram / X / Twitch / Dailymotion / Facebook** | Native captions (uploaded > auto-generated) or Whisper fallback | Yes (title, duration, uploader, views, chapters, upload date) | No | Yes (capped at 1080p) | yt-dlp installed; cookies for Instagram / age-restricted (see below) |
  211. | **Direct URL** (.mp4, .mov, .mkv, .webm, …) | No | Duration only | No | Yes | None |
  212. | **Direct URL + TwelveLabs** | Yes (Pegasus, best-effort) | Duration floor + title | No | Yes | `TWELVELABS_API_KEY` |
  213. | **Local file** (absolute path or `file://` URI) | Sidecar `.vtt`/`.srt` or Whisper fallback | Probed via ffmpeg (duration, dims, codec, audio presence) | No | Yes | None |
  214. > **Loom frames**: transcript, metadata, and comments come straight from Loom's API with no extra tooling. Frame extraction is different — Loom serves most videos as separate DASH video+audio streams, which only [yt-dlp](https://github.com/yt-dlp/yt-dlp) (`pip install yt-dlp`) fetches and merges. Merging uses the bundled `ffmpeg-static`, so no system ffmpeg is required. Without yt-dlp a direct-CDN fallback still covers some videos; when it can't, you get transcript + metadata + comments plus a warning explaining why frames are missing.
  215. >
  216. > **Local files**: pass an absolute path (e.g., `/Users/you/clip.mp4`) or a `file://` URI as the `url` argument to any tool. Relative paths are rejected — the server's working directory is unpredictable from the MCP client. Note that any caller of the MCP server can ask it to read any file the server process has access to. UNC / network share paths (`\\host\share\clip.mp4`) are the exception: they reach the network rather than local disk, so they follow the [network destination](#network-destinations) rules and need `MCP_ALLOW_PRIVATE_URLS=1`.
  217. >
  218. > **Sidecar transcripts**: if a `clip.vtt`, `clip.srt`, `clip.en.vtt`, etc. lives next to `clip.mp4`, it's used as the transcript automatically — no Whisper roundtrip needed. SRT is converted to VTT in-memory.
  219. >
  220. > **Embedded subtitles**: if no sidecar is found and the container has an embedded subtitle stream (common in `.mkv` / `.mov` / `.mp4` from screen recorders), it's transmuxed to VTT via ffmpeg and used as the transcript.
  221. >
  222. > **Recognized extensions** (local files and direct URLs): `.mp4` `.mov` `.mkv` `.webm` `.avi` `.m4v` `.wmv` `.flv` `.mpeg` `.mpg` `.m2ts` `.mts` `.3gp` `.ogv`. The extension only gates routing — ffmpeg does the actual demuxing, so most common containers work. `.ts` is excluded to avoid colliding with TypeScript source files.
  223. ### Network destinations
  224. Only `http://` and `https://` URLs are fetched, and only to **public** addresses. Requests to loopback (`localhost`, `127.0.0.1`, `::1`), private/LAN ranges, link-local, CGNAT, `.local` mDNS names, and Windows UNC paths are refused, as are non-HTTP schemes like `ftp://` and `data:`.
  225. This matters because the `url` argument is attacker-reachable in the normal case: an agent driving this server can be steered by the content it reads, so a URL it passes in is not necessarily one the user chose. Without the restriction the server is a proxy into whatever network it happens to sit on.
  226. The check runs on the resolved address, not just the text, so a public hostname that resolves to `10.0.0.5` is refused too — and **every hop of a redirect chain is re-checked**, since a public URL answering `302 Location: http://127.0.0.1/` would otherwise walk straight past a first-hop-only check.
  227. ```bash
  228. # Serving videos from a NAS or a local dev server? Opt back in:
  229. MCP_ALLOW_PRIVATE_URLS=1
  230. ```
  231. Cloud instance metadata endpoints (`169.254.169.254`, Azure's `168.63.129.16`, and friends) stay blocked **even with that set** — there is no legitimate video there, and they are what an SSRF is usually after.
  232. Known limitation: the address is checked at resolution time, not at connection time, so DNS rebinding — a domain answering a public address to the check and a private one to the connection — is not covered. Run the server behind an egress proxy if that is in your threat model.
  233. ### Platform URLs via yt-dlp (YouTube, Instagram, TikTok, …)
  234. Single-video pages on major platforms route through [yt-dlp](https://github.com/yt-dlp/yt-dlp) (`pip install yt-dlp` — required for these URLs). Playlists, channels, and profile pages are rejected by design; pass individual video URLs (batch them with `analyze_videos`).
  235. - **Transcript**: native captions are preferred and free — uploaded subtitles first, auto-generated captions as fallback (rolling-window duplication is collapsed). `WHISPER_LANGUAGE` (e.g. `pt`) is also used to pick the caption language. Videos with no captions at all fall through to the normal Whisper chain.
  236. - **Metadata**: title, duration, uploader/channel, view count, upload date, and chapters — no download needed.
  237. - **Download**: capped at 1080p (frames/OCR don't need more), live streams are skipped, and DASH audio+video is merged with the bundled `ffmpeg-static` (no system ffmpeg required).
  238. - **Cookies** — Instagram and age-restricted videos usually require a logged-in session:
  239. | Env var | What it does | Example |
  240. |---------|-------------|---------|
  241. | `YTDLP_COOKIES` | Cookie file (Netscape format), wins when both are set | `C:/secrets/cookies.txt` |
  242. | `YTDLP_COOKIES_FROM_BROWSER` | Extract cookies from an installed browser | `chrome`, `edge`, `firefox` |
  243. > Browser cookie extraction requires the browser to be **closed** on Windows (the cookie database is locked while it runs). If that's inconvenient, export a `cookies.txt` once (e.g. with a "Get cookies.txt" browser extension) and point `YTDLP_COOKIES` at it. Private/age-restricted videos without valid cookies don't crash the tool — the yt-dlp `ERROR:` line surfaces in `warnings[]`.
  244. ### TwelveLabs Pegasus (optional)
  245. Set the `TWELVELABS_API_KEY` environment variable to analyze direct video URLs with [TwelveLabs](https://twelvelabs.io) **Pegasus**. Pegasus analyzes the video server-side (visuals **and** its own audio) and returns an **AI-generated, timestamped transcript** plus an AI summary as text — capabilities the `DirectAdapter` can't provide (a raw `.mp4` URL has no transcript or summary on its own), and with **no Whisper key required**.
  246. The transcript is best-effort LLM output, not a deterministic ASR dump: Pegasus is *prompted* to emit `[MM:SS] line` rows, and lines that don't match that shape are dropped, so wording and exact timestamps depend on the model's prompt adherence. Failures (bad key, timeout, API error) surface in the tool's `warnings[]` rather than silently returning an empty transcript.
  247. The biggest win is on the text-only paths: `get_transcript` and `get_metadata` return a Pegasus transcript and summary for direct URLs — a few KB of text, no frame images, no per-frame token cost. `analyze_video` at `detail: "standard"`/`"detailed"` still extracts frames in addition (use `detail: "brief"` to stay text-only).
  248. > **Long videos**: the summary and full transcript share a single capped completion (`max_tokens` = 16384), so for very long videos the transcript may be truncated. For multi-hour content, chunking by time window is the better approach.
  249. It's fully opt-in and non-breaking: when `TWELVELABS_API_KEY` is set the `TwelveLabsAdapter` handles direct video URLs (it registers the public URL with TwelveLabs — no upload); when it's unset, the `DirectAdapter` handles them exactly as before. Loom URLs are unaffected. Get a key at [playground.twelvelabs.io](https://playground.twelvelabs.io).
  250. ### Transcription (Whisper fallback)
  251. When a source has no native transcript (no sidecar `.vtt`/`.srt`, no embedded subtitles, no platform captions), the audio track is transcribed with Whisper via a graceful fallback chain (in execution order):
  252. > **Silent tracks**: before any Whisper run, the audio is probed with ffmpeg `volumedetect` (first 2 minutes). A present-but-mute track — common in muted Reels/Stories — skips transcription entirely and emits a warning that the empty transcript is **expected content, not an error**, saving a pointless Whisper run.
  253. 1. **@huggingface/transformers** (JS-native, zero external deps) — **opt-in only**: this strategy runs *first*, but **only when `WHISPER_HF_MODEL` is explicitly set**. When it's unset (the default) the strategy is skipped entirely, so the CLI below wins and its `WHISPER_MODEL`/`WHISPER_LANGUAGE` settings are never silently overridden.
  254. 2. **`whisper` CLI** — used when a `whisper` executable is found (`pip install -U openai-whisper`). Point `WHISPER_BIN` at the executable if it isn't on `PATH`. Model via `WHISPER_MODEL`, language via `WHISPER_LANGUAGE`. The bundled `ffmpeg-static` is put on the CLI's `PATH` automatically, so no system ffmpeg is required.
  255. 3. **OpenAI Whisper API** — used when `OPENAI_API_KEY` is set.
  256. > **No backend configured?** If none of the three is available (no `whisper` on `PATH`/`WHISPER_BIN`, no `OPENAI_API_KEY`, no `WHISPER_HF_MODEL`), transcription tools return an empty transcript **with a warning telling you how to enable one** — rather than a silent "no transcript". Install `openai-whisper` or set one of the keys above. (The CLI is spawned with `PYTHONUTF8=1` so non-English/CJK transcripts don't crash the Python process on Windows.)
  257. | Env var | Applies to | Default | Example |
  258. |---------|-----------|---------|---------|
  259. | `WHISPER_MODEL` | `whisper` CLI | `tiny` | `small`, `medium` |
  260. | `WHISPER_LANGUAGE` | `whisper` CLI / OpenAI API | auto-detect | `pt`, `en`, `es` |
  261. | `WHISPER_PROMPT` | `whisper` CLI / OpenAI API | — | `Doha, Smiles, Livelo, Latam, milheiro` |
  262. | `WHISPER_BIN` | `whisper` CLI | `whisper` (on PATH) | `C:/.../Scripts/whisper.exe` |
  263. | `WHISPER_DEVICE` | `whisper` CLI (sent only if set) | — | `cuda`, `cpu` |
  264. | `WHISPER_COMPUTE` | `whisper-ctranslate2` only | — | `float16`, `int8_float16`, `int8` |
  265. | `WHISPER_BEAM_SIZE` | `whisper` CLI (sent only if set) | — | `5` |
  266. | `WHISPER_WORD_TIMESTAMPS` | `whisper` CLI (sent only if set) | off | `1` |
  267. | `WHISPER_HF_MODEL` | HF transformers (opt-in) | — (strategy off) | `Xenova/whisper-small` |
  268. | `OPENAI_API_KEY` | OpenAI API | — | `sk-…` |
  269. > The default `tiny` model is fast but weak for non-English audio. For Portuguese (or other non-English) sources, install the CLI and set `WHISPER_MODEL=small` (or `medium`) + `WHISPER_LANGUAGE=pt` for much better accuracy. Add `WHISPER_PROMPT` with a domain glossary (brand/place names) to fix proper nouns. You can also override `model`/`language`/`initialPrompt` **per call** on `analyze_video` / `get_transcript` / `analyze_videos` — no restart needed.
  270. >
  271. > **GPU (faster-whisper):** `whisper-ctranslate2` (`pip install -U whisper-ctranslate2`) is a drop-in CLI with the same flags plus `--device cuda` / `--compute_type` / `--beam_size`. Point `WHISPER_BIN` at it and set `WHISPER_DEVICE=cuda` (+ optionally `WHISPER_COMPUTE=float16`). These GPU flags are **env-gated** — they're only passed when set, so plain `openai-whisper` (which rejects `--compute_type`) keeps working when they're unset.
  272. >
  273. > **Windows note:** pip installs `whisper.exe` into the Python `Scripts/` dir, which is often **not** on the `PATH` that GUI-launched MCP clients inherit. If transcripts come back empty, set `WHISPER_BIN` to the full path of `whisper.exe`.
  274. ### Frame Extraction Strategies
  275. Frame extraction uses a two-strategy fallback chain — no single dependency is required:
  276. | Strategy | How it works | Speed | Requirements |
  277. |----------|-------------|-------|-------------|
  278. | **yt-dlp + ffmpeg** (primary) | Downloads video, extracts frames via scene detection | Fast, precise | [yt-dlp](https://github.com/yt-dlp/yt-dlp) (`pip install yt-dlp`) |
  279. | **Browser** (fallback) | Opens video in headless Chrome, seeks to timestamps, takes screenshots | Slower, no download needed | Chrome or Chromium installed |
  280. The fallback is automatic — if yt-dlp is not available, the server tries browser-based extraction via `puppeteer-core`. If neither is available, analysis still returns transcript + metadata + comments, just no frames.
  281. ### Post-Processing Pipeline
  282. After frame extraction, the pipeline automatically applies:
  283. | Step | What it does | Why |
  284. |------|-------------|-----|
  285. | **Frame deduplication** | Removes near-identical consecutive frames using perceptual hashing (dHash + Hamming distance) | Screencasts often have long static moments — dedup removes redundant frames, saving tokens |
  286. | **OCR** | Extracts text visible on screen from each frame (via tesseract.js). Each frame is first preprocessed — grayscale + 2× upscale + contrast normalization + sharpen — which materially improves accuracy on stylized overlays (prices, dates, coupons, CTAs). | Captures code, error messages, terminal output, UI text that the transcript doesn't cover |
  287. | **Annotated timeline** | Merges transcript timestamps + frame timestamps + OCR text into a single chronological view | Gives the AI a unified "what was said, what changed visually, and what text appeared" at each moment |
  288. The OCR step requires `tesseract.js` (included as a dependency). If it fails to load, analysis continues without OCR — no frames or transcript are lost. OCR preprocessing is on by default; set `MCP_OCR_PREPROCESS=0` to OCR the raw frames instead.
  289. OCR always reads the **full-resolution** frame, not the copy emitted to the client. The two have different jobs: the emitted frame is capped for token cost, while recognition needs every pixel it can get.
  290. ### Frame size (dense UI captures)
  291. Emitted frames are capped at 800 px wide, which suits the common case — talking-head clips, Reels, bug repros — where the subject fills the frame.
  292. It is the wrong size for a **dense UI capture**: a terminal, dashboard, IDE or spreadsheet recording, where the meaning lives in small text. An unscaled 1920×1080 screen recording lands at 800×450, and a 15 px UI font drops below what a vision model can resolve.
  293. Pass `maxWidth` per call to keep more (or all) of the source resolution — `0` disables the cap:
  294. ```jsonc
  295. get_frames(url, { maxFrames: 8, maxWidth: 0 }) // source resolution
  296. get_frame_at(url, "2:14", { maxWidth: 1920 })
  297. analyze_video(url, { detail: "standard", maxWidth: 1568 })
  298. ```
  299. Supported on `analyze_video`, `analyze_videos`, `analyze_moment`, `get_frames`, `get_frame_at` and `get_frame_burst`, and on the CLI as `--max-width <px>`.
  300. Native frames cost several times more context than the default, so raise the cap deliberately — `get_frames` returns up to 20 frames and `analyze_video` at `detailed` up to 60.
  301. | Variable | Applies to | Default | Notes |
  302. |---|---|---|---|
  303. | `MCP_FRAME_MAX_WIDTH` | Emitted frame width, in px | `800` | `0` (or `native`/`full`/`original`) disables the cap. A per-call `maxWidth` wins over it |
  304. | `MCP_FRAME_JPEG_QUALITY` | Emitted frame JPEG quality | `70` | Raise it when thin glyphs matter; env only, there is no per-call quality parameter. Values outside 1–100 fall back |
  305. | `MCP_CACHE_DIR` | Root for the tessdata cache and the CLI's default `--out` | per-user cache dir | Absolute paths only (a relative value is ignored). Use it when `$HOME` is read-only or absent — a hardened container, `ProtectHome=`, a quota'd home. The published Docker image sets it to `/tmp/mcp-video-analyzer-cache` so `--read-only --tmpfs /tmp` works out of the box |
  306. | `MCP_ALLOW_PRIVATE_URLS` | Reaching private/loopback network addresses | off | `1` allows `localhost`, LAN addresses (`192.168.x`, `10.x`, …), `.local` names and UNC paths. Off by default — see [Network destinations](#network-destinations) below. **Cloud metadata endpoints stay blocked either way** |
  307. A value either variable can't use — `1e3`, `1920px`, a quality of `150` — is rejected with a one-time warning on stderr and the default applies. It is not silently accepted: the whole point of the setting is to escape a downscale that otherwise looks like a normal result.
  308. Prefer the per-call parameter: the server starts once per session, so an environment variable cannot differ between an overview of a YouTube clip and a close read of a screen recording. The width a call actually uses is part of the cache and sidecar key, so analyzing the same video at 800 px and then at `maxWidth: 0` re-runs the pipeline instead of returning the first result twice.
  309. ## Complementary Tools
  310. ### Chrome DevTools MCP
  311. For **live web debugging** alongside video analysis, pair this server with the [Chrome DevTools MCP](https://github.com/anthropics/anthropic-quickstarts/tree/main/mcp-devtools):
  312. ```bash
  313. claude mcp add chrome-devtools npx @anthropic-ai/mcp-devtools@latest
  314. ```
  315. **When to use each:**
  316. | Scenario | Tool |
  317. |----------|------|
  318. | Bug report recorded as a Loom video | `mcp-video-analyzer` — extract transcript, frames, and error text from the recording |
  319. | Live debugging a web page | Chrome DevTools MCP — inspect DOM, console, network, take screenshots |
  320. | Video shows UI issue, need to reproduce it | Use both: analyze the video first, then open the page in Chrome DevTools to reproduce |
  321. The two MCPs complement each other: video analyzer understands **recorded** content, DevTools interacts with **live** pages.
  322. ## Example Output
  323. The [`examples/loom-demo/`](examples/loom-demo/) folder contains **real outputs** from analyzing a public Loom video ([Boost In-App Demo Video](https://www.loom.com/share/bdebdfe44b294225ac718bad241a94fe), 2:55).
  324. | File | What it shows |
  325. |------|--------------|
  326. | [`metadata.json`](examples/loom-demo/metadata.json) | Title, duration, platform |
  327. | [`transcript.json`](examples/loom-demo/transcript.json) | 42 timestamped entries with speaker IDs |
  328. | [`timeline.json`](examples/loom-demo/timeline.json) | Unified chronological view (transcript + frames merged) |
  329. | [`moment-transcript-0m30s-0m45s.json`](examples/loom-demo/moment-transcript-0m30s-0m45s.json) | Filtered transcript for `analyze_moment` (0:30–0:45) |
  330. | [`full-analysis.json`](examples/loom-demo/full-analysis.json) | Complete `analyze_video` output |
  331. **Frame images** (19 total in [`examples/loom-demo/frames/`](examples/loom-demo/frames/)):
  332. - `scene_*.jpg` — scene-change detection (key visual transitions)
  333. - `dense_*.jpg` — 1fps dense sampling (every 10th frame saved as sample)
  334. - `burst_*.jpg` — burst extraction for moment analysis (0:30–0:45)
  335. > **Regenerate after changes:** `npx tsx examples/generate.ts` — requires yt-dlp + network access.
  336. ## Development
  337. ```bash
  338. # Install dependencies
  339. npm install
  340. # Run all checks (format, lint, typecheck, knip, tests)
  341. npm run check
  342. # Audit dependencies. `security` covers what the published package ships and
  343. # is a blocking CI job; `security:all` adds devDependencies. Both also run on
  344. # a weekly cron, because npm audit reads a live advisory database.
  345. npm run security
  346. # Build
  347. npm run build
  348. # Run E2E tests (requires network; add WHISPER_E2E=1 to include the
  349. # transcription outcome test — needs a whisper CLI installed)
  350. npm run test:e2e
  351. # Just the video-format matrix: a real clip per container/codec
  352. # (mp4/h264+hevc+av1, webm, mkv, mov, avi, m4v, mpeg, mpg, m2ts, mts,
  353. # 3gp, ogv, flv, wmv) decoded end to end. ~15s on a warm cache; the
  354. # first run fetches ~7MB of tesseract traineddata.
  355. npm run test:formats
  356. # Build + boot the real MCP server/CLI (seconds)
  357. npm run test:smoke
  358. # Everything: check → e2e → smoke → verify-package
  359. npm run verify-all
  360. # Open MCP Inspector for manual testing
  361. npm run inspect
  362. ```
  363. ## Architecture
  364. ```
  365. src/
  366. ├── index.ts # Entry point (shebang + stdio)
  367. ├── server.ts # FastMCP server + tool registration
  368. ├── tools/ # MCP tool definitions (7 tools)
  369. │ ├── analyze-video.ts # Full analysis with detail levels + caching
  370. │ ├── analyze-moment.ts # Deep-dive on a time range
  371. │ ├── get-transcript.ts # Transcript-only with Whisper fallback
  372. │ ├── get-metadata.ts # Metadata + comments + chapters
  373. │ ├── get-frames.ts # Frames-only (scene-change or dense)
  374. │ ├── get-frame-at.ts # Single frame at timestamp
  375. │ └── get-frame-burst.ts # N frames in a time range
  376. ├── adapters/ # Source-specific logic
  377. │ ├── adapter.interface.ts # IVideoAdapter interface + registry
  378. │ ├── loom.adapter.ts # Loom: authless GraphQL
  379. │ ├── local-file.adapter.ts # Local files: absolute path or file:// URI
  380. │ ├── twelvelabs.adapter.ts # TwelveLabs Pegasus: transcript + AI summary (opt-in)
  381. │ └── direct.adapter.ts # Direct URL: any mp4/webm link
  382. ├── processors/ # Shared processing
  383. │ ├── frame-extractor.ts # ffmpeg scene detection + dense + burst extraction
  384. │ ├── browser-frame-extractor.ts # Headless Chrome fallback for frames
  385. │ ├── audio-transcriber.ts # Whisper fallback (HF transformers → CLI → OpenAI)
  386. │ ├── image-optimizer.ts # sharp resize/compress
  387. │ ├── frame-dedup.ts # Perceptual dedup (dHash + Hamming distance)
  388. │ ├── frame-ocr.ts # OCR text extraction (tesseract.js)
  389. │ └── annotated-timeline.ts # Unified timeline (transcript + frames + OCR)
  390. ├── config/
  391. │ └── detail-levels.ts # brief / standard / detailed config
  392. ├── utils/
  393. │ ├── cache.ts # In-memory TTL cache with LRU eviction
  394. │ ├── field-filter.ts # Selective field filtering for responses
  395. │ ├── url-detector.ts # Platform detection from URL
  396. │ ├── vtt-parser.ts # WebVTT → transcript entries
  397. │ └── temp-files.ts # Temp directory management
  398. └── types.ts # Shared TypeScript interfaces
  399. ```
  400. ### Burst timing
  401. Burst extraction accepts fractional timestamps (for example, `0:01.1`). The
  402. FFmpeg path selects up to the requested count of existing source frames within
  403. `[from, to)`, without duplicating frames to satisfy an excessive sampling rate.
  404. Processor results retain each selected frame's video-relative presentation time,
  405. including fractional seconds. Browser fallback preserves fractional seek targets
  406. and separate screenshot files; its times are requested seeks, not measured source
  407. frame PTS. Browser seeking is not a frame-accurate substitute for local decoding.
  408. `get_frame_burst` returns a JSON text block containing
  409. `{ frameCount, from, to, warnings, frames: [{ time, timingOrigin }] }`, followed
  410. by images in exactly the same order as `frames`. `timingOrigin: "source-pts"`
  411. means measured video-relative FFmpeg presentation time; `"seek-target"` means
  412. requested browser seek time. Empty/degraded results contain `frames: []`.
  413. ## License
  414. MIT
src/utils/ssrf-guard.test.ts · Bundled script · 265 lines · 2 findings marked
  1. import { afterEach, describe, expect, it, vi } from 'vitest';
  2. import {
  3. BLOCKED_RANGE_COUNT,
  4. assertPublicUrl,
  5. isBlockedAddress,
  6. isBlockedHostLiteral,
  7. } from './ssrf-guard.js';
  8. // A failing assertion before an inline unstub would otherwise leave the opt-in
  9. // set for every later test in this file — which is how a single real failure
  10. // cascades into unrelated ones.
  11. afterEach(() => {
  12. vi.unstubAllEnvs();
  13. });
  14. describe('isBlockedAddress', () => {
  15. // Every row here is a destination some real advisory reached. The bypass
  16. // rows matter most: they are the ones a "block RFC1918 + loopback" list
  17. // passes, which is what Gitea's GHSA-2r5c-gw76-rh3w scored 9.6 for.
  18. it.each([
  19. // the reporter's own PoC
  20. ['127.0.0.1', 'private'],
  21. ['127.1.2.3', 'private'],
  22. // RFC1918
  23. ['10.0.0.1', 'private'],
  24. ['172.16.0.1', 'private'],
  25. ['192.168.1.5', 'private'],
  26. // mcp-searxng CVE-2026-54689: 0.0.0.0 reaches loopback-bound services
  27. ['0.0.0.0', 'private'],
  28. // Gitea GHSA-2r5c-gw76-rh3w: ranges Go's net.IP.IsPrivate() misses
  29. ['100.64.0.1', 'private'], // CGNAT
  30. ['172.32.0.1', 'private'],
  31. ['198.18.0.1', 'private'],
  32. ['192.0.0.1', 'private'],
  33. ['255.255.255.255', 'private'],
  34. ['224.0.0.1', 'private'],
  35. // metadata — a separate verdict, because the opt-in must not unlock it
  36. ['169.254.169.254', 'metadata'],
  37. ['168.63.129.16', 'metadata'], // Azure WireServer
  38. ['100.100.100.200', 'metadata'], // Alibaba
  39. ['169.254.1.1', 'private'], // link-local but not metadata
  40. // IPv6
  41. ['::1', 'private'],
  42. ['::', 'private'],
  43. ['fc00::1', 'private'],
  44. ['fd12:3456::1', 'private'],
  45. ['fe80::1', 'private'],
  46. ['2002::1', 'private'], // 6to4
  47. ['2001::1', 'private'], // Teredo
  48. ['2001:db8::1', 'private'],
  49. ['fd00:ec2::254', 'metadata'],
  50. ['64:ff9b::8.8.8.8', 'private'], // NAT64 prefix is never a video host
  51. // NAT64/6to4 reaching the AWS IMDS — 169.254.169.254 embedded as IPv6.
  52. // `metadata`, not `private`: this IS the metadata service, and `private` is
  53. // the verdict MCP_ALLOW_PRIVATE_URLS unlocks.
  54. ['64:ff9b::a9fe:a9fe', 'metadata'],
  55. ['2002:a9fe:a9fe::', 'metadata'],
  56. // mcp-searxng CVE-2026-54689: IPv4-mapped IPv6 canonicalization bypass
  57. ['::ffff:127.0.0.1', 'private'],
  58. ['::ffff:169.254.169.254', 'metadata'],
  59. // ...and the spelling production actually sees. `new URL()` normalizes an
  60. // IPv4-mapped literal to its hex form, so the two dotted rows above are the
  61. // only ones a string match catches and the only ones that never arrive.
  62. ['::ffff:7f00:1', 'private'],
  63. ['::ffff:a9fe:a9fe', 'metadata'],
  64. // Deprecated IPv4-compatible (`::/96`) embeds a v4 address the same way.
  65. ['::7f00:1', 'private'],
  66. ['::a9fe:a9fe', 'metadata'],
  67. ])('blocks %s as %s', (address, reason) => {
  68. expect(isBlockedAddress(address)).toBe(reason);
  69. });
  70. it.each([
  71. ['8.8.8.8'],
  72. ['1.1.1.1'],
  73. ['93.184.216.34'],
  74. ['172.15.0.1'], // just below the RFC1918 block
  75. ['172.64.0.1'], // just above 172.32.0.0/11, which ends at 172.63.255.255
  76. ['100.63.255.255'], // just below CGNAT
  77. ['100.128.0.1'], // just above CGNAT
  78. ['2606:4700::1111'],
  79. ])('allows the public address %s', (address) => {
  80. expect(isBlockedAddress(address)).toBeNull();
  81. });
  82. it('returns null for things that are not IP addresses', () => {
  83. expect(isBlockedAddress('example.com')).toBeNull();
  84. expect(isBlockedAddress('')).toBeNull();
  85. expect(isBlockedAddress('999.999.999.999')).toBeNull();
  86. });
  87. it('alternate spellings of a metadata address are still metadata', () => {
  88. // A string-keyed set would miss both of these while the canonical form hit.
  89. expect(isBlockedAddress('fd00:0ec2:0000:0000:0000:0000:0000:0254')).toBe('metadata');
  90. expect(isBlockedAddress('::ffff:168.63.129.16')).toBe('metadata');
  91. });
  92. it('scanned a non-empty range table', () => {
  93. // Guards the "test that cannot fail" case: if BLOCKED_RANGES were emptied,
  94. // every row above would return null and only this assertion would notice.
  95. expect(BLOCKED_RANGE_COUNT).toBeGreaterThanOrEqual(20);
  96. });
  97. });
  98. describe('isBlockedHostLiteral', () => {
  99. it.each([
  100. ['localhost', 'private'],
  101. ['LOCALHOST', 'private'],
  102. ['api.localhost', 'private'],
  103. ['nas.local', 'private'], // mDNS resolves on the local link only
  104. ['127.0.0.1', 'private'],
  105. ['[::1]', 'private'], // new URL() keeps IPv6 hostnames bracketed
  106. ['169.254.169.254', 'metadata'],
  107. ])('blocks the host literal %s', (hostname, reason) => {
  108. expect(isBlockedHostLiteral(hostname)).toBe(reason);
  109. });
  110. it('lets a public hostname through — resolution is assertPublicUrl’s job', () => {
  111. expect(isBlockedHostLiteral('example.com')).toBeNull();
  112. expect(isBlockedHostLiteral('videos.cdn.example.com')).toBeNull();
  113. });
  114. });
  115. describe('assertPublicUrl', () => {
  116. it('rejects the reporter’s PoC URL', async () => {
  117. await expect(assertPublicUrl('http://127.0.0.1:8931/x.mp4')).rejects.toThrow(
  118. /private or loopback/i,
  119. );
  120. });
  121. it('names the env var in the private-address message', async () => {
  122. // The message is the only route a LAN user has to the opt-in.
  123. await expect(assertPublicUrl('http://192.168.1.5/clip.mp4')).rejects.toThrow(
  124. /MCP_ALLOW_PRIVATE_URLS=1/,
  125. );
  126. });
  127. it.each(['ftp://example.com/x.mp4', 'data:text/plain,x.mp4', 'file:///etc/passwd.mp4'])(
  128. 'rejects the non-http scheme in %s',
  129. async (url) => {
  130. await expect(assertPublicUrl(url)).rejects.toThrow(/only http/i);
  131. },
  132. );
  133. it('rejects a malformed URL', async () => {
  134. await expect(assertPublicUrl('not-a-url')).rejects.toThrow(/valid URL/i);
  135. });
  136. it('allows a public IP literal without resolving it', async () => {
  137. await expect(assertPublicUrl('http://93.184.216.34/video.mp4')).resolves.toBeUndefined();
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 150 on GitHub
  138. });
  139. it('blocks a hostname that RESOLVES to a private address', async () => {
  140. // The literal check passes here — this is the case only DNS resolution
  141. // catches, and the one mcp-searxng's GHSA-mrvx-jmjw-vggc was filed for.
  142. vi.doMock('node:dns/promises', () => ({
  143. lookup: vi.fn().mockResolvedValue([{ address: '10.1.2.3', family: 4 }]),
  144. }));
  145. vi.resetModules();
  146. const { assertPublicUrl: guard } = await import('./ssrf-guard.js');
  147. await expect(guard('http://internal.example.com/x.mp4')).rejects.toThrow(
  148. /private or loopback/i,
  149. );
  150. vi.doUnmock('node:dns/promises');
  151. vi.resetModules();
  152. });
  153. it('blocks when ANY resolved address is private, not just the first', async () => {
  154. vi.doMock('node:dns/promises', () => ({
  155. lookup: vi.fn().mockResolvedValue([
  156. { address: '93.184.216.34', family: 4 },
  157. { address: '127.0.0.1', family: 4 },
  158. ]),
  159. }));
  160. vi.resetModules();
  161. const { assertPublicUrl: guard } = await import('./ssrf-guard.js');
  162. await expect(guard('http://split-horizon.example.com/x.mp4')).rejects.toThrow(
  163. /private or loopback/i,
  164. );
  165. vi.doUnmock('node:dns/promises');
  166. vi.resetModules();
  167. });
  168. it('rejects a hostname that cannot be resolved', async () => {
  169. vi.doMock('node:dns/promises', () => ({
  170. lookup: vi.fn().mockRejectedValue(new Error('ENOTFOUND')),
  171. }));
  172. vi.resetModules();
  173. const { assertPublicUrl: guard } = await import('./ssrf-guard.js');
  174. await expect(guard('http://nope.invalid/x.mp4')).rejects.toThrow(/could not be resolved/i);
  175. vi.doUnmock('node:dns/promises');
  176. vi.resetModules();
  177. });
  178. });
  179. describe('MCP_ALLOW_PRIVATE_URLS opt-in', () => {
  180. it('allows a private address when set', async () => {
  181. // Without this the whole suite would still pass with the opt-in dead —
  182. // every other assertion here is a rejection.
  183. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  184. await expect(assertPublicUrl('http://192.168.1.5/clip.mp4')).resolves.toBeUndefined();
  185. await expect(assertPublicUrl('http://127.0.0.1:8080/clip.mp4')).resolves.toBeUndefined();
  186. vi.unstubAllEnvs();
  187. });
  188. it('still blocks cloud metadata when set', async () => {
  189. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  190. await expect(assertPublicUrl('http://169.254.169.254/latest.mp4')).rejects.toThrow(
  191. /metadata endpoint/i,
  192. );
  193. await expect(assertPublicUrl('http://168.63.129.16/x.mp4')).rejects.toThrow(
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 217 on GitHub
  194. /metadata endpoint/i,
  195. );
  196. vi.unstubAllEnvs();
  197. });
  198. it('still rejects a non-http scheme when set', async () => {
  199. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  200. await expect(assertPublicUrl('file:///etc/passwd.mp4')).rejects.toThrow(/only http/i);
  201. vi.unstubAllEnvs();
  202. });
  203. it('still blocks metadata reached through an embedded-IPv4 spelling', async () => {
  204. // The opt-in unlocks `private`, never `metadata`. An embedded-IPv4 v6
  205. // literal is the same destination as the dotted form, so it must reach the
  206. // same verdict — otherwise the opt-in silently unlocks the IMDS.
  207. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  208. for (const url of [
  209. 'http://[::ffff:169.254.169.254]/latest.mp4', // normalizes to ::ffff:a9fe:a9fe
  210. 'http://[64:ff9b::a9fe:a9fe]/latest.mp4', // NAT64
  211. 'http://[::a9fe:a9fe]/latest.mp4', // deprecated IPv4-compatible
  212. ]) {
  213. await expect(assertPublicUrl(url)).rejects.toThrow(/metadata endpoint/i);
  214. }
  215. vi.unstubAllEnvs();
  216. });
  217. });
  218. describe('embedded-IPv4 IPv6 literals through a real URL', () => {
  219. // `new URL()` rewrites `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]`, so these
  220. // are the only spellings the sinks ever hand to the guard. Asserting the
  221. // dotted form alone is a test that cannot fail.
  222. it.each([
  223. ['http://[::ffff:127.0.0.1]/x.mp4', /private or loopback/i],
  224. ['http://[::ffff:7f00:1]/x.mp4', /private or loopback/i],
  225. ['http://[::ffff:169.254.169.254]/x.mp4', /metadata endpoint/i],
  226. ['http://[::ffff:a9fe:a9fe]/x.mp4', /metadata endpoint/i],
  227. ['http://[::7f00:1]/x.mp4', /private or loopback/i],
  228. ])('refuses %s', async (url, message) => {
  229. await expect(assertPublicUrl(url)).rejects.toThrow(message);
  230. });
  231. it('normalizes the dotted spelling away, which is why the numeric check matters', () => {
  232. // Pins the assumption the rows above rest on. If Node ever stopped
  233. // rewriting these, the guard would still be correct — but this test
  234. // documents why the hex rows exist at all.
  235. expect(new URL('http://[::ffff:169.254.169.254]/').hostname).toBe('[::ffff:a9fe:a9fe]');
  236. });
  237. });
src/utils/url-detector.test.ts · Bundled script · 367 lines · 4 findings marked
  1. import { resolve } from 'node:path';
  2. import { pathToFileURL } from 'node:url';
  3. import { afterEach, describe, expect, it, vi } from 'vitest';
  4. import {
  5. detectPlatform,
  6. extractLoomId,
  7. isVideoSource,
  8. sourceRejectionMessage,
  9. toLocalPath,
  10. } from './url-detector.js';
  11. // Not per-test: an assertion that fails BEFORE an inline `vi.unstubAllEnvs()`
  12. // leaves MCP_ALLOW_PRIVATE_URLS set for every later test in the file, which
  13. // turned one genuine cross-platform failure into three confusing ones on CI.
  14. afterEach(() => {
  15. vi.unstubAllEnvs();
  16. });
  17. describe('detectPlatform', () => {
  18. it('detects Loom share URLs', () => {
  19. expect(detectPlatform('https://www.loom.com/share/abc123def456')).toBe('loom');
  20. });
  21. it('detects Loom share URLs without www', () => {
  22. expect(detectPlatform('https://loom.com/share/abc123def456')).toBe('loom');
  23. });
  24. it('detects Loom embed URLs', () => {
  25. expect(detectPlatform('https://www.loom.com/embed/abc123def456')).toBe('loom');
  26. });
  27. it('detects Loom URLs with query params', () => {
  28. expect(detectPlatform('https://www.loom.com/share/abc123?sid=xyz')).toBe('loom');
  29. });
  30. it('detects direct .mp4 URLs', () => {
  31. expect(detectPlatform('https://example.com/video.mp4')).toBe('direct');
  32. });
  33. it('detects direct .webm URLs', () => {
  34. expect(detectPlatform('https://example.com/video.webm')).toBe('direct');
  35. });
  36. it('detects direct .mov URLs', () => {
  37. expect(detectPlatform('https://example.com/video.mov')).toBe('direct');
  38. });
  39. it('detects direct .avi URLs', () => {
  40. expect(detectPlatform('https://example.com/video.avi')).toBe('direct');
  41. });
  42. it('detects direct .mkv URLs', () => {
  43. expect(detectPlatform('https://example.com/video.mkv')).toBe('direct');
  44. });
  45. it('detects direct .m4v URLs', () => {
  46. expect(detectPlatform('https://example.com/video.m4v')).toBe('direct');
  47. });
  48. it('detects additional direct video container formats', () => {
  49. for (const ext of ['wmv', 'flv', 'mpeg', 'mpg', 'm2ts', 'mts', '3gp', 'ogv']) {
  50. expect(detectPlatform(`https://example.com/video.${ext}`)).toBe('direct');
  51. }
  52. });
  53. it('does not treat .ts (TypeScript) paths as video', () => {
  54. expect(detectPlatform('https://example.com/module.ts')).toBeNull();
  55. expect(detectPlatform('/Users/me/src/index.ts')).toBeNull();
  56. });
  57. it('detects YouTube URLs as ytdlp', () => {
  58. expect(detectPlatform('https://www.youtube.com/watch?v=abc123')).toBe('ytdlp');
  59. expect(detectPlatform('https://www.youtube.com/watch?foo=1&v=abc123')).toBe('ytdlp');
  60. expect(detectPlatform('https://youtube.com/shorts/abc123')).toBe('ytdlp');
  61. expect(detectPlatform('https://m.youtube.com/watch?v=abc123')).toBe('ytdlp');
  62. expect(detectPlatform('https://www.youtube.com/live/abc123')).toBe('ytdlp');
  63. expect(detectPlatform('https://youtu.be/abc123')).toBe('ytdlp');
  64. });
  65. it('detects other yt-dlp platforms as ytdlp', () => {
  66. expect(detectPlatform('https://vimeo.com/123456789')).toBe('ytdlp');
  67. expect(detectPlatform('https://www.tiktok.com/@user/video/1234567890')).toBe('ytdlp');
  68. expect(detectPlatform('https://www.instagram.com/reel/AbC123/')).toBe('ytdlp');
  69. expect(detectPlatform('https://www.instagram.com/p/AbC123/')).toBe('ytdlp');
  70. expect(detectPlatform('https://x.com/user/status/1234567890')).toBe('ytdlp');
  71. expect(detectPlatform('https://twitter.com/user/status/1234567890')).toBe('ytdlp');
  72. expect(detectPlatform('https://www.twitch.tv/videos/123456789')).toBe('ytdlp');
  73. expect(detectPlatform('https://www.twitch.tv/streamer/clip/SomeClip-abc')).toBe('ytdlp');
  74. expect(detectPlatform('https://clips.twitch.tv/SomeClip-abc')).toBe('ytdlp');
  75. expect(detectPlatform('https://www.dailymotion.com/video/x8abc12')).toBe('ytdlp');
  76. expect(detectPlatform('https://www.facebook.com/watch?v=1234567890')).toBe('ytdlp');
  77. expect(detectPlatform('https://www.facebook.com/somepage/videos/1234567890')).toBe('ytdlp');
  78. expect(detectPlatform('https://fb.watch/abc123/')).toBe('ytdlp');
  79. });
  80. it('rejects playlist/channel/profile pages (single videos only)', () => {
  81. expect(detectPlatform('https://www.youtube.com/playlist?list=PL123')).toBeNull();
  82. expect(detectPlatform('https://www.youtube.com/@somechannel')).toBeNull();
  83. expect(detectPlatform('https://www.instagram.com/someuser/')).toBeNull();
  84. expect(detectPlatform('https://www.twitch.tv/streamername')).toBeNull();
  85. expect(detectPlatform('https://vimeo.com/user12345')).toBeNull();
  86. });
  87. it('rejects listing pages that lack a video id', () => {
  88. expect(detectPlatform('https://www.instagram.com/reels/')).toBeNull(); // Reels feed
  89. expect(detectPlatform('https://www.facebook.com/somepage/videos/')).toBeNull(); // videos tab
  90. expect(detectPlatform('https://www.facebook.com/reel/')).toBeNull();
  91. expect(detectPlatform('https://www.facebook.com/watch/')).toBeNull();
  92. });
  93. it('accepts id-bearing variants of the tightened patterns', () => {
  94. expect(detectPlatform('https://www.instagram.com/reels/AbC12_3/')).toBe('ytdlp');
  95. expect(detectPlatform('https://www.facebook.com/reel/1234567890')).toBe('ytdlp');
  96. expect(detectPlatform('https://www.facebook.com/somepage/videos/9876543210/')).toBe('ytdlp');
  97. });
  98. it('returns null for HTML pages', () => {
  99. expect(detectPlatform('https://example.com/page.html')).toBeNull();
  100. });
  101. it('returns null for non-video URLs', () => {
  102. expect(detectPlatform('https://example.com/some-page')).toBeNull();
  103. });
  104. it('returns null for invalid URLs', () => {
  105. expect(detectPlatform('not-a-url')).toBeNull();
  106. });
  107. it('returns null for empty string', () => {
  108. expect(detectPlatform('')).toBeNull();
  109. });
  110. it('handles case-insensitive extensions', () => {
  111. expect(detectPlatform('https://example.com/VIDEO.MP4')).toBe('direct');
  112. });
  113. it('detects absolute POSIX paths to video files as local', () => {
  114. expect(detectPlatform('/Users/me/Movies/clip.mp4')).toBe('local');
  115. expect(detectPlatform('/tmp/video.webm')).toBe('local');
  116. expect(detectPlatform('/tmp/recording.mkv')).toBe('local');
  117. expect(detectPlatform('/tmp/camera.mts')).toBe('local');
  118. });
  119. it('detects file:// URIs as local', () => {
  120. // Derive the URI from a real absolute path so it is valid on the host OS —
  121. // a hardcoded POSIX `file://` literal throws under fileURLToPath on Windows.
  122. expect(detectPlatform(pathToFileURL(resolve('Movies', 'clip.mp4')).href)).toBe('local');
  123. expect(detectPlatform(pathToFileURL(resolve('tmp', 'video.mov')).href)).toBe('local');
  124. });
  125. // Windows drive paths are only absolute on win32; guard so the suite stays
  126. // green on POSIX CI too.
  127. (process.platform === 'win32' ? it : it.skip)('detects Windows drive paths as local', () => {
  128. expect(detectPlatform('C:\\Users\\me\\clip.mp4')).toBe('local');
  129. expect(detectPlatform('C:\\Users\\me\\notes.txt')).toBeNull();
  130. });
  131. it('returns null for absolute paths that are not video files', () => {
  132. expect(detectPlatform('/Users/me/notes.txt')).toBeNull();
  133. expect(detectPlatform('/tmp/page.html')).toBeNull();
  134. });
  135. it('returns null for relative paths', () => {
  136. expect(detectPlatform('./video.mp4')).toBeNull();
  137. expect(detectPlatform('video.mp4')).toBeNull();
  138. expect(detectPlatform('../movies/clip.mp4')).toBeNull();
  139. });
  140. });
  141. // GHSA-hpmc-4g74-v53v. Every URL below classified as 'direct' before the fix —
  142. // the extension was the only thing checked, so the destination never was.
  143. // Proven against the pre-fix code, not asserted: see the PoC table below.
  144. describe('detectPlatform — blocked network destinations', () => {
  145. it.each([
  146. ['http://127.0.0.1:8931/x.mp4'], // the reporter's own PoC
  147. ['http://127.0.0.1/video.mp4'],
  148. ['http://localhost:8080/clip.mp4'],
  149. ['http://LocalHost/clip.mp4'],
  150. ['http://api.localhost/clip.mp4'],
  151. ['http://nas.local/movie.mkv'],
  152. ['http://[::1]:8080/x.mp4'],
  153. ['http://192.168.1.5/clip.mp4'],
  154. ['http://10.0.0.7/clip.mp4'],
  155. ['http://172.16.4.2/clip.mp4'],
  156. ['http://0.0.0.0:8080/x.mp4'],
  157. ['http://100.64.0.1/x.mp4'],
  158. ['https://169.254.169.254/latest.mp4'], // cloud metadata
  159. ['http://168.63.129.16/x.mp4'],
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 188 on GitHub
  160. ['http://user:pass@10.0.0.5/x.mp4'], // credentials must not smuggle a host past
  161. ])('rejects %s', (url) => {
  162. expect(detectPlatform(url)).toBeNull();
  163. expect(isVideoSource(url)).toBe(false);
  164. });
  165. it.each([
  166. ['ftp://example.com/video.mp4'],
  167. ['data:text/plain,x.mp4'],
  168. ['gopher://example.com/x.mp4'],
  169. ['blob:https://example.com/abcd.mp4'],
  170. ])('rejects the non-http scheme in %s', (url) => {
  171. expect(detectPlatform(url)).toBeNull();
  172. });
  173. it('still accepts public hosts that merely look unusual', () => {
  174. expect(detectPlatform('http://93.184.216.34/video.mp4')).toBe('direct');
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 205 on GitHub
  175. expect(detectPlatform('https://cdn.example.com:8443/video.mp4')).toBe('direct');
  176. // 172.15 and 172.64 sit just outside the blocked 172.16/12 and 172.32/11.
  177. expect(detectPlatform('http://172.15.0.1/video.mp4')).toBe('direct');
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 208 on GitHub
  178. expect(detectPlatform('http://172.64.0.1/video.mp4')).toBe('direct');
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 209 on GitHub
  179. });
  180. it('rejects UNC paths, which reach the network over SMB', () => {
  181. // Backslash form is checked on every platform; see isUncPath.
  182. expect(detectPlatform('\\\\attacker.example\\share\\x.mp4')).toBeNull();
  183. });
  184. (process.platform === 'win32' ? it : it.skip)(
  185. 'rejects a file:// URI whose authority makes it a UNC path',
  186. () => {
  187. expect(detectPlatform('file://attacker.example/share/x.mp4')).toBeNull();
  188. },
  189. );
  190. it('lets the operator opt back in with MCP_ALLOW_PRIVATE_URLS', () => {
  191. // Without this the opt-in could be dead code and every assertion above
  192. // would still pass. It must NOT unlock metadata or the scheme check.
  193. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  194. expect(detectPlatform('http://192.168.1.5/clip.mp4')).toBe('direct');
  195. expect(detectPlatform('http://localhost:8080/clip.mp4')).toBe('direct');
  196. expect(detectPlatform('https://169.254.169.254/latest.mp4')).toBeNull();
  197. expect(detectPlatform('ftp://example.com/video.mp4')).toBeNull();
  198. });
  199. // Only on win32: a backslash path is not absolute on POSIX, so it can never
  200. // resolve to a local file there no matter what the opt-in says. The
  201. // *refusal* above is platform-independent; accepting it is not.
  202. (process.platform === 'win32' ? it : it.skip)(
  203. 'accepts an opted-in UNC path as a local file',
  204. () => {
  205. vi.stubEnv('MCP_ALLOW_PRIVATE_URLS', '1');
  206. expect(detectPlatform('\\\\nas.example\\share\\x.mp4')).toBe('local');
  207. },
  208. );
  209. });
  210. describe('sourceRejectionMessage', () => {
  211. it('points a LAN user at the opt-in instead of at a typo hunt', () => {
  212. const message = sourceRejectionMessage('http://192.168.1.5/clip.mp4');
  213. expect(message).toMatch(/private or loopback/i);
  214. expect(message).toMatch(/MCP_ALLOW_PRIVATE_URLS=1/);
  215. });
  216. it('does not offer the opt-in for metadata, which it cannot unlock', () => {
  217. const message = sourceRejectionMessage('https://169.254.169.254/latest.mp4');
  218. expect(message).toMatch(/metadata endpoint/i);
  219. expect(message).not.toMatch(/MCP_ALLOW_PRIVATE_URLS/);
  220. });
  221. it('names the scheme problem rather than the generic shape problem', () => {
  222. expect(sourceRejectionMessage('ftp://example.com/video.mp4')).toMatch(/only http/i);
  223. });
  224. it('names UNC paths', () => {
  225. expect(sourceRejectionMessage('\\\\attacker.example\\share\\x.mp4')).toMatch(/UNC/);
  226. });
  227. it('falls back to the original wording for a genuinely unsupported source', () => {
  228. expect(sourceRejectionMessage('https://example.com/page.html')).toMatch(
  229. /Must be a supported video URL/,
  230. );
  231. expect(sourceRejectionMessage('./relative.mp4')).toMatch(/Must be a supported video URL/);
  232. expect(sourceRejectionMessage(42)).toMatch(/Must be a supported video URL/);
  233. });
  234. });
  235. describe('toLocalPath', () => {
  236. it('returns the path unchanged for absolute POSIX paths', () => {
  237. expect(toLocalPath('/tmp/video.mp4')).toBe('/tmp/video.mp4');
  238. });
  239. it('converts file:// URIs to fs paths', () => {
  240. const abs = resolve('tmp', 'video.mp4');
  241. expect(toLocalPath(pathToFileURL(abs).href)).toBe(abs);
  242. });
  243. it('returns null for HTTP URLs', () => {
  244. expect(toLocalPath('https://example.com/video.mp4')).toBeNull();
  245. });
  246. it('returns null for relative paths', () => {
  247. expect(toLocalPath('./video.mp4')).toBeNull();
  248. expect(toLocalPath('video.mp4')).toBeNull();
  249. });
  250. it('returns null for empty string', () => {
  251. expect(toLocalPath('')).toBeNull();
  252. });
  253. });
  254. describe('isVideoSource', () => {
  255. it('accepts Loom URLs', () => {
  256. expect(isVideoSource('https://loom.com/share/abc123')).toBe(true);
  257. });
  258. it('accepts direct video URLs', () => {
  259. expect(isVideoSource('https://example.com/video.mp4')).toBe(true);
  260. });
  261. it('accepts absolute paths to video files', () => {
  262. expect(isVideoSource('/tmp/video.mp4')).toBe(true);
  263. });
  264. it('accepts file:// URIs to video files', () => {
  265. // Same reason as the detectPlatform case above: a hardcoded POSIX literal
  266. // throws under fileURLToPath on Windows. It used to pass here anyway,
  267. // because the unparsable path fell through to the URL branch and the `.mp4`
  268. // pathname classified it as 'direct' — a file:// URI routed to the HTTP
  269. // downloader. The scheme check removed that fallthrough.
  270. expect(isVideoSource(pathToFileURL(resolve('tmp', 'video.mp4')).href)).toBe(true);
  271. });
  272. it('rejects relative paths', () => {
  273. expect(isVideoSource('./video.mp4')).toBe(false);
  274. });
  275. it('rejects non-video URLs', () => {
  276. expect(isVideoSource('https://example.com/page.html')).toBe(false);
  277. });
  278. it('rejects empty string', () => {
  279. expect(isVideoSource('')).toBe(false);
  280. });
  281. });
  282. describe('extractLoomId', () => {
  283. it('extracts ID from share URL', () => {
  284. expect(extractLoomId('https://www.loom.com/share/abc123def456')).toBe('abc123def456');
  285. });
  286. it('extracts ID from embed URL', () => {
  287. expect(extractLoomId('https://www.loom.com/embed/abc123def456')).toBe('abc123def456');
  288. });
  289. it('extracts ID without query params polluting it', () => {
  290. expect(extractLoomId('https://www.loom.com/share/abc123def456?sid=xyz')).toBe('abc123def456');
  291. });
  292. it('extracts UUID-style IDs', () => {
  293. expect(extractLoomId('https://www.loom.com/share/a1b2c3d4-e5f6-7890-abcd-ef1234567890')).toBe(
  294. 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
  295. );
  296. });
  297. it('returns null for non-Loom URLs', () => {
  298. expect(extractLoomId('https://example.com/video.mp4')).toBeNull();
  299. });
  300. it('returns null for empty string', () => {
  301. expect(extractLoomId('')).toBeNull();
  302. });
  303. it('returns null for Loom URLs without share/embed path', () => {
  304. expect(extractLoomId('https://www.loom.com/pricing')).toBeNull();
  305. });
  306. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.