Docs menu

C# API reference

Public types and members of the s&box Network Storage library, generated from its source and XML documentation comments. Most games only need NetworkStorage: Configure once, then call endpoints, documents and queries.

Core

enum EntryKind

  • _entries
  • if
  • _entries
  • _version

Code/Core/NetLog.cs:12

class JsonHelpers

Shared JSON deserialization helpers for Network Storage responses. Handles type coercion (string → number), missing keys, and fallback defaults.

public static int GetInt(JsonElement el, string key, int fallback)

Get an integer from a JSON element, with fallback.

public static float GetFloat(JsonElement el, string key, float fallback)

Get a float from a JSON element, with fallback.

public static string GetString(JsonElement el, string key, string fallback)

Get a string from a JSON element, with fallback.

public static bool GetBool(JsonElement el, string key, bool fallback)

Get a bool from a JSON element, with fallback.

Code/Core/JsonHelpers.cs:10

class NetLog

Static ring buffer that captures Network Storage events for in-game debug windows. Used internally by NetworkStorage and available for game code to log custom events.

public static void Request(string tag, string message)
public static void Response(string tag, string message)
public static void Warning(string tag, string message)
public static void Error(string tag, string message)
public static void Info(string tag, string message)
public static void Clear()

Code/Core/NetLog.cs:10

class NetworkStorage

public static void AutoConfigure()

Auto-configure from network-storage.credentials.json. Called automatically on first API use.

Code/Core/NetworkStorageAutoConfig.cs:6

class NetworkStorage

Network Storage client for sboxcool.com.

Auto-configures from network-storage.credentials.json on first use. You can also call Configure() manually to override.

public static string BaseUrl

Base API URL (no trailing slash).

public static string ApiVersion

API version prefix.

public const string LibraryVersion = ""

Library SemVer, independent of the s&box package and game revisions.

public const string MinServerVersion = ""

Oldest self-hosted server baseline; newer features require capability checks.

public static string PackageVersion

Library version reported to analytics. Retained as an LTS public API.

public static string ProjectId

Your project ID from the sboxcool.com dashboard.

public static string ApiKey

Your public API key (sbox_ns_ prefix).

public static bool IsConfigured

True after Configure() or auto-config has loaded valid credentials.

public static string CdnUrl

Optional CDN URL for storage reads.

public static string ApiRoot

The full versioned API root, e.g. https://api.sboxcool.com/v3.

public static bool ProxyEnabled

Whether non-host clients route API calls through the game host.

public static bool EnableAuthSessions

Project flag for fast auth sessions.

public static bool EnableEncryptedRequests

Project flag for encrypted Network Storage requests.

public static string PublishTarget

Runtime publish target for Network Storage resources ("live" or staged "next").

public static Func<string, string, string, string, Task<string>> RequestProxy

Delegate for proxying endpoint calls through the game host.

public static Func<string, string, string, string, Task<string>> DocumentProxy

Delegate for proxying document reads through the game host.

public static bool IsHost

True if this client is the network host or single-player.

public static void Configure(string projectId, string apiKey, string baseUrl = null, string apiVersion = null, string cdnUrl = null, string publishTarget = null)

Configure the client manually. Call once at game startup.

public static void SetPublishTarget(string publishTarget)

Override the runtime publish target used for endpoint/storage/value requests.

public static void ResetAutoConfigureFlag()

Reset the auto-configure guard so AutoConfigure() can retry.

Code/Core/NetworkStorageClient.cs:12

class NetworkStorage

public static void EnsureConfigured()

Code/Core/NetworkStorageHttp.cs:7

class NetworkStorage

Helpers for writing revision metadata to lobbies. Call BuildLobbyMetadata when creating a lobby to stamp revision tracking keys that other clients can use to discover lobbies running the latest game version.

Key schema (short names for efficient network transfer): ns_rev — RuntimeRevisionId (0 for editor/local sessions) ns_stale — 1 if outdated, 0 if current ns_grace_end — Grace period end unix timestamp, or 0 ns_mig — 1 if this lobby supports migration, 0 otherwise ns_mig_rev — Migration target revision, or 0 ns_src — Source lobby ID (set when created via "Create New Game")

