Skip to content

Python SDK Documentation ​

Zero Knowledge secret sharing - API consistent with CLI commands

πŸš€ Installation ​

⚠️ Important Note: This package is not yet available on PyPI. This documentation describes the future API based on existing implementation.

bash
# Not yet available
# pip install sharokey

⚑ Quick Start ​

python
import asyncio
import sharokey

async def main():
    # Configuration (equivalent: sharokey config --token xxx)
    client = sharokey.SharokeyClient('YOUR_API_KEY')
    
    # Create a secret (equivalent: sharokey create "secret" --hours 24 --views 1)
    secret = await client.create("My confidential secret", 24, 1)
    print(f"Share URL: {secret.share_url}")
    
    # List secrets (equivalent: sharokey list)
    secrets = await client.list()
    print(f"Total: {len(secrets.data)} secrets")

asyncio.run(main())

πŸ“š API - Consistent with CLI ​

Configuration ​

python
import sharokey

# Basic configuration
client = sharokey.SharokeyClient(
    token='YOUR_API_KEY',           # REQUIRED
    api_url="https://...",             # Optional (default: production)
    timeout=30                         # Optional (default: 30s)
)

Create a Secret ​

python
# Simple secret (equivalent: sharokey create "message" --hours 24 --views 1)
secret = await client.create("My secret password", 24, 1)
print(f"URL: {secret.share_url}")
print(f"Expires on: {secret.expiration}")

# With all options including security features
secret = await client.create(
    "Critical information",
    hours=2,
    views=3,
    description="Production server access",
    message="Use within 2 hours",
    password="additional-protection",
    otp_email="[email protected]",  # OTP via email
    captcha=True,                    # CAPTCHA verification
    ip_whitelist="192.168.1.0/24,10.0.0.1",  # IP restrictions
    geolocation="FR,US,CA"           # Country restrictions
)

# With SMS OTP (mutually exclusive with email OTP)
secret = await client.create(
    "Access code",
    hours=1,
    views=1,
    otp_phone="+33674747474"  # OTP via SMS
)

# With attachments and security restrictions
secret = await client.create(
    "Confidential documents",
    hours=48,
    views=5,
    description="Contract and annexes",
    attachments=["contract.pdf", "conditions.docx"],  # File paths
    password="protection2024",
    captcha=True,                    # CAPTCHA required
    ip_whitelist="192.168.1.0/24"   # Office network only
)

List Secrets ​

python
# List all (equivalent: sharokey list)
secrets = await client.list()
print(f"{len(secrets.data)} secrets found")

# With filters (equivalent: sharokey list --status active --limit 10)
secrets = await client.list(
    status='active',
    limit=10,
    creator='[email protected]',
    search='server'
)

# Browse results
for secret in secrets.data:
    remaining_views = secret.maximum_views - secret.current_views if secret.maximum_views else "unlimited"
    print(f"{secret.slug}: {secret.description} ({remaining_views} views remaining)")

Secret Details ​

python
# Get details (equivalent: sharokey get ABC123)
secret = await client.get("ABC123XYZ")

print(f"Description: {secret.description}")
print(f"Creator: {secret.creator}")
print(f"Views: {secret.current_views}/{secret.maximum_views}")
print(f"Expires on: {secret.expiration}")
print(f"Has attachments: {secret.has_attachments}")
print(f"Attachment count: {secret.attachments_count}")

# Security features (if available)
if hasattr(secret, 'captcha'):
    print(f"CAPTCHA enabled: {secret.captcha}")
if hasattr(secret, 'ip_whitelist'):
    print(f"IP whitelist: {secret.ip_whitelist}")
if hasattr(secret, 'geolocation'):
    print(f"Geolocation: {secret.geolocation}")

Delete Secret ​

python
# Delete (equivalent: sharokey delete ABC123)
success = await client.delete("ABC123XYZ")
if success:
    print("Secret deleted successfully")

Statistics ​

