mailkite 0.13.0

Official MailKite SDK for Rust — inbound email → webhook, sending, templates, broadcasts, at-rest encryption, and webhook signature verification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
// The official MailKite SDK for Rust.
//
// Shape shared by every MailKite SDK: one low-level `request` plus one thin
// method per API endpoint (see `methods.rs`, generated from the shared spec).
// Bodies and responses are plain `serde_json::Value`. On top of the HTTP surface
// the SDK also ships purely-local helpers — webhook signature verification, the
// canonical reply bodies, and hybrid RSA/AES at-rest encryption that is
// byte-compatible with the other MailKite SDKs and MailKite's own WebCrypto.
//
// ```no_run
// let mk = mailkite::Client::new(std::env::var("MAILKITE_API_KEY").unwrap());
// let res = mk.send(serde_json::json!({
//     "from": "hello@app.mailkite.dev",
//     "to": "ada@example.com",
//     "subject": "Hi",
//     "text": "It works.",
// }))?;
// # Ok::<(), mailkite::Error>(())
// ```

mod methods;

use std::sync::Arc;

use aes_gcm::{
    aead::{Aead, KeyInit},
    Aes256Gcm, Key, Nonce,
};
use base64::{engine::general_purpose::STANDARD, Engine};
use hmac::{Hmac, Mac};
use rand::{rngs::OsRng, RngCore};
use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey};
use rsa::{Oaep, RsaPrivateKey, RsaPublicKey};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};

/// The production API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.mailkite.dev";

/// Reject webhook events older than this (ms) to block replays. Pass 0 to
/// [`verify_webhook_with_tolerance`] to disable the freshness check.
pub const DEFAULT_TOLERANCE_MS: i64 = 5 * 60 * 1000;

type HmacSha256 = Hmac<Sha256>;

// --- Error -------------------------------------------------------------------

/// Returned for any non-2xx response (or a local failure). `status` is the HTTP
/// status code (0 for a transport/local error), `message` is the API's `error`
/// field when present, and `body` is the parsed response body when there was one.
#[derive(Debug, Clone)]
pub struct Error {
    pub status: u16,
    pub message: String,
    pub body: Option<Value>,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for Error {}

fn local_err(message: impl Into<String>) -> Error {
    Error { status: 0, message: message.into(), body: None }
}

// --- Client ------------------------------------------------------------------

type TokenProvider = Arc<dyn Fn() -> Result<String, Error> + Send + Sync>;

/// Talks to the MailKite API.
///
/// The credential is always a Bearer token — an API key (`mk_live_…`) OR an
/// OAuth access token. Use [`Client::new_with_token`] with a callback when you
/// hold short-lived OAuth access tokens so the SDK always sends a fresh one.
#[derive(Clone)]
pub struct Client {
    token: String,
    token_provider: Option<TokenProvider>,
    base_url: String,
}

impl Client {
    /// A client for the production API. `token` is a Bearer credential — an API
    /// key (`mk_live_…`) or an OAuth access token.
    pub fn new(token: impl Into<String>) -> Client {
        Client {
            token: token.into(),
            token_provider: None,
            base_url: DEFAULT_BASE_URL.to_string(),
        }
    }

    /// A client pointed at a custom base URL.
    pub fn new_with_base_url(token: impl Into<String>, base_url: impl Into<String>) -> Client {
        Client {
            token: token.into(),
            token_provider: None,
            base_url: base_url.into().trim_end_matches('/').to_string(),
        }
    }

    /// A client that calls `get_token` before each request to obtain a fresh
    /// Bearer token — use it with short-lived OAuth access tokens so the SDK
    /// always sends a valid one.
    pub fn new_with_token<F>(get_token: F) -> Client
    where
        F: Fn() -> Result<String, Error> + Send + Sync + 'static,
    {
        Client {
            token: String::new(),
            token_provider: Some(Arc::new(get_token)),
            base_url: DEFAULT_BASE_URL.to_string(),
        }
    }

    /// Resolve the Bearer token for one request: from the token provider if set,
    /// else the static token.
    fn resolve_token(&self) -> Result<String, Error> {
        match &self.token_provider {
            Some(p) => p(),
            None => Ok(self.token.clone()),
        }
    }

