@lobehub/chat 1.20.4 → 1.20.5

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/CHANGELOG.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 1.20.5](https://github.com/lobehub/lobe-chat/compare/v1.20.4...v1.20.5)
6
+
7
+ <sup>Released on **2024-09-29**</sup>
8
+
9
+ <br/>
10
+
11
+ <details>
12
+ <summary><kbd>Improvements and Fixes</kbd></summary>
13
+
14
+ </details>
15
+
16
+ <div align="right">
17
+
18
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
19
+
20
+ </div>
21
+
5
22
  ### [Version 1.20.4](https://github.com/lobehub/lobe-chat/compare/v1.20.3...v1.20.4)
6
23
 
7
24
  <sup>Released on **2024-09-28**</sup>
package/Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
- ## Base image for all the stages
1
+ ## Base image for all building stages
2
2
  FROM node:20-slim AS base
3
3
 
4
4
  ARG USE_CN_MIRROR
@@ -10,19 +10,22 @@ RUN \
10
10
  if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \
11
11
  sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" "/etc/apt/sources.list.d/debian.sources"; \
12
12
  fi \
13
- # Add required package & update base package
13
+ # Add required package
14
14
  && apt update \
15
- && apt install busybox proxychains-ng -qy \
16
- && apt full-upgrade -qy \
17
- && apt autoremove -qy --purge \
18
- && apt clean -qy \
19
- # Configure BusyBox
20
- && busybox --install -s \
21
- # Add nextjs:nodejs to run the app
22
- && addgroup --system --gid 1001 nodejs \
23
- && adduser --system --home "/app" --gid 1001 -uid 1001 nextjs \
24
- # Set permission for nextjs:nodejs
25
- && chown -R nextjs:nodejs "/etc/proxychains4.conf" \
15
+ && apt install ca-certificates proxychains-ng -qy \
16
+ # Prepare required package to distroless
17
+ && mkdir -p /distroless/bin /distroless/etc /distroless/etc/ssl/certs /distroless/lib \
18
+ # Copy proxychains to distroless
19
+ && cp /usr/lib/$(arch)-linux-gnu/libproxychains.so.4 /distroless/lib/libproxychains.so.4 \
20
+ && cp /usr/lib/$(arch)-linux-gnu/libdl.so.2 /distroless/lib/libdl.so.2 \
21
+ && cp /usr/bin/proxychains4 /distroless/bin/proxychains \
22
+ && cp /etc/proxychains4.conf /distroless/etc/proxychains4.conf \
23
+ # Copy node to distroless
24
+ && cp /usr/lib/$(arch)-linux-gnu/libstdc++.so.6 /distroless/lib/libstdc++.so.6 \
25
+ && cp /usr/lib/$(arch)-linux-gnu/libgcc_s.so.1 /distroless/lib/libgcc_s.so.1 \
26
+ && cp /usr/local/bin/node /distroless/bin/node \
27
+ # Copy CA certificates to distroless
28
+ && cp /etc/ssl/certs/ca-certificates.crt /distroless/etc/ssl/certs/ca-certificates.crt \
26
29
  # Cleanup temp files
27
30
  && rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/*
28
31
 
@@ -61,6 +64,7 @@ RUN \
61
64
  if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \
62
65
  export SENTRYCLI_CDNURL="https://npmmirror.com/mirrors/sentry-cli"; \
63
66
  npm config set registry "https://registry.npmmirror.com/"; \
67
+ echo 'canvas_binary_host_mirror=https://npmmirror.com/mirrors/canvas' >> .npmrc; \
64
68
  fi \
65
69
  # Set the registry for corepack
66
70
  && export COREPACK_NPM_REGISTRY=$(npm config get registry | sed 's/\/$//') \
@@ -80,7 +84,9 @@ COPY . .
80
84
  RUN npm run build:docker
81
85
 
82
86
  ## Application image, copy all the files for production
83
- FROM scratch AS app
87
+ FROM busybox:latest AS app
88
+
89
+ COPY --from=base /distroless/ /
84
90
 
85
91
  COPY --from=builder /app/public /app/public
86
92
 
@@ -90,13 +96,25 @@ COPY --from=builder /app/.next/standalone /app/
90
96
  COPY --from=builder /app/.next/static /app/.next/static
91
97
  COPY --from=builder /deps/node_modules/.pnpm /app/node_modules/.pnpm
92
98
 
99
+ # Copy server launcher
100
+ COPY --from=builder /app/scripts/serverLauncher/startServer.js /app/startServer.js
101
+
102
+ RUN \
103
+ # Add nextjs:nodejs to run the app
104
+ addgroup -S -g 1001 nodejs \
105
+ && adduser -D -G nodejs -H -S -h /app -u 1001 nextjs \
106
+ # Set permission for nextjs:nodejs
107
+ && chown -R nextjs:nodejs /app /etc/proxychains4.conf
108
+
93
109
  ## Production image, copy all the files and run next
94
- FROM base
110
+ FROM scratch
95
111
 
96
112
  # Copy all the files from app, set the correct permission for prerender cache
97
- COPY --from=app --chown=nextjs:nodejs /app /app
113
+ COPY --from=app / /
98
114
 
99
115
  ENV NODE_ENV="production" \
116
+ NODE_OPTIONS="--use-openssl-ca" \
117
+ NODE_EXTRA_CA_CERTS="/etc/ssl/certs/ca-certificates.crt" \
100
118
  NODE_TLS_REJECT_UNAUTHORIZED=""
101
119
 
102
120
  # set hostname to localhost
@@ -176,36 +194,6 @@ USER nextjs
176
194
 
177
195
  EXPOSE 3210/tcp
178
196
 
179
- CMD \
180
- if [ -n "$PROXY_URL" ]; then \
181
- # Set regex for IPv4
182
- IP_REGEX="^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$"; \
183
- # Set proxychains command
184
- PROXYCHAINS="proxychains -q"; \
185
- # Parse the proxy URL
186
- host_with_port="${PROXY_URL#*//}"; \
187
- host="${host_with_port%%:*}"; \
188
- port="${PROXY_URL##*:}"; \
189
- protocol="${PROXY_URL%%://*}"; \
190
- # Resolve to IP address if the host is a domain
191
- if ! [[ "$host" =~ "$IP_REGEX" ]]; then \
192
- nslookup=$(nslookup -q="A" "$host" | tail -n +3 | grep 'Address:'); \
193
- if [ -n "$nslookup" ]; then \
194
- host=$(echo "$nslookup" | tail -n 1 | awk '{print $2}'); \
195
- fi; \
196
- fi; \
197
- # Generate proxychains configuration file
198
- printf "%s\n" \
199
- 'localnet 127.0.0.0/255.0.0.0' \
200
- 'localnet ::1/128' \
201
- 'proxy_dns' \
202
- 'remote_dns_subnet 224' \
203
- 'strict_chain' \
204
- 'tcp_connect_time_out 8000' \
205
- 'tcp_read_time_out 15000' \
206
- '[ProxyList]' \
207
- "$protocol $host $port" \
208
- > "/etc/proxychains4.conf"; \
209
- fi; \
210
- # Run the server
211
- ${PROXYCHAINS} node "/app/server.js";
197
+ ENTRYPOINT ["/bin/node"]
198
+
199
+ CMD ["/app/startServer.js"]
@@ -1,4 +1,4 @@
1
- ## Base image for all the stages
1
+ ## Base image for all building stages
2
2
  FROM node:20-slim AS base
