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:
1 parent
db700fd003
commit
4aebac5336
23 files changed
+1894
-1
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user