ath-sdk-python 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: ath-sdk-python
3
+ Version: 0.1.0
4
+ Summary: ATH 1.0 智能体可信握手客户端 SDK(Agent Trust Handshake)——纯标准库,零第三方依赖
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/tanbopiao/ath-sdk-python
7
+ Project-URL: Conformance, https://github.com/tanbopiao/ath-conformance-suite
8
+ Keywords: ath,agent,handshake,authentication,security,a2a
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: langchain
22
+ Requires-Dist: langchain-core>=0.1; extra == "langchain"
23
+ Provides-Extra: mcp
24
+ Requires-Dist: mcp<2,>=1.0; extra == "mcp"
25
+ Dynamic: license-file
26
+
27
+ <!-- mcp-name: io.github.tanbopiao/athsdk -->
28
+ # ATH SDK(Python)—— 智能体可信握手客户端
29
+
30
+ 对接 [ATH 1.0](https://www.caict.ac.cn)(智能体可信握手协议,Agent Trust Handshake Protocol,schema 0.1)网关的轻量客户端 SDK。
31
+
32
+ **纯 Python 标准库,零第三方依赖,Python 3.8+,核心就一个文件**——不想装包的话,把 [`ath_sdk/client.py`](ath_sdk/client.py) 直接拷进你的项目也能用。
33
+
34
+ ## 为什么需要它
35
+
36
+ 智能体之间、智能体与服务之间通信前,先「验明身份、讲清权限、再放行」——这就是 ATH 九步可信握手:
37
+
38
+ ```
39
+ 发现 → 注册 → 握手互验 → 授权请求 → 三方权限交集确认 → 令牌 → 受保护访问 → 吊销
40
+ ```
41
+
42
+ 三方权限交集(Agent 请求 ∩ 用户同意 ∩ 服务策略)保证:客户端要得再多,用户没同意、服务方不允许的权限都拿不到。
43
+
44
+ ## 安装
45
+
46
+ ```bash
47
+ pip install ath-sdk-python # 从 PyPI 安装
48
+ # 或直接拷贝单文件:
49
+ cp ath_sdk/client.py your_project/ath_client.py
50
+ ```
51
+
52
+ ## 十分钟上手
53
+
54
+ ```python
55
+ from ath_sdk import ATHConnector
56
+
57
+ agent = ATHConnector("https://gateway.example.com")
58
+
59
+ # 1. 注册(首次):用网关运营方发放的注册凭证
60
+ agent.register("your-account", "<注册凭证>", scopes=["a2a:discover"])
61
+ # 返回 client_id / client_secret / did,请妥善保存(client_secret 仅注册时返回一次)
62
+
63
+ # 2. 完成握手与授权(每次会话)
64
+ agent.discover()
65
+ agent.handshake()
66
+ agent.request_scopes(["a2a:discover"], user_id="user-xxx")
67
+
68
+ # 3. 用户确认:确认凭证由网关运营方就本次请求动态签发(邮箱等带外通道获取)
69
+ agent.confirm(["a2a:discover"], confirm_credential="<确认凭证>")
70
+
71
+ # 4. 拿令牌、访问受保护资源
72
+ agent.get_token()
73
+ agent.protected("/ath/protected/ping")
74
+
75
+ # 5. 用完即吊销
76
+ agent.revoke()
77
+ ```
78
+
79
+ 或一步到位:
80
+
81
+ ```python
82
+ from ath_sdk import connect
83
+
84
+ agent = connect("https://gateway.example.com",
85
+ client_id="...", client_secret="...", client_did="did:ath:...",
86
+ user_id="user-xxx", confirm_credential="<确认凭证>")
87
+ agent.protected("/ath/protected/ping")
88
+ ```
89
+
90
+ 已注册的凭证也可走环境变量:`ATH_CLIENT_ID` / `ATH_CLIENT_SECRET` / `ATH_CLIENT_DID`。
91
+
92
+ ## 命令行自检
93
+
94
+ ```bash
95
+ python -m ath_sdk --gateway https://gateway.example.com --action discover # 只读发现
96
+ python -m ath_sdk --gateway https://gateway.example.com --action handshake # 握手互验(需凭证)
97
+ ```
98
+
99
+ ## API 一览
100
+
101
+ | 方法 | 对应步骤 | 说明 |
102
+ | --- | --- | --- |
103
+ | `discover()` | 0 | 读取 `/.well-known/ath.json`,记录支持的权限 |
104
+ | `register(account, credential, scopes)` | — | 注册身份,取得 client_id / client_secret / DID |
105
+ | `handshake()` | 1–4 | 握手发起 + HMAC-SHA256 身份互验 |
106
+ | `request_scopes(scopes, user_id)` | 5–6 | 授权请求,返回 request_id |
107
+ | `confirm(scopes, confirm_credential)` | 7–8 | 用户确认,返回三方交集后的最终权限 |
108
+ | `get_token()` | 9 | 换取访问令牌(自动缓存,TTL 3600s) |
109
+ | `protected(path)` | — | 带令牌访问受保护端点 |
110
+ | `revoke()` | — | 吊销令牌,立即失效 |
111
+ | `ready(...)` / `connect(...)` | 0–9 | 一步到位 |
112
+
113
+ ## LangChain 智能体集成(可选)
114
+
115
+ 把已就绪的连接器包成 LangChain 工具,让 AI 智能体在可信握手治理下访问受保护资源:
116
+
117
+ ```bash
118
+ pip install "ath-sdk-python[langchain]" # 可选增强;不装也不影响主包零依赖
119
+ ```
120
+
121
+ ```python
122
+ from ath_sdk import connect
123
+ from ath_sdk.langchain_tool import make_ath_tools
124
+
125
+ agent = connect("https://gateway.example.com", client_id=..., client_secret=...)
126
+ tools = make_ath_tools(agent) # 默认仅放行 /ath/protected/ 前缀
127
+ # 传入 create_react_agent 等;或独立调用:tools[0].invoke({"path": "/ath/protected/ping"})
128
+ ```
129
+
130
+ 未安装 langchain-core 时工具以独立模式工作(逻辑完整,只是不能挂进智能体框架);
131
+ `allowed_prefixes` 参数可收窄智能体可访问的端点范围,防止越权。完整示例见 `examples/langchain_agent.py`。
132
+
133
+ ## MCP 服务(可选)
134
+
135
+ 把 ATH 能力以标准 MCP 服务对外提供,一份服务覆盖所有支持 MCP 的客户端与平台
136
+ (DSH、华为九问、Dify、Coze、Claude Desktop、Cursor、阿里百炼、百度千帆等):
137
+
138
+ ```bash
139
+ pip install "ath-sdk-python[mcp]" # 可选增强;不装也不影响主包零依赖
140
+
141
+ # stdio(桌面客户端 / DSH / 九问本地拉起)
142
+ ATH_GATEWAY=https://gateway.example.com \
143
+ ATH_CLIENT_ID=... ATH_CLIENT_SECRET=... ATH_CLIENT_DID=... \
144
+ python -m ath_sdk.mcp_server
145
+
146
+ # streamable-http(远程平台:百炼 / 千帆工作流 / Dify 等)
147
+ python -m ath_sdk.mcp_server --transport streamable-http --port 9131
148
+ ```
149
+
150
+ 四个工具:`ath_handshake`(九步到令牌一步就绪)、`ath_request`(带令牌访问受保护端点,
151
+ 默认仅放行 `/ath/protected/` 前缀)、`ath_verify`(令牌校验)、`ath_status`(配置与令牌状态,密钥零回显)。
152
+
153
+ 配置走环境变量:`ATH_GATEWAY`、`ATH_CLIENT_ID/SECRET/DID`、`ATH_USER_ID`、
154
+ `ATH_USER_CONFIRM_SECRET`(设置后由服务就每次授权请求现算确认证明)、
155
+ `ATH_MCP_ALLOWED_PREFIXES`(路径白名单,逗号分隔)。
156
+
157
+ ### 集成矩阵
158
+
159
+ | 接入面 | 方式 | 状态 |
160
+ | --- | --- | --- |
161
+ | LangChain / LangGraph | `athsdk[langchain]` 工具集成 | ✅ 已验证(真实网关端到端) |
162
+ | DeepSeek Harness(DSH) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(dsh-mcp-client 桥接实测 9/9,见 [docs/dsh-integration.md](docs/dsh-integration.md)) |
163
+ | 九问(openJiuwen / JiuwenSwarm) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(openjiuwen StdioClient 实测 8/8,见 [docs/jiuwen-integration.md](docs/jiuwen-integration.md)) |
164
+ | MCP 客户端与平台(Dify / Coze / Claude Desktop / Cursor / 百炼 / 千帆等) | `athsdk[mcp]` MCP 服务(stdio + streamable-http) | ✅ 已验证(本地网关端到端 8/8;配置样例见 [docs/clients-platforms.md](docs/clients-platforms.md)) |
165
+ | LlamaIndex / AutoGen / OpenAI Agents SDK / CrewAI | 各框架 MCP 客户端接入本服务 | 按需薄适配 |
166
+
167
+ ## 安全约定
168
+
169
+ - **凭证外置**:`client_secret` 只在注册响应中返回一次,SDK 不落盘、不打印;建议用环境变量传入。
170
+ - **确认凭证动态签发**:每次授权请求由网关运营方就 `request_id + user_id` 现算现发,无法预置或重放——这是三方权限交集设计的一部分。
171
+ - **最小权限**:只请求业务需要的 scope;越权项会被网关三方交集拦截。
172
+
173
+ ## 配套工具
174
+
175
+ - 一致性测试套件:[ath-conformance-suite](https://github.com/tanbopiao/ath-conformance-suite) —— 对任意 ATH 1.0 网关做端到端一致性验证(13 项检查,可接 CI)。
176
+ - 参考网关实现:[agent-community-gateway](https://github.com/tanbopiao/agent-community-gateway) —— ATH 1.0 网关的产品与评估文档集,含网关参考实现、演示接入指南与实测指标,本 SDK 的对接目标即此协议。
177
+
178
+ ## 声明
179
+
180
+ 本 SDK 是「对齐信通院 ATH 1.0 规范的实践者」实现的客户端库,非中国信通院官方组件;对接官方评估请以信通院发布为准。
181
+
182
+ ## License
183
+
184
+ Apache-2.0
@@ -0,0 +1,158 @@
1
+ <!-- mcp-name: io.github.tanbopiao/athsdk -->
2
+ # ATH SDK(Python)—— 智能体可信握手客户端
3
+
4
+ 对接 [ATH 1.0](https://www.caict.ac.cn)(智能体可信握手协议,Agent Trust Handshake Protocol,schema 0.1)网关的轻量客户端 SDK。
5
+
6
+ **纯 Python 标准库,零第三方依赖,Python 3.8+,核心就一个文件**——不想装包的话,把 [`ath_sdk/client.py`](ath_sdk/client.py) 直接拷进你的项目也能用。
7
+
8
+ ## 为什么需要它
9
+
10
+ 智能体之间、智能体与服务之间通信前,先「验明身份、讲清权限、再放行」——这就是 ATH 九步可信握手:
11
+
12
+ ```
13
+ 发现 → 注册 → 握手互验 → 授权请求 → 三方权限交集确认 → 令牌 → 受保护访问 → 吊销
14
+ ```
15
+
16
+ 三方权限交集(Agent 请求 ∩ 用户同意 ∩ 服务策略)保证:客户端要得再多,用户没同意、服务方不允许的权限都拿不到。
17
+
18
+ ## 安装
19
+
20
+ ```bash
21
+ pip install ath-sdk-python # 从 PyPI 安装
22
+ # 或直接拷贝单文件:
23
+ cp ath_sdk/client.py your_project/ath_client.py
24
+ ```
25
+
26
+ ## 十分钟上手
27
+
28
+ ```python
29
+ from ath_sdk import ATHConnector
30
+
31
+ agent = ATHConnector("https://gateway.example.com")
32
+
33
+ # 1. 注册(首次):用网关运营方发放的注册凭证
34
+ agent.register("your-account", "<注册凭证>", scopes=["a2a:discover"])
35
+ # 返回 client_id / client_secret / did,请妥善保存(client_secret 仅注册时返回一次)
36
+
37
+ # 2. 完成握手与授权(每次会话)
38
+ agent.discover()
39
+ agent.handshake()
40
+ agent.request_scopes(["a2a:discover"], user_id="user-xxx")
41
+
42
+ # 3. 用户确认:确认凭证由网关运营方就本次请求动态签发(邮箱等带外通道获取)
43
+ agent.confirm(["a2a:discover"], confirm_credential="<确认凭证>")
44
+
45
+ # 4. 拿令牌、访问受保护资源
46
+ agent.get_token()
47
+ agent.protected("/ath/protected/ping")
48
+
49
+ # 5. 用完即吊销
50
+ agent.revoke()
51
+ ```
52
+
53
+ 或一步到位:
54
+
55
+ ```python
56
+ from ath_sdk import connect
57
+
58
+ agent = connect("https://gateway.example.com",
59
+ client_id="...", client_secret="...", client_did="did:ath:...",
60
+ user_id="user-xxx", confirm_credential="<确认凭证>")
61
+ agent.protected("/ath/protected/ping")
62
+ ```
63
+
64
+ 已注册的凭证也可走环境变量:`ATH_CLIENT_ID` / `ATH_CLIENT_SECRET` / `ATH_CLIENT_DID`。
65
+
66
+ ## 命令行自检
67
+
68
+ ```bash
69
+ python -m ath_sdk --gateway https://gateway.example.com --action discover # 只读发现
70
+ python -m ath_sdk --gateway https://gateway.example.com --action handshake # 握手互验(需凭证)
71
+ ```
72
+
73
+ ## API 一览
74
+
75
+ | 方法 | 对应步骤 | 说明 |
76
+ | --- | --- | --- |
77
+ | `discover()` | 0 | 读取 `/.well-known/ath.json`,记录支持的权限 |
78
+ | `register(account, credential, scopes)` | — | 注册身份,取得 client_id / client_secret / DID |
79
+ | `handshake()` | 1–4 | 握手发起 + HMAC-SHA256 身份互验 |
80
+ | `request_scopes(scopes, user_id)` | 5–6 | 授权请求,返回 request_id |
81
+ | `confirm(scopes, confirm_credential)` | 7–8 | 用户确认,返回三方交集后的最终权限 |
82
+ | `get_token()` | 9 | 换取访问令牌(自动缓存,TTL 3600s) |
83
+ | `protected(path)` | — | 带令牌访问受保护端点 |
84
+ | `revoke()` | — | 吊销令牌,立即失效 |
85
+ | `ready(...)` / `connect(...)` | 0–9 | 一步到位 |
86
+
87
+ ## LangChain 智能体集成(可选)
88
+
89
+ 把已就绪的连接器包成 LangChain 工具,让 AI 智能体在可信握手治理下访问受保护资源:
90
+
91
+ ```bash
92
+ pip install "ath-sdk-python[langchain]" # 可选增强;不装也不影响主包零依赖
93
+ ```
94
+
95
+ ```python
96
+ from ath_sdk import connect
97
+ from ath_sdk.langchain_tool import make_ath_tools
98
+
99
+ agent = connect("https://gateway.example.com", client_id=..., client_secret=...)
100
+ tools = make_ath_tools(agent) # 默认仅放行 /ath/protected/ 前缀
101
+ # 传入 create_react_agent 等;或独立调用:tools[0].invoke({"path": "/ath/protected/ping"})
102
+ ```
103
+
104
+ 未安装 langchain-core 时工具以独立模式工作(逻辑完整,只是不能挂进智能体框架);
105
+ `allowed_prefixes` 参数可收窄智能体可访问的端点范围,防止越权。完整示例见 `examples/langchain_agent.py`。
106
+
107
+ ## MCP 服务(可选)
108
+
109
+ 把 ATH 能力以标准 MCP 服务对外提供,一份服务覆盖所有支持 MCP 的客户端与平台
110
+ (DSH、华为九问、Dify、Coze、Claude Desktop、Cursor、阿里百炼、百度千帆等):
111
+
112
+ ```bash
113
+ pip install "ath-sdk-python[mcp]" # 可选增强;不装也不影响主包零依赖
114
+
115
+ # stdio(桌面客户端 / DSH / 九问本地拉起)
116
+ ATH_GATEWAY=https://gateway.example.com \
117
+ ATH_CLIENT_ID=... ATH_CLIENT_SECRET=... ATH_CLIENT_DID=... \
118
+ python -m ath_sdk.mcp_server
119
+
120
+ # streamable-http(远程平台:百炼 / 千帆工作流 / Dify 等)
121
+ python -m ath_sdk.mcp_server --transport streamable-http --port 9131
122
+ ```
123
+
124
+ 四个工具:`ath_handshake`(九步到令牌一步就绪)、`ath_request`(带令牌访问受保护端点,
125
+ 默认仅放行 `/ath/protected/` 前缀)、`ath_verify`(令牌校验)、`ath_status`(配置与令牌状态,密钥零回显)。
126
+
127
+ 配置走环境变量:`ATH_GATEWAY`、`ATH_CLIENT_ID/SECRET/DID`、`ATH_USER_ID`、
128
+ `ATH_USER_CONFIRM_SECRET`(设置后由服务就每次授权请求现算确认证明)、
129
+ `ATH_MCP_ALLOWED_PREFIXES`(路径白名单,逗号分隔)。
130
+
131
+ ### 集成矩阵
132
+
133
+ | 接入面 | 方式 | 状态 |
134
+ | --- | --- | --- |
135
+ | LangChain / LangGraph | `athsdk[langchain]` 工具集成 | ✅ 已验证(真实网关端到端) |
136
+ | DeepSeek Harness(DSH) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(dsh-mcp-client 桥接实测 9/9,见 [docs/dsh-integration.md](docs/dsh-integration.md)) |
137
+ | 九问(openJiuwen / JiuwenSwarm) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(openjiuwen StdioClient 实测 8/8,见 [docs/jiuwen-integration.md](docs/jiuwen-integration.md)) |
138
+ | MCP 客户端与平台(Dify / Coze / Claude Desktop / Cursor / 百炼 / 千帆等) | `athsdk[mcp]` MCP 服务(stdio + streamable-http) | ✅ 已验证(本地网关端到端 8/8;配置样例见 [docs/clients-platforms.md](docs/clients-platforms.md)) |
139
+ | LlamaIndex / AutoGen / OpenAI Agents SDK / CrewAI | 各框架 MCP 客户端接入本服务 | 按需薄适配 |
140
+
141
+ ## 安全约定
142
+
143
+ - **凭证外置**:`client_secret` 只在注册响应中返回一次,SDK 不落盘、不打印;建议用环境变量传入。
144
+ - **确认凭证动态签发**:每次授权请求由网关运营方就 `request_id + user_id` 现算现发,无法预置或重放——这是三方权限交集设计的一部分。
145
+ - **最小权限**:只请求业务需要的 scope;越权项会被网关三方交集拦截。
146
+
147
+ ## 配套工具
148
+
149
+ - 一致性测试套件:[ath-conformance-suite](https://github.com/tanbopiao/ath-conformance-suite) —— 对任意 ATH 1.0 网关做端到端一致性验证(13 项检查,可接 CI)。
150
+ - 参考网关实现:[agent-community-gateway](https://github.com/tanbopiao/agent-community-gateway) —— ATH 1.0 网关的产品与评估文档集,含网关参考实现、演示接入指南与实测指标,本 SDK 的对接目标即此协议。
151
+
152
+ ## 声明
153
+
154
+ 本 SDK 是「对齐信通院 ATH 1.0 规范的实践者」实现的客户端库,非中国信通院官方组件;对接官方评估请以信通院发布为准。
155
+
156
+ ## License
157
+
158
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ # -*- coding: utf-8 -*-
2
+ """ATH SDK —— 智能体可信握手客户端(ATH 1.0)"""
3
+ from .client import ATHConnector, ATHError, connect, __version__
4
+
5
+ __all__ = ["ATHConnector", "ATHError", "connect", "__version__"]
6
+
7
+
8
+ def __getattr__(name):
9
+ # LangChain 集成为可选增强:仅在显式导入时才要求已安装 langchain-core
10
+ if name in ("ATHAgentTool", "make_ath_tools"):
11
+ from . import langchain_tool as _lt
12
+ return getattr(_lt, name)
13
+ raise AttributeError("module %r has no attribute %r" % (__name__, name))
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """命令行自检:python -m ath_sdk --gateway https://api.example.com"""
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from .client import ATHConnector, ATHError
10
+
11
+
12
+ def main():
13
+ ap = argparse.ArgumentParser(description="ATH 1.0 客户端自检")
14
+ ap.add_argument("--gateway", default=os.environ.get("ATH_GATEWAY", ""),
15
+ help="ATH 网关地址(或环境变量 ATH_GATEWAY)")
16
+ ap.add_argument("--action", choices=["discover", "handshake"], default="discover",
17
+ help="discover=只读发现文档;handshake=发现+握手互验(需凭证)")
18
+ args = ap.parse_args()
19
+ if not args.gateway:
20
+ sys.exit("请通过 --gateway 或环境变量 ATH_GATEWAY 指定网关地址")
21
+ try:
22
+ c = ATHConnector(args.gateway)
23
+ doc = c.discover()
24
+ if args.action == "discover":
25
+ print(json.dumps(doc, ensure_ascii=False, indent=2))
26
+ return
27
+ c.handshake()
28
+ print("握手互验通过")
29
+ except ATHError as e:
30
+ sys.exit("自检失败: %s (status=%s)" % (e, e.status))
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ATH SDK —— 智能体可信握手客户端(ATH 1.0,纯标准库,零第三方依赖)
4
+
5
+ 一个文件即可拷走使用:本模块不依赖包内其他文件。
6
+ 九步可信握手:发现 → 注册 → 握手互验 → 授权请求 → 三方交集确认 → 令牌 → 受保护访问 → 吊销。
7
+
8
+ 快速上手:
9
+ from ath_sdk import ATHConnector, connect
10
+
11
+ agent = connect(
12
+ gateway="https://api.example.com", # ATH 网关地址
13
+ client_id="...", client_secret="...", client_did="did:ath:...",
14
+ user_id="user-xxx",
15
+ confirm_credential="...", # 网关运营方就本次请求签发的确认凭证
16
+ )
17
+ agent.protected("/ath/protected/ping") # 带令牌访问受保护资源
18
+
19
+ 未注册的智能体先用注册凭证注册(见 register());
20
+ 确认凭证经网关运营方的带外通道(如邮箱)就每次授权请求动态获取。
21
+ """
22
+ import hashlib
23
+ import hmac
24
+ import json
25
+ import os
26
+ import time
27
+ import urllib.error
28
+ import urllib.request
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ DEFAULT_TIMEOUT = 10
33
+
34
+
35
+ class ATHError(RuntimeError):
36
+ """ATH 流程错误,携带 HTTP 状态码与响应体,便于定位协议偏离点。"""
37
+
38
+ def __init__(self, message, status=None, response=None):
39
+ super().__init__(message)
40
+ self.status = status
41
+ self.response = response
42
+
43
+
44
+ class ATHConnector:
45
+ """ATH 1.0 客户端。一个实例对应一个网关接入身份与会话状态。"""
46
+
47
+ def __init__(self, gateway, client_id=None, client_secret=None,
48
+ client_did=None, timeout=DEFAULT_TIMEOUT):
49
+ if not gateway:
50
+ raise ATHError("缺少网关地址:请传入 gateway 或设置环境变量 ATH_GATEWAY")
51
+ self.gateway = gateway.rstrip("/")
52
+ self.client_id = client_id or os.environ.get("ATH_CLIENT_ID", "")
53
+ self.client_secret = client_secret or os.environ.get("ATH_CLIENT_SECRET", "")
54
+ self.client_did = client_did or os.environ.get("ATH_CLIENT_DID", "")
55
+ self.timeout = timeout
56
+ self.hs_id = None
57
+ self.scopes_supported = []
58
+ self.request_id = None
59
+ self.final_scopes = []
60
+ self._token = None
61
+ self._token_exp = 0.0
62
+
63
+ # ---- 底层 HTTP ----
64
+ def _request(self, method, path, body=None, headers=None):
65
+ req = urllib.request.Request(
66
+ self.gateway + path,
67
+ json.dumps(body).encode() if body is not None else None,
68
+ headers=headers or {}, method=method)
69
+ try:
70
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
71
+ return r.status, json.loads(r.read().decode("utf-8"))
72
+ except urllib.error.HTTPError as e:
73
+ try:
74
+ return e.code, json.loads(e.read().decode("utf-8"))
75
+ except Exception:
76
+ return e.code, {}
77
+ except urllib.error.URLError as e:
78
+ raise ATHError("网络错误: %s" % e.reason)
79
+
80
+ def _post(self, path, body=None, headers=None):
81
+ return self._request("POST", path, body, headers)
82
+
83
+ def _get(self, path, headers=None):
84
+ return self._request("GET", path, None, headers)
85
+
86
+ # ---- 步骤 0:发现 ----
87
+ def discover(self):
88
+ """读取网关发现文档(/.well-known/ath.json),记录支持的权限。"""
89
+ status, doc = self._get("/.well-known/ath.json")
90
+ if status != 200:
91
+ raise ATHError("发现文档不可达", status, doc)
92
+ self.scopes_supported = [s for p in doc.get("supported_providers", [])
93
+ for s in p.get("scopes_supported", [])]
94
+ return doc
95
+
96
+ # ---- 注册(需网关运营方发放的注册凭证)----
97
+ def register(self, account, registration_credential, scopes=None):
98
+ """用注册凭证注册,取得 client_id / client_secret / DID。
99
+
100
+ 注册凭证 = HMAC-SHA256(注册密钥, "register:" + 账号名),只对固定账号名有效,
101
+ 由网关运营方发放(演示凭证或邮箱申请)。
102
+ """
103
+ status, resp = self._post("/ath/agents/register", {
104
+ "name": account,
105
+ "registration_proof": registration_credential,
106
+ "scopes": scopes or ["a2a:discover"],
107
+ })
108
+ if status != 200:
109
+ raise ATHError("注册失败", status, resp)
110
+ self.client_id = resp.get("client_id", self.client_id)
111
+ self.client_secret = resp.get("client_secret", self.client_secret)
112
+ self.client_did = resp.get("did", self.client_did)
113
+ return resp
114
+
115
+ # ---- 步骤 1-4:握手与身份互验 ----
116
+ def handshake(self):
117
+ """发起握手并完成身份证明(proof = HMAC-SHA256(client_secret, 服务端 nonce))。"""
118
+ if not (self.client_id and self.client_secret and self.client_did):
119
+ raise ATHError("缺少客户端凭证,请先 register() 或配置 ATH_CLIENT_* 环境变量")
120
+ status, hr = self._post("/ath/handshake/init",
121
+ {"client_did": self.client_did,
122
+ "nonce": os.urandom(16).hex()})
123
+ if status != 200 or hr.get("type") != "handshake_response":
124
+ raise ATHError("握手发起失败", status, hr)
125
+ self.hs_id = hr["hs_id"]
126
+ proof = hmac.new(self.client_secret.encode(), hr["nonce"].encode(),
127
+ hashlib.sha256).hexdigest()
128
+ status, ir = self._post("/ath/handshake/verify",
129
+ {"hs_id": self.hs_id, "client_id": self.client_id,
130
+ "proof": proof})
131
+ if status != 200 or not ir.get("success"):
132
+ raise ATHError("身份验证未通过", status, ir)
133
+ return ir
134
+
135
+ # ---- 步骤 5-6:授权请求 ----
136
+ def request_scopes(self, scopes, user_id):
137
+ """请求权限,返回 request_id。越权项由网关三方交集拦截。"""
138
+ if not self.hs_id:
139
+ raise ATHError("请先完成 handshake()")
140
+ status, ar = self._post("/ath/auth/request",
141
+ {"hs_id": self.hs_id, "client_id": self.client_id,
142
+ "user_id": user_id, "scopes": list(scopes)})
143
+ if status != 200:
144
+ raise ATHError("授权请求失败", status, ar)
145
+ self.request_id = ar["request_id"]
146
+ return self.request_id
147
+
148
+ # ---- 步骤 7-8:用户确认(三方权限交集)----
149
+ def confirm(self, approved_scopes, confirm_credential=None):
150
+ """用户侧确认,返回三方交集后的最终权限。
151
+
152
+ confirm_credential 为网关运营方就本次请求动态签发的确认凭证
153
+ (HMAC-SHA256(确认密钥, "confirm:" + request_id + ":" + user_id)),
154
+ 经邮箱等带外通道获取;网关未启用确认证明校验时可省略。
155
+ """
156
+ if not self.request_id:
157
+ raise ATHError("请先 request_scopes()")
158
+ body = {"request_id": self.request_id, "approved": True,
159
+ "scopes": list(approved_scopes)}
160
+ if confirm_credential:
161
+ body["confirmation_proof"] = confirm_credential
162
+ status, pa = self._post("/ath/auth/confirm", body)
163
+ if status != 200:
164
+ raise ATHError("授权确认失败", status, pa)
165
+ self.final_scopes = pa.get("scope_intersection", {}).get("final", [])
166
+ return self.final_scopes
167
+
168
+ # ---- 步骤 9:令牌 ----
169
+ def get_token(self):
170
+ """凭 request_id 换取访问令牌(默认 TTL 3600s,自动缓存)。"""
171
+ if self._token and time.time() < self._token_exp - 30:
172
+ return self._token
173
+ if not self.request_id:
174
+ raise ATHError("请先完成授权确认")
175
+ # P7 对齐: 令牌颁发绑定客户端身份——client_id + 对 request_id 的
176
+ # client_secret 证明, 防止凭泄露的 request_id 截取令牌
177
+ client_proof = hmac.new(self.client_secret.encode(),
178
+ ("token:" + self.request_id).encode(),
179
+ hashlib.sha256).hexdigest()
180
+ status, tr = self._post("/ath/token", {"request_id": self.request_id,
181
+ "client_id": self.client_id,
182
+ "client_proof": client_proof})
183
+ if status != 200 or not tr.get("access_token", "").startswith("ath_"):
184
+ raise ATHError("令牌颁发失败", status, tr)
185
+ self._token = tr["access_token"]
186
+ self._token_exp = time.time() + int(tr.get("expires_in", 3600))
187
+ return self._token
188
+
189
+ # ---- 受保护访问与吊销 ----
190
+ def protected(self, path):
191
+ """带令牌访问受保护端点(如 /ath/protected/ping)。"""
192
+ token = self.get_token()
193
+ status, resp = self._get(path, {"Authorization": "Bearer " + token})
194
+ if status != 200:
195
+ raise ATHError("受保护访问失败", status, resp)
196
+ return resp
197
+
198
+ def revoke(self):
199
+ """吊销当前令牌,吊销后立即失效。"""
200
+ if not self._token:
201
+ return
202
+ self._post("/ath/token/revoke", {},
203
+ {"Authorization": "Bearer " + self._token})
204
+ self._token = None
205
+ self._token_exp = 0.0
206
+
207
+ # ---- 一步到位 ----
208
+ def ready(self, scopes=("a2a:discover",), user_id="user-default",
209
+ confirm_credential=None):
210
+ """发现 → 握手 → 授权 → 确认 → 令牌,返回自身(已就绪)。"""
211
+ self.discover()
212
+ self.handshake()
213
+ self.request_scopes(scopes, user_id)
214
+ self.confirm(scopes, confirm_credential=confirm_credential)
215
+ self.get_token()
216
+ return self
217
+
218
+
219
+ def connect(gateway, scopes=("a2a:discover",), user_id="user-default",
220
+ client_id=None, client_secret=None, client_did=None,
221
+ confirm_credential=None, timeout=DEFAULT_TIMEOUT):
222
+ """一步到位:创建客户端并完成到令牌为止的全流程,返回已就绪的 ATHConnector。"""
223
+ c = ATHConnector(gateway, client_id=client_id, client_secret=client_secret,
224
+ client_did=client_did, timeout=timeout)
225
+ return c.ready(scopes=scopes, user_id=user_id,
226
+ confirm_credential=confirm_credential)