-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
483 lines (425 loc) · 13.3 KB
/
common.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package cmd
import (
"errors"
"regexp"
"strings"
"github.com/99designs/keyring"
"github.com/AlecAivazis/survey/v2"
"github.com/brawaru/marct/launcher"
"github.com/brawaru/marct/launcher/accounts"
"github.com/brawaru/marct/locales"
minecraftAccount "github.com/brawaru/marct/minecraft/account"
"github.com/brawaru/marct/utils/slices"
"github.com/brawaru/marct/xbox"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/urfave/cli/v2"
)
type ctxKey string
const (
accountsStoreKey ctxKey = "accounts"
instanceKey ctxKey = "instance"
workDirKey ctxKey = "workDir"
)
func keyringOpenPrompt(req string) (resp string, err error) {
// FIXME: translate request
err = survey.AskOne(&survey.Password{
Message: locales.Translate(&i18n.Message{
ID: "cli.prompts.open-keyring-password.message",
Other: "Enter password to unlock keyring",
}),
Help: locales.Translate(&i18n.Message{
ID: "cli.prompts.open-keyring-password.help",
Other: "Keyring is a secure storage in your system to store important credentials.\n" +
"We use it to store your Microsoft account keys since they cannot be stored in regular files.",
}),
}, &resp)
return
}
func keyringBackendSelectPrompt(backends []keyring.BackendType) (resp keyring.BackendType, err error) {
var options []string
optionsMappings := make(map[string]keyring.BackendType)
for _, b := range backends {
option := string(b)
switch b {
case keyring.FileBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.file",
Other: "File",
})
case keyring.WinCredBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.wincred",
Other: "Windows Credential Manager",
})
case keyring.KWalletBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.kwallet",
Other: "KWallet",
})
case keyring.SecretServiceBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.secretservice",
Other: "Secret Service",
})
case keyring.InvalidBackend:
continue
case keyring.KeyCtlBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.keyctl",
Other: "Keyctl",
})
case keyring.KeychainBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.keychain",
Other: "Keychain",
})
case keyring.PassBackend:
option = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.pass",
Other: "Pass",
})
}
options = append(options, option)
optionsMappings[option] = b
}
var selection string
err = survey.AskOne(&survey.Select{
Message: locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.message",
Other: "Select credentials storage",
}),
Default: options[0],
Options: options,
Help: locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.help",
Other: "Select the keyring backend to use for storing your credentials.\n" +
"If you don't know which one to use, use the default one.",
}),
}, &selection, survey.WithValidator(func(answer interface{}) error {
i, ok := answer.(survey.OptionAnswer)
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.error.survey-validation-invalid-type",
Other: "Invalid response type.",
}))
}
_, ok = optionsMappings[i.Value]
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-keyring-backend.error.survey-validation-invalid-option",
Other: "Invalid option.",
}))
}
return nil
}))
resp = optionsMappings[selection]
return
}
// keyringOpenFlow provides a standard CLI flow for opening a keyring.
// It accepts launcher instance as an argument which it uses to open settings
// and read existing backend preference, or, if it's not set, ask the user to
// select one of the available backends and then saves the settings.
// It returns the selected backend or an error if something went wrong.
// Error will be wrapped as a cli.ExitCoder, so there's no need to handle it.
func keyringOpenFlow(instance *launcher.Instance) (keyring.Keyring, error) {
s, err := instance.OpenSettings()
if err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]any{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.flows.open-keyring.error.open-settings",
Other: "Cannot read your settings: {{ .Error }}",
},
}), 1)
}
var bt keyring.BackendType
if s.Keyring.Backend == nil || !slices.Includes(keyring.AvailableBackends(), *s.Keyring.Backend) {
bt, err = launcher.SelectKeyringBackend(keyringBackendSelectPrompt)
if err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]any{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.flows.open-keyring.error.select-backend",
Other: "Cannot select keyring backend: {{ .Error }}",
},
}), 1)
}
s.Keyring.Backend = &bt
if err := s.Save(); err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]any{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.flows.open-keyring.error.save-settings",
Other: "Cannot save your preference: {{ .Error }}",
},
}), 1)
}
} else {
bt = *s.Keyring.Backend
}
k, err := instance.OpenKeyring(launcher.KeyringOpenOptions{
PromptFunc: keyringOpenPrompt,
Backend: bt,
PassCmd: s.Keyring.PassCmd,
PassDir: s.Keyring.PassDir,
})
if err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.flows.open-keyring.error.open-keyring",
Other: "Cannot open your keyring: {{ .Error }}",
},
}), 1)
}
return k, nil
}
func xboxDeviceAuthPrompt(devAuth xbox.DeviceAuthResponse) error {
println(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Link": devAuth.VerificationURI,
"Code": devAuth.UserCode,
},
// this is the exact thing Microsoft sends, but made into a translatable string by us
DefaultMessage: &i18n.Message{
ID: "cli.prompts.xbox-login-how-to",
Other: "To sign in, use a web browser to open the page {{ .Link }} and enter the code {{ .Code }} to authenticate.",
},
}))
return nil
}
func SelectAccountFlow(accounts map[string]*accounts.Account) (*accounts.Account, error) {
var options []string
optionsMappings := make(map[string]string)
for accountID, account := range accounts {
option := ""
properties, err := minecraftAccount.ReadProperties(account)
if err != nil {
option = locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"ID": accountID,
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-account.unknown-account",
Other: "Unknown account ({{ .ID }})",
},
})
} else {
option = properties.Username
}
options = append(options, option)
optionsMappings[option] = accountID
}
var selectedOption string
if err := survey.AskOne(&survey.Select{
Message: locales.Translate(&i18n.Message{
ID: "cli.prompts.select-account.prompt",
Other: "Select account to launch:",
}),
Options: options,
}, &selectedOption, survey.WithValidator(func(ans interface{}) error {
i, ok := ans.(survey.OptionAnswer)
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-account.error.survey-validation-invalid-type",
Other: "Invalid response type.",
}))
}
_, ok = optionsMappings[i.Value]
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-account.error.invalid-selection",
Other: "Invalid selection. Please select one of the options.",
}))
}
return nil
})); err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-account.error.account-select-failed",
Other: "Failed to read your selection: {{ .Error }}",
},
}), 1)
}
return accounts[optionsMappings[selectedOption]], nil
}
type selectProfileFlowOptions struct {
SkipSelected bool // Whether to skip the selected account.
Message *string // Message to display. If empty, the default "Select profile" message will be used.
}
type SelectProfileFlowOption func(*selectProfileFlowOptions)
func WithoutSelected() SelectProfileFlowOption {
return func(o *selectProfileFlowOptions) {
o.SkipSelected = true
}
}
func WithMessage(v string) SelectProfileFlowOption {
return func(o *selectProfileFlowOptions) {
o.Message = &v
}
}
func SelectProfileFlow(p *launcher.Profiles, options ...SelectProfileFlowOption) (*launcher.Profile, error) {
var o selectProfileFlowOptions
for _, opt := range options {
opt(&o)
}
if p == nil || len(p.Profiles) == 0 {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Command": strings.Join([]string{
app.Name,
profileCommand.Name,
profileCreateCommand.Name,
}, " "),
},
DefaultMessage: &i18n.Message{
ID: "cli.flows.select-profile.error.no-profiles",
Other: "No profiles found. Create your first profile using `{{ .Command }}`.",
},
}), 1)
}
if !o.SkipSelected && p.SelectedProfile != nil {
p, ok := p.Profiles[*p.SelectedProfile]
if ok {
return &p, nil
}
}
var selection string
var variants []string
variantMappings := make(map[string]string)
for i, v := range p.Profiles {
name := v.Name
if name == "" {
name = locales.Translate(&i18n.Message{
ID: "cli.prompts.select-profile.unnamed",
Other: "Unnamed profile",
})
}
option := locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Name": name,
"Version": v.LastVersionID,
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-profile.option",
Other: "{{ .Name }} ({{ .Version }})",
},
})
variants = append(variants, option)
variantMappings[option] = i
}
var msg string
if o.Message != nil {
msg = *o.Message
} else {
msg = locales.TranslateUsing(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-profile.message",
Other: "Select profile",
},
})
}
err := survey.AskOne(&survey.Select{
Message: msg,
Options: variants,
}, &selection, survey.WithValidator(func(ans interface{}) error {
i, ok := ans.(survey.OptionAnswer)
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-profile.error.invalid-type",
Other: "Invalid answer type",
}))
}
_, ok = variantMappings[i.Value]
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.select-profile.error.invalid-option",
Other: "Invalid option",
}))
}
return nil
}))
if err != nil {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-profile.error.survey-failed",
Other: "Cannot read your answer: {{ .Error }}",
},
}), 1)
}
s, ok := p.Profiles[variantMappings[selection]]
if !ok {
return nil, cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Selection": selection,
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.select-profile.error.invalid-selection",
Other: "Invalid selection: {{ .Selection }}",
},
}), 1)
}
return &s, nil
}
// Regular Expression for checking the valid Minecraft username.
//
// Current rules for usernames are (as per https://help.minecraft.net/hc/en-us/articles/4408950195341):
// - must have 3-16 characters
// - must not have spaces
// - A-Z, a-z, 0-9
// - the only allowed special character is _
var minecraftUsernameRegex = regexp.MustCompile(`^[a-zA-Z0-9_]{3,16}$`)
func offlineUsernamePrompt() (string, error) {
var username string
err := survey.AskOne(&survey.Input{
Message: locales.Translate(&i18n.Message{
ID: "cli.prompts.offline-username",
Other: "Username",
}),
Help: locales.Translate(&i18n.Message{
ID: "cli.prompts.offline-username.help",
Other: "Enter your username to use for offline account.",
}),
}, &username, survey.WithValidator(func(ans interface{}) error {
i, ok := ans.(string)
if !ok {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.offline-username.error.invalid-type",
Other: "Invalid answer type",
}))
}
if !minecraftUsernameRegex.MatchString(i) {
return errors.New(locales.Translate(&i18n.Message{
ID: "cli.prompts.offline-username.error.invalid-format",
Other: "Invalid username",
}))
}
return nil
}))
if err != nil {
return "", cli.Exit(locales.TranslateUsing(&i18n.LocalizeConfig{
TemplateData: map[string]string{
"Error": err.Error(),
},
DefaultMessage: &i18n.Message{
ID: "cli.prompts.offline-username.error.survey-failed",
Other: "Cannot read your answer: {{ .Error }}",
},
}), 1)
}
return username, nil
}