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
7 changes: 7 additions & 0 deletions .changeset/admin-credential-client-ip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@reelsaw/server": minor
---

Security fixes. An admin's API key made without instance administration, or an MCP connector signed in through OAuth, can no longer restore or permanently delete other accounts' deleted projects and clips, or download instance-wide diagnostics in an issue report; those now need the admin's browser session or a key with instance administration, the same rule the admin tools already followed.

Sign-in and sign-up limits now key on the address of the connection itself, so a client can no longer pick a new address for each attempt by sending `X-Forwarded-For`, and visitors no longer share one limit when the instance is reached directly. `TRUST_PROXY` now defaults to `false`. **If Reelsaw runs behind a reverse proxy, set `TRUST_PROXY=true`** (the app warns once in its log when a request carries a forwarding header while it is off), and optionally `TRUSTED_PROXIES` to the proxy's address or range so only it may name the client. The installers write `TRUST_PROXY=false`, which fits the port they publish.
8 changes: 5 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,14 @@ SIGNUP_MODE=open
# RESEND_API_KEY=
# With an email driver: users must click the verification link before they can sign in. The link works for 24 hours and is single-use; an expired one offers a new send. Runtime setting: admins can change it under Settings → System without a restart.
# REQUIRE_EMAIL_VERIFICATION=false
# Take the client address from the reverse proxy's header (see TRUSTED_PROXY_HEADER): the Docker deployment sits behind Caddy, so the default is on. false when the app is exposed directly, or the header is whatever the client sent. The address feeds the sign-up cap and the OAuth client-registration limit.
# TRUST_PROXY=true
# true when a reverse proxy (Caddy, nginx, Cloudflare, a platform's edge) sits in front of the app: the client address then comes from the proxy's header (see TRUSTED_PROXY_HEADER, TRUSTED_PROXY_HOPS, TRUSTED_PROXIES). Default false, for an app exposed directly (what the compose files and installers set up): the address is the connection's own, and any forwarding header a client sends is ignored. The address keys the sign-in and sign-up rate limits, the accounts-per-address cap and the OAuth client-registration limit; behind a proxy with this off, every client shares the proxy's address in them (the app warns once when a request carries the header).
# TRUST_PROXY=false
# With x-forwarded-for: how many trusted proxies sit in front of the app, each appending the address it saw. The client is the entry that many places from the right, so entries a client prepends are ignored. 1 for Caddy alone, 2 for Cloudflare in front of Caddy.
# TRUSTED_PROXY_HOPS=1
# Header that carries the client address when TRUST_PROXY is on: x-forwarded-for (default; Caddy, nginx, most load balancers), cf-connecting-ip (Cloudflare, with the origin closed to everything else) or x-real-ip (Railway, whose edge sets it to the visitor's address). Only the selected header is read, so a client cannot choose its address by sending a different one. (x-forwarded-for | cf-connecting-ip | x-real-ip)
# TRUSTED_PROXY_HEADER=x-forwarded-for
# With TRUST_PROXY: the addresses or CIDR ranges of the proxies allowed to name the client, comma-separated (172.16.0.0/12 for a proxy container on a Docker network, 127.0.0.1,::1 for one on the same host). A request from any other address is keyed on its own address and its header ignored, so a client that reaches the app's port around the proxy cannot choose its address. Empty (default) trusts the header from any connection: only safe when the port is reachable through the proxy alone.
# TRUSTED_PROXIES=
# Accounts one network address may create per day (sign-up guard). 0 = unlimited. Runtime setting: admins can change it under Settings → System without a restart.
# MAX_SIGNUPS_PER_IP_PER_DAY=0
# Refuse sign-ups from known temporary-address domains. Runtime setting: admins can change it under Settings → System without a restart.
Expand Down Expand Up @@ -372,7 +374,7 @@ CLEANUP_WORKDIR=true
# POSTHOG_KEY=
# PostHog ingestion host (https://eu.i.posthog.com for the EU cloud, or a self-hosted instance).
# POSTHOG_HOST=https://us.i.posthog.com
# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For, when TRUST_PROXY is on. Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY.
# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For (resolved as for the rate limits: see TRUST_PROXY). Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY.
# POSTHOG_PROXY=false
# Capture model calls: none, logs (one structured line per call: prompt, response, tokens, latency) or langfuse (a trace per job, a generation per call tagged with its step's prompt version, and, for accounts with learning on, a score per decision about the output on the project's session: clip.kept, clip.found, clip.untouched, clip.bounds_kept, clip.copy_kept, fix.accepted, fix.found); comma-separate for several. A failed call's log line carries errName, statusCode and the provider's errCode beside the error.
# LLM_TRACE=none
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/stack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ jobs:
echo "OPENAI_API_KEY=mock"
echo "AI_MODEL=openai:mock"
echo "TRANSCRIPTION_MODEL=openai:whisper-1"
# the tests play the reverse proxy: abuse-stack and signup-rules-stack name each client in X-Forwarded-For
echo "TRUST_PROXY=true"
} > .env
# the image compose runs (reelsaw:latest), built with buildx so layers come from a cache: pushes
# to main write the `stack` scope (PRs can read main's caches, not each other's), and the
Expand Down
21 changes: 13 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,8 +455,8 @@ them), so a single-user box stays as it is:
- **Bot protection**: `CAPTCHA_PROVIDER` (Cloudflare Turnstile, reCAPTCHA, hCaptcha) with site and
secret keys puts a widget on sign-up, sign-in and password reset.
- **Free-tier abuse** (all off unless set; `apps/server/src/abuse.ts`): `MAX_SIGNUPS_PER_IP_PER_DAY`
caps accounts per network address (behind a proxy, `TRUST_PROXY` reads `CF-Connecting-IP`,
`X-Real-IP`, `X-Forwarded-For`); `BLOCK_DISPOSABLE_EMAILS` refuses temporary-address domains; one
caps accounts per network address (the connection's, or behind a proxy with `TRUST_PROXY` the one
in `CF-Connecting-IP`, `X-Real-IP` or `X-Forwarded-For`); `BLOCK_DISPOSABLE_EMAILS` refuses temporary-address domains; one
account per real mailbox (`john.doe+x@gmail.com` is `johndoe@gmail.com`); `MAX_REQUESTS_PER_MINUTE`
/ `_HOUR` cap changes (API mutations, MCP tool calls) per account, with plan and per-user
overrides like the other quotas. An hourly pass flags accounts that
Expand All @@ -477,12 +477,17 @@ them), so a single-user box stays as it is:
consent page shows the address the approval returns to, registrations are capped at 20 per
network address per day, and each person lists and revokes the apps they allowed under
Settings → Account → Connected apps.
- **Client address behind a proxy** (`TRUST_PROXY`, `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`):
the sign-up cap and the registration limit key on the client address. With the default
`x-forwarded-for` it is the entry `TRUSTED_PROXY_HOPS` places from the right (1 behind Caddy,
2 behind Cloudflare and Caddy), so addresses a client prepends do not count; the other headers
are read only when selected. On Railway set `TRUSTED_PROXY_HEADER=x-real-ip`: its edge puts the
visitor's address there, and the server warns at boot when it is left on `x-forwarded-for`.
- **Client address** (`TRUST_PROXY`, `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`, `TRUSTED_PROXIES`):
the sign-in and sign-up rate limits, the sign-up cap and the registration limit key on the
client address. By default it is the connection's own address and forwarding headers are
ignored, which is right for the compose files and installers (the app's port is published
directly). Behind a reverse proxy set `TRUST_PROXY=true`: with the default `x-forwarded-for`
the address is the entry `TRUSTED_PROXY_HOPS` places from the right (1 behind Caddy, 2 behind
Cloudflare and Caddy), so addresses a client prepends do not count; the other headers are read
only when selected. `TRUSTED_PROXIES` (addresses or CIDR ranges) limits whose header is
believed, so a client reaching the port around the proxy is keyed on its own address. On
Railway set `TRUSTED_PROXY_HEADER=x-real-ip`: its edge puts the visitor's address there, and
the server warns at boot when it is left on `x-forwarded-for`.

