// Ephemer.pw — reference client for the public API (v1), in Java.
//
// 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: Java 17+. No dependency, except for --passphrase, which needs
// BouncyCastle (Argon2id) on the classpath: org.bouncycastle:bcprov-jdk18on
//
// Run directly (no build step):
//   java Ephemer.java --views 3 --expires 7d < secret.txt
//   EPHEMER_PASSPHRASE="…" java -cp bcprov-jdk18on.jar Ephemer.java --passphrase < secret.txt
//
// Use as a library: copy this file into your project (add a package line if
// needed) and call Ephemer.createSecret(...).
//
// Protocol: https://ephemer.pw/developers  ·  License: MIT

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class Ephemer {

    public static final List<String> EXPIRY_OPTIONS =
            List.of("5m", "30m", "1h", "12h", "24h", "3d", "7d");
    public static final int MAX_PLAINTEXT_BYTES = 64 * 1024;

    private static final String ID_ALPHABET =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
    private static final SecureRandom RANDOM = new SecureRandom();
    // HTTP/1.1: the default HTTP/2 client tries a cleartext "h2c" upgrade on
    // http:// URLs, which Node servers and many proxies reject.
    private static final HttpClient HTTP =
            HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();

    private Ephemer() {}

    /** The JSON body of POST /api/v1/secrets, without views/expiresIn. */
    public record Payload(String id, String ciphertext, String iv, String salt, String authToken) {}

    /** Never send {@code fragment} to the API: it is the key. */
    public record EncryptedSecret(String id, String fragment, Payload payload) {}

    public record SharedSecret(String url, String expiresAt, int viewsLeft) {}

    // -----------------------------------------------------------------------
    // Library
    // -----------------------------------------------------------------------

    /** Encrypts and stores a secret, returns the link to share. */
    public static SharedSecret createSecret(
            String text, int views, String expiresIn, String passphrase, String api)
            throws IOException, InterruptedException, GeneralSecurityException {
        if (!EXPIRY_OPTIONS.contains(expiresIn)) {
            throw new IllegalArgumentException("expiresIn must be one of " + EXPIRY_OPTIONS);
        }
        EncryptedSecret secret = encryptSecret(text, passphrase);
        Payload p = secret.payload();

        // Every value is base64url or a fixed token: no JSON escaping needed.
        String body = "{\"id\":\"" + p.id() + "\",\"ciphertext\":\"" + p.ciphertext()
                + "\",\"iv\":\"" + p.iv() + "\",\"salt\":\"" + p.salt()
                + "\",\"authToken\":" + (p.authToken() == null ? "null" : "\"" + p.authToken() + "\"")
                + ",\"views\":" + views + ",\"expiresIn\":\"" + expiresIn + "\"}";

        HttpRequest request = HttpRequest.newBuilder(URI.create(api + "/api/v1/secrets"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() / 100 != 2) {
            String code = jsonString(response.body(), "error");
            throw new IOException("HTTP " + response.statusCode() + ": "
                    + (code == null ? "unknown_error" : code));
        }
        return new SharedSecret(
                api + "/s/" + secret.id() + "#" + secret.fragment(),
                jsonString(response.body(), "expiresAt"),
                Integer.parseInt(jsonNumber(response.body(), "viewsLeft")));
    }

    /** Same as {@link #createSecret} with defaults: 1 view, 24h, no passphrase. */
    public static SharedSecret createSecret(String text)
            throws IOException, InterruptedException, GeneralSecurityException {
        return createSecret(text, 1, "24h", null, "https://ephemer.pw");
    }

    /** Encrypts locally. Nothing is sent anywhere. */
    public static EncryptedSecret encryptSecret(String text, String passphrase)
            throws GeneralSecurityException {
        byte[] plaintext = text.getBytes(StandardCharsets.UTF_8);
        if (plaintext.length == 0) throw new IllegalArgumentException("The secret is empty");
        if (plaintext.length > MAX_PLAINTEXT_BYTES) {
            throw new IllegalArgumentException("The secret exceeds " + MAX_PLAINTEXT_BYTES + " bytes");
        }

        // 16 characters over a 64-symbol alphabet (96 bits); 256 % 64 == 0: unbiased.
        StringBuilder id = new StringBuilder(16);
        for (byte b : randomBytes(16)) id.append(ID_ALPHABET.charAt(b & 63));
        byte[] salt = randomBytes(16);
        byte[] urlKey = randomBytes(32);
        byte[] iv = randomBytes(12);

        // ikm = Argon2id(passphrase, salt) || urlKey  — or urlKey alone
        boolean usesPassphrase = passphrase != null && !passphrase.isEmpty();
        byte[] ikm = usesPassphrase ? concat(argon2id(passphrase, salt), urlKey) : urlKey;

        byte[] contentKey = hkdfSha256(ikm, salt, "ephemer:v1:content");
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(contentKey, "AES"),
                new GCMParameterSpec(128, iv));
        // The id is bound as additional authenticated data; the tag is appended.
        cipher.updateAAD(id.toString().getBytes(StandardCharsets.UTF_8));
        byte[] ciphertext = cipher.doFinal(plaintext);

        String authToken = usesPassphrase
                ? base64Url(hkdfSha256(ikm, salt, "ephemer:v1:auth"))
                : null;

        return new EncryptedSecret(id.toString(), base64Url(urlKey), new Payload(
                id.toString(), base64Url(ciphertext), base64Url(iv), base64Url(salt), authToken));
    }

    // -----------------------------------------------------------------------
    // Primitives
    // -----------------------------------------------------------------------

    /** HKDF-SHA-256 (RFC 5869), 32-byte output: one expand block. */
    static byte[] hkdfSha256(byte[] ikm, byte[] salt, String info) throws GeneralSecurityException {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(salt, "HmacSHA256"));
        byte[] prk = mac.doFinal(ikm);
        mac.init(new SecretKeySpec(prk, "HmacSHA256"));
        mac.update(info.getBytes(StandardCharsets.UTF_8));
        mac.update((byte) 1);
        return mac.doFinal();
    }

    /**
     * Argon2id(t=2, m=19456 KiB, p=1, 32 bytes) through BouncyCastle, loaded by
     * reflection so the client has no dependency unless a passphrase is used.
     */
    static byte[] argon2id(String passphrase, byte[] salt) throws GeneralSecurityException {
        try {
            Class<?> params = Class.forName("org.bouncycastle.crypto.params.Argon2Parameters");
            Class<?> builderClass = Class.forName("org.bouncycastle.crypto.params.Argon2Parameters$Builder");
            Object builder = builderClass.getConstructor(int.class)
                    .newInstance(params.getField("ARGON2_id").getInt(null));
            builderClass.getMethod("withVersion", int.class)
                    .invoke(builder, params.getField("ARGON2_VERSION_13").getInt(null));
            builderClass.getMethod("withIterations", int.class).invoke(builder, 2);
            builderClass.getMethod("withMemoryAsKB", int.class).invoke(builder, 19456);
            builderClass.getMethod("withParallelism", int.class).invoke(builder, 1);
            builderClass.getMethod("withSalt", byte[].class).invoke(builder, (Object) salt);
            Object built = builderClass.getMethod("build").invoke(builder);

            Class<?> generatorClass = Class.forName("org.bouncycastle.crypto.generators.Argon2BytesGenerator");
            Object generator = generatorClass.getConstructor().newInstance();
            generatorClass.getMethod("init", params).invoke(generator, built);
            byte[] out = new byte[32];
            generatorClass.getMethod("generateBytes", byte[].class, byte[].class)
                    .invoke(generator, passphrase.getBytes(StandardCharsets.UTF_8), out);
            return out;
        } catch (ClassNotFoundException e) {
            throw new GeneralSecurityException(
                    "--passphrase requires BouncyCastle on the classpath (org.bouncycastle:bcprov-jdk18on)");
        } catch (ReflectiveOperationException e) {
            throw new GeneralSecurityException("Argon2id failed", e);
        }
    }

    private static byte[] randomBytes(int length) {
        byte[] bytes = new byte[length];
        RANDOM.nextBytes(bytes);
        return bytes;
    }

    private static byte[] concat(byte[] a, byte[] b) {
        byte[] out = new byte[a.length + b.length];
        System.arraycopy(a, 0, out, 0, a.length);
        System.arraycopy(b, 0, out, a.length, b.length);
        return out;
    }

    private static String base64Url(byte[] bytes) {
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }

    /** Minimal readers for the API's flat JSON responses. */
    private static String jsonString(String json, String key) {
        Matcher m = Pattern.compile("\"" + key + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json);
        return m.find() ? m.group(1) : null;
    }

    private static String jsonNumber(String json, String key) {
        Matcher m = Pattern.compile("\"" + key + "\"\\s*:\\s*(\\d+)").matcher(json);
        return m.find() ? m.group(1) : "0";
    }

    // -----------------------------------------------------------------------
    // Command line
    // -----------------------------------------------------------------------

    public static void main(String[] args) {
        int views = 1;
        String expiresIn = "24h";
        String api = "https://ephemer.pw";
        String passphrase = null;
        List<String> positional = new ArrayList<>();

        try {
            for (int i = 0; i < args.length; i++) {
                switch (args[i]) {
                    case "--views" -> views = Integer.parseInt(args[++i]);
                    case "--expires" -> expiresIn = args[++i];
                    case "--api" -> api = args[++i].replaceAll("/+$", "");
                    case "--passphrase" -> {
                        passphrase = System.getenv("EPHEMER_PASSPHRASE");
                        if (passphrase == null || passphrase.isEmpty()) {
                            throw new IllegalArgumentException("set EPHEMER_PASSPHRASE");
                        }
                    }
                    default -> positional.add(args[i]);
                }
            }

            // Prefer stdin: a secret typed as an argument ends up in shell history.
            // (System.console() cannot detect a pipe reliably since Java 22.)
            String text = !positional.isEmpty()
                    ? String.join(" ", positional)
                    : new String(System.in.readAllBytes(), StandardCharsets.UTF_8);

            SharedSecret result = createSecret(text, views, expiresIn, passphrase, api);
            System.out.println(result.url());
            System.err.println("views: " + result.viewsLeft() + ", expires: " + result.expiresAt());
        } catch (Exception e) {
            System.err.println("ephemer: " + e.getMessage());
            System.exit(1);
        }
    }
}