    /// The low-level call. Every generated method is a one-liner on top of it.
    /// Sends `Authorization: Bearer <token>`, a JSON body when `body` is `Some`,
    /// parses the JSON response, and on a non-2xx status returns an [`Error`].
    pub fn request(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value, Error> {
        let url = format!("{}{}", self.base_url, path);
        let tok = self.resolve_token()?;
        let req = ureq::request(method, &url).set("Authorization", &format!("Bearer {}", tok));

        let result = match body {
            Some(v) => {
                let s = serde_json::to_string(&v).map_err(|e| local_err(e.to_string()))?;
                req.set("Content-Type", "application/json").send_string(&s)
            }
            None => req.call(),
        };
        handle_response(result)
    }

    /// POST raw file bytes (not JSON, not multipart) to `path`, passing
    /// `filename`/`retention_days` as query params and the media type as the
    /// Content-Type header. Parsed exactly like [`Client::request`].
    fn request_binary(
        &self,
        path: &str,
        data: &[u8],
        filename: &str,
        content_type: &str,
        retention_days: i64,
    ) -> Result<Value, Error> {
        let ct = if content_type.is_empty() { "application/octet-stream" } else { content_type };
        let mut query: Vec<String> = Vec::new();
        if !filename.is_empty() {
            query.push(format!("filename={}", enc(filename)));
        }
        if retention_days != 0 {
            query.push(format!("retentionDays={}", retention_days));
        }
        let mut url = format!("{}{}", self.base_url, path);
        if !query.is_empty() {
            url.push('?');
            url.push_str(&query.join("&"));
        }
        let tok = self.resolve_token()?;
        let result = ureq::request("POST", &url)
            .set("Authorization", &format!("Bearer {}", tok))
            .set("Content-Type", ct)
            .send_bytes(data);
        handle_response(result)
    }

    /// Upload a file and get back a secure, time-limited URL to reference as a
    /// `send` attachment (`{ filename, url }`) — instead of base64-inlining large
    /// files on every send. Provide the file ONE of four ways (checked in this
    /// order): `url` (MailKite fetches & re-hosts), `bytes` (raw binary upload),
    /// `path` (read off disk, raw binary upload), or `content` (base64).
    pub fn upload_attachment(&self, file: AttachmentUpload) -> Result<Value, Error> {
        // 1. URL → JSON body {url, filename?, contentType?, retentionDays?}.
        if let Some(url) = non_empty(&file.url) {
            let mut obj = serde_json::Map::new();
            obj.insert("url".into(), json!(url));
            add_meta(&mut obj, &file);
            return self.request("POST", "/v1/attachments", Some(Value::Object(obj)));
        }

        // 2. Bytes / 3. Path → raw binary upload.
        let has_path = non_empty(&file.path).is_some();
        if file.bytes.is_some() || has_path {
            let mut data = file.bytes.clone().unwrap_or_default();
            let mut filename = file.filename.clone().unwrap_or_default();
            let mut content_type = file.content_type.clone().unwrap_or_default();
            if let Some(path) = non_empty(&file.path) {
                data = std::fs::read(path).map_err(|e| local_err(e.to_string()))?;
                if filename.is_empty() {
                    filename = basename(path);
                }
                if content_type.is_empty() {
                    content_type = guess_content_type(path);
                }
            }
            if content_type.is_empty() {
                content_type = guess_content_type(&filename);
            }
            return self.request_binary(
                "/v1/attachments",
                &data,
                &filename,
                &content_type,
                file.retention_days.unwrap_or(0),
            );
        }

        // 4. Content (base64) → JSON body {content, filename?, contentType?, retentionDays?}.
        if let Some(content) = non_empty(&file.content) {
            let mut obj = serde_json::Map::new();
            obj.insert("content".into(), json!(content));
            add_meta(&mut obj, &file);
            return self.request("POST", "/v1/attachments", Some(Value::Object(obj)));
        }

        Err(local_err(
            "mailkite: upload_attachment needs one of url, bytes, path, or content",
        ))
    }

    // --- Local helpers (also exposed as free functions) ----------------------

    /// Verify an `x-mailkite-signature` header for `payload` using the default
    /// 5-minute replay window. Local HMAC-SHA256 check — no network call.
    pub fn verify_webhook(&self, signature: &str, payload: &str, secret: &str) -> bool {
        verify_webhook(signature, payload, secret)
    }

    /// Verify the signature and reject events older than `tolerance_ms` (0
    /// disables the freshness check).
    pub fn verify_webhook_with_tolerance(
        &self,
        signature: &str,
        payload: &str,
        secret: &str,
        tolerance_ms: i64,
    ) -> bool {
        verify_webhook_with_tolerance(signature, payload, secret, tolerance_ms)
    }

    /// `{"status":"ok"}` — acknowledge a webhook event.
    pub fn reply_ok(&self) -> &'static str {
        reply_ok()
    }
    /// `{"status":"spam"}` — mark the message as spam.
    pub fn reply_spam(&self) -> &'static str {
        reply_spam()
    }
    /// `{"status":"drop"}` — drop (discard) the message.
    pub fn reply_drop(&self) -> &'static str {
        reply_drop()
    }
    /// `{"status":"ok","actions":[{"type":"block-sender"}]}` — block the sender.
    pub fn reply_block_sender(&self) -> &'static str {
        reply_block_sender()
    }

    /// Encrypt a UTF-8 plaintext to an RSA public key (SPKI PEM), returning the
    /// at-rest envelope as a compact JSON string. Local only — no network call.
    pub fn encrypt(&self, plaintext: &str, public_key_pem: &str) -> Result<String, Error> {
        encrypt(plaintext, public_key_pem)
    }

    /// Reverse [`Client::encrypt`]: given an at-rest envelope (JSON string) and an
    /// RSA private key (PKCS#8 PEM), return the original UTF-8 plaintext.
    pub fn decrypt(&self, envelope_json: &str, private_key_pem: &str) -> Result<String, Error> {
        decrypt(envelope_json, private_key_pem)
    }
}

