add basic CSV to password support

This commit is contained in:
bunnie 2022-11-29 23:53:27 +08:00
parent 501b694db8
commit 79c773e245
5 changed files with 116 additions and 0 deletions

1
Cargo.lock generated
View file

@ -4329,6 +4329,7 @@ dependencies = [
"base64 0.5.2",
"cbor",
"clap 3.2.12",
"csv",
"ctaphid",
"env_logger 0.9.0",
"hex 0.4.3",

View file

@ -23,6 +23,7 @@ url = "2.2.2"
base64 = "0.5.2"
base32 = "0.4.0"
protobuf = "3.1.0"
csv = "1.1.6"
[build-dependencies]
protobuf-codegen = "3.1.0"

View file

@ -0,0 +1,68 @@
use serde::{Deserialize, Serialize};
use csv;
#[derive(Serialize, Debug, Deserialize)]
pub struct Entry {
pub site: Option<String>,
pub username: Option<String>,
pub password: Option<String>,
pub notes: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Items {
pub items: Vec<Entry>,
}
impl Items {
pub fn logins(&self) -> Vec<&Entry> {
let ret: Vec<&Entry> = self
.items
.iter()
.filter(|element| element.site.is_some())
.collect();
ret
}
}
impl std::error::Error for CsvError {}
#[derive(Debug)]
pub enum CsvError {
Err(String),
}
impl From::<csv::Error> for CsvError {
fn from(err: csv::Error) -> Self {
CsvError::Err(
format!("{:?}", err)
)
}
}
impl std::fmt::Display for CsvError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Err(err) => write!(f, "CSV deserialization error, {:?}", err),
}
}
}
impl TryFrom<std::fs::File> for Items {
type Error = CsvError;
fn try_from(data: std::fs::File) -> Result<Items, Self::Error> {
let mut ret = Vec::<Entry>::new();
let mut rdr = csv::Reader::from_reader(data);
let mut iter = rdr.deserialize();
loop {
if let Some(result) = iter.next() {
let record: Entry = result?;
ret.push(record);
} else {
break;
}
}
Ok(Items{ items: ret })
}
}

View file

@ -1,5 +1,6 @@
mod bitwarden;
mod authenticator;
mod csvpass;
use anyhow::Result;
use clap::Parser;
use clap::Subcommand;
@ -46,6 +47,7 @@ struct SubcommandFields {
enum FormatTargets {
Bitwarden,
Authenticator,
CsvPass,
}
#[derive(Debug, PartialEq, clap::Args, Clone)]
@ -131,6 +133,35 @@ fn main() -> Result<()> {
let f = std::fs::File::open(params.path)?;
match params.target {
FormatTargets::CsvPass => {
println!("Formatting CSV file to uploadable JSON -> csv_to_vault_passwords.json");
let items = csvpass::Items::try_from(f)?;
let items = items.logins();
let mut passwords = backup::PasswordEntries::default();
for (idx, item) in items.into_iter().enumerate() {
let mut pw = backup::PasswordEntry::default();
if item.username.is_none() || item.site.is_none() {
log::error!("entry {} is missing username and/or site. Skipping.", idx);
continue
}
pw.password = item.password.as_ref().unwrap_or(&String::new()).clone();
pw.username = item.username.as_ref().unwrap().clone();
pw.description = item.site.as_ref().unwrap().clone();
pw.notes = item.notes.as_ref().unwrap_or(&String::new()).clone();
passwords.0.push(pw);
}
std::fs::write(
"csv_to_vault_passwords.json",
serde_json::ser::to_vec(&passwords)?,
)?;
Ok(())
}
FormatTargets::Bitwarden => {
let items = bitwarden::Items::try_from(f)?;
let items = items.logins();

View file

@ -0,0 +1,15 @@
site,username,password,notes
test.com,bunnie,f00b4r,a test password
commas.net,troll,"c0mm4,c,c","a site that loves commas, in a CSV,,,"
ftp://special.xyz,@foo@bar,z2T47*d1!FIx,"~!@#$%^&*()-_=+[]\{}|;':"",./<>?"
unicode.chars,¯\_(ツ)_/¯,@yGKpU8W2^s8tjjK,🤷why not
test.fr,test,Lhi0pEzggo,"Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en
canoë au delà des îles, près du mälström où brûlent les novæ."
emoji.net,😊😂🤣😒😁😉😎😢,$LepF2ajQr7$yAbx,"古池や蛙飛び込む水の音
    ふるいけやかわずとびこむみずのおと"
"multiline
test case","user
on two lines","g4p09ao
民以食为天","three
line
note"
1 site username password notes
2 test.com bunnie f00b4r a test password
3 commas.net troll c0mm4,c,c a site that loves commas, in a CSV,,,
4 ftp://special.xyz @foo@bar z2T47*d1!FIx ~!@#$%^&*()-_=+[]\{}|;':",./<>?
5 unicode.chars ¯\_(ツ)_/¯ @yGKpU8W2^s8tjjK 🤷why not
6 test.fr test Lhi0pEzggo Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en canoë au delà des îles, près du mälström où brûlent les novæ.
7 emoji.net 😊😂🤣😒😁😉😎😢 $LepF2ajQr7$yAbx 古池や蛙飛び込む水の音     ふるいけやかわずとびこむみずのおと
8 multiline test case user on two lines g4p09ao 民以食为天 three line note