Source of truth. This page mirrors state-server/docs/JS/authentication.md. The repo is canonical — update there first, then resync here.
Authentication is managed by AuthService (via sdk.auth). The top-level SDK exposes wrappers (sdk.login(), sdk.register(), sdk.logout()) that maintain SDK-level auth state and emit events.
const auth = await sdk.register({
username: 'john_doe',
email: '[email protected]',
password: 'TestPass123',
display_name: 'John Doe', // optional
});
// auth.user, auth.access_token, auth.refresh_token, auth.expires_in, auth.token_type
Input (RegisterRequest)
| Field | Type | Required | Description |
|---|---|---|---|
username |
string | yes | Unique username. |
email |
string | yes | Email address. |
password |
string | yes | Password. |
display_name |
string | no | Also accepts displayName. |
Response (AuthResponse): user (User), access_token, refresh_token, expires_in, token_type (always "Bearer").
The wrapper sets sdk.authenticated = true, syncs the token to the WebSocket client, and emits authenticated.
const auth = await sdk.login('[email protected]', 'TestPass123');
const auth2 = await sdk.login('john_doe', 'TestPass123'); // by username
Server receives { username: identifier, password }. Same AuthResponse shape as register.
await sdk.logout();
Sends stored refresh_token to POST /api/v1/auth/logout. Clears local + stored session, resets API/WS tokens, emits unauthenticated.
const result = await sdk.auth.refreshToken();
// result.access_token, result.refresh_token
Uses the stored refresh_token. Throws if no refresh token is available. Returns the same AuthResponse shape.
await sdk.auth.verifyEmail(token); // GET /api/v1/auth/verify?token=<token>
Emits emailVerified.
await sdk.auth.resendVerification('[email protected]'); // POST /api/v1/auth/resend-verification
Rate limited to 1 per 5 minutes per email.
await sdk.auth.changePassword('currentPass', 'newPass');
Server receives { old_password, new_password } to POST /api/v1/users/{userId}/change-password. Invalidates all existing sessions.
await sdk.auth.forgotPassword('[email protected]'); // POST /api/v1/auth/forgot-password
Rate limited 1 per 5 minutes per email.
await sdk.auth.resetPassword(resetToken, 'newPassword');
Server receives { token, new_password } to POST /api/v1/auth/reset-password.
const googleUrl = sdk.auth.getGoogleOAuthUrl();
const microsoftUrl = sdk.auth.getMicrosoftOAuthUrl();
const url = sdk.auth.getOAuthUrl('google'); // or 'microsoft'
After redirect back from provider:
try {
const auth = await sdk.auth.handleOAuthCallback('google', code, state);
console.log(auth.user, auth.access_token);
} catch (error) {
if (error.code === 'OAUTH_REDIRECT') {
console.log('Redirect to:', error.location);
}
}
Calls GET /api/v1/auth/oauth/{provider}/callback?code=...&state=.... Returns the standard AuthResponse. Throws OAUTH_REDIRECT with error.location if the server redirects to a frontend URL. The callback uses redirect: 'manual' and credentials: 'include' for cookie-based session handling.
Browser — sessions stored in localStorage under key state_server_session as JSON: access_token, refresh_token, user, expires_at.
Node.js — no built-in persistence; implement your own or use sdk.setAuthToken(token).
Auto-loading — sdk.initialize({ loadSession: true }) restores a non-expired session.
Validation — sdk.auth.validateSession() checks local state only; sdk.auth.isSessionExpired() checks expiry; sdk.auth.getSessionExpiry() returns ms.
Auto-refresh — sdk.auth.autoRefreshToken() refreshes if expiring within 5 minutes.
sdk.setAuthToken('eyJhbGciOi...');
Sets the token across ApiClient, WebSocketClient, and AuthService simultaneously. Useful for SSR or external auth providers.
sdk.isAuthenticated();
sdk.getCurrentUser();
sdk.auth.getCurrentSession();
sdk.auth.isSessionExpired();
| Event | Source | Payload | When |
|---|---|---|---|
authenticated |
SDK | User |
After login/register. |
unauthenticated |
SDK | — | After logout. |
auth:login, auth:logout, auth:tokenRefreshed |
SDK (forwarded) | varies | Forwarded from AuthService. |
registered, login, logout, tokenRefreshed |
AuthService | varies | After each operation. |
emailVerified, passwordChanged, passwordResetRequested, passwordReset, verificationResent |
AuthService | varies | After each operation. |
oauth-login |
AuthService | {provider, user} |
After OAuth callback. |
AuthResponse — { user, access_token, refresh_token, expires_in, token_type }.
Session — { session_id, user_id, access_token, refresh_token, created_at, expires_at, device_id?, ip_address?, user_agent? }.
state-server/docs/JS/configuration.md, state-server/docs/JS/error-handling.md, state-server/docs/JS/events-reference.md (in-repo; mirror pending).