/// Parse a ureq result into a `Value` or an [`Error`], matching the Go SDK: 2xx →
/// parsed body (or `Null` when empty); non-2xx → `Error` with the `error` field
/// as the message (else `HTTP <status>`); transport failure → `Error{status:0}`.
fn handle_response(result: Result<ureq::Response, ureq::Error>) -> Result<Value, Error> {
    match result {
        Ok(resp) => {
            let text = resp.into_string().unwrap_or_default();
            if text.is_empty() {
                Ok(Value::Null)
            } else {
                Ok(serde_json::from_str(&text).unwrap_or(Value::Null))
            }
        }
        Err(ureq::Error::Status(code, resp)) => {
            let text = resp.into_string().unwrap_or_default();
            let data: Option<Value> = if text.is_empty() {
                None
            } else {
                serde_json::from_str(&text).ok()
            };
            let msg = data
                .as_ref()
                .and_then(|d| d.get("error"))
                .and_then(|e| e.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| format!("HTTP {}", code));
            Err(Error { status: code, message: msg, body: data })
        }
        Err(ureq::Error::Transport(t)) => Err(local_err(t.to_string())),
    }
}

// --- Path / query helpers (used by the generated methods) --------------------

/// Percent-encode one path or query segment (RFC 3986 unreserved set kept).
pub fn enc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

/// Build the list query string: `""` when nothing is set, otherwise
/// `?before=&limit=&search=` (only the params that are present, in this order).
pub fn page_query(before: Option<i64>, limit: Option<i64>, search: Option<&str>) -> String {
    let mut parts: Vec<String> = Vec::new();
    if let Some(b) = before {
        parts.push(format!("before={}", b));
    }
    if let Some(l) = limit {
        parts.push(format!("limit={}", l));
    }
    if let Some(s) = search {
        parts.push(format!("search={}", enc(s)));
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!("?{}", parts.join("&"))
    }
}

// --- Attachment upload -------------------------------------------------------

/// Describes a file to upload via [`Client::upload_attachment`]. Provide the file
/// ONE of four ways (checked in this order): `url`, `bytes`, `path`, or
/// `content` (base64). `retention_days` optionally overrides how long the hosted
/// file lives.
#[derive(Debug, Clone, Default)]
pub struct AttachmentUpload {
    pub url: Option<String>,
    pub content: Option<String>,
    pub filename: Option<String>,
    pub content_type: Option<String>,
    pub retention_days: Option<i64>,
    pub path: Option<String>,
    pub bytes: Option<Vec<u8>>,
}

fn non_empty(o: &Option<String>) -> Option<&str> {
    o.as_deref().filter(|s| !s.is_empty())
}

