客户端设备识别(Device)

归属 kxed 插件生态:官网 | 在线文档 | 源码仓库 | 主包主页

离线解析 HTTP 请求的 User-Agent 与现代浏览器 Sec-CH-UA* Client Hints,输出终端形态、品牌、型号、操作系统、浏览器与内核、App 内嵌 WebView 及爬虫画像。插件零外部网络依赖、内置高覆盖率预编译规则集与有界 LRU 缓存,支持加载兼容外部 JSON 格式的规则快照并通过 device-update 后台校验原子热更新。

快速接入#

在 Cargo.toml 开启主包 kxed 的 device 特性(需要后台定时拉取外部规则快照时改开 device-update,自动包含 http-client):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["device"] }

注册 DevicePlugin::new() 后,可直接在原生路由 handler 中提取 DeviceInfo / ClientHints,或在 Procedure 中调用 ctx.detect_headers(&headers) / ctx.detect_user_agent(ua):

Rust
use kxed::plugins::device::{ClientHints, DeviceInfo, DevicePlugin};
use kxed::prelude::*;

async fn device_profile(info: DeviceInfo, hints: ClientHints) -> String {
    format!(
        "kind={} os={:?} browser={:?} mobile={} has_hints={}",
        info.device_type.as_str(),
        info.os_name,
        info.browser_name,
        info.is_mobile,
        !hints.is_empty(),
    )
}

#[query(name = "analytics.parse_ua", public)]
pub async fn parse_ua(ctx: &AppCtx, ua: String) -> Result<DeviceInfo, AppErr> {
    ctx.detect_user_agent(&ua)
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(DevicePlugin::new())
        .routes(|router| {
            router.route("/api/device", get(device_profile));
        })
        .run()
        .await
}

核心用法#

User-Agent 与 Client Hints 融合识别#

随着主流浏览器冻结 User-Agent 中的机型与系统小版本,优先使用 detect_headers(&headers)(或 Axum 提取器 DeviceInfo)同时融合 User-Agent 与 RFC 8941 结构化 Sec-CH-UA* 请求头:

  • 提取的 Client Hints 字段:Sec-CH-UA(品牌列表)、Sec-CH-UA-Full-Version-List(优先提供完整浏览器版本)、Sec-CH-UA-Mobile(?1/?0 移动态)、Sec-CH-UA-Platform、Sec-CH-UA-Platform-Version 与 Sec-CH-UA-Model(还原被冻结为 K 的 Android 真实机型)。
  • 独立提取器:ClientHints 实现了无失败的 FromRequestParts,即使未注册 DevicePlugin 也可在 handler 中直接提取;DeviceInfo 提取器依赖已注册的 DevicePlugin。
  • 离线纯内存调用:单测或批处理脚本可直接构造 DeviceDetector::builtin(),调用 detect(ua, &hints)、detect_user_agent(ua)、reload_from_json(bytes)、snapshot_version()、rule_count() 与 clear_cache()。

输出字段说明#

DeviceInfo 标记为 #[non_exhaustive],完整描述一次识别结果:

字段类型说明
device_typeDeviceKind设备形态:desktop、smartphone、tablet、bot、console、tv、wearable、unknown
brand / modelOption<String>设备品牌(如 Apple、Huawei、Xiaomi、OPPO、vivo)与具体型号
os_name / os_versionOption<String>操作系统名(如 iOS、Android、HarmonyOS、Windows、macOS)与版本
browser_name / browser_version / engineOption<String>浏览器名、完整或主版本号与排版引擎(如 Blink、WebKit、Gecko、ArkWeb)
app_name / is_webviewOption<String> / bool识别到的宿主 App(如 WeChat、Alipay、Douyin、Xiaohongshu、Lark)及内嵌 WebView 标记
is_bot / bot_namebool / Option<String>是否为爬虫、监控探针或自动化脚本及其名称
is_mobilebool是否为手机、平板或显式声明移动态的终端

外部规则快照与后台原子热更新#

内置规则已开箱覆盖主流桌面、移动端、国产机型、常见 App WebView 与爬虫;如需快速跟进新机型或自定义内部客户端,可提供外部 JSON 规则快照(RuleSnapshot,包含 version、bots、apps、oss、browsers、devices 与按品牌分组的 brands):

  • 安全与性能护栏:单条 UA 送入正则匹配前先按 device.max_ua_bytes(默认 1024 字节)在 UTF-8 字符边界截断;单份规则快照不得超过 device.update.max_rules_bytes(上限 16 MiB),单条正则与总规则数均受硬上限(MAX_REGEX_PATTERN_BYTES、MAX_TOTAL_RULES)保护,且编译后使用线性时间 DFA 引擎无回溯 ReDoS 风险。
  • 后台热更新(device-update):开启 device-update、注册 HttpClientPlugin 并配置 device.update.url 后,后台任务每隔 device.update.interval 带 If-None-Match(ETag)拉取新快照;若配置了 device.update.sha256 先执行常量时间 SHA-256 校验,再在阻塞线程池完成 JSON 解析与正则预编译,全部校验通过后才经 ArcSwap 无锁替换规则集并清空旧 LRU 缓存;如同时配置了 device.rules_path,会先落同目录临时文件 fsync 再原子 rename 持久化。任何下载、摘要或规则错误均保留旧规则继续服务。

配置#

键缺省范围与含义
device.rules_path空可选外部 JSON 规则快照路径;未配置时仅用内置规则
device.max_ua_bytes1024单条 UA 送入匹配前的截断字节上限,范围 64..=16384
device.cache_capacity16384进程内有界 LRU 缓存容量(以 UA 与 Client Hints 组合为键),0 为关闭,上限 1000000
device.builtin_fallbacktrue加载外部规则后,外部规则未命中的维度是否回退内置默认规则
device.update.url空远程规则快照下载地址(SecretString,日志与 config show 脱敏,须 http:// 或 https://)
device.update.interval24h后台热更新轮询周期,范围 10ms..=365d
device.update.timeout30s单次拉取外部规则快照的 HTTP 超时,范围 100ms..=5m
device.update.sha256空可选 64 位十六进制 SHA-256 摘要,不匹配直接拒收
device.update.max_rules_bytes16777216(16 MiB)单份外部规则快照允许的最大字节数,范围 1024..=67108864(64 MiB)

错误码、多实例与 Prometheus 指标#

  • 错误码映射:DeviceError::InvalidRules 映射为 422 device_invalid_rules;DeviceError::DigestMismatch 映射为 502 device_digest_mismatch;DeviceError::RulesIo 与 DeviceError::UpdateFailed 映射为 500 device_rules_failed / device_update_failed。
  • 多实例部署:每个实例在进程内独立持有只读编译规则与 LRU 缓存,无跨节点锁竞争;多实例共用本地 device.rules_path 时采用独立临时文件原子 rename 互不覆盖,大集群建议把规则快照托管在内部对象存储或静态文件 CDN 上并启用 ETag 304 协商。
指标类型与标签含义
kxed_device_lookup_totalCounter(outcome)设备识别总次数(matched / bot / unknown)
kxed_device_cache_hit_totalCounterLRU 缓存命中次数
kxed_device_cache_miss_totalCounterLRU 缓存未命中次数
kxed_device_rules_reload_totalCounter(outcome)规则热更新与手动重载结果计数(reloaded / not_modified / invalid / failed)