python
# Get stats (equivalent: sharokey stats)
stats = await client.stats()

print(f"Total secrets: {stats.total_secrets}")
print(f"Active secrets: {stats.active_secrets}")
print(f"Expired secrets: {stats.expired_secrets}")
print(f"Total views: {stats.total_views}")
print(f"Secrets with password: {stats.secrets_with_password}")
print(f"Created today: {stats.secrets_created_today}")
print(f"Created this week: {stats.secrets_created_this_week}")
print(f"Created this month: {stats.secrets_created_this_month}")

πŸ”§ Utility Functions ​

Generate Password ​

python
# Generate password (CLI equivalent: --generate-password)
password = client.generate_password(length=20)
print(f"Generated password: {password}")

# Generate and create secret in one go
password, secret = await client.create_password(
    length=16,
    hours=1,
    views=1,
    description="Auto-generated password"
)
print(f"Password: {password}")
print(f"Share URL: {secret.share_url}")

Test Connectivity ​

python
# Test API connection
connected = await client.test_connection()
if not connected:
    print("Unable to connect to Sharokey")

πŸ’‘ Practical Examples ​

Automation Script ​

python
#!/usr/bin/env python3
import asyncio
import sharokey
from pathlib import Path

async def deploy_credentials():
    """Deploy credentials securely."""
    
    client = sharokey.SharokeyClient('YOUR_API_KEY')
    
    # Create secret for deployment credentials with IP restrictions
    secret = await client.create(
        "DB_PASSWORD=super_secret_pwd",
        hours=1,  # Expires in 1 hour
        views=1,  # Single view
        description="Database credentials - deployment",
        otp_email="[email protected]",
        ip_whitelist="10.0.0.0/8,192.168.1.0/24",  # Internal networks only
        captcha=True  # Extra security
    )
    
    print(f"πŸ” Credentials created: {secret.share_url}")
    return secret.share_url

# Usage
if __name__ == "__main__":
    url = asyncio.run(deploy_credentials())
    print(f"Send this URL to the team: {url}")

Secure File Sharing ​

python
import asyncio
import sharokey
from pathlib import Path

async def share_files():
    """Share files securely."""
    
    client = sharokey.SharokeyClient('YOUR_API_KEY')
    
    # Files to share
    files = [
        "documents/contract.pdf",
        "documents/specifications.docx", 
        "documents/budget.xlsx"
    ]
    
    # Create secret with attachments and geographic restrictions
    secret = await client.create(
        "Client ABC folder - contractual documents",
        hours=72,  # 3 days
        views=10,  # 10 consultations max
        description="Contract documents ABC Corp",
        attachments=files,
        password="ContractABC2024",
        otp_email="[email protected]",
        geolocation="FR,US,CA,GB",  # Authorized countries only
        captcha=True  # CAPTCHA protection
    )
    
    print(f"πŸ“Ž Folder shared: {secret.share_url}")
    print(f"πŸ“„ {len(files)} files attached")
    print(f"πŸ”’ Protected by password, email OTP, and CAPTCHA")
    print(f"🌍 Accessible only from: FR, US, CA, GB")
    
    return secret

# Usage
asyncio.run(share_files())

Secret Requests ​

python
# Create a secret request (ask someone to share a secret with you)
request = await client.create_request(
    message="Please share the database credentials",
    description="Production DB access needed",
    secret_expiration_hours=24,  # Secret will expire in 24h
    request_expiration_hours=48, # Request expires in 48h
    maximum_views=1,             # Secret can be viewed once
    email_to="[email protected]",
    email_reply="[email protected]"
)

print(f"Request created: {request.url}")
print(f"Send this URL to recipient: {request.url}")

# List your secret requests
requests = await client.list_requests(status='active', limit=10)
print(f"Active requests: {len(requests.data)}")

for req in requests.data:
    print(f"Request {req.token}: {req.description}")
    print(f"  Status: {req.status}")
    print(f"  Expires: {req.request_expiration}")

