com.jimuwd.xian.registry-proxy 1.0.133 → 1.0.134

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 CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  ## 概述
8
8
 
9
- 本项目提供了一个代理服务器(`registry-proxy`),允许 Yarn 从多个注册表获取包,并支持身份验证令牌。项目还包括一个脚本(`scripts/install-from-proxy-registries.sh`),用于自动化启动代理服务器、安装依赖和清理资源的过程。该设置确保与 Yarn 无缝集成,开发者只需使用标准的 `yarn` 命令即可通过代理安装依赖。
9
+ 本项目提供了一个本地代理服务器(`registry-proxy`),允许 Yarn 从多个注册表获取包,并支持身份验证令牌。项目还包括一个脚本(`src/client/yarn-install`),用于自动化启动代理服务器、安装依赖和清理资源的过程。该设置确保与 Yarn 无缝集成,开发者只需使用标准的 `yarn` 命令即可通过代理安装依赖。
10
10
 
11
11
  ## 功能
12
12
 
@@ -63,31 +63,22 @@ registries:
63
63
 
64
64
  ```yaml
65
65
  unsafeHttpWhitelist:
66
- - "localhost"
66
+ - "[::1]"
67
67
  ```
68
68
 
69
- ### 4. 创建安装脚本
70
-
71
- `scripts/` 目录下创建 `install-from-proxy-registries.sh` 脚本,用于自动化代理设置和依赖安装:
72
-
73
- ### 5. 设置脚本权限
74
-
75
- 确保脚本具有可执行权限,并将权限状态提交到版本控制:
76
-
77
- ```bash
78
- chmod +x scripts/install-from-proxy-registries.sh
79
- git add scripts/install-from-proxy-registries.sh
80
- git commit -m "Add install script with executable permission"
69
+ ### 4. 安装命令
70
+ ```shell
71
+ yarn dlx -p com.jimuwd.xian.registry-proxy yarn-install
81
72
  ```
82
73
 
83
- ### 6. 与 Yarn 集成
74
+ ### 5. 与 Yarn 集成
84
75
 
85
76
  更新 `package.json`,使 `yarn` 命令自动运行脚本:
86
77
 
87
78
  ```json
88
79
  {
89
80
  "scripts": {
90
- "preinstall": "bash scripts/install-from-proxy-registries.sh",
81
+ "preinstall": "yarn dlx -p com.jimuwd.xian.registry-proxy yarn-install",
91
82
  "install": "echo 'Custom install script is running via preinstall, skipping default install.'"
92
83
  }
93
84
  }
@@ -276,7 +267,7 @@ A lightweight proxy server for Yarn to fetch packages from multiple registries w
276
267
 
277
268
  ## Overview
278
269
 
279
- This project provides a proxy server (`registry-proxy`) that allows Yarn to fetch packages from multiple registries, with support for authentication tokens. It also includes a script (`scripts/install-from-proxy-registries.sh`) to automate the process of starting the proxy server, installing dependencies, and cleaning up resources. The setup ensures seamless integration with Yarn, allowing developers to use the standard `yarn` command to install dependencies via the proxy.
270
+ This project provides a proxy server (`registry-proxy`) that allows Yarn to fetch packages from multiple registries, with support for authentication tokens. It also includes a script (`src/client/yarn-install`) to automate the process of starting the proxy server, installing dependencies, and cleaning up resources. The setup ensures seamless integration with Yarn, allowing developers to use the standard `yarn` command to install dependencies via the proxy.
280
271
 
281
272
  ## Features
282
273
 
@@ -333,167 +324,24 @@ Create a `.yarnrc.yml` file in your project root to allow Yarn to use the local
333
324
 