3
3
 
4
4
  ARG USE_CN_MIRROR
@@ -10,19 +10,22 @@ RUN \
10
10
  if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \
11
11
  sed -i "s/deb.debian.org/mirrors.ustc.edu.cn/g" "/etc/apt/sources.list.d/debian.sources"; \
12
12
  fi \
13
- # Add required package & update base package
13
+ # Add required package
14
14
  && apt update \
15
- && apt install busybox proxychains-ng -qy \
16
- && apt full-upgrade -qy \
17
- && apt autoremove -qy --purge \
18
- && apt clean -qy \
19
- # Configure BusyBox
20
- && busybox --install -s \
21
- # Add nextjs:nodejs to run the app
22
- && addgroup --system --gid 1001 nodejs \
23
- && adduser --system --home "/app" --gid 1001 -uid 1001 nextjs \
24
- # Set permission for nextjs:nodejs
25
- && chown -R nextjs:nodejs "/etc/proxychains4.conf" \
15
+ && apt install ca-certificates proxychains-ng -qy \
16
+ # Prepare required package to distroless
17
+ && mkdir -p /distroless/bin /distroless/etc /distroless/etc/ssl/certs /distroless/lib \
18
+ # Copy proxychains to distroless
19
+ && cp /usr/lib/$(arch)-linux-gnu/libproxychains.so.4 /distroless/lib/libproxychains.so.4 \
20
+ && cp /usr/lib/$(arch)-linux-gnu/libdl.so.2 /distroless/lib/libdl.so.2 \
21
+ && cp /usr/bin/proxychains4 /distroless/bin/proxychains \
22
+ && cp /etc/proxychains4.conf /distroless/etc/proxychains4.conf \
23
+ # Copy node to distroless
24
+ && cp /usr/lib/$(arch)-linux-gnu/libstdc++.so.6 /distroless/lib/libstdc++.so.6 \
25
+ && cp /usr/lib/$(arch)-linux-gnu/libgcc_s.so.1 /distroless/lib/libgcc_s.so.1 \
26
+ && cp /usr/local/bin/node /distroless/bin/node \
27
+ # Copy CA certificates to distroless
28
+ && cp /etc/ssl/certs/ca-certificates.crt /distroless/etc/ssl/certs/ca-certificates.crt \
26
29
  # Cleanup temp files
