package cli import ( "bufio" "errors" "fmt" "io" "os" "strings" "time" "github.com/charmbracelet/huh" "github.com/spf13/cobra" "tangled.org/rockorager.dev/knit/internal/git" "tangled.org/rockorager.dev/knit/internal/session" "tangled.org/rockorager.dev/knit/internal/tangled" ) func newAuthCmd(app *App) *cobra.Command { cmd := &cobra.Command{ Use: "auth ", Short: "Authenticate knit and git with Tangled", } cmd.AddCommand( newAuthLoginCmd(app), newAuthLogoutCmd(app), newAuthStatusCmd(app), newAuthSetupGitCmd(app), newAuthGitCredentialCmd(app), ) return cmd } func newAuthLoginCmd(app *App) *cobra.Command { var handle string var appPassword bool cmd := &cobra.Command{ Use: "login", Short: "Log in to a Tangled account", Long: `Log in to a Tangled account. By default knit opens your browser to approve access with atproto OAuth. On a machine without a browser, such as over SSH, open the printed URL on any other device and approve there. The browser then fails to load a 127.0.0.1 page; paste that page's address into knit to finish. Alternatively, use --app-password with an app password created in your PDS's settings. With a non-interactive stdin, the password is read from stdin. Credentials are stored in knit's configuration directory, readable only by you.`, Example: ` knit auth login knit auth login --handle alice.tngl.sh echo "$APP_PASSWORD" | knit auth login --app-password --handle alice.tngl.sh`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() if handle == "" { if !app.interactive() { return errors.New("--handle is required when not running interactively") } if err := app.promptInput("Handle", "alice.tngl.sh", &handle); err != nil { return err } } handle = strings.TrimPrefix(strings.TrimSpace(handle), "@") var s *session.Session var err error if appPassword { var password string if app.InTTY { err = huh.NewInput().Title("App password").EchoMode(huh.EchoModePassword).Value(&password).Run() } else { var data []byte data, err = io.ReadAll(app.In) password = string(data) } if err != nil { return err } s, err = session.LoginAppPassword(ctx, handle, strings.TrimSpace(password)) } else { var paste io.Reader if app.InTTY { paste = app.In } s, err = session.LoginOAuth(ctx, handle, func(url string) { app.Infof("Open this URL to approve access:\n\n %s\n\n", url) if app.interactive() { _ = app.openBrowser(url) } if paste != nil { app.Infof("If your browser is on another machine, approve there, then paste\nthe address of the page it fails to load here.\n\n") } app.Infof("Waiting for approval...\n") }, paste) } if err != nil { return fmt.Errorf("logging in: %w", err) } app.Success("Logged in as %s", app.Bold(s.Handle)) return nil }, } cmd.Flags().StringVarP(&handle, "handle", "u", "", "Your handle or DID") cmd.Flags().BoolVar(&appPassword, "app-password", false, "Log in with an app password instead of the browser") return cmd } func newAuthLogoutCmd(app *App) *cobra.Command { return &cobra.Command{ Use: "logout", Short: "Log out of Tangled", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { s, err := session.Load() if err != nil { return err } if err := s.Logout(cmd.Context()); err != nil { app.Infof("Couldn't revoke the session on your PDS: %v\n", err) } app.Success("Logged out %s", app.Bold(s.Handle)) return nil }, } } func newAuthStatusCmd(app *App) *cobra.Command { return &cobra.Command{ Use: "status", Short: "Show the logged-in account", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { s, err := session.Load() if err != nil { return err } c := app.Client() pds, err := c.PDS(cmd.Context()) if err == nil { err = c.PDSGet(cmd.Context(), "com.atproto.server.getSession", nil, nil) } if err != nil { app.Printf("%s Logged in as %s, but the session doesn't work: %v\n", app.Red("X"), app.Bold(s.Handle), err) app.Printf(" Run `knit auth login` to log in again.\n") return errSilent } method := "OAuth" if s.Method == session.MethodAppPassword { method = "app password" } app.Printf("%s Logged in as %s\n", app.Green("✓"), app.Bold(s.Handle)) app.Printf(" DID: %s\n", s.DID) app.Printf(" PDS: %s\n", pds.Host) app.Printf(" Method: %s\n", method) return nil }, } } // errSilent makes knit exit non-zero after a command already explained why. var errSilent = errors.New("") func newAuthSetupGitCmd(app *App) *cobra.Command { var hosts []string cmd := &cobra.Command{ Use: "setup-git", Short: "Use knit to authenticate git pushes over HTTPS", Long: `Configure git to ask knit for credentials when pushing to a knot over HTTPS. Knots accept a short-lived service-auth token, minted by your PDS, as the password for HTTPS pushes. This sets knit as git's credential helper for each knot host, so you don't need an SSH key to push.`, Example: ` knit auth setup-git knit auth setup-git --hostname knot.example.com`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { if len(hosts) == 0 { hosts = []string{app.Config.Get("knot")} } exe, err := os.Executable() if err != nil { return err } for _, host := range hosts { key := "credential." + tangled.ServiceURL(host) + ".helper" // an empty helper first clears any inherited helpers if err := git.Run("config", "--global", "--replace-all", key, ""); err != nil { return err } if err := git.Run("config", "--global", "--add", key, "!"+shellQuote(exe)+" auth git-credential"); err != nil { return err } app.Success("Configured git to push to %s with knit", host) } return nil }, } cmd.Flags().StringSliceVar(&hosts, "hostname", nil, "Knot host to configure (default: the configured knot)") return cmd } func newAuthGitCredentialCmd(app *App) *cobra.Command { return &cobra.Command{ Use: "git-credential ", Short: "Implements the git credential helper protocol", Hidden: true, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if args[0] != "get" { return nil } attrs := map[string]string{} sc := bufio.NewScanner(app.In) for sc.Scan() { k, v, ok := strings.Cut(sc.Text(), "=") if !ok { break } attrs[k] = v } if attrs["protocol"] != "https" || attrs["host"] == "" { return nil } // knots accept a push token until it expires, and one push makes // several requests token, err := app.Client().ServiceAuth(cmd.Context(), tangled.ServiceDID(attrs["host"]), "org.tangled.git.receivePack", 5*time.Minute) if err != nil { return err } // knots only read the password, and split user:password at the // first colon, so the username must not be a DID app.Printf("username=knit\npassword=%s\n", token) return nil }, } } func shellQuote(s string) string { if !strings.ContainsAny(s, " '\"\\$`") { return s } return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }