aoc_toolkit/client/
session.rs1use keyring::v1::{Entry, Error};
2use std::env::{self, VarError};
3use std::fs;
4use std::io::ErrorKind;
5use std::path::{Path, PathBuf};
6
7use super::cache;
8use super::error::ClientError;
9use super::http::session_cookie;
10use sha2::{Digest, Sha256};
11
12const SERVICE: &str = "dev.kyrboforge.aoc-toolkit";
13const ACCOUNT: &str = "adventofcode.com";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum SessionSource {
17 Environment,
18 Dotenv,
19 CredentialStore,
20}
21
22pub(crate) struct SessionStore;
23
24impl SessionStore {
25 fn entry() -> Result<Entry, ClientError> {
26 Entry::new(SERVICE, ACCOUNT).map_err(|_| ClientError::CredentialStore)
27 }
28
29 pub(crate) fn load() -> Result<Option<String>, ClientError> {
30 match Self::entry()?.get_password() {
31 Ok(token) => Ok(Some(token)),
32 Err(Error::NoEntry) => Ok(None),
33 Err(_) => Err(ClientError::CredentialStore),
34 }
35 }
36
37 #[cfg(feature = "cli")]
38 pub(crate) fn save(token: &str) -> Result<(), ClientError> {
39 session_cookie(token)?;
40
41 Self::entry()?
42 .set_password(token)
43 .map_err(|_| ClientError::CredentialStore)
44 }
45
46 #[cfg(feature = "cli")]
47 pub(crate) fn delete() -> Result<(), ClientError> {
48 match Self::entry()?.delete_credential() {
49 Ok(()) | Err(Error::NoEntry) => Ok(()),
50 Err(_) => Err(ClientError::CredentialStore),
51 }
52 }
53
54 fn account_path(root: &Path, token: &str) -> PathBuf {
55 let fingerprint = hex::encode(Sha256::digest(token.as_bytes()));
56
57 root.join("sessions").join(format!("{fingerprint}.txt"))
58 }
59
60 pub(crate) fn known_account(root: &Path, token: &str) -> Result<Option<u64>, ClientError> {
61 let path = Self::account_path(root, token);
62
63 let content = match fs::read_to_string(&path) {
64 Ok(content) => content,
65
66 Err(error) if error.kind() == ErrorKind::NotFound => {
67 return Ok(None);
68 }
69
70 Err(source) => {
71 return Err(cache::io_error(&path, source));
72 }
73 };
74
75 let account_id = content
76 .trim()
77 .parse::<u64>()
78 .ok()
79 .filter(|id| *id != 0)
80 .ok_or(ClientError::AccountIdentityUnavailable)?;
81
82 Ok(Some(account_id))
83 }
84
85 pub(crate) fn remember_account_at(
86 root: &Path,
87 token: &str,
88 account_id: u64,
89 ) -> Result<(), ClientError> {
90 session_cookie(token)?;
91
92 if account_id == 0 {
93 return Err(ClientError::AccountIdentityUnavailable);
94 }
95
96 let _guard = cache::lock(&root.join("sessions.lock"))?;
97
98 match Self::known_account(root, token)? {
99 Some(existing) if existing != account_id => Err(ClientError::AccountIdentityMismatch),
100
101 Some(_) => Ok(()),
102
103 None => cache::store(&Self::account_path(root, token), &account_id.to_string()),
104 }
105 }
106
107 #[cfg(feature = "cli")]
108 pub(crate) fn remember_account(token: &str, account_id: u64) -> Result<(), ClientError> {
109 Self::remember_account_at(&cache::root()?, token, account_id)
110 }
111}
112
113fn read_override() -> Result<Option<(String, SessionSource)>, ClientError> {
114 match env::var("SESSION_ID") {
115 Ok(token) => {
116 return Ok(Some((token, SessionSource::Environment)));
117 }
118
119 Err(VarError::NotPresent) => {}
120
121 Err(VarError::NotUnicode(_)) => {
122 return Err(ClientError::InvalidSession);
123 }
124 }
125
126 let entries = match dotenvy::dotenv_iter() {
127 Ok(entries) => entries,
128
129 Err(error) if error.not_found() => {
130 return Ok(None);
131 }
132
133 Err(_) => {
134 return Err(ClientError::InvalidSessionConfiguration);
135 }
136 };
137
138 let mut session = None;
139
140 for entry in entries {
141 let (key, value) = entry.map_err(|_| ClientError::InvalidSessionConfiguration)?;
142
143 if key == "SESSION_ID" && session.is_none() {
144 session = Some((value, SessionSource::Dotenv));
145 }
146 }
147
148 Ok(session)
149}
150
151fn resolve_with(
152 session_override: Option<(String, SessionSource)>,
153 load_stored: impl FnOnce() -> Result<Option<String>, ClientError>,
154) -> Result<Option<(String, SessionSource)>, ClientError> {
155 let session = match session_override {
156 Some(session) => Some(session),
157
158 None => load_stored()?.map(|token| (token, SessionSource::CredentialStore)),
159 };
160
161 if let Some((token, _)) = &session {
162 session_cookie(token)?;
163 }
164
165 Ok(session)
166}
167
168pub(crate) fn resolve_session() -> Result<Option<(String, SessionSource)>, ClientError> {
169 resolve_with(read_override()?, SessionStore::load)
170}
171
172pub(super) fn get_session() -> Result<String, ClientError> {
173 resolve_session()?
174 .map(|(token, _)| token)
175 .ok_or(ClientError::MissingSession)
176}
177
178#[cfg(test)]
179mod tests;