334
325
  ```yaml
335
326
  unsafeHttpWhitelist:
336
- - "localhost"
337
- ```
338
-
339
- ### 4. Create the Install Script
340
-
341
- Create a script at `scripts/install-from-proxy-registries.sh` to automate the proxy setup and dependency installation:
342
-
343
- ```bash
344
- #!/bin/bash
345
-
346
- # 启用严格模式,但移除 set -e,手动处理错误
347
- set -u # 未定义变量时退出
348
- set -o pipefail # 管道中任一命令失败时退出
349
-
350
- # 动态确定项目根目录(假设 package.json 所在目录为根目录)
351
- find_project_root() {
352
- local dir="$PWD"
353
- while [ "$dir" != "/" ]; do
354
- if [ -f "$dir/package.json" ]; then
355
- echo "$dir"
356
- return 0
357
- fi
358
- dir=$(dirname "$dir")
359
- done
360
- echo "Error: Could not find project root (package.json not found)" >&2
361
- exit 1
362
- }
363
-
364
- PROJECT_ROOT=$(find_project_root)
365
-
366
- # 定义锁文件和端口文件路径(固定在项目根目录)
367
- LOCK_FILE="$PROJECT_ROOT/.registry-proxy-install.lock"
368
-
369
- # 检查是否已经在运行(通过锁文件)
370
- if [ -f "$LOCK_FILE" ]; then
371
- echo "Custom install script is already running (lock file $LOCK_FILE exists)."
372
- echo "If this is unexpected, please remove $LOCK_FILE and try again."
373
- exit 0 # 内层脚本直接退出,表示任务已由外层脚本完成
374
- fi
375
-
376
- # 创建锁文件
377
- touch "$LOCK_FILE"
378
-
379
- # 清理函数,支持不同的退出状态
380
- # 参数 $1:退出状态(0 表示正常退出,1 表示异常退出)
381
- cleanup() {
382
- local exit_code=${1:-1} # 默认退出码为 1(异常退出)
383
-
384
- # 显式清除 EXIT 信号的 trap,避免潜在的误解
385
- trap - EXIT
386
-
387
- if [ "$exit_code" -eq 0 ]; then
388
- echo "Cleaning up after successful execution..."
389
- else
390
- echo "Caught interrupt signal or error, cleaning up..."
391
- fi
392
-
393
- # 清理临时文件
394
- rm -f "$LOCK_FILE" 2>/dev/null
395
- # PORT_FILE端口临时文件是registry-proxy服务器管理的文件这里不负责清理,服务器退出时会自动清理
396
- #rm -f "$PORT_FILE" 2>/dev/null
397
-
398
- # 停止代理服务器
399
- if [ -n "${PROXY_PID:-}" ]; then
400
- echo "Stopping proxy server (PID: $PROXY_PID)..."
401
- kill -TERM "$PROXY_PID" 2>/dev/null
402
- wait "$PROXY_PID" 2>/dev/null || true
403
- echo "Proxy server stopped."
404
- fi
405
-
406
- # 切换到项目根目录
407
- # shellcheck disable=SC2164
408
- cd "$PROJECT_ROOT"
409
-
410
- # 清理 npmRegistryServer 配置
411
- yarn config unset npmRegistryServer 2>/dev/null || true
412
- echo "Cleared npmRegistryServer configuration"
413
-
414
- # 根据退出状态退出
415
- exit "$exit_code"
416
- }
417
-
418
- # 注册信号处理
419
- trap 'cleanup 1' SIGINT SIGTERM EXIT # 异常退出时调用 cleanup,退出码为 1
420
-
421
- # 切换到项目根目录
422
- # shellcheck disable=SC2164
423
- cd "$PROJECT_ROOT"
424
-
425
- # 使用 yarn dlx 直接运行 registry-proxy,可通过环境变量指定registry-proxy版本号,默认是latest,registry-proxy将会被放入后台运行,并在安装结束后自动退出。
426
- REGISTRY_PROXY_VERSION="${REGISTRY_PROXY_VERSION:-latest}"
427
- echo "Starting registry-proxy@$REGISTRY_PROXY_VERSION in the background (logs will be displayed below)..."
428
- # 下载registry-proxy临时可执行程序并运行 因yarn可能会缓存tarball url的缘故(yarn.lock内<package>.resolution值),这里不得已只能写死本地代理端口地址,以便无论是从缓存获取tarball url还是从代理服务提供的元数据获取tarball url地址都能成功下载tarball文件
429
- # 但是注意 这个端口不能暴露到外部使用,只允许本地使用,避免不必要的安全隐患 事实上registry-proxy server也是只监听着::1本机端口的。
430
- yarn dlx com.jimuwd.xian.registry-proxy@"$REGISTRY_PROXY_VERSION" .registry-proxy.yml .yarnrc.yml ~/.yarnrc.yml 40061 &
431
- PROXY_PID=$!
432
-
433
- # 等待代理服务器启动并写入端口,最多 30 秒
434
- echo "Waiting for proxy server to start (up to 30 seconds)..."
435
- PORT_FILE="$PROJECT_ROOT/.registry-proxy-port"
436
- # shellcheck disable=SC2034
437
- for i in {1..300}; do # 300 次循环,每次 0.1 秒,总共 30 秒
438
- if [ -f "$PORT_FILE" ]; then
439
- PROXY_PORT=$(cat "$PORT_FILE")
440
- if [ -z "$PROXY_PORT" ]; then
441
- echo "Error: Port file $PORT_FILE is empty"
442
- cleanup 1
443
- fi
444
- if nc -z localhost "$PROXY_PORT" 2>/dev/null; then
445
- echo "Proxy server is ready on port $PROXY_PORT!"
446
- break
447
- else
448
- # 检查端口是否被占用
449
- if netstat -tuln 2>/dev/null | grep -q ":$PROXY_PORT "; then
450
- echo "Error: Port $PROXY_PORT is already in use by another process"
451
- cleanup 1
452
- fi
453
- fi
454
- fi
455
- sleep 0.1
456
- done
457
-
458
- # 检查是否成功启动
459
- if [ -z "${PROXY_PORT:-}" ] || ! nc -z localhost "$PROXY_PORT" 2>/dev/null; then
460
- echo "Error: Proxy server failed to start after 30 seconds"
461
- echo "Please check the registry-proxy logs above for more details."
462
- cleanup 1
463
- fi
464
-
465
- # 动态设置 npmRegistryServer 为代理地址 注意:yarn对“localhost”域名不友好,请直接使用 [::1]
466
- yarn config set npmRegistryServer "http://[::1]:$PROXY_PORT"
467
- echo "Set npmRegistryServer to http://[::1]:$PROXY_PORT"
468
-
469
- # 使用动态代理端口运行 yarn install,并捕获错误
470
- if ! yarn install; then
471
- echo "Error: yarn install failed"
472
- cleanup 1
473
- fi
474
-
475
- # 正常执行完成,调用 cleanup 并传入退出码 0
476
- cleanup 0
327
+ - "[::1]"
477
328
  ```
