Compare commits

...
178 Commits
Author SHA1 Message Date
jfmonty2 0798124811 add db migrations and restore config on unlock 2026-11-18 05:49:45 -05:00
jfmonty2 a10510ed6e persist database salt and rework config loading 2026-11-13 13:43:06 -05:00
jfmonty2 2371486f39 add unlock screen 2026-11-12 14:47:10 -05:00
jfmonty2 a1e5daba59 rework basically everything 2026-11-12 11:28:18 -05:00
jfmonty2 2bd81a66a4 initial commit - just the welcome screen and db connection, at present 2026-11-05 11:02:33 -05:00
jfmonty2 d67871f491 clear everything out in preparation for rewrite 2026-11-03 14:00:56 -05:00
jfmonty2 1a7f502fce add Arch packaging 2025-08-31 05:24:36 -04:00
jfmonty2 b2c27d26e8 update auto-launch to 0.5.0 to deal with windows task manager issue 2025-01-05 08:04:10 -05:00
jfmonty2 8fa3a15807 include generated linux schema 2025-01-04 11:05:40 -05:00
jfmonty2 862c68c846 update todo 2025-01-04 11:02:58 -05:00
jfmonty2 ac62171467 upgrade to tauri 2.2.0 2025-01-04 10:50:04 -05:00
jfmonty2 2080fb897b fix autolaunch name in dev/prod 2025-01-03 16:43:45 -05:00
jfmonty2 bf62054c2b make windows work again 2025-01-03 07:52:10 -05:00
jfmonty2 cd4c613758 improve start-minimized and start-on-login behavior
Previously, when Creddy was configured to start minimized, it would always start minimized, regardless of how it was launched. Really, though, when you use this setting what you probably want is for it to start minimized only when it's being launched automatically, i.e. on login. This update changes its behavior so that it will only start minimized when auto-launching.

