
Research
Supply Chain Attack on Axios Pulls Malicious Dependency from npm
A supply chain attack on Axios introduced a malicious dependency, plain-crypto-js@4.2.1, published minutes earlier and absent from the project’s GitHub releases.
lightrate-client
Advanced tools
A JavaScript/TypeScript client for the LightRate token management API, providing easy-to-use methods for consuming tokens with local bucket management.
npm install lightrate-client
Or with yarn:
yarn add lightrate-client
Configure the client with your API credentials:
const { configure, getClient } = require('lightrate-client');
configure({
apiKey: 'your_api_key',
applicationId: 'your_application_id', // required
timeout: 30, // optional, defaults to 30 seconds
retryAttempts: 3, // optional, defaults to 3
logger: console // optional, for request logging
});
const { LightRateClient, createClient } = require('lightrate-client');
// Simple usage - pass your API key and application ID
const client = new LightRateClient('your_api_key', 'your_application_id');
// Or use the convenience method
const client = createClient('your_api_key', 'your_application_id');
// With additional options
const client = new LightRateClient('your_api_key', 'your_application_id', {
timeout: 60,
defaultLocalBucketSize: 10
});
// Or configure globally and use the default client
configure({
apiKey: 'your_api_key',
applicationId: 'your_application_id'
});
const client = getClient();
// Consume tokens by operation
const response = await client.consumeTokens(
'user123', // userIdentifier
1, // tokensRequested
'send_email' // operation
);
// Or consume tokens by path
const response = await client.consumeTokens(
'user123', // userIdentifier
1, // tokensRequested
undefined, // operation (not used when path is specified)
'/api/v1/emails/send', // path
'POST' // httpMethod (required when path is specified)
);
if (response.success) {
console.log(`Tokens consumed successfully. Remaining: ${response.tokensRemaining}`);
} else {
console.log(`Failed to consume tokens: ${response.error}`);
}
The client supports local token buckets for improved performance. Buckets are automatically created based on the rules returned by the API, and are matched against incoming requests using the matcher field from the rule. Each bucket is associated with a specific user and rule, ensuring proper isolation.
// Configure client with default bucket size
const client = new LightRateClient('your_api_key', 'your_application_id', {
defaultLocalBucketSize: 20 // All operations use this bucket size
});
// Consume tokens using local bucket (more efficient)
const result = await client.consumeLocalBucketToken(
'user123', // userIdentifier
'send_email' // operation
);
console.log(`Success: ${result.success}`);
console.log(`Used local token: ${result.usedLocalToken}`);
console.log(`Bucket status: ${JSON.stringify(result.bucketStatus)}`);
// Note: If the API returns a default rule (isDefault: true),
// no local bucket is created and tokens are consumed directly from the API
Bucket Matching:
matcher field from the rule, which supports regex patternsconst { ConsumeTokensRequest } = require('lightrate-client');
// Create a consume tokens request
const request = new ConsumeTokensRequest({
operation: 'send_email',
userIdentifier: 'user123',
tokensRequested: 1
});
// Consume tokens
const response = await client.consumeTokensWithRequest(request);
if (response.success) {
console.log(`Tokens consumed successfully. Remaining: ${response.tokensRemaining}`);
} else {
console.log(`Failed to consume tokens: ${response.error}`);
}
const { LightRateClient } = require('lightrate-client');
// Create a client with your API key and application ID
const client = new LightRateClient('your_api_key', 'your_application_id');
async function example() {
try {
// Consume tokens
const consumeResponse = await client.consumeTokens(
'user123',
1,
'send_email'
);
if (consumeResponse.success) {
console.log(`Successfully consumed tokens. Remaining: ${consumeResponse.tokensRemaining}`);
// Proceed with your operation
} else {
console.log(`Failed to consume tokens: ${consumeResponse.error}`);
// Handle rate limiting
}
} catch (error) {
if (error.name === 'UnauthorizedError') {
console.log(`Authentication failed: ${error.message}`);
} else if (error.name === 'TooManyRequestsError') {
console.log(`Rate limited: ${error.message}`);
} else if (error.name === 'APIError') {
console.log(`API Error (${error.statusCode}): ${error.message}`);
} else if (error.name === 'NetworkError') {
console.log(`Network error: ${error.message}`);
}
}
}
example();
This package includes full TypeScript support with type definitions:
import {
LightRateClient,
ConsumeTokensRequest,
ClientOptions
} from 'lightrate-client';
const client = new LightRateClient('your_api_key', 'your_application_id', {
timeout: 30,
retryAttempts: 3
} as ClientOptions);
const request: ConsumeTokensRequest = {
operation: 'send_email',
userIdentifier: 'user123',
tokensRequested: 1
};
const response = await client.consumeTokensWithRequest(request);
The client provides comprehensive error handling with specific exception types:
try {
const response = await client.consumeTokens('send_email', undefined, undefined, 'user123', 1);
} catch (error) {
if (error.name === 'UnauthorizedError') {
console.log('Authentication failed:', error.message);
} else if (error.name === 'NotFoundError') {
console.log('Resource not found:', error.message);
} else if (error.name === 'APIError') {
console.log(`API Error (${error.statusCode}):`, error.message);
} else if (error.name === 'NetworkError') {
console.log('Network error:', error.message);
} else if (error.name === 'TimeoutError') {
console.log('Request timed out:', error.message);
}
}
Available error types:
LightRateError - Base error classConfigurationError - Configuration-related errorsAuthenticationError - Authentication-related errorsAPIError - Base API error classBadRequestError - 400 errorsUnauthorizedError - 401 errorsForbiddenError - 403 errorsNotFoundError - 404 errorsUnprocessableEntityError - 422 errorsTooManyRequestsError - 429 errorsInternalServerError - 500 errorsServiceUnavailableError - 503 errorsNetworkError - Network-related errorsTimeoutError - Request timeout errorsLightRateClientMain client class for interacting with the LightRate API.
Constructor:
new LightRateClient(apiKey: string, applicationId: string, options?: ClientOptions)
Methods:
consumeTokens(userIdentifier, tokensRequested, operation?, path?, httpMethod?): Promise<ConsumeTokensResponse>consumeLocalBucketToken(userIdentifier, operation?, path?, httpMethod?): Promise<ConsumeLocalBucketTokenResponse>consumeTokensWithRequest(request): Promise<ConsumeTokensResponse>getAllBucketStatuses(): Record<string, any>resetAllBuckets(): voidgetConfiguration(): ConfigurationConfigurationConfiguration class for client settings.
Constructor:
new Configuration(options?: Partial<ConfigurationOptions>)
Methods:
isValid(): booleantoObject(): Record<string, any>update(options): voidTokenBucketToken bucket for local token management. Buckets are matched against incoming requests using the matcher field from the rule returned by the API. Each bucket is associated with a specific rule and user identifier.
Constructor:
new TokenBucket(maxTokens: number, ruleId: string, userIdentifier: string, matcher?: string, httpMethod?: string)
Methods:
hasTokens(): booleanconsumeToken(): booleanconsumeTokens(count): numberrefill(tokensToFetch): numbergetStatus(): TokenBucketStatusreset(): voidmatches(operation?, path?, httpMethod?): boolean - Check if this bucket matches the given request using the matcher regexexpired(): boolean - Check if bucket has expired (not accessed in 60 seconds)checkAndConsumeToken(): boolean - Atomically check and consume a tokenconfigure(options): void - Configure global clientgetClient(): LightRateClient - Get global client instancecreateClient(apiKey, applicationId, options?): LightRateClient - Create new clientreset(): void - Reset global configurationConsumeTokensRequest - Includes optional tokensRequestedForDefaultBucketMatch fieldConsumeTokensResponseConsumeLocalBucketTokenResponseRule - Includes matcher (regex pattern) and httpMethod fields for bucket matching, plus isDefault flagConfigurationOptionsClientOptionsTokenBucketStatusAfter checking out the repo, run npm install to install dependencies. Then, run npm test to run the tests. You can also run npm run dev for development mode with watch.
To build the project, run npm run build.
Bug reports and pull requests are welcome on GitHub at https://github.com/lightbourne-technologies/lightrate-client-javascript. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The package is available as open source under the terms of the MIT License.
Everyone interacting in the LightRate Client JavaScript project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
FAQs
A JavaScript client for the Lightrate token management API
We found that lightrate-client demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
A supply chain attack on Axios introduced a malicious dependency, plain-crypto-js@4.2.1, published minutes earlier and absent from the project’s GitHub releases.

Research
Malicious versions of the Telnyx Python SDK on PyPI delivered credential-stealing malware via a multi-stage supply chain attack.

Security News
TeamPCP is partnering with ransomware group Vect to turn open source supply chain attacks on tools like Trivy and LiteLLM into large-scale ransomware operations.