use serde::{Serialize, de::DeserializeOwned};
use super::{
CursorError, MIN_CURSOR_SECRET_BYTES,
cursor::{
decode_cursor_with_kind, encode_cursor_with_kind, validate_cursor_kind,
validate_cursor_length,
},
};
use crate::signing::SigningKeys;
#[derive(Debug, Clone)]
pub struct SignedCursorCodec {
keys: SigningKeys,
}
impl SignedCursorCodec {
pub fn new(key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
Ok(Self {
keys: SigningKeys::new(key).map_err(|_| CursorError::InvalidSecret {
min_bytes: MIN_CURSOR_SECRET_BYTES,
})?,
})
}
pub fn with_previous_key(mut self, key: impl AsRef<[u8]>) -> Result<Self, CursorError> {
self.keys
.add_previous(key)
.map_err(|_| CursorError::InvalidSecret {
min_bytes: MIN_CURSOR_SECRET_BYTES,
})?;
Ok(self)
}
pub fn with_previous_keys<I, S>(mut self, keys: I) -> Result<Self, CursorError>
where
I: IntoIterator<Item = S>,
S: AsRef<[u8]>,
{
for key in keys {
self = self.with_previous_key(key)?;
}
Ok(self)
}
pub fn encode<T>(&self, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
self.encode_with_kind(None, value)
}
pub fn decode<T>(&self, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
self.decode_with_kind(None, cursor)
}
pub fn encode_typed<T>(&self, kind: impl Into<String>, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
self.encode_with_kind(Some(validate_cursor_kind(kind)?), value)
}
pub fn decode_typed<T>(&self, kind: &str, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_kind(kind)?;
self.decode_with_kind(Some(kind), cursor)
}
fn encode_with_kind<T>(&self, kind: Option<String>, value: &T) -> Result<String, CursorError>
where
T: Serialize,
{
let payload = encode_cursor_with_kind(kind, value)?;
let signature = self
.keys
.sign(payload.as_bytes())
.map_err(|_| CursorError::InvalidSignature)?;
let cursor = format!("{payload}.{signature}");
validate_cursor_length(&cursor)?;
Ok(cursor)
}
fn decode_with_kind<T>(
&self,
expected_kind: Option<&str>,
cursor: &str,
) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_length(cursor)?;
let (payload, signature) = cursor
.split_once('.')
.ok_or(CursorError::InvalidSignature)?;
self.keys
.verify(payload.as_bytes(), signature)
.map_err(|_| CursorError::InvalidSignature)?;
decode_cursor_with_kind(expected_kind, payload)
}
}