-
Notifications
You must be signed in to change notification settings - Fork 260
/
publish.go
192 lines (169 loc) · 5 KB
/
publish.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
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/keygen"
"github.com/mattn/go-isatty"
gap "github.com/muesli/go-app-paths"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
const (
ghostHost = "ghost.charm.sh"
ghostPort = 22
)
var publishCmd = &cobra.Command{
Use: "publish <gif>",
Short: "Publish your GIF to vhs.charm.sh and get a shareable URL",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true, // we print our own errors
RunE: func(cmd *cobra.Command, args []string) error {
file := args[0]
if strings.HasSuffix(file, ".tape") {
log.Printf("Use vhs %s --publish flag to publish tapes\n", file)
return errors.New("must pass a GIF file")
}
if !strings.HasSuffix(file, gif) {
return errors.New("must pass a GIF file")
}
url, err := Publish(cmd.Context(), file)
if err != nil {
return err
}
if quietFlag || !isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println(url)
return nil
}
publishShareInstructions(url)
cmd.Print(" " + URLStyle.Render(url))
cmd.Println()
return nil
},
}
func dataPath() (string, error) {
scope := gap.NewScope(gap.User, "vhs")
dataPath, err := scope.DataPath("")
if err != nil {
return "", err
}
return dataPath, nil
}
// hostKeyCallback returns a callback that will be used to verify the host key.
//
// it creates a file in the given path, and uses that to verify hosts and keys.
// if the host does not exist there, it adds it so its available next time, as plain old `ssh` does.
func hostKeyCallback(path string) ssh.HostKeyCallback {
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
kh, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:gomnd
if err != nil {
return fmt.Errorf("failed to open known_hosts: %w", err)
}
defer func() { _ = kh.Close() }()
callback, err := knownhosts.New(kh.Name())
if err != nil {
return fmt.Errorf("failed to check known_hosts: %w", err)
}
if err := callback(hostname, remote, key); err != nil {
var kerr *knownhosts.KeyError
if errors.As(err, &kerr) {
if len(kerr.Want) > 0 {
return fmt.Errorf("possible man-in-the-middle attack: %w", err)
}
// if want is empty, it means the host was not in the known_hosts file, so lets add it there.
_, _ = fmt.Fprintln(kh, knownhosts.Line([]string{hostname}, key))
return nil
}
return fmt.Errorf("failed to check known_hosts: %w", err)
}
return nil
}
}
func sshSession() (*ssh.Session, error) {
dp, err := dataPath()
if err != nil {
return nil, err
}
kp, err := keygen.New(filepath.Join(dp, "vhs_ed25519"), keygen.WithKeyType(keygen.Ed25519), keygen.WithWrite())
if err != nil {
return nil, err
}
signer, err := ssh.NewSignerFromKey(kp.PrivateKey())
if err != nil {
return nil, err
}
pkam := ssh.PublicKeys(signer)
sshConfig := &ssh.ClientConfig{
User: "vhs",
Auth: []ssh.AuthMethod{pkam},
HostKeyCallback: hostKeyCallback(filepath.Join(dp, "known_hosts")),
}
c, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", ghostHost, ghostPort), sshConfig)
if err != nil {
return nil, err
}
s, err := c.NewSession()
if err != nil {
return nil, err
}
return s, nil
}
// publishShareInstructions log shareable URL
// If log level is set to `logLevelQuiet` the log message will be forced
func publishShareInstructions(url string) {
log.Println("\n" + GrayStyle.Render(" Share your GIF with Markdown:"))
log.Println(CommandStyle.Render(" ![Made with VHS]") + URLStyle.Render("("+url+")"))
log.Println(GrayStyle.Render("\n Or HTML (with badge):"))
log.Println(CommandStyle.Render(" <img ") + CommandStyle.Render("src=") + URLStyle.Render(`"`+url+`"`) + CommandStyle.Render(" alt=") + URLStyle.Render(`"Made with VHS"`) + CommandStyle.Render(">"))
log.Println(CommandStyle.Render(" <a ") + CommandStyle.Render("href=") + URLStyle.Render(`"https://vhs.charm.sh"`) + CommandStyle.Render(">"))
log.Println(CommandStyle.Render(" <img ") + CommandStyle.Render("src=") + URLStyle.Render(`"https://stuff.charm.sh/vhs/badge.svg"`) + CommandStyle.Render(">"))
log.Println(CommandStyle.Render(" </a>"))
log.Println(GrayStyle.Render("\n Or link to it:"))
}
// Publish publishes the given GIF file to the web.
func Publish(ctx context.Context, path string) (string, error) {
s, err := sshSession()
if err != nil {
return "", err
}
defer s.Close() //nolint:errcheck
// Close connection when context is done
go func() {
<-ctx.Done()
_ = s.Close()
}()
in, err := s.StdinPipe()
if err != nil {
return "", err
}
out, err := s.StdoutPipe()
if err != nil {
return "", err
}
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close() //nolint:errcheck
if err := s.Start(""); err != nil {
return "", err
}
_, err = io.Copy(in, f)
if err != nil {
return "", err
}
_ = in.Close()
b, err := io.ReadAll(out)
if err != nil {
return "", err
}
return string(b), nil
}