Author SHA1 Message Date
rogeeandmultica-agent 925ce84339 HH-620: secure default host bindings
Docker image / Test (pull_request) Successful in 39s
Docker image / Build and publish (pull_request) Successful in 3m2s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-24 17:44:55 +08:00
rogeeandmultica-agent 6a349f62c8 HH-620: harden authentication and volume rebuild
Docker image / Test (pull_request) Successful in 38s
Docker image / Build and publish (pull_request) Successful in 2m15s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-24 17:18:29 +08:00
rogeeandmultica-agent ab0f9d3eec HH-620: require authentication before exposing setup
Docker image / Test (pull_request) Successful in 39s
Docker image / Build and publish (pull_request) Successful in 2m41s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-24 16:44:55 +08:00
rogeeandmultica-agent 8d6e7c0098 HH-620: expose SSClash Web UI on port 9091
Docker image / Test (pull_request) Successful in 36s
Docker image / Build and publish (pull_request) Successful in 2m19s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-24 16:12:38 +08:00
rogee 39f1841bc8 HH-609: fix packaged ACL4SSR providers (#2)
Docker image / Test (push) Successful in 41s
Docker image / Build and publish (push) Failing after 23s
2026-08-24 15:00:34 +08:00
rogee 37643321fc HH-594: generate ACL4SSR subscription config (#1)
Docker image / Test (push) Successful in 38s
Docker image / Build and publish (push) Failing after 31s
2026-08-24 12:45:44 +08:00
Rogee 05e78dc882 ci: publish amd64 image to GHCR
Docker image / Test (push) Canceled after 0s
Docker image / Build and publish (push) Canceled after 0s
2026-08-21 13:55:26 +08:00
15 changed files with 1495 additions and 144 deletions
+5 -2
View File
@@ -1,6 +1,9 @@
IMAGE_NAME=mohomo-docker:local
CONTAINER_NAME=mohomo-docker
WEB_BIND=0.0.0.0
SUBSCRIPTION_URL=https://subscription.example.invalid/mihomo
SSCLASH_PASSWORD=
# 9091 is always host-loopback; expose it through a host HTTPS reverse proxy.
WEB_PORT=9091
PROXY_BIND=0.0.0.0
# Public opt-in: use 0.0.0.0 only behind a trusted-network firewall/ACL.
PROXY_BIND=127.0.0.1
PROXY_PORT=7890
+87
View File
@@ -0,0 +1,87 @@
name: Docker image
on:
push:
branches:
- main
tags:
- "v*"
pull_request:
branches:
- main
workflow_dispatch:
permissions:
contents: read
concurrency:
group: docker-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Go
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
cache: false
- name: Run tests
run: ./scripts/test.sh
build:
name: Build and publish
needs: test
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- name: Log in to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Generate image metadata
id: meta
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=sha-
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
- name: Build and push image
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
context: .
platforms: linux/amd64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max,ignore-error=true
provenance: mode=max
sbom: true
+1
View File
@@ -22,3 +22,4 @@
- Do not commit SSClash or Mihomo binaries to this repository.
- The Dockerfile may link to official release URLs and users build the image for their own deployment.
- Do not publish a prebuilt image containing SSClash without permission from its copyright holder.
- GitHub Actions may push the amd64 image to private GHCR for this deployment; do not make the package public without that permission.
+19 -3
View File
@@ -47,6 +47,20 @@ RUN case "${TARGETARCH}" in \
gzip -d mihomo.gz; \
chmod 0755 mihomo
FROM alpine:${ALPINE_VERSION} AS acl4ssr-assets
ARG ACL4SSR_REF=6e27259b8625e360699c014f98f978ee7408c644
ARG ACL4SSR_SHA256=72229e2f0a38fc9776720a20dd4ecb44fdd0b0704bbf1f5141732562a237bff2
RUN apk add --no-cache ca-certificates curl
RUN curl --fail --show-error --silent --location --retry 3 \
--output /tmp/acl4ssr.tar.gz \
"https://github.com/ACL4SSR/ACL4SSR/archive/${ACL4SSR_REF}.tar.gz"; \
printf '%s %s\n' "${ACL4SSR_SHA256}" /tmp/acl4ssr.tar.gz | sha256sum -c -; \
mkdir -p /out/rules; \
tar -xzf /tmp/acl4ssr.tar.gz -C /out/rules --strip-components=3 \
"ACL4SSR-${ACL4SSR_REF}/Clash/Providers"; \
tar -xOzf /tmp/acl4ssr.tar.gz "ACL4SSR-${ACL4SSR_REF}/LICENCE" \
> /out/ACL4SSR-LICENSE
FROM alpine:${ALPINE_VERSION}
RUN apk add --no-cache ca-certificates curl gzip tzdata \
&& addgroup -S ssclash \
@@ -56,17 +70,19 @@ RUN apk add --no-cache ca-certificates curl gzip tzdata \
COPY --from=bootstrap-builder /out/bootstrap /usr/local/bin/bootstrap
COPY --from=release-assets /assets/ssclash /usr/local/bin/ssclash
COPY --from=release-assets /assets/mihomo /usr/local/lib/ssclash/clash
COPY --from=acl4ssr-assets /out/rules /usr/local/share/ssclash/rules
COPY --from=acl4ssr-assets /out/ACL4SSR-LICENSE /usr/local/share/licenses/ACL4SSR-LICENSE
COPY config/config.yaml /usr/local/share/ssclash/config.yaml
ENV SSCLASH_ROOT=/opt/clash \
SSCLASH_TMP=/tmp/ssclash \
SSCLASH_PLATFORM=linux \
SSCLASH_ADDR=:9091
SSCLASH_ADDR=0.0.0.0:9091 \
SAFE_PATHS=/usr/local/share/ssclash
USER ssclash
VOLUME ["/opt/clash"]
EXPOSE 9091/tcp 7890/tcp 7890/udp
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=4 \
CMD curl --fail --silent --show-error http://127.0.0.1:9091/ >/dev/null
CMD curl --fail --silent --show-error http://127.0.0.1:9090/version >/dev/null
ENTRYPOINT ["/usr/local/bin/bootstrap"]
CMD ["serve"]
+2
View File
@@ -22,3 +22,5 @@ SOFTWARE.
This license covers only the original files in this repository. Downloaded
SSClash-Go and Mihomo binaries remain subject to their respective licenses.
ACL4SSR rule files are packaged from their pinned upstream revision and remain
subject to ACL4SSR's CC BY-SA 4.0 license, included in the built image.
+41 -31
View File
@@ -1,63 +1,73 @@
# mohomo-docker
Docker packaging for the official SSClash-Go daemon and Mihomo core. It intentionally provides only:
- SSClash embedded Web UI on port `9091`;
- Mihomo HTTP/SOCKS mixed proxy on port `7890`;
- server mode, without TUN, transparent proxy, firewall, routing, or DNS interception.
Minimal Mihomo service with the ACL4SSR `Online Full MultiMode` routing model. The host publishes the SSClash Web UI on loopback port `9091` and the mixed proxy on loopback port `7890` by default; Mihomo's controller remains private to the container.
## Quick start
```sh
cp .env.example .env
# Generate a password, then set SUBSCRIPTION_URL and SSCLASH_PASSWORD in .env.
openssl rand -base64 24
docker compose up -d --build
docker compose logs -f ssclash
```
Open `http://<server>:9091`, create the administrator password, review `config.yaml`, and start the proxy from the Web UI. The seeded configuration exposes a direct-only `PROXY` group so port `7890` can be tested before adding a subscription.
Configure clients with either of these endpoints:
The subscription endpoint must return a Clash/Mihomo proxy-provider YAML document (`proxies:`). Use an HTTPS endpoint when its URL contains a credential. A fresh volume refuses to start without an `SSCLASH_PASSWORD` of at least 12 characters; bootstrap uses SSClash's own `setpass` command before the Web listener starts. On the Docker host, open `http://127.0.0.1:9091` and log in with that password. A valid existing authentication file is preserved, so later starts do not require or replace the password. Local proxy clients connect to either endpoint:
```text
HTTP proxy: http://<server>:7890
SOCKS5 proxy: socks5://<server>:7890
HTTP proxy: http://127.0.0.1:7890
SOCKS5 proxy: socks5://127.0.0.1:7890
```
The Web UI and proxy listen on all host interfaces by default. Change `WEB_BIND` or `PROXY_BIND` in `.env` to restrict them. Do not expose the Web UI to the Internet without HTTPS and an additional access-control layer. Configure Mihomo proxy authentication before exposing port `7890` outside a trusted network.
The Compose boundary fixes plaintext `9091` to host loopback. To provide the required external Web access, configure a host HTTPS reverse proxy to `127.0.0.1:${WEB_PORT:-9091}`; for example, a host-native Caddy configuration is:
```caddyfile
ssclash.example.com {
reverse_proxy 127.0.0.1:9091
}
```
Replace the domain and ensure its DNS reaches the host; Caddy then obtains and serves the TLS certificate. Do not publish 9091 directly as public HTTP.
`WEB_PORT`, `PROXY_BIND`, and `PROXY_PORT` are optional deployment overrides. Port 7890 also defaults to `127.0.0.1`; setting `PROXY_BIND=0.0.0.0` is the explicit public opt-in. The packaged Mihomo proxy has no client authentication, so use that opt-in only when a host firewall or network ACL restricts clients to a trusted range. Prefer binding `PROXY_BIND` to a specific trusted host address.
## Update and secret handling
The bootstrap fetches the subscription once before startup and every hour thereafter. Each candidate is limited to 16 MiB and validated with the packaged Mihomo binary before an atomic replacement and hot reload. A failed reload restores and reloads the previous provider; if that recovery cannot be confirmed, both services stop instead of running with uncertain state.
The subscription URL and bootstrap administrator password are removed from child-process environments and never printed. The password is persisted only as SSClash's PBKDF2 authentication file. Before opening the Web listener, bootstrap requires that file to be a readable, process-owned regular file with exact mode `0600` and SSClash v6.1.0's expected PBKDF2 format; a missing or abnormal file fails closed. The generated configuration contains only a local provider path. Subscription data lives under `/dev/shm/mohomo`, so neither the image nor the `/opt/clash` volume stores its URL, response, or node credentials. Container restarts intentionally fetch a fresh subscription instead of persisting credentials.
Do not commit `.env`; it is ignored by Git. Docker still exposes bootstrap environment variables to principals allowed to inspect the container, so restrict Docker daemon access.
## ACL4SSR rules
The image packages ACL4SSR provider files from pinned commit `6e27259b8625e360699c014f98f978ee7408c644`. The archive checksum is pinned in the Dockerfile. Runtime routing uses only those local files—there is no online rule converter or rule-provider download.
The generated groups and rule order mirror `ACL4SSR_Online_Full_MultiMode.ini`: automatic selection, fallback, load balancing, regional selectors, service/media splits, ad rejection, China direct routing, GFW routing, and final fallback.
## Persistent data
The named volume `ssclash-data` is mounted at `/opt/clash` and stores:
`/opt/clash` stores only SSClash settings, the packaged Mihomo core, and the non-secret generated configuration. Bootstrap creates missing files, preserves existing regular non-empty files, enforces `OPERATING_MODE=server` and `PROXY_MODE=none`, and rejects corrupt or ambiguous persistent state. On container replacement it repairs only SSClash's exact `rule-providers` and `proxy-providers` links into `SSCLASH_TMP`; unexpected links are rejected without deleting their targets.
- `config.yaml` and named configurations;
- SSClash settings and administrator credentials;
- subscription, rule-provider, and proxy-provider files;
- the active Mihomo core and its runtime data.
## Reproducible inputs
The bootstrap process creates missing files only. Existing Mihomo and configuration files are preserved. It explicitly enforces `OPERATING_MODE=server` and `PROXY_MODE=none`; the latter prevents SSClash from synchronizing gateway-only TProxy, redirect, or TUN listeners into `config.yaml`. Duplicate mode entries or empty runtime files cause startup to fail with a diagnostic message.
The Dockerfile pins:
Resetting the volume deletes configuration and credentials. Inspect the exact Compose project and volume name before doing so.
- SSClash-Go `v6.1.0`, verified with its release checksum file;
- Mihomo `v1.19.30`, verified with repository-pinned SHA-256 values;
- ACL4SSR rules by commit and archive SHA-256.
## Version updates
The GitHub Actions workflow builds `linux/amd64`, runs tests first, publishes only to private GHCR, and attaches SBOM and provenance. Do not make an image containing SSClash-Go public without permission from its copyright holder.
Versions are pinned in the Dockerfile:
- SSClash-Go `v6.1.0`;
- Mihomo `v1.19.30`.
SSClash is verified against the checksum file from its official release. Mihomo amd64 and arm64 archives are verified against pinned SHA-256 values. To update either component, update the version and checksums together, then run the complete test suite.
## Tests
## Verification
```sh
./scripts/test.sh
./tests/container-smoke.sh
```
The unit suite enforces at least 65% statement coverage for bootstrap behavior. The container smoke test builds the image, validates the Mihomo configuration, starts the Web UI with all Linux capabilities dropped, authenticates to SSClash, starts Mihomo through the Web API, rejects gateway-listener/error regressions, and sends an HTTPS request through the mapped mixed proxy port.
The unit suite checks strict fail-closed authentication-file validation, provider-link recovery, atomic rollback, URL redaction, server-only listeners, local ACL4SSR providers, and at least 65% bootstrap coverage. The container smoke test verifies loopback-only Compose defaults and proxy-only public opt-in, proves 7890/9091 are unreachable through a non-loopback host address, checks fresh-volume authentication and credential isolation, and repeats health and login checks after recreating the container with the same volume.
## License boundary
This repository contains only original Docker packaging and bootstrap code. It downloads SSClash-Go and Mihomo from their official releases while building.
SSClash-Go uses a proprietary binary license that permits personal/internal use but prohibits redistributing its binary to third parties. Do not publish the resulting image without the copyright holder's permission. Mihomo is separately licensed under GPL-3.0.
Original packaging code is MIT licensed. SSClash-Go, Mihomo, and packaged ACL4SSR rule files retain their upstream licenses; the image includes ACL4SSR's CC BY-SA 4.0 text.
+29 -9
View File
@@ -1,19 +1,24 @@
package main
import (
"context"
"errors"
"log"
"os"
"path/filepath"
"os/signal"
"syscall"
"time"
"git.ipao.vip/rogee/mohomo-docker/internal/bootstrap"
)
const (
defaultRoot = "/opt/clash"
defaultSSClashTemp = "/tmp/ssclash"
defaultCoreSource = "/usr/local/lib/ssclash/clash"
defaultConfigSource = "/usr/local/share/ssclash/config.yaml"
ssclashBinary = "/usr/local/bin/ssclash"
defaultRuntimeDir = "/dev/shm/mohomo"
)
func main() {
@@ -23,28 +28,43 @@ func main() {
result, err := bootstrap.Prepare(bootstrap.Config{
Root: root,
SSClashTemp: envOrDefault("SSCLASH_TMP", defaultSSClashTemp),
CoreSource: defaultCoreSource,
ConfigSource: defaultConfigSource,
})
if err != nil {
log.Fatalf("bootstrap: runtime preparation failed: %v", err)
}
adminPasswordInitialized, err := bootstrap.EnsureAdminPassword(root, ssclashBinary, os.Getenv("SSCLASH_PASSWORD"))
if err != nil {
log.Fatalf("bootstrap: admin authentication setup failed: %v", err)
}
log.Printf(
"bootstrap: ready root=%s core_initialized=%t config_initialized=%t server_settings_changed=%t",
"bootstrap: ready root=%s core_initialized=%t config_initialized=%t server_settings_changed=%t admin_password_initialized=%t",
root,
result.CoreInitialized,
result.ConfigInitialized,
result.ServerSettingsChanged,
adminPasswordInitialized,
)
arguments := os.Args[1:]
if len(arguments) == 0 {
arguments = []string{"serve"}
subscriptionURL := os.Getenv("SUBSCRIPTION_URL")
if subscriptionURL == "" {
log.Fatal("bootstrap: SUBSCRIPTION_URL is required")
}
argv := append([]string{filepath.Base(ssclashBinary)}, arguments...)
log.Printf("bootstrap: exec path=%s command=%s", ssclashBinary, arguments[0])
if err := syscall.Exec(ssclashBinary, argv, os.Environ()); err != nil {
log.Fatalf("bootstrap: exec failed: %v", err)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
err = bootstrap.Run(ctx, bootstrap.RuntimeConfig{
CoreBinary: defaultCoreSource,
SSClashBinary: ssclashBinary,
ConfigSource: defaultConfigSource,
RuntimeDir: defaultRuntimeDir,
SubscriptionURL: subscriptionURL,
UpdateInterval: time.Hour,
})
if err != nil && !errors.Is(err, context.Canceled) {
log.Fatalf("bootstrap: service failed: %v", err)
}
}
+7 -3
View File
@@ -6,10 +6,14 @@ services:
container_name: ${CONTAINER_NAME:-mohomo-docker}
restart: unless-stopped
init: true
environment:
SUBSCRIPTION_URL: ${SUBSCRIPTION_URL:?set SUBSCRIPTION_URL in .env}
SSCLASH_PASSWORD: ${SSCLASH_PASSWORD:-}
ports:
- "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-9091}:9091/tcp"
- "${PROXY_BIND:-0.0.0.0}:${PROXY_PORT:-7890}:7890/tcp"
- "${PROXY_BIND:-0.0.0.0}:${PROXY_PORT:-7890}:7890/udp"
# Keep the plaintext Web UI behind a host-local HTTPS reverse proxy.
- "127.0.0.1:${WEB_PORT:-9091}:9091/tcp"
- "${PROXY_BIND:-127.0.0.1}:${PROXY_PORT:-7890}:7890/tcp"
- "${PROXY_BIND:-127.0.0.1}:${PROXY_PORT:-7890}:7890/udp"
volumes:
- ssclash-data:/opt/clash
cap_drop:
+196 -7
View File
@@ -7,16 +7,205 @@ ipv6: false
external-controller: 127.0.0.1:9090
profile:
store-selected: true
store-fake-ip: true
store-selected: false
store-fake-ip: false
proxies: []
proxy-providers:
subscription:
type: file
path: ./subscription.yaml
health-check:
enable: true
url: http://www.gstatic.com/generate_204
interval: 300
lazy: true
proxy-groups:
- name: PROXY
- name: 🚀 节点选择
type: select
proxies:
- DIRECT
proxies: [♻️ 自动选择, 🔯 故障转移, 🔮 负载均衡, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 🚀 手动切换
type: select
use: [subscription]
- name: ♻️ 自动选择
type: url-test
use: [subscription]
url: http://www.gstatic.com/generate_204
interval: 300
tolerance: 50
- name: 🔯 故障转移
type: fallback
use: [subscription]
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🔮 负载均衡
type: load-balance
use: [subscription]
url: http://www.gstatic.com/generate_204
interval: 300
strategy: consistent-hashing
- name: 🇭🇰 香港节点
type: url-test
use: [subscription]
filter: "(?i)(港|HK|Hong ?Kong)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🇨🇳 台湾节点
type: url-test
use: [subscription]
filter: "(?i)(台|TW|Taiwan)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🇸🇬 狮城节点
type: url-test
use: [subscription]
filter: "(?i)(新加坡|坡|狮城|SG|Singapore)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🇯🇵 日本节点
type: url-test
use: [subscription]
filter: "(?i)(日本|东京|大阪|JP|Japan)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🇺🇲 美国节点
type: url-test
use: [subscription]
filter: "(?i)(美|US|United ?States|Los ?Angeles|Seattle)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🇰🇷 韩国节点
type: url-test
use: [subscription]
filter: "(?i)(韩|韓|KR|Korea|Seoul)"
url: http://www.gstatic.com/generate_204
interval: 300
- name: 🎥 奈飞节点
type: select
use: [subscription]
filter: "(?i)(NF|奈飞|解锁|Netflix|Media)"
- name: 📲 电报消息
type: select
proxies: [🚀 节点选择, ♻️ 自动选择, 🇸🇬 狮城节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 💬 Ai平台
type: select
proxies: [🚀 节点选择, ♻️ 自动选择, 🇸🇬 狮城节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 📹 油管视频
type: select
proxies: [🚀 节点选择, ♻️ 自动选择, 🇸🇬 狮城节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 🎥 奈飞视频
type: select
proxies: [🎥 奈飞节点, 🚀 节点选择, ♻️ 自动选择, 🇸🇬 狮城节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 📺 巴哈姆特
type: select
proxies: [🇨🇳 台湾节点, 🚀 节点选择, 🚀 手动切换, DIRECT]
- name: 📺 哔哩哔哩
type: select
proxies: [🎯 全球直连, 🇨🇳 台湾节点, 🇭🇰 香港节点]
- name: 🌍 国外媒体
type: select
proxies: [🚀 节点选择, ♻️ 自动选择, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换, DIRECT]
- name: 🌏 国内媒体
type: select
proxies: [DIRECT, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🚀 手动切换]
- name: 📢 谷歌FCM
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: Ⓜ️ 微软Bing
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: Ⓜ️ 微软云盘
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: Ⓜ️ 微软服务
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: 🍎 苹果服务
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: 🎮 游戏平台
type: select
proxies: [DIRECT, 🚀 节点选择, 🇺🇲 美国节点, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇰🇷 韩国节点, 🚀 手动切换]
- name: 🎶 网易音乐
type: select
proxies: [DIRECT, 🚀 节点选择, ♻️ 自动选择]
- name: 🎯 全球直连
type: select
proxies: [DIRECT, 🚀 节点选择, ♻️ 自动选择]
- name: 🛑 广告拦截
type: select
proxies: [REJECT, DIRECT]
- name: 🍃 应用净化
type: select
proxies: [REJECT, DIRECT]
- name: 🐟 漏网之鱼
type: select
proxies: [🚀 节点选择, ♻️ 自动选择, DIRECT, 🇭🇰 香港节点, 🇨🇳 台湾节点, 🇸🇬 狮城节点, 🇯🇵 日本节点, 🇺🇲 美国节点, 🇰🇷 韩国节点, 🚀 手动切换]
rule-providers:
LocalAreaNetwork: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/LocalAreaNetwork.yaml}
UnBan: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/UnBan.yaml}
BanAD: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/BanAD.yaml}
BanProgramAD: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/BanProgramAD.yaml}
GoogleFCM: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/GoogleFCM.yaml}
GoogleCN: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/GoogleCN.yaml}
SteamCN: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/SteamCN.yaml}
Bing: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Bing.yaml}
OneDrive: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/OneDrive.yaml}
Microsoft: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Microsoft.yaml}
Apple: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Apple.yaml}
Telegram: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Telegram.yaml}
AI: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/AI.yaml}
OpenAi: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/OpenAi.yaml}
NetEaseMusic: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/NetEaseMusic.yaml}
Epic: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Epic.yaml}
Origin: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Origin.yaml}
Sony: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Sony.yaml}
Steam: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Steam.yaml}
Nintendo: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Nintendo.yaml}
YouTube: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/YouTube.yaml}
Netflix: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Netflix.yaml}
Bahamut: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Bahamut.yaml}
BilibiliHMT: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/BilibiliHMT.yaml}
Bilibili: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Bilibili.yaml}
ChinaMedia: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/ChinaMedia.yaml}
ProxyMedia: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/ProxyMedia.yaml}
ProxyGFWlist: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/ProxyGFWlist.yaml}
ChinaDomain: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/ChinaDomain.yaml}
ChinaCompanyIp: {type: file, behavior: ipcidr, format: yaml, path: /usr/local/share/ssclash/rules/ChinaCompanyIp.yaml}
Download: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Download.yaml}
rules:
- MATCH,PROXY
- RULE-SET,LocalAreaNetwork,🎯 全球直连
- RULE-SET,UnBan,🎯 全球直连
- RULE-SET,BanAD,🛑 广告拦截
- RULE-SET,BanProgramAD,🍃 应用净化
- RULE-SET,GoogleFCM,📢 谷歌FCM
- RULE-SET,GoogleCN,🎯 全球直连
- RULE-SET,SteamCN,🎯 全球直连
- RULE-SET,Bing,Ⓜ️ 微软Bing
- RULE-SET,OneDrive,Ⓜ️ 微软云盘
- RULE-SET,Microsoft,Ⓜ️ 微软服务
- RULE-SET,Apple,🍎 苹果服务
- RULE-SET,Telegram,📲 电报消息
- RULE-SET,AI,💬 Ai平台
- RULE-SET,OpenAi,💬 Ai平台
- RULE-SET,NetEaseMusic,🎶 网易音乐
- RULE-SET,Epic,🎮 游戏平台
- RULE-SET,Origin,🎮 游戏平台
- RULE-SET,Sony,🎮 游戏平台
- RULE-SET,Steam,🎮 游戏平台
- RULE-SET,Nintendo,🎮 游戏平台
- RULE-SET,YouTube,📹 油管视频
- RULE-SET,Netflix,🎥 奈飞视频
- RULE-SET,Bahamut,📺 巴哈姆特
- RULE-SET,BilibiliHMT,📺 哔哩哔哩
- RULE-SET,Bilibili,📺 哔哩哔哩
- RULE-SET,ChinaMedia,🌏 国内媒体
- RULE-SET,ProxyMedia,🌍 国外媒体
- RULE-SET,ProxyGFWlist,🚀 节点选择
- RULE-SET,ChinaDomain,🎯 全球直连
- RULE-SET,ChinaCompanyIp,🎯 全球直连
- RULE-SET,Download,🎯 全球直连
- GEOIP,CN,🎯 全球直连
- MATCH,🐟 漏网之鱼
+435 -2
View File
@@ -1,14 +1,29 @@
package bootstrap
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
)
const (
maxSubscriptionSize = 16 << 20
minAdminPasswordLength = 12
)
var errMihomoStateUncertain = errors.New("Mihomo subscription state could not be restored")
type enforcedSetting struct {
key string
value string
@@ -24,14 +39,15 @@ var runtimeDirectories = []string{
".ssclash",
"configs",
"local-rules",
"rule-providers",
"proxy-providers",
"subscriptions",
"ui",
}
var managedProviderDirectories = []string{"rule-providers", "proxy-providers"}
type Config struct {
Root string
SSClashTemp string
CoreSource string
ConfigSource string
}
@@ -42,6 +58,15 @@ type Result struct {
ServerSettingsChanged bool
}
type RuntimeConfig struct {
CoreBinary string
SSClashBinary string
ConfigSource string
RuntimeDir string
SubscriptionURL string
UpdateInterval time.Duration
}
func Prepare(config Config) (Result, error) {
var result Result
root := filepath.Clean(config.Root)
@@ -51,6 +76,10 @@ func Prepare(config Config) (Result, error) {
if !filepath.IsAbs(root) {
return result, fmt.Errorf("root must be absolute: %q", config.Root)
}
ssclashTemp := filepath.Clean(config.SSClashTemp)
if !filepath.IsAbs(ssclashTemp) || ssclashTemp == string(filepath.Separator) {
return result, fmt.Errorf("unsafe SSClash temporary directory %q", config.SSClashTemp)
}
if err := validateSource(config.CoreSource, "core source"); err != nil {
return result, err
}
@@ -63,6 +92,11 @@ func Prepare(config Config) (Result, error) {
return result, fmt.Errorf("create runtime directory %s: %w", directory, err)
}
}
for _, directory := range managedProviderDirectories {
if err := reconcileManagedProviderDirectory(root, ssclashTemp, directory); err != nil {
return result, err
}
}
var err error
result.CoreInitialized, err = copyIfAbsent(config.CoreSource, filepath.Join(root, "bin", "clash"), 0o755)
@@ -81,6 +115,405 @@ func Prepare(config Config) (Result, error) {
return result, nil
}
func EnsureAdminPassword(root, binary, password string) (bool, error) {
root = filepath.Clean(root)
if root == "." || root == string(filepath.Separator) || !filepath.IsAbs(root) {
return false, fmt.Errorf("unsafe root %q", root)
}
passwordPath := filepath.Join(root, ".ssclash", "password")
configured, err := adminPasswordConfigured(passwordPath)
if err != nil {
return false, err
}
if configured {
return false, nil
}
if password == "" {
return false, errors.New("SSCLASH_PASSWORD is required to initialize a fresh volume")
}
if len(password) < minAdminPasswordLength {
return false, fmt.Errorf("SSCLASH_PASSWORD must be at least %d characters", minAdminPasswordLength)
}
if err := validateSource(binary, "SSClash binary"); err != nil {
return false, err
}
command := exec.Command(binary, "setpass", password)
command.Env = childEnvironment()
command.Stdout = io.Discard
command.Stderr = io.Discard
if err := command.Run(); err != nil {
return false, errors.New("SSClash password initialization failed")
}
configured, err = adminPasswordConfigured(passwordPath)
if err != nil {
return false, err
}
if !configured {
return false, errors.New("SSClash password initialization did not create an authentication file")
}
return true, nil
}
func adminPasswordConfigured(path string) (bool, error) {
return adminPasswordConfiguredFor(path, uint32(os.Geteuid()), uint32(os.Getegid()))
}
func adminPasswordConfiguredFor(path string, expectedUID, expectedGID uint32) (bool, error) {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("inspect SSClash authentication file: %w", err)
}
if !info.Mode().IsRegular() {
return false, errors.New("SSClash authentication file must be a regular file")
}
if info.Mode().Perm() != 0o600 {
return false, fmt.Errorf("SSClash authentication file permissions are %o; want 600", info.Mode().Perm())
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return false, errors.New("SSClash authentication file ownership could not be verified")
}
if stat.Uid != expectedUID || stat.Gid != expectedGID {
return false, fmt.Errorf("SSClash authentication file owner is %d:%d; want %d:%d", stat.Uid, stat.Gid, expectedUID, expectedGID)
}
file, err := os.Open(path)
if err != nil {
return false, fmt.Errorf("read SSClash authentication file: %w", err)
}
defer file.Close()
openedInfo, err := file.Stat()
if err != nil {
return false, fmt.Errorf("inspect opened SSClash authentication file: %w", err)
}
if !os.SameFile(info, openedInfo) {
return false, errors.New("SSClash authentication file changed while being verified")
}
content, err := io.ReadAll(io.LimitReader(file, 257))
if err != nil {
return false, fmt.Errorf("read SSClash authentication file: %w", err)
}
if len(content) > 256 {
return false, errors.New("SSClash authentication file is too large")
}
if err := validateAdminPasswordHash(content); err != nil {
return false, err
}
return true, nil
}
func validateAdminPasswordHash(content []byte) error {
text := string(content)
if !strings.HasSuffix(text, "\n") {
return errors.New("SSClash authentication file has an invalid password hash")
}
parts := strings.Split(strings.TrimSuffix(text, "\n"), "$")
if len(parts) != 4 || parts[0] != "pbkdf2" || parts[1] != "120000" || len(parts[2]) != 32 || len(parts[3]) != 64 {
return errors.New("SSClash authentication file has an invalid password hash")
}
if _, err := hex.DecodeString(parts[2]); err != nil {
return errors.New("SSClash authentication file has an invalid password hash")
}
if _, err := hex.DecodeString(parts[3]); err != nil {
return errors.New("SSClash authentication file has an invalid password hash")
}
return nil
}
func reconcileManagedProviderDirectory(root, ssclashTemp, directory string) error {
path := filepath.Join(root, directory)
expectedTarget := filepath.Join(ssclashTemp, directory)
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(path, 0o755); err != nil {
return fmt.Errorf("create runtime directory %s: %w", directory, err)
}
return nil
}
if err != nil {
return fmt.Errorf("inspect runtime directory %s: %w", directory, err)
}
if info.IsDir() {
return nil
}
if info.Mode()&os.ModeSymlink == 0 {
return fmt.Errorf("runtime path %s is not a directory", directory)
}
target, err := os.Readlink(path)
if err != nil {
return fmt.Errorf("read runtime symlink %s: %w", directory, err)
}
if target != expectedTarget {
return fmt.Errorf("runtime path %s has unexpected symlink target %q", directory, target)
}
if err := os.Remove(path); err != nil {
return fmt.Errorf("remove managed runtime symlink %s: %w", directory, err)
}
if err := os.MkdirAll(path, 0o755); err != nil {
return fmt.Errorf("recreate runtime directory %s: %w", directory, err)
}
return nil
}
func Run(ctx context.Context, config RuntimeConfig) error {
if err := validateSubscriptionURL(config.SubscriptionURL); err != nil {
return err
}
if config.UpdateInterval <= 0 {
return errors.New("subscription update interval must be positive")
}
runtimeDir := filepath.Clean(config.RuntimeDir)
if !filepath.IsAbs(runtimeDir) || runtimeDir == string(filepath.Separator) {
return fmt.Errorf("unsafe runtime directory %q", config.RuntimeDir)
}
for path, label := range map[string]string{
config.CoreBinary: "Mihomo core",
config.SSClashBinary: "SSClash binary",
config.ConfigSource: "config source",
} {
if err := validateSource(path, label); err != nil {
return err
}
}
if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
return fmt.Errorf("create in-memory runtime directory: %w", err)
}
runtimeConfig := filepath.Join(runtimeDir, "config.yaml")
if err := copyFile(config.ConfigSource, runtimeConfig, 0o600); err != nil {
return fmt.Errorf("prepare in-memory config: %w", err)
}
activeSubscription := filepath.Join(runtimeDir, "subscription.yaml")
client := &http.Client{Timeout: 30 * time.Second}
validate := func(candidate string) error {
return validateSubscription(ctx, config, runtimeConfig, candidate)
}
reload := func(ctx context.Context) error {
return reloadSubscription(ctx, client)
}
if err := updateSubscription(ctx, client, config.SubscriptionURL, activeSubscription, validate); err != nil {
return fmt.Errorf("initial subscription update failed")
}
if err := validateMihomoConfig(ctx, config.CoreBinary, runtimeDir, runtimeConfig); err != nil {
return errors.New("generated Mihomo configuration failed validation")
}
serviceCtx, cancel := context.WithCancel(ctx)
defer cancel()
ssclash := serviceCommand(serviceCtx, config.SSClashBinary, "serve")
mihomo := serviceCommand(serviceCtx, config.CoreBinary, "-d", runtimeDir, "-f", runtimeConfig)
if err := ssclash.Start(); err != nil {
return fmt.Errorf("start SSClash: %w", err)
}
if err := mihomo.Start(); err != nil {
cancel()
_ = ssclash.Wait()
return fmt.Errorf("start Mihomo: %w", err)
}
log.Printf("bootstrap: services started mode=server subscription_update_interval=%s", config.UpdateInterval)
type processResult struct {
name string
err error
}
exits := make(chan processResult, 2)
go func() { exits <- processResult{name: "SSClash", err: ssclash.Wait()} }()
go func() { exits <- processResult{name: "Mihomo", err: mihomo.Wait()} }()
ticker := time.NewTicker(config.UpdateInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
cancel()
<-exits
<-exits
return ctx.Err()
case result := <-exits:
cancel()
<-exits
if result.err == nil {
return fmt.Errorf("%s exited", result.name)
}
return fmt.Errorf("%s exited: %w", result.name, result.err)
case <-ticker.C:
if err := updateAndReload(ctx, client, config, activeSubscription, validate, reload); errors.Is(err, errMihomoStateUncertain) {
log.Print("bootstrap: subscription rollback failed; stopping services")
cancel()
<-exits
<-exits
return err
} else if err != nil {
log.Print("bootstrap: subscription update rejected; keeping previous valid configuration")
continue
}
log.Print("bootstrap: subscription updated and reloaded")
}
}
}
func validateSubscriptionURL(raw string) error {
parsed, err := url.ParseRequestURI(raw)
if err != nil || parsed.Host == "" || (parsed.Scheme != "https" && parsed.Scheme != "http") {
return errors.New("SUBSCRIPTION_URL must be an absolute HTTP(S) URL")
}
if parsed.User != nil {
return errors.New("SUBSCRIPTION_URL must not contain user information")
}
return nil
}
func updateSubscription(ctx context.Context, client *http.Client, endpoint, target string, validate func(string) error) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return errors.New("create subscription request")
}
request.Header.Set("Accept", "application/yaml, text/yaml, text/plain")
request.Header.Set("User-Agent", "mihomo")
response, err := client.Do(request)
if err != nil {
return errors.New("subscription request failed")
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("subscription endpoint returned HTTP %d", response.StatusCode)
}
content, err := io.ReadAll(io.LimitReader(response.Body, maxSubscriptionSize+1))
if err != nil {
return errors.New("read subscription response")
}
if len(content) == 0 || len(content) > maxSubscriptionSize {
return errors.New("subscription response is empty or too large")
}
candidate := filepath.Join(filepath.Dir(target), ".subscription-candidate.yaml")
if err := atomicWrite(candidate, 0o600, func(output *os.File) error {
_, err := output.Write(content)
return err
}); err != nil {
return fmt.Errorf("write subscription candidate: %w", err)
}
defer os.Remove(candidate)
if err := validate(candidate); err != nil {
return errors.New("subscription candidate failed Mihomo validation")
}
if err := os.Rename(candidate, target); err != nil {
return fmt.Errorf("activate subscription candidate: %w", err)
}
return nil
}
func validateSubscription(ctx context.Context, config RuntimeConfig, runtimeConfig, candidate string) error {
content, err := os.ReadFile(runtimeConfig)
if err != nil {
return err
}
candidateConfig := strings.Replace(string(content), "path: ./subscription.yaml", "path: ./"+filepath.Base(candidate), 1)
if candidateConfig == string(content) {
return errors.New("subscription provider path is missing from config")
}
path := filepath.Join(config.RuntimeDir, ".candidate-config.yaml")
if err := atomicWrite(path, 0o600, func(output *os.File) error {
_, err := output.WriteString(candidateConfig)
return err
}); err != nil {
return err
}
defer os.Remove(path)
return validateMihomoConfig(ctx, config.CoreBinary, config.RuntimeDir, path)
}
func validateMihomoConfig(ctx context.Context, binary, runtimeDir, configPath string) error {
command := exec.CommandContext(ctx, binary, "-t", "-d", runtimeDir, "-f", configPath)
command.Env = childEnvironment()
command.Stdout = io.Discard
command.Stderr = io.Discard
if err := command.Run(); err != nil {
return errors.New("Mihomo validation failed")
}
return nil
}
func updateAndReload(ctx context.Context, client *http.Client, config RuntimeConfig, target string, validate func(string) error, reload func(context.Context) error) error {
previous, err := os.ReadFile(target)
if err != nil {
return err
}
if err := updateSubscription(ctx, client, config.SubscriptionURL, target, validate); err != nil {
return err
}
if err := reload(ctx); err == nil {
return nil
}
if rollbackErr := atomicWrite(target, 0o600, func(output *os.File) error {
_, writeErr := output.Write(previous)
return writeErr
}); rollbackErr != nil {
return fmt.Errorf("%w: restore previous subscription file: %v", errMihomoStateUncertain, rollbackErr)
}
if err := reload(ctx); err != nil {
return fmt.Errorf("%w: reload previous subscription", errMihomoStateUncertain)
}
return errors.New("new subscription reload failed; previous subscription restored")
}
func reloadSubscription(ctx context.Context, client *http.Client) error {
request, err := http.NewRequestWithContext(ctx, http.MethodPut, "http://127.0.0.1:9090/providers/proxies/subscription", nil)
if err != nil {
return errors.New("create Mihomo reload request")
}
response, err := client.Do(request)
if err != nil {
return errors.New("Mihomo reload request failed")
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, response.Body)
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("Mihomo reload returned HTTP %d", response.StatusCode)
}
return nil
}
func serviceCommand(ctx context.Context, binary string, arguments ...string) *exec.Cmd {
command := exec.CommandContext(ctx, binary, arguments...)
command.Env = childEnvironment()
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.Cancel = func() error {
return command.Process.Signal(syscall.SIGTERM)
}
command.WaitDelay = 10 * time.Second
return command
}
func childEnvironment() []string {
environment := os.Environ()
result := environment[:0]
for _, entry := range environment {
if strings.HasPrefix(entry, "SUBSCRIPTION_URL=") || strings.HasPrefix(entry, "SSCLASH_PASSWORD=") {
continue
}
result = append(result, entry)
}
return result
}
func copyFile(source, target string, mode os.FileMode) error {
input, err := os.Open(source)
if err != nil {
return err
}
defer input.Close()
return atomicWrite(target, mode, func(output *os.File) error {
_, err := io.Copy(output, input)
return err
})
}
func validateSource(path, label string) error {
info, err := os.Stat(path)
if err != nil {
+396
View File
@@ -1,10 +1,17 @@
package bootstrap
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestPrepareInitializesServerRuntime(t *testing.T) {
@@ -17,6 +24,7 @@ func TestPrepareInitializesServerRuntime(t *testing.T) {
result, err := Prepare(Config{
Root: root,
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: coreSource,
ConfigSource: configSource,
})
@@ -68,6 +76,7 @@ func TestPreparePreservesUserDataAndForcesServerMode(t *testing.T) {
result, err := Prepare(Config{
Root: root,
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: writeFixture(t, tempDir, "mihomo", "image-core"),
ConfigSource: writeFixture(t, tempDir, "default.yaml", "image: config\n"),
})
@@ -83,6 +92,214 @@ func TestPreparePreservesUserDataAndForcesServerMode(t *testing.T) {
assertFileContent(t, filepath.Join(root, ".ssclash", "settings"), "LOG_LEVEL=debug\nOPERATING_MODE=server\nPROXY_MODE=none\n")
}
func TestEnsureAdminPasswordFailsClosedOnFreshVolume(t *testing.T) {
t.Parallel()
_, err := EnsureAdminPassword(t.TempDir(), "unused", "")
if err == nil || !strings.Contains(err.Error(), "SSCLASH_PASSWORD") {
t.Fatalf("EnsureAdminPassword() error = %v, want missing password error", err)
}
}
func TestEnsureAdminPasswordInitializesOnlyWhenMissing(t *testing.T) {
t.Parallel()
root := filepath.Join(t.TempDir(), "data")
if err := os.MkdirAll(filepath.Join(root, ".ssclash"), 0o755); err != nil {
t.Fatal(err)
}
binary := writeFixture(t, filepath.Join(root, "bin"), "ssclash", `#!/bin/sh
set -eu
[ "$1" = setpass ]
[ "$2" = fresh-volume-password ]
password="$(dirname "$0")/../.ssclash/password"
printf 'pbkdf2$120000$0123456789abcdef0123456789abcdef$0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n' > "$password"
chmod 0600 "$password"
`)
if err := os.Chmod(binary, 0o755); err != nil {
t.Fatal(err)
}
initialized, err := EnsureAdminPassword(root, binary, "fresh-volume-password")
if err != nil {
t.Fatalf("EnsureAdminPassword() error = %v", err)
}
if !initialized {
t.Fatal("EnsureAdminPassword() initialized = false, want true")
}
assertFileContent(t, filepath.Join(root, ".ssclash", "password"), validAdminPasswordHash)
if err := os.Remove(binary); err != nil {
t.Fatal(err)
}
initialized, err = EnsureAdminPassword(root, binary, "replacement-password")
if err != nil {
t.Fatalf("EnsureAdminPassword() existing password error = %v", err)
}
if initialized {
t.Fatal("EnsureAdminPassword() replaced existing password")
}
assertFileContent(t, filepath.Join(root, ".ssclash", "password"), validAdminPasswordHash)
}
func TestAdminPasswordConfiguredRejectsUnsafeFiles(t *testing.T) {
t.Parallel()
for _, testCase := range []struct {
name string
setup func(t *testing.T, path string)
}{
{name: "mode 000", setup: passwordFileSetup(validAdminPasswordHash, 0o000)},
{name: "mode 0200", setup: passwordFileSetup(validAdminPasswordHash, 0o200)},
{name: "mode 0400", setup: passwordFileSetup(validAdminPasswordHash, 0o400)},
{name: "mode 0644", setup: passwordFileSetup(validAdminPasswordHash, 0o644)},
{name: "empty", setup: passwordFileSetup("", 0o600)},
{name: "invalid hash", setup: passwordFileSetup("pbkdf2$test\n", 0o600)},
{name: "non-hex hash", setup: passwordFileSetup("pbkdf2$120000$zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz$0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n", 0o600)},
{name: "directory", setup: func(t *testing.T, path string) {
t.Helper()
if err := os.Mkdir(path, 0o700); err != nil {
t.Fatal(err)
}
}},
{name: "symlink", setup: func(t *testing.T, path string) {
t.Helper()
target := path + ".target"
passwordFileSetup(validAdminPasswordHash, 0o600)(t, target)
if err := os.Symlink(target, path); err != nil {
t.Fatal(err)
}
}},
} {
t.Run(testCase.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "password")
testCase.setup(t, path)
if configured, err := adminPasswordConfigured(path); err == nil || configured {
t.Fatalf("adminPasswordConfigured() = %t, %v; want false, error", configured, err)
}
})
}
}
func TestAdminPasswordConfiguredRequiresOwner(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "password")
passwordFileSetup(validAdminPasswordHash, 0o600)(t, path)
for _, owner := range []struct {
name string
uid uint32
gid uint32
}{
{name: "UID", uid: uint32(os.Geteuid() + 1), gid: uint32(os.Getegid())},
{name: "GID", uid: uint32(os.Geteuid()), gid: uint32(os.Getegid() + 1)},
} {
t.Run(owner.name, func(t *testing.T) {
configured, err := adminPasswordConfiguredFor(path, owner.uid, owner.gid)
if err == nil || configured {
t.Fatalf("adminPasswordConfiguredFor() = %t, %v; want false, owner error", configured, err)
}
})
}
}
func TestAdminPasswordConfiguredAcceptsSecureFile(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "password")
passwordFileSetup(validAdminPasswordHash, 0o600)(t, path)
configured, err := adminPasswordConfigured(path)
if err != nil || !configured {
t.Fatalf("adminPasswordConfigured() = %t, %v; want true, nil", configured, err)
}
}
func TestPrepareRepairsManagedProviderSymlinks(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
root := filepath.Join(tempDir, "data")
ssclashTemp := filepath.Join(tempDir, "tmp")
config := Config{
Root: root,
SSClashTemp: ssclashTemp,
CoreSource: writeFixture(t, tempDir, "mihomo", "core"),
ConfigSource: writeFixture(t, tempDir, "config.yaml", "config"),
}
if _, err := Prepare(config); err != nil {
t.Fatalf("first Prepare() error = %v", err)
}
for _, directory := range []string{"rule-providers", "proxy-providers"} {
path := filepath.Join(root, directory)
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(ssclashTemp, directory), path); err != nil {
t.Fatal(err)
}
}
if _, err := Prepare(config); err != nil {
t.Fatalf("second Prepare() error = %v", err)
}
for _, directory := range []string{"rule-providers", "proxy-providers"} {
info, err := os.Lstat(filepath.Join(root, directory))
if err != nil {
t.Fatal(err)
}
if !info.IsDir() {
t.Errorf("%s mode = %s, want directory", directory, info.Mode())
}
}
}
func TestPrepareRejectsUnexpectedProviderSymlink(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
root := filepath.Join(tempDir, "data")
ssclashTemp := filepath.Join(tempDir, "tmp")
config := Config{
Root: root,
SSClashTemp: ssclashTemp,
CoreSource: writeFixture(t, tempDir, "mihomo", "core"),
ConfigSource: writeFixture(t, tempDir, "config.yaml", "config"),
}
if _, err := Prepare(config); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "rule-providers")
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(tempDir, "unexpected"), path); err != nil {
t.Fatal(err)
}
if _, err := Prepare(config); err == nil || !strings.Contains(err.Error(), "unexpected symlink") {
t.Fatalf("Prepare() error = %v, want unexpected symlink error", err)
}
target, err := os.Readlink(path)
if err != nil {
t.Fatal(err)
}
if target != filepath.Join(tempDir, "unexpected") {
t.Fatalf("unexpected symlink target = %q", target)
}
}
func TestChildEnvironmentRemovesCredentials(t *testing.T) {
t.Setenv("SUBSCRIPTION_URL", "https://subscription.example.invalid/?token=secret")
t.Setenv("SSCLASH_PASSWORD", "secret-password")
environment := strings.Join(childEnvironment(), "\n")
for _, key := range []string{"SUBSCRIPTION_URL=", "SSCLASH_PASSWORD="} {
if strings.Contains(environment, key) {
t.Errorf("childEnvironment() retained %s", key)
}
}
}
func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
t.Parallel()
@@ -100,6 +317,7 @@ func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
name: "filesystem root",
config: Config{
Root: "/",
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: coreSource,
ConfigSource: configSource,
},
@@ -109,6 +327,7 @@ func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
name: "missing core source",
config: Config{
Root: filepath.Join(tempDir, "missing-core"),
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: filepath.Join(tempDir, "does-not-exist"),
ConfigSource: configSource,
},
@@ -118,6 +337,7 @@ func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
name: "duplicate operating mode",
config: Config{
Root: filepath.Join(tempDir, "duplicate-mode"),
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: coreSource,
ConfigSource: configSource,
},
@@ -134,6 +354,7 @@ func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
name: "duplicate proxy mode",
config: Config{
Root: filepath.Join(tempDir, "duplicate-proxy-mode"),
SSClashTemp: filepath.Join(tempDir, "tmp"),
CoreSource: coreSource,
ConfigSource: configSource,
},
@@ -161,6 +382,167 @@ func TestPrepareRejectsUnsafeOrAmbiguousState(t *testing.T) {
}
}
func TestUpdateSubscriptionKeepsPreviousValidFile(t *testing.T) {
t.Parallel()
response := "proxies:\n - name: valid\n"
var responseLock sync.RWMutex
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
responseLock.RLock()
defer responseLock.RUnlock()
_, _ = writer.Write([]byte(response))
}))
defer server.Close()
target := filepath.Join(t.TempDir(), "subscription.yaml")
validate := func(path string) error {
content, err := os.ReadFile(path)
if err != nil {
return err
}
if strings.Contains(string(content), "invalid") {
return errors.New("invalid provider")
}
return nil
}
if err := updateSubscription(context.Background(), server.Client(), server.URL, target, validate); err != nil {
t.Fatalf("initial updateSubscription() error = %v", err)
}
responseLock.Lock()
response = "invalid"
responseLock.Unlock()
if err := updateSubscription(context.Background(), server.Client(), server.URL, target, validate); err == nil {
t.Fatal("updateSubscription() accepted invalid replacement")
}
assertFileContent(t, target, "proxies:\n - name: valid\n")
}
func TestSubscriptionErrorsDoNotExposeURL(t *testing.T) {
t.Parallel()
secretURL := "https://subscription.example.invalid/feed?token=do-not-log"
client := &http.Client{Transport: roundTripperFunc(func(request *http.Request) (*http.Response, error) {
return nil, errors.New(request.URL.String())
})}
err := updateSubscription(context.Background(), client, secretURL, filepath.Join(t.TempDir(), "subscription.yaml"), func(string) error { return nil })
if err == nil {
t.Fatal("updateSubscription() error = nil")
}
if strings.Contains(err.Error(), "do-not-log") || strings.Contains(err.Error(), secretURL) {
t.Fatalf("updateSubscription() leaked subscription URL: %v", err)
}
}
func TestUpdateAndReloadRestoresRuntimeAfterAmbiguousFailure(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte("proxies:\n - name: updated\n"))
}))
defer server.Close()
for _, testCase := range []struct {
name string
recover bool
wantFatal bool
}{
{name: "rollback reload succeeds", recover: true},
{name: "rollback reload fails", wantFatal: true},
} {
t.Run(testCase.name, func(t *testing.T) {
target := writeFixture(t, t.TempDir(), "subscription.yaml", "proxies:\n - name: previous\n")
var applied []string
reload := func(context.Context) error {
content, err := os.ReadFile(target)
if err != nil {
return err
}
applied = append(applied, string(content))
if len(applied) == 1 || !testCase.recover {
return errors.New("connection lost after server applied provider")
}
return nil
}
err := updateAndReload(context.Background(), server.Client(), RuntimeConfig{SubscriptionURL: server.URL}, target, func(string) error { return nil }, reload)
if err == nil {
t.Fatal("updateAndReload() error = nil")
}
if got := errors.Is(err, errMihomoStateUncertain); got != testCase.wantFatal {
t.Fatalf("errors.Is(state uncertain) = %t, want %t: %v", got, testCase.wantFatal, err)
}
if len(applied) != 2 || !strings.Contains(applied[0], "updated") || !strings.Contains(applied[1], "previous") {
t.Fatalf("reload sequence = %q, want updated then previous", applied)
}
assertFileContent(t, target, "proxies:\n - name: previous\n")
})
}
}
func TestRunStopsServicesWhenRollbackReloadFails(t *testing.T) {
tempDir := t.TempDir()
binary := writeFixture(t, tempDir, "fake-service", "#!/bin/sh\nif [ \"$1\" = -t ]; then exit 0; fi\nexec sleep 3600\n")
if err := os.Chmod(binary, 0o755); err != nil {
t.Fatal(err)
}
config := writeFixture(t, tempDir, "config.yaml", "proxy-providers:\n subscription:\n type: file\n path: ./subscription.yaml\n")
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
name := "updated"
if requests.Add(1) == 1 {
name = "initial"
}
_, _ = writer.Write([]byte("proxies:\n - name: " + name + "\n"))
}))
defer server.Close()
runResult := make(chan error, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
runResult <- Run(ctx, RuntimeConfig{
CoreBinary: binary,
SSClashBinary: binary,
ConfigSource: config,
RuntimeDir: filepath.Join(tempDir, "runtime"),
SubscriptionURL: server.URL,
UpdateInterval: 20 * time.Millisecond,
})
}()
var err error
select {
case err = <-runResult:
case <-time.After(5 * time.Second):
t.Fatal("Run() did not reach rollback failure")
}
if !errors.Is(err, errMihomoStateUncertain) {
t.Fatalf("Run() error = %v, want uncertain Mihomo state", err)
}
if requests.Load() < 2 {
t.Fatalf("subscription requests = %d, want initial fetch and timed update", requests.Load())
}
assertFileContent(t, filepath.Join(tempDir, "runtime", "subscription.yaml"), "proxies:\n - name: initial\n")
}
func TestValidateSubscriptionURL(t *testing.T) {
t.Parallel()
for _, raw := range []string{"", "relative/path", "ftp://example.com/feed", "https://user@example.com/feed"} {
if err := validateSubscriptionURL(raw); err == nil {
t.Errorf("validateSubscriptionURL(%q) error = nil", raw)
}
}
if err := validateSubscriptionURL("https://example.com/feed"); err != nil {
t.Fatalf("validateSubscriptionURL() error = %v", err)
}
}
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (function roundTripperFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
func writeFixture(t *testing.T, directory, name, content string) string {
t.Helper()
if err := os.MkdirAll(directory, 0o755); err != nil {
@@ -173,6 +555,20 @@ func writeFixture(t *testing.T, directory, name, content string) string {
return path
}
const validAdminPasswordHash = "pbkdf2$120000$0123456789abcdef0123456789abcdef$0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n"
func passwordFileSetup(content string, mode os.FileMode) func(t *testing.T, path string) {
return func(t *testing.T, path string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, mode); err != nil {
t.Fatal(err)
}
}
}
func assertFileContent(t *testing.T, path, want string) {
t.Helper()
content, err := os.ReadFile(path)
@@ -37,3 +37,33 @@ func TestSeededConfigExposesOnlyServerListeners(t *testing.T) {
}
}
}
func TestSeededConfigUsesLocalACL4SSRRulesAndMemorySubscription(t *testing.T) {
t.Parallel()
content, err := os.ReadFile("../../config/config.yaml")
if err != nil {
t.Fatalf("read seeded config: %v", err)
}
config := string(content)
for _, required := range []string{
"path: ./subscription.yaml",
"RULE-SET,LocalAreaNetwork,🎯 全球直连",
"RULE-SET,BanAD,🛑 广告拦截",
"RULE-SET,ProxyGFWlist,🚀 节点选择",
"MATCH,🐟 漏网之鱼",
"GoogleCN: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/GoogleCN.yaml}",
"Bing: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Bing.yaml}",
"OneDrive: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/OneDrive.yaml}",
"Microsoft: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Microsoft.yaml}",
"Telegram: {type: file, behavior: classical, format: yaml, path: /usr/local/share/ssclash/rules/Ruleset/Telegram.yaml}",
"ChinaCompanyIp: {type: file, behavior: ipcidr, format: yaml, path: /usr/local/share/ssclash/rules/ChinaCompanyIp.yaml}",
} {
if !strings.Contains(config, required) {
t.Errorf("seeded config is missing %q", required)
}
}
if strings.Contains(config, "raw.githubusercontent.com") || strings.Contains(config, "type: http") {
t.Error("seeded config depends on an online rule or subscription provider")
}
}
+3 -1
View File
@@ -4,6 +4,8 @@ set -eu
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_root"
./tests/workflow-contract.sh
unformatted=$(gofmt -l cmd internal)
if [ -n "$unformatted" ]; then
echo "Go files require formatting:" >&2
@@ -22,5 +24,5 @@ echo "unit test coverage: ${coverage}%"
go test ./...
if command -v docker >/dev/null 2>&1; then
docker compose config --quiet
SUBSCRIPTION_URL=https://subscription.example.invalid/mihomo docker compose config --quiet
fi
+213 -86
View File
@@ -4,118 +4,245 @@ set -eu
image=${1:-mohomo-docker:smoke}
suffix="$$"
container="mohomo-docker-smoke-${suffix}"
volume="mohomo-docker-smoke-${suffix}"
unconfigured="mohomo-docker-unconfigured-${suffix}"
provider="mohomo-provider-smoke-${suffix}"
network="mohomo-network-smoke-${suffix}"
volume="mohomo-volume-smoke-${suffix}"
provider_dir=""
cookie=""
login_html=""
config_html=""
secret="container-smoke-secret"
admin_password="container-smoke-admin-password"
case "$container:$volume" in
mohomo-docker-smoke-*':mohomo-docker-smoke-'*) ;;
*) echo "refusing unsafe cleanup targets" >&2; exit 1 ;;
case "$container:$unconfigured:$provider:$network:$volume" in
mohomo-docker-smoke-*':mohomo-docker-unconfigured-'*':mohomo-provider-smoke-'*':mohomo-network-smoke-'*':mohomo-volume-smoke-'*) ;;
*) echo "refusing unsafe cleanup targets" >&2; exit 1 ;;
esac
cleanup() {
docker container rm --force "$container" >/dev/null 2>&1 || true
docker container rm --force "$container" "$unconfigured" "$provider" >/dev/null 2>&1 || true
docker volume rm "$volume" >/dev/null 2>&1 || true
docker network rm "$network" >/dev/null 2>&1 || true
[ -z "$provider_dir" ] || rm -rf "$provider_dir"
[ -z "$cookie" ] || rm -f "$cookie"
[ -z "$login_html" ] || rm -f "$login_html"
[ -z "$config_html" ] || rm -f "$config_html"
}
trap cleanup EXIT INT TERM
wait_for_health() {
attempt=0
until [ "$(docker inspect --format '{{.State.Health.Status}}' "$container")" = healthy ]; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 30 ]; then
docker logs "$container" >&2
echo "container did not become healthy" >&2
exit 1
fi
sleep 1
done
}
assert_published_ports() {
published=$(docker port "$container")
for port in 7890/tcp 7890/udp 9091/tcp; do
printf '%s\n' "$published" | grep -F "$port ->" >/dev/null
done
if printf '%s\n' "$published" | grep -vE '^(7890/(tcp|udp)|9091/tcp)' >/dev/null; then
echo "container published a port other than 7890 or 9091" >&2
exit 1
fi
}
assert_web_login() {
web_port=$1
: > "$cookie"
setup_redirect=$(curl --silent --show-error --output /dev/null \
--write-out '%{http_code} %{redirect_url}' \
"http://127.0.0.1:${web_port}/setup")
if [ "$setup_redirect" != "303 http://127.0.0.1:${web_port}/login" ]; then
echo "configured Web UI exposed setup: ${setup_redirect}" >&2
exit 1
fi
login_html=$(curl --fail --silent --show-error --cookie-jar "$cookie" \
"http://127.0.0.1:${web_port}/login")
login_csrf=$(printf '%s' "$login_html" | sed -n 's/.*name="csrf" value="\([^"]*\)".*/\1/p' | head -1)
test -n "$login_csrf"
curl --fail --silent --show-error \
--cookie "$cookie" \
--cookie-jar "$cookie" \
--request POST \
--data-urlencode "csrf=${login_csrf}" \
--data-urlencode "password=${admin_password}" \
"http://127.0.0.1:${web_port}/login" >/dev/null
curl --fail --silent --show-error --cookie "$cookie" \
"http://127.0.0.1:${web_port}/config" | grep -F 'csrf-token' >/dev/null
}
default_compose=$(SUBSCRIPTION_URL=https://subscription.example.invalid/mihomo docker compose config)
loopback_bindings=$(printf '%s\n' "$default_compose" | awk '$1 == "host_ip:" && $2 == "127.0.0.1" { count++ } END { print count + 0 }')
if [ "$loopback_bindings" -ne 3 ]; then
echo "Compose must bind 7890/tcp, 7890/udp, and 9091/tcp to host loopback by default" >&2
exit 1
fi
public_proxy_compose=$(SUBSCRIPTION_URL=https://subscription.example.invalid/mihomo \
PROXY_BIND=0.0.0.0 WEB_BIND=0.0.0.0 docker compose config)
public_bindings=$(printf '%s\n' "$public_proxy_compose" | awk '$1 == "host_ip:" && $2 == "0.0.0.0" { count++ } END { print count + 0 }')
loopback_bindings=$(printf '%s\n' "$public_proxy_compose" | awk '$1 == "host_ip:" && $2 == "127.0.0.1" { count++ } END { print count + 0 }')
if [ "$public_bindings" -ne 2 ] || [ "$loopback_bindings" -ne 1 ]; then
echo "public opt-in must affect only 7890; 9091 must remain on host loopback" >&2
exit 1
fi
docker build --tag "$image" .
docker run --rm --entrypoint /usr/local/lib/ssclash/clash "$image" \
-t -d /usr/local/share/ssclash
-t -d /usr/local/share/ssclash -f /usr/local/share/ssclash/config.yaml >/dev/null 2>&1 && {
echo "config validation unexpectedly passed without a subscription provider" >&2
exit 1
}
provider_dir=$(mktemp -d)
printf '%s\n' \
'proxies:' \
' - name: smoke-node' \
' type: socks5' \
' server: 127.0.0.1' \
' port: 9' \
> "$provider_dir/provider.yaml"
chmod 0755 "$provider_dir"
chmod 0644 "$provider_dir/provider.yaml"
docker network create "$network" >/dev/null
docker volume create "$volume" >/dev/null
docker run --detach \
--name "$container" \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--volume "$volume:/opt/clash" \
--publish 127.0.0.1::9091/tcp \
--publish 127.0.0.1::7890/tcp \
"$image" >/dev/null
web_port=$(docker port "$container" 9091/tcp | awk -F: 'NR == 1 { print $NF }')
proxy_port=$(docker port "$container" 7890/tcp | awk -F: 'NR == 1 { print $NF }')
test -n "$web_port"
test -n "$proxy_port"
docker run --detach --rm \
--name "$provider" \
--network "$network" \
--volume "$provider_dir:/srv:ro" \
--entrypoint /bin/sh \
"$image" -c 'while :; do { printf "HTTP/1.1 200 OK\r\nContent-Type: text/yaml\r\nConnection: close\r\n\r\n"; cat /srv/provider.yaml; } | nc -l -p 8080; done' >/dev/null
attempt=0
until curl --fail --silent --show-error "http://127.0.0.1:${web_port}/" >/dev/null; do
until docker exec "$provider" wget -qO- http://127.0.0.1:8080/provider.yaml >/dev/null; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 30 ]; then
docker logs "$container" >&2
echo "web UI did not become ready" >&2
if [ "$attempt" -ge 10 ]; then
echo "subscription fixture did not become ready" >&2
exit 1
fi
sleep 1
done
docker run --detach \
--name "$unconfigured" \
--network "$network" \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--env "SUBSCRIPTION_URL=http://${provider}:8080/provider.yaml" \
--volume "$volume:/opt/clash" \
--publish 127.0.0.1::9091/tcp \
"$image" >/dev/null
unconfigured_port=$(docker port "$unconfigured" 9091/tcp | awk -F: 'NR == 1 { print $NF }')
attempt=0
while [ "$(docker inspect --format '{{.State.Running}}' "$unconfigured")" = true ]; do
if curl --fail --silent --show-error --max-time 1 \
"http://127.0.0.1:${unconfigured_port}/setup" >/dev/null 2>&1; then
echo "fresh volume exposed anonymous setup" >&2
exit 1
fi
attempt=$((attempt + 1))
if [ "$attempt" -ge 10 ]; then
echo "fresh volume did not fail closed without SSCLASH_PASSWORD" >&2
exit 1
fi
sleep 1
done
if [ "$(docker inspect --format '{{.State.ExitCode}}' "$unconfigured")" -eq 0 ]; then
echo "fresh volume exited successfully without SSCLASH_PASSWORD" >&2
exit 1
fi
docker logs "$unconfigured" 2>&1 | grep -F 'SSCLASH_PASSWORD is required' >/dev/null
if docker logs "$unconfigured" 2>&1 | grep -F 'web UI listening' >/dev/null; then
echo "fresh volume started the Web UI before authentication was configured" >&2
exit 1
fi
docker container rm "$unconfigured" >/dev/null
cookie=$(mktemp)
docker run --detach \
--name "$container" \
--network "$network" \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--env "SUBSCRIPTION_URL=http://${provider}:8080/provider.yaml?token=${secret}" \
--env "SSCLASH_PASSWORD=${admin_password}" \
--volume "$volume:/opt/clash" \
--publish 127.0.0.1::7890/tcp \
--publish 127.0.0.1::7890/udp \
--publish 127.0.0.1::9091/tcp \
"$image" >/dev/null
wait_for_health
assert_published_ports
web_port=$(docker port "$container" 9091/tcp | awk -F: 'NR == 1 { print $NF }')
assert_web_login "$web_port"
host_gateway=$(docker network inspect "$network" --format '{{(index .IPAM.Config 0).Gateway}}')
container_ip=$(docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$container")
proxy_port=$(docker port "$container" 7890/tcp | awk -F: 'NR == 1 { print $NF }')
if curl --fail --silent --show-error --max-time 2 --noproxy "" \
--proxy "http://${host_gateway}:${proxy_port}" \
"http://${container_ip}:9090/version" >/dev/null 2>&1; then
echo "default 7890 publish was reachable through a non-loopback host address" >&2
exit 1
fi
if curl --fail --silent --show-error --max-time 2 \
"http://${host_gateway}:${web_port}/login" >/dev/null 2>&1; then
echo "default 9091 publish was reachable through a non-loopback host address" >&2
exit 1
fi
docker exec "$container" grep -Fx 'OPERATING_MODE=server' /opt/clash/.ssclash/settings >/dev/null
docker exec "$container" grep -Fx 'PROXY_MODE=none' /opt/clash/.ssclash/settings >/dev/null
docker exec "$container" grep -Fx 'mixed-port: 7890' /opt/clash/config.yaml >/dev/null
docker exec "$container" test -s /dev/shm/mohomo/subscription.yaml
docker exec "$container" /usr/local/lib/ssclash/clash \
-t -d /dev/shm/mohomo -f /dev/shm/mohomo/config.yaml >/dev/null
docker exec "$container" curl --fail --silent --show-error \
http://127.0.0.1:9090/version >/dev/null
docker exec "$container" /usr/local/bin/ssclash setpass container-smoke-only >/dev/null
cookie=$(mktemp)
login_html=$(mktemp)
config_html=$(mktemp)
curl --fail --silent --show-error --cookie-jar "$cookie" \
"http://127.0.0.1:${web_port}/login" > "$login_html"
login_csrf=$(sed -n 's/.*name="csrf" value="\([^"]*\)".*/\1/p' "$login_html" | head -1)
test -n "$login_csrf"
curl --fail --silent --show-error \
--cookie "$cookie" \
--cookie-jar "$cookie" \
--request POST \
--data-urlencode "csrf=${login_csrf}" \
--data-urlencode 'password=container-smoke-only' \
"http://127.0.0.1:${web_port}/login" >/dev/null
curl --fail --silent --show-error \
--cookie "$cookie" \
"http://127.0.0.1:${web_port}/config" > "$config_html"
api_csrf=$(sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p' "$config_html" | head -1)
test -n "$api_csrf"
start_response=$(curl --fail --silent --show-error \
--cookie "$cookie" \
--header "X-CSRF-Token: ${api_csrf}" \
--header 'Content-Type: application/json' \
--data '{"action":"start"}' \
"http://127.0.0.1:${web_port}/api/service")
printf '%s' "$start_response" | grep -F '"ok":true' >/dev/null
status_response=$(curl --fail --silent --show-error \
--cookie "$cookie" \
--header "X-CSRF-Token: ${api_csrf}" \
"http://127.0.0.1:${web_port}/api/status")
printf '%s' "$status_response" | grep -F '"running":true' >/dev/null
printf '%s' "$status_response" | grep -F '"operatingMode":"server"' >/dev/null
attempt=0
until curl --fail --silent --show-error \
--proxy "http://127.0.0.1:${proxy_port}" \
--max-time 10 \
https://example.com/ >/dev/null; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 20 ]; then
docker logs "$container" >&2
echo "mixed proxy did not become ready" >&2
exit 1
fi
sleep 1
done
if docker exec "$container" grep -Eq '^(tproxy-port|redir-port|tun):' /opt/clash/config.yaml; then
docker logs "$container" >&2
echo "gateway listener leaked into server-only config" >&2
if docker exec "$container" grep -R -F "$secret" /opt/clash /dev/shm/mohomo >/dev/null 2>&1; then
echo "subscription URL credential was written to runtime files" >&2
exit 1
fi
if docker logs "$container" 2>&1 | grep -Ei '\[(error|fatal)\]|operation not permitted' >/dev/null; then
docker logs "$container" >&2
echo "container emitted an error during Web-managed startup" >&2
if docker logs "$container" 2>&1 | grep -F "$secret" >/dev/null; then
echo "subscription URL credential was written to logs" >&2
exit 1
fi
if docker exec "$container" grep -R -F "$admin_password" /opt/clash /dev/shm/mohomo >/dev/null 2>&1; then
echo "administrator password was written to runtime files" >&2
exit 1
fi
if docker logs "$container" 2>&1 | grep -F "$admin_password" >/dev/null; then
echo "administrator password was written to logs" >&2
exit 1
fi
echo "container smoke test passed: web_port=${web_port} proxy_port=${proxy_port}"
docker container rm --force "$container" >/dev/null
docker run --rm \
--volume "$volume:/opt/clash" \
--entrypoint /bin/sh \
"$image" -c 'test -L /opt/clash/rule-providers && test ! -e /opt/clash/rule-providers && test "$(readlink /opt/clash/rule-providers)" = /tmp/ssclash/rule-providers'
docker run --detach \
--name "$container" \
--network "$network" \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--env "SUBSCRIPTION_URL=http://${provider}:8080/provider.yaml?token=${secret}" \
--volume "$volume:/opt/clash" \
--publish 127.0.0.1::7890/tcp \
--publish 127.0.0.1::7890/udp \
--publish 127.0.0.1::9091/tcp \
"$image" >/dev/null
wait_for_health
assert_published_ports
web_port=$(docker port "$container" 9091/tcp | awk -F: 'NR == 1 { print $NF }')
assert_web_login "$web_port"
echo "container smoke test passed: fresh volume fails closed; authenticated 9091 survives same-volume rebuild; only 7890/9091 are published"
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
set -eu
workflow=.github/workflows/docker.yml
test -f "$workflow" || {
echo "missing GHCR workflow: $workflow" >&2
exit 1
}
grep -F 'packages: write' "$workflow" >/dev/null
# Match the GitHub expression literally.
# shellcheck disable=SC2016
grep -F 'ghcr.io/${{ github.repository }}' "$workflow" >/dev/null
grep -F 'platforms: linux/amd64' "$workflow" >/dev/null
grep -F 'needs: test' "$workflow" >/dev/null
grep -F 'cache-to: type=gha,mode=max,ignore-error=true' "$workflow" >/dev/null
# Match the GitHub expression literally.
# shellcheck disable=SC2016
grep -F 'push: ${{ github.event_name != '\''pull_request'\'' }}' "$workflow" >/dev/null
if grep -Ei 'arm64|setup-qemu' "$workflow" >/dev/null; then
echo "workflow must build linux/amd64 only and must not configure QEMU" >&2
exit 1
fi
uses_count=$(grep -Ec '^[[:space:]]+uses:' "$workflow")
pinned_count=$(grep -Ec '^[[:space:]]+uses: [^ ]+@[0-9a-f]{40}([[:space:]]|$)' "$workflow")
if [ "$uses_count" -eq 0 ] || [ "$uses_count" -ne "$pinned_count" ]; then
echo "every GitHub Action must be pinned to a full commit SHA" >&2
exit 1
fi