1use zeroize::Zeroize;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub enum ItemKind {
15 Note,
17 Login,
19 Card,
21 SshKey,
23 Wifi,
25 ApiToken,
27 Bank,
29 File,
31 Unknown(String),
43}
44
45impl ItemKind {
46 pub fn as_str(&self) -> &str {
48 match self {
49 Self::Note => "note",
50 Self::Login => "login",
51 Self::Card => "card",
52 Self::SshKey => "ssh-key",
53 Self::Wifi => "wifi",
54 Self::ApiToken => "api-token",
55 Self::Bank => "bank",
56 Self::File => "file",
57 Self::Unknown(name) => name,
58 }
59 }
60
61 pub fn parse(value: &str) -> Self {
71 match value {
72 "note" => Self::Note,
73 "login" | LEGACY_LOGIN_NAME => Self::Login,
74 "card" => Self::Card,
75 "ssh-key" => Self::SshKey,
76 "wifi" => Self::Wifi,
77 "api-token" => Self::ApiToken,
78 "bank" => Self::Bank,
79 "file" => Self::File,
80 other => Self::Unknown(other.to_owned()),
81 }
82 }
83
84 pub fn is_known(&self) -> bool {
86 !matches!(self, Self::Unknown(_))
87 }
88
89 pub fn template(&self) -> Option<&'static Template> {
94 TEMPLATES.iter().find(|template| &template.kind == self)
95 }
96
97 pub fn is_record(&self) -> bool {
102 self.template().is_some()
103 }
104
105 pub fn known() -> [Self; 8] {
107 [
108 Self::Note,
109 Self::Login,
110 Self::Card,
111 Self::SshKey,
112 Self::Wifi,
113 Self::ApiToken,
114 Self::Bank,
115 Self::File,
116 ]
117 }
118}
119
120pub const LEGACY_LOGIN_NAME: &str = "credential";
126
127impl std::fmt::Display for ItemKind {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 f.write_str(self.as_str())
130 }
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Template {
141 pub kind: ItemKind,
143 pub fields: &'static [FieldSpec],
145}
146
147impl Template {
148 pub fn field(&self, name: &str) -> Option<&FieldSpec> {
150 self.fields.iter().find(|field| field.name == name)
151 }
152
153 pub fn default_field(&self) -> Option<&FieldSpec> {
159 self.fields.iter().find(|field| field.secret)
160 }
161
162 pub fn fill_order(&self) -> impl Iterator<Item = &FieldSpec> {
164 self.fields.iter().filter(|field| field.fill)
165 }
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct FieldSpec {
171 pub name: &'static str,
173 pub description: &'static str,
175 pub secret: bool,
178 pub fill: bool,
181 pub audit: AuditAs,
183}
184
185impl FieldSpec {
186 const fn new(
187 name: &'static str,
188 description: &'static str,
189 secret: bool,
190 fill: bool,
191 audit: AuditAs,
192 ) -> Self {
193 Self {
194 name,
195 description,
196 secret,
197 fill,
198 audit,
199 }
200 }
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum AuditAs {
209 Password,
212 Unique,
216 Nothing,
220}
221
222impl AuditAs {
223 pub fn of(kind: &ItemKind, field: &Field) -> Self {
230 if let Some(spec) = kind
231 .template()
232 .and_then(|template| template.field(&field.name))
233 {
234 return spec.audit;
235 }
236 if !field.secret {
237 return Self::Nothing;
238 }
239 TEMPLATES
240 .iter()
241 .find_map(|template| template.field(&field.name))
242 .map_or(Self::Nothing, |spec| spec.audit)
243 }
244}
245
246pub fn normalize_value(name: &str, value: &str) -> crate::Result<String> {
254 match name {
255 crate::otp::FIELD => crate::otp::normalize(value),
256 crate::expiry::FIELD => crate::expiry::normalize(value),
257 _ => Ok(value.to_owned()),
258 }
259}
260
261const PUBLIC: bool = false;
263const SECRET: bool = true;
264const FILL: bool = true;
265const KEEP: bool = false;
266const CHOSEN: AuditAs = AuditAs::Password;
267const ISSUED: AuditAs = AuditAs::Unique;
268const UNCHECKED: AuditAs = AuditAs::Nothing;
269
270static TEMPLATES: &[Template] = &[
276 Template {
277 kind: ItemKind::Login,
278 fields: &[
279 FieldSpec::new(
280 "login",
281 "username, email, or whatever the service calls it",
282 PUBLIC,
283 FILL,
284 UNCHECKED,
285 ),
286 FieldSpec::new("password", "the secret itself", SECRET, FILL, CHOSEN),
287 FieldSpec::new("url", "where the account lives", PUBLIC, KEEP, UNCHECKED),
288 FieldSpec::new(
290 crate::otp::FIELD,
291 "key for one-time passwords",
292 SECRET,
293 FILL,
294 ISSUED,
295 ),
296 FieldSpec::new(
297 "notes",
298 "anything else worth remembering",
299 PUBLIC,
300 KEEP,
301 UNCHECKED,
302 ),
303 ],
304 },
305 Template {
306 kind: ItemKind::Card,
307 fields: &[
308 FieldSpec::new("number", "the card number", SECRET, FILL, ISSUED),
309 FieldSpec::new(
310 "holder",
311 "name embossed on the card",
312 PUBLIC,
313 FILL,
314 UNCHECKED,
315 ),
316 FieldSpec::new(
318 crate::expiry::FIELD,
319 "the month it runs out, as printed: 03/29",
320 PUBLIC,
321 FILL,
322 UNCHECKED,
323 ),
324 FieldSpec::new(
325 "cvv",
326 "verification code on the back",
327 SECRET,
328 FILL,
329 UNCHECKED,
330 ),
331 FieldSpec::new("pin", "the PIN", SECRET, KEEP, UNCHECKED),
333 FieldSpec::new(
334 "notes",
335 "bank, account, anything else",
336 PUBLIC,
337 KEEP,
338 UNCHECKED,
339 ),
340 ],
341 },
342 Template {
343 kind: ItemKind::SshKey,
344 fields: &[
345 FieldSpec::new(
346 "private-key",
347 "the private key, as it appears in the file",
348 SECRET,
349 KEEP,
350 ISSUED,
351 ),
352 FieldSpec::new(
353 "passphrase",
354 "passphrase protecting the private key",
355 SECRET,
356 FILL,
357 CHOSEN,
358 ),
359 FieldSpec::new("public-key", "the public key", PUBLIC, KEEP, UNCHECKED),
360 FieldSpec::new("host", "where the key is used", PUBLIC, KEEP, UNCHECKED),
361 FieldSpec::new(
362 "notes",
363 "anything else worth remembering",
364 PUBLIC,
365 KEEP,
366 UNCHECKED,
367 ),
368 ],
369 },
370 Template {
371 kind: ItemKind::Wifi,
372 fields: &[
373 FieldSpec::new("ssid", "the network's name", PUBLIC, FILL, UNCHECKED),
374 FieldSpec::new("password", "the network key", SECRET, FILL, CHOSEN),
375 FieldSpec::new("security", "WPA2, WPA3, open", PUBLIC, KEEP, UNCHECKED),
376 FieldSpec::new("notes", "where it is, whose it is", PUBLIC, KEEP, UNCHECKED),
377 ],
378 },
379 Template {
380 kind: ItemKind::ApiToken,
381 fields: &[
382 FieldSpec::new("token", "the token itself", SECRET, FILL, ISSUED),
383 FieldSpec::new(
384 "url",
385 "where it is issued and revoked",
386 PUBLIC,
387 KEEP,
388 UNCHECKED,
389 ),
390 FieldSpec::new(
391 "scopes",
392 "what it is allowed to do",
393 PUBLIC,
394 KEEP,
395 UNCHECKED,
396 ),
397 FieldSpec::new(
398 crate::expiry::FIELD,
399 "the last day it works: 2027-01-31",
400 PUBLIC,
401 KEEP,
402 UNCHECKED,
403 ),
404 FieldSpec::new("notes", "what uses it", PUBLIC, KEEP, UNCHECKED),
405 ],
406 },
407 Template {
408 kind: ItemKind::Bank,
409 fields: &[
410 FieldSpec::new("account", "account number or IBAN", SECRET, FILL, ISSUED),
411 FieldSpec::new(
412 "holder",
413 "whose name the account is in",
414 PUBLIC,
415 FILL,
416 UNCHECKED,
417 ),
418 FieldSpec::new("bank", "the bank", PUBLIC, FILL, UNCHECKED),
419 FieldSpec::new(
420 "routing",
421 "SWIFT/BIC, routing or sort code",
422 PUBLIC,
423 FILL,
424 UNCHECKED,
425 ),
426 FieldSpec::new(
427 "notes",
428 "branch, contact, anything else",
429 PUBLIC,
430 KEEP,
431 UNCHECKED,
432 ),
433 ],
434 },
435];
436
437#[derive(Debug, Clone, PartialEq, Eq, Zeroize)]
443pub struct Field {
444 pub name: String,
446 pub value: String,
448 #[zeroize(skip)]
450 pub secret: bool,
451}
452
453impl Field {
454 pub fn public(name: impl Into<String>, value: impl Into<String>) -> Self {
456 Self {
457 name: name.into(),
458 value: value.into(),
459 secret: false,
460 }
461 }
462
463 pub fn secret(name: impl Into<String>, value: impl Into<String>) -> Self {
465 Self {
466 name: name.into(),
467 value: value.into(),
468 secret: true,
469 }
470 }
471}
472
473#[derive(Debug, Clone, PartialEq, Eq)]
475pub enum Payload {
476 Note {
478 text: String,
480 },
481 Fields {
483 kind: ItemKind,
485 fields: Vec<Field>,
487 },
488 File {
490 filename: String,
492 bytes: Vec<u8>,
494 },
495 Unknown {
501 kind: String,
503 },
504}
505
506impl Payload {
507 pub fn fields(kind: ItemKind, fields: impl IntoIterator<Item = Field>) -> Self {
509 Self::Fields {
510 kind,
511 fields: fields.into_iter().collect(),
512 }
513 }
514
515 pub fn kind(&self) -> ItemKind {
517 match self {
518 Self::Note { .. } => ItemKind::Note,
519 Self::Fields { kind, .. } => kind.clone(),
520 Self::File { .. } => ItemKind::File,
521 Self::Unknown { kind } => ItemKind::Unknown(kind.clone()),
522 }
523 }
524
525 pub fn field(&self, name: &str) -> Option<&Field> {
527 match self {
528 Self::Fields { fields, .. } => fields.iter().find(|field| field.name == name),
529 _ => None,
530 }
531 }
532}
533
534impl Zeroize for Payload {
535 fn zeroize(&mut self) {
536 match self {
537 Self::Note { text } => text.zeroize(),
538 Self::Fields { fields, .. } => fields.zeroize(),
539 Self::File { filename, bytes } => {
540 filename.zeroize();
541 bytes.zeroize();
542 }
543 Self::Unknown { .. } => {}
546 }
547 }
548}
549
550#[derive(Debug, Clone, PartialEq, Eq)]
552pub struct ItemSummary {
553 pub id: i64,
557 pub uuid: String,
560 pub title: String,
562 pub kind: ItemKind,
564 pub tags: Vec<String>,
566 pub created_at: i64,
568 pub updated_at: i64,
570}
571
572#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct Item {
575 pub summary: ItemSummary,
577 pub payload: Payload,
579}
580
581#[derive(Debug, Clone)]
583pub struct NewItem {
584 pub title: String,
586 pub payload: Payload,
588 pub tags: Vec<String>,
590}
591
592impl NewItem {
593 pub fn new(title: impl Into<String>, payload: Payload) -> Self {
595 Self {
596 title: title.into(),
597 payload,
598 tags: Vec::new(),
599 }
600 }
601
602 pub fn with_tags<I, S>(mut self, tags: I) -> Self
604 where
605 I: IntoIterator<Item = S>,
606 S: Into<String>,
607 {
608 self.tags = tags.into_iter().map(Into::into).collect();
609 self
610 }
611}
612
613#[derive(Debug, Clone, Default)]
615pub struct Query {
616 pub text: Option<String>,
620 pub kind: Option<ItemKind>,
622 pub tags: Vec<String>,
624}
625
626impl Query {
627 pub fn all() -> Self {
629 Self::default()
630 }
631
632 pub fn text(mut self, text: impl Into<String>) -> Self {
634 self.text = Some(text.into());
635 self
636 }
637
638 pub fn kind(mut self, kind: ItemKind) -> Self {
640 self.kind = Some(kind);
641 self
642 }
643
644 pub fn tags<I, S>(mut self, tags: I) -> Self
646 where
647 I: IntoIterator<Item = S>,
648 S: Into<String>,
649 {
650 self.tags = tags.into_iter().map(Into::into).collect();
651 self
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 #[test]
660 fn kind_names_round_trip() {
661 for kind in ItemKind::known() {
662 assert_eq!(ItemKind::parse(kind.as_str()), kind);
663 }
664 }
665
666 #[test]
667 fn an_unheard_of_kind_keeps_its_name_instead_of_failing() {
668 let kind = ItemKind::parse("passport");
669 assert_eq!(kind, ItemKind::Unknown("passport".to_owned()));
670 assert_eq!(kind.as_str(), "passport");
671 assert!(!kind.is_known());
672 assert_eq!(ItemKind::parse(kind.as_str()), kind);
674 }
675
676 #[test]
677 fn the_old_name_for_a_login_still_reads() {
678 assert_eq!(ItemKind::parse(LEGACY_LOGIN_NAME), ItemKind::Login);
679 assert_eq!(ItemKind::Login.as_str(), "login");
681 }
682
683 #[test]
684 fn only_field_backed_kinds_have_a_template() {
685 assert!(ItemKind::Login.template().is_some());
686 assert!(ItemKind::Card.template().is_some());
687 assert!(ItemKind::SshKey.template().is_some());
688 assert!(ItemKind::Wifi.template().is_some());
689 assert!(ItemKind::ApiToken.template().is_some());
690 assert!(ItemKind::Bank.template().is_some());
691 assert!(ItemKind::Note.template().is_none());
692 assert!(ItemKind::File.template().is_none());
693 assert!(
694 ItemKind::Unknown("passport".to_owned())
695 .template()
696 .is_none()
697 );
698 }
699
700 #[test]
701 fn every_template_names_its_fields_uniquely() {
702 for template in TEMPLATES {
703 let mut seen: Vec<&str> = Vec::new();
704 for field in template.fields {
705 assert!(
706 !seen.contains(&field.name),
707 "{} names {} twice",
708 template.kind,
709 field.name
710 );
711 seen.push(field.name);
712 }
713 }
714 }
715
716 #[test]
717 fn the_default_field_is_the_first_secret_one() {
718 assert_eq!(
719 ItemKind::Login
720 .template()
721 .unwrap()
722 .default_field()
723 .unwrap()
724 .name,
725 "password"
726 );
727 assert_eq!(
728 ItemKind::Card
729 .template()
730 .unwrap()
731 .default_field()
732 .unwrap()
733 .name,
734 "number"
735 );
736 assert_eq!(
737 ItemKind::SshKey
738 .template()
739 .unwrap()
740 .default_field()
741 .unwrap()
742 .name,
743 "private-key"
744 );
745 }
746
747 #[test]
748 fn every_kind_but_a_note_and_a_file_is_a_record_with_a_template_row() {
749 for kind in ItemKind::known() {
750 let expected = !matches!(kind, ItemKind::Note | ItemKind::File);
751 assert_eq!(kind.is_record(), expected, "{kind}");
752 }
753 for template in TEMPLATES {
755 assert!(
756 ItemKind::known().contains(&template.kind),
757 "{}",
758 template.kind
759 );
760 }
761 }
762
763 #[test]
764 fn a_one_time_password_key_is_secret_wherever_a_template_has_one() {
765 for template in TEMPLATES {
766 if let Some(field) = template.field(crate::otp::FIELD) {
767 assert!(field.secret, "{} keeps its key in the open", template.kind);
768 }
769 }
770 }
771
772 #[test]
773 fn a_field_name_is_audited_the_same_way_in_every_template() {
774 for template in TEMPLATES {
777 for field in template.fields {
778 for other in TEMPLATES {
779 if let Some(same) = other.field(field.name) {
780 assert_eq!(
781 same.audit, field.audit,
782 "{} in {} and {}",
783 field.name, template.kind, other.kind
784 );
785 }
786 }
787 }
788 }
789 }
790
791 #[test]
792 fn only_a_secret_is_ever_audited() {
793 for template in TEMPLATES {
794 for field in template.fields {
795 if !field.secret {
796 assert_eq!(field.audit, AuditAs::Nothing, "{}", field.name);
797 }
798 }
799 }
800 }
801
802 #[test]
803 fn a_field_outside_the_template_is_audited_as_its_name_is_elsewhere() {
804 let bank = ItemKind::Bank;
805 assert_eq!(
806 AuditAs::of(&bank, &Field::secret("password", "p")),
807 AuditAs::Password
808 );
809 assert_eq!(
810 AuditAs::of(&bank, &Field::secret("token", "t")),
811 AuditAs::Unique
812 );
813 assert_eq!(
815 AuditAs::of(&bank, &Field::public("password", "p")),
816 AuditAs::Nothing
817 );
818 assert_eq!(
820 AuditAs::of(&bank, &Field::secret("recovery", "r")),
821 AuditAs::Nothing
822 );
823 assert_eq!(
825 AuditAs::of(&ItemKind::Card, &Field::secret("pin", "1234")),
826 AuditAs::Nothing
827 );
828 }
829
830 #[test]
831 fn a_value_with_a_shape_is_checked_and_stored_in_it() {
832 assert_eq!(normalize_value("expires", "03/29").unwrap(), "2029-03");
833 assert!(normalize_value("expires", "soon").is_err());
834 assert_eq!(normalize_value("notes", " as is ").unwrap(), " as is ");
835 assert!(normalize_value(crate::otp::FIELD, "not a key!").is_err());
836 }
837
838 #[test]
839 fn a_login_fills_in_the_order_a_sign_in_form_asks() {
840 let order: Vec<&str> = ItemKind::Login
841 .template()
842 .unwrap()
843 .fill_order()
844 .map(|field| field.name)
845 .collect();
846 assert_eq!(order, ["login", "password", crate::otp::FIELD]);
847 }
848
849 #[test]
850 fn a_field_is_looked_up_by_name() {
851 let payload = Payload::fields(
852 ItemKind::Login,
853 [
854 Field::public("login", "ada"),
855 Field::secret("password", "s"),
856 ],
857 );
858 assert_eq!(payload.field("login").unwrap().value, "ada");
859 assert!(payload.field("password").unwrap().secret);
860 assert!(payload.field("url").is_none());
861 }
862}