@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 validreason
(string, optional): Reason for failure if the token is invaliddata
(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 optionssecretKey
(string): Secret key for token verificationtokenExpiration
(number): Token expiration time in secondsrateLimit
(object): Rate limiting configurationenabled
(boolean): Whether rate limiting is enabledmaxRequests
(number): Maximum number of requests allowed in the time windowwindowMs
(number): Time window in milliseconds
ipProtection
(object): IP protection configurationenabled
(boolean): Whether IP protection is enabledblacklist
(string[]): List of blacklisted IP addressessuspiciousAttempts
(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
Keep Your Secret Key Secure
- Store your secret key in environment variables
- Never expose it in client-side code
- Rotate keys periodically
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
Set Appropriate Token Expiration
- Short expiration times (5-15 minutes) are recommended
- Balance security with user experience
Monitor Verification Attempts
- Log suspicious activity
- Set up alerts for unusual patterns
- Regularly review logs
Use HTTPS
- Always use HTTPS in production
- Secure cookie settings
- Implement proper CORS policies
Next Steps
- Explore integration examples for common use cases
- Learn about behavior analysis for advanced security