Files
browser/platform_web/api/contracts.md
T
2026-09-03 11:27:19 +08:00

12 KiB

Frontend API Contracts

API clients and DTO types live here, not inside page components.

Client Groups

  • users: user and role APIs.
  • serverPlugins: plugin marketplace and installed plugin APIs.
  • serverInstances: create server, lifecycle, deployment/member/detail APIs, and scoped plugin-data collections.
  • aiProviders: provider CRUD, test, and model APIs.
  • jobs: job status and operation APIs.
  • runEndpoints: run endpoint status, lifecycle capabilities, and capacity APIs.
  • artifacts: artifact upload/download APIs.
  • logs: internal historical cursor APIs used for maintenance/debug views, not server-detail raw log products.
  • pluginPageBridge: safe bridge APIs for hosted plugin page.

Every API client must use named request and response types.

PlatformApiClient converts 401 into a safe re-login error, clears its in-memory bearer token, and notifies the session store to remove browser persistence. A 403 remains a safe capability/ownership denial and does not disclose server error details. Neither error path renders tokens, secret refs, paths, or sockets.

Normal browser login uses the platform's HttpOnly SameSite cookie and credentials=same-origin; the JSON response does not expose a session token. Reading an older localStorage bearer remains a migration compatibility path only, and any 401 removes it.

Server Management Workflows

  • createServerWorkflow posts ServerLifecycleCreateRequest with the create-wizard deployment definition to /server-instances/workflows/create, including deployment mode, plugin create inputs, and custom startup fields when provided. It never includes a deployment target, Run endpoint, lifecycle profile, or Run identity binding. The generated Run package uses plugin defaults and Platform observes the active Run from its authenticated heartbeat.
  • getServerRuntimeBinding reads /server-instances/{id}/runtime-binding; updateServerRuntimeBinding patches the selected profile and logical refs for internal/advanced logical transports. Server detail must not expose a manual runtime-binding tab or require these fields before normal start/stop when plugin-declared deployment/lifecycle data is sufficient. Responses contain only profile metadata, logical key names, configured/secret-backed flags, missing keys, and safe reasons. They never contain stored refs or secret values.
  • startServerInstance and stopServerInstance post ServerLifecycleCommandRequest with the current config version and receive the lifecycle job response.
  • listServerAdministratorCandidates, addServerAdministrator, and removeServerAdministrator call server membership endpoints so server owners can invite or remove active non-platform-admin server administrators.
  • Game-specific pages use the scoped plugin-data collection API and declared plugin bridge machine actions; Platform does not expose game-specific projection or workflow clients.
  • dispatchFileOperation posts FileOperationDispatchRequest to /file-operations/dispatch using logical file keys and scoped refs rather than raw host paths; it remains the low-level compatibility dispatch for file work.
  • getServerFileWorkspace, browseServerFiles, listServerFiles, refreshServerFiles, readServerFile, getServerFileReadSnapshot, writeServerFile, uploadServerFile, and prepareServerFileDownload power the first-party server-detail file manager. The page renders a generic server-root entry and uses browseServerFiles as the live directory path for open, refresh, and search actions; compatibility list/refresh clients remain available for older flows. File reads use files.read, saves use files.write, and browser uploads stage server-instance artifacts before Run pulls input chunks on the dedicated file-transfer channel. Server detail may call only these server-file APIs plus the encapsulated download helper; it must not call raw artifact-transfer methods directly.
  • listArtifacts, openArtifactDownload, downloadArtifactContent, and readArtifactContent use platform artifact routes for available job/server artifacts. Browser downloads stream the full body through /artifacts/{id}/content; explicit range reads may still use bounded offset/limit chunks and must render only safe filenames, checksums, progress, and platform storage behavior.
  • authorizePluginBridge posts PluginBridgeAuthorizeRequest to /plugin-bridge/authorize for preflight decisions.
  • executePluginBridge posts PluginBridgeExecuteRequest to /plugin-bridge/execute from host-owned bridge dispatch utilities only. Plugin pages receive typed PluginBridgeExecuteResponse envelopes and never receive the platform API client, bearer token, raw provider key, run socket, host path, or storage credential.
  • invokeAI posts AIInvocationRequest to /ai/invocations for platform-mediated AI assistance. Responses carry redacted recommendations, usage metadata, optional reviewable config suggestions, and safe errors; they must not include provider base URLs, key refs, raw keys, or direct provider transport details.
  • listRunEndpoints and listJobs provide refresh data for endpoint availability, capacity, and durable lifecycle status. Job projections include retrying, attempt/max-attempt counts, next retry timing, safe ack/lease deadlines, cancellation timestamps/reason, terminal time, and reconciliation outcome/count.
  • getDependencyCatalog reads GET /server-instances/{id}/dependencies and returns only target-matched probe state/evidence, typed plan step summaries, approved download hosts, and immutable SHA-256 planDigest values. Install requests must submit the selected digest; the browser never receives bindings, commands, paths, credentials, tokens, or private download refs.
  • listRunUpdates reads GET /server-instances/{id}/run/update and returns only target, artifact checksum, release identity, phase, bounded status message, rollback flag, and timestamps. The UI treats restart-requested/activating as non-terminal until a later safe projection confirms health.
  • listMetricHistory, listBackups, and getBackup read bounded owner-scoped metric and backup projections. Backup responses contain artifact IDs/checksums and recovery/retention state only; they never include body bytes or storage paths.
  • listRemoteAdapters and requestRemoteAdapter use declaration-backed logical target keys and return queued status/result references. The browser never receives adapter credentials, host addresses, sockets, Run tokens, leases, session hashes, or secret refs.
  • Server management DTOs may include bounded ownerUserId and adminUserIds metadata, but must not include raw run credentials, host paths, direct socket details, user password hashes, or AI provider keys.
  • Server creation and detail forms use plugin-declared deployment inputs only; lifecycle profile selection, Run identity binding, and Run registration waits are not operator controls. Platform applies the plugin default and observes the active Run from authenticated heartbeats.
  • AI provider responses expose apiKeyConfigured only. Existing secret refs are never rehydrated into edit forms; a blank update preserves the platform-owned secret reference.