public static Dictionary<string, string> BuildLobbyMetadata(long? migrationRevision = null, string sourceLobbyId = null)

Build a lobby metadata dictionary with revision tracking keys. Pass the result to your lobby creation API (e.g. lobby.SetMetadata).

  • migrationRevision

    Target revision for migration, or null.

  • sourceLobbyId

    Previous lobby ID (for "Create New Game" flow), or null.

public static bool IsLobbyOnCurrentRevision(Dictionary<string, string> metadata)

Check whether a lobby's metadata indicates it's running the latest revision. Useful for filtering stale lobbies.

public static bool IsLobbyStale(Dictionary<string, string> metadata)

Check whether a lobby's metadata says it's stale (outdated revision).

Code/Core/NetworkStorageLobbyMetadata.cs:20

class NetworkStorage

public static bool TryGetLastEndpointError(string slug, out string code, out string message)

Code/Core/NetworkStorageResponse.cs:7

class NetworkStorage

public static event Action<RevisionOutdatedData> OnRevisionOutdated

Fired when the load-profile endpoint reports an outdated revision, or when TestFireRevisionOutdated is called. Subscribe to show custom in-game UI for revision warnings.

Code/Core/NetworkStorageRevisionOutdated.cs:192

class NetworkStorage

public static RevisionSettings RevisionSettings

Public settings for the revision/outdated-session system. Configure these once during game startup.

Code/Core/NetworkStorageRevisionSettings.cs:87

class NetworkStorage

public static void OpenRevisionOutdatedMessage(Panel parent = null)

Open the outdated revision message panel. Requires a parent panel to attach to. If parent is null, a warning is logged and no UI is created, but the OnRevisionOutdated hook still fires.

public static void CloseRevisionOutdatedMessage()

Close the outdated revision message panel if it is open.

public static void ToggleRevisionOutdatedMessage(Panel parent = null)

Toggle the outdated revision message panel open/closed.

public static async Task RefreshRevisionLobbyListAsync()

Refresh the lobby list to find lobbies running the latest revision. This is a stub — game code should override with actual lobby query logic by subscribing to OnRefreshLobbyListRequested.

public static event Action OnRefreshLobbyListRequested

Fired when RefreshRevisionLobbyListAsync is called. Game code should subscribe and perform the actual lobby refresh.

public static void TestShowRevisionOutdatedMessage(Panel parent = null)

Simulate an outdated revision detection for testing. Creates a fake RevisionOutdatedData with Reason = ManualTest and fires the full UI pipeline: - Updates NetworkStoragePackageInfo state - Fires OnRevisionOutdated for custom hooks - Opens the default message panel (if configured)

Does NOT require the backend to report a mismatch. Bypasses ShowOnlyOnce. Logs clearly that this is a test.

public static void TestFireRevisionOutdated()

Fire the OnRevisionOutdated event with test data. Does NOT show the default UI — only fires the event so game code can test custom hooks without interference from the default panel. Logs clearly that this is a test.

Code/Core/NetworkStorageRevisionUI.cs:7

class NetworkStorage

Code/Core/NetworkStorageRuntimeContext.cs:5

class NetworkStorage

Code/Core/NetworkStorageServerErrors.cs:6

class NetworkStorageExtensions

Extension helpers for working with Network Storage JSON responses. Reduces boilerplate when parsing endpoint responses into game objects.

Usage: var ores = response.ReadDictionary( "ores", prop => (float)prop.GetDouble() ); var upgrades = response.ReadStringList( "purchasedUpgrades" ); var level = response.Int( "level", 1 );

public static int Int(this JsonElement el, string key, int fallback = 0)

Get an int from a JsonElement, with fallback.

public static float Float(this JsonElement el, string key, float fallback = 0f)

Get a float from a JsonElement, with fallback.

public static string Str(this JsonElement el, string key, string fallback = "")

Get a string from a JsonElement, with fallback.

public static bool Bool(this JsonElement el, string key, bool fallback = false)

Get a bool from a JsonElement, with fallback.

public static List<string> ReadStringList(this JsonElement el, string key)

Read a JSON array property as a List of strings. Returns empty list if property missing or wrong type.

