Debian Codegraph @

pkg/generators/xoauth2/xoauth2.go

raw
1 // Package xoauth2 provides OAuth2 authentication for email services.
2 package xoauth2
3
4 import (
5 "bufio"
6 "context"
7 "crypto/rand"
8 "encoding/base64"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "os"
13 "strings"
14
15 "golang.org/x/oauth2"
16 "golang.org/x/oauth2/google"
17
18 "github.com/nicholas-fedor/shoutrrr/pkg/services/email/smtp"
19 "github.com/nicholas-fedor/shoutrrr/pkg/types"
20 )
21
22 // Generator is the XOAuth2 Generator implementation.
23 type Generator struct{}
24
25 // SMTP port constants.
26 const (
27 DefaultSMTPPort uint16 = 25 // Standard SMTP port without encryption
28 GmailSMTPPortStartTLS uint16 = 587 // Gmail SMTP port with STARTTLS
29 )
30
31 // StateLength is the length in bytes for OAuth 2.0 state randomness (128 bits).
32 const StateLength int = 16
33
34 // Errors.
35 var (
36 ErrReadFileFailed = errors.New("failed to read file")
37 ErrUnmarshalFailed = errors.New("failed to unmarshal JSON")
38 ErrScanFailed = errors.New("failed to scan input")
39 ErrTokenExchangeFailed = errors.New("failed to exchange token")
40 )
41
42 // Generate generates a service URL from a set of user questions/answers.
43 func (g *Generator) Generate(
44 _ types.Service,
45 props map[string]string,
46 args []string,
47 ) (types.ServiceConfig, error) {
48 if provider, found := props["provider"]; found {
49 if provider == "gmail" {
50 return oauth2GeneratorGmail(args[0])
51 }
52 }
53
54 if len(args) > 0 {
55 return oauth2GeneratorFile(args[0])
56 }
57
58 return oauth2Generator()
59 }
60
61 // generateOauth2Config completes the OAuth2 flow and generates SMTP configuration.
62 func generateOauth2Config(conf *oauth2.Config, host string) (*smtp.Config, error) {
63 scanner := bufio.NewScanner(os.Stdin)
64
65 // Generate a random state value
66 stateBytes := make([]byte, StateLength)
67 if _, err := rand.Read(stateBytes); err != nil {
68 return nil, fmt.Errorf("generating random state: %w", err)
69 }
70
71 state := base64.URLEncoding.EncodeToString(stateBytes)
72
73 if _, err := fmt.Fprintf(
74 os.Stdout,
75 "Visit the following URL to authenticate:\n%s\n\n",
76 conf.AuthCodeURL(state),
77 ); err != nil {
78 return nil, fmt.Errorf("writing to stdout: %w", err)
79 }
80
81 var verCode string
82
83 if _, err := fmt.Fprint(os.Stdout, "Enter verification code: "); err != nil {
84 return nil, fmt.Errorf("writing to stdout: %w", err)
85 }
86
87 if scanner.Scan() {
88 verCode = scanner.Text()
89 } else {
90 return nil, fmt.Errorf("verification code: %w", ErrScanFailed)
91 }
92
93 ctx := context.Background()
94
95 token, err := conf.Exchange(ctx, verCode)
96 if err != nil {
97 return nil, fmt.Errorf("%s: %w", verCode, ErrTokenExchangeFailed)
98 }
99
100 var sender string
101
102 if _, err := fmt.Fprint(os.Stdout, "Enter sender e-mail: "); err != nil {
103 return nil, fmt.Errorf("writing to stdout: %w", err)
104 }
105
106 if scanner.Scan() {
107 sender = scanner.Text()
108 } else {
109 return nil, fmt.Errorf("sender email: %w", ErrScanFailed)
110 }
111
112 // Determine the appropriate port based on the host
113 port := DefaultSMTPPort
114 if host == "smtp.gmail.com" {
115 port = GmailSMTPPortStartTLS // Use 587 for Gmail with STARTTLS
116 }
117
118 svcConf := &smtp.Config{
119 Host: host,
120 Port: port,
121 Username: sender,
122 Password: token.AccessToken,
123 FromAddress: sender,
124 FromName: "Shoutrrr",
125 ToAddresses: []string{sender},
126 Auth: smtp.AuthTypes.OAuth2,
127 UseStartTLS: true,
128 UseHTML: true,
129 }
130
131 return svcConf, nil
132 }
133
134 // oauth2Generator generates OAuth2 configuration from user input.
135 func oauth2Generator() (*smtp.Config, error) {
136 scanner := bufio.NewScanner(os.Stdin)
137
138 var clientID string
139
140 if _, err := fmt.Fprint(os.Stdout, "ClientID: "); err != nil {
141 return nil, fmt.Errorf("writing to stdout: %w", err)
142 }
143
144 if scanner.Scan() {
145 clientID = scanner.Text()
146 } else {
147 return nil, fmt.Errorf("clientID: %w", ErrScanFailed)
148 }
149
150 var clientSecret string
151
152 if _, err := fmt.Fprint(os.Stdout, "ClientSecret: "); err != nil {
153 return nil, fmt.Errorf("writing to stdout: %w", err)
154 }
155
156 if scanner.Scan() {
157 clientSecret = scanner.Text()
158 } else {
159 return nil, fmt.Errorf("clientSecret: %w", ErrScanFailed)
160 }
161
162 var authURL string
163
164 if _, err := fmt.Fprint(os.Stdout, "AuthURL: "); err != nil {
165 return nil, fmt.Errorf("writing to stdout: %w", err)
166 }
167
168 if scanner.Scan() {
169 authURL = scanner.Text()
170 } else {
171 return nil, fmt.Errorf("authURL: %w", ErrScanFailed)
172 }
173
174 var tokenURL string
175
176 if _, err := fmt.Fprint(os.Stdout, "TokenURL: "); err != nil {
177 return nil, fmt.Errorf("writing to stdout: %w", err)
178 }
179
180 if scanner.Scan() {
181 tokenURL = scanner.Text()
182 } else {
183 return nil, fmt.Errorf("tokenURL: %w", ErrScanFailed)
184 }
185
186 var redirectURL string
187
188 if _, err := fmt.Fprint(os.Stdout, "RedirectURL: "); err != nil {
189 return nil, fmt.Errorf("writing to stdout: %w", err)
190 }
191
192 if scanner.Scan() {
193 redirectURL = scanner.Text()
194 } else {
195 return nil, fmt.Errorf("redirectURL: %w", ErrScanFailed)
196 }
197
198 var scopes string
199
200 if _, err := fmt.Fprint(os.Stdout, "Scopes: "); err != nil {
201 return nil, fmt.Errorf("writing to stdout: %w", err)
202 }
203
204 if scanner.Scan() {
205 scopes = scanner.Text()
206 } else {
207 return nil, fmt.Errorf("scopes: %w", ErrScanFailed)
208 }
209
210 var hostname string
211
212 if _, err := fmt.Fprint(os.Stdout, "SMTP Hostname: "); err != nil {
213 return nil, fmt.Errorf("writing to stdout: %w", err)
214 }
215
216 if scanner.Scan() {
217 hostname = scanner.Text()
218 } else {
219 return nil, fmt.Errorf("hostname: %w", ErrScanFailed)
220 }
221
222 conf := oauth2.Config{
223 ClientID: clientID,
224 ClientSecret: clientSecret,
225
226 Endpoint: oauth2.Endpoint{
227 AuthURL: authURL,
228 TokenURL: tokenURL,
229 AuthStyle: oauth2.AuthStyleAutoDetect,
230 },
231 RedirectURL: redirectURL,
232 Scopes: strings.Split(scopes, ","),
233 }
234
235 return generateOauth2Config(&conf, hostname)
236 }
237
238 // oauth2GeneratorFile generates OAuth2 configuration from a JSON file.
239 func oauth2GeneratorFile(file string) (*smtp.Config, error) {
240 jsonData, err := os.ReadFile(file)
241 if err != nil {
242 return nil, fmt.Errorf("%s: %w", file, ErrReadFileFailed)
243 }
244
245 var providerConfig struct {
246 ClientID string `json:"client_id"`
247
248 ClientSecret string `json:"client_secret"`
249 RedirectURL string `json:"redirect_url"`
250 AuthURL string `json:"auth_url"`
251 TokenURL string `json:"token_url"`
252 Hostname string `json:"smtp_hostname"`
253 Scopes []string `json:"scopes"`
254 }
255
256 if err := json.Unmarshal(jsonData, &providerConfig); err != nil {
257 return nil, fmt.Errorf("%s: %w", file, ErrUnmarshalFailed)
258 }
259
260 conf := oauth2.Config{
261 ClientID: providerConfig.ClientID,
262 ClientSecret: providerConfig.ClientSecret,
263
264 Endpoint: oauth2.Endpoint{
265 AuthURL: providerConfig.AuthURL,
266 TokenURL: providerConfig.TokenURL,
267 AuthStyle: oauth2.AuthStyleAutoDetect,
268 },
269 RedirectURL: providerConfig.RedirectURL,
270 Scopes: providerConfig.Scopes,
271 }
272
273 return generateOauth2Config(&conf, providerConfig.Hostname)
274 }
275
276 // oauth2GeneratorGmail generates OAuth2 configuration for Gmail using credentials file.
277 func oauth2GeneratorGmail(credFile string) (*smtp.Config, error) {
278 data, err := os.ReadFile(credFile)
279 if err != nil {
280 return nil, fmt.Errorf("%s: %w", credFile, ErrReadFileFailed)
281 }
282
283 conf, err := google.ConfigFromJSON(data, "https://mail.google.com/")
284 if err != nil {
285 return nil, fmt.Errorf("%s: %w", credFile, err)
286 }
287
288 return generateOauth2Config(conf, "smtp.gmail.com")
289 }