@anycon/sdk 0.1.1 → 0.3.0
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.
- package/README.md +52 -14
- package/README.zh-CN.md +50 -14
- package/dist/attachments.d.ts +62 -14
- package/dist/attachments.d.ts.map +1 -1
- package/dist/attachments.js +126 -15
- package/dist/attachments.js.map +1 -1
- package/dist/client.d.ts +53 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +205 -3
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/hub.d.ts +10 -0
- package/dist/hub.d.ts.map +1 -1
- package/dist/hub.js +18 -1
- package/dist/hub.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +27 -7
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +41 -10
- package/dist/node.js.map +1 -1
- package/dist/pair.d.ts.map +1 -1
- package/dist/pair.js +6 -1
- package/dist/pair.js.map +1 -1
- package/dist/rotation.d.ts +33 -0
- package/dist/rotation.d.ts.map +1 -0
- package/dist/rotation.js +41 -0
- package/dist/rotation.js.map +1 -0
- package/dist/session.d.ts +5 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js.map +1 -1
- package/dist/storage.d.ts +11 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +16 -2
- package/dist/storage.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +6 -6
- package/src/attachments.ts +167 -22
- package/src/client.ts +292 -2
- package/src/errors.ts +3 -3
- package/src/hub.ts +23 -1
- package/src/index.ts +13 -1
- package/src/node.ts +49 -13
- package/src/pair.ts +9 -2
- package/src/rotation.ts +50 -0
- package/src/session.ts +5 -3
- package/src/storage.ts +24 -2
- package/src/version.ts +1 -1
package/src/client.ts
CHANGED
|
@@ -12,12 +12,27 @@ import {
|
|
|
12
12
|
|
|
13
13
|
import { defaultStorage } from './default-storage.js'
|
|
14
14
|
import { Emitter } from './emitter.js'
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
AnyconError,
|
|
17
|
+
ConnectionError,
|
|
18
|
+
NodeRejected,
|
|
19
|
+
PairingRequired,
|
|
20
|
+
ProtocolMismatch,
|
|
21
|
+
} from './errors.js'
|
|
16
22
|
import { HubConnection, type BackoffOptions } from './hub.js'
|
|
17
23
|
import { NodeLink } from './link.js'
|
|
18
24
|
import { Node, type NodeOptions } from './node.js'
|
|
19
25
|
import type { PermissionPolicy } from './permissions.js'
|
|
20
26
|
import { detectPlatform } from './runtime.js'
|
|
27
|
+
import {
|
|
28
|
+
ROTATE_CLOSE_WAIT_MS,
|
|
29
|
+
ROTATE_RECHECK_MS,
|
|
30
|
+
ROTATE_RETRY_MS,
|
|
31
|
+
ROTATE_TIMEOUT_MS,
|
|
32
|
+
TOKEN_MAX_AGE_MS,
|
|
33
|
+
isTokenDue,
|
|
34
|
+
nextRotationDelay,
|
|
35
|
+
} from './rotation.js'
|
|
21
36
|
import { StateStore, envCredentials, type SdkStorage, type StoredNode } from './storage.js'
|
|
22
37
|
import { SDK_VERSION } from './version.js'
|
|
23
38
|
import { toWsUrl, type WebSocketFactory } from './ws.js'
|
|
@@ -50,6 +65,29 @@ export interface ClientOptions {
|
|
|
50
65
|
resendBufferBytes?: number
|
|
51
66
|
/** 发出不满这么久的信封永不逐出(它们可能还在路上),毫秒。默认 10000。主要给测试用。 */
|
|
52
67
|
resendRetainMs?: number
|
|
68
|
+
/**
|
|
69
|
+
* 设备 token 轮换(docs/spec/sdk.md § 2)。默认:身份由 SDK 自己存(`pair()` 写的、或你给的 `storage`)时,
|
|
70
|
+
* token 满 30 天(或没有签发时间的老记录)在连上 hub 后自动轮换并写回存储;凭据来自环境变量
|
|
71
|
+
* (`ANYCON_DEVICE_TOKEN`)时不自动轮换——SDK 没法保存新 token,要轮换请自己调 `client.rotateToken()` 并保存结果。
|
|
72
|
+
* 除 `auto` 外的几项主要给测试用。
|
|
73
|
+
*/
|
|
74
|
+
tokenRotation?: {
|
|
75
|
+
/** 设成 `false` 关闭自动轮换(默认 `true`;环境变量凭据不论如何都不自动轮换)。 */
|
|
76
|
+
auto?: boolean
|
|
77
|
+
/** token 多久算该轮换,毫秒。默认 30 天。 */
|
|
78
|
+
maxAgeMs?: number
|
|
79
|
+
/** 发出请求后没等到回复,多久再发一次,毫秒。默认 75 秒(头 3 次发送之间的间隔)。 */
|
|
80
|
+
retryAfterMs?: number
|
|
81
|
+
/** 头几次发送之后(以及 token 还不到期时)复查的间隔,毫秒。默认 1 小时。 */
|
|
82
|
+
recheckMs?: number
|
|
83
|
+
/** `close()` 最多多等多久,让刚发出的轮换请求的回复落盘,毫秒。默认 2 秒。 */
|
|
84
|
+
closeWaitMs?: number
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 设备 token 轮换成功时调用(和 `tokenRotated` 事件同一时刻、同一个参数)。凭据来自环境变量、由你保存新 token 时用它——
|
|
88
|
+
* 在 `connect()` / `Client.open()` 里直接传,不会错过 `open` 返回之前就发生的轮换。回调里抛错或返回的 promise 被拒都会被吞掉。
|
|
89
|
+
*/
|
|
90
|
+
onTokenRotated?: (rotation: TokenRotation) => void | Promise<void>
|
|
53
91
|
/** 注入 Noise 实现(默认 wasm)。 */
|
|
54
92
|
crypto?: Crypto
|
|
55
93
|
/** 注入 WebSocket 构造(默认:浏览器原生 / Node 用 `ws`)。 */
|
|
@@ -61,9 +99,28 @@ export interface ClientOptions {
|
|
|
61
99
|
headers?: Record<string, string>
|
|
62
100
|
}
|
|
63
101
|
|
|
102
|
+
/** 一次设备 token 轮换的结果(`client.rotateToken()` 的返回值,也是 `tokenRotated` 事件的参数)。 */
|
|
103
|
+
export interface TokenRotation {
|
|
104
|
+
/** hub 签发的新设备 token。敏感;旧 token 在轮换 60 秒后失效。 */
|
|
105
|
+
deviceToken: string
|
|
106
|
+
/** 新 token 的签发时间(SDK 收到它的时刻),Unix 毫秒。 */
|
|
107
|
+
issuedAtMs: number
|
|
108
|
+
/**
|
|
109
|
+
* SDK 是否已把新 token 写进自己的存储。`false` 表示要你自己保存:凭据来自环境变量,或写存储时出错(见 `persistError`)。
|
|
110
|
+
* 没保存就丢了新 token 的话,旧 token 一失效这台设备就得重新配对。
|
|
111
|
+
*/
|
|
112
|
+
persisted: boolean
|
|
113
|
+
/** 写存储失败时的错误;这时新 token 仍在内存里,本进程的重连会用它。 */
|
|
114
|
+
persistError?: Error
|
|
115
|
+
}
|
|
116
|
+
|
|
64
117
|
export interface ClientEvents {
|
|
65
118
|
/** hub 认证成功(含每次重连后)。 */
|
|
66
119
|
connected: []
|
|
120
|
+
/**
|
|
121
|
+
* 设备 token 轮换成功(自动的、或 `rotateToken()` 触发的)。凭据由你自己管理(环境变量)时在这里保存新 token。
|
|
122
|
+
*/
|
|
123
|
+
tokenRotated: [TokenRotation]
|
|
67
124
|
/** hub 连接断开。 */
|
|
68
125
|
disconnected: [willReconnect: boolean]
|
|
69
126
|
/** 不会再恢复的错误(被顶掉、设备被吊销、token 失效)。 */
|
|
@@ -92,6 +149,31 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
92
149
|
readonly #links = new Map<string, NodeLink>()
|
|
93
150
|
readonly #onlinePeers = new Set<string>()
|
|
94
151
|
readonly #identityStored: boolean
|
|
152
|
+
readonly #autoRotate: boolean
|
|
153
|
+
readonly #rotation: {
|
|
154
|
+
maxAgeMs: number
|
|
155
|
+
retryAfterMs: number
|
|
156
|
+
recheckMs: number
|
|
157
|
+
closeWaitMs: number
|
|
158
|
+
}
|
|
159
|
+
#tokenIssuedAtMs: number | undefined
|
|
160
|
+
#rotateTimer: ReturnType<typeof setTimeout> | undefined
|
|
161
|
+
/** 这条 hub 连接上已经发了几次 `rotate_token`(新连接清零)。 */
|
|
162
|
+
#rotateSends = 0
|
|
163
|
+
/** 最近一次 `rotate_token` 的发出时刻;回复处理完(或连接没了)清掉。 */
|
|
164
|
+
#rotateSentAt: number | undefined
|
|
165
|
+
/** 正在落盘的 `token_rotated` 个数。 */
|
|
166
|
+
#persisting = 0
|
|
167
|
+
/** `close()` 在等回复时留下的唤醒函数。 */
|
|
168
|
+
#rotationWaiters: Array<() => void> = []
|
|
169
|
+
#pendingRotation:
|
|
170
|
+
| {
|
|
171
|
+
promise: Promise<TokenRotation>
|
|
172
|
+
resolve: (r: TokenRotation) => void
|
|
173
|
+
reject: (e: Error) => void
|
|
174
|
+
timer: ReturnType<typeof setTimeout>
|
|
175
|
+
}
|
|
176
|
+
| undefined
|
|
95
177
|
#fatal: Error | undefined
|
|
96
178
|
#closed = false
|
|
97
179
|
|
|
@@ -104,9 +186,19 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
104
186
|
options: ClientOptions,
|
|
105
187
|
envNode: StoredNode | undefined,
|
|
106
188
|
identityStored: boolean,
|
|
189
|
+
tokenIssuedAtMs: number | undefined,
|
|
107
190
|
) {
|
|
108
191
|
super()
|
|
109
192
|
this.#identityStored = identityStored
|
|
193
|
+
this.#tokenIssuedAtMs = tokenIssuedAtMs
|
|
194
|
+
// 只有 SDK 自己存着身份时才自动轮换:环境变量里的 token 换了没地方存,换完旧的还作废,等于把设备锁在外面。
|
|
195
|
+
this.#autoRotate = identityStored && options.tokenRotation?.auto !== false
|
|
196
|
+
this.#rotation = {
|
|
197
|
+
maxAgeMs: options.tokenRotation?.maxAgeMs ?? TOKEN_MAX_AGE_MS,
|
|
198
|
+
retryAfterMs: options.tokenRotation?.retryAfterMs ?? ROTATE_RETRY_MS,
|
|
199
|
+
recheckMs: options.tokenRotation?.recheckMs ?? ROTATE_RECHECK_MS,
|
|
200
|
+
closeWaitMs: options.tokenRotation?.closeWaitMs ?? ROTATE_CLOSE_WAIT_MS,
|
|
201
|
+
}
|
|
110
202
|
this.hubUrl = hubUrl
|
|
111
203
|
this.#hub = hub
|
|
112
204
|
this.#store = store
|
|
@@ -116,6 +208,9 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
116
208
|
this.#envNode = envNode
|
|
117
209
|
|
|
118
210
|
hub.on('authed', (ok) => {
|
|
211
|
+
this.#rotateSends = 0
|
|
212
|
+
this.#clearRotateTimer()
|
|
213
|
+
if (this.#autoRotate) this.#checkRotation()
|
|
119
214
|
this.#onlinePeers.clear()
|
|
120
215
|
for (const id of ok.peers_online) this.#onlinePeers.add(id)
|
|
121
216
|
for (const link of this.#links.values()) link.onHubAuthed(ok.peers_online)
|
|
@@ -127,13 +222,22 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
127
222
|
for (const link of this.#links.values()) link.onControl(ctrl)
|
|
128
223
|
})
|
|
129
224
|
hub.on('envelope', (env) => this.#links.get(env.from)?.onEnvelope(env))
|
|
225
|
+
hub.on('tokenRotated', (deviceToken) => void this.#onTokenRotated(deviceToken))
|
|
130
226
|
hub.on('disconnected', ({ willReconnect }) => {
|
|
227
|
+
this.#stopRotation(
|
|
228
|
+
new ConnectionError(
|
|
229
|
+
'the hub connection dropped before the token rotation was confirmed; ' +
|
|
230
|
+
'the hub may have rotated the token without the new one reaching this client; the previous token stays valid for 60 s, ' +
|
|
231
|
+
'but a connection that authenticated with it cannot rotate again, so pair again if the grace runs out',
|
|
232
|
+
),
|
|
233
|
+
)
|
|
131
234
|
this.#onlinePeers.clear()
|
|
132
235
|
for (const link of this.#links.values()) link.onHubDown()
|
|
133
236
|
this.emit('disconnected', willReconnect)
|
|
134
237
|
})
|
|
135
238
|
hub.on('fatal', (err) => {
|
|
136
239
|
this.#fatal = err
|
|
240
|
+
this.#stopRotation(err)
|
|
137
241
|
if (err instanceof NodeRejected) void this.#forgetRevokedIdentity()
|
|
138
242
|
for (const link of this.#links.values()) link.onHubDown()
|
|
139
243
|
this.emit('error', err)
|
|
@@ -164,7 +268,17 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
164
268
|
...(options.webSocket ? { webSocket: options.webSocket } : {}),
|
|
165
269
|
...(options.headers ? { headers: options.headers } : {}),
|
|
166
270
|
})
|
|
167
|
-
const client = new Client(
|
|
271
|
+
const client = new Client(
|
|
272
|
+
hubUrl,
|
|
273
|
+
hub,
|
|
274
|
+
store,
|
|
275
|
+
crypto,
|
|
276
|
+
keypair,
|
|
277
|
+
options,
|
|
278
|
+
env.node,
|
|
279
|
+
!env.identity,
|
|
280
|
+
env.identity ? undefined : stored?.tokenIssuedAtMs,
|
|
281
|
+
)
|
|
168
282
|
try {
|
|
169
283
|
await hub.start()
|
|
170
284
|
} catch (err) {
|
|
@@ -248,6 +362,175 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
248
362
|
return node
|
|
249
363
|
}
|
|
250
364
|
|
|
365
|
+
/**
|
|
366
|
+
* 请求 hub 轮换本设备的 token,等到新 token 回来(默认最多 10 秒,`timeoutMs` 可改)并返回。
|
|
367
|
+
*
|
|
368
|
+
* - SDK 自己存着身份时,新 token 和签发时间会先写回存储,再用于之后的重连;凭据来自环境变量时 SDK 没有地方存,
|
|
369
|
+
* `persisted` 是 `false`——**你必须自己保存返回值里的 `deviceToken`**(或在 `tokenRotated` 事件里保存)。
|
|
370
|
+
* 旧 token 在轮换 60 秒后失效,没保存就等于把这台设备锁在外面,只能重新配对。
|
|
371
|
+
* - hub 对同一设备 1 分钟内的第二次请求不回复,这里表现为 `rotate_timeout`;没连上 hub 抛 `not_connected`。
|
|
372
|
+
* - 已经有一个请求在等回复时返回同一个结果,不重复发。
|
|
373
|
+
*/
|
|
374
|
+
rotateToken(options: { timeoutMs?: number } = {}): Promise<TokenRotation> {
|
|
375
|
+
if (this.#closed)
|
|
376
|
+
return Promise.reject(new AnyconError('client_closed', 'the client has been closed'))
|
|
377
|
+
if (this.#fatal) return Promise.reject(this.#fatal)
|
|
378
|
+
if (!this.#hub.ready) {
|
|
379
|
+
return Promise.reject(
|
|
380
|
+
new AnyconError('not_connected', 'not connected to the hub: wait for the connection first'),
|
|
381
|
+
)
|
|
382
|
+
}
|
|
383
|
+
if (this.#pendingRotation) return this.#pendingRotation.promise
|
|
384
|
+
const timeoutMs = options.timeoutMs ?? ROTATE_TIMEOUT_MS
|
|
385
|
+
let resolve!: (r: TokenRotation) => void
|
|
386
|
+
let reject!: (e: Error) => void
|
|
387
|
+
const promise = new Promise<TokenRotation>((res, rej) => {
|
|
388
|
+
resolve = res
|
|
389
|
+
reject = rej
|
|
390
|
+
})
|
|
391
|
+
const timer = setTimeout(() => {
|
|
392
|
+
if (this.#pendingRotation?.promise !== promise) return
|
|
393
|
+
this.#pendingRotation = undefined
|
|
394
|
+
reject(
|
|
395
|
+
new AnyconError(
|
|
396
|
+
'rotate_timeout',
|
|
397
|
+
`the hub did not answer the token rotation request within ${Math.round(timeoutMs / 1000)} s ` +
|
|
398
|
+
'(it ignores a second request within a minute of the previous rotation, and hubs without rotation never answer)',
|
|
399
|
+
),
|
|
400
|
+
)
|
|
401
|
+
}, timeoutMs)
|
|
402
|
+
unrefTimer(timer)
|
|
403
|
+
this.#pendingRotation = { promise, resolve, reject, timer }
|
|
404
|
+
if (!this.#sendRotateRequest()) {
|
|
405
|
+
clearTimeout(timer)
|
|
406
|
+
this.#pendingRotation = undefined
|
|
407
|
+
reject(
|
|
408
|
+
new AnyconError('not_connected', 'not connected to the hub: wait for the connection first'),
|
|
409
|
+
)
|
|
410
|
+
}
|
|
411
|
+
return promise
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
#sendRotateRequest(): boolean {
|
|
415
|
+
try {
|
|
416
|
+
this.#hub.sendControl({ type: 'rotate_token' })
|
|
417
|
+
this.#rotateSentAt = Date.now()
|
|
418
|
+
return true
|
|
419
|
+
} catch {
|
|
420
|
+
return false
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
#clearRotateTimer(): void {
|
|
425
|
+
if (this.#rotateTimer !== undefined) clearTimeout(this.#rotateTimer)
|
|
426
|
+
this.#rotateTimer = undefined
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
#armRotateTimer(delayMs: number): void {
|
|
430
|
+
this.#clearRotateTimer()
|
|
431
|
+
this.#rotateTimer = setTimeout(() => this.#checkRotation(), delayMs)
|
|
432
|
+
unrefTimer(this.#rotateTimer)
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 停掉自动轮换的计时,并让还在等回复的 `rotateToken()` 以 `reason` 失败(连接没了,回复不会来)。 */
|
|
436
|
+
#stopRotation(reason: Error): void {
|
|
437
|
+
this.#clearRotateTimer()
|
|
438
|
+
this.#rotateSentAt = undefined
|
|
439
|
+
this.#wakeRotationWaiters()
|
|
440
|
+
const pending = this.#pendingRotation
|
|
441
|
+
if (!pending) return
|
|
442
|
+
clearTimeout(pending.timer)
|
|
443
|
+
this.#pendingRotation = undefined
|
|
444
|
+
pending.reject(reason)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* 自动轮换的一次检查:token 到期就发 `rotate_token`(回复由 `#onTokenRotated` 处理),然后安排下一次——
|
|
449
|
+
* 头几次间隔 `retryAfterMs`(回复可能丢了),之后和「还没到期」时一样按 `recheckMs` 复查(长连接不重连也要换)。
|
|
450
|
+
*/
|
|
451
|
+
#checkRotation(): void {
|
|
452
|
+
this.#rotateTimer = undefined
|
|
453
|
+
if (this.#closed || this.#fatal || !this.#autoRotate || !this.#hub.ready) return
|
|
454
|
+
const { maxAgeMs, retryAfterMs, recheckMs } = this.#rotation
|
|
455
|
+
if (!isTokenDue(this.#tokenIssuedAtMs, Date.now(), maxAgeMs)) {
|
|
456
|
+
this.#armRotateTimer(recheckMs)
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
this.#sendRotateRequest()
|
|
460
|
+
this.#rotateSends += 1
|
|
461
|
+
this.#armRotateTimer(nextRotationDelay(this.#rotateSends, retryAfterMs, recheckMs))
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* hub 回了新 token。先写存储(token 和签发时间一次写完)再换掉重连用的 token:写成功之前新 token 不会成为
|
|
466
|
+
* 唯一的凭据。写失败也照样换——旧 token 60 秒后就失效,留着它只会让下次重连失败——并在事件里报告 `persisted: false`。
|
|
467
|
+
* 超时之后才到的回复同样处理(hub 已经轮换过了,新 token 不能丢)。
|
|
468
|
+
*/
|
|
469
|
+
async #onTokenRotated(deviceToken: string): Promise<void> {
|
|
470
|
+
const issuedAtMs = Date.now()
|
|
471
|
+
let persisted = false
|
|
472
|
+
let persistError: Error | undefined
|
|
473
|
+
this.#persisting += 1
|
|
474
|
+
try {
|
|
475
|
+
if (this.#identityStored) {
|
|
476
|
+
try {
|
|
477
|
+
persisted = await this.#store.rotateIdentityToken(deviceToken, issuedAtMs)
|
|
478
|
+
} catch (cause) {
|
|
479
|
+
persistError = cause instanceof Error ? cause : new Error(String(cause))
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
this.#hub.setToken(deviceToken)
|
|
483
|
+
this.#tokenIssuedAtMs = issuedAtMs
|
|
484
|
+
this.#rotateSends = 0
|
|
485
|
+
} finally {
|
|
486
|
+
this.#persisting -= 1
|
|
487
|
+
this.#rotateSentAt = undefined
|
|
488
|
+
this.#wakeRotationWaiters()
|
|
489
|
+
}
|
|
490
|
+
const result: TokenRotation = {
|
|
491
|
+
deviceToken,
|
|
492
|
+
issuedAtMs,
|
|
493
|
+
persisted,
|
|
494
|
+
...(persistError ? { persistError } : {}),
|
|
495
|
+
}
|
|
496
|
+
const pending = this.#pendingRotation
|
|
497
|
+
if (pending) {
|
|
498
|
+
clearTimeout(pending.timer)
|
|
499
|
+
this.#pendingRotation = undefined
|
|
500
|
+
pending.resolve(result)
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
const returned = this.#options.onTokenRotated?.(result)
|
|
504
|
+
if (returned instanceof Promise) returned.catch(() => undefined)
|
|
505
|
+
} catch {
|
|
506
|
+
// 回调的异常不能影响连接
|
|
507
|
+
}
|
|
508
|
+
this.emit('tokenRotated', result)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
#wakeRotationWaiters(): void {
|
|
512
|
+
const waiters = this.#rotationWaiters
|
|
513
|
+
this.#rotationWaiters = []
|
|
514
|
+
for (const wake of waiters) wake()
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** `close()` 之前:刚发出的 `rotate_token` 还没收到 / 处理完回复时,最多再等一小会儿,免得新 token 丢掉。 */
|
|
518
|
+
async #settleRotationBeforeClose(): Promise<void> {
|
|
519
|
+
const { closeWaitMs } = this.#rotation
|
|
520
|
+
const sent = this.#rotateSentAt
|
|
521
|
+
const left =
|
|
522
|
+
this.#persisting > 0 ? closeWaitMs : sent === undefined ? 0 : sent + closeWaitMs - Date.now()
|
|
523
|
+
if (left <= 0) return
|
|
524
|
+
await new Promise<void>((resolve) => {
|
|
525
|
+
const timer = setTimeout(resolve, left)
|
|
526
|
+
unrefTimer(timer)
|
|
527
|
+
this.#rotationWaiters.push(() => {
|
|
528
|
+
clearTimeout(timer)
|
|
529
|
+
resolve()
|
|
530
|
+
})
|
|
531
|
+
})
|
|
532
|
+
}
|
|
533
|
+
|
|
251
534
|
/** 设备被 hub 吊销(4004 / auth_fail revoked):token 已作废,清掉本地凭据,下次 connect 抛 PairingRequired。 */
|
|
252
535
|
async #forgetRevokedIdentity(): Promise<void> {
|
|
253
536
|
if (this.#identityStored) await this.#store.clearIdentity().catch(() => undefined)
|
|
@@ -267,6 +550,8 @@ export class Client extends Emitter<ClientEvents> {
|
|
|
267
550
|
async close(): Promise<void> {
|
|
268
551
|
if (this.#closed) return
|
|
269
552
|
this.#closed = true
|
|
553
|
+
await this.#settleRotationBeforeClose()
|
|
554
|
+
this.#stopRotation(new AnyconError('client_closed', 'the client has been closed'))
|
|
270
555
|
for (const id of Array.from(this.#links.keys())) this.#drop(id)
|
|
271
556
|
this.#hub.close()
|
|
272
557
|
}
|
|
@@ -349,3 +634,8 @@ function waitSettled(link: NodeLink, timeoutMs: number): Promise<void> {
|
|
|
349
634
|
check()
|
|
350
635
|
})
|
|
351
636
|
}
|
|
637
|
+
|
|
638
|
+
/** 计时器不拖住 Node 进程退出(浏览器的计时器没有 `unref`)。 */
|
|
639
|
+
function unrefTimer(timer: ReturnType<typeof setTimeout>): void {
|
|
640
|
+
;(timer as { unref?: () => void }).unref?.()
|
|
641
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -129,11 +129,11 @@ export class NodeBusy extends RpcError {
|
|
|
129
129
|
/**
|
|
130
130
|
* 附件(blob 通道,ADR-35)被 daemon 拒绝时的 `data.reason`(protocol.md § 5.6):
|
|
131
131
|
*
|
|
132
|
-
* - `too_large`(`invalid
|
|
132
|
+
* - `too_large`(`invalid`):单个文件超过 `sessions.max_attachment_bytes`(默认 10 MiB),或一条消息的附件合计超过 20 MiB
|
|
133
133
|
* - `quota`(`busy`):完成但没被引用的 blob 全节点合计超过 1 GiB——先发出去或 `discardAttachment()` 一些
|
|
134
134
|
* - `disk_full`(`busy`):daemon 数据目录所在卷剩余空间不够
|
|
135
135
|
* - `blob`(`not_found`):消息引用的 blob 不存在(24 小时没被引用已被回收、被丢掉了,或文件不见了)——重新上传
|
|
136
|
-
* - `blob_in_use`(`invalid`):blob
|
|
136
|
+
* - `blob_in_use`(`invalid`):blob 已经绑定到**别的**会话的消息上——一个附件只能属于一个会话,重新上传
|
|
137
137
|
* - `in_use`(`invalid`):`blob.discard` 一个已被消息引用的 blob
|
|
138
138
|
* - `finalizing`(`invalid`):`put_end` 已经开始收尾之后又来了块
|
|
139
139
|
* - `incomplete` / `hash_mismatch` / `mime_mismatch`(`invalid`):`put_end` 校验失败(缺块 / SHA-256 不符 / 文件头和 mime 不符)
|
|
@@ -167,7 +167,7 @@ const ATTACHMENT_CODES: ReadonlySet<string> = new Set(['invalid', 'busy', 'not_f
|
|
|
167
167
|
|
|
168
168
|
/**
|
|
169
169
|
* 附件被 daemon 拒绝(`blob.*`,或 `session.send` / `session.create` 核对附件时)。`code` 仍是稳定码
|
|
170
|
-
* (`invalid` / `busy` / `not_found`),`reason` 是 `AttachmentErrorReason
|
|
170
|
+
* (`invalid` / `busy` / `not_found`),`reason` 是 `AttachmentErrorReason`,按它决定重传、换文件还是提示用户。
|
|
171
171
|
*/
|
|
172
172
|
export class AttachmentError extends RpcError {
|
|
173
173
|
override readonly name: string = 'AttachmentError'
|
package/src/hub.ts
CHANGED
|
@@ -65,6 +65,11 @@ export interface HubEvents {
|
|
|
65
65
|
control: [Control]
|
|
66
66
|
/** handshake / data / notify 信封。 */
|
|
67
67
|
envelope: [Envelope]
|
|
68
|
+
/**
|
|
69
|
+
* hub 轮换了设备 token(`token_rotated`),参数是新 token。只在本连接持有设备 token 时才会触发;
|
|
70
|
+
* 消息不经过 `control`(新 token 是秘密,不往外多扇出)。调用方要先持久化它再 {@link HubConnection.setToken}。
|
|
71
|
+
*/
|
|
72
|
+
tokenRotated: [deviceToken: string]
|
|
68
73
|
disconnected: [info: { code: number; reason: string; willReconnect: boolean }]
|
|
69
74
|
/** 不会再重连的终止性错误(被顶掉、被吊销、token 无效……)。 */
|
|
70
75
|
fatal: [Error]
|
|
@@ -96,6 +101,8 @@ export class HubConnection extends Emitter<HubEvents> {
|
|
|
96
101
|
readonly #factory: WebSocketFactory
|
|
97
102
|
readonly #backoff: Required<BackoffOptions>
|
|
98
103
|
readonly #authTimeoutMs: number
|
|
104
|
+
/** 之后每次(重)连接认证用的设备 token;轮换后由 {@link HubConnection.setToken} 换成新的。 */
|
|
105
|
+
#token: string | undefined
|
|
99
106
|
#state: State = 'idle'
|
|
100
107
|
#ws: WebSocketLike | undefined
|
|
101
108
|
#deviceId: string
|
|
@@ -116,6 +123,7 @@ export class HubConnection extends Emitter<HubEvents> {
|
|
|
116
123
|
constructor(options: HubConnectionOptions) {
|
|
117
124
|
super()
|
|
118
125
|
this.#opts = options
|
|
126
|
+
this.#token = options.token
|
|
119
127
|
this.#factory = options.webSocket ?? defaultWebSocket
|
|
120
128
|
const r = typeof options.reconnect === 'object' ? options.reconnect : {}
|
|
121
129
|
this.#backoff = { initialMs: r.initialMs ?? 1000, maxMs: r.maxMs ?? 30_000 }
|
|
@@ -131,6 +139,14 @@ export class HubConnection extends Emitter<HubEvents> {
|
|
|
131
139
|
this.#deviceId = id
|
|
132
140
|
}
|
|
133
141
|
|
|
142
|
+
/**
|
|
143
|
+
* 轮换成功后换上新的设备 token:之后的重连用它认证。当前这条连接不受影响(认证只在连接建立时发生)。
|
|
144
|
+
* 临时连接(没有 token)调用无效。
|
|
145
|
+
*/
|
|
146
|
+
setToken(token: string): void {
|
|
147
|
+
if (this.#token !== undefined) this.#token = token
|
|
148
|
+
}
|
|
149
|
+
|
|
134
150
|
/** hub 分配 / 确认的设备 id(`auth_ok` 之后可用)。 */
|
|
135
151
|
get deviceId(): string {
|
|
136
152
|
return this.#deviceId
|
|
@@ -262,7 +278,7 @@ export class HubConnection extends Emitter<HubEvents> {
|
|
|
262
278
|
)
|
|
263
279
|
const auth: Control = {
|
|
264
280
|
type: 'auth',
|
|
265
|
-
...(this.#
|
|
281
|
+
...(this.#token ? { device_token: this.#token } : {}),
|
|
266
282
|
protocol_version: PROTOCOL_VERSION,
|
|
267
283
|
client: this.#opts.client,
|
|
268
284
|
}
|
|
@@ -336,6 +352,12 @@ export class HubConnection extends Emitter<HubEvents> {
|
|
|
336
352
|
this.emit('control', ctrl)
|
|
337
353
|
return
|
|
338
354
|
}
|
|
355
|
+
case 'token_rotated':
|
|
356
|
+
// 临时连接(没有设备 token)不该收到;收到的话当作 hub 的噪声丢掉。
|
|
357
|
+
if (this.#token !== undefined && this.#state === 'ready' && ctrl.device_token) {
|
|
358
|
+
this.emit('tokenRotated', ctrl.device_token)
|
|
359
|
+
}
|
|
360
|
+
return
|
|
339
361
|
default:
|
|
340
362
|
this.emit('control', ctrl)
|
|
341
363
|
}
|
package/src/index.ts
CHANGED
|
@@ -14,7 +14,13 @@
|
|
|
14
14
|
* ```
|
|
15
15
|
*/
|
|
16
16
|
export { connect, type ConnectOptions } from './connect.js'
|
|
17
|
-
export {
|
|
17
|
+
export {
|
|
18
|
+
Client,
|
|
19
|
+
selectNode,
|
|
20
|
+
type ClientEvents,
|
|
21
|
+
type ClientOptions,
|
|
22
|
+
type TokenRotation,
|
|
23
|
+
} from './client.js'
|
|
18
24
|
export {
|
|
19
25
|
PAIR_ACK_TIMEOUT_MS,
|
|
20
26
|
forgetNode,
|
|
@@ -48,12 +54,18 @@ export {
|
|
|
48
54
|
type TurnStream,
|
|
49
55
|
} from './session.js'
|
|
50
56
|
export {
|
|
57
|
+
DEFAULT_FILE_MIME,
|
|
51
58
|
IMAGE_MIME_TYPES,
|
|
52
59
|
MAX_CHUNKS_IN_FLIGHT,
|
|
60
|
+
acceptsAttachment,
|
|
53
61
|
detectImageMime,
|
|
62
|
+
guessMime,
|
|
63
|
+
isNativeAttachment,
|
|
64
|
+
normalizeMime,
|
|
54
65
|
type DownloadOptions,
|
|
55
66
|
type DownloadedAttachment,
|
|
56
67
|
type ImageMime,
|
|
68
|
+
type UploadFileOptions,
|
|
57
69
|
type UploadImageOptions,
|
|
58
70
|
} from './attachments.js'
|
|
59
71
|
export {
|
package/src/node.ts
CHANGED
|
@@ -34,9 +34,12 @@ import {
|
|
|
34
34
|
import {
|
|
35
35
|
downloadAttachment,
|
|
36
36
|
raceAbort,
|
|
37
|
-
|
|
37
|
+
resolveFileMime,
|
|
38
|
+
resolveImageMime,
|
|
39
|
+
uploadBlob,
|
|
38
40
|
type DownloadOptions,
|
|
39
41
|
type DownloadedAttachment,
|
|
42
|
+
type UploadFileOptions,
|
|
40
43
|
type UploadImageOptions,
|
|
41
44
|
} from './attachments.js'
|
|
42
45
|
import type { Client } from './client.js'
|
|
@@ -107,7 +110,7 @@ export interface CreateSessionParams {
|
|
|
107
110
|
*/
|
|
108
111
|
prompt?: string
|
|
109
112
|
/**
|
|
110
|
-
* 第一条消息的附件(`node.uploadImage()` 的结果,原样放进来)。有附件时 `prompt` 可以为空,照样发第一条消息。
|
|
113
|
+
* 第一条消息的附件(`node.uploadImage()` / `node.uploadFile()` 的结果,原样放进来)。有附件时 `prompt` 可以为空,照样发第一条消息。
|
|
111
114
|
* daemon 的核对见 `Session.send` 的 `attachments`。
|
|
112
115
|
*/
|
|
113
116
|
attachments?: AttachmentRef[]
|
|
@@ -315,13 +318,22 @@ export class Node extends Emitter<NodeEvents> {
|
|
|
315
318
|
|
|
316
319
|
readonly projects = {
|
|
317
320
|
list: async (): Promise<Project[]> => (await this.call('workspace.list', {})).projects,
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
321
|
+
/**
|
|
322
|
+
* `root`:建在哪个 workspace 根下(`info().workspace_roots` 里某一项的 `path`),缺省 = 主根;
|
|
323
|
+
* 不在列表里 → `invalid`,在列表里但现在不可用(`available: false`)→ `not_found`。
|
|
324
|
+
*/
|
|
325
|
+
create: (name: string, options: { gitInit?: boolean; root?: string } = {}) =>
|
|
326
|
+
this.call('workspace.create', {
|
|
327
|
+
name,
|
|
328
|
+
git_init: options.gitInit ?? false,
|
|
329
|
+
...(options.root !== undefined ? { root: options.root } : {}),
|
|
330
|
+
}),
|
|
331
|
+
/** 克隆是长任务:返回 `Job`,`job.progress()` 看进度,`job.wait()` 等结束。`root` 同 `create`。 */
|
|
332
|
+
clone: async (url: string, options: { name?: string; root?: string } = {}): Promise<Job> => {
|
|
322
333
|
const started = await this.call('workspace.clone', {
|
|
323
334
|
url,
|
|
324
335
|
...(options.name !== undefined ? { name: options.name } : {}),
|
|
336
|
+
...(options.root !== undefined ? { root: options.root } : {}),
|
|
325
337
|
})
|
|
326
338
|
return this.#jobHandle(started.job_id)
|
|
327
339
|
},
|
|
@@ -421,28 +433,52 @@ export class Node extends Emitter<NodeEvents> {
|
|
|
421
433
|
/**
|
|
422
434
|
* 把一张图片传到节点(`blob.put_begin` → 512 KiB 一块、最多 2 块在途的 `blob.put_chunk` → `blob.put_end`),
|
|
423
435
|
* 返回 daemon 的记录(`AttachmentRef`,含宽高),原样放进 `session.send(text, { attachments })` /
|
|
424
|
-
* `sessions.create({ attachments })
|
|
436
|
+
* `sessions.create({ attachments })`。同一个节点上的上传(图片和文件)排队、一个一个传。
|
|
425
437
|
*
|
|
426
|
-
*
|
|
438
|
+
* 只收 `image/png` / `image/jpeg` / `image/gif` / `image/webp`:`mime` 缺省而文件头认不出,或者给的不是这四种,
|
|
439
|
+
* 抛 `AnyconError('unsupported_image')`,什么都不发。别的文件用 `uploadFile()`。
|
|
440
|
+
* SDK 不缩放、不重编码:调用方自己把图控制在长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB(daemon 每个文件默认上限 10 MiB)。
|
|
427
441
|
* 被拒绝时抛 `AttachmentError`(`reason`:`too_large` / `quota` / `disk_full` / `hash_mismatch` / `mime_mismatch` / …)
|
|
428
|
-
* 或 `RpcError`(`
|
|
442
|
+
* 或 `RpcError`(`busy`:这台设备同时进行的上传太多)。没传完的上传会被 `blob.discard`。
|
|
429
443
|
* 没上传完就不要了用 `signal`;传完了但不发了用 `discardAttachment()`(不丢的话 daemon 24 小时后回收)。
|
|
430
444
|
*/
|
|
431
445
|
async uploadImage(bytes: Uint8Array, options: UploadImageOptions): Promise<AttachmentRef> {
|
|
446
|
+
const mime = resolveImageMime(bytes, options)
|
|
447
|
+
return this.#queueUpload(options.signal, () => uploadBlob(this, bytes, mime, options))
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* 把任意文件传到节点,和 `uploadImage()` 走同一套分块上传、同一个队列,返回 `AttachmentRef`(四种图片才有宽高)。
|
|
452
|
+
*
|
|
453
|
+
* `mime` 缺省时:文件头是四种图片之一就用它,否则按 `name` 的扩展名猜(`pdf`、`txt`、`md`、`csv`、`json`、`zip`、
|
|
454
|
+
* `py`、`rs`……),猜不出用 `application/octet-stream`。给了 `mime` 就必须是成形的 `type/subtype`(不带参数,
|
|
455
|
+
* 发出去前转小写),否则抛 `AnyconError('invalid_mime')`,什么都不发;真正的校验在 daemon。
|
|
456
|
+
* agent 原生收的类型(`AgentInfo.capabilities.attachments`,一般是四种图片)由 daemon 交给 adapter;其余的 daemon 复制到
|
|
457
|
+
* 会话工作目录的 `.anycon/attachments/<session_id>/` 下,并在发给 agent 的文字末尾附上路径(ADR-44)。节点带
|
|
458
|
+
* `capabilities.file_attachments` 才收这些,看 `acceptsAttachment(await node.info(), agent, ref.mime)`;旧节点上 `send()` /
|
|
459
|
+
* `sessions.create()` 对不原生收的类型得到 `RpcError`(`unsupported`)。拒绝、中止、清理同 `uploadImage()`。
|
|
460
|
+
*/
|
|
461
|
+
async uploadFile(bytes: Uint8Array, options: UploadFileOptions): Promise<AttachmentRef> {
|
|
462
|
+
const mime = resolveFileMime(bytes, options)
|
|
463
|
+
return this.#queueUpload(options.signal, () => uploadBlob(this, bytes, mime, options))
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** 同一个节点上的上传排队:前一个结束(成功或失败)才开始下一个;排队时被中止的什么都不发。 */
|
|
467
|
+
async #queueUpload<T>(signal: AbortSignal | undefined, run: () => Promise<T>): Promise<T> {
|
|
432
468
|
const prev = this.#uploadTail
|
|
433
469
|
let release!: () => void
|
|
434
470
|
this.#uploadTail = new Promise<void>((resolve) => (release = resolve))
|
|
435
471
|
try {
|
|
436
|
-
await raceAbort(prev,
|
|
437
|
-
return await
|
|
472
|
+
await raceAbort(prev, signal)
|
|
473
|
+
return await run()
|
|
438
474
|
} finally {
|
|
439
|
-
//
|
|
475
|
+
// 排队时被中止:等前一个传完再放行下一个,保证同时只有一个在传
|
|
440
476
|
void prev.then(release)
|
|
441
477
|
}
|
|
442
478
|
}
|
|
443
479
|
|
|
444
480
|
/**
|
|
445
|
-
*
|
|
481
|
+
* 下载一个附件(图片或任意文件,`blob.get` 按 512 KiB 分页拉)。任何已配对设备都能读任何 blob;不存在 / 文件不见了 →
|
|
446
482
|
* `RpcError`(`not_found`,文件不见了时是 `AttachmentError`,`reason = 'blob'`)。
|
|
447
483
|
*/
|
|
448
484
|
downloadAttachment(
|
package/src/pair.ts
CHANGED
|
@@ -205,7 +205,9 @@ function join(
|
|
|
205
205
|
/** msg3 之后的新传输:只用来读 daemon 的 `pair.ack`,之后丢弃(重连走 IK)。 */
|
|
206
206
|
let transport: Transport | undefined
|
|
207
207
|
let nodePublic: Uint8Array | undefined
|
|
208
|
-
let done:
|
|
208
|
+
let done:
|
|
209
|
+
| { peer: string; deviceId: string; deviceToken: string; tokenIssuedAtMs: number | undefined }
|
|
210
|
+
| undefined
|
|
209
211
|
const early: Uint8Array[] = []
|
|
210
212
|
const reassembler = new Reassembler()
|
|
211
213
|
let settled = false
|
|
@@ -294,7 +296,9 @@ function join(
|
|
|
294
296
|
return
|
|
295
297
|
}
|
|
296
298
|
if (msg.device_id) hub.adoptDeviceId(msg.device_id)
|
|
297
|
-
|
|
299
|
+
// hub 这次签发了新 token:签发时间就是现在;沿用已有 token 时保留原来的记录(可能没有,那就当作很旧)。
|
|
300
|
+
const tokenIssuedAtMs = msg.device_token ? Date.now() : existing?.tokenIssuedAtMs
|
|
301
|
+
done = { peer: msg.peer, deviceId, deviceToken, tokenIssuedAtMs }
|
|
298
302
|
ackTimer = setTimeout(
|
|
299
303
|
() =>
|
|
300
304
|
fail(
|
|
@@ -369,6 +373,9 @@ function join(
|
|
|
369
373
|
const identity: StoredIdentity = {
|
|
370
374
|
deviceId: confirmed.deviceId,
|
|
371
375
|
deviceToken: confirmed.deviceToken,
|
|
376
|
+
...(confirmed.tokenIssuedAtMs !== undefined
|
|
377
|
+
? { tokenIssuedAtMs: confirmed.tokenIssuedAtMs }
|
|
378
|
+
: {}),
|
|
372
379
|
secretKey: hexOf(keypair.secret),
|
|
373
380
|
name: options.name,
|
|
374
381
|
createdAtMs: existing?.createdAtMs ?? Date.now(),
|