@agentunion/fastaun 0.2.13

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.
Files changed (69) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +78 -0
  3. package/dist/auth.d.ts +287 -0
  4. package/dist/auth.js +1668 -0
  5. package/dist/auth.js.map +1 -0
  6. package/dist/client.d.ts +359 -0
  7. package/dist/client.js +3918 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/config.d.ts +43 -0
  10. package/dist/config.js +119 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/crypto.d.ts +41 -0
  13. package/dist/crypto.js +85 -0
  14. package/dist/crypto.js.map +1 -0
  15. package/dist/discovery.d.ts +22 -0
  16. package/dist/discovery.js +110 -0
  17. package/dist/discovery.js.map +1 -0
  18. package/dist/e2ee-group.d.ts +192 -0
  19. package/dist/e2ee-group.js +1134 -0
  20. package/dist/e2ee-group.js.map +1 -0
  21. package/dist/e2ee.d.ts +120 -0
  22. package/dist/e2ee.js +890 -0
  23. package/dist/e2ee.js.map +1 -0
  24. package/dist/errors.d.ts +115 -0
  25. package/dist/errors.js +253 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/events.d.ts +39 -0
  28. package/dist/events.js +82 -0
  29. package/dist/events.js.map +1 -0
  30. package/dist/index.d.ts +23 -0
  31. package/dist/index.js +32 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/keystore/aid-db.d.ts +79 -0
  34. package/dist/keystore/aid-db.js +621 -0
  35. package/dist/keystore/aid-db.js.map +1 -0
  36. package/dist/keystore/file.d.ts +82 -0
  37. package/dist/keystore/file.js +395 -0
  38. package/dist/keystore/file.js.map +1 -0
  39. package/dist/keystore/index.d.ts +88 -0
  40. package/dist/keystore/index.js +7 -0
  41. package/dist/keystore/index.js.map +1 -0
  42. package/dist/keystore/sqlite-backup.d.ts +40 -0
  43. package/dist/keystore/sqlite-backup.js +379 -0
  44. package/dist/keystore/sqlite-backup.js.map +1 -0
  45. package/dist/logger.d.ts +6 -0
  46. package/dist/logger.js +53 -0
  47. package/dist/logger.js.map +1 -0
  48. package/dist/namespaces/auth.d.ts +49 -0
  49. package/dist/namespaces/auth.js +248 -0
  50. package/dist/namespaces/auth.js.map +1 -0
  51. package/dist/namespaces/custody.d.ts +47 -0
  52. package/dist/namespaces/custody.js +231 -0
  53. package/dist/namespaces/custody.js.map +1 -0
  54. package/dist/secret-store/file-store.d.ts +25 -0
  55. package/dist/secret-store/file-store.js +124 -0
  56. package/dist/secret-store/file-store.js.map +1 -0
  57. package/dist/secret-store/index.d.ts +28 -0
  58. package/dist/secret-store/index.js +19 -0
  59. package/dist/secret-store/index.js.map +1 -0
  60. package/dist/seq-tracker.d.ts +29 -0
  61. package/dist/seq-tracker.js +221 -0
  62. package/dist/seq-tracker.js.map +1 -0
  63. package/dist/transport.d.ts +60 -0
  64. package/dist/transport.js +355 -0
  65. package/dist/transport.js.map +1 -0
  66. package/dist/types.d.ts +170 -0
  67. package/dist/types.js +12 -0
  68. package/dist/types.js.map +1 -0
  69. package/package.json +42 -0
