WebAPI security, launcher, and deployment
Overview
This area owns the WebAPI's local-first security model, native process lifecycle, self-update/restore restart path, and deployable packaging assets. The security entry points are under v2rayN/v2rayN.WebAPI/Security/: WebAuthService.cs manages the management key, WebSessionService.cs manages in-memory bearer sessions and SSE tickets, WebSessionAuthenticationMiddleware.cs protects /api/**, WebCorsPolicy.cs rejects untrusted origins before API execution, WebAuthRateLimiting.cs defines login/setup rate limits, WebAuthRequestBodyLimitMiddleware.cs caps auth/setup request bodies, and WebSecurityHeadersMiddleware.cs adds browser hardening headers.
Authentication has two modes in v2rayN/…/WebAuthService.cs. If V2RAYN_WEB_API_KEY is supplied, login validation compares the supplied key with that environment value in fixed time after a dummy PBKDF2 derivation to keep the no-file path timing similar. If no environment key is supplied, first-run setup creates a stored verifier: keys must be 12 to 4096 characters, must match confirmation, and are written as PBKDF2-HMAC-SHA256 metadata with 600,000 iterations, a 16-byte salt, and a 32-byte verifier. WebAuthStorage.cs places that verifier at WebAPIData/WebAPI-auth.json, migrates older webData/web-auth.json and legacy config-path copies into the private location, deletes stale copies, and tightens Linux permissions on the directory and file.
Setup is deliberately local-only. v2rayN/…/WebSetupAccessPolicy.cs allows setup only when the request is same-origin, has no Forwarded, X-Real-IP, or X-Forwarded-* headers, comes from a loopback peer, and uses localhost, 127.0.0.1, or [::1]/::1 as Host. The separate IsLocalDiagnosticSource rule is used for local health diagnostics and matches the launcher probe policy in v2rayN/…/WebProbeUriResolver.cs.
Session state is process-local in v2rayN/…/WebSessionService.cs. A login creates a 32-byte random base64url token, stores only its SHA-256 digest, and returns a bearer token with a 7-day sliding lifetime capped by a 30-day absolute lifetime. Successful protected API calls renew the sliding expiry; /api/auth/sse-ticket validates without renewal. SSE access uses short-lived one-use tickets: TryCreateSseTicket binds a random ticket digest to the session digest for 45 seconds, and TryConsumeSseTicket removes the ticket before validating the underlying session. Revoking or expiring a session cancels its revocation token and removes outstanding SSE tickets.
v2rayN/…/WebSessionAuthenticationMiddleware.cs treats /api/health, /api/setup/status, /api/setup, and /api/auth/login as unauthenticated API paths. /api/events must present sse_ticket in the query string and consumes that one-use ticket. Other /api/** paths must present Authorization: Bearer <token>; failed checks return the API envelope with unauthorized.
Listener and deployment startup checks are split so request headers cannot influence listener safety. v2rayN/…/WebListenerSecurityPolicy.cs defaults Kestrel to http://127.0.0.1:5080 when no URL/port configuration exists, derives effective URLs from ASPNETCORE_URLS, http_ports, https_ports, or Kestrel endpoints, and rejects non-loopback listeners unless a management key is configured. v2rayN/…/WebDeploymentSecurityPolicy.cs separately requires a management key in supervised or container deployments. v2rayN/…/WebCorsPolicy.cs parses V2RAYN_WEB_ALLOWED_ORIGINS as comma-separated HTTP(S) origins with no wildcards, credentials, paths, queries, or fragments, then WebOriginGuardMiddleware rejects disallowed /api Origins with 403 before authentication, rate limiting, SSE-ticket consumption, or mutations. Same-origin browser requests may also be recognized through Sec-Fetch-Site: same-origin plus a valid Origin, which supports TLS/path-prefix reverse proxies without granting setup or diagnostic access.
The native launcher flow is under v2rayN/v2rayN.WebAPI/Launcher/. WebLaunchOptions.cs parses --stop, --foreground, --background, --background-child, --no-open, and help flags; on Linux outside containers it defaults interactive launches to a background launcher unless foreground is requested, while containers and daemons run foreground. LauncherEnvironment distinguishes systemd/container/shell launches and carries V2RAYN_WEB_INTERACTIVE_LAUNCH through detached children. WebInstanceLock.cs enforces one WebAPI instance per data scope with a lock file, writes the owner PID when requested, uses flock on Linux and a byte-range lock on Windows, and keeps the PID readable for probes and update helpers.
v2rayN/…/WebLauncher.cs starts and reuses native instances. Before spawning, ExistingInstanceHandler.TryReuseAsync tries to acquire the lock; if another owner holds it, it probes the loopback health URL, verifies the health header PID matches the lock owner, and optionally opens the API URL with xdg-open. New background launches run through setsid using WebReplacementCommand, then wait up to 30 seconds for the lock owner and health endpoint to agree. Background children detach stdin/stdout/stderr to /dev/null on Linux or free the console on Windows.
Stopping is conservative in v2rayN/…/WebStopper.cs. It refuses to signal when the lock is absent, the owner PID cannot be read, the owner is systemd-managed, no loopback HTTP health URI is available, or health does not identify the same owner PID. After a verified SIGTERM, it polls until the endpoint no longer identifies the old owner and the lock is released or replaced, then reports success only if previously observed Core process IDs are no longer alive.
Native restart, backup restore, and self-update use the same lock/probe identity checks. v2rayN/…/WebRestartCoordinator.cs chooses restart ownership: external supervisors own restart in daemon/container environments, native restart owns it on Linux/Windows when supported, and otherwise no replacement is started. NativeWebRestorePreflight.cs resolves a loopback health URI and replacement command before restore mutates Core/config state; it refuses native restore restart when the executable, managed DLL, Linux setsid, or probeable health endpoint is unavailable. NativeWebUpdateWorkflow.cs wraps candidate install, health verification, rollback, and backup cleanup as a transaction.
v2rayN/…/NativeWebUpdateHelper.cs executes the self-update transaction from a plan file. It validates platform, RID, version identity, expected commit, non-container/non-systemd context, probeable loopback HTTP health URI, fully-qualified in-scope lock/runtime/progress paths, sibling candidate/backup directories, matching v2rayN.WebAPI.build.json, writable install directory, and absence of symlinks in staged or installed app paths. Linux single-file helpers copy themselves to an isolated .v2rayn-WebAPI-update-helper-* executable before swapping files so lazy bundle loads keep a stable executable path; Windows isolated helper cleanup is scheduled through PowerShell, with MoveFileEx delayed-delete as fallback. The helper waits for owner release, backs up the current executable and build identity, moves the candidate executable and identity into place with transient retry, starts the replacement, verifies lock owner, health PID, Web version, and runtime Core intent, and restores the backup if candidate health fails.
Deployment assets define two supported topologies. v2rayN/…/compose.yaml builds v2rayN/v2rayN.WebAPI/Containerfile, requires V2RAYN_WEB_API_KEY, binds the WebAPI and proxy ports only to host loopback by default, enables Web/Core autostart settings, and persists /data through a named volume. v2rayN/v2rayN.WebAPI/Containerfile fetches the official upstream Core/data bundle, publishes a self-contained single-file WebAPI for the selected RID, copies the complete bin/ payload, runs as UID/GID 10001, uses /data for state and .NET bundle extraction, exposes 5080 plus proxy TCP/UDP, and starts /app/v2rayN.WebAPI --foreground. v2rayN/v2rayN.WebAPI/Deploy/Systemd/v2rayn-web.service runs /opt/v2rayn-web/v2rayN.WebAPI --foreground as user/group v2rayn, listens on 0.0.0.0:5080, sets V2RAYN_DATA_HOME=/var/lib/v2rayn-web, enables autostart, uses StateDirectory and UMask=0077, restarts always, and hardens the unit with NoNewPrivileges, PrivateTmp, ProtectSystem=strict, ProtectHome=true, and ReadWritePaths=/var/lib/v2rayn-web.
Release and verification scripts share the same asset map. v2rayN/…/web-assets.json maps each supported RID to its public architecture string, full release ZIP name, and app-only update ZIP name. Scripts/fetch-core-bundle.sh downloads the official core bundle for Linux RIDs from 2dust/v2rayN-core-bin, sanity-checks required Core/data files, preserves the whole upstream bin/ tree, and fixes executable modes. Scripts/publish-native.sh publishes Linux native single-file builds and writes v2rayN.WebAPI.build.json with product/version/commit/buildDate/RID. Scripts/web-release-assets.py builds full and app-only ZIPs from a publish directory; full ZIPs include .env.example from the reviewed source path and exclude any local .env, while app-only ZIPs contain only the executable and build identity. Scripts/web-update-manifest.py writes/verifies WebAPI-update.json, checks official GitHub release URLs, SHA-256/size, app-only archive layout, build identity, and Windows PE machine type. Scripts/verify.sh restores/builds/tests, publishes a Linux native build, runs startup security, backup/restore, packaging, full-ZIP runtime, and native-update regression checks. Properties/AssemblyInfo.cs exposes internals to WebAPI tests, and Properties/launchSettings.json is the local development profile.
Routing/covers
This doc owns:
v2rayN/v2rayN.WebAPI/Security/**v2rayN/v2rayN.WebAPI/Launcher/**v2rayN/v2rayN.WebAPI/Deploy/**v2rayN/v2rayN.WebAPI/Scripts/**v2rayN/v2rayN.WebAPI/Assets/**v2rayN/v2rayN.WebAPI/Properties/**- v2rayN/…/.env.example
- v2rayN/…/compose.yaml
v2rayN/v2rayN.WebAPI/Containerfilev2rayN/v2rayN.WebAPI/Containerfile.dockerignore
Coupling
- If auth endpoint paths change, update both v2rayN/…/WebSessionAuthenticationMiddleware.cs and v2rayN/…/WebAuthRequestBodyLimitMiddleware.cs; the body cap is hard-coded only for
POST /api/auth/loginandPOST /api/setup, while the auth middleware has its own unauthenticated-path list and special/api/eventsand/api/auth/sse-ticketbehavior. - If setup or health diagnostics allow new local hosts or forwarding behavior, update v2rayN/…/WebSetupAccessPolicy.cs and v2rayN/…/WebProbeUriResolver.cs together; launcher stop/restart/update identity checks only trust loopback HTTP URIs that satisfy the probe resolver and health diagnostic source rules.
- If session token shape changes in v2rayN/…/WebSessionService.cs, verify every bearer-token and SSE-ticket caller still presents 43-character base64url tokens; invalid lengths or characters are rejected before hashing.
- If
V2RAYN_WEB_ALLOWED_ORIGINSsemantics change in v2rayN/…/WebCorsPolicy.cs, keep the CORS builder andWebOriginGuardMiddlewarein sync; CORS controls browser readability, but the guard is what blocks disallowed Origins before auth and API mutations. - If listener defaults or Kestrel URL handling change in v2rayN/…/WebListenerSecurityPolicy.cs, verify v2rayN/…/WebProbeUriResolver.cs, v2rayN/…/compose.yaml,
v2rayN/v2rayN.WebAPI/Containerfile, andv2rayN/v2rayN.WebAPI/Deploy/Systemd/v2rayn-web.service; non-loopback bindings require a management key, while the launcher requires a loopback HTTP health route for native control. - If the instance lock filename, owner-PID format, or data scope changes in v2rayN/…/WebInstanceLock.cs, update WebStopper.cs, WebLauncher.cs, WebRestartCoordinator.cs, NativeWebUpdateHelper.cs, and NativeWebRestorePreflight.cs; stop, reuse, replacement, and update all use lock ownership as their process identity anchor.
- If health response headers change, update
v2rayN/v2rayN.WebAPI/Launcher/HttpWebHealthProbeand every caller that checksInstanceProcessId,CoreProcessIds,CoreState,WebVersion, orCoreProfileId; native stop/update/restart decisions depend on those parsed headers matching the lock owner and runtime intent. - If release asset names or supported RIDs change, update v2rayN/…/web-assets.json, Scripts/web-release-assets.py, Scripts/web-update-manifest.py, Scripts/publish-native.sh, Scripts/fetch-core-bundle.sh, and
v2rayN/v2rayN.WebAPI/Containerfile; the runtime updater, manifest verifier, packager, and container build all assume the same RID-to-asset map. - If app-only update ZIP contents change, update both v2rayN/…/web-release-assets.py and v2rayN/…/web-update-manifest.py; the packager currently emits only the executable plus v2rayN.WebAPI.build.json, and the manifest verifier rejects any extra entry.
- If service/container deployment starts under a supervisor, keep v2rayN/…/WebDeploymentSecurityPolicy.cs,
Launcher/LauncherEnvironmentin WebLaunchOptions.cs,Launcher/WebLifecyclePlannerin WebRestartCoordinator.cs,Deploy/Systemd/v2rayn-web.service, and compose.yaml aligned; supervised/container deployments require a management key and delegate restart ownership away from native self-restart.
Risks
- v2rayN/…/WebSetupAccessPolicy.cs intentionally rejects any forwarded headers during setup. If a reverse proxy path accidentally exposes first-run setup while stripping or rewriting Host/Origin incorrectly, setup access can either be blocked for legitimate local setup or, worse, granted in an unintended trust boundary; verify forwarded-header handling whenever setup is made reachable through a proxy.
- v2rayN/…/WebSessionService.cs stores sessions only in memory. Restarting the WebAPI invalidates all bearer sessions and SSE tickets; if callers assume session persistence across native update/restart, they will receive
401until they log in again. - v2rayN/…/WebStopper.cs sends
SIGTERMonly after lock owner and health PID agree. If the health endpoint becomes unavailable on a non-loopback/HTTPS-only listener,--stopreturnsProbeUnavailableand leaves the process running rather than risking a stale PID signal. - v2rayN/…/NativeWebUpdateHelper.cs contains multiple guards against symlink-managed installs and staged symlink entries. If those checks are weakened, a self-update could overwrite files outside the intended install directory or fail rollback after replacing the executable.
- v2rayN/…/NativeWebUpdateHelper.cs retries Windows file replacement because antivirus or indexing can transiently hold a new executable open. Removing that bounded retry turns temporary
IOException/UnauthorizedAccessExceptionraces into failed updates or rollbacks. - v2rayN/…/web-release-assets.py excludes .env from packages and injects only the reviewed .env.example;
v2rayN/v2rayN.WebAPI/Containerfile.dockerignorealso excludes .env and local state/build directories. If packaging starts copying publish trees without these filters, local secrets or mutable runtime state can enter release artifacts or container build contexts.