Skip to content

Authentication ​

Logstyx uses different authentication mechanisms depending on the type of client making the request. Authentication is validated asynchronously after the request is queued.

Authentication Methods ​

1. Browser Client Authentication (Origin Validation) ​

For web applications running in browsers, authentication is performed by validating the request origin against a whitelist configured in your project settings.

How it Works ​

  1. The browser automatically sends an Origin header with each request
  2. Logstyx checks if the origin is in your project's allowed origins list
  3. If the origin matches, the request is authorized

Configuration ​

In your Logstyx project settings, configure the allowed origins:

json
{
  "settings": {
    "allowedOrigin": [
      "http://localhost:3000",
      "https://yourapp.com",
      "https://staging.yourapp.com"
    ]
  }
}

Example Request ​

bash
curl -X POST https://your-domain.com/api/v1/logs \
  -H "Content-Type: application/json" \
  -H "Origin: https://yourapp.com" \
  -d '{
    "level": "info",
    "projectId": "your_project_id",
    "message": "User logged in",
    "data": {
      "userId": "12345",
      "action": "login"
    }
  }'

Important Notes ​

  • The Origin header is automatically set by the browser and cannot be modified by JavaScript
  • Only include trusted domains in your allowed origins list
  • Use HTTPS in production to prevent man-in-the-middle attacks
  • Wildcards are not supported; you must list each origin explicitly

2. Mobile Client Authentication (App ID Validation) ​

For mobile applications (iOS, Android, React Native), authentication uses an application ID that you configure in your project settings.

How it Works ​

  1. Include an appid in the request body
  2. Logstyx validates the appid against your project's allowed app IDs
  3. If the app ID matches, the request is authorized

Configuration ​

In your Logstyx project settings, configure the allowed app IDs:

json
{
  "settings": {
    "allowedOrigin": [
      "com.yourcompany.app.ios",
      "com.yourcompany.app.android",
      "com.yourcompany.app.development"
    ]
  }
}

Note: App IDs are stored in the same allowedOrigin array as browser origins.

Example Request ​

bash
curl -X POST https://your-domain.com/api/v1/logs \
  -H "Content-Type: application/json" \
  -d '{
    "level": "warning",
    "projectId": "your_project_id",
    "appid": "com.yourcompany.app.ios",
    "device": {
        type: "iPhone 15 Pro",
        origin: null,
        os: null,
        platform: null,
        browser: null,
        screen: null
    };
    ,
    "message": "API request failed",
    "data": {
      "endpoint": "/api/users",
      "statusCode": 500
    }
  }'

SDK Usage Example ​

javascript
import { useLogstyx } from 'logstyx-js-react-native';

const logger = useLogstyx({
  projectId: 'your_project_id',
  appid: 'com.yourcompany.app.ios',
  endpoint: 'https://your-domain.com/api/v1/logs'
});

logger.warning({
  message: 'API request failed',
  data: {
    endpoint: '/api/users',
    statusCode: 500
  }
});

Important Notes ​

  • Use reverse domain notation for app IDs (e.g., com.company.app)
  • Store app IDs as constants in your app configuration
  • Different app IDs can be used for development, staging, and production
  • Never hardcode sensitive information in mobile apps

3. Server Client Authentication (HMAC Signature) ​

For server-side applications and backend services, Logstyx uses HMAC-SHA256 signature verification to ensure request authenticity and integrity.

How it Works ​

  1. Create a payload from specific request body fields
  2. Generate a hash string combining the projectId, payload, and timestamp
  3. Create an HMAC-SHA256 signature using your project secret
  4. Send the signature and timestamp in request headers
  5. Logstyx recomputes the signature and compares it with yours

Required Headers ​

Content-Type: application/json
timestamp: <unix_timestamp_in_milliseconds>
signature: <hmac_sha256_signature_uppercase>

Signature Generation Algorithm ​

javascript
// 1. Extract fields from request body
const { level, projectId, device, context, data } = requestBody;

// 2. Create payload object (order matters!)
const payload = {
  level,
  projectId,
  device,
  context,
  data
};

// 3. Create hash string
const params = JSON.stringify(payload);
const timestamp = Date.now(); // Current time in milliseconds
const hashString = projectId + params + Math.floor(timestamp);

// 4. Generate HMAC signature
const crypto = require('crypto');
const signature = crypto
  .createHmac('SHA256', projectSecret)
  .update(hashString)
  .digest('hex')
  .toUpperCase();

Complete Example (Node.js) ​

javascript
const crypto = require('crypto');
const axios = require('axios');