Additionally, if Creddy detects on startup that its start-on-login configuration doesn't match the system, it will modify its own settings to match the system (unless it's the very first launch, of course.) That way if you disable Creddy's start-on-login behavior from your system dialog, it will respect your change.
2024-12-30 21:09:45 -05:00
jfmonty2 efbf6c687c add test to ensure that client and server agree on socket address 2024-12-28 07:36:38 -05:00
jfmonty2 ee495478ff start working on test for server address 2024-12-28 07:24:43 -05:00
jfmonty2 4c18de8b7a fix docker credential helper when credentials are not found 2024-12-28 06:59:09 -05:00
jfmonty2 0cfa9fc07a correct server socket differentiation 2024-12-27 15:49:42 -05:00
jfmonty2 9e9bc2b0ae separate dev and production instances and add visual indicators of dev mode 2024-12-27 08:17:49 -05:00
jfmonty2 07bf98e522 bump version to 0.6.0 2024-11-25 14:58:53 -05:00
jfmonty2 e0e758554c finish basic Docker credential helper implementation 2024-11-25 14:47:30 -05:00
jfmonty2 479a0a96eb add Docker credentials to management page 2024-11-25 12:02:44 -05:00
jfmonty2 c6e22fc91b show client username, check whether credential exists before requesting confirmation from frontend 2024-11-25 11:22:27 -05:00
jfmonty2 9bc9cb56c1 finish extremely basic implementation of docker credentials 2024-11-25 07:58:02 -05:00
jfmonty2 8bcdc5420a add CliRequest variants to store/erase docker credentials 2024-11-25 07:58:02 -05:00
jfmonty2 0a355c299b working implementation of docker get 2024-11-25 07:58:02 -05:00
jfmonty2 192d9058c3 send SaveCredential request to frontend on docker store 2024-11-25 07:58:02 -05:00
jfmonty2 b88b32d0f1 add Docker credentials to app and CLI 2024-11-25 07:58:02 -05:00
jfmonty2 12c97c4a7d start working on docker helper 2024-11-25 07:58:02 -05:00
jfmonty2 97528d65d6 link visibility of passphrase inputs on EnterPassphrase page 2024-11-24 09:37:33 -05:00
jfmonty2 295698e62f focus unlock input when window is focused 2024-09-18 09:29:14 -04:00
jfmonty2 3b61aa924a test CLI credentials against main app 2024-07-21 06:38:25 -04:00
jfmonty2 02ba19d709 switch to clap derive instead of builder 2024-07-15 14:54:25 -04:00
jfmonty2 55801384eb split into workspace so CLI can be a standalone crate 2024-07-15 10:34:51 -04:00
jfmonty2 27c2f467c4 fix cli invocations in gui entrypoint 2024-07-14 20:51:49 -04:00
jfmonty2 cab5ec40cc make server_addr configurable for client 2024-07-12 14:50:36 -04:00
jfmonty2 5cf848f7fe clean up warnings 2024-07-11 06:04:56 -04:00
jfmonty2 a32e36be7e fix RSA key signatures 2024-07-04 21:57:27 -04:00
jfmonty2 10231df860 add alternate entry mode for ssh keys 2024-07-03 16:28:31 -04:00
jfmonty2 ae93a57aab v0.5.0 2024-07-03 14:56:35 -04:00
jfmonty2 9fd355b68e finish SSH key support 2024-07-03 14:54:10 -04:00
jfmonty2 00089d7efb fix compiler warnings 2024-07-03 06:47:25 -04:00
jfmonty2 0124f77f7b initial working implementation of ssh agent 2024-07-03 06:33:58 -04:00
jfmonty2 6711ce2c43 finish manage ui for ssh keys 2024-07-02 09:57:02 -04:00
jfmonty2 a3a11897c2 persistence for ssh keys 2024-07-01 13:27:20 -04:00
jfmonty2 5e6542d08e initial ssh key model and creation ui 2024-07-01 06:38:46 -04:00
jfmonty2 f311fde74e fix permissions errors and terminal launching 2024-06-29 20:42:51 -04:00
jfmonty2 acc5c71bfa rework error alerts 2024-06-28 20:35:18 -04:00
jfmonty2 504c0b4156 add passphrase reset 2024-06-28 11:19:52 -04:00
jfmonty2 bf0a2ca72d finish manage-credentials page and rework home screen 2024-06-28 06:25:55 -04:00
jfmonty2 bb980c5eef continue working on default credentials 2024-06-26 22:24:44 -04:00
jfmonty2 ce7d75f15a almost finish refactoring PersistentCredential trait 2024-06-26 15:01:07 -04:00
jfmonty2 37b44ddb2e start refactoring for default credentials 2024-06-26 11:10:50 -04:00
jfmonty2 8c668e51a6 still in progress 2024-06-25 15:19:29 -04:00
jfmonty2 9928996fab get backend running 2024-06-19 05:10:55 -04:00
jfmonty2 d0a2532c27 start working on generalizing credential logic 2024-06-16 07:08:10 -04:00
jfmonty2 0491cb5790 fix error popup on startup 2024-06-03 01:33:35 -04:00
jfmonty2 816bd7db00 upgrade to tauri 2.0 beta 2024-06-02 17:20:37 -04:00
jfmonty2 b165965289 update todo 2024-05-08 11:37:07 -04:00
jfmonty2 86896d68c2 update Cargo.lock 2024-02-24 19:42:39 -08:00
jfmonty2 64a2927b94 return to Approve screen after cancelling unlock during request approval 2024-02-07 13:03:12 -08:00
jfmonty2 87617a0726 add ui for idle timeout 2024-02-06 20:27:51 -08:00
jfmonty2 141334f7e2 add idle timeout and version on settings screen 2024-01-31 13:14:08 -08:00
jfmonty2 69f6a39396 change tray menu text when toggling visibility 2024-01-26 21:03:45 -08:00
jfmonty2 70e23c7e20 add version to BaseCredentials 2024-01-23 10:58:39 -08:00
jfmonty2 1df849442e cancel approval flow on frontend when request is abandoned by client 2024-01-21 13:46:39 -08:00
jfmonty2 7fdb336c79 rework approval buttons and add hotkey for base approval 2024-01-20 11:06:27 -08:00
jfmonty2 46b8d810c5 allow user to choose whether to send base credentials at approval screen 2024-01-10 17:10:14 -08:00
jfmonty2 dd40eb379e update dependencies 2024-01-10 16:31:10 -08:00
Joseph Montanaro 13545ac725 v0.4.1 2023-11-09 14:25:20 -08:00
Joseph Montanaro 040a01536a work around Gnome focus-stealing prevention 2023-11-09 14:24:44 -08:00
Joseph Montanaro 4e2a90b15b remove old client info code 2023-11-09 13:46:15 -08:00
jfmonty2 e0d919ed4a fix Windows pipe server 2023-10-09 16:29:41 -07:00
jfmonty2 3f4efc5f8f bump version to 0.4.0 2023-10-09 10:06:28 -07:00
jfmonty2 4881b90b0b merge branch 'pipe' 2023-10-09 08:54:26 -07:00
jfmonty2 1b749a857c disable hotkeys if initial registration fails 2023-10-09 08:50:31 -07:00
jfmonty2 2079f99d04 bump version to 0.3.4 2023-10-08 22:53:22 -07:00
jfmonty2 5e0ffc1155 use save dialog for settings instead of autosaving 2023-10-08 22:06:30 -07:00
jfmonty2 d4fa8966b2 add unix listener, split win/unix into separate submodules 2023-09-23 11:10:54 -07:00
jfmonty2 a293d8f92c ignore .env so it can be system-specific 2023-09-22 12:43:44 -07:00
Joseph Montanaro 367a140e2a disable keyboard shortcuts if registration fails 2023-09-21 14:55:02 -07:00
jfmonty2 4b06dce7f4 keep working on cli shortcuts, unify visibility management 2023-09-21 10:44:35 -07:00
jfmonty2 47a3e1cfef start work on invoking shortcuts from CLI 2023-09-18 20:13:56 -07:00
jfmonty2 1047818fdc basic implementation of named-pipe server 2023-09-18 20:13:29 -07:00
Joseph Montanaro 3d093a3a45 show version in cli 2023-09-14 15:22:38 -07:00
Joseph Montanaro 992d2a4d06 show non-fatal setup errors on home screen instead of in popup 2023-09-14 15:13:19 -07:00
Joseph Montanaro 12f0f187a6 update cargo and npm 2023-09-14 12:49:45 -07:00
jfmonty2 997e8b419f handle setup errors more gracefully 2023-09-13 11:06:40 -07:00
jfmonty2 1d9132de3b make hotkey configuration more timing tolerant 2023-09-12 21:46:25 -07:00
Joseph Montanaro e1c2618dc8 bump version 2023-09-12 15:31:03 -07:00
Joseph Montanaro a7df7adc8e Ignore keyup events for modifier keys 2023-09-12 15:27:15 -07:00
Joseph Montanaro 03d164c9d3 Inherit rehide flag from existing request if present 2023-09-12 14:10:57 -07:00
jfmonty2 f522674a1c don't remove request from state until after re-hiding window 2023-09-12 11:47:33 -07:00
jfmonty2 51fcccafa2 fix os type calculation and bump version 2023-09-11 16:18:05 -07:00
jfmonty2 e3913ab4c9 add todo list 2023-09-11 16:11:06 -07:00
jfmonty2 c16f21bba3 Merge branch 'terminal' 2023-09-11 16:10:58 -07:00
jfmonty2 61d9acc7c6 request unlock/credentials when terminal is launched from locked/empty state 2023-09-11 16:00:58 -07:00
jfmonty2 8d7b01629d make keybinds configurable 2023-09-10 14:04:09 -07:00
jfmonty2 5685948608 add hotkeys to show window and launch terminal 2023-09-09 07:29:57 -07:00
jfmonty2 c98a065587 make terminal emulator configurable 2023-09-09 06:30:19 -07:00
jfmonty2 e46c3d2b4d tweak home screen 2023-09-05 06:12:26 -07:00
jfmonty2 fa228acc3a use svg animation for spinner 2023-08-06 21:25:24 -07:00
jfmonty2 e7e0f9d33e very basic launch button 2023-08-03 22:08:24 -07:00
jfmonty2 a51b20add7 combine ExecError with LaunchError and use Session::try_get() instead of matching 2023-08-03 21:57:55 -07:00
Joseph Montanaro 890f715388 usable backend for terminal launch 2023-08-03 16:35:15 -07:00
jfmonty2 89bc74e644 start working on terminal launcher 2023-08-02 19:57:37 -07:00
Joseph Montanaro 60c24e3ee4 don't autohide on first launch 2023-07-11 16:13:20 -07:00
Joseph Montanaro 486001b584 improve display of GetSessionError 2023-07-11 14:34:54 -07:00
Joseph Montanaro 52c949e396 v0.2.3 2023-07-11 10:35:56 -07:00
Joseph Montanaro d7c5c2f37b update dependencies 2023-07-11 09:52:13 -07:00
Joseph Montanaro ae5b8f31db remove spinner when unlock fails 2023-07-11 09:50:35 -07:00
jfmonty2 c260e37e78 cryptography notes 2023-05-19 10:04:48 -07:00
jfmonty2 7501253970 add separate binary for Windows CLI 2023-05-15 13:09:26 -07:00
jfmonty2 5b9c711008 fix subprocess exec for unix 2023-05-09 09:47:11 -07:00
jfmonty2 ddd1005067 switch crypto implementation and add spinner 2023-05-08 22:14:35 -07:00
jfmonty2 e866a4a643 change location of dev db and bump version 2023-05-06 22:09:41 -07:00
jfmonty2 94400ba7d5 get host addr/port from database when requesting credentials 2023-05-06 16:56:45 -07:00
jfmonty2 616600687d add show/exec commands and refactor AppState 2023-05-06 12:01:56 -07:00
Joseph Montanaro e8b8dc2976 cargo update 2023-05-02 15:24:46 -07:00
Joseph Montanaro ddf865d0b4 switch to tokio RwLock instead of std 2023-05-02 15:24:35 -07:00
jfmonty2 96bbc2dbc2 session renewal 2023-05-02 11:33:18 -07:00
jfmonty2 161148d1f6 store base credentials as well as session credentials 2023-05-01 23:03:34 -07:00
jfmonty2 760987f09b show approval errors in approval view 2023-05-01 16:53:24 -07:00
jfmonty2 a75f34865e return to previous view after approval flow 2023-05-01 13:27:28 -07:00
jfmonty2 886fcd9bb8 restrictive CSP and tauri allowlist 2023-05-01 09:05:46 -07:00
jfmonty2 55775b6b05 move error dialog to trait 2023-04-30 14:10:21 -07:00
jfmonty2 871dedf0a3 display setup errors 2023-04-30 10:52:46 -07:00
jfmonty2 913148a75a minor tweaks 2023-04-29 10:01:45 -07:00
jfmonty2 e746963052 change frontpage image and toast animation 2023-04-28 22:34:50 -07:00
jfmonty2 b761d3b493 find data dir properly 2023-04-28 22:34:17 -07:00
jfmonty2 c5dcc2e50a handle errors on config update 2023-04-28 14:33:23 -07:00
jfmonty2 70d71ce14e restart listener when config changes 2023-04-28 14:33:04 -07:00
Joseph Montanaro 33a5600a30 prevent NumericSetting from accepting non-numeric inputs 2023-04-27 16:15:19 -07:00
Joseph Montanaro 741169d807 start on login 2023-04-27 14:24:08 -07:00
jfmonty2 ebc00a5df6 confirm passphrase 2023-04-26 17:13:58 -07:00
jfmonty2 c2cc007a81 display tweaks and approval page timing 2023-04-26 17:06:37 -07:00
jfmonty2 4aab08e6f0 save settings to db 2023-04-26 15:49:08 -07:00
jfmonty2 12d9d733a5 fix circular imports from routing 2023-04-26 13:05:51 -07:00
jfmonty2 35271049dd settings page 2023-04-25 22:10:28 -07:00
jfmonty2 6f9cd6b471 move app state to store 2023-04-25 08:49:00 -07:00
jfmonty2 865b7fd5c4 add settings page 2023-04-24 22:18:55 -07:00
jfmonty2 f35352eedd links, navs, and more 2023-04-24 22:16:25 -07:00
jfmonty2 53580d7919 rework routing 2023-04-24 12:05:11 -07:00
jfmonty2 049b81610d rewrite frontend with DaisyUI 2023-04-23 22:29:12 -07:00
Joseph Montanaro fd60899f16 don't re-hide when a request comes in while showing approval screen 2023-04-21 11:18:20 -07:00
Joseph Montanaro e0c4c849dc serializable structured errors 2022-12-29 16:40:48 -08:00
Joseph Montanaro cb26201506 unproductive flailing 2022-12-28 15:48:25 -08:00
Joseph Montanaro 992e3c8db2 build improvements 2022-12-28 10:16:06 -08:00
Joseph Montanaro 4956b64371 only print incoming requests in debug mode 2022-12-28 08:54:08 -08:00
jfmonty2 df6b362a31 return structured errors from commands (wip) 2022-12-23 11:34:17 -08:00
jfmonty2 2943634248 button component 2022-12-22 21:50:09 -08:00
jfmonty2 06f5a1af42 icon picker component 2022-12-22 19:53:14 -08:00
Joseph Montanaro 61d674199f store config in database, macro for state access 2022-12-22 16:36:32 -08:00
Joseph Montanaro 398916fe10 use different ports for dev and live modes 2022-12-21 16:22:24 -08:00
Joseph Montanaro bf4c46238e move re-hide to main request handler 2022-12-21 16:04:12 -08:00
Joseph Montanaro 5ffa55c03c basic system tray functionality 2022-12-21 14:49:01 -08:00
Joseph Montanaro 50f0985f4f display client info and unlock errors to user 2022-12-21 13:43:37 -08:00
Joseph Montanaro 69475604c0 update npm deps 2022-12-21 11:02:19 -08:00
Joseph Montanaro 856b6f1e1b use thiserror for errors 2022-12-21 11:01:34 -08:00
Joseph Montanaro 414379b74e completely reorganize http server 2022-12-20 16:11:49 -08:00
Joseph Montanaro 80b92ebe69 generalize pid conversion 2022-12-20 13:01:44 -08:00
jfmonty2 983d0e8639 autofocus passphrase field in unlock view 2022-12-19 20:45:26 -08:00
Joseph Montanaro d77437cda8 ban list 2022-12-19 16:20:46 -08:00
Joseph Montanaro 3d5cbedae1 working basic flow 2022-12-19 15:26:44 -08:00
jfmonty2 10fd1d6028 more work on establishing credentials 2022-12-14 14:52:16 -08:00
jfmonty2 67705aa2d1 add credentials entry view 2022-12-13 21:50:34 -08:00
Joseph Montanaro 9055fa41aa switch to invokes instead of emits 2022-12-13 16:50:44 -08:00
Joseph Montanaro 48269855e5 start listing some specific threats 2022-12-13 10:58:52 -08:00
jfmonty2 1e4e1c9a5f encrypt/decrypt and db interaction 2022-12-03 21:47:09 -08:00
jfmonty2 196510e9a2 connect to db on startup 2022-12-02 22:59:13 -08:00
jfmonty2 e423df8e51 add to migration 2022-11-30 21:45:43 -08:00
Joseph Montanaro 2cfde4d841 first migration 2022-11-30 16:27:59 -08:00
Joseph Montanaro 7d462645b4 update readme because why not 2022-11-30 16:04:14 -08:00
Joseph Montanaro 8c271281f7 add security document 2022-11-30 15:29:41 -08:00
Joseph Montanaro 234d9e0471 fix some things 2022-11-29 16:13:09 -08:00
Joseph Montanaro 397928b8f1 reorganize backend 2022-11-28 16:16:33 -08:00
jfmonty2 c19b573b26 all is change; in change is all again made new 2022-11-27 22:03:15 -08:00
jfmonty2 cee43342b9 event-based routing? 2022-11-23 17:11:44 -08:00
60 changed files with 10373 additions and 6945 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[env]
# in development (i.e. when running through Cargo), store state in project directory
CREDDY_DATA_DIR = { value = "data", relative = true }
+14 -5
View File
@@ -1,8 +1,17 @@
dist **/creddy.db
**/node_modules # state directory for development work
src-tauri/target/ data/
.vscode
# just in case pacman/pkg
credentials* pacman/src
pacman/*.deb
pacman/*.tar.zst
# temporary worktree for master while we work on rewrite
master
# Added by cargo
/target
Generated
+9000
View File
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "creddy"
version = "0.7.0"
description = "A friendly AWS credentials manager"
authors = ["Joseph Montanaro"]
license = ""
repository = ""
default-run = "creddy"
edition = "2024"
[dependencies]
argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] }
base64ct = "1.8.3"
dirs = "7.0.0"
duckdb = { version = "1.20000.1", features = ["bundled"] }
getrandom = { version = "0.4.3", features = ["sys_rng"] }
gpui-kit = "0.7.0"
gpui-omarchy = "0.2.1"
include_dir = "0.7.4"
serde = "1.0.229"
serde_json = "1.0.154"
testresult = "0.4.2"
thiserror = "2.0.21"
[dev-dependencies]
tempfile = "3.27.0"
-1
View File
@@ -1 +0,0 @@
## Creddy: Low-friction AWS credential manager
+4
View File
@@ -0,0 +1,4 @@
fn main() {
// include_dir! only tracks files that already exist, so rebuild when one is added
println!("cargo:rerun-if-changed=migrations");
}
+9
View File
@@ -0,0 +1,9 @@
My original plan was to use [libsodium](https://doc.libsodium.org/) to handle encryption. However, the Rust bindings for libsodium are no longer actively maintained, which left me uncomfortable with using it. Instead, I switched to the [RustCrypto](https://github.com/RustCrypto) implementations of the same (or nearly the same) cryptographic primitives provided by libsodium.
Creddy makes use of two cryptographic primitives: A key-derivation function, which is currently `argon2id`, and a symmetric encryption algorithm, currently `XChaCha20Poly1305`.
* I chose `argon2id` because it's what libsodium uses, and because its difficulty parameters admit of very granular tuning.
* I chose `XChaCha20Poly1305` because it's _almost_ what libsodium uses - libsodium uses `XSalsa20Poly1305`, and it's my undersatnding that `XChaCha20Poly1305` is an evolution of the former. In both cases I use the eXtended variants, which make use of longer (24-byte) nonces than the non-X variants. This appealed to me because I wanted to be able to randomly generate a nonce every time I needed one, and I have seen [recommendations](https://latacora.micro.blog/2018/04/03/cryptographic-right-answers.html) that the 12-byte nonces used by the non-X variants are _juuust_ a touch small for that to be truly worry-free. The RustCrypto implementation of `XChaCha20Poly1305` has also been subject to a security audit, which is nice.
I tuned the `argon2id` parameters so that key-derivation would take ~800ms on my Ryzen 1600X. This is probably overkill, but I don't intend for key-derivation to be a frequent occurrence - no more than once a day, under normal circumstances. Taking in the neighborhood of 1 second seemed about the longest I could reasonably go.
**DISCLAIMER**: I am not a professional cryptographer, merely an interested amateur. While I've tried to be as careful as possible with selecting and making use of the cryptographic building blocks I've chosen here, there is always the possibility that I've screwed something up. If anyone would like to sponsor an _actual_ security review of Creddy by people who _actually_ know what they're doing instead of just what they've read on the internet, please let me know.
+50
View File
@@ -0,0 +1,50 @@
## Security considerations
The following is a list of security features that I hope to add eventually, in approximately the order in which I expect to add them.
* Request logging, obviously.
* Disallow all Tauri APIs except for `invoke` and `emit`. The sole job of the frontend should be to collect user interaction. Everything else should be mediated through the backend.
* Maximally-restrictive CSP - not sure if Tauri does this by default. Also not sure whether it will interfere with IPC to set a zero-access CSP.
* Allow user to specify a role to assume, so that role can be given narrower permissions. Allow falling back to the root credentials in the event that broader permissions are required. (Unsure about this one, is there a good way to make it low-friction?)
* To defend against the possibility that an attacker could replace, say, the `aws` executable with a malicious one that snarfs your credentials and then passes the command on to the real one, maybe track the path (and maybe even the hash) of the executable, and raise a warning if this is the first time we've seen that one? Using the hash would be safer, but would also introduce a lot of false positives, since every time the application gets updated it would trigger. On the other hand, users should presumably know when they've updated things, so maybe it would be ok. On the _other_ other hand, if somebody doesn't use `aws` very often then it might be weeks or months in between updating it and actually using the updated executable, in which case they probably won't remember that this is the first time they've used it since updating.
Another possible approach is to _watch_ the files in question, and alert the user whenever any of them changes. Presumably the user will know whether this change is expected or not.
* Downgrade privileges after launching. In particular, if possible, disallow any kind of outgoing network access (obviously we have to bind the listening socket, but maybe we can filter that down to _just_ the ability to bind that particular address/port) and filesystem access outside of state db. I think this is doable on Linux, although it may involve high levels of `seccomp` grossness. No idea whether it's possible on Windows. Probably possible on MacOS although it may require lengths to which I am currently unwilling to go (e.g. pay for a certificate from Apple or something.)
* "Panic button" - if a potential attack is detected (e.g. the user denies a request but Creddy discovers the request has already succeeded somehow), offer a one-click option to lock out the current IAM user. Sadly, you can't revoke session tokens, so this is the only way to limit a potential compromise. Obviously this would require the current user having the ability to revoke their own IAM permissions.)
* Some kind of Yubikey or other HST integration. (Optional, since not everyone will have a HST.) This comes in two flavors:
1. (Probably doable) Store the encryption key for the passphrase on the HST, and ask the HST to decrypt the passphrase instead of asking the user to enter it. This has the advantage of being a) lower-friction, since the user doesn't have to type in the passphrase, and b) more secure, since the application code never sees the encryption key.
2. (Less doable) Store the actual AWS secret key on the HST, and then ask the HST to just sign the whole `GetSessionToken` request. This requires that the HST support the exact signing algorithm required by AWS, which a) it probably doesn't, and b) is subject to change anyway. So this is probably not doable, but it's worth at least double-checking, since it would provide the maximum theoretical level of security. (That is, after initial setup, the application would never again see the long-lived AWS secret key.)
## Threat model
Who exactly are we defending against and why?
The basic idea behind Creddy is that it provides "gap coverage" between two wildly different security models: 1) the older, user-based model, where all code executing as a given user is assumed to have the same level of trust, and 2) the newer, application-based model (most clearly seen on mobile devices) where that bondary instead exists around each _application_.
The unfortunate reality is that desktop environments are unlikely to adopt the latter model any time soon, if ever. This is primarily due to friction: Per-application security is a nightmare to manage. The only reason it works at all on mobile devices is because most mobile apps eschew the local device in favor of cloud-backed services where they can, e.g. for file storage. Arguably, the higher-friction trust model of mobile environments (along with the frequently-replaced nature of mobile devices) is in part _why_ mobile apps tend to be cloud-first.
Regardless, we live in a world where it's difficult to run untrusted code without giving it an inordinate level of access to the machine on which it runs. Creddy attempts to prevent that access from including your AWS credentials. The threat model is thus "untrusted code running under your user". This is especially likely to occur in the form of a supply-chain attack, where the compromised code is not your own but rather a dependency, or a dependency of a dependency, etc.
## Particular attacks
There are lots of ways that I can imagine someone might try to circumvent Creddy's protection. Most of them require that the attacker be targeting Creddy in particular, rather than just "AWS credentials generally". In addition, most of them are "noisy" - that is, there's a good chance that the attack will alert the user to the fact that they are being attacked. This is generally something attackers try to avoid, since an easily-detected attack is likely to be shut down before it can spread very far.
### Tricking Creddy into allowing a request that it shouldn't
If an attacker is able to compromise Creddy's frontend, e.g. via a JS library that Creddy relies on, they could forge "request accepted" responses and cause the backend to hand out credentials to an unauthorized client. Most likely, the user would immediately be alerted to the fact that Something Is Up because Creddy would pop up requesting then permission, and then immediately disappear again because the request had been approved. Additionally, the request and (hopefully) what executable made it would be logged.
### Tricking the user into allowing a request they didn't intend to
If an attacker can edit the user's .bashrc or similar, they could theoretically insert a function or pre-command hook that wraps, say, the `aws` command, and dump the credentials before continuing on with the user's command. The attacker could inject the credentials into the environment before running the original command, so as to avoid alerting the user by issuing a second credentials request.
Another attack along the same lines would be replacing the `aws` executable, or any other executable that is always expected to ask for AWS credentials, with a malicious wrapper that snarfs the credentials before passing them through to the original command. Creddy could defend against this to a certain extent by storing the hash of the executable, as discussed above.
### Pretending to be the user
Most desktop environments don't prevent applications from simulating user-input events such as mouse clicks and keypresses. An attacker could issue a credentials request, then immediately simulate whatever hotkey or mouse click Creddy normally interprets as "confirm this request". To mitigate this Creddy could implement a minimum time for which it _must_ be on screen before dismissal. The attacker could try to wait for the machine to be unattended before executing this attack, but this is chancy and could still result in detection. The request would still be logged in any case.
### Twiddling with Creddy's persistent state
The solutions to or mitigations for a lot of these attacks rely on Creddy being able to assume that its local database hasn't been tampered with. Unfortunately, given that our threat model is "other code running as the same user", this isn't a safe assumption.
The solution to this problem is probably just to encrypt the entire database. This introduces a bit of complexity since certain settings, like `start_on_login` and `start_minimized`, will need to be accessible before the app is unlocked,but these settings can probably just be stashed alongside the database and kept in sync on every config save.
+26
View File
@@ -0,0 +1,26 @@
## Definitely
* ~~Switch to "process" provider for AWS credentials (much less hacky)~~
* ~~Frontend needs to react when request is cancelled from backend~~
* ~~Session timeout~~
* ~~Fix rehide behavior when new request comes in while old one is still being resolved~~
* ~~Switch tray menu item to Hide when window is visible~~
* Clear password input after unlock fails
* Indicate on approval screen when additional requests are pending
* Additional hotkey configuration (approve/deny at the very least)
* Logging
* Icon
* Auto-updates
* ~~SSH key handling~~
* ~~Docker credential helper~~
* Encrypted sync server
## Maybe
* Flatten error type hierarchy
* Rehide after terminal launch from locked
* Generalize Request across both credentials and terminal launch?
* Make hotkey configuration a little more tolerant of slight mistiming
* Distinguish between request that was denied and request that was canceled (e.g. due to error)
* Use atomic types for primitive state values instead of RwLock'd types
* Rework approval flow to be a fullscreen overlay instead of mixing with normal navigation (as more views are added the pain of the current situation will only increase)
-25
View File
@@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Svelte</title>
<style>
body {
margin: 0;
display: grid;
align-items: center;
justify-items: center;
min-width: 100vw;
min-height: 100vh;
}
</style>
</head>
<body class="bg-zinc-800">
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
View File
Whitespace-only changes.
+4
View File
@@ -0,0 +1,4 @@
-- config will only ever hold a single row with a single value
CREATE TABLE config (value JSON);
-- seed it with an empty object, which will be populated with default values on deserialization
INSERT INTO config VALUES ('{}');
-2687
View File
File diff suppressed because it is too large. Load diff
-22
View File
@@ -1,22 +0,0 @@
{
"name": "creddy",
"version": "0.1.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^1.0.1",
"@tauri-apps/cli": "^1.0.5",
"autoprefixer": "^10.4.8",
"postcss": "^8.4.16",
"svelte": "^3.49.0",
"tailwindcss": "^3.1.8",
"vite": "^3.0.7"
},
"dependencies": {
"@tauri-apps/api": "^1.0.2"
}
}
-6
View File
@@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
-3805
View File
File diff suppressed because it is too large. Load diff
-31
View File
@@ -1,31 +0,0 @@
[package]
name = "app"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
license = ""
repository = ""
default-run = "app"
edition = "2021"
rust-version = "1.57"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.0.4", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.5", features = ["api-all"] }
sodiumoxide = "0.2.7"
tokio = { version = ">=1.19", features = ["full"] }
# futures = ">=0.3.21"
[features]
# by default Tauri runs in production mode
# when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL
default = [ "custom-protocol" ]
# this feature is used used for production builds where `devPath` points to the filesystem
# DO NOT remove this
custom-protocol = [ "tauri/custom-protocol" ]
-3
View File
@@ -1,3 +0,0 @@
fn main() {
tauri_build::build()
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

-42
View File
@@ -1,42 +0,0 @@
use std::fmt::{Display, Formatter};
use std::convert::From;
use std::str::Utf8Error;
// use tokio::sync::oneshot::error::RecvError;
// Represents errors encountered while handling an HTTP request
pub enum RequestError {
StreamIOError(std::io::Error),
InvalidUtf8,
MalformedHttpRequest,
RequestTooLarge,
}
impl From<tokio::io::Error> for RequestError {
fn from(e: std::io::Error) -> RequestError {
RequestError::StreamIOError(e)
}
}
impl From<Utf8Error> for RequestError {
fn from(_e: Utf8Error) -> RequestError {
RequestError::InvalidUtf8
}
}
// impl From<RecvError> for RequestError {
// fn from (_e: RecvError) -> RequestError {
// RequestError::
// }
// }
impl Display for RequestError {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
use RequestError::*;
match self {
StreamIOError(e) => write!(f, "Stream IO error: {e}"),
InvalidUtf8 => write!(f, "Could not decode UTF-8 from bytestream"),
MalformedHttpRequest => write!(f, "Maformed HTTP request"),
RequestTooLarge => write!(f, "HTTP request too large"),
}
}
}
-99
View File
@@ -1,99 +0,0 @@
use std::io;
use std::net::SocketAddrV4;
use tokio::net::{TcpListener, TcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tauri::{AppHandle, Manager};
mod errors;
use errors::RequestError;
pub async fn serve(addr: SocketAddrV4, app_handle: AppHandle) -> io::Result<()> {
let listener = TcpListener::bind(&addr).await?;
println!("Listening on {addr}");
loop {
let new_handle = app_handle.app_handle();
match listener.accept().await {
Ok((stream, _)) => {
tokio::spawn(async {
if let Err(e) = handle(stream, new_handle).await {
eprintln!("{e}");
}
});
},
Err(e) => {
println!("Error accepting connection: {e}");
}
}
}
}
// it doesn't really return a String, we just need to placate the compiler
async fn stall(stream: &mut TcpStream) -> Result<String, tokio::io::Error> {
let delay = std::time::Duration::from_secs(1);
loop {
tokio::time::sleep(delay).await;
stream.write(b"x").await?;
}
}
async fn handle(mut stream: TcpStream, app_handle: AppHandle) -> Result<(), RequestError> {
let mut buf = [0; 8192]; // it's what tokio's BufReader uses
let mut n = 0;
loop {
n += stream.read(&mut buf[n..]).await?;
if &buf[(n - 4)..n] == b"\r\n\r\n" {break;}
if n == buf.len() {return Err(RequestError::RequestTooLarge);}
}
println!("{}", std::str::from_utf8(&buf).unwrap());
stream.write(b"HTTP/1.0 200 OK\r\n").await?;
stream.write(b"Content-Type: application/json\r\n").await?;
stream.write(b"X-Creddy-delaying-tactic: ").await?;
let creds = tokio::select!{
r = stall(&mut stream) => r?, // this will never return Ok, just Err if it can't write to the stream
c = get_creds(&app_handle) => c?,
};
stream.write(b"\r\nContent-Length: ").await?;
stream.write(creds.as_bytes().len().to_string().as_bytes()).await?;
stream.write(b"\r\n\r\n").await?;
stream.write(creds.as_bytes()).await?;
stream.write(b"\r\n\r\n").await?;
Ok(())
}
use tokio::io::{stdin, stdout, BufReader, AsyncBufReadExt};
use crate::storage;
use tokio::sync::oneshot;
async fn get_creds(app_handle: &AppHandle) -> io::Result<String> {
app_handle.emit_all("credentials-request", ()).unwrap();
// let mut out = stdout();
// out.write_all(b"Enter passphrase: ").await?;
// out.flush().await?;
let (tx, rx) = oneshot::channel();
app_handle.once_global("passphrase-entered", |event| {
match event.payload() {
Some(p) => {tx.send(p.to_string());}
None => {tx.send("".to_string());} // will fail decryption, we just need to unblock the outer function
}
});
// Error is only returned if the rx is closed/dropped before receiving, which should never happen
let passphrase = rx.await.unwrap();
// let mut passphrase = String::new();
// let mut reader = BufReader::new(stdin());
// reader.read_line(&mut passphrase).await?;
Ok(storage::load(&passphrase.trim()))
}
-30
View File
@@ -1,30 +0,0 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use std::str::FromStr;
// use tokio::runtime::Runtime;
mod storage;
mod http;
fn main() {
tauri::Builder::default()
.setup(|app| {
let addr = std::net::SocketAddrV4::from_str("127.0.0.1:12345").unwrap();
tauri::async_runtime::spawn(http::serve(addr, app.handle()));
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
// let addr = std::net::SocketAddrV4::from_str("127.0.0.1:12345").unwrap();
// let rt = Runtime::new().unwrap();
// rt.block_on(http::serve(addr)).unwrap();
// let creds = std::fs::read_to_string("credentials.json").unwrap();
// storage::save(&creds, "correct horse battery staple");
}
-31
View File
@@ -1,31 +0,0 @@
use sodiumoxide::crypto::{pwhash, secretbox};
pub fn save(data: &str, passphrase: &str) {
let salt = pwhash::Salt([0; 32]); // yes yes, just for now
let mut kbuf = [0; secretbox::KEYBYTES];
pwhash::derive_key_interactive(&mut kbuf, passphrase.as_bytes(), &salt)
.expect("Couldn't compute password hash. Are you out of memory?");
let key = secretbox::Key(kbuf);
let nonce = secretbox::Nonce([0; 24]); // we don't care about e.g. replay attacks so this might be safe?
let encrypted = secretbox::seal(data.as_bytes(), &nonce, &key);
//todo: store in a database, along with salt, nonce, and hash parameters
std::fs::write("credentials.enc", &encrypted).expect("Failed to write file.");
//todo: key is automatically zeroed, but we should use 'zeroize' or something to zero out passphrase and data
}
pub fn load(passphrase: &str) -> String {
let salt = pwhash::Salt([0; 32]);
let mut kbuf = [0; secretbox::KEYBYTES];
pwhash::derive_key_interactive(&mut kbuf, passphrase.as_bytes(), &salt)
.expect("Couldn't compute password hash. Are you out of memory?");
let key = secretbox::Key(kbuf);
let nonce = secretbox::Nonce([0; 24]);
let encrypted = std::fs::read("credentials.enc").expect("Failed to read file.");
let decrypted = secretbox::open(&encrypted, &nonce, &key).expect("Failed to decrypt.");
String::from_utf8(decrypted).expect("Invalid utf-8")
}
-66
View File
@@ -1,66 +0,0 @@
{
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"build": {
"beforeBuildCommand": "npm run build",
"beforeDevCommand": "npm run dev",
"devPath": "http://localhost:5173",
"distDir": "../dist"
},
"package": {
"productName": "creddy",
"version": "0.1.0"
},
"tauri": {
"allowlist": {
"all": true
},
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "",
"deb": {
"depends": []
},
"externalBin": [],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.tauri.dev",
"longDescription": "",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "",
"targets": "all",
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
},
"security": {
"csp": null
},
"updater": {
"active": false
},
"windows": [
{
"fullscreen": false,
"height": 600,
"resizable": true,
"title": "Creddy",
"width": 800
}
]
}
}
-13
View File
@@ -1,13 +0,0 @@
<script>
import { emit, listen } from '@tauri-apps/api/event';
import Home from './views/Home.svelte';
import Approve from './views/Approve.svelte';
let activeComponent = Home;
listen('credentials-request', (event) => {
activeComponent = Approve;
})
</script>
<svelte:component this={activeComponent} />
+3
View File
@@ -0,0 +1,3 @@
mod passphrase_input;
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
+97
View File
@@ -0,0 +1,97 @@
use gpui_kit::assets::IconName;
use gpui_kit::base::input::{InputEvent, InputState};
use gpui_kit::{
App, AppContext, Context, Entity, EventEmitter, IntoElement, Render, SharedString, Styled,
Subscription, Window,
};
use gpui_omarchy::{ButtonVariant, icon_button, input};
/// A masked passphrase field with a show/hide toggle.
///
/// The `show` flag is passed in from outside so that it can be shared
/// (e.g. passphrase and confirm-passphrase inputs should share it).
pub struct PassphraseInput {
state: Entity<InputState>,
show: Entity<bool>,
_subscriptions: Vec<Subscription>,
}
pub enum PassphraseInputEvent {
/// The user pressed Enter in the field.
Submit,
/// The field's text changed.
Change,
/// The field lost focus.
Blur,
}
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
impl PassphraseInput {
pub fn new(show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let masked = !*show.read(cx);
let state = cx.new(|cx| {
InputState::new(window, cx)
.masked(masked)
.placeholder("correct horse battery staple")
});
// keep this field's masking in sync with the shared flag
let sync_mask = cx.observe_in(&show, window, |this, show, window, cx| {
let masked = !*show.read(cx);
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx));
cx.notify();
});
// re-emit the subset of input events that consumers care about
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
let event = match event {
InputEvent::PressEnter { .. } => PassphraseInputEvent::Submit,
InputEvent::Change => PassphraseInputEvent::Change,
InputEvent::Blur => PassphraseInputEvent::Blur,
InputEvent::Focus => return,
};
cx.emit(event);
});
Self {
state,
show,
_subscriptions: vec![sync_mask, forward],
}
}
pub fn value(&self, cx: &App) -> SharedString {
self.state.read(cx).value()
}
pub fn focus(&self, window: &mut Window, cx: &mut App) {
self.state.update(cx, |state, cx| state.focus(window, cx));
}
fn toggle_show(&mut self, cx: &mut Context<Self>) {
self.show.update(cx, |show, cx| {
*show = !*show;
cx.notify();
});
}
}
impl Render for PassphraseInput {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (icon, label) = if *self.show.read(cx) {
(IconName::EyeOff, "Hide passphrase")
}
else {
(IconName::Eye, "Show passphrase")
};
input("passphrase", &self.state, window, cx)
.w_full()
.suffix(
icon_button("toggle-show", icon, label, ButtonVariant::Secondary, cx)
.on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))),
)
}
}
+246
View File
@@ -0,0 +1,246 @@
use std::env;
use std::ffi::OsString;
use std::fs::File;
use std::path::{Path, PathBuf};
use gpui_kit::Global;
use serde::{Serialize, Deserialize};
use crate::error::CreddyError;
/// Config that doesn't need to or can't be stored in the encrypted db
/// (such as settings that must be known at startup, before unlock).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicConfig {
db_salt: [u8; 32],
}
impl PublicConfig {
/// Construct a PublicConfig with default values, in case there is nothing saved on disk
pub fn default() -> PublicConfig {
let mut db_salt = [0u8; 32];
let _ = getrandom::fill(&mut db_salt);
PublicConfig { db_salt }
}
/// Load non-sensitive config from disk.
pub fn load(path: &Path) -> Result<PublicConfig, CreddyError> {
if path.exists() {
let f = File::open(path)?;
serde_json::from_reader(f).map_err(|e| CreddyError::InvalidJSON(e))
}
else {
Ok(PublicConfig::default())
}
}
pub fn save(&self, path: &Path) -> Result<(), CreddyError> {
let file = File::create(path)?;
serde_json::to_writer(file, self)?;
Ok(())
}
}
/// Config that can be stored in the encrypted db
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivateConfig {
rehide_ms: u64,
}
impl Default for PrivateConfig {
fn default() -> PrivateConfig {
PrivateConfig {
rehide_ms: 1000,
}
}
}
#[derive(Debug, Clone)]
pub struct AppConfig {
pub data_dir: PathBuf,
pub db_salt: [u8; 32],
pub rehide_ms: u64,
}
impl AppConfig {
/// Load config from disk, using defaults for non-public values.
pub fn load() -> Result<AppConfig, CreddyError> {
let data_dir = AppConfig::resolve_data_dir(
env::var_os("CREDDY_DATA_DIR"),
dirs::data_dir(),
)?;
AppConfig::load_from(data_dir)
}
pub fn load_from(data_dir: PathBuf) -> Result<AppConfig, CreddyError> {
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
let private_config = PrivateConfig::default();
Ok(AppConfig::from_parts(data_dir, public_config, private_config))
}
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
creddy_data_dir
.map(PathBuf::from)
.or_else(|| platform_data_dir.map(|d| d.join("creddy")))
.ok_or(CreddyError::DataDirNotFound)
}
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
fn from_parts(data_dir: PathBuf, public: PublicConfig, private: PrivateConfig) -> AppConfig {
AppConfig {
data_dir,
db_salt: public.db_salt,
rehide_ms: private.rehide_ms,
}
}
pub fn merge_private(&mut self, private: PrivateConfig) {
self.rehide_ms = private.rehide_ms;
}
pub fn public_config_path(&self) -> PathBuf {
self.data_dir.join("public_config.json")
}
pub fn db_path(&self) -> PathBuf {
self.data_dir.join("creddy.duckdb")
}
pub fn public_config(&self) -> PublicConfig {
PublicConfig {
db_salt: self.db_salt,
}
}
pub fn private_config(&self) -> PrivateConfig {
PrivateConfig {
rehide_ms: self.rehide_ms,
}
}
}
impl Default for AppConfig {
fn default() -> AppConfig {
// AppConfig::default will only be called for testing or to fill in
// remaining defaults when constructing otherwise, and data_dir is
// always specified otherwise
AppConfig::from_parts(
PathBuf::from(""),
PublicConfig::default(),
PrivateConfig::default(),
)
}
}
impl Global for AppConfig {}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
use testresult::TestResult;
#[test]
fn test_public_default() {
let conf = PublicConfig::default();
assert!(conf.db_salt.len() == 32);
}
#[test]
fn test_public_config_load_not_present() -> TestResult {
let p = tempfile::tempdir()?.path().join("public_config.json");
let conf = PublicConfig::load(&p)?;
assert!(conf.db_salt.len() == 32);
Ok(())
}
#[test]
fn test_public_config_load_present() -> TestResult {
let data_dir = tempfile::tempdir()?;
let p = data_dir.path().join("public_config.json");
let expected = PublicConfig::default(); // uses a random db salt
let f = File::create(&p)?;
serde_json::to_writer(f, &expected)?;
let loaded = PublicConfig::load(&p)?;
assert!(loaded.db_salt == expected.db_salt);
Ok(())
}
#[test]
fn test_config_load_not_present() -> TestResult {
let data_dir = tempfile::tempdir()?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
assert!(config.data_dir == data_dir.path());
assert!(config.db_salt.len() == 32);
Ok(())
}
#[test]
fn test_config_load_present() -> TestResult {
let data_dir = tempfile::tempdir()?;
let p = data_dir.path().join("public_config.json");
let public = PublicConfig::default(); // uses a random db salt
let f = File::create(&p)?;
serde_json::to_writer(f, &public)?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
assert!(config.data_dir == data_dir.path());
assert!(config.db_salt == public.db_salt);
Ok(())
}
#[test]
fn test_resolve_data_dir_override() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
Some(OsString::from("/tmp/creddy")),
None,
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test]
fn test_resolve_data_dir_default() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
None,
Some(PathBuf::from("/tmp")),
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test]
fn test_config_paths() {
let mut config = AppConfig::default();
config.data_dir = PathBuf::from("/tmp/creddy");
assert!(config.db_path() == PathBuf::from("/tmp/creddy/creddy.duckdb"));
assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json"));
}
#[test]
fn test_public_config_from_app_config() {
let mut config = AppConfig::default();
config.data_dir = PathBuf::from("/tmp/creddy");
let public = config.public_config();
assert!(public.db_salt == config.db_salt);
}
#[test]
fn test_public_config_save_load() -> TestResult {
let file = NamedTempFile::new()?;
let expected = PublicConfig::default();
expected.save(file.path())?;
let loaded = PublicConfig::load(file.path())?;
assert!(loaded.db_salt == expected.db_salt);
Ok(())
}
}
+54
View File
@@ -0,0 +1,54 @@
use crate::config::PrivateConfig;
use crate::error::CreddyError;
use super::Db;
impl Db {
pub fn load_private_config(&self) -> Result<PrivateConfig, CreddyError> {
let conn = self.connection.lock().unwrap();
let json: String = conn.query_row("SELECT value FROM config", [], |row| row.get(0))?;
let config: PrivateConfig = serde_json::from_str(&json)?;
Ok(config)
}
pub fn save_private_config(&self, config: &PrivateConfig) -> Result<(), CreddyError> {
let json = serde_json::to_string(&config)?;
let conn = self.connection.lock().unwrap();
conn.execute("INSERT INTO config VALUES (?);", [&json])?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use testresult::TestResult;
use tempfile::TempDir;
use crate::config::AppConfig;
use super::*;
fn test_db() -> Result<(Db, TempDir), CreddyError> {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
let db = Db::connect(&config, "correct horse battery staple")?;
Ok((db, data_dir))
}
#[test]
fn test_save_private_config() -> TestResult {
let (db, _data_dir) = test_db()?;
let private_config = PrivateConfig::default();
db.save_private_config(&private_config)?;
Ok(())
}
#[test]
fn test_load_priate_config() -> TestResult {
let (db, _data_dir) = test_db()?;
let private_config = PrivateConfig::default();
db.save_private_config(&private_config)?;
let loaded = db.load_private_config()?;
assert_eq!(loaded, private_config);
Ok(())
}
}
+174
View File
@@ -0,0 +1,174 @@
use duckdb::Connection;
use include_dir::{Dir, include_dir};
use crate::error::CreddyError;
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
struct Migration {
id: &'static str,
sql: &'static str,
}
/// Run all unapplied database migrations.
pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> {
apply_migrations(conn, &embedded_migrations())
}
/// Sorted list of migration files, checked for utf-8-ness at compile time.
fn embedded_migrations() -> Vec<Migration> {
let mut migrations: Vec<Migration> = MIGRATIONS_DIR
.files()
.filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
.map(|f| Migration {
// these are baked in at compile time, so a bad file is a build problem, not a runtime one
id: f.path().file_name().and_then(|n| n.to_str()).expect("migration filename is not UTF-8"),
sql: f.contents_utf8().expect("migration file is not UTF-8"),
})
.collect();
migrations.sort_by_key(|m| m.id);
migrations
}
/// Run a specific list of migrations. (Makes testing easier than always hard-coding)
fn apply_migrations(conn: &mut Connection, known: &[Migration]) -> Result<(), CreddyError> {
create_migrations_table(conn)?;
let applied = list_applied_migrations(conn)?;
// the applied migrations must be exactly the first N known ones
for (i, id) in applied.iter().enumerate() {
if known.get(i).is_some_and(|m| m.id == id) {
continue;
}
// at this point, either known[i] doesn't exist or doesn't match `id`
if known.iter().any(|m| m.id == id) {
return Err(CreddyError::MigrationOutOfOrder(id.clone()));
}
//
return Err(CreddyError::DbTooNew(id.clone()));
}
for migration in &known[applied.len()..] {
let tx = conn.transaction()?;
tx.execute_batch(migration.sql)?;
tx.execute("INSERT INTO _migrations (id) VALUES (?);", [migration.id])?;
tx.commit()?;
}
Ok(())
}
/// Create the migrations table if it doesn't exist already.
fn create_migrations_table(conn: &Connection) -> Result<(), CreddyError> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS _migrations (
id VARCHAR PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp
);",
)?;
Ok(())
}
/// List migrations that have been applied to this database, in the order they were applied.
fn list_applied_migrations(conn: &Connection) -> Result<Vec<String>, CreddyError> {
let mut stmt = conn.prepare("SELECT id FROM _migrations ORDER BY id;")?;
let ids = stmt
.query_map([], |row| row.get(0))?
.collect::<Result<Vec<String>, _>>()?;
Ok(ids)
}
#[cfg(test)]
mod tests {
use testresult::TestResult;
use super::*;
const FIRST: Migration = Migration {
id: "0001_first.sql",
sql: "CREATE TABLE a (x INTEGER);",
};
const SECOND: Migration = Migration {
id: "0002_second.sql",
sql: "CREATE TABLE b (x INTEGER); INSERT INTO b VALUES (1);",
};
fn table_exists(conn: &Connection, name: &str) -> duckdb::Result<bool> {
conn.query_row(
"SELECT count(*) > 0 FROM duckdb_tables() WHERE table_name = ?;",
[name],
|row| row.get(0),
)
}
#[test]
fn test_embedded_migrations_apply() -> TestResult {
let mut conn = Connection::open_in_memory()?;
migrate(&mut conn)?;
let applied = list_applied_migrations(&conn)?;
let expected: Vec<_> = embedded_migrations().iter().map(|m| m.id.to_string()).collect();
assert_eq!(applied, expected);
Ok(())
}
#[test]
fn test_apply_incrementally() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[FIRST])?;
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
// already-applied migrations are skipped, so re-running FIRST would fail if it weren't
apply_migrations(&mut conn, &[FIRST, SECOND])?;
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql", "0002_second.sql"]);
assert!(table_exists(&conn, "b")?);
Ok(())
}
#[test]
fn test_failed_migration_rolls_back() -> TestResult {
let mut conn = Connection::open_in_memory()?;
let broken = Migration {
id: "0002_broken.sql",
sql: "CREATE TABLE b (x INTEGER); this is not sql;",
};
let res = apply_migrations(&mut conn, &[FIRST, broken]);
assert!(matches!(res, Err(CreddyError::Db(_))));
// FIRST stays applied, but nothing from the broken migration survives
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
assert!(table_exists(&conn, "a")?);
assert!(!table_exists(&conn, "b")?);
Ok(())
}
#[test]
fn test_db_too_new() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[FIRST, SECOND])?;
// simulates running an older version of the app, which doesn't know about SECOND
match apply_migrations(&mut conn, &[FIRST]) {
Err(CreddyError::DbTooNew(id)) => assert_eq!(id, "0002_second.sql"),
res => panic!("Expected DbTooNew, got {res:?}"),
}
Ok(())
}
#[test]
fn test_migration_out_of_order() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[SECOND])?;
// FIRST sorts before an already-applied migration, so it was added after the fact
match apply_migrations(&mut conn, &[FIRST, SECOND]) {
Err(CreddyError::MigrationOutOfOrder(id)) => assert_eq!(id, "0002_second.sql"),
res => panic!("Expected MigrationOutOfOrder, got {res:?}"),
}
Ok(())
}
}
+182
View File
@@ -0,0 +1,182 @@
use std::fs;
use std::sync::Mutex;
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
use base64ct::{Base64, Encoding};
use duckdb::{
Connection,
params,
};
use crate::error::CreddyError;
use crate::config::AppConfig;
mod config;
mod migrations;
// tests take forever with production parameters, so we turn them down in dev
#[cfg(not(debug_assertions))]
const MEM_COST: u32 = 128 * 1024;
#[cfg(not(debug_assertions))]
const TIME_COST: u32 = 8;
#[cfg(not(debug_assertions))]
const PARALLELISM_COST: u32 = 4;
#[cfg(debug_assertions)]
const MEM_COST: u32 = 1024;
#[cfg(debug_assertions)]
const TIME_COST: u32 = 1;
#[cfg(debug_assertions)]
const PARALLELISM_COST: u32 = 1;
#[derive(Debug)]
pub struct Db {
connection: Mutex<Connection>,
}
impl Db {
/// Connect to the database, creating it if necessary.
pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> {
fs::create_dir_all(&config.data_dir)?;
// since we are about to make use of the salt stored in `config`, we need to save it now
config.public_config().save(&config.public_config_path())?;
let path = config.db_path()
.into_os_string()
.into_string()
.map_err(|s| CreddyError::InvalidPath(s))?;
let key = Db::derive_key(passphrase, &config.db_salt)?;
dbg!(&key);
let mut conn = Connection::open_in_memory()?;
conn.execute(
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
params![path, key],
)?;
// must come before migrating, or the tables end up in the in-memory db
conn.execute("USE creddy;", [])?;
migrations::migrate(&mut conn)?;
Ok(Self{ connection: Mutex::new(conn) })
}
/// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB
fn derive_key(passphrase: &str, salt: &[u8; 32]) -> Result<String, Argon2Error> {
let params = ParamsBuilder::new()
.m_cost(MEM_COST)
.t_cost(TIME_COST)
.p_cost(PARALLELISM_COST)
.build()
.unwrap(); // only errors if the given params are invalid
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
hasher.hash_password_into(passphrase.as_bytes(), salt, &mut key)?;
Ok(Base64::encode_string(&key))
}
}
#[cfg(test)]
mod tests {
use testresult::TestResult;
use duckdb::Error;
use super::*;
const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
const TEST_SALT: [u8; 32] = [0; 32];
// the result of hashing TEST_PASSPHRASE with TEST_SALT and encoding to Base64
const TEST_KEY: &'static str = "YvOfk7EXGX+SnvdGySbTtf8OXAXg3AGikvKxJOLkLOo=";
#[test]
fn test_connect_new() -> TestResult {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
let res = Db::connect(&config, TEST_PASSPHRASE);
assert!(res.is_ok());
// confirm that db is in fact encrypted
match Connection::open(&config.db_path()) {
Err(Error::DuckDBFailure(error, _desc)) => {
assert!(error.code == duckdb::ErrorCode::Unknown);
assert!(error.extended_code == 1);
},
Err(e) => panic!("Unexpected error type: {e:?}"),
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"),
};
// confirm that using a different passphrase won't work
let res = Db::connect(&config, "not the correct passphrase");
match res {
Err(CreddyError::Db(Error::DuckDBFailure(error, Some(desc)))) => {
assert!(error.code == duckdb::ErrorCode::Unknown);
assert!(error.extended_code == 1);
assert!(desc.contains("Wrong encryption key"));
},
Err(e) => panic!("Unexpected error type: {e:?}"),
Ok(_) => panic!("Should not be able to open database with a different passphrase"),
}
Ok(())
}
#[test]
fn test_connect_existing() -> TestResult {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
config.db_salt = TEST_SALT;
dbg!(TEST_KEY);
let conn = Connection::open_in_memory()?;
conn.execute(
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
params![&config.db_path().to_string_lossy(), TEST_KEY],
)?;
Db::connect(&config, TEST_PASSPHRASE)?;
Ok(())
}
#[test]
fn test_connect_create_dir() -> TestResult {
let tmp_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = tmp_dir.path().join("creddy");
// data_dir does not exist at this point
Db::connect(&config, TEST_PASSPHRASE)?;
Ok(())
}
#[test]
fn test_connect_migrates_attached_db() -> TestResult {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
let db = Db::connect(&config, TEST_PASSPHRASE)?;
// the migrations table should live in the encrypted db, not the in-memory one
let database: String = db.connection.lock().unwrap().query_row(
"SELECT database_name FROM duckdb_tables() WHERE table_name = '_migrations';",
[],
|row| row.get(0),
)?;
assert_eq!(database, "creddy");
Ok(())
}
#[test]
fn test_derive_key() -> TestResult {
let key = Db::derive_key(TEST_PASSPHRASE, &TEST_SALT)?;
dbg!(&key);
dbg!(TEST_KEY);
assert!(key == TEST_KEY);
Ok(())
}
}
+33
View File
@@ -0,0 +1,33 @@
use std::ffi::OsString;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum CreddyError {
#[error("Couldn't determine location for app state")]
DataDirNotFound,
#[error("Invalid path: {0:?}")]
InvalidPath(OsString),
#[error("Error from database: {0}")]
Db(#[from] duckdb::Error),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("Unable to hash password: {0}")]
PasswordHash(#[from] argon2::Error),
#[error("Unable to get random data: {0}")]
Entropy(#[from] getrandom::Error),
#[error("This database was created by a newer version of Creddy (unknown migration {0})")]
DbTooNew(String),
#[error("Migration {0} was applied before an earlier migration that hasn't been")]
MigrationOutOfOrder(String),
#[error("Invalid JSON: {0}")]
InvalidJSON(#[from] serde_json::Error),
}
-30
View File
@@ -1,30 +0,0 @@
/* Simple asynchronous queue.
To make `get` blocking, we create a new promise and store its `resolve` function in `resolvers`.
The next time an item is added to the queue, it will be resolved.
*/
export default function() {
return {
items: [],
resolvers: [],
put(item) {
this.items.push(item);
if (this.resolvers.length > 0) {
let resolver = this.resolvers.shift();
resolver();
}
},
async get() {
if (this.items.length === 0) {
await new Promise((resolve, reject) => {
this.resolvers.push(resolve);
})
}
return this.items.shift();
},
}
}
-8
View File
@@ -1,8 +0,0 @@
import './style.css';
import App from './App.svelte';
const app = new App({
target: document.getElementById('app')
})
export default app;
+70
View File
@@ -0,0 +1,70 @@
use gpui_kit::{
AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div,
};
use gpui_omarchy::ActiveTheme;
mod components;
mod config;
mod db;
mod error;
mod screens;
mod session;
#[cfg(test)]
mod test_data;
use config::AppConfig;
use session::AppSession;
use screens::{HomeScreen, UnlockScreen, WelcomeScreen};
struct CreddyApp {}
impl Render for CreddyApp {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let session = cx.global::<AppSession>();
let screen = match session {
AppSession::Empty => window
.use_keyed_state("welcome", cx, |window, cx| {
WelcomeScreen::new(window, cx)
})
.into_any_element(),
AppSession::Locked => window
.use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx))
.into_any_element(),
AppSession::Unlocked { .. } => window
.use_keyed_state("home", cx, |_, _| HomeScreen {})
.into_any_element(),
};
let theme = cx.omarchy();
div()
.size_full()
.bg(theme.background)
.text_color(theme.foreground)
.font_family(theme.font.clone())
.child(screen)
}
}
fn main() {
// todo: replace this with proper error handling
let app_config = AppConfig::load().expect("failed to load config");
let app_session = AppSession::load(&app_config);
// Icons are read through the asset source, so register the bundle.
gpui_kit::application()
.with_assets(gpui_kit::assets::Assets)
.run(|app| {
gpui_omarchy::init(app);
app.set_global(app_config);
app.set_global(app_session);
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
// but these values aren't expected to change very frequently, so it shouldn't be a problem
app.observe_global::<AppConfig>(|app| app.refresh_windows()).detach();
app.observe_global::<AppSession>(|app| app.refresh_windows()).detach();
app.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window");
app.activate(true);
});
}
+13
View File
@@ -0,0 +1,13 @@
use gpui_kit::{div, Render, Window, Context, IntoElement, Styled, ParentElement};
pub struct HomeScreen {}
impl Render for HomeScreen {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.justify_center()
.items_center()
.child("Creddy is unlocked")
}
}
+7
View File
@@ -0,0 +1,7 @@
mod home;
mod unlock;
mod welcome;
pub use home::HomeScreen;
pub use unlock::UnlockScreen;
pub use welcome::WelcomeScreen;
+137
View File
@@ -0,0 +1,137 @@
use gpui_kit::{
AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
Styled, Subscription, Task, Window, div, rems,
};
use gpui_omarchy::{ButtonVariant, Status, alert, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent};
use crate::config::AppConfig;
use crate::db::Db;
use crate::error::CreddyError;
use crate::session::AppSession;
/// Shown at startup when a database exists: enter the passphrase to open it.
pub struct UnlockScreen {
passphrase: Entity<PassphraseInput>,
error: Option<SharedString>,
/// Set while the KDF is running; dropping it cancels the task.
pending: Option<Task<()>>,
_subscriptions: Vec<Subscription>,
}
impl UnlockScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
// nothing else shares the show/hide flag, so it's private to this input
let show = cx.new(|_| false);
let passphrase = cx.new(|cx| PassphraseInput::new(show, window, cx));
passphrase.update(cx, |input, cx| input.focus(window, cx));
let submit = cx.subscribe_in(&passphrase, window, |this, _, event, window, cx| {
if let PassphraseInputEvent::Submit = event {
this.submit(window, cx);
}
});
Self {
passphrase,
error: None,
pending: None,
_subscriptions: vec![submit],
}
}
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
if self.pending.is_some() {
return;
}
let passphrase = self.passphrase.read(cx).value(cx);
if passphrase.is_empty() {
self.error = Some("Passphrase is empty.".into());
cx.notify();
return;
}
let config = cx.global::<AppConfig>().clone();
self.error = None;
self.pending = Some(cx.spawn(async move |this, cx| {
// argon2 is deliberately slow, so keep it off the UI thread
let result = cx
.background_spawn(async move {
let db = Db::connect(&config, passphrase.as_str())?;
// Some of AppConfig comes from the db, but we couldn't see it until now
let private_config = db.load_private_config()?;
Ok((db, private_config))
})
.await;
// db connection has been established or not, so now we handle the result
let _ = this.update(cx, |this, cx| {
this.pending = None;
match result {
Ok((db, private_config)) => {
cx.update_global::<AppConfig, _>(|config, _cx| config.merge_private(private_config));
cx.set_global(AppSession::Unlocked(db));
},
Err(e) => this.error = Some(error_message(&e)),
}
cx.notify();
});
}));
cx.notify();
}
}
/// Turn a failed unlock into something fit to show the user.
fn error_message(e: &CreddyError) -> SharedString {
// todo: have Db::connect return a dedicated error variant for this instead
if let CreddyError::Db(duckdb::Error::DuckDBFailure(_, Some(desc))) = e
&& desc.contains("Wrong encryption key")
{
return "Incorrect passphrase.".into();
}
format!("Failed to unlock: {e}").into()
}
impl Render for UnlockScreen {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
focus_scope("unlock")
.size_full()
.flex()
.flex_col()
.items_center()
.p(rems(0.5))
.child(
div()
.text_size(rems(1.875))
.font_weight(FontWeight::BOLD)
.child("Creddy is locked"),
)
.child(
// fill the rest of the window so the form sits in the middle of it
div()
.flex_1()
.w_full()
.max_w(rems(24.))
.flex()
.flex_col()
.justify_center()
.gap(rems(1.))
.child(
div()
.text_center()
.text_size(rems(1.25))
.font_weight(FontWeight::BOLD)
.child("Please enter your passphrase"),
)
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
.child(self.passphrase.clone())
.child(
button("submit", "Submit", ButtonVariant::Primary, cx)
.disabled(self.pending.is_some())
.on_click(cx.listener(|this, _, window, cx| this.submit(window, cx))),
),
)
}
}
+178
View File
@@ -0,0 +1,178 @@
use gpui_kit::{
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
Styled, Subscription, Task,Window, div, rems,
};
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent};
use crate::config::AppConfig;
use crate::db::Db;
use crate::session::AppSession;
const MISMATCH: &str = "Passphrases do not match.";
/// First-run screen: choose a passphrase, derive the key, and unlock the session.
pub struct WelcomeScreen {
passphrase: Entity<PassphraseInput>,
confirm: Entity<PassphraseInput>,
error: Option<SharedString>,
/// Set while the KDF is running; dropping it cancels the task.
pending: Option<Task<()>>,
_subscriptions: Vec<Subscription>,
}
impl WelcomeScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let show = cx.new(|_| false);
let passphrase = cx.new(|cx| PassphraseInput::new(show.clone(), window, cx));
let confirm = cx.new(|cx| PassphraseInput::new(show, window, cx));
passphrase.update(cx, |input, cx| input.focus(window, cx));
let mut _subscriptions = Vec::new();
for input in [&passphrase, &confirm] {
_subscriptions.push(cx.subscribe_in(input, window, |this, _, event, window, cx| {
match event {
PassphraseInputEvent::Submit => this.submit(window, cx),
// typing only dismisses the mismatch error, never raises it
PassphraseInputEvent::Change if this.passphrases_match(cx) => {
this.error = None;
cx.notify();
}
_ => (),
}
}));
}
// leaving the confirm field is what raises the mismatch error
_subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| {
if let PassphraseInputEvent::Blur = event
&& !this.passphrases_match(cx)
{
this.error = Some(MISMATCH.into());
cx.notify();
}
}));
Self {
passphrase,
confirm,
error: None,
pending: None,
_subscriptions,
}
}
fn passphrases_match(&self, cx: &Context<Self>) -> bool {
self.passphrase.read(cx).value(cx) == self.confirm.read(cx).value(cx)
}
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
if self.pending.is_some() {
return;
}
let passphrase = self.passphrase.read(cx).value(cx);
if !self.passphrases_match(cx) {
self.error = Some(MISMATCH.into());
cx.notify();
return;
}
if passphrase.is_empty() {
self.error = Some("Passphrase is empty.".into());
cx.notify();
return;
}
let config = cx.global::<AppConfig>().clone();
self.error = None;
// todo: persist the salt (and KDF params) so the database can be unlocked again later
self.pending = Some(cx.spawn(async move |this, cx| {
// argon2 is deliberately slow, so keep it off the UI thread
let result = cx
.background_spawn(async move {
Db::connect(&config, passphrase.as_str())
})
.await;
let _ = this.update(cx, |this, cx| {
this.pending = None;
match result {
Ok(db) => cx.set_global(AppSession::Unlocked(db)),
Err(e) => this.error = Some(format!("Failed to derive key: {e}").into()),
}
cx.notify();
});
}));
cx.notify();
}
}
impl Render for WelcomeScreen {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let t = cx.omarchy();
let field = |label: &'static str, input: &Entity<PassphraseInput>| {
div()
.flex()
.flex_col()
.gap(rems(0.25))
.child(div().text_size(rems(0.875)).child(label))
.child(input.clone())
};
focus_scope("welcome")
.size_full()
.flex()
.justify_center()
.items_center()
.bg(t.background)
.text_color(t.foreground)
.font_family(t.font.clone())
.child(
div()
.w_full()
.max_w(rems(32.))
.flex()
.flex_col()
.gap(rems(2.))
.child(
div()
.text_center()
.text_size(rems(1.5))
.font_weight(FontWeight::BOLD)
.child("Welcome to Creddy!"),
)
.child(
div()
.flex()
.flex_col()
.gap(rems(1.))
.child("Create a passphrase to get started.")
.child(
"Please note that if you forget your passphrase, there is no way \
to recover your stored credentials. You will have to start over \
with a new passphrase.",
),
)
.child(
div()
.w_full()
.max_w(rems(24.))
.mx_auto()
.flex()
.flex_col()
.gap(rems(1.))
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
.child(field("Passphrase", &self.passphrase))
.child(field("Re-enter passphrase", &self.confirm))
.child(
button("submit", "Submit", ButtonVariant::Primary, cx)
.disabled(self.pending.is_some())
.on_click(cx.listener(|this, _, window, cx| {
this.submit(window, cx)
})),
),
),
)
}
}
+43
View File
@@ -0,0 +1,43 @@
use gpui_kit::Global;
use crate::config::AppConfig;
use crate::error::CreddyError;
use crate::db::Db;
#[derive(Debug)]
pub enum AppSession {
Empty,
Locked,
Unlocked(Db),
}
impl AppSession {
pub fn load(config: &AppConfig) -> AppSession {
if config.db_path().exists() {
AppSession::Locked
} else {
AppSession::Empty
}
}
pub fn unlock(&mut self, passphrase: &str) -> Result<AppSession, CreddyError> {
todo!()
}
}
impl Global for AppSession {}
#[cfg(test)]
mod tests {
use super::*;
// #[test]
// fn test_new() {
// let passphrase = "correct horse battery staple";
// let salt = AppSession::salt().expect("salt generation failed.");
// let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
// match session {
// AppSession::Unlocked { .. } => (),
// _ => panic!("AppSession::new() should return an unlocked session"),
// }
// }
}
-3
View File
@@ -1,3 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
-19
View File
@@ -1,19 +0,0 @@
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
</script>
<h2 class="text-3xl text-gray-200">An application would like to access your AWS credentials.</h2>
<button on:click={() => dispatch('response', 'approved')}>
<svg class="w-32 stroke-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
<button on:click={() => dispatch('response', 'denied')}>
<svg class="w-32 stroke-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
<path stroke-linecap="round" stroke-linejoin="round" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
-1
View File
@@ -1 +0,0 @@
<h1 class="text-4xl text-gray-300">Creddy</h1>
-11
View File
@@ -1,11 +0,0 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./index.html",
"./src/**/*.{svelte,html}",
],
theme: {
extend: {},
},
plugins: [],
}
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()]
})