npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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/js

Features

  • 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 allowed

Utility 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-access URL parameter)
  • Requires authenticated user
  • Requires game ID (from game-id URL parameter)
  • User ID is automatically extracted from JWT (cannot be spoofed)

URL Parameters Expected:

  • hyve-access - JWT authentication token
  • game-id - Game identifier (associates all telemetry with this game)
  • hyve-token or signature+message - For user authentication

Features:

  • Automatically includes session_id and game_id from client
  • Objects in event_details and custom_data are 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 items
  • GET /api/v1/inventory/:id - Get specific item

Requirements:

  • JWT token must be available (via hyve-access URL 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 ID
  • getGameId() - Get game ID from URL parameters
  • isUserAuthenticated() - Check if user is authenticated
  • hasJwtToken() - Check if JWT token is available
  • getJwtToken() - Get JWT token string
  • logout() - Clear user authentication
  • reset() - Reset client state with new session

API Calls

  • callApi<T>(endpoint, options?) - Generic authenticated API call
  • getInventory() - Get user's inventory
  • getInventoryItem(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 URL
  • updateTelemetryConfig(config) - Update client configuration

Authentication Flow

Modern Token Flow (Recommended)

  1. User authenticates on platform
  2. Platform generates hyve-token: signature.address.random.timestamp
  3. Token passed via URL parameter hyve-token
  4. SDK verifies token with verifyHyveToken() or verifyAuthentication()

Legacy Token Flow

  1. User signs message containing metadata (expiration, address)
  2. Signature and message passed via URL parameters
  3. SDK verifies with handleVerifyMessage() or verifyAuthentication()

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 build

Documentation

For complete documentation and examples, visit https://docs.hyve.gg

License

MIT