-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
537 lines (439 loc) · 10.9 KB
/
main.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path"
"sort"
"strings"
"time"
aw "github.com/deanishe/awgo"
"github.com/hazcod/enpass-cli/pkg/enpass"
"github.com/pquerna/otp/totp"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
"github.com/v-braun/alfred-enpass/imgcache"
"github.com/zalando/go-keyring"
)
type SetupMode = string
const SetupModeDbPath SetupMode = "dbpath"
const SetupModeDbPassword SetupMode = "password"
const SetupModeCommit SetupMode = "commit"
// const SetupModeCommitDbPath SetupMode = "commitdbpath"
// const SetupModeCommitDbPassword SetupMode = "commitpassword"
type WorkflowExecCtx struct {
SetupMode SetupMode `env:"setupMode"`
EnpassFile string `env:"enpassFile"`
TmpEnpassPass string `env:"enpassPass"`
PickedRootItem string `env:"pickedRootItem"`
imgCacheRepo *imgcache.ImageCacheRepo
}
type EnPassEntry struct {
id string
cards []enpass.Card
title string
ico string
}
var (
wf *aw.Workflow
setKey, getKey string
)
func init() {
wf = aw.New()
// flag.StringVar(&setKey, "set", "", "save a value")
// flag.StringVar(&getKey, "get", "", "enter a new value")
}
func appendFile(filename, text string) {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(text); err != nil {
panic(err)
}
}
func run() {
wf.Args()
flag.Parse()
log.Println("start app")
// appendFile("/Users/vbr/tmp/alfred-test/tmp.log", fmt.Sprintf("start pid: %d", os.Getegid()))
// time.Sleep(time.Second * 60)
// Default configuration
ctx := &WorkflowExecCtx{
SetupMode: "",
EnpassFile: "",
TmpEnpassPass: "",
PickedRootItem: "",
imgCacheRepo: imgcache.NewRepo(wf),
}
// Update config from environment variables
if err := wf.Config.To(ctx); err != nil {
panic(err)
}
// ----------------------------------------------------------------
// Parse command-line flags and decide what to do
if handleUpdateCache(ctx) {
return
}
defer func() {
ctx.imgCacheRepo.StoreIndexFile()
}()
if handleSetupDbPath(ctx) {
return
}
if handleSetupDbPass(ctx) {
return
}
if handleSetupComplete(ctx) {
return
}
if handleNeedSetup(ctx) {
return
}
if handleSearchEntries(ctx) {
defer func() {
startBgCmd(wf)
}()
return
}
if handleSearchWithinEntry(ctx) {
return
}
wf.WarnEmpty("No Matching Items", "Try a different query?")
wf.SendFeedback()
}
func main() {
wf.Run(run)
}
func handleNeedSetup(ctx *WorkflowExecCtx) bool {
setupAndSendItem := func() bool {
wf.NewItem("Setup Workflow").
Subtitle("↩ to start setup").
Valid(true).
Var("setupMode", SetupModeDbPath)
return sendFeedbackAndEnd()
}
pass, err := keyring.Get("alfred-enpass", "enpass")
if err != nil {
log.Println("ERR", "get keyring pass", err.Error())
return setupAndSendItem()
}
if pass == "" {
log.Println("WARN", "pass not found in keyring")
return setupAndSendItem()
}
if ctx.EnpassFile == "" {
log.Println("WARN", "enpass file not known")
return setupAndSendItem()
}
vault := openAndAuthVault(ctx)
if vault == nil {
return setupAndSendItem()
} else {
vault.Close()
}
return false
}
func openAndAuthVault(ctx *WorkflowExecCtx) *enpass.Vault {
vault, err := enpass.NewVault(ctx.EnpassFile, logrus.DebugLevel)
if err != nil {
log.Println("ERR", "could not open enpass vault", err.Error())
return nil
}
pass, err := keyring.Get("alfred-enpass", "enpass")
if err != nil {
log.Println("ERR", "get keyring pass", err.Error())
return nil
}
err = vault.Open(&enpass.VaultCredentials{Password: pass})
if err != nil {
log.Println("ERR", "could not decrypt enpass vault", err.Error())
return nil
}
return vault
}
func sendFeedbackAndEnd() bool {
wf.SendFeedback()
return true
}
func handleSearchWithinEntry(ctx *WorkflowExecCtx) bool {
if ctx.PickedRootItem == "" {
return false
}
entries, err := getEntries(ctx)
if err != nil {
wf.NewItem(err.Error()).
Subtitle("please check logs in alfred").
Valid(false)
return sendFeedbackAndEnd()
}
entry, _ := lo.Find(entries, func(t *EnPassEntry) bool {
return t.id == ctx.PickedRootItem
})
if entry == nil {
return true
}
for _, row := range entry.cards {
if row.Category == "section" {
continue
}
if row.RawValue == "" {
continue
}
beautyType := beautyfiyType(row.Type)
typeIco := typeIco(row.Type)
title := strings.Trim(row.Label, " ")
if title == "" {
title = beautyType
}
rowValue := row.RawValue
subTitle := row.Type
if !row.Sensitive {
subTitle = fmt.Sprintf("%s", row.RawValue)
} else {
subTitle = fmt.Sprintf("%s", "***********")
rowValue, err = row.Decrypt()
if err != nil {
log.Println("ERR fail decrypt sensetive data", err.Error())
rowValue = row.RawValue
}
}
if row.Type == "totp" {
totpInput := strings.ReplaceAll(row.RawValue, " ", "")
code, _ := totp.GenerateCode(totpInput, time.Now())
rowValue = code
if code != "" && len(code) >= 6 {
subTitle = fmt.Sprintf("%s %s", code[0:3], code[3:])
}
}
wf.NewItem(fmt.Sprintf("%s", title)).
Subtitle(fmt.Sprintf("%s", subTitle)).
Icon(&aw.Icon{
Value: typeIco,
Type: aw.IconTypeImage,
}).
Var("clipVal", rowValue).
Var("pickedRootItem", "").
Valid(true)
}
query := flag.Arg(0)
if query != "" {
wf.Filter(query)
}
wf.SendFeedback()
return sendFeedbackAndEnd()
}
func beautyfiyType(t string) string {
if t == "username" {
return "Username"
}
if t == "email" {
return "E-Mail"
}
if t == "totp" {
return "One-time code"
}
if t == "url" {
return "Website"
}
if t == "password" {
return "Password"
}
if t == "text" {
return "Text"
}
return t
}
func typeIco(t string) string {
if t == "username" {
return path.Join(wf.Data.Dir, "user.png")
}
if t == "email" {
return path.Join(wf.Data.Dir, "mail.png")
}
if t == "totp" {
return path.Join(wf.Data.Dir, "totp.png")
}
if t == "url" {
return path.Join(wf.Data.Dir, "url.png")
}
if t == "password" {
return path.Join(wf.Data.Dir, "pass.png")
}
if t == "text" {
return path.Join(wf.Data.Dir, "unknown.png")
}
return path.Join(wf.Data.Dir, "unknown.png")
}
func handleSearchEntries(ctx *WorkflowExecCtx) bool {
if ctx.PickedRootItem != "" {
return false
}
entries, err := getEntries(ctx)
if err != nil {
wf.NewItem(err.Error()).
Subtitle("please check logs in alfred").
Valid(false)
return sendFeedbackAndEnd()
}
for _, entry := range entries {
matches := []string{strings.Trim(entry.title, " ")}
for _, card := range entry.cards {
matches = append(matches, strings.Trim(card.Label, " "))
}
ctx.imgCacheRepo.SetFavFor(entry.id, entry.ico)
icoFilePath := ctx.imgCacheRepo.GetImagePath(entry.id)
if icoFilePath == "" {
icoFilePath = typeIco("")
}
wf.NewItem(fmt.Sprintf("%s", entry.title)).
Subtitle(fmt.Sprintf("%d items", len(entry.cards))).
// Match(strings.Join(matches, " ")).
Icon(&aw.Icon{
Value: icoFilePath,
Type: aw.IconTypeImage,
}).
Var("pickedRootItem", entry.id).
Valid(true)
}
query := flag.Arg(0)
if query != "" {
wf.Filter(query)
}
wf.SendFeedback()
return true
}
func handleUpdateCache(ctx *WorkflowExecCtx) bool {
if flag.Arg(0) != "update-cache" {
return false
}
fmt.Println("INFO", "begin update cache")
ctx.imgCacheRepo.CacheImages()
return true
}
func startBgCmd(wf *aw.Workflow) {
programm, err := os.Executable()
log.Println("INFO", "triggering BG img caching", programm)
if err != nil {
log.Println("ERR", "could not get executable", err.Error())
return
}
err = wf.RunInBackground("CACHE_IMAGES", exec.Command(programm, "update-cache"))
if err != nil {
log.Println("ERR", "could not start BG process", err.Error())
}
log.Println("INFO", "BG image caching triggered")
}
func handleSetupDbPath(ctx *WorkflowExecCtx) bool {
if ctx.SetupMode != SetupModeDbPath {
return false
}
query := flag.Arg(0)
if query == "" {
wf.NewItem("Please enter the db file path").
Valid(false)
return sendFeedbackAndEnd()
}
home, _ := os.UserHomeDir()
if home != "" {
query = strings.ReplaceAll(query, "~", home)
}
// ~/Library/Containers/in.sinew.Enpass-Desktop/Data/Documents/Vaults/primary
_, err := enpass.NewVault(query, logrus.TraceLevel)
if err != nil {
wf.NewItem(fmt.Sprintf("Invalid file: %s", err.Error())).
Valid(false)
return sendFeedbackAndEnd()
}
wf.NewItem("Accept path").
Subtitle("↩ to accept").
Var("enpassFile", query).
Var("setupMode", SetupModeDbPassword).
Valid(true)
return sendFeedbackAndEnd()
}
func handleSetupDbPass(ctx *WorkflowExecCtx) bool {
if ctx.SetupMode != SetupModeDbPassword {
return false
}
query := flag.Arg(0)
if query == "" {
wf.NewItem("Please enter the db password").
Valid(false)
return sendFeedbackAndEnd()
}
log.Println("INFO", "open vault", ctx.EnpassFile)
vault, err := enpass.NewVault(ctx.EnpassFile, logrus.TraceLevel)
if err != nil {
wf.NewItem(fmt.Sprintf("Invalid file: %s", err.Error())).
Valid(false)
return sendFeedbackAndEnd()
}
err = vault.Open(&enpass.VaultCredentials{
Password: query,
})
if err != nil {
log.Printf("could not open db %v\n", err)
wf.NewItem("Could not unlock vault, invalid password?").
Subtitle(fmt.Sprintf("ERR %s", err.Error())).
Valid(false)
return sendFeedbackAndEnd()
}
wf.NewItem("Accept password (will be stored in keychain)").
Subtitle("↩ to accept").
Var("enpassPass", query).
Var("enpassFile", ctx.EnpassFile).
Var("setupMode", SetupModeCommit).
Valid(true)
return sendFeedbackAndEnd()
}
func handleSetupComplete(ctx *WorkflowExecCtx) bool {
if ctx.SetupMode != SetupModeCommit {
return false
}
err := keyring.Set("alfred-enpass", "enpass", ctx.TmpEnpassPass)
if err != nil {
log.Println("ERR", "store data in keychain", err)
return sendFeedbackAndEnd()
}
if err := wf.Config.Set("enpassFile", ctx.EnpassFile, false).Do(); err != nil {
log.Println("ERR", "store data in keychain", err)
return sendFeedbackAndEnd()
}
return sendFeedbackAndEnd()
}
func getEntries(ctx *WorkflowExecCtx) ([]*EnPassEntry, error) {
vault := openAndAuthVault(ctx)
if vault == nil {
return []*EnPassEntry{}, errors.New("Error accessing vault")
}
cards, err := vault.GetEntries("", []string{})
if err != nil {
log.Println("ERR", "error vault.getEntries: %s", err.Error())
return []*EnPassEntry{}, errors.New("Error accessing vault")
}
cards = lo.Filter(cards, func(card enpass.Card, i int) bool {
return !card.IsDeleted() && !card.IsTrashed()
})
cardMap := lo.GroupBy(cards, func(t enpass.Card) string {
return t.UUID
})
entries := make([]*EnPassEntry, 0)
for k, secrets := range cardMap {
first := secrets[0]
entries = append(entries, &EnPassEntry{
id: k,
cards: secrets,
title: first.Title,
ico: first.Icon,
})
}
sort.SliceStable(entries, func(i, j int) bool {
return strings.ToLower(entries[i].title) < strings.ToLower(entries[j].title)
})
return entries, nil
}