public static Dictionary<string, T> ReadDictionary<T>(this JsonElement el, string key, Func<JsonElement, T> converter)

Read a JSON object property as a Dictionary with a value converter. Useful for ore inventories: response.ReadDictionary("ores", v => (float)v.GetDouble())

public static List<T> ReadList<T>(this JsonElement el, string key, Func<JsonElement, T> converter)

Read a JSON array property as a List with a row converter. Useful for tables: response.ReadList("rows", row => new OreInfo(row))

public static List<string> FindMismatches(this JsonElement serverData, Dictionary<string, (object Local, Func<JsonElement, object> Extract)> fields)

Compare local state against a server response and return a list of mismatches. Fields is a dictionary of fieldName → (localValue, serverExtractor).

Code/Core/NetworkStorageExtensions.cs:16

class NetworkStorageLogConfig

Controls which Network Storage log categories are printed to the console. All categories default to enabled. Call DisableAll() then enable specific ones, or EnableAll() then disable specific ones.

public static bool LogRequests

Log outgoing request details (method, URL, body).

public static bool LogResponses

Log response bodies and status.

public static bool LogTokens

Log auth token acquisition and status.

public static bool LogProxy

Log proxy RPC traffic (host/client handoff).

public static bool LogErrors

Log errors and warnings (failures, HTTP errors).

public static bool LogConfig

Log configuration and startup messages.

public static void EnableAll()

Enable all log categories.

public static void DisableAll()

Disable all log categories.

Code/Core/NetworkStorageLogConfig.cs:8

class NetworkStorageOutdatedUI

Built-in simple in-game UI for outdated revision warnings. Supports two enforcement modes: - Force Upgrade: Warning with grace countdown, Dismiss button - Allow Continue: Informational with Continue Playing primary

Uses RevisionSettings for configuration. Subscribes to OnRevisionOutdated when AutoOpenOnOutdated is true.

The panel is hidden via CSS class toggling (SetClass("hidden", ...)). A parent panel MUST be provided — the UI does not auto-attach.

public static void ResetState()

Reset the popup state. Call this when starting a new game session. This allows the popup to show again even if showPopupOnce is enabled.

public static Panel RootPanel

The parent panel to use when auto-opening the UI. If not set, the library will auto-create a ScreenPanel.

public static bool IsOpen

True when the panel instance exists and is not hidden.

public static event Action OnCreateNewGame

Fired when the user clicks "Create New Game".

public static event Action OnJoinNewLobby

Fired when the user clicks "Join New Lobby".

public static event Action OnContinuePlaying

Fired when the user clicks "Continue Playing" (Allow Continue mode).

public static event Action OnDismiss

Fired when the user dismisses the popup.

public static void Open(Panel parent = null)

Open the outdated revision window. Uses parent if provided, otherwise falls back to RootPanel. If no parent is available, logs a warning and returns without creating UI.

public static void Close()

Dismiss the panel if it is visible.

public override void OnDeleted()
public override void Tick()

Code/Core/NetworkStorageOutdatedUI.cs:19

class NetworkStoragePackageInfo

Detects and caches package/revision information from s&box APIs. Used to track which revision is running and to build sync payloads for the sboxcool.com backend.

public static long? CurrentRevisionId

The revision ID detected for the package ident, if available.

public static long? RuntimeRevisionId

The revision ID to send with runtime requests. This is only set for published game bundles; editor/local projects do not masquerade as the live revision.

public static long? LatestRevisionId

The latest published revision ID for the package.

public static string PackageIdent

The full package ident, e.g. "org.game".

public static string OrgIdent

The organization ident, e.g. "hooked_inc".

public static string PackageTitle

The human-readable package title.

public static string PublishStatus

The publish status of the current revision (e.g. "live").

public static string PackageType

The package type (e.g. "game", "addon", "map").

public static bool IsEditorContext

True when running from the editor, an editor local instance, or an active local project.

public static bool IsPublishedGameBundle

True only when the engine is running an actual published game bundle.

public static string RuntimeClientType

The client type sent to Network Storage: "editor", "dedicated", or "game".

public static bool IsDetected

True if detection has run and found package info.