/// Add the optional `filename` / `contentType` / `retentionDays` fields to a
/// JSON upload body (only when present / non-zero), matching the Go SDK.
fn add_meta(obj: &mut serde_json::Map<String, Value>, file: &AttachmentUpload) {
    if let Some(f) = non_empty(&file.filename) {
        obj.insert("filename".into(), json!(f));
    }
    if let Some(ct) = non_empty(&file.content_type) {
        obj.insert("contentType".into(), json!(ct));
    }
    if let Some(rd) = file.retention_days.filter(|v| *v != 0) {
        obj.insert("retentionDays".into(), json!(rd));
    }
}

fn basename(path: &str) -> String {
    path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
}

/// Return a media type from `name`'s extension, defaulting to
/// `application/octet-stream`.
fn guess_content_type(name: &str) -> String {
    let ext = match name.rfind('.') {
        Some(pos) => name[pos + 1..].to_lowercase(),
        None => String::new(),
    };
    let ct = match ext.as_str() {
        "pdf" => "application/pdf",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "csv" => "text/csv",
        "txt" => "text/plain",
        "html" => "text/html",
        "json" => "application/json",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xls" => "application/vnd.ms-excel",
        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "ics" | "ical" => "text/calendar",
        _ => "application/octet-stream",
    };
    ct.to_string()
}

// --- Webhook verification ----------------------------------------------------

/// Package-level webhook verification with the default 5-minute replay window.
pub fn verify_webhook(signature: &str, payload: &str, secret: &str) -> bool {
    verify_webhook_with_tolerance(signature, payload, secret, DEFAULT_TOLERANCE_MS)
}

/// Verify the signature and reject events older than `tolerance_ms` (0 disables
/// the freshness check). Parses `t=<ms>,v1=<hex>` and checks
/// `HMAC-SHA256(secret, "<t>.<payload>")`.
pub fn verify_webhook_with_tolerance(
    signature: &str,
    payload: &str,
    secret: &str,
    tolerance_ms: i64,
) -> bool {
    if signature.is_empty() {
        return false;
    }
    let mut t = "";
    let mut v1 = "";
    for seg in signature.split(',') {
        if let Some(i) = seg.find('=') {
            let key = seg[..i].trim();
            let val = seg[i + 1..].trim();
            match key {
                "t" => t = val,
                "v1" => v1 = val,
                _ => {}
            }
        }
    }
    if t.is_empty() || v1.is_empty() {
        return false;
    }
    let ts: i64 = match t.parse() {
        Ok(v) => v,
        Err(_) => return false,
    };
    // The t in the header is milliseconds since the epoch.
    if tolerance_ms > 0 {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);
        if (now - ts).abs() > tolerance_ms {
            return false;
        }
    }
    let mut mac = match <HmacSha256 as Mac>::new_from_slice(secret.as_bytes()) {
        Ok(m) => m,
        Err(_) => return false,
    };
    mac.update(t.as_bytes());
    mac.update(b".");
    mac.update(payload.as_bytes());
    let expected = to_hex(&mac.finalize().into_bytes());
    constant_time_eq(expected.as_bytes(), v1.as_bytes())
}

// --- Reply helpers -----------------------------------------------------------

/// `{"status":"ok"}` — acknowledge a webhook event.
pub fn reply_ok() -> &'static str {
    "{\"status\":\"ok\"}"
}
/// `{"status":"spam"}` — mark the message as spam.
pub fn reply_spam() -> &'static str {
    "{\"status\":\"spam\"}"
}
/// `{"status":"drop"}` — drop (discard) the message.
pub fn reply_drop() -> &'static str {
    "{\"status\":\"drop\"}"
}
/// `{"status":"ok","actions":[{"type":"block-sender"}]}` — block the sender.
pub fn reply_block_sender() -> &'static str {
    "{\"status\":\"ok\",\"actions\":[{\"type\":\"block-sender\"}]}"
}

// --- At-rest encryption ------------------------------------------------------

/// The stored/serialized at-rest encryption envelope. All binary fields are
/// base64. Byte-compatible with MailKite's WebCrypto envelope and every other
/// MailKite SDK.
#[derive(Debug, Serialize, Deserialize)]
struct Envelope {
    v: i64,
    #[serde(rename = "keyAlg")]
    key_alg: String,
    fp: String,
    enc: String,
    iv: String,
    #[serde(rename = "wrappedKey")]
    wrapped_key: String,
    ciphertext: String,
}

