Skip to content

@gameshield/server

The @gameshield/server package provides server-side verification and security features for GameShield. It allows you to validate tokens generated by the client-side components and implement additional security measures.

Installation

bash
# Using npm
npm install @gameshield/server

# Using yarn
yarn add @gameshield/server

# Using pnpm
pnpm add @gameshield/server

Key Features

  • Token Verification: Validate tokens generated by client-side components
  • Security Utilities: Protection against common attack vectors
  • Rate Limiting: Prevent abuse through configurable rate limits
  • IP Protection: Block suspicious IP addresses
  • Framework Agnostic: Works with any Node.js server framework

Basic Usage

Token Verification

Verify tokens in your API endpoint:

javascript
import express from 'express';
import { verifyToken } from '@gameshield/server';

const app = express();
app.use(express.json());

app.post('/api/verify', (req, res) => {
  const { token } = req.body;
  
  if (!token) {
    return res.status(400).json({
      success: false,
      message: 'Token is required'
    });
  }
  
  const verification = verifyToken(token);
  
  if (verification.valid) {
    // Token is valid, proceed with protected action
    return res.status(200).json({
      success: true,
      message: 'Verification successful'
    });
  } else {
    // Token is invalid, reject the request
    return res.status(400).json({
      success: false,
      message: 'Verification failed',
      reason: verification.reason
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Configuration

Configure the server package with your specific requirements:

javascript
import { configureServer } from '@gameshield/server';

configureServer({
  // Security settings
  secretKey: process.env.GAMESHIELD_SECRET_KEY,
  tokenExpiration: 300, // 5 minutes in seconds
  
  // Rate limiting
  rateLimit: {
    enabled: true,
    maxRequests: 100,
    windowMs: 15 * 60 * 1000, // 15 minutes
  },
  
  // IP protection
  ipProtection: {
    enabled: true,
    blacklist: ['123.456.789.0'],
    suspiciousAttempts: 5
  }
});

API Reference

Token Verification

verifyToken(token: string): VerificationResult

Verifies a token generated by the client-side component.

Parameters:

  • token (string): The token to verify

Returns:

  • VerificationResult (object):
    • valid (boolean): Whether the token is valid
    • reason (string, optional): Reason for failure if the token is invalid
    • data (object, optional): The decoded token data if the token is valid

Example:

javascript
const result = verifyToken(token);

if (result.valid) {
  console.log('Token is valid');
  console.log('Game type:', result.data.gameType);
  console.log('Is human:', result.data.behaviorMetrics.isHuman);
} else {
  console.log('Token is invalid:', result.reason);
}

Configuration

configureServer(options: ServerOptions): void

Configures the server package with the specified options.

Parameters:

  • options (object): Configuration options
    • secretKey (string): Secret key for token verification
    • tokenExpiration (number): Token expiration time in seconds
    • rateLimit (object): Rate limiting configuration
      • enabled (boolean): Whether rate limiting is enabled
      • maxRequests (number): Maximum number of requests allowed in the time window
      • windowMs (number): Time window in milliseconds
    • ipProtection (object): IP protection configuration
      • enabled (boolean): Whether IP protection is enabled
      • blacklist (string[]): List of blacklisted IP addresses
      • suspiciousAttempts (number): Number of suspicious attempts before an IP is blacklisted

Example:

javascript
configureServer({
  secretKey: 'your-secret-key',
  tokenExpiration: 300,
  rateLimit: {
    enabled: true,
    maxRequests: 100,
    windowMs: 15 * 60 * 1000
  },
  ipProtection: {
    enabled: true,
    blacklist: [],
    suspiciousAttempts: 5
  }
});

Integration with Web Frameworks

Express.js Middleware

Create a middleware for Express.js applications:

javascript
import express from 'express';
import { verifyToken } from '@gameshield/server';

const app = express();
app.use(express.json());

// Create a middleware for CAPTCHA verification
const captchaMiddleware = (req, res, next) => {
  const token = req.body.captchaToken || req.query.captchaToken || req.headers['x-captcha-token'];
  
  if (!token) {
    return res.status(400).json({
      success: false,
      message: 'CAPTCHA token is required'
    });
  }
  
  const verification = verifyToken(token);
  
  if (!verification.valid) {
    return res.status(400).json({
      success: false,
      message: 'CAPTCHA verification failed',
      reason: verification.reason
    });
  }
  
  // Token is valid, attach verification data to request
  req.captchaVerification = verification;
  next();
};

// Use the middleware for protected routes
app.post('/api/protected', captchaMiddleware, (req, res) => {
  // Access verification data
  const { data } = req.captchaVerification;
  
  // Process the request
  res.json({
    success: true,
    message: 'Protected action completed',
    verificationData: {
      isHuman: data.behaviorMetrics.isHuman,
      confidence: data.behaviorMetrics.confidence
    }
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Next.js API Route

Use with Next.js API routes:

javascript
// pages/api/verify.js
import { verifyToken } from '@gameshield/server';

export default function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Method not allowed' });
  }
  
  const { token } = req.body;
  
  if (!token) {
    return res.status(400).json({
      success: false,
      message: 'Token is required'
    });
  }
  
  const verification = verifyToken(token);
  
  if (verification.valid) {
    return res.status(200).json({
      success: true,
      message: 'Verification successful'
    });
  } else {
    return res.status(400).json({
      success: false,
      message: 'Verification failed',
      reason: verification.reason
    });
  }
}

Fastify Plugin

Create a Fastify plugin:

javascript
// captcha-plugin.js
import { verifyToken } from '@gameshield/server';

export default async function captchaPlugin(fastify, options) {
  fastify.decorate('verifyCaptcha', (token) => {
    return verifyToken(token);
  });
  
  fastify.addHook('preHandler', async (request, reply) => {
    const { captchaRequired } = request.routeOptions.config;
    
    if (captchaRequired) {
      const token = request.body?.captchaToken || request.query?.captchaToken || request.headers['x-captcha-token'];
      
      if (!token) {
        reply.code(400).send({
          success: false,
          message: 'CAPTCHA token is required'
        });
        return reply;
      }
      
      const verification = fastify.verifyCaptcha(token);
      
      if (!verification.valid) {
        reply.code(400).send({
          success: false,
          message: 'CAPTCHA verification failed',
          reason: verification.reason
        });
        return reply;
      }
      
      request.captchaVerification = verification;
    }
  });
}

// server.js
import Fastify from 'fastify';
import captchaPlugin from './captcha-plugin.js';

const fastify = Fastify();
fastify.register(captchaPlugin);

fastify.post('/api/protected', {
  config: {
    captchaRequired: true
  },
  handler: async (request, reply) => {
    // Access verification data
    const { data } = request.captchaVerification;
    
    // Process the request
    return {
      success: true,
      message: 'Protected action completed',
      verificationData: {
        isHuman: data.behaviorMetrics.isHuman,
        confidence: data.behaviorMetrics.confidence
      }
    };
  }
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log('Server running on port 3000');
});

Security Best Practices

  1. Keep Your Secret Key Secure

    • Store your secret key in environment variables
    • Never expose it in client-side code
    • Rotate keys periodically
  2. Implement Rate Limiting

    • Limit the number of verification attempts
    • Use IP-based rate limiting for additional protection
    • Adjust limits based on your application's needs
  3. Set Appropriate Token Expiration

    • Short expiration times (5-15 minutes) are recommended
    • Balance security with user experience
  4. Monitor Verification Attempts

    • Log suspicious activity
    • Set up alerts for unusual patterns
    • Regularly review logs
  5. Use HTTPS

    • Always use HTTPS in production
    • Secure cookie settings
    • Implement proper CORS policies

Next Steps

Released under the MIT License.