install_debian.sh 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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_hour_range() {
  107. local label="$1" value="$2" min="$3" max="$4"
  108. if [[ ! "$value" =~ ^[0-9]+$ ]]; then
  109. log_err "Error: $label must be an integer from ${min} to ${max}, got: '$value'"
  110. exit 1
  111. fi
  112. local n=$((10#$value))
  113. if [[ "$n" -lt "$min" ]] || [[ "$n" -gt "$max" ]]; then
  114. log_err "Error: $label must be from ${min} to ${max}, got: '$value'"
  115. exit 1
  116. fi
  117. }
  118. validate_tz() {
  119. local value="$1"
  120. if [[ ! "$value" =~ ^[A-Za-z0-9_+/.-]+$ ]] || [[ ${#value} -gt 64 ]]; then
  121. log_err "Error: invalid --peak-tz: '$value' (must match [A-Za-z0-9_+/.-]{1,64})"
  122. exit 1
  123. fi
  124. }
  125. validate_ident "service name" "$SERVICE_NAME"
  126. while [[ $# -gt 0 ]]; do
  127. case "$1" in
  128. --user)
  129. RUN_USER="$2"
  130. RUN_USER_SET="1"
  131. shift 2
  132. ;;
  133. --group)
  134. RUN_GROUP="$2"
  135. RUN_GROUP_SET="1"
  136. shift 2
  137. ;;
  138. --interval)
  139. OFFPEAK_INTERVAL="$2"
  140. shift 2
  141. ;;
  142. --peak-start)
  143. PEAK_START_HOUR="$2"
  144. shift 2
  145. ;;
  146. --peak-end)
  147. PEAK_END_HOUR="$2"
  148. shift 2
  149. ;;
  150. --peak-tz)
  151. PEAK_TZ="$2"
  152. shift 2
  153. ;;
  154. --peak-interval)
  155. PEAK_INTERVAL="$2"
  156. shift 2
  157. ;;
  158. --offpeak-interval)
  159. OFFPEAK_INTERVAL="$2"
  160. shift 2
  161. ;;
  162. --config)
  163. CONFIG_PATH="$2"
  164. shift 2
  165. ;;
  166. --git-push)
  167. GIT_PUSH_ENABLED="$2"
  168. shift 2
  169. ;;
  170. --git-push-remote)
  171. GIT_PUSH_REMOTE="$2"
  172. shift 2
  173. ;;
  174. --git-http-username)
  175. GIT_HTTP_USERNAME="$2"
  176. shift 2
  177. ;;
  178. --git-http-token)
  179. GIT_HTTP_TOKEN="$2"
  180. shift 2
  181. ;;
  182. --git-http-token-file)
  183. GIT_HTTP_TOKEN_FILE="$2"
  184. shift 2
  185. ;;
  186. --git-use-credential-store)
  187. GIT_USE_CREDENTIAL_STORE="$2"
  188. shift 2
  189. ;;
  190. --git-credentials-file)
  191. GIT_CREDENTIALS_FILE="$2"
  192. shift 2
  193. ;;
  194. --no-install-deps)
  195. INSTALL_DEPS="0"
  196. shift
  197. ;;
  198. -h|--help)
  199. usage
  200. exit 0
  201. ;;
  202. *)
  203. log_err "Unknown option: $1"
  204. usage
  205. exit 1
  206. ;;
  207. esac
  208. done
  209. if [[ "$(id -u)" -ne 0 ]]; then
  210. log_err "Please run as root (use sudo)."
  211. exit 1
  212. fi
  213. if ! command -v runuser >/dev/null 2>&1; then
  214. log_err "Error: runuser is required on Debian for configuring service-user git credentials"
  215. exit 1
  216. fi
  217. SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
  218. if ! git -C "$SOURCE_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  219. log_err "Error: Current directory is not a git repository."
  220. log_err "This script must be run from within a git repository."
  221. exit 1
  222. fi
  223. APP_DIR="$SOURCE_DIR"
  224. if [[ -z "$CONFIG_PATH" ]]; then
  225. CONFIG_PATH="${APP_DIR}/config.server.json"
  226. elif [[ "$CONFIG_PATH" != /* ]]; then
  227. CONFIG_PATH="${APP_DIR}/${CONFIG_PATH}"
  228. fi
  229. if [[ ! -r "$CONFIG_PATH" ]]; then
  230. log_err "Error: config file not found or unreadable: $CONFIG_PATH"
  231. exit 1
  232. fi
  233. if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_USER_SET" != "1" ]]; then
  234. RUN_USER="$SUDO_USER"
  235. fi
  236. if [[ -n "${SUDO_USER:-}" ]] && [[ "$RUN_GROUP_SET" != "1" ]]; then
  237. RUN_GROUP="$(id -gn "$SUDO_USER")"
  238. fi
  239. if [[ -z "$RUN_USER" ]]; then
  240. log_err "Error: Could not determine service user. Please run with sudo or specify --user"
  241. exit 1
  242. fi
  243. if [[ -z "$RUN_GROUP" ]]; then
  244. log_err "Error: Could not determine service group. Please run with sudo or specify --group"
  245. exit 1
  246. fi
  247. validate_ident "service user" "$RUN_USER"
  248. validate_ident "service group" "$RUN_GROUP"
  249. validate_tz "$PEAK_TZ"
  250. validate_hour_range "--peak-start" "$PEAK_START_HOUR" 0 23
  251. validate_hour_range "--peak-end" "$PEAK_END_HOUR" 1 24
  252. validate_path "APP_DIR" "$APP_DIR"
  253. validate_path "CONFIG_PATH" "$CONFIG_PATH"
  254. if [[ ! "$GIT_PUSH_ENABLED" =~ ^[01]$ ]]; then
  255. log_err "Error: --git-push must be 0 or 1"
  256. exit 1
  257. fi
  258. if [[ ! "$GIT_USE_CREDENTIAL_STORE" =~ ^[01]$ ]]; then
  259. log_err "Error: --git-use-credential-store must be 0 or 1"
  260. exit 1
  261. fi
  262. if [[ -z "$GIT_PUSH_REMOTE" ]]; then
  263. log_err "Error: --git-push-remote cannot be empty"
  264. exit 1
  265. fi
  266. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
  267. log_err "Error: provide either --git-http-token or --git-http-token-file, not both"
  268. exit 1
  269. fi
  270. if [[ -n "$GIT_HTTP_TOKEN_FILE" ]] && [[ ! -r "$GIT_HTTP_TOKEN_FILE" ]]; then
  271. log_err "Error: cannot read token file: $GIT_HTTP_TOKEN_FILE"
  272. exit 1
  273. fi
  274. if [[ -n "$GIT_HTTP_TOKEN_FILE" ]]; then
  275. GIT_HTTP_TOKEN="$(tr -d '\r\n' < "$GIT_HTTP_TOKEN_FILE")"
  276. fi
  277. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ -z "$GIT_HTTP_USERNAME" ]]; then
  278. log_err "Error: --git-http-username cannot be empty when token is set"
  279. exit 1
  280. fi
  281. if [[ -n "$GIT_HTTP_TOKEN" ]] && [[ "$RUN_USER" == "root" ]]; then
  282. log_err "Error: refusing to store git token for root service user"
  283. log_err "Use --user <non-root> or disable push with --git-push 0"
  284. exit 1
  285. fi
  286. RUN_HOME="$(getent passwd "$RUN_USER" | cut -d: -f6)"
  287. if [[ -z "$RUN_HOME" ]]; then
  288. log_err "Error: could not determine home directory for user: $RUN_USER"
  289. exit 1
  290. fi
  291. to_minutes() {
  292. local val="$1"
  293. if [[ "$val" =~ ^([0-9]+)min$ ]] || [[ "$val" =~ ^([0-9]+)m$ ]]; then
  294. echo $((10#${BASH_REMATCH[1]}))
  295. elif [[ "$val" =~ ^([0-9]+)h$ ]]; then
  296. echo $((10#${BASH_REMATCH[1]} * 60))
  297. elif [[ "$val" =~ ^[0-9]+$ ]]; then
  298. echo $((10#$val))
  299. else
  300. echo ""
  301. fi
  302. }
  303. validate_interval "--peak-interval" "$PEAK_INTERVAL"
  304. validate_interval "--offpeak-interval" "$OFFPEAK_INTERVAL"
  305. PEAK_INTERVAL_MIN=$(to_minutes "$PEAK_INTERVAL")
  306. OFFPEAK_INTERVAL_MIN=$(to_minutes "$OFFPEAK_INTERVAL")
  307. if [[ -z "$PEAK_INTERVAL_MIN" ]] || [[ "$PEAK_INTERVAL_MIN" -eq 0 ]]; then
  308. log_err "Error: invalid peak interval: $PEAK_INTERVAL"
  309. exit 1
  310. fi
  311. if [[ -z "$OFFPEAK_INTERVAL_MIN" ]] || [[ "$OFFPEAK_INTERVAL_MIN" -eq 0 ]]; then
  312. log_err "Error: invalid offpeak interval: $OFFPEAK_INTERVAL"
  313. exit 1
  314. fi
  315. # Timer runs at the minimum of the two intervals to handle both schedules
  316. if [[ "$PEAK_INTERVAL_MIN" -lt "$OFFPEAK_INTERVAL_MIN" ]]; then
  317. TIMER_INTERVAL="$PEAK_INTERVAL"
  318. else
  319. TIMER_INTERVAL="$OFFPEAK_INTERVAL"
  320. fi
  321. if [[ "$INSTALL_DEPS" == "1" ]]; then
  322. export DEBIAN_FRONTEND=noninteractive
  323. apt-get update -y
  324. apt-get install -y python3 ca-certificates git
  325. fi
  326. 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"])')"
  327. validate_path "RUNTIME_DIR" "$RUNTIME_DIR"
  328. mkdir -p "$RUNTIME_DIR"
  329. chmod +x "$APP_DIR/scripts/run_update_and_commit.sh" || true
  330. chown -R "$RUN_USER:$RUN_GROUP" "$RUNTIME_DIR"
  331. SERVICE_STATE_DIR="/var/lib/${SERVICE_NAME}"
  332. ENV_FILE="/etc/${SERVICE_NAME}.env"
  333. TOKEN_FILE=""
  334. REMOTE_URL=""
  335. AUTH_MODE="header"
  336. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  337. AUTH_MODE="credential-helper-store"
  338. fi
  339. mkdir -p "$SERVICE_STATE_DIR"
  340. chown "$RUN_USER:$RUN_GROUP" "$SERVICE_STATE_DIR"
  341. chmod 750 "$SERVICE_STATE_DIR"
  342. if [[ "$GIT_PUSH_ENABLED" == "1" ]]; then
  343. REMOTE_URL="$(git -C "$APP_DIR" remote get-url "$GIT_PUSH_REMOTE" 2>/dev/null || true)"
  344. if [[ -z "$REMOTE_URL" ]]; then
  345. log_err "Warning: remote '$GIT_PUSH_REMOTE' not found now. Push may fail until remote is configured."
  346. fi
  347. fi
  348. if [[ -n "$GIT_HTTP_TOKEN" ]]; then
  349. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  350. if [[ "$REMOTE_URL" =~ ^https:// ]]; then
  351. helper_value="store"
  352. if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
  353. helper_value="store --file ${GIT_CREDENTIALS_FILE}"
  354. mkdir -p "$(dirname "$GIT_CREDENTIALS_FILE")"
  355. touch "$GIT_CREDENTIALS_FILE"
  356. chown "$RUN_USER:$RUN_GROUP" "$GIT_CREDENTIALS_FILE"
  357. chmod 600 "$GIT_CREDENTIALS_FILE"
  358. fi
  359. run_as_service_user git config --global credential.helper "$helper_value"
  360. printf 'url=%s\nusername=%s\npassword=%s\n\n' "$REMOTE_URL" "$GIT_HTTP_USERNAME" "$GIT_HTTP_TOKEN" | run_as_service_user git credential approve
  361. else
  362. log_err "Warning: token provided but remote is not HTTPS; credential.helper store setup skipped."
  363. log_err "Warning: fallback to header-token-file auth mode for this install."
  364. GIT_USE_CREDENTIAL_STORE="0"
  365. fi
  366. fi
  367. if [[ "$GIT_USE_CREDENTIAL_STORE" != "1" ]]; then
  368. TOKEN_FILE="${SERVICE_STATE_DIR}/git_http_token"
  369. printf '%s\n' "$GIT_HTTP_TOKEN" >"$TOKEN_FILE"
  370. chown "$RUN_USER:$RUN_GROUP" "$TOKEN_FILE"
  371. chmod 600 "$TOKEN_FILE"
  372. AUTH_MODE="header-token-file"
  373. fi
  374. fi
  375. run_as_service_user git config --global --add safe.directory "$APP_DIR" || true
  376. cat >"$ENV_FILE" <<EOF
  377. GIT_PUSH_ENABLED=${GIT_PUSH_ENABLED}
  378. GIT_PUSH_REQUIRED=${GIT_PUSH_ENABLED}
  379. GIT_PUSH_REMOTE=${GIT_PUSH_REMOTE}
  380. GIT_RUNTIME_BRANCH=runtime-state
  381. GIT_HTTP_USERNAME=${GIT_HTTP_USERNAME}
  382. HOME=${RUN_HOME}
  383. PEAK_START_HOUR=${PEAK_START_HOUR}
  384. PEAK_END_HOUR=${PEAK_END_HOUR}
  385. PEAK_TZ=${PEAK_TZ}
  386. PEAK_INTERVAL_MIN=${PEAK_INTERVAL_MIN}
  387. OFFPEAK_INTERVAL_MIN=${OFFPEAK_INTERVAL_MIN}
  388. EOF
  389. if [[ "$GIT_USE_CREDENTIAL_STORE" == "1" ]]; then
  390. if [[ -n "$GIT_CREDENTIALS_FILE" ]]; then
  391. printf 'GIT_CREDENTIAL_HELPER=store --file %s\n' "$GIT_CREDENTIALS_FILE" >>"$ENV_FILE"
  392. else
  393. printf 'GIT_CREDENTIAL_HELPER=store\n' >>"$ENV_FILE"
  394. fi
  395. fi
  396. if [[ -n "$TOKEN_FILE" ]]; then
  397. printf 'GIT_HTTP_TOKEN_FILE=%s\n' "$TOKEN_FILE" >>"$ENV_FILE"
  398. fi
  399. chown root:root "$ENV_FILE"
  400. chmod 600 "$ENV_FILE"
  401. cat >"/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
  402. [Unit]
  403. Description=VMess Domain Rotator updater
  404. After=network-online.target
  405. Wants=network-online.target
  406. [Service]
  407. Type=oneshot
  408. User=${RUN_USER}
  409. Group=${RUN_GROUP}
  410. SyslogIdentifier=${SERVICE_NAME}
  411. WorkingDirectory=${APP_DIR}
  412. EnvironmentFile=-${ENV_FILE}
  413. UMask=0077
  414. ExecStart=/bin/bash "${APP_DIR}/scripts/run_update_and_commit.sh" "${CONFIG_PATH}"
  415. EOF
  416. cat >"/etc/systemd/system/${SERVICE_NAME}.timer" <<EOF
  417. [Unit]
  418. Description=Run VMess Domain Rotator every ${TIMER_INTERVAL}
  419. [Timer]
  420. OnBootSec=2min
  421. OnUnitActiveSec=${TIMER_INTERVAL}
  422. AccuracySec=30s
  423. Unit=${SERVICE_NAME}.service
  424. Persistent=true
  425. [Install]
  426. WantedBy=timers.target
  427. EOF
  428. systemctl daemon-reload
  429. systemctl enable --now "${SERVICE_NAME}.timer"
  430. systemctl start "${SERVICE_NAME}.service"
  431. log ""
  432. log "✓ Installation complete!"
  433. log ""
  434. log "Configuration:"
  435. log " Working directory: ${APP_DIR}"
  436. log " Config path: ${CONFIG_PATH}"
  437. log " Service user: ${RUN_USER}"
  438. log " Service group: ${RUN_GROUP}"
  439. log " Timer interval: ${TIMER_INTERVAL}"
  440. log " Peak hour: ${PEAK_START_HOUR} to ${PEAK_END_HOUR} (${PEAK_TZ})"
  441. log " Peak interval: ${PEAK_INTERVAL}"
  442. log " Off-peak interval: ${OFFPEAK_INTERVAL}"
  443. log " Push enabled: ${GIT_PUSH_ENABLED}"
  444. log " Push remote: ${GIT_PUSH_REMOTE}"
  445. log " Auth mode: ${AUTH_MODE}"
  446. log " Env file: ${ENV_FILE}"
  447. log ""
  448. log "Commands:"
  449. log " Check status: systemctl status ${SERVICE_NAME}.timer"
  450. log " View logs: journalctl -u ${SERVICE_NAME}.service -n 50 --no-pager"
  451. log " Manual run: sudo systemctl start ${SERVICE_NAME}.service"
  452. log " Force commit: sudo -u ${RUN_USER} /bin/bash ${APP_DIR}/scripts/run_update_and_commit.sh --force-commit ${CONFIG_PATH}"
  453. log ""