@hyve-sdk/js
v1.2.2
Published
Hyve SDK - TypeScript wrapper for Hyve game server integration
Downloads
1,587
Readme
@hyve-sdk/js
TypeScript SDK for web3 authentication and game integration, providing secure signature verification and utility functions.
Installation
bun add @hyve-sdk/js
# or
npm install @hyve-sdk/js
# or
pnpm add @hyve-sdk/jsFeatures
- Web3 Authentication: EVM signature validation and verification
- Modern & Legacy Token Support: Dual authentication token formats
- JWT Authentication: Support for JWT tokens passed via URL parameters
- API Integration: Authenticated API calls with JWT token support
- Inventory Management: Built-in methods for user inventory operations
- Telemetry Tracking: Session-based analytics and event tracking
- Security Utilities: Domain validation and referrer checking
- URL Parameter Parsing: Easy extraction of authentication parameters
- UUID Generation: Built-in UUID v4 generation
Core Components
HyveClient
Main client class for SDK operations including authentication, telemetry, and API calls.
import { HyveClient } from "@hyve-sdk/js";
// Initialize with optional configuration
const client = new HyveClient({
isDev: true, // Development mode (default: true)
apiBaseUrl: 'https://...' // Optional custom API URL
});
// Authenticate from URL parameters
// Extracts: hyve-token/signature, hyve-access (JWT), game-id
const authenticated = await client.authenticateFromUrl();
if (authenticated) {
console.log('User ID:', client.getUserId());
console.log('Session ID:', client.getSessionId());
console.log('Has JWT:', client.hasJwtToken());
console.log('Game ID:', client.getGameId());
}Authentication Utilities
Parse URL Parameters
Extract authentication and game parameters from URL:
import { parseUrlParams } from "@hyve-sdk/js";
const params = parseUrlParams(window.location.search);
// Returns:
// {
// signature: string,
// message: string,
// gameStartTab: string,
// hyveToken: string,
// platform: string,
// hyveAccess: string, // JWT token
// gameId: string // Game identifier
// }Verify Authentication
Unified verification supporting both modern and legacy tokens:
import { verifyAuthentication } from "@hyve-sdk/js";
const result = verifyAuthentication({
hyveToken: params.hyveToken, // Modern token format
signature: params.signature, // Legacy format
message: params.message // Legacy format
});
if (result.isValid) {
console.log('Authenticated address:', result.address);
console.log('Auth method used:', result.method); // 'modern' or 'legacy'
}Modern Token Verification (Hyve Token)
Verify modern authentication tokens with expiration:
import { verifyHyveToken } from "@hyve-sdk/js";
// Token format: signature.address.randomBase64.timestamp
const address = verifyHyveToken(hyveToken, 600); // 600 seconds max age
if (address) {
console.log('Valid token for address:', address);
}Legacy Token Verification
Verify legacy signed messages with metadata:
import { handleVerifyMessage, validateSignature } from "@hyve-sdk/js";
// Method 1: Verify message with embedded metadata
const address = handleVerifyMessage(signature, message);
// Method 2: Simple signature validation
const isValid = validateSignature(signature, message, userId);Security Utilities
Domain Validation
Check if current domain is allowed:
import { isDomainAllowed } from "@hyve-sdk/js";
// Single domain
const allowed = isDomainAllowed('example.com', window.location.hostname);
// Multiple domains with wildcard support
const allowed = isDomainAllowed(
['example.com', '*.subdomain.com'],
window.location.hostname
);
// Note: localhost is always allowedUtility Functions
UUID Generation
Generate random UUID v4:
import { generateUUID } from "@hyve-sdk/js";
const id = generateUUID();Telemetry & Analytics
Send Telemetry Events
Track user actions and game events using JWT authentication:
// Send a user-level telemetry event
// Game ID is automatically extracted from 'game-id' URL parameter
await client.sendTelemetry(
'game', // Event location
'player', // Event category
'action', // Event action
'combat', // Event sub-category (optional)
'attack', // Event sub-action (optional)
{ // Event details - auto-stringified (optional)
button: 'attack-btn',
screenPosition: { x: 100, y: 200 }
},
{ // Custom data - auto-stringified (optional)
damage: 100,
targetId: 'enemy-123',
weaponType: 'sword',
level: 3
},
'web-chrome' // Platform ID (optional)
);Requirements:
- Requires JWT token (from
hyve-accessURL parameter) - Requires authenticated user
- Requires game ID (from
game-idURL parameter) - User ID is automatically extracted from JWT (cannot be spoofed)
URL Parameters Expected:
hyve-access- JWT authentication tokengame-id- Game identifier (associates all telemetry with this game)hyve-tokenorsignature+message- For user authentication
Features:
- Automatically includes
session_idandgame_idfrom client - Objects in
event_detailsandcustom_dataare auto-stringified to JSON - All events tied to authenticated user identity
API Integration
JWT Authentication
The SDK supports JWT tokens and game IDs passed via URL parameters:
// URL: https://game.com?hyve-access=your-jwt-token&game-id=my-game
// Authenticate extracts JWT and game ID automatically
await client.authenticateFromUrl();
// Check availability
if (client.hasJwtToken()) {
console.log('JWT token:', client.getJwtToken());
console.log('Game ID:', client.getGameId());
}Generic API Calls
Make authenticated API requests:
// GET request
const userData = await client.callApi('/api/v1/user');
// POST request with body
const result = await client.callApi('/api/v1/game/score', {
method: 'POST',
body: JSON.stringify({ score: 1000 })
});
// With TypeScript typing
interface UserData {
id: string;
username: string;
}
const user = await client.callApi<UserData>('/api/v1/user');Inventory Management
Get User Inventory
Retrieve all inventory items:
const inventory = await client.getInventory();
console.log(`Total items: ${inventory.total_count}`);
inventory.items.forEach(item => {
console.log(`${item.item_type}: ${item.quantity}x`);
});Response Type:
interface Inventory {
items: InventoryItem[];
total_count: number;
}
interface InventoryItem {
id: string;
user_id: string;
item_type: string;
item_id: string;
quantity: number;
metadata?: Record<string, any>;
created_at: string;
updated_at: string;
}Get Specific Inventory Item
Fetch details for a single item:
const item = await client.getInventoryItem('item-id-123');
console.log(`Item: ${item.item_type}`);
console.log(`Quantity: ${item.quantity}`);
if (item.metadata) {
console.log('Metadata:', item.metadata);
}API Endpoints:
GET /api/v1/inventory- Get all inventory itemsGET /api/v1/inventory/:id- Get specific item
Requirements:
- JWT token must be available (via
hyve-accessURL parameter) - User must be authenticated
Client Methods Reference
Authentication
authenticateFromUrl(urlParams?)- Authenticate from URL parameters (extracts JWT, game ID, user auth)getUserId()- Get authenticated user ID (address)getSessionId()- Get unique session IDgetGameId()- Get game ID from URL parametersisUserAuthenticated()- Check if user is authenticatedhasJwtToken()- Check if JWT token is availablegetJwtToken()- Get JWT token stringlogout()- Clear user authenticationreset()- Reset client state with new session
API Calls
callApi<T>(endpoint, options?)- Generic authenticated API callgetInventory()- Get user's inventorygetInventoryItem(itemId)- Get specific inventory item
Telemetry
sendTelemetry(location, category, action, subCategory?, subAction?, details?, customData?, platformId?)- Send JWT-authenticated analytics event (uses game ID from URL)updateTelemetryConfig(config)- Update telemetry settings
Configuration
getApiBaseUrl()- Get current API base URLupdateTelemetryConfig(config)- Update client configuration
Authentication Flow
Modern Token Flow (Recommended)
- User authenticates on platform
- Platform generates hyve-token:
signature.address.random.timestamp - Token passed via URL parameter
hyve-token - SDK verifies token with
verifyHyveToken()orverifyAuthentication()
Legacy Token Flow
- User signs message containing metadata (expiration, address)
- Signature and message passed via URL parameters
- SDK verifies with
handleVerifyMessage()orverifyAuthentication()
Security Considerations
- Token Expiration: Modern tokens expire after 10 minutes by default
- Domain Validation: Always validate origin domains in production
- Signature Verification: All signatures verified using ethers.js
- Localhost Exception: localhost always allowed for development
TypeScript Support
Full TypeScript support with exported types for all utilities and return values.
Dependencies
- ethers: ^6.13.7 - Ethereum signature verification
- uuid: (peer dependency) - UUID generation
Build Configuration
The SDK builds to multiple formats:
- CommonJS (
dist/index.js) - ES Modules (
dist/index.mjs) - TypeScript declarations (
dist/index.d.ts)
Development
# Install dependencies
bun install
# Type checking
bun run check-types
# Linting
bun run lint
# Build
bun run buildDocumentation
For complete documentation and examples, visit https://docs.hyve.gg
License
MIT
