1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 cryptorand "crypto/rand"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 htmltemplate "html/template"
11 "io"
12 "log"
13 "net/http"
14 "os"
15 "strings"
16
17 "github.com/mjl-/mox/mlog"
18 "github.com/mjl-/mox/updates"
19)
20
21func cmdUpdatesAddSigned(c *cmd) {
22 c.unlisted = true
23 c.params = "privkey-file changes-file < message"
24 c.help = "Add a signed change to the changes file."
25 args := c.Parse()
26 if len(args) != 2 {
27 c.Usage()
28 }
29
30 f, err := os.Open(args[0])
31 xcheckf(err, "open private key file")
32 defer func() {
33 err := f.Close()
34 c.log.Check(err, "closing private key file")
35 }()
36 seed, err := io.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
37 xcheckf(err, "read private key file")
38 if len(seed) != ed25519.SeedSize {
39 log.Fatalf("private key is %d bytes, must be %d", len(seed), ed25519.SeedSize)
40 }
41
42 vf, err := os.Open(args[1])
43 xcheckf(err, "open changes file")
44 var changelog updates.Changelog
45 err = json.NewDecoder(vf).Decode(&changelog)
46 xcheckf(err, "parsing changes file")
47
48 privKey := ed25519.NewKeyFromSeed(seed)
49
50 fmt.Fprintln(os.Stderr, "reading changelog text from stdin")
51 buf, err := io.ReadAll(os.Stdin)
52 xcheckf(err, "parse message")
53
54 if len(buf) == 0 {
55 log.Fatalf("empty message")
56 }
57 // Message starts with headers similar to email, with "version" and "date".
58 // todo future: enforce this format?
59 sig := ed25519.Sign(privKey, buf)
60
61 change := updates.Change{
62 PubKey: privKey.Public().(ed25519.PublicKey),
63 Sig: sig,
64 Text: string(buf),
65 }
66 changelog.Changes = append([]updates.Change{change}, changelog.Changes...)
67
68 var b bytes.Buffer
69 enc := json.NewEncoder(&b)
70 enc.SetIndent("", "\t")
71 err = enc.Encode(changelog)
72 xcheckf(err, "encode changelog as json")
73 err = os.WriteFile(args[1], b.Bytes(), 0644)
74 xcheckf(err, "writing versions file")
75}
76
77func cmdUpdatesVerify(c *cmd) {
78 c.unlisted = true
79 c.params = "pubkey-base64 < changelog-file"
80 c.help = "Verify the changelog file against the public key."
81 args := c.Parse()
82 if len(args) != 1 {
83 c.Usage()
84 }
85
86 pubKey := ed25519.PublicKey(base64Decode(args[0]))
87
88 var changelog updates.Changelog
89 err := json.NewDecoder(os.Stdin).Decode(&changelog)
90 xcheckf(err, "parsing changelog file")
91
92 for i, c := range changelog.Changes {
93 if !bytes.Equal(c.PubKey, pubKey) {
94 log.Fatalf("change has different public key %x, expected %x", c.PubKey, pubKey)
95 } else if !ed25519.Verify(pubKey, []byte(c.Text), c.Sig) {
96 log.Fatalf("verification failed for change with index %d", i)
97 }
98 }
99 fmt.Printf("%d change(s) verified\n", len(changelog.Changes))
100}
101
102func cmdUpdatesGenkey(c *cmd) {
103 c.unlisted = true
104 c.params = ">privkey"
105 c.help = "Generate a key for signing a changelog file with."
106 args := c.Parse()
107 if len(args) != 0 {
108 c.Usage()
109 }
110
111 buf := make([]byte, ed25519.SeedSize)
112 _, err := cryptorand.Read(buf)
113 xcheckf(err, "generating key")
114 enc := base64.NewEncoder(base64.StdEncoding, os.Stdout)
115 _, err = enc.Write(buf)
116 xcheckf(err, "writing private key")
117 err = enc.Close()
118 xcheckf(err, "writing private key")
119}
120
121func cmdUpdatesPubkey(c *cmd) {
122 c.unlisted = true
123 c.params = "<privkey >pubkey"
124 c.help = "Print the public key for a private key."
125 args := c.Parse()
126 if len(args) != 0 {
127 c.Usage()
128 }
129
130 seed := make([]byte, ed25519.SeedSize)
131 _, err := io.ReadFull(base64.NewDecoder(base64.StdEncoding, os.Stdin), seed)
132 xcheckf(err, "reading private key")
133 privKey := ed25519.NewKeyFromSeed(seed)
134 pubKey := []byte(privKey.Public().(ed25519.PublicKey))
135 enc := base64.NewEncoder(base64.StdEncoding, os.Stdout)
136 _, err = enc.Write(pubKey)
137 xcheckf(err, "writing public key")
138 err = enc.Close()
139 xcheckf(err, "writing public key")
140}
141
142var updatesTemplate = htmltemplate.Must(htmltemplate.New("changelog").Parse(`<!doctype html>
143<html>
144 <head>
145 <meta charset="utf-8" />
146 <meta name="viewport" content="width=device-width, initial-scale=1" />
147 <title>mox changelog</title>
148 <style>
149body, html { padding: 1em; font-size: 16px; }
150* { font-size: inherit; font-family: ubuntu, lato, sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
151h1, h2, h3, h4 { margin-bottom: 1ex; }
152h1 { font-size: 1.2rem; }
153.literal { background-color: #fdfdfd; padding: .5em 1em; border: 1px solid #eee; border-radius: 4px; white-space: pre-wrap; font-family: monospace; font-size: 15px; tab-size: 4; }
154 </style>
155 </head>
156 <body>
157 <h1>Changes{{ if .FromVersion }} since {{ .FromVersion }}{{ end }}</h1>
158 {{ if not .Changes }}
159 <div>No changes</div>
160 {{ end }}
161 {{ range .Changes }}
162 <pre class="literal">{{ .Text }}</pre>
163 <hr style="margin:1ex 0" />
164 {{ end }}
165 </body>
166</html>
167`))
168
169func cmdUpdatesServe(c *cmd) {
170 c.unlisted = true
171 c.help = "Serve changelog.json with updates."
172 var address, changelog string
173 c.flag.StringVar(&address, "address", "127.0.0.1:8596", "address to serve /changelog on")
174 c.flag.StringVar(&changelog, "changelog", "changelog.json", "changelog file to serve")
175 args := c.Parse()
176 if len(args) != 0 {
177 c.Usage()
178 }
179
180 parseFile := func() (*updates.Changelog, error) {
181 f, err := os.Open(changelog)
182 if err != nil {
183 return nil, err
184 }
185 defer func() {
186 err := f.Close()
187 c.log.Check(err, "closing changelog file")
188 }()
189 var cl updates.Changelog
190 if err := json.NewDecoder(f).Decode(&cl); err != nil {
191 return nil, err
192 }
193 return &cl, nil
194 }
195
196 _, err := parseFile()
197 if err != nil {
198 log.Fatalf("parsing %s: %v", changelog, err)
199 }
200
201 srv := http.NewServeMux()
202 srv.HandleFunc("/changelog", func(w http.ResponseWriter, r *http.Request) {
203 cl, err := parseFile()
204 if err != nil {
205 log.Printf("parsing %s: %v", changelog, err)
206 http.Error(w, "500 - internal server error", http.StatusInternalServerError)
207 return
208 }
209 from := r.URL.Query().Get("from")
210 var fromVersion *updates.Version
211 if from != "" {
212 v, err := updates.ParseVersion(from)
213 if err == nil {
214 fromVersion = &v
215 }
216 }
217 if fromVersion != nil {
218 nextchange:
219 for i, c := range cl.Changes {
220 for _, line := range strings.Split(strings.Split(c.Text, "\n\n")[0], "\n") {
221 if strings.HasPrefix(line, "version:") {
222 v, err := updates.ParseVersion(strings.TrimSpace(strings.TrimPrefix(line, "version:")))
223 if err == nil && !v.After(*fromVersion) {
224 cl.Changes = cl.Changes[:i]
225 break nextchange
226 }
227 }
228 }
229 }
230 }
231
232 // Check if client accepts html. If so, we'll provide a human-readable version.
233 accept := r.Header.Get("Accept")
234 var html bool
235 accept:
236 for _, ac := range strings.Split(accept, ",") {
237 var ok bool
238 for i, kv := range strings.Split(strings.TrimSpace(ac), ";") {
239 if i == 0 {
240 ct := strings.TrimSpace(kv)
241 if strings.EqualFold(ct, "text/html") || strings.EqualFold(ct, "text/*") {
242 ok = true
243 continue
244 }
245 continue accept
246 }
247 t := strings.SplitN(strings.TrimSpace(kv), "=", 2)
248 if !strings.EqualFold(t[0], "q") || len(t) != 2 {
249 continue
250 }
251 switch t[1] {
252 case "0", "0.", "0.0", "0.00", "0.000":
253 ok = false
254 continue accept
255 }
256 break
257 }
258 if ok {
259 html = true
260 break
261 }
262 }
263
264 if html {
265 w.Header().Set("Content-Type", "text/html; charset=utf-8")
266 err := updatesTemplate.Execute(w, map[string]any{
267 "FromVersion": fromVersion,
268 "Changes": cl.Changes,
269 })
270 if err != nil && !mlog.IsClosed(err) {
271 log.Printf("writing changelog html: %v", err)
272 }
273 } else {
274 w.Header().Set("Content-Type", "application/json; charset=utf-8")
275 if err := json.NewEncoder(w).Encode(cl); err != nil && !mlog.IsClosed(err) {
276 log.Printf("writing changelog json: %v", err)
277 }
278 }
279 })
280 log.Printf("listening on %s", address)
281 log.Fatalln(http.ListenAndServe(address, srv))
282}
283