Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ jobs:
name: ci
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0

- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22
cache: npm

- run: npm ci

- uses: actions/cache@v4
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
id: playwright-cache
with:
path: ~/.cache/ms-playwright
Expand Down
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Now share a URL from Safari or another app, choose the shortcut, and URL Cleaner

### Share Sheet limitations

- The Shortcut passes the link after the `#`, which browsers never send to a server, so the link stays on your device. Older Shortcuts that use `?url=` still work, but that form sends the link to the web host in the page request; switch them to `/#url=`.
- The Shortcut passes the link after the `#`, which browsers never send to a server, so the link stays on your device. The Android share target POSTs into the service worker, which redirects to `/#url=` without a network request. Older Shortcuts that use `?url=` still work, but that form sends the link to the web host in the page request; switch them to `/#url=`.
- The **Share** button uses the browser's Web Share support. It appears only where that API is available; **Copy** remains the fallback.
- iOS and macOS may block silent clipboard writes when a page opens without a direct user gesture. The app therefore always displays the cleaned URL, and the **Share** and **Copy** buttons remain reliable final steps.
- The app removes the handoff value from the address bar after loading it.
Expand Down Expand Up @@ -213,7 +213,7 @@ The test suite covers:
- Local tracker explanations, rich tracker-of-the-day profiles, and deterministic daily selection
- Tracking fingerprint scoring, URL X-Ray categorization, encoded value decoding, and weirdness flags
- Opt-in aggressive cleaning and identical-duplicate cleanup, including batch mode
- Share-target, `#url=` and `?url=` handoff parsing
- Share-target POST, `#url=` and `?url=` handoff parsing
- Manifest, service worker, and CSP constraints for the installable app
- Every root web file matching its `dist/` copy byte-for-byte, since Vercel serves `dist/`

Expand All @@ -231,7 +231,8 @@ GitHub Actions runs `npm test` on every push to `main` and on pull requests.
| [handoff.js](./handoff.js) | Share-target, hash handoff, and clipboard-permission helpers |
| [app.js](./app.js) | Form, clipboard, settings, and copy interactions |
| [manifest.webmanifest](./manifest.webmanifest) | Web app manifest and share target |
| [sw.js](./sw.js) | Minimal service worker for installability (no caching) |
| [sw.js](./sw.js) | Service worker for installability and local share-target POST handoff (no caching, no network) |
| [middleware.js](./middleware.js) | Vercel Routing Middleware: 303 share-target POSTs to `/` without reading the body |
| [tests/](./tests) | Automated tests (cleaning, batch, explanations, handoff, PWA, favicon, production URL, `dist/` sync) |
| [vercel.json](./vercel.json) | Vercel config: serves `dist/` and sets the security headers |
| [.github/workflows/test.yml](./.github/workflows/test.yml) | Runs `npm test` in CI |
Expand Down Expand Up @@ -261,9 +262,10 @@ How a link reaches the app matters:

- **Paste, Paste button, clipboard offer:** the link never leaves the page.
- **Shortcut (`/#url=`):** the link is passed after the `#`. Browsers do not send that part to the server, so the host only sees a plain request for the page.
- **Android share target and old `?url=` links:** the Web Share Target API can only pass the link as a query string, so the shared link is included in the page request to the static host (Vercel) before the app cleans it and removes it from the address bar. Use the Shortcut or paste if you want to avoid that.
- **Android share target:** the installed PWA receives a POST. When the service worker is controlling the page, it intercepts that POST and redirects to a `/#url=&text=&title=` hash, so the shared fields never leave the device and an invalid `url` field can still fall back to a link in `text` or `title`. If the worker is not yet active (first launch or cleared storage), Vercel Routing Middleware responds `303` to `/` without reading the POST body, so the host never logs the shared link; the URL is dropped and you can paste or share again after install.
- **Old `?url=` links:** still work, but that form sends the link to the web host in the page request. Use `/#url=` or paste if you want to avoid that.

