UNPKG

flamesshield-sdk

Version:

Flames Shield Smart rate limiting for Firebase Cloud Functions to protect your services from excessive requests

155 lines (119 loc) 4.91 kB
# FlameShield SDK FlameShield is a rate limiting SDK for Firebase Cloud Functions that helps protect your services from excessive requests. ## Installation ```bash npm install flamesshield-sdk ``` ## Usage FlameShield provides a simple way to add rate limiting to your Firebase Cloud Functions. ### Basic Example ```typescript import { rateLimit } from 'flamesshield-sdk'; import { initializeApp } from 'firebase-admin/app'; const app = initializeApp(); export const myFunction = async (req, res) => { try { await rateLimit({ maxCalls: 100, periodSeconds: 60, app: app, onSuccess: () => { // Your function logic here res.status(200).send('Success!'); }, onFailure: () => { res.status(429).send('Too many requests'); } }); } catch (error) { res.status(500).send('Error: ' + error.message); } }; ``` ### Parameters The `rateLimit` function accepts the following parameters: | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `maxCalls` | number | Yes | | Maximum number of calls allowed in the period | | `periodSeconds` | number | Yes | | Time period in seconds for the rate limit | | `onSuccess` | function | Yes | | Function to execute when rate limit is not exceeded | | `app` | App | Yes | | Firebase Admin App instance | | `name` | string | No | Environment variable* | The name of your function | | `qualifier` | string | No | | Optional identifier (e.g., userId) to create separate rate limits for different entities | | `onFailure` | function | No | throws Error | Function to execute when rate limit is exceeded | | `apiKey` | string | No | process.env.API_KEY | API key for FlameShield service | | `verbose` | boolean | No | false | Enable verbose logging | \* The SDK will automatically try to use one of the following environment variables: `FUNCTION_TARGET`, `K_SERVICE`, or `FUNCTION_NAME`. ### Rate Limiting Parameters Explained #### maxCalls and periodSeconds These parameters work together to define your rate limiting policy: - `maxCalls`: Defines the maximum number of function invocations allowed - `periodSeconds`: Defines the time window in seconds for the rate limit For example: - `maxCalls: 100, periodSeconds: 60` allows 100 calls per minute - `maxCalls: 1000, periodSeconds: 3600` allows 1000 calls per hour - `maxCalls: 10000, periodSeconds: 86400` allows 10000 calls per day Choose these values based on your function's resource consumption and expected traffic patterns. #### qualifier The `qualifier` parameter is optional but useful for creating separate rate limits for different entities: ```typescript await rateLimit({ maxCalls: 50, periodSeconds: 3600, app: app, qualifier: userId, // Create separate rate limits per user onSuccess: () => { /* function logic */ }, }); ``` Common use cases for `qualifier`: - User ID: Limit each user to a specific number of requests - IP address: Rate limit by client IP - Subscription tier: Apply different limits based on customer tier - Region/location: Create separate quotas for different geographic regions ### Advanced Example ```typescript import { rateLimit } from 'flamesshield-sdk'; import { initializeApp } from 'firebase-admin/app'; const app = initializeApp(); export const processOrder = async (req, res) => { try { // Using userId as qualifier to create separate rate limits per user const userId = req.auth.uid; await rateLimit({ maxCalls: 500, periodSeconds: 3600, // 1 hour app: app, qualifier: userId, apiKey: process.env.FLAMESHIELD_API_KEY, verbose: true, onSuccess: () => { // Process the order const result = processOrderLogic(req.body); res.status(200).json(result); }, onFailure: () => { // Handle rate limit exceeded res.status(429).json({ error: 'Rate limit exceeded', message: 'You have exceeded your order processing limit for this hour' }); } }); } catch (error) { console.error('Order processing error:', error); res.status(500).json({ error: 'Internal server error' }); } }; function processOrderLogic(orderData) { // Your order processing logic return { orderId: '12345', status: 'processed' }; } ``` ## Error Handling If the rate limit is exceeded and no `onFailure` function is provided, the SDK will throw an error with the message 'Rate limit exceeded'. ## Environment Configuration The SDK can be configured using environment variables: - `API_KEY`: Default API key for FlameShield service - `FUNCTION_TARGET`, `K_SERVICE`, or `FUNCTION_NAME`: Default function name if not specified ## Verbose Logging When `verbose` is set to `true`, the SDK will log detailed information about the rate limiting process, which can be helpful for debugging.