27
30
  && rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/*
28
31
 
@@ -65,6 +68,7 @@ RUN \
65
68
  if [ "${USE_CN_MIRROR:-false}" = "true" ]; then \
66
69
  export SENTRYCLI_CDNURL="https://npmmirror.com/mirrors/sentry-cli"; \
67
70
  npm config set registry "https://registry.npmmirror.com/"; \
71
+ echo 'canvas_binary_host_mirror=https://npmmirror.com/mirrors/canvas' >> .npmrc; \
68
72
  fi \
69
73
  # Set the registry for corepack
70
74
  && export COREPACK_NPM_REGISTRY=$(npm config get registry | sed 's/\/$//') \
@@ -84,7 +88,9 @@ COPY . .
84
88
  RUN npm run build:docker
85
89
 
86
90
  ## Application image, copy all the files for production
87
- FROM scratch AS app
91
+ FROM busybox:latest AS app
92
+
93
+ COPY --from=base /distroless/ /
88
94
 
89
95
  COPY --from=builder /app/public /app/public
90
96
 
@@ -103,13 +109,25 @@ COPY --from=builder /app/src/database/server/migrations /app/migrations
103
109
  COPY --from=builder /app/scripts/migrateServerDB/docker.cjs /app/docker.cjs
104
110
  COPY --from=builder /app/scripts/migrateServerDB/errorHint.js /app/errorHint.js
105
111
 
112
+ # Copy server launcher
113
+ COPY --from=builder /app/scripts/serverLauncher/startServer.js /app/startServer.js
114
+
115
+ RUN \
116
+ # Add nextjs:nodejs to run the app
117
+ addgroup -S -g 1001 nodejs \
118
+ && adduser -D -G nodejs -H -S -h /app -u 1001 nextjs \
119
+ # Set permission for nextjs:nodejs
120
+ && chown -R nextjs:nodejs /app /etc/proxychains4.conf
121
+
106
122
  ## Production image, copy all the files and run next
107
- FROM base
123
+ FROM scratch
108
124
 
109
125
  # Copy all the files from app, set the correct permission for prerender cache
110
- COPY --from=app --chown=nextjs:nodejs /app /app
126
+ COPY --from=app / /
111
127
 
112
128
  ENV NODE_ENV="production" \
129
+ NODE_OPTIONS="--use-openssl-ca" \
130
+ NODE_EXTRA_CA_CERTS="/etc/ssl/certs/ca-certificates.crt" \
113
131
  NODE_TLS_REJECT_UNAUTHORIZED=""
114
132
 
115
133
  # set hostname to localhost
@@ -208,40 +226,6 @@ USER nextjs
208
226
 
209
227
  EXPOSE 3210/tcp
210
228
 
211
- CMD \
212
- if [ -n "$PROXY_URL" ]; then \
213
- # Set regex for IPv4
214
- IP_REGEX="^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$"; \
215
- # Set proxychains command
216
- PROXYCHAINS="proxychains -q"; \
217
- # Parse the proxy URL
218
- host_with_port="${PROXY_URL#*//}"; \
219
- host="${host_with_port%%:*}"; \
220
- port="${PROXY_URL##*:}"; \
221
- protocol="${PROXY_URL%%://*}"; \
222
- # Resolve to IP address if the host is a domain
223
- if ! [[ "$host" =~ "$IP_REGEX" ]]; then \
224
- nslookup=$(nslookup -q="A" "$host" | tail -n +3 | grep 'Address:'); \
225
- if [ -n "$nslookup" ]; then \
226
- host=$(echo "$nslookup" | tail -n 1 | awk '{print $2}'); \
227
- fi; \
228
- fi; \
229
- # Generate proxychains configuration file
230
- printf "%s\n" \
231
- 'localnet 127.0.0.0/255.0.0.0' \
232
- 'localnet ::1/128' \
233
- 'proxy_dns' \
234
- 'remote_dns_subnet 224' \
235
- 'strict_chain' \
236
- 'tcp_connect_time_out 8000' \
237
- 'tcp_read_time_out 15000' \
238
- '[ProxyList]' \
239
- "$protocol $host $port" \
240
- > "/etc/proxychains4.conf"; \
241
- fi; \
242
- # Run migration
243
- node "/app/docker.cjs"; \
244
- if [ "$?" -eq "0" ]; then \
245
- # Run the server
246
- ${PROXYCHAINS} node "/app/server.js"; \
247
- fi;
229
+ ENTRYPOINT ["/bin/node"]
230
+
231
+ CMD ["/app/startServer.js"]
@@ -88,7 +88,7 @@ docker compose up -d
88
88
  - `Redirect URI` should be `http://localhost:3210/api/auth/callback/logto`
