Add explicit Remote clipboard text transfer

A session-only option adds clipboard-exchange to the consent request.
Sending reads the clipboard only through an explicit command and sends
up to 8 KiB of text; files are refused. Received text is held in memory
and copied to the clipboard only by an explicit receive command, once.
Nothing is written or spoken automatically and disconnect discards it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chase CichorzandClaude Opus 5.5 committed 2026-11-06 16:06:38 -05:00
1 parent 2541ce58e4
commit db19f04c43
11 files changed
+333 -4

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"encoding/json"
"slices"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// Clipboard transfer is explicit in both directions. Sending reads this
// computer's clipboard only when the user runs the send command. Received text
// is held in memory for this connection and written to the clipboard only when
// the user runs the receive command; it never overwrites the clipboard by
// itself, is never spoken automatically and is dropped at disconnect.
func (stream *speechStream) clipboard_enabled() bool {
return slices.Contains(stream.grants, "clipboard-exchange")
}
// receive_clipboard keeps the newest peer text, replacing older unread text.
// Membership/origin checks already ran in the relay reader.
func (c *coordinator) receive_clipboard(a *connectionAttempt, stream *speechStream, message message) bool {
if message.kind != "set_clipboard_text" || !stream.clipboard_enabled() {
return false
}
text, ok := message.payload.(string)
if !ok || !boundedText(text, maxTextBytes) {
return false
}
c.mu.Lock()
defer c.mu.Unlock()
if c.active == a && a.ctx.Err() == nil {
stream.received, stream.hasReceived = text, true
}
return true
}
// send_clipboard queues one explicit transfer on the ordered relay writer.
func (c *coordinator) send_clipboard(text string) error {
if text == "" || !boundedText(text, maxTextBytes) {
return errLimit
}
frame, err := encodeMessage("set_clipboard_text", map[string]string{"text": text})
if err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
a := c.active
if a == nil || a.speech == nil || !a.speech.clipboard_enabled() || !c.speech_ready_locked(a, a.speech) {
return errLease
}
stream := a.speech
if stream.items == maxSpeechItems || stream.bytes+len(frame) > maxQueuedBytes {
return errLimit
}
stream.items++
stream.bytes += len(frame)
stream.outgoing <- frame // Capacity reserved above.
return nil
}
// take_clipboard returns unread peer text once.
func (c *coordinator) take_clipboard() (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
a := c.active
if a == nil || a.speech == nil || !a.speech.hasReceived || a.ctx.Err() != nil {
return "", false
}
text := a.speech.received
a.speech.received, a.speech.hasReceived = "", false
return text, true
}
func (c *coordinator) clipboard_waiting() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.active != nil && c.active.speech != nil && c.active.speech.hasReceived && c.active.ctx.Err() == nil
}
func clipboard_message(text string) sdk.Interaction {
return sdk.Interaction{Presentation: sdk.Presentation{Speech: text, Braille: text}, Done: true}
}
// send_clipboard_command asks the reader for the clipboard as an explicit,
// user-initiated read; send_clipboard_item receives it.
func (command *connectionCommand) send_clipboard_command(ctx context.Context, _ json.RawMessage) (any, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return sdk.Interaction{Source: "clipboard", Next: "remote-clipboard-item"}, nil
}
func (command *connectionCommand) send_clipboard_item(ctx context.Context, raw json.RawMessage) (any, error) {
var value sdk.Submission
if json.Unmarshal(raw, &value) != nil {
return nil, sdk.ErrProtocol
}
if ctx.Err() != nil || value.Cancelled {
return clipboard_message("Clipboard not sent."), nil
}
if value.Item == nil || value.Item.Path != "" || value.Item.Text == "" {
return clipboard_message("Only clipboard text can be sent. Files are not transferred."), nil
}
switch command.coordinator.send_clipboard(value.Item.Text) {
case nil:
return clipboard_message("Clipboard text sent to the other computer."), nil
case errLimit:
return clipboard_message("Clipboard text is too large to send. The limit is 8 kilobytes."), nil
default:
return clipboard_message("Clipboard transfer needs a connected session with clipboard transfer approved."), nil
}
}
func (command *connectionCommand) receive_clipboard_command(ctx context.Context, _ json.RawMessage) (any, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
text, ok := command.coordinator.take_clipboard()
if !ok {
return clipboard_message("No clipboard text has been received from the other computer."), nil
}
result := clipboard_message("Received clipboard text copied to this computer's clipboard.")
result.Clipboard = &text
return result, nil
}
+143
View File
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"encoding/json"
"io"
"net"
"strings"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// clipboardRelay joins one peer of the opposite role, sends the supplied
// frames and records clipboard frames from this computer.
func clipboardRelay(t *testing.T, r role, frames []string, received chan<- string) endpoint {
t.Helper()
cert, roots := testCertificate(t, true)
peer := "slave"
if r == controlled {
peer = "master"
}
e := testRelay(t, cert, func(conn net.Conn) {
reader := relayHandshake(t, conn, r)
if reader == nil {
return
}
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"`+peer+`"}]}`+"\n")
for _, frame := range frames {
_, _ = io.WriteString(conn, frame+"\n")
}
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
if strings.Contains(line, "set_clipboard_text") {
received <- strings.TrimSpace(line)
}
}
})
e.roots = roots
return e
}
func clipboardSubmit(t *testing.T, command *connectionCommand, item *sdk.Item) sdk.Interaction {
t.Helper()
raw, _ := json.Marshal(sdk.Submission{Item: item})
value, err := command.send_clipboard_item(t.Context(), raw)
if err != nil {
t.Fatal(err)
}
return value.(sdk.Interaction)
}
func TestClipboardExplicitTransferBothDirections(t *testing.T) {
for _, roleName := range []string{"controller", "controlled"} {
t.Run(roleName, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
command := &connectionCommand{coordinator: c}
r, grant := controller, "remote-present"
if roleName == "controlled" {
r, grant = controlled, "output-observe"
}
action := approveGrants(t, c, f, 1, roleName, grant, "clipboard-exchange")
text := " tab\\tline\\n é 世界 "
received := make(chan string, 4)
incoming := `{"type":"set_clipboard_text","origin":7,"text":"from peer é"}`
if err := c.connect(action, clipboardRelay(t, r, []string{incoming}, received), "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" })
deadline := time.Now().Add(4 * time.Second)
for !c.clipboard_waiting() {
if time.Now().After(deadline) {
t.Fatal("received clipboard not held")
}
time.Sleep(time.Millisecond)
}
value, _ := command.receive_clipboard_command(t.Context(), nil)
result := value.(sdk.Interaction)
if result.Clipboard == nil || *result.Clipboard != "from peer é" {
t.Fatal("receive did not return the held text", result)
}
value, _ = command.receive_clipboard_command(t.Context(), nil)
if value.(sdk.Interaction).Clipboard != nil {
t.Fatal("held text was returned twice")
}
start, _ := command.send_clipboard_command(t.Context(), nil)
if start.(sdk.Interaction).Source != "clipboard" {
t.Fatal("send did not request an explicit clipboard read")
}
if clipboardSubmit(t, command, &sdk.Item{Path: "/private/file"}).Clipboard != nil {
t.Fatal("file item produced clipboard data")
}
select {
case frame := <-received:
t.Fatal("file was transferred", frame)
default:
}
if result := clipboardSubmit(t, command, &sdk.Item{Text: strings.Repeat("x", maxTextBytes+1)}); !strings.Contains(result.Speech, "too large") {
t.Fatal("oversized text not reported", result.Speech)
}
clipboardSubmit(t, command, &sdk.Item{Text: text})
select {
case frame := <-received:
var decoded struct{ Text string }
if json.Unmarshal([]byte(frame), &decoded) != nil || decoded.Text != text || strings.Contains(frame, "origin") {
t.Fatal("sent clipboard changed", frame)
}
case <-time.After(4 * time.Second):
t.Fatal("clipboard text not sent")
}
})
}
}
func TestClipboardRequiresGrant(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
command := &connectionCommand{coordinator: c}
action := approveGrants(t, c, f, 1, "controller", "remote-present")
received := make(chan string, 4)
incoming := `{"type":"set_clipboard_text","origin":7,"text":"unapproved"}`
if err := c.connect(action, clipboardRelay(t, controller, []string{incoming}, received), "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 1 })
if c.clipboard_waiting() {
t.Fatal("clipboard held without approval")
}
if result := clipboardSubmit(t, command, &sdk.Item{Text: "local"}); !strings.Contains(result.Speech, "approved") {
t.Fatal("unapproved send not refused", result.Speech)
}
select {
case frame := <-received:
t.Fatal("clipboard sent without approval", frame)
case <-time.After(200 * time.Millisecond):
}
}
+13
View File
@@ -48,6 +48,7 @@ type connectionCommand struct {
workflow *connectionWorkflow
keyboard bool // Session-only; never persisted.
keyProfile string // "portable" or "us"; session-only.
clipboard bool // Session-only; never persisted.
}
func (command *connectionCommand) commands() []sdk.Command {
@@ -60,6 +61,9 @@ func (command *connectionCommand) commands() []sdk.Command {
{"remote-approved", "Continue after reader-owned Remote approval", command.approved},
{"remote-connection", "Remote connection controls", command.submit},
{"remote-focus", "Send this keyboard to the remote computer (F11 returns)", command.remote_focus},
{"remote-send-clipboard", "Send clipboard text to the other Remote computer", command.send_clipboard_command},
{"remote-clipboard-item", "Send the clipboard text chosen for Remote", command.send_clipboard_item},
{"remote-receive-clipboard", "Copy clipboard text received over Remote", command.receive_clipboard_command},
}
var commands []sdk.Command
for _, entry := range entries {
@@ -67,6 +71,10 @@ func (command *connectionCommand) commands() []sdk.Command {
switch entry.id {
case "remote":
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}}
case "remote-send-clipboard":
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+C"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+C"}}
case "remote-receive-clipboard":
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+V"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+V"}}
case "remote-focus":
value.Interaction = false
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+F"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+F"}}
@@ -92,6 +100,7 @@ func (command *connectionCommand) selection_form(notice string) sdk.Interaction
{ID: "role", Label: "Connection role", Kind: sdk.List, Items: roles},
{ID: "keyboard", Label: "Include keyboard control for this session: controlling sends this keyboard when remote focus is on; allowing access lets the helper type here", Kind: sdk.CheckBox, Checked: command.keyboard},
{ID: "key-profile", Label: "Keys that may be sent", Kind: sdk.List, Items: profiles},
{ID: "clipboard", Label: "Allow explicit clipboard text transfer in both directions for this session", Kind: sdk.CheckBox, Checked: command.clipboard},
{ID: "review-access", Label: "Review access for this session", Kind: sdk.Button},
{ID: "save-settings", Label: "Save relay and role without connecting", Kind: sdk.Button},
}}, Next: "remote-select"}
@@ -164,6 +173,7 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
}
command.selected = selected
command.keyboard = value.Values["keyboard"].Checked
command.clipboard = value.Values["clipboard"].Checked
command.keyProfile = "portable"
if value.Values["key-profile"].Selected == "us" {
command.keyProfile = "us"
@@ -186,6 +196,9 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
grants = append(grants, keyboardGrant)
command.coordinator.set_keyboard(command.keyProfile)
}
if command.clipboard {
grants = append(grants, "clipboard-exchange")
}
command.awaiting = true
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: grants}, Next: "remote-approved"}, nil
}
+1 -1
View File
@@ -20,7 +20,7 @@ func TestRemoteCommandSelectsEndpointWithoutAccessOrNetworking(t *testing.T) {
store, _, saved := settingsFixture(t)
command := &connectionCommand{coordinator: c, store: store, selected: saved}
for _, entry := range command.commands() {
if entry.ID != "remote" && entry.ID != "remote-focus" && len(entry.Bindings) != 0 {
if (entry.ID == "remote-select" || entry.ID == "remote-approved" || entry.ID == "remote-connection" || entry.ID == "remote-clipboard-item") && len(entry.Bindings) != 0 {
t.Fatal("continuation has a shortcut")
}
}
+11 -1
View File
@@ -152,6 +152,9 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
text := "This connection attempt has ended. Fresh local approval is required to connect again."
if status.epoch == w.action.Epoch {
text = connection_status_text(status)
if status.state == "ready" && w.owner.clipboard_waiting() {
text += " Clipboard text from the other computer is waiting; use the receive clipboard command to copy it."
}
if status.state == "ready" && slices.Contains(w.action.Grants, "keyboard-capture") {
switch status.focus {
case "remote":
@@ -188,7 +191,14 @@ func session_scope_text(action sdk.SessionEvent) string {
} else if slices.Contains(action.Grants, "keyboard-inject") {
text += " and keyboard control of this computer by the helper"
}
return text + "; live verification is pending. Clipboard and Braille services are unavailable."
if slices.Contains(action.Grants, "clipboard-exchange") {
text += ", and explicit clipboard text transfer"
}
text += "; live verification is pending. Braille services are unavailable."
if !slices.Contains(action.Grants, "clipboard-exchange") {
text += " Clipboard transfer was not approved."
}
return text
}
func connection_status_text(status connectionStatus) string {
+1 -1
View File
@@ -155,7 +155,7 @@ func TestConnectionWorkflowConnectUsesLoadedKeyWithoutEcho(t *testing.T) {
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
result = workflowSubmit(t, w, "refresh", "")
encoded, _ := json.Marshal(result)
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "Clipboard and Braille services are unavailable") || strings.Contains(string(encoded), "keyboard control") {
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "Braille services are unavailable") || !strings.Contains(string(encoded), "Clipboard transfer was not approved") || strings.Contains(string(encoded), "keyboard control") {
t.Fatal("status advertised desktop control or omitted waiting state")
}
if w.key != "" {
+3
View File
@@ -414,6 +414,9 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
if err == nil && !handled {
handled, err = c.receive_key(a, stream, m)
}
if err == nil && !handled {
handled = c.receive_clipboard(a, stream, m)
}
if err != nil {
failure = err
return
+3
View File
@@ -43,6 +43,9 @@ type speechStream struct {
captured chan sdk.RemoteCapturedKey
capturedItems int // Queued plus in-flight; coordinator.mu.
focusRequests chan bool // Sent by speech_operations in sequence.
// Explicit clipboard transfer; coordinator.mu.
received string
hasReceived bool
}
func newSpeechStream(lease sdk.RemoteLease, approval sdk.SessionEvent) *speechStream {