-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.go
More file actions
409 lines (319 loc) · 9.14 KB
/
utils.go
File metadata and controls
409 lines (319 loc) · 9.14 KB
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
// Utility functions
package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/atotto/clipboard"
"github.com/kirsle/configdir"
"golang.org/x/crypto/ssh/terminal"
"io/fs"
"os"
"path/filepath"
"strings"
)
const DELIMSIZE int = 69
// Over-ride settings via cmd line
type SettingsOverride struct {
ShowPasswords bool
CopyPassword bool
}
// Settings structure for local config
type Settings struct {
ActiveDB string `json:"active_db"`
Cipher string `json:"cipher"`
AutoEncrypt bool `json:"auto_encrypt"`
KeepEncrypted bool `json:"encrypt_on"`
ShowPasswords bool `json:"visible_passwords"`
ConfigPath string `json:"path"`
// Key to order listings when using -a option
// Valid values are
// 1. timestamp,{desc,asc}
// 2. title,{desc,asc}
// 3. username, {desc,asc}
// 4. id, {desc,asc{
ListOrder string `json:"list_order"`
Delim string `json:"delimiter"`
Color string `json:"color"` // fg color to print
BgColor string `json:"bgcolor"` // bg color to print
}
// Global settings override
var settingsRider SettingsOverride
// Write settings to disk
func writeSettings(settings *Settings, configFile string) error {
fh, err := os.Create(configFile)
if err != nil {
fmt.Printf("Error generating configuration file %s - \"%s\"\n", configFile, err.Error())
return err
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.SetIndent("", "\t")
err = encoder.Encode(&settings)
return err
}
// Write updated settings to disk
func updateSettings(settings *Settings, configFile string) error {
fh, err := os.OpenFile(configFile, os.O_RDWR, 0644)
if err != nil {
fmt.Printf("Error opening config file %s - \"%s\"\n", configFile, err.Error())
return err
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.SetIndent("", "\t")
err = encoder.Encode(&settings)
if err != nil {
fmt.Printf("Error updating config %s - \"%s\"\n", configFile, err.Error())
return err
}
return err
}
// Make the per-user configuration folder and return local settings
func getOrCreateLocalConfig(app string) (error, *Settings) {
var settings Settings
var configPath string
var configFile string
var err error
var fh *os.File
configPath = configdir.LocalConfig(app)
err = configdir.MakePath(configPath) // Ensure it exists.
if err != nil {
return err, nil
}
configFile = filepath.Join(configPath, "config.json")
// fmt.Printf("Config file, path => %s %s\n", configFile, configPath)
if _, err = os.Stat(configFile); err == nil {
fh, err = os.Open(configFile)
if err != nil {
return err, nil
}
defer fh.Close()
decoder := json.NewDecoder(fh)
err = decoder.Decode(&settings)
if err != nil {
return err, nil
}
} else {
// fmt.Printf("Creating default configuration ...")
settings = Settings{"", "aes", true, true, false, configFile, "id,asc", "+", "default", "bgblack"}
if err = writeSettings(&settings, configFile); err == nil {
// fmt.Println(" ...done")
} else {
return err, nil
}
}
return nil, &settings
}
// Return if there is an active, decrypted database
func hasActiveDatabase() bool {
err, settings := getOrCreateLocalConfig(APP)
if err == nil && settings.ActiveDB != "" {
if _, err := os.Stat(settings.ActiveDB); err == nil {
if _, flag := isFileEncrypted(settings.ActiveDB); !flag {
return true
}
return false
}
}
if err != nil {
fmt.Printf("Error parsing local config - \"%s\"\n", err.Error())
}
return false
}
// Get the current active database
func getActiveDatabase() (error, string) {
err, settings := getOrCreateLocalConfig(APP)
if err == nil && settings.ActiveDB != "" {
if _, err := os.Stat(settings.ActiveDB); err == nil {
return nil, settings.ActiveDB
}
}
if err != nil {
fmt.Printf("Error parsing local config - \"%s\"\n", err.Error())
}
return err, ""
}
// Update the active db path
func updateActiveDbPath(dbPath string) error {
_, settings := getOrCreateLocalConfig(APP)
if settings != nil {
settings.ActiveDB = dbPath
}
return updateSettings(settings, settings.ConfigPath)
}
// Read the password from console without echoing
func readPassword() (error, string) {
var passwd []byte
var err error
passwd, err = terminal.ReadPassword(int(os.Stdin.Fd()))
return err, string(passwd)
}
// Rewrite the contents of the base file (path minus extension) with the new contents
func rewriteBaseFile(path string, contents []byte, mode fs.FileMode) (error, string) {
var err error
var origFile string
origFile = strings.TrimSuffix(path, filepath.Ext(path))
// Overwrite it
err = os.WriteFile(origFile, contents, 0644)
if err == nil {
// Chmod it
os.Chmod(origFile, mode)
}
return err, origFile
}
// Get color codes for console colors
func getColor(code string) string {
colors := map[string]string{
"black": "\x1b[30m",
"blue": "\x1B[34m",
"red": "\x1B[31m",
"green": "\x1B[32m",
"yellow": "\x1B[33m",
"magenta": "\x1B[35m",
"cyan": "\x1B[36m",
"white": "\x1B[37m",
// From https://gist.github.com/abritinthebay/d80eb99b2726c83feb0d97eab95206c4
// esoteric options
"bright": "\x1b[1m",
"dim": "\x1b[2m",
"underscore": "\x1b[4m",
"blink": "\x1b[5m",
"reverse": "\x1b[7m",
"hidden": "\x1b[8m",
// background color options
"bgblack": "\x1b[40m",
"bgred": "\x1b[41m",
"bggreen": "\x1b[42m",
"bgyellow": "\x1b[43m",
"bgblue": "\x1b[44m",
"bgmagenta": "\x1b[45m",
"bgcyan": "\x1b[46m",
"bgwhite": "\x1b[47m",
// reset color code
"reset": "\x1B[0m",
"default": "\x1B[0m",
}
if color, ok := colors[code]; ok {
return color
} else {
return colors["default"]
}
}
// Print the delimiter line for listings
func printDelim(delimChar string, color string) {
var delims []string
if color == "underscore" {
// Override delimieter to space
delimChar = " "
}
if len(delimChar) > 1 {
// slice it - take only the first
delimChar = string(delimChar[0])
}
for i := 0; i < DELIMSIZE; i++ {
delims = append(delims, delimChar)
}
fmt.Println(strings.Join(delims, ""))
}
// Print an entry to the console
func printEntry(entry *Entry, delim bool) error {
var err error
var settings *Settings
err, settings = getOrCreateLocalConfig(APP)
if err != nil {
fmt.Printf("Error parsing config - \"%s\"\n", err.Error())
return err
}
fmt.Printf("%s", getColor(strings.ToLower(settings.Color)))
if strings.HasPrefix(settings.BgColor, "bg") {
fmt.Printf("%s", getColor(strings.ToLower(settings.BgColor)))
}
if delim {
printDelim(settings.Delim, settings.Color)
}
fmt.Printf("ID: %d\n", entry.ID)
fmt.Printf("Title: %s\n", entry.Title)
fmt.Printf("User: %s\n", entry.User)
fmt.Printf("URL: %s\n", entry.Url)
if settings.ShowPasswords || settingsRider.ShowPasswords {
fmt.Printf("Password: %s\n", entry.Password)
} else {
var asterisks []string
for i := 0; i < len(entry.Password); i++ {
asterisks = append(asterisks, "*")
}
fmt.Printf("Password: %s\n", strings.Join(asterisks, ""))
}
fmt.Printf("Notes: %s\n", entry.Notes)
fmt.Printf("Modified: %s\n", entry.Timestamp.Format("2006-06-02 15:04:05"))
printDelim(settings.Delim, settings.Color)
// Reset
fmt.Printf("%s", getColor("default"))
return nil
}
// Read user input and return entered value
func readInput(reader *bufio.Reader, prompt string) string {
var input string
fmt.Printf(prompt + ": ")
input, _ = reader.ReadString('\n')
return strings.TrimSpace(input)
}
// Check for an active, decrypted database
func checkActiveDatabase() error {
if !hasActiveDatabase() {
fmt.Printf("No decrypted active database found.\n")
return errors.New("no active database")
}
return nil
}
// Return true if active database is encrypted
func isActiveDatabaseEncrypted() bool {
err, settings := getOrCreateLocalConfig(APP)
if err == nil && settings.ActiveDB != "" {
if _, err := os.Stat(settings.ActiveDB); err == nil {
if _, flag := isFileEncrypted(settings.ActiveDB); flag {
return true
}
}
}
return false
}
// Return true if always encrypt is on
func isEncryptOn() bool {
_, settings := getOrCreateLocalConfig(APP)
return settings.KeepEncrypted
}
// Combination of above 2 logic plus auto encryption on (a play on CryptOn)
func isActiveDatabaseEncryptedAndMaxKryptOn() (bool, string) {
err, settings := getOrCreateLocalConfig(APP)
if err == nil && settings.ActiveDB != "" {
if _, err := os.Stat(settings.ActiveDB); err == nil {
if _, flag := isFileEncrypted(settings.ActiveDB); flag && settings.KeepEncrypted && settings.AutoEncrypt {
return true, settings.ActiveDB
}
}
}
return false, ""
}
// (Temporarily) enable showing of passwords
func setShowPasswords() error {
// fmt.Printf("Setting show passwords to true\n")
settingsRider.ShowPasswords = true
return nil
}
// Copy the password to clipboard - only for single listings or single search results
func setCopyPasswordToClipboard() error {
settingsRider.CopyPassword = true
return nil
}
func copyPasswordToClipboard(passwd string) {
clipboard.WriteAll(passwd)
}
// Generate a random file name
func randomFileName(folder string, suffix string) string {
_, name := generateRandomBytes(16)
return filepath.Join(folder, hex.EncodeToString(name)+suffix)
}