89
89
  - `Post sign-out redirect URI` should be `http://localhost:3210/`
90
90
 
91
- 3. Obtain the `App ID` and `App secrets`, and fill them into your `.env` file corresponding to `LOGTO_CLIENT_ID` and `LOGTO_CLIENT_SECRET`.
91
+ 3. Obtain the `App ID` and `App secrets`, and fill them into your `.env` file corresponding to `AUTH_LOGTO_ID` and `AUTH_LOGTO_SECRET`.
92
92
 
93
93
  ### Configure MinIO S3
94
94
 
@@ -258,9 +258,9 @@ You need to first access the WebUI for configuration:
258
258
  src="https://github.com/user-attachments/assets/5b816379-c07b-40ea-bde4-df16e2e4e523"
259
259
  />
260
260
 
261
- 5. Obtain `App ID` and `App secrets`, and fill them into your `.env` file under `LOGTO_CLIENT_ID` and `LOGTO_CLIENT_SECRET`.
261
+ 5. Obtain `App ID` and `App secrets`, and fill them into your `.env` file under `AUTH_LOGTO_ID` and `AUTH_LOGTO_SECRET`.
262
262
 
263
- 6. Set `LOGTO_ISSUER` in your `.env` file to `https://lobe-auth-api.example.com/oidc`.
263
+ 6. Set `AUTH_LOGTO_ISSUER` in your `.env` file to `https://lobe-auth-api.example.com/oidc`.
264
264
 
