Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0798124811 | ||
|
|
a10510ed6e | ||
|
|
2371486f39 | ||
|
|
a1e5daba59 | ||
|
|
2bd81a66a4 | ||
|
|
d67871f491 | ||
|
|
1a7f502fce | ||
|
|
b2c27d26e8 | ||
|
|
8fa3a15807 | ||
|
|
862c68c846 | ||
|
|
ac62171467 | ||
|
|
2080fb897b | ||
|
|
bf62054c2b | ||
|
|
cd4c613758 | ||
|
|
efbf6c687c | ||
|
|
ee495478ff | ||
|
|
4c18de8b7a | ||
|
|
0cfa9fc07a | ||
|
|
9e9bc2b0ae | ||
|
|
07bf98e522 | ||
|
|
e0e758554c | ||
|
|
479a0a96eb | ||
|
|
c6e22fc91b | ||
|
|
9bc9cb56c1 | ||
|
|
8bcdc5420a | ||
|
|
0a355c299b | ||
|
|
192d9058c3 | ||
|
|
b88b32d0f1 | ||
|
|
12c97c4a7d | ||
|
|
97528d65d6 | ||
|
|
295698e62f | ||
|
|
3b61aa924a | ||
|
|
02ba19d709 | ||
|
|
55801384eb | ||
|
|
27c2f467c4 | ||
|
|
cab5ec40cc | ||
|
|
5cf848f7fe | ||
|
|
a32e36be7e | ||
|
|
10231df860 | ||
|
|
ae93a57aab | ||
|
|
9fd355b68e | ||
|
|
00089d7efb | ||
|
|
0124f77f7b | ||
|
|
6711ce2c43 | ||
|
|
a3a11897c2 | ||
|
|
5e6542d08e | ||
|
|
f311fde74e | ||
|
|
acc5c71bfa | ||
|
|
504c0b4156 | ||
|
|
bf0a2ca72d | ||
|
|
bb980c5eef | ||
|
|
ce7d75f15a | ||
|
|
37b44ddb2e | ||
|
|
8c668e51a6 | ||
|
|
9928996fab | ||
|
|
d0a2532c27 | ||
|
|
0491cb5790 | ||
|
|
816bd7db00 | ||
|
|
b165965289 | ||
|
|
86896d68c2 | ||
|
|
64a2927b94 | ||
|
|
87617a0726 | ||
|
|
141334f7e2 | ||
|
|
69f6a39396 | ||
|
|
70e23c7e20 | ||
|
|
1df849442e | ||
|
|
7fdb336c79 | ||
|
|
46b8d810c5 | ||
|
|
dd40eb379e | ||
|
|
13545ac725 | ||
|
|
040a01536a | ||
|
|
4e2a90b15b | ||
|
|
e0d919ed4a | ||
|
|
3f4efc5f8f | ||
|
|
4881b90b0b | ||
|
|
1b749a857c | ||
|
|
2079f99d04 | ||
|
|
5e0ffc1155 | ||
|
|
d4fa8966b2 | ||
|
|
a293d8f92c | ||
|
|
367a140e2a | ||
|
|
4b06dce7f4 | ||
|
|
47a3e1cfef | ||
|
|
1047818fdc | ||
|
|
3d093a3a45 | ||
|
|
992d2a4d06 | ||
|
|
12f0f187a6 | ||
|
|
997e8b419f | ||
|
|
1d9132de3b | ||
|
|
e1c2618dc8 | ||
|
|
a7df7adc8e | ||
|
|
03d164c9d3 | ||
|
|
f522674a1c | ||
|
|
51fcccafa2 | ||
|
|
e3913ab4c9 | ||
|
|
c16f21bba3 | ||
|
|
61d9acc7c6 | ||
|
|
8d7b01629d | ||
|
|
5685948608 | ||
|
|
c98a065587 | ||
|
|
e46c3d2b4d | ||
|
|
fa228acc3a | ||
|
|
e7e0f9d33e | ||
|
|
a51b20add7 | ||
|
|
890f715388 | ||
|
|
89bc74e644 | ||
|
|
60c24e3ee4 | ||
|
|
486001b584 | ||
|
|
52c949e396 | ||
|
|
d7c5c2f37b | ||
|
|
ae5b8f31db | ||
|
|
c260e37e78 | ||
|
|
7501253970 | ||
|
|
5b9c711008 | ||
|
|
ddd1005067 | ||
|
|
e866a4a643 | ||
|
|
94400ba7d5 | ||
|
|
616600687d | ||
|
|
e8b8dc2976 | ||
|
|
ddf865d0b4 | ||
|
|
96bbc2dbc2 | ||
|
|
161148d1f6 | ||
|
|
760987f09b | ||
|
|
a75f34865e | ||
|
|
886fcd9bb8 | ||
|
|
55775b6b05 | ||
|
|
871dedf0a3 | ||
|
|
913148a75a | ||
|
|
e746963052 | ||
|
|
b761d3b493 | ||
|
|
c5dcc2e50a | ||
|
|
70d71ce14e | ||
|
|
33a5600a30 | ||
|
|
741169d807 | ||
|
|
ebc00a5df6 | ||
|
|
c2cc007a81 | ||
|
|
4aab08e6f0 | ||
|
|
12d9d733a5 | ||
|
|
35271049dd | ||
|
|
6f9cd6b471 | ||
|
|
865b7fd5c4 | ||
|
|
f35352eedd | ||
|
|
53580d7919 | ||
|
|
049b81610d | ||
|
|
fd60899f16 | ||
|
|
e0c4c849dc | ||
|
|
cb26201506 | ||
|
|
992e3c8db2 | ||
|
|
4956b64371 | ||
|
|
df6b362a31 | ||
|
|
2943634248 | ||
|
|
06f5a1af42 | ||
|
|
61d674199f | ||
|
|
398916fe10 | ||
|
|
bf4c46238e | ||
|
|
5ffa55c03c | ||
|
|
50f0985f4f | ||
|
|
69475604c0 | ||
|
|
856b6f1e1b | ||
|
|
414379b74e | ||
|
|
80b92ebe69 | ||
|
|
983d0e8639 | ||
|
|
d77437cda8 | ||
|
|
3d5cbedae1 | ||
|
|
10fd1d6028 | ||
|
|
67705aa2d1 | ||
|
|
9055fa41aa | ||
|
|
48269855e5 | ||
|
|
1e4e1c9a5f | ||
|
|
196510e9a2 | ||
|
|
e423df8e51 | ||
|
|
2cfde4d841 | ||
|
|
7d462645b4 | ||
|
|
8c271281f7 | ||
|
|
234d9e0471 | ||
|
|
397928b8f1 | ||
|
|
c19b573b26 | ||
|
|
cee43342b9 |
No files matched your search
@@ -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 }
|
||||||
@@ -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
|
||||||
@@ -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"
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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)
|
||||||
@@ -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>
|
|
||||||
@@ -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 ('{}');
|
||||||
@@ -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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
plugins: {
|
|
||||||
tailwindcss: {},
|
|
||||||
autoprefixer: {},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -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" ]
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
tauri_build::build()
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 974 B |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 903 B |
|
Before Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 14 KiB |
@@ -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"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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()))
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
}
|
|
||||||
@@ -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")
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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} />
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
mod passphrase_input;
|
||||||
|
|
||||||
|
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
|
||||||
@@ -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))),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
|
}
|
||||||
@@ -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();
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import './style.css';
|
|
||||||
import App from './App.svelte';
|
|
||||||
|
|
||||||
const app = new App({
|
|
||||||
target: document.getElementById('app')
|
|
||||||
})
|
|
||||||
|
|
||||||
export default app;
|
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
mod home;
|
||||||
|
mod unlock;
|
||||||
|
mod welcome;
|
||||||
|
|
||||||
|
pub use home::HomeScreen;
|
||||||
|
pub use unlock::UnlockScreen;
|
||||||
|
pub use welcome::WelcomeScreen;
|
||||||
@@ -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))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"),
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
@tailwind base;
|
|
||||||
@tailwind components;
|
|
||||||
@tailwind utilities;
|
|
||||||
@@ -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 +0,0 @@
|
|||||||
<h1 class="text-4xl text-gray-300">Creddy</h1>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/** @type {import('tailwindcss').Config} */
|
|
||||||
module.exports = {
|
|
||||||
content: [
|
|
||||||
"./index.html",
|
|
||||||
"./src/**/*.{svelte,html}",
|
|
||||||
],
|
|
||||||
theme: {
|
|
||||||
extend: {},
|
|
||||||
},
|
|
||||||
plugins: [],
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { defineConfig } from 'vite'
|
|
||||||
import { svelte } from '@sveltejs/vite-plugin-svelte'
|
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [svelte()]
|
|
||||||
})
|
|
||||||