Skip to content

alts-codex/unity-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AltsCodex Unity SDK

Official Unity client SDK for AltsCodex DeOAuth — a decentralized identity layer that bridges OAuth with on-chain account abstraction. This package is the Unity-side counterpart of the JavaScript / Python / Go server SDKs in the AltsCodex family:

📚 Docs · Support · Sign updevelopers.altscodex.com 🏠 Platformaltscodex.com


⚠️ Scope — read this first

This SDK is the client side of the AltsCodex flow. It opens the AltsCodex login URL in a browser and returns the user's short-lived JWT to your Unity game. You then send that JWT to your own game backend, which uses one of the server SDKs (Node.js, Python, or Go) to resolve the user's slot info via the server-only client_secret.

[Unity client]                  [Your game backend]              [DeOAuth server]
     │                                  │                              │
     │ 1. AltsCodexLogin.LoginAsync() ─→│                              │
     │    (opens browser, gets JWT)     │                              │
     │                                  │                              │
     │ 2. POST /login (jwt) ───────────→│                              │
     │                                  │ 3. get_slot_info(jwt) ──────→│
     │                                  │    ◄── slot info ────────────│
     │ ◄── session token + user data ───│                              │

Never embed client_secret in a Unity build. It would be extractable via decompilation in under a minute (il2cpp_dumper, dnSpy). This SDK only handles the public client_id half of the OAuth flow.

Supported build targets (0.1.x)

Target Status Mechanism
WebGL ✅ Supported window.open popup + postMessage (identical to JS SDK)
Standalone Windows ✅ Supported Application.OpenURL + loopback HttpListener
Standalone macOS ✅ Supported same as Windows
Standalone Linux ✅ Supported same as Windows
Unity Editor (Play mode) ✅ Supported uses the Standalone path for testing
iOS ❌ Out of scope for 0.1.x needs SFSafariViewController plugin + URL scheme registration
Android ❌ Out of scope for 0.1.x needs Custom Tabs plugin + App Link manifest
Other (tvOS, Switch, …) ❌ Out of scope returns LoginResult.Failed immediately

Mobile support is a deliberate non-goal for this release line. A future 0.2.x may add it via OS-native plugins; until then, build for WebGL on mobile if you need browser-equivalent UX.


Table of Contents


Installation

Unity Package Manager (UPM) Git URL — the simplest path:

  1. Open Window → Package Manager
  2. Click the + button → Add package from git URL...
  3. Paste:
https://github.com/alts-codex/unity-sdk.git

Pin to a specific version with #v0.1.0:

https://github.com/alts-codex/unity-sdk.git#v0.1.0

Or edit Packages/manifest.json directly:

{
  "dependencies": {
    "com.alts-codex.auth-sdk": "https://github.com/alts-codex/unity-sdk.git#v0.1.0"
  }
}

Compatibility

Item Range
Unity 2020.3 LTS or newer
Scripting backend Mono or IL2CPP
API compatibility level .NET Standard 2.1 (also works on .NET Framework)
External dependencies None — uses only UnityEngine + System.*

Quick start

using System.Threading;
using UnityEngine;
using AltsCodex;

public class LoginButton : MonoBehaviour
{
    public async void OnClick()
    {
        var config = new LoginConfig
        {
            ClientId    = "YOUR_CLIENT_ID",          // Developer Center 발급
            RedirectUri = "https://yourgame.example.com/callback",
            // AltsCodexUrl defaults to https://altscodex.com
        };

        var result = await AltsCodexLogin.LoginAsync(config);

        if (!result.Success)
        {
            Debug.LogWarning("login failed: " + result.ErrorMessage);
            return;
        }

        // Send result.Jwt to your game backend.
        // Your backend then calls Node/Python/Go SDK to resolve slot info.
        Debug.Log("JWT received, length=" + result.Jwt.Length);
    }
}

A complete runnable example lives in Samples~/BasicLogin/BasicLoginExample.cs — install via Package Manager → AltsCodex Auth SDK → Samples → Basic Login → Import.


How each platform works

WebGL

Behaves exactly like the JavaScript frontend SDK:

  1. C# LoginAsync calls into the .jslib via [DllImport("__Internal")].
  2. JavaScript window.open(loginUrl, ...) opens a popup pointing at altscodex.com/oauth/login.
  3. After the user logs in, altscodex.com calls window.opener.postMessage({ from: "altscodex", type: "success", data: <jwt> }, "...").
  4. The .jslib event listener verifies event.origin matches your AltsCodexUrl, then sends the payload back into Unity via unityInstance.SendMessage("AltsCodex_BrowserDispatcher", "OnLoginMessage", json).
  5. The internal BrowserDispatcher (a hidden MonoBehaviour) parses the JSON and completes the awaiting Task<LoginResult>.

