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
|
/*
* Copyright (c) 2024 Runxi Yu <https://runxiyu.org>
* SPDX-License-Identifier: BSD-2-Clause
*
* Key inspiration was taken from mutt_oauth2.py written by Alexander Perlis,
* licensed under the GNU General Public License, version 2 or later, as
* published by the Free Software Foundation. I don't think that this program
* is a derivative work of mutt_oauth2.py in terms of GPL interpretation, but I
* might be wrong. Consult your lawyer if you want to use this program in a
* context incompatible with the GPL.
* https://raw.githubusercontent.com/muttmua/mutt/master/contrib/mutt_oauth2.py
*/
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"time"
)
type Registration struct {
AuthorizeEndpoint string
DevicecodeEndpoint string
TokenEndpoint string
Tenant string
Scope string
ClientID string
}
type Token struct {
AccessToken string `json:"access_token"`
AccessTokenExpiration string `json:"access_token_expiration"`
RefreshToken string `json:"refresh_token"`
Email string `json:"email"`
}
var ykps = Registration{
AuthorizeEndpoint: "https://login.microsoftonline.com/ddd3d26c-b197-4d00-a32d-1ffd84c0c295/oauth2/v2.0/authorize",
DevicecodeEndpoint: "https://login.microsoftonline.com/ddd3d26c-b197-4d00-a32d-1ffd84c0c295/oauth2/v2.0/devicecode",
TokenEndpoint: "https://login.microsoftonline.com/ddd3d26c-b197-4d00-a32d-1ffd84c0c295/oauth2/v2.0/token",
Tenant: "ddd3d26c-b197-4d00-a32d-1ffd84c0c295",
Scope: "offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send",
ClientID: "fea760d5-b496-4f63-be1e-93855c1c5f78",
}
var token Token
var tokenFile string
var authorize_email string
func init() {
flag.StringVar(&tokenFile, "tokenfile", "", "(required) persistent token storage")
flag.StringVar(&authorize_email, "authorize", "", "email to newly authorize")
flag.Parse()
}
func readTokenFile() error {
data, err := os.ReadFile(tokenFile)
if err != nil {
return err
}
return json.Unmarshal(data, &token)
}
func writeTokenFile() error {
data, err := json.Marshal(&token)
if err != nil {
return err
}
return os.WriteFile(tokenFile, data, 0600)
}
func accessTokenValid() bool {
if token.AccessTokenExpiration == "" {
return false
}
expirationTime, err := time.Parse(time.RFC3339, token.AccessTokenExpiration)
if err != nil {
return false
}
return time.Now().Before(expirationTime)
}
func updateTokens(r map[string]interface{}) error {
token.AccessToken = r["access_token"].(string)
expiresIn := int(r["expires_in"].(float64))
token.AccessTokenExpiration = time.Now().Add(time.Duration(expiresIn) * time.Second).Format(time.RFC3339)
if refreshToken, ok := r["refresh_token"]; ok {
token.RefreshToken = refreshToken.(string)
}
return writeTokenFile()
}
func generateCodeVerifier() (string, string, error) {
verifier := make([]byte, 90)
_, err := rand.Read(verifier)
if err != nil {
return "", "", err
}
codeVerifier := base64.RawURLEncoding.EncodeToString(verifier)
hash := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
return codeVerifier, codeChallenge, nil
}
func startHTTPServer() (chan string, int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, 0, err
}
codeChan := make(chan string)
server := &http.Server{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if code != "" {
codeChan <- code
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Done, please check your terminal")
})
go func() {
if err := server.Serve(listener); err != http.ErrServerClosed {
log.Fatalf("HTTP server error: %v", err)
}
}()
return codeChan, listener.Addr().(*net.TCPAddr).Port, nil
}
func authorize_request() error {
p := url.Values{
"client_id": {ykps.ClientID},
"tenant": {ykps.Tenant},
"scope": {ykps.Scope},
}
codeVerifier, codeChallenge, err := generateCodeVerifier()
if err != nil {
return err
}
codeChan, port, err := startHTTPServer()
if err != nil {
return err
}
redirectURI := fmt.Sprintf("http://localhost:%d/", port)
p.Set("redirect_uri", redirectURI)
p.Set("response_type", "code")
p.Set("code_challenge", codeChallenge)
p.Set("code_challenge_method", "S256")
p.Set("login_hint", token.Email)
authorizeURL := ykps.AuthorizeEndpoint + "?" + p.Encode()
fmt.Fprintf(os.Stderr, "Please visit:\n%s\n", authorizeURL)
authCode := <-codeChan
data := url.Values{
"client_id": {ykps.ClientID},
"tenant": {ykps.Tenant},
"code": {authCode},
"redirect_uri": {redirectURI},
"grant_type": {"authorization_code"},
"code_verifier": {codeVerifier},
}
resp, err := http.PostForm(ykps.TokenEndpoint, data)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
var response map[string]interface{}
if err := json.Unmarshal(body, &response); err != nil {
return err
}
if _, ok := response["error"]; ok {
return fmt.Errorf("authorization error: %v", response["error"])
}
return updateTokens(response)
}
func refreshToken() error {
if token.RefreshToken == "" {
return errors.New("no refresh token available")
}
data := url.Values{
"client_id": {ykps.ClientID},
"tenant": {ykps.Tenant},
"refresh_token": {token.RefreshToken},
"grant_type": {"refresh_token"},
}
resp, err := http.PostForm(ykps.TokenEndpoint, data)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
var response map[string]interface{}
if err := json.Unmarshal(body, &response); err != nil {
return err
}
if _, ok := response["error"]; ok {
return fmt.Errorf("refresh token error: %v", response["error"])
}
return updateTokens(response)
}
func main() {
if tokenFile == "" {
log.Fatal("You must provide a token file path.")
}
if err := readTokenFile(); err != nil {
if !os.IsNotExist(err) {
log.Fatalf("Error reading token file: %v", err)
}
if authorize_email == "" {
log.Fatalf("You must run the script with --authorize at least once.")
}
token.Email = authorize_email
token.AccessToken = ""
token.AccessTokenExpiration = ""
token.RefreshToken = ""
if err := writeTokenFile(); err != nil {
log.Fatalf("Error writing token file: %v", err)
}
}
if authorize_email != "" {
if err := authorize_request(); err != nil {
log.Fatalf("Authorization error: %v", err)
}
} else if !accessTokenValid() {
if err := refreshToken(); err != nil {
log.Fatalf("Refresh token error: %v", err)
}
}
if !accessTokenValid() {
log.Fatal("No valid access token. This should not be able to happen.")
}
fmt.Println(token.AccessToken)
}
|