package/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024-2026 Agent Union Network
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # AUN Protocol — Node.js SDK
2
+
3
+ ## Overview
4
+
5
+ AUN (Agent Union Network) defines a standard interface for secure communication between Agents — based on WebSocket + JSON-RPC 2.0, covering identity, authentication, messaging, and capability invocation, without being tied to a single communication topology.
6
+
7
+ ---
8
+
9
+ ## Core Concepts
10
+
11
+ **Problem**: AI Agents are trapped in their respective platforms, unable to communicate across domains and invoke each other's capabilities.
12
+
13
+ **AUN's Answer**:
14
+
15
+ - **AID Identity**: Globally unique identifier in `{name}.{issuer}` format (e.g., `alice.agentid.pub`), based on X.509 certificate chain
16
+ - **Three Connection Modes**: Gateway (standard access), Peer (point-to-point direct), Relay (relay forwarding), with consistent application-layer API
17
+ - **Capability Invocation**: Native `tool_call` / `tool_result` message types, allowing cross-domain discovery and invocation of Agent capabilities
18
+
19
+ ```
20
+ ┌─ Gateway ──→ Standard access (browser/mobile/server)
21
+ Agent A ← WSS → ─┤─ Peer ─────→ Point-to-point direct (same network/low latency)
22
+ └─ Relay ────→ Relay forwarding (NAT traversal/lightweight deployment)
23
+ ```
24
+
25
+ **This SDK** is the Node.js/TypeScript client implementation of the AUN protocol. Install with `npm install @agentunion/fastaun`.
26
+
27
+ ---
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ npm install @agentunion/fastaun
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ```typescript
38
+ import { AunClient } from '@agentunion/fastaun';
39
+
40
+ // Create client
41
+ const client = new AunClient({
42
+ aid: 'alice.agentid.pub',
43
+ gatewayUrl: 'wss://gateway.agentid.pub',
44
+ dataDir: './data'
45
+ });
46
+
47
+ // Connect
48
+ await client.connect();
49
+
50
+ // Send message
51
+ await client.sendMessage({
52
+ to: 'bob.agentid.pub',
53
+ content: 'Hello from Alice!'
54
+ });
55
+
56
+ // Receive messages
57
+ client.on('message', (msg) => {
58
+ console.log('Received:', msg);
59
+ });
60
+ ```
61
+
62
+ ## Features
63
+
64
+ - ✅ AID-based identity authentication
65
+ - ✅ End-to-end encrypted messaging
66
+ - ✅ Group chat with E2EE
67
+ - ✅ Cross-domain communication
68
+ - ✅ Tool call/result support
69
+ - ✅ Storage service integration
70
+ - ✅ TypeScript support with full type definitions
71
+
72
+ ## Documentation
73
+
74
+ For detailed documentation, visit: https://github.com/agentunion/aun-sdk-core
75
+
76
+ ## License
77
+
78
+ Apache-2.0
package/dist/auth.d.ts ADDED
@@ -0,0 +1,287 @@
1
+ /**
2
+ * AuthFlow — 认证流程管理
3
+ *
4
+ * Node.js 完整实现,与 Python SDK 的 AuthFlow 接口对齐。
5
+ * 功能:
6
+ * - AID 创建(在 Gateway 注册身份)
7
+ * - 两阶段挑战-应答认证(login1 + login2)
8
+ * - 证书链验证(chain + CRL + OCSP)
9
+ * - Token 刷新
10
+ * - 会话初始化
11
+ * - 证书恢复与自动续期
12
+ */
13
+ import WebSocket from 'ws';
14
+ import type { CryptoProvider } from './crypto.js';
15
+ import type { KeyStore } from './keystore/index.js';
16
+ import type { RPCTransport } from './transport.js';
17
+ import { type IdentityRecord, type JsonObject, type RpcMessage } from './types.js';
18
+ /** 默认连接工厂:创建临时 WebSocket 连接 */
19
+ type ConnectionFactory = (url: string) => Promise<WebSocket>;
20
+ export declare class AuthFlow {
21
+ private static readonly _INSTANCE_STATE_FIELDS;
22
+ private _keystore;
23
+ private _crypto;
24
+ private _aid;
25
+ private _deviceId;
26
+ private _slotId;
27
+ private _verifySsl;
28
+ private _connectionFactory;
29
+ private _rootCaPath;
30
+ private _chainCacheTtl;
31
+ private _rootCerts;
32
+ private _gatewayChainCache;
33
+ private _gatewayCrlCache;
34
+ private _gatewayOcspCache;
35
+ private _chainVerifiedCache;
36
+ private _gatewayCaVerified;
37
+ constructor(opts: {
38
+ keystore: KeyStore;
39
+ crypto: CryptoProvider;
40
+ aid?: string | null;
41
+ deviceId?: string;
42
+ slotId?: string;
43
+ connectionFactory?: ConnectionFactory;
44
+ rootCaPath?: string | null;
45
+ chainCacheTtl?: number;
46
+ verifySsl?: boolean;
47
+ });
48
+ /** 加载身份信息(密钥对 + 证书 + 元数据) */
49
+ loadIdentity(aid?: string): IdentityRecord;
50
+ /** 加载身份信息,不存在时返回 null */
51
+ loadIdentityOrNone(aid?: string): IdentityRecord | null;
52
+ /** 与 Browser/JS SDK 对齐的别名:加载身份信息,不存在时返回 null */
53
+ loadIdentityOrNull(aid?: string): IdentityRecord | null;
54
+ /** 获取 access_token 的过期时间戳(秒) */
55
+ getAccessTokenExpiry(identity: IdentityRecord): number | null;
56
+ setInstanceContext(opts: {
57
+ deviceId: string;
58
+ slotId?: string;
59
+ }): void;
60
+ /**
61
+ * 创建 AID 并注册到 Gateway。
62
+ * 如果 AID 已在服务端注册但本地证书丢失,尝试从 PKI 端点下载恢复。
63
+ */
64
+ createAid(gatewayUrl: string, aid: string): Promise<JsonObject>;
65
+ /**
66
+ * 认证(登录)到 Gateway。
67
+ * 执行两阶段挑战-应答认证,返回 token 信息。
68
+ */
69
+ authenticate(gatewayUrl: string, opts?: {
70
+ aid?: string;
71
+ }): Promise<JsonObject>;
72
+ /**
73
+ * 确保已认证(自动创建 + 登录)。
74
+ * 如果没有本地身份则创建,然后执行登录流程。
75
+ */
76
+ ensureAuthenticated(gatewayUrl: string): Promise<AuthContext>;
77
+ /**
78
+ * 刷新缓存的 token。
79
+ * 使用 refresh_token 获取新的 access_token。
80
+ */
81
+ refreshCachedTokens(gatewayUrl: string, identity: IdentityRecord): Promise<IdentityRecord>;
82
+ /**
83
+ * 使用 token 初始化 WebSocket 会话。
84
+ * 发送 auth.connect RPC 完成会话握手。
85
+ */
86
+ initializeWithToken(transport: RPCTransport, challenge: RpcMessage | null, accessToken: string, opts?: {
87
+ deviceId?: string;
88
+ slotId?: string;
89
+ deliveryMode?: JsonObject | null;
90
+ }): Promise<void>;
91
+ /**
92
+ * 连接会话(自动选择认证策略)。
93
+ * 依次尝试:显式 token → 缓存 token → 刷新 token → 完整重认证。
94
+ */
95
+ connectSession(transport: RPCTransport, challenge: RpcMessage | null, gatewayUrl: string, opts?: {
96
+ accessToken?: string;
97
+ deviceId?: string;
98
+ slotId?: string;
99
+ deliveryMode?: JsonObject | null;
100
+ }): Promise<AuthContext>;
101
+ /**
102
+ * 验证对端证书:时间有效性 + 链验证 + CRL + OCSP + AID 绑定。
103
+ * 用于 E2EE 握手中验证通信对端的身份证书。
104
+ */
105
+ verifyPeerCertificate(gatewayUrl: string, certPem: string, expectedAid: string): Promise<void>;
106
+ /**
107
+ * 通过临时 WebSocket 发送单次 JSON-RPC 请求。
108
+ * 流程:连接 → 接收 challenge → 发送请求 → 接收响应 → 关闭。
109
+ */
110
+ private _shortRpc;
111
+ /** 从 WebSocket 接收一条消息(Promise 封装) */
112
+ private _wsRecv;
113
+ /** 注册 AID 到 Gateway */
114
+ private _createAid;
115
+ /** 两阶段登录 */
116
+ private _login;
117
+ /** 刷新 access_token */
118
+ private _refreshAccessToken;
119
+ /** 会话初始化:发送 auth.connect RPC */
120
+ private _initializeSession;
121
+ /**
122
+ * 验证 Phase 1 响应:
123
+ * 1. 解析 auth_cert
124
+ * 2. 验证证书链 + CRL + OCSP
125
+ * 3. 验证 client_nonce_signature
126
+ */
127
+ private _verifyPhase1Response;
128
+ /**
129
+ * 验证认证证书链。
130
+ * 1. 检查缓存
131
+ * 2. 时间有效性
132
+ * 3. 签名链验证
133
+ * 4. BasicConstraints 检查
134
+ * 5. 根证书自签 + 受信根锚定
135
+ */
136
+ private _verifyAuthCertChain;
137
+ /** 加载 Gateway CA 链(带缓存) */
138
+ private _loadGatewayCaChain;
139
+ /** 从 Gateway PKI 端点获取 CA 链 */
140
+ private _fetchGatewayCaChain;
141
+ /**
142
+ * CRL 吊销检查。
143
+ * 从 Gateway 的 /pki/crl.json 端点获取 CRL,
144
+ * 验证签发者签名,检查证书序列号是否在吊销列表中。
145
+ */
146
+ private _verifyAuthCertRevocation;
147
+ /** 加载 Gateway 吊销列表(带缓存) */
148
+ private _loadGatewayRevokedSerials;
149
+ /**
150
+ * 从 Gateway /pki/crl.json 获取 CRL 并解析。
151
+ *
152
+ * 响应格式: { crl_pem: "...", revoked_serials?: [...] }
153
+ *
154
+ * 注意:完整的 CRL PEM 签名验证需要 ASN.1/DER 解析,
155
+ * Node.js 标准库不直接支持 CRL 解析。
156
+ * 这里使用 JSON 响应中的 revoked_serials 字段作为可信数据源,
157
+ * 并验证 crl_pem 存在性。完整的 CRL 签名验证需要依赖
158
+ * @peculiar/x509 或手动 ASN.1 解析。
159
+ */
160
+ private _fetchGatewayCrl;
161
+ /**
162
+ * 从 CRL PEM 解析吊销序列号。
163
+ * 简化的 ASN.1 DER 解析:提取 TBSCertList 中的 revokedCertificates 序列号。
164
+ *
165
+ * CRL ASN.1 结构(简化):
166
+ * CertificateList ::= SEQUENCE {
167
+ * tbsCertList TBSCertList,
168
+ * signatureAlgorithm AlgorithmIdentifier,
169
+ * signature BIT STRING
170
+ * }
171
+ *
172
+ * TBSCertList ::= SEQUENCE {
173
+ * version INTEGER OPTIONAL,
174
+ * signature AlgorithmIdentifier,
175
+ * issuer Name,
176
+ * thisUpdate Time,
177
+ * nextUpdate Time OPTIONAL,
178
+ * revokedCertificates SEQUENCE OF SEQUENCE { ... } OPTIONAL,
179
+ * ...
180
+ * }
181
+ */
182
+ private _parseCrlRevokedSerials;
183
+ /**
184
+ * OCSP 状态检查。
185
+ * 从 Gateway 的 /pki/ocsp/{serial_hex} 端点获取 OCSP 响应。
186
+ */
187
+ private _verifyAuthCertOcsp;
188
+ /** 加载 Gateway OCSP 状态(带缓存) */
189
+ private _loadGatewayOcspStatus;
190
+ /**
191
+ * 从 Gateway /pki/ocsp/{serial_hex} 获取 OCSP 状态。
192
+ *
193
+ * 响应格式: { status: "good"|"revoked"|"unknown", ocsp_response: "base64..." }
194
+ *
195
+ * 注意:完整的 OCSP DER 响应解析需要 ASN.1 解析。
196
+ * 这里从 JSON 响应中提取 status 字段,并验证 ocsp_response 存在性。
197
+ * 对于 ocsp_response 的签名验证,实现简化的 DER 解析以提取关键字段。
198
+ */
199
+ private _fetchGatewayOcspStatus;
200
+ /**
201
+ * 简化的 OCSP DER 响应解析。
202
+ *
203
+ * OCSPResponse ::= SEQUENCE {
204
+ * responseStatus ENUMERATED { successful(0), ... },
205
+ * responseBytes [0] EXPLICIT SEQUENCE {
206
+ * responseType OID,
207
+ * response OCTET STRING (BasicOCSPResponse DER)
208
+ * } OPTIONAL
209
+ * }
210
+ *
211
+ * BasicOCSPResponse ::= SEQUENCE {
212
+ * tbsResponseData ResponseData,
213
+ * signatureAlgorithm AlgorithmIdentifier,
214
+ * signature BIT STRING,
215
+ * ...
216
+ * }
217
+ *
218
+ * ResponseData ::= SEQUENCE {
219
+ * version [0] EXPLICIT INTEGER DEFAULT v1,
220
+ * responderID ...,
221
+ * producedAt GeneralizedTime,
222
+ * responses SEQUENCE OF SingleResponse,
223
+ * ...
224
+ * }
225
+ *
226
+ * SingleResponse ::= SEQUENCE {
227
+ * certID CertID,
228
+ * certStatus CHOICE { good [0], revoked [1], unknown [2] },
229
+ * thisUpdate GeneralizedTime,
230
+ * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
231
+ * }
232
+ *
233
+ * 这里只做关键字段提取:responseStatus、certStatus。
234
+ * 完整签名验证依赖更全面的 ASN.1 库。
235
+ */
236
+ private _parseOcspResponse;
237
+ /** 读取 ASN.1 SEQUENCE 标签,返回内容偏移和长度 */
238
+ private _readAsn1Sequence;
239
+ /** 读取任意 ASN.1 标签的长度信息 */
240
+ private _readAsn1Tag;
241
+ /**
242
+ * 从 PKI HTTP 端点下载证书恢复。
243
+ * 本地有密钥但无证书、服务端已注册时使用。
244
+ */
245
+ private _recoverCertViaDownload;
246
+ /**
247
+ * 验证服务端返回的 new_cert,通过后才正式接受。
248
+ * 安全要点:CN/公钥/时间 + 完整链验证 + 受信根锚定 + CRL/OCSP。
249
+ */
250
+ private _validateNewCert;
251
+ /**
252
+ * 从认证结果中提取并保存 token 到 identity。
253
+ * 与 Python SDK 的 _remember_tokens 对齐。
254
+ */
255
+ private static _rememberTokens;
256
+ /**
257
+ * 获取缓存的 access_token(30 秒提前过期余量)。
258
+ * 返回空字符串表示 token 不可用。
259
+ */
260
+ private static _getCachedAccessToken;
261
+ private static readonly _AID_NAME_RE;
262
+ private static _validateAidName;
263
+ /** 确保本地有指定 AID 的身份(不存在则创建密钥对) */
264
+ private _ensureLocalIdentity;
265
+ /** 加载身份信息,不存在时抛出 StateError */
266
+ private _loadIdentityOrRaise;
267
+ /** 确保有身份(不存在时自动创建密钥对) */
268
+ private _ensureIdentity;
269
+ private _loadInstanceState;
270
+ private _persistIdentity;
271
+ /** 从 challenge 消息中提取 nonce */
272
+ private _extractChallengeNonce;
273
+ /** 加载受信根证书列表 */
274
+ private _loadTrustedRoots;
275
+ /**
276
+ * 加载根证书:内置 + 自定义路径。
277
+ * 在 SDK 的 certs/ 目录下查找 *.crt 文件。
278
+ */
279
+ private _loadRootCerts;
280
+ /** 清理过期的 gateway 缓存条目(供外部定时调用) */
281
+ cleanExpiredCaches(): void;
282
+ }
283
+ interface AuthContext extends JsonObject {
284
+ token?: string;
285
+ identity?: IdentityRecord;
286
+ }
287
+ export {};