-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodejob_auth.go
More file actions
88 lines (73 loc) · 2.14 KB
/
Copy pathcodejob_auth.go
File metadata and controls
88 lines (73 loc) · 2.14 KB
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
package devflow
import (
"fmt"
"os"
"strings"
"golang.org/x/term"
)
const julesAPIKeyKey = "JULES_API_KEY"
const julesAPIKeyURL = "https://jules.google.com/settings/api"
// termLink returns an OSC 8 terminal hyperlink (supported by most modern terminals).
func termLink(text, url string) string {
return "\x1b]8;;" + url + "\x1b\\" + text + "\x1b]8;;\x1b\\"
}
// JulesAuth manages the Jules API key via the system keyring.
// On first use it prompts the user to enter the key and stores it securely.
type JulesAuth struct {
kr *Keyring
log func(...any)
}
// NewJulesAuth creates a JulesAuth with an initialized keyring.
func NewJulesAuth() (*JulesAuth, error) {
kr, _ := NewKeyring()
return &JulesAuth{
kr: kr,
log: func(...any) {},
}, nil
}
// SetLog sets the logging function.
func (a *JulesAuth) SetLog(fn func(...any)) {
if fn != nil {
a.log = fn
}
}
// HasKey returns true if the Jules API key is already stored in the environment or keyring.
func (a *JulesAuth) HasKey() bool {
if os.Getenv("JULES_API_KEY") != "" {
return true
}
if a.kr == nil {
return false
}
key, err := a.kr.Get(julesAPIKeyKey)
return err == nil && key != ""
}
// EnsureAPIKey returns the Jules API key from the environment or keyring.
// If absent, prompts the user for it once and persists it.
func (a *JulesAuth) EnsureAPIKey() (string, error) {
if envKey := os.Getenv("JULES_API_KEY"); envKey != "" {
return envKey, nil
}
if a.kr == nil {
return "", fmt.Errorf("keyring is unavailable and JULES_API_KEY env var is not set")
}
key, err := a.kr.Get(julesAPIKeyKey)
if err == nil && key != "" {
return key, nil
}
fmt.Fprintf(os.Stderr, "Jules API Key not found. Get yours at %s\nEnter it now: ",
termLink(julesAPIKeyURL, julesAPIKeyURL))
raw, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", fmt.Errorf("could not read API key: %w", err)
}
key = strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("API key cannot be empty")
}
if err := a.kr.Set(julesAPIKeyKey, key); err != nil {
a.log(fmt.Sprintf("warning: could not save API key to keyring: %v", err))
}
return key, nil
}