## Billing (enterprise edition)

Expand Down
9 changes: 6 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,12 @@ should follow the update check (Settings → System) or watch releases.
keys stored in Settings.
- Leave `ALLOW_PRIVATE_SOURCE_URLS` off unless the instance must read from a NAS.
- Put the instance behind an HTTPS reverse proxy and keep `TRUST_PROXY` matched to the
deployment (`false` when the app is exposed directly). Set `TRUSTED_PROXY_HOPS` to the number
of proxies in front of the app (2 for Cloudflare in front of Caddy) so the client address is
the entry from the right that your proxies wrote, not one the client sent; use
deployment: `false` (the default) when the app is exposed directly, so rate limits key on the
connection's address and forwarding headers are ignored; `true` behind a proxy, or every client
shares the proxy's address. Set `TRUSTED_PROXY_HOPS` to the number of proxies in front of the
app (2 for Cloudflare in front of Caddy) so the client address is the entry from the right that
your proxies wrote, not one the client sent, and `TRUSTED_PROXIES` to their addresses or ranges
when the app's port is reachable other than through them; use
`TRUSTED_PROXY_HEADER=cf-connecting-ip` only when the origin accepts traffic from Cloudflare alone.
- Create API keys without "Allow instance administration" unless the agent must change
instance settings. OAuth connectors never get admin tools. Connected apps can be revoked under
Expand Down
8 changes: 6 additions & 2 deletions apps/server/scripts/docs-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,16 @@ export const DOCS: Record<string, [GroupId, string]> = {
],
TRUST_PROXY: [
"accounts",
"Take the client address from the reverse proxy's header (see `TRUSTED_PROXY_HEADER`): the Docker deployment sits behind Caddy, so the default is on. `false` when the app is exposed directly, or the header is whatever the client sent. The address feeds the sign-up cap and the OAuth client-registration limit.",
"`true` when a reverse proxy (Caddy, nginx, Cloudflare, a platform's edge) sits in front of the app: the client address then comes from the proxy's header (see `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`, `TRUSTED_PROXIES`). Default `false`, for an app exposed directly (what the compose files and installers set up): the address is the connection's own, and any forwarding header a client sends is ignored. The address keys the sign-in and sign-up rate limits, the accounts-per-address cap and the OAuth client-registration limit; behind a proxy with this off, every client shares the proxy's address in them (the app warns once when a request carries the header).",
],
TRUSTED_PROXY_HEADER: [
"accounts",
"Header that carries the client address when `TRUST_PROXY` is on: `x-forwarded-for` (default; Caddy, nginx, most load balancers), `cf-connecting-ip` (Cloudflare, with the origin closed to everything else) or `x-real-ip` (Railway, whose edge sets it to the visitor's address). Only the selected header is read, so a client cannot choose its address by sending a different one.",
],
TRUSTED_PROXIES: [
"accounts",
"With `TRUST_PROXY`: the addresses or CIDR ranges of the proxies allowed to name the client, comma-separated (`172.16.0.0/12` for a proxy container on a Docker network, `127.0.0.1,::1` for one on the same host). A request from any other address is keyed on its own address and its header ignored, so a client that reaches the app's port around the proxy cannot choose its address. Empty (default) trusts the header from any connection: only safe when the port is reachable through the proxy alone.",
],
TRUSTED_PROXY_HOPS: [
"accounts",
"With `x-forwarded-for`: how many trusted proxies sit in front of the app, each appending the address it saw. The client is the entry that many places from the right, so entries a client prepends are ignored. 1 for Caddy alone, 2 for Cloudflare in front of Caddy.",
Expand Down Expand Up @@ -428,7 +432,7 @@ export const DOCS: Record<string, [GroupId, string]> = {
POSTHOG_HOST: ["observability", "PostHog ingestion host (`https://eu.i.posthog.com` for the EU cloud, or a self-hosted instance)."],
POSTHOG_PROXY: [
"observability",
"`true` has the web app send PostHog events to the app's own origin at `/api/relay`, which the server forwards to `POSTHOG_HOST` (and `/static/*` to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For, when TRUST_PROXY is on. Default `false`: the browser talks to `POSTHOG_HOST` directly. Only used with `POSTHOG_KEY`.",
"`true` has the web app send PostHog events to the app's own origin at `/api/relay`, which the server forwards to `POSTHOG_HOST` (and `/static/*` to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For (resolved as for the rate limits: see `TRUST_PROXY`). Default `false`: the browser talks to `POSTHOG_HOST` directly. Only used with `POSTHOG_KEY`.",
],

FFMPEG_PATH: ["tools", "ffmpeg binary."],
Expand Down
53 changes: 45 additions & 8 deletions apps/server/src/abuse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
*
* Every refusal is a sentence. Nothing here reads the request body or the video.
*/
import { isIP, type BlockList } from "node:net";
import { and, eq, gte, sql } from "drizzle-orm";
import type { Context } from "hono";
import { getConnInfo } from "@hono/node-server/conninfo";
import { ACCOUNT_EXISTS_MESSAGE, type AbuseFlag } from "@reelsaw/shared";
import disposable from "disposable-email-domains/index.json" with { type: "json" };
import { schema, type Db } from "./db/index.js";
Expand All @@ -24,23 +27,57 @@ import type { Logger } from "./log.js";
import type { Config } from "./config.js";
import { msg } from "@lingui/core/runtime-macro";
import { AppError } from "./i18n.js";
import { parseTrustedProxies } from "./lib/trusted-proxies.js";

const DISPOSABLE = new Set<string>(disposable);

type ProxyTrust = Pick<Config, "TRUST_PROXY" | "TRUSTED_PROXY_HEADER" | "TRUSTED_PROXY_HOPS" | "TRUSTED_PROXIES">;

/** `::ffff:1.2.3.4` (an IPv4 client on a dual-stack socket) as `1.2.3.4`, so one client has one key. */
function plainAddress(address: string | null | undefined): string | null {
const a = address?.trim();
if (!a) return null;
return /^::ffff:\d+\.\d+\.\d+\.\d+$/i.test(a) ? a.slice(7) : a;
}

const proxyLists = new Map<string, BlockList>();
/** Whether the connection may name the client: any peer with an empty list, else only one in it (an unknown peer never). */
function trustedPeer(peer: string | null, list: string): boolean {
if (!list.trim()) return true;
if (!peer) return false;
let parsed = proxyLists.get(list);
if (!parsed) proxyLists.set(list, (parsed = parseTrustedProxies(list)));
return parsed.check(peer, isIP(peer) === 6 ? "ipv6" : "ipv4");
}

/**
* The client's address. Behind a reverse proxy (Caddy, Cloudflare; TRUST_PROXY=true, the default for the
* Docker deployment) the proxy's headers name it; otherwise they are whatever the client sent, so they are
* ignored and the guard keys on "unknown" (which never counts).
* The client's address. `peer` is the address of the connection itself (`requestPeer`), which nobody can choose. With
* TRUST_PROXY on (a reverse proxy in front: Caddy, nginx, Cloudflare) the proxy's header names the client instead, but
* only on a connection from a proxy in TRUSTED_PROXIES (any peer when that is empty). Otherwise, or when the header is
* missing or shorter than TRUSTED_PROXY_HOPS, it is the peer: never a value the client sent, and never "unknown", so
* every per-address guard keeps working on an install with no proxy.
*/
export function clientIp(headers: Headers, trust: Pick<Config, "TRUST_PROXY" | "TRUSTED_PROXY_HEADER" | "TRUSTED_PROXY_HOPS">): string | null {
if (!trust.TRUST_PROXY) return null;
export function clientIp(headers: Headers, peer: string | null | undefined, trust: ProxyTrust): string | null {
const direct = plainAddress(peer);
if (!trust.TRUST_PROXY) return direct;
if (!trustedPeer(direct, trust.TRUSTED_PROXIES)) return direct;
const value = headers.get(trust.TRUSTED_PROXY_HEADER);
if (!value) return null;
if (trust.TRUSTED_PROXY_HEADER !== "x-forwarded-for") return value.trim() || null;
if (!value) return direct;
if (trust.TRUSTED_PROXY_HEADER !== "x-forwarded-for") return plainAddress(value) ?? direct;
// each trusted proxy appends the address it saw, so the client is `hops` entries from the right; anything a client
// prepends sits to the left of that and is ignored. Fewer entries than hops means the request did not come through them.
const entries = value.split(",").map((e) => e.trim());
return entries[entries.length - trust.TRUSTED_PROXY_HOPS] || null;
return plainAddress(entries[entries.length - trust.TRUSTED_PROXY_HOPS]) ?? direct;
}

/** The address of the connection a request came in on (Node's socket), or null outside the Node server (app.request in tests). */
export function requestPeer(c: Context): string | null {
try {
return getConnInfo(c).remote.address ?? null;
} catch {
// no Node bindings on this context (a request made in-process): there is no connection to name
return null;
}
}

/**
Expand Down
Loading
Loading