Required setup in your WebGL HTML template

The .jslib needs access to the Unity instance via window.unityInstance. In the default Unity 2020+ WebGL template, expose it like this:

createUnityInstance(canvas, config).then((unityInstance) => {
    window.unityInstance = unityInstance;   // ← add this line
});

Without this, the bridge logs an explicit error to the browser console and the login Task never completes.

COOP / popup-close detection

If your page sets Cross-Origin-Opener-Policy: same-origin, the browser blocks the SDK's popup.closed poll. The SDK degrades gracefully — it stops polling and relies on postMessage + the configured TimeoutSeconds. Recommended COOP for pages hosting the WebGL build: same-origin-allow-popups or unsafe-none.


Standalone

Standard OAuth-for-native-apps pattern (RFC 8252):

  1. SDK binds a System.Net.HttpListener to http://127.0.0.1:<port>/callback/ (port is ephemeral by default).
  2. SDK constructs redirect_uri = http://127.0.0.1:<port>/callback and overrides whatever you passed in LoginConfig.RedirectUri.
  3. Application.OpenURL(loginUrl) opens the user's default browser at altscodex.com/oauth/login?...&redirect_uri=http://127.0.0.1:<port>/callback&....
  4. After login, the platform server redirects the browser to that loopback URI with jwt=...&state=... (or code=...&state=... for the OAuth code grant).
  5. The HttpListener receives the request, parses query parameters, responds with a "Login successful, you may close this window" HTML page, and resolves the awaiting Task<LoginResult>.

Required Developer Center setup

The loopback URI must be registered. Two options:

  • Fixed port — register http://127.0.0.1:17070/callback exactly, and set LoginConfig.LoopbackPort = 17070. Easier to register, but the port could clash with other apps.
  • Wildcard — register the pattern http://127.0.0.1:*/callback if the Developer Center supports it. Each launch picks a free ephemeral port.

If neither works for your deployment, contact the AltsCodex team — the platform side may need to add support for the OAuth-for-native-apps redirect mode.

Firewall prompts

On Windows the first launch may trigger a firewall prompt because HttpListener opens an inbound port. The port is bound to 127.0.0.1 (loopback only — not externally reachable), so allowing it is safe. macOS / Linux do not prompt for loopback binds.


API reference

All public types live in the AltsCodex namespace.

AltsCodexLogin

public static class AltsCodexLogin
{
    public static Task<LoginResult> LoginAsync(
        LoginConfig config,
        CancellationToken cancellationToken = default);
}

The only entry point you call directly. Internally it generates a CSRF state, selects the appropriate bridge for the current build target, and returns a Task<LoginResult>.

  • Cancel via the CancellationToken — closes the popup (WebGL) or stops the listener (Standalone).
  • Honours LoginConfig.TimeoutSeconds (default 120s) as a wall-clock timeout.

LoginConfig

[Serializable]
public sealed class LoginConfig
{
    public string AltsCodexUrl   = "https://altscodex.com";  // platform base URL
    public string ClientId;                                  // required
    public string RedirectUri;                               // required for WebGL; ignored on Standalone
    public string ResponseType   = "code";                   // OAuth response_type
    public int    TimeoutSeconds = 120;                      // wall-clock timeout

    // Standalone only:
    public int    LoopbackPort   = 0;                        // 0 = ephemeral
    public string LoopbackPath   = "/callback";

    // WebGL only:
    public int    PopupWidth     = 600;
    public int    PopupHeight    = 500;
}

The class is [Serializable] so you can populate it from a MonoBehaviour Inspector.

LoginResult

[Serializable]
public sealed class LoginResult
{
    public bool   Success;
    public string Jwt;          // populated when Success == true
    public string State;        // CSRF state that was used
    public string ErrorMessage; // populated when Success == false
                                // (or ErrorMessage == "code-grant" when Jwt holds an OAuth code)
}

