Skip to content

JavaScript Library Documentation

Sharokey JavaScript Library is a single-file solution for managing encrypted secrets with Zero Knowledge architecture. API identical to CLI commands.

Installation

html
<!-- Include from CDN (latest version) -->
<script src="https://cdn.jsdelivr.net/gh/Sharokey/sharokey-cdn@latest/sharokey.js"></script>

<!-- Or specific version for production -->
<script src="https://cdn.jsdelivr.net/gh/Sharokey/[email protected]/sharokey.js"></script>

<script>
    // Configure once
    Sharokey.config({token: 'your_api_token_here'});
    
    // Test connectivity
    const results = await Sharokey.test();
    console.log('Tests passed:', results.passed + '/' + results.total);
</script>

Commands

MethodCLI EquivalentDescriptionExample
config()sharokey configConfigure tokenSharokey.config({token: 'TOKEN'})
create()sharokey createCreate secretSharokey.create("password", 24, 1)
list()sharokey listList secretsSharokey.list({limit: 10, status: 'active'})
get()sharokey getGet secret detailsSharokey.get('ABC123')
delete()sharokey deleteExpire secret (clears content)Sharokey.delete('ABC123')
stats()sharokey statsShow statisticsSharokey.stats()
test()sharokey testTest connectivitySharokey.test()

Secret Requests

MethodCLI EquivalentDescriptionExample
createRequest()sharokey create-requestCreate requestSharokey.createRequest({message: "Share credentials", secretExpirationHours: 24, requestExpirationHours: 48, maximumViews: 1, locale: "fr"})
listRequests()sharokey list-requestsList requestsSharokey.listRequests({status: 'active', limit: 10})
getRequest()sharokey get-requestGet request detailsSharokey.getRequest('abc123token456')
deleteRequest()sharokey delete-requestExpire request (cancels)Sharokey.deleteRequest('abc123token456')
requestStats()sharokey request-statsRequest statisticsSharokey.requestStats()

Parameters

Create Secret

ParameterDescriptionExample
contentSecret content (255 chars max)"Database password: admin123"
hoursExpiration hours (1-1000)24
viewsMaximum views (1-10)1
options.descriptionSecret description (255 chars max){description: "DB credentials"}
options.messageViewer message (255 chars max){message: "Use carefully"}
options.passwordAdditional protection (4-100 chars){password: "secret123"}
options.captchaEnable CAPTCHA verification{captcha: true}
options.otpEmailOTP via email (valid format){otpEmail: "[email protected]"}
options.otpPhoneOTP via SMS (international format){otpPhone: "+33674747474"}
options.ipWhitelistAllowed IPs (255 chars max){ipWhitelist: "203.0.113.5,198.51.100.10"}
options.geolocationAllowed countries (255 chars max){geolocation: "FR,US,DE"}
options.attachmentsFile array (10 files, 10MB max){attachments: [file1, file2]}

Security Priority

If multiple security options are specified, only the highest level is applied:
captcha < password < otpEmail < otpPhone (highest)

Example: {password: "secret", captcha: true, otpPhone: "+33123456789"} → Only OTP phone will be used

Configuration

ParameterDescriptionExample
tokenAPI token (required){token: 'abcd1234...'}
timeoutRequest timeout in milliseconds{timeout: 60000}

Output Format

All methods return JSON objects (same structure as CLI JSON output).

Examples

Basic Usage

javascript
// Simple secret
const secret = await Sharokey.create("Database password: admin123", 24, 1);
console.log('Share URL:', secret.share_url);


// With description and message
const secret2 = await Sharokey.create(
    "API credentials", 
    48, //Expiration hours
    3, //Maximum views
    {
        description: "Production API access",
        message: "Valid until project end"
    }
);


// CAPTCHA protection
const secret3 = await Sharokey.create(
    "Server access", 
    12, //Expiration hours
    1, //Maximum views
    {
        captcha: true
    }
);


// Password protection  
const secret4 = await Sharokey.create(
    "Sensitive data", 
    6, //Expiration hours
    2, //Maximum views
    {
        password: "mySecretPass123"
    }
);