async function sendLog(projectId, projectSecret, logData) {
  const timestamp = Date.now();
  
  // Prepare request body
  const body = {
    level: logData.level,
    projectId: projectId,
    device: logData.device || 'server',
    context: logData.context || {},
    data: logData.data
  };
  
  // Create signature payload (must match server order)
  const payload = {
    level: body.level,
    projectId: body.projectId,
    device: body.device,
    context: body.context,
    data: body.data
  };
  
  // Generate signature
  const params = JSON.stringify(payload);
  const hashString = projectId + params + Math.floor(timestamp);
  const signature = crypto
    .createHmac('SHA256', projectSecret)
    .update(hashString)
    .digest('hex')
    .toUpperCase();
  
  // Send request
  try {
    const response = await axios.post(
      'https://your-domain.com/api/v1/logs',
      body,
      {
        headers: {
          'Content-Type': 'application/json',
          'timestamp': timestamp.toString(),
          'signature': signature
        }
      }
    );
    
    console.log('Log sent successfully:', response.data);
  } catch (error) {
    console.error('Failed to send log:', error.message);
  }
}

// Usage
sendLog('your_project_id', 'your_project_secret', {
  level: 'error',
  device: 'api-server-01',
  context: { service: 'payment' },
  data: {
    message: 'Payment processing failed',
    errorCode: 'PAYMENT_GATEWAY_TIMEOUT',
    amount: 99.99
  }
});

Python Example ​

python
import hmac
import hashlib
import json
import time
import requests

def send_log(project_id, project_secret, log_data):
    timestamp = int(time.time() * 1000)  # milliseconds
    
    # Prepare request body
    body = {
        'level': log_data.get('level'),
        'projectId': project_id,
        'device': log_data.get('device', 'server'),
        'context': log_data.get('context', {}),
        'data': log_data.get('data')
    }
    
    # Create signature payload
    payload = {
        'level': body['level'],
        'projectId': body['projectId'],
        'device': body['device'],
        'context': body['context'],
        'data': body['data']
    }
    
    # Generate signature
    params = json.dumps(payload, separators=(',', ':'))
    hash_string = f"{project_id}{params}{int(timestamp)}"
    signature = hmac.new(
        project_secret.encode('utf-8'),
        hash_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest().upper()
    
    # Send request
    response = requests.post(
        'https://your-domain.com/api/v1/logs',
        json=body,
        headers={
            'Content-Type': 'application/json',
            'timestamp': str(timestamp),
            'signature': signature
        }
    )
    
    return response.json()

# Usage
send_log('your_project_id', 'your_project_secret', {
    'level': 'error',
    'device': 'api-server-01',
    'context': {'service': 'payment'},
    'data': {
        'message': 'Payment processing failed',
        'errorCode': 'PAYMENT_GATEWAY_TIMEOUT',
        'amount': 99.99
    }
})

Important Notes ​

  • Field Order: The payload fields must be in exact order: level, projectId, device, context, data
  • JSON Serialization: Use consistent JSON serialization (no extra spaces)
  • Timestamp Conversion: Convert timestamp to integer when creating the hash string
  • Uppercase: The final signature must be in uppercase
  • Secret Security: Never expose your project secret in client-side code
  • Replay Protection: Timestamps should be recent (consider implementing server-side timestamp validation)

Authentication Priority ​

When multiple authentication methods are present in a request, Logstyx checks them in this order:

  1. Browser client (checks for browser Origin header)
  2. Mobile client (checks for appid in body)
  3. Server client (checks for signature in headers)

If none of these authentication methods are valid, the request will fail authorization during processing.

Retrieving Your Credentials ​

Project ID ​

Your project ID is available in the Logstyx dashboard after creating a project.

Project Secret ​

Your project secret is generated when you create a project and should be stored securely. It's used for server-side HMAC signature generation.

Configuring Origins and App IDs ​

Navigate to your project settings in the Logstyx dashboard to configure:

  • Allowed browser origins
  • Allowed mobile app IDs

Security Best Practices ​

  1. Use HTTPS: Always use HTTPS in production to encrypt data in transit
  2. Secure Secrets: Store project secrets in environment variables, never in code
  3. Minimal Origins: Only whitelist necessary origins and app IDs
  4. Monitor Access: Regularly review your logs for unauthorized access attempts
  5. Client-Side: Browser and mobile authentication is less secure than server-side signatures
  6. Sensitive Data: Avoid logging sensitive information like passwords or API keys

Troubleshooting ​

Authorization Failed ​

If your logs aren't appearing in the dashboard, check:

  • Browser clients: Ensure the origin is in the allowed origins list
  • Mobile clients: Verify the app ID matches your configuration
  • Server clients: Check signature generation algorithm, field order, and secret
  • All clients: Confirm the project ID is correct

Common Signature Errors ​

  • Wrong field order: Ensure payload fields are ordered correctly
  • Lowercase signature: Convert signature to uppercase
  • Timestamp issues: Use integer timestamp without decimals
  • JSON formatting: Avoid extra spaces in JSON serialization
  • Wrong secret: Verify you're using the correct project secret

Released under the MIT License.