install_debian.sh 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. timestamp() {
  4. date '+%Y-%m-%d %H:%M:%S'
  5. }
  6. log() {
  7. printf '[%s] %s\n' "$(timestamp)" "$*"
  8. }
  9. log_err() {
  10. printf '[%s] %s\n' "$(timestamp)" "$*" >&2
  11. }
  12. SERVICE_NAME="vmess-domain-rotator"
  13. RUN_USER=""
  14. RUN_GROUP=""
  15. RUN_USER_SET="0"
  16. RUN_GROUP_SET="0"
  17. RUN_HOME=""
  18. PEAK_START_HOUR="19"
  19. PEAK_END_HOUR="24"
  20. PEAK_TZ="Asia/Shanghai"
  21. PEAK_INTERVAL="10min"
  22. OFFPEAK_INTERVAL="30min"
  23. INSTALL_DEPS="1"
  24. CONFIG_PATH=""
  25. GIT_PUSH_ENABLED="1"
  26. GIT_PUSH_REMOTE="origin"
  27. GIT_HTTP_USERNAME="git"
  28. GIT_HTTP_TOKEN=""
  29. GIT_HTTP_TOKEN_FILE=""
  30. GIT_USE_CREDENTIAL_STORE="1"
  31. GIT_CREDENTIALS_FILE=""
  32. usage() {
  33. cat <<'EOF'
  34. Usage: sudo bash scripts/install_debian.sh [options]
  35. Default behavior:
  36. - Uses current git repository directory as working directory (in-place mode)
  37. - Uses the user executing sudo as service user
  38. - Enables git push after runtime-state commits
  39. Options:
  40. --user <name> Service user (default: current sudo user)
  41. --group <name> Service group (default: current sudo user's group)
  42. --interval <value> Alias for --offpeak-interval (default: 30min)
  43. --peak-start <hour> Peak period start hour, 0-23 (default: 19)
  44. --peak-end <hour> Peak period end hour, 1-24 (default: 24)
  45. --peak-tz <timezone> Peak period timezone (default: Asia/Shanghai)
  46. --peak-interval <value> Update interval during peak (default: 10min)
  47. --offpeak-interval <value> Update interval during offpeak (default: 30min)
  48. --config <path> Config file path (default: <repo>/config.server.json)
  49. --git-push <0|1> Enable/disable push to remote (default: 1)
  50. --git-push-remote <name> Remote name for push (default: origin)
  51. --git-http-username <u> Username for HTTPS auth (default: git)
  52. --git-http-token <t> HTTPS token for non-interactive push
  53. --git-http-token-file <f> Read HTTPS token from file
  54. --git-use-credential-store <0|1> Use git credential.helper store (default: 1)
  55. --git-credentials-file <f> Custom credentials file for helper store
  56. --no-install-deps Skip apt dependency install
  57. -h, --help Show help
  58. Examples:
  59. sudo bash scripts/install_debian.sh
  60. sudo bash scripts/install_debian.sh --config /opt/vmess-domain-rotator/config.server.json
  61. sudo bash scripts/install_debian.sh --peak-start 18 --peak-end 23
  62. sudo bash scripts/install_debian.sh --peak-interval 5min --offpeak-interval 15min
  63. sudo bash scripts/install_debian.sh --git-push 0
  64. EOF
  65. }
  66. run_as_service_user() {
  67. runuser -u "$RUN_USER" -- env HOME="$RUN_HOME" "$@"
  68. }
  69. # --- H4: validators for inputs that flow into systemd unit files / shell ---
  70. # Refuse anything that could break unit syntax or inject directives.
  71. validate_ident() {
  72. # user/group/service names: POSIX-portable charset only.
  73. local label="$1" value="$2"
  74. if [[ ! "$value" =~ ^[A-Za-z_][A-Za-z0-9_.-]*$ ]] || [[ ${#value} -gt 64 ]]; then
  75. log_err "Error: invalid $label: '$value' (must match [A-Za-z_][A-Za-z0-9_.-]{0,63})"
  76. exit 1
  77. fi
  78. }
  79. validate_path() {
  80. # Absolute path; no CR/LF; no characters that have meaning inside
  81. # systemd unit-file value parsing or bash ExecStart parsing.
  82. # (POSIX paths cannot contain NUL, so we don't need to test for it.)
  83. local label="$1" value="$2"
  84. if [[ "$value" != /* ]]; then
  85. log_err "Error: $label must be an absolute path: '$value'"
  86. exit 1
  87. fi
  88. if [[ "$value" == *$'\n'* ]] || [[ "$value" == *$'\r'* ]]; then
  89. log_err "Error: $label contains a newline/CR byte"
  90. exit 1
  91. fi
  92. case "$value" in
  93. *'"'*|*'%'*|*'$'*|*'`'*|*'\\'*|*';'*|*'|'*|*'&'*|*'<'*|*'>'*|*' '*)
  94. log_err "Error: $label contains a forbidden character (one of: space \" % \$ \\\` \\\\ ; | & < >): '$value'"
  95. exit 1
  96. ;;
  97. esac
  98. }
  99. validate_interval() {
  100. local label="$1" value="$2"
  101. if [[ ! "$value" =~ ^[0-9]+(min|m|h)$ ]]; then
  102. log_err "Error: $label must look like '30min' / '5m' / '1h', got: '$value'"
  103. exit 1
  104. fi
  105. }
  106. validate_tz() {
  107. local value="$1"
  108. if [[ ! "$value" =~ ^[A-Za-z0-9_+/.-]+$ ]] || [[ ${#value} -gt 64 ]]; then
  109. log_err "Error: invalid --peak-tz: '$value' (must match [A-Za-z0-9_+/.-]{1,64})"
  110. exit 1
  111. fi
  112. }
  113. validate_ident "service name" "$SERVICE_NAME"
  114. while [[ $# -gt 0 ]]; do
  115. case "$1" in
  116. --user)
  117. RUN_USER="$2"
  118. RUN_USER_SET="1"
  119. shift 2
  120. ;;
  121. --group)
  122. RUN_GROUP="$2"
  123. RUN_GROUP_SET="1"
  124. shift 2
  125. ;;
  126. --interval)
  127. OFFPEAK_INTERVAL="$2"
  128. shift 2
  129. ;;
  130. --peak-start)
  131. PEAK_START_HOUR="$2"
  132. shift 2
  133. ;;
  134. --peak-end)
  135. PEAK_END_HOUR="$2"
  136. shift 2
  137. ;;
  138. --peak-tz)
  139. PEAK_TZ="$2"
  140. shift 2
  141. ;;
  142. --peak-interval)
  143. PEAK_INTERVAL="$2"
  144. shift 2
  145. ;;
  146. --offpeak-interval)
  147. OFFPEAK_INTERVAL="$2"
  148. shift 2
  149. ;;
  150. --config)
  151. CONFIG_PATH="$2"
  152. shift 2
  153. ;;
  154. --git-push)
  155. GIT_PUSH_ENABLED="$2"
  156. shift 2
  157. ;;
  158. --git-push-remote)
  159. GIT_PUSH_REMOTE="$2"
  160. shift 2
  161. ;;
  162. --git-http-username)
  163. GIT_HTTP_USERNAME="$2"
  164. shift 2
  165. ;;
  166. --git-http-token)
  167. GIT_HTTP_TOKEN="$2"
  168. shift 2
  169. ;;
  170. --git-http-token-file)
  171. GIT_HTTP_TOKEN_FILE="$2"
  172. shift 2
  173. ;;
  174. --git-use-credential-store)
  175. GIT_USE_CREDENTIAL_STORE="$2"
  176. shift 2
  177. ;;
  178. --git-credentials-file)
  179. GIT_CREDENTIALS_FILE="$2"
  180. shift 2
  181. ;;
  182. --no-install-deps)
  183. INSTALL_DEPS="0"
  184. shift
  185. ;;
  186. -h|--help)
  187. usage
  188. exit 0
  189. ;;
  190. *)
  191. log_err "Unknown option: $1"
  192. usage
  193. exit 1
  194. ;;
  195. esac
  196. done
  197. if [[ "$(id -u)" -ne 0 ]]; then
  198. log_err "Please run as root (use sudo)."
  199. exit 1
  200. fi
  201. if ! command -v runuser >/dev/null 2>&1; then
  202. log_err "Error: runuser is required on Debian for configuring service-user git credentials"
  203. exit 1
  204. fi
  205. SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
  206. if ! git -C "$SOURCE_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  207. log_err "Error: Current directory is not a git repository."
  208. log_err "This script must be run from within a git repository."
  209. exit 1
  210. fi
  211. APP_DIR="$SOURCE_DIR"
  212. if [[ -z "$CONFIG_PATH" ]]; then
  213. CONFIG_PATH="${APP_DIR}/config.server.json"
  214. elif [[ "$CONFIG_PATH" != /* ]]; then
  215. CONFIG_PATH="${APP_DIR}/${CONFIG_PATH}"
  216. fi
  217. if [[ ! -r "$CONFIG_PATH" ]]; then
  218. log_err "Error: config file not found or unreadable: $CONFIG_PATH"
  219. exit 1
  220. fi
  221. if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_USER_SET" != "1" ]]; then
  222. RUN_USER="$SUDO_USER"
  223. fi
  224. if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_GROUP_SET" != "1" ]]; then
  225. RUN_GROUP="$(id -gn "$SUDO_USER")"
  226. fi
  227. if [[ -z "$RUN_USER" ]]; then
  228. log_err "Error: Could not determine service user. Please run with sudo or specify --user"
  229. exit 1
  230. fi
  231. if [[ -z "$RUN_GROUP" ]]; then
  232. log_err "Error: Could not determine service group. Please run with sudo or specify --group"
  233. exit 1
  234. fi
  235. validate_ident "service user" "$RUN_USER"
  236. validate_ident "service group" "$RUN_GROUP"
  237. validate_tz "$PEAK_TZ"
  238. validate_path "APP_DIR" "$APP_DIR"
  239. validate_path "CONFIG_PATH" "$CONFIG_PATH"
  240. if [[ ! "$GIT_PUSH_ENABLED" =~ ^[01]$ ]]; then
  241. log_err "Error: --git-push must be 0 or 1"
  242. exit 1
  243. fi
  244. if [[ ! "$GIT_USE_CREDENTIAL_STORE" =~ ^[01]$ ]]; then
  245. log_err "Error: --git-use-credential-store must be 0 or 1"
  246. exit 1
  247. fi
  248. if [[ -z "$GIT_PUSH_REMOTE" ]]; then
  249. log_err "Error: --git-push-remote cannot be empty"
  250. exit 1
  251. fi
  252. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
  253. log_err "Error: provide either --git-http-token or --git-http-token-file, not both"
  254. exit 1
  255. fi
  256. if [[ -n "$GIT_HTTP_TOKEN_FILE" ]] && [[ ! -r "$GIT_HTTP_TOKEN_FILE" ]]; then
  257. log_err "Error: cannot read token file: $GIT_HTTP_TOKEN_FILE"
  258. exit 1
  259. fi
  260. if [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
  261. GIT_HTTP_TOKEN="$(tr -d '\r\n' < "$GIT_HTTP_TOKEN_FILE")"
  262. fi
  263. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -z "$GIT_HTTP_USERNAME" ]]; then
  264. log_err "Error: --git-http-username cannot be empty when token is set"
  265. exit 1
  266. fi
  267. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ "$RUN_USER" == "root" ]]; then
  268. log_err "Error: refusing to store git token for root service user"
  269. log_err "Use --user <non-root> or disable push with --git-push 0"
  270. exit 1
  271. fi
  272. RUN_HOME="$(getent passwd "$RUN_USER" | cut -d: -f6)"
  273. if [[ -z "$RUN_HOME" ]]; then
  274. log_err "Error: could not determine home directory for user: $RUN_USER"
  275. exit 1
  276. fi
  277. to_minutes() {
  278. local val="$1"
  279. if [[ "$val" =~ ^([0-9]+)min$ ]] || [[ "$val" =~ ^([0-9]+)m$ ]]; then
  280. echo "${BASH_REMATCH[1]}"
  281. elif [[ "$val" =~ ^([0-9]+)h$ ]]; then
  282. echo $(( ${BASH_REMATCH[1]} * 60 ))
  283. elif [[ "$val" =~ ^[0-9]+$ ]]; then
  284. echo "$val"
  285. else
  286. echo ""
  287. fi
  288. }
  289. validate_interval "--peak-interval" "$PEAK_INTERVAL"
  290. validate_interval "--offpeak-interval" "$OFFPEAK_INTERVAL"
  291. PEAK_INTERVAL_MIN=$(to_minutes "$PEAK_INTERVAL")
  292. OFFPEAK_INTERVAL_MIN=$(to_minutes "$OFFPEAK_INTERVAL")
  293. if [[ -z "$PEAK_INTERVAL_MIN" ]] || [[ "$PEAK_INTERVAL_MIN" -eq 0 ]]; then
  294. log_err "Error: invalid peak interval: $PEAK_INTERVAL"
  295. exit 1
  296. fi
  297. if [[ -z "$OFFPEAK_INTERVAL_MIN" ]] || [[ "$OFFPEAK_INTERVAL_MIN" -eq 0 ]]; then
  298. log_err "Error: invalid offpeak interval: $OFFPEAK_INTERVAL"
  299. exit 1
  300. fi
  301. # Timer runs at the minimum of the two intervals to handle both schedules
  302. if [[ "$PEAK_INTERVAL_MIN" -lt "$OFFPEAK_INTERVAL_MIN" ]]; then
  303. TIMER_INTERVAL="$PEAK_INTERVAL"
  304. else
  305. TIMER_INTERVAL="$OFFPEAK_INTERVAL"
  306. fi
  307. if [[ "$INSTALL_DEPS" == "1" ]]; then
  308. export DEBIAN_FRONTEND=noninteractive
  309. apt-get update -y
  310. apt-get install -y python3 ca-certificates git
  311. fi
  312. RUNTIME_DIR="$(/usr/bin/python3 "${APP_DIR}/scripts/domain_updater.py" --config "$CONFIG_PATH" --print-output-settings | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin)["runtime_dir"])')"
  313. validate_path "RUNTIME_DIR" "$RUNTIME_DIR"
  314. mkdir -p "$RUNTIME_DIR"
  315. chmod +x "$APP_DIR/scripts/run_update_and_commit.sh" || true
  316. chown -R "$RUN_USER:$RUN_GROUP" "$RUNTIME_DIR"
  317. SERVICE_STATE_DIR="/var/lib/${SERVICE_NAME}"
  318. ENV_FILE="/etc/${SERVICE_NAME}.env"
  319. TOKEN_FILE=""
  320. REMOTE_URL=""
  321. AUTH_MODE="header"
  322. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  323. AUTH_MODE="credential-helper-store"
  324. fi
  325. mkdir -p "$SERVICE_STATE_DIR"
  326. chown "$RUN_USER:$RUN_GROUP" "$SERVICE_STATE_DIR"
  327. chmod 750 "$SERVICE_STATE_DIR"
  328. if [[ "$GIT_PUSH_ENABLED" == "1" ]]; then
  329. REMOTE_URL="$(git -C "$APP_DIR" remote get-url "$GIT_PUSH_REMOTE" 2>/dev/null || true)"
  330. if [[ -z "$REMOTE_URL" ]]; then
  331. log_err "Warning: remote '$GIT_PUSH_REMOTE' not found now. Push may fail until remote is configured."
  332. fi
  333. fi
  334. if [[ -n "$GIT_HTTP_TOKEN" ]]; then
  335. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  336. if [[ "$REMOTE_URL" =~ ^https:// ]]; then
  337. helper_value="store"
  338. if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
  339. helper_value="store --file ${GIT_CREDENTIALS_FILE}"
  340. mkdir -p "$(dirname "$GIT_CREDENTIALS_FILE")"
  341. touch "$GIT_CREDENTIALS_FILE"
  342. chown "$RUN_USER:$RUN_GROUP" "$GIT_CREDENTIALS_FILE"
  343. chmod 600 "$GIT_CREDENTIALS_FILE"
  344. fi
  345. run_as_service_user git config --global credential.helper "$helper_value"
  346. printf 'url=%s\nusername=%s\npassword=%s\n\n' "$REMOTE_URL" "$GIT_HTTP_USERNAME" "$GIT_HTTP_TOKEN" | run_as_service_user git credential approve
  347. else
  348. log_err "Warning: token provided but remote is not HTTPS; credential.helper store setup skipped."
  349. log_err "Warning: fallback to header-token-file auth mode for this install."
  350. GIT_USE_CREDENTIAL_STORE="0"
  351. fi
  352. fi
  353. if [[ "$GIT_USE_CREDENTIAL_STORE" != "1" ]]; then
  354. TOKEN_FILE="${SERVICE_STATE_DIR}/git_http_token"
  355. printf '%s\n' "$GIT_HTTP_TOKEN" >"$TOKEN_FILE"
  356. chown "$RUN_USER:$RUN_GROUP" "$TOKEN_FILE"
  357. chmod 600 "$TOKEN_FILE"
  358. AUTH_MODE="header-token-file"
  359. fi
  360. fi
  361. run_as_service_user git config --global --add safe.directory "$APP_DIR" || true
  362. cat >"$ENV_FILE" <<EOF
  363. GIT_PUSH_ENABLED=${GIT_PUSH_ENABLED}
  364. GIT_PUSH_REQUIRED=${GIT_PUSH_ENABLED}
  365. GIT_PUSH_REMOTE=${GIT_PUSH_REMOTE}
  366. GIT_RUNTIME_BRANCH=runtime-state
  367. GIT_HTTP_USERNAME=${GIT_HTTP_USERNAME}
  368. HOME=${RUN_HOME}
  369. PEAK_START_HOUR=${PEAK_START_HOUR}
  370. PEAK_END_HOUR=${PEAK_END_HOUR}
  371. PEAK_TZ=${PEAK_TZ}
  372. PEAK_INTERVAL_MIN=${PEAK_INTERVAL_MIN}
  373. OFFPEAK_INTERVAL_MIN=${OFFPEAK_INTERVAL_MIN}
  374. EOF
  375. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  376. if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
  377. printf 'GIT_CREDENTIAL_HELPER=store --file %s\n' "$GIT_CREDENTIALS_FILE" >>"$ENV_FILE"
  378. else
  379. printf 'GIT_CREDENTIAL_HELPER=store\n' >>"$ENV_FILE"
  380. fi
  381. fi
  382. if [[ -n "$TOKEN_FILE" ]]; then
  383. printf 'GIT_HTTP_TOKEN_FILE=%s\n' "$TOKEN_FILE" >>"$ENV_FILE"
  384. fi
  385. chown root:root "$ENV_FILE"
  386. chmod 600 "$ENV_FILE"
  387. cat >"/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
  388. [Unit]
  389. Description=VMess Domain Rotator updater
  390. After=network-online.target
  391. Wants=network-online.target
  392. [Service]
  393. Type=oneshot
  394. User=${RUN_USER}
  395. Group=${RUN_GROUP}
  396. WorkingDirectory=${APP_DIR}
  397. EnvironmentFile=-${ENV_FILE}
  398. UMask=0077
  399. ExecStart=/bin/bash "${APP_DIR}/scripts/run_update_and_commit.sh" "${CONFIG_PATH}"
  400. EOF
  401. cat >"/etc/systemd/system/${SERVICE_NAME}.timer" <<EOF
  402. [Unit]
  403. Description=Run VMess Domain Rotator every ${TIMER_INTERVAL}
  404. [Timer]
  405. OnBootSec=2min
  406. OnUnitActiveSec=${TIMER_INTERVAL}
  407. AccuracySec=30s
  408. Unit=${SERVICE_NAME}.service
  409. Persistent=true
  410. [Install]
  411. WantedBy=timers.target
  412. EOF
  413. systemctl daemon-reload
  414. systemctl enable --now "${SERVICE_NAME}.timer"
  415. systemctl start "${SERVICE_NAME}.service"
  416. log ""
  417. log "✓ Installation complete!"
  418. log ""
  419. log "Configuration:"
  420. log " Working directory: ${APP_DIR}"
  421. log " Config path: ${CONFIG_PATH}"
  422. log " Service user: ${RUN_USER}"
  423. log " Service group: ${RUN_GROUP}"
  424. log " Timer interval: ${TIMER_INTERVAL}"
  425. log " Peak hour: ${PEAK_START_HOUR} to ${PEAK_END_HOUR} (${PEAK_TZ})"
  426. log " Peak interval: ${PEAK_INTERVAL}"
  427. log " Off-peak interval: ${OFFPEAK_INTERVAL}"
  428. log " Push enabled: ${GIT_PUSH_ENABLED}"
  429. log " Push remote: ${GIT_PUSH_REMOTE}"
  430. log " Auth mode: ${AUTH_MODE}"
  431. log " Env file: ${ENV_FILE}"
  432. log ""
  433. log "Commands:"
  434. log " Check status: systemctl status ${SERVICE_NAME}.timer"
  435. log " View logs: journalctl -t ${SERVICE_NAME} -u ${SERVICE_NAME}.service -n 50 --no-pager"
  436. log " Manual run: sudo systemctl start ${SERVICE_NAME}.service"
  437. log " Force commit: sudo -u ${RUN_USER} /bin/bash ${APP_DIR}/scripts/run_update_and_commit.sh --force-commit ${CONFIG_PATH}"
  438. log ""