feat: desktop-agent für windows, macos und linux

Go-Programm lc-agent: sendet neu kopierten Text als Clip ins Projekt
"Zwischenablage" und übernimmt eigene Clips anderer Geräte live in die
Zwischenablage. Von Passwort-Managern markierte Inhalte werden nie
gesendet; Größengrenze, Ausschlussmuster, nur die letzten 50 eigenen
Clips. Wiederholt beim Start, bis der Server erreichbar ist; beendet sich
bei widerrufenem Token mit Exit-Code 3. Build für alle Plattformen per
build.sh im Container, Autostart-Vorlagen für alle drei Systeme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 15:11:40 +01:00
1 parent db700fd003
commit 4aebac5336
23 files changed
+1894 -1

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ data
frontend/dist frontend/dist
*.md *.md
!README.md !README.md
# Desktop agent is built separately (agent/build.sh)
agent
+5 -1
View File
@@ -2,7 +2,7 @@
Selbst gehostetes Web-Clipboard für das private Netz (LAN/VPN). Mehrere Benutzer synchronisieren Texte und Code-Snippets live zwischen ihren Geräten. Selbst gehostetes Web-Clipboard für das private Netz (LAN/VPN). Mehrere Benutzer synchronisieren Texte und Code-Snippets live zwischen ihren Geräten.
> **Stand:** Meilenstein 9 (Stufe A) – API-Tokens und iPhone-Kurzbefehle; Projekte mit anderen Benutzern teilen; Dateiaustausch; Projekte und Suche; als PWA installierbar, für iPhone/iPad optimiert; Live-Sync, Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung. > **Stand:** Meilenstein 9 – API-Tokens, iPhone-Kurzbefehle und Desktop-Agent (`agent/`); Projekte mit anderen Benutzern teilen; Dateiaustausch; Projekte und Suche; als PWA installierbar, für iPhone/iPad optimiert; Live-Sync, Clips (Text und Code mit Syntax-Highlighting), Benutzer, Login, Admin-Verwaltung.
## Aufbau ## Aufbau
@@ -139,6 +139,10 @@ iOS erlaubt keinen Agenten im Hintergrund. Mit einem Token und der App „Kurzbe
Für jedes Gerät einen eigenen Token verwenden, dann lässt sich ein verlorenes iPhone einzeln widerrufen. Für jedes Gerät einen eigenen Token verwenden, dann lässt sich ein verlorenes iPhone einzeln widerrufen.
### Desktop-Agent
Der Agent unter [`agent/`](agent/README.md) synchronisiert die Zwischenablage von Windows-, macOS- und Linux-Rechnern automatisch (Text, beide Richtungen, Passwort-Manager-Inhalte werden nie gesendet). Bauen mit `agent/build.sh` (nur Docker nötig), Einrichtung und Autostart siehe [agent/README.md](agent/README.md).
## Dateien ## Dateien
- Dateien sind Clips der Art „Datei“: Sie stehen in derselben Liste, lassen sich Projekten zuordnen, anheften, über den Dateinamen suchen und werden live auf alle Geräte übertragen. - Dateien sind Clips der Art „Datei“: Sie stehen in derselben Liste, lassen sich Projekten zuordnen, anheften, über den Dateinamen suchen und werden live auf alle Geräte übertragen.
+2
View File
@@ -0,0 +1,2 @@
/.cache/
/dist/
+68
View File
@@ -0,0 +1,68 @@
# lc-agent – Desktop-Agent für LAN-Clipboard
Synchronisiert die Zwischenablage eines Rechners (Windows, macOS, Linux) automatisch mit LAN-Clipboard:
- **Senden:** Neu kopierter Text wird ein Clip im Projekt „Zwischenablage“ (einstellbar). Was beim Start schon in der Zwischenablage liegt, wird nicht gesendet.
- **Empfangen:** Neue Text- und Code-Clips **des eigenen Benutzers** von anderen Geräten (Web-App, iPhone-Kurzbefehl, anderer Rechner) landen sofort in der Zwischenablage. Clips anderer Mitglieder geteilter Projekte werden nicht übernommen.
- Empfangenes wird nicht zurückgeschickt; vom Agent gesendete Clips kommen nicht als „neu“ zurück.
- Vom Agent gesendete Clips werden auf die letzten 50 pro Gerät begrenzt (`keep`), ältere löscht der Agent selbst.
- Nur Text. Dateien und Bilder bleiben der Web-App vorbehalten.
## Passwörter und Datenschutz
- Inhalte, die ein Passwort-Manager als geheim markiert, werden **nie** gesendet:
Windows `ExcludeClipboardContentFromMonitorProcessing` / `Clipboard Viewer Ignore`, macOS `org.nspasteboard.ConcealedType` (auch Transient/AutoGenerated), Linux `x-kde-passwordManagerHint` (KeePassXC u. a.).
- Zusätzlich: Größengrenze (`max_chars`) und eigene Ausschlussmuster (`exclude`, reguläre Ausdrücke), z. B. `"^\\d{6}$"` für 2FA-Codes.
- Das Protokoll enthält nie Inhalte, nur Zeichenzahlen.
- Wer gar nichts automatisch senden will: `"direction": "receive"`.
## Einrichtung
1. In der Web-App unter **Konto → Geräte-Tokens** einen Token für dieses Gerät erstellen.
2. Passende Datei aus `dist/` nehmen (siehe unten) und `lc-agent setup` ausführen: Server-Adresse, Token, Richtung, Projekt. Die Verbindung wird geprüft, die Konfiguration landet in
- Windows: `%APPDATA%\lan-clipboard\agent.json`
- macOS: `~/Library/Application Support/lan-clipboard/agent.json`
- Linux: `~/.config/lan-clipboard/agent.json` (Rechte `0600`)
3. Testen mit `lc-agent run` (Strg+C beendet), dann Autostart einrichten.
| System | Datei | Autostart |
|---|---|---|
| Windows | `lc-agent.exe` (Konsole, für `setup`), `lc-agentw.exe` (ohne Fenster) | `install/autostart-windows.ps1` (Verknüpfung im Autostart-Ordner) |
| macOS Apple Silicon / Intel | `lc-agent-macos-apple` / `lc-agent-macos-intel` | `install/lan-clipboard.agent.plist` (LaunchAgent) |
| Linux x86_64 / ARM | `lc-agent-linux-amd64` / `lc-agent-linux-arm64` | `install/lc-agent.service` (systemd-User-Unit) |
**Linux** braucht `wl-clipboard` (Wayland) oder `xclip` (X11), z. B. `sudo apt install wl-clipboard xclip`.
**macOS:** Die Dateien sind nicht signiert. Nach dem Herunterladen einmal `xattr -d com.apple.quarantine lc-agent-macos-apple` ausführen, sonst blockiert Gatekeeper den Start. Beim ersten Lauf fragt macOS evtl. nach Erlaubnis für den Zugriff auf die Zwischenablage bzw. auf „osascript“.
**Windows:** SmartScreen warnt bei unbekannten Programmen („Weitere Informationen“ → „Trotzdem ausführen“).
## Konfiguration (`agent.json`)
| Feld | Standard | Bedeutung |
|---|---|---|
| `server` | – | z. B. `https://clip.webbildhauer.com` (nur HTTPS, außer `localhost`) |
| `token` | – | Geräte-Token `lc_…` |
| `direction` | `both` | `both`, `send` (nur senden) oder `receive` (nur empfangen) |
| `project` | `Zwischenablage` | Projekt für gesendete Clips; wird angelegt, falls es fehlt. Leer: kein Projekt |
| `keep` | `50` | So viele eigene Clips behält der Agent auf dem Server |
| `max_chars` | `100000` | Längere Inhalte werden nicht gesendet |
| `exclude` | `[]` | Reguläre Ausdrücke; passende Inhalte werden nicht gesendet |
| `poll_ms` | `700` | Abfrageintervall der Zwischenablage |
## Verhalten bei Fehlern
- Server beim Start nicht erreichbar (z. B. vor dem WLAN): neuer Versuch mit wachsender Wartezeit bis 1 Minute.
- Live-Verbindung bricht ab: Wiederverbinden nach 1–30 s.
- Token widerrufen oder Benutzer deaktiviert: Der Agent beendet sich mit Exit-Code **3** (systemd startet ihn dann nicht neu). Neuen Token erstellen und `lc-agent setup` ausführen.
## Entwicklung
```bash
./build.sh # gofmt, go vet (Linux/Windows/macOS), Tests, Builds nach dist/ – nur Docker nötig
```
- `internal/agent`: Abgleich-Logik (plattformunabhängig, mit Fakes getestet)
- `internal/api`: REST und WebSocket mit Token
- `internal/clipboard`: Windows nativ (user32, ohne cgo), macOS über `osascript` (JXA) und `pbcopy`, Linux über `wl-clipboard`/`xclip`
- Getestet: Unit-Tests (auch mit Race-Detector) und ein Ende-zu-Ende-Test unter Linux (Xvfb + xclip gegen den echten Server). Windows und macOS sind gebaut, aber noch nicht auf echten Rechnern geprüft.
Executable
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Checks and builds lc-agent for all platforms in a throwaway Go container.
# Output: dist/. Usage: ./build.sh (needs only Docker on the host)
set -eu
cd "$(dirname "$0")"
VERSION="$(git describe --tags --always --dirty 2>/dev/null || echo dev)"
docker run --rm -v "$PWD":/src -w /src \
-e GOMODCACHE=/src/.cache/mod -e GOCACHE=/src/.cache/build \
-e GOFLAGS=-buildvcs=false -e CGO_ENABLED=0 -e VERSION="$VERSION" \
golang:1.26-alpine sh -euc '
test -z "$(gofmt -l .)" || { gofmt -l .; echo "gofmt: Dateien nicht formatiert"; exit 1; }
for os in linux windows darwin; do GOOS=$os go vet ./...; done
go test ./...
rm -rf dist && mkdir dist
build() { GOOS=$1 GOARCH=$2 go build -trimpath -ldflags "-s -w -X main.version=$VERSION ${4:-}" -o "dist/$3" ./cmd/lc-agent; }
build linux amd64 lc-agent-linux-amd64
build linux arm64 lc-agent-linux-arm64
build darwin amd64 lc-agent-macos-intel
build darwin arm64 lc-agent-macos-apple
build windows amd64 lc-agent.exe
# No console window; for autostart (log with -log)
build windows amd64 lc-agentw.exe "-H=windowsgui"
cd dist && sha256sum * > SHA256SUMS
'
ls -l dist
+213
View File
@@ -0,0 +1,213 @@
// lc-agent syncs the clipboard of this computer with LAN-Clipboard.
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
"golang.org/x/term"
"lan-clipboard/agent/internal/agent"
"lan-clipboard/agent/internal/api"
"lan-clipboard/agent/internal/clipboard"
"lan-clipboard/agent/internal/config"
)
// Set at build time with -ldflags "-X main.version=…"
var version = "dev"
// Exit code for a rejected token, so autostart (systemd) does not restart in a loop
const exitUnauthorized = 3
const usage = `lc-agent – Zwischenablage mit LAN-Clipboard synchronisieren
Befehle:
lc-agent setup Server und Token eingeben, Verbindung prüfen, Konfiguration speichern
lc-agent run Synchronisieren (läuft, bis er beendet wird)
lc-agent version Version anzeigen
Optionen:
-config DATEI Konfigurationsdatei (Standard: %s)
-log DATEI Protokoll in eine Datei statt auf die Konsole schreiben
`
func main() {
defaultPath, _ := config.DefaultPath()
flags := flag.NewFlagSet("lc-agent", flag.ExitOnError)
configPath := flags.String("config", defaultPath, "")
logPath := flags.String("log", "", "")
flags.Usage = func() { fmt.Fprintf(os.Stderr, usage, defaultPath) }
if len(os.Args) < 2 {
flags.Usage()
os.Exit(2)
}
command := os.Args[1]
flags.Parse(os.Args[2:])
var err error
switch command {
case "setup":
err = setup(*configPath)
case "run":
err = run(*configPath, *logPath)
case "version":
fmt.Println("lc-agent", version)
default:
flags.Usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "Fehler:", err)
if errors.Is(err, api.ErrUnauthorized) {
os.Exit(exitUnauthorized)
}
os.Exit(1)
}
}
func run(configPath, logPath string) error {
cfg, err := config.Load(configPath)
if err != nil {
return err
}
out := io.Writer(os.Stderr)
if logPath != "" {
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer file.Close()
out = file
}
logger := log.New(out, "", log.LstdFlags)
cb, err := clipboard.New()
if err != nil {
return err
}
client, err := api.New(cfg.Server, cfg.Token, version)
if err != nil {
return err
}
a, err := agent.New(cfg, client, cb, logger, config.StatePath(configPath))
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := setupWithRetry(ctx, a, logger); err != nil {
return explain(err)
}
err = a.Run(ctx)
if err != nil {
return explain(err)
}
logger.Print("Beendet")
return nil
}
func explain(err error) error {
if errors.Is(err, api.ErrUnauthorized) {
return fmt.Errorf("%w – neuen Token erstellen und \"lc-agent setup\" ausführen", err)
}
return err
}
// setupWithRetry waits for the server, e.g. when the computer starts before the network.
// Only a rejected token ends the agent.
func setupWithRetry(ctx context.Context, a *agent.Agent, logger *log.Logger) error {
delay := 2 * time.Second
for {
err := a.Setup(ctx)
if ctx.Err() != nil {
return nil // stopped while waiting (Ctrl+C, shutdown)
}
if err == nil || errors.Is(err, api.ErrUnauthorized) {
return err
}
logger.Printf("Server nicht erreichbar (%v), neuer Versuch in %s", err, delay)
select {
case <-ctx.Done():
return nil
case <-time.After(delay):
}
delay = min(delay*2, time.Minute)
}
}
func setup(configPath string) error {
in := bufio.NewReader(os.Stdin)
cfg := config.Defaults()
if existing, err := config.Load(configPath); err == nil {
cfg = existing
}
cfg.Server = ask(in, "Server-Adresse", cfg.Server)
fmt.Print("Token (unter \"Konto\" → \"Geräte-Tokens\" erstellen): ")
token, err := readSecret(in)
if err != nil {
return err
}
if token != "" {
cfg.Token = token
}
cfg.Direction = config.Direction(ask(in, "Richtung: both (senden und empfangen), send oder receive", string(cfg.Direction)))
cfg.Project = ask(in, "Projekt für gesendete Clips (leer: keins)", cfg.Project)
if err := cfg.Validate(); err != nil {
return err
}
client, err := api.New(cfg.Server, cfg.Token, version)
if err != nil {
return err
}
user, err := client.Me(context.Background())
if err != nil {
return fmt.Errorf("Verbindung fehlgeschlagen: %w", err)
}
if err := config.Save(configPath, cfg); err != nil {
return err
}
fmt.Printf("Verbunden als %s. Konfiguration gespeichert in %s\n", user.Username, configPath)
fmt.Println("Starten mit: lc-agent run")
return nil
}
func ask(in *bufio.Reader, prompt, current string) string {
if current != "" {
fmt.Printf("%s [%s]: ", prompt, current)
} else {
fmt.Printf("%s: ", prompt)
}
line, _ := in.ReadString('\n')
if line = strings.TrimSpace(line); line != "" {
return line
}
return current
}
// readSecret reads without echo when attached to a terminal.
func readSecret(in *bufio.Reader) (string, error) {
if term.IsTerminal(int(os.Stdin.Fd())) {
data, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return strings.TrimSpace(string(data)), err
}
line, err := in.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
return strings.TrimSpace(line), nil
}
+9
View File
@@ -0,0 +1,9 @@
module lan-clipboard/agent
go 1.26.0
require (
github.com/coder/websocket v1.8.15
golang.org/x/sys v0.49.0
golang.org/x/term v0.47.0
)
+6
View File
@@ -0,0 +1,6 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
+17
View File
@@ -0,0 +1,17 @@
# Windows: start lc-agentw.exe (no console window) at login via the Startup folder.
# Run in PowerShell from the folder containing lc-agentw.exe:
# powershell -ExecutionPolicy Bypass -File autostart-windows.ps1
$target = Join-Path $env:LOCALAPPDATA "lan-clipboard"
New-Item -ItemType Directory -Force -Path $target | Out-Null
Copy-Item -Force (Join-Path $PSScriptRoot "lc-agentw.exe") $target
Copy-Item -Force (Join-Path $PSScriptRoot "lc-agent.exe") $target
$shell = New-Object -ComObject WScript.Shell
$link = $shell.CreateShortcut((Join-Path ([Environment]::GetFolderPath("Startup")) "LAN-Clipboard Agent.lnk"))
$link.TargetPath = Join-Path $target "lc-agentw.exe"
$link.Arguments = "run -log `"$target\agent.log`""
$link.WorkingDirectory = $target
$link.Save()
Write-Host "Autostart eingerichtet. Jetzt einmalig einrichten mit:"
Write-Host " & `"$target\lc-agent.exe`" setup"
Write-Host "Danach abmelden/anmelden oder lc-agentw.exe direkt starten. Protokoll: $target\agent.log"
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!--
macOS LaunchAgent: starts lc-agent at login.
cp lc-agent-macos-apple /usr/local/bin/lc-agent (Intel: lc-agent-macos-intel)
cp lan-clipboard.agent.plist ~/Library/LaunchAgents/
launchctl load ~/Library/LaunchAgents/lan-clipboard.agent.plist
Replace USERNAME below with your macOS user name.
-->
<plist version="1.0">
<dict>
<key>Label</key>
<string>lan-clipboard.agent</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/lc-agent</string>
<string>run</string>
<string>-log</string>
<string>/Users/USERNAME/Library/Logs/lc-agent.log</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>ThrottleInterval</key>
<integer>30</integer>
</dict>
</plist>
+20
View File
@@ -0,0 +1,20 @@
# systemd user unit for Linux.
# cp lc-agent-linux-amd64 ~/.local/bin/lc-agent && chmod +x ~/.local/bin/lc-agent
# cp lc-agent.service ~/.config/systemd/user/
# systemctl --user enable --now lc-agent
# Log: journalctl --user -u lc-agent -f
[Unit]
Description=LAN-Clipboard agent (clipboard sync)
# Needs the graphical session for the clipboard
After=graphical-session.target
PartOf=graphical-session.target
[Service]
ExecStart=%h/.local/bin/lc-agent run
Restart=on-failure
RestartSec=10
# Exit code 3: token revoked; restarting would not help
RestartPreventExitStatus=3
[Install]
WantedBy=graphical-session.target
+304
View File
@@ -0,0 +1,304 @@
// Package agent keeps the local clipboard and the server in sync.
//
// Sending: the clipboard is polled; new text becomes a clip in the agent's project.
// Receiving: new text/code clips of the same user from other devices are written to
// the clipboard. A hash of the last seen content prevents sending received text back.
package agent
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
"unicode/utf8"
"lan-clipboard/agent/internal/api"
"lan-clipboard/agent/internal/clipboard"
"lan-clipboard/agent/internal/config"
)
const (
minRetry = time.Second
maxRetry = 30 * time.Second
)
// Stands for "concealed content" so a secret staying in the clipboard is logged once
var concealedHash = sha256.Sum256([]byte("\x00concealed\x00"))
// API is the part of the server client the agent uses (faked in tests).
type API interface {
Me(ctx context.Context) (api.User, error)
Projects(ctx context.Context) ([]api.Project, error)
CreateProject(ctx context.Context, name string) (api.Project, error)
CreateClip(ctx context.Context, content string, projectID *int64) (api.Clip, error)
DeleteClip(ctx context.Context, id int64) error
Events(ctx context.Context, handle func(api.Event)) error
}
// state is persisted between runs: the ids of clips this device created, oldest first.
type state struct {
Sent []int64 `json:"sent"`
}
type Agent struct {
cfg config.Config
api API
clipboard clipboard.Clipboard
log *log.Logger
statePath string
patterns []*regexp.Regexp
mu sync.Mutex
me int64
projectID *int64
lastHash [32]byte
sent []int64
// Clips created by this device; their live events are not written back
own map[int64]bool
}
func New(cfg config.Config, client API, cb clipboard.Clipboard, logger *log.Logger, statePath string) (*Agent, error) {
patterns, err := cfg.Patterns()
if err != nil {
return nil, err
}
return &Agent{
cfg: cfg,
api: client,
clipboard: cb,
log: logger,
statePath: statePath,
patterns: patterns,
own: map[int64]bool{},
}, nil
}
// Setup identifies the user, finds or creates the project and loads the state.
// Whatever is in the clipboard at start is not sent: only later changes are.
func (a *Agent) Setup(ctx context.Context) error {
me, err := a.api.Me(ctx)
if err != nil {
return err
}
a.me = me.ID
if a.cfg.Project != "" {
id, err := a.ensureProject(ctx, a.cfg.Project)
if err != nil {
return err
}
a.projectID = &id
}
a.loadState()
if content, err := a.clipboard.Read(); err == nil {
a.lastHash = sha256.Sum256([]byte(content.Text))
}
a.log.Printf("Verbunden als %s, Richtung %s, Projekt %q", me.Username, a.cfg.Direction, a.cfg.Project)
return nil
}
func (a *Agent) ensureProject(ctx context.Context, name string) (int64, error) {
projects, err := a.api.Projects(ctx)
if err != nil {
return 0, err
}
for _, p := range projects {
// Only an own project: a shared one with the same name belongs to someone else
if p.Role == "owner" && strings.EqualFold(p.Name, name) {
return p.ID, nil
}
}
project, err := a.api.CreateProject(ctx, name)
if err != nil {
return 0, err
}
a.log.Printf("Projekt %q angelegt", name)
return project.ID, nil
}
// Run polls the clipboard and listens for live events until ctx ends or the token
// is rejected.
func (a *Agent) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
errs := make(chan error, 2)
if a.cfg.Direction.Sends() {
go func() { errs <- a.pollLoop(ctx) }()
}
if a.cfg.Direction.Receives() {
go func() { errs <- a.eventLoop(ctx) }()
}
err := <-errs
if errors.Is(err, context.Canceled) {
return nil
}
return err
}
func (a *Agent) pollLoop(ctx context.Context) error {
ticker := time.NewTicker(time.Duration(a.cfg.PollMs) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := a.Tick(ctx); errors.Is(err, api.ErrUnauthorized) {
return err
}
}
}
}
func (a *Agent) eventLoop(ctx context.Context) error {
delay := minRetry
for {
started := time.Now()
err := a.api.Events(ctx, a.HandleEvent)
if ctx.Err() != nil {
return ctx.Err()
}
if errors.Is(err, api.ErrUnauthorized) {
return err
}
if time.Since(started) > time.Minute {
delay = minRetry // was connected for a while; start backing off anew
}
a.log.Printf("Live-Verbindung unterbrochen (%v), neuer Versuch in %s", err, delay)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
delay = min(delay*2, maxRetry)
}
}
// skipReason tells why a text is not sent, or "" if it may be sent.
func (a *Agent) skipReason(text string) string {
if strings.TrimSpace(text) == "" {
return "leer"
}
if utf8.RuneCountInString(text) > a.cfg.MaxChars {
return "zu lang"
}
for _, re := range a.patterns {
if re.MatchString(text) {
return "Ausschlussmuster"
}
}
return ""
}
// Tick checks the clipboard once and sends new text. Content is never logged.
func (a *Agent) Tick(ctx context.Context) error {
content, err := a.clipboard.Read()
if err != nil {
return nil // transient (clipboard busy); try again next tick
}
hash := sha256.Sum256([]byte(content.Text))
if content.Concealed {
hash = concealedHash // the text is unknown; remember "a secret is there" instead
}
a.mu.Lock()
if hash == a.lastHash {
a.mu.Unlock()
return nil
}
a.lastHash = hash
a.mu.Unlock()
if content.Concealed {
a.log.Print("Von einem Passwort-Manager markierten Inhalt übersprungen")
return nil
}
if reason := a.skipReason(content.Text); reason != "" {
if reason != "leer" {
a.log.Printf("Inhalt nicht gesendet: %s", reason)
}
return nil
}
clip, err := a.api.CreateClip(ctx, content.Text, a.projectID)
if err != nil {
a.log.Printf("Senden fehlgeschlagen: %v", err)
return err
}
a.log.Printf("Gesendet (%d Zeichen)", utf8.RuneCountInString(content.Text))
a.mu.Lock()
a.own[clip.ID] = true
a.sent = append(a.sent, clip.ID)
excess := max(len(a.sent)-a.cfg.Keep, 0)
old := append([]int64(nil), a.sent[:excess]...)
a.sent = a.sent[excess:]
a.mu.Unlock()
for _, id := range old {
if err := a.api.DeleteClip(ctx, id); err != nil {
a.log.Printf("Alten Clip %d nicht gelöscht: %v", id, err)
}
}
a.saveState()
return nil
}
// HandleEvent writes new text/code clips of the same user from other devices to the
// clipboard.
func (a *Agent) HandleEvent(event api.Event) {
if event.Type != "clip.created" {
return
}
var clip api.Clip
if err := json.Unmarshal(event.Data, &clip); err != nil {
return
}
if clip.Kind != "text" && clip.Kind != "code" {
return
}
hash := sha256.Sum256([]byte(clip.Content))
a.mu.Lock()
// Clips of other members of shared projects stay out of this clipboard
skip := clip.UserID != a.me || a.own[clip.ID] || hash == a.lastHash
if !skip {
a.lastHash = hash // so the next poll does not send it back
}
a.mu.Unlock()
if skip {
return
}
if err := a.clipboard.Write(clip.Content); err != nil {
a.log.Printf("Zwischenablage nicht gesetzt: %v", err)
return
}
a.log.Printf("Empfangen (%d Zeichen)", utf8.RuneCountInString(clip.Content))
}
func (a *Agent) loadState() {
data, err := os.ReadFile(a.statePath)
if err != nil {
return
}
var s state
if json.Unmarshal(data, &s) == nil {
a.sent = s.Sent
for _, id := range s.Sent {
a.own[id] = true
}
}
}
func (a *Agent) saveState() {
a.mu.Lock()
data, err := json.Marshal(state{Sent: a.sent})
a.mu.Unlock()
if err != nil {
return
}
tmp := a.statePath + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err == nil {
os.Rename(tmp, a.statePath)
}
}
+280
View File
@@ -0,0 +1,280 @@
package agent
import (
"bytes"
"context"
"encoding/json"
"io"
"log"
"path/filepath"
"strings"
"sync"
"testing"
"lan-clipboard/agent/internal/api"
"lan-clipboard/agent/internal/clipboard"
"lan-clipboard/agent/internal/config"
)
const me = 1
type fakeClipboard struct {
mu sync.Mutex
content clipboard.Content
writes []string
}
func (f *fakeClipboard) Read() (clipboard.Content, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.content, nil
}
func (f *fakeClipboard) Write(text string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.writes = append(f.writes, text)
f.content = clipboard.Content{Text: text}
return nil
}
func (f *fakeClipboard) set(text string, concealed bool) {
f.mu.Lock()
defer f.mu.Unlock()
f.content = clipboard.Content{Text: text, Concealed: concealed}
}
type fakeAPI struct {
projects []api.Project
created []string
clipIDs []int64
deleted []int64
nextID int64
projName string
}
func (f *fakeAPI) Me(context.Context) (api.User, error) {
return api.User{ID: me, Username: "anna"}, nil
}
func (f *fakeAPI) Projects(context.Context) ([]api.Project, error) { return f.projects, nil }
func (f *fakeAPI) CreateProject(_ context.Context, name string) (api.Project, error) {
f.projName = name
return api.Project{ID: 99, Name: name, Role: "owner"}, nil
}
func (f *fakeAPI) CreateClip(_ context.Context, content string, _ *int64) (api.Clip, error) {
f.nextID++
f.created = append(f.created, content)
f.clipIDs = append(f.clipIDs, f.nextID)
return api.Clip{ID: f.nextID, UserID: me, Kind: "text", Content: content}, nil
}
func (f *fakeAPI) DeleteClip(_ context.Context, id int64) error {
f.deleted = append(f.deleted, id)
return nil
}
func (f *fakeAPI) Events(context.Context, func(api.Event)) error { return nil }
type fixture struct {
agent *Agent
api *fakeAPI
cb *fakeClipboard
logs *bytes.Buffer
state string
}
func setup(t *testing.T, mutate func(*config.Config)) fixture {
t.Helper()
cfg := config.Defaults()
cfg.Server, cfg.Token = "https://x.org", "lc_x"
if mutate != nil {
mutate(&cfg)
}
f := fixture{api: &fakeAPI{}, cb: &fakeClipboard{}, logs: &bytes.Buffer{}}
f.state = filepath.Join(t.TempDir(), "state.json")
f.cb.set("already there at start", false)
a, err := New(cfg, f.api, f.cb, log.New(f.logs, "", 0), f.state)
if err != nil {
t.Fatal(err)
}
if err := a.Setup(context.Background()); err != nil {
t.Fatal(err)
}
f.agent = a
return f
}
func (f fixture) tick(t *testing.T) {
t.Helper()
if err := f.agent.Tick(context.Background()); err != nil {
t.Fatal(err)
}
}
func event(t *testing.T, kind string, clip api.Clip) api.Event {
t.Helper()
data, _ := json.Marshal(clip)
return api.Event{Type: kind, Data: data}
}
func TestSendsNewTextOnlyOnce(t *testing.T) {
f := setup(t, nil)
f.tick(t) // content present at start is not sent
f.cb.set("hello", false)
f.tick(t)
f.tick(t)
if strings.Join(f.api.created, "|") != "hello" {
t.Fatalf("sent %q", f.api.created)
}
if strings.Contains(f.logs.String(), "hello") {
t.Fatal("clipboard content must never be logged")
}
}
func TestNeverSendsConcealedContent(t *testing.T) {
f := setup(t, nil)
f.cb.set("", true)
f.tick(t)
f.tick(t)
f.tick(t)
if len(f.api.created) != 0 {
t.Fatal("secret sent")
}
if n := strings.Count(f.logs.String(), "Passwort-Manager"); n != 1 {
t.Fatalf("logged %d times, want once", n)
}
}
func TestSkipsBlankLongAndExcludedText(t *testing.T) {
f := setup(t, func(c *config.Config) {
c.MaxChars = 10
c.Exclude = []string{`^\d{6}$`}
})
for _, text := range []string{" \n", strings.Repeat("ä", 11), "123456"} {
f.cb.set(text, false)
f.tick(t)
}
f.cb.set(strings.Repeat("ä", 10), false)
f.tick(t)
if len(f.api.created) != 1 || f.api.created[0] != strings.Repeat("ä", 10) {
t.Fatalf("sent %q", f.api.created)
}
}
func TestReceivesOwnClipsFromOtherDevices(t *testing.T) {
f := setup(t, nil)
f.agent.HandleEvent(event(t, "clip.created", api.Clip{ID: 50, UserID: me, Kind: "code", Content: "from phone"}))
if strings.Join(f.cb.writes, "|") != "from phone" {
t.Fatalf("written %q", f.cb.writes)
}
f.tick(t) // must not bounce back to the server
if len(f.api.created) != 0 {
t.Fatalf("received text was sent back: %q", f.api.created)
}
}
func TestIgnoresOtherEvents(t *testing.T) {
f := setup(t, nil)
f.cb.set("mine", false)
f.tick(t)
ownID := f.api.clipIDs[0]
for _, e := range []api.Event{
event(t, "clip.created", api.Clip{ID: ownID, UserID: me, Kind: "text", Content: "echo"}),
event(t, "clip.created", api.Clip{ID: 60, UserID: 2, Kind: "text", Content: "other member"}),
event(t, "clip.created", api.Clip{ID: 61, UserID: me, Kind: "file", Content: "bild.png"}),
event(t, "clip.updated", api.Clip{ID: 62, UserID: me, Kind: "text", Content: "edited"}),
{Type: "clip.created", Data: json.RawMessage(`not json`)},
} {
f.agent.HandleEvent(e)
}
if len(f.cb.writes) != 0 {
t.Fatalf("written %q", f.cb.writes)
}
}
func TestDirection(t *testing.T) {
f := setup(t, func(c *config.Config) { c.Direction = config.Receive })
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := f.agent.Run(ctx); err != nil {
t.Fatal(err)
}
if len(f.api.created) != 0 {
t.Fatal("receive-only agent sent something")
}
}
func TestKeepsOnlyTheNewestClips(t *testing.T) {
f := setup(t, func(c *config.Config) { c.Keep = 2 })
for _, text := range []string{"a", "b", "c", "d"} {
f.cb.set(text, false)
f.tick(t)
}
if got := f.api.deleted; len(got) != 2 || got[0] != 1 || got[1] != 2 {
t.Fatalf("deleted %v, want [1 2]", got)
}
// State survives a restart: the next send deletes clip 3
again, _ := New(f.agent.cfg, f.api, f.cb, log.New(io.Discard, "", 0), f.state)
again.Setup(context.Background())
f.cb.set("e", false)
again.Tick(context.Background())
if got := f.api.deleted; len(got) != 3 || got[2] != 3 {
t.Fatalf("deleted %v after restart", got)
}
}
func TestProjectSetup(t *testing.T) {
f := setup(t, nil)
if f.api.projName != "Zwischenablage" || *f.agent.projectID != 99 {
t.Fatalf("project not created: %q", f.api.projName)
}
existing := &fakeAPI{projects: []api.Project{
{ID: 5, Name: "zwischenablage", Role: "edit"}, // shared by someone else: not ours
{ID: 6, Name: "Zwischenablage", Role: "owner"},
}}
cfg := f.agent.cfg
a, _ := New(cfg, existing, f.cb, log.New(io.Discard, "", 0), f.state)
a.Setup(context.Background())
if *a.projectID != 6 || existing.projName != "" {
t.Fatalf("existing own project not used: %v", *a.projectID)
}
cfg.Project = ""
none, _ := New(cfg, &fakeAPI{}, f.cb, log.New(io.Discard, "", 0), f.state)
none.Setup(context.Background())
if none.projectID != nil {
t.Fatal("no project configured, but one is used")
}
}
// Polling and live events run in separate goroutines; run with -race.
func TestTickAndEventsConcurrently(t *testing.T) {
f := setup(t, nil)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := range 200 {
f.cb.set(strings.Repeat("x", i%7+1), false)
f.agent.Tick(context.Background())
}
}()
go func() {
defer wg.Done()
for i := range 200 {
f.agent.HandleEvent(event(t, "clip.created", api.Clip{ID: int64(1000 + i), UserID: me, Kind: "text", Content: "remote"}))
}
}()
wg.Wait()
}
+190
View File
@@ -0,0 +1,190 @@
// Package api talks to the LAN-Clipboard server with a device token.
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
"strings"
"time"
"github.com/coder/websocket"
)
// ErrUnauthorized means the token is invalid, revoked or its user deactivated.
var ErrUnauthorized = errors.New("Token ungültig oder widerrufen")
const (
closeUnauthorized = 4401
// The server pings every 30 s; silence beyond this means the connection is dead
readTimeout = 75 * time.Second
// Largest event: a clip of up to 200,000 characters, JSON-escaped
maxMessageBytes = 4 << 20
)
type Clip struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Kind string `json:"kind"`
Content string `json:"content"`
ProjectID *int64 `json:"project_id"`
}
type Project struct {
ID int64 `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
}
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
}
// Event is a live-sync message, e.g. {"type": "clip.created", "data": {...}}.
type Event struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}
type Client struct {
base *url.URL
token string
userAgent string
http *http.Client
}
func New(server, token, version string) (*Client, error) {
base, err := url.Parse(strings.TrimRight(server, "/"))
if err != nil {
return nil, err
}
return &Client{
base: base,
token: token,
userAgent: fmt.Sprintf("lc-agent/%s (%s)", version, runtime.GOOS),
http: &http.Client{Timeout: 30 * time.Second},
}, nil
}
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
var reader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, c.base.String()+path, reader)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return ErrUnauthorized
}
if resp.StatusCode >= 300 {
return fmt.Errorf("%s %s: %s", method, path, errorDetail(resp))
}
if out == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
func errorDetail(resp *http.Response) string {
var payload struct {
Detail any `json:"detail"`
}
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
if json.Unmarshal(data, &payload) == nil {
if s, ok := payload.Detail.(string); ok {
return fmt.Sprintf("%d %s", resp.StatusCode, s)
}
}
return resp.Status
}
func (c *Client) Me(ctx context.Context) (User, error) {
var user User
return user, c.do(ctx, http.MethodGet, "/api/users/me", nil, &user)
}
func (c *Client) Projects(ctx context.Context) ([]Project, error) {
var projects []Project
return projects, c.do(ctx, http.MethodGet, "/api/projects", nil, &projects)
}
func (c *Client) CreateProject(ctx context.Context, name string) (Project, error) {
var project Project
return project, c.do(ctx, http.MethodPost, "/api/projects", map[string]string{"name": name}, &project)
}
func (c *Client) CreateClip(ctx context.Context, content string, projectID *int64) (Clip, error) {
var clip Clip
body := map[string]any{"content": content, "kind": "text", "project_id": projectID}
return clip, c.do(ctx, http.MethodPost, "/api/clips", body, &clip)
}
// DeleteClip deletes a clip; one that is already gone counts as success.
func (c *Client) DeleteClip(ctx context.Context, id int64) error {
err := c.do(ctx, http.MethodDelete, fmt.Sprintf("/api/clips/%d", id), nil, nil)
if err != nil && strings.Contains(err.Error(), ": 404") {
return nil
}
return err
}
// Events connects to the live sync and calls handle for every message until the
// connection ends. It returns ErrUnauthorized if the server rejects the token.
func (c *Client) Events(ctx context.Context, handle func(Event)) error {
wsURL := *c.base
wsURL.Scheme = map[string]string{"https": "wss", "http": "ws"}[c.base.Scheme]
wsURL.Path += "/api/ws"
header := http.Header{}
header.Set("Authorization", "Bearer "+c.token)
header.Set("User-Agent", c.userAgent)
conn, resp, err := websocket.Dial(ctx, wsURL.String(), &websocket.DialOptions{HTTPHeader: header})
if err != nil {
if resp != nil && resp.StatusCode == http.StatusUnauthorized {
return ErrUnauthorized
}
return err
}
defer conn.CloseNow()
conn.SetReadLimit(maxMessageBytes)
for {
readCtx, cancel := context.WithTimeout(ctx, readTimeout)
_, data, err := conn.Read(readCtx)
cancel()
if err != nil {
if websocket.CloseStatus(err) == closeUnauthorized {
return ErrUnauthorized
}
return err
}
var event Event
if json.Unmarshal(data, &event) == nil {
handle(event)
}
}
}
+107
View File
@@ -0,0 +1,107 @@
package api
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
)
func newServer(t *testing.T, handler http.HandlerFunc) *Client {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
client, err := New(srv.URL+"/", "lc_token", "test")
if err != nil {
t.Fatal(err)
}
return client
}
func TestRequestsCarryTokenAndJSON(t *testing.T) {
var seen *http.Request
var body map[string]any
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
seen = r
data, _ := io.ReadAll(r.Body)
json.Unmarshal(data, &body)
w.WriteHeader(http.StatusCreated)
io.WriteString(w, `{"id": 7, "user_id": 1, "kind": "text", "content": "hi", "project_id": 3}`)
})
project := int64(3)
clip, err := client.CreateClip(context.Background(), "hi", &project)
if err != nil {
t.Fatal(err)
}
if clip.ID != 7 || *clip.ProjectID != 3 {
t.Fatalf("unexpected clip %+v", clip)
}
if seen.URL.Path != "/api/clips" || seen.Method != http.MethodPost {
t.Fatalf("unexpected request %s %s", seen.Method, seen.URL.Path)
}
if seen.Header.Get("Authorization") != "Bearer lc_token" {
t.Fatal("token missing")
}
if !strings.HasPrefix(seen.Header.Get("User-Agent"), "lc-agent/test") {
t.Fatalf("user agent %q", seen.Header.Get("User-Agent"))
}
if body["content"] != "hi" || body["kind"] != "text" || body["project_id"] != float64(3) {
t.Fatalf("unexpected body %v", body)
}
}
func TestErrors(t *testing.T) {
status := http.StatusUnauthorized
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
io.WriteString(w, `{"detail": "Projekt nicht gefunden."}`)
})
if _, err := client.Me(context.Background()); !errors.Is(err, ErrUnauthorized) {
t.Fatalf("want ErrUnauthorized, got %v", err)
}
status = http.StatusNotFound
if err := client.DeleteClip(context.Background(), 5); err != nil {
t.Fatalf("deleting a missing clip should succeed: %v", err)
}
if _, err := client.CreateProject(context.Background(), "x"); err == nil ||
!strings.Contains(err.Error(), "Projekt nicht gefunden.") {
t.Fatalf("detail not reported: %v", err)
}
}
func TestEventsDeliversMessagesAndDetectsRevokedToken(t *testing.T) {
client := newServer(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/ws" || r.Header.Get("Authorization") != "Bearer lc_token" {
http.Error(w, "bad", http.StatusBadRequest)
return
}
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
ctx := r.Context()
conn.Write(ctx, websocket.MessageText, []byte(`{"type":"hello"}`))
conn.Write(ctx, websocket.MessageText, []byte(`{"type":"clip.created","data":{"id":1}}`))
conn.Close(4401, "revoked")
})
var types []string
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := client.Events(ctx, func(e Event) { types = append(types, e.Type) })
if !errors.Is(err, ErrUnauthorized) {
t.Fatalf("want ErrUnauthorized, got %v", err)
}
if strings.Join(types, ",") != "hello,clip.created" {
t.Fatalf("events %v", types)
}
}
+16
View File
@@ -0,0 +1,16 @@
// Package clipboard reads and writes the system clipboard (text only) and detects
// content that password managers mark as secret.
package clipboard
// Content is the current clipboard text. Concealed is set when a password manager
// marked it as secret; the text is then left empty and must never be sent anywhere.
type Content struct {
Text string
Concealed bool
}
// Clipboard is implemented per operating system (see New in the *_<os>.go files).
type Clipboard interface {
Read() (Content, error)
Write(text string) error
}
@@ -0,0 +1,70 @@
package clipboard
import (
"context"
"encoding/json"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// JXA script: returns the pasteboard's change count and, if it changed since the count
// passed as argument, its types and text. One osascript call per poll, no cgo needed.
const readScript = `
ObjC.import('AppKit');
function run(argv) {
const pb = $.NSPasteboard.generalPasteboard;
const count = Number(pb.changeCount);
if (String(count) === argv[0]) return JSON.stringify({ count: count, same: true });
const types = ObjC.deepUnwrap(pb.types) || [];
const text = ObjC.unwrap(pb.stringForType($.NSPasteboardTypeString)) || '';
return JSON.stringify({ count: count, types: types, text: text });
}`
type darwinClipboard struct {
lastCount int
last Content
}
func New() (Clipboard, error) {
return &darwinClipboard{lastCount: -1}, nil
}
func (c *darwinClipboard) Read() (Content, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "osascript", "-l", "JavaScript", "-e", readScript,
strconv.Itoa(c.lastCount)).Output()
if err != nil {
return Content{}, err
}
var result struct {
Count int `json:"count"`
Same bool `json:"same"`
Types []string `json:"types"`
Text string `json:"text"`
}
if err := json.Unmarshal(out, &result); err != nil {
return Content{}, err
}
if result.Same {
return c.last, nil
}
c.lastCount = result.Count
if isConcealed(result.Types) {
c.last = Content{Concealed: true}
} else {
c.last = Content{Text: result.Text}
}
return c.last, nil
}
func (c *darwinClipboard) Write(text string) error {
cmd := exec.Command("pbcopy")
// pbcopy only keeps non-ASCII text intact with a UTF-8 locale
cmd.Env = append(os.Environ(), "LANG=en_US.UTF-8")
cmd.Stdin = strings.NewReader(text)
return cmd.Run()
}
@@ -0,0 +1,86 @@
package clipboard
import (
"bytes"
"context"
"errors"
"os"
"os/exec"
"strings"
"time"
)
const commandTimeout = 3 * time.Second
// Linux has no clipboard API without a toolkit; the standard tools are used instead:
// wl-clipboard on Wayland, xclip on X11.
type linuxClipboard struct {
listTypes []string
read func(textType string) []string
write []string
}
// New picks Wayland or X11 depending on the session and the installed tools.
func New() (Clipboard, error) {
if os.Getenv("WAYLAND_DISPLAY") != "" && hasCommand("wl-paste") && hasCommand("wl-copy") {
return &linuxClipboard{
listTypes: []string{"wl-paste", "--list-types"},
read: func(t string) []string { return []string{"wl-paste", "--no-newline", "--type", t} },
write: []string{"wl-copy"},
}, nil
}
if os.Getenv("DISPLAY") != "" && hasCommand("xclip") {
return &linuxClipboard{
listTypes: []string{"xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"},
read: func(t string) []string { return []string{"xclip", "-selection", "clipboard", "-t", t, "-o"} },
write: []string{"xclip", "-selection", "clipboard", "-i"},
}, nil
}
return nil, errors.New("keine Zwischenablage gefunden: unter Wayland wl-clipboard, unter X11 xclip installieren")
}
func hasCommand(name string) bool {
_, err := exec.LookPath(name)
return err == nil
}
func run(args []string, stdin string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
if stdin != "" {
cmd.Stdin = strings.NewReader(stdin)
}
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
return out.String(), err
}
func (c *linuxClipboard) Read() (Content, error) {
output, err := run(c.listTypes, "")
if err != nil {
// Empty clipboard: the tools exit with an error; not worth reporting
return Content{}, nil
}
types := parseTypes(output)
if isConcealed(types) {
return Content{Concealed: true}, nil
}
textType := textType(types)
if textType == "" {
return Content{}, nil
}
text, err := run(c.read(textType), "")
if err != nil {
return Content{}, err
}
return Content{Text: text}, nil
}
func (c *linuxClipboard) Write(text string) error {
// xclip and wl-copy keep serving the selection in the background after we return
cmd := exec.Command(c.write[0], c.write[1:]...)
cmd.Stdin = strings.NewReader(text)
return cmd.Run()
}
@@ -0,0 +1,141 @@
package clipboard
import (
"errors"
"runtime"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
const (
cfUnicodeText = 13
gmemMoveable = 0x0002
)
var (
user32 = windows.NewLazySystemDLL("user32.dll")
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
openClipboard = user32.NewProc("OpenClipboard")
closeClipboard = user32.NewProc("CloseClipboard")
emptyClipboard = user32.NewProc("EmptyClipboard")
getClipboardData = user32.NewProc("GetClipboardData")
setClipboardData = user32.NewProc("SetClipboardData")
isClipboardFormatAvailable = user32.NewProc("IsClipboardFormatAvailable")
registerClipboardFormat = user32.NewProc("RegisterClipboardFormatW")
globalAlloc = kernel32.NewProc("GlobalAlloc")
globalFree = kernel32.NewProc("GlobalFree")
globalLock = kernel32.NewProc("GlobalLock")
globalUnlock = kernel32.NewProc("GlobalUnlock")
)
// Formats that password managers and other tools set to keep content out of
// clipboard history and sync tools (documented by Microsoft for cloud clipboard).
var concealedFormats = []string{
"ExcludeClipboardContentFromMonitorProcessing",
"Clipboard Viewer Ignore",
}
type windowsClipboard struct {
concealed []uintptr
}
func New() (Clipboard, error) {
c := &windowsClipboard{}
for _, name := range concealedFormats {
ptr, err := windows.UTF16PtrFromString(name)
if err != nil {
return nil, err
}
if id, _, _ := registerClipboardFormat.Call(uintptr(unsafe.Pointer(ptr))); id != 0 {
c.concealed = append(c.concealed, id)
}
}
return c, nil
}
// lockedMemory turns the address returned by GlobalLock into a pointer. The memory is
// owned by Windows and locked, not part of the Go heap, so the garbage collector cannot
// move it; reading the uintptr through a pointer keeps "go vet" from flagging the
// (here intended) uintptr conversion.
func lockedMemory(addr uintptr) unsafe.Pointer {
return *(*unsafe.Pointer)(unsafe.Pointer(&addr))
}
// open retries briefly: another program may hold the clipboard for a moment.
func open() error {
for i := 0; i < 10; i++ {
if r, _, _ := openClipboard.Call(0); r != 0 {
return nil
}
time.Sleep(20 * time.Millisecond)
}
return errors.New("Zwischenablage ist belegt")
}
func available(format uintptr) bool {
r, _, _ := isClipboardFormatAvailable.Call(format)
return r != 0
}
func (c *windowsClipboard) Read() (Content, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if err := open(); err != nil {
return Content{}, err
}
defer closeClipboard.Call()
for _, format := range c.concealed {
if available(format) {
return Content{Concealed: true}, nil
}
}
if !available(cfUnicodeText) {
return Content{}, nil
}
handle, _, _ := getClipboardData.Call(cfUnicodeText)
if handle == 0 {
return Content{}, nil
}
ptr, _, _ := globalLock.Call(handle)
if ptr == 0 {
return Content{}, errors.New("Zwischenablage nicht lesbar")
}
defer globalUnlock.Call(handle)
return Content{Text: windows.UTF16PtrToString((*uint16)(lockedMemory(ptr)))}, nil
}
func (c *windowsClipboard) Write(text string) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
data, err := windows.UTF16FromString(text)
if err != nil {
return err
}
if err := open(); err != nil {
return err
}
defer closeClipboard.Call()
emptyClipboard.Call()
size := uintptr(len(data) * 2)
handle, _, _ := globalAlloc.Call(gmemMoveable, size)
if handle == 0 {
return errors.New("kein Speicher für die Zwischenablage")
}
ptr, _, _ := globalLock.Call(handle)
if ptr == 0 {
globalFree.Call(handle)
return errors.New("kein Speicher für die Zwischenablage")
}
copy(unsafe.Slice((*uint16)(lockedMemory(ptr)), len(data)), data)
globalUnlock.Call(handle)
// On success the system owns the memory; only free it if the hand-over failed
if r, _, _ := setClipboardData.Call(cfUnicodeText, handle); r == 0 {
globalFree.Call(handle)
return errors.New("Zwischenablage konnte nicht gesetzt werden")
}
return nil
}
+49
View File
@@ -0,0 +1,49 @@
package clipboard
import "strings"
// Markers set by password managers (KeePassXC, 1Password, Bitwarden, …) on Linux and macOS.
// Windows uses registered clipboard formats instead (see clipboard_windows.go).
var concealedTypes = map[string]bool{
"x-kde-passwordManagerHint": true, // Linux (KDE convention, KeePassXC)
"org.nspasteboard.ConcealedType": true, // macOS
"org.nspasteboard.TransientType": true, // macOS: not meant to be kept
"org.nspasteboard.AutoGeneratedType": true,
}
// Text types offered by X11/Wayland clipboards, in order of preference.
var textTypes = []string{"text/plain;charset=utf-8", "UTF8_STRING", "text/plain", "STRING", "TEXT"}
// parseTypes splits the output of "wl-paste --list-types" or "xclip -t TARGETS -o".
func parseTypes(output string) []string {
var types []string
for _, line := range strings.Split(output, "\n") {
if line = strings.TrimSpace(line); line != "" {
types = append(types, line)
}
}
return types
}
func isConcealed(types []string) bool {
for _, t := range types {
if concealedTypes[t] {
return true
}
}
return false
}
// textType returns the best text type on offer, or "" (e.g. only an image was copied).
func textType(types []string) string {
offered := make(map[string]bool, len(types))
for _, t := range types {
offered[t] = true
}
for _, t := range textTypes {
if offered[t] {
return t
}
}
return ""
}
+26
View File
@@ -0,0 +1,26 @@
package clipboard
import "testing"
func TestParseTypes(t *testing.T) {
got := parseTypes("TARGETS\n UTF8_STRING \n\nx-kde-passwordManagerHint\n")
if len(got) != 3 || got[1] != "UTF8_STRING" {
t.Fatalf("got %q", got)
}
}
func TestConcealedAndTextType(t *testing.T) {
keepass := []string{"TARGETS", "x-kde-passwordManagerHint", "UTF8_STRING"}
if !isConcealed(keepass) {
t.Fatal("KeePassXC hint not detected")
}
if isConcealed([]string{"UTF8_STRING", "text/plain"}) {
t.Fatal("plain text treated as secret")
}
if got := textType([]string{"STRING", "text/plain;charset=utf-8"}); got != "text/plain;charset=utf-8" {
t.Fatalf("preferred type %q", got)
}
if textType([]string{"image/png"}) != "" {
t.Fatal("image treated as text")
}
}
+139
View File
@@ -0,0 +1,139 @@
// Package config loads and stores the agent configuration (server, token, options).
package config
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
// Direction controls which way the clipboard is synchronised.
type Direction string
const (
Both Direction = "both"
Send Direction = "send"
Receive Direction = "receive"
)
// Config is stored as JSON; the file contains the token and is only readable by the user.
type Config struct {
Server string `json:"server"`
Token string `json:"token"`
Direction Direction `json:"direction"`
// Project for clips sent by the agent; created if missing. Empty: no project.
Project string `json:"project"`
// Number of own clips kept on the server; older ones are deleted by the agent.
Keep int `json:"keep"`
MaxChars int `json:"max_chars"`
Exclude []string `json:"exclude"`
PollMs int `json:"poll_ms"`
}
// Defaults returns the configuration used for missing fields.
func Defaults() Config {
return Config{
Direction: Both,
Project: "Zwischenablage",
Keep: 50,
MaxChars: 100_000,
Exclude: []string{},
PollMs: 700,
}
}
// DefaultPath is <user config dir>/lan-clipboard/agent.json.
func DefaultPath() (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "lan-clipboard", "agent.json"), nil
}
// StatePath is the file next to the config that remembers the agent's own clips.
func StatePath(configPath string) string {
return filepath.Join(filepath.Dir(configPath), "agent-state.json")
}
// Load reads the config file on top of the defaults and validates it.
func Load(path string) (Config, error) {
cfg := Defaults()
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return cfg, fmt.Errorf("keine Konfiguration unter %s – zuerst \"lc-agent setup\" ausführen", path)
}
return cfg, err
}
if err := json.Unmarshal(data, &cfg); err != nil {
return cfg, fmt.Errorf("%s: %w", path, err)
}
return cfg, cfg.Validate()
}
// Save writes the config atomically with permissions 0600 (directory 0700).
func Save(path string, cfg Config) error {
if err := cfg.Validate(); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// Validate checks all fields; the token is only sent over HTTPS (or to localhost).
func (c Config) Validate() error {
u, err := url.Parse(c.Server)
if err != nil || u.Host == "" {
return fmt.Errorf("ungültige Server-Adresse %q", c.Server)
}
local := u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1"
if u.Scheme != "https" && !(u.Scheme == "http" && local) {
return errors.New("die Server-Adresse muss mit https:// beginnen")
}
if !strings.HasPrefix(c.Token, "lc_") {
return errors.New("der Token muss mit lc_ beginnen (unter \"Konto\" → \"Geräte-Tokens\" erstellen)")
}
switch c.Direction {
case Both, Send, Receive:
default:
return fmt.Errorf("ungültige Richtung %q (both, send oder receive)", c.Direction)
}
if c.Keep < 1 || c.MaxChars < 1 || c.PollMs < 100 {
return errors.New("keep und max_chars müssen ≥ 1 sein, poll_ms ≥ 100")
}
_, err = c.Patterns()
return err
}
// Patterns compiles the exclude expressions.
func (c Config) Patterns() ([]*regexp.Regexp, error) {
patterns := make([]*regexp.Regexp, 0, len(c.Exclude))
for _, expr := range c.Exclude {
re, err := regexp.Compile(expr)
if err != nil {
return nil, fmt.Errorf("Ausschlussmuster %q: %w", expr, err)
}
patterns = append(patterns, re)
}
return patterns, nil
}
// Sends and Receives tell whether the direction includes that way.
func (d Direction) Sends() bool { return d == Both || d == Send }
func (d Direction) Receives() bool { return d == Both || d == Receive }
+87
View File
@@ -0,0 +1,87 @@
package config
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func valid() Config {
cfg := Defaults()
cfg.Server = "https://clip.example.org"
cfg.Token = "lc_abc"
return cfg
}
func TestSaveAndLoad(t *testing.T) {
path := filepath.Join(t.TempDir(), "sub", "agent.json")
cfg := valid()
cfg.Exclude = []string{`^\d{6}$`}
if err := Save(path, cfg); err != nil {
t.Fatal(err)
}
got, err := Load(path)
if err != nil {
t.Fatal(err)
}
if got.Server != cfg.Server || got.Token != cfg.Token || got.Exclude[0] != cfg.Exclude[0] {
t.Fatalf("roundtrip mismatch: %+v", got)
}
if runtime.GOOS != "windows" {
info, _ := os.Stat(path)
if info.Mode().Perm() != 0o600 {
t.Fatalf("config readable by others: %v", info.Mode())
}
}
}
func TestLoadFillsDefaults(t *testing.T) {
path := filepath.Join(t.TempDir(), "agent.json")
os.WriteFile(path, []byte(`{"server":"https://x.org","token":"lc_x"}`), 0o600)
cfg, err := Load(path)
if err != nil {
t.Fatal(err)
}
if cfg.Direction != Both || cfg.Keep != 50 || cfg.Project != "Zwischenablage" {
t.Fatalf("defaults missing: %+v", cfg)
}
}
func TestMissingFileExplainsSetup(t *testing.T) {
_, err := Load(filepath.Join(t.TempDir(), "nope.json"))
if err == nil || !strings.Contains(err.Error(), "lc-agent setup") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestValidate(t *testing.T) {
cases := map[string]func(*Config){
"http to remote": func(c *Config) { c.Server = "http://clip.example.org" },
"no host": func(c *Config) { c.Server = "https://" },
"bad token": func(c *Config) { c.Token = "secret" },
"bad direction": func(c *Config) { c.Direction = "sideways" },
"keep zero": func(c *Config) { c.Keep = 0 },
"poll too fast": func(c *Config) { c.PollMs = 10 },
"bad exclude": func(c *Config) { c.Exclude = []string{"("} },
}
for name, mutate := range cases {
cfg := valid()
mutate(&cfg)
if cfg.Validate() == nil {
t.Errorf("%s: expected an error", name)
}
}
local := valid()
local.Server = "http://localhost:8000"
if err := local.Validate(); err != nil {
t.Errorf("localhost over http should be allowed: %v", err)
}
}
func TestDirection(t *testing.T) {
if !Both.Sends() || !Both.Receives() || Send.Receives() || Receive.Sends() {
t.Fatal("direction helpers wrong")
}
}