249 Commits
Author SHA1 Message Date
RandyTheSilly 95c743a3f8 Prepare for release v0.2.0 2024-08-06 14:57:09 -04:00
RandyTheSilly fcfc1a5f96 Bump Go to v1.22.6; bump dependencies 2024-08-06 14:34:23 -04:00
RandyTheSilly 28bd098c2a [wiki/MUTN] Link Glamour issue for v0.8.0 regression 2024-08-05 23:10:17 -04:00
RandyTheSilly b49d8995d6 Do not use deprecated golang.org/x/crypto/ssh/terminal 2024-08-05 22:29:43 -04:00
RandyTheSilly 14140f6574 [wiki/MUTN] Specify why MUTN is using out-of-date Glamour 2024-08-05 15:42:40 -04:00
RandyTheSilly 4ef9cb0c80 Retrieve packaging version number from a temporary Go program 2024-08-05 14:00:49 -04:00
RandyTheSilly 22117579db Add initial packaging script (currently only for generating source PKGBUILD) 2024-08-05 13:36:05 -04:00
RandyTheSilly a04b1b2eb9 Bump dependencies 2024-08-05 10:09:16 -04:00
RandyTheSilly b7a470116a Announce TOTP code has been copied only after the entry has already been decrypted 2024-07-30 18:32:14 -04:00
RandyTheSilly 2904c76ffb [wiki/MUTN] Fix ordered list in usage guide 2024-07-30 16:20:44 -04:00
RandyTheSilly 596129d37d [wiki/MUTN] Link to usage guide from installation guide 2024-07-30 16:00:24 -04:00
RandyTheSilly fe9d91d299 Update README.md w/banner image and a link to the installation guide 2024-07-30 15:57:43 -04:00
RandyTheSilly eb73fbc8e1 Add fallback SSH identity file (~/.ssh/id_ed25519) 2024-07-21 22:56:24 -04:00
RandyTheSilly 410f826b8c Verify user-specified SSH identity file exists 2024-07-21 22:41:13 -04:00
RandyTheSilly c7ed0eec5c [wiki/main] Remove notification of crossed out items 2024-07-19 18:01:46 -04:00
RandyTheSilly 3a1ca0b68d [wiki/MUTN] Add basic setup and usage instructions 2024-07-19 17:56:42 -04:00
RandyTheSilly 35192fa568 Fail early if adding an entry to a directory that does not exist (or if the directory is a file) 2024-07-19 15:53:54 -04:00
RandyTheSilly 83aa4ee497 Fix rename prompting for new location before verifying old one exists 2024-07-19 13:48:14 -04:00
RandyTheSilly 3b6db54dd7 Update README.md 2024-07-19 03:17:30 -04:00
RandyTheSilly 5b196faf03 [wiki/libmutton] Update known bugs list and add a relevant bug to the developer guide 2024-07-18 17:51:05 -04:00
RandyTheSilly 530fde8f11 Improve StringGen to allow creating file name-safe complex strings; remove in-code references to future additions 2024-07-18 17:04:48 -04:00
RandyTheSilly 85fddc0382 When server and client clocks are out of sync, warn the user that they should update mod times even if the pending upload operations appear correct 2024-07-18 16:16:50 -04:00
RandyTheSilly fb0626c5a0 Do not upload/download any entries if the client and server time are more than 30 seconds out of sync; appropriately warn the user 2024-07-18 15:55:50 -04:00
RandyTheSilly df5f10d188 Fix ANSI escapes (on Windows) not being interpreted after using GPG pinentry 2024-07-17 18:54:29 -04:00
RandyTheSilly 1bf72332df Simplify text editor fallback 2024-07-17 17:26:01 -04:00
RandyTheSilly 424d587e65 Move text editor config under [MUTN] section header in libmutton.ini 2024-07-17 15:53:17 -04:00
RandyTheSilly e81bfa935a Allow writing to different section headers in libmutton.ini 2024-07-17 15:49:45 -04:00
RandyTheSilly 4917149299 Move text editor determination to cli package 2024-07-17 14:59:57 -04:00
RandyTheSilly 2ae4fe19e8 Allow parsing different section headers in libmutton.ini 2024-07-17 14:44:18 -04:00
RandyTheSilly 0fc0a2cfc0 Use more specific names for global variables in Bash and ZSH completions 2024-07-16 18:35:31 -04:00
RandyTheSilly f0cdd217d9 Allow using Powershell completions on non-Windows platforms 2024-07-16 18:12:34 -04:00
RandyTheSilly 9a6d6fe98d [wiki/MUTN] Add more Glamour-related issues to known bugs list 2024-07-16 16:24:57 -04:00
RandyTheSilly c6310582c5 Clarify key-based authentication requirement in man page 2024-07-16 16:05:29 -04:00
RandyTheSilly cbf625b2d3 Add tag for building without Markdown support 2024-07-16 15:30:48 -04:00
RandyTheSilly 32adbe0b66 Do not initialize extra iterator in EntryReader() 2024-07-16 14:52:09 -04:00
RandyTheSilly a0c1b09d32 Update .gitignore to ignore specific files rather than everything not manually added 2024-07-16 14:17:38 -04:00
RandyTheSilly d3ba55987b Bump "regexp2" to v1.11.2 2024-07-15 16:59:58 -04:00
RandyTheSilly bfec617f46 Add initial man page and make help info wording more consistent 2024-07-15 16:01:43 -04:00
RandyTheSilly c4e474304a [wiki/libmutton] Add config file info to developer guide 2024-07-15 14:54:47 -04:00
RandyTheSilly 70eba7cec3 Replace use of ASCII control characters with unicode characters allowed in Windows filenames (fixes shearing with a Windows server) 2024-07-10 15:23:13 -04:00
RandyTheSilly 97ba7da6e4 Remove "-v" and "-h" shortcuts from server for consistency with MUTN cli 2024-07-10 03:44:59 -04:00
RandyTheSilly abb2b65c69 Fix "shear" throwing errors if no device ID is present (instead of running in offline mode) 2024-07-10 02:07:59 -04:00
RandyTheSilly 897301343e Split sync.Rename into separate functions for client and server to avoid compiling SSH into the server binary 2024-07-10 00:01:59 -04:00
RandyTheSilly be1f602770 Implement synchronized renaming 2024-07-09 23:18:13 -04:00
RandyTheSilly 42bed109d6 Expand "~" to home directory when specifying ssh identity file 2024-07-09 17:23:36 -04:00
RandyTheSilly e056dcf4ba Append UNIX timestamp to device ID to guarantee uniqueness 2024-07-09 16:42:47 -04:00
RandyTheSilly 98308782a9 Do not always save executable name in memory in sync package 2024-07-09 16:04:03 -04:00
RandyTheSilly 10d5dea6c3 Prompt for SSH port before IP (to avoid users responding to the IP prompt with a socket); specify SSH address may be a domain name 2024-07-09 15:26:17 -04:00
RandyTheSilly b3f4b2b000 Fix printing full executable path in error messages on Windows 2024-07-09 15:20:36 -04:00
RandyTheSilly 7e935c2875 [wiki/MUTN] Add known bugs list 2024-07-09 14:51:47 -04:00
RandyTheSilly 6075f6defd Fix PowerShell completions not completing after directories containing spaces 2024-07-09 14:29:15 -04:00
RandyTheSilly ed5f6a0054 [wiki/libmutton] Add developer guide (for third-party implementations) 2024-07-07 23:52:33 -04:00
RandyTheSilly 7072831f20 [wiki/libmutton] Add guide for migrating from other password managers 2024-07-07 23:25:25 -04:00
RandyTheSilly 637002bc42 [wiki/MUTN] Move shell completions download link to completions.md 2024-07-07 23:08:11 -04:00
RandyTheSilly 2ab833b91f Sort shell completions scripts into folders so that their intended names can be used 2024-07-07 23:04:53 -04:00
RandyTheSilly ff6f5da824 [wiki/MUTN] Add basic building/installation instructions 2024-07-07 22:59:55 -04:00
RandyTheSilly cb6cde9e8e [wiki/libmutton] Add list of planned breaking changes 2024-07-07 22:23:21 -04:00
RandyTheSilly 32557391db [wiki/MUTN] Add list of Windows quirks 2024-07-06 00:18:32 -04:00
RandyTheSilly 7ad081b78a [wiki/MUTN] Add shell completions troubleshooting guide 2024-07-06 00:04:28 -04:00
RandyTheSilly 1fa014abc0 Implement initial markdown wiki w/copy of clipboard troubleshooting info from sshyp 2024-07-05 23:42:40 -04:00
RandyTheSilly ccea9c73a7 Bump Go to v1.22.5, bump dependencies 2024-07-05 22:32:34 -04:00
RandyTheSilly 356d1eab4e Replace most occurrences of os.Exit(0) in the backend and sync packages with a custom backend.Exit function that can allow "soft exit" in GUI/TUI environments to avoid killing the entire process; currently all major errors still result in killing the entire process 2024-07-05 22:18:17 -04:00
RandyTheSilly a9cf524cfa Remove mention of "mutn" in sync package error messages to account for third-party CLI clients 2024-07-05 21:55:56 -04:00
RandyTheSilly 43d87a5b46 Remove "-v" shortcut for "version" argument, as it does not work with Powershell completion; remove "-h" visual option for "help" for consistency 2024-07-05 21:41:18 -04:00
RandyTheSilly f25c68cea3 Handle error for failing to create local device ID file 2024-06-05 18:29:38 -04:00
RandyTheSilly 4844620ed1 Improve error clarity in cli.editNote 2024-06-05 18:19:01 -04:00
RandyTheSilly dbcd71b5ca Handle error in writeToStdin; remove unused function removeFile 2024-06-05 18:05:26 -04:00
RandyTheSilly ce53ee39c3 Handle error for GPG key generation failure 2024-06-05 17:53:30 -04:00
RandyTheSilly 02adfef817 Handle error for failing to read clipboard contents on all platforms 2024-06-05 17:45:49 -04:00
RandyTheSilly f3d06429ca Improve generic UNIX clipboard clearing logic 2024-06-05 17:43:21 -04:00
RandyTheSilly 3bac84dc0c Provide feedback after successful server directory initialization 2024-06-05 17:24:45 -04:00
RandyTheSilly 4f9c57d6da Write and append to config file using ini package 2024-06-05 14:56:17 -04:00
RandyTheSilly 97a9c0a921 Enforce more consistent meanings for the various field separator characters 2024-06-04 21:51:58 -04:00
RandyTheSilly 71666578f6 Server stdin migration: register 2024-06-04 20:05:12 -04:00
RandyTheSilly 4b7bfdc013 Server stdin migration: shear 2024-06-04 15:57:00 -04:00
RandyTheSilly d6ee612c68 Server stdin migration: fetch 2024-06-04 15:38:46 -04:00
RandyTheSilly 18a8668acf Server stdin migration: addfolder 2024-06-04 15:33:50 -04:00
RandyTheSilly 1127e96863 Add initial support for reading stdin from the server binary 2024-06-04 15:09:57 -04:00
RandyTheSilly 50f514ece4 Fix Windows sync (WalkEntryDir now returns only UNIX-style separators); fix setting remote mod time on remote files when downloading; fix server binary compilation; fix init failing silently during SSH configuration 2024-05-31 01:23:50 -04:00
RandyTheSilly b4f0a4e896 Fix init deleting device ID immediately after generating it; fix sync failure for non-manual syncs 2024-05-30 23:25:08 -04:00
RandyTheSilly b03d751618 Save server EntryRoot and OS type during init, use to progress toward Windows server support 2024-05-30 22:57:05 -04:00
RandyTheSilly 6cf01e0d3c Simplify clipboard build constraints 2024-05-30 22:21:39 -04:00
RandyTheSilly 3fcd20b1ca No longer unnecessarily send client OS type to server 2024-05-30 22:15:51 -04:00
RandyTheSilly 1f44d0b5f3 Lay groundwork for NT/UNIX-like sync interoperability 2024-05-30 22:12:29 -04:00
RandyTheSilly ea34f644f3 Add "wsl_clipboard" build tag for creating Linux binaries that use the Windows clipboard 2024-05-29 15:42:15 -04:00
RandyTheSilly ae7bebc461 Update README.md now that native sync has been implemented 2024-05-29 13:59:43 -04:00
RandyTheSilly f3c0836eba Bump dependencies 2024-05-29 13:26:28 -04:00
RandyTheSilly 54cbe098d7 Reorganize function parameters to not specify repeat types 2024-05-29 13:23:08 -04:00
RandyTheSilly 54fea00b9d Fix error when shearing without a device ID (offline mode) 2024-05-29 13:07:26 -04:00
RandyTheSilly 833eaa9926 Rename "hidePassword" to "hideSecrets" for clarity 2024-05-29 12:50:47 -04:00
RandyTheSilly 67bf6e42b9 Move TOTP secrets to a dedicated entry field (breaks sshyp entry format compatibility) 2024-05-21 19:21:42 -04:00
RandyTheSilly 637e718199 When syncing deletions, specify that a target is only sheared if it exists 2024-05-19 21:20:22 -04:00
RandyTheSilly 71f3a8d71f Format deletions messages to match new upload/download messages 2024-05-19 21:14:23 -04:00
RandyTheSilly 70e9ce34fc Set modification times during syncs - sync support is now usably functional 2024-05-19 21:04:07 -04:00
RandyTheSilly c7fee92ca4 Do not call sftpSync if no entries need to be uploaded/downloaded 2024-05-19 20:24:42 -04:00
RandyTheSilly dc4ecaecd8 Only call sftpSync once, as it now iterates over provided lists without the need to create a new sftp client for each entry 2024-05-19 20:20:02 -04:00
RandyTheSilly 912520ff1e Reduce size of server binary by not compiling SSH 2024-05-19 19:34:28 -04:00
RandyTheSilly 17d0e8bfcd Switch from SCP to SFTP for sync 2024-05-19 17:30:39 -04:00
RandyTheSilly 524b30cf1f Promote native sync to replace sshyp-based sync on all platforms 2024-05-17 19:49:49 -04:00
RandyTheSilly 9242b6caa0 Make server respond to "fetch" with output formatted for the client's OS family 2024-05-17 19:36:23 -04:00
RandyTheSilly df33a5b149 Fix building for Windows 2024-05-17 18:08:44 -04:00
RandyTheSilly 513ed74833 Implement initial SCP functionality (not yet usable due to mod times not being preserved) 2024-05-17 15:44:15 -04:00
RandyTheSilly a0ac99ff3c Ensure a device ID exists when sending a "fetch" command to libmuttonserver 2024-05-17 12:32:05 -04:00
RandyTheSilly d55ad76098 Fix import cycle (over SSH keyfile passphrase input) 2024-05-17 12:25:10 -04:00
RandyTheSilly 2a175d0c69 Handle instances where the server does not respond to "fetch" as expected 2024-05-17 11:48:06 -04:00
RandyTheSilly c7635a1ef0 Implement initial support for passphrase-protected SSH keyfiles 2024-05-17 11:42:44 -04:00
RandyTheSilly 774b761d25 Add help and version info for server binary 2024-05-16 22:22:12 -04:00
RandyTheSilly 193d577477 Remove pre-existing config directory during init, structure Windows config directory more similarly to UNIX 2024-05-16 21:40:02 -04:00
RandyTheSilly 578aa60b76 Move device ID generation to sync.DeviceIDGen 2024-05-16 21:26:42 -04:00
RandyTheSilly 8571faee94 When a folder is created on the client, also create it on the server 2024-05-16 21:15:16 -04:00
RandyTheSilly 1ca55b8ac6 Enable real sync deletions on client 2024-05-16 18:14:57 -04:00
RandyTheSilly 77726e9af3 Sync remote folders to client 2024-05-16 18:02:19 -04:00
RandyTheSilly 309ef84803 Parse deletions per-deviceID 2024-05-16 17:46:03 -04:00
RandyTheSilly 0faf2dc732 Implement device ID server registration and server-side init 2024-05-16 17:14:42 -04:00
RandyTheSilly 56e8dc613a Implement initial server-side shearing logic 2024-05-16 16:35:05 -04:00
RandyTheSilly 278c2c1fe4 Map entries to mod times from the beginning 2024-05-16 14:39:33 -04:00
RandyTheSilly 6b120930d0 Implement initial sorting/syncing logic - not yet complete or utilized 2024-05-15 18:36:37 -04:00
RandyTheSilly 170a3e807f Bump dependencies 2024-05-15 17:14:36 -04:00
RandyTheSilly 8a7d41df04 Check against ~/.ssh/known_hosts 2024-05-15 17:12:09 -04:00
RandyTheSilly 6587bda17b Better fetch remote data in a way that does not add blank items to slices 2024-05-15 16:57:46 -04:00
RandyTheSilly 3a03fae9ee Implement initial server-side code 2024-05-15 16:25:42 -04:00
RandyTheSilly 5e83178046 Implement initial SSH data retrieval 2024-05-15 14:58:21 -04:00
RandyTheSilly f86c2d8153 Initial groundwork for native sync support 2024-05-11 20:52:38 -04:00
RandyTheSilly 3acaa607e4 Prepare to tag v0.1.0 2024-04-16 11:33:06 -04:00
RandyTheSilly d4360c06ba Merge EditEntryNote into EditEntryField 2024-04-16 11:20:22 -04:00
RandyTheSilly 2cf786b2d7 Refactor for better modularity (share more code among edit functions, rename "offline" package to "backend" 2024-04-15 18:16:05 -04:00
RandyTheSilly b784fd8bd7 Strip trailing whitespace from each line in notes before saving 2024-04-15 16:52:16 -04:00
RandyTheSilly 7d272f77ca Use gruvbox colors for version info graphic 2024-04-12 21:32:06 -04:00
RandyTheSilly 424aa61c46 Move initial directory indentation multiplier determination to be with rest of indentation logic 2024-04-12 16:00:34 -04:00
RandyTheSilly bff179e881 Show total entry count in entry list 2024-04-12 11:32:25 -04:00
RandyTheSilly 65b622d465 Bump dependencies 2024-04-12 11:16:34 -04:00
RandyTheSilly b7bfdbf62f (Markdown) Improve consistency of in-line code and block quote colors (block quotes are currently busted) 2024-04-11 16:46:31 -04:00
RandyTheSilly 1e2f1dea7e (Markdown) Reduce quantity of "+" in lower-tier headings 2024-04-11 16:15:12 -04:00
RandyTheSilly 5d83e912ac (Markdown) Fix definitions lists, set color for HR, images 2024-04-11 16:10:44 -04:00
RandyTheSilly b11e8bbcf2 (Markdown) Make code block syntax highlighting more consistent with gruvbox 2024-04-11 15:45:41 -04:00
RandyTheSilly d07a4cc398 (Markdown) Make headers more aesthetically pleasing 2024-04-11 14:49:13 -04:00
RandyTheSilly 67420b0713 (Markdown) Add new, more consistent header design 2024-04-10 22:30:42 -04:00
RandyTheSilly ff10d843ad (Markdown) More clearly identify code blocks 2024-04-10 21:32:17 -04:00
RandyTheSilly 0392cf6fea (Markdown) Use full terminal width for horizontal rulers 2024-04-10 20:16:39 -04:00
RandyTheSilly 804fc29087 Lay groundwork for multiple color-scheme support 2024-04-10 17:03:37 -04:00
RandyTheSilly d29da29018 Wrap markdown text at full terminal width 2024-04-05 18:48:48 -04:00
RandyTheSilly 7c5c2105f9 Do not surround in-line code with spaces 2024-04-05 15:37:02 -04:00
RandyTheSilly b4919f0e82 Support hard line breaks in markdown notes 2024-04-05 14:18:35 -04:00
RandyTheSilly 0ee803dc78 Break out of switch after printing notes (no need to check additional lines) 2024-04-05 12:57:57 -04:00
RandyTheSilly ed9e9a3af8 Build default Glamour style into binary 2024-04-04 19:57:22 -04:00
RandyTheSilly 2668b2951c Commit WIP glamour style 2024-04-04 18:28:40 -04:00
RandyTheSilly 4e131d2870 Implement initial markdown notes support with Glamour (buggy, not ready for daily use) 2024-04-04 18:26:32 -04:00
RandyTheSilly 498ecd9a50 Implement Steam TOTP support using github.com/fortis/go-steam-totp 2024-03-22 20:53:08 -04:00
RandyTheSilly 8f98f1b61c Only fetch current time once per refresh for TOTP code generation 2024-03-21 14:44:58 -04:00
RandyTheSilly ad7524f544 Split TOTP key generation into its own function 2024-03-20 18:10:35 -04:00
RandyTheSilly 0687ce0954 Do not check time/refresh TOTP every second - calculate time till next 30-second interval, instead 2024-03-18 19:17:47 -04:00
RandyTheSilly ca14abbae9 Advertise TOTP support in printInfo.go, add to shell completions 2024-03-18 18:38:42 -04:00
RandyTheSilly 3171d1c1cd Update README.md with current progress 2024-03-18 17:03:19 -04:00
RandyTheSilly c1a415e5b0 Implement initial TOTP support (secret in third notes line, will eventually have its own dedicated field) 2024-03-18 16:44:22 -04:00
RandyTheSilly 56eaec02c6 Add "help" fallback to PowerShell completions 2024-03-18 15:21:29 -04:00
RandyTheSilly e4de8f930b Do not auto-complete directories in shell completions (only entries) 2024-03-18 14:39:55 -04:00
RandyTheSilly 26a5898e15 Better document new blank option="password" shortcut, order arguments in order of expected use, list passwords first in entry reader 2024-03-18 12:59:18 -04:00
RandyTheSilly dd0d1ffe55 Revert use of ":" for options on Windows, use "-" but replace "-p" with "-pw" to avoid ambiguity, interpret no options as "password" 2024-03-17 17:32:13 -04:00
RandyTheSilly ff9092bc9f Fix slice bounds errors when editing notes on short entries 2024-03-17 15:59:47 -04:00
RandyTheSilly 279384ee4a Allow passing show flag arguments with PowerShell completions 2024-03-15 14:57:46 -04:00
RandyTheSilly 7e5823c35e Do not require a pre-existing entry name for PowerShell completions 2024-03-14 18:33:22 -04:00
RandyTheSilly 80e4148b9b Switch Windows to use ":" instead of "-" for options flags because PowerShell is horrible and interprets "-" as a named parameter 2024-03-14 17:01:12 -04:00
RandyTheSilly 02fb625230 Correctly handle entry names with spaces in PowerShell completion 2024-03-14 15:59:03 -04:00
RandyTheSilly fb984f4514 Call mutn.exe from PowerShell completion function 2024-03-14 14:47:49 -04:00
RandyTheSilly 148212b276 Implement initial PowerShell 6.0+ tab-completions (missing help fallback, show) 2024-03-13 15:40:35 -04:00
RandyTheSilly 5cee48d412 Fix complex strings failing to copy on Windows 2024-03-11 15:09:30 -04:00
RandyTheSilly c7735d32be Specify that "mutn init" generates libmutton.ini 2024-03-08 13:15:16 -05:00
RandyTheSilly 2252be1463 Use panic in editNote to prevent temp files from being left behind 2024-03-08 12:57:10 -05:00
RandyTheSilly edf1a4cd9a Strip carriage returns from user input 2024-03-08 12:48:19 -05:00
RandyTheSilly 82b4fbee64 Properly close files to fix various issues on Windows (fixes GPG keygen, note temp files not being deleted) 2024-03-08 12:19:05 -05:00
RandyTheSilly 404f24d361 Better sanitize user input in inputInt 2024-03-08 11:23:08 -05:00
RandyTheSilly f83bdb9bdb Disable sshyp-sync-shim on Windows 2024-03-08 10:43:00 -05:00
RandyTheSilly f35d1b3741 Add current UNIX timestamp to generated GPG ID, identify key based on it 2024-03-08 10:36:01 -05:00
RandyTheSilly a0ca7803f1 Manually select auto-generated GPG key due to inconsistent GPG output, use tempfile for gpg-gen 2024-03-08 00:46:22 -05:00
RandyTheSilly 431082f711 Better detect if fallback editor needs to be used 2024-03-07 23:51:34 -05:00
RandyTheSilly 652ef48dd5 Prevent EntryListGen errors from appearing in-line with header 2024-03-07 23:46:19 -05:00
RandyTheSilly b01e5bded4 Exit after errors in EntryListGen 2024-03-07 23:43:35 -05:00
RandyTheSilly 31bc17cb0d Remove the gpg-gen file after use 2024-03-07 23:40:35 -05:00
RandyTheSilly 5a12eaf4cf Allow automatic generation of GPG keys 2024-03-07 23:35:38 -05:00
RandyTheSilly 7d17af9b61 Allow picking GPG key ID from a generated list 2024-03-07 22:48:57 -05:00
RandyTheSilly c6ee5fff06 Implement temporary "init" functionality 2024-03-07 22:12:38 -05:00
RandyTheSilly aa1098d472 Fixed indentation in main help menu for "edit -r" 2024-03-07 20:38:25 -05:00
RandyTheSilly 148ee53073 Add TEMPORARY sshyp-sync shim so that MUTN can be tested while native sync is under development 2024-03-07 20:35:24 -05:00
RandyTheSilly 408cff1a79 Replace TODO comment to correspond with learned information 2024-03-07 20:20:30 -05:00
RandyTheSilly 22758460ab Implement note editing 2024-03-07 20:15:01 -05:00
RandyTheSilly 3a90bef48a Allow generating new passwords for existing entries 2024-03-07 19:09:23 -05:00
RandyTheSilly 300516c3cd Implement initial entry editing support (no notes editing or gen update) 2024-03-07 18:34:12 -05:00
RandyTheSilly 9f1955eb82 Implement entry/directory renaming/moving 2024-03-07 17:40:57 -05:00
RandyTheSilly 609ef9bd8c Do not print redundant newline after creating a notes-only entry 2024-03-07 16:09:54 -05:00
RandyTheSilly 1e1a26b098 Implement password generation on new entries 2024-03-07 16:04:46 -05:00
RandyTheSilly 22fcad2fed Implement error messages for missing key values in libmutton.ini 2024-03-07 13:07:24 -05:00
RandyTheSilly b1f3a9eeec Properly set config file path on Windows 2024-03-07 12:34:50 -05:00
RandyTheSilly d6443c1966 Do not allow creating empty entries 2024-03-07 12:13:31 -05:00
RandyTheSilly 56ffe7e36f Allow optionally adding notes to new password entries 2024-03-07 12:01:49 -05:00
RandyTheSilly 14b3d7bd45 More correctly use build constraints in entryList.go 2024-03-06 20:45:02 -05:00
RandyTheSilly 11644b37ff Implement notes editor (required rewrite of offline.ReadConfig) 2024-03-05 17:11:53 -05:00
RandyTheSilly 1580227007 Implement initial entry adding (partial, missing notes support) 2024-03-05 14:09:50 -05:00
RandyTheSilly 85067fef40 Implement offline shearing/removal 2024-03-05 12:29:10 -05:00
RandyTheSilly 8704ba6972 Implement ability to add folders/directories (offline) 2024-03-05 11:52:33 -05:00
RandyTheSilly dfe917a4ff Implement Termux clipboard support 2024-03-05 10:47:41 -05:00
RandyTheSilly 24b899a83a Greatly reduce code duplication in clipboard implementations 2024-03-03 23:26:39 -05:00
RandyTheSilly 6fecf5a686 Move "clipclear" argument functionality to offline function to better facilitate third-party implementations 2024-03-03 22:47:58 -05:00
RandyTheSilly 0e6210f1af Implement untested MacOS clipboard support via pbcopy 2024-03-03 22:36:20 -05:00
RandyTheSilly 207a4762b6 Handle errors resulting from failed decryption 2024-03-03 22:15:35 -05:00
RandyTheSilly 0f65cd31cb Implement errors for copying entry fields that do not exist or are blank 2024-03-03 22:02:51 -05:00
RandyTheSilly 988724bac6 Handle errors when running clipboard-related commands with exec 2024-03-03 21:24:29 -05:00
RandyTheSilly 9802b7498b Implement X11 clipboard support via xclip 2024-03-03 20:58:51 -05:00
RandyTheSilly 00e0a70ee6 Fix clipboard clearing on Windows 2024-03-03 19:57:45 -05:00
RandyTheSilly 7a17df4aa3 Implement clipboard support for Windows 2024-03-03 19:09:25 -05:00
RandyTheSilly 3d621f5e38 Implement clipboard clearing functionality on Wayland 2024-03-02 00:12:55 -05:00
RandyTheSilly 4bd44e7b44 Implement initial clipboard functionality for Wayland 2024-03-01 22:36:10 -05:00
RandyTheSilly b17a3ae372 Implement password hiding in entry readouts 2024-03-01 22:11:59 -05:00
RandyTheSilly 51313eb307 Re-write argument parsing, implement skeleton of copy functionality 2024-03-01 21:09:56 -05:00
RandyTheSilly 0afcdbb29b Implement initial entry readout formatting 2024-03-01 18:26:05 -05:00
RandyTheSilly cefb91f1f6 Implement initial GPG decryption 2024-03-01 15:55:21 -05:00
RandyTheSilly fc2a6ab22f Do not trim file extensions from entries (file extensions are no longer expected) 2024-03-01 14:07:53 -05:00
RandyTheSilly 7d5bd76489 Fix initial entry reader shortcut on Windows 2024-03-01 13:47:28 -05:00
RandyTheSilly adcc05f3f4 Initial read shortcut support (target status checking) 2024-02-29 12:12:11 -05:00
RandyTheSilly ba89fbeab6 Replace remaining ANSI escape codes with constants 2024-02-27 12:01:35 -05:00
RandyTheSilly fa6d5bc78a Implement ReadConfig for reading ~/.config/libmutton/libmutton.ini 2024-02-27 11:48:02 -05:00
RandyTheSilly 86b152875e Fix awkward wording, clarify extension support 2024-02-26 17:16:09 -05:00
RandyTheSilly e61beb3f94 Split into separate packages 2024-02-26 16:58:39 -05:00
RandyTheSilly b26a29dd3d Implement argument-specific help menus 2024-02-12 16:54:49 -05:00
RandyTheSilly 9f5cf7fd1e Isolate trimmed/"vanity" directory from "directory" to avoid incorrect processing 2024-01-30 22:18:56 -05:00
RandyTheSilly 2012e332f3 Fix incorrect method of simplifying directory headers 2024-01-30 22:06:46 -05:00
RandyTheSilly 00ec6417af Use PathSeparator when simplifying indented directory headers 2024-01-23 16:48:16 -05:00
RandyTheSilly e54fef3d74 For indented directory headers, only print the new portion of the header 2024-01-23 16:35:05 -05:00
RandyTheSilly fc48c1dd21 Optimize some if-statements 2024-01-23 15:21:14 -05:00
RandyTheSilly 2d55d10d17 Remove all global variables (slices) only used in entryList.go 2024-01-23 14:58:32 -05:00
RandyTheSilly c2618088c6 Reduce unneeded iterations in indentSubtractor 2024-01-23 14:08:20 -05:00
RandyTheSilly 08689a4013 Replace version info heart with a slab of mutton 2024-01-22 17:04:30 -05:00
RandyTheSilly cb5dc659f2 Center all text on version info screen 2024-01-22 10:29:22 -05:00
RandyTheSilly b4848b6db6 Take row indentation into account when deciding to do line wrapping 2024-01-21 21:49:14 -05:00
RandyTheSilly c279711120 Adjust visual indentation for skipped directories 2024-01-21 21:41:04 -05:00
RandyTheSilly 4092b4f737 Fix indentation with multiple rows of entries, fix errors with negative indentation multiplier 2024-01-21 16:24:17 -05:00
RandyTheSilly e31878bd7d Use better method of error type detection 2024-01-19 21:40:39 -05:00
RandyTheSilly 6b4891a59f Assign ANSI escape colors to named constants 2024-01-19 21:36:48 -05:00
RandyTheSilly 29c9fb812c Clean up comments and re-organize variable declarations 2024-01-19 20:59:50 -05:00
RandyTheSilly 274aa4fcce Merge fileList slices into one, remove now-redundant loop 2024-01-19 20:47:14 -05:00
RandyTheSilly ed56b26cad Remove seemingly redundant sorting - revert if bugs are found 2024-01-19 20:27:48 -05:00
RandyTheSilly d3d9b2f764 Add initial support for indenting nested folders in the entry list 2024-01-19 20:10:28 -05:00
RandyTheSilly 5affff5def Remove nextStartIndex optimization that led to incorrect entry list generation in cases where a subdirectory's entry takes alphabetical priority over a current directory's entry 2024-01-18 00:03:56 -05:00
RandyTheSilly 9e7b6aa61d Make empty directory warning more visually distinct from errors 2024-01-17 23:13:08 -05:00
RandyTheSilly cd78442257 Automatically create the entry directory when printing the entry list (if it does not already exist) 2024-01-17 23:00:16 -05:00
RandyTheSilly 95eff67340 Replace redundancy copyright notice with "MIT License" header 2024-01-16 18:03:07 -05:00
RandyTheSilly 88b2bb51a3 Fix empty directory warning appearing for root if no subdirectories are present (but files are) 2024-01-16 17:56:24 -05:00
RandyTheSilly 6e4453c773 Fix build-constraint typos 2024-01-16 16:28:42 -05:00
RandyTheSilly af6600de80 Initial code commit 2024-01-16 14:35:34 -05:00
Randall Winkhart c20c8bc349 Initial commit 2024-01-16 12:33:11 -05:00
59 changed files with 2056 additions and 278 deletions
+3 -3
View File
@@ -1,6 +1,6 @@
/mutn
/mutn.exe
/main
/main.exe
/libmuttonserver
/libmuttonserver.exe
/version.go
1output
output
+19 -21
View File
@@ -2,7 +2,7 @@
---
Pronounced as: "mutton", "muh·tn"
MUTN is a simple, self-hosted, SSH-synchronized password and note manager based on [libmutton](https://github.com/rwinkhart/libmutton). It is the successor to [sshyp](https://github.com/rwinkhart/sshyp).
MUTN is a simple, self-hosted, SSH-synchronized password and note manager based on libmutton. It is the successor to [sshyp](https://github.com/rwinkhart/sshyp).
> [!WARNING]
>It is your responsibility to assess the security and stability of MUTN and to ensure it meets your needs before using it.
@@ -16,33 +16,31 @@ MUTN is a simple, self-hosted, SSH-synchronized password and note manager based
MUTN aims to make it as easy as possible to manage passwords and notes via CLI across multiple devices in a secure, self-hosted fashion.
# Installation/Building
See the [installation guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/install.md).
Additionally, MUTN is available as a source package ("[mutn](https://aur.archlinux.org/packages/mutn)") on the AUR.
After installing, please review the [usage guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/usage.md).
See the [installation guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/install.md).
# Roadmap
#### Release v0.2.1
- [ ] Only run getSSHClient once to prevent being asked for keyfile password multiple times
- [ ] After this, handle all errors in client.go
- [ ] Ensure all config files and entry files are created with 0600 permissions
- [ ] Add fail-specific error codes
- [ ] Split into separate repos
1. libmutton
2. libmutton-server
3. MUTN
#### Release v0.3.0
- [ ] Replace Glamour with a more minimal Markdown renderer (likely custom)
#### Release v0.4.0
- [ ] libmutton v0.3.0
- [ ] Swap to native (cascade) encryption (custom)
- [ ] Implement "netpin" (quick-unlock) with new encryption
- [ ] Swap to native (cascade) encryption (custom)
- [ ] Implement "netpin" (quick-unlock) with new encryption
#### Release v0.5.0
- [ ] libmutton v0.4.0
- [ ] Password aging support
- [ ] Password aging support
- [ ] Append UNIX timestamp to entry names
- [ ] Add yellow/red dot indicators to entry list readout for when passwords should be changed
#### Release v0.6.0
- [ ] libmutton v0.5.0
- [ ] Add refresh/re-encrypt functionality
- [ ] Re-implement init menu
- [ ] Implement tweak menu
#### Release v1.0.0
- [ ] Add refresh/re-encrypt functionality
#### Release v1.0.0 - Distribution packages
- [ ] Create packaging scripts
- [x] Stable source PKGBUILD
- [ ] Stable source APKBUILD
- [ ] Debian/Ubuntu
- [ ] Fedora
- [ ] FreeBSD
- [ ] Windows installer
- Hunt for polishing opportunities and bugs
- Perform extensive testing
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/sh
gofmt -l -w -s ./src/cli/*.go ./mutn.go
gofmt -l -w -s ./src/cli/*.go ./src/backend/*.go ./mutn.go ./libmuttonserver.go
git commit -am "$1"
git push
+3 -25
View File
@@ -1,4 +1,4 @@
.TH MUTN 1 "13 August 2024" "v0.2.1" "MUTN man page"
.TH MUTN 1 "06 August 2024" "v0.2.0" "MUTN man page"
.SH NAME
\fBmutn\fR - Simple, self-hosted, SSH-synchronized password and note management based on libmutton. It is the successor to sshyp.
@@ -144,30 +144,8 @@ Once this has been done, you may proceed with the client setup:
...and then restart your shell.
.SH EXIT CODES (defined by libmutton)
0: no error
101: read error
102: write error
103: sync process error
104: server connection error
105: target not found
106: target already exists
107: target wrong type (file/directory)
108: decryption error
109: encryption error
110: clipboard error
111: other error
.SH EXIT CODES
TBD
.SH AUTHOR
Randall Winkhart (https://github.com/rwinkhart)
+3 -37
View File
@@ -1,38 +1,4 @@
**WARNING: AS LIBMUTTON HAS NOT YET REACHED v1.0.0, [BREAKING CHANGES](https://github.com/rwinkhart/libmutton/blob/main/wiki/breaking.md) IN FUTURE UPDATES ARE PLANNED**
**MUTN v0.2.1**
Built with libmutton v0.2.1
August 13, 2024
# The Tripe Transmission Update - Patch 1
This release marks the completion of splitting MUTN and [libmutton](https://github.com/rwinkhart/libmutton) into separate repositories. The server binary must now be downloaded from the [libmutton releases page](https://github.com/rwinkhart/libmutton/releases).
Please see the [installation guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/install.md) for updated instructions.
## Breaking Changes
- The server binary must also be updated to v0.2.1 (grab it [here](https://github.com/rwinkhart/libmutton/releases/tag/v0.2.1))
## Features
- From libmutton v0.2.1:
- MUTN will now remove the previous device ID from the server when creating a new one
- Exit codes are now specific to the type of error encountered
## Fixes
- From libmutton v0.2.1:
- The user is no longer prompted for their ssh keyfile passphrase multiple times during synchronization
- Config/entry files are now created with 0600 permissions
- The TOTP copy message is no longer unnecessarily verbose
- Function documentation is now properly formatted for display on pkg.go.dev
## Dependencies
- Bumps (direct and indirect)
- golang.org/x/sys: v0.23.0 => v0.24.0
- New (direct)
- github.com/rwinkhart/libmutton: v0.2.1
- Was previously included in this repo
---
**WARNING: AS MUTN HAS NOT YET REACHED v1.0.0, [BREAKING CHANGES](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/breaking.md) IN FUTURE UPDATES ARE PLANNED**
**MUTN v0.2.0**
August 06, 2024
@@ -89,11 +55,11 @@ Compared to v0.1.0, this version adds fully native SSH synchronization with self
- github.com/pkg/sftp: v1.13.6
## Installation Notes
Though this is the initial public debut, it is still an overall early release of MUTN/libmutton. Because of this, no distribution packages are provided as of yet. MUTN is, however, available as a source package from the AUR as "mutn". Please see the [install guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/install.md) for help installing or building MUTN in its current state (as well as getting started).
Though this is the initial public debut, it is still an overall early release of MUTN/libmutton. Because of this, no distribution packages are provided as of yet. Please see the [install guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/install.md) for help installing or building MUTN in its current state (as well as getting started).
Note that libmuttonserver, libmutton, and MUTN have not yet been separated into their own respective repos (this will be done for v0.2.1). As such, libmuttonserver is built with the `noMarkdown` build tag to avoid pulling in Glamour and its dependencies.
It is highly recommended to also install the relevant [shell completions](https://github.com/rwinkhart/MUTN/blob/main/wiki/completions.md).
It is highly recommended to also install the relevant [shell completions](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/completions.md).
---
+6 -7
View File
@@ -4,8 +4,12 @@ go 1.22.6
require (
github.com/charmbracelet/glamour v0.7.0
github.com/rwinkhart/libmutton v0.2.1
github.com/fortis/go-steam-totp v0.0.0-20171114202746-18e928674727
github.com/pkg/sftp v1.13.6
github.com/pquerna/otp v1.4.1-0.20231130234153-3357de7c0481
golang.org/x/crypto v0.26.0
golang.org/x/term v0.23.0
gopkg.in/ini.v1 v1.67.0
)
require (
@@ -14,7 +18,6 @@ require (
github.com/aymerick/douceur v0.2.0 // indirect
github.com/boombuler/barcode v1.0.2 // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/fortis/go-steam-totp v0.0.0-20171114202746-18e928674727 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
@@ -24,14 +27,10 @@ require (
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pkg/sftp v1.13.6 // indirect
github.com/pquerna/otp v1.4.1-0.20231130234153-3357de7c0481 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/stretchr/testify v1.8.4 // indirect
github.com/yuin/goldmark v1.7.4 // indirect
github.com/yuin/goldmark-emoji v1.0.3 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sys v0.24.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
golang.org/x/sys v0.23.0 // indirect
)
+2 -4
View File
@@ -52,8 +52,6 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rwinkhart/libmutton v0.2.1 h1:J6tRCOJ22D3r0At7c1PnU5eHQkxxtrtue5b5lu/90Qw=
github.com/rwinkhart/libmutton v0.2.1/go.mod h1:W4xYquN2Hz5rNyaaIUZCMTLvTNcAx804f1Y4vaUBmiw=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
@@ -88,8 +86,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+92
View File
@@ -0,0 +1,92 @@
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/cli"
"github.com/rwinkhart/MUTN/src/sync"
)
func main() {
args := os.Args
if len(args) < 2 {
helpServer()
}
// check if stdin was provided
stdinInfo, _ := os.Stdin.Stat()
stdinPresent := stdinInfo.Mode()&os.ModeNamedPipe != 0
var stdin []string
if stdinPresent {
// read stdin, appending each line to the stdin slice
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
stdin = append(stdin, scanner.Text())
}
}
switch args[1] {
case "fetch":
// print all information needed for syncing to stdout for interpretation by the client
// stdin[0] is expected to be the device ID
sync.GetRemoteDataFromServer(stdin[0])
case "rename":
// move an entry to a new location before using fallthrough to add its previous iteration to the deletions directory
// stdin[0] is evaluated after fallthrough
// stdin[1] is expected to be the OLD incomplete target location with FSPath representing path separators - always pass in UNIX format
// stdin[2] is expected to be the NEW incomplete target location with FSPath representing path separators - always pass in UNIX format
sync.RenameLocal(strings.ReplaceAll(stdin[1], sync.FSPath, "/"), strings.ReplaceAll(stdin[2], sync.FSPath, "/"), true)
fallthrough // fallthrough to add the old entry to the deletions directory
case "shear":
// shear an entry from the server and add it to the deletions directory
// stdin[0] is expected to be the device ID
// stdin[1] is expected to be the incomplete target location with FSPath representing path separators - always pass in UNIX format
sync.ShearLocal(strings.ReplaceAll(stdin[1], sync.FSPath, "/"), stdin[0])
case "addfolder":
// add a new folder to the server
// stdin[0] is expected to be the incomplete target location with FSPath representing path separators - always pass in UNIX format
sync.AddFolderLocal(strings.ReplaceAll(stdin[0], sync.FSPath, "/"))
case "register":
// register a new device ID
// stdin[0] is expected to be the device ID
_, _ = os.Create(backend.ConfigDir + backend.PathSeparator + "devices" + backend.PathSeparator + stdin[0]) // error ignored; failure unlikely to occur if init was successful; "register" is not a user-facing argument and thus the error would not be visible
// print EntryRoot and bool indicating OS type to stdout for client to store in config
fmt.Print(backend.EntryRoot + sync.FSSpace + strconv.FormatBool(backend.IsWindows))
case "init":
// create the necessary directories for libmuttonserver to function
backend.DirInit(false)
_ = os.MkdirAll(backend.ConfigDir+backend.PathSeparator+"deletions", 0700) // error ignored; failure would have occurred by this point in backend.DirInit
fmt.Println("libmuttonserver directories initialized")
case "version":
versionServer()
default:
helpServer()
}
}
func helpServer() {
fmt.Print(cli.AnsiBold + "\nlibmuttonserver | Copyright (c) 2024 Randall Winkhart\n" + backend.AnsiReset + `
This software exists under the MIT license; you may redistribute it under certain conditions.
This program comes with absolutely no warranty; type "libmuttonserver version" for details.
` + cli.AnsiBold + "Usage:" + backend.AnsiReset + ` libmuttonserver <argument>
` + cli.AnsiBold + "Arguments (user):" + backend.AnsiReset + `
help Bring up this menu
version Display version and license information
init Create the necessary directories for libmuttonserver to function` + "\n\n")
os.Exit(0)
}
func versionServer() {
cli.MITLicense()
fmt.Print(cli.AnsiBold + "\n\n libmuttonserver" + backend.AnsiReset + " Version " + backend.LibmuttonVersion + `
Copyright (c) 2024 Randall Winkhart` + "\n\n")
}
+9 -9
View File
@@ -5,9 +5,9 @@ import (
"os"
"strings"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/cli"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/libmutton/sync"
"github.com/rwinkhart/MUTN/src/sync"
)
func main() {
@@ -25,7 +25,7 @@ func main() {
if strings.HasPrefix(args[1], "/") {
// store location of target entry
targetLocation := core.TargetLocationFormat(args[1])
targetLocation := backend.TargetLocationFormat(args[1])
// entry reader shortcut (if no other arguments are supplied)
if argsCount == 2 {
@@ -38,7 +38,7 @@ func main() {
case "show", "-s":
cli.EntryReaderDecrypt(targetLocation, false)
case "copy":
core.CopyArgument(args[0], targetLocation, 0)
backend.CopyArgument(args[0], targetLocation, 0)
case "edit":
cli.EditEntryField(targetLocation, true, 0)
case "gen":
@@ -82,7 +82,7 @@ func main() {
default:
cli.HelpCopy()
}
core.CopyArgument(args[0], targetLocation, field)
backend.CopyArgument(args[0], targetLocation, field)
case "edit":
var field int // indicates which (numbered) field to edit
switch args[3] {
@@ -97,8 +97,8 @@ func main() {
case "note", "-n":
field = 4
case "rename", "-r":
core.TargetIsFile(targetLocation, true, 0) // ensure location exists before prompting for new location
cli.RenameCli(args[1]) // pass the incomplete path as the server and all clients (reading from the deletions directory) will have a different home directory
backend.TargetIsFile(targetLocation, true, 0) // ensure location exists before prompting for new location
cli.RenameCli(args[1]) // pass the incomplete path as the server and all clients (reading from the deletions directory) will have a different home directory
default:
cli.HelpEdit()
}
@@ -158,13 +158,13 @@ func main() {
} else {
switch args[1] {
case "clipclear":
core.ClipClearArgument()
backend.ClipClearArgument()
case "sync":
sync.RunJob(true)
case "init":
cli.TempInitCli()
case "tweak":
fmt.Println(core.AnsiError + "\"tweak\" is not yet implemented" + core.AnsiReset)
fmt.Println(backend.AnsiError + "\"tweak\" is not yet implemented" + backend.AnsiReset)
os.Exit(0)
case "copy":
cli.HelpCopy()
+6 -10
View File
@@ -1,9 +1,9 @@
#!/bin/sh
# get version number from cli package
# get version number from LibmuttonVersion
cd ..
printf 'package main\nimport (\n"fmt"\n"github.com/rwinkhart/MUTN/src/cli"\n)\nfunc main() {\nfmt.Println(cli.MUTNVersion)\n}' > ./version.go
version=$(go run -ldflags="-s -w" -tags noMarkdown ./version.go)
printf 'package main\nimport (\n"fmt"\n"github.com/rwinkhart/MUTN/src/backend"\n)\nfunc main() {\nfmt.Println(backend.LibmuttonVersion)\n}' > ./version.go
version=$(go run ./version.go)
rm ./version.go
cd ./packaging
@@ -15,18 +15,14 @@ else
fi
# ensure output directory exists
mkdir -p ./1output
mkdir -p ./output
case "$1" in
release-binaries)
. ./resources/release-binaries.sh
create_release_binaries
;;
pkgbuild-git-stable)
. ./resources/pkgbuild-git-stable.sh
. ./pkgbuild-git-stable.sh
create_pkgbuild_git_stable
;;
*)
printf '\nusage: package.sh [target] <revision>\n\ntargets: release-binaries pkgbuild-git-stable\n\n'
printf '\nusage: package.sh [target] <revision>\n\ntargets: pkgbuild-git-stable\n\n'
;;
esac
@@ -1,17 +1,17 @@
#!/bin/sh
create_pkgbuild_git_stable() {
printf '\nGenerating PKGBUILD...\n'
printf '\ngenerating PKGBUILD...\n'
local source="git+https://github.com/rwinkhart/MUTN.git#tag=v\${pkgver}"
printf "# Maintainer: Randall Winkhart <idgr at tutanota dot com>
pkgname=mutn
pkgver="$version"
pkgrel="$revision"
pkgdesc='A simple, self-hosted, SSH-synchronized password/note manager for the CLI (based on libmutton)'
pkgdesc='A simple, self-hosted, SSH-synchronized password/note manager based on libmutton'
arch=('x86_64' 'i686' 'i486' 'pentium4' 'aarch64' 'armv7h' 'riscv64')
url='https://github.com/rwinkhart/MUTN'
license=('MIT')
makedepends=(go util-linux gzip)
makedepends=(go util-linux)
optdepends=(
'wl-clipboard: Wayland clipboard support'
'xclip: X11 clipboard support'
@@ -21,20 +21,15 @@ source=(\""$source"\")
sha512sums=(SKIP)
build() {
cd \${srcdir}/MUTN
# compress man page
gzip -kf ./docs/man
# determine microarchitecture feature level
case \$CARCH in
'x86_64')
lscpuOutput=\$(lscpu | grep Flags)
if [ ! -z \"\$(echo \$lscpuOutput | grep avx512f)\" ]; then
if [ -z \"\$(echo \$lscpuOutput | grep avx512f)\" ]; then
export GOAMD64=v4
elif [ ! -z \"\$(echo \$lscpuOutput | grep avx2)\" ]; then
elif [ -z \"\$(echo \$lscpuOutput | grep avx2)\" ]; then
export GOAMD64=v3
elif [ ! -z \"\$(echo \$lscpuOutput | grep sse4_2)\" ]; then
elif [ -z \"\$(echo \$lscpuOutput | grep sse4_2)\" ]; then
export GOAMD64=v2
else
export GOAMD64=v1
@@ -43,7 +38,7 @@ build() {
# TODO check aarch64 feature level
esac
# compile binary
cd \${srcdir}/MUTN
CGO_ENABLED=1 go build -ldflags=\"-s -w\" -trimpath ./mutn.go
}
@@ -53,8 +48,7 @@ package() {
install -Dm644 ./LICENSE \${pkgdir}/usr/share/licenses/mutn/LICENSE
install -Dm644 ./completions/zsh/_mutn \${pkgdir}/usr/share/zsh/site-functions/_mutn
install -Dm644 ./completions/bash/mutn \${pkgdir}/usr/share/bash-completion/completions/mutn
install -Dm644 ./docs/man.gz \${pkgdir}/usr/share/man/man1/mutn.1.gz
}
" > 1output/PKGBUILD
" > output/PKGBUILD
printf '\nPKGBUILD generated\n\n'
}
-11
View File
@@ -1,11 +0,0 @@
#!/bin/sh
create_release_binaries() {
printf '\nGenerating release binaries...\n'
cd ..
GOOS=linux CGO_ENABLED=0 GOAMD64=v1 go build -o ./packaging/1output/mutn-linux-x86_64_v1 -ldflags="-s -w" -trimpath ./mutn.go
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o ./packaging/1output/mutn-linux-aarch64 -ldflags="-s -w" -trimpath ./mutn.go
GOOS=windows CGO_ENABLED=0 GOAMD64=v1 go build -o ./packaging/1output/mutn-windows-x86_64_v1.exe -ldflags="-s -w" -trimpath ./mutn.go
GOOS=windows GOARCH=arm64 CGO_ENABLED=0 go build -o ./packaging/1output/mutn-windows-aarch64.exe -ldflags="-s -w" -trimpath ./mutn.go
cd ./packaging
}
+17
View File
@@ -0,0 +1,17 @@
package backend
import (
"os"
)
// global variables used across multiple files
var (
Home, _ = os.UserHomeDir()
)
// global constants used across multiple files
const (
AnsiError = "\033[38;5;9m"
AnsiReset = "\033[0m"
LibmuttonVersion = "0.2.0" // untagged releases feature a letter suffix corresponding to the eventual release version, e.g "0.2.A" -> "0.2.0", "0.2.B" -> "0.2.1"
)
+20
View File
@@ -0,0 +1,20 @@
//go:build !windows
package backend
// EntryRoot path to libmutton entry directory
var EntryRoot = Home + "/.local/share/libmutton"
var ConfigDir = Home + "/.config/libmutton"
var ConfigPath = ConfigDir + "/libmutton.ini"
// PathSeparator defines the character used to separate directories in a path (platform-specific)
const (
PathSeparator = "/"
IsWindows = false
)
// enableVirtualTerminalProcessing is a dummy function on UNIX-like systems (only needed on Windows)
// TODO remove after migration off of GPG, as pinentry is responsible for disabling ANSI escape sequence interpretation
func enableVirtualTerminalProcessing() {
return
}
+31
View File
@@ -0,0 +1,31 @@
//go:build windows
package backend
import (
"os"
"syscall"
)
// EntryRoot path to libmutton entry directory
var EntryRoot = Home + "\\AppData\\Local\\libmutton\\entries"
var ConfigDir = Home + "\\AppData\\Local\\libmutton\\config"
var ConfigPath = ConfigDir + "\\libmutton.ini"
// PathSeparator defines the character used to separate directories in a path (platform-specific)
const (
PathSeparator = "\\"
IsWindows = true
)
// enableVirtualTerminalProcessing ensures ANSI escape sequences are interpreted properly on Windows
// TODO remove after migration off of GPG, as pinentry is responsible for disabling ANSI escape sequence interpretation
func enableVirtualTerminalProcessing() {
stdout := syscall.Handle(os.Stdout.Fd())
var originalMode uint32
syscall.GetConsoleMode(stdout, &originalMode)
originalMode |= 0x0004
syscall.MustLoadDLL("kernel32").MustFindProc("SetConsoleMode").Call(uintptr(stdout), uintptr(originalMode))
}
+86
View File
@@ -0,0 +1,86 @@
package backend
import (
"fmt"
"os"
"gopkg.in/ini.v1"
)
// loadConfig loads the libmutton.ini file and returns the configuration
// utility function for ParseConfig and WriteConfig, do not call directly
func loadConfig() *ini.File {
cfg, err := ini.Load(ConfigPath)
if err != nil {
fmt.Println(AnsiError + "Failed to load libmutton.ini: " + err.Error() + AnsiReset)
os.Exit(1)
}
return cfg
}
// ParseConfig reads the libmutton.ini file and returns a slice of values for the specified keys
// requires requestedValues: a slice of arrays (length 2) each containing a section and a key name
// requires missingValueError: an error message to display if a key is missing a value, set to "" for auto-generated or "0" to exit/return silently with code 0
// returns config: a slice of values for the specified keys
func ParseConfig(valuesRequested [][2]string, missingValueError string) []string {
cfg := loadConfig()
var config []string
for _, pair := range valuesRequested {
value := cfg.Section(pair[0]).Key(pair[1]).String()
// ensure specified key has a value
if value == "" {
switch missingValueError {
case "":
fmt.Println(AnsiError + "Failed to find value for key \"" + pair[1] + "\" in section \"[" + pair[0] + "]\" in libmutton.ini" + AnsiReset)
case "0":
Exit(0)
default:
fmt.Println(AnsiError + missingValueError + AnsiReset)
}
os.Exit(1)
}
config = append(config, value)
}
return config
}
// WriteConfig writes the provided key-value pairs under the specified section headers in the libmutton.ini file
// requires valuesToWrite: a slice of arrays (length 3) each containing a section, a key name, and a value
func WriteConfig(valuesToWrite [][3]string, append bool) {
var cfg *ini.File
if append {
// load existing ini file
cfg = loadConfig()
} else {
// create empty ini container
cfg = ini.Empty()
}
// set all specified key-value pairs in their respective sections
var section *ini.Section
for _, trio := range valuesToWrite {
if cfg.Section(trio[0]) == nil {
// create and aquire section if it doesn't exist
section, _ = cfg.NewSection(trio[0])
} else {
// acquire existing section
section = cfg.Section(trio[0])
}
// set key-value pair
section.Key(trio[1]).SetValue(trio[2])
}
// save to libmutton.ini
err := cfg.SaveTo(ConfigPath)
if err != nil {
fmt.Println(AnsiError + "Failed to save libmutton.ini: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
+91
View File
@@ -0,0 +1,91 @@
package backend
import (
"bufio"
"fmt"
"os"
"strings"
"time"
steamtotp "github.com/fortis/go-steam-totp"
"github.com/pquerna/otp/totp"
)
// CopyArgument copies a field from an entry to the clipboard
func CopyArgument(executableName, targetLocation string, field int) {
if isFile, _ := TargetIsFile(targetLocation, true, 2); isFile {
decryptedEntry := DecryptGPG(targetLocation)
var copySubject string // will store data to be copied
// ensure field exists in entry
if len(decryptedEntry) > field {
// ensure field is not empty
if decryptedEntry[field] == "" {
fmt.Println(AnsiError + "Field is empty" + AnsiReset)
os.Exit(1)
}
if field != 2 {
copySubject = decryptedEntry[field]
} else { // TOTP mode
var secret string // stores secret for TOTP generation
var forSteam bool // indicates whether to generate TOTP in Steam format
if strings.HasPrefix(decryptedEntry[2], "steam@") {
secret = decryptedEntry[2][6:]
forSteam = true
} else {
secret = decryptedEntry[2]
}
fmt.Println("TOTP code has been copied to the clipboard - your clipboard will be kept up to date with the current code until this process is closed")
for { // keep field copied to clipboard, refresh on 30-second intervals
currentTime := time.Now()
copyField("", GenTOTP(secret, currentTime, forSteam))
// sleep until next 30-second interval
time.Sleep(time.Duration(30-(currentTime.Second()%30)) * time.Second)
}
}
} else {
fmt.Println(AnsiError + "Field does not exist in entry" + AnsiReset)
os.Exit(1)
}
// copy field to clipboard, launch clipboard clearing process
copyField(executableName, copySubject)
}
}
// ClipClearArgument is called to clear the clipboard after 30 seconds if the contents have not been modified
func ClipClearArgument() {
// read previous clipboard contents from stdin
clipScanner := bufio.NewScanner(os.Stdin)
if clipScanner.Scan() {
oldContents := clipScanner.Text()
clipClear(oldContents)
} else {
os.Exit(0) // use os.Exit instead of backend.Exit, as this function runs out of a background subprocess that is invisible to the user (will never appear in GUI/TUI environment)
}
}
// GenTOTP generates a TOTP token from a secret (supports standard and Steam TOTP)
func GenTOTP(secret string, time time.Time, forSteam bool) string {
var totpToken string
var err error
if forSteam {
totpToken, err = steamtotp.GenerateAuthCode(secret, time)
} else {
totpToken, err = totp.GenerateCode(secret, time)
}
if err != nil {
fmt.Println(AnsiError + "Error generating TOTP code" + AnsiReset)
os.Exit(1)
}
return totpToken
}
+59
View File
@@ -0,0 +1,59 @@
//go:build darwin
package backend
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// TODO MacOS support is entirely untested - I would appreciate feedback on this implementation
// copyField copies a field from an entry to the clipboard
func copyField(executableName, copySubject string) {
cmd := exec.Command("pbcopy")
writeToStdin(cmd, copySubject)
err := cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to copy to clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
// launch clipboard clearing process if executableName is provided
if executableName != "" {
cmd = exec.Command(executableName, "clipclear")
writeToStdin(cmd, copySubject)
err = cmd.Start()
if err != nil {
fmt.Println(AnsiError + "Failed to launch automated clipboard clearing process - does this libmutton implementation support the \"clipclear\" argument?" + AnsiReset)
os.Exit(1)
}
Exit(0) // only exit if clipboard clearing process is launched, otherwise assume continuous clipboard refresh
}
}
// clipClear is called in a separate process to clear the clipboard after 30 seconds
func clipClear(oldContents string) {
time.Sleep(30 * time.Second)
cmd := exec.Command("pbpaste")
newContents, err := cmd.Output()
if err != nil {
fmt.Println(AnsiError + "Failed to read clipboard contents: " + err.Error() + AnsiReset)
os.Exit(1)
}
if oldContents == strings.TrimRight(string(newContents), "\r\n") {
cmd = exec.Command("pbcopy")
writeToStdin(cmd, "")
err = cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to clear clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
os.Exit(0) // use os.Exit instead of backend.Exit, as this function runs out of a background subprocess that is invisible to the user (will never appear in GUI/TUI environment)
}
+57
View File
@@ -0,0 +1,57 @@
//go:build linux && termux
package backend
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// copyField copies a field from an entry to the clipboard
func copyField(executableName, copySubject string) {
cmd := exec.Command("termux-clipboard-set")
writeToStdin(cmd, copySubject)
err := cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to copy to clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
// launch clipboard clearing process if executableName is provided
if executableName != "" {
cmd = exec.Command(executableName, "clipclear")
writeToStdin(cmd, copySubject)
err = cmd.Start()
if err != nil {
fmt.Println(AnsiError + "Failed to launch automated clipboard clearing process - does this libmutton implementation support the \"clipclear\" argument?" + AnsiReset)
os.Exit(1)
}
Exit(0) // only exit if clipboard clearing process is launched, otherwise assume continuous clipboard refresh
}
}
// clipClear is called in a separate process to clear the clipboard after 30 seconds
func clipClear(oldContents string) {
time.Sleep(30 * time.Second)
cmd := exec.Command("termux-clipboard-get")
newContents, err := cmd.Output()
if err != nil {
fmt.Println(AnsiError + "Failed to read clipboard contents: " + err.Error() + AnsiReset)
os.Exit(1)
}
if oldContents == strings.TrimRight(string(newContents), "\r\n") {
cmd = exec.Command("termux-clipboard-set")
writeToStdin(cmd, "")
err = cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to clear clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
os.Exit(0) // use os.Exit instead of backend.Exit, as this function runs out of a background subprocess that is invisible to the user (will never appear in GUI/TUI environment)
}
+81
View File
@@ -0,0 +1,81 @@
//go:build !windows && !darwin && !termux && !wsl
package backend
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// copyField copies a field from an entry to the clipboard
func copyField(executableName, copySubject string) {
var envSet bool // track whether environment variables are set
var cmd *exec.Cmd
// determine whether to use wl-copy (Wayland) or xclip (X11)
if _, envSet = os.LookupEnv("WAYLAND_DISPLAY"); envSet {
cmd = exec.Command("wl-copy")
} else if _, envSet = os.LookupEnv("DISPLAY"); envSet {
cmd = exec.Command("xclip", "-sel", "c")
} else {
fmt.Println(AnsiError + "Clipboard platform could not be determined - note that the clipboard does not function in a raw TTY" + AnsiReset)
os.Exit(1)
}
writeToStdin(cmd, copySubject)
err := cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to copy to clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
// launch clipboard clearing process if executableName is provided
if executableName != "" {
cmd = exec.Command(executableName, "clipclear")
writeToStdin(cmd, copySubject)
err = cmd.Start()
if err != nil {
fmt.Println(AnsiError + "Failed to launch automated clipboard clearing process - does this libmutton implementation support the \"clipclear\" argument?" + AnsiReset)
os.Exit(1)
}
Exit(0) // only exit if clipboard clearing process is launched, otherwise assume continuous clipboard refresh
}
}
// clipClear is called in a separate process to clear the clipboard after 30 seconds
func clipClear(oldContents string) {
time.Sleep(30 * time.Second)
// determine clipboard tool to use (wl-clipboard VS xclip)
var envSet bool
var cmdClear, cmdPaste *exec.Cmd
if _, envSet = os.LookupEnv("WAYLAND_DISPLAY"); envSet {
cmdClear = exec.Command("wl-copy", "-c")
cmdPaste = exec.Command("wl-paste")
} else if _, envSet = os.LookupEnv("DISPLAY"); envSet {
cmdClear = exec.Command("xclip", "-i", "/dev/null", "-sel", "c")
cmdPaste = exec.Command("xclip", "-o", "-sel", "c")
} else {
fmt.Println(AnsiError + "Clipboard platform could not be determined - neither $WAYLAND_DISPLAY nor $DISPLAY are set" + AnsiReset)
os.Exit(1)
}
// read current clipboard contents
newContents, err := cmdPaste.Output()
if err != nil {
fmt.Println(AnsiError + "Failed to read clipboard contents: " + err.Error() + AnsiReset)
os.Exit(1)
}
// clear clipboard if contents have not been modified
if oldContents == strings.TrimRight(string(newContents), "\r\n") {
err = cmdClear.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to clear clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
os.Exit(0) // use os.Exit instead of backend.Exit, as this function runs out of a background subprocess that is invisible to the user (will never appear in GUI/TUI environment)
}
+55
View File
@@ -0,0 +1,55 @@
//go:build windows || (linux && wsl)
package backend
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
)
// copyField copies a field from an entry to the clipboard
func copyField(executableName, copySubject string) {
cmd := exec.Command("powershell.exe", "-c", fmt.Sprintf("echo '%s' | Set-Clipboard", strings.ReplaceAll(copySubject, "'", "''")))
err := cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to copy to clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
// launch clipboard clearing process if executableName is provided
if executableName != "" {
cmd = exec.Command(executableName, "clipclear")
writeToStdin(cmd, copySubject)
err = cmd.Start()
if err != nil {
fmt.Println(AnsiError + "Failed to launch automated clipboard clearing process - does this libmutton implementation support the \"clipclear\" argument?" + AnsiReset)
os.Exit(1)
}
Exit(0) // only exit if clipboard clearing process is launched, otherwise assume continuous clipboard refresh
}
}
// clipClear is called in a separate process to clear the clipboard after 30 seconds
func clipClear(oldContents string) {
time.Sleep(30 * time.Second)
cmd := exec.Command("powershell.exe", "-c", "Get-Clipboard")
newContents, err := cmd.Output()
if err != nil {
fmt.Println(AnsiError + "Failed to read clipboard contents: " + err.Error() + AnsiReset)
os.Exit(1)
}
if oldContents == strings.TrimRight(string(newContents), "\r\n") {
cmd = exec.Command("powershell.exe", "-c", "Set-Clipboard")
err = cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to clear clipboard: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
os.Exit(0) // use os.Exit instead of backend.Exit, as this function runs out of a background subprocess that is invisible to the user (will never appear in GUI/TUI environment)
}
+25
View File
@@ -0,0 +1,25 @@
package backend
// GetOldEntryData decrypts and returns old entry data (with all required lines present)
func GetOldEntryData(targetLocation string, field int) []string {
// ensure targetLocation exists
TargetIsFile(targetLocation, true, 2)
// read old entry data
unencryptedEntry := DecryptGPG(targetLocation)
// return the old entry data with all required lines present
if field > 0 {
return EnsureSliceLength(unencryptedEntry, field)
} else {
return unencryptedEntry
}
}
// EnsureSliceLength ensures slice is long enough to contain the specified index
func EnsureSliceLength(slice []string, index int) []string {
for len(slice) <= index {
slice = append(slice, "")
}
return slice
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !returnOnExit
package backend
import "os"
func Exit(code int) {
os.Exit(code)
}
+7
View File
@@ -0,0 +1,7 @@
//go:build returnOnExit
package backend
func Exit(code int) {
return code
}
+39
View File
@@ -0,0 +1,39 @@
package backend
import (
"fmt"
"os"
"os/exec"
"strings"
)
// TODO GPG support is a temporary feature - it will be replaced with a different encryption scheme in the future
// DecryptGPG decrypts a GPG-encrypted file and returns the contents as a slice of (trimmed) strings
func DecryptGPG(targetLocation string) []string {
cmd := exec.Command("gpg", "--pinentry-mode", "loopback", "-q", "-d", targetLocation)
output, err := cmd.Output()
// ensure ANSI escape sequences are interpreted properly on Windows
enableVirtualTerminalProcessing()
if err != nil {
fmt.Println(AnsiError + "Failed to decrypt \"" + targetLocation + "\" - ensure it is a valid GPG-encrypted file and that you entered your passphrase correctly" + AnsiReset)
os.Exit(1)
}
outputSlice := strings.Split(string(output), "\n")
return outputSlice
}
// EncryptGPG encrypts a slice of strings using GPG and returns the encrypted data as a byte slice
func EncryptGPG(input []string) []byte {
cmd := exec.Command("gpg", "-q", "-r", ParseConfig([][2]string{{"LIBMUTTON", "gpgID"}}, "")[0], "-e")
writeToStdin(cmd, strings.Join(input, "\n"))
encryptedBytes, err := cmd.Output()
if err != nil {
fmt.Println(AnsiError + "Failed to encrypt data - ensure that your GPG key is valid and that you have a valid GPG ID set in libmutton.ini" + AnsiReset)
os.Exit(1)
}
return encryptedBytes
}
+82
View File
@@ -0,0 +1,82 @@
package backend
import (
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// GpgUIDListGen generates a list of all GPG key IDs on the system and returns them as a slice of strings
func GpgUIDListGen() []string {
cmd := exec.Command("gpg", "-k", "--with-colons")
gpgOutputBytes, _ := cmd.Output()
gpgOutputLines := strings.Split(string(gpgOutputBytes), "\n")
var uidSlice []string
for _, line := range gpgOutputLines {
if strings.HasPrefix(line, "uid") {
uid := strings.Split(line, ":")[9]
uidSlice = append(uidSlice, uid)
}
}
return uidSlice
}
// GpgKeyGen generates a new GPG key and returns the key ID
func GpgKeyGen() string {
gpgGenTempFile := CreateTempFile()
defer func(name string) {
_ = os.Remove(name) // error ignored; if the file could be created, it can probably be removed
}(gpgGenTempFile.Name())
// create and write gpg-gen file
unixTime := strconv.FormatInt(time.Now().Unix(), 10)
_, _ = gpgGenTempFile.WriteString(strings.Join([]string{"Key-Type: eddsa", "Key-Curve: ed25519", "Key-Usage: sign", "Subkey-Type: ecdh", "Subkey-Curve: cv25519", "Subkey-Usage: encrypt", "Name-Real: libmutton-" + unixTime, "Name-Comment: gpg-libmutton", "Name-Email: github.com/rwinkhart/libmutton", "Expire-Date: 0"}, "\n")) // error ignored; if the file could be created, it can probably be written to
// close gpg-gen file
_ = gpgGenTempFile.Close() // error ignored; if the file could be created, it can probably be closed
// generate GPG key based on gpg-gen file
cmd := exec.Command("gpg", "-q", "--batch", "--generate-key", gpgGenTempFile.Name())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
if err != nil {
fmt.Println(AnsiError + "Failed to generate GPG key: " + err.Error() + AnsiReset)
os.Exit(1)
}
return "libmutton-" + unixTime + " (gpg-libmutton) <github.com/rwinkhart/libmutton>"
}
// DirInit creates the libmutton directories
func DirInit(preserveOldConfigDir bool) {
// create EntryRoot
err := os.MkdirAll(EntryRoot, 0700)
if err != nil {
fmt.Println(AnsiError + "Failed to create \"" + EntryRoot + "\":" + err.Error() + AnsiReset)
os.Exit(1)
}
// remove existing config directory (if it exists and not in append mode)
if !preserveOldConfigDir {
_, isAccessible := TargetIsFile(ConfigDir, false, 1)
if isAccessible {
err = os.RemoveAll(ConfigDir)
if err != nil {
fmt.Println(AnsiError + "Failed to remove existing config directory: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
}
// create config directory w/devices subdirectory
err = os.MkdirAll(ConfigDir+PathSeparator+"devices", 0700)
if err != nil {
fmt.Println(AnsiError + "Failed to create \"" + ConfigDir + "\":" + err.Error() + AnsiReset)
os.Exit(1)
}
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !windows
package backend
// TargetLocationFormat returns the full location of an entry (given the name) formatted for the current platform
func TargetLocationFormat(targetLocationIncomplete string) string {
return EntryRoot + targetLocationIncomplete
}
+10
View File
@@ -0,0 +1,10 @@
//go:build windows
package backend
import "strings"
// TargetLocationFormat returns the full location of an entry (given the name) formatted for the current platform
func TargetLocationFormat(targetLocationIncomplete string) string {
return EntryRoot + strings.ReplaceAll(targetLocationIncomplete, "/", PathSeparator)
}
+157
View File
@@ -0,0 +1,157 @@
package backend
import (
"crypto/rand"
"fmt"
"io"
"math"
"math/big"
"os"
"os/exec"
"strings"
)
// TargetIsFile TargetStatusCheck checks if the targetLocation is a file, directory, or is inaccessible
// failCondition: 0 = fail on inaccessible, 1 = fail on inaccessible/file, 2 = fail on inaccessible/directory
// returns: isFile, isAccessible
func TargetIsFile(targetLocation string, errorOnFail bool, failCondition uint8) (bool, bool) {
targetInfo, err := os.Stat(targetLocation)
if err != nil {
if errorOnFail {
fmt.Println(AnsiError + "Failed to access \"" + targetLocation + "\" - ensure it exists and has the correct permissions" + AnsiReset)
os.Exit(1)
} else {
return false, false
}
}
if targetInfo.IsDir() {
if errorOnFail && failCondition == 2 {
fmt.Println(AnsiError + "\"" + targetLocation + "\" is a directory" + AnsiReset)
os.Exit(1)
}
return false, true
} else {
if errorOnFail && failCondition == 1 {
fmt.Println(AnsiError + "\"" + targetLocation + "\" is a file" + AnsiReset)
os.Exit(1)
}
return true, true
}
}
// WriteEntry writes entryData to an encrypted file at targetLocation
func WriteEntry(targetLocation string, entryData []string, verifyEntryDoesNotExist bool) {
if verifyEntryDoesNotExist {
_, isAccessible := TargetIsFile(targetLocation, false, 0)
if isAccessible {
fmt.Println(AnsiError + "Target location already exists" + AnsiReset)
os.Exit(1)
}
}
encryptedBytes := EncryptGPG(entryData)
err := os.WriteFile(targetLocation, encryptedBytes, 0600)
if err != nil {
fmt.Println(AnsiError + "Failed to write to file: " + err.Error() + AnsiReset)
os.Exit(1)
}
}
// writeToStdin writes a string to a command's stdin
func writeToStdin(cmd *exec.Cmd, input string) {
stdin, err := cmd.StdinPipe()
if err != nil {
fmt.Println(AnsiError + "Failed to access stdin for system command: " + err.Error() + AnsiReset)
os.Exit(1)
}
go func() {
defer func(stdin io.WriteCloser) {
_ = stdin.Close() // error ignored; if stdin could be accessed, it can probably be closed
}(stdin)
_, _ = io.WriteString(stdin, input)
}()
}
// CreateTempFile creates a temporary file and returns a pointer to it
func CreateTempFile() *os.File {
tempFile, err := os.CreateTemp("", "*.markdown")
if err != nil {
fmt.Println(AnsiError + "Failed to create temporary file: " + err.Error() + AnsiReset)
os.Exit(1)
}
return tempFile
}
// RemoveTrailingEmptyStrings removes empty strings from the end of a slice
func RemoveTrailingEmptyStrings(slice []string) []string {
for i := len(slice) - 1; i >= 0; i-- {
if slice[i] != "" {
return slice[:i+1]
}
}
return []string{}
}
// StringGen generates a random string of a specified length and complexity
// safeForFileName: if true, the generated string will only contain special characters that are safe for file names (only impacts complex strings)
// complexity: minimum percentage of special characters to be returned in the generated string (only impacts complex strings)
func StringGen(length int, complex bool, complexity float64, safeForFileName bool) string {
var actualSpecialChars int // track the number of special characters in the generated string
var minSpecialChars int // track the minimum number of special characters to accept
var extendedCharset string // additions to character set used for complex strings
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // default character set used for all strings
const extendedCharsetFiles = "!#$%&'()+,-.;=@[]^_`{}~" // additional special characters for complex strings (safe in file names)
const extendedCharsetPassword = "\"*:><?/\\|" // additional special characters for complex strings (NOT safe in file names)
if complex {
minSpecialChars = int(math.Round(float64(length) * complexity)) // determine minimum number of special characters to accept
if !safeForFileName {
extendedCharset = extendedCharsetFiles + extendedCharsetPassword
} else {
extendedCharset = extendedCharsetFiles
}
charset += extendedCharset
}
// loop until a string of the desired complexity is generated
for {
// generate a random string
result := make([]byte, length)
for i := range result {
val, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
result[i] = charset[val.Int64()]
}
// return early if the string is not complex
if !complex {
return string(result)
}
// count the number of special characters in the generated string
for _, char := range string(result) {
if strings.ContainsRune(extendedCharset, char) {
actualSpecialChars++
}
}
// return the generated string if it contains enough special characters
if actualSpecialChars >= minSpecialChars {
return string(result)
}
// reset special character counter
fmt.Println("Regenerating string until desired complexity is achieved...")
actualSpecialChars = 0
}
}
// EntryIsNotEmpty iterates through entryData and returns true if any line is not empty
func EntryIsNotEmpty(entryData []string) bool {
for _, line := range entryData {
if line != "" {
return true
}
}
return false
}
+2 -2
View File
@@ -6,13 +6,13 @@ import (
"golang.org/x/term"
)
// global variables used across multiple files
var (
width, _, _ = term.GetSize(int(os.Stdout.Fd()))
)
// global constants used across multiple files
const (
MUTNVersion = "0.2.1" // untagged releases feature a letter suffix corresponding to the eventual release version, e.g "0.2.A" -> "0.2.0", "0.2.B" -> "0.2.1"
AnsiBold = "\033[1m"
ansiBlackOnWhite = "\033[38;5;0;48;5;15m"
)
+8 -8
View File
@@ -5,21 +5,21 @@ import (
"os"
"strings"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/MUTN/src/backend"
)
// AddEntry creates a new entry at targetLocation by taking user input via CLI prompts.
// Requires: entryType (0 = standard password entry, 1 = auto-generated password entry, 2 = note-only entry).
// AddEntry creates a new entry at targetLocation by taking user input via CLI prompts
// entryType: 0 = standard (password), 1 = auto-generated password, 2 = note
func AddEntry(targetLocation string, hideSecrets bool, entryType uint8) {
// ensure target location does not already exist
_, isAccessible := core.TargetIsFile(targetLocation, false, 0)
_, isAccessible := backend.TargetIsFile(targetLocation, false, 0)
if isAccessible {
fmt.Println(core.AnsiError + "Target location already exists" + core.AnsiReset)
os.Exit(core.ErrorTargetExists)
fmt.Println(backend.AnsiError + "Target location already exists" + backend.AnsiReset)
os.Exit(1)
}
// ensure target containing directory exists and is a directory (not a file)
core.TargetIsFile(targetLocation[:strings.LastIndex(targetLocation, "/")], true, 1)
backend.TargetIsFile(targetLocation[:strings.LastIndex(targetLocation, "/")], true, 1)
var unencryptedEntry []string
@@ -31,7 +31,7 @@ func AddEntry(targetLocation string, hideSecrets bool, entryType uint8) {
if entryType == 0 {
password = inputHidden("Password:")
} else {
password = core.StringGen(inputInt("Password length:", -1), inputBinary("Generate a complex (special characters) password?"), 0.2, false)
password = backend.StringGen(inputInt("Password length:", -1), inputBinary("Generate a complex (special characters) password?"), 0.2, false)
}
totp := inputHidden("TOTP secret:")
+17 -17
View File
@@ -8,11 +8,11 @@ import (
"reflect"
"strings"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/libmutton/sync"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/sync"
)
// RenameCli renames an entry at oldLocationIncomplete to a new location (user input) on both the client and the server.
// RenameCli renames an entry at oldLocationIncomplete to a new location (user input) on both the client and the server
func RenameCli(oldLocationIncomplete string) {
// prompt user for new location and rename
newLocationIncomplete := input("New location:")
@@ -21,10 +21,10 @@ func RenameCli(oldLocationIncomplete string) {
// exit is done from sync.RenameRemoteFromClient
}
// EditEntryField edits a field of an entry at targetLocation (user input).
// EditEntryField edits a field of an entry at targetLocation (user input)
func EditEntryField(targetLocation string, hideSecrets bool, field int) {
// fetch old entry data (with all required lines present)
unencryptedEntry := core.GetOldEntryData(targetLocation, field)
unencryptedEntry := backend.GetOldEntryData(targetLocation, field)
// edit the field
switch field {
@@ -44,8 +44,8 @@ func EditEntryField(targetLocation string, hideSecrets bool, field int) {
// edit the note
editedNote, noteEdited := editNote(noteData)
if !noteEdited { // exit early if the note was not edited
fmt.Println(core.AnsiError + "Entry is unchanged" + core.AnsiReset)
os.Exit(0)
fmt.Println(backend.AnsiError + "Entry is unchanged" + backend.AnsiReset)
os.Exit(1)
}
unencryptedEntry = append(nonNoteData, editedNote...)
}
@@ -54,28 +54,28 @@ func EditEntryField(targetLocation string, hideSecrets bool, field int) {
writeEntryCLI(targetLocation, unencryptedEntry, hideSecrets, false)
}
// GenUpdate generates a new password for an entry at targetLocation (user input).
// GenUpdate generates a new password for an entry at targetLocation (user input)
func GenUpdate(targetLocation string, hideSecrets bool) {
// fetch old entry data
unencryptedEntry := core.GetOldEntryData(targetLocation, 0)
unencryptedEntry := backend.GetOldEntryData(targetLocation, 0)
// generate a new password
unencryptedEntry[0] = core.StringGen(inputInt("Password length:", -1), inputBinary("Generate a complex (special characters) password?"), 0.2, false)
unencryptedEntry[0] = backend.StringGen(inputInt("Password length:", -1), inputBinary("Generate a complex (special characters) password?"), 0.2, false)
// write and preview the modified entry
writeEntryCLI(targetLocation, unencryptedEntry, hideSecrets, false)
}
// editNote uses the user-specified text editor to edit an existing note (or create a new one if baseNote is empty).
// Returns the edited note and a boolean indicating whether the note was edited.
// editNote uses the user-specified text editor to edit an existing note (or create a new one if baseNote is empty)
// returns the edited note and a boolean indicating whether the note was edited
func editNote(baseNote []string) ([]string, bool) {
tempFile := core.CreateTempFile()
tempFile := backend.CreateTempFile()
defer func(name string) {
_ = os.Remove(name) // error ignored; if the file could be created, it can probably be removed
}(tempFile.Name())
// fetch the user's text editor
editor := core.ParseConfig([][2]string{{"MUTN", "textEditor"}}, "")[0]
editor := backend.ParseConfig([][2]string{{"MUTN", "textEditor"}}, "")[0]
// write baseNote to tempFile (if it is not empty)
if len(baseNote) > 0 {
@@ -94,13 +94,13 @@ func editNote(baseNote []string) ([]string, bool) {
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
panic(core.AnsiError + "Failed to write note with " + editor + core.AnsiReset) // panic is used to ensure the tempFile is removed, as per the defer statement
panic(backend.AnsiError + "Failed to write note with " + editor + backend.AnsiReset) // panic is used to ensure the tempFile is removed, as per the defer statement
}
// open the tempFile for reading
tempFile, err = os.Open(tempFile.Name())
if err != nil {
panic(core.AnsiError + "Failed to read note written with " + editor + core.AnsiReset) // panic is used to ensure the tempFile is removed, as per the defer statement
panic(backend.AnsiError + "Failed to read note written with " + editor + backend.AnsiReset) // panic is used to ensure the tempFile is removed, as per the defer statement
}
// read the edited note from the tempFile
@@ -114,7 +114,7 @@ func editNote(baseNote []string) ([]string, bool) {
_ = tempFile.Close() // error ignored; if the file could be opened, it can probably be closed
// remove trailing empty strings from the edited note
note = core.RemoveTrailingEmptyStrings(note)
note = backend.RemoveTrailingEmptyStrings(note)
// trim trailing whitespace from each note line
for i, line := range note {
+11 -12
View File
@@ -2,21 +2,20 @@ package cli
import (
"fmt"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/sync"
"os"
"strings"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/libmutton/sync"
)
// ANSI color constants used only in this file
// global constants used only in this file
const (
ansiAlternateEntryColor = "\033[38;5;8m"
ansiDirectoryHeader = "\033[38;5;7;48;5;8m"
ansiEmptyDirectoryWarning = "\033[38;5;11m"
)
// determineIndentation calculates and returns the final visual indentation multiplier (needed to adjust indentation for skipped parent directories); also subtracts "old" text from directory header.
// calculates and returns the final visual indentation multiplier (needed to adjust indentation for skipped parent directories) - also subtracts "old" text from directory header
func determineIndentation(skippedDirList []bool, dirList []string, currentDirIndex int) (int, string) {
var subtractor int // tracks how much to subtract from expected indentation multiplier
var lastPrefixIndex int // tracks the index (in both skippedDirList and dirList) of the last displayed parent directory
@@ -46,7 +45,7 @@ func determineIndentation(skippedDirList []bool, dirList []string, currentDirInd
return indent, trimmedDirectory
}
// printFileEntry handles processing for printing file entries (determines color, wraps lines, and prints).
// processing for printing file entries (determines color, line wrapping, and prints)
func printFileEntry(entry string, lastSlash, charCounter, indent int, colorAlternator int8) (int, int8) {
// determine color to print fileEntryName (alternate each time function is run)
var colorCode string
@@ -72,17 +71,17 @@ func printFileEntry(entry string, lastSlash, charCounter, indent int, colorAlter
}
// print fileEntryName to screen
fmt.Printf("%s%s%s ", colorCode, fileEntryName, core.AnsiReset)
fmt.Printf("%s%s%s ", colorCode, fileEntryName, backend.AnsiReset)
return charCounter, colorAlternator
}
// EntryListGen generates and displays the full libmutton entry list.
// EntryListGen generates and displays full libmutton entry list
func EntryListGen() {
fileList, dirList := sync.WalkEntryDir()
// print header bar w/total entry count
fmt.Print("\n"+ansiBlackOnWhite, len(fileList), " libmutton entries:"+core.AnsiReset)
fmt.Print("\n"+ansiBlackOnWhite, len(fileList), " libmutton entries:"+backend.AnsiReset)
// dirList iteration
dirListLength := len(dirList) // save length for multiple references below
@@ -128,7 +127,7 @@ func EntryListGen() {
containsFiles = true
skippedDirList[i] = false // the directory header is being printed, indicate that it is not being skipped
indent, vanityDirectory = determineIndentation(skippedDirList, dirList, i) // calculate the final indentation multiplier
fmt.Printf("\n\n"+strings.Repeat(" ", indent*2)+ansiDirectoryHeader+"%s/"+core.AnsiReset+"\n", vanityDirectory)
fmt.Printf("\n\n"+strings.Repeat(" ", indent*2)+ansiDirectoryHeader+"%s/"+backend.AnsiReset+"\n", vanityDirectory)
}
charCounter, colorAlternator = printFileEntry(file, lastSlash, charCounter, indent, colorAlternator)
@@ -140,8 +139,8 @@ func EntryListGen() {
if dirListLength > 1 { // and directories besides the root-level exist... display directory header and empty directory warning
skippedDirList[i] = false // the directory header is being printed, indicate that it is not being skipped
indent, vanityDirectory = determineIndentation(skippedDirList, dirList, i) // calculate the final indentation multiplier
fmt.Printf("\n\n"+strings.Repeat(" ", indent*2)+ansiDirectoryHeader+"%s/"+core.AnsiReset+"\n", vanityDirectory)
fmt.Print(strings.Repeat(" ", indent*2) + ansiEmptyDirectoryWarning + "-empty directory-" + core.AnsiReset)
fmt.Printf("\n\n"+strings.Repeat(" ", indent*2)+ansiDirectoryHeader+"%s/"+backend.AnsiReset+"\n", vanityDirectory)
fmt.Print(strings.Repeat(" ", indent*2) + ansiEmptyDirectoryWarning + "-empty directory-" + backend.AnsiReset)
} else { // warn if the only thing that exists is the root-level directory
fmt.Print("\n\nNothing's here! For help creating your first entry, run \"mutn help\".")
}
+13 -13
View File
@@ -5,13 +5,13 @@ import (
"os"
"strings"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/libmutton/sync"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/sync"
)
const ansiShownPassword = "\033[38;5;10m"
// EntryReader prints the decrypted contents of a libmutton entry in a human-readable format.
// EntryReader prints the decrypted contents of a libmutton entry in a human-readable format
func EntryReader(decryptedEntry []string, hideSecrets, syncEnabled bool) {
fmt.Println()
@@ -21,33 +21,33 @@ func EntryReader(decryptedEntry []string, hideSecrets, syncEnabled bool) {
// if the first field (password) is not empty, print it
if decryptedEntry[0] != "" {
if !hideSecrets {
fmt.Print(ansiDirectoryHeader + "Password:" + core.AnsiReset + "\n" + ansiShownPassword + decryptedEntry[0] + core.AnsiReset + "\n\n")
fmt.Print(ansiDirectoryHeader + "Password:" + backend.AnsiReset + "\n" + ansiShownPassword + decryptedEntry[0] + backend.AnsiReset + "\n\n")
} else {
fmt.Print(ansiDirectoryHeader + "Password:" + core.AnsiReset + "\n" + ansiEmptyDirectoryWarning + "End command in \"show\" or \"-s\" to view" + core.AnsiReset + "\n\n")
fmt.Print(ansiDirectoryHeader + "Password:" + backend.AnsiReset + "\n" + ansiEmptyDirectoryWarning + "End command in \"show\" or \"-s\" to view" + backend.AnsiReset + "\n\n")
}
}
case 1:
// if the second field (username) is not empty, print it
if decryptedEntry[1] != "" {
fmt.Print(ansiDirectoryHeader + "Username:" + core.AnsiReset + "\n" + decryptedEntry[1] + "\n\n")
fmt.Print(ansiDirectoryHeader + "Username:" + backend.AnsiReset + "\n" + decryptedEntry[1] + "\n\n")
}
case 2:
// if the third field (TOTP secret) is not empty, print it
if decryptedEntry[2] != "" {
if !hideSecrets {
fmt.Print(ansiDirectoryHeader + "TOTP Secret:" + core.AnsiReset + "\n" + ansiShownPassword + decryptedEntry[2] + core.AnsiReset + "\n\n")
fmt.Print(ansiDirectoryHeader + "TOTP Secret:" + backend.AnsiReset + "\n" + ansiShownPassword + decryptedEntry[2] + backend.AnsiReset + "\n\n")
} else {
fmt.Print(ansiDirectoryHeader + "TOTP Secret:" + core.AnsiReset + "\n" + ansiEmptyDirectoryWarning + "End command in \"show\" or \"-s\" to view" + core.AnsiReset + "\n\n")
fmt.Print(ansiDirectoryHeader + "TOTP Secret:" + backend.AnsiReset + "\n" + ansiEmptyDirectoryWarning + "End command in \"show\" or \"-s\" to view" + backend.AnsiReset + "\n\n")
}
}
case 3:
// if the fourth field (url) is not empty, print it
if decryptedEntry[3] != "" {
fmt.Print(ansiDirectoryHeader + "URL:" + core.AnsiReset + "\n" + decryptedEntry[3] + "\n\n")
fmt.Print(ansiDirectoryHeader + "URL:" + backend.AnsiReset + "\n" + decryptedEntry[3] + "\n\n")
}
case 4:
// print the notes header
fmt.Println(ansiDirectoryHeader + "Notes:" + core.AnsiReset)
fmt.Println(ansiDirectoryHeader + "Notes:" + backend.AnsiReset)
// combine remaining fields into a single string (to support Markdown rendering)
var notesSlice []string
@@ -71,10 +71,10 @@ func EntryReader(decryptedEntry []string, hideSecrets, syncEnabled bool) {
os.Exit(0)
}
// EntryReaderDecrypt is a wrapper for EntryReader that first decrypts a GPG-encrypted file before sending it to EntryReader.
// EntryReaderDecrypt is a wrapper for EntryReader that first decrypts a GPG-encrypted file before sending it to EntryReader
func EntryReaderDecrypt(targetLocation string, hideSecrets bool) {
if isFile, _ := core.TargetIsFile(targetLocation, true, 2); isFile {
EntryReader(core.DecryptGPG(targetLocation), hideSecrets, false) // never sync if decrypting straight to EntryReader, as this means the entry could not have been modified
if isFile, _ := backend.TargetIsFile(targetLocation, true, 2); isFile {
EntryReader(backend.DecryptGPG(targetLocation), hideSecrets, false) // never sync if decrypting straight to EntryReader, as this means the entry could not have been modified
}
// do not exit, as this is the job of EntryReader
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/charmbracelet/glamour"
)
// renderNote renders the notes section of an entry (in Markdown) to stdout.
// renderNote renders the notes section of an entry (in Markdown) to stdout
func renderNote(note *string) {
r, _ := glamour.NewTermRenderer(glamour.WithStylesFromJSONBytes(glamourStyle()), glamour.WithPreservedNewLines(), glamour.WithWordWrap(width))
markdownNotesString, _ := r.Render(*note)
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"fmt"
)
// renderNote prints the notes section of an entry to stdout (when Markdown rendering is disabled).
// renderNote prints the notes section of an entry to stdout (when Markdown rendering is disabled)
func renderNote(note *string) {
fmt.Print("\n" + *note + "\n\n")
}
+17 -17
View File
@@ -6,23 +6,23 @@ import (
"os"
"strconv"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/libmutton/sync"
"github.com/rwinkhart/MUTN/src/backend"
"github.com/rwinkhart/MUTN/src/sync"
)
// TempInitCli initializes the MUTN environment based on user input.
// TempInitCli initializes the MUTN environment based on user input (will be replaced with a TUI menu)
func TempInitCli() {
// gpgID
var gpgID string
if inputBinary("Auto-generate GPG key?") {
gpgID = core.GpgKeyGen()
gpgID = backend.GpgKeyGen()
} else {
// select GPG key from menu
uidSlice := core.GpgUIDListGen()
uidSlice := backend.GpgUIDListGen()
gpgIDInt := inputMenuGen("Select GPG key:", uidSlice)
if gpgIDInt == 0 {
fmt.Println(core.AnsiError + "No GPG keys found - please generate one" + core.AnsiReset)
os.Exit(core.ErrorTargetNotFound)
fmt.Println(backend.AnsiError + "No GPG keys found - please generate one" + backend.AnsiReset)
os.Exit(1)
}
gpgID = uidSlice[gpgIDInt-1]
}
@@ -34,7 +34,7 @@ func TempInitCli() {
configSSH := inputBinary("Configure SSH settings (for synchronization)?")
if configSSH {
// necessary SSH info
fmt.Println(AnsiBold + "\nNote:" + core.AnsiReset + " Only key-based authentication is supported (keys may optionally be passphrase-protected).\nThe remote server must already be in your ~" + core.PathSeparator + ".ssh" + core.PathSeparator + "known_hosts file.")
fmt.Println(AnsiBold + "\nNote:" + backend.AnsiReset + " Only key-based authentication is supported (keys may optionally be passphrase-protected).\nThe remote server must already be in your ~" + backend.PathSeparator + ".ssh" + backend.PathSeparator + "known_hosts file.")
sshUser := input("Remote SSH username:")
sshPort := input("Remote SSH port:")
sshIP := input("Remote SSH IP/domain:")
@@ -43,32 +43,32 @@ func TempInitCli() {
var sshKey string
var sshKeyIsFile bool
for !sshKeyIsFile {
fallbackSSHKey := core.Home + core.PathSeparator + ".ssh" + core.PathSeparator + "id_ed25519"
fallbackSSHKey := backend.Home + backend.PathSeparator + ".ssh" + backend.PathSeparator + "id_ed25519"
sshKey = cmp.Or(expandPathWithHome(input("SSH private identity file path (falls back to \""+fallbackSSHKey+"\"):")), fallbackSSHKey)
sshKeyIsFile, _ = core.TargetIsFile(sshKey, false, 0)
sshKeyIsFile, _ = backend.TargetIsFile(sshKey, false, 0)
if !sshKeyIsFile {
fmt.Println(core.AnsiError+"SSH identity file not found:", sshKey+core.AnsiReset)
fmt.Println(backend.AnsiError + "SSH identity file not found: " + sshKey + backend.AnsiReset)
}
}
sshKeyProtected := inputBinary("Is the identity file password-protected?")
// initialize libmutton directories
oldDeviceID := core.DirInit(false)
backend.DirInit(false)
// write config file (temporarily assigns sshEntryRoot and sshIsWindows to null to pass initial device ID registration)
core.WriteConfig([][3]string{{"MUTN", "textEditor", textEditor}, {"LIBMUTTON", "gpgID", gpgID}, {"LIBMUTTON", "sshUser", sshUser}, {"LIBMUTTON", "sshIP", sshIP}, {"LIBMUTTON", "sshPort", sshPort}, {"LIBMUTTON", "sshKey", sshKey}, {"LIBMUTTON", "sshKeyProtected", strconv.FormatBool(sshKeyProtected)}, {"LIBMUTTON", "sshEntryRoot", "null"}, {"LIBMUTTON", "sshIsWindows", "false"}}, false)
backend.WriteConfig([][3]string{{"MUTN", "textEditor", textEditor}, {"LIBMUTTON", "gpgID", gpgID}, {"LIBMUTTON", "sshUser", sshUser}, {"LIBMUTTON", "sshIP", sshIP}, {"LIBMUTTON", "sshPort", sshPort}, {"LIBMUTTON", "sshKey", sshKey}, {"LIBMUTTON", "sshKeyProtected", strconv.FormatBool(sshKeyProtected)}, {"LIBMUTTON", "sshEntryRoot", "null"}, {"LIBMUTTON", "sshIsWindows", "null"}}, false)
// generate and register device ID
sshEntryRoot, sshIsWindows := sync.DeviceIDGen(oldDeviceID)
sshEntryRoot, sshIsWindows := sync.DeviceIDGen()
// update config file with sshEntryRoot and sshIsWindows
core.WriteConfig([][3]string{{"LIBMUTTON", "sshEntryRoot", sshEntryRoot}, {"LIBMUTTON", "sshIsWindows", sshIsWindows}}, true)
backend.WriteConfig([][3]string{{"LIBMUTTON", "sshEntryRoot", sshEntryRoot}, {"LIBMUTTON", "sshIsWindows", sshIsWindows}}, true)
} else {
// initialize libmutton directories
core.DirInit(false)
backend.DirInit(false)
// write config file
core.WriteConfig([][3]string{{"MUTN", "textEditor", textEditor}, {"LIBMUTTON", "gpgID", gpgID}}, false)
backend.WriteConfig([][3]string{{"MUTN", "textEditor", textEditor}, {"LIBMUTTON", "gpgID", gpgID}}, false)
}
}
+31 -33
View File
@@ -4,23 +4,23 @@ import (
"fmt"
"os"
"github.com/rwinkhart/libmutton/core"
"github.com/rwinkhart/MUTN/src/backend"
)
// ANSI color constants used only in this file
// global constants used only in this file
const (
ansiVersionMeat = "\033[38;2;157;0;6m"
ansiVersionOutline = "\033[38;2;131;165;152m"
)
func HelpMain() {
fmt.Print(AnsiBold + "\nMUTN | Copyright (c) 2024 Randall Winkhart\n" + core.AnsiReset + `
fmt.Print(AnsiBold + "\nMUTN | Copyright (c) 2024 Randall Winkhart\n" + backend.AnsiReset + `
This software exists under the MIT license; you may redistribute it under certain conditions.
This program comes with absolutely no warranty; type "mutn version" for details.
` + AnsiBold + "Usage:" + core.AnsiReset + ` mutn [/<entry name> [argument] [option]] | [argument]
` + AnsiBold + "Usage:" + backend.AnsiReset + ` mutn [/<entry name> [argument] [option]] | [argument]
` + AnsiBold + "Arguments:" + core.AnsiReset + `
` + AnsiBold + "Arguments:" + backend.AnsiReset + `
help Bring up this menu
version Display version and license information
init Set up MUTN (generates libmutton.ini)
@@ -31,7 +31,7 @@ This program comes with absolutely no warranty; type "mutn version" for details.
shear Delete an existing entry
sync Manually sync the entry directory
` + AnsiBold + "Options:" + core.AnsiReset + `
` + AnsiBold + "Options:" + backend.AnsiReset + `
copy:
password|-pw|<blank> Copy the password in an entry to your clipboard
username|-u Copy the username in an entry to your clipboard
@@ -52,17 +52,17 @@ This program comes with absolutely no warranty; type "mutn version" for details.
note|-n Add a note entry
folder|-f Add a new folder for entries
` + AnsiBold + "Tip 1:" + core.AnsiReset + ` You can quickly read an entry with "mutn /<entry name>"
` + AnsiBold + "Tip 2:" + core.AnsiReset + ` Type "mutn" (no arguments/options) to view a list of saved entries
` + AnsiBold + "Tip 3:" + core.AnsiReset + ` Provide "add", "edit", "copy", or "gen" as the only argument to receive more specific help
` + AnsiBold + "Tip 4:" + core.AnsiReset + " Using \"add\", \"edit\", or \"copy\" without specifying an option (field) will default to \"password\"\n\n")
` + AnsiBold + "Tip 1:" + backend.AnsiReset + ` You can quickly read an entry with "mutn /<entry name>"
` + AnsiBold + "Tip 2:" + backend.AnsiReset + ` Type "mutn" (no arguments/options) to view a list of saved entries
` + AnsiBold + "Tip 3:" + backend.AnsiReset + ` Provide "add", "edit", "copy", or "gen" as the only argument to receive more specific help
` + AnsiBold + "Tip 4:" + backend.AnsiReset + " Using \"add\", \"edit\", or \"copy\" without specifying an option (field) will default to \"password\"\n\n")
os.Exit(0)
}
func HelpAdd() {
fmt.Print(AnsiBold + "\nUsage:" + core.AnsiReset + ` mutn /<entry name> add <option>
fmt.Print(AnsiBold + "\nUsage:" + backend.AnsiReset + ` mutn /<entry name> add <option>
` + AnsiBold + "Options:" + core.AnsiReset + `
` + AnsiBold + "Options:" + backend.AnsiReset + `
add:
password|-pw|<blank> Add a password entry
note|-n Add a note entry
@@ -71,9 +71,9 @@ func HelpAdd() {
}
func HelpEdit() {
fmt.Print(AnsiBold + "\nUsage:" + core.AnsiReset + ` mutn /<entry name> edit <option>
fmt.Print(AnsiBold + "\nUsage:" + backend.AnsiReset + ` mutn /<entry name> edit <option>
` + AnsiBold + "Options:" + core.AnsiReset + `
` + AnsiBold + "Options:" + backend.AnsiReset + `
edit:
password|-pw|<blank> Change the password in an entry
username|-u Change the username in an entry
@@ -85,9 +85,9 @@ func HelpEdit() {
}
func HelpCopy() {
fmt.Print(AnsiBold + "\nUsage:" + core.AnsiReset + ` mutn /<entry name> copy <option>
fmt.Print(AnsiBold + "\nUsage:" + backend.AnsiReset + ` mutn /<entry name> copy <option>
` + AnsiBold + "Options:" + core.AnsiReset + `
` + AnsiBold + "Options:" + backend.AnsiReset + `
copy:
password|-pw|<blank> Copy the password in an entry to your clipboard
username|-u Copy the username in an entry to your clipboard
@@ -98,18 +98,18 @@ func HelpCopy() {
}
func HelpGen() {
fmt.Print(AnsiBold + "\nUsage:" + core.AnsiReset + ` mutn /<entry name> gen [option]
fmt.Print(AnsiBold + "\nUsage:" + backend.AnsiReset + ` mutn /<entry name> gen [option]
` + AnsiBold + "Options:" + core.AnsiReset + `
` + AnsiBold + "Options:" + backend.AnsiReset + `
gen:
update|-u Generate a password for an existing entry
` + AnsiBold + "Tip:" + core.AnsiReset + " If no options are provided, a new password entry is generated\n\n")
` + AnsiBold + "Tip:" + backend.AnsiReset + " If no options are provided, a new password entry is generated\n\n")
os.Exit(0)
}
func MITLicense() {
fmt.Print(AnsiBold + "\n MIT License" + core.AnsiReset + `
fmt.Print(AnsiBold + "\n MIT License" + backend.AnsiReset + `
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
@@ -141,20 +141,18 @@ func Version() {
MITLicense()
fmt.Print("\n\n MUTN is a simple, self-hosted,\n SSH-synchronized password manager based on libmutton\n\n" +
" .. ..\n" +
" /()\\''.''. " + ansiVersionMeat + "♥♥♥♥" + core.AnsiReset + " .''.''/()\\ _)\n" +
" _. : * " + ansiVersionMeat + "♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥" + core.AnsiReset + " * : <[◎]|_|=\n" +
" }-}-*] `..'..' " + ansiVersionMeat + "♥♥♥♥♥♥♥♥♥♥♥♥♥" + core.AnsiReset + " `..'..' |\n" +
" ◎-◎ // \\\\ " + ansiVersionMeat + "♥♥♥♥♥♥♥♥♥" + core.AnsiReset + " // \\\\ /|\\\n" +
" /()\\''.''. " + ansiVersionMeat + "♥♥♥♥" + backend.AnsiReset + " .''.''/()\\ _)\n" +
" _. : * " + ansiVersionMeat + "♥♥♥♥♥♥ ♥♥♥♥♥♥♥♥" + backend.AnsiReset + " * : <[◎]|_|=\n" +
" }-}-*] `..'..' " + ansiVersionMeat + "♥♥♥♥♥♥♥♥♥♥♥♥♥" + backend.AnsiReset + " `..'..' |\n" +
" ◎-◎ // \\\\ " + ansiVersionMeat + "♥♥♥♥♥♥♥♥♥" + backend.AnsiReset + " // \\\\ /|\\\n" +
ansiVersionOutline + "<><><><><><><><><><><><><><>-<><><><><><><><><><><><><><>\n" +
"\\" + ansiBlackOnWhite + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " MUTN v" + MUTNVersion + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " The Tripe Transmission Update " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " Built with libmutton v" + core.LibmuttonVersion + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " Copyright (c) 2024 Randall Winkhart " + core.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " " + core.AnsiReset + ansiVersionOutline + "/\n" +
"<><><><><><><><><><><><><><>-<><><><><><><><><><><><><><>\n" + core.AnsiReset +
"\\" + ansiBlackOnWhite + " " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " MUTN Version " + backend.LibmuttonVersion + " " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " The Tripe Transmission Update " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " Copyright (c) 2024 Randall Winkhart " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"\\" + ansiBlackOnWhite + " " + backend.AnsiReset + ansiVersionOutline + "/\n" +
"<><><><><><><><><><><><><><>-<><><><><><><><><><><><><><>\n" + backend.AnsiReset +
"\n For more information, see:\n\n" +
" https://github.com/rwinkhart/MUTN\n" +
" https://github.com/rwinkhart/libmutton\n\n")
+17 -17
View File
@@ -6,11 +6,11 @@ import (
"os"
"strings"
"github.com/rwinkhart/libmutton/core"
"golang.org/x/term"
"github.com/rwinkhart/MUTN/src/backend"
"golang.org/x/crypto/ssh/terminal"
)
// input prompts the user for input and returns the input as a string.
// input prompts the user for input and returns the input as a string
func input(prompt string) string {
fmt.Print("\n" + prompt + " ")
reader := bufio.NewReader(os.Stdin)
@@ -18,17 +18,17 @@ func input(prompt string) string {
return strings.TrimRight(userInput, "\n\r ") // remove trailing newlines, carriage returns, and spaces
}
// inputHidden prompts the user for input and returns the input as a string, hiding the input from the terminal.
// inputHidden prompts the user for input and returns the input as a string, hiding the input from the terminal
func inputHidden(prompt string) string {
fmt.Print("\n" + prompt + " ")
byteInput, _ := term.ReadPassword(int(os.Stdin.Fd()))
byteInput, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
password := string(byteInput)
fmt.Println()
return password
}
// inputInt prompts the user for input and returns the input as an integer.
// A maxValue of 0 will cause the function to return 0, an error - a negative maxValue will disable the maxValue check.
// inputInt prompts the user for input and returns the input as an integer
// a maxValue of 0 will cause the function to return 0, an error - a negative maxValue will disable the maxValue check
func inputInt(prompt string, maxValue int) int {
if maxValue == 0 {
return 0
@@ -45,7 +45,7 @@ func inputInt(prompt string, maxValue int) int {
}
}
// inputBinary prompts the user with a yes/no question and returns the response as a boolean.
// inputBinary prompts the user with a yes/no question and returns the response as a boolean
func inputBinary(prompt string) bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print("\n" + prompt + " (y/N) ")
@@ -56,7 +56,7 @@ func inputBinary(prompt string) bool {
return false
}
// inputMenuGen prompts the user with a menu and returns the user's choice as an integer.
// inputMenuGen prompts the user with a menu and returns the user's choice as an integer
func inputMenuGen(prompt string, options []string) int {
for i, option := range options {
fmt.Printf("%d. %s\n", i+1, option)
@@ -64,21 +64,21 @@ func inputMenuGen(prompt string, options []string) int {
return inputInt(prompt, len(options))
}
// writeEntryCLI writes an entry to targetLocation and previews it (errors if no data is supplied).
// writeEntryCLI writes an entry to targetLocation and previews it (errors if no data is supplied)
func writeEntryCLI(targetLocation string, unencryptedEntry []string, hideSecrets, verifyEntryDoesNotExist bool) {
if core.EntryIsNotEmpty(unencryptedEntry) {
if backend.EntryIsNotEmpty(unencryptedEntry) {
// write the entry to the target location
core.WriteEntry(targetLocation, unencryptedEntry, verifyEntryDoesNotExist)
backend.WriteEntry(targetLocation, unencryptedEntry, verifyEntryDoesNotExist)
// preview the entry
fmt.Println(AnsiBold + "\nEntry Preview:" + core.AnsiReset)
fmt.Println(AnsiBold + "\nEntry Preview:" + backend.AnsiReset)
EntryReader(unencryptedEntry, hideSecrets, true)
} else {
fmt.Println(core.AnsiError + "No data supplied for entry" + core.AnsiReset)
os.Exit(core.ErrorTargetNotFound)
fmt.Println(backend.AnsiError + "No data supplied for entry" + backend.AnsiReset)
os.Exit(1)
}
}
// expandPathWithHome, given a path (as a string) containing "~", returns the path with "~" expanded to the user's home directory.
// expandPathWithHome, given a path (as a string) containing "~", returns the path with "~" expanded to the user's home directory
func expandPathWithHome(path string) string {
return strings.Replace(path, "~", core.Home, 1)
return strings.Replace(path, "~", backend.Home, 1)
}
+13
View File
@@ -0,0 +1,13 @@
package sync
import "github.com/rwinkhart/MUTN/src/backend"
// define field separator constants
const (
FSSpace = "\u259d" // ▝ space/list separator
FSPath = "\u259e" // ▞ path separator
FSMisc = "\u259f" // ▟ misc. field separator (if \u259d is already used)
)
// rootLength stores length of backend.EntryRoot string
var rootLength = len(backend.EntryRoot)
+477
View File
@@ -0,0 +1,477 @@
package sync
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/pkg/sftp"
"github.com/rwinkhart/MUTN/src/backend"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
// global constants used only in this file
const (
ansiDelete = "\033[38;5;1m"
ansiDownload = "\033[38;5;2m"
ansiUpload = "\033[38;5;4m"
)
// getSSHClient returns an SSH client connection to the server (also returns the remote EntryRoot as a string and the server's OS as a bool - IsWindows)
// only supports key-based authentication (passphrases are supported for CLI-based implementations)
func getSSHClient(manualSync bool) (*ssh.Client, string, bool) {
// get SSH config info, exit if not configured (displaying an error if the sync job was called manually)
var sshUserConfig []string
var missingValueError string
if manualSync {
missingValueError = joinErrorWithEXE("SSH settings not configured - run \"", " init\" to configure")
} else {
missingValueError = "0"
}
sshUserConfig = backend.ParseConfig([][2]string{{"LIBMUTTON", "sshUser"}, {"LIBMUTTON", "sshIP"}, {"LIBMUTTON", "sshPort"}, {"LIBMUTTON", "sshKey"}, {"LIBMUTTON", "sshKeyProtected"}, {"LIBMUTTON", "sshEntryRoot"}, {"LIBMUTTON", "sshIsWindows"}}, missingValueError)
var user, ip, port, keyFile, keyFileProtected, entryRoot string
var isWindows bool
for i, key := range sshUserConfig {
switch i {
case 0:
user = key
case 1:
ip = key
case 2:
port = key
case 3:
keyFile = key
case 4:
keyFileProtected = key
case 5:
entryRoot = key
case 6:
isWindows, _ = strconv.ParseBool(key)
}
}
// read private key
key, err := os.ReadFile(keyFile)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - unable to read private key file:", keyFile+backend.AnsiReset)
os.Exit(1)
}
// parse private key
var parsedKey ssh.Signer
if keyFileProtected != "true" {
parsedKey, err = ssh.ParsePrivateKey(key)
} else {
parsedKey, err = ssh.ParsePrivateKeyWithPassphrase(key, inputKeyFilePassphrase())
}
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to parse private key:", keyFile+backend.AnsiReset)
os.Exit(1)
}
// read known hosts file
hostKeyCallback, err := knownhosts.New(backend.Home + backend.PathSeparator + ".ssh" + backend.PathSeparator + "known_hosts")
if err != nil {
fmt.Println(backend.AnsiError + "Sync failed - Unable to read known hosts file:" + err.Error() + backend.AnsiReset)
os.Exit(1)
}
// configure SSH client
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(parsedKey),
},
HostKeyCallback: hostKeyCallback,
}
// connect to SSH server
sshClient, err := ssh.Dial("tcp", ip+":"+port, sshConfig)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to connect to remote server:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
return sshClient, entryRoot, isWindows
}
// GetSSHOutput runs a command over SSH and returns the output as a string
// TODO run getSSHClient() only ONCE (from RunJob) - this saves re-creating the client AND prevents prompting for keyfile passphrase multiple times
func GetSSHOutput(cmd, stdin string, manualSync bool) string {
sshClient, _, _ := getSSHClient(manualSync)
defer sshClient.Close()
// create a session
sshSession, err := sshClient.NewSession()
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to establish SSH session:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// provide stdin data for session
sshSession.Stdin = strings.NewReader(stdin)
// run the provided command
var output []byte
output, err = sshSession.CombinedOutput(cmd)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to run SSH command:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// convert the output to a string and remove leading/trailing whitespace
outputString := string(output)
outputString = strings.TrimSpace(outputString)
return outputString
}
// getRemoteDataFromClient returns a map of remote entries to their modification times, a list of remote folders, a list of queued deletions, and the current server+client times as UNIX timestamps
func getRemoteDataFromClient(manualSync bool) (map[string]int64, []string, []string, int64, int64) {
// get remote output over SSH
clientDeviceID, _ := os.ReadDir(backend.ConfigDir + backend.PathSeparator + "devices")
if len(clientDeviceID) == 0 {
if manualSync {
fmt.Println(joinErrorWithEXE("Sync failed - No device ID found; run \"", " init\" to generate a device ID"))
os.Exit(1)
} else {
backend.Exit(0) // exit silently if the sync job was called automatically, as the user may just be in offline mode
}
}
clientTime := time.Now().Unix() // get client time now to avoid accuracy issues caused by unpredictable sync time
output := GetSSHOutput("libmuttonserver fetch", clientDeviceID[0].Name(), manualSync)
// split output into slice based on occurrences of FSSpace
outputSlice := strings.Split(output, FSSpace)
// parse output/re-form lists
if len(outputSlice) != 5 { // ensure information from server is complete
fmt.Println(backend.AnsiError + "Sync failed - Unable to fetch remote data; server returned an unexpected response" + backend.AnsiReset)
os.Exit(1)
}
serverTime, _ := strconv.ParseInt(outputSlice[0], 10, 64)
entries := strings.Split(outputSlice[1], FSMisc)[1:]
modsStrings := strings.Split(outputSlice[2], FSMisc)[1:]
folders := strings.Split(outputSlice[3], FSMisc)[1:]
deletions := strings.Split(outputSlice[4], FSMisc)[1:]
// convert the mod times to int64
var mods []int64
for _, modString := range modsStrings {
mod, _ := strconv.ParseInt(modString, 10, 64)
mods = append(mods, mod)
}
// map remote entries to their modification times
entryModMap := make(map[string]int64)
for i, entry := range entries {
entryModMap[entry] = mods[i]
}
return entryModMap, folders, deletions, serverTime, clientTime
}
// getLocalData returns a map of local entries to their modification times
func getLocalData() map[string]int64 {
// get a list of all entries
entries, _ := WalkEntryDir()
// get a list of all entry modification times
modList := getModTimes(entries)
// map the entries to their modification times
entryModMap := make(map[string]int64)
for i, entry := range entries {
entryModMap[entry] = modList[i]
}
// return the lists
return entryModMap
}
// targetLocationFormatSFTP formats the target location to match the remote server's entry directory and path separator
func targetLocationFormatSFTP(targetName, serverEntryRoot string, serverIsWindows bool) string {
if !serverIsWindows {
return serverEntryRoot + targetName
} else {
return serverEntryRoot + strings.ReplaceAll(targetName, "/", "\\")
}
}
// sftpSync takes two slices of entries (one for downloads and one for uploads) and syncs them between the client and server using SFTP
func sftpSync(downloadList, uploadList []string, manualSync bool) {
// establish an SSH connection for transfers
sshClient, sshEntryRoot, sshIsWindows := getSSHClient(manualSync)
defer sshClient.Close()
// create an SFTP client
sftpClient, err := sftp.NewClient(sshClient)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to establish SFTP session:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
defer sftpClient.Close()
// iterate over the download list
var filesTransferred bool
for _, entryName := range downloadList {
filesTransferred = true // set a flag to indicate that files have been downloaded (used to determine whether to print a gap between download and upload messages)
fmt.Println("Downloading " + ansiDownload + entryName + backend.AnsiReset)
// store path to remote entry
remoteEntryFullPath := targetLocationFormatSFTP(entryName, sshEntryRoot, sshIsWindows)
// save modification time of remote file
var fileInfo os.FileInfo
fileInfo, err = sftpClient.Stat(remoteEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to get remote file info (mod time):", err.Error()+backend.AnsiReset)
os.Exit(1)
}
modTime := fileInfo.ModTime()
// open remote file
var remoteFile *sftp.File
remoteFile, err = sftpClient.Open(remoteEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to open remote file:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// store path to local entry
localEntryFullPath := backend.TargetLocationFormat(entryName)
// create local file
var localFile *os.File
localFile, err = os.Create(localEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to create local file:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// download the file
_, err = remoteFile.WriteTo(localFile)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to download remote file:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// close the files
remoteFile.Close()
localFile.Close()
// set the modification time of the local file to match the value saved from the remote file (from before the download)
err = os.Chtimes(localEntryFullPath, time.Now(), modTime)
}
if filesTransferred {
fmt.Println() // add a gap between download and upload messages
}
// iterate over the upload list
filesTransferred = false
for _, entryName := range uploadList {
filesTransferred = true // set a flag to indicate that files have been uploaded (used to determine whether to print a gap between upload and sync complete messages)
fmt.Println("Uploading " + ansiUpload + entryName + backend.AnsiReset)
// store path to local entry
localEntryFullPath := backend.TargetLocationFormat(entryName)
// save modification time of local file
var fileInfo os.FileInfo
fileInfo, err = os.Stat(localEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to get local file info (mod time):", err.Error()+backend.AnsiReset)
os.Exit(1)
}
modTime := fileInfo.ModTime()
// open local file
var localFile *os.File
localFile, err = os.Open(localEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to open local file:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// store path to remote entry
remoteEntryFullPath := targetLocationFormatSFTP(entryName, sshEntryRoot, sshIsWindows)
// create remote file
var remoteFile *sftp.File
remoteFile, err = sftpClient.Create(remoteEntryFullPath)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to create remote file ("+remoteEntryFullPath+"):", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// upload the file
_, err = localFile.WriteTo(remoteFile)
if err != nil {
fmt.Println(backend.AnsiError+"Sync failed - Unable to upload local file:", err.Error()+backend.AnsiReset)
os.Exit(1)
}
// close the files
localFile.Close()
remoteFile.Close()
// set the modification time of the remote file to match the value saved from the local file (from before the upload)
err = sftpClient.Chtimes(remoteEntryFullPath, time.Now(), modTime)
}
if filesTransferred {
fmt.Println() // add a gap between upload and sync complete messages
}
}
// syncLists determines which entries need to be downloaded and uploaded for synchronizations and calls sftpSync with this information
// using maps means that syncing will be done in an arbitrary order, but it is a worthy tradeoff for speed and simplicity
func syncLists(localEntryModMap, remoteEntryModMap map[string]int64, manualSync bool, serverTime int64, clientTime int64) {
// initialize slices to store entries that need to be downloaded or uploaded
var downloadList, uploadList []string
// ensure client and server times are synchronized
var timeSynced = true
timeDiff := serverTime - clientTime
if timeDiff < -45 || timeDiff > 45 {
timeSynced = false
fmt.Print(backend.AnsiError + "Client and server clocks are out of sync.\n\nPlease ensure both clocks are correct before attempting to sync again.\n\nA dry sync output will be printed below (if any operations would have been performed). It is strongly recommended to review it and manually update the modification times as applicable to ensure the correct version of each entry is kept.\n\nIf the client's clock is at fault, update the modification times of any entries pending upload, even if the correct (upload) operation is being performed on them. Failure to do so could result in entries being uploaded to the server with the incorrect modification times (could result in data loss).\n\n" + backend.AnsiReset)
}
// iterate over client entries
for entry, localModTime := range localEntryModMap {
// check if the entry is present in the server map
if remoteModTime, present := remoteEntryModMap[entry]; present {
// entry exists on both client and server, compare mod times
if remoteModTime > localModTime {
fmt.Println(ansiDownload+entry+backend.AnsiReset, "is newer on server, adding to download list")
downloadList = append(downloadList, entry)
} else if remoteModTime < localModTime {
fmt.Println(ansiUpload+entry+backend.AnsiReset, "is newer on client, adding to upload list")
uploadList = append(uploadList, entry)
}
// remove entry from remoteEntryModMap (process of elimination)
delete(remoteEntryModMap, entry)
} else {
fmt.Println(ansiUpload+entry+backend.AnsiReset, "does not exist on server, adding to upload list")
uploadList = append(uploadList, entry)
}
}
// iterate over remaining entries in remoteEntryModMap
for entry := range remoteEntryModMap {
fmt.Println(ansiDownload+entry+backend.AnsiReset, "does not exist on client, adding to download list")
downloadList = append(downloadList, entry)
}
// call sftpSync with the download and upload lists
if timeSynced && (max(len(downloadList), len(uploadList)) > 0) { // only call sftpSync if there are entries to download or upload
fmt.Println() // add a gap between list-add messages and the actual sync messages from sftpSync
sftpSync(downloadList, uploadList, manualSync)
} else if !timeSynced {
// do not call sftpSync if the client and server times are out of sync
backend.Exit(1)
}
fmt.Println("Client is synchronized with server")
}
// deletionSync removes entries from the client that have been deleted on the server (multi-client deletion)
func deletionSync(deletions []string) {
var filesDeleted bool
for _, deletion := range deletions {
filesDeleted = true // set a flag to indicate that files have been deleted (used to determine whether to print a gap between deletion and other messages)
fmt.Println(ansiDelete+deletion+backend.AnsiReset, "has been sheared, removing locally (if it exists)")
os.RemoveAll(backend.TargetLocationFormat(deletion))
}
if filesDeleted {
fmt.Println() // add a gap between deletion and other messages
}
}
// ShearRemoteFromClient removes the target file or directory from the local system and calls the server to remove it remotely and add it to the deletions list
// can safely be called in offline mode, as well, so this is the intended interface for shearing (ShearLocal should only be used directly by the server binary)
func ShearRemoteFromClient(targetLocationIncomplete string) {
deviceID := ShearLocal(targetLocationIncomplete, "") // remove the target from the local system and get the device ID of the client
if deviceID != "" { // ensure a device ID exists (online mode)
// call the server to remotely shear the target and add it to the deletions list
GetSSHOutput("libmuttonserver shear", deviceID+"\n"+
strings.ReplaceAll(targetLocationIncomplete, backend.PathSeparator, FSPath), false)
}
backend.Exit(0) // sync is not required after shearing since the target has already been removed from the local system
}
// RenameRemoteFromClient renames oldLocationIncomplete to newLocationIncomplete on the local system and calls the server to perform the rename remotely and add the old target to the deletions list
// can safely be called in offline mode, as well, so this is the intended interface for renaming (RenameLocal should only be used directly by the server binary)
func RenameRemoteFromClient(oldLocationIncomplete, newLocationIncomplete string) {
RenameLocal(oldLocationIncomplete, newLocationIncomplete, false) // move the target on the local system
deviceIDList := genDeviceIDList()
if len(*deviceIDList) > 0 { // ensure a device ID exists (online mode)
// call the server to move the target on the remote system and add the old target to the deletions list
GetSSHOutput("libmuttonserver rename",
(*deviceIDList)[0].Name()+"\n"+
strings.ReplaceAll(oldLocationIncomplete, backend.PathSeparator, FSPath)+"\n"+
strings.ReplaceAll(newLocationIncomplete, backend.PathSeparator, FSPath), false)
}
backend.Exit(0)
}
// AddFolderRemoteFromClient creates a new entry-containing directory on the local system and calls the server to create the folder remotely
// can safely be called in offline mode, as well, so this is the intended interface for adding folders (AddFolderLocal should only be used directly by the server binary)
func AddFolderRemoteFromClient(targetLocationIncomplete string) {
AddFolderLocal(targetLocationIncomplete) // add the folder on the local system
GetSSHOutput("libmuttonserver addfolder", strings.ReplaceAll(targetLocationIncomplete, backend.PathSeparator, FSPath), false) // call the server to create the folder remotely
backend.Exit(0)
}
// folderSync creates folders on the client (from the given list of folder names)
func folderSync(folders []string) {
for _, folder := range folders {
// store the full local path of the folder
folderFullPath := backend.TargetLocationFormat(folder)
// check if folder already exists
isFile, isAccessible := backend.TargetIsFile(folderFullPath, false, 1)
if !isFile && !isAccessible {
os.MkdirAll(folderFullPath, 0700)
} else if isFile {
fmt.Println(backend.AnsiError + "Sync failed - Failed to create folder \"" + folder + "\" - a file with the same name already exists" + backend.AnsiReset)
os.Exit(1)
}
}
}
// RunJob runs the SSH sync job
func RunJob(manualSync bool) {
// fetch remote lists
remoteEntryModMap, remoteFolders, deletions, serverTime, clientTime := getRemoteDataFromClient(manualSync)
// sync folders
folderSync(remoteFolders)
// sync deletions
deletionSync(deletions)
// fetch local lists
localEntryModMap := getLocalData()
// sync new and updated entries
syncLists(localEntryModMap, remoteEntryModMap, manualSync, serverTime, clientTime)
// exit program after successful sync
backend.Exit(0)
}
+124
View File
@@ -0,0 +1,124 @@
package sync
import (
"fmt"
"io/fs"
"os"
"strings"
"github.com/rwinkhart/MUTN/src/backend"
)
// getModTimes returns a list of all entry modification times
func getModTimes(entryList []string) []int64 {
var modList []int64
for _, file := range entryList {
modTime, _ := os.Stat(backend.TargetLocationFormat(file))
modList = append(modList, modTime.ModTime().Unix())
}
return modList
}
// genDeviceIDList returns a pointer to a slice of all registered device IDs
func genDeviceIDList() *[]fs.DirEntry {
// create a slice of all registered devices
deviceIDList, err := os.ReadDir(backend.ConfigDir + backend.PathSeparator + "devices")
if err != nil {
fmt.Println(backend.AnsiError + "Failed to read the devices directory: " + err.Error() + backend.AnsiReset)
os.Exit(1)
}
return &deviceIDList
}
// ShearLocal removes the target file or directory from the local system
// returns: deviceID (on client), for use in ShearRemoteFromClient
// if the local system is a server, it will also add the target to the deletions list for all clients (except the requesting client)
// this function should only be used directly by the server binary
func ShearLocal(targetLocationIncomplete, clientDeviceID string) string {
// determine if running on a server
var onServer bool
if clientDeviceID != "" {
onServer = true
}
deviceIDList := genDeviceIDList()
// add the sheared target (incomplete, vanity) to the deletions list (if running on a server)
if onServer {
for _, device := range *deviceIDList {
if device.Name() != clientDeviceID {
_, err := os.Create(backend.ConfigDir + backend.PathSeparator + "deletions" + backend.PathSeparator + device.Name() + FSSpace + strings.ReplaceAll(targetLocationIncomplete, "/", FSPath))
if err != nil {
// do not print error as there is currently no way of seeing server-side errors
// failure to add the target to the deletions list will exit the program and result in a client re-uploading the target (non-critical)
os.Exit(1)
}
}
}
}
// get the full targetLocation path and remove the target
targetLocationComplete := backend.TargetLocationFormat(targetLocationIncomplete)
if !onServer { // error if target does not exist on client, needed because os.RemoveAll does not return an error if target does not exist
backend.TargetIsFile(targetLocationComplete, true, 0)
}
err := os.RemoveAll(targetLocationComplete)
if err != nil {
fmt.Println(backend.AnsiError + "Failed to remove local target: " + err.Error() + backend.AnsiReset)
os.Exit(1)
}
if !onServer && len(*deviceIDList) > 0 { // return the device ID if running on the client and a device ID exists (online mode)
return (*deviceIDList)[0].Name()
}
return ""
// do not exit program, as this function is used as part of ShearRemoteFromClient
}
// RenameLocal renames oldLocationIncomplete to newLocationIncomplete on the local system
// this function should only be used directly by the server binary
func RenameLocal(oldLocationIncomplete, newLocationIncomplete string, verifyOldLocationExists bool) {
// get full paths for both locations
oldLocation := backend.TargetLocationFormat(oldLocationIncomplete)
newLocation := backend.TargetLocationFormat(newLocationIncomplete)
if verifyOldLocationExists {
backend.TargetIsFile(oldLocation, true, 0)
}
// ensure newLocation does not exist
_, isAccessible := backend.TargetIsFile(newLocation, false, 0)
if isAccessible {
fmt.Println(backend.AnsiError + "\"" + newLocation + "\" already exists" + backend.AnsiReset)
os.Exit(1)
}
// rename oldLocation to newLocation
err := os.Rename(oldLocation, newLocation)
if err != nil {
fmt.Println(backend.AnsiError + "Failed to rename - does the target containing directory exist?" + backend.AnsiReset)
}
// do not exit program, as this function is used as part of RenameRemoteFromClient
}
// AddFolderLocal creates a new entry-containing directory on the local system
// this function should only be used directly by the server binary
func AddFolderLocal(targetLocationIncomplete string) {
// get the full targetLocation path and create the target
targetLocationComplete := backend.TargetLocationFormat(targetLocationIncomplete)
err := os.Mkdir(targetLocationComplete, 0700)
if err != nil {
if os.IsExist(err) {
fmt.Println(backend.AnsiError + "Directory already exists" + backend.AnsiReset)
os.Exit(1)
} else {
fmt.Println(backend.AnsiError + "Failed to create directory: " + err.Error() + backend.AnsiReset)
os.Exit(1)
}
}
// do not exit program, as this function is used as part of AddFolderRemoteFromClient
}
+54
View File
@@ -0,0 +1,54 @@
//go:build !windows
package sync
import (
"fmt"
"github.com/rwinkhart/MUTN/src/backend"
"io/fs"
"os"
"path/filepath"
)
// WalkEntryDir walks the entry directory and returns lists of all files and directories found (two separate lists)
// regardless of platform, all paths are stored with forward slashes (UNIX-style)
func WalkEntryDir() ([]string, []string) {
// define file/directory containing slices so that they may be accessed by the anonymous WalkDir function
var fileList []string
var dirList []string
// walk entry directory
_ = filepath.WalkDir(backend.EntryRoot,
func(fullPath string, entry fs.DirEntry, err error) error {
// check for errors encountered while walking directory
if err != nil {
if os.IsNotExist(err) {
fmt.Println(backend.AnsiError+"The entry directory does not exist - run \""+os.Args[0], "init"+"\" to create it"+backend.AnsiReset)
} else {
// otherwise, print the source of the error
fmt.Println(backend.AnsiError + "An unexpected error occurred while generating the entry list: " + err.Error() + backend.AnsiReset)
}
os.Exit(1)
}
// trim root path from each path before storing
trimmedPath := fullPath[rootLength:]
// append the path to the appropriate slice
if !entry.IsDir() {
fileList = append(fileList, trimmedPath)
} else {
dirList = append(dirList, trimmedPath)
}
return nil
})
return fileList, dirList
}
// joinErrorWithEXE joins and returns the two strings it is provided (in error format) with the executable name inserted between them
func joinErrorWithEXE(firstHalf, secondHalf string) string {
return backend.AnsiError + firstHalf + os.Args[0] + secondHalf + backend.AnsiReset
}
+55
View File
@@ -0,0 +1,55 @@
//go:build windows
package sync
import (
"fmt"
"github.com/rwinkhart/MUTN/src/backend"
"io/fs"
"os"
"path/filepath"
"strings"
)
// WalkEntryDir walks the entry directory and returns lists of all files and directories found (two separate lists)
// regardless of platform, all paths are stored with forward slashes (UNIX-style)
func WalkEntryDir() ([]string, []string) {
// define file/directory containing slices so that they may be accessed by the anonymous WalkDir function
var fileList []string
var dirList []string
// walk entry directory
_ = filepath.WalkDir(backend.EntryRoot,
func(fullPath string, entry fs.DirEntry, err error) error {
// check for errors encountered while walking directory
if err != nil {
if os.IsNotExist(err) {
fmt.Println(joinErrorWithEXE("The entry directory does not exist - run \"", " init"+"\" to create it"))
} else {
// otherwise, print the source of the error
fmt.Println(backend.AnsiError + "An unexpected error occurred while generating the entry list: " + err.Error() + backend.AnsiReset)
}
os.Exit(1)
}
// trim root path from each path before storing and replace backslashes with forward slashes
trimmedPath := strings.ReplaceAll(fullPath[rootLength:], "\\", "/")
// append the path to the appropriate slice
if !entry.IsDir() {
fileList = append(fileList, trimmedPath)
} else {
dirList = append(dirList, trimmedPath)
}
return nil
})
return fileList, dirList
}
// joinErrorWithEXE joins and returns the two strings it is provided (in error format) with the executable name inserted between them
func joinErrorWithEXE(firstHalf, secondHalf string) string {
return backend.AnsiError + firstHalf + os.Args[0][strings.LastIndex(os.Args[0], "\\")+1:] + secondHalf + backend.AnsiReset
}
+32
View File
@@ -0,0 +1,32 @@
package sync
import (
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
"github.com/rwinkhart/MUTN/src/backend"
)
// DeviceIDGen generates a new client device ID and registers it with the server
// device IDs are only needed for online synchronization
// device IDs are guaranteed unique as the current UNIX time is appended to them
// returns the remote EntryRoot and OS type (OS type is a bool: backend.IsWindows)
func DeviceIDGen() (string, string) {
deviceIDPrefix, _ := os.Hostname()
deviceIDSuffix := backend.StringGen(rand.Intn(32)+48, true, 0.2, true) + "-" + strconv.FormatInt(time.Now().Unix(), 10)
deviceID := deviceIDPrefix + "-" + deviceIDSuffix
_, err := os.Create(backend.ConfigDir + backend.PathSeparator + "devices" + backend.PathSeparator + deviceID) // TODO remove existing device ID file if it exists (from both client and server)
if err != nil {
fmt.Println(backend.AnsiError + "Failed to create local device ID file: " + err.Error() + backend.AnsiReset)
}
// register device ID with server and fetch remote EntryRoot and OS type
//manualSync is true so the user is alerted if device ID registration fails
sshEntryRootSSHIsWindows := strings.Split(GetSSHOutput("libmuttonserver register", deviceID, true), FSSpace)
return sshEntryRootSSHIsWindows[0], sshEntryRootSSHIsWindows[1]
}
+16
View File
@@ -0,0 +1,16 @@
package sync
import (
"fmt"
"golang.org/x/crypto/ssh/terminal"
"os"
)
// inputKeyFilePassphrase prompts the user for a passphrase for an SSH key file
// TODO support non-CLI implementations
func inputKeyFilePassphrase() []byte {
fmt.Print("\nEnter passphrase for your SSH keyfile: ")
passphrase, _ := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return passphrase
}
+59
View File
@@ -0,0 +1,59 @@
package sync
import (
"fmt"
"os"
"strings"
"time"
"github.com/rwinkhart/MUTN/src/backend"
)
// GetRemoteDataFromServer prints to stdout the remote entries, mod times, folders, and deletions
// lists in output are separated by FSSpace
// output is meant to be captured over SSH for interpretation by the client
func GetRemoteDataFromServer(clientDeviceID string) {
entryList, dirList := WalkEntryDir()
modList := getModTimes(entryList)
deletionsList, err := os.ReadDir(backend.ConfigDir + backend.PathSeparator + "deletions")
if err != nil {
fmt.Println(backend.AnsiError + "Failed to read the deletions directory: " + err.Error() + backend.AnsiReset)
os.Exit(1)
}
// print the current UNIX timestamp to stdout
fmt.Print(time.Now().Unix())
// print the lists to stdout
// entry list
fmt.Print(FSSpace)
for _, entry := range entryList {
fmt.Print(FSMisc + entry)
}
// modification time list
fmt.Print(FSSpace)
for _, mod := range modList {
fmt.Print(FSMisc)
fmt.Print(mod)
}
// directory/folder list
fmt.Print(FSSpace)
for _, dir := range dirList {
fmt.Print(FSMisc + dir)
}
// deletions list
fmt.Print(FSSpace)
for _, deletion := range deletionsList {
// print deletion if it is relevant to the current client device
affectedIDTargetLocationIncomplete := strings.Split(deletion.Name(), FSSpace)
if affectedIDTargetLocationIncomplete[0] == clientDeviceID {
fmt.Print(FSMisc + strings.ReplaceAll(affectedIDTargetLocationIncomplete[1], FSPath, "/"))
// assume successful client deletion and remove deletions file (if assumption is somehow false, worst case scenario is that the client will re-upload the deleted entry)
_ = os.Remove(backend.ConfigDir + backend.PathSeparator + "deletions" + backend.PathSeparator + deletion.Name()) // error ignored; function not run from a user-facing argument and thus the error would not be visible
}
}
}
-1
View File
@@ -6,4 +6,3 @@
- [Extra blank lines after nested list items](https://github.com/charmbracelet/glamour/issues/102)
- [Incorrect wrapping of text in lists](https://github.com/charmbracelet/glamour/issues/56)
- [Excessive binary size and increased program startup time](https://github.com/charmbracelet/glamour/issues/288)
- Relevant [libmutton bugs](https://github.com/rwinkhart/libmutton/blob/main/wiki/bugs.md)
+3
View File
@@ -1,7 +1,10 @@
## Building
This repository is currently home to both the MUTN client and the general libmutton server software.
Official binaries are stripped of debug info for size and built without CGO (except for distribution packages) for portability, as follows:
```
CGO_ENABLED=0 go build -ldflags="-s -w" -trimpath ./mutn.go
CGO_ENABLED=0 go build -ldflags="-s -w" -trimpath ./libmuttonserver.go
```
Additionally, some custom build tags can be used to create different binaries. The following tags are not used in official builds:
+8
View File
@@ -0,0 +1,8 @@
## Installation
MUTN is still in early development and thus no installation packages are officially distributed.
For now, please [compile from source](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/build.md).
After compiling and placing the binaries in your $PATH, it is highly recommended to also download and correctly place/source the relevant [shell completions scripts](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/completions.md).
Please see the [usage guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/usage.md) for help getting started.
+2 -2
View File
@@ -8,13 +8,13 @@ libmutton operates on a client-server model, and thus sync support requires you
For security reasons, libmutton deliberately does not support password-based SSH authentication; you must use key-based authentication to connect to your server (password-protected keys are also supported). You are responsible for setting up SSH connectivity on your own.
The libmutton server software is shipped as its own dedicated binary (in [libmutton releases](https://github.com/rwinkhart/libmutton/releases)) and must be installed on the server and configured with `libmuttonserver init`. The server binary _**MUST**_ be in your $PATH and _**MUST**_ be named "libmuttonserver" for clients to successfully reach it.
The libmutton server software is shipped as its own dedicated binary and must be installed on the server and configured with `libmuttonserver init`.
Once this has been done, you may proceed with the client setup:
1. Install MUTN
2. Run `mutn init` and follow the prompts
3. If you already have entries on the server, sync them using `mutn sync`
4. Optionally, shell completions (Bash, ZSH, and PowerShell 7+) can be [enabled with your shell's respective method](https://github.com/rwinkhart/MUTN/blob/main/wiki/completions.md)
4. Optionally, shell completions (Bash, ZSH, and PowerShell 7+) can be [enabled with your shell's respective method](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/completions.md)
### Tips
#### Operating on Passwords
-12
View File
@@ -1,12 +0,0 @@
## Installation
MUTN is still in early development and thus no installation packages are officially distributed.
For now, please manually install the binaries from the [latest release](https://github.com/rwinkhart/MUTN/releases) or [compile from source](https://github.com/rwinkhart/MUTN/blob/main/wiki/build.md). All pre-built binaries were compiled with CGO disabled and thus are libc-independent.
Additionally, MUTN is available as a source package ("[mutn](https://aur.archlinux.org/packages/mutn)") on the AUR.
Please note that the server binary (available in [libmutton releases](https://github.com/rwinkhart/libmutton/releases)) must be called "libmuttonserver" in order for clients to successfully reach it.
After placing the binaries in your $PATH, it is highly recommended to also download and correctly place/source the relevant [shell completions scripts](https://github.com/rwinkhart/MUTN/blob/main/wiki/completions.md).
Please see the [usage guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/usage.md) for help getting started.
+10
View File
@@ -0,0 +1,10 @@
## Planned Breaking Changes
Leading up to the v1.0.0 release, breaking changes are both expected and planned. These changes are expected to require manual intervention from the end-user, and thus MUTN/libmutton should not be used prior to v1.0.0 if this is not acceptable.
These changes include, but may expand beyond the following:
- Migration to Go-native encryption (no reliance on GnuPG)
- Will be based on symmetrical encryption
- Will eventually allow combining multiple common encryption algorithms (cascading encryption)
- Password aging data will be stored for each entry (to remind the user when it is time to change passwords)
- Will be included in entry names or in external file (to prevent needing to decrypt entries to access this information)
+7
View File
@@ -0,0 +1,7 @@
## Known Bugs - libmutton
- On Windows, GPG is sometimes (seems unpredictable) incredibly slow to start (often after a reboot), leading to many operations seemingly hanging
- **This will be addressed** in the migration off of GPG that will take place before v1.0.0
- If a client is reconfigured to use a new device ID, the old one will remain present on the server. This will not cause any immediate issues, however it will lead to the server creating unnecessary deletions files for the old device ID. Currently, it is recommended to manually delete the old device ID from the server's "devices" directory.
- **This will be addressed** in v0.2.1
- Using a password-protected SSH identity file will prompt for the key's password multiple times when syncing
- **This will be addressed** in v0.2.1
+11
View File
@@ -0,0 +1,11 @@
## Clipboard Troubleshooting + Clipboard Manager Rant
### Clipboard managers can break libmutton-based password managers
***
The intended way for libmutton to interact with the system clipboard is for it to clear it 30 seconds after copying a field. **Unfortunately, this does not work by default on all systems due to the prevalence of clipboard managers.**
Clipboard managers save a history of what has been copied to the clipboard, which is already a big enough issue on its own for people who copy sensitive information to their clipboard. Some **clipboard managers simply will not allow the clipboard to be empty** and will replace its contents with the last copied item if you attempt to clear it. One such naughty clipboard manager is **KDE Klipper**, which comes **packaged into KDE Plasma** and is typically **enabled by default** on most distributions. Due to this behavior, **KDE Klipper breaks libmutton's clipboard clearing functionality** and should not be left enabled.
It is likely other popular clipboard managers exhibit this behavior. I noticed it with KDE Klipper, which is what prompted me to create this wiki page. **Clipboard managers should not be enabled by default in any environment** or distribution due to their **potential security implications**.
### Termux cannot clear the clipboard from the background
***
If using libmutton on Termux (Android), the clipboard may not successfully be cleared after the 30 second timeout period if Termux is not actively in the foreground when the sleep timer expires. This is an unfortunate side-effect of running on Android and cannot be easily fixed. Due to Termux being at the bottom of the platform support priority list, I will not be investing time into working around this.
+49
View File
@@ -0,0 +1,49 @@
## Developer Guide (for third-party libmutton-based clients)
**Important Notice**: libmutton is in early development and is currently a moving target to develop off of. Feel free to jump in early, but greater change stability will be met with release v1.0.0. Check [here](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/breaking.md) for planned breaking changes.
libmutton was designed to be usable as a library for building other compatible password managers off of. [MUTN](https://github.com/rwinkhart/MUTN) is the official reference CLI password manager, however libmutton can be implemented in many other unique ways.
All functionality in the `backend` and `sync` packages are designed to be used in other implementations.
If any functionality in these two packages proves to be difficult to implement in a third-party client, please open an issue so that it can be addressed.
## Build Tags
Custom build tags can (and sometimes must) be used to achieve desired results.
These are as follows:
- `returnOnExit`: If making an interactive interface (GUI/TUI/interactive CLI), you probably need to use this build tag. Without it, your entire program will exit after any given operation is completed. This behavior is only desired for non-interactive CLI implementations, such as MUTN. Currently, errors will result in the program exiting **even with this build tag**. This may be changed in the future (under evaluation).
- `wsl`: Allows creating a Linux binary that can interact with the Windows clipboard (for WSL)
- `termux`: Allows creating a Linux binary that can interact with the Termux clipboard (for Android)
## Required Arguments
libmutton-based password manager clients should accept at least one specific required argument, as well as another recommended one:
- `clipclear`: This argument is required for correct functionality. In order to clear the clipboard on a timer, libmutton-based password managers call another instance of their executable with the `clipclear` argument (e.g. `mutn clipclear`) with the intended clipboard contents provided via STDIN. If after 30 seconds the clipboard contents have not changed, they are cleared. Please accept a `clipclear` argument that is processed before the launch of any interactive interface. All this argument needs to do is call `backend.ClipClearArgument()`.
- `init`: This argument is optional, but recommended for CLI interfaces. Some error messages request the user to use the `init` argument to fix configuration issues. If the argument does not exist, this may confuse the user.
## Configuration
libmutton-based password manager clients should all share the same INI configuration file.
On UNIX-like systems, this is located at `~/.config/libmutton/libmutton.ini`. On Windows, it is located at `~\AppData\Local\libmutton\config\libmutton.ini`.
### Base `libmutton.ini` Layout
The current base layout of `libmutton.ini` will change leading up to release v1.0.0. As of right now, the specification is as follows:
```
[LIBMUTTON]
gpgID = <gpg key id>
sshUser = <remote user>
sshIP = <remote ip>
sshPort = <remote ssh port>
sshKey = <ssh private key identity file path>
sshKeyProtected = <true/false>
sshEntryRoot = <remote entry root>
sshIsWindows = <true/false>
```
If creating a third-party client that requires extra configuration to be stored, please use the same file and create a new INI section for your application-specific configuration, e.g.:
```
[THIRD-PARTY-CLIENT-NAME]
configKey = <value>
```
This ensures that a user can use multiple client applications with the same configuration while avoiding conflicts.
# Relevant Bugs Affecting Third-Party Implementations
- Password-protected SSH identity files currently only prompt for password entry in the CLI, and thus they are not yet supported in GUI/TUI implementations
+8
View File
@@ -0,0 +1,8 @@
## Migrating From Other Password Managers
**Important Notice**: The libmutton entry format is not final and has two [breaking changes planned prior to release v1.0.0](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/breaking.md). This guide will be updated accordingly.
### pass
libmutton-based password managers *currently* use GnuPG encryption and an entry format similar to that of [pass](https://www.passwordstore.org/). Because of this, any entries in `pass` format can simply be dropped into `~/.local/share/libmutton`.
### sshyp
sshyp, though also `pass`-compatible, makes some changes to the entry format that take effect once the entry has been imported. The changes made by sshyp are not compatible with libmutton, and as such sshyp entries must be converted before they can be used. A script for doing that has been created and is available in the sshyp extension store. Simply run `sshyp tweak`, go to the "extension management" menu, and download the "export-to-libmutton" extension. After doing this, the `sshyp export` command can be used to export entries in libmutton format.
### Other
The formats for many other password managers can be converted to the `pass` format with community scripts. Some of these scripts are listed [here](https://www.passwordstore.org/#migration). Once converted, entries can be dropped into `~/.local/share/libmutton`.
+24
View File
@@ -0,0 +1,24 @@
## MUTN Wiki
### MUTN-specific Information
[Installation](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/install.md)
[Building](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/build.md)
[Setup/Usage](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/usage.md)
[Shell Completions Troubleshooting](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/completions.md)
[Known Bugs](https://github.com/rwinkhart/MUTN/blob/main/wiki/MUTN/bugs.md)
---
### libmutton Information (will likely be moved to libmutton repository in the future)
[Planned Breaking Changes](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/breaking.md)
[Migrating From Other Password Managers](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/migration.md)
[Clipboard Troubleshooting](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/clipboard.md)
[Developer Guide](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/developers.md)
[Known Bugs](https://github.com/rwinkhart/MUTN/blob/main/wiki/libmutton/bugs.md)