forked from robertknight/1pass
/
client.go
1445 lines (1295 loc) · 35.5 KB
/
client.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"syscall"
"time"
"code.google.com/p/go.crypto/ssh/terminal"
"github.com/robertknight/1pass/cmdmodes"
"github.com/robertknight/1pass/jsonutil"
"github.com/robertknight/1pass/onepass"
"github.com/robertknight/1pass/rangeutil"
"github.com/robertknight/clipboard"
)
var commandModes = []cmdmodes.Mode{
{
Command: "new",
Description: "Create a new vault",
ArgNames: []string{"[path]"},
},
{
Command: "gen-password",
Description: "Generate a new random password",
},
{
Command: "set-vault",
Description: "Set the path to the 1Password vault",
ArgNames: []string{"[path]"},
},
{
Command: "info",
Description: "Display info about the current vault",
},
{
Command: "list",
Description: "List items in the vault",
ArgNames: []string{"[pattern]"},
ExtraHelp: listHelp,
},
{
Command: "list-folder",
Description: "List items in a folder",
ArgNames: []string{"pattern"},
},
{
Command: "list-tag",
Description: "List items with a given tag",
ArgNames: []string{"tag"},
},
{
Command: "list-tags",
Description: "List all tags",
},
{
Command: "show-json",
Description: "Show the raw decrypted JSON for the given item",
ArgNames: []string{"pattern"},
},
{
Command: "show",
Description: "Display the details of the given item",
ArgNames: []string{"pattern"},
},
{
Command: "add",
Description: "Add a new item to the vault",
ArgNames: []string{"type", "title"},
ExtraHelp: itemTypesHelp,
},
{
Command: "edit",
Description: "Edit an existing item",
ArgNames: []string{"pattern"},
},
{
Command: "move",
Description: "Move items to a folder",
ArgNames: []string{"item-pattern", "[folder-pattern]"},
},
{
Command: "remove",
Description: "Remove items from the vault matching the given pattern",
ArgNames: []string{"pattern"},
},
{
Command: "trash",
Description: "Move items to the trash",
ArgNames: []string{"pattern"},
},
{
Command: "restore",
Description: "Restore items from the trash",
ArgNames: []string{"pattern"},
},
{
Command: "rename",
Description: "Renames an item in the vault",
ArgNames: []string{"pattern", "new-title"},
},
{
Command: "copy",
Description: "Copy information from the given item to the clipboard",
ArgNames: []string{"pattern", "[field]"},
ExtraHelp: copyItemHelp,
},
{
Command: "export",
Description: "Export item to an unencrypted '1Password Interchange Format' directory",
ArgNames: []string{"pattern", "path"},
},
{
Command: "import",
Description: "Import an item from an unencrypted '1Password Interchange Format' file or directory",
ArgNames: []string{"path"},
},
{
Command: "set-password",
Description: "Change the master password for the vault",
ExtraHelp: setPasswordHelp,
},
{
Command: "help",
Description: "Display usage information",
},
{
Command: "export-item-templates",
Description: "Create item templates from items matching the given pattern",
ArgNames: []string{"pattern"},
Internal: true,
},
{
Command: "add-tag",
Description: "Add a tag to an item",
ArgNames: []string{"pattern", "tag"},
},
{
Command: "remove-tag",
Description: "Remove tags from an item",
ArgNames: []string{"pattern", "tag"},
},
}
type clientConfig struct {
VaultDir string
}
var configPath = os.Getenv("HOME") + "/.1pass"
// displays a prompt and reads a line of input
func readLinePrompt(prompt string, args ...interface{}) string {
fmt.Printf(fmt.Sprintf("%s: ", prompt), args...)
return readLine()
}
// reads a line of input from stdin
func readLine() string {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
return scanner.Text()
}
func readConfig() clientConfig {
var config clientConfig
_ = jsonutil.ReadFile(configPath, &config)
return config
}
func writeConfig(config *clientConfig) {
_ = jsonutil.WriteFile(configPath, config)
}
func logItemAction(action string, item onepass.Item) {
fmt.Printf("%s '%s' (%s)\n", action, item.Title, item.Uuid[0:4])
}
// generate a random password with default settings
// for length and characters
func genDefaultPassword() string {
return onepass.GenPassword(12)
}
// attempt to locate the keychain directory automatically
func findKeyChainDirs() []string {
paths := []string{}
// try using 'locate'
locateCmd := exec.Command("locate", "-b", "--existing", ".agilekeychain")
locateOutput, err := locateCmd.Output()
if err == nil {
locateLines := strings.Split(string(locateOutput), "\n")
for _, path := range locateLines {
err = onepass.CheckVault(path)
if err == nil {
paths = append(paths, path)
}
}
}
// try default paths
defaultPaths := []string{
os.Getenv("HOME") + "/Dropbox/1Password/1Password.agilekeychain",
}
for _, defaultPath := range defaultPaths {
ok := rangeutil.Contains(0, len(paths), func(i int) bool {
return paths[i] == defaultPath
})
if !ok {
err = onepass.CheckVault(defaultPath)
if err == nil {
paths = append(paths, defaultPath)
}
}
}
return paths
}
func listMatchingItems(vault *onepass.Vault, pattern string) {
var items []onepass.Item
var err error
if len(pattern) > 0 {
items, err = lookupItems(vault, pattern)
} else {
items, err = vault.ListItems()
}
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to list vault items: %v\n", err)
os.Exit(1)
}
listItems(vault, items)
}
func listItems(vault *onepass.Vault, items []onepass.Item) {
rangeutil.Sort(0, len(items), func(i, k int) bool {
return strings.ToLower(items[i].Title) < strings.ToLower(items[k].Title)
},
func(i, k int) {
items[i], items[k] = items[k], items[i]
})
for _, item := range items {
trashState := ""
if item.Trashed {
trashState = " (in trash)"
}
fmt.Printf("%s (%s, %s)%s\n", item.Title, item.Type(), item.Uuid[0:4], trashState)
}
}
func listFolder(vault *onepass.Vault, pattern string) {
pattern = "folder:" + pattern
folder, err := lookupSingleItem(vault, pattern)
if err != nil {
fatalErr(err, "Failed to find folder")
}
items, err := vault.ListItems()
if err != nil {
fatalErr(err, "Failed to list items")
}
itemsInFolder := []onepass.Item{}
for _, item := range items {
if item.FolderUuid == folder.Uuid {
itemsInFolder = append(itemsInFolder, item)
}
}
listItems(vault, itemsInFolder)
}
func prettyJson(src []byte) []byte {
var buffer bytes.Buffer
json.Indent(&buffer, src, "", " ")
return buffer.Bytes()
}
func showItems(vault *onepass.Vault, pattern string, asJson bool) {
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items")
}
if len(items) == 0 {
fmt.Fprintf(os.Stderr, "No matching items\n")
}
for i, item := range items {
if i > 0 {
fmt.Println()
}
if asJson {
showItemJson(item)
} else {
showItem(vault, item)
}
}
}
func showItem(vault *onepass.Vault, item onepass.Item) {
typeName := item.TypeName
itemType, ok := onepass.ItemTypes[item.TypeName]
if ok {
typeName = itemType.Name
}
fmt.Printf("%s (%s)\n", item.Title, typeName)
fmt.Printf("Info:\n")
fmt.Printf(" ID: %s\n", item.Uuid)
updateTime := int64(item.UpdatedAt)
if updateTime == 0 {
updateTime = int64(item.CreatedAt)
}
fmt.Printf(" Updated: %s\n", time.Unix(updateTime, 0).Format("15:04 02/01/06"))
if len(item.FolderUuid) > 0 {
folder, err := vault.LoadItem(item.FolderUuid)
if err != nil {
fmt.Fprintf(os.Stderr, "Item folder '%s' not found", item.FolderUuid)
// continue
}
fmt.Printf(" Folder: %s\n", folder.Title)
}
if len(item.OpenContents.Tags) > 0 {
fmt.Printf(" Tags: %s\n", strings.Join(item.OpenContents.Tags, ", "))
}
fmt.Println()
content, err := item.Content()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to decrypt item: %s: %v", item.Title, err)
return
}
fmt.Printf(content.String())
}
func showItemJson(item onepass.Item) {
fmt.Printf("%s: %s: %s\n", item.Title, item.Uuid, item.ContentsHash)
decrypted, err := item.ContentJson()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to decrypt item: %s: %v", item.Title, err)
return
}
fmt.Println(string(prettyJson([]byte(decrypted))))
}
func readFieldValue(field onepass.ItemField) interface{} {
var newValue interface{}
for newValue == nil {
var valueStr string
if field.Kind == "concealed" {
valueStr, _ = readNewPassword(field.Title)
} else if field.Kind == "address" {
newValue = onepass.ItemAddress{
Street: readLinePrompt("Street"),
City: readLinePrompt("City"),
Zip: readLinePrompt("Zip"),
State: readLinePrompt("State"),
Country: readLinePrompt("Country"),
}
} else {
valueStr = readLinePrompt("%s (%s)", field.Title, field.Kind)
}
if len(valueStr) == 0 {
break
}
if newValue == nil {
var err error
newValue, err = onepass.FieldValueFromString(field.Kind, valueStr)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
}
}
return newValue
}
func readFormFieldValue(field onepass.WebFormField) string {
var newValue string
if field.Type == "P" {
for {
var err error
newValue, err = readNewPassword(field.Name)
if err == nil {
break
}
}
} else {
newValue = readLinePrompt("%s (%s)", field.Name, field.Type)
}
return newValue
}
func addItem(vault *onepass.Vault, title string, shortTypeName string) {
itemContent := onepass.ItemContent{}
var typeName string
for typeKey, itemType := range onepass.ItemTypes {
if itemType.ShortAlias == shortTypeName {
itemContent = onepass.ItemContent{}
typeName = typeKey
}
}
if len(typeName) == 0 {
fatalErr(fmt.Errorf("Unknown item type '%s'", shortTypeName), "")
}
template, ok := onepass.StandardTemplate(typeName)
if !ok {
fatalErr(fmt.Errorf("No template for item type '%s'", shortTypeName), "")
}
// read sections
for _, sectionTemplate := range template.Sections {
section := onepass.ItemSection{
Name: sectionTemplate.Name,
Title: sectionTemplate.Title,
Fields: []onepass.ItemField{},
}
for _, fieldTemplate := range sectionTemplate.Fields {
field := onepass.ItemField{
Name: fieldTemplate.Name,
Title: fieldTemplate.Title,
Kind: fieldTemplate.Kind,
}
field.Value = readFieldValue(field)
section.Fields = append(section.Fields, field)
}
itemContent.Sections = append(itemContent.Sections, section)
}
// read form fields
for _, formFieldTemplate := range template.FormFields {
field := onepass.WebFormField{
Name: formFieldTemplate.Name,
Id: formFieldTemplate.Id,
Type: formFieldTemplate.Type,
Designation: formFieldTemplate.Designation,
}
field.Value = readFormFieldValue(field)
itemContent.FormFields = append(itemContent.FormFields, field)
}
// read URLs
for _, urlTemplate := range template.Urls {
url := onepass.ItemUrl{
Label: urlTemplate.Label,
}
url.Url = readLinePrompt("%s (URL)", url.Label)
itemContent.Urls = append(itemContent.Urls, url)
}
// save item to vault
item, err := vault.AddItem(title, typeName, itemContent)
if err != nil {
fatalErr(err, "Unable to add item")
}
logItemAction("Added new item", item)
}
func editItem(vault *onepass.Vault, pattern string) {
item, err := lookupSingleItem(vault, pattern)
if err != nil {
fatalErr(err, "Failed to find item")
}
logItemAction("Editing item", item)
content, err := item.Content()
if err != nil {
fatalErr(err, "Unable to read item content")
}
formSectionId := len(content.Sections) + 1
urlSectionId := len(content.Sections) + 2
for i, section := range content.Sections {
fmt.Printf("%d : %s\n", i+1, section.Title)
}
fmt.Printf("%d : Web Form fields\n", formSectionId)
fmt.Printf("%d : URLs\n", urlSectionId)
var section *onepass.ItemSection
var field *onepass.ItemField
sectionIdStr := readLinePrompt("Section (or title of new section)")
sectionId, err := strconv.Atoi(sectionIdStr)
if err != nil {
// new section
content.Sections = append(content.Sections, onepass.ItemSection{
Name: sectionIdStr,
Title: sectionIdStr,
Fields: []onepass.ItemField{},
})
section = &content.Sections[len(content.Sections)-1]
} else if sectionId > 0 && sectionId <= len(content.Sections) {
section = &content.Sections[sectionId-1]
} else if sectionId != formSectionId && sectionId != urlSectionId {
fatalErr(nil, "Unknown section number")
}
if section != nil {
for i, field := range section.Fields {
fmt.Printf("%d : %s (%s)\n", i+1, field.Title, field.ValueString())
}
fieldIdStr := readLinePrompt("Field (or title of new field)")
fieldId, err := strconv.Atoi(fieldIdStr)
if err != nil {
// new field
section.Fields = append(section.Fields, onepass.ItemField{
Name: fieldIdStr,
Kind: "string",
Title: fieldIdStr,
})
field = §ion.Fields[len(section.Fields)-1]
} else if fieldId > 0 && fieldId <= len(section.Fields) {
field = §ion.Fields[fieldId-1]
} else {
fatalErr(nil, "Unknown field number")
}
field.Value = readFieldValue(*field)
} else if sectionId == formSectionId {
for i, field := range content.FormFields {
fmt.Printf("%d : %s (%s)\n", i+1, field.Name, field.Value)
}
fieldIdStr := readLinePrompt("Field")
fieldId, err := strconv.Atoi(fieldIdStr)
if err == nil && fieldId > 0 && fieldId <= len(content.FormFields) {
content.FormFields[fieldId-1].Value = readFormFieldValue(content.FormFields[fieldId-1])
} else {
fatalErr(nil, "Unknown field number")
}
} else if sectionId == urlSectionId {
for i, url := range content.Urls {
fmt.Printf("%d : %s (%s)\n", i+1, url.Label, url.Url)
}
var url *onepass.ItemUrl
urlIdStr := readLinePrompt("URL (or label of new URL)")
urlId, err := strconv.Atoi(urlIdStr)
if err != nil {
// new URL
content.Urls = append(content.Urls, onepass.ItemUrl{
Label: urlIdStr,
})
url = &content.Urls[len(content.Urls)-1]
} else if urlId > 0 && urlId <= len(content.Urls) {
url = &content.Urls[urlId-1]
} else {
fatalErr(nil, "Unknown URL number")
}
url.Url = readLinePrompt("%s", url.Label)
}
err = item.SetContent(content)
if err != nil {
fatalErr(err, "Unable to save updated content")
}
err = item.Save()
if err != nil {
fatalErr(err, "Unable to save updated item")
}
}
func listHelp() string {
result := `[pattern] is an optional pattern which can match
part of an item's title, part of an item's ID or the type of item.
You can also specify both an item type and a title/ID pattern
using '<item type>:<pattern>'.
`
result += itemTypesHelp()
return result
}
func itemTypesHelp() string {
typeAliases := map[string]onepass.ItemType{}
sortedAliases := []string{}
for code, itemType := range onepass.ItemTypes {
if code == "system.Tombstone" {
continue
}
typeAliases[itemType.ShortAlias] = itemType
sortedAliases = append(sortedAliases, itemType.ShortAlias)
}
sort.Strings(sortedAliases)
result := "Item Types:\n\n"
for i, alias := range sortedAliases {
if i > 0 {
result += "\n"
}
result = result + fmt.Sprintf(" %s - %s", alias, typeAliases[alias].Name)
}
return result
}
func copyItemHelp() string {
return `[field] specifies a pattern for the name of the field, form field or URL
to copy. If omitted, defaults to 'password'.
[field] patterns are matched against the field names in
the same way that item name patterns are matched against item titles.`
}
// Returns the type code associated with a given alias.
// eg. 'folder' => 'system.Folder'.
// Returns an empty string if the given alias does not
// correspond to any known item type
func typeFromAlias(alias string) string {
for key, itemType := range onepass.ItemTypes {
if itemType.ShortAlias == alias {
return key
}
}
return ""
}
func lookupItems(vault *onepass.Vault, pattern string) ([]onepass.Item, error) {
typeName := typeFromAlias(pattern)
if typeName != "" {
pattern = ""
}
if strings.Contains(pattern, ":") {
parts := strings.SplitN(pattern, ":", 2)
typeName = typeFromAlias(parts[0])
pattern = parts[1]
if typeName == "" {
fatalErr(nil, fmt.Sprintf("Unknown type name '%s'", parts[0]))
}
}
items, err := vault.ListItems()
if err != nil {
return items, err
}
patternLower := strings.ToLower(pattern)
matches := []onepass.Item{}
for _, item := range items {
patternMatch := pattern == ""
typeMatch := typeName == "" || item.TypeName == typeName
if strings.Contains(strings.ToLower(item.Title), patternLower) ||
strings.HasPrefix(strings.ToLower(item.Uuid), patternLower) {
patternMatch = true
}
if patternMatch && typeMatch {
matches = append(matches, item)
}
}
return matches, nil
}
// read a response to a yes/no question from stdin
func readConfirmation() bool {
var response string
count, err := fmt.Scanln(&response)
return err == nil && count > 0 && strings.ToLower(response) == "y"
}
func fatalErr(err error, context string) {
if err == nil {
err = fmt.Errorf("")
}
if context == "" {
fmt.Fprintf(os.Stderr, "%v\n", err)
} else {
fmt.Fprintf(os.Stderr, "%s: %v\n", context, err)
}
os.Exit(1)
}
func readNewPassword(passType string) (string, error) {
fmt.Printf("%s (or '-' for a random new %s): ", passType, passType)
pwd, _ := terminal.ReadPassword(0)
if len(pwd) == 0 {
fmt.Println()
return "", nil
}
if string(pwd) == "-" {
pwd = []byte(genDefaultPassword())
fmt.Printf("(Random new password generated)")
} else {
fmt.Printf("\nRe-enter %s: ", passType)
pwd2, _ := terminal.ReadPassword(0)
if string(pwd) != string(pwd2) {
return "", fmt.Errorf("Passwords do not match")
}
}
fmt.Println()
return string(pwd), nil
}
func createNewVault(path string, lowSecurity bool) {
if !strings.HasSuffix(path, ".agilekeychain") {
path += ".agilekeychain"
}
fmt.Printf("Creating new vault in %s\n", path)
fmt.Printf("Enter master password: ")
masterPwd, err := terminal.ReadPassword(0)
fmt.Printf("\nRe-enter master password: ")
masterPwd2, _ := terminal.ReadPassword(0)
if !bytes.Equal(masterPwd, masterPwd2) {
fatalErr(nil, "Passwords do not match")
}
security := onepass.VaultSecurity{MasterPwd: string(masterPwd)}
if lowSecurity {
// use fewer PBKDF2 iterations to speed up
// master key decryption
security.Iterations = 10
}
_, err = onepass.NewVault(path, security)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create new vault: %v", err)
}
}
func setPassword(vault *onepass.Vault, currentPwd string) {
// TODO - Prompt for hint and save that to the .password.hint file
fmt.Printf("New master password: ")
newPwd, err := terminal.ReadPassword(0)
fmt.Printf("\nRe-enter new master password: ")
newPwd2, err := terminal.ReadPassword(0)
fmt.Println()
if !bytes.Equal(newPwd, newPwd2) {
fatalErr(nil, "Passwords do not match")
}
err = vault.SetMasterPassword(currentPwd, string(newPwd))
if err != nil {
fatalErr(err, "Failed to change master password")
}
fmt.Printf("The master password has been updated.\n\n")
fmt.Printf(setPasswordSyncNote)
}
const setPasswordSyncNote = `Note that after changing the password,
other 1Password apps may still expect the old password until
you unlock the vault with them and your new password is synced.
`
func setPasswordHelp() string {
return setPasswordSyncNote
}
func moveItemsToFolder(vault *onepass.Vault, itemPattern string, folderPattern string) {
items, err := lookupItems(vault, itemPattern)
if err != nil {
fatalErr(err, "Unable to lookup items to move")
}
folderPattern = "folder:" + folderPattern
var folder onepass.Item
if len(folderPattern) > 0 {
folder, err = lookupSingleItem(vault, folderPattern)
}
for _, item := range items {
logItemAction("Moving item", item)
item.FolderUuid = folder.Uuid
err = item.Save()
if err != nil {
fatalErr(err, "Failed to move item to folder")
}
}
}
func removeItems(vault *onepass.Vault, pattern string) {
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items to remove")
}
for _, item := range items {
fmt.Printf("Remove '%s' from vault? This cannot be undone. Y/N\n", item.Title)
if readConfirmation() {
err = item.Remove()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to remove item: %s\n", err)
}
}
}
}
func trashItems(vault *onepass.Vault, pattern string) {
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items to trash")
}
for _, item := range items {
logItemAction("Trashing item", item)
item.Trashed = true
err = item.Save()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to trash item: %s\n", err)
}
}
}
func restoreItems(vault *onepass.Vault, pattern string) {
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items to restore")
}
for _, item := range items {
logItemAction("Restoring item", item)
item.Trashed = false
err = item.Save()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to restore item: %s\n", err)
}
}
}
func lookupSingleItem(vault *onepass.Vault, pattern string) (onepass.Item, error) {
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items")
}
if len(items) == 0 {
return onepass.Item{}, fmt.Errorf("No matching items")
}
if len(items) > 1 {
fmt.Fprintf(os.Stderr, "Multiple matching items:\n")
for _, item := range items {
fmt.Fprintf(os.Stderr, " %s (%s)\n", item.Title, item.Uuid)
}
return onepass.Item{}, fmt.Errorf("Multiple matching items")
}
return items[0], nil
}
func renameItem(vault *onepass.Vault, pattern string, newTitle string) {
item, err := lookupSingleItem(vault, pattern)
if err != nil {
fatalErr(err, "Failed to find item to rename")
}
logItemAction("Renaming item", item)
item.Title = newTitle
err = item.Save()
if err != nil {
fatalErr(err, "Failed to rename item")
}
}
func copyToClipboard(vault *onepass.Vault, pattern string, fieldPattern string) {
item, err := lookupSingleItem(vault, pattern)
if err != nil {
fatalErr(err, "Failed to find item to copy")
}
content, err := item.Content()
if err != nil {
fatalErr(err, fmt.Sprintf("Failed to decrypt item '%s'", item.Title))
}
if fieldPattern == "" {
fieldPattern = "password"
}
fieldTitle := ""
value := ""
field := content.FieldByPattern(fieldPattern)
if field != nil {
fieldTitle = field.Title
value = field.ValueString()
} else {
formField := content.FormFieldByPattern(fieldPattern)
if formField != nil {
fieldTitle = formField.Name
value = formField.Value
} else {
urlField := content.UrlByPattern(fieldPattern)
if urlField != nil {
fieldTitle = urlField.Label
value = urlField.Url
}
}
}
if len(value) == 0 {
fatalErr(fmt.Errorf("onepass.Item has no fields, web form fields or websites matching pattern '%s'\n", fieldPattern), "")
}
err = clipboard.WriteAll(value)
if err != nil {
fatalErr(err, fmt.Sprintf("Failed to copy '%s' field to clipboard", field))
}
fmt.Printf("Copied '%s' to clipboard for item '%s'\n", fieldTitle, item.Title)
}
// create a set of item templates based on existing
// items in a vault
func exportItemTemplates(vault *onepass.Vault, pattern string) {
items, err := vault.ListItems()
if err != nil {
fatalErr(err, "Unable to list vault items")
}
typeTemplates := map[string]onepass.ItemContent{}
for _, item := range items {
typeTemplate := onepass.ItemContent{
Sections: []onepass.ItemSection{},
FormFields: []onepass.WebFormField{},
}
if !strings.HasPrefix(strings.ToLower(item.Title), pattern) {
continue
}
content, err := item.Content()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to decrypt item: %v\n", err)
}
// section templates
for _, section := range content.Sections {
sectionTemplate := onepass.ItemSection{
Name: section.Name,
Title: section.Title,
Fields: []onepass.ItemField{},
}
for _, field := range section.Fields {
fieldTemplate := onepass.ItemField{
Name: field.Name,
Title: field.Title,
Kind: field.Kind,
}
sectionTemplate.Fields = append(sectionTemplate.Fields, fieldTemplate)
}
typeTemplate.Sections = append(typeTemplate.Sections, sectionTemplate)
}
// web form field templates
for _, formField := range content.FormFields {
formTemplate := onepass.WebFormField{
Name: formField.Name,
Id: formField.Id,
Type: formField.Type,
Designation: formField.Designation,
}
typeTemplate.FormFields = append(typeTemplate.FormFields, formTemplate)
}
// URL templates
for _, url := range content.Urls {
urlTemplate := onepass.ItemUrl{Label: url.Label}
typeTemplate.Urls = append(typeTemplate.Urls, urlTemplate)
}
typeTemplates[item.TypeName] = typeTemplate
}
data, err := json.Marshal(typeTemplates)
if err != nil {
fatalErr(err, "Unable to export item templates")
}
_, _ = os.Stdout.Write(prettyJson(data))
}
func exportItems(vault *onepass.Vault, pattern string, path string) {
if !strings.HasSuffix(path, ".1pif") {
path += ".1pif"
}
items, err := lookupItems(vault, pattern)
if err != nil {
fatalErr(err, "Unable to lookup items")
}
for _, item := range items {
logItemAction("Exporting item", item)
}
err = onepass.ExportItems(items, path)
if err != nil {
fatalErr(err, "Unable to export items")
}
}