#!/usr/bin/env python3
"""Ephemer.pw — reference client for the public API (v1), in Python.

Encrypts a secret locally, stores only the ciphertext on Ephemer and prints a
self-destructing link. The decryption key never leaves this machine except
inside the link you share (after the #).

Requirements: Python 3.10+, `pip install cryptography argon2-cffi`
(argon2-cffi is only used with a passphrase).

Usage:
    python ephemer.py --views 3 --expires 7d < secret.txt
    EPHEMER_PASSPHRASE="…" python ephemer.py --passphrase < secret.txt

Protocol: https://ephemer.pw/developers  ·  License: MIT
"""

import argparse
import base64
import json
import os
import sys
import urllib.error
import urllib.request

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

EXPIRY_OPTIONS = ["5m", "30m", "1h", "12h", "24h", "3d", "7d"]
MAX_PLAINTEXT_BYTES = 64 * 1024
ID_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def hkdf(ikm: bytes, salt: bytes, info: str) -> bytes:
    return HKDF(
        algorithm=hashes.SHA256(), length=32, salt=salt, info=info.encode()
    ).derive(ikm)


def encrypt_secret(text: str, passphrase: str | None = None):
    """Returns (id, fragment, payload). Never send the fragment to the API."""
    plaintext = text.encode()
    if not plaintext:
        raise ValueError("The secret is empty")
    if len(plaintext) > MAX_PLAINTEXT_BYTES:
        raise ValueError(f"The secret exceeds {MAX_PLAINTEXT_BYTES} bytes")

    # 16 chars over a 64-symbol alphabet (96 bits); 256 % 64 == 0: unbiased.
    secret_id = "".join(ID_ALPHABET[b & 63] for b in os.urandom(16))
    salt, url_key, iv = os.urandom(16), os.urandom(32), os.urandom(12)

    # ikm = Argon2id(passphrase, salt) || urlKey  — or urlKey alone
    ikm = url_key
    if passphrase:
        from argon2.low_level import Type, hash_secret_raw

        pass_key = hash_secret_raw(
            passphrase.encode(), salt,
            time_cost=2, memory_cost=19456, parallelism=1,
            hash_len=32, type=Type.ID,
        )
        ikm = pass_key + url_key

    content_key = hkdf(ikm, salt, "ephemer:v1:content")
    # The id is bound as additional authenticated data; the tag is appended.
    ciphertext = AESGCM(content_key).encrypt(iv, plaintext, secret_id.encode())
    auth_token = b64url(hkdf(ikm, salt, "ephemer:v1:auth")) if passphrase else None

    payload = {
        "id": secret_id,
        "ciphertext": b64url(ciphertext),
        "iv": b64url(iv),
        "salt": b64url(salt),
        "authToken": auth_token,
    }
    return secret_id, b64url(url_key), payload


def create_secret(text, views=1, expires_in="24h", passphrase=None,
                  api="https://ephemer.pw"):
    """Encrypts and stores a secret. Returns (url, response body)."""
    if expires_in not in EXPIRY_OPTIONS:
        raise ValueError(f"expires_in must be one of {', '.join(EXPIRY_OPTIONS)}")
    secret_id, fragment, payload = encrypt_secret(text, passphrase)

    request = urllib.request.Request(
        f"{api}/api/v1/secrets",
        data=json.dumps({**payload, "views": views, "expiresIn": expires_in}).encode(),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request) as response:
            body = json.load(response)
    except urllib.error.HTTPError as error:
        detail = json.loads(error.read() or b"{}").get("error", "unknown_error")
        raise RuntimeError(f"HTTP {error.code}: {detail}") from None

    return f"{api}/s/{secret_id}#{fragment}", body


def main():
    parser = argparse.ArgumentParser(description="Create an Ephemer.pw secret link")
    parser.add_argument("secret", nargs="?", help="prefer stdin (shell history!)")
    parser.add_argument("--views", type=int, default=1)
    parser.add_argument("--expires", default="24h", choices=EXPIRY_OPTIONS)
    parser.add_argument("--passphrase", action="store_true",
                        help="read the passphrase from EPHEMER_PASSPHRASE")
    parser.add_argument("--api", default="https://ephemer.pw")
    args = parser.parse_args()

    passphrase = os.environ.get("EPHEMER_PASSPHRASE") if args.passphrase else None
    if args.passphrase and not passphrase:
        sys.exit("ephemer: set EPHEMER_PASSPHRASE")

    text = args.secret if args.secret is not None else sys.stdin.read()
    url, body = create_secret(text, args.views, args.expires, passphrase,
                              args.api.rstrip("/"))
    print(url)
    print(f"views: {body['viewsLeft']} · expires: {body['expiresAt']}", file=sys.stderr)


if __name__ == "__main__":
    main()