265
265
  <Image
266
266
  alt="Configure environment variables"
@@ -349,8 +349,8 @@ To facilitate one-click copying, here are the example configuration files needed
349
349
 
350
350
  ```sh
351
351
  # Logto secret
352
- LOGTO_CLIENT_ID=
353
- LOGTO_CLIENT_SECRET=
352
+ AUTH_LOGTO_ID=
353
+ AUTH_LOGTO_SECRET=
354
354
 
355
355
  # MinIO S3 configuration
356
356
  MINIO_ROOT_USER=YOUR_MINIO_USER
@@ -467,7 +467,7 @@ services:
467
467
  - 'KEY_VAULTS_SECRET=Kix2wcUONd4CX51E/ZPAd36BqM4wzJgKjPtz2sGztqQ='
468
468
  - 'NEXT_AUTH_SECRET=NX2kaPE923dt6BL2U8e9oSre5RfoT7hg'
469
469
  - 'NEXTAUTH_URL=http://localhost:${LOBE_PORT}/api/auth'
470
- - 'LOGTO_ISSUER=http://localhost:${LOGTO_PORT}/oidc'
470
+ - 'AUTH_LOGTO_ISSUER=http://localhost:${LOGTO_PORT}/oidc'
471
471
  - 'DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgresql:5432/${LOBE_DB_NAME}'
472
472
  - 'S3_ENDPOINT=http://localhost:${MINIO_PORT}'
473
473
  - 'S3_BUCKET=${MINIO_LOBE_BUCKET}'
@@ -519,9 +519,9 @@ NEXTAUTH_URL=https://lobe.example.com/api/auth
519
519
 
520
520
  # NextAuth providers configuration (example using Logto)
521
521
  # For other providers, see: https://lobehub.com/docs/self-hosting/environment-variables/auth
522
- LOGTO_CLIENT_ID=YOUR_LOGTO_CLIENT_ID
523
- LOGTO_CLIENT_SECRET=YOUR_LOGTO_CLIENT_SECRET
524
- LOGTO_ISSUER=https://lobe-auth-api.example.com/oidc
522
+ AUTH_LOGTO_ID=YOUR_LOGTO_CLIENT_ID
523
+ AUTH_LOGTO_SECRET=YOUR_LOGTO_CLIENT_SECRET
524
+ AUTH_LOGTO_ISSUER=https://lobe-auth-api.example.com/oidc
525
525
 
526
526
  # Proxy settings (if needed, e.g., when using GitHub as an auth provider)
527
527
  # HTTP_PROXY=http://localhost:7890
@@ -86,7 +86,7 @@ docker compose up -d
86
86
  - `Redirect URI` 为 `http://localhost:3210/api/auth/callback/logto`
87
87
  - `Post sign-out redirect URI` 为 `http://localhost:3210/`
88
88
 
89
- 3. 获取 `App ID` 和 `App secrets`,填入 `.env` 文件中对应的 `LOGTO_CLIENT_ID` 、 `LOGTO_CLIENT_SECRETT`
89
+ 3. 获取 `App ID` 和 `App secrets`,填入 `.env` 文件中对应的 `AUTH_LOGTO_ID` 、 `AUTH_LOGTO_SECRET`
90
90
 
91
91
  ### 配置 MinIO S3
92
92
 
@@ -256,9 +256,9 @@ docker compose up -d # 重新启动
256
256
  src="https://github.com/user-attachments/assets/5b816379-c07b-40ea-bde4-df16e2e4e523"
257
257
  />
258
258
 