// OTP email protection (higher priority than password)
const secret5 = await Sharokey.create(
    "Bank details", 
    24, //Expiration hours
    1, //Maximum views
    {
        password: "backup",
        otpEmail: "[email protected]"
    }
);


// OTP SMS protection (highest priority - will override all others)
const secret6 = await Sharokey.create(
    "Critical access", 
    2, //Expiration hours
    1, //Maximum views
    {
        password: "backup",
        captcha: true,
        otpEmail: "[email protected]",
        otpPhone: "+33674747474"
    }
);


// IP restriction
const secret7 = await Sharokey.create(
    "External access", 
    48, //Expiration hours
    10, //Maximum views
    {
        ipWhitelist: "203.0.113.5,198.51.100.10"
    }
);


// Geolocation restriction
const secret8 = await Sharokey.create(
    "EU only data", 
    72, //Expiration hours
    5, //Maximum views
    {
        geolocation: "FR,DE,BE,IT,ES"
    }
);


// Combined restrictions
const secret9 = await Sharokey.create(
    "Restricted access", 
    24, //Expiration hours
    2, //Maximum views
    {
        password: "secure123",
        ipWhitelist: "203.0.113.100",
        geolocation: "FR,US"
    }
);

File Attachments

html
<input type="file" id="fileInput" multiple>
<button onclick="shareWithFiles()">Share Secret</button>


<script>
async function shareWithFiles() {
    const files = Array.from(document.getElementById('fileInput').files);
    
    const secret = await Sharokey.create("Contract files", 48, 5, {
        description: "Client XYZ documents",
        attachments: files
    });
    
    console.log('Share URL with attachments:', secret.share_url);
}
</script>

Secret Requests

javascript
// Create request with email delivery (JSON output by default - direct API response)
const request = await Sharokey.createRequest({
    message: "Please share VPN credentials",
    emailTo: "[email protected]",
    emailReply: "[email protected]",
    requestExpirationHours: 48,
    secretExpirationHours: 24,
    maximumViews: 3,
    locale: "fr"
});
console.log('Request URL:', request.url);


// Get request details by token (JSON by default - direct API response)
const requestDetails = await Sharokey.getRequest('abc123token456');


// List requests with filters (JSON by default - direct API response)
const requests = await Sharokey.listRequests({
    status: 'active',
    limit: 20
});


// Expire request by token (cancels and makes it inactive)
await Sharokey.deleteRequest('abc123token456');


// View request statistics (JSON only - direct API response)
const stats = await Sharokey.requestStats();


// Request parameters: secretExpirationHours (1-1000), requestExpirationHours (1-1000), maximumViews (1-10)
// Email fields: emailTo and emailReply (valid email format required)
// Locale: "en" or "fr" - sets email language when sending notifications

Management

javascript
// List all secrets
const allSecrets = await Sharokey.list();


// List with filters
const filtered = await Sharokey.list({
    status: 'active',
    creator: '[email protected]',
    limit: 20
});


// JSON output (default)
const secrets = await Sharokey.list({limit: 5});
// Output: {"success": true, "count": 2, "secrets": [{"slug": "ABC123", "maximum_views": 1, ...}]}


// Get secret details
const secret = await Sharokey.get('ABC123');


// Expire secret (clears content, forces expiration)
await Sharokey.delete('ABC123');


// Statistics
const stats = await Sharokey.stats();

Limits & Constraints

Content & Text

  • Secret content: 255 characters max (before encryption)
  • Description: 255 characters max
  • Message: 255 characters max
  • Password: 4-100 characters
  • IP whitelist: 255 characters max (public IPs only, comma-separated)
  • Geolocation: 255 characters max (ISO country codes)

Attachments

  • Maximum files: 10 per secret
  • Total size: 10MB across all files
  • Supported formats: Documents, Images, Audio, Video, Archives
  • Encryption: Files encrypted client-side before upload

Time & Access

  • Expiration: 1-1000 hours
  • Maximum views: 1-10 views

Security

Zero Knowledge Architecture

  • Client-side encryption: AES-GCM-256 with PBKDF2 (10,000 iterations)
  • Split keys: KeyA (sent to server) + KeyB (in URL fragment)
  • No server access: Server cannot decrypt secrets
  • Perfect Forward Secrecy: Keys never stored server-side

