feat(tds): TDS 出向客户端(照抄上游 TdsReportClient 的 internal 通道)

- 9 个方法:internal_catalog/apply/apply_batch + list/dispute/confirm/settle/receipt/voucher
- 出向固定 6 个头(App-Code: sswflow / Jnpf-Origin: pc / Vue-Version: 3 / X-Internal-Token / X-Protocol-Version: 1.0)
- 超时 3s 连 / 5s 读;no_proxy 避免系统代理劫持 loopback 的 TDS
- 路径段白名单(字母数字下划线短横线,≤64)

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-25 13:21:27 +08:00
1 parent cda8729a3e
commit 03e9f05736
2 files changed
+378

No files matched your search

+1
View File
@@ -22,3 +22,4 @@ pub mod registry;
pub mod routes;
pub mod session;
pub mod state;
pub mod tds;
+377
View File
@@ -0,0 +1,377 @@
//! TDS 出向客户端(照抄上游 `TdsReportClient` 的 **internal 通道**)。
//!
//! 上游真源:`/tmp/sswtdc-probe/boot/ssw-tdc/ssw-tdc-biz/src/main/java/ssw/tdc/client/TdsReportClient.java`
//! (`internalHeaders()` / `restTemplate()` / `internalCatalog` / `internalApply` / `internalApplyBatch`
//! / `listBillingForConnector` / `disputeBilling` / `confirmBilling` / `settleBilling` / `receiptBilling`
//! / `voucherBilling`)。
//!
//! 🔴 **只实现 internal 通道**(`X-Internal-Token` + 固定头,走 TDS `white-url` 放行的内部端点)。
//! 上游还有一条 login/`ensureToken` 通道(JNPF 登录换 token)⇒ 本轮**不做**(见 spec §5)。
use std::time::Duration;
use serde_json::{json, Value};
/// 连接超时(照抄上游 `restTemplate()`:`setConnectTimeout(3000)`)。
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
/// 读取超时(照抄上游 `restTemplate()`:`setReadTimeout(5000)`)。
pub const READ_TIMEOUT: Duration = Duration::from_secs(5);
/// 未配置 TDS 地址(本地单机模式)时的降级文案。
pub const NOOP_MESSAGE: &str = "未配置 TDS 地址(本地单机模式)";
/// 账本 / 订单等 id 的路径段白名单:仅 ASCII 字母数字、下划线、短横线。
///
/// 🔴 出向 URL **只由固定路径模板 + 已校验的段**拼出 ⇒ 用户输入绝不直接进 URL 路径。
pub fn is_safe_path_segment(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 64
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}
/// 解包型方法的信封拆解:`code == 200` ⇒ 取 `data`;否则取 `msg` 当拒因。
///
/// 照抄上游 `internalCatalog` / `internalApply` / `internalApplyBatch`:
/// `code==200` ⇒ 返回 `data`;否则返回 `{fail: msg}`;异常 ⇒ `{fail: msg + ": " + e}`。
/// Rust 侧统一成 `Result`(spec D2),但**语义逐条对齐**。
fn unwrap_data(envelope: Value, fallback_msg: &str) -> Result<Value, String> {
let code = envelope.get("code").and_then(|v| v.as_i64()).unwrap_or(0);
if code == 200 {
Ok(envelope.get("data").cloned().unwrap_or(Value::Null))
} else {
let msg = envelope
.get("msg")
.and_then(|v| v.as_str())
.filter(|s| !s.trim().is_empty())
.unwrap_or(fallback_msg);
Err(msg.to_string())
}
}
/// TDS 出向客户端(≡ 上游 `TdsReportClient` 的 internal 通道)。
#[derive(Clone)]
pub struct TdsClient {
/// TDS 基地址;`None` ⇒ **NOOP**(未配 `SSW_TDS_BASE_URL` ⇒ 本地单机模式)。
base_url: Option<String>,
/// 出向内部令牌(`SSW_TDS_INTERNAL_TOKEN`)。
internal_token: String,
http: reqwest::Client,
}
impl TdsClient {
/// 造客户端。
///
/// 🔴 `.no_proxy()`:reqwest 默认会读**系统代理**
/// (`hyper_util` 的 `Matcher::from_system()` ⇒ 读 `HTTP_PROXY` 等环境变量,
/// 且在 macOS 上还读**系统网络设置**里的代理)⇒ loopback 的 TDS 会被劫持。
/// TDS 是**内网直连**服务 ⇒ 出向**必须直连**。
///
/// ⚠️ 超时照抄上游 `restTemplate()`:连接 3s / 读取 5s(**快速失败**,别拖垮本地业务)。
pub fn new(base_url: Option<String>, internal_token: String) -> Self {
let http = reqwest::Client::builder()
.no_proxy()
.connect_timeout(CONNECT_TIMEOUT)
.timeout(READ_TIMEOUT)
.build()
.expect("构造 TDS 出向 HTTP 客户端失败");
Self {
base_url: base_url.map(|b| b.trim().trim_end_matches('/').to_string()),
internal_token,
http,
}
}
/// 是否处于 NOOP 模式(未配置 TDS 地址)。
pub fn is_noop(&self) -> bool {
self.base_url.is_none()
}
/// 拼出向 URL(固定路径模板 + 基地址)。
///
/// 🔴 路径段必须已过 [`is_safe_path_segment`](调用方负责)⇒ 这里只做拼接。
fn url(&self, path: &str) -> Result<String, String> {
match &self.base_url {
Some(base) => Ok(format!("{}{}", base, path)),
None => Err(NOOP_MESSAGE.to_string()),
}
}
/// 出向请求头(**逐字照抄**上游 `internalHeaders()`,正好 6 个)。
///
/// | 头 | 值 |
/// |---|---|
/// | `Content-Type` | `application/json` |
/// | `App-Code` | `sswflow`(⚠️ **不是** `tdc`,那是 `Bridge/**` 通道,本轮不做) |
/// | `Jnpf-Origin` | `pc` |
/// | `Vue-Version` | `3` |
/// | `X-Internal-Token` | 出向令牌 |
/// | `X-Protocol-Version` | `1.0`(与上游 `InternalTokenSupport.PROTOCOL_VERSION` 一致) |
///
/// 🔴 **绝不**加 `Authorization` / `Cookie` ⇒ 本地会话令牌不外泄。
fn internal_headers(&self) -> reqwest::header::HeaderMap {
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
let mut h = HeaderMap::new();
h.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
h.insert("app-code", HeaderValue::from_static("sswflow"));
h.insert("jnpf-origin", HeaderValue::from_static("pc"));
h.insert("vue-version", HeaderValue::from_static("3"));
if let Ok(v) = HeaderValue::from_str(&self.internal_token) {
h.insert("x-internal-token", v);
}
h.insert("x-protocol-version", HeaderValue::from_static("1.0"));
h
}
/// 发一次出向请求,返回 TDS 的**原始信封** `{code,msg,data}`。
///
/// `Err(msg)` = **不可达 / 超时 / 网络错 / 响应不是 JSON**(≠ TDS 业务拒绝)。
async fn send(
&self,
method: reqwest::Method,
path: &str,
body: Option<&Value>,
) -> Result<Value, String> {
let url = self.url(path)?;
let mut req = self
.http
.request(method, &url)
.headers(self.internal_headers());
if let Some(b) = body {
req = req.json(b);
}
let resp = req.send().await.map_err(|e| format!("TDS 不可达: {}", e))?;
// 🔴 TDS 业务失败走 **HTTP 200 + body code != 200** ⇒ 这里**不**按状态码判成败,
// 一律把 body 交给上层判 `code`。
let text = resp
.text()
.await
.map_err(|e| format!("读取 TDS 响应失败: {}", e))?;
serde_json::from_str::<Value>(&text).map_err(|e| format!("TDS 响应不是合法 JSON: {}", e))
}
// ---------------- 解包型(上游返回 `data` 或 `{fail:msg}`) ----------------
/// 服务目录(上游 `internalCatalog`):`POST /api/ssw/tds/Catalog/Internal/Catalog`。
///
/// ⚠️ 上游 `body.put("keyword", keyword)` —— `keyword` 为 `null` 时**也**带这个键 ⇒ 照抄。
pub async fn internal_catalog(
&self,
space_id: &str,
keyword: Option<&str>,
) -> Result<Value, String> {
let body = json!({"spaceId": space_id, "keyword": keyword});
let env = self
.send(
reqwest::Method::POST,
"/api/ssw/tds/Catalog/Internal/Catalog",
Some(&body),
)
.await?;
unwrap_data(env, "目录查询失败")
}
/// 内部下单(上游 `internalApply`):`POST /api/ssw/tds/TradeOrder/Internal/Apply`。
pub async fn internal_apply(&self, body: &Value) -> Result<Value, String> {
let env = self
.send(
reqwest::Method::POST,
"/api/ssw/tds/TradeOrder/Internal/Apply",
Some(body),
)
.await?;
unwrap_data(env, "下单失败")
}
/// 内部批次下单(上游 `internalApplyBatch`):`POST /api/ssw/tds/TradeOrder/Internal/ApplyBatch`。
pub async fn internal_apply_batch(&self, body: &Value) -> Result<Value, String> {
let env = self
.send(
reqwest::Method::POST,
"/api/ssw/tds/TradeOrder/Internal/ApplyBatch",
Some(body),
)
.await?;
unwrap_data(env, "批次下单失败")
}
// ---------------- 整包型(上游原样返回 `{code,msg,data}`) ----------------
/// 本方账单列表(上游 `listBillingForConnector`):`POST /api/ssw/tds/BillingLedger/Internal/List`。
///
/// ⚠️ 上游 `keyword` **可选**:缺省时**不带**这个键(`ownsLedger` 复用本方法做越权校验,
/// 缺省时不得过滤)。上游异常时返回 `null` ⇒ 本方法返回 `Err`。
pub async fn list_billing_for_connector(
&self,
connector_id: &str,
keyword: Option<&str>,
) -> Result<Value, String> {
let mut body = json!({"connectorId": connector_id});
if let Some(k) = keyword {
if !k.trim().is_empty() {
body["keyword"] = Value::String(k.trim().to_string());
}
}
self.send(
reqwest::Method::POST,
"/api/ssw/tds/BillingLedger/Internal/List",
Some(&body),
)
.await
}
/// 发起异议(上游 `disputeBilling`):`PUT /api/ssw/tds/BillingLedger/{id}/Dispute`,体 `{}`。
pub async fn dispute_billing(&self, ledger_id: &str) -> Result<Value, String> {
let path = ledger_path(ledger_id, "Dispute")?;
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
.await
}
/// 确认账单(上游 `confirmBilling`):`PUT .../{id}/Confirm?connectorId=<enc>`,体 `{}`。
pub async fn confirm_billing(
&self,
ledger_id: &str,
connector_id: &str,
) -> Result<Value, String> {
let path = ledger_action_path(ledger_id, "Confirm", connector_id)?;
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
.await
}
/// 结算账单(上游 `settleBilling`):`PUT .../{id}/Settle?connectorId=<enc>`,体 `{}`。
pub async fn settle_billing(
&self,
ledger_id: &str,
connector_id: &str,
) -> Result<Value, String> {
let path = ledger_action_path(ledger_id, "Settle", connector_id)?;
self.send(reqwest::Method::PUT, &path, Some(&json!({})))
.await
}
/// 上传结算回执(上游 `receiptBilling`):**`POST`** `/api/ssw/tds/BillingLedger/{id}/Receipt`。
///
/// ⚠️ TDS 侧是 **POST**(我们对外仍 PUT,对齐上游 TDC 控制器)。
/// ⚠️ 上游**只挑** `receiptNo` / `remark` 两个键;`body` 为空 ⇒ 发空对象。
pub async fn receipt_billing(&self, ledger_id: &str, body: &Value) -> Result<Value, String> {
let path = ledger_path(ledger_id, "Receipt")?;
let mut payload = json!({});
if let Some(obj) = body.as_object() {
for key in ["receiptNo", "remark"] {
if let Some(v) = obj.get(key) {
payload[key] = v.clone();
}
}
}
self.send(reqwest::Method::POST, &path, Some(&payload))
.await
}
/// 对账凭证(上游 `voucherBilling`):`GET /api/ssw/tds/BillingLedger/{id}/Voucher`。
pub async fn voucher_billing(&self, ledger_id: &str) -> Result<Value, String> {
let path = ledger_path(ledger_id, "Voucher")?;
self.send(reqwest::Method::GET, &path, None).await
}
}
/// 账本动作路径(`/api/ssw/tds/BillingLedger/{id}/{action}`),段过白名单。
fn ledger_path(ledger_id: &str, action: &str) -> Result<String, String> {
if !is_safe_path_segment(ledger_id) {
return Err(format!("账本 id 非法: {}", ledger_id));
}
Ok(format!(
"/api/ssw/tds/BillingLedger/{}/{}",
ledger_id, action
))
}
/// 账本动作路径 + `connectorId` 查询串(上游 `billingAction`)。
///
/// ⚠️ `connectorId` 走**查询串**(不是头)⇒ 必须 URL 编码。
fn ledger_action_path(ledger_id: &str, action: &str, connector_id: &str) -> Result<String, String> {
let base = ledger_path(ledger_id, action)?;
if connector_id.trim().is_empty() {
return Ok(base);
}
Ok(format!("{}?connectorId={}", base, url_encode(connector_id)))
}
/// 最小 URL 编码(查询串用;只保留 `A-Za-z0-9-_.~`,其余按 `%XX` 编码)。
fn url_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(*b as char)
}
_ => out.push_str(&format!("%{:02X}", b)),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn path_segment_whitelist_accepts_only_safe_ids() {
assert!(is_safe_path_segment("854250096668180741"));
assert!(is_safe_path_segment("L-1"));
assert!(is_safe_path_segment("a_b-c"));
assert!(!is_safe_path_segment(""));
assert!(!is_safe_path_segment("a/b"));
assert!(!is_safe_path_segment("a b"));
assert!(!is_safe_path_segment("../etc"));
assert!(!is_safe_path_segment("a?b=1"));
assert!(!is_safe_path_segment(&"x".repeat(65)));
}
#[test]
fn unwrap_data_returns_data_on_200_and_msg_otherwise() {
let ok = unwrap_data(json!({"code":200,"msg":"ok","data":{"list":[]}}), "兜底");
assert_eq!(ok.unwrap(), json!({"list":[]}));
let rejected = unwrap_data(json!({"code":600,"msg":"登录过期"}), "兜底");
assert_eq!(rejected.unwrap_err(), "登录过期");
// 没有 msg ⇒ 回落调用方给的兜底文案
let bare = unwrap_data(json!({"code":600}), "目录查询失败");
assert_eq!(bare.unwrap_err(), "目录查询失败");
}
#[test]
fn internal_headers_carry_the_six_upstream_headers_and_nothing_else() {
let c = TdsClient::new(
Some("http://127.0.0.1:30041".to_string()),
"tok-123".to_string(),
);
let h = c.internal_headers();
assert_eq!(h.get("content-type").unwrap(), "application/json");
assert_eq!(h.get("app-code").unwrap(), "sswflow");
assert_eq!(h.get("jnpf-origin").unwrap(), "pc");
assert_eq!(h.get("vue-version").unwrap(), "3");
assert_eq!(h.get("x-internal-token").unwrap(), "tok-123");
assert_eq!(h.get("x-protocol-version").unwrap(), "1.0");
// 🔴 出向**不得**带 Authorization / Cookie(本地会话令牌不外泄)
assert!(h.get("authorization").is_none());
assert!(h.get("cookie").is_none());
// 头总数正好 6(多一个就说明漏了「只带这 6 个」的约束)
assert_eq!(h.len(), 6, "出向头必须正好 6 个,实际 {:?}", h);
}
#[test]
fn url_is_built_from_base_and_fixed_path() {
let c = TdsClient::new(
Some("http://127.0.0.1:30041/".to_string()),
"tok".to_string(),
);
assert_eq!(
c.url("/api/ssw/tds/Catalog/Internal/Catalog").unwrap(),
"http://127.0.0.1:30041/api/ssw/tds/Catalog/Internal/Catalog"
);
// 未配地址 ⇒ NOOP
let noop = TdsClient::new(None, "tok".to_string());
assert!(noop.is_noop());
assert_eq!(noop.url("/api/ssw/tds/x").unwrap_err(), NOOP_MESSAGE);
}
}