JavaScript SDK
Sharokey JavaScript SDK for secure secret sharing with Zero Knowledge encryption. NPM package with TypeScript support and Node.js/Browser compatibility.
Installation
# Install via NPM
npm install Sharokey/sharokey-js
# Configure and test
import Sharokey from 'sharokey-js';
Sharokey.config({token: 'your_api_token_here'});
await Sharokey.test();
Commands
Method | CLI Equivalent | Description | Example |
---|---|---|---|
config() | sharokey config | Configure token | Sharokey.config({token: 'TOKEN'}) |
create() | sharokey create | Create secret | Sharokey.create("password", 24, 1) |
list() | sharokey list | List secrets | Sharokey.list({limit: 10, status: 'active'}) |
get() | sharokey get | Get secret details | Sharokey.get('ABC123') |
delete() | sharokey delete | Expire secret (clears content) | Sharokey.delete('ABC123') |
stats() | sharokey stats | Show statistics | Sharokey.stats() |
test() | sharokey test | Test connectivity | Sharokey.test() |
Secret Requests
Method | CLI Equivalent | Description | Example |
---|---|---|---|
createRequest() | sharokey create-request | Create request | Sharokey.createRequest({secretExpirationHours: 24, requestExpirationHours: 48, maximumViews: 1}) |
listRequests() | sharokey list-requests | List requests | Sharokey.listRequests({status: 'active', limit: 10}) |
getRequest() | sharokey get-request | Get request details | Sharokey.getRequest('abc123token456') |
deleteRequest() | sharokey delete-request | Expire request (cancels) | Sharokey.deleteRequest('abc123token456') |
requestStats() | sharokey request-stats | Request statistics | Sharokey.requestStats() |
Parameters
Create Secret
Parameter | Description | Example |
---|---|---|
content | Secret content (255 chars max) | "Database password: admin123" |
hours | Expiration hours (1-8760) | 24 |
views | Maximum views (1-100) | 1 |
options.description | Secret description (255 chars max) | {description: "DB credentials"} |
options.message | Viewer message (255 chars max) | {message: "Use carefully"} |
options.password | Additional protection (4-100 chars) | {password: "secret123"} |
options.captcha | Enable CAPTCHA verification | {captcha: true} |
options.otpEmail | OTP via email (valid format) | {otpEmail: "[email protected]"} |
options.otpPhone | OTP via SMS (international format) | {otpPhone: "+33674747474"} |
options.ipWhitelist | Allowed IPs (255 chars max) | {ipWhitelist: "203.0.113.5,198.51.100.10"} |
options.geolocation | Allowed countries (255 chars max) | {geolocation: "FR,US,DE"} |
options.attachments | File 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
Parameter | Description | Example |
---|---|---|
token | API token (required) | {token: 'abcd1234...'} |
timeout | Request timeout in milliseconds | {timeout: 60000} |
debug | Enable debug logging | {debug: true} |
Usage Types
Import Type | Usage | Example |
---|---|---|
ES Modules | Modern JavaScript/TypeScript | import Sharokey from 'sharokey-js'; |
CommonJS | Node.js require | const Sharokey = require('sharokey-js'); |
TypeScript | With full type support | import Sharokey, { type Secret } from 'sharokey-js'; |
Examples
Basic Usage
// ES Module
import Sharokey from 'sharokey-js';
Sharokey.config({token: 'your-token'});
// Simple secret
const secret = await Sharokey.create("Database password: admin123", 24, 1);
console.log('Share URL:', secret.share_url);
// With security options
const protectedSecret = await Sharokey.create("Sensitive data", 12, 1, {
description: "Production credentials",
password: "extraSecurity123",
otpEmail: "[email protected]"
});
Node.js Server
// server.js
const Sharokey = require('sharokey-js');
const express = require('express');
Sharokey.config({token: process.env.SHAROKEY_TOKEN});
const app = express();
app.use(express.json());
app.post('/create-secret', async (req, res) => {
try {
const secret = await Sharokey.create(req.body.content, 24, 1, {
description: `Created by ${req.user.email}`,
ipWhitelist: req.ip
});
res.json({shareUrl: secret.share_url});
} catch (error) {
res.status(500).json({error: error.message});
}
});
TypeScript Usage
import Sharokey, { type Secret, type SharokeyConfig } from 'sharokey-js';
const config: SharokeyConfig = {
token: process.env.SHAROKEY_TOKEN!,
timeout: 15000,
debug: true
};
Sharokey.config(config);
const secret: Secret = await Sharokey.create('TypeScript secret', 24, 1, {
description: 'Fully typed secret creation'
});
File Attachments
// Browser file upload
const fileInput = document.getElementById('fileInput');
const files = Array.from(fileInput.files);
const secret = await Sharokey.create('Project files', 48, 5, {
description: 'Shared project documents',
attachments: files
});
// Node.js file handling
const fs = require('fs').promises;
const fileData = await fs.readFile('document.pdf');
const fileObject = {
name: 'document.pdf',
arrayBuffer: () => Promise.resolve(fileData.buffer),
size: fileData.length
};
const secret = await Sharokey.create('Document', 24, 1, {
attachments: [fileObject]
});
Advanced Filtering
// List active secrets with filtering
const activeSecrets = await Sharokey.list({
status: 'active',
limit: 20,
creator: '[email protected]'
});
// Search functionality
const searchResults = await Sharokey.search('database credentials', {
limit: 10,
status: 'active'
});
// Get only active secrets
const onlyActive = await Sharokey.getActiveSecrets({limit: 50});
Secret Requests
// Create a secret request
const request = await Sharokey.createRequest({
secretExpirationHours: 24,
requestExpirationHours: 72,
maximumViews: 1,
message: "Please share the API credentials securely",
emailTo: "[email protected]",
locale: "en"
});
console.log('Request URL:', request.url);
console.log('Request token:', request.token);
// Manage requests
const requests = await Sharokey.listRequests({status: 'active'});
const requestDetails = await Sharokey.getRequest('token-here');
await Sharokey.deleteRequest('token-here');
React Integration
import { useState, useEffect } from 'react';
import Sharokey, { type Secret } from 'sharokey-js';
export function useSecrets() {
const [secrets, setSecrets] = useState<Secret[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
Sharokey.config({token: process.env.REACT_APP_SHAROKEY_TOKEN!});
}, []);
const createSecret = async (content: string) => {
setLoading(true);
try {
const secret = await Sharokey.create(content, 24, 1);
setSecrets(prev => [secret, ...prev]);
return secret.share_url;
} finally {
setLoading(false);
}
};
return {secrets, loading, createSecret};
}
Test & Diagnostics
The SDK provides comprehensive testing tools to verify connectivity and diagnose issues:
// Comprehensive diagnostics (6 checks)
const results = await Sharokey.test();
console.log(`Tests passed: ${results.passed}/${results.total}`);
console.log('Details:', results.details);
// Simple boolean check
const isConnected = await Sharokey.testConnection();
console.log('Connected:', isConnected);
// Get SDK information
const info = Sharokey.getInfo();
console.log('SDK version:', info.version);
console.log('Features:', info.features);
Test Process:
- ✅ Configuration: Verifies API token is present
- ✅ Network: Tests server connectivity via health endpoint
- ✅ Authentication: Validates token with API
- ✅ Read Access: Tests secrets listing permissions
- ✅ Write Access: Verifies secret creation capabilities
- ✅ Statistics: Tests analytics endpoint access
Unlike the simple health endpoint, test()
provides comprehensive client-side diagnostics including token validation, permissions, and feature availability.
Utility Methods
// Get current configuration (without token)
const config = Sharokey.getConfig();
console.log('API URL:', config.apiUrl);
console.log('Has token:', config.hasToken);
// Statistics and analytics
const stats = await Sharokey.stats();
console.log('Total secrets:', stats.data.total_secrets);
console.log('Active secrets:', stats.data.active_secrets);
// Environment-specific features
if (typeof window !== 'undefined') {
// Browser-specific code
console.log('Running in browser');
} else {
// Node.js-specific code
console.log('Running in Node.js');
}
Error Handling
try {
const secret = await Sharokey.create('test', 24, 1);
} catch (error) {
if (error.message.includes('Token not configured')) {
console.error('Configure your API token first');
} else if (error.message.includes('timeout')) {
console.error('Request timeout - check connection');
} else {
console.error('Error:', error.message);
}
}
// Validation errors
try {
await Sharokey.create('', 24, 1); // Empty content
} catch (error) {
// Error: Content is required and must be a non-empty string
}
try {
await Sharokey.create('test', 9000, 1); // Invalid hours
} catch (error) {
// Error: Hours must be between 1 and 8760
}
Related Resources
- CLI Documentation - Command-line interface reference
- JavaScript CDN - Lightweight browser-only version
- Python SDK - Python library for server-side applications
- Zero Knowledge Security - Understanding our security model
Troubleshooting
Common issues:
- "Token not configured": Use
Sharokey.config({token: 'TOKEN'})
first - "Web Crypto API not supported": Update to Node.js 16+ or modern browser
- Import errors: Check ES Module vs CommonJS usage
- File attachment failures: Ensure files have
name
,size
, andarrayBuffer()
method
Sharokey provides the best JavaScript SDK for secure secret sharing with comprehensive TypeScript support and Zero Knowledge encryption. 🔐