Best Practices

  • Use short expiration times for sensitive data
  • Limit view counts appropriately
  • Choose appropriate security level: OTP phone (highest) > OTP email > password > CAPTCHA
  • Combine with IP restrictions and geo restrictions for access control
  • Only the highest security level will be applied if multiple are specified

Browser Requirements

  • Chrome: 60+
  • Firefox: 55+
  • Safari: 11+
  • Edge: 79+
  • Web Crypto API: Required for encryption

Utilities

Connectivity Test

javascript
// Simple test (boolean)
const isConnected = await Sharokey.testConnection();


// Detailed test (like CLI)
const results = await Sharokey.test();
console.log(`Tests: ${results.passed}/${results.total}`);
// Output: {config: true, network: true, auth: true, read: true, stats: true, total: 5, passed: 5, success: true}

Test Details:

  1. Config - Validates API token configuration
  2. Network - HTTP connectivity test (calls /health endpoint)
  3. Auth - Authentication verification via API
  4. Read - Secret listing permission test
  5. Stats - Statistics endpoint access test

Test Function Details

The test() function performs comprehensive client-side diagnostics including server health verification, authentication validation, and permission checks. This ensures full API functionality beyond basic connectivity.

Error Handling

javascript
try {
    const secret = await Sharokey.create('My secret', 24, 1);
    console.log('Success:', secret.share_url);
} catch (error) {
    console.error('Error:', error.message);
    
    // Common errors:
    // - "Token not configured" - Use Sharokey.config() first
    // - "Content is required" - Check parameters
    // - "Hours must be between 1 and 1000" - Invalid expiration
    // - "Invalid phone format" - Use +33674747474 format
    // - "Too many attachments" - Max 10 files, 10MB total
}

Browser Compatibility Check

javascript
// Check before initialization
if (!window.crypto || !window.crypto.subtle) {
    alert('Browser not supported. Please use Chrome 60+, Firefox 55+, Safari 11+, or Edge 79+');
} else {
    Sharokey.config({token: 'your-token'});
}

Quick Integration

Complete Example

html
<!DOCTYPE html>
<html>
<head>
    <title>Sharokey Integration</title>
    <script src="https://cdn.jsdelivr.net/gh/Sharokey/sharokey-cdn@latest/sharokey.js"></script>
</head>
<body>
    <form id="secretForm">
        <textarea id="content" placeholder="Secret content" required></textarea>
        <input type="number" id="hours" value="24" min="1" max="1000" placeholder="Hours">
        <input type="number" id="views" value="1" min="1" max="10" placeholder="Views">
        <input type="password" id="password" placeholder="Password (optional)">
        <input type="file" id="files" multiple>
        <button type="submit">Create Secret</button>
    </form>
    
    <div id="result"></div>


    <script>
        // Configure
        Sharokey.config({token: 'your_api_token_here'});


        // Handle form
        document.getElementById('secretForm').onsubmit = async (e) => {
            e.preventDefault();
            
            try {
                const options = {};
                const password = document.getElementById('password').value;
                const files = Array.from(document.getElementById('files').files);
                
                if (password) options.password = password;
                if (files.length) options.attachments = files;
                
                const secret = await Sharokey.create(
                    document.getElementById('content').value,
                    parseInt(document.getElementById('hours').value),
                    parseInt(document.getElementById('views').value),
                    options
                );
                
                document.getElementById('result').innerHTML = 
                    `<p>Secret created! <br><a href="${secret.share_url}" target="_blank">${secret.share_url}</a></p>`;
                    
                document.getElementById('secretForm').reset();
                
            } catch (error) {
                document.getElementById('result').innerHTML = 
                    `<p style="color:red">Error: ${error.message}</p>`;
            }
        };
    </script>
</body>
</html>

Troubleshooting

Common issues:

  • "Token not configured": Use Sharokey.config({token: 'TOKEN'}) first
  • "Web Crypto API not supported": Update browser (Chrome 60+, Firefox 55+, Safari 11+, Edge 79+)
  • "Content is required": Check secret content parameter
  • "Invalid phone format": Use international format (+33674747474)
  • "Too many attachments": Max 10 files, 10MB total
  • "IP whitelist error": Only public IP addresses supported

Released under the MIT License.