WebAPI runtime and endpoints
Overview
v2rayN/…/Program.cs is the headless ASP.NET Core entry point. Startup first loads a native .env from the executable directory through Configuration/NativeEnvironmentFile.cs, validates the optional V2RAYN_WEB_API_KEY, applies listener/CORS security defaults, prepares the ServiceLib data scope from V2RAYN_DATA_HOME or local-app-data fallback, and enforces a single instance with v2rayN.WebAPI.instance.lock. The same entry point also handles launcher modes (--help, Linux background/stop flows) and the detached native self-update helper mode --apply-WebAPI-update before it builds the web host.
Program.RunWebHostAsync registers the process-wide runtime services: EventHub, LogBuffer, RuntimeOperationCoordinator, V2rayRuntime, WebAuthService, WebSessionService, auth rate limiting, CORS, JSON enum conversion, and V2rayHostedService. Middleware order is intentional: security headers/body limits, routing, origin guard, CORS preflight, rate limiting, session authentication, API exception normalization, and then runtime-operation leasing. Public paths are limited to /api/health, /api/setup/*, /api/auth/*, and /api/events ticket/session handling; protected API paths are mapped by Api/WebApiEndpoints.cs, Api/WebAuthEndpoints.cs, and Api/WebSetupEndpoints.cs, with an /api/{**path} fallback returning the stable envelope from Contracts/ApiModels.cs.
Endpoint groups in Api/WebApiEndpoints.cs are thin adapters over Services/V2rayRuntime* partials:
- Health/status/logging/events:
/api/health,/api/status,/api/operations,/api/logs,/api/logs/page, and/api/events. Api/WebHealthEndpoint.cs only emits diagnostic headers such as PID, version, core state, process IDs, and shutdown stage for direct local diagnostic requests. SSE events come from Services/EventHub.cs; logs are retained by Services/LogBuffer.cs and optionally streamed aslogevents. - Auth/setup: Api/WebAuthEndpoints.cs exchanges the Management Key at
POST /api/auth/login, revokes sessions at logout, and issues one-use SSE tickets at/api/auth/sse-ticket. Api/WebSetupEndpoints.cs allows first-run key setup only when the setup access policy permits it and returns a session immediately after setup. - Profiles and subscriptions: profile groups, CRUD/import/export/move/sort/deduplicate, profile selection, latency/speed tests, subscription CRUD/share/update, and subscription background progress. State is read and written through ServiceLib database/config APIs from V2rayRuntime.cs and V2rayRuntime.Profiles.cs under the runtime mutation gate.
- Settings: inbound, core, application, speed-test, core-type mapping, routing, DNS, full config templates, WebDAV settings, regional presets, statistics cleanup, backup/restore, and option discovery. These live primarily in V2rayRuntime.Settings.cs and use ServiceLib option lists rather than duplicating desktop constants.
- Core/Web/Geo maintenance:
/api/core/start|stop|restart,/api/core-updates*, legacy Xray endpoints,/api/core/geo/update, and/api/web-updates*are implemented by V2rayRuntime.cs, V2rayRuntime.CoreUpdate.cs, and V2rayRuntime.WebUpdate.cs.
Services/V2rayRuntime.cs owns the ServiceLib bridge and hosted core lifecycle. V2rayHostedService.cs calls InitializeAsync at host start and ShutdownAsync at host stop; initialization runs AppManager.Instance.InitApp/InitComponents, installs Adapters/HeadlessWindowDialog.cs, initializes builtin DNS/templates/routing, normalizes Web update target names, applies Web proxy environment overrides, initializes CoreManager, StatisticsManager, certificates, profile extensions, and scheduled operations. Core start builds ServiceLib core config with CoreLaunchPreflight.cs, rejects TUN-generated contexts, validates selected core executables, checks projected TCP/UDP listener availability, snapshots CoreRuntimeSnapshot, launches through CoreManager.Instance.LoadCore, tracks child process identities with CoreProcessTracker.cs, waits for the configured listener, and starts a monitor that marks the runtime faulted if the tracked child exits or no longer owns the listener. Core stop/restart always uses _coreGate, StopCoreAndConfirmAsync, and tracked process identity rather than port ownership alone.
Runtime mutation and restart coordination is split between two gates. RuntimeMutationGate.cs serializes Web-owned writes to ServiceLib config and SQLite state. RuntimeOperationCoordinator.cs leases request/runtime work: normal operations can overlap, exclusive maintenance blocks mutations/restores/updates, some exclusive windows permit read-only observations, and shutdown cancels linked operation tokens before cleanup. RuntimeRequestOperationPolicy.cs classifies HTTP requests before endpoint execution: background starters (subscription updates, speed tests, update starts, restores, regional presets) enqueue work without holding the request lease for the full operation; settings mutations and backups take stronger leases so runtime state cannot be swapped underneath them.
Core-affecting settings in V2rayRuntime.Settings.cs use a transactional apply path. BeginCoreSettingsApplyAsync snapshots Config, active runtime state, routing rows, DNS rows, and full config templates while holding _coreGate. After ServiceLib/SQLite writes, CompleteCoreAffectingChangeAsync uses CoreSettingsApplyPolicy.cs to decide save-only versus restart versus busy/inconsistent failure. If restart fails, RollBackCoreSettingsAsync restores config/database snapshots and attempts to recover the old core runtime; responses include rollback flags so clients can distinguish saved settings, restored settings, and restart failures.
Backup and restore live in V2rayRuntime.Backup.cs. Backup downloads and WebDAV uploads create the existing guiConfigs/ ZIP shape while excluding WebAPI-auth.json; Api/DeleteAfterFileResult.cs deletes temporary download archives after streaming. Restore validates archive size/shape, rejects path traversal/symlinks, ignores any auth file in the archive, parses config.json, checks SQLite compatibility through BackupDatabaseCompatibility.cs, writes a runtime restart intent, stops Core, saves/flushes ServiceLib state, closes SQLite, atomically replaces the config directory, rejects new operations, and requests host shutdown. Native Linux/Windows restores can plan a replacement process through launcher types and are gated by BackupRestorePreflightGate.cs; startup reads the restore marker and RuntimeRestartRecovery.cs restarts the previous, selected, or default profile when possible.
Core, GeoFiles, and Web update flows are staged before destructive actions. V2rayRuntime.CoreUpdate.cs exposes update settings/progress/check/apply and serializes all update tasks with _updateTaskGate; core package installation uses CoreUpdatePackageStager.cs to flatten/extract supported archives, version-check staged executables with CoreExecutableVersionCheck.cs, copy existing Geo data for Xray, move install/candidate/backup directories, restart only the affected running core, and roll back files/runtime if apply fails. GeoFiles updates wrap ServiceLib UpdateService.UpdateGeoFileAll in GeoFilesUpdateGate.cs, GeoFilesUpdateTransaction.cs, and GeoFilesUpdateCompletion.cs: managed required files and configured SRS rule-set files are backed up, symlinks/directories are rejected, completion must be reported, and failures roll files back before progress is marked failed.
Web self-update is a separate v2rayN.WebAPI target. WebBuildIdentity.cs reads assembly metadata from v2rayN.WebAPI.csproj; WebReleaseChannel.cs trusts only upstream GitHub release assets matching WebAPI-update.json; WebReleaseAssets.cs is the embedded source of release asset names; WebUpdatePackageStager.cs validates manifest product/version/RID, asset URL/size/SHA-256, ZIP boundaries, allowed app-only files, build identity, and native ELF/PE architecture. V2rayRuntime.WebUpdate.cs permits install only for writable native Linux/Windows single-file deployments according to WebUpdateDeploymentPolicy.cs, with containers/systemd/read-only deployments check-only. Apply writes runtime intent and progress files, creates a native helper plan, launches --apply-WebAPI-update, and stops the host only after network download and package verification complete.
API contracts are centralized in Contracts/ApiModels.cs: response envelopes are { success, code, messageKey, data }, operations use OperationView, stable message keys live in ApiMessageKeys, status includes runtime/build/capability fields, and request/view records cover subscriptions, profiles, settings, DNS/routing, backup/WebDAV, updates, traffic, logs, and SSE events. Contracts/WebApiCapabilities.cs advertises durable feature flags such as auth.sessions, events.sse, backup.restore, core.updates, and WebAPI.self-update. The module is an ASP.NET Microsoft.NET.Sdk.Web app targeting net10.0 and references ServiceLib directly in v2rayN.WebAPI.csproj; README.md and FEATURE-MAP.md document the ServiceLib/API boundary and release/update contract.
Routing / covers
This doc owns the headless WebAPI runtime and endpoint surface under:
- v2rayN/…/Program.cs
v2rayN/v2rayN.WebAPI/Api/**v2rayN/v2rayN.WebAPI/Contracts/**v2rayN/v2rayN.WebAPI/Services/**v2rayN/v2rayN.WebAPI/Adapters/**v2rayN/v2rayN.WebAPI/Configuration/**- v2rayN/…/FEATURE-MAP.md
- v2rayN/…/README.md
v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj
Use this doc for reviews involving /api/* endpoint behavior, hosted ServiceLib/Core lifecycle, runtime mutation or restart coordination, WebDAV backup/restore, core/GeoFiles/Web update workflows, WebAPI release identity, and the contracts returned to WebAPI clients.
Coupling
- If a new
/api/*route is added in Api/WebApiEndpoints.cs, Api/WebAuthEndpoints.cs, or Api/WebSetupEndpoints.cs, also classify it in Services/RuntimeRequestOperationPolicy.cs when it starts background work, mutates ServiceLib state, downloads backups, or swaps runtime files; otherwise it defaults to a shared request lease and may run during maintenance windows that assume stronger exclusion. - If a response, request, event, or message key changes in Contracts/ApiModels.cs, verify every endpoint returning it in Api/WebApiEndpoints.cs and every progress publisher in Services/V2rayRuntime.CoreUpdate.cs, Services/V2rayRuntime.WebUpdate.cs, Services/V2rayRuntime.Profiles.cs, and Services/V2rayRuntime.cs; clients rely on stable
code,messageKey, eventtype, and capability strings rather than localized text. - If ServiceLib config or SQLite mutation behavior changes, audit every
_mutations.RunAsynccall in Services/V2rayRuntime*.cs; WebAPI assumes ServiceLib writes are not independently serialized and wraps profile/subscription/settings/routing/DNS/update timestamp saves itself. - If core runtime state names or transitions change in Services/CoreRuntimeSnapshot.cs, update Services/V2rayRuntime.cs, Services/CoreSettingsApplyPolicy.cs, Api/WebHealthEndpoint.cs, and Contracts/ApiModels.cs; status, health headers, settings apply, update installability, restore, and SSE all interpret the same state machine.
- If ServiceLib changes GeoFiles download selection or SRS naming, update Services/V2rayRuntime.CoreUpdate.cs and Services/GeoFilesUpdateTransaction.cs; the transaction intentionally mirrors ServiceLib-managed required files and configured rule-set files so rollback covers exactly the files the upstream updater may touch.
- If WebAPI release asset names or package contents change, update Services/WebReleaseAssets.cs, Services/WebUpdatePackageStager.cs, Services/V2rayRuntime.WebUpdate.cs, and the embedded asset map referenced by
v2rayN.WebAPI.csproj; the updater rejects app-only ZIPs that contain anything beyond the executable and v2rayN.WebAPI.build.json. - If backup archive shape changes in ServiceLib, update Services/V2rayRuntime.Backup.cs and Services/BackupDatabaseCompatibility.cs; restore only accepts flat files under a
guiConfigs/segment, excludes WebAPI-auth.json, and validates known SQLite primary keys before replacing the config directory. - If startup/environment variables change in Program.cs or Configuration/NativeEnvironmentFile.cs, keep README.md aligned; startup security decisions are based on the effective environment and listener configuration, and the native .env parser deliberately rejects shell syntax instead of evaluating it.
Risks
- Services/V2rayRuntime.Settings.cs and Services/CoreSettingsApplyPolicy.cs: a settings save that affects the running core must either restart successfully or roll back config/database/runtime. If new settings paths bypass
BeginCoreSettingsApplyAsync/CompleteCoreAffectingChangeAsync, clients can observe saved settings while the old core keeps serving stale configuration. - Services/V2rayRuntime.CoreUpdate.cs, Services/CoreUpdatePackageStager.cs, and Services/GeoFilesUpdateTransaction.cs: update flows modify executable/core/geofile directories on disk. If archive validation, version checks, or rollback moves are weakened, a bad package can replace the running core or leave GeoFiles partially updated after ServiceLib reports progress errors.
- Services/V2rayRuntime.WebUpdate.cs and Services/WebUpdatePackageStager.cs: Web self-update deliberately verifies the release manifest, asset URL, SHA-256, RID identity, and ELF/PE architecture before stopping the host. If installation starts before
WebProbeUriResolvercan produce a loopback health probe, the helper cannot prove replacement health or rollback safely. - Services/V2rayRuntime.Backup.cs: restore closes SQLite and atomically replaces the config directory before requesting host shutdown. If restore runtime-state markers are not written/committed correctly, startup may fail to recover a previously running core or may retry stale restore intent.
- Services/CoreProcessTracker.cs and Services/V2rayRuntime.cs: the runtime treats tracked process identity as ownership and explicitly avoids using port occupancy as ownership. If future stop/restart/update code infers ownership from a listening port, it may mistake an unrelated process for the Web-owned core or report a clean stop while the actual child remains alive.