@simonyea/holysheep-cli 1.7.42 → 1.7.43

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simonyea/holysheep-cli",
3
- "version": "1.7.42",
3
+ "version": "1.7.43",
4
4
  "description": "Claude Code/Cursor/Cline API relay for China — ¥1=$1, WeChat/Alipay payment, no credit card, no VPN. One command setup for all AI coding tools.",
5
5
  "keywords": [
6
6
  "openai-china",
@@ -58,41 +58,36 @@ async function readJsonResponse(response) {
58
58
  }
59
59
  }
60
60
 
61
- async function requestSessionLease(config, sessionId) {
62
- const cached = leaseCache.get(sessionId)
63
- if (cached?.expiresAt && new Date(cached.expiresAt).getTime() - Date.now() > 30_000) {
64
- return cached
65
- }
66
-
61
+ // relay 申请新 lease(启动时 + CONNECT 失败时被动重试)
62
+ async function fetchFreshLease(config, sessionId) {
67
63
  const controlPlaneUrl = getControlPlaneUrl(config)
68
64
  if (!controlPlaneUrl) throw new Error('Claude relay control plane is not configured')
69
65
 
70
- try {
71
- const response = await fetch(`${controlPlaneUrl}/session/open`, {
72
- method: 'POST',
73
- headers: { 'content-type': 'application/json' },
74
- body: JSON.stringify({
75
- sessionId,
76
- bridgeId: config.bridgeId || 'local-bridge',
77
- deviceId: config.deviceId || '',
78
- installSource: config.installSource || 'holysheep-cli',
79
- proxyMode: 'claude-process',
80
- }),
81
- })
66
+ const response = await fetch(`${controlPlaneUrl}/session/open`, {
67
+ method: 'POST',
68
+ headers: { 'content-type': 'application/json' },
69
+ body: JSON.stringify({
70
+ sessionId,
71
+ bridgeId: config.bridgeId || 'local-bridge',
72
+ deviceId: config.deviceId || '',
73
+ installSource: config.installSource || 'holysheep-cli',
74
+ proxyMode: 'claude-process',
75
+ }),
76
+ })
82
77
 
83
- const payload = await response.json().catch(() => null)
84
- if (!response.ok || !payload?.success || !payload?.data?.ticket) {
85
- throw new Error(payload?.error?.message || `Failed to open Claude session (HTTP ${response.status})`)
86
- }
87
- leaseCache.set(sessionId, payload.data)
88
- return payload.data
89
- } catch (error) {
90
- // 续约失败时,只要旧 lease 还没真正过期就继续用,避免网络抖动导致 session 中断
91
- if (cached?.expiresAt && new Date(cached.expiresAt).getTime() > Date.now()) {
92
- return cached
93
- }
94
- throw error
78
+ const payload = await response.json().catch(() => null)
79
+ if (!response.ok || !payload?.success || !payload?.data?.ticket) {
80
+ throw new Error(payload?.error?.message || `Failed to open Claude session (HTTP ${response.status})`)
95
81
  }
82
+ leaseCache.set(sessionId, payload.data)
83
+ return payload.data
84
+ }
85
+
86
+ // 请求路径:只读缓存,不检查过期时间(续约由失败触发,不由时间触发)
87
+ function getCachedLease(sessionId) {
88
+ const cached = leaseCache.get(sessionId)
89
+ if (!cached) throw new Error('No session lease available')
90
+ return cached
96
91
  }
97
92
 
98
93
  function buildAuthHeaders(config, lease) {
@@ -157,84 +152,100 @@ function pipeWithCleanup(a, b) {
157
152
 
158
153
  function createProcessProxyServer({ sessionId, configPath = CONFIG_PATH }) {
159
154
  const server = http.createServer(async (clientReq, clientRes) => {
160
- try {
155
+ const doForward = async (lease) => {
161
156
  const config = readConfig(configPath)
162
- const lease = await requestSessionLease(config, sessionId)
163
157
  const nodeProxyUrl = deriveNodeProxyUrl(lease)
164
158
  const headers = {
165
159
  ...buildAuthHeaders(config, lease),
166
160
  host: new URL(clientReq.url).host,
167
161
  }
168
-
169
162
  const upstream = new URL(nodeProxyUrl)
170
- const forwardReq = http.request({
171
- host: upstream.hostname,
172
- port: Number(upstream.port || 80),
173
- method: clientReq.method,
174
- path: clientReq.url,
175
- headers: {
176
- ...clientReq.headers,
177
- ...headers,
178
- connection: 'close',
179
- },
180
- }, (forwardRes) => {
181
- clientRes.writeHead(forwardRes.statusCode || 502, forwardRes.headers)
182
- forwardRes.pipe(clientRes)
163
+ return new Promise((resolve, reject) => {
164
+ const forwardReq = http.request({
165
+ host: upstream.hostname,
166
+ port: Number(upstream.port || 80),
167
+ method: clientReq.method,
168
+ path: clientReq.url,
169
+ headers: { ...clientReq.headers, ...headers, connection: 'close' },
170
+ }, (forwardRes) => {
171
+ clientRes.writeHead(forwardRes.statusCode || 502, forwardRes.headers)
172
+ forwardRes.pipe(clientRes)
173
+ resolve()
174
+ })
175
+ forwardReq.once('error', reject)
176
+ clientReq.pipe(forwardReq)
183
177
  })
178
+ }
184
179
 
185
- forwardReq.once('error', (error) => {
180
+ try {
181
+ await doForward(getCachedLease(sessionId))
182
+ } catch {
183
+ // lease 失效,拿新 lease 重试一次
184
+ try {
185
+ const config = readConfig(configPath)
186
+ leaseCache.delete(sessionId)
187
+ const freshLease = await fetchFreshLease(config, sessionId)
188
+ await doForward(freshLease)
189
+ } catch (retryError) {
186
190
  clientRes.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
187
- clientRes.end(error.message || 'Proxy error')
188
- })
189
-
190
- clientReq.pipe(forwardReq)
191
- } catch (error) {
192
- clientRes.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
193
- clientRes.end(error.message || 'Proxy error')
191
+ clientRes.end(retryError.message || 'Proxy error')
192
+ }
194
193
  }
195
194
  })
196
195
 
197
196
  server.on('connect', async (req, clientSocket, head) => {
198
- try {
199
- const config = readConfig(configPath)
200
- const lease = await requestSessionLease(config, sessionId)
201
- const target = String(req.url || '').trim()
202
- const [host, rawPort] = target.split(':')
203
- const port = Number(rawPort || 443)
204
- if (!host || !Number.isInteger(port) || ![80, 443].includes(port)) {
205
- clientSocket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
206
- return clientSocket.destroy()
207
- }
197
+ const target = String(req.url || '').trim()
198
+ const [host, rawPort] = target.split(':')
199
+ const port = Number(rawPort || 443)
200
+ if (!host || !Number.isInteger(port) || ![80, 443].includes(port)) {
201
+ clientSocket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
202
+ return clientSocket.destroy()
203
+ }
208
204
 
205
+ const doConnect = async (lease) => {
209
206
  const upstreamSocket = await createConnectTunnel(
210
207
  deriveNodeProxyUrl(lease),
211
208
  target,
212
- buildAuthHeaders(config, lease)
209
+ buildAuthHeaders(readConfig(configPath), lease)
213
210
  )
214
-
215
211
  clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
216
212
  if (head?.length) upstreamSocket.write(head)
217
213
  pipeWithCleanup(clientSocket, upstreamSocket)
218
- } catch (error) {
219
- clientSocket.write(`HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain; charset=utf-8\r\n\r\n${error.message}`)
220
- clientSocket.destroy()
214
+ }
215
+
216
+ try {
217
+ await doConnect(getCachedLease(sessionId))
218
+ } catch {
219
+ // lease 失效,拿新 lease 重试一次
220
+ try {
221
+ const config = readConfig(configPath)
222
+ leaseCache.delete(sessionId)
223
+ const freshLease = await fetchFreshLease(config, sessionId)
224
+ await doConnect(freshLease)
225
+ } catch (retryError) {
226
+ clientSocket.write(`HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain; charset=utf-8\r\n\r\n${retryError.message}`)
227
+ clientSocket.destroy()
228
+ }
221
229
  }
222
230
  })
223
231
 
224
232
  return server
225
233
  }
226
234
 
227
- function startProcessProxy({ port = null, sessionId = null, configPath = CONFIG_PATH } = {}) {
235
+ async function startProcessProxy({ port = null, sessionId = null, configPath = CONFIG_PATH } = {}) {
228
236
  const config = readConfig(configPath)
229
237
  const preferredPort = port || getProcessProxyPort(config)
230
238
  const effectiveSessionId = sessionId || crypto.randomUUID()
239
+
240
+ // 启动时拿一次 lease,之后靠被动重试维持,不再主动续约
241
+ await fetchFreshLease(config, effectiveSessionId)
242
+
231
243
  const server = createProcessProxyServer({ sessionId: effectiveSessionId, configPath })
232
244
 
233
245
  return new Promise((resolve, reject) => {
234
246
  const tryListen = (p) => {
235
247
  server.once('error', (err) => {
236
248
  if (err.code === 'EADDRINUSE') {
237
- // 端口被占用,让 OS 分配一个随机可用端口
238
249
  server.once('error', reject)
239
250
  server.listen(0, '127.0.0.1')
240
251
  } else {
@@ -272,7 +283,6 @@ module.exports = {
272
283
  getProcessProxyPort,
273
284
  getControlPlaneUrl,
274
285
  readConfig,
275
- requestSessionLease,
276
286
  startProcessProxy,
277
287
  writeConfig,
278
288
  }