Skip to main content

atmos/os_lib/
cookie.rs

1//! CookieJar および Cookie 属性パーサー(純粋モジュール)
2//!
3//! Web 標準(RFC 6265 / Cookie Store API / document.cookie)に準拠した
4//! クッキーの解析・保持・期限切れ判定・リクエストヘッダ文字列化を提供する。
5
6extern crate alloc;
7use alloc::collections::BTreeMap;
8use alloc::string::String;
9use alloc::vec::Vec;
10
11/// Cookie の属性情報
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
13pub struct CookieRecord {
14    pub name: String,
15    pub value: String,
16    pub max_age: Option<i64>,
17    pub expires: Option<String>,
18    pub domain: Option<String>,
19    pub path: Option<String>,
20    pub secure: bool,
21    pub http_only: bool,
22    pub same_site: Option<String>,
23}
24
25impl CookieRecord {
26    /// 期限切れ(削除対象)かどうかを判定する。
27    pub fn is_expired(&self) -> bool {
28        if let Some(max_age) = self.max_age {
29            if max_age <= 0 {
30                return true;
31            }
32        }
33        if let Some(ref exp) = self.expires {
34            // 過去の西暦(1970年〜2000年、エポック以前)が含まれているか
35            if exp.contains("1970") || exp.contains("1980") || exp.contains("1990") || exp.contains("2000") {
36                return true;
37            }
38        }
39        false
40    }
41}
42
43/// 単一の `Set-Cookie` または `document.cookie` 代入文字列をパースする。
44pub fn parse_cookie_line(s: &str) -> Option<CookieRecord> {
45    let mut parts = s.split(';');
46    let first = parts.next()?.trim();
47    let (name, value) = first.split_once('=')?;
48    let name = name.trim();
49    let value = value.trim();
50    if name.is_empty() {
51        return None;
52    }
53
54    let mut record = CookieRecord {
55        name: String::from(name),
56        value: String::from(value),
57        ..Default::default()
58    };
59
60    for attr in parts {
61        let attr = attr.trim();
62        if attr.is_empty() {
63            continue;
64        }
65        if let Some((k, v)) = attr.split_once('=') {
66            let k = k.trim();
67            let v = v.trim();
68            if k.eq_ignore_ascii_case("max-age") {
69                if let Ok(sec) = v.parse::<i64>() {
70                    record.max_age = Some(sec);
71                }
72            } else if k.eq_ignore_ascii_case("expires") {
73                record.expires = Some(String::from(v));
74            } else if k.eq_ignore_ascii_case("domain") {
75                record.domain = Some(String::from(v));
76            } else if k.eq_ignore_ascii_case("path") {
77                record.path = Some(String::from(v));
78            } else if k.eq_ignore_ascii_case("samesite") {
79                record.same_site = Some(String::from(v));
80            }
81        } else {
82            if attr.eq_ignore_ascii_case("secure") {
83                record.secure = true;
84            } else if attr.eq_ignore_ascii_case("httponly") {
85                record.http_only = true;
86            }
87        }
88    }
89
90    Some(record)
91}
92
93/// インメモリ Cookie ストア
94#[derive(Debug, Clone, Default)]
95pub struct CookieJar {
96    cookies: BTreeMap<String, CookieRecord>,
97}
98
99impl CookieJar {
100    pub const fn new() -> Self {
101        Self {
102            cookies: BTreeMap::new(),
103        }
104    }
105
106    /// `document.cookie = "..."` または `Set-Cookie` の適用
107    pub fn apply_cookie(&mut self, s: &str) {
108        if let Some(record) = parse_cookie_line(s) {
109            if record.is_expired() {
110                self.cookies.remove(&record.name);
111            } else {
112                self.cookies.insert(record.name.clone(), record);
113            }
114        }
115    }
116
117    /// `Cookie: name=value; name2=value2` 文字列の生成(HTTP リクエスト用または `document.cookie` 取得用)
118    pub fn cookie_string(&self) -> String {
119        self.cookies
120            .values()
121            .map(|c| alloc::format!("{}={}", c.name, c.value))
122            .collect::<Vec<_>>()
123            .join("; ")
124    }
125
126    /// Cookie の直接取得
127    pub fn get(&self, name: &str) -> Option<&CookieRecord> {
128        self.cookies.get(name)
129    }
130
131    /// 全 Cookie のイテレータ
132    pub fn all(&self) -> impl Iterator<Item = &CookieRecord> {
133        self.cookies.values()
134    }
135
136    /// Cookie の明示的削除
137    pub fn delete(&mut self, name: &str) {
138        self.cookies.remove(name);
139    }
140
141    /// Cookie の直接登録
142    pub fn insert(&mut self, name: &str, value: &str) {
143        let record = CookieRecord {
144            name: String::from(name),
145            value: String::from(value),
146            ..Default::default()
147        };
148        self.cookies.insert(String::from(name), record);
149    }
150
151    /// クリーンアップ(全削除)
152    pub fn clear(&mut self) {
153        self.cookies.clear();
154    }
155}