UniClipboard
Core Features

Hybrid Relay & Self-Hosting

How P2P-first, zero-wait zero-knowledge E2EE temporary relay works, how to configure it, and how to self-host with Docker Compose or Cloudflare Workers.

Edit on GitHub

When paired devices are online and reachable directly, unic always prefers direct P2P with zero relay traffic. Only when a target device is temporarily offline or cold-starting (such as waking a mobile app from the background or sharing over cellular) does unic automatically use Hybrid Relay (Hyper Relay) to start sending with zero wait while waking P2P in the background.

Hybrid Relay is only for short-lived, end-to-end encrypted temporary staging (10-minute default TTL, deleted immediately after delivery confirmation). It is not a cloud clipboard history store. Neither the relay server nor object storage can read your plaintext, file names, MIME types, or source app names.

Two Separate Relay Programs

The unic ecosystem has two orthogonal, independently deployed relay programs. Do not confuse them:

DimensionTailcat P2P / DERP RelayHyper Hybrid Relay (UniClipboard/relay)
LayerTransport / tunnel layer: assists builtin.tailcat with NAT traversal and real-time WireGuard packet forwardingApplication / chunk layer: zero-wait E2EE temporary chunk control plane + SSE push notifications
Stores payloads?No — live online byte forwarding only; both peers must be online to complete the tunnel handshakeYes — ciphertext chunks are staged in object storage via presigned URLs (10 min default TTL) and deleted on ACK
Ciphertext data pathEncrypted tunnel traffic transits the DERP nodeDirect-to-S3: ciphertext chunks go directly between devices and S3/R2/COS/OSS/MinIO, never through the relay server
Self-hosting boundaryOwned by builtin.tailcat; completely decoupled from Hybrid RelayStandalone HTTP service (Go container or Cloudflare Workers); can be self-hosted independently of or alongside DERP

Unless otherwise noted, "Hybrid Relay" below refers to Hyper Relay (open-source repository: UniClipboard/relay).

