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 errorsLocal 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 β
| Feature | Parameter | Description | Example |
|---|---|---|---|
| CAPTCHA | captcha=True | Requires CAPTCHA verification | captcha=True |
| IP Whitelist | ip_whitelist | Comma-separated IPs/CIDR | "192.168.1.0/24,10.0.0.1" |
| Geolocation | geolocation | Comma-separated country codes | "FR,US,CA,DE" |
| Password | password | Additional password protection | "secure-password" |
| OTP Email | otp_email | Email for OTP verification | "[email protected]" |
| OTP SMS | otp_phone | Phone for SMS OTP | "+33674747474" |
| Message | message | Custom message for recipient | "Handle with care" |
π Comparison with CLI β
| Feature | CLI C# | Python SDK |
|---|---|---|
| Configuration | sharokey config --token xxx | SharokeyClient('YOUR_API_KEY') |
| Creation | sharokey create "secret" --hours 24 | client.create("secret", 24, 1) |
| List | sharokey list --limit 10 | client.list(limit=10) |
| Details | sharokey get ABC123 | client.get('ABC123') |
| Deletion | sharokey delete ABC123 | client.delete('ABC123') |
| Stats | sharokey stats | client.stats() |
| Attachments | --attach file1 --attach file2 | attachments=['file1', 'file2'] |
| Email OTP | --otp-email [email protected] | otp_email='[email protected]' |
| SMS OTP | --otp-phone +33123456789 | otp_phone='+33123456789' |
| CAPTCHA | --captcha | captcha=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 β
- GitHub Issues: https://github.com/sharokey/python-sdk/issues
- Documentation: https://docs.sharokey.com/python
- Examples: examples/
β‘ Ready to Use! β
Your Sharokey Python SDK is ready!
- β
Install:
pip install sharokey - β
Configure:
client = SharokeyClient('YOUR_API_KEY') - β Use: API consistent with CLI!
Python SDK 1.0.0 - Compatible with Sharokey API
