1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

// detectTerminalEmulator finds an available terminal emulator.
// Priority: $TERMINAL env var > alacritty > kitty > gnome-terminal > xterm
func detectTerminalEmulator() (string, error) {
	// 1. Check TERMINAL environment variable (user's preference)
	if terminal := os.Getenv("TERMINAL"); terminal != "" {
		if path, err := exec.LookPath(terminal); err == nil {
			return path, nil
		}
		// TERMINAL is set but not found - log warning but continue
		log.Printf("Warning: TERMINAL=%s not found, trying fallbacks\n", terminal)
	}

	// 2. Fall back to detecting common terminals
	terminals := []string{
		"alacritty",
		"kitty",
		"gnome-terminal",
		"konsole",
		"xterm",
	}

	for _, term := range terminals {
		if path, err := exec.LookPath(term); err == nil {
			return path, nil
		}
	}

	return "", fmt.Errorf("no terminal emulator found (set $TERMINAL or install alacritty/kitty/xterm)")
}

// getTerminalCommand constructs the command to run the dialog subcommand in a terminal.
// Different terminals have different command-line arguments.
// The terminal emulator provides the PTY directly.
func getTerminalCommand(terminal, selfPath, jsonData string) *exec.Cmd {
	termName := filepath.Base(terminal)

	switch termName {
	case "gnome-terminal":
		return exec.Command(terminal, "--", selfPath, "dialog", "--json", jsonData)
	case "alacritty", "kitty", "xterm", "konsole":
		return exec.Command(terminal, "-e", selfPath, "dialog", "--json", jsonData)
	default:
		// Default to -e flag
		return exec.Command(terminal, "-e", selfPath, "dialog", "--json", jsonData)
	}
}

// escapeShell escapes a string for safe use in shell scripts.
// Wraps in single quotes and escapes any single quotes inside.
func escapeShell(s string) string {
	// Replace ' with '\''
	escaped := strings.ReplaceAll(s, "'", "'\\''")
	return "'" + escaped + "'"
}

// UserApproval prompts the user to approve or deny a token request.
// Uses gum in a terminal emulator for a rich TUI experience.
// Returns true if approved, false if denied.
// NOTE: Capability service is DUMB - it doesn't know what token types mean!
// It just shows the user what was requested and gets approval.
// The requesting service can provide descriptions to help the user understand.
func (cs *CapabilityServer) UserApproval(
	tokenID string,
	scope map[string]any,
	sessionID string,
	reason string,
	tokenDescription string,
	fieldDescriptions map[string]any,
) (bool, error) {
	// Generate dialog ID
	dialogIDBytes := make([]byte, 16)
	if _, err := rand.Read(dialogIDBytes); err != nil {
		return false, fmt.Errorf("failed to generate dialog ID: %w", err)
	}
	dialogID := base64.URLEncoding.EncodeToString(dialogIDBytes)
	log.Printf("Generated dialog ID: %s\n", dialogID)

	// Create channel for result
	resultChan := make(chan bool, 1)

	// Register channel
	cs.dialogMutex.Lock()
	cs.dialogChannels[dialogID] = resultChan
	cs.dialogMutex.Unlock()

	// Ensure cleanup
	defer func() {
		cs.dialogMutex.Lock()
		delete(cs.dialogChannels, dialogID)
		cs.dialogMutex.Unlock()
		close(resultChan)
	}()

	// Detect terminal emulator
	terminal, err := detectTerminalEmulator()
	if err != nil {
		return false, fmt.Errorf("terminal detection failed: %w", err)
	}
	log.Printf("Using terminal: %s\n", terminal)

	// Build token request JSON
	req := TokenRequest{
		TokenID:           tokenID,
		Scope:             scope,
		SessionID:         sessionID,
		Reason:            reason,
		TokenDescription:  tokenDescription,
		FieldDescriptions: fieldDescriptions,
	}

	jsonBytes, err := json.Marshal(req)
	if err != nil {
		return false, fmt.Errorf("failed to marshal token request: %w", err)
	}
	jsonData := string(jsonBytes)
	log.Printf("Generated JSON (%d bytes)\n", len(jsonData))

	// Get path to our own binary
	selfPath, err := os.Executable()
	if err != nil {
		return false, fmt.Errorf("failed to get executable path: %w", err)
	}

	// Launch terminal with dialog subcommand
	cmd := getTerminalCommand(terminal, selfPath, jsonData)
	cmd.Env = append(os.Environ(), fmt.Sprintf("DIALOG_ID=%s", dialogID))
	log.Printf("Executing: %v\n", cmd.Args)

	if err := cmd.Start(); err != nil {
		return false, fmt.Errorf("failed to start dialog: %w", err)
	}

	// Wait for callback with timeout (2 minutes)
	timeout := time.After(2 * time.Minute)

	select {
	case approved := <-resultChan:
		if approved {
			log.Printf("User approved token request\n")
		} else {
			log.Printf("User denied token request\n")
		}
		return approved, nil

	case <-timeout:
		log.Printf("Dialog timeout - no response received\n")
		return false, fmt.Errorf("dialog timeout: user did not respond")
	}
}

// NotifyTokenIssued shows a notification that a token was issued.
// Uses gum toast for non-intrusive feedback.
func NotifyTokenIssued(tokenID string, scope map[string]any) {
	// Build notification text
	var text strings.Builder
	text.WriteString(fmt.Sprintf("Token issued: %s\n", tokenID))
	for key, value := range scope {
		text.WriteString(fmt.Sprintf("%s: %v\n", key, value))
	}

	// Run gum toast (fire and forget)
	cmd := exec.Command("gum", "style", "--foreground", "2", text.String())
	_ = cmd.Start()
}

// NotifyTokenDenied shows a notification that a token request was denied.
func NotifyTokenDenied(tokenID string) {
	cmd := exec.Command("gum", "style", "--foreground", "1", fmt.Sprintf("Token request denied: %s", tokenID))
	_ = cmd.Start()
}