For the code-grant edge case on Standalone — if the platform redirects with ?code=... instead of ?jwt=..., the SDK fills LoginResult.Jwt with the code, marks Success = true, and sets ErrorMessage = "code-grant". Your code is responsible for exchanging that code via your game backend (which calls one of the server SDKs' code-exchange endpoint).

Helpers

public static class StateGenerator
{
    public static string Generate();  // 16 random bytes, hex-encoded (32 chars)
}

public static class LoginUrlBuilder
{
    public static string Build(
        LoginConfig config,
        string state,
        string redirectUriOverride = null);
}

These are exposed for tests and advanced integrations. Most users only call AltsCodexLogin.LoginAsync.


Configuration

The SDK reads no environment variables. All configuration is passed explicitly to LoginAsync. Typical pattern: load config from a ScriptableObject checked into source control (without secrets — there are no secrets on the client side).

[CreateAssetMenu(menuName = "AltsCodex/LoginSettings")]
public class AltsCodexLoginSettings : ScriptableObject
{
    public string clientId;
    public string redirectUri;
    public string altsCodexUrl = "https://altscodex.com";
}
var result = await AltsCodexLogin.LoginAsync(new LoginConfig
{
    AltsCodexUrl = settings.altsCodexUrl,
    ClientId     = settings.clientId,
    RedirectUri  = settings.redirectUri,
});

Security

  • No client_secret on the client. This SDK never sees one. Your game backend uses the server SDKs (Node/Python/Go) for client_secret-protected calls.
  • RedirectUri must match the Developer Center registration exactly — including scheme, host, port, path, and trailing slash. For Standalone, register the loopback URI form your build will actually use.
  • CSRF state is generated automatically by StateGenerator.Generate() and verified inside the SDK on Standalone callbacks. WebGL relies on event.origin checking inside the .jslib.
  • Don't persist the JWT. It's short-lived. Exchange it for your own session token via your backend immediately after login.
  • WebGL CORS / COOP — see the WebGL section for the required headers.

Common pitfalls

1. Wrong subdomain in AltsCodexUrl

Use https://altscodex.com for production, http://localhost:3000 for local development. Do NOT invent subdomains like oauth.altscodex.com, auth.altscodex.com, login.altscodex.com — they resolve to NXDOMAIN and login silently fails with a long timeout.

2. WebGL: unityInstance not exposed

Default templates do not expose the Unity instance globally. Add window.unityInstance = unityInstance; after createUnityInstance().then(...). Without this, the .jslib cannot deliver the JWT back to C#.

3. WebGL: popup blocked

Browsers block popups that are not opened in a direct user-gesture handler. Call AltsCodexLogin.LoginAsync from a Button.onClick (or similar). Calling it from Start(), Update(), async continuations, or a coroutine timer will trip the popup blocker — the SDK returns LoginResult.Failed("Popup blocked. Please allow popups.").

4. Standalone: RedirectUri not registered

The Developer Center must whitelist the exact loopback URI form your build uses. If the platform rejects the redirect, the browser shows an invalid_client / redirect_uri mismatch page and the SDK times out.

5. Standalone: HttpListener permission on macOS

macOS sandbox-signed builds may require the com.apple.security.network.server entitlement. Standard Unity Standalone builds work without it; only matters if you sign for the Mac App Store.

6. Mobile platforms

iOS and Android intentionally return LoginResult.Failed("...not supported") in 0.1.x. Build the game for WebGL if you need a browser-equivalent login UX on mobile devices.

7. The JWT is not your session token

The JWT from LoginResult.Jwt proves the user authenticated against AltsCodex right now. It is not a session token for your game. Send it to your backend, exchange it for slot info via the server SDK, then issue your own session token (cookie / JWT) for the game session. Discard the AltsCodex JWT after that exchange.


Comparison with the sister SDKs

Feature JS (@altscodex/sdk) Python Go Unity (this)
Browser popup login ✅ (WebGL)
System-browser login ✅ (Standalone)
Server-side get_token chain ❌ — call your own backend
client_secret storage closure name-mangled private field none — never seen
Token return mechanism postMessage (server-only) (server-only) postMessage (WebGL) / loopback redirect (Standalone)
Distribution channel npm PyPI Go module proxy UPM Git URL
Test framework jest pytest go test NUnit (Editor)

All four SDKs are designed to interoperate. Typical deployment: Unity (this) on the client, one of Node/Python/Go on the game backend, AltsCodex as the identity provider.


Testing

Editor-only unit tests for LoginUrlBuilder and StateGenerator ship with the package.

  1. Window → General → Test Runner
  2. Switch to the PlayMode or EditMode tab
  3. Click Run All

The integration paths (WebGL .jslib + Standalone HttpListener) require platform-specific harnesses and are tested manually against the Developer Center's local test server. See the JavaScript SDK for the protocol-level Jest test scenarios that motivate the design.


Versioning & releases

  • Semantic versioning. 0.x line may contain breaking changes between minor versions while the API stabilises; 1.0 will lock the public surface.
  • Releases are tagged in this repo (v0.1.0, v0.2.0, …). UPM Git URL with #vX.Y.Z pins to a specific release.
  • Mobile support, when it arrives, will ship on the 0.2.x line.

Resources

Resource URL
Platform altscodex.com
Developer Center developers.altscodex.com
Backend SDK guide developers.altscodex.com/sdk_backend
JS SDK @altscodex/sdk on npm
Python SDK altscodex-sdk on PyPI
Go SDK pkg.go.dev/github.com/alts-codex/auth-sdk
This repo github.com/alts-codex/unity-sdk

License

MIT — see LICENSE.

About

Unity SDK for AltsCodex DeOAuth login (WebGL + Standalone only)

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors