Simplify Remote setup and prepare experimental 0.1.1 release
This commit is contained in:
1 parent
346ec77c75
commit
6d043ee01f
14 files changed
+684
-640
No files matched your search
+161
-88
@@ -7,7 +7,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -44,12 +46,7 @@ type connectionCommand struct {
|
||||
coordinator *coordinator
|
||||
store *settingsStore
|
||||
selected settings
|
||||
awaiting bool
|
||||
workflow *connectionWorkflow
|
||||
keyboard bool // Session-only; never persisted.
|
||||
keyProfile string // "portable" or "us"; session-only.
|
||||
clipboard bool // Session-only; never persisted.
|
||||
braille bool // Session-only; never persisted.
|
||||
}
|
||||
|
||||
func (command *connectionCommand) commands() []sdk.Command {
|
||||
@@ -57,11 +54,15 @@ func (command *connectionCommand) commands() []sdk.Command {
|
||||
id, title string
|
||||
handler sdk.Handler
|
||||
}{
|
||||
{"remote", "Remote relay connection (experimental speech and keyboard)", command.open},
|
||||
{"remote", "Remote connection", 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},
|
||||
{"remote-focus", "Send this keyboard to the remote computer (F11 returns)", command.remote_focus},
|
||||
{"remote-poll", "Remote connection progress", command.poll},
|
||||
{"remote-disconnect", "Disconnect Remote", command.disconnect_command},
|
||||
{"remote-status", "Remote connection status", command.status_command},
|
||||
{"remote-mute", "Mute or unmute Remote speech", command.mute_command},
|
||||
{"remote-focus", "Switch between local and remote keyboard control", 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},
|
||||
@@ -76,9 +77,18 @@ func (command *connectionCommand) commands() []sdk.Command {
|
||||
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-disconnect":
|
||||
value.Interaction = false
|
||||
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Alt+Page_Down"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Alt+Page_Down"}}
|
||||
case "remote-status":
|
||||
value.Interaction = false
|
||||
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+Page_Up"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+Page_Up"}}
|
||||
case "remote-mute":
|
||||
value.Interaction = false
|
||||
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Alt+M"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Alt+M"}}
|
||||
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"}}
|
||||
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Alt+Tab"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Alt+Tab"}}
|
||||
}
|
||||
commands = append(commands, value)
|
||||
}
|
||||
@@ -86,25 +96,21 @@ func (command *connectionCommand) commands() []sdk.Command {
|
||||
}
|
||||
|
||||
func (command *connectionCommand) selection_form(notice string) sdk.Interaction {
|
||||
roles := []sdk.ListItem{{ID: "controller", Label: "Control another computer"}, {ID: "controlled", Label: "Allow a helper to access this computer"}}
|
||||
roles := []sdk.ListItem{{ID: "controller", Label: "Control another computer"}, {ID: "controlled", Label: "Allow this computer to be controlled"}}
|
||||
if command.selected.Role == "controlled" {
|
||||
roles[0], roles[1] = roles[1], roles[0]
|
||||
}
|
||||
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]
|
||||
host := command.selected.Host
|
||||
if host != "" && command.selected.Port != 6837 {
|
||||
host = net.JoinHostPort(host, strconv.Itoa(command.selected.Port))
|
||||
}
|
||||
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Experimental speech, keyboard, clipboard and Braille; live verification is pending.", Elements: []sdk.Element{
|
||||
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote", 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: "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: "braille", Label: "Include Braille for this session: controlling shows the other computer's Braille on this display; allowing access sends this computer's Braille", Kind: sdk.CheckBox, Checked: command.braille},
|
||||
{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},
|
||||
{ID: "role", Label: "Mode", Kind: sdk.List, Items: roles},
|
||||
{ID: "host", Label: "Host", Kind: sdk.Entry, Text: host, MaxLength: 300},
|
||||
{ID: "channel-key", Label: "Key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
|
||||
{ID: "connect", Label: "Connect", Kind: sdk.Button},
|
||||
{ID: "options", Label: "More options", Kind: sdk.Button},
|
||||
}}, Next: "remote-select"}
|
||||
if notice != "" {
|
||||
result.Presentation = security_message(notice).Presentation
|
||||
@@ -112,6 +118,28 @@ func (command *connectionCommand) selection_form(notice string) sdk.Interaction
|
||||
return result
|
||||
}
|
||||
|
||||
func parse_relay_address(value string) (string, int, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
host, port := value, 6837
|
||||
if strings.HasPrefix(value, "[") || strings.Count(value, ":") == 1 {
|
||||
var portText string
|
||||
var err error
|
||||
host, portText, err = net.SplitHostPort(value)
|
||||
if err != nil {
|
||||
return "", 0, errSettings
|
||||
}
|
||||
port, err = strconv.Atoi(portText)
|
||||
if err != nil {
|
||||
return "", 0, errSettings
|
||||
}
|
||||
}
|
||||
selected := settings{Version: 1, Host: host, Port: port, Role: "controller"}
|
||||
if _, err := selected.endpoint(); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
return host, port, nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) open(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
command.mu.Lock()
|
||||
defer command.mu.Unlock()
|
||||
@@ -119,6 +147,14 @@ func (command *connectionCommand) open(ctx context.Context, _ json.RawMessage) (
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if command.workflow != nil {
|
||||
status := command.coordinator.snapshot()
|
||||
command.workflow.mu.Lock()
|
||||
ended := command.workflow.mode == "status" && (status.state == "closed" || status.state == "failed")
|
||||
command.workflow.mu.Unlock()
|
||||
if ended {
|
||||
command.workflow.close()
|
||||
<-command.workflow.done
|
||||
}
|
||||
select {
|
||||
case <-command.workflow.done:
|
||||
command.workflow = nil
|
||||
@@ -126,9 +162,6 @@ func (command *connectionCommand) open(ctx context.Context, _ json.RawMessage) (
|
||||
return command.workflow.form(), nil
|
||||
}
|
||||
}
|
||||
if command.awaiting {
|
||||
return security_message("A Remote access review is already pending."), nil
|
||||
}
|
||||
if err := command.refresh_pin(&command.selected); err != nil {
|
||||
return security_message("Saved relay trust could not be read."), nil
|
||||
}
|
||||
@@ -159,54 +192,37 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
|
||||
if ctx.Err() != nil || value.Cancelled || value.Activated == "cancel" {
|
||||
return security_message("Remote setup cancelled."), nil
|
||||
}
|
||||
if command.awaiting || command.workflow != nil {
|
||||
return security_message("A Remote connection workflow is already open."), nil
|
||||
if command.workflow != nil {
|
||||
return security_message("Remote setup is already open."), nil
|
||||
}
|
||||
if value.Activated != "review-access" && value.Activated != "save-settings" {
|
||||
if value.Activated != "connect" && value.Activated != "options" {
|
||||
return command.selection_form(""), nil
|
||||
}
|
||||
port, err := strconv.Atoi(value.Values["port"].Text)
|
||||
selected := settings{Version: 1, Host: value.Values["host"].Text, Port: port, Role: value.Values["role"].Selected}
|
||||
if _, validationErr := selected.endpoint(); err != nil || validationErr != nil {
|
||||
return command.selection_form("Enter a valid relay host, port and connection role."), nil
|
||||
host, port, err := parse_relay_address(value.Values["host"].Text)
|
||||
selected := settings{Version: 1, Host: host, Port: port, Role: value.Values["role"].Selected}
|
||||
target, validationErr := selected.endpoint()
|
||||
if err != nil || validationErr != nil {
|
||||
return command.selection_form("Enter a valid host and mode. Add :port for a nonstandard port."), nil
|
||||
}
|
||||
if err := command.refresh_pin(&selected); err != nil {
|
||||
return command.selection_form("Saved relay trust could not be read."), nil
|
||||
}
|
||||
command.selected = selected
|
||||
command.keyboard = value.Values["keyboard"].Checked
|
||||
command.clipboard = value.Values["clipboard"].Checked
|
||||
command.braille = value.Values["braille"].Checked
|
||||
command.keyProfile = "portable"
|
||||
if value.Values["key-profile"].Selected == "us" {
|
||||
command.keyProfile = "us"
|
||||
target, _ = selected.endpoint()
|
||||
if err := command.store.save(selected); err != nil {
|
||||
return command.selection_form("Relay settings could not be saved."), nil
|
||||
}
|
||||
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
|
||||
workflow, err := new_setup_workflow(command.coordinator, target, command.store, selected.Role)
|
||||
if err != nil {
|
||||
return security_message("Remote setup is unavailable."), nil
|
||||
}
|
||||
grants := []string{"remote-present"}
|
||||
keyboardGrant := "keyboard-capture"
|
||||
if selected.Role == "controlled" {
|
||||
grants, keyboardGrant = []string{"output-observe"}, "keyboard-inject"
|
||||
command.workflow = workflow
|
||||
workflow.key = value.Values["channel-key"].Text
|
||||
workflow.profile = "portable"
|
||||
if value.Activated == "connect" {
|
||||
return workflow.submit(ctx, sdk.Submission{Activated: "connect"})
|
||||
}
|
||||
command.coordinator.set_keyboard("")
|
||||
if command.keyboard {
|
||||
// The reader's consent dialog discloses keyboard control separately;
|
||||
// the profile limits which keys can be converted in either direction.
|
||||
grants = append(grants, keyboardGrant)
|
||||
command.coordinator.set_keyboard(command.keyProfile)
|
||||
}
|
||||
if command.clipboard {
|
||||
grants = append(grants, "clipboard-exchange")
|
||||
}
|
||||
if command.braille {
|
||||
grants = append(grants, "braille-stream")
|
||||
}
|
||||
command.awaiting = true
|
||||
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: grants}, Next: "remote-approved"}, nil
|
||||
return workflow.form(), nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) approved(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
@@ -216,46 +232,56 @@ func (command *connectionCommand) approved(ctx context.Context, raw json.RawMess
|
||||
if json.Unmarshal(raw, &value) != nil {
|
||||
return nil, sdk.ErrProtocol
|
||||
}
|
||||
if !command.awaiting || command.workflow != nil {
|
||||
return security_message("Start a fresh Remote access review."), nil
|
||||
w := command.workflow
|
||||
if w == nil {
|
||||
return security_message("Start a fresh Remote connection."), nil
|
||||
}
|
||||
command.awaiting = false
|
||||
if value.Cancelled || value.Remote == nil || ctx.Err() != nil {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if value.Cancelled || value.Remote == nil || ctx.Err() != nil || w.mode != "approval" || w.ctx.Err() != nil {
|
||||
w.finish_locked()
|
||||
return security_message("Remote access was not approved."), nil
|
||||
}
|
||||
// The event consumer and command handlers run independently. Wait briefly
|
||||
// for this exact SDK-delivered action; a command argument alone cannot mint
|
||||
// approval. Role/grants from the event remain authoritative in the coordinator.
|
||||
waitCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
for {
|
||||
select {
|
||||
case action, open := <-command.coordinator.actions:
|
||||
if !open {
|
||||
w.finish_locked()
|
||||
return security_message("Reader approval is unavailable."), nil
|
||||
}
|
||||
if action.Action != value.Remote.Action || action.Epoch != value.Remote.Epoch {
|
||||
continue
|
||||
}
|
||||
if action.Role != command.selected.Role {
|
||||
return security_message("Remote role changed. Start a fresh access review."), nil
|
||||
if action.Role != w.role {
|
||||
w.finish_locked()
|
||||
return security_message("Remote mode changed. Start again."), nil
|
||||
}
|
||||
target, err := command.selected.endpoint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
w.action = action
|
||||
command.coordinator.set_keyboard(w.profile)
|
||||
if err := command.coordinator.connect(action, w.target, w.key); err != nil {
|
||||
w.finish_locked()
|
||||
return security_message("The connection could not start. Start again."), nil
|
||||
}
|
||||
workflow, err := new_connection_workflow(command.coordinator.ctx, command.coordinator, action, target, command.store)
|
||||
if err != nil {
|
||||
return security_message("Remote approval ended. Start a fresh access review."), nil
|
||||
}
|
||||
command.workflow = workflow
|
||||
return workflow.form(), nil
|
||||
w.key, w.mode, w.autoBackground = "", "status", true
|
||||
return w.form_locked(), nil
|
||||
case <-waitCtx.Done():
|
||||
return security_message("Remote approval ended. Start a fresh access review."), nil
|
||||
w.finish_locked()
|
||||
return security_message("Reader approval expired. Start again."), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (command *connectionCommand) poll(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
command.mu.Lock()
|
||||
defer command.mu.Unlock()
|
||||
if command.workflow == nil {
|
||||
return security_message("Remote setup ended."), nil
|
||||
}
|
||||
return command.workflow.poll(ctx), nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) submit(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
command.mu.Lock()
|
||||
defer command.mu.Unlock()
|
||||
@@ -282,16 +308,63 @@ func (command *connectionCommand) close() {
|
||||
<-command.coordinator.done
|
||||
}
|
||||
|
||||
// remote_focus asks the reader to send this keyboard to the remote computer.
|
||||
// It only enters remote focus: F11 or any Remote shortcut returns it, handled
|
||||
// by the reader without this process.
|
||||
// The reader owns capture and the emergency return path.
|
||||
func (command *connectionCommand) remote_focus(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if err := command.coordinator.request_focus(true); err != nil {
|
||||
text := "Remote keyboard control needs a connected controller session with keyboard control approved."
|
||||
return sdk.Presentation{Speech: text, Braille: text}, nil
|
||||
remote := command.coordinator.snapshot().focus != "remote"
|
||||
if err := command.coordinator.request_focus(remote); err != nil {
|
||||
return sdk.Presentation{Speech: "Keyboard control needs a connected session with keyboard access allowed."}, nil
|
||||
}
|
||||
return sdk.Presentation{Speech: "Requesting remote keyboard focus.", Braille: "Requesting remote keyboard focus."}, nil
|
||||
text := "Switching keyboard control to this computer."
|
||||
if remote {
|
||||
text = "Switching keyboard control to the other computer. F11 returns here."
|
||||
}
|
||||
return sdk.Presentation{Speech: text, Braille: text}, nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) disconnect_command(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
command.mu.Lock()
|
||||
if command.workflow != nil {
|
||||
command.workflow.close()
|
||||
}
|
||||
command.mu.Unlock()
|
||||
command.coordinator.disconnect()
|
||||
return sdk.Presentation{Speech: "Remote disconnected.", Braille: "Remote disconnected."}, nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) status_command(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
status := command.coordinator.snapshot()
|
||||
text := connection_status_text(status)
|
||||
if status.focus == "remote" {
|
||||
text += " Keyboard controls the other computer."
|
||||
} else {
|
||||
text += " Keyboard controls this computer."
|
||||
}
|
||||
if status.muted {
|
||||
text += " Remote speech muted."
|
||||
}
|
||||
return sdk.Presentation{Speech: text, Braille: text}, nil
|
||||
}
|
||||
|
||||
func (command *connectionCommand) mute_command(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
muted, err := command.coordinator.toggle_mute()
|
||||
text := "Remote speech needs a connected controller session."
|
||||
if err == nil {
|
||||
text = "Remote speech unmuted."
|
||||
if muted {
|
||||
text = "Remote speech muted."
|
||||
}
|
||||
}
|
||||
return sdk.Presentation{Speech: text, Braille: text}, nil
|
||||
}
|
||||
+77
-41
@@ -15,43 +15,46 @@ import (
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func TestRemoteCommandSelectsEndpointWithoutAccessOrNetworking(t *testing.T) {
|
||||
func TestRemoteCommandCollectsCredentialsBeforeApproval(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
store, _, saved := settingsFixture(t)
|
||||
command := &connectionCommand{coordinator: c, store: store, selected: saved}
|
||||
for _, entry := range command.commands() {
|
||||
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")
|
||||
form := command.selection_form("")
|
||||
if len(form.Form.Elements) != 6 {
|
||||
t.Fatal("connection form has extra controls")
|
||||
}
|
||||
for _, element := range form.Form.Elements {
|
||||
if element.ID == "channel-key" && (!element.Secret || element.Text != "") {
|
||||
t.Fatal("key is unmasked or prefilled")
|
||||
}
|
||||
if element.Kind == sdk.CheckBox {
|
||||
t.Fatal("permissions duplicated in connection form")
|
||||
}
|
||||
}
|
||||
for _, role := range []string{"controller", "controlled"} {
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "review-access", Values: map[string]sdk.Value{
|
||||
"host": {Text: "relay.invalid"}, "port": {Text: "6837"}, "role": {Selected: role},
|
||||
}})
|
||||
value, err := command.select_relay(t.Context(), raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := value.(sdk.Interaction)
|
||||
grant := "remote-present"
|
||||
if role == "controlled" {
|
||||
grant = "output-observe"
|
||||
}
|
||||
if result.Remote == nil || result.Remote.Role != role || len(result.Remote.Grants) != 1 || result.Remote.Grants[0] != grant {
|
||||
t.Fatal("selection did not request core approval for its role")
|
||||
}
|
||||
// A fabricated command argument cannot replace an SDK action event.
|
||||
limited, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
|
||||
fake, _ := json.Marshal(sdk.Submission{Remote: &sdk.SessionEvent{Kind: "remote.action", Epoch: 1, Action: strings.Repeat("a", 32)}})
|
||||
value, err = command.approved(limited, fake)
|
||||
cancel()
|
||||
if err != nil || !value.(sdk.Interaction).Done || command.workflow != nil {
|
||||
t.Fatal("fabricated approval opened connection controls")
|
||||
}
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "options", Values: map[string]sdk.Value{"host": {Text: "relay.invalid:7000"}, "role": {Selected: "controller"}}})
|
||||
result, err := command.select_relay(t.Context(), raw)
|
||||
if err != nil || result.(sdk.Interaction).Form == nil || command.workflow == nil {
|
||||
t.Fatal("options did not open", err)
|
||||
}
|
||||
if command.selected.Host != "relay.invalid" || command.selected.Port != 7000 {
|
||||
t.Fatal("address did not parse")
|
||||
}
|
||||
w := command.workflow
|
||||
w.mu.Lock()
|
||||
w.mode = "approval"
|
||||
w.key = "sample-key"
|
||||
w.mu.Unlock()
|
||||
limited, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
fake, _ := json.Marshal(sdk.Submission{Remote: &sdk.SessionEvent{Kind: "remote.action", Epoch: 1, Action: strings.Repeat("a", 32)}})
|
||||
result, err = command.approved(limited, fake)
|
||||
if err != nil || !result.(sdk.Interaction).Done {
|
||||
t.Fatal("fabricated approval accepted", err)
|
||||
}
|
||||
awaitDone(t, w.done)
|
||||
select {
|
||||
case call := <-client.calls:
|
||||
t.Fatal("selection or forged approval opened a lease", call.method)
|
||||
t.Fatal("setup made a reader call", call.method)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -60,26 +63,24 @@ func TestRemoteCommandRejectsInvalidSelectionAndDropsEndpointPin(t *testing.T) {
|
||||
c, _ := fixtureCoordinator(t, nil)
|
||||
store, _, saved := settingsFixture(t)
|
||||
command := &connectionCommand{coordinator: c, store: store, selected: saved}
|
||||
for _, host := range []string{"bad\nrelay", "bad\x00relay", ""} {
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "review-access", Values: map[string]sdk.Value{
|
||||
"host": {Text: host}, "port": {Text: "6837"}, "role": {Selected: "controller"},
|
||||
}})
|
||||
for _, host := range []string{"bad\nrelay", "bad\x00relay", "", "relay:0", "relay:abc"} {
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "options", Values: map[string]sdk.Value{"host": {Text: host}, "role": {Selected: "controller"}}})
|
||||
value, err := command.select_relay(t.Context(), raw)
|
||||
if err != nil || value.(sdk.Interaction).Remote != nil || command.awaiting {
|
||||
t.Fatal("invalid endpoint reached approval")
|
||||
if err != nil || value.(sdk.Interaction).Remote != nil || command.workflow != nil {
|
||||
t.Fatal("invalid endpoint accepted")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "save-settings", Values: map[string]sdk.Value{
|
||||
"host": {Text: "other.invalid"}, "port": {Text: "6838"}, "role": {Selected: "controlled"},
|
||||
}})
|
||||
raw, _ := json.Marshal(sdk.Submission{Activated: "options", Values: map[string]sdk.Value{"host": {Text: "other.invalid:6838"}, "role": {Selected: "controlled"}}})
|
||||
value, err := command.select_relay(t.Context(), raw)
|
||||
if err != nil || value.(sdk.Interaction).Remote != nil {
|
||||
t.Fatal("saving settings requested access")
|
||||
t.Fatal("options requested approval")
|
||||
}
|
||||
loaded, found, err := store.load()
|
||||
if err != nil || !found || loaded.Host != "other.invalid" || loaded.Pin != nil || loaded.Role != "controlled" {
|
||||
t.Fatal("endpoint change retained old trust or did not save settings")
|
||||
t.Fatal("endpoint change retained trust")
|
||||
}
|
||||
command.workflow.close()
|
||||
awaitDone(t, command.workflow.done)
|
||||
}
|
||||
|
||||
func TestRemoteCommandRefreshesRemovedPinsAndFailsClosedOnStorageError(t *testing.T) {
|
||||
@@ -126,7 +127,7 @@ func TestConnectionWorkflowRememberPinAndForgetAreExplicit(t *testing.T) {
|
||||
store.close()
|
||||
}
|
||||
result := workflowSubmit(t, w, "remember-pin", "")
|
||||
if result.Form == nil || result.Form.Title != "Connect Remote relay" {
|
||||
if result.Form == nil || result.Form.Title != "Remote options" {
|
||||
t.Fatal("Remember did not return to explicit Connect")
|
||||
}
|
||||
if failWrite {
|
||||
@@ -156,3 +157,38 @@ func TestConnectionWorkflowRememberPinAndForgetAreExplicit(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteSetupChecksTrustBeforeRequestingApproval(t *testing.T) {
|
||||
c, client := fixtureCoordinator(t, nil)
|
||||
cert, roots := testCertificate(t, true)
|
||||
inspected := make(chan struct{})
|
||||
target := testRelay(t, cert, func(connection net.Conn) {
|
||||
data, _ := io.ReadAll(connection)
|
||||
if len(data) != 0 {
|
||||
t.Error("preflight disclosed application data")
|
||||
}
|
||||
close(inspected)
|
||||
})
|
||||
target.roots = roots
|
||||
w, err := new_setup_workflow(c, target, nil, "controller")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
|
||||
result, err := w.submit(t.Context(), sdk.Submission{Activated: "connect", Values: map[string]sdk.Value{"channel-key": {Text: "sample-key"}}})
|
||||
if err != nil || result.Poll != "remote-poll" || result.Remote != nil {
|
||||
t.Fatal("setup skipped certificate progress")
|
||||
}
|
||||
awaitDone(t, w.probeDone)
|
||||
awaitDone(t, inspected)
|
||||
result = w.poll(t.Context())
|
||||
if result.Remote == nil || result.Remote.Role != "controller" || len(result.Remote.OptionalGrants) != 3 || result.Next != "remote-approved" {
|
||||
t.Fatal("verified setup did not request optional local access")
|
||||
}
|
||||
assertSecretAbsent(t, result, "sample-key")
|
||||
select {
|
||||
case call := <-client.calls:
|
||||
t.Fatal("preflight opened reader access", call.method)
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ func testConnectionWorkflowPublicSDKProcess(t *testing.T, role string) {
|
||||
assertSecretAbsent(t, result, "synthetic-fixture")
|
||||
return result
|
||||
}
|
||||
if result := invoke("remote-test-open", "", ""); result.Form == nil || result.Form.Title != "Connect Remote relay" {
|
||||
if result := invoke("remote-test-open", "", ""); result.Form == nil || result.Form.Title != "Remote options" {
|
||||
t.Fatal("SDK did not open connection controls")
|
||||
}
|
||||
invoke("remote-connection", "saved-key-actions", "")
|
||||
|
||||
+188
-53
@@ -4,12 +4,15 @@ package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
@@ -20,21 +23,26 @@ import (
|
||||
// Ordinary form cancellation ends the workflow. An explicit desktop return
|
||||
// retains it under the reader lease, which lock/handoff or process loss revokes.
|
||||
type connectionWorkflow struct {
|
||||
mu sync.Mutex
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
setupCtx context.Context
|
||||
owner *coordinator
|
||||
action sdk.SessionEvent
|
||||
target endpoint
|
||||
store *settingsStore
|
||||
mode string // credentials, inspecting, certificate, saved-key, status, finished
|
||||
notice string
|
||||
key string // Explicitly loaded only; never placed back into a form.
|
||||
review *certificateReview
|
||||
keys *keyActions
|
||||
probeDone chan struct{}
|
||||
mu sync.Mutex
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
setupCtx context.Context
|
||||
owner *coordinator
|
||||
action sdk.SessionEvent
|
||||
target endpoint
|
||||
store *settingsStore
|
||||
mode string // credentials, inspecting, certificate, saved-key, status, finished
|
||||
notice string
|
||||
key string // Explicitly loaded only; never placed back into a form.
|
||||
review *certificateReview
|
||||
keys *keyActions
|
||||
probeDone chan struct{}
|
||||
role string
|
||||
profile string
|
||||
needsApproval bool
|
||||
autoBackground bool
|
||||
lastStatus string
|
||||
}
|
||||
|
||||
func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) (*connectionWorkflow, error) {
|
||||
@@ -57,7 +65,7 @@ func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk
|
||||
}
|
||||
lifetime, cancel := context.WithCancel(owner.ctx)
|
||||
w := &connectionWorkflow{ctx: lifetime, cancel: cancel, done: make(chan struct{}), setupCtx: setupCtx,
|
||||
owner: owner, action: approval, target: target, store: store, mode: "credentials"}
|
||||
owner: owner, action: approval, target: target, store: store, mode: "credentials", role: approval.Role}
|
||||
stopParent := context.AfterFunc(ctx, cancel)
|
||||
go func() {
|
||||
defer close(w.done)
|
||||
@@ -105,7 +113,7 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
|
||||
address := net.JoinHostPort(w.target.host, strconv.Itoa(w.target.port))
|
||||
details := sdk.Element{ID: "details", Label: "Connection details", Kind: sdk.List, Items: []sdk.ListItem{
|
||||
{ID: "endpoint", Label: "Relay: " + address},
|
||||
{ID: "role", Label: "Approved role: " + w.action.Role},
|
||||
{ID: "role", Label: "Mode: " + w.role},
|
||||
{ID: "privacy", Label: "The relay can read the channel key and session contents. A channel key does not verify the other person's identity."},
|
||||
{ID: "scope", Label: session_scope_text(w.action)},
|
||||
}}
|
||||
@@ -117,27 +125,30 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
|
||||
}
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "trust", Label: trust})
|
||||
if w.key != "" {
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "loaded-key", Label: "A saved key was explicitly loaded. Leave Channel key empty to use it, or enter a replacement for this attempt."})
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "loaded-key", Label: "A key is ready for this attempt. Leave Key empty to use it, or enter a replacement."})
|
||||
}
|
||||
elements := []sdk.Element{details,
|
||||
{ID: "channel-key", Label: "Channel key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
|
||||
{ID: "connect", Label: "Connect relay", Kind: sdk.Button},
|
||||
{ID: "channel-key", Label: "Key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
|
||||
{ID: "connect", Label: "Connect", Kind: sdk.Button},
|
||||
{ID: "inspect-certificate", Label: "Inspect relay certificate", Kind: sdk.Button},
|
||||
}
|
||||
if w.store != nil {
|
||||
elements = append(elements,
|
||||
sdk.Element{ID: "load-key", Label: "Use saved key", Kind: sdk.Button},
|
||||
sdk.Element{ID: "saved-key-actions", Label: "Remember or forget a key", Kind: sdk.Button})
|
||||
sdk.Element{ID: "saved-key-actions", Label: "Saved key settings", Kind: sdk.Button})
|
||||
if w.target.pin != nil {
|
||||
elements = append(elements, sdk.Element{ID: "forget-pin", Label: "Forget this relay's pin and use normal certificate validation", Kind: sdk.Button})
|
||||
}
|
||||
}
|
||||
elements = append(elements, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
|
||||
result.Form = &sdk.Form{Title: "Connect Remote relay", Elements: elements}
|
||||
case "inspecting":
|
||||
profiles := []sdk.ListItem{{ID: "portable", Label: "Letters, numbers and navigation"}, {ID: "us", Label: "Include US punctuation"}}
|
||||
if w.profile == "us" {
|
||||
profiles[0], profiles[1] = profiles[1], profiles[0]
|
||||
}
|
||||
elements = append(elements, sdk.Element{ID: "key-profile", Label: "Keyboard mapping", Kind: sdk.List, Items: profiles}, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
|
||||
result.Form = &sdk.Form{Title: "Remote options", Elements: elements}
|
||||
case "inspecting", "checking":
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "inspection", Label: "Inspecting the certificate without sending a channel key. No connection will start automatically."})
|
||||
result.Form = &sdk.Form{Title: "Inspecting Remote certificate", Elements: []sdk.Element{details,
|
||||
{ID: "refresh", Label: "Refresh inspection status", Kind: sdk.Button},
|
||||
result.Form = &sdk.Form{Title: "Checking Remote certificate", Elements: []sdk.Element{details,
|
||||
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
|
||||
}}
|
||||
case "certificate":
|
||||
@@ -165,18 +176,22 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
|
||||
}
|
||||
}
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "status", Label: text})
|
||||
result.Form = &sdk.Form{Title: "Remote relay status", Elements: []sdk.Element{details,
|
||||
{ID: "desktop", Label: "Return to desktop and keep this connection", Kind: sdk.Button},
|
||||
{ID: "refresh", Label: "Refresh connection status", Kind: sdk.Button},
|
||||
result.Form = &sdk.Form{Title: "Remote status", Elements: []sdk.Element{details,
|
||||
{ID: "desktop", Label: "Close", Kind: sdk.Button},
|
||||
{ID: "disconnect", Label: "Disconnect", Kind: sdk.Button},
|
||||
{ID: "cancel", Label: "Disconnect and close", Kind: sdk.Button},
|
||||
}}
|
||||
if w.autoBackground {
|
||||
result.Form = &sdk.Form{Title: "Connecting Remote", Elements: []sdk.Element{{ID: "disconnect", Label: "Cancel", Kind: sdk.Button}}}
|
||||
}
|
||||
default:
|
||||
return security_message("Remote connection workflow closed.")
|
||||
}
|
||||
// Nested forms always return through this instance's owner, never through
|
||||
// the standalone handlers or a newly selected endpoint.
|
||||
result.Next = "remote-connection"
|
||||
if w.mode == "inspecting" || w.mode == "checking" || w.mode == "status" && w.autoBackground {
|
||||
result.Poll = "remote-poll"
|
||||
}
|
||||
if w.notice != "" {
|
||||
result.Presentation = security_message(w.notice).Presentation
|
||||
}
|
||||
@@ -185,26 +200,23 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
|
||||
|
||||
// session_scope_text names what this approved session can actually do.
|
||||
func session_scope_text(action sdk.SessionEvent) string {
|
||||
text := "Experimental speech"
|
||||
if slices.Contains(action.Grants, "keyboard-capture") {
|
||||
text += " and keyboard control of the remote computer"
|
||||
} else if slices.Contains(action.Grants, "keyboard-inject") {
|
||||
text += " and keyboard control of this computer by the helper"
|
||||
var access []string
|
||||
if slices.Contains(action.Grants, "output-observe") || slices.Contains(action.Grants, "remote-present") {
|
||||
access = append(access, "Speech")
|
||||
}
|
||||
if slices.Contains(action.Grants, "keyboard-capture") || slices.Contains(action.Grants, "keyboard-inject") {
|
||||
access = append(access, "keyboard")
|
||||
}
|
||||
if slices.Contains(action.Grants, "clipboard-exchange") {
|
||||
text += ", explicit clipboard text transfer"
|
||||
access = append(access, "clipboard")
|
||||
}
|
||||
if slices.Contains(action.Grants, "braille-stream") {
|
||||
text += ", Braille display output and routing"
|
||||
access = append(access, "Braille")
|
||||
}
|
||||
text += "; live verification is pending."
|
||||
if !slices.Contains(action.Grants, "clipboard-exchange") {
|
||||
text += " Clipboard transfer was not approved."
|
||||
if len(access) == 0 {
|
||||
return "Choose access in the reader approval dialog before connecting."
|
||||
}
|
||||
if !slices.Contains(action.Grants, "braille-stream") {
|
||||
text += " Braille was not approved."
|
||||
}
|
||||
return text
|
||||
return "Allowed: " + strings.Join(access, ", ") + "."
|
||||
}
|
||||
|
||||
func connection_status_text(status connectionStatus) string {
|
||||
@@ -214,9 +226,9 @@ func connection_status_text(status connectionStatus) string {
|
||||
case "connecting":
|
||||
return "Connecting and authenticating the relay."
|
||||
case "waiting":
|
||||
return "Connected to the relay; waiting for one opposite-role peer."
|
||||
return "Connected; waiting for the other computer."
|
||||
case "ready":
|
||||
return "One opposite-role peer has joined."
|
||||
return "Connected to the other computer."
|
||||
case "stopping":
|
||||
return "Disconnecting and releasing the reader lease."
|
||||
case "failed":
|
||||
@@ -233,10 +245,10 @@ func connection_status_text(status connectionStatus) string {
|
||||
}
|
||||
}
|
||||
|
||||
// Inspection is explicit and runs outside the command deadline. Only Refresh
|
||||
// Inspection is explicit and runs outside the command deadline. Polling
|
||||
// presents its result; neither completion nor Trust once starts a connection.
|
||||
func (w *connectionWorkflow) inspect_locked() {
|
||||
w.key, w.notice, w.mode = "", "", "inspecting"
|
||||
w.notice, w.mode = "", "inspecting"
|
||||
done := make(chan struct{})
|
||||
w.probeDone = done
|
||||
probeCtx, cancel := context.WithCancel(w.setupCtx)
|
||||
@@ -253,7 +265,7 @@ func (w *connectionWorkflow) inspect_locked() {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
w.mode, w.notice = "credentials", "Certificate inspection failed. No trust was changed and no channel key was sent."
|
||||
w.mode, w.notice = "credentials", "Certificate inspection failed. No trust was changed and no key was sent."
|
||||
return
|
||||
}
|
||||
// The probe's short-lived context ends here. The review belongs to the
|
||||
@@ -271,6 +283,13 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
return security_message("Remote connection approval ended. Start a fresh local connection action."), nil
|
||||
}
|
||||
if value.Cancelled {
|
||||
if w.mode == "status" && !w.autoBackground {
|
||||
if lease, ok := w.owner.background_lease(w.action.Epoch); ok {
|
||||
result := security_message("Remote controls closed.")
|
||||
result.RemoteBackground = &lease
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
w.finish_locked()
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
@@ -283,6 +302,9 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
case "credentials":
|
||||
switch value.Activated {
|
||||
case "connect":
|
||||
if selected := value.Values["key-profile"].Selected; selected == "portable" || selected == "us" {
|
||||
w.profile = selected
|
||||
}
|
||||
key := value.Values["channel-key"].Text
|
||||
if key == "" {
|
||||
key = w.key
|
||||
@@ -291,6 +313,11 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
w.notice = "Enter a valid channel key or explicitly load a saved key."
|
||||
break
|
||||
}
|
||||
if w.needsApproval {
|
||||
w.key = key
|
||||
w.check_locked()
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
err := w.owner.connect(w.action, w.target, key)
|
||||
w.key = ""
|
||||
w.target.pin = nil
|
||||
@@ -313,6 +340,9 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
w.key, w.notice = key, "Saved key loaded for this relay. Choose Connect relay to use it."
|
||||
}
|
||||
case "inspect-certificate":
|
||||
if key := value.Values["channel-key"].Text; validChannelKey(key) {
|
||||
w.key = key
|
||||
}
|
||||
w.inspect_locked()
|
||||
case "saved-key-actions":
|
||||
w.key = ""
|
||||
@@ -353,7 +383,7 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
if err != nil {
|
||||
w.notice = "Certificate review ended without approval."
|
||||
} else if approved.host != "" && remember {
|
||||
selected := settings{Version: 1, Role: w.action.Role, Host: approved.host, Port: approved.port,
|
||||
selected := settings{Version: 1, Role: w.role, Host: approved.host, Port: approved.port,
|
||||
Pin: &savedPin{Host: approved.host, Port: approved.port, SHA256: hex.EncodeToString(approved.pin.sha256[:])}}
|
||||
if w.store.save(selected) != nil {
|
||||
w.notice = "The certificate pin save failed. Stored trust may have changed; review it before another connection."
|
||||
@@ -386,15 +416,120 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
|
||||
case "status":
|
||||
if value.Activated == "desktop" {
|
||||
if lease, ok := w.owner.background_lease(w.action.Epoch); ok {
|
||||
result := security_message("Remote connection controls closed. Press Cthulhu+Control+Shift+R to review status or disconnect. Speech support is experimental.")
|
||||
result := security_message("Remote controls closed. Cthulhu+Ctrl+Shift+R opens status.")
|
||||
result.RemoteBackground = &lease
|
||||
return result, nil
|
||||
}
|
||||
w.notice = "No live reader lease is available. Refresh connection status or disconnect."
|
||||
w.notice = "No live reader lease is available. Disconnect and start again."
|
||||
}
|
||||
if value.Activated == "disconnect" {
|
||||
w.owner.disconnect_epoch(w.action.Epoch)
|
||||
w.finish_locked()
|
||||
return security_message("Remote disconnected."), nil
|
||||
}
|
||||
}
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
|
||||
// Setup belongs to the command's local interaction until it receives approval.
|
||||
// No short-lived reader action is issued during key entry or certificate review.
|
||||
func new_setup_workflow(owner *coordinator, target endpoint, store *settingsStore, role string) (*connectionWorkflow, error) {
|
||||
if _, err := target.tlsConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if owner.ctx.Err() != nil {
|
||||
return nil, errLease
|
||||
}
|
||||
lifetime, cancel := context.WithCancel(owner.ctx)
|
||||
w := &connectionWorkflow{ctx: lifetime, cancel: cancel, done: make(chan struct{}), setupCtx: lifetime, owner: owner, target: target, store: store, role: role, mode: "credentials", needsApproval: true}
|
||||
go func() {
|
||||
defer close(w.done)
|
||||
<-lifetime.Done()
|
||||
w.mu.Lock()
|
||||
w.finish_locked()
|
||||
probeDone := w.probeDone
|
||||
w.mu.Unlock()
|
||||
if probeDone != nil {
|
||||
<-probeDone
|
||||
}
|
||||
}()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// A normal verified TLS handshake sends no application bytes. Failed trust
|
||||
// returns to explicit inspection; it never enables an insecure fallback.
|
||||
func (w *connectionWorkflow) check_locked() {
|
||||
w.mode, w.notice = "checking", "Checking relay certificate."
|
||||
done := make(chan struct{})
|
||||
w.probeDone = done
|
||||
target := w.target
|
||||
go func() {
|
||||
defer close(done)
|
||||
ctx, cancel := context.WithTimeout(w.ctx, dialTimeout)
|
||||
defer cancel()
|
||||
config, err := target.tlsConfig()
|
||||
if err == nil {
|
||||
dialer := tls.Dialer{NetDialer: &net.Dialer{Timeout: dialTimeout}, Config: config}
|
||||
connection, dialErr := dialer.DialContext(ctx, "tcp", net.JoinHostPort(target.host, strconv.Itoa(target.port)))
|
||||
err = dialErr
|
||||
if connection != nil {
|
||||
connection.SetDeadline(time.Now().Add(time.Second))
|
||||
connection.Close()
|
||||
}
|
||||
}
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.mode != "checking" || w.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
w.mode, w.notice = "credentials", "Could not verify the relay. No key was sent. Check the address or inspect its certificate."
|
||||
} else {
|
||||
w.mode, w.notice = "approval", ""
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (w *connectionWorkflow) poll(ctx context.Context) sdk.Interaction {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if ctx.Err() != nil || w.ctx.Err() != nil {
|
||||
w.finish_locked()
|
||||
return security_message("Remote setup ended.")
|
||||
}
|
||||
switch w.mode {
|
||||
case "checking", "inspecting":
|
||||
return sdk.Interaction{}
|
||||
case "approval":
|
||||
grant, keyboard := "remote-present", "keyboard-capture"
|
||||
if w.role == "controlled" {
|
||||
grant, keyboard = "output-observe", "keyboard-inject"
|
||||
}
|
||||
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: w.role, Grants: []string{grant}, OptionalGrants: []string{keyboard, "clipboard-exchange", "braille-stream"}}, Next: "remote-approved"}
|
||||
case "status":
|
||||
status := w.owner.snapshot()
|
||||
if w.autoBackground && status.epoch == w.action.Epoch && (status.state == "waiting" || status.state == "ready") {
|
||||
if lease, ok := w.owner.background_lease(w.action.Epoch); ok {
|
||||
w.autoBackground = false
|
||||
text := connection_status_text(status)
|
||||
if slices.Contains(w.action.Grants, "keyboard-capture") {
|
||||
text += " Keyboard remains local. Cthulhu+Alt+Tab switches control."
|
||||
}
|
||||
result := security_message(text)
|
||||
result.RemoteBackground = &lease
|
||||
return result
|
||||
}
|
||||
}
|
||||
if status.state == "failed" || status.state == "closed" {
|
||||
w.finish_locked()
|
||||
return security_message(connection_status_text(status))
|
||||
}
|
||||
text := connection_status_text(status)
|
||||
if text != w.lastStatus {
|
||||
w.lastStatus = text
|
||||
return sdk.Interaction{Presentation: sdk.Presentation{Speech: text, Braille: text}}
|
||||
}
|
||||
return sdk.Interaction{}
|
||||
default:
|
||||
return w.form_locked()
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func TestConnectionWorkflowBindsReaderActionAndFreezesTrust(t *testing.T) {
|
||||
}
|
||||
result := w.form()
|
||||
encoded, _ := json.Marshal(result)
|
||||
if result.Form == nil || result.Next != "remote-connection" || !strings.Contains(string(encoded), "was not approved") {
|
||||
if result.Form == nil || result.Next != "remote-connection" || !strings.Contains(string(encoded), "Allowed: Speech") {
|
||||
t.Fatal("missing form, continuation or service limitation")
|
||||
}
|
||||
workflowSubmit(t, w, "connect", strings.Repeat("猫", 200))
|
||||
@@ -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), "Braille was not approved") || !strings.Contains(string(encoded), "Clipboard transfer was not approved") || strings.Contains(string(encoded), "keyboard control") {
|
||||
if !strings.Contains(string(encoded), "waiting for the other computer") || strings.Contains(string(encoded), "Allowed: Speech, keyboard") {
|
||||
t.Fatal("status advertised desktop control or omitted waiting state")
|
||||
}
|
||||
if w.key != "" {
|
||||
@@ -219,7 +219,7 @@ func TestConnectionWorkflowBackgroundRequiresOpenedLease(t *testing.T) {
|
||||
nextCall(t, f, "remote.heartbeat")
|
||||
command := &connectionCommand{coordinator: c, workflow: w}
|
||||
reopened, err := command.open(t.Context(), nil)
|
||||
if err != nil || reopened.(sdk.Interaction).Form.Title != "Remote relay status" {
|
||||
if err != nil || reopened.(sdk.Interaction).Form.Title != "Remote status" {
|
||||
t.Fatal("shortcut did not reopen connection status", err)
|
||||
}
|
||||
f.events <- sdk.SessionEvent{Kind: "remote.revoked", Lease: result.RemoteBackground.Lease, Epoch: 1}
|
||||
|
||||
@@ -28,6 +28,7 @@ type connectionStatus struct {
|
||||
epoch uint64
|
||||
peer int
|
||||
ignored uint64
|
||||
muted bool
|
||||
focus string // Controller keyboard: "", "local" or "remote", as reported by core.
|
||||
err error // Local constant errors only; never RPC/server diagnostic text.
|
||||
}
|
||||
|
||||
+84
-17
@@ -17,28 +17,32 @@ const maxSpeechItems = 64
|
||||
const maxKeyItems = 256
|
||||
|
||||
type speechItem struct {
|
||||
speech sdk.RemoteSpeech
|
||||
bytes int
|
||||
batch bool
|
||||
first bool
|
||||
final bool
|
||||
generation uint64
|
||||
speech sdk.RemoteSpeech
|
||||
bytes int
|
||||
batch bool
|
||||
first bool
|
||||
final bool
|
||||
}
|
||||
|
||||
// One stream belongs to one attempt and lease. The coordinator mutex owns
|
||||
// admission/accounting, including in-flight work. Only speech_operations owns
|
||||
// sequence; teardown reads it after that worker finishes.
|
||||
type speechStream struct {
|
||||
lease sdk.RemoteLease
|
||||
role string
|
||||
grants []string
|
||||
incoming chan speechItem
|
||||
outgoing chan []byte
|
||||
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 a keyboard grant.
|
||||
lease sdk.RemoteLease
|
||||
role string
|
||||
grants []string
|
||||
incoming chan speechItem
|
||||
outgoing chan []byte
|
||||
items int
|
||||
bytes int
|
||||
sequence uint64
|
||||
muted bool
|
||||
speechGeneration uint64
|
||||
muteCancel chan struct{}
|
||||
keys chan sdk.RemoteKey // Controlled keyboard-inject only.
|
||||
keyItems int // Queued plus in-flight; coordinator.mu.
|
||||
mapping *keyboardMap // Immutable; nil without a keyboard grant.
|
||||
// Controller keyboard-capture only.
|
||||
captured chan sdk.RemoteCapturedKey
|
||||
capturedItems int // Queued plus in-flight; coordinator.mu.
|
||||
@@ -57,7 +61,7 @@ type speechStream struct {
|
||||
|
||||
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),
|
||||
muteCancel: make(chan struct{}, 1), incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems),
|
||||
keys: make(chan sdk.RemoteKey, maxKeyItems), captured: make(chan sdk.RemoteCapturedKey, maxCapturedKeys),
|
||||
focusRequests: make(chan bool, 4), brailleOps: make(chan sdk.RemoteBraille, maxBrailleOps),
|
||||
readerCellsSignal: make(chan struct{}, 1), displaySignal: make(chan struct{}, 1)}
|
||||
@@ -151,6 +155,12 @@ func (c *coordinator) receive_speech(a *connectionAttempt, stream *speechStream,
|
||||
if !c.speech_ready_locked(a, stream) {
|
||||
return true, errLease
|
||||
}
|
||||
if stream.muted {
|
||||
return true, nil
|
||||
}
|
||||
for index := range items {
|
||||
items[index].generation = stream.speechGeneration
|
||||
}
|
||||
if stream.items+len(items) > maxSpeechItems || stream.bytes+bytes > maxQueuedBytes {
|
||||
return true, errLimit
|
||||
}
|
||||
@@ -226,7 +236,25 @@ func (c *coordinator) speech_operations_ticks(a *connectionAttempt, stream *spee
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
cancelMuted := func() bool {
|
||||
stream.sequence++
|
||||
request := sdk.RemotePresentation{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Speech: sdk.RemoteSpeech{Kind: "cancel"}}
|
||||
if c.call("remote.present", request, nil) != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-stream.muteCancel:
|
||||
if !cancelMuted() {
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
// Every effect shares the heartbeat deadline, including Braille and
|
||||
// focus requests. A continuously ready queue must not starve it.
|
||||
select {
|
||||
@@ -243,6 +271,10 @@ func (c *coordinator) speech_operations_ticks(a *connectionAttempt, stream *spee
|
||||
if !heartbeat() {
|
||||
return
|
||||
}
|
||||
case <-stream.muteCancel:
|
||||
if !cancelMuted() {
|
||||
return
|
||||
}
|
||||
case value := <-stream.brailleOps:
|
||||
if !c.braille_call(a, stream, value) {
|
||||
return
|
||||
@@ -274,9 +306,22 @@ func (c *coordinator) speech_operations_ticks(a *connectionAttempt, stream *spee
|
||||
return
|
||||
}
|
||||
case item := <-stream.incoming:
|
||||
select {
|
||||
case <-stream.muteCancel:
|
||||
if !cancelMuted() {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
}
|
||||
default:
|
||||
}
|
||||
c.mu.Lock()
|
||||
discard := stream.muted || item.generation != stream.speechGeneration
|
||||
ready := c.speech_ready_locked(a, stream)
|
||||
c.mu.Unlock()
|
||||
if discard {
|
||||
c.speech_release(stream, item.bytes)
|
||||
continue
|
||||
}
|
||||
if !ready {
|
||||
c.speech_release(stream, item.bytes)
|
||||
return
|
||||
@@ -384,3 +429,25 @@ func (c *coordinator) speech_output(a *connectionAttempt, stream *speechStream,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mute invalidates queued speech and serializes cancellation through the same
|
||||
// remote lease owner. It never invokes the reader's general speech cancellation.
|
||||
func (c *coordinator) toggle_mute() (bool, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
a := c.active
|
||||
if a == nil || a.speech == nil || a.speech.role != "controller" || !slices.Contains(a.speech.grants, "remote-present") || !c.speech_ready_locked(a, a.speech) {
|
||||
return false, errLease
|
||||
}
|
||||
stream := a.speech
|
||||
stream.muted = !stream.muted
|
||||
stream.speechGeneration++
|
||||
c.status.muted = stream.muted
|
||||
if stream.muted {
|
||||
select {
|
||||
case stream.muteCancel <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
return stream.muted, nil
|
||||
}
|
||||
@@ -354,3 +354,41 @@ func TestSpeechStreamAdmissionBoundsAndGrants(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteMuteDiscardsOldSpeechAndCancelsOnlyItsLease(t *testing.T) {
|
||||
c, a, stream := inertSpeechStream(t, "controller", []string{"remote-present"})
|
||||
client := &fixtureClient{events: make(chan sdk.SessionEvent, 1), calls: make(chan readerCall, 16)}
|
||||
c.client = client
|
||||
message := message{kind: "speak", payload: speech{parts: []speechPart{{kind: "text", text: "old"}}}}
|
||||
if _, err := c.receive_speech(a, stream, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if muted, err := c.toggle_mute(); err != nil || !muted {
|
||||
t.Fatal("mute failed", err)
|
||||
}
|
||||
if _, err := c.receive_speech(a, stream, message); err != nil || len(stream.incoming) != 1 {
|
||||
t.Fatal("muted speech queued")
|
||||
}
|
||||
if muted, err := c.toggle_mute(); err != nil || muted {
|
||||
t.Fatal("unmute failed", err)
|
||||
}
|
||||
message.payload = speech{parts: []speechPart{{kind: "text", text: "new"}}}
|
||||
if _, err := c.receive_speech(a, stream, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); c.speech_operations_ticks(a, stream, make(chan time.Time)) }()
|
||||
cancel := nextCall(t, client, "remote.present").params.(sdk.RemotePresentation)
|
||||
if cancel.Speech.Kind != "cancel" || cancel.Lease != stream.lease.Lease || cancel.Epoch != 1 {
|
||||
t.Fatal("mute used general or wrong-session cancellation")
|
||||
}
|
||||
spoken := nextCall(t, client, "remote.present").params.(sdk.RemotePresentation)
|
||||
if len(spoken.Speech.Parts) != 1 || spoken.Speech.Parts[0].Text != "new" || spoken.Sequence <= cancel.Sequence {
|
||||
t.Fatal("old speech replayed or cancel reordered", spoken)
|
||||
}
|
||||
a.cancel()
|
||||
awaitDone(t, done)
|
||||
if stream.items != 0 || stream.bytes != 0 {
|
||||
t.Fatal("muted queue accounting leaked")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user