wordval-utils 1.0.3

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Web 解析工具:URL 解析、IP 提取、User-Agent 解析等

use std::net::SocketAddr;

/// 检查是否为私有 IP(IPv4/IPv6)
///
/// IPv4 私有地址包括:私有地址(10/8, 172.16/12, 192.168/16)、环回地址(127/8)、
/// 链路本地地址(169.254/16)、未指定地址(0.0.0.0)、组播地址(224/4)
///
/// IPv6 私有地址包括:环回地址(::1)、未指定地址(::)、链路本地单播(fe80::/10)、
/// 唯一本地地址(fc00::/7)、组播地址(ff::/8)
///
/// # 参数
/// - `ip`: IP 地址字符串
///
/// # 返回
/// 若为私有 IP 返回 true,否则返回 false
pub fn is_private_ip(ip: &str) -> bool {
    if let Ok(addr) = ip.parse::<std::net::IpAddr>() {
        match addr {
            std::net::IpAddr::V4(ipv4) => {
                ipv4.is_private()
                    || ipv4.is_loopback()
                    || ipv4.is_link_local()
                    || ipv4.is_unspecified()
                    || ipv4.is_multicast()
            }
            std::net::IpAddr::V6(ipv6) => {
                let seg0 = ipv6.segments()[0];
                ipv6.is_loopback()
                    || ipv6.is_unspecified()
                    // fe80::/10 链路本地(MSRV 1.75 无 is_unicast_link_local,手写段判断)
                    || (seg0 & 0xffc0) == 0xfe80
                    // fc00::/7 唯一本地
                    || (seg0 & 0xfe00) == 0xfc00
                    || ipv6.is_multicast()
            }
        }
    } else {
        false
    }
}

/// 安全默认:从直连对端地址提取客户端 IP。
///
/// **不信任任何代理头**(X-Forwarded-For / CF-Connecting-IP 等)。
///
/// 若服务前置可信反代/负载均衡,请改用 [`extract_client_ip_trusted`]
/// 并在配置中声明 `trusted_proxies`,仅在直连对端为可信网段时才读取头部。
pub fn extract_client_ip(_headers: &http::HeaderMap, connect_info: &SocketAddr) -> String {
    connect_info.ip().to_string()
}

/// 可信代理网段集合(支持精确 IP 或 CIDR,如 `10.0.0.0/8`)
pub struct TrustedProxies {
    nets: Vec<(std::net::IpAddr, u32)>,
}

impl TrustedProxies {
    /// 从配置字符串列表解析可信代理(支持 `ip` 或 `ip/bits` CIDR)。
    /// 无法解析的项会被静默忽略。
    pub fn new(specs: &[String]) -> Self {
        let mut nets = Vec::with_capacity(specs.len());
        for s in specs {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                continue;
            }
            let (ip_str, bits) = match trimmed.split_once('/') {
                Some((ip_s, pre_s)) => {
                    match (
                        ip_s.trim().parse::<std::net::IpAddr>(),
                        pre_s.trim().parse::<u32>(),
                    ) {
                        (Ok(ip), Ok(b)) => (ip, b),
                        _ => continue,
                    }
                }
                None => match trimmed.parse::<std::net::IpAddr>() {
                    Ok(ip) => (ip, if ip.is_ipv4() { 32 } else { 128 }),
                    _ => continue,
                },
            };
            nets.push((ip_str, bits));
        }
        TrustedProxies { nets }
    }

    /// 是否为空(未配置任何可信代理)
    pub fn is_empty(&self) -> bool {
        self.nets.is_empty()
    }

    /// 判断给定 IP 是否落在某个可信网段内
    pub fn contains(&self, ip: &std::net::IpAddr) -> bool {
        self.nets
            .iter()
            .any(|(net, bits)| ip_in_net(ip, net, *bits))
    }
}

/// 判断 `ip` 是否落在以 `net` 为网络地址、`bits` 为前缀长度的网络内
fn ip_in_net(ip: &std::net::IpAddr, net: &std::net::IpAddr, bits: u32) -> bool {
    match (ip, net) {
        (std::net::IpAddr::V4(a), std::net::IpAddr::V4(b)) => {
            let bits = bits.min(32);
            if bits == 0 {
                return true;
            }
            let mask = if bits >= 32 {
                u32::MAX
            } else {
                !(u32::MAX >> bits)
            };
            (u32::from(*a) & mask) == (u32::from(*b) & mask)
        }
        (std::net::IpAddr::V6(a), std::net::IpAddr::V6(b)) => {
            let bits = bits.min(128);
            if bits == 0 {
                return true;
            }
            let ma = a.segments();
            let mb = b.segments();
            let mut done = 0u32;
            for i in 0..8 {
                if done >= bits {
                    return true;
                }
                let remain = bits - done;
                let m: u16 = if remain >= 16 {
                    0xFFFF
                } else {
                    !(0xFFFFu16 >> remain)
                };
                if (ma[i] & m) != (mb[i] & m) {
                    return false;
                }
                done += 16;
            }
            true
        }
        _ => false,
    }
}

