-
Notifications
You must be signed in to change notification settings - Fork 9
/
clerk.go
239 lines (197 loc) · 5.82 KB
/
clerk.go
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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package clerk
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/spf13/pflag"
"namespacelabs.dev/foundation/internal/fnerrors"
)
var (
ErrUnauthorized = fnerrors.New("Unauthorized")
devClerk = false
)
const (
prodAddress = "https://clerk.namespace.so/"
devAddress = "https://clerk.firm.hare-7.lcl.dev"
prodTokenPrefix = "ct_"
devTokenPrefix = "devct_"
)
func SetupFlags(flags *pflag.FlagSet) {
flags.BoolVar(&devClerk, "dev_clerk", devClerk, "Use DEV Clerk instance.")
_ = flags.MarkHidden("dev_clerk")
}
type devBrowserResponse struct {
ID string `json:"id"`
InstanceID string `json:"instance_id"`
Token string `json:"token"`
ClientID string `json:"client_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
HomeOrigin string `json:"home_origin"`
}
type clerkResponse struct {
Response struct {
Identifier string `json:"identifier"`
} `json:"response"`
Client struct {
Sessions []struct {
User struct {
ExternalAccounts []struct {
Provider string `json:"provider"`
Username string `json:"username"`
Verification struct {
Status string `json:"status"`
}
} `json:"external_accounts"`
} `json:"user"`
} `json:"sessions"`
} `json:"client"`
}
type State struct {
Email string `json:"email,omitempty"`
Name string `json:"name,omitempty"`
ClerkClient string `json:"clerk_client,omitempty"`
GithubUsername string `json:"github_username,omitempty"`
DevSession string `json:"dev_session,omitempty"` // Only for DEV instance
}
func Login(ctx context.Context, ticket string) (*State, error) {
form := url.Values{}
form.Add("strategy", "ticket")
form.Add("ticket", ticket)
devSession := ""
signinsURL := prodAddress + "/v1/client/sign_ins"
if devClerk {
req, err := http.NewRequestWithContext(ctx, "POST", devAddress+"/v1/dev_browser", nil)
if err != nil {
return nil, err
}
req.Header.Add("Origin", "https://accounts.namespace.so")
req.Header.Add("User-Agent", "NamespaceCLI/1.0")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fnerrors.InvocationError("login", "failed to authenticate client: %v", resp.Status)
}
var x devBrowserResponse
if err := json.NewDecoder(resp.Body).Decode(&x); err != nil {
return nil, fnerrors.InvocationError("login", "bad response for client authentication: %w", err)
}
devSession = x.Token
signinsURL = devAddress + "/v1/client/sign_ins?__dev_session=" + devSession
}
req, err := http.NewRequestWithContext(ctx, "POST", signinsURL, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Add("Origin", "https://accounts.namespace.so")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("User-Agent", "NamespaceCLI/1.0")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fnerrors.InvocationError("login", "failed to authenticate: %v", resp.Status)
}
var client string
for _, k := range resp.Cookies() {
if k.Name == "__client" {
client = k.Value
}
}
if k := resp.Header.Get("Clerk-Cookie"); devClerk && k != "" {
client = k
}
if client == "" {
return nil, fnerrors.InvocationError("login", "missing client cookie")
}
var x clerkResponse
if err := json.NewDecoder(resp.Body).Decode(&x); err != nil {
return nil, fnerrors.InvocationError("login", "bad response: %w", err)
}
state := &State{
Email: x.Response.Identifier,
ClerkClient: client,
DevSession: devSession,
}
for _, session := range x.Client.Sessions {
for _, external := range session.User.ExternalAccounts {
if external.Provider == "oauth_github" && external.Verification.Status == "verified" {
state.GithubUsername = external.Username
}
}
}
return state, nil
}
type jwtResponse struct {
JWT string `json:"jwt"`
}
type cachedJWT struct {
JWT string
CreatedAt time.Time
}
var (
tokenCache = map[string]cachedJWT{}
tokenCacheMu sync.Mutex
)
func JWT(ctx context.Context, st *State) (string, error) {
tokenCacheMu.Lock()
defer tokenCacheMu.Unlock()
if cached, ok := tokenCache[st.ClerkClient]; ok {
if time.Now().Before(cached.CreatedAt.Add(10 * time.Second)) {
return cached.JWT, nil
} else {
delete(tokenCache, st.ClerkClient)
}
}
tokenPrefix := prodTokenPrefix
url := prodAddress + "/v1/me/tokens"
if devClerk {
url = devAddress + "/v1/me/tokens?__dev_session=" + st.DevSession
tokenPrefix = devTokenPrefix
}
req, err := http.NewRequestWithContext(ctx, "POST", url, nil)
if err != nil {
return "", err
}
req.AddCookie(&http.Cookie{
Name: "__client",
Value: st.ClerkClient,
})
req.Header.Add("Origin", "https://cli.namespace.so")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("User-Agent", "NamespaceCLI/1.0")
now := time.Now()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fnerrors.InvocationError("jwt", "failed to obtain token: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusUnauthorized {
return "", ErrUnauthorized
}
return "", fnerrors.InvocationError("jwt", "failed to obtain token: %v", resp.Status)
}
var x jwtResponse
if err := json.NewDecoder(resp.Body).Decode(&x); err != nil {
return "", fnerrors.InvocationError("jwt", "bad response: %w", err)
}
token := tokenPrefix + x.JWT
tokenCache[st.ClerkClient] = cachedJWT{
CreatedAt: now,
JWT: token,
}
return token, nil
}