entrypoint.sh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #!/usr/bin/env bash
  2. # 容器入口脚本
  3. # dsh-web 容器入口:校验必需变量 → 可选 bcrypt → 首启初始化数据卷 → 启动 supervisord
  4. # dsh 启动后,后台抓取 0.1.2-rc.1 的一次性 token URL 写到 $DHS_HOME/web-launch-url.txt
  5. #
  6. # Container Entrypoint Script
  7. # dsh-web container entrypoint: validate required env vars → optional bcrypt → initialize the data volume on first run → start supervisord
  8. # Once dsh starts, a background tail greps the 0.1.2-rc.1 one-time token URL and persists
  9. # it to $DHS_HOME/web-launch-url.txt so operators can read it (see the post-supervisord block)
  10. set -euo pipefail
  11. log() { echo "[entrypoint] $*"; }
  12. # ---- 必需变量校验 ----
  13. # DEEPSEEK_API_KEY 是 dsh 运行时必需;DSH_AUTH_USER / DSH_AUTH_PASSWORD 自 0.1.2-rc.1
  14. # 不再被 caddy 使用(鉴权迁回 dsh 自身),改为可选保留以便回退到 ≤0.1.1-rc.2 时继续生效
  15. #
  16. # ---- Required variable validation ----
  17. # DEEPSEEK_API_KEY is required by dsh at runtime. DSH_AUTH_USER / DSH_AUTH_PASSWORD are
  18. # no longer used by caddy since 0.1.2-rc.1 (auth moved into dsh itself) but kept optional
  19. # so a rollback to ≤0.1.1-rc.2 still works without .env surgery
  20. : "${DEEPSEEK_API_KEY:?必须设置 DEEPSEEK_API_KEY(.env)}"
  21. # ---- basic auth:明文密码 → bcrypt 哈希(为回退兼容保留,0.1.2-rc.1+ 不被任何消费者使用)----
  22. # 0.1.2-rc.1+ 的 Caddyfile 已不引用 {$DSH_AUTH_HASH}(Caddyfile 块本身不出现该占位符,
  23. # 见 PR #7 改动)。本块在当前 image 是无消费者的导出,仅在回退到 ≤0.1.1-rc.2 流程时
  24. # 才被旧 Caddyfile 使用——回退需要从 git history 拉回旧 Caddyfile(basic_auth 块 + 占位符)
  25. # 一起恢复,因此 DSH_AUTH_HASH 仍必须在此处派生(否则回退到旧 image 时 caddy 启动报错)。
  26. # 视为「回退兼容位的准备代码」而非「当前生效的鉴权逻辑」——删它会破坏回退路径
  27. #
  28. # ---- Basic auth hash: retained for rollback compatibility, no current consumer ----
  29. # The 0.1.2-rc.1+ Caddyfile does not reference {$DSH_AUTH_HASH}. This block is a no-consumer
  30. # export in the current image; it only feeds the old Caddyfile (≤0.1.1-rc.2) on rollback,
  31. # which requires restoring the basic_auth block from git history. Delete this block only
  32. # if rollback support to ≤0.1.1-rc.2 is also dropped.
  33. if [ -n "${DSH_AUTH_PASSWORD:-}" ]; then
  34. DSH_AUTH_HASH="$(caddy hash-password --plaintext "$DSH_AUTH_PASSWORD" | tail -n 1)"
  35. else
  36. # 占位 bcrypt 哈希:格式合法($2a$10$... + 22 字符 salt)但内容不匹配任何输入。
  37. # 当前 image 不消费此变量;若被误用到旧 Caddyfile,任何 basic auth 试探必 401,等效关闭
  38. #
  39. # Placeholder bcrypt hash: well-formed (passes parser) but never matches any input.
  40. # Current image has no consumer; if accidentally used by an old Caddyfile, deterministically
  41. # 401s any basic-auth probe (effectively closed)
  42. # shellcheck disable=SC2016 # 单引号是有意的:占位 bcrypt 哈希($2a$10$...)需要字面 $ 字符
  43. DSH_AUTH_HASH='$2a$10$invalidplaceholderhashthatnevermatches0000000000000'
  44. log "DSH_AUTH_PASSWORD 未设置:DSH_AUTH_HASH 写占位值(回退兼容位;当前 image 不使用)"
  45. fi
  46. export DSH_AUTH_HASH
  47. # ---- 数据卷首启初始化(/home/node/.dsh,node 用户为 uid 1000)----
  48. #
  49. # ---- Data volume first-run initialization (/home/node/.dsh, node user with uid 1000) ----
  50. DHS_HOME=/home/node/.dsh
  51. mkdir -p "$DHS_HOME"
  52. # 1. settings.yaml:不存在时复制默认模板(之后由用户持久化维护)
  53. #
  54. # 1. settings.yaml: copy the default template when absent (later maintained by the user)
  55. if [ ! -f "$DHS_HOME/settings.yaml" ]; then
  56. cp /opt/dsh/defaults/settings.yaml "$DHS_HOME/settings.yaml"
  57. log "已初始化默认 settings.yaml"
  58. fi
  59. # 1b. AGENTS.md:容器环境指引(dsh 会话自动加载,agent 必读)
  60. #
  61. # 1b. AGENTS.md: container environment guide (auto-loaded by dsh sessions, mandatory for agents)
  62. if [ ! -f "$DHS_HOME/AGENTS.md" ]; then
  63. cp /opt/dsh/defaults/AGENTS.md "$DHS_HOME/AGENTS.md"
  64. log "已初始化 AGENTS.md(容器环境指引)"
  65. fi
  66. # 2. trustedHosts 注入 cordis.patch.yml
  67. # profile 其余文件(package.json/pnpm-workspace.yaml)由 dsh 首启自动补全,
  68. # 且 dsh 的 initProfile 对已存在文件绝不覆盖("Existing files are never touched"),
  69. # 故此处预写安全。
  70. # 注入条件:patch 不存在,或为 dsh 首启生成的空模板(顶层数组 [])。
  71. # 已有任何条目(用户维护)或不可解析时跳过——绝不覆盖用户文件。
  72. #
  73. # 2. Inject trustedHosts into cordis.patch.yml
  74. # The rest of the profile (package.json/pnpm-workspace.yaml) is auto-completed by dsh on first run,
  75. # and dsh's initProfile never touches existing files ("Existing files are never touched"),
  76. # so pre-writing here is safe.
  77. # Injection happens when the patch is absent, or when it is the empty template dsh generates
  78. # on first run (top-level array []). Any existing entries (user-maintained) or an unparseable
  79. # file cause a skip — user files are never overwritten.
  80. if [ -n "${DSH_TRUSTED_HOSTS:-}" ]; then
  81. PROFILE_DIR="$DHS_HOME/profiles/web"
  82. PATCH="$PROFILE_DIR/cordis.patch.yml"
  83. INJECT=1
  84. if [ -f "$PATCH" ]; then
  85. PATCH_LEN="$(yq '. | length' "$PATCH" 2>/dev/null || true)"
  86. if [ "$PATCH_LEN" != "0" ]; then
  87. INJECT=0
  88. log "cordis.patch.yml 已有内容,跳过 trustedHosts 注入(用户维护;若需变更请直接编辑该文件)"
  89. fi
  90. fi
  91. if [ "$INJECT" = 1 ]; then
  92. mkdir -p "$PROFILE_DIR"
  93. {
  94. echo "# 由 dsh-web entrypoint 自动注入(DSH_TRUSTED_HOSTS)"
  95. echo "# Auto-injected by the dsh-web entrypoint (DSH_TRUSTED_HOSTS)"
  96. echo "- id: connection"
  97. echo " config:"
  98. echo " trustedHosts:"
  99. # shellcheck disable=SC2086 # 有意按空白分词(逗号分隔列表)
  100. for host in ${DSH_TRUSTED_HOSTS//,/ }; do
  101. # 仅接受 域名/IP[:端口] 形态(字母数字 . : -),拒绝其余字符以免破坏 YAML
  102. #
  103. # Accept only host[:port] shapes (alphanumerics . : -); reject anything else so the YAML stays valid
  104. if [[ "$host" =~ ^[A-Za-z0-9.:-]+$ ]]; then
  105. echo " - $host"
  106. else
  107. log "警告:跳过非法的 trustedHost 条目 [$host](仅允许字母数字 . : -)"
  108. fi
  109. done
  110. } > "$PATCH"
  111. log "已注入 trustedHosts: $DSH_TRUSTED_HOSTS"
  112. fi
  113. fi
  114. # 3. 修正数据卷属主(bind mount 挂整个 /home/node,首启属主可能是 root)
  115. # 仅当根目录属主非 1000 时全量修正;后续启动跳过——数据卷含 x-cmd 工具,
  116. # 全量递归 chown 在大卷上会拖慢启动
  117. #
  118. # 3. Fix data volume ownership (the whole /home/node is bind-mounted; owner may be root on first run)
  119. # Only fix recursively when the root owner is not 1000; later starts skip it —
  120. # the volume holds x-cmd tools and a full recursive chown slows startup on large volumes
  121. if [ "$(stat -c '%u:%g' /home/node 2>/dev/null || echo '0:0')" != "1000:1000" ]; then
  122. chown -R node:node /home/node
  123. log "已修正数据卷属主(uid:gid → 1000:1000)"
  124. else
  125. log "数据卷属主正确,跳过 chown"
  126. fi
  127. # ---- x-cmd:agent 自行配置运行环境的工具(幂等安装 + 系统 PATH 接入)----
  128. # agent 的 bash 工具环境是白名单(PATH 固定为 /usr/local/sbin:/usr/local/bin:/usr/bin,无 HOME),
  129. # 因此:1) 生成 HOME 注入的 x wrapper;2) 把已 use 包的 shim 软链进 /usr/local/bin。
  130. # agent 用法见数据卷 AGENTS.md:`x env use <pkg>` 安装,`x <pkg>` 前缀调用(始终可用),
  131. # 裸命令对本次启动前已 use 的包可用(重启容器后对新装包生效)。
  132. #
  133. # ---- x-cmd: tools agents install to configure their runtime (idempotent install + system PATH integration) ----
  134. # The agent's bash tool environment is a whitelist (PATH fixed to /usr/local/sbin:/usr/local/bin:/usr/bin, no HOME),
  135. # hence: 1) generate an x wrapper that injects HOME; 2) symlink shims of already-used packages into /usr/local/bin.
  136. # Agent usage is documented in the data-volume AGENTS.md: install with `x env use <pkg>`, invoke with the `x <pkg>` prefix (always available),
  137. # Bare commands work for packages used before this startup (newly installed packages take effect after a container restart).
  138. XCMD_HOME=/home/node/.x-cmd.root
  139. if [ ! -x "$XCMD_HOME/bin/x" ]; then
  140. log "首次启动:安装 x-cmd(agent 环境自举,约 80MB,写入数据卷;阿里云 OSS 源)"
  141. if timeout 300 su -s /bin/bash node -c 'HOME=/home/node curl -fsSL https://get.x-cmd.com | sh' >/dev/null 2>&1; then
  142. log "x-cmd 安装完成"
  143. else
  144. log "警告:x-cmd 安装失败(网络或 su 受限?),dsh 照常启动;"
  145. log " 可稍后手动安装:docker exec -it dsh-web su -s /bin/bash node -c 'curl -fsSL https://get.x-cmd.com | sh'"
  146. fi
  147. fi
  148. if [ -x "$XCMD_HOME/bin/x" ]; then
  149. # 1) x wrapper:agent bash 无 HOME,x 需要 HOME 定位安装根
  150. #
  151. # 1) x wrapper: the agent bash has no HOME; x needs HOME to locate its install root
  152. cat > /usr/local/bin/x <<EOF
  153. #!/bin/bash
  154. export HOME=/home/node
  155. exec /home/node/.x-cmd.root/bin/x "$@"
  156. EOF
  157. chmod 755 /usr/local/bin/x
  158. # 2) 已 use 包 shim 快照软链 → /usr/local/bin(裸命令直接可用)
  159. # exec/<pkg> 文件内容为 shim_bin 路径;shim_bin/<pkg> 是 `#! /bin/sh + exec 真实 bin` 包装
  160. #
  161. # 2) Symlink the shim snapshot of used packages → /usr/local/bin (bare commands become directly usable)
  162. # exec/<pkg> contains the shim_bin path; shim_bin/<pkg> is a `#! /bin/sh + exec real bin` wrapper
  163. for shim in "$XCMD_HOME/local/data/pkg/exec"/*; do
  164. [ -f "$shim" ] || continue
  165. pkg="$(basename "$shim")"
  166. target="$(head -n 1 "$shim" 2>/dev/null)" || continue
  167. if [ -n "$target" ] && [ -e "$target" ]; then
  168. ln -sf "$target" "/usr/local/bin/$pkg"
  169. fi
  170. done
  171. pkg_list="$("$XCMD_HOME/bin/x" env ls 2>/dev/null | awk '{print $1}' | tr '\n' ' ')"
  172. log "x-cmd 就绪(已启用包:$pkg_list)"
  173. fi
  174. # ---- dsh 0.1.2-rc.1 一次性 token 提取后台任务 ----
  175. # dsh 启动时打印 `dsh web: http://127.0.0.1:3080/?token=XXX`,但因 dsh 强制 loopback bind
  176. # (上游拒 --host 0.0.0.0),外部浏览器拿不到这个 URL;supervisord 把 dsh 输出 tee 到
  177. # $DHS_HOME/web-server.log(见 supervisord.conf),这里起一个后台 tail 任务:
  178. # 1) 等文件出现(dsh 可能要 30+ 秒才就绪)
  179. # 2) grep 一次 ?token=… 并写入 $DHS_HOME/web-launch-url.txt
  180. # 3) 写完后退出(任务只做一次:首启一次性 token 即可让浏览器完成 cookie 交换,
  181. # 后续重启 cookie 已持久化在 $DHS_HOME/.credentials.yaml,无需重抓)
  182. #
  183. # ---- Background task: extract dsh 0.1.2-rc.1's one-time token URL ----
  184. # dsh prints `dsh web: http://127.0.0.1:3080/?token=XXX` on startup, but since dsh 0.1.2-rc.1
  185. # hard-binds to loopback (upstream refuses --host 0.0.0.0), external browsers can't see it.
  186. # supervisord tees dsh's output to $DHS_HOME/web-server.log; we spawn a background tail that
  187. # (1) waits for the file (dsh may take 30+ s), (2) greps the token URL once, (3) writes it
  188. # to $DHS_HOME/web-launch-url.txt, then exits. One-time is enough: the first exchange
  189. # persists a cookie in $DHS_HOME/.credentials.yaml that survives restarts.
  190. # 0.1.1-rc.2 doesn't print this URL, so on older dsh the file stays empty — harmless.
  191. WEB_LOG="$DHS_HOME/web-server.log"
  192. WEB_URL_FILE="$DHS_HOME/web-launch-url.txt"
  193. # 预创建必须让 node 可写:entrypoint 以 root 运行,裸 touch 会留下 root:root 0644,
  194. # supervisord 中 dsh 以 user=node 执行 `tee -a` 追加时 EACCES,启动日志(含 ?token= URL)
  195. # 永远写不进文件,后台 tail 也就抓不到 token。故创建后立即把属主交给 node。
  196. # 仅首启会触发:文件已存在且属主正确时 touch 不改属主,二次启动天然正常。
  197. #
  198. # Pre-creation must leave the file writable by node: the entrypoint runs as root, so a bare
  199. # touch leaves root:root 0644 and dsh's `tee -a` under user=node fails with EACCES — the
  200. # startup log (including the ?token= URL) never reaches the file, so the background tail
  201. # cannot extract the token. Hand ownership to node right after creation.
  202. # First run only: when the file already exists with the right owner, touch keeps it,
  203. # so subsequent starts are fine.
  204. touch "$WEB_LOG"
  205. chown node:node "$WEB_LOG"
  206. (
  207. # 在子 shell 中等 + 抓 + 写 + 退出;不影响 entrypoint 主体
  208. #
  209. # In a subshell: wait + grep + write + exit. Doesn't block the main entrypoint
  210. set +e # 关闭子 shell 严格模式:grep 没匹配时正常返回非零
  211. url="$(tail -F -n 0 -- "$WEB_LOG" 2>/dev/null | grep -m1 -oE 'http://127\.0\.0\.1:[0-9]+/\?token=[A-Za-z0-9_-]{43}')"
  212. if [ -n "${url:-}" ]; then
  213. printf '%s\n' "$url" > "$WEB_URL_FILE"
  214. chmod 644 "$WEB_URL_FILE"
  215. log "已抓取 dsh 启动 URL: $url"
  216. log " 写入 $WEB_URL_FILE(外部用户首次访问需先访问该 URL 拿 cookie)"
  217. else
  218. log "未在 dsh 启动日志中捕获到 ?token= URL(可能 dsh <0.1.2-rc.1,无 token 鉴权)"
  219. fi
  220. ) &
  221. disown || true
  222. log "dsh token 提取后台任务已启动(pid=$!),结果写入 $WEB_URL_FILE"
  223. # ---- 启动 supervisord(dsh + caddy)----
  224. #
  225. # ---- Start supervisord (dsh + caddy) ----
  226. log "启动 supervisord(DSH_AUTH_USER=${DSH_AUTH_USER:-<unset,0.1.2-rc.1+ 不再使用>},对外端口由 compose 映射)"
  227. exec supervisord -c /etc/supervisor/conf.d/dsh.conf