478
329
 
479
- ### 5. Set Script Permissions
330
+ ### 4. install Script
480
331
 
481
- Ensure the script is executable and commit the permission to version control:
482
-
483
- ```bash
484
- chmod +x scripts/install-from-proxy-registries.sh
485
- git add scripts/install-from-proxy-registries.sh
486
- git commit -m "Add install script with executable permission"
332
+ use below cmd to automate the proxy setup and dependency installation.
333
+ ```shell
334
+ yarn dlx -p com.jimuwd.xian.registry-proxy yarn-install
487
335
  ```
488
336
 
489
- ### 6. Integrate with Yarn
337
+ ### 5. Integrate with Yarn
490
338
 
491
339
  Update your `package.json` to run the script automatically when `yarn` is executed:
492
340
 
493
341
  ```json
494
342
  {
495
343
  "scripts": {
496
- "preinstall": "bash scripts/install-from-proxy-registries.sh",
344
+ "preinstall": "yarn dlx -p com.jimuwd.xian.registry-proxy yarn-install",
497
345
  "install": "echo 'Custom install script is running via preinstall, skipping default install.'"
498
346
  }
499
347
  }
@@ -160,7 +160,7 @@ async function fetchFromRegistry(registry, targetUrl, reqFromDownstreamClient, l
160
160
  limiter.release();
161
161
  }
162
162
  }