public static bool IsOutdatedRevision

Latest revision status: true when running an older revision.

public static int? GraceRemainingMinutes

Minutes remaining in the grace period, if applicable.

public static bool GraceExpired

True when the grace period has expired.

public static string RevisionAction

Current enforcement action: "warn", "block_writes", or "block_all".

public static string RevisionMessage

Human-readable message from the server about revision status.

public static long? ServerCurrentRevision

The server's current (latest) revision ID.

public static int? PolicyGracePeriodMinutes

Revision policy synced from server.

public static string PolicyPostGraceAction
public static bool PolicyForceEndpointUpgrade
public static string PolicyNotifyMessage
public static bool PolicyShowUpdateOptions
public static bool PolicyShowPopupOnce
public static bool PolicyShowDefaultMessage
public static RevisionEnforcementMode EnforcementMode

Enforcement mode from server: ForceUpgrade (default) or AllowContinue.

public static event Action<RevisionStatusInfo> OnRevisionStatusChanged

Fired when revision status changes. Game code can subscribe to show UI.

public static async Task DetectAsync()

Detect package and revision info from the current s&box context. Safe to call multiple times — subsequent calls re-detect from scratch.

public static JsonElement BuildSyncPayload()

Build the package-sync payload matching the backend contract: POST /v3/manage/:projectId/package-sync

public static void Reset()

Clear all cached detection data.

public static void UpdateFromServerResponse(JsonElement response)

Extract _revisionStatus from any server response and update static state. Called automatically by ParseResponse on every endpoint call.

Code/Core/NetworkStoragePackageInfo.cs:13

class NetworkStorageRevisionConfig

Opt-in configuration for revision enforcement features. All settings default to false — game code must explicitly opt in.

public static bool EnableRevisionWarningUI

Show built-in warning UI when an outdated revision is detected.

public static bool EnableAutoDisconnectHost

Auto-disconnect the local client when the revision grace period has expired. DANGEROUS: test thoroughly before enabling in production.

public static bool EnableBlockSavesOnOutdated

Set BlockWrites when running an outdated revision. Endpoint code should check this flag before performing writes. DANGEROUS: may cause data loss if callers ignore the flag.

public static bool EnableOutdatedUI

Enable the entire outdated revision notification UI system.

public static bool ShowDefaultWindow

Show the built-in default warning window.

public static bool ShowOnlyOnce

Only show the warning once per session.

public static float GracePeriod

Grace period override (seconds) before showing the warning. 0 = show immediately.

public static bool AutoRefreshLobbyList

Auto-refresh the lobby list when revision is outdated.

public static float LobbyRefreshInterval

Interval in seconds between lobby list refreshes.

Code/Core/NetworkStorageRevisionConfig.cs:7

class NetworkStorageRevisionHandler

Wires OnRevisionStatusChanged to concrete actions based on RevisionSettings configuration. Call Initialize once during game startup.

public static bool BlockWrites

Set when RevisionSettings has block-saves enabled and the client is running an outdated revision. Endpoint code MUST check this flag before performing write operations.

public static Action<RevisionStatusInfo> OnShowRevisionWarning

Game code can assign a handler to receive revision warnings. Useful for showing custom in-game UI when the built-in console logging is not enough.

public static void Initialize()

Subscribe to revision status change events. Safe to call multiple times — subsequent calls are no-ops.

Code/Core/NetworkStorageRevisionHandler.cs:10

class NetworkStorageRevisionInit

Sends a one-time revision-init packet at game startup so the backend knows which revision this client is running. Call once after Configure.

public static RevisionInitResult? LastInitResult

Cached result from the last successful SendInitAsync call.

public static async Task<RevisionInitResult> SendInitAsync()

Send the revision init packet to the backend. Safe to call even when package/revision data is unavailable — the request proceeds without revision headers and the result reflects the gap.

Code/Core/NetworkStorageRevisionInit.cs:34

enum RevisionEnforcementMode

How the server enforces revision updates.

  • ForceUpgrade

    Grace period countdown, then block saves/all requests.

  • AllowContinue

    Players can keep playing indefinitely with a notification.

Code/Core/NetworkStorageRevisionSettings.cs:8

