package pkg import ( "bufio" "context" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "io/fs" "net" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "time" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/youtube/v3" ) const ( scopeUpload = youtube.YoutubeUploadScope scopeReadonly = youtube.YoutubeReadonlyScope defaultManualAuthPort = 8090 ) // AuthOptions configures OAuth authorization. type AuthOptions struct { ClientSecretFile string TokenFile string // NeedReadonly requests the youtube.readonly scope in addition to the // upload scope. NeedReadonly bool // Manual selects the paste-the-redirect-URL flow instead of a loopback // callback. It is useful when ytcat runs on a machine that cannot receive // the browser's callback. Manual bool // Port is the loopback callback port. Zero means an ephemeral port for the // loopback flow and defaultManualAuthPort for the manual flow. A fixed port // allows SSH port forwarding to reach the remote machine's callback. Port int // In supplies the pasted redirect URL for the manual flow. In io.Reader // Out receives authorization instructions. A nil Out discards them. Out io.Writer } // storedToken is the on-disk token format. It mirrors the fields of // oauth2.Token and records the granted scopes so that a cached token can be // rejected when -wait needs videos.list access it was not granted. type storedToken struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type,omitempty"` RefreshToken string `json:"refresh_token,omitempty"` // omitempty has no effect on a struct such as time.Time; omitzero does. Expiry time.Time `json:"expiry,omitzero"` Scopes []string `json:"scopes,omitempty"` } func (t storedToken) token() *oauth2.Token { return &oauth2.Token{ AccessToken: t.AccessToken, TokenType: t.TokenType, RefreshToken: t.RefreshToken, Expiry: t.Expiry, } } // Authorize returns an HTTP client authorized for YouTube uploads. // // The OAuth client configuration is read from ClientSecretFile. An existing // token is loaded from TokenFile and refreshed as needed. If no usable token // exists, the authorization code flow is started and the resulting token is // written back to TokenFile. func Authorize(ctx context.Context, opts AuthOptions) (*http.Client, error) { if opts.Out == nil { opts.Out = io.Discard } scopes := []string{scopeUpload} if opts.NeedReadonly { scopes = append(scopes, scopeReadonly) } conf, err := configFromFile(opts.ClientSecretFile, scopes...) if err != nil { return nil, err } stored, err := loadToken(opts.TokenFile) reauthorize := false switch { case errors.Is(err, fs.ErrNotExist): reauthorize = true case err != nil: return nil, err default: token := stored.token() if opts.NeedReadonly && !hasScope(stored.Scopes, scopeReadonly) { reauthorize = true } else if token.RefreshToken == "" && !token.Valid() { reauthorize = true } } if reauthorize { token, err := authorize(ctx, conf, opts) if err != nil { return nil, err } // Google may not return a new refresh token when re-consenting to add // a scope; keep the existing one in that case. if token.RefreshToken == "" { token.RefreshToken = stored.RefreshToken } if err := saveToken(opts.TokenFile, token, scopes); err != nil { return nil, err } return conf.Client(ctx, token), nil } return conf.Client(ctx, stored.token()), nil } func authorize(ctx context.Context, conf *oauth2.Config, opts AuthOptions) (*oauth2.Token, error) { if opts.Manual { if opts.In == nil { return nil, errors.New("manual authorization requires an input reader") } return authorizeManual(ctx, conf, opts.Port, opts.In, opts.Out) } return authorizeWeb(ctx, conf, opts.Port, opts.Out) } func configFromFile(path string, scopes ...string) (*oauth2.Config, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("could not read OAuth client secret %q: %w", path, err) } conf, err := google.ConfigFromJSON(data, scopes...) if err != nil { return nil, fmt.Errorf("could not parse OAuth client secret %q: %w", path, err) } return conf, nil } func loadToken(path string) (storedToken, error) { f, err := os.Open(path) if err != nil { return storedToken{}, err } defer func() { _ = f.Close() }() var stored storedToken if err := json.NewDecoder(f).Decode(&stored); err != nil { return storedToken{}, fmt.Errorf("could not decode token file %q: %w", path, err) } return stored, nil } func saveToken(path string, token *oauth2.Token, requestedScopes []string) error { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return fmt.Errorf("could not create token directory: %w", err) } stored := storedToken{ AccessToken: token.AccessToken, TokenType: token.TokenType, RefreshToken: token.RefreshToken, Expiry: token.Expiry, Scopes: grantedScopes(token, requestedScopes), } data, err := json.MarshalIndent(stored, "", " ") if err != nil { return fmt.Errorf("could not encode token: %w", err) } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return fmt.Errorf("could not create token file %q: %w", path, err) } if _, err := f.Write(data); err != nil { _ = f.Close() return fmt.Errorf("could not write token file %q: %w", path, err) } if err := f.Close(); err != nil { return fmt.Errorf("could not close token file %q: %w", path, err) } return nil } // grantedScopes returns the scopes granted by the token response, falling back // to the scopes ytcat asked for when the response did not include them. func grantedScopes(token *oauth2.Token, requestedScopes []string) []string { if scope, ok := token.Extra("scope").(string); ok { if fields := strings.Fields(scope); len(fields) > 0 { return fields } } return requestedScopes } func hasScope(scopes []string, want string) bool { for _, scope := range scopes { if scope == want { return true } } return false } type authResult struct { code string err error } func authorizeWeb(ctx context.Context, conf *oauth2.Config, port int, out io.Writer) (*oauth2.Token, error) { addr := "127.0.0.1:0" if port > 0 { addr = "127.0.0.1:" + strconv.Itoa(port) } ln, err := net.Listen("tcp", addr) if err != nil { return nil, fmt.Errorf("could not start local OAuth server: %w", err) } defer func() { _ = ln.Close() }() conf.RedirectURL = "http://" + ln.Addr().String() state, err := randomState() if err != nil { return nil, err } results := make(chan authResult, 1) srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if errParam := r.FormValue("error"); errParam != "" { http.Error(w, "authorization failed: "+errParam, http.StatusBadRequest) results <- authResult{err: fmt.Errorf("authorization failed: %s", errParam)} return } if r.FormValue("state") != state { http.Error(w, "invalid state", http.StatusBadRequest) results <- authResult{err: errors.New("invalid OAuth state")} return } code := r.FormValue("code") if code == "" { http.Error(w, "missing code", http.StatusBadRequest) results <- authResult{err: errors.New("missing OAuth code")} return } _, _ = fmt.Fprintln(w, "ytcat: authorization received, you can close this window.") results <- authResult{code: code} })} go func() { _ = srv.Serve(ln) }() defer func() { _ = srv.Shutdown(context.Background()) }() authURL := conf.AuthCodeURL(state, oauth2.AccessTypeOffline) _, _ = fmt.Fprintf(out, "Open the following URL in your browser to authorize ytcat:\n\n%s\n\n", authURL) select { case <-ctx.Done(): return nil, ctx.Err() case result := <-results: if result.err != nil { return nil, result.err } token, err := conf.Exchange(ctx, result.code) if err != nil { return nil, fmt.Errorf("could not exchange authorization code: %w", err) } return token, nil } } // authorizeManual prints the authorization URL, then reads back the redirect // URL that the browser tried to open. This works when ytcat runs on a machine // that cannot receive the callback itself. func authorizeManual(ctx context.Context, conf *oauth2.Config, port int, in io.Reader, out io.Writer) (*oauth2.Token, error) { if port <= 0 { port = defaultManualAuthPort } conf.RedirectURL = fmt.Sprintf("http://127.0.0.1:%d", port) state, err := randomState() if err != nil { return nil, err } authURL := conf.AuthCodeURL(state, oauth2.AccessTypeOffline) _, _ = fmt.Fprintf(out, "Open the following URL in a browser on any machine:\n\n%s\n\n", authURL) _, _ = fmt.Fprintf(out, "After approving, the browser will try to open %s and probably fail.\nCopy the full URL from the address bar and paste it here:\n\n> ", conf.RedirectURL, ) line, err := bufio.NewReader(in).ReadString('\n') if err != nil && !errors.Is(err, io.EOF) { return nil, err } if errors.Is(err, io.EOF) && strings.TrimSpace(line) == "" { return nil, io.ErrUnexpectedEOF } code, err := authorizationCode(line, state) if err != nil { return nil, err } token, err := conf.Exchange(ctx, code) if err != nil { return nil, fmt.Errorf("could not exchange authorization code: %w", err) } return token, nil } // authorizationCode extracts and validates the authorization code from the // redirect URL pasted by the user. func authorizationCode(redirectURL, state string) (string, error) { raw := strings.TrimSpace(redirectURL) if raw == "" { return "", errors.New("empty redirect URL") } if !strings.Contains(raw, "://") { raw = "http://" + raw } u, err := url.Parse(raw) if err != nil { return "", fmt.Errorf("could not parse redirect URL: %w", err) } query := u.Query() if errParam := query.Get("error"); errParam != "" { return "", fmt.Errorf("authorization failed: %s", errParam) } if got := query.Get("state"); got != state { return "", errors.New("invalid OAuth state in redirect URL") } code := query.Get("code") if code == "" { return "", errors.New("redirect URL does not contain a code") } return code, nil } func randomState() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", fmt.Errorf("could not generate OAuth state: %w", err) } return base64.RawURLEncoding.EncodeToString(b), nil }