/// 从请求头提取客户端真实 IP(仅在直连对端为可信代理时读取头部)。
///
/// 算法:
/// 1. 若直连对端 IP 不在可信网段内,直接返回直连 IP(不读取任何头部)。
/// 2. 若直连对端可信,则优先取 `CF-Connecting-IP`;否则解析 `X-Forwarded-For`
///    从右向左遍历,跳过可信网段与私有/环回/未指定地址,取第一个真实公网 IP。
pub fn extract_client_ip_trusted(
    headers: &http::HeaderMap,
    connect_info: &SocketAddr,
    trusted: &TrustedProxies,
) -> String {
    let peer = connect_info.ip();
    if !trusted.contains(&peer) {
        return peer.to_string();
    }

    // 直连对端是可信代理,从头部取真实 IP
    if let Some(v) = headers
        .get("CF-Connecting-IP")
        .and_then(|h| h.to_str().ok())
    {
        if let Ok(ip) = v.trim().parse::<std::net::IpAddr>() {
            if !trusted.contains(&ip) {
                return ip.to_string();
            }
        }
    }

    if let Some(v) = headers.get("X-Forwarded-For").and_then(|h| h.to_str().ok()) {
        let ips: Vec<std::net::IpAddr> = v
            .split(',')
            .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
            .collect();
        for ip in ips.iter().rev() {
            if trusted.contains(ip) || is_internal_ip(ip) {
                continue;
            }
            return ip.to_string();
        }
    }

    peer.to_string()
}

/// 判断 IP 是否为内部/不可路由地址(私有、环回、未指定、IPv6 唯一本地)
fn is_internal_ip(ip: &std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(a) => a.is_private() || a.is_loopback() || a.is_unspecified(),
        std::net::IpAddr::V6(a) => {
            // fc00::/7 唯一本地(MSRV 1.75 无 is_unique_local,手写段判断)
            a.is_loopback() || a.is_unspecified() || (a.segments()[0] & 0xfe00) == 0xfc00
        }
    }
}

/// Web 解析工具
///
/// 提供 URL 解析、真实 IP 获取、私网 IP 判断、查询字符串构造等功能。
pub struct WebExt;

impl WebExt {
    /// 拆分 URL:返回 `(host[:port], 路径部分)`。路径部分含开头 `/`,无路径时为 None。
    /// 仅支持带 `scheme://` 的绝对 URL(与原 url crate 行为一致:相对 URL 返回 None)。
    fn split_authority(url_str: &str) -> Option<(&str, Option<&str>)> {
        let rest = url_str.split_once("://")?.1;
        let (authority, path_part) = match rest.find(['/', '?', '#']) {
            Some(i) => (&rest[..i], Some(&rest[i..])),
            None => (rest, None),
        };
        // authority 中跳过 userinfo(`user:pass@`),取最后一个 `@` 之后
        let host_port = authority
            .rsplit_once('@')
            .map(|(_, h)| h)
            .unwrap_or(authority);
        Some((host_port, path_part))
    }

    /// 解析 URL 获取域名(自研实现,替代 url crate)
    ///
    /// 支持 userinfo、IPv6 括号形式;端口会被剥离,IPv6 返回无括号形式。
    pub fn domain(url_str: &str) -> Option<String> {
        let (host_port, _) = Self::split_authority(url_str)?;
        if host_port.is_empty() {
            return None;
        }
        if let Some(ipv6) = host_port.strip_prefix('[') {
            return ipv6.find(']').map(|end| ipv6[..end].to_string());
        }
        host_port.split(':').next().map(|h| h.to_string())
    }

    /// 解析 URL 获取路径(含开头的 `/`,不含 query/fragment;自研实现,替代 url crate)
    pub fn path(url_str: &str) -> Option<String> {
        let (_, path_part) = Self::split_authority(url_str)?;
        match path_part {
            None => Some("/".to_string()),
            Some(p) => {
                if p.starts_with('?') || p.starts_with('#') {
                    return Some("/".to_string());
                }
                let end = p.find(['?', '#']).unwrap_or(p.len());
                Some(p[..end].to_string())
            }
        }
    }

