Forward controller keys to an approved controlled reader

The source command offers a session-only keyboard-control option and key
profile for the controlled role. With it, consent covers keyboard-inject
and the coordinator converts relay keys and sends them through
remote.key in the shared operation sequence. Unconvertible keys are
ignored for press and release; a full queue stops the connection.

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 714d8243ff
commit bf27c84ebc
9 files changed
+324 -12

No files matched your search

+25 -5
View File
@@ -46,6 +46,8 @@ type connectionCommand struct {
selected settings
awaiting bool
workflow *connectionWorkflow
keyboard bool // Session-only; never persisted.
keyProfile string // "portable" or "us"; session-only.
}
func (command *connectionCommand) commands() []sdk.Command {
@@ -53,7 +55,7 @@ func (command *connectionCommand) commands() []sdk.Command {
id, title string
handler sdk.Handler
}{
{"remote", "Remote relay connection (experimental speech)", command.open},
{"remote", "Remote relay connection (experimental speech and keyboard)", command.open},
{"remote-select", "Choose Remote relay and role", command.select_relay},
{"remote-approved", "Continue after reader-owned Remote approval", command.approved},
{"remote-connection", "Remote connection controls", command.submit},
@@ -74,11 +76,17 @@ func (command *connectionCommand) selection_form(notice string) sdk.Interaction
if command.selected.Role == "controlled" {
roles[0], roles[1] = roles[1], roles[0]
}
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Experimental speech; keyboard, clipboard and Braille services are unavailable.", Elements: []sdk.Element{
profiles := []sdk.ListItem{{ID: "portable", Label: "Letters, digits and navigation only"}, {ID: "us", Label: "Also US layout punctuation"}}
if command.keyProfile == "us" {
profiles[0], profiles[1] = profiles[1], profiles[0]
}
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Experimental speech and keyboard; clipboard and Braille services are unavailable.", Elements: []sdk.Element{
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
{ID: "host", Label: "Relay host", Kind: sdk.Entry, Text: command.selected.Host, MaxLength: 253},
{ID: "port", Label: "Relay port", Kind: sdk.Entry, Text: strconv.Itoa(command.selected.Port), MaxLength: 5},
{ID: "role", Label: "Connection role", Kind: sdk.List, Items: roles},
{ID: "keyboard", Label: "When allowing access, also let the helper control this keyboard for this session", Kind: sdk.CheckBox, Checked: command.keyboard},
{ID: "key-profile", Label: "Keys the helper may send", Kind: sdk.List, Items: profiles},
{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"}
@@ -150,18 +158,30 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
return command.selection_form("Saved relay trust could not be read."), nil
}
command.selected = selected
command.keyboard = value.Values["keyboard"].Checked
command.keyProfile = "portable"
if value.Values["key-profile"].Selected == "us" {
command.keyProfile = "us"
}
if value.Activated == "save-settings" {
if err := command.store.save(selected); err != nil {
return command.selection_form("Relay settings could not be saved."), nil
}
return command.selection_form("Relay and role saved. No connection was started."), nil
}
grant := "remote-present"
grants := []string{"remote-present"}
command.coordinator.set_keyboard("")
if selected.Role == "controlled" {
grant = "output-observe"
grants = []string{"output-observe"}
if command.keyboard {
// The reader's consent dialog discloses keyboard control separately;
// the profile limits which relay keys can be converted.
grants = append(grants, "keyboard-inject")
command.coordinator.set_keyboard(command.keyProfile)
}
}
command.awaiting = true
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: []string{grant}}, Next: "remote-approved"}, nil
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: grants}, Next: "remote-approved"}, nil
}
func (command *connectionCommand) approved(ctx context.Context, raw json.RawMessage) (any, error) {
+22 -1
View File
@@ -57,7 +57,8 @@ type coordinator struct {
setupClaimed bool
active *connectionAttempt
status connectionStatus
unavailable bool // Failed close cannot be followed by another connection.
unavailable bool // Failed close cannot be followed by another connection.
keyboard string // Agreed key profile for the next attempt; empty disables input.
}
func newCoordinator(ctx context.Context, client sessionClient) *coordinator {
@@ -236,6 +237,14 @@ func (c *coordinator) disconnect_epoch(epoch uint64) <-chan struct{} {
return done
}
// set_keyboard selects the explicitly agreed key profile for later attempts.
// An active connection keeps the map it started with.
func (c *coordinator) set_keyboard(profile string) {
c.mu.Lock()
c.keyboard = profile
c.mu.Unlock()
}
// close ends the event owner too. Callers may wait on done and disconnect's
// barrier before disposing the process session; neither path needs the relay.
func (c *coordinator) close() { c.cancel() }
@@ -338,6 +347,15 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
c.mu.Unlock()
stream = newSpeechStream(lease, approval)
c.mu.Lock()
profile := c.keyboard
c.mu.Unlock()
if profile != "" {
if stream.mapping, err = newKeyboardMap(profile); err != nil {
failure = err
return
}
}
c.mu.Lock()
a.speech = stream
c.mu.Unlock()
operationsDone = make(chan struct{})
@@ -380,6 +398,9 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
}
if accepted {
handled, err := c.receive_speech(a, stream, m)
if err == nil && !handled {
handled, err = c.receive_key(a, stream, m)
}
if err != nil {
failure = err
return
+151
View File
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"io"
"net"
"strconv"
"strings"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func approveGrants(t *testing.T, c *coordinator, f *fixtureClient, epoch uint64, role string, grants ...string) sdk.SessionEvent {
t.Helper()
f.events <- sdk.SessionEvent{Sequence: epoch, Kind: "remote.action", Action: strings.Repeat("a", 32), Epoch: epoch, Role: role, Grants: grants}
select {
case event := <-c.actions:
return event
case <-time.After(time.Second):
t.Fatal("missing action")
return sdk.SessionEvent{}
}
}
// keyRelay joins one controller peer and writes the supplied key frames.
func keyRelay(t *testing.T, frames []string) endpoint {
t.Helper()
cert, roots := testCertificate(t, true)
e := testRelay(t, cert, func(conn net.Conn) {
if relayHandshake(t, conn, controlled) == nil {
return
}
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"master"}]}`+"\n")
for _, frame := range frames {
_, _ = io.WriteString(conn, frame+"\n")
}
_, _ = io.Copy(io.Discard, conn)
})
e.roots = roots
return e
}
func keyFrame(vk int, pressed bool) string {
state := "false"
if pressed {
state = "true"
}
return `{"type":"key","origin":7,"vk_code":` + strconv.Itoa(vk) + `,"extended":false,"pressed":` + state + `}`
}
func TestCoordinatorDeliversControlledKeysInSequence(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
c.set_keyboard("portable")
action := approveGrants(t, c, f, 1, "controlled", "output-observe", "keyboard-inject")
// 0xBA is US OEM punctuation: unavailable under the portable profile and
// ignored for both press and release.
e := keyRelay(t, []string{keyFrame(0x41, true), keyFrame(0xBA, true), keyFrame(0xBA, false), keyFrame(0x41, false)})
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
var previous uint64
for _, pressed := range []bool{true, false} {
var call readerCall
for {
call = <-f.calls
if call.method != "remote.heartbeat" {
break
}
previous = call.params.(sdk.RemoteOperation).Sequence
}
if call.method != "remote.key" {
t.Fatalf("got %s, want remote.key", call.method)
}
request := call.params.(sdk.RemoteKeyRequest)
if request.Key.Name != "a" || request.Key.Pressed != pressed || request.Epoch != 1 || request.Sequence <= previous || !sdk.ValidRemoteKeyRequest(request) {
t.Fatalf("bad key request %+v", request)
}
previous = request.Sequence
}
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 2 })
}
func TestCoordinatorIgnoresKeysWithoutGrantOrProfile(t *testing.T) {
for name, test := range map[string]struct {
profile string
grants []string
}{
"no grant": {"portable", []string{"output-observe"}},
"no profile": {"", []string{"output-observe", "keyboard-inject"}},
} {
t.Run(name, func(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
c.set_keyboard(test.profile)
action := approveGrants(t, c, f, 1, "controlled", test.grants...)
if err := c.connect(action, keyRelay(t, []string{keyFrame(0x41, true), keyFrame(0x41, false)}), "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 == 2 })
for {
select {
case call := <-f.calls:
if call.method == "remote.key" {
t.Fatal("key delivered without keyboard consent and profile")
}
default:
return
}
}
})
}
}
func TestCoordinatorKeyQueueOverflowStopsConnection(t *testing.T) {
block := make(chan struct{})
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
switch method {
case "remote.open":
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: params.(sdk.RemoteOpen).Epoch}
case "remote.key":
select {
case <-block:
case <-ctx.Done():
}
}
return nil
})
t.Cleanup(func() { close(block) })
go func() {
for range f.calls {
}
}()
c.set_keyboard("portable")
action := approveGrants(t, c, f, 1, "controlled", "keyboard-inject")
frames := make([]string, 0, maxKeyItems+4)
for index := 0; index < maxKeyItems+4; index++ {
frames = append(frames, keyFrame(0x41, index%2 == 0))
}
if err := c.connect(action, keyRelay(t, frames), "synthetic-fixture"); err != nil {
t.Fatal(err)
}
status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
if status.err != errLimit {
t.Fatal("overflow did not stop the connection", status.err)
}
}
+78 -1
View File
@@ -12,6 +12,10 @@ import (
const maxSpeechItems = 64
// maxKeyItems matches the reader's 256-transition mailbox. A full queue stops
// the connection rather than dropping a release.
const maxKeyItems = 256
type speechItem struct {
speech sdk.RemoteSpeech
bytes int
@@ -32,11 +36,19 @@ type speechStream struct {
items int
bytes int
sequence uint64
keys chan sdk.RemoteKey // Controlled keyboard-inject only.
keyItems int // Queued plus in-flight; coordinator.mu.
mapping *keyboardMap // Immutable; nil without keyboard-inject.
}
func newSpeechStream(lease sdk.RemoteLease, approval sdk.SessionEvent) *speechStream {
return &speechStream{lease: lease, role: approval.Role, grants: slices.Clone(approval.Grants),
incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems)}
incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems),
keys: make(chan sdk.RemoteKey, maxKeyItems)}
}
func (stream *speechStream) keyboard_enabled() bool {
return stream.mapping != nil && stream.role == "controlled" && slices.Contains(stream.grants, "keyboard-inject")
}
func (stream *speechStream) drain() {
@@ -48,6 +60,8 @@ func (stream *speechStream) drain() {
case frame := <-stream.outgoing:
stream.items--
stream.bytes -= len(frame)
case <-stream.keys:
stream.keyItems--
default:
return
}
@@ -128,6 +142,38 @@ func (c *coordinator) receive_speech(a *connectionAttempt, stream *speechStream,
return true, nil
}
// receive_key admits one controller transition for a controlled keyboard-inject
// lease. Membership/direction checks already ran in the relay reader. Keys the
// agreed map cannot represent are ignored consistently for both press and
// release, so no unmatched ownership is created; the reader's destination
// ledger owns release of every admitted key on revocation.
func (c *coordinator) receive_key(a *connectionAttempt, stream *speechStream, message message) (bool, error) {
if message.kind != "key" || !stream.keyboard_enabled() {
return false, nil
}
key, err := reader_key(stream.mapping, message)
if err != nil {
return false, nil
}
c.mu.Lock()
defer c.mu.Unlock()
if !c.speech_ready_locked(a, stream) {
return true, errLease
}
if stream.keyItems == maxKeyItems {
return true, errLimit
}
stream.keyItems++
stream.keys <- key // Capacity reserved above, including in-flight work.
return true, nil
}
func (c *coordinator) key_release(stream *speechStream) {
c.mu.Lock()
stream.keyItems--
c.mu.Unlock()
}
func (c *coordinator) speech_release(stream *speechStream, bytes int) {
c.mu.Lock()
stream.items--
@@ -164,6 +210,18 @@ func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStre
if !heartbeat() {
return
}
case key := <-stream.keys:
select {
case <-ticker.C:
if !heartbeat() {
c.key_release(stream)
return
}
default:
}
if !c.deliver_key(a, stream, key) {
return
}
case item := <-stream.incoming:
select {
case <-ticker.C:
@@ -200,6 +258,25 @@ func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStre
}
}
func (c *coordinator) deliver_key(a *connectionAttempt, stream *speechStream, key sdk.RemoteKey) bool {
defer c.key_release(stream)
c.mu.Lock()
ready := c.speech_ready_locked(a, stream)
c.mu.Unlock()
if !ready {
return false
}
stream.sequence++
request := sdk.RemoteKeyRequest{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Key: key}
if err := c.call("remote.key", request, nil); err != nil {
c.mu.Lock()
c.stop_locked(errLease)
c.mu.Unlock()
return false
}
return true
}
func (c *coordinator) speech_output(a *connectionAttempt, stream *speechStream, conn *relayConn) {
for {
select {