# Get specific request details
request = await client.get_request(123)
print(f"Request: {request.message}")
print(f"Active: {request.is_active()}")

# Delete a request
success = await client.delete_request(123)
if success:
    print("Request deleted successfully")

# Get request statistics
stats = await client.request_stats()
print(f"Total requests: {stats.get('total_requests', 0)}")

Monitoring Dashboard ​

python
import asyncio
import sharokey

async def dashboard():
    """Simple secrets dashboard."""
    
    client = sharokey.SharokeyClient('YOUR_API_KEY')
    
    # Get statistics
    stats = await client.stats()
    
    print("πŸ“Š SHAROKEY DASHBOARD")
    print("=" * 40)
    print(f"Total secrets:     {stats.total_secrets:>8}")
    print(f"Active secrets:    {stats.active_secrets:>8}")
    print(f"Expired secrets:   {stats.expired_secrets:>8}")
    print(f"Total views:       {stats.total_views:>8}")
    print()
    
    # List recent secrets
    recent = await client.list(limit=5)
    print("πŸ” RECENT SECRETS")
    print("=" * 40)
    
    for secret in recent.data:
        status = "🟒 Active" if secret.current_views < (secret.maximum_views or 999999) else "πŸ”΄ Exhausted"
        print(f"{secret.slug} | {status} | {secret.description or 'No description'}")

# Run dashboard
asyncio.run(dashboard())

🚨 Error Handling ​

Common Errors ​

python
import sharokey

async def handle_errors():
    client = sharokey.SharokeyClient('YOUR_API_KEY')
    
    try:
        # Attempt creation with invalid parameters
        await client.create("", -1, 0)
        
    except sharokey.ValidationError as e:
        print(f"❌ Validation error: {e}")
        # Example: "Content is required and must be non-empty"
        
    except sharokey.AuthenticationError as e:
        print(f"❌ Authentication error: {e}")
        # Invalid or expired token
        
    except sharokey.NotFoundError as e:
        print(f"❌ Secret not found: {e}")
        # Secret doesn't exist or has expired
        
    except sharokey.AttachmentError as e:
        print(f"❌ File error: {e}")
        # File too large, not found, etc.
        
    except sharokey.NetworkError as e:
        print(f"❌ Network error: {e}")
        # Timeout, rate limiting, etc.
        
    except sharokey.SharokeyError as e:
        print(f"❌ General error: {e}")
        # All other API errors

Local Validation ​

python
# The SDK automatically validates:
# - Non-empty content
# - Hours between 1 and 1000 
# - Views between 1 and 1000
# - Token configured
# - Attachments: max 10 files, 10MB total
# - OTP: email and phone mutually exclusive

try:
    await client.create("", -1, 0)  # Multiple errors
except sharokey.ValidationError as e:
    print(e)  # "Content is required and must be non-empty"

# Attachment error
try:
    files = ["huge_file.zip"]  # > 10MB
    await client.create("test", 24, 1, attachments=files)
except sharokey.AttachmentError as e:
    print(e)  # "Total attachments size too large: 25.3MB. Maximum 10MB allowed"

πŸ” Security ​

Zero Knowledge Encryption ​

  • Algorithms: AES-GCM-256 + PBKDF2 (10,000 iterations)
  • Client-side encryption: Your secrets never leave your machine in plaintext
  • Dual key: keyA (server) + keyB (URL fragment)
  • Full compatibility: Secrets created by Python can be decrypted everywhere (CLI, web, etc.)
  • Zero Knowledge: Server cannot decrypt your content

Advanced Security Features ​

CAPTCHA Protection ​

python
# Enable CAPTCHA verification for extra security
secret = await client.create(
    "Sensitive data",
    hours=2,
    views=1,
    captcha=True,  # Requires CAPTCHA solving
    description="CAPTCHA protected secret"
)

IP Whitelist Restrictions ​