    /// 从请求头获取真实 IP(X-Forwarded-For 或 X-Real-IP)。
    ///
    /// # 安全警告
    ///
    /// 本方法**无条件信任** `X-Forwarded-For` / `X-Real-IP` 头,任何客户端都能
    /// 伪造这些头来伪装来源 IP。**切勿**用于限流、鉴权、审计等安全敏感场景。
    /// 仅当服务确定运行在可信反向代理之后、且该代理会覆盖这些头时才可使用。
    ///
    /// 安全场景请改用 [`extract_client_ip_trusted`],它会校验直连对端是否为
    /// 可信代理网段后再读取头部。
    pub fn real_ip(headers: &[(String, String)], remote_addr: &str) -> String {
        for (key, val) in headers {
            if key.eq_ignore_ascii_case("x-forwarded-for") {
                // 取最左侧(最接近原始客户端)的有效 IP
                if let Some(ip) = val
                    .split(',')
                    .filter_map(|p| p.trim().parse::<std::net::IpAddr>().ok())
                    .next()
                {
                    return ip.to_string();
                }
            }
            if key.eq_ignore_ascii_case("x-real-ip") {
                if let Ok(ip) = val.trim().parse::<std::net::IpAddr>() {
                    return ip.to_string();
                }
            }
        }
        // 兜底:优先按 `IP:port` / `[IPv6]:port` 解析,其次按裸 IP,最后才做字符串截断
        let trimmed = remote_addr.trim();
        if let Ok(sa) = trimmed.parse::<SocketAddr>() {
            return sa.ip().to_string();
        }
        if let Ok(ip) = trimmed.parse::<std::net::IpAddr>() {
            return ip.to_string();
        }
        trimmed.split(':').next().unwrap_or(trimmed).to_string()
    }
    /// 检查是否为私有 IP(委托给公共函数 `is_private_ip`)
    pub fn is_private_ip(ip: &str) -> bool {
        is_private_ip(ip)
    }
    /// 构建 URL 查询字符串
    pub fn build_query(params: &[(&str, &str)]) -> String {
        if params.is_empty() {
            return String::new();
        }
        let parts: Vec<String> = params
            .iter()
            .map(|(k, v)| format!("{}={}", Self::percent_encode(k), Self::percent_encode(v)))
            .collect();
        format!("?{}", parts.join("&"))
    }

    /// URL 路径段/查询参数编码:仅保留字母数字与 `-` `.` `_` `~`,其余字节转 `%XX`(大写)。
    ///
    /// 对应 RFC 3986 unreserved 字符集,与 SigV4 canonical URI/query 编码要求一致。
    /// 逐字节直接拼装,不为每个转义字节分配临时字符串。
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::WebExt;
    ///
    /// assert_eq!(WebExt::percent_encode("a-b_c.d~"), "a-b_c.d~");
    /// assert_eq!(WebExt::percent_encode("a b"), "a%20b");
    /// assert_eq!(WebExt::percent_encode("/"), "%2F");
    /// assert_eq!(WebExt::percent_encode("中文"), "%E4%B8%AD%E6%96%87");
    /// ```
    pub fn percent_encode(seg: &str) -> String {
        const HEX: &[u8; 16] = b"0123456789ABCDEF";
        // 容量按最大膨胀(每字节 -> %XX,3 倍)预留,避免二次分配
        let mut out = String::with_capacity(seg.len() * 3);
        for &byte in seg.as_bytes() {
            if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
                out.push(byte as char);
            } else {
                out.push('%');
                out.push(HEX[(byte >> 4) as usize] as char);
                out.push(HEX[(byte & 0x0f) as usize] as char);
            }
        }
        out
    }

    /// 按扩展名推断 MIME 类型(返回静态字符串,零分配;需要所有权时自行 `to_string()`)
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::WebExt;
    ///
    /// assert_eq!(WebExt::mime_guess("a.PNG"), "image/png");
    /// assert_eq!(WebExt::mime_guess("noext"), "application/octet-stream");
    /// ```
    pub fn mime_guess(filename: &str) -> &'static str {
        let ext = std::path::Path::new(filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("bin");

        match ext.to_ascii_lowercase().as_str() {
            "jpg" | "jpeg" => "image/jpeg",
            "png" => "image/png",
            "gif" => "image/gif",
            "webp" => "image/webp",
            "svg" => "image/svg+xml",
            "pdf" => "application/pdf",
            "json" => "application/json",
            "html" | "htm" => "text/html",
            "css" => "text/css",
            "js" => "application/javascript",
            "txt" => "text/plain",
            "csv" => "text/csv",
            "zip" => "application/zip",
            "mp4" => "video/mp4",
            "mp3" => "audio/mpeg",
            "doc" => "application/msword",
            "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "xls" => "application/vnd.ms-excel",
            "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            _ => "application/octet-stream",
        }
    }

    /// URL 解码(`%E4%BD%A0` → `"你"`)
    ///
    /// 支持 `%XX` 十六进制编码和 `+` 作为空格。
    /// 非法编码(如 `%ZZ` 或不完整的 `%X`)会原样保留。
    pub fn url_decode(s: &str) -> String {
        urldecode(s)
    }

    /// 解析 Content-Type 头,提取 MIME 类型
    ///
    /// # 示例
    ///
    /// ```
    /// use wordval_utils::WebExt;
    ///
    /// assert_eq!(
    ///     WebExt::content_type_mime("application/json; charset=utf-8"),
    ///     Some("application/json".to_string())
    /// );
    /// assert_eq!(
    ///     WebExt::content_type_mime("text/html"),
    ///     Some("text/html".to_string())
    /// );
    /// ```
    pub fn content_type_mime(content_type: &str) -> Option<String> {
        content_type
            .split(';')
            .next()
            .map(|s| s.trim().to_lowercase())
            .filter(|s| !s.is_empty())
    }
}