struct RevisionInitResult

Result of the one-time revision init handshake with the backend.

public bool Ok

True when the backend acknowledged the init successfully.

public bool IsOutdatedRevision

True when the server reports a newer revision is available.

public long? PlayerRevision

The revision this client is running, if known.

public long? CurrentRevision

The latest revision reported by the backend.

public string Message

Human-readable status or warning message from the server.

Code/Core/NetworkStorageRevisionInit.cs:11

struct RevisionOutdatedData

Data from the load-profile endpoint's revision block. Fires OnRevisionOutdated when the server reports the client's revision is outdated.

public RevisionOutdatedData()

Creates a default instance.

public long CurrentRevisionId

The revision the client is running.

public long LatestRevisionId

The latest revision available on the server.

public bool RevisionOutdated

True when the client revision is older than latest.

public int GraceSeconds

Seconds remaining in the grace period, or 0.

public long? GraceEndsAtUnixSeconds

Unix timestamp when grace ends, or null.

public long ServerUnixSeconds

Server's current unix timestamp.

public string Source

Source identifier describing where the detection came from. Typical values: "load-profile", "manual-test", "lobby"

public RevisionOutdatedReason Reason

Why this revision-outdated event was raised.

public RevisionEnforcementMode EnforcementMode

The enforcement mode from the server. Defaults to ForceUpgrade for backward compatibility.

public string Message

Custom message from the server to display to players.

public string Action

What action is currently required: "warn", "block_saves", "block_all".

public bool GraceExpired

True when the grace period has expired (from server).

public int? GraceRemainingMinutes

Minutes remaining in the grace period (from server), or null if no grace.

public bool ShowUpdateOptions

True if the server wants to show update options (Create/Join buttons).

public bool ShowPopupOnce

True if popup should only show once per session.

public int TimeRemaining

Seconds until grace expires (negative if already expired).

public bool IsGraceExpired

True when the grace period has fully expired.

Code/Core/NetworkStorageRevisionOutdated.cs:29

enum RevisionOutdatedReason

Why the revision was detected as outdated.

  • LoadProfileDetected

    Detected via the load-profile endpoint response.

  • ManualTest

    Triggered manually for testing (no backend required).

  • LobbyMismatch

    Lobby metadata indicates a different revision.

  • GraceExpired

    Grace period expired, revision is now blocked.

Code/Core/NetworkStorageRevisionOutdated.cs:9

class RevisionSettings

Public settings for the NetworkStorage revision/outdated-session system.

Usage: NetworkStorage.RevisionSettings.ShowDefaultMessage = false;