163
- async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDownstreamClient, upstreamResponse, reqFromDownstreamClient, proxyInfo, proxyPort, registryInfos) {
163
+ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDownstreamClient, upstreamResponse, reqFromDownstreamClient, proxyInfo, _proxyPort, registryInfos) {
164
164
  logger.info(`Writing upstream registry server ${registryInfo.normalizedRegistryUrl}'s ${upstreamResponse.status}${upstreamResponse.statusText ? (' "' + upstreamResponse.statusText + '"') : ''} response to downstream client.`);
165
165
  if (!upstreamResponse.ok)
166
166
  throw new Error("Only 2xx upstream response is supported");
@@ -174,7 +174,7 @@ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDow
174
174
  const data = await upstreamResponse.json();
175
175
  if (data.versions) { // 处理node依赖包元数据
176
176
  logger.info("Write package meta data application/json response from upstream to downstream", targetUrl);
177
- const host = reqFromDownstreamClient.headers.host /*|| `[::1]:${proxyPort}`*/;
177
+ const host = reqFromDownstreamClient.headers.host /*|| `[::1]:${_proxyPort}`*/;
178
178
  const baseUrl = `${proxyInfo.https ? 'https' : 'http'}://${host}${proxyInfo.basePath === '/' ? '' : proxyInfo.basePath}`;
179
179
  for (const versionKey in data.versions) {
180
180
  const packageVersion = data.versions[versionKey];
@@ -190,10 +190,11 @@ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDow
190
190
  logger.info("Write none meta data application/json response from upstream to downstream", targetUrl);
191
191
  }
192
192
  const bodyData = JSON.stringify(data);
193
- resToDownstreamClient.removeHeader('Transfer-Encoding');
194
- // 默认是 connection: keep-alive 和 keep-alive: timeout=5,这里直接给它咔嚓掉
195
- resToDownstreamClient.setHeader('Connection', 'close');
196
- resToDownstreamClient.removeHeader('Keep-Alive');
193
+ // remove transfer-encoding = chunked header if present, because the content-length is fixed.
194
+ resToDownstreamClient.removeHeader('transfer-encoding');
195
+ /* 默认是 connection: keep-alive 和 keep-alive: timeout=5
196
+ resToDownstreamClient.setHeader('connection', 'close');
197
+ resToDownstreamClient.removeHeader('Keep-Alive');*/
197
198
  resToDownstreamClient.setHeader('content-type', contentType);
198
199
  resToDownstreamClient.setHeader('content-length', Buffer.byteLength(bodyData));
199
200
  logger.info(`Response to downstream client headers`, JSON.stringify(resToDownstreamClient.getHeaders()), targetUrl);
@@ -207,41 +208,33 @@ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDow
207
208
  }
208
209
  else {
209
210
  // write back to client
210
- // 准备通用响应头信息
211
211
  const safeHeaders = new Map();
212
- safeHeaders.set("Content-Type", contentType);
213
212
  // 复制所有可能需要的头信息(不包含安全相关的敏感头信息,如access-control-allow-origin、set-cookie、server、strict-transport-security等,这意味着代理服务器向下游客户端屏蔽了这些认证等安全数据)
214
213
  // 也不能包含cf-cache-status、cf-ray(Cloudflare 特有字段)可能干扰客户端解析。
215
- const headersToCopy = ['cache-control', 'connection', 'content-encoding', 'content-length', /*'date',*/ 'etag', 'last-modified', 'transfer-encoding', 'vary',];
214
+ const headersToCopy = ['cache-control', 'etag', 'last-modified', 'vary', 'connection', 'keep-alive', 'content-encoding'];
216
215
  headersToCopy.forEach(header => {
217
216
  const value = upstreamResponse.headers.get(header);
218
217
  if (value)
219
218
  safeHeaders.set(header, value);
220
219
  });
221
- // 必须使用 ServerResponse.setHeaders(safeHeaders)来覆盖现有headers而不是ServerResponse.writeHead(status,headers)来合并headers
222
- // 这个坑害我浪费很久事件来调试!
220
+ // 强制设置二进制流传输的响应头,需要使用 ServerResponse.setHeaders(safeHeaders)来覆盖现有headers而不是ServerResponse.writeHead(status,headers)来合并headers,避免不必要的麻烦
223
221
  resToDownstreamClient.setHeaders(safeHeaders);
224
- // 调试代码
225
- resToDownstreamClient.removeHeader('content-encoding');
226
- resToDownstreamClient.removeHeader('Transfer-Encoding');
222
+ resToDownstreamClient.setHeader("content-type", contentType);
227
223
  resToDownstreamClient.removeHeader('content-length');
228
224
  resToDownstreamClient.setHeader('transfer-encoding', 'chunked');
229
- // 默认是 connection: keep-alive 和 keep-alive: timeout=5,这里直接给它咔嚓掉
230
- resToDownstreamClient.removeHeader('connection');
225
+ /* 这两个header使用upstream透传过来的header即可
231
226
  resToDownstreamClient.setHeader('connection', 'close');
232
- resToDownstreamClient.removeHeader('Keep-Alive');
233
- resToDownstreamClient.removeHeader('content-type');
234
- resToDownstreamClient.setHeader('content-type', contentType);
227
+ resToDownstreamClient.removeHeader('Keep-Alive');*/
235
228
  logger.info(`Response to downstream client headers`, JSON.stringify(resToDownstreamClient.getHeaders()), targetUrl);
236
229
  // 不再writeHead()而是设置状态码,然后执行pipe操作
237
230
  resToDownstreamClient.statusCode = upstreamResponse.status;
238
231
  resToDownstreamClient.statusMessage = upstreamResponse.statusText;
239
- // resToDownstreamClient.writeHead(upstreamResponse.status);
240
232
  // stop pipe when req from client is closed accidentally.
233
+ // this is good when proxying big stream from upstream to downstream.
241
234
  const cleanup = () => {
242
235
  reqFromDownstreamClient.off('close', cleanup);
243
236
  logger.info(`Req from downstream client is closed, stop pipe from upstream ${targetUrl} to downstream client.`);
244
- // upstreamResponse.body?.unpipe();
237
+ upstreamResponse.body?.unpipe();
245
238
  };
246
239
  reqFromDownstreamClient.on('close', cleanup);
247
240
  reqFromDownstreamClient.on('end', () => logger.info("Req from downstream client ends."));
@@ -253,20 +246,15 @@ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDow
253
246
  };
254
247
  resToDownstreamClient.on('close', cleanup0);
255
248
  // write back body data (chunked probably)
256
- // pipe upstream body to downstream client
249
+ // pipe upstream body-stream to downstream stream and automatically ends the stream to downstream when upstream stream is ended.
257
250
  upstreamResponse.body.pipe(resToDownstreamClient, { end: true });
258
251
  upstreamResponse.body
259
252
  .on('data', (chunk) => logger.debug(`Chunk transferred from ${targetUrl} to downstream client size=${chunk.length}`))
260
- .on('end', () => {
261
- logger.info(`Upstream server ${targetUrl} response.body ended.`);
262
- // resToDownstreamClient.end();
263
- })
253
+ .on('end', () => logger.info(`Upstream server ${targetUrl} response.body ended.`))
264
254
  // connection will be closed automatically when all chunk data is transferred (after stream ends).
265
- .on('close', () => {
266
- logger.info(`Upstream server ${targetUrl} closed connection.`);
267
- })
255
+ .on('close', () => logger.info(`Upstream server ${targetUrl} closed connection.`))
268
256
  .on('error', (err) => {
269
- const errMsg = `Stream error: ${err.message}`;
257
+ const errMsg = `Stream error between upstream and registry-proxy server: ${err.message}. Upstream url is ${targetUrl}`;
270
258
  logger.error(errMsg);
271
259
  resToDownstreamClient.destroy(new Error(errMsg, { cause: err, }));
272
260
  reqFromDownstreamClient.destroy(new Error(errMsg, { cause: err, }));
@@ -274,15 +262,15 @@ async function writeResponseToDownstreamClient(registryInfo, targetUrl, resToDow
274
262
  }
275
263
  }
276
264
  else {
277
- logger.warn(`Write unsupported content-type=${contentType} response from upstream to downstream ${targetUrl}`);
265
+ logger.warn(`Write unsupported content-type=${contentType} response from upstream to downstream. Upstream url is ${targetUrl}`);
278
266
  const bodyData = await upstreamResponse.text();
279
- resToDownstreamClient.removeHeader('Transfer-Encoding');
267
+ resToDownstreamClient.removeHeader('transfer-encoding');
280
268
  // 默认是 connection: keep-alive 和 keep-alive: timeout=5,这里直接给它咔嚓掉
281
- resToDownstreamClient.setHeader('Connection', 'close');
269
+ resToDownstreamClient.setHeader('connection', 'close');
282
270
  resToDownstreamClient.removeHeader('Keep-Alive');
283
271
  resToDownstreamClient.setHeader('content-type', contentType);
284
272
  resToDownstreamClient.setHeader('content-length', Buffer.byteLength(bodyData));
285
- logger.info(`Response to downstream client headers`, JSON.stringify(resToDownstreamClient.getHeaders()), targetUrl);
273
+ logger.info(`Response to downstream client headers`, JSON.stringify(resToDownstreamClient.getHeaders()), `Upstream url is ${targetUrl}`);
286
274
  resToDownstreamClient.writeHead(upstreamResponse.status).end(bodyData);
287
275
  }
288
276
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "com.jimuwd.xian.registry-proxy",
3
- "version": "1.0.133",
3
+ "version": "1.0.134",
4
4
  "description": "A lightweight npm registry proxy with fallback support",
5
5
  "type": "module",
6
6
  "main": "dist/server/index.js",