The hosted site enforces this with security headers set in [vercel.json](./vercel.json). The Content Security Policy uses `connect-src 'none'`, so the page cannot make network requests even if it tried, and only loads its own scripts and styles. It also sends `Referrer-Policy: no-referrer`, refuses to be framed, and disables camera, microphone, geolocation, payment, and USB access. The service worker exists only for installability and caches nothing.
The hosted site enforces this with security headers set in [vercel.json](./vercel.json). The Content Security Policy uses `connect-src 'none'`, so the page cannot make network requests even if it tried, and only loads its own scripts and styles. It also sends `Referrer-Policy: no-referrer`, refuses to be framed, and disables camera, microphone, geolocation, payment, and USB access. The service worker exists for installability and to keep share-target POSTs on-device; it caches nothing and never fetches the shared URL.

## License

Expand Down
18 changes: 11 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
removedDuplicateIndicesForBeforeView
} from "./cleaner.js";
import { explainParameter, trackerOfTheDay } from "./explanations.js";
import { canReadClipboard, parseHandoffUrl } from "./handoff.js";
import { canReadClipboard, hasHandoffFields, parseHandoffUrl } from "./handoff.js";
import { createIcon, wrapIconButton } from "./icons.js";
import { breakableUrlMarkup } from "./url-break.js";
import {
Expand Down Expand Up @@ -685,12 +685,16 @@ function clearHandoffFromAddressBar() {
}

function loadHandoff() {
const handedOff = parseHandoffUrl(window.location.href);
if (!handedOff) return false;
input.value = handedOff;
runClean({ allowAutoCopy: false });
clearHandoffFromAddressBar();
return true;
const href = window.location.href;
const handedOff = parseHandoffUrl(href);
if (handedOff) {
input.value = handedOff;
runClean({ allowAutoCopy: false });
}
if (handedOff || hasHandoffFields(href)) {
clearHandoffFromAddressBar();
}
return Boolean(handedOff);
}

initTheme();
Expand Down
21 changes: 15 additions & 6 deletions cleaner.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ const REDIRECT_RELATED_PARAMETERS = new Set([

export const MAX_UNWRAP_DEPTH = 5;

export class InputError extends Error {
constructor(message) {
super(message);
this.name = "InputError";
}
}

// %30-%39 (0-9), %41-%5A (A-Z) and %61-%7A (a-z).
const ENCODED_ALPHANUMERIC_PATTERN = /%(?:3[0-9]|4[1-9a-f]|5[0-9a]|6[1-9a-f]|7[0-9a])/i;

Expand Down Expand Up @@ -136,17 +143,17 @@ function getWrapperInfo(url) {

function parseHttpUrl(input) {
const value = String(input ?? "").trim();
if (!value) throw new TypeError("Enter a URL to clean.");
if (!value) throw new InputError("Enter a URL to clean.");

let url;
try {
url = new URL(value);
} catch {
throw new TypeError("Enter a valid URL, including https:// or http://.");
throw new InputError("Enter a valid URL, including https:// or http://.");
}

if (!isHttpUrl(url)) {
throw new TypeError("Enter a valid URL, including https:// or http://.");
throw new InputError("Enter a valid URL, including https:// or http://.");
}

return url;
Expand Down Expand Up @@ -432,7 +439,7 @@ export function cleanUrl(input, options = {}) {
};
}

export function cleanBatch(text, options = {}) {
export function cleanBatch(text, options = {}, clean = cleanUrl) {
const lines = String(text ?? "").split(/\r?\n/);
const results = [];

Expand All @@ -445,14 +452,16 @@ export function cleanBatch(text, options = {}) {
line: index + 1,
input,
ok: true,
result: cleanUrl(input, options)
result: clean(input, options)
});
} catch (error) {
results.push({
line: index + 1,
input,
ok: false,
error: error.message
error: error instanceof InputError
? error.message
: "Internal error while cleaning this URL."
});
}
}
Expand Down
12 changes: 10 additions & 2 deletions handoff.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,21 @@ export function parseHandoffParams(searchParams) {
return "";
}

// Links handed over after the "#" (#url=) are never sent to the server, so
// they win. The ?url= form stays for the share target and legacy handoff links.
// Links handed over after the "#" are never sent to the server, so they win.
// The Android share target POSTs into the service worker, which redirects to
// /#url=&text=&title= without a network request so parseHandoffParams can try
// each field. The ?url= form stays for legacy handoff links only.
export function parseHandoffUrl(href) {
const url = new URL(href);
return parseHandoffParams(url.hash.slice(1)) || parseHandoffParams(url.searchParams);
}

export function hasHandoffFields(href) {
const parsed = new URL(href);
const sources = [new URLSearchParams(parsed.hash.slice(1)), parsed.searchParams];
return sources.some((params) => ["url", "text", "title"].some((name) => params.has(name)));
}

export function canReadClipboard(permissionState) {
return permissionState === "granted";
}
Expand Down
2 changes: 1 addition & 1 deletion manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
],
"share_target": {
"action": "./",
"method": "GET",
"method": "POST",
"enctype": "application/x-www-form-urlencoded",
"params": {
"title": "title",
Expand Down
5 changes: 3 additions & 2 deletions mcp/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ HOST=127.0.0.1
PORT=8787
# Optional: comma-separated full origins (scheme+host+port) for POST /mcp; loopback on any port is always allowed
# MCP_ALLOWED_ORIGINS=https://app.example:8443,http://localhost:3000
# Optional: Host header allowlist (literal match); include :port when PORT is not 80
# MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859,mcp.example.com
# Optional: extra Host header values (literal match); include :port when PORT is not 80.
# Loopback names are already allowed when HOST is 127.0.0.1 or a wildcard (0.0.0.0 / ::).
# MCP_ALLOWED_HOSTS=mcp.example.com
# Optional: override engine location (default is repo root, one level up from mcp/)
# ENGINE_DIR=..
6 changes: 3 additions & 3 deletions mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Official MCP adapter for [URL Cleaner](https://github.com/heyandromeda/url-clean
Every tool result comes from engine functions only. The server does not fetch or open URLs. Each result includes `engineInvoked` (function names + best-effort git SHA of the loaded engine).

- **stdio** (default): newline-delimited JSON-RPC for Cursor, Claude Code, Codex, and other local MCP clients.
- **HTTP**: Streamable HTTP on `POST /mcp` (JSON responses), bearer auth, binds `127.0.0.1` by default. `GET /healthz` is public.
- **HTTP**: Streamable HTTP on `POST /mcp` (JSON responses), bearer auth, binds `127.0.0.1` by default. `GET /healthz` is unauthenticated and Host-checked (`{ ok: true }` only).
- Protocol: `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`. JSON-RPC batches accepted.
- Logs (stderr): tool name, duration, status, and auth rejections only — never URLs, arguments, or tokens.

Expand Down Expand Up @@ -40,7 +40,7 @@ Environment:
| Variable | Purpose |
|---|---|
| `MCP_AUTH_TOKEN` | Required for HTTP mode (≥ 24 characters) |
| `HOST` | Default `127.0.0.1`. With `HOST=0.0.0.0`, the default allowed `Host` set follows the bind address only and **excludes** `localhost` and `127.0.0.1`; local clients must set `MCP_ALLOWED_HOSTS` (see **Host** below). |
| `HOST` | Default `127.0.0.1`. Binding `0.0.0.0` or `::` also allows loopback `Host` values (`localhost`, `127.0.0.1`, `[::1]`, with and without port). Proxy hostnames still need `MCP_ALLOWED_HOSTS` (see **Host** below). |
| `PORT` | Default `8787` |
| `ENGINE_DIR` | Default `..` (repo root) |
| `ENGINE_SHA` | Optional override for `engineInvoked.sha` |
Expand All @@ -53,7 +53,7 @@ Environment:

**Origin (DNS rebinding):** On `POST /mcp`, if the client sends an `Origin` header it must pass **either** the default loopback rule (`http`/`https` on `localhost`, `127.0.0.1`, or `[::1]` on **any** port) **or** match a full origin in `MCP_ALLOWED_ORIGINS` (scheme, host, and port compared via `URL().origin` — `https://app.example:8443` does not admit `http://app.example` or `https://app.example:9999`). A disallowed Origin returns **403** before auth or body handling. Requests with no `Origin` header are still accepted.

**Host:** The `Host` header must match the bound loopback address/port **or** an entry in `MCP_ALLOWED_HOSTS` (comma-separated, lowercase). Values are compared literally to the request `Host` header. Include the port in each entry when the server listens on a non-80 port (e.g. `MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859`); a bare host such as `127.0.0.1` does **not** match `127.0.0.1:8859` and returns **403**. On port **80** only, clients may send a host without `:80`, so a bare entry can match. Use this when binding `0.0.0.0` or when a reverse proxy forwards with a public hostname. `/healthz` is not subject to Origin checks.
**Host:** The `Host` header must match the bound address/port **or** an entry in `MCP_ALLOWED_HOSTS` (comma-separated, lowercase). Values are compared literally to the request `Host` header. Include the port in each entry when the server listens on a non-80 port (e.g. `MCP_ALLOWED_HOSTS=127.0.0.1:8859,localhost:8859`); a bare host such as `127.0.0.1` does **not** match `127.0.0.1:8859` and returns **403**. On port **80** only, clients may send a host without `:80`, so a bare entry can match. When binding `0.0.0.0` or `::`, the defaults also include loopback names (`localhost`, `127.0.0.1`, `[::1]`, with and without the listen port) so local clients work without `MCP_ALLOWED_HOSTS`. Use `MCP_ALLOWED_HOSTS` when a reverse proxy forwards with a public hostname. `/healthz` is Host-checked the same way, is not subject to Origin or token checks, and does not include the engine SHA.

There is **no** public hosted MCP endpoint in this repo. Run stdio locally or bind HTTP on localhost for your own clients.

Expand Down
12 changes: 7 additions & 5 deletions mcp/scripts/http-smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
# Local-only smoke test: starts the server on 127.0.0.1 with a random throwaway token (never printed), runs curl calls, stops it.
set -uo pipefail
cd "$(dirname "$0")/.."
WORKDIR="$(mktemp -d)"
export MCP_AUTH_TOKEN="$(node -e 'process.stdout.write(require("crypto").randomBytes(32).toString("hex"))')"
export PORT="${PORT:-8799}" HOST=127.0.0.1
node server.mjs --http 2> /tmp/ucmcp-http.log & PID=$!
trap 'kill $PID 2>/dev/null' EXIT
node server.mjs --http 2> "$WORKDIR/http.log" & PID=$!
cleanup() { kill "$PID" 2>/dev/null || true; rm -rf "$WORKDIR"; }
trap cleanup EXIT
for i in $(seq 1 30); do curl -s "http://127.0.0.1:$PORT/healthz" >/dev/null && break; sleep 0.1; done
U="http://127.0.0.1:$PORT/mcp"
rpc() { curl -s -w ' [HTTP %{http_code}]\n' -H "Authorization: Bearer $MCP_AUTH_TOKEN" -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -d "$1" "$U"; }
Expand All @@ -15,7 +17,7 @@ echo "### wrong token"; curl -s -o /dev/null -w '[HTTP %{http_code}]\n' -H 'Auth
echo "### initialize"; rpc '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
echo "### initialized"; rpc '{"jsonrpc":"2.0","method":"notifications/initialized"}'
echo "### ping"; rpc '{"jsonrpc":"2.0","id":2,"method":"ping"}'
echo "### tools/list"; rpc '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' > /tmp/ucmcp-list.json; cat /tmp/ucmcp-list.json | tail -c 40
echo "### tools/list"; rpc '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' > "$WORKDIR/list.json"; cat "$WORKDIR/list.json" | tail -c 40
for spec in \
'10|clean_url|{"url":"https://example.com/p?utm_source=x&utm_medium=y&id=5&fbclid=abc"}' \
'11|clean_url|{"url":"https://www.google.com/url?q=https%3A%2F%2Fexample.com%2F%3Futm_source%3Dx"}' \
Expand All @@ -30,6 +32,6 @@ for spec in \
'60|clean_url|{}' \
'61|no_such_tool|{}' ; do
IFS='|' read -r id name args <<< "$spec"
echo "### $id $name $args"; call "$id" "$name" "$args" > "/tmp/ucmcp-$id.json"; tail -c 20 "/tmp/ucmcp-$id.json"
echo "### $id $name $args"; call "$id" "$name" "$args" > "$WORKDIR/$id.json"; tail -c 20 "$WORKDIR/$id.json"
done
echo "### server log (stderr)"; cat /tmp/ucmcp-http.log
echo "### server log (stderr)"; cat "$WORKDIR/http.log"
Loading
Loading