# Calling the API without an SDK

This page is for a language Mailset has no SDK for, or a client you would rather write yourself. With an SDK or the CLI you can skip it, since both sign every request for you. [Authentication](https://mailset.app/docs/authentication) covers making a key and keeping it alive.

Every request carries a token and a signature made with a private key. Both live inside one credential, so your code holds one secret and signs each request with it. A captured request can't be changed, or replayed more than 2 minutes later, because the signature covers the body and the time.

An app key (`MAILSET_KEY`) and an API token (`MAILSET_TOKEN`) sign requests the same way.

## What is inside

Take the prefix off (`msk1_` or `mst_`) and decode the rest as base64url. It is JSON:

```json
{
	"api": "https://mailset.app",
	"token": "the bearer token",
	"privateKey": { "kty": "EC", "crv": "P-256", "d": "…", "x": "…", "y": "…" }
}
```

`privateKey` is a P-256 key as a JWK. An API token has no `api`: send its requests to `https://mailset.app`.

## Sign a request

Send three headers with every request.

| Header          | Value                                                    |
| --------------- | -------------------------------------------------------- |
| `Authorization` | `Bearer ` and the credential's `token`                   |
| `ms-time`       | The time now, in milliseconds since the epoch, as digits |
| `ms-proof`      | The signature, base64url with no padding                 |

To make `ms-proof`:

1. Hash the body's bytes with SHA-256 and write the hash as base64url with no padding. With no body, hash zero bytes.
2. Join five lines with a line feed (`\n`), with none after the last: the text `ms-proof-v1`, the method in capitals, the path with its query string, the same `ms-time`, and the hash from step 1.
3. Sign that text's UTF-8 bytes with the private key: ECDSA on P-256 with SHA-256.
4. Write the signature as the 32 bytes of `r` followed by the 32 bytes of `s`, then base64url those 64 bytes.

Mailset accepts a request whose `ms-time` is within 2 minutes of its own clock.

## Two traps

**Your library returns DER, and Mailset wants raw `r` and `s`.** Most ECDSA libraries answer with an ASN.1 structure of 70 to 72 bytes. Take `r` and `s` out of it and pad each to 32 bytes. Go's `ecdsa.Sign` gives you both numbers already. Java has `SHA256withECDSAinP1363Format` and Rust's `p256` has `to_bytes()`, and each writes the 64 bytes directly. Python, Ruby and PHP need the conversion, and the clients below do it.

**The key is a JWK, and your library may want something else.** `d` is the private number, 32 bytes, big-endian, in base64url. Python, Go and Rust build a key from it directly. Ruby and PHP want a DER or PEM key, so the clients below wrap `d` in the fixed bytes of a P-256 private key.

Smaller things that give the same refusal:

- Sign the bytes you send. Encode the JSON once, sign those bytes, and send them unchanged.
- The path includes the query string, exactly as sent.
- `ms-time` is milliseconds, not seconds.
- base64url uses `-` and `_`, and has no `=` at the end.

Every signing mistake gets the same answer, `401` with `unauthorized`, so a wrong signature tells an attacker nothing. Check your code against the vector below to find out which step is off.

## Test vector

The key here is a public example, made for this page. It is no one's credential.

The key, as `MAILSET_KEY`:

```text
msk1_eyJhcGkiOiJodHRwczovL21haWxzZXQuYXBwIiwidG9rZW4iOiJleGFtcGxlLXNlc3Npb24tdG9rZW4tbm90LWEtcmVhbC1vbmUiLCJwcml2YXRlS2V5Ijp7ImNydiI6IlAtMjU2IiwiZCI6Imp3SlNWRnpaY3NqQW5FNzRoYWVtclEtbHJCbFo1T05xT2ctUUp0OFJNdVEiLCJleHQiOnRydWUsImtleV9vcHMiOlsic2lnbiJdLCJrdHkiOiJFQyIsIngiOiJsclRfcTRjcGpubC05c1BDTG1KNnp1OVpWcURpMURJVy0zT25uMDdPaXNzIiwieSI6IjFkbjdaUGRjeWNFYW0tdVFuRnZRQnRKZHFTWUUycXZQa05meTl2eW1BZWcifX0
```

What it decodes to:

```json
{
  "api": "https://mailset.app",
  "token": "example-session-token-not-a-real-one",
  "privateKey": {
    "crv": "P-256",
    "d": "jwJSVFzZcsjAnE74haemrQ-lrBlZ5ONqOg-QJt8RMuQ",
    "ext": true,
    "key_ops": [
      "sign"
    ],
    "kty": "EC",
    "x": "lrT_q4cpjnl-9sPCLmJ6zu9ZVqDi1DIW-3Onn07Oiss",
    "y": "1dn7ZPdcycEam-uQnFvQBtJdqSYE2qvPkNfy9vymAeg"
  }
}
```

The request is `POST /v1/grants.current` at `ms-time: 1800000000000`, with this body:

```json
{"input":{}}
```

The body’s digest, base64url of its SHA-256:

```text
LucVGPpXytzpZJYfHPBNn_to9wFu4zKm0rqNW0-CXSQ
```

The text to sign, five lines joined by a line feed, with none after the last:

```text
ms-proof-v1
POST
/v1/grants.current
1800000000000
LucVGPpXytzpZJYfHPBNn_to9wFu4zKm0rqNW0-CXSQ
```

A signature is different every time, so yours won’t match this one. This one is valid for the text above, and your verifier should accept it with the public key below:

```text
KU1GgeZBYLyL81sJwaXinOvjxQpYdTDFSw8YjE9HK3ff5pOYc7oAjH6xmw4qlnhHs84FW8b_udj8nzSu43WqSw
```

```json
{
  "kty": "EC",
  "crv": "P-256",
  "x": "lrT_q4cpjnl-9sPCLmJ6zu9ZVqDi1DIW-3Onn07Oiss",
  "y": "1dn7ZPdcycEam-uQnFvQBtJdqSYE2qvPkNfy9vymAeg"
}
```

## A client in your language

Each file is a whole program: it reads `MAILSET_KEY` or `MAILSET_TOKEN`, signs a request and prints the answer. `sign_request` is the part to copy, and `run` is one signed call. These are the files Mailset's own tests run against the API.

```python
"""Calls Mailset's HTTP API from Python: one signed request, and its answer.

    pip install cryptography    # the standard library has no ECDSA
    MAILSET_KEY=msk1_... python3 request.py

An API token works the same way, on the commands a person may run:

    MAILSET_TOKEN=mst_... python3 request.py whoami
"""

import base64
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature


def b64url(data: bytes) -> str:
    """base64url with no padding, as Mailset writes it."""
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def b64url_decode(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def sign_request(method: str, path: str, body: bytes, key: dict, now_ms: int) -> dict:
    """The three headers that prove this key made this request, now.

    path carries its query string. body is the exact bytes you send.
    """
    digest = b64url(hashlib.sha256(body).digest())
    message = f"ms-proof-v1\n{method.upper()}\n{path}\n{now_ms}\n{digest}"

    # The private key comes as a JWK. Its "d" is the P-256 scalar, big-endian.
    scalar = int.from_bytes(b64url_decode(key["privateKey"]["d"]), "big")
    private_key = ec.derive_private_key(scalar, ec.SECP256R1())

    # cryptography answers in DER. Mailset reads r then s, 32 bytes each.
    der = private_key.sign(message.encode(), ec.ECDSA(hashes.SHA256()))
    r, s = decode_dss_signature(der)
    proof = r.to_bytes(32, "big") + s.to_bytes(32, "big")

    return {
        "Authorization": f"Bearer {key['token']}",
        "ms-time": str(now_ms),
        "ms-proof": b64url(proof),
    }


def load_key() -> dict:
    """The credential in the environment, decoded: api, token and privateKey.

    MAILSET_KEY is "msk1_" and MAILSET_TOKEN is "mst_", each followed by
    base64url JSON. A token names no API, so it goes to mailset.app.
    """
    text = os.environ.get("MAILSET_KEY") or os.environ.get("MAILSET_TOKEN") or ""
    prefix, _, encoded = text.strip().partition("_")
    if prefix not in ("msk1", "mst"):
        sys.exit("Set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...).")
    key = json.loads(b64url_decode(encoded))
    key.setdefault("api", "https://mailset.app")
    return key


def run(command: str, input: dict, key: dict) -> dict:
    """POST /v1/<command>. Returns Mailset's answer, a refusal included."""
    path = f"/v1/{command}"
    # Encode once: the bytes signed have to be the bytes sent.
    body = json.dumps({"input": input}).encode()
    now_ms = int(time.time() * 1000)
    api = key["api"]
    headers = sign_request("POST", path, body, key, now_ms)
    headers["Content-Type"] = "application/json"
    request = urllib.request.Request(api + path, data=body, headers=headers)
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return json.load(response)
    except urllib.error.HTTPError as refusal:
        # urllib raises on a 4xx, and the refusal is in its body:
        # {"ok": false, "error": {"code": ..., "message": ...}}
        return json.load(refusal)


if __name__ == "__main__":
    command = sys.argv[1] if len(sys.argv) > 1 else "grants.current"
    answer = run(command, {}, load_key())
    print(json.dumps(answer, indent=2))
    sys.exit(0 if answer.get("ok") else 1)
```

```go
// Calls Mailset's HTTP API from Go: one signed request, and its answer.
// Standard library only, Go 1.25 or later.
//
//	MAILSET_KEY=msk1_... go run request.go
//
// An API token works the same way, on the commands a person may run:
//
//	MAILSET_TOKEN=mst_... go run request.go whoami
package main

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

// Key is the credential in the environment, decoded.
type Key struct {
	API        string `json:"api"`
	Token      string `json:"token"`
	PrivateKey struct {
		D string `json:"d"`
	} `json:"privateKey"`
}

// loadKey reads MAILSET_KEY ("msk1_") or MAILSET_TOKEN ("mst_"): the prefix,
// then base64url JSON. A token names no API, so it goes to mailset.app.
func loadKey() (Key, error) {
	key := Key{API: "https://mailset.app"}
	text := os.Getenv("MAILSET_KEY")
	if text == "" {
		text = os.Getenv("MAILSET_TOKEN")
	}
	prefix, encoded, _ := strings.Cut(strings.TrimSpace(text), "_")
	if prefix != "msk1" && prefix != "mst" {
		return key, errors.New("set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...)")
	}
	decoded, err := b64url.DecodeString(encoded)
	if err != nil {
		return key, err
	}
	return key, json.Unmarshal(decoded, &key)
}


// base64url with no padding, as Mailset writes it.
var b64url = base64.RawURLEncoding

// signRequest returns the three headers that prove this key made this
// request, now. path carries its query string. body is the exact bytes sent.
func signRequest(method, path string, body []byte, key Key, nowMs int64) (http.Header, error) {
	digest := sha256.Sum256(body)
	message := fmt.Sprintf("ms-proof-v1\n%s\n%s\n%d\n%s",
		strings.ToUpper(method), path, nowMs, b64url.EncodeToString(digest[:]))

	// The private key comes as a JWK. Its "d" is the P-256 scalar,
	// big-endian, which is what ParseRawPrivateKey reads (Go 1.25).
	scalar, err := b64url.DecodeString(key.PrivateKey.D)
	if err != nil {
		return nil, err
	}
	privateKey, err := ecdsa.ParseRawPrivateKey(elliptic.P256(), scalar)
	if err != nil {
		return nil, err
	}

	// SignASN1 would answer in DER. Sign answers r and s as numbers, and
	// Mailset reads r then s, 32 bytes each. FillBytes keeps the leading
	// zeros that Bytes would drop.
	hash := sha256.Sum256([]byte(message))
	r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:])
	if err != nil {
		return nil, err
	}
	proof := make([]byte, 64)
	r.FillBytes(proof[:32])
	s.FillBytes(proof[32:])

	headers := http.Header{}
	headers.Set("Authorization", "Bearer "+key.Token)
	headers.Set("ms-time", strconv.FormatInt(nowMs, 10))
	headers.Set("ms-proof", b64url.EncodeToString(proof))
	return headers, nil
}


// run posts /v1/<command> and returns Mailset's answer, a refusal included.
func run(command string, input any, key Key) (map[string]any, error) {
	path := "/v1/" + command
	// Encode once: the bytes signed have to be the bytes sent.
	body, err := json.Marshal(map[string]any{"input": input})
	if err != nil {
		return nil, err
	}
	nowMs := time.Now().UnixMilli()
	api := key.API

	request, err := http.NewRequest("POST", api+path, bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	if request.Header, err = signRequest("POST", path, body, key, nowMs); err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	// A refusal is JSON too: {"ok": false, "error": {"code": ..., "message": ...}}
	var answer map[string]any
	return answer, json.NewDecoder(response.Body).Decode(&answer)
}

func main() {
	key, err := loadKey()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	command := "grants.current"
	if len(os.Args) > 1 {
		command = os.Args[1]
	}
	// An empty input has to be {} on the wire. A nil map would write null.
	answer, err := run(command, map[string]any{}, key)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	text, _ := json.MarshalIndent(answer, "", "  ")
	fmt.Println(string(text))
	if answer["ok"] != true {
		os.Exit(1)
	}
}
```

```ruby
# Calls Mailset's HTTP API from Ruby: one signed request, and its answer.
# Standard library only. On Ruby 3.4 and later under Bundler, add gem "base64".
#
#   MAILSET_KEY=msk1_... ruby request.rb
#
# An API token works the same way, on the commands a person may run:
#
#   MAILSET_TOKEN=mst_... ruby request.rb whoami

require 'base64'
require 'json'
require 'net/http'
require 'openssl'

# base64url with no padding, as Mailset writes it.
def b64url(bytes)
  Base64.urlsafe_encode64(bytes, padding: false)
end

# The three headers that prove this key made this request, now.
# path carries its query string. body is the exact bytes you send.
def sign_request(method, path, body, key, now_ms)
  digest = b64url(OpenSSL::Digest::SHA256.digest(body))
  message = "ms-proof-v1\n#{method.upcase}\n#{path}\n#{now_ms}\n#{digest}"

  # The private key comes as a JWK. Its "d" is the P-256 scalar, big-endian.
  # OpenSSL 3 keys can't be filled in after they are made, so wrap the scalar
  # in the ASN.1 of an EC private key (RFC 5915) and load that.
  scalar = Base64.urlsafe_decode64(key['privateKey']['d']).rjust(32, "\0")
  private_key = OpenSSL::PKey::EC.new(
    OpenSSL::ASN1::Sequence([
      OpenSSL::ASN1::Integer(1),
      OpenSSL::ASN1::OctetString(scalar),
      OpenSSL::ASN1::ObjectId('prime256v1', 0, :EXPLICIT)
    ]).to_der
  )

  # OpenSSL answers in DER: a sequence of two integers. Mailset reads r then
  # s, 32 bytes each, so write each one out to its full width.
  der = private_key.sign('SHA256', message)
  proof = OpenSSL::ASN1.decode(der).value.map { |n| n.value.to_s(2).rjust(32, "\0") }.join

  {
    'Authorization' => "Bearer #{key['token']}",
    'ms-time' => now_ms.to_s,
    'ms-proof' => b64url(proof)
  }
end

# The credential in the environment, decoded: api, token and privateKey.
# MAILSET_KEY is "msk1_" and MAILSET_TOKEN is "mst_", each followed by
# base64url JSON. A token names no API, so it goes to mailset.app.
def load_key
  text = (ENV['MAILSET_KEY'] || ENV['MAILSET_TOKEN']).to_s.strip
  prefix, encoded = text.split('_', 2)
  abort 'Set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...).' unless %w[msk1 mst].include?(prefix)
  key = JSON.parse(Base64.urlsafe_decode64(encoded))
  key['api'] ||= 'https://mailset.app'
  key
end

# POST /v1/<command>. Returns Mailset's answer, a refusal included.
def run(command, input, key)
  path = "/v1/#{command}"
  # Encode once: the bytes signed have to be the bytes sent.
  body = JSON.generate({ input: input })
  now_ms = (Time.now.to_f * 1000).to_i
  api = key['api']
  uri = URI(api + path)
  headers = sign_request('POST', path, body, key, now_ms)
  headers['Content-Type'] = 'application/json'
  # A refusal is JSON too: {"ok": false, "error": {"code": ..., "message": ...}}
  JSON.parse(Net::HTTP.post(uri, body, headers).body)
end

if $PROGRAM_NAME == __FILE__
  answer = run(ARGV[0] || 'grants.current', {}, load_key)
  puts JSON.pretty_generate(answer)
  exit(answer['ok'] ? 0 : 1)
end
```

```php
<?php
// Calls Mailset's HTTP API from PHP 8: one signed request, and its answer.
// Needs the openssl and curl extensions. No Composer packages.
//
//   MAILSET_KEY=msk1_... php request.php
//
// An API token works the same way, on the commands a person may run:
//
//   MAILSET_TOKEN=mst_... php request.php whoami

// base64url with no padding, as Mailset writes it.
function b64url(string $bytes): string
{
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

function b64urlDecode(string $text): string
{
    return base64_decode(strtr($text, '-_', '+/'));
}

// The three headers that prove this key made this request, now.
// $path carries its query string. $body is the exact bytes you send.
function signRequest(string $method, string $path, string $body, array $key, int $nowMs): array
{
    $digest = b64url(hash('sha256', $body, true));
    $message = "ms-proof-v1\n" . strtoupper($method) . "\n$path\n$nowMs\n$digest";

    // The private key comes as a JWK and openssl_sign wants PEM. Its "d" is
    // the P-256 scalar, big-endian: wrap it in the ASN.1 of an EC private key
    // (RFC 5915). The bytes around it are the same for every P-256 key.
    $scalar = str_pad(b64urlDecode($key['privateKey']['d']), 32, "\0", STR_PAD_LEFT);
    $der = hex2bin('30310201010420') . $scalar . hex2bin('a00a06082a8648ce3d030107');
    $pem = "-----BEGIN EC PRIVATE KEY-----\n"
        . chunk_split(base64_encode($der), 64, "\n")
        . "-----END EC PRIVATE KEY-----\n";

    // openssl_sign answers in DER: 30 <len> 02 <len> r 02 <len> s. Mailset
    // reads r then s, 32 bytes each, so cut both out and pad them.
    if (!openssl_sign($message, $signature, $pem, OPENSSL_ALGO_SHA256)) {
        throw new RuntimeException("The key can't sign: " . openssl_error_string());
    }
    $rLength = ord($signature[3]);
    $proof = '';
    foreach ([substr($signature, 4, $rLength), substr($signature, 6 + $rLength)] as $number) {
        $proof .= str_pad(ltrim($number, "\0"), 32, "\0", STR_PAD_LEFT);
    }

    return [
        'Authorization' => 'Bearer ' . $key['token'],
        'ms-time' => (string) $nowMs,
        'ms-proof' => b64url($proof),
    ];
}

// The credential in the environment, decoded: api, token and privateKey.
// MAILSET_KEY is "msk1_" and MAILSET_TOKEN is "mst_", each followed by
// base64url JSON. A token names no API, so it goes to mailset.app.
function loadKey(): array
{
    $text = trim(getenv('MAILSET_KEY') ?: getenv('MAILSET_TOKEN') ?: '');
    [$prefix, $encoded] = explode('_', $text, 2) + ['', ''];
    if ($prefix !== 'msk1' && $prefix !== 'mst') {
        fwrite(STDERR, "Set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...).\n");
        exit(2);
    }
    return json_decode(b64urlDecode($encoded), true) + ['api' => 'https://mailset.app'];
}

// POST /v1/<command>. Returns Mailset's answer, a refusal included.
function run(string $command, array|object $input, array $key): array
{
    $path = "/v1/$command";
    // Encode once: the bytes signed have to be the bytes sent.
    $body = json_encode(['input' => $input]);
    $nowMs = (int) floor(microtime(true) * 1000);
    $api = $key['api'];

    $headers = ['Content-Type: application/json'];
    foreach (signRequest('POST', $path, $body, $key, $nowMs) as $name => $value) {
        $headers[] = "$name: $value";
    }
    $curl = curl_init($api . $path);
    curl_setopt_array($curl, [
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $reply = curl_exec($curl);
    if ($reply === false) {
        throw new RuntimeException(curl_error($curl));
    }
    // A refusal is JSON too: {"ok": false, "error": {"code": ..., "message": ...}}
    return json_decode($reply, true);
}

// An empty input has to be {} on the wire: json_encode([]) would write [].
$answer = run($argv[1] ?? 'grants.current', new stdClass(), loadKey());
echo json_encode($answer, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n";
exit($answer['ok'] ? 0 : 1);
```

```java
// Calls Mailset's HTTP API from Java 17: one signed request, and its answer.
// Standard library only.
//
//   MAILSET_KEY=msk1_... java Request.java
//
// An API token works the same way, on the commands a person may run:
//
//   MAILSET_TOKEN=mst_... java Request.java whoami

import java.math.BigInteger;
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.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPrivateKeySpec;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Request {
    /** The credential in the environment, decoded. d is the private key's JWK "d". */
    record Key(String api, String token, String d) {}

    /**
     * One string field of a JSON text. The JDK has no JSON parser, and this is
     * enough for a key, whose values need no escapes. In a service, use yours.
     */
    static String field(String json, String name) {
        Matcher found = Pattern.compile("\"" + name + "\"\\s*:\\s*\"([^\"\\\\]*)\"").matcher(json);
        return found.find() ? found.group(1) : null;
    }

    /**
     * MAILSET_KEY is "msk1_" and MAILSET_TOKEN is "mst_", each followed by
     * base64url JSON. A token names no API, so it goes to mailset.app.
     */
    static Key loadKey() {
        String text = System.getenv("MAILSET_KEY");
        if (text == null) text = System.getenv("MAILSET_TOKEN");
        String[] parts = (text == null ? "" : text.strip()).split("_", 2);
        if (parts.length < 2 || !(parts[0].equals("msk1") || parts[0].equals("mst"))) {
            System.err.println("Set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...).");
            System.exit(2);
        }
        String json = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
        String api = field(json, "api");
        return new Key(api == null ? "https://mailset.app" : api, field(json, "token"), field(json, "d"));
    }

    /**
     * The three headers that prove this key made this request, now.
     * path carries its query string. body is the exact bytes you send.
     */
    static Map<String, String> signRequest(
            String method, String path, byte[] body, Key key, long nowMs)
            throws GeneralSecurityException {
        Base64.Encoder b64url = Base64.getUrlEncoder().withoutPadding();
        String digest = b64url.encodeToString(MessageDigest.getInstance("SHA-256").digest(body));
        String message = String.join("\n",
                "ms-proof-v1", method.toUpperCase(Locale.ROOT), path, Long.toString(nowMs), digest);

        // The private key comes as a JWK. Its "d" is the P-256 scalar,
        // big-endian. The 1 says positive: a first byte of 0x80 or more
        // would otherwise read as a negative number.
        BigInteger scalar = new BigInteger(1, Base64.getUrlDecoder().decode(key.d()));
        AlgorithmParameters curve = AlgorithmParameters.getInstance("EC");
        curve.init(new ECGenParameterSpec("secp256r1"));
        PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(
                new ECPrivateKeySpec(scalar, curve.getParameterSpec(ECParameterSpec.class)));

        // "SHA256withECDSA" answers in DER. The P1363 format is the one
        // Mailset reads: r then s, 32 bytes each.
        Signature signer = Signature.getInstance("SHA256withECDSAinP1363Format");
        signer.initSign(privateKey);
        signer.update(message.getBytes(StandardCharsets.UTF_8));

        return Map.of(
                "Authorization", "Bearer " + key.token(),
                "ms-time", Long.toString(nowMs),
                "ms-proof", b64url.encodeToString(signer.sign()));
    }

    /** POST /v1/command, with input as JSON text. Returns Mailset's answer, refusals included. */
    static String run(String command, String input, Key key) throws Exception {
        String path = "/v1/" + command;
        // Encode once: the bytes signed have to be the bytes sent.
        byte[] body = ("{\"input\":" + input + "}").getBytes(StandardCharsets.UTF_8);
        long nowMs = System.currentTimeMillis();
        String api = key.api();

        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(api + path))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofByteArray(body));
        signRequest("POST", path, body, key, nowMs).forEach(request::header);
        // A refusal is JSON too: {"ok":false,"error":{"code":...,"message":...}}
        return HttpClient.newHttpClient()
                .send(request.build(), HttpResponse.BodyHandlers.ofString())
                .body();
    }

    public static void main(String[] args) throws Exception {
        String answer = run(args.length > 0 ? args[0] : "grants.current", "{}", loadKey());
        System.out.println(answer);
        // With no JSON parser here, this reads the text. Parse it in a service.
        boolean ok = answer.contains("\"ok\":true") && !answer.contains("\"ok\":false");
        System.exit(ok ? 0 : 1);
    }
}
```

```rust
// Calls Mailset's HTTP API from Rust: one signed request, and its answer.
//
// Rust runs a project, not a file, so make one and put this file in it:
//
//   cargo new mailset-request && cp request.rs mailset-request/src/main.rs
//   cd mailset-request && MAILSET_KEY=msk1_... cargo run
//
// with these lines in its Cargo.toml:
//
//   [dependencies]
//   base64 = "0.23.1"
//   p256 = { version = "0.14.0", features = ["ecdsa"] }
//   reqwest = { version = "0.13.5", features = ["blocking"] }
//   serde_json = "1.0.154"
//   sha2 = "0.11.3"
//
// An API token works the same way, on the commands a person may run:
//
//   MAILSET_TOKEN=mst_... cargo run -- whoami

use std::env;
use std::error::Error;
use std::process::exit;
use std::time::{SystemTime, UNIX_EPOCH};

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{Signature, SigningKey};
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};

/// The three headers that prove this key made this request, now.
/// path carries its query string. body is the exact bytes you send.
fn sign_request(
    method: &str,
    path: &str,
    body: &[u8],
    key: &Value,
    now_ms: u64,
) -> Result<HeaderMap, Box<dyn Error>> {
    // URL_SAFE_NO_PAD is base64url with no padding, as Mailset writes it.
    let digest = URL_SAFE_NO_PAD.encode(Sha256::digest(body));
    let method = method.to_uppercase();
    let message = format!("ms-proof-v1\n{method}\n{path}\n{now_ms}\n{digest}");

    // The private key comes as a JWK. Its "d" is the P-256 scalar,
    // big-endian, and from_slice takes those 32 bytes as they are.
    let d = key["privateKey"]["d"]
        .as_str()
        .ok_or("The key has no private key.")?;
    let signing_key = SigningKey::from_slice(&URL_SAFE_NO_PAD.decode(d)?)?;

    // A p256 Signature is already r then s, 32 bytes each, which is what
    // Mailset reads: to_bytes() writes them out. to_der() would be DER, and
    // Mailset refuses that.
    let signature: Signature = signing_key.sign(message.as_bytes());

    let token = key["token"].as_str().unwrap_or_default();
    let proof = URL_SAFE_NO_PAD.encode(signature.to_bytes());
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, format!("Bearer {token}").parse()?);
    headers.insert("ms-time", now_ms.to_string().parse()?);
    headers.insert("ms-proof", proof.parse()?);
    Ok(headers)
}

/// The credential in the environment, decoded: api, token and privateKey.
/// MAILSET_KEY is "msk1_" and MAILSET_TOKEN is "mst_", each followed by
/// base64url JSON. A token names no API, so it goes to mailset.app.
fn load_key() -> Result<Value, Box<dyn Error>> {
    let text = env::var("MAILSET_KEY")
        .or_else(|_| env::var("MAILSET_TOKEN"))
        .unwrap_or_default();
    let (prefix, encoded) = text.trim().split_once('_').unwrap_or_default();
    if prefix != "msk1" && prefix != "mst" {
        return Err("Set MAILSET_KEY (msk1_...) or MAILSET_TOKEN (mst_...).".into());
    }
    let mut key: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(encoded)?)?;
    if key["api"].is_null() {
        key["api"] = json!("https://mailset.app");
    }
    Ok(key)
}

/// POST /v1/<command>. Returns Mailset's answer, a refusal included.
fn run(command: &str, input: Value, key: &Value) -> Result<Value, Box<dyn Error>> {
    let path = format!("/v1/{command}");
    // Encode once: the bytes signed have to be the bytes sent.
    let body = serde_json::to_vec(&json!({ "input": input }))?;
    let now_ms = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
    let api = key["api"].as_str().unwrap_or_default().to_string();

    let response = reqwest::blocking::Client::new()
        .post(format!("{api}{path}"))
        .headers(sign_request("POST", &path, &body, key, now_ms)?)
        .header(CONTENT_TYPE, "application/json")
        .body(body)
        .send()?;
    // A refusal is JSON too: {"ok": false, "error": {"code": ..., "message": ...}}
    Ok(serde_json::from_str(&response.text()?)?)
}

fn main() -> Result<(), Box<dyn Error>> {
    let key = load_key().unwrap_or_else(|error| {
        eprintln!("{error}");
        exit(2)
    });
    let command = env::args().nth(1).unwrap_or("grants.current".to_string());
    let answer = run(&command, json!({}), &key)?;
    println!("{}", serde_json::to_string_pretty(&answer)?);
    exit(if answer["ok"] == true { 0 } else { 1 })
}
```

Python needs the `cryptography` package, since its standard library has no ECDSA. Go needs 1.25 or later. Ruby, PHP and Java use what ships with them. Rust needs 1.88 or later and the `p256`, `sha2`, `base64`, `reqwest` and `serde_json` crates. It runs a project, not a file, so the client opens with the lines for `Cargo.toml` and the commands to run it.

## Run a command

Every command is `POST /v1/<command id>` with a JSON body, `{ "input": { … } }`. The answer is JSON:

```json
{
	"ok": true,
	"data": { "name": "Acme API", "expiresAt": 1803772800000, "mailboxes": [] }
}
```

Or a refusal, with an HTTP status to match:

```json
{
	"ok": false,
	"error": {
		"code": "forbidden",
		"message": "This app’s grant doesn’t allow that."
	}
}
```

An org's command also takes `org` beside `input`, for a person in more than one org. [Errors and limits](https://mailset.app/docs/errors) lists every code, and the [API reference](https://mailset.app/docs/api) every command.

To send an email this way, build the whole message and submit it. [Send your own MIME](https://mailset.app/docs/recipes/mime) has the code in each language.

## Commands that need a passkey

Some commands change something an attacker would want: adding a mailbox, removing a domain. With an API token they answer `403` with `step_up_required` and a `purpose`. To go ahead:

1. `POST /v1/approvals` with that `purpose` as the body. The answer has an `id` and an `approveUrl`.
2. Open `approveUrl` on a device with your passkey and approve it.
3. `GET /v1/approvals/<id>` until `state` is `approved`. It can also end `denied` or `expired`.
4. Send the command again with `"approval": "<id>"` beside `input`.

Both calls are signed like any other. An app key never meets this: nothing it can run needs a passkey.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content