All settings are static and should be configured once during game startup (e.g. in your game's initialization code).

public bool Enabled

Enable revision-outdated detection and hook firing. When false, no detection occurs and no events fire. Default: true

public bool ShowDefaultMessage

Show the built-in default "OUTDATED REVISION" message panel when the revision becomes outdated. Set to true to enable the default UI, or leave false and use your own via OnRevisionOutdated. Default: false

public bool ShowOnlyOnce

Only show the default message once per session. If false, the panel re-appears every time load-profile reports the revision is outdated. Default: true

public TimeSpan GracePeriod

Grace period before the outdated warning appears. Use Zero to show immediately. Default: TimeSpan.Zero

public bool AutoRefreshLobbies

Auto-refresh the lobby list when the revision is outdated. Default: false

public float LobbyRefreshInterval

Interval in seconds between lobby list refreshes. Only used when AutoRefreshLobbies is true. Default: 10

public bool AllowSpaceToClose

Allow the SPACE key to close the default message panel. Default: true

public bool AutoOpenOnOutdated

Automatically open the default message panel when the revision becomes outdated. Set to false if you want to control when the UI appears via OpenRevisionOutdatedMessage. Default: true

Code/Core/NetworkStorageRevisionSettings.cs:27

struct RevisionStatusInfo

Snapshot of revision status, passed to OnRevisionStatusChanged.

public bool IsOutdated
public bool GraceExpired
public int? GraceRemainingMinutes
public string Action
public string Message
public long? PlayerRevision
public long? CurrentRevision
public int? PolicyGracePeriodMinutes
public string PolicyPostGraceAction
public bool PolicyForceEndpointUpgrade
public string PolicyNotifyMessage
public bool PolicyShowUpdateOptions
public bool PolicyShowPopupOnce
public bool PolicyShowDefaultMessage
public RevisionEnforcementMode EnforcementMode

Code/Core/NetworkStoragePackageInfo.cs:423

Analytics

class NetworkStorage

public static Task TrackAnalyticsEvent(string eventType, object payload = null)
public static Task TrackAnalyticsWarning(string code, string message = null, object context = null)
public static Task TrackAnalyticsError(Exception exception, string code = null, object context = null)
public static Task TrackAnalyticsError(string code, string message = null, string stack = null, object context = null)
public static Task TrackSessionStart(object context = null)
public static Task TrackSessionHeartbeat(double sessionSeconds = 0, object context = null, object fps = null)
public static Task TrackSessionEnd(double durationSeconds = 0, object context = null)

Code/Analytics/NetworkStorageAnalytics.cs:8

class NetworkStorage

public static bool EnablePlayerAnalytics
public static bool AnalyticsCaptureSessions
public static bool AnalyticsCaptureWarnings
public static bool AnalyticsCaptureErrors
public static bool AnalyticsCaptureLocalWarnings
public static bool AnalyticsCaptureLocalErrors
public static bool AnalyticsCaptureEndpointDiagnostics
public static bool AnalyticsManagedLibraryEvents
public static bool AnalyticsManagedPerformance
public static bool AnalyticsManagedNetwork
public static bool AnalyticsManagedVoice
public static bool AnalyticsManagedInputFocus
public static bool AnalyticsManagedScene
public static bool AnalyticsManagedRuntime
public static bool AnalyticsManagedRevision
public static bool AnalyticsManagedSystemInfo
public static bool AnalyticsRetainErrorStacks

Code/Analytics/NetworkStorageAnalyticsConfig.cs:6

class NetworkStorageAnalytics

Convenience facade for Player Analytics. Methods forward to NetworkStorage so projects can use either NetworkStorageAnalytics.TrackEvent(...) or NetworkStorage.TrackAnalyticsEvent(...).

public static Task TrackEvent(string eventType, object payload = null)
public static Task Warning(string code, string message = null, object context = null)
public static Task Error(Exception exception, string code = null, object context = null)
public static Task Error(string code, string message = null, string stack = null, object context = null)
public static Task SessionStart(object context = null)
public static Task SessionHeartbeat(double sessionSeconds = 0, object context = null, object fps = null)
public static Task SessionEnd(double durationSeconds = 0, object context = null)

Code/Analytics/NetworkStorageAnalyticsFacade.cs:11

Auth

class NetworkStorage

public static async Task<bool> EnsureEndpointAuthAsync(string slug)

Code/Auth/NetworkStorageAuthTokens.cs:7

class NetworkStorage

Code/Auth/NetworkStorageDedicatedSecretLoaders.cs:7

class NetworkStorage

public static string NetworkStorageSecretKeyDashedConVar
public static string NetworkStorageSecretKeyConVar
public static string SboxCoolSecretKeyConVar
public static string NetworkStorageSecretKeyCamelConVar
public static string SboxCoolSecretKeyCamelConVar
public static string NsSecretKeyCamelConVar
public static string NsSecretKeyConVar
public static bool HasDedicatedServerSecretKey

True when this process is a dedicated server and a runtime endpoint secret key was supplied. The key is never read on clients or listen servers.

public static string DedicatedServerSecretKeySource

Where the dedicated endpoint secret key was loaded from, without exposing the key.

public static void ConfigureDedicatedServerSecretKey(string secretKey)

Manually provide a runtime endpoint secret key. This is accepted only on dedicated servers. Prefer the dedicated launch flag: +network_storage_secret_key sbox_sk_...

Code/Auth/NetworkStorageDedicatedServerSecret.cs:6

class NetworkStorage

public static Task<bool> EnsureDedicatedServerSecretValidatedAsync(string reason = "", bool forceRefresh = false)

Validates the configured dedicated-server secret key against the management API. No-op outside dedicated server hosts. Logs success/failure without exposing the key.

Code/Auth/NetworkStorageDedicatedServerSecretValidation.cs:8

Endpoints

class NetworkStorage

Code/Endpoints/NetworkStorageAes.cs:5

class NetworkStorage

Code/Endpoints/NetworkStorageCryptoHelpers.cs:6

class NetworkStorage

Code/Endpoints/NetworkStorageEncryptedEnvelope.cs:8

class NetworkStorage

Code/Endpoints/NetworkStorageEndpointSecurity.cs:9

class NetworkStorage

Code/Endpoints/NetworkStorageEndpointUrlSupport.cs:6

class NetworkStorage

public static Task<JsonElement?> CallEndpoint(string slug, object input = null)

Call a server endpoint by slug or dashboard endpoint URL. Returns the response body on success, null on any failure.

Code/Endpoints/NetworkStorageEndpoints.cs:7

class NetworkStorage

public static async Task<JsonElement?> GetGameValues()

Load all game values (groups + tables).

Code/Endpoints/NetworkStorageGameValues.cs:7

class NetworkStorage

Code/Endpoints/NetworkStorageProxySignature.cs:6

class NetworkStorage

Frontend helpers for request security metadata used by encrypted Network Storage calls.

public static string CreateEncryptedRequestId()

Creates a one-use encrypted request id in "{unixSeconds}_{random}" format. The backend must reject stale or repeated ids before running endpoint logic.

public static bool TryParseEncryptedRequestId(string requestId, out long unixSeconds, out string random)

Validates and parses an encrypted request id in "{unixSeconds}_{random6plus}" format.

Code/Endpoints/NetworkStorageRequestSecurity.cs:10

class NetworkStorage

public static bool RuntimeSecurityConfigLoaded
public static bool RuntimeEnableAuthSessions
public static bool RuntimeEnableEncryptedRequests
public static string RuntimeSecurityConfigVersion
public static string RuntimeSecurityClientMode
public static string RuntimeSecurityConfigSource
public static string LastSecurityConfigDiagnostics
public static bool IsSecurityConfigMismatchCode(string code)
public static async Task<bool> EnsureRuntimeSecurityConfigAsync(string reason = "", bool forceRefresh = false)
public static void MarkRuntimeSecurityMismatch(string code, string requestMode = "")
public static void ApplyServerExpectedSecurityConfig(string code, JsonElement expected, string expectedConfigVersion = null)

Code/Endpoints/NetworkStorageRuntimeSecurityConfig.cs:7

class NetworkStorage

Code/Endpoints/NetworkStorageRuntimeSecurityConfigLoad.cs:7

class NetworkStorage

Code/Endpoints/NetworkStorageRuntimeSecuritySnapshot.cs:6

Proxy

class NetworkStorage

public static async Task<JsonElement?> CallEndpointAs(string targetSteamId, string clientToken, string slug, object input = null)

Call an endpoint on behalf of another player (host only). Requires the client's auth token as proof of consent. Sends: host auth (Facepunch-verified) + client token + HMAC proxy signature scoped to this project + endpoint to prevent cross-server replay.

public static async Task<JsonElement?> GetDocumentAs(string targetSteamId, string clientToken, string collectionId, string documentId = null)

Read a document on behalf of another player (host only). Requires the client's auth token as proof of consent.

Code/Proxy/NetworkStorageHostProxyClient.cs:7

class NetworkStorage

Code/Proxy/NetworkStorageProxyClient.cs:7

class NetworkStorageProxyComponent

Bridges NetworkStorage proxy delegates to s&box RPCs.

When proxy mode is enabled (Editor → Network Storage → Settings): - Non-host clients route API calls through this component via [Rpc.Broadcast] - The host receives the request, calls CallEndpointAs / GetDocumentAs, and sends the result back - The client awaits the result via a TaskCompletionSource keyed by request ID

Security: The client's auth token is forwarded to the host, which includes it in the HMAC proxy signature sent to the backend. This proves client consent without requiring the backend to verify the client's token against Facepunch (which fails for non-host clients).

Attach to each player's GameObject via PlayerSpawner.

Code/Proxy/NetworkStorageProxyComponent.cs:22

Storage

class NetworkStorage

public static Task<JsonElement?> SaveDocument(string collectionId, string documentId, object data)

Save or replace a collection document. Defaults to the current player's Steam ID. On dedicated servers, a configured secret key is sent automatically so endpoint-only collections can be edited when the key has collection execute permission.

public static Task<JsonElement?> SetDocument(string collectionId, string documentId, object data)

Alias for SaveDocument.

public static Task<JsonElement?> UpdateDocument(string collectionId, string documentId, IEnumerable<NetworkStorageOperation> operations)

Apply server-side operations to a collection document. This avoids sending the full document and lets the backend validate increments, ledgers, and rate limits.

public static Task<JsonElement?> UpdateDocument(string collectionId, string documentId, params NetworkStorageOperation[] operations)

Apply server-side operations to a collection document.

public static Task<JsonElement?> PatchDocument(string collectionId, string documentId, params NetworkStorageOperation[] operations)

Alias for UpdateDocument.

public static Task<JsonElement?> DeleteDocument(string collectionId, string documentId = null)

Delete a collection document. The backend must have allowRecordDelete enabled for the collection. Defaults to the current player's Steam ID.

public static Task<JsonElement?> ListRecords(string collectionId, string steamId = null)

List save-record metadata for a player in a multi-record collection.

public static Task<JsonElement?> CreateRecord(string collectionId, string steamId = null, string recordName = null)

Create a save-record entry for a player in a multi-record collection.

public static Task<JsonElement?> DeleteRecord(string collectionId, string recordId, string steamId = null)

Delete a save-record entry and its stored document data.

public static Task<JsonElement?> RenameRecord(string collectionId, string recordId, string recordName, string steamId = null)

Rename a save-record entry.

Code/Storage/NetworkStorageCollections.cs:10

class NetworkStorage

public static async Task<JsonElement?> GetDocument(string collectionId, string documentId = null)

Read a document from a collection. If documentId is null, uses the current player's Steam ID.

Code/Storage/NetworkStorageDocuments.cs:7

class NetworkStorage

public static Task<JsonElement?> RunQuery(string queryId)

Run a dashboard query by ID. Public queries use the public runtime key. On dedicated servers, a configured secret key is sent automatically so secret-gated queries can run without s&box auth tokens.

public static async Task<JsonElement?> GetQuery(string queryId)

Alias for RunQuery.

Code/Storage/NetworkStorageQueries.cs:7

class NetworkStorageOperation

A server-side document mutation for Network Storage collection records. Operations are applied by the backend against the current document, so callers can update counters and arrays without sending a full replacement document.

public string Op
public string Path
public object Value
public object Match
public string Source
public string Reason
public static NetworkStorageOperation Set(string path, object value, string source = null, string reason = null)
public static NetworkStorageOperation Increment(string path, double amount, string source = null, string reason = null)
public static NetworkStorageOperation Push(string path, object value)
public static NetworkStorageOperation Pull(string path, object match)
public static NetworkStorageOperation Remove(string path, object value)

Code/Storage/NetworkStorageOperation.cs:10

enum SaveState

  • PendingCalls
  • SetState
  • if
  • NetLog
  • var
  • PendingCalls
  • if
  • else
  • return

Code/Storage/SaveStateTracker.cs:23

class SaveStateTracker

Tracks the save state of endpoint calls for HUD feedback. Wraps NetworkStorage.CallEndpoint with automatic state management and logging.

Usage: var tracker = new SaveStateTracker(); var result = await tracker.Call( "mine-ore", new { ore_id = "moon_ore", kg = 5 } ); if ( result.HasValue ) Apply( result.Value );

Properties: tracker.State → Idle, Saving, Saved, Error tracker.IsBusy → true while any call is in progress tracker.LastError → error message from last failure

public async Task<bool> CallAndApply(string slug, object input, Action applyOptimistic, Action<JsonElement> applyServer, Action revert)

Call an endpoint, apply the result to a callback on success, revert on failure. Handles the optimistic update → server confirm → revert pattern.

public void Reset()

Code/Storage/SaveStateTracker.cs:21

Generated from sbox-cool/sbox-network-storage/Code at main (13f51a8).