diff --git a/README.md b/README.md index ed0ead8..01631aa 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Install If you are on a Debian or Debian derived system, you can directly download and install the latest version. Check out the [releases](https://github.com/pythonhacker/varuh/releases) page and use `dpkg` to install the binary. - $ sudo dpkg -i varuh-${VERSION}_amd64.deb + $ sudo dpkg -i varuh-${VERSION}_amd64.deb The binary will be installed in `/usr/bin` folder. @@ -44,24 +44,24 @@ You need the [Go compiler](https://golang.org/dl/) to build the code. (This can Install `make` by using your native package manager. Something like, - $ sudo apt install make -y + $ sudo apt install make -y should work. Then, - $ make - Building varuh - go: downloading github.com/akamensky/argparse v1.3.1 - go: downloading golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 - go: downloading github.com/atotto/clipboard v0.1.4 - go: downloading github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f - go: downloading github.com/pythonhacker/argparse v1.3.2 - go: downloading gorm.io/driver/sqlite v1.2.3 - ... + $ make + Building varuh + go: downloading github.com/akamensky/argparse v1.3.1 + go: downloading golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 + go: downloading github.com/atotto/clipboard v0.1.4 + go: downloading github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f + go: downloading github.com/pythonhacker/argparse v1.3.2 + go: downloading gorm.io/driver/sqlite v1.2.3 + ... - $ sudo make install - Installing varuh...done + $ sudo make install + Installing varuh...done The binary will be installed in `/usr/local/bin` folder. @@ -69,41 +69,44 @@ The binary will be installed in `/usr/local/bin` folder. Usage ===== - $ ./varuh -h + $ varuh -h usage: varuh [-h|--help] [-I|--init ""] [-d|--decrypt ""] [-C|--clone ""] [-R|--remove ""] [-U|--use-db - ""] [-f|--find ""] [-E|--edit ""] - [-l|--list-entry ""] [-x|--export ""] [-e|--encrypt] - [-A|--add] [-p|--path] [-a|--list-all] [-g|--genpass] [-s|--show] - [-c|--copy] [-v|--version] + ""] [-E|--edit ""] [-l|--list-entry ""] + [-x|--export ""] [-m|--migrate ""] [-f|--find + "" [-f|--find "" ...]] [-e|--encrypt] [-A|--add] + [-p|--path] [-a|--list-all] [-g|--genpass] [-s|--show] [-c|--copy] + [-y|--assume-yes] [-v|--version] Password manager for the command line for Unix like operating systems Options: - -h --help Print help information - -I --init Initialize a new database - -d --decrypt Decrypt password database - -C --clone Clone an entry with - -R --remove Remove an entry with - -U --use-db Set as active database - -f --find Search entries with - -E --edit Edit entry by - -l --list-entry List entry by - -x --export Export all entries to - -e --encrypt Encrypt the current database - -A --add Add a new entry - -p --path Show current database path - -a --list-all List all entries in current database - -g --genpass Generate a strong password of length from 12 - 16 - -s --show Show passwords when listing entries - -c --copy Copy password to clipboard - -v --version Show version information and exit + -h --help Print help information + -I --init Initialize a new database + -d --decrypt Decrypt password database + -C --clone Clone an entry with + -R --remove Remove an entry with or + -U --use-db Set as active database + -E --edit Edit entry by + -l --list-entry List entry by + -x --export Export all entries to + -m --migrate Migrate a database to latest schema + -f --find ... Search entries with terms + -e --encrypt Encrypt the current database + -A --add Add a new entry + -p --path Show current database path + -a --list-all List all entries in current database + -g --genpass Generate a strong password (length: 12 - 16) + -s --show Show passwords when listing entries + -c --copy Copy password to clipboard + -y --assume-yes Assume yes to actions requiring confirmation + -v --version Show version information and exit AUTHORS - Copyright (C) 2021 Anand B Pillai + Copyright (C) 2022 Anand B Pillai Encryption and Security @@ -130,66 +133,144 @@ Databases ## Create a database - $ varuh -I mypasswds - Created new database - mypasswds - Updating active db path - /home/anand/mypasswds + $ varuh -I mypasswds + Created new database - mypasswds + Updating active db path - /home/anand/mypasswds - $ ls -lt mypasswds - -rw------- 1 anand anand 8192 Nov 9 23:06 mypasswds + $ ls -lt mypasswds + -rw------- 1 anand anand 8192 Nov 9 23:06 mypasswds The password database is created and is active now. You can start adding entries to it. ## Add an entry - $ varuh -A - Title: My Website Login - URL: mywebsite.name - Username: mememe - Password (enter to generate new): - Generating password ...done - Notes: Website uses Nginx auth - Created new entry with id: 1 + $ varuh -A + Title: My Website Login + URL: mywebsite.name + Username: mememe + Password (enter to generate new): + Generating password ...done + Tags (separated by space): testing test website + Notes: Website uses Nginx auth + Do you want to add custom fields [y/N]: + Created new entry with id: 1 You can now list the entry with one of the list options. - $ varuh -l 1 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 1 - Title: My Website Login - User: mememe - URL: http://mywebsite.name - Password: **************** - Notes: Website uses Nginx auth - Modified: 2021-21-09 23:12:35 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $ varuh -l 1 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 1 + Title: My Website Login + User: mememe + URL: http://mywebsite.name + Password: **************** + Tags: testing test website + Notes: Website uses Nginx auth + Modified: 2021-21-09 23:12:35 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + +## Add an entry with custom fields + +From version 0.3 onwards, custom fields are supported. + + $ varuh -A + Title: Github token + URL: https://github.com/mydev/myproject + Username: mydev + Password (enter to generate new): ghp_ipQrStuVwxYz1a2b3cdEF10ghI689kLaMnOp + Tags (separated by space): token github + Notes: Never Expires + Do you want to add custom fields [y/N]: y + Field Name: Domain + Value for Domain: github.com + Field Name: Type + Value for Type: Auth Token + Field Name: + Created new entry with id: 6 + + $ varuh -l 6 + ID: 6 + Title: Github token + User: mydev + URL: https://github.com/mydev/myproject + Password: ghp_ipQrStuVwxYz1a2b3cdEF10ghI689kLaMnOp + Tags: token github + Notes: Never Expires + Domain: github.com + Type: Auth Token + Modified: 2021-21-13 00:07:18 For more on listing see the [Listing and Searching](#listing-and-searching) section below. ## Edit an entry - $ varuh -E 1 - Current Title: My Website Login - New Title: My Blog Login - Current URL: http://mywebsite.name - New URL: myblog.name - Current Username: mememe - New Username: meblog - Current Password: lTzC2z9kRppnYsYl - New Password ([y/Y] to generate new, enter will keep old one): - Current Notes: Website uses Nginx auth - New Notes: Website uses Apache - Updated entry. - - $ varuh -l 1 -s - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 1 - Title: My Blog Login - User: meblog - URL: http://myblog.name - Password: myblog123 - Notes: Website uses Apache - Modified: 2021-21-09 23:15:29 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $ varuh -E 1 + Current Title: My Website Login + New Title: My Blog Login + Current URL: http://mywebsite.name + New URL: myblog.name + Current Username: mememe + New Username: meblog + Current Password: lTzC2z9kRppnYsYl + New Password ([y/Y] to generate new, enter will keep old one): + Current Tags: testing test website + New Tags: + Current Notes: Website uses Nginx auth + New Notes: Website uses Apache + Do you want to add custom fields [y/N]: + Updated entry. + + $ varuh -l 1 -s + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 1 + Title: My Blog Login + User: meblog + URL: http://myblog.name + Password: myblog123 + Tags: testing test website + Notes: Website uses Apache + Modified: 2021-21-09 23:15:29 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + +## Edit an entry with custom fields + +When you edit an entry with custom fields, you get the option to change the name of the fields or delete the fields entirely. + + $ varuh -E 6 + Current Title: Github token + New Title: + Current URL: https://github.com/mydev/myproject + New URL: + Current Username: mydev + New Username: + Current Password: ghp_ipQrStuVwxYz1a2b3cdEF10ghI689kLaMnOp + New Password ([y/Y] to generate new, enter will keep old one): + Current Tags: token github + New Tags: + Current Notes: Never Expires + New Notes: + Editing/deleting custom fields + Field Name: Domain + New Field Name (Enter to keep, "x" to delete): x + Deleting field: Domain + Field Name: Type + New Field Name (Enter to keep, "x" to delete): Token Type + Field Value: Auth Token + New Field Value (Enter to keep): + Do you want to add custom fields [y/N]: + Created 1 custom entries for entry: 21. + Updated entry. + + $ varuh -l 6 -s + ID: 6 + Title: Github token + User: mydev + URL: https://github.com/mydev/myproject + Password: ghp_ipQrStuVwxYz1a2b3cdEF10ghI689kLaMnOp + Tags: token github + Notes: Never Expires + Token Type: Auth Token + Modified: 2021-21-13 00:16:41 (*-s* turns on visible passwords) @@ -197,30 +278,59 @@ For more on listing see the [Listing and Searching](#listing-and-searching) sect To clone (copy) an entry, - $ $ varuh -C 1 - Cloned to new entry, id: 2 + $ $ varuh -C 1 + Cloned to new entry, id: 3 ## Remove an entry - $ varuh -R 1 - Entry with id 1 was removed from the database + $ varuh -R 1 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + Title: My Website Login + User: mememe + URL: https://mywebsite.name + Modified: 2021-21-09 23:12:35 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + Please confirm removal [Y/n]: + Entry with id 1 was removed from the database It is an error if the id does not exist. - $ varuh -R 3 - No entry with id 3 was found + $ varuh -R 4 + No entry with id 4 was found + +## Remove a range of entries + +You can remove a range of entry ids from id1-id2 using the following command. + + $ varuh -R id1-id2 + +Example: + + $ varuh -R 1-4 + +This will remove entries from 1 to 4 inclusive, asking for confirmation from the user every time. + +## Removal without confirmation + +If you are very sure, you can avoid the confirmation prompt by passing the `-y` flag which will remove the entry without confirmation. + + $ varuh -R 2 -y + ... + ... + ... + Entry with id 2 was removed from the database ## Switch to a new database Once a database is active, creating another one automatically encrypts the current one and makes the new one the active database. The automatic encryption happens only if the configuration flag `auto_encrypt` is turned on (See section [Configuration](#configuration) below). - $ varuh -I mysecrets - Encrytping current database - /home/anand/mypasswds - Password: - Password again: - Encryption complete. - Created new database - mysecrets - Updating active db path - /home/anand/mysecrets + $ varuh -I mysecrets + Encrytping current database - /home/anand/mypasswds + Password: + Password again: + Encryption complete. + Created new database - mysecrets + Updating active db path - /home/anand/mysecrets The previous database is now encrypted with the configured block cipher using the password. Please make sure you remember the password. @@ -228,48 +338,67 @@ The previous database is now encrypted with the configured block cipher using th If you want to switch back to a previous database, you can use the `-U` option. The same process is repeated with the current database getting encrypted and the older one getting decrypted. - $ varuh -U mypasswds - Encrypting current active database - /home/anand/mysecrets - Password: - Password again: - Encryption complete. - Database /home/anand/mypasswds is encrypted, decrypting it - Password: + $ varuh -U mypasswds + Encrypting current active database - /home/anand/mysecrets + Password: + Password again: + Encryption complete. + Database /home/anand/mypasswds is encrypted, decrypting it + Password: + Decryption complete. + Switched active database successfully. + +## Database Migration + +(New in version 0.4) + +When new features are added - sometimes new fields would be required to be added in the database schema. To make sure your old databases work with the new features in such cases, the `-m/--migrate` option can be used to migrate your existing databases. + + $ ./varuh -m /home/anand/mypasswds + Password: Decryption complete. - Switched active database successfully. - + Migrating tables ... + + Encryption complete. + Migration successful. + +For migration you need to provide the database path - even for the active database. Once migrated, you can continue to use your database as before. + +NOTE: It is suggested to make a backup copy of your current active database before migration. + ## Manual encryption and decryption You can manually encrypt the current database using the `-e` option. - $ varuh -e - Password: - Password again: - Encryption complete. + $ varuh -e + Password: + Password again: + Encryption complete. Note that once you encrypt the active database, you cannot use the listings any more unless it is decrypted. - $ varuh -l 2 - No decrypted active database found. + $ varuh -l 2 + No decrypted active database found. Manually decrypt the database using `-d` option. - $ varuh -d mypasswds - Password: - Decryption complete. + $ varuh -d mypasswds + Password: + Decryption complete. Now the database is active again and you can see the listings. - $ varuh -l 2 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 2 - Title: My Blog Login - User: myblog.name - URL: http://meblog - Password: ********* - Notes: Website uses Apache - Modified: 2021-21-09 23:21:32 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $ varuh -l 3 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 2 + Title: My Blog Login + User: myblog.name + URL: http://meblog + Password: ********* + Tags: test testing website + Notes: Website uses Apache + Modified: 2021-21-09 23:21:32 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ## Always on encryption @@ -277,20 +406,21 @@ If the config param `encrypt_on` is set to `true` along with `auto_encrypt` (def ### Example - $ varuh -f my -s - Password: - Decryption complete. - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 2 - Title: MY LOCAL BANK - User: banklogin - URL: https://my.localbank.com - Password: bankpass123 - Notes: - Modified: 2021-21-18 12:44:10 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - - Encryption complete. + $ varuh -f my -s + Password: + Decryption complete. + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 2 + Title: MY LOCAL BANK + User: banklogin + URL: https://my.localbank.com + Password: bankpass123 + Tags: bank banking finance + Notes: + Modified: 2021-21-18 12:44:10 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + Encryption complete. In this mode, your data is provided maximum safety as the database remains decrypted only for a short while on the disk while the data is being read and once done is encrypted back again. @@ -301,79 +431,98 @@ Listing and Searching To list an entry using its id, - $ varuh -l 8 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 8 - Title: Google account - User: anandpillai@alumni.iitm.ac.in - URL: - Password: *********** - Notes: - Modified: 2021-21-25 15:02:50 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $ varuh -l 8 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 8 + Title: Google account + User: anandpillai@alumni.iitm.ac.in + URL: + Password: *********** + Notes: + Modified: 2021-21-25 15:02:50 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ## To search an entry An entry can be searched on its title, username, URL or notes. Search is case-insensitive. - $ varuh -f google - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 8 - Title: Google account - User: anandpillai@alumni.iitm.ac.in - URL: - Password: ********** - Notes: - Modified: 2021-21-25 15:02:50 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 9 - Title: Google account - User: xyz@gmail.com - URL: - Password: ******** - Notes: - Modified: 2021-21-25 15:05:36 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 10 - Title: Google account - User: somethingaboutme@gmail.com - URL: - Password: *********** - Notes: - Modified: 2021-21-25 15:09:51 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + $ varuh -f google + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 8 + Title: Google account + User: anandpillai@alumni.iitm.ac.in + URL: + Password: ********** + Notes: + Modified: 2021-21-25 15:02:50 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 9 + Title: Google account + User: xyz@gmail.com + URL: + Password: ******** + Notes: + Modified: 2021-21-25 15:05:36 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 10 + Title: Google account + User: somethingaboutme@gmail.com + URL: + Password: *********** + Notes: + Modified: 2021-21-25 15:09:51 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + +## To search using multiple terms + +The `-f` option supports multiple terms, so you can specify this more than one time to narrow a search down to a specific entry. + + $ varuh -f google -f anand + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 8 + Title: Google account + User: anandpillai@alumni.iitm.ac.in + URL: + Password: ********** + Notes: + Modified: 2021-21-25 15:02:50 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + $ varuh -f google -f priya + Entry for "google priya" not found ## To list all entries To list all entries, use the option `-a`. - $ varuh -a - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 1 - Title: My Bank #1 - User: myusername1 - URL: https://mysuperbank1.com - Password: *********** - Notes: - Modified: 2021-21-15 15:40:29 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 2 - Title: My Digital Locker #1 - User: mylockerusername - URL: https://mysuperlocker1.com - Password: ********** - Notes: - Modified: 2021-21-18 12:44:10 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ID: 3 - Title: My Bank Login #2 - User: mybankname2 - URL: https://myaveragebank.com - Password: ********** - Notes: - Modified: 2021-21-19 14:16:33 - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - ... + $ varuh -a + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 1 + Title: My Bank #1 + User: myusername1 + URL: https://mysuperbank1.com + Password: *********** + Notes: + Modified: 2021-21-15 15:40:29 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 2 + Title: My Digital Locker #1 + User: mylockerusername + URL: https://mysuperlocker1.com + Password: ********** + Notes: + Modified: 2021-21-18 12:44:10 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ID: 3 + Title: My Bank Login #2 + User: mybankname2 + URL: https://myaveragebank.com + Password: ********** + Notes: + Modified: 2021-21-19 14:16:33 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + ... By default the listing is in ascending ID order. This can be changed in the configuration (see below). @@ -389,8 +538,8 @@ This is useful to copy the password to a password input field in the browser for ## See current active database path - $ varuh -p - /home/anand/mypasswds + $ varuh -p + /home/anand/mypasswds Export ====== @@ -404,37 +553,37 @@ Export To export use the `-x` option. The type of file is automatically figured out from the filename extension. - $ varuh -x passwds.csv - !WARNING: Passwords are stored in plain-text! - Exported 14 records to passwds.csv . - Exported to passwds.csv. + $ varuh -x passwds.csv + !WARNING: Passwords are stored in plain-text! + Exported 14 records to passwds.csv . + Exported to passwds.csv. - $ varuh -x passwds.html - Exported to passwds.html. + $ varuh -x passwds.html + Exported to passwds.html. PDF export is supported if `pandoc` is installed along with the required `pdflatex` packages. The following command (on `Debian` and derived systems) should install the required dependencies. - $ sudo apt-get install pandoc texlive-latex-base texlive-fonts-recommended texlive-fonts-extra texlive-latex-extra texlive-xetex lmodern -y + $ sudo apt-get install pandoc texlive-latex-base texlive-fonts-recommended texlive-fonts-extra texlive-latex-extra texlive-xetex lmodern -y Then, - $ varuh -x passwds.pdf - pdftk not found, PDF won't be secure! + $ varuh -x passwds.pdf + pdftk not found, PDF won't be secure! - File passwds.pdf created without password. - Exported to passwds.pdf. + File passwds.pdf created without password. + Exported to passwds.pdf. PDF files are exported in landscape mode with 150 dpi and 600 columns. To avoid the data not fitting into one page the fields `Notes` and `URL` are not exported. If `pdftk` is installed, the PDF files will be encrypted with an (optional) password. - $ sudo apt-get install pdftk -y + $ sudo apt-get install pdftk -y - $ varuh -x passwds.pdf - PDF Encryption Password: ****** - File passwds.pdf created without password. - Added password to passwds.pdf. - Exported to passwds.pdf. + $ varuh -x passwds.pdf + PDF Encryption Password: ****** + File passwds.pdf created without password. + Added password to passwds.pdf. + Exported to passwds.pdf. Misc ==== @@ -445,14 +594,14 @@ Generate a strong password of length ranging from 12 - 16. A `strong` password is defined as a cryptographically secure string contaning at least one upper-case letter, one punctuation character and one number. - $ varuh -g - 7%zv/uzIgpqexJ + $ varuh -g + 7%zv/uzIgpqexJ - By passing the `-c` option, the password is also copied to the clipboard. + By passing the `-c` option, the password is also copied to the clipboard. - $ varuh -g -c - y6UpD$~uBI#8 - Password copied to clipboard + $ varuh -g -c + y6UpD$~uBI#8 + Password copied to clipboard Configuration @@ -462,19 +611,19 @@ Configuration The config file is named *config.json*. It looks as follows. - `{ - "active_db": "/home/anand/mypasswds", - "cipher": "aes", - "auto_encrypt": true, - "visible_passwords": false, - "encrypt_on": true, - "path": "/home/anand/.config/varuh/config.json", - "list_order": "id,asc", - "delimiter": "+", - "color": "default", - "bgcolor": "bgblack" - } - ` + `{ + "active_db": "/home/anand/mypasswds", + "cipher": "aes", + "auto_encrypt": true, + "visible_passwords": false, + "encrypt_on": true, + "path": "/home/anand/.config/varuh/config.json", + "list_order": "id,asc", + "delimiter": ">", + "color": "default", + "bgcolor": "bgblack" + } + ` You can modify the following variables. 1. `auto_encrypt` - Set this to true to enable automatic encryption/decryption when switching databases. Otherwise you have to do this manually. The default is `true`. @@ -487,7 +636,7 @@ You can modify the following variables. * `title` - Uses the `Title` field. * `username` - Uses the `User` field. - Always specify this configuration as `,`. Supported `` values are `asc` and `desc`. + Always specify this configuration as `,`. Supported `` values are `asc` and `desc`. 1. `delimiter` - This modifies the delimiter string when printing a listing. Only one character is allowed. 1. `color` - The foreground color of the text when printing listings. 1. `bgcolor` - The background color of the text when printing listings. diff --git a/actions.go b/actions.go index e6db91c..09c94ca 100644 --- a/actions.go +++ b/actions.go @@ -6,6 +6,7 @@ import ( "encoding/csv" "errors" "fmt" + "gorm.io/gorm" "os" "os/exec" "os/signal" @@ -15,6 +16,11 @@ import ( "syscall" ) +type CustomEntry struct { + fieldName string + fieldValue string +} + // Wrappers (closures) for functions accepting strings as input for in/out encryption func WrapperMaxKryptStringFunc(fn actionFunc) actionFunc { @@ -170,14 +176,19 @@ func setActiveDatabasePath(dbPath string) error { } if newEncrypted { - // Decrypt new database if it is encrypted - fmt.Printf("Database %s is encrypted, decrypting it\n", fullPath) - err, _ = decryptDatabase(fullPath) - if err != nil { - fmt.Printf("Decryption Error - \"%s\", not switching databases\n", err.Error()) - return err + if !settings.AutoEncrypt { + // Decrypt new database if it is encrypted + fmt.Printf("Database %s is encrypted, decrypting it\n", fullPath) + err, _ = decryptDatabase(fullPath) + if err != nil { + fmt.Printf("Decryption Error - \"%s\", not switching databases\n", err.Error()) + return err + } else { + newEncrypted = false + } } else { - newEncrypted = false + // New database is encrypted and autoencrypt is set - so keep it like that + // fmt.Printf("Database %s is already encrypted, nothing to do\n", fullPath) } } } @@ -188,7 +199,7 @@ func setActiveDatabasePath(dbPath string) error { return nil } - if newEncrypted { + if newEncrypted && !settings.AutoEncrypt { // Use should manually decrypt before switching fmt.Println("Auto-encrypt disabled, decrypt new database manually before switching.") return nil @@ -218,7 +229,9 @@ func addNewEntry() error { var url string var notes string var passwd string + var tags string var err error + var customEntries []CustomEntry if err = checkActiveDatabase(); err != nil { return err @@ -242,9 +255,10 @@ func addNewEntry() error { err, passwd = generateStrongPassword() fmt.Printf("done") } - // fmt.Printf("Password => %s\n", passwd) + // fmt.Printf("Password => %s\n", passwd) - notes = readInput(reader, "\nNotes") + tags = readInput(reader, "\nTags (separated by space): ") + notes = readInput(reader, "Notes") // Title and username/password are mandatory if len(title) == 0 { @@ -260,8 +274,10 @@ func addNewEntry() error { return errors.New("invalid input") } + customEntries = addCustomFields(reader) + // Trim spaces - err = addNewDatabaseEntry(title, userName, url, passwd, notes) + err = addNewDatabaseEntry(title, userName, url, passwd, tags, notes, customEntries) if err != nil { fmt.Printf("Error adding entry - \"%s\"\n", err.Error()) @@ -270,6 +286,86 @@ func addNewEntry() error { return err } +// Function to update existing custom entries and add new ones +// The bool part of the return value indicates whether to take action +func addOrUpdateCustomFields(reader *bufio.Reader, entry *Entry) ([]CustomEntry, bool) { + + var customEntries []ExtendedEntry + var editedCustomEntries []CustomEntry + var newCustomEntries []CustomEntry + var flag bool + + customEntries = getExtendedEntries(entry) + + if len(customEntries) > 0 { + + fmt.Println("Editing/deleting custom fields") + for _, customEntry := range customEntries { + var fieldName string + var fieldValue string + + fmt.Println("Field Name: " + customEntry.FieldName) + fieldName = readInput(reader, "\tNew Field Name (Enter to keep, \"x\" to delete)") + if strings.ToLower(strings.TrimSpace(fieldName)) == "x" { + fmt.Println("Deleting field: " + customEntry.FieldName) + } else { + if strings.TrimSpace(fieldName) == "" { + fieldName = customEntry.FieldName + } + + fmt.Println("Field Value: " + customEntry.FieldValue) + fieldValue = readInput(reader, "\tNew Field Value (Enter to keep)") + if strings.TrimSpace(fieldValue) == "" { + fieldValue = customEntry.FieldValue + } + + editedCustomEntries = append(editedCustomEntries, CustomEntry{fieldName, fieldValue}) + } + } + } + + newCustomEntries = addCustomFields(reader) + + editedCustomEntries = append(editedCustomEntries, newCustomEntries...) + + // Cases where length == 0 + // 1. Existing entries - all deleted + flag = len(customEntries) > 0 || len(editedCustomEntries) > 0 + + return editedCustomEntries, flag +} + +// Function to add custom fields to an entry +func addCustomFields(reader *bufio.Reader) []CustomEntry { + + // Custom fields + var custom string + var customEntries []CustomEntry + + custom = readInput(reader, "Do you want to add custom fields [y/N]") + if strings.ToLower(custom) == "y" { + + fmt.Println("Keep entering custom field name followed by the value. Press return with no input once done.") + for true { + var customFieldName string + var customFieldValue string + + customFieldName = strings.TrimSpace(readInput(reader, "Field Name")) + if customFieldName != "" { + customFieldValue = strings.TrimSpace(readInput(reader, "Value for "+customFieldName)) + } + + if customFieldName == "" && customFieldValue == "" { + break + } + + customEntries = append(customEntries, CustomEntry{customFieldName, customFieldValue}) + } + } + + return customEntries +} + // Edit a current entry by id func editCurrentEntry(idString string) error { @@ -277,6 +373,7 @@ func editCurrentEntry(idString string) error { var title string var url string var notes string + var tags string var passwd string var err error var entry *Entry @@ -317,13 +414,18 @@ func editCurrentEntry(idString string) error { fmt.Printf("\nGenerating new password ...") err, passwd = generateStrongPassword() } - // fmt.Printf("Password => %s\n", passwd) + // fmt.Printf("Password => %s\n", passwd) + + fmt.Printf("\nCurrent Tags: %s\n", entry.Tags) + tags = readInput(reader, "New Tags") fmt.Printf("\nCurrent Notes: %s\n", entry.Notes) notes = readInput(reader, "New Notes") + customEntries, flag := addOrUpdateCustomFields(reader, entry) + // Update - err = updateDatabaseEntry(entry, title, userName, url, passwd, notes) + err = updateDatabaseEntry(entry, title, userName, url, passwd, tags, notes, customEntries, flag) if err != nil { fmt.Printf("Error updating entry - \"%s\"\n", err.Error()) } @@ -344,7 +446,7 @@ func listCurrentEntry(idString string) error { id, _ = strconv.Atoi(idString) - // fmt.Printf("Listing current entry - %d\n", id) + // fmt.Printf("Listing current entry - %d\n", id) err, entry = getEntryById(id) if err != nil || entry == nil { fmt.Printf("No entry found for id %d\n", id) @@ -354,7 +456,7 @@ func listCurrentEntry(idString string) error { err = printEntry(entry, true) if err == nil && settingsRider.CopyPassword { - // fmt.Printf("Copying password " + entry.Password + " to clipboard\n") + // fmt.Printf("Copying password " + entry.Password + " to clipboard\n") copyPasswordToClipboard(entry.Password) } @@ -421,12 +523,15 @@ func findCurrentEntry(term string) error { var err error var entries []Entry + var terms []string if err = checkActiveDatabase(); err != nil { return err } - err, entries = searchDatabaseEntry(term) + terms = strings.Split(term, " ") + + err, entries = searchDatabaseEntries(terms, "AND") if err != nil || len(entries) == 0 { fmt.Printf("Entry for query \"%s\" not found\n", term) return err @@ -457,17 +562,51 @@ func findCurrentEntry(term string) error { return err } +// Remove a range of entries - say 10-14 +func removeMultipleEntries(idRangeEntry string) error { + + var err error + var idRange []string + var id1, id2 int + + idRange = strings.Split(idRangeEntry, "-") + + if len(idRange) != 2 { + fmt.Println("Invalid id range - " + idRangeEntry) + return errors.New("Invalid id range - " + idRangeEntry) + } + + id1, _ = strconv.Atoi(idRange[0]) + id2, _ = strconv.Atoi(idRange[1]) + + if id1 >= id2 { + fmt.Println("Invalid id range - " + idRangeEntry) + return errors.New("Invalid id range - " + idRangeEntry) + } + + for idNum := id1; idNum <= id2; idNum++ { + err = removeCurrentEntry(fmt.Sprintf("%d", idNum)) + } + + return err +} + // Remove current entry by id func removeCurrentEntry(idString string) error { var err error var entry *Entry var id int + var response string if err = checkActiveDatabase(); err != nil { return err } + if strings.Contains(idString, "-") { + return removeMultipleEntries(idString) + } + id, _ = strconv.Atoi(idString) err, entry = getEntryById(id) @@ -476,10 +615,22 @@ func removeCurrentEntry(idString string) error { return err } - // Drop from the database - err = removeDatabaseEntry(entry) - if err == nil { - fmt.Printf("Entry with id %d was removed from the database\n", id) + printEntryMinimal(entry, true) + + if !settingsRider.AssumeYes { + response = readInput(bufio.NewReader(os.Stdin), "Please confirm removal [Y/n]: ") + } else { + response = "y" + } + + if strings.ToLower(response) != "n" { + // Drop from the database + err = removeDatabaseEntry(entry) + if err == nil { + fmt.Printf("Entry with id %d was removed from the database\n", id) + } + } else { + fmt.Println("Removal of entry cancelled by user.") } return err @@ -490,6 +641,9 @@ func copyCurrentEntry(idString string) error { var err error var entry *Entry + var entryNew *Entry + var exEntries []ExtendedEntry + var id int if err = checkActiveDatabase(); err != nil { @@ -504,12 +658,24 @@ func copyCurrentEntry(idString string) error { return err } - err, _ = cloneEntry(entry) + err, entryNew = cloneEntry(entry) if err != nil { fmt.Printf("Error cloning entry: \"%s\"\n", err.Error()) return err } + exEntries = getExtendedEntries(entry) + + if len(exEntries) > 0 { + fmt.Printf("%d extended entries found\n", len(exEntries)) + + err = cloneExtendedEntries(entryNew, exEntries) + if err != nil { + fmt.Printf("Error cloning extended entries: \"%s\"\n", err.Error()) + return err + } + } + return err } @@ -545,11 +711,11 @@ func encryptDatabase(dbPath string, givenPasswd *string) error { } if len(passwd) == 0 { - fmt.Printf("Password: ") + fmt.Printf("Encryption Password: ") err, passwd = readPassword() if err == nil { - fmt.Printf("\nPassword again: ") + fmt.Printf("\nEncryption Password again: ") err, passwd2 = readPassword() if err == nil { if passwd != passwd2 { @@ -565,7 +731,7 @@ func encryptDatabase(dbPath string, givenPasswd *string) error { } } - // err = encryptFileAES(dbPath, passwd) + // err = encryptFileAES(dbPath, passwd) _, settings := getOrCreateLocalConfig(APP) switch settings.Cipher { @@ -597,7 +763,7 @@ func decryptDatabase(dbPath string) (error, string) { return err, "" } - fmt.Printf("Password: ") + fmt.Printf("Decryption Password: ") err, passwd = readPassword() if err != nil { @@ -618,12 +784,65 @@ func decryptDatabase(dbPath string) (error, string) { } if err == nil { - fmt.Println("\nDecryption complete.") + fmt.Println("...decryption complete.") } return err, passwd } +// Migrate an existing database to the new schema +func migrateDatabase(dbPath string) error { + + var err error + var flag bool + var passwd string + var db *gorm.DB + + if _, err = os.Stat(dbPath); os.IsNotExist(err) { + fmt.Printf("Error - path %s does not exist\n", dbPath) + return err + } + + if err, flag = isFileEncrypted(dbPath); flag { + err, passwd = decryptDatabase(dbPath) + } + + if err != nil { + return err + } + + err, db = openDatabase(dbPath) + + if err != nil { + fmt.Printf("Error opening database path - %s: %s\n", dbPath, err.Error()) + return err + } + + fmt.Println("Migrating tables ...") + err = db.AutoMigrate(&Entry{}) + + if err != nil { + fmt.Printf("Error migrating table \"entries\" - %s: %s\n", dbPath, err.Error()) + return err + } + + err = db.AutoMigrate(&ExtendedEntry{}) + + if err != nil { + fmt.Printf("Error migrating table \"exentries\" - %s: %s\n", dbPath, err.Error()) + return err + } + + if flag { + // File was encrypted - encrypt it again + encryptDatabase(dbPath, &passwd) + } + + fmt.Println("Migration successful.") + + return nil +} + // Export data to a varity of file types func exportToFile(fileName string) error { @@ -706,7 +925,7 @@ func exportToMarkdown(fileName string) error { } } - // fmt.Printf("%+v\n", maxLengths) + // fmt.Printf("%+v\n", maxLengths) fh, err = os.Create(fileName) if err != nil { fmt.Printf("Cannt open \"%s\" for writing - \"%s\"\n", fileName, err.Error()) @@ -720,7 +939,7 @@ func exportToMarkdown(fileName string) error { // Write markdown header for idx, length := range maxLengths { delta := length - len(headers[idx]) - // fmt.Printf("%d\n", delta) + // fmt.Printf("%d\n", delta) if delta > 0 { for i := 0; i < delta+2; i++ { headers[idx] += " " @@ -782,7 +1001,7 @@ func exportToPDF(fileName string) error { } tmpFile = randomFileName(os.TempDir(), ".tmp") - // fmt.Printf("Temp file => %s\n", tmpFile) + // fmt.Printf("Temp file => %s\n", tmpFile) err = exportToMarkdownLimited(tmpFile) if err == nil { @@ -799,7 +1018,7 @@ func exportToPDF(fileName string) error { if pdfTkFound && len(passwd) > 0 { tmpFile = randomFileName(".", ".pdf") - // fmt.Printf("pdf file => %s\n", tmpFile) + // fmt.Printf("pdf file => %s\n", tmpFile) args = []string{fileName, "output", tmpFile, "user_pw", passwd} cmd = exec.Command("pdftk", args...) _, err = cmd.Output() @@ -845,7 +1064,7 @@ func exportToMarkdownLimited(fileName string) error { } } - // fmt.Printf("%+v\n", maxLengths) + // fmt.Printf("%+v\n", maxLengths) fh, err = os.Create(fileName) if err != nil { fmt.Printf("Cannt open \"%s\" for writing - \"%s\"\n", fileName, err.Error()) @@ -859,7 +1078,7 @@ func exportToMarkdownLimited(fileName string) error { // Write markdown header for idx, length := range maxLengths { delta := length - len(headers[idx]) - // fmt.Printf("%d\n", delta) + // fmt.Printf("%d\n", delta) if delta > 0 { for i := 0; i < delta+2; i++ { headers[idx] += " " @@ -910,7 +1129,7 @@ func exportToHTML(fileName string) error { return err } - // fmt.Printf("%+v\n", maxLengths) + // fmt.Printf("%+v\n", maxLengths) fh, err = os.Create(fileName) if err != nil { fmt.Printf("Cannt open \"%s\" for writing - \"%s\"\n", fileName, err.Error()) diff --git a/crypto.go b/crypto.go index 2c9ac69..c1744b7 100644 --- a/crypto.go +++ b/crypto.go @@ -278,7 +278,7 @@ func decryptFileAES(encDbPath string, password string) error { return err } - err, origFile = rewriteBaseFile(encDbPath, plainText, 0600) + err, origFile = rewriteFile(encDbPath, plainText, 0600) if err != nil { fmt.Printf("Error writing decrypted data to %s - \"%s\"\n", origFile, err.Error()) @@ -425,8 +425,8 @@ func decryptFileXChachaPoly(encDbPath string, password string) error { return err } - // err = os.WriteFile("test.sqlite3", plainText, 0600) - err, origFile = rewriteBaseFile(encDbPath, plainText, 0600) + // err = os.WriteFile("test.sqlite3", oplainText, 0600) + err, origFile = rewriteFile(encDbPath, plainText, 0600) if err != nil { fmt.Printf("Error writing decrypted data to %s - \"%s\"\n", origFile, err.Error()) diff --git a/db.go b/db.go index 9992591..fa2f75a 100644 --- a/db.go +++ b/db.go @@ -22,6 +22,7 @@ type Entry struct { Url string `gorm:"column:url"` Password string `gorm:"column:password"` Notes string `gorm:"column:notes"` + Tags string `gorm:"column:tags"` Timestamp time.Time `gorm:"type:timestamp;default:(datetime('now','localtime'))"` // sqlite3 } @@ -29,6 +30,21 @@ func (e *Entry) TableName() string { return "entries" } +// Structure representing an extended entry in the db - for custom fields +type ExtendedEntry struct { + ID int `gorm:"column:id;autoIncrement;primaryKey"` + FieldName string `gorm:"column:field_name"` + FieldValue string `gorm:"column:field_value"` + Timestamp time.Time `gorm:"type:timestamp;default:(datetime('now','localtime'))"` // sqlite3 + + Entry Entry `gorm:"foreignKey:EntryID"` + EntryID int +} + +func (ex *ExtendedEntry) TableName() string { + return "exentries" +} + // Clone an entry func (e1 *Entry) Copy(e2 *Entry) { @@ -41,6 +57,16 @@ func (e1 *Entry) Copy(e2 *Entry) { } } +// Clone an entry +func (e1 *ExtendedEntry) Copy(e2 *ExtendedEntry) { + + if e2 != nil { + e1.FieldName = e2.FieldName + e1.FieldValue = e2.FieldValue + e1.EntryID = e2.EntryID + } +} + // Create a new database func openDatabase(filePath string) (error, *gorm.DB) { @@ -55,6 +81,11 @@ func createNewEntry(db *gorm.DB) error { return db.AutoMigrate(&Entry{}) } +// Create a new table for Extended Entries in the database +func createNewExEntry(db *gorm.DB) error { + return db.AutoMigrate(&ExtendedEntry{}) +} + // Init new database including tables func initNewDatabase(dbPath string) error { @@ -94,6 +125,12 @@ func initNewDatabase(dbPath string) error { return err } + err = createNewExEntry(db) + if err != nil { + fmt.Printf("Error creating schema - \"%s\"\n", err.Error()) + return err + } + fmt.Printf("Created new database - %s\n", dbPath) // Update config @@ -133,21 +170,86 @@ func openActiveDatabase() (error, *gorm.DB) { return nil, db } +// Add custom entries to a database entry +func addCustomEntries(db *gorm.DB, entry *Entry, customEntries []CustomEntry) error { + + var count int + var err error + + err = createNewExEntry(db) + if err != nil { + fmt.Printf("Error creating schema - \"%s\"\n", err.Error()) + return err + } + + for _, customEntry := range customEntries { + var exEntry ExtendedEntry + + exEntry = ExtendedEntry{FieldName: customEntry.fieldName, FieldValue: customEntry.fieldValue, + EntryID: entry.ID} + + resultEx := db.Create(&exEntry) + if resultEx.Error == nil && resultEx.RowsAffected == 1 { + count += 1 + } + } + + fmt.Printf("Created %d custom entries for entry: %d.\n", count, entry.ID) + return nil +} + +// Replace custom entries to a database entry (Drop existing and add fresh) +func replaceCustomEntries(db *gorm.DB, entry *Entry, updatedEntries []CustomEntry) error { + + var count int + var err error + var customEntries []ExtendedEntry + + err = createNewExEntry(db) + if err != nil { + fmt.Printf("Error creating schema - \"%s\"\n", err.Error()) + return err + } + + db.Where("entry_id = ?", entry.ID).Delete(&customEntries) + + for _, customEntry := range updatedEntries { + var exEntry ExtendedEntry + + exEntry = ExtendedEntry{FieldName: customEntry.fieldName, FieldValue: customEntry.fieldValue, + EntryID: entry.ID} + + resultEx := db.Create(&exEntry) + if resultEx.Error == nil && resultEx.RowsAffected == 1 { + count += 1 + } + } + + fmt.Printf("Created %d custom entries for entry: %d.\n", count, entry.ID) + return nil +} + // Add a new entry to current database -func addNewDatabaseEntry(title, userName, url, passwd, notes string) error { +func addNewDatabaseEntry(title, userName, url, passwd, tags string, + notes string, customEntries []CustomEntry) error { var entry Entry var err error var db *gorm.DB - entry = Entry{Title: title, User: userName, Url: url, Password: passwd, Notes: notes} + entry = Entry{Title: title, User: userName, Url: url, Password: passwd, Tags: strings.TrimSpace(tags), + Notes: notes} err, db = openActiveDatabase() if err == nil && db != nil { - // result := db.Debug().Create(&entry) + // result := db.Debug().Create(&entry) result := db.Create(&entry) if result.Error == nil && result.RowsAffected == 1 { + // Add custom fields if given fmt.Printf("Created new entry with id: %d.\n", entry.ID) + if len(customEntries) > 0 { + return addCustomEntries(db, &entry, customEntries) + } return nil } else if result.Error != nil { return result.Error @@ -158,13 +260,20 @@ func addNewDatabaseEntry(title, userName, url, passwd, notes string) error { } // Update current database entry with new values -func updateDatabaseEntry(entry *Entry, title, userName, url, passwd, notes string) error { +func updateDatabaseEntry(entry *Entry, title, userName, url, passwd, tags string, + notes string, customEntries []CustomEntry, flag bool) error { var updateMap map[string]interface{} updateMap = make(map[string]interface{}) - keyValMap := map[string]string{"title": title, "user": userName, "url": url, "password": passwd, "notes": notes} + keyValMap := map[string]string{ + "title": title, + "user": userName, + "url": url, + "password": passwd, + "notes": notes, + "tags": tags} for key, val := range keyValMap { if len(val) > 0 { @@ -172,7 +281,7 @@ func updateDatabaseEntry(entry *Entry, title, userName, url, passwd, notes strin } } - if len(updateMap) == 0 { + if len(updateMap) == 0 && !flag { fmt.Printf("Nothing to update\n") return nil } @@ -188,6 +297,9 @@ func updateDatabaseEntry(entry *Entry, title, userName, url, passwd, notes strin return result.Error } + if flag { + replaceCustomEntries(db, entry, customEntries) + } fmt.Println("Updated entry.") return nil } @@ -249,6 +361,73 @@ func searchDatabaseEntry(term string) (error, []Entry) { } +// Union of two entry arrays +func union(entry1 []Entry, entry2 []Entry) []Entry { + + m := make(map[int]bool) + + for _, item := range entry1 { + m[item.ID] = true + } + + for _, item := range entry2 { + if _, ok := m[item.ID]; !ok { + entry1 = append(entry1, item) + } + } + + return entry1 +} + +// Intersection of two entry arrays +func intersection(entry1 []Entry, entry2 []Entry) []Entry { + + var common []Entry + + m := make(map[int]bool) + + for _, item := range entry1 { + m[item.ID] = true + } + + for _, item := range entry2 { + if _, ok := m[item.ID]; ok { + common = append(common, item) + } + } + + return common +} + +// Search database for the given terms and returns matches according to operator +func searchDatabaseEntries(terms []string, operator string) (error, []Entry) { + + var err error + var finalEntries []Entry + + for idx, term := range terms { + var entries []Entry + + err, entries = searchDatabaseEntry(term) + if err != nil { + fmt.Printf("Error searching for term: %s - \"%s\"\n", term, err.Error()) + return err, entries + } + + if idx == 0 { + finalEntries = entries + } else { + if operator == "AND" { + finalEntries = intersection(finalEntries, entries) + } else if operator == "OR" { + finalEntries = union(finalEntries, entries) + } + } + } + + return nil, finalEntries +} + // Remove a given database entry func removeDatabaseEntry(entry *Entry) error { @@ -257,11 +436,22 @@ func removeDatabaseEntry(entry *Entry) error { err, db = openActiveDatabase() if err == nil && db != nil { + var exEntries []ExtendedEntry + res := db.Delete(entry) if res.Error != nil { return res.Error } + // Delete extended entries if any + exEntries = getExtendedEntries(entry) + if len(exEntries) > 0 { + res = db.Delete(exEntries) + if res.Error != nil { + return res.Error + } + } + return nil } @@ -291,6 +481,31 @@ func cloneEntry(entry *Entry) (error, *Entry) { return err, nil } +// Clone extended entries for an entry and return error code +func cloneExtendedEntries(entry *Entry, exEntries []ExtendedEntry) error { + + var err error + var db *gorm.DB + + err, db = openActiveDatabase() + if err == nil && db != nil { + for _, exEntry := range exEntries { + var exEntryNew ExtendedEntry + + exEntryNew.Copy(&exEntry) + // Update the ID! + exEntryNew.EntryID = entry.ID + + result := db.Create(&exEntryNew) + if result.Error != nil { + return result.Error + } + } + } + + return err +} + // Return an iterator over all entries using the given order query keys func iterateEntries(orderKey string, order string) (error, []Entry) { @@ -354,3 +569,19 @@ func entriesToStringArray(skipLongFields bool) (error, [][]string) { return err, dataArray } + +// Get extended entries associated to an entry +func getExtendedEntries(entry *Entry) []ExtendedEntry { + + var err error + var db *gorm.DB + var customEntries []ExtendedEntry + + err, db = openActiveDatabase() + + if err == nil && db != nil { + db.Where("entry_id = ?", entry.ID).Find(&customEntries) + } + + return customEntries +} diff --git a/main.go b/main.go index 6f90f87..c1ce900 100644 --- a/main.go +++ b/main.go @@ -6,14 +6,15 @@ import ( "fmt" "github.com/pythonhacker/argparse" "os" + "strings" ) -const VERSION = 0.3 +const VERSION = 0.4 const APP = "varuh" const AUTHOR_INFO = ` AUTHORS - Copyright (C) 2021 Anand B Pillai + Copyright (C) 2022 Anand B Pillai ` type actionFunc func(string) error @@ -32,7 +33,7 @@ type CmdOption struct { // Print the program's usage string and exit func printUsage() error { - // getopt.Usage() + // getopt.Usage() os.Exit(0) return nil @@ -86,11 +87,15 @@ func performAction(optMap map[string]interface{}) { "edit": WrapperMaxKryptStringFunc(editCurrentEntry), "init": initNewDatabase, "list-entry": WrapperMaxKryptStringFunc(listCurrentEntry), - "find": WrapperMaxKryptStringFunc(findCurrentEntry), "remove": WrapperMaxKryptStringFunc(removeCurrentEntry), "clone": WrapperMaxKryptStringFunc(copyCurrentEntry), "use-db": setActiveDatabasePath, "export": exportToFile, + "migrate": migrateDatabase, + } + + stringListActionsMap := map[string]actionFunc{ + "find": WrapperMaxKryptStringFunc(findCurrentEntry), } stringActions2Map := map[string]actionFunc2{ @@ -102,8 +107,9 @@ func performAction(optMap map[string]interface{}) { } flagsActionsMap := map[string]voidFunc{ - "show": setShowPasswords, - "copy": setCopyPasswordToClipboard, + "show": setShowPasswords, + "copy": setCopyPasswordToClipboard, + "assume-yes": setAssumeYes, } // Flag actions - always done @@ -145,6 +151,18 @@ func performAction(optMap map[string]interface{}) { } } + for key, mappedFunc := range stringListActionsMap { + if len(*optMap[key].(*[]string)) > 0 { + + var vals = *(optMap[key].(*[]string)) + // Convert to single string + var singleVal = strings.Join(vals, " ") + mappedFunc(singleVal) + flag = true + break + } + } + if flag { return } @@ -168,26 +186,35 @@ func initializeCmdLine(parser *argparse.Parser) map[string]interface{} { {"I", "init", "Initialize a new database", "", ""}, {"d", "decrypt", "Decrypt password database", "", ""}, {"C", "clone", "Clone an entry with ", "", ""}, - {"R", "remove", "Remove an entry with ", "", ""}, + {"R", "remove", "Remove an entry with or ", "", ""}, {"U", "use-db", "Set as active database", "", ""}, - {"f", "find", "Search entries with ", "", ""}, {"E", "edit", "Edit entry by ", "", ""}, {"l", "list-entry", "List entry by ", "", ""}, {"x", "export", "Export all entries to ", "", ""}, + {"m", "migrate", "Migrate a database to latest schema", "", ""}, } for _, opt := range stringOptions { optMap[opt.Long] = parser.String(opt.Short, opt.Long, &argparse.Options{Help: opt.Help, Path: opt.Path}) } + stringListOptions := []CmdOption{ + {"f", "find", "Search entries with terms", " ...", ""}, + } + + for _, opt := range stringListOptions { + optMap[opt.Long] = parser.StringList(opt.Short, opt.Long, &argparse.Options{Help: opt.Help, Path: opt.Path}) + } + boolOptions := []CmdOption{ {"e", "encrypt", "Encrypt the current database", "", ""}, {"A", "add", "Add a new entry", "", ""}, {"p", "path", "Show current database path", "", ""}, {"a", "list-all", "List all entries in current database", "", ""}, - {"g", "genpass", "Generate a strong password of length from 12 - 16", "", ""}, + {"g", "genpass", "Generate a strong password (length: 12 - 16)", "", ""}, {"s", "show", "Show passwords when listing entries", "", ""}, {"c", "copy", "Copy password to clipboard", "", ""}, + {"y", "assume-yes", "Assume yes to actions requiring confirmation", "", ""}, {"v", "version", "Show version information and exit", "", ""}, {"h", "help", "Print this help message and exit", "", ""}, } diff --git a/utils.go b/utils.go index dab41f7..8c57d62 100644 --- a/utils.go +++ b/utils.go @@ -22,6 +22,7 @@ const DELIMSIZE int = 69 type SettingsOverride struct { ShowPasswords bool CopyPassword bool + AssumeYes bool } // Settings structure for local config @@ -104,7 +105,7 @@ func getOrCreateLocalConfig(app string) (error, *Settings) { } configFile = filepath.Join(configPath, "config.json") - // fmt.Printf("Config file, path => %s %s\n", configFile, configPath) + // fmt.Printf("Config file, path => %s %s\n", configFile, configPath) if _, err = os.Stat(configFile); err == nil { fh, err = os.Open(configFile) @@ -121,8 +122,8 @@ func getOrCreateLocalConfig(app string) (error, *Settings) { } } else { - // fmt.Printf("Creating default configuration ...") - settings = Settings{"", "aes", true, true, false, configFile, "id,asc", "+", "default", "bgblack"} + // 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") @@ -212,6 +213,22 @@ func rewriteBaseFile(path string, contents []byte, mode fs.FileMode) (error, str return err, origFile } +// Rewrite the contents of the file with the new contents +func rewriteFile(path string, contents []byte, mode fs.FileMode) (error, string) { + + var err error + + // Overwrite it + err = os.WriteFile(path, contents, 0644) + + if err == nil { + // Chmod it + os.Chmod(path, mode) + } + + return err, path +} + // Get color codes for console colors func getColor(code string) string { @@ -283,6 +300,7 @@ func printEntry(entry *Entry, delim bool) error { var err error var settings *Settings + var customEntries []ExtendedEntry err, settings = getOrCreateLocalConfig(APP) @@ -315,8 +333,60 @@ func printEntry(entry *Entry, delim bool) error { } fmt.Printf("Password: %s\n", strings.Join(asterisks, "")) } - fmt.Printf("Notes: %s\n", entry.Notes) + + if len(entry.Tags) > 0 { + fmt.Printf("Tags: %s\n", entry.Tags) + } + if len(entry.Notes) > 0 { + fmt.Printf("Notes: %s\n", entry.Notes) + } + // Query extended entries + customEntries = getExtendedEntries(entry) + + if len(customEntries) > 0 { + for _, customEntry := range customEntries { + fmt.Printf("%s: %s\n", customEntry.FieldName, customEntry.FieldValue) + } + } + + 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 + +} + +// Print an entry to the console with minimal data +func printEntryMinimal(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("Title: %s\n", entry.Title) + fmt.Printf("User: %s\n", entry.User) + fmt.Printf("URL: %s\n", entry.Url) fmt.Printf("Modified: %s\n", entry.Timestamp.Format("2006-06-02 15:04:05")) + printDelim(settings.Delim, settings.Color) // Reset @@ -386,7 +456,7 @@ func isActiveDatabaseEncryptedAndMaxKryptOn() (bool, string) { // (Temporarily) enable showing of passwords func setShowPasswords() error { - // fmt.Printf("Setting show passwords to true\n") + // fmt.Printf("Setting show passwords to true\n") settingsRider.ShowPasswords = true return nil } @@ -397,6 +467,11 @@ func setCopyPasswordToClipboard() error { return nil } +func setAssumeYes() error { + settingsRider.AssumeYes = true + return nil +} + func copyPasswordToClipboard(passwd string) { clipboard.WriteAll(passwd) }