How It Works

  • Zero relay overhead when P2P is online: If a peer already has an active P2P session, transfers go straight over P2P with zero HTTP relay requests.
  • Zero-wait offline fallback: When a peer has no active P2P session and the payload fits within the per-transfer cap (official default 25 MB), unic starts encrypted HTTPS upload immediately while asynchronously waking P2P reconnection.
  • Direct-to-S3 control/data split & geo-routed storage: Official hosting uses a single global origin (https://relay.uniclipboard.app), keeping relay_origin and mailbox_id identical across borders and proxy switches. The control plane handles only small JSON messages, Ed25519 auth, SSE push, and short-lived AWS SigV4 presigned URLs, while object storage routes by region per transfer (Tencent Cloud COS in mainland China, Cloudflare R2 overseas) with transparent cross-region download. Self-hosted setups work with any S3-compatible bucket so even a 1 vCPU / 1 Mbps VM handles large transfers cleanly.
  • Mid-transfer P2P handoff for large payloads: Payloads larger than 2 MiB are split into 1 MiB independently encrypted chunks. If P2P comes online mid-upload, both devices reconcile received chunks via bitmaps, stream only the remaining chunks over P2P into the same assembly buffer, and clean up cloud chunks once committed. If P2P drops mid-handoff, the transfer seamlessly falls back to HTTP without losing already-received chunks.
  • Zero-knowledge E2EE: Reuses existing paired Ed25519 device keys (mapped to X25519) with a fresh per-transfer AES-256-GCM content key (CEK). No account registration or re-pairing is required. Unpairing a device or pausing sync immediately cancels in-flight relay transfers and revokes that peer's delivery token.

Client Setup & UniClipboard Cloud Sign-In

The official managed relay (https://relay.uniclipboard.app, or an authorized Cloud-hosted HTTPS origin) is one of the hosted capabilities unlocked by signing in to UniClipboard Cloud (https://cloud.uniclipboard.app). Signing in automatically mints and silently rotates short/medium-lived scoped managed device credentials (uc_dc_...) stored in owner-only cloud-session.json (0600) and enables Hybrid Relay automatically, while fresh installs keep it disabled until you sign in or configure a self-hosted relay. Local history and direct P2P sync always work without an account.

In official mode (Server URL / sync.relay.url left empty), Desktop and Mobile hide all manual access-key controls—you never need to copy, clear, or refetch a key:

  • Desktop: Open Settings → Cloud Services and click Sign in (or toggle Enable Hybrid Relay under Settings → Sync → Hybrid Relay). Fine-tune the per-transfer size cap or switch to a custom server URL under Settings → Sync → Hybrid Relay.
  • Mobile (iOS / Android): Open Cloud Services at the top of Settings and tap Sign in, then manage Hybrid Relay under Settings → Advanced network → Hybrid Relay.

Desktop Settings → Cloud Services / Hybrid Relay in official mode

  • CLI: Manage your Cloud account with unic cloud (pass --no-browser to print the URL—note the signing-in browser must still reach the local 127.0.0.1 loopback callback on the host running unic, e.g. via SSH port forwarding—or --no-relay to skip enabling sync.relay.enabled when saved TOML sync.relay.url is empty; login checks saved sync.relay.url, not unicd's UNIC_RELAY_URL, and never turns on global sync.enabled if it is off):
# Sign in to UniClipboard Cloud and automatically enable official Hybrid Relay (when saved sync.relay.url is empty)
unic cloud login

# Inspect current Cloud account status
unic cloud status

# Sign out (best-effort remote revocation first, then attempts local cloud-session.json removal even if remote fails;
# --keep-relay skips only the CLI write—unicd evaluates its own host UNIC_RELAY_URL / UNIC_RELAY_ACCESS_KEY and may still disable official relay)
unic cloud logout

When an active session exists, client sign-out first attempts best-effort remote revocation under a bounded request context (updating Cloud D1 only when the server processes the request; revoking a device at https://cloud.uniclipboard.app/account/devices updates D1 directly on the server), then still attempts to delete local cloud-session.json and clear the in-memory session snapshot even if remote revocation fails. Local lock or file operations can still fail, so immediate cleanup, a fixed total timeout, or guaranteed offline success is not promised (the snapshot is cleared only after cloud-session.json removal succeeds). Revocation invalidates only that device session's managed credential (uc_dc_...) and never affects other signed-in devices, manual API keys (uc_ak_...), or self-hosted configurations. Downstream UniClipboard/relay instances consult a configurable positive verification cache (60 seconds default in d51e721).

Manual API Keys (Headless / Scripts), Config File & CLI

For headless servers or automation without browser sign-in, create a scoped manual API Key (uc_ak_... with the relay scope) at https://cloud.uniclipboard.app/account/api-keys and supply it via sync.relay.access_key or UNIC_RELAY_ACCESS_KEY (legacy unscoped uc_rk_ keys are not accepted). For a self-hosted UniClipboard/relay instance, set sync.relay.url (entering a custom Server URL in Desktop or Mobile reveals the write-only Access key controls for that server).

Edit $UNIC_HOME/config.toml (hot-reloaded on save) or run unic config set / unic config apply:

[sync.relay]
enabled = true
url = ""                           # leave empty for official mode (or set custom https://... / $UNIC_RELAY_URL)
access_key = ""                    # optional manual Cloud API key (uc_ak_...) or self-hosted X-Unic-Relay-Key
max_bytes = "25MB"                 # per-transfer relay cap (up to 4GiB)
# Disable Hybrid Relay (zero relay network requests)
unic config set sync.relay.enabled false

# Switch to a self-hosted endpoint and raise the size cap
unic config set sync.relay.url '"https://relay.example.com"'
unic config set sync.relay.max_bytes '"100MB"'

You can also provide defaults through UNIC_RELAY_URL and UNIC_RELAY_ACCESS_KEY on the unicd host, plus UNIC_CLOUD_URL for unic cloud (--cloud-url overrides UNIC_CLOUD_URL; there is no cloud_url key in config.toml, and host UNIC_RELAY_ACCESS_KEY fallback stays active independently across config edits). Both unic config set and unic config apply save through the revision-checked PUT /v1/config service path: unic config set and Desktop Settings build from the redacted service snapshot (access_key omitted), so changing sync.relay.url drops any previous persisted sync.relay.access_key; unic config apply <file> clears a previous key if access_key is omitted on URL change, or treats any access_key = "..." line present in <file> as explicit input. Only direct on-disk edits to config.toml bypass PUT /v1/config and reload verbatim—when editing config.toml directly to switch URLs, always clear (access_key = "" or remove the line) or replace access_key in the same edit. Cloud-managed device credentials (uc_dc_...) stay in cloud-session.json, bind strictly to their authorized official origin, and never enter config.toml. See Environment Variables.

URL validation distinguishes three sources: Cloud-advertised official relay URLs strictly require https:// (plain HTTP is rejected); explicitly configured self-hosted sync.relay.url / UNIC_RELAY_URL entries accept canonical https:// or http:// and may target a private network (loopback HTTP is used by local test/simulator fixtures; use HTTPS on public networks); and peer-advertised relay_profile addresses require a trusted peer device and an exact match with this device's current canonical relay target—unknown or mismatched peer origins are rejected. When self-hosting, configure the same relay URL on all devices that should sync with each other, and let them connect over P2P at least once to exchange delivery routes.

Preparing Object Storage

Hyper Relay works with any S3-compatible object storage supporting standard AWS SigV4. Create a private bucket and obtain an Access Key / Secret Key scoped to read, write, and delete objects in that bucket:

ProviderS3_ENDPOINTS3_REGIONS3_FORCE_PATH_STYLE
Cloudflare R2https://<ACCOUNT_ID>.r2.cloudflarestorage.comautotrue
Tencent Cloud COShttps://cos.<region>.myqcloud.come.g. ap-guangzhoufalse (bucket <name>-<appid>)
AWS S3https://s3.<region>.amazonaws.come.g. us-east-1false
Aliyun OSShttps://oss-<region>.aliyuncs.come.g. oss-cn-hangzhoufalse
Local MinIOhttp://minio:9000 (with S3_PUBLIC_ENDPOINT)us-east-1true

Configure a 1-day bucket expiration lifecycle rule: In your storage provider console, add a lifecycle rule on prefix mailboxes/ to expire objects after 1 day. Normal ACKs, cancellations, and TTL sweeps call DeleteObject immediately, while the 1-day rule guarantees orphaned chunks from interrupted uploads never accumulate.

Option 1: Docker Compose (VPS / Cloud VM / NAS)

Recommended for VPS, Tencent Cloud Lighthouse / CVM, Kubernetes, or a NAS with a public reverse proxy. The image (ghcr.io/uniclipboard/hyper-relay:latest) is a minimal distroless Go binary with very low memory overhead for long-lived SSE streams and predictable flat-rate hosting.

1. Prepare .env

git clone https://github.com/UniClipboard/relay.git
cd relay
cp .env.example .env

Edit .env with your public HTTPS origin, S3 credentials, and admission keys (example shown for Tencent Cloud COS; swap values from the table above for R2 / S3 / OSS):

# Required: public HTTPS origin matching what clients configure (no trailing slash)
HYPER_ORIGIN=https://relay.example.com

# Abuse protection: enable either or both (see below)
RELAY_ACCESS_KEY=your-strong-random-key
RELAY_ALLOWED_PUBKEYS=

# Object storage (Tencent Cloud COS example)
S3_ENDPOINT=https://cos.ap-guangzhou.myqcloud.com
S3_REGION=ap-guangzhou
S3_BUCKET=uniclipboard-relay-1250000000
S3_ACCESS_KEY_ID=your-access-key-id
S3_SECRET_ACCESS_KEY=your-secret-access-key
S3_FORCE_PATH_STYLE=false
S3_KEY_PREFIX=mailboxes
S3_PRESIGN_TTL=5m

# Optional quota overrides (defaults: 25 MiB / 10m TTL / 32 active transfers per mailbox)
HYPER_MAX_TRANSFER_BYTES=26214400
HYPER_DEFAULT_TTL=10m
HYPER_MAX_TTL=30m

If you prefer not to use external cloud storage, enable the bundled MinIO profile on the same host (expose MinIO over public HTTPS and set S3_PUBLIC_ENDPOINT):

docker compose --profile minio up -d

2. Start and Verify Health

docker compose up -d
curl --fail http://127.0.0.1:8080/healthz
# Expected: {"service":"hyper-relay","status":"ok","storage":"s3-direct"}

3. Configure Reverse Proxy for SSE

Terminate TLS in front of 127.0.0.1:8080. With Nginx, disable proxy buffering and extend the read timeout on the SSE stream path (/v1/relay/mailboxes/*/events) so notifications are pushed immediately:

server {
    listen 443 ssl http2;
    server_name relay.example.com;

    # TLS certificates omitted

    location ~ ^/v1/relay/mailboxes/[^/]+/events$ {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        proxy_cache off;
        proxy_read_timeout 1h;
    }

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        client_max_body_size 2m;
    }
}

With Caddy, streaming works out of the box:

relay.example.com {
    reverse_proxy 127.0.0.1:8080 {
        flush_interval -1
    }
}

Option 2: One-Click Deploy on Cloudflare Workers + Durable Objects

Ideal for zero-ops personal or small-team deployments. The control plane runs on Cloudflare Workers + SQLite Durable Objects (sharded by mailbox_id, with alarm() TTL cleanup) and can point direct chunk traffic at Cloudflare R2, Tencent Cloud COS, AWS S3, or Aliyun OSS.

One-Click Deploy

Click Deploy to Cloudflare and follow the guided setup.

Manual Wrangler CLI Deployment

git clone https://github.com/UniClipboard/relay.git
cd relay/deploy/cloudflare
npm ci
  1. Configure non-secret vars: Edit vars in wrangler.jsonc (or in Cloudflare Dashboard → Worker → Settings → Variables). Example for Cloudflare R2:
"vars": {
  "RELAY_ORIGIN": "https://relay.example.com",
  "S3_ENDPOINT": "https://<ACCOUNT_ID>.r2.cloudflarestorage.com",
  "S3_REGION": "auto",
  "S3_BUCKET": "uniclipboard-hyper-chunks",
  "S3_FORCE_PATH_STYLE": "true",
  "S3_KEY_PREFIX": "mailboxes",
  "S3_PRESIGN_TTL_SEC": "300"
}
  1. Create the R2 bucket and 1-day fallback lifecycle rule (when using R2):
npx wrangler r2 bucket create uniclipboard-hyper-chunks
npx wrangler r2 bucket lifecycle add uniclipboard-hyper-chunks expire-orphaned-chunks \
  --prefix mailboxes/ --expire-days 1
  1. Store credentials as Wrangler secrets (never commit secrets into wrangler.jsonc or Git):
# Create an R2 API Token scoped to Object Read & Write on this bucket in the Cloudflare Dashboard
npx wrangler secret put S3_ACCESS_KEY_ID
npx wrangler secret put S3_SECRET_ACCESS_KEY

# Strongly recommended: protect your personal instance from unauthorized use
npx wrangler secret put RELAY_ACCESS_KEY
  1. Bind a custom domain and deploy: Add a custom domain route (custom_domain: true) in wrangler.jsonc or the Dashboard, then deploy:
npx wrangler deploy
curl --fail https://relay.example.com/healthz

Avoid relying on the default *.workers.dev subdomain for production use: it is unreliable in some regions and cannot attach Cloudflare Zone WAF or rate-limiting rules. Always configure RELAY_ACCESS_KEY or RELAY_ALLOWED_PUBKEYS on personal instances so strangers cannot spin up mailboxes and consume your Durable Objects or R2 quota.

About Tencent Cloud Serverless: EdgeOne Pages Functions, SCF, and CloudBase Run lack a native Durable Objects equivalent for stateful single-writer per-mailbox coordination and long-lived SSE fan-out, so no one-click Tencent Cloud serverless template is provided. On Tencent Cloud, run Docker Compose on Lighthouse / CVM with Tencent Cloud COS, or pair Cloudflare Workers with Tencent Cloud COS.

Preventing Unauthorized Use & Hardening

Publicly reachable self-hosted instances support two zero-knowledge-compatible admission controls that can be enabled individually or together:

1. Shared Instance Access Key (RELAY_ACCESS_KEY)

  • Server: Set a high-entropy random secret (for example openssl rand -base64 32) in .env (Docker) or via wrangler secret put RELAY_ACCESS_KEY (Cloudflare).
  • Enforcement: Every control-plane request (both Owner Auth and sender Bearer requests) must include a matching X-Unic-Relay-Key header verified in constant time; missing or invalid keys receive 401.
  • Client: Enter a custom Server URL in Desktop or Mobile settings to reveal the write-only Access key field, set sync.relay.access_key in config.toml, or pass UNIC_RELAY_ACCESS_KEY on the service host. (Official Cloud users sign in instead of entering keys.)
  • Secret isolation: When uploading or downloading chunks directly against presigned object storage URLs, clients strictly strip X-Unic-Relay-Key and all X-Unic-* headers, and never write keys or presigned URLs to logs or backups.

2. Device Public-Key Allowlist (RELAY_ALLOWED_PUBKEYS)

  • Server: Provide a comma-separated list of allowed device Ed25519 public keys (unpadded base64url). Only allowlisted keys can pass Owner Auth (register/revoke delivery tokens, subscribe to SSE, download chunks, or acknowledge transfers).
  • Even if someone discovers your relay hostname, they cannot create mailboxes or trigger object storage writes.
  • Recommended setup: Start with RELAY_ACCESS_KEY to block all unauthenticated traffic at the edge, and optionally layer RELAY_ALLOWED_PUBKEYS to pin access to specific devices.

3. Additional Hardening Tips

  • Quotas & rate limiting: Tune HYPER_MAX_TRANSFER_BYTES, HYPER_MAX_TRANSFERS, and reverse-proxy or Cloudflare Rate Limiting rules to cap request bursts.
  • Health monitoring: Probe GET /healthz and monitor bucket object counts; under normal operation, object count returns to zero within minutes as transfers are acknowledged or expire.

On this page