-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathrelay.go
263 lines (239 loc) · 7.07 KB
/
relay.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
"github.com/beeper/mac-registration-provider/versions"
)
type WebsocketRequest[T any] struct {
Command string `json:"command"`
ReqID int `json:"id,omitempty"`
Data T `json:"data,omitempty"`
}
type RegisterBody struct {
Code string `json:"code,omitempty"`
Secret string `json:"secret,omitempty"`
Commit string `json:"commit,omitempty"`
Versions versions.Versions `json:"versions"`
Error string `json:"error,omitempty"`
}
type ErrorResponse struct {
Error string `json:"error,omitempty"`
}
type EmptyResponse struct{}
type VersionsResponse struct {
Versions versions.Versions `json:"versions"`
}
type ValidationDataResponse struct {
Data []byte `json:"data"`
ValidUntil time.Time `json:"valid_until"`
}
var dataCache ValidationDataResponse
var cacheLock sync.Mutex
func cachedGenerateData(ctx context.Context) (ValidationDataResponse, error) {
cacheLock.Lock()
defer cacheLock.Unlock()
if time.Now().UTC().Add(5 * time.Minute).After(dataCache.ValidUntil) {
data, validUntil, err := GenerateValidationData(ctx)
if err != nil {
return ValidationDataResponse{}, err
}
dataCache = ValidationDataResponse{Data: data, ValidUntil: validUntil}
}
return dataCache, nil
}
func handleCommand(ctx context.Context, req WebsocketRequest[json.RawMessage]) (any, error) {
switch req.Command {
case "pong":
return nil, nil
case "ping":
// Pre-cache validation data on ping
go func() {
_, err := cachedGenerateData(ctx)
if err != nil {
log.Printf("Failed to pregenerate validation data on ping: %v", err)
} else {
log.Println("Pregenerated validation data on ping")
}
}()
return EmptyResponse{}, nil
case "get-version-info":
return VersionsResponse{Versions: versions.Current}, nil
case "get-validation-data":
return cachedGenerateData(ctx)
default:
return nil, fmt.Errorf("unknown command %q", req.Command)
}
}
type RelayConfig struct {
Code string `json:"code"`
Secret string `json:"secret"`
}
func isDir(dir string) bool {
stat, err := os.Stat(dir)
return err == nil && stat.IsDir()
}
func readConfig() (string, *RelayConfig, error) {
var configPath string
if *overrideConfigPath != "" {
configPath = *overrideConfigPath
} else {
baseConfigDir, err := os.UserConfigDir()
if err != nil {
return "", nil, fmt.Errorf("failed to get user config dir: %w", err)
}
configPath = filepath.Join(baseConfigDir, "beeper-registration-provider", "config.json")
configDir := filepath.Dir(configPath)
legacyConfigDir := filepath.Join(baseConfigDir, "beeper-validation-provider")
if isDir(legacyConfigDir) && !isDir(configDir) {
err = os.Rename(legacyConfigDir, configDir)
if err != nil {
log.Printf("Failed to rename legacy config dir: %v", err)
}
}
}
configData, err := os.ReadFile(configPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return "", nil, fmt.Errorf("failed to read config file: %w", err)
}
var config RelayConfig
if configData != nil {
err = json.Unmarshal(configData, &config)
if err != nil {
return "", nil, fmt.Errorf("failed to parse config file: %w", err)
}
}
return configPath, &config, nil
}
func writeConfig(cfg *RelayConfig, configPath string) error {
err := os.MkdirAll(filepath.Dir(configPath), 0700)
if err != nil {
return fmt.Errorf("failed to create config dir: %w", err)
}
file, err := os.OpenFile(configPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()
err = json.NewEncoder(file).Encode(cfg)
if err != nil {
return fmt.Errorf("failed to write config file: %w", err)
}
return nil
}
func ConnectRelay(ctx context.Context, addr string) error {
configPath, config, err := readConfig()
if err != nil {
return err
}
c, _, err := websocket.Dial(ctx, addr+"/api/v1/provider", &websocket.DialOptions{
HTTPHeader: http.Header{
"User-Agent": []string{submitUserAgent},
},
})
if err != nil {
return err
}
defer c.CloseNow()
err = wsjson.Write(ctx, c, &WebsocketRequest[*RegisterBody]{
Command: "register",
ReqID: 1,
Data: &RegisterBody{
Code: config.Code,
Secret: config.Secret,
Commit: Commit,
Versions: versions.Current,
},
})
if err != nil {
return fmt.Errorf("failed to write register request: %w", err)
}
var registerResp WebsocketRequest[*RegisterBody]
err = wsjson.Read(ctx, c, ®isterResp)
if err != nil {
return fmt.Errorf("failed to read register response: %w", err)
} else if registerResp.Command != "response" || registerResp.ReqID != 1 {
return fmt.Errorf("unexpected register response %+v", registerResp)
} else if registerResp.Data.Error != "" {
_ = os.Rename(configPath, configPath+".bak")
return fmt.Errorf("failed to register: %s", registerResp.Data.Error)
}
if config.Code == "" || config.Code != registerResp.Data.Code {
if config.Code != "" {
log.Println("Registration token changed")
}
config.Code = registerResp.Data.Code
config.Secret = registerResp.Data.Secret
err = writeConfig(config, configPath)
if err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
}
if *jsonOutput {
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
"code": registerResp.Data.Code,
"path": configPath,
})
} else {
fmt.Println()
fmt.Println(" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓")
fmt.Println(" ┃ iMessage registration code:", registerResp.Data.Code, "┃")
fmt.Println(" ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛")
fmt.Println()
fmt.Println("Delete", configPath, "if you want to regenerate the token")
}
reqID := 1
cancelableCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
ticker := time.NewTicker(3 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
reqID++
err = wsjson.Write(ctx, c, WebsocketRequest[any]{
Command: "ping",
ReqID: reqID,
})
case <-cancelableCtx.Done():
return
}
}
}()
log.Printf("Connection successful")
for {
var req WebsocketRequest[json.RawMessage]
err = wsjson.Read(ctx, c, &req)
if err != nil {
return fmt.Errorf("failed to read request: %w", err)
}
log.Printf("Received command %s/%d", req.Command, req.ReqID)
resp, err := handleCommand(ctx, req)
if err != nil {
log.Printf("Command %s/%d failed: %v", req.Command, req.ReqID, err)
resp = ErrorResponse{Error: err.Error()}
} else if resp == nil {
continue
} else {
log.Printf("Command %s/%d succeeded", req.Command, req.ReqID)
}
err = wsjson.Write(ctx, c, WebsocketRequest[any]{
Command: "response",
ReqID: req.ReqID,
Data: resp,
})
if err != nil {
return fmt.Errorf("failed to write response to %d: %w", req.ReqID, err)
}
}
}