fn urldecode(s: &str) -> String {
    fn hex_val(c: u8) -> Option<u8> {
        match c {
            b'0'..=b'9' => Some(c - b'0'),
            b'a'..=b'f' => Some(c - b'a' + 10),
            b'A'..=b'F' => Some(c - b'A' + 10),
            _ => None,
        }
    }
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'%' => match (bytes.get(i + 1), bytes.get(i + 2)) {
                (Some(&h), Some(&l)) => match (hex_val(h), hex_val(l)) {
                    (Some(h), Some(l)) => {
                        out.push((h << 4) | l);
                        i += 3;
                    }
                    // 非法十六进制,`%` 原样保留
                    _ => {
                        out.push(b'%');
                        i += 1;
                    }
                },
                // 不完整,`%` 原样保留
                _ => {
                    out.push(b'%');
                    i += 1;
                }
            },
            b'+' => {
                // URL 编码中 + 表示空格
                out.push(b' ');
                i += 1;
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    // 尝试转换为 UTF-8,失败则原样返回
    String::from_utf8(out).unwrap_or_else(|_| s.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_url_decode_basic() {
        assert_eq!(WebExt::url_decode("hello%20world"), "hello world");
        assert_eq!(WebExt::url_decode("hello+world"), "hello world");
    }

    #[test]
    fn test_url_decode_utf8() {
        // "%E4%BD%A0%E5%A5%BD" = "你好"
        assert_eq!(WebExt::url_decode("%E4%BD%A0%E5%A5%BD"), "你好");
    }

    #[test]
    fn test_url_decode_invalid() {
        // 非法十六进制,原样保留
        assert_eq!(WebExt::url_decode("%ZZ"), "%ZZ");
        // 不完整
        assert_eq!(WebExt::url_decode("%E"), "%E");
    }

    #[test]
    fn test_url_decode_no_encoding() {
        assert_eq!(WebExt::url_decode("hello"), "hello");
    }

    #[test]
    fn test_percent_encode_keeps_unreserved() {
        assert_eq!(WebExt::percent_encode("a-b_c.d~"), "a-b_c.d~");
        assert_eq!(WebExt::percent_encode("a b"), "a%20b");
        assert_eq!(WebExt::percent_encode("/"), "%2F");
        assert_eq!(WebExt::percent_encode("中文"), "%E4%B8%AD%E6%96%87");
    }

    #[test]
    fn test_mime_guess_extensions() {
        assert_eq!(WebExt::mime_guess("a.PNG"), "image/png");
        assert_eq!(WebExt::mime_guess("a.jpeg"), "image/jpeg");
        assert_eq!(WebExt::mime_guess("noext"), "application/octet-stream");
    }

    #[test]
    fn test_content_type_mime_json() {
        assert_eq!(
            WebExt::content_type_mime("application/json; charset=utf-8"),
            Some("application/json".to_string())
        );
    }

    #[test]
    fn test_content_type_mime_html() {
        assert_eq!(
            WebExt::content_type_mime("text/html"),
            Some("text/html".to_string())
        );
    }

    #[test]
    fn test_content_type_mime_with_params() {
        assert_eq!(
            WebExt::content_type_mime("multipart/form-data; boundary=something"),
            Some("multipart/form-data".to_string())
        );
    }

    #[test]
    fn test_content_type_mime_empty() {
        assert_eq!(WebExt::content_type_mime(""), None);
    }

    #[test]
    fn test_content_type_mime_case_insensitive() {
        assert_eq!(
            WebExt::content_type_mime("Application/JSON"),
            Some("application/json".to_string())
        );
    }
}