This repository was archived by the owner on Mar 17, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclient.go
More file actions
582 lines (484 loc) · 14.8 KB
/
client.go
File metadata and controls
582 lines (484 loc) · 14.8 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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package http
import (
"bytes"
"context"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
"github.com/nitrictech/suga/cli/internal/config"
"github.com/nitrictech/suga/cli/internal/utils"
)
const DEFAULT_HOSTNAME = "api.workos.com"
// Errors
type CodeExchangeError struct {
Message string
}
func (e *CodeExchangeError) Error() string {
return e.Message
}
type RefreshError struct {
Message string
}
func (e *RefreshError) Error() string {
return e.Message
}
// Authentication response types
type AuthenticationResponseRaw struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
User User `json:"user"`
}
type User struct {
ID string `json:"id"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
ProfilePictureURL string `json:"profile_picture_url"`
LastSignInAt string `json:"last_sign_in_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ExternalID string `json:"external_id"`
}
type AuthenticationResponse struct {
AccessToken string
RefreshToken string
User User
}
type JWKsResponse struct {
Keys []JWK `json:"keys"`
}
type JWK struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
Alg string `json:"alg"`
N string `json:"n"`
E string `json:"e"`
X5c []string `json:"x5c"`
X5tS256 string `json:"x5t#S256"`
}
// Authorization URL options
type GetAuthorizationUrlOptions struct {
ConnectionID string
Context string
DomainHint string
LoginHint string
OrganizationID string
Provider string
RedirectURI string
State string
ScreenHint string
PasswordResetToken string
InvitationToken string
CodeChallenge string
CodeChallengeMethod string
}
// HttpClient represents the WorkOS HTTP client
type HttpClient struct {
baseURL string
clientID string
client *http.Client
debugEnabled bool
}
// NewHttpClient creates a new WorkOS HTTP client
func NewHttpClient(clientID string, cfg *config.Config, options ...ClientOption) *HttpClient {
clientConfig := &clientConfig{
hostname: DEFAULT_HOSTNAME,
scheme: "https",
}
for _, option := range options {
option(clientConfig)
}
baseURL := &url.URL{
Scheme: clientConfig.scheme,
Host: clientConfig.hostname,
}
if clientConfig.port != 0 {
baseURL.Host = fmt.Sprintf("%s:%d", clientConfig.hostname, clientConfig.port)
}
return &HttpClient{
baseURL: baseURL.String(),
clientID: clientID,
client: &http.Client{},
debugEnabled: cfg.Debug,
}
}
// logRequest logs the HTTP request details if debug mode is enabled
func (h *HttpClient) logRequest(req *http.Request) {
if !h.debugEnabled {
return
}
fmt.Fprintf(os.Stderr, "[DEBUG] WorkOS Request:\n")
if dump, err := httputil.DumpRequest(req, true); err == nil {
fmt.Fprintf(os.Stderr, "%s\n\n", dump)
}
}
// logResponse logs the HTTP response details if debug mode is enabled
func (h *HttpClient) logResponse(resp *http.Response) {
if !h.debugEnabled {
return
}
fmt.Fprintf(os.Stderr, "[DEBUG] WorkOS Response:\n")
if dump, err := httputil.DumpResponse(resp, true); err == nil {
fmt.Fprintf(os.Stderr, "%s\n\n", dump)
}
}
type clientConfig struct {
hostname string
port int
scheme string
}
type ClientOption func(*clientConfig)
func WithHostname(hostname string) ClientOption {
return func(c *clientConfig) {
c.hostname = hostname
}
}
func WithPort(port int) ClientOption {
return func(c *clientConfig) {
c.port = port
}
}
func WithScheme(scheme string) ClientOption {
return func(c *clientConfig) {
c.scheme = scheme
}
}
func jwkToRSAPublicKey(jwk JWK) (*rsa.PublicKey, error) {
// Decode the modulus (n)
nBytes, err := base64.RawURLEncoding.DecodeString(jwk.N)
if err != nil {
return nil, err
}
// Decode the exponent (e)
eBytes, err := base64.RawURLEncoding.DecodeString(jwk.E)
if err != nil {
return nil, err
}
// Create the RSA public key
return &rsa.PublicKey{
N: new(big.Int).SetBytes(nBytes),
E: int(new(big.Int).SetBytes(eBytes).Int64()),
}, nil
}
// GetRSAPublicKey gets the RSA public key for a given JWT kid
func (h *HttpClient) GetRSAPublicKey(kid string) (*rsa.PublicKey, error) {
jwk, err := h.GetJWK(kid)
if err != nil {
return nil, err
}
return jwkToRSAPublicKey(jwk)
}
func (h *HttpClient) GetJWK(kid string) (JWK, error) {
jwks, err := h.GetJWKs()
if err != nil {
return JWK{}, err
}
for _, jwk := range jwks {
if jwk.Kid == kid {
return jwk, nil
}
}
return JWK{}, fmt.Errorf("JWK not found")
}
func (h *HttpClient) GetJWKs() ([]JWK, error) {
jwkPath := path.Join("sso/jwks", h.clientID)
response, err := h.get(jwkPath)
if err != nil {
return nil, err
}
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
var jwksResponse JWKsResponse
if err := json.Unmarshal(body, &jwksResponse); err != nil {
return nil, err
}
return jwksResponse.Keys, nil
}
// AuthenticateWithCode authenticates using an authorization code
func (h *HttpClient) AuthenticateWithCode(code, codeVerifier string) (*AuthenticationResponse, error) {
body := map[string]interface{}{
"code": code,
"client_id": h.clientID,
"grant_type": "authorization_code",
"code_verifier": codeVerifier,
}
response, err := h.post("/user_management/authenticate", body)
if err != nil {
return nil, err
}
// read the body into a string
resBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusOK {
var data AuthenticationResponseRaw
if err := json.Unmarshal(resBody, &data); err != nil {
return nil, err
}
return deserializeAuthenticationResponse(data), nil
}
return nil, &CodeExchangeError{Message: fmt.Sprintf("Error authenticating with API, status: %d, body: %s", response.StatusCode, string(resBody))}
}
// post performs a POST request to the specified path
func (h *HttpClient) post(path string, body map[string]interface{}) (*http.Response, error) {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, err
}
baseURL, err := url.Parse(h.baseURL)
if err != nil {
return nil, fmt.Errorf("invalid base URL: %w", err)
}
// Join the base URL with the path safely
fullURL := baseURL.JoinPath(path)
req, err := http.NewRequest("POST", fullURL.String(), bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-amz-content-sha256", utils.CalculateSHA256(jsonBody))
// Log the request
h.logRequest(req)
resp, err := h.client.Do(req)
if err != nil {
return nil, err
}
// Log the response
h.logResponse(resp)
return resp, nil
}
func (h *HttpClient) get(path string) (*http.Response, error) {
baseURL, err := url.Parse(h.baseURL)
if err != nil {
return nil, fmt.Errorf("invalid base URL: %w", err)
}
fullURL := baseURL.JoinPath(path)
req, err := http.NewRequest("GET", fullURL.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json, text/plain, */*")
// Log the request
h.logRequest(req)
resp, err := h.client.Do(req)
if err != nil {
return nil, err
}
// Log the response
h.logResponse(resp)
return resp, nil
}
type AuthenticatedWithRefreshTokenOptions struct {
OrganizationID string `json:"organization_id,omitempty"`
}
// AuthenticateWithRefreshToken authenticates using a refresh token via backend proxy
func (h *HttpClient) AuthenticateWithRefreshToken(refreshToken string, options AuthenticatedWithRefreshTokenOptions) (*AuthenticationResponse, error) {
body := map[string]interface{}{
"refresh_token": refreshToken,
}
if options.OrganizationID != "" {
body["organization_id"] = options.OrganizationID
}
response, err := h.post("/auth/refresh", body)
if err != nil {
return nil, err
}
resBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusOK {
var data AuthenticationResponseRaw
if err := json.Unmarshal(resBody, &data); err != nil {
return nil, err
}
return deserializeAuthenticationResponse(data), nil
}
return nil, &RefreshError{Message: fmt.Sprintf("Error refreshing token: status %d, body: %s", response.StatusCode, string(resBody))}
}
// GetAuthorizationUrl generates an authorization URL
func (h *HttpClient) GetAuthorizationUrl(options GetAuthorizationUrlOptions) (string, error) {
if options.Provider == "" && options.ConnectionID == "" && options.OrganizationID == "" {
return "", fmt.Errorf("incomplete arguments. need to specify either a 'connectionId', 'organizationId', or 'provider'")
}
if options.Provider != "" && options.Provider != "authkit" && options.ScreenHint != "" {
return "", fmt.Errorf("'screenHint' is only supported for 'authkit' provider")
}
baseURL, err := url.Parse(h.baseURL)
if err != nil {
return "", fmt.Errorf("invalid base URL: %w", err)
}
// Join the base URL with the authorize path
authURL := baseURL.JoinPath("user_management", "authorize")
// Build query parameters
params := url.Values{}
if options.ConnectionID != "" {
params.Set("connection_id", options.ConnectionID)
}
if options.Context != "" {
params.Set("context", options.Context)
}
if options.OrganizationID != "" {
params.Set("organization_id", options.OrganizationID)
}
if options.DomainHint != "" {
params.Set("domain_hint", options.DomainHint)
}
if options.LoginHint != "" {
params.Set("login_hint", options.LoginHint)
}
if options.Provider != "" {
params.Set("provider", options.Provider)
}
params.Set("client_id", h.clientID)
if options.RedirectURI != "" {
params.Set("redirect_uri", options.RedirectURI)
}
params.Set("response_type", "code")
if options.State != "" {
params.Set("state", options.State)
}
if options.ScreenHint != "" {
params.Set("screen_hint", options.ScreenHint)
}
if options.InvitationToken != "" {
params.Set("invitation_token", options.InvitationToken)
}
if options.PasswordResetToken != "" {
params.Set("password_reset_token", options.PasswordResetToken)
}
if options.CodeChallenge != "" {
params.Set("code_challenge", options.CodeChallenge)
}
if options.CodeChallengeMethod != "" {
params.Set("code_challenge_method", options.CodeChallengeMethod)
}
authURL.RawQuery = params.Encode()
return authURL.String(), nil
}
// GetLogoutUrl generates a logout URL
func (h *HttpClient) GetLogoutUrl(sessionID, returnTo string) string {
baseURL, err := url.Parse(h.baseURL)
if err != nil {
// If base URL is invalid, return a basic string (this shouldn't happen with proper initialization)
return ""
}
// Join the base URL with the logout path
logoutURL := baseURL.JoinPath("user_management", "sessions", "logout")
// Build query parameters
params := url.Values{}
params.Set("session_id", sessionID)
if returnTo != "" {
params.Set("return_to", returnTo)
}
logoutURL.RawQuery = params.Encode()
return logoutURL.String()
}
// deserializeAuthenticationResponse converts the raw response to the structured response
func deserializeAuthenticationResponse(raw AuthenticationResponseRaw) *AuthenticationResponse {
return &AuthenticationResponse{
AccessToken: raw.AccessToken,
RefreshToken: raw.RefreshToken,
User: raw.User,
}
}
// RequestDeviceAuthorization requests device authorization from backend
func (c *HttpClient) RequestDeviceAuthorization() (*DeviceAuthorizationResponse, error) {
response, err := c.post("/auth/device", map[string]interface{}{})
if err != nil {
return nil, fmt.Errorf("failed to make device authorization request: %w", err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read device authorization response: %w", err)
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("device authorization request failed with status %d: %s", response.StatusCode, string(body))
}
var deviceResp DeviceAuthorizationResponse
if err := json.Unmarshal(body, &deviceResp); err != nil {
return nil, fmt.Errorf("failed to parse device authorization response: %w", err)
}
return &deviceResp, nil
}
// PollDeviceTokenWithContext polls for device token from backend with a context for cancellation/timeout
func (c *HttpClient) PollDeviceTokenWithContext(ctx context.Context, deviceCode string) (*DeviceTokenResponse, error) {
reqBody := map[string]interface{}{"device_code": deviceCode}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
baseURL, err := url.Parse(c.baseURL)
if err != nil {
return nil, fmt.Errorf("invalid base URL: %w", err)
}
// Join the base URL with the path safely
fullURL := baseURL.JoinPath("/auth/device/token")
req, err := http.NewRequestWithContext(ctx, "POST", fullURL.String(), bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-amz-content-sha256", utils.CalculateSHA256(jsonBody))
// Log the request
c.logRequest(req)
response, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make device token request: %w", err)
}
defer response.Body.Close()
// Log the response
c.logResponse(response)
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read device token response: %w", err)
}
if response.StatusCode == http.StatusOK {
var tokenResp DeviceTokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse device token response: %w", err)
}
return &tokenResp, nil
}
// Handle error response from backend
var errorResp map[string]string
if err := json.Unmarshal(body, &errorResp); err == nil {
if errorCode, ok := errorResp["error"]; ok {
return nil, errors.New(errorCode)
}
}
return nil, fmt.Errorf("device token request failed with status %d: %s", response.StatusCode, string(body))
}
// DeviceAuthorizationResponse represents device authorization response
type DeviceAuthorizationResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}
// DeviceTokenResponse represents device token response
type DeviceTokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
User User `json:"user"`
}