python
# Restrict access to specific IP addresses or ranges
secret = await client.create(
    "Internal documentation",
    hours=24,
    views=5,
    ip_whitelist="192.168.1.100,10.0.0.0/24,203.0.113.5",  # CIDR and specific IPs
    description="Office network access only"
)

Geolocation Restrictions ​

python
# Restrict access to specific countries (ISO country codes)
secret = await client.create(
    "Regional data",
    hours=12,
    views=3,
    geolocation="FR,DE,BE,NL,IT,ES",  # European Union countries (max 255 chars)
    description="EU-only access"
)

Combined Security (Maximum Protection) ​

python
# Use all security features together
secret = await client.create(
    "Top secret information",
    hours=1,
    views=1,
    description="Maximum security secret",
    message="Handle with extreme care",
    password="extra-secure-password",
    captcha=True,                     # CAPTCHA verification
    ip_whitelist="192.168.1.0/24",   # Internal network only
    geolocation="FR,US",              # Specific countries
    otp_email="[email protected]"  # Email OTP
)

Security Best Practices ​

python
# βœ… Recommended - Maximum security
secret = await client.create(
    "super-secret-password", 
    hours=1,        # Short duration
    views=1,        # Single view
    password="additional-protection",
    otp_email="[email protected]",
    captcha=True,   # CAPTCHA verification
    ip_whitelist="192.168.1.0/24",  # Restrict to office network
    geolocation="FR,US"  # Restrict to specific countries
)

# ❌ To avoid - Weak security
secret = await client.create(
    "super-secret-password",
    hours=1000,     # Too long
    views=10        # Too many possible views
    # No additional security measures
)

Security Features Summary ​

FeatureParameterDescriptionExample
CAPTCHAcaptcha=TrueRequires CAPTCHA verificationcaptcha=True
IP Whitelistip_whitelistComma-separated IPs/CIDR"192.168.1.0/24,10.0.0.1"
GeolocationgeolocationComma-separated country codes"FR,US,CA,DE"
PasswordpasswordAdditional password protection"secure-password"
OTP Emailotp_emailEmail for OTP verification"[email protected]"
OTP SMSotp_phonePhone for SMS OTP"+33674747474"
MessagemessageCustom message for recipient"Handle with care"

πŸ†š Comparison with CLI ​

FeatureCLI C#Python SDK
Configurationsharokey config --token xxxSharokeyClient('YOUR_API_KEY')
Creationsharokey create "secret" --hours 24client.create("secret", 24, 1)
Listsharokey list --limit 10client.list(limit=10)
Detailssharokey get ABC123client.get('ABC123')
Deletionsharokey delete ABC123client.delete('ABC123')
Statssharokey statsclient.stats()
Attachments--attach file1 --attach file2attachments=['file1', 'file2']
Email OTP--otp-email [email protected]otp_email='[email protected]'
SMS OTP--otp-phone +33123456789otp_phone='+33123456789'
CAPTCHA--captchacaptcha=True
IP Whitelist--ip-whitelist "IPs"ip_whitelist="192.168.1.0/24"
Geolocation--geolocation "FR,US"geolocation="FR,US,CA"
Encryptionβœ… Zero Knowledgeβœ… Identical

πŸ“¦ Development Installation ​

⚠️ Not yet available

bash
# Repository not yet created
# git clone https://github.com/sharokey/python-sdk.git
# cd python-sdk

# Install in development mode
# pip install -e .[dev]

# Run tests
# pytest

# Linting
# black sharokey/
# isort sharokey/
# mypy sharokey/

πŸ› Support ​

⚑ Ready to Use! ​

Your Sharokey Python SDK is ready!

  1. βœ… Install: pip install sharokey
  2. βœ… Configure: client = SharokeyClient('YOUR_API_KEY')
  3. βœ… Use: API consistent with CLI!

Python SDK 1.0.0 - Compatible with Sharokey API

Released under the MIT License.