|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +// Sign-in is the OAuth 2.0 device authorization grant (RFC 8628) against |
| 16 | +// Zitadel: `work login` prints a code, you approve it in a browser with your |
| 17 | +// own Google account, and the CLI keeps the access + refresh tokens in |
| 18 | +// ~/.config/work/token.json (0600). The access token is a JWT whose audience |
| 19 | +// includes the Switchboard project, which is what Switchboard's /mcp accepts. |
| 20 | +const ( |
| 21 | + issuer = "https://identity.jumpstartlab.com" |
| 22 | + clientID = "399472863209404232" // "work CLI" native app, Switchboard project |
| 23 | + scope = "openid email profile offline_access urn:zitadel:iam:org:project:id:383836969857207435:aud" |
| 24 | +) |
| 25 | + |
| 26 | +type token struct { |
| 27 | + AccessToken string `json:"access_token"` |
| 28 | + RefreshToken string `json:"refresh_token"` |
| 29 | + Expiry time.Time `json:"expiry"` |
| 30 | +} |
| 31 | + |
| 32 | +func tokenPath() string { |
| 33 | + dir := os.Getenv("XDG_CONFIG_HOME") |
| 34 | + if dir == "" { |
| 35 | + home, _ := os.UserHomeDir() |
| 36 | + dir = filepath.Join(home, ".config") |
| 37 | + } |
| 38 | + return filepath.Join(dir, "work", "token.json") |
| 39 | +} |
| 40 | + |
| 41 | +func loadToken() (*token, error) { |
| 42 | + b, err := os.ReadFile(tokenPath()) |
| 43 | + if err != nil { |
| 44 | + return nil, errors.New("not signed in — run `work login`") |
| 45 | + } |
| 46 | + var t token |
| 47 | + if err := json.Unmarshal(b, &t); err != nil { |
| 48 | + return nil, fmt.Errorf("token file unreadable (%v) — run `work login`", err) |
| 49 | + } |
| 50 | + return &t, nil |
| 51 | +} |
| 52 | + |
| 53 | +func saveToken(t *token) error { |
| 54 | + p := tokenPath() |
| 55 | + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + b, _ := json.MarshalIndent(t, "", " ") |
| 59 | + return os.WriteFile(p, b, 0o600) |
| 60 | +} |
| 61 | + |
| 62 | +type tokenResponse struct { |
| 63 | + AccessToken string `json:"access_token"` |
| 64 | + RefreshToken string `json:"refresh_token"` |
| 65 | + ExpiresIn int `json:"expires_in"` |
| 66 | + Error string `json:"error"` |
| 67 | + ErrorDesc string `json:"error_description"` |
| 68 | +} |
| 69 | + |
| 70 | +func postForm(path string, form url.Values) (*tokenResponse, map[string]any, error) { |
| 71 | + resp, err := http.PostForm(issuer+path, form) |
| 72 | + if err != nil { |
| 73 | + return nil, nil, err |
| 74 | + } |
| 75 | + defer resp.Body.Close() |
| 76 | + var raw map[string]any |
| 77 | + if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil { |
| 78 | + return nil, nil, fmt.Errorf("%s: unreadable response (%s)", path, resp.Status) |
| 79 | + } |
| 80 | + b, _ := json.Marshal(raw) |
| 81 | + var tr tokenResponse |
| 82 | + _ = json.Unmarshal(b, &tr) |
| 83 | + return &tr, raw, nil |
| 84 | +} |
| 85 | + |
| 86 | +func (tr *tokenResponse) toToken(prevRefresh string) *token { |
| 87 | + t := &token{AccessToken: tr.AccessToken, RefreshToken: tr.RefreshToken, |
| 88 | + Expiry: time.Now().Add(time.Duration(tr.ExpiresIn) * time.Second)} |
| 89 | + if t.RefreshToken == "" { |
| 90 | + t.RefreshToken = prevRefresh |
| 91 | + } |
| 92 | + return t |
| 93 | +} |
| 94 | + |
| 95 | +func login() error { |
| 96 | + _, raw, err := postForm("/oauth/v2/device_authorization", url.Values{"client_id": {clientID}, "scope": {scope}}) |
| 97 | + if err != nil { |
| 98 | + return err |
| 99 | + } |
| 100 | + if e, ok := raw["error"]; ok { |
| 101 | + return fmt.Errorf("sign-in refused: %v %v", e, raw["error_description"]) |
| 102 | + } |
| 103 | + device, _ := raw["device_code"].(string) |
| 104 | + code, _ := raw["user_code"].(string) |
| 105 | + link, _ := raw["verification_uri_complete"].(string) |
| 106 | + interval := 5 |
| 107 | + if v, ok := raw["interval"].(float64); ok && v > 0 { |
| 108 | + interval = int(v) |
| 109 | + } |
| 110 | + fmt.Printf("Open %s\nand confirm the code %s (sign in with your own Google account).\n", link, code) |
| 111 | + openBrowser(link) |
| 112 | + |
| 113 | + deadline := time.Now().Add(10 * time.Minute) |
| 114 | + for time.Now().Before(deadline) { |
| 115 | + time.Sleep(time.Duration(interval) * time.Second) |
| 116 | + tr, _, err := postForm("/oauth/v2/token", url.Values{ |
| 117 | + "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, |
| 118 | + "device_code": {device}, "client_id": {clientID}}) |
| 119 | + if err != nil { |
| 120 | + return err |
| 121 | + } |
| 122 | + switch tr.Error { |
| 123 | + case "": |
| 124 | + if err := saveToken(tr.toToken("")); err != nil { |
| 125 | + return err |
| 126 | + } |
| 127 | + who, _ := whoami() |
| 128 | + fmt.Printf("Signed in%s.\n", strings.TrimSpace(" as "+who)) |
| 129 | + return nil |
| 130 | + case "authorization_pending": |
| 131 | + case "slow_down": |
| 132 | + interval += 5 |
| 133 | + default: |
| 134 | + return fmt.Errorf("sign-in failed: %s %s", tr.Error, tr.ErrorDesc) |
| 135 | + } |
| 136 | + } |
| 137 | + return errors.New("sign-in timed out — run `work login` again") |
| 138 | +} |
| 139 | + |
| 140 | +// accessToken returns a live access token, refreshing it when it is within a |
| 141 | +// minute of expiry. |
| 142 | +func accessToken() (string, error) { |
| 143 | + t, err := loadToken() |
| 144 | + if err != nil { |
| 145 | + return "", err |
| 146 | + } |
| 147 | + if time.Until(t.Expiry) > time.Minute { |
| 148 | + return t.AccessToken, nil |
| 149 | + } |
| 150 | + if t.RefreshToken == "" { |
| 151 | + return "", errors.New("session expired — run `work login`") |
| 152 | + } |
| 153 | + tr, _, err := postForm("/oauth/v2/token", url.Values{ |
| 154 | + "grant_type": {"refresh_token"}, "refresh_token": {t.RefreshToken}, |
| 155 | + "client_id": {clientID}, "scope": {scope}}) |
| 156 | + if err != nil { |
| 157 | + return "", err |
| 158 | + } |
| 159 | + if tr.Error != "" { |
| 160 | + return "", fmt.Errorf("session expired (%s) — run `work login`", tr.Error) |
| 161 | + } |
| 162 | + nt := tr.toToken(t.RefreshToken) |
| 163 | + if err := saveToken(nt); err != nil { |
| 164 | + return "", err |
| 165 | + } |
| 166 | + return nt.AccessToken, nil |
| 167 | +} |
| 168 | + |
| 169 | +// whoami reads the email claim from the access token (display only; Switchboard |
| 170 | +// verifies it). |
| 171 | +func whoami() (string, error) { |
| 172 | + t, err := loadToken() |
| 173 | + if err != nil { |
| 174 | + return "", err |
| 175 | + } |
| 176 | + parts := strings.Split(t.AccessToken, ".") |
| 177 | + if len(parts) != 3 { |
| 178 | + return "", errors.New("access token is not a JWT") |
| 179 | + } |
| 180 | + b, err := decodeSegment(parts[1]) |
| 181 | + if err != nil { |
| 182 | + return "", err |
| 183 | + } |
| 184 | + var claims struct { |
| 185 | + Email string `json:"email"` |
| 186 | + } |
| 187 | + _ = json.Unmarshal(b, &claims) |
| 188 | + return claims.Email, nil |
| 189 | +} |
| 190 | + |
| 191 | +func logout() error { |
| 192 | + err := os.Remove(tokenPath()) |
| 193 | + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 194 | + return err |
| 195 | + } |
| 196 | + fmt.Println("Signed out.") |
| 197 | + return nil |
| 198 | +} |
0 commit comments