259
- 5. 获取 `App ID` 和 `App secrets`,填入你的 `.env` 文件中的 `LOGTO_CLIENT_ID` 和 `LOGTO_CLIENT_SECRETT` 中
259
+ 5. 获取 `App ID` 和 `App secrets`,填入你的 `.env` 文件中的 `AUTH_LOGTO_ID` 和 `AUTH_LOGTO_SECRET` 中
260
260
 
261
- 6. 配置你的 `.env` 文件中 `LOGTO_ISSUER` 为 `https://lobe-auth-api.example.com/oidc`
261
+ 6. 配置你的 `.env` 文件中 `AUTH_LOGTO_ISSUER` 为 `https://lobe-auth-api.example.com/oidc`
262
262
 
263
263
  <Image
264
264
  alt="配置 Logto 环境变量"
@@ -346,8 +346,8 @@ docker compose up -d # 重新启动
346
346
 
347
347
  ```sh
348
348
  # Logto secret
349
- LOGTO_CLIENT_ID=
350
- LOGTO_CLIENT_SECRET=
349
+ AUTH_LOGTO_ID=
350
+ AUTH_LOGTO_SECRET=
351
351
 
352
352
  # MinIO S3 配置
353
353
  MINIO_ROOT_USER=YOUR_MINIO_USER
@@ -464,7 +464,7 @@ services:
464
464
  - 'KEY_VAULTS_SECRET=Kix2wcUONd4CX51E/ZPAd36BqM4wzJgKjPtz2sGztqQ='
465
465
  - 'NEXT_AUTH_SECRET=NX2kaPE923dt6BL2U8e9oSre5RfoT7hg'
466
466
  - 'NEXTAUTH_URL=http://localhost:${LOBE_PORT}/api/auth'
467
- - 'LOGTO_ISSUER=http://localhost:${LOGTO_PORT}/oidc'
467
+ - 'AUTH_LOGTO_ISSUER=http://localhost:${LOGTO_PORT}/oidc'
468
468
  - 'DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgresql:5432/${LOBE_DB_NAME}'
469
469
  - 'S3_ENDPOINT=http://localhost:${MINIO_PORT}'
470
470
  - 'S3_BUCKET=${MINIO_LOBE_BUCKET}'
@@ -515,9 +515,9 @@ NEXTAUTH_URL=https://lobe.example.com/api/auth
515
515
 
516
516
  # NextAuth 鉴权服务提供商部分,以 Logto 为例
517
517
  # 其他鉴权服务提供商所需的环境变量,请参考:https://lobehub.com/zh/docs/self-hosting/environment-variables/auth
518
- LOGTO_CLIENT_ID=YOUR_LOGTO_CLIENT_ID
519
- LOGTO_CLIENT_SECRET=YOUR_LOGTO_CLIENT_SECRET
520
- LOGTO_ISSUER=https://lobe-auth-api.example.com/oidc
518
+ AUTH_LOGTO_ID=YOUR_LOGTO_CLIENT_ID
519
+ AUTH_LOGTO_SECRET=YOUR_LOGTO_CLIENT_SECRET
520
+ AUTH_LOGTO_ISSUER=https://lobe-auth-api.example.com/oidc
521
521
 
522
522
  # 代理相关,如果你需要的话(比如你使用 GitHub 作为鉴权服务提供商)
523
523
  # HTTP_PROXY=http://localhost:7890
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "1.20.4",
3
+ "version": "1.20.5",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -0,0 +1,181 @@
1
+ const dns = require('dns').promises;
2
+ const fs = require('fs');
3
+ const tls = require('tls');
4
+ const { spawn } = require('child_process');
5
+
6
+ // Set file paths
7
+ const DB_MIGRATION_SCRIPT_PATH = '/app/docker.cjs';
8
+ const SERVER_SCRIPT_PATH = '/app/server.js';
9
+ const PROXYCHAINS_CONF_PATH = '/etc/proxychains4.conf';
10
+
11
+ // Function to check if a string is a valid IP address
12
+ const isValidIP = (ip, version = 4) => {
13
+ const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/;
14
+ const ipv6Regex = /^(([0-9a-f]{1,4}:){7,7}[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,7}:|([0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,5}(:[0-9a-f]{1,4}){1,2}|([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{1,4}){1,3}|([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}|([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}|[0-9a-f]{1,4}:((:[0-9a-f]{1,4}){1,6})|:((:[0-9a-f]{1,4}){1,7}|:)|fe80:(:[0-9a-f]{0,4}){0,4}%[0-9a-z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-f]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
15
+
16
+ switch (version) {
17
+ case 4:
18
+ return ipv4Regex.test(ip);
19
+ case 6:
20
+ return ipv6Regex.test(ip);
21
+ default:
22
+ return ipv4Regex.test(ip) || ipv6Regex.test(ip);
23
+ }
24
+ };
25
+
26
+ // Function to check TLS validity of a URL
27
+ const isValidTLS = (url = '') => {
28
+ if (!url) {
29
+ console.log('⚠️ TLS Check: No URL provided. Skipping TLS check. Ensure correct setting ENV.');
30
+ console.log('-------------------------------------');
31
+ return Promise.resolve();
32
+ }
33
+
34
+ const { protocol, host, port } = parseUrl(url);
35
+ if (protocol !== 'https') {
36
+ console.log(`⚠️ TLS Check: Non-HTTPS protocol (${protocol}). Skipping TLS check for ${url}.`);
37
+ console.log('-------------------------------------');
38
+ return Promise.resolve();
39
+ }
40
+
41
+ const options = { host, port, servername: host };
42
+ return new Promise((resolve, reject) => {
43
+ const socket = tls.connect(options, () => {
44
+ if (socket.authorized) {
45
+ console.log(`✅ TLS Check: Valid certificate for ${host}:${port}.`);
46
+ console.log('-------------------------------------');
47
+ resolve();
48
+ }
49
+ socket.end();
50
+ });
51
+
52
+ socket.on('error', (err) => {
53
+ const errMsg = `❌ TLS Check: Error for ${host}:${port}. Details:`;
54
+ switch (err.code) {
55
+ case 'CERT_HAS_EXPIRED':
56
+ case 'DEPTH_ZERO_SELF_SIGNED_CERT':
57
+ console.error(`${errMsg} Certificate is not valid. Consider setting NODE_TLS_REJECT_UNAUTHORIZED="0" or mapping /etc/ssl/certs/ca-certificates.crt.`);
58
+ break;
59
+ case 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY':
60
+ console.error(`${errMsg} Unable to verify issuer. Ensure correct mapping of /etc/ssl/certs/ca-certificates.crt.`);
61
+ break;
62
+ default:
63
+ console.error(`${errMsg} Network issue. Check firewall or DNS.`);
64
+ break;
65
+ }
66
+ reject(err);
67
+ });
68
+ });
69
+ };
70
+
71
+ // Function to check TLS connections for OSS and Auth Issuer
72
+ const checkTLSConnections = async () => {
73
+ await Promise.all([
74
+ isValidTLS(process.env.S3_ENDPOINT),
75
+ isValidTLS(process.env.S3_PUBLIC_DOMAIN),
76
+ isValidTLS(getEnvVarsByKeyword('_ISSUER')),
77
+ ]);
78
+ };
79
+
80
+ // Function to get environment variable by keyword
81
+ const getEnvVarsByKeyword = (keyword) => {
82
+ return Object.entries(process.env)
83
+ .filter(([key, value]) => key.includes(keyword) && value)
84
+ .map(([, value]) => value)[0] || null;
85
+ };
86
+
87
+ // Function to parse protocol, host and port from a URL
88
+ const parseUrl = (url) => {
89
+ const { protocol, hostname: host, port } = new URL(url);
90
+ return { protocol: protocol.replace(':', ''), host, port: port || 443 };
91
+ };
92
+
93
+ // Function to resolve host IP via DNS
94
+ const resolveHostIP = async (host, version = 4) => {
95
+ try {
96
+ const { address } = await dns.lookup(host, { family: version });
97
+
98
+ if (!isValidIP(address, version)) {
99
+ console.error(`❌ DNS Error: Invalid resolved IP: ${address}. IP address must be IPv${version}.`);
100
+ process.exit(1);
101
+ }
102
+
103
+ return address;
104
+ } catch (err) {
105
+ console.error(`❌ DNS Error: Could not resolve ${host}. Check DNS server.`, err);
106
+ process.exit(1);
107
+ }
108
+ };
109
+
110
+ // Function to generate proxychains configuration
111
+ const runProxyChainsConfGenerator = async (url) => {
112
+ const { protocol, host, port } = parseUrl(url);
113
+
114
+ if (!['http', 'socks4', 'socks5'].includes(protocol)) {
115
+ console.error(`❌ ProxyChains: Invalid protocol (${protocol}). Protocol must be 'http', 'socks4' and 'socks5'.`);
116
+ process.exit(1);
117
+ }
118
+
119
+ const validPort = parseInt(port, 10);
120
+ if (isNaN(validPort) || validPort <= 0 || validPort > 65535) {
121
+ console.error(`❌ ProxyChains: Invalid port (${port}). Port must be a number between 1 and 65535.`);
122
+ process.exit(1);
123
+ }
124
+
125
+ let ip = isValidIP(host, 4) ? host : await resolveHostIP(host, 4);
126
+
127
+ const configContent = `
128
+ localnet 127.0.0.0/255.0.0.0
129
+ localnet ::1/128
130
+ proxy_dns
131
+ remote_dns_subnet 224
132
+ strict_chain
133
+ tcp_connect_time_out 8000
134
+ tcp_read_time_out 15000
135
+ [ProxyList]
136
+ ${protocol} ${ip} ${port}
137
+ `.trim();
138
+
139
+ fs.writeFileSync(PROXYCHAINS_CONF_PATH, configContent);
140
+ console.log(`✅ ProxyChains: All outgoing traffic routed via ${protocol}://${ip}:${port}.`);
141
+ console.log('-------------------------------------');
142
+ };
143
+
144
+ // Function to execute a script with child process spawn
145
+ const runScript = (scriptPath, useProxy = false) => {
146
+ const command = useProxy ? ['/bin/proxychains', '-q', '/bin/node', scriptPath] : ['/bin/node', scriptPath];
147
+ return new Promise((resolve, reject) => {
148
+ const process = spawn(command.shift(), command, { stdio: 'inherit' });
149
+ process.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`🔴 Process exited with code ${code}`))));
150
+ });
151
+ };
152
+
153
+ // Main function to run the server with optional proxy
154
+ const runServer = async () => {
155
+ const PROXY_URL = process.env.PROXY_URL || ''; // Default empty string to avoid undefined errors
156
+
157
+ if (PROXY_URL) {
158
+ await runProxyChainsConfGenerator(PROXY_URL);
159
+ return runScript(SERVER_SCRIPT_PATH, true);
160
+ }
161
+ return runScript(SERVER_SCRIPT_PATH);
162
+ };
163
+
164
+ // Main execution block
165
+ (async () => {
166
+ console.log('🌐 DNS Server:', dns.getServers());
167
+ console.log('-------------------------------------');
168
+
169
+ if (process.env.DATABASE_DRIVER) {
170
+ try {
171
+ await runScript(DB_MIGRATION_SCRIPT_PATH);
172
+ await checkTLSConnections();
173
+ } catch (err) {
174
+ console.error('❌ Error during DB migration or TLS connection check:', err);
175
+ process.exit(1);
176
+ }
177
+ }
178
+
179
+ // Run the server in either database or non-database mode
180
+ await runServer();
181
+ })();