Redesign Contract Gaps (redesign-platform-web-interactions)

Existing platform APIs already cover server lifecycle, jobs, log stream metadata and cursor query, users, run endpoints, game plugins, plugin bridge authorization, and AI provider health/test. The redesigned UI additionally declares the following frontend contracts; where the platform backend does not yet serve them, the UI must degrade to a clearly labeled local/unavailable state instead of failing silently:

  • POST /api/v1/auth/register (RegisterRequest/AuthSessionResponse): visitor registration. Implemented: the first registered user becomes an active platform administrator; later self-registered users become pending server-scoped users and do not receive platform administrator privileges.
  • POST /api/v1/auth/login (LoginRequest/AuthSessionResponse), POST /api/v1/auth/rotate, and POST /api/v1/auth/logout: implemented bounded, durable bearer session lifecycle for authenticated workspace entry.
  • GET /api/v1/users/current (CurrentUserResponse): implemented current session identity, roles, profile summary, and theme preference reference for role-aware navigation and default landing.
  • PUT /api/v1/users/current/profile (UserProfileUpdateRequest/CurrentUserResponse): implemented current-user profile updates such as display name, avatar reference, phone, QQ, and bounded contact fields.
  • PUT /api/v1/users/current/theme (UserThemePreferenceRequest/UserThemePreferenceResponse): implemented per-user theme preferences, including selected palette IDs such as mecha-black or magical-girl, uploaded background reference or safe persisted data URL metadata, and readable overlay preference.
  • GET /api/v1/metrics/platform (PlatformResourceUsageResponse): implemented platform-level CPU/memory/disk usage and LLM connectivity summary for the overview first screen.
  • GET /api/v1/metrics/server-instances (ServerMetricsListResponse): implemented per-server online state, player count, TPS, latency, CPU/memory/disk for server cards on the server list.
  • Server-scoped raw config routes (GET /api/v1/server-instances/{id}/config, POST .../config/diff, POST .../config/approve) are removed from the product API. AI configuration assistance uses /api/v1/ai/invocations plus reviewable AI config-diff approval APIs; plugin pages do not receive raw config text.
  • POST /api/v1/file-operations/dispatch (FileOperationDispatchRequest/FileOperationDispatchResponse): implemented scoped file operation dispatch using logical keys and refs only.
  • POST /api/v1/ai/config-suggestions (LlmConfigSuggestionRequest/LlmConfigSuggestionResponse) and POST /api/v1/ai/invocations (AIInvocationRequest/AIInvocationResponse): platform-mediated AI recommendation or diff scoped to one server. Provider keys stay in platform/; responses carry only recommendation text, usage metadata, and reviewable suggestions, never keys or provider secrets.
  • Per-server plugin controls are rendered from installed plugin manifests (bridgeActions, lifecycleActions, pages, declaredPermissions); a richer declared-control schema remains a future plugin contract. Hosted bridge execution uses POST /api/v1/plugin-bridge/execute for server context, scoped file, log, job, artifact reference, and AI action envelopes instead of direct plugin fetches to platform internals.
  • Operation/job traceability reuses GET /api/v1/jobs, GET /api/v1/jobs/{id}, and POST /api/v1/jobs/{id}/cancel; the frontend wraps these in one visible operation lifecycle per user intent.

Browser Job contracts explicitly exclude raw or hashed lease tokens, Run session tokens/generations, secret refs, host paths, sockets, and credentials. The safe schema rejects those keys, and existing API client 401/403 behavior remains authoritative for expired sessions and cross-owner access.

  • Server-scoped terminal log streaming (GET /api/v1/server-instances/{id}/logs/events) is used by the server detail terminal drawer for platform-accepted live SSE output only. It does not replay retained log entries, and accepted batches whose source entry timestamps predate the current SSE connection after a small clock-skew allowance stay out of the terminal stream; raw log list/backfill routes (GET .../logs/live, POST .../logs/backfill) and direct management-terminal/RCON input routes remain removed from product clients, and internal log ingest and cursor query remain available to platform services and maintenance/debug flows.

Client Manager API projection

PlatformApiClient exposes list/detail and typed deploy, control, update, retry, revoke-session, and uninstall methods. schemas/clientManagerLifecycle.ts validates status/action/job/health fields and rejects forbidden machine or credential fields before rendering. Lifecycle commands carry profile, distribution, expected deployment generation, approval/confirmation, and idempotency only. Artifact bytes remain in the platform-owned artifact transfer client.