/// Protect a UTF-8 plaintext to an RSA public key (SPKI PEM), returning the
/// at-rest envelope serialized as a compact JSON string. Hybrid scheme — a fresh
/// AES-256-GCM content key encrypts the data and is wrapped with RSA-OAEP
/// (SHA-256). Local only — no network call.
pub fn encrypt(plaintext: &str, public_key_pem: &str) -> Result<String, Error> {
    let der = pem_to_der(public_key_pem)?;
    let pub_key = RsaPublicKey::from_public_key_der(&der)
        .map_err(|e| local_err(format!("mailkite: parse public key: {}", e)))?;

    // fp = lowercase hex sha256 of the SPKI DER (the PEM block bytes).
    let fp = to_hex(&Sha256::digest(&der));

    // Fresh 32-byte AES-256 content key + 12-byte IV.
    let mut raw_key = [0u8; 32];
    OsRng.fill_bytes(&mut raw_key);
    let mut iv = [0u8; 12];
    OsRng.fill_bytes(&mut iv);

    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&raw_key));
    // encrypt returns ciphertext||tag, matching WebCrypto's AES-GCM output.
    let ct = cipher
        .encrypt(Nonce::from_slice(&iv), plaintext.as_bytes())
        .map_err(|_| local_err("mailkite: aes-gcm encrypt failed"))?;

    // Wrap the AES key with RSA-OAEP (SHA-256 for both hash and MGF1).
    let wrapped = pub_key
        .encrypt(&mut OsRng, Oaep::new::<Sha256>(), &raw_key)
        .map_err(|e| local_err(format!("mailkite: wrap content key: {}", e)))?;

    let env = Envelope {
        v: 1,
        key_alg: "RSA-OAEP-256".to_string(),
        fp,
        enc: "A256GCM".to_string(),
        iv: STANDARD.encode(iv),
        wrapped_key: STANDARD.encode(wrapped),
        ciphertext: STANDARD.encode(ct),
    };
    serde_json::to_string(&env).map_err(|e| local_err(e.to_string()))
}

/// Reverse [`encrypt`]: given an at-rest envelope (JSON string) and an RSA
/// private key (PKCS#8 PEM), return the original UTF-8 plaintext. Local only.
pub fn decrypt(envelope_json: &str, private_key_pem: &str) -> Result<String, Error> {
    let env: Envelope = serde_json::from_str(envelope_json)
        .map_err(|e| local_err(format!("mailkite: parse envelope: {}", e)))?;

    let priv_key = RsaPrivateKey::from_pkcs8_pem(private_key_pem)
        .map_err(|e| local_err(format!("mailkite: parse private key: {}", e)))?;

    let wrapped = STANDARD
        .decode(env.wrapped_key.as_bytes())
        .map_err(|e| local_err(format!("mailkite: decode wrappedKey: {}", e)))?;
    let iv = STANDARD
        .decode(env.iv.as_bytes())
        .map_err(|e| local_err(format!("mailkite: decode iv: {}", e)))?;
    let ct = STANDARD
        .decode(env.ciphertext.as_bytes())
        .map_err(|e| local_err(format!("mailkite: decode ciphertext: {}", e)))?;

    let raw_key = priv_key
        .decrypt(Oaep::new::<Sha256>(), &wrapped)
        .map_err(|e| local_err(format!("mailkite: unwrap content key: {}", e)))?;

    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&raw_key));
    // decrypt expects ciphertext||tag, matching WebCrypto.
    let pt = cipher
        .decrypt(Nonce::from_slice(&iv), ct.as_ref())
        .map_err(|_| local_err("mailkite: decrypt failed"))?;
    String::from_utf8(pt).map_err(|e| local_err(format!("mailkite: utf8: {}", e)))
}

// --- Small crypto/util helpers ----------------------------------------------

/// Decode a PEM block to its DER bytes (the base64 body between the header/footer
/// lines), matching Go's `pem.Decode(...).Bytes`.
fn pem_to_der(pem: &str) -> Result<Vec<u8>, Error> {
    let mut b64 = String::new();
    for line in pem.lines() {
        let t = line.trim();
        if t.is_empty() || t.starts_with("-----") {
            continue;
        }
        b64.push_str(t);
    }
    STANDARD
        .decode(b64.as_bytes())
        .map_err(|e| local_err(format!("mailkite: decode PEM: {}", e)))
}

fn to_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{:02x}", b));
    }
    s
}

fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}