# jwt

`jwt` signs and checks JSON Web Tokens (RFC 7519) with HMAC: HS256 and HS512. It is the part that is easy to get wrong: the key decides the algorithm, never the token, so `alg: none` and a swap to another algorithm are refused; the token's `kid` picks the key, so an old key keeps working while a new one takes over; the signature is compared in constant time; and the claims are read only after the signature is checked. It is written in Agentica over the `OpenSSL.HMAC`, `Base64` and `JSON` builtins, with no C.

It has no public-key algorithms (RS256, ES256, EdDSA) and no JWKS, since Agentica's standard library has no asymmetric signatures yet. Use it where the same service, or services that share a secret, both sign and check the tokens: access tokens of your own server, a signed request kept across a sign-in, a link in an email.

## Install

Needs Agentica 0.40.0 or later. Add it in a project with an `agentica.toml`, with its prefixed tag and its folder as `--subdir`:

```sh
agentica add jwt agentica-lang/packages --tag jwt-0.1.0 --subdir jwt
```

That writes this line of `agentica.toml`, and the entry of `agentica.lock`:

```toml
[dependencies]
jwt = { git = "https://github.com/agentica-lang/packages", tag = "jwt-0.1.0", subdir = "jwt" }
```

## Example

`encode` signs claims under a key, and `decode` checks the token and gives the claims back. The time is passed in, in milliseconds, so a test can fix it; a program passes `Time.now_ms()`.

```agentica
import Jwt from "pkg/jwt/jwt"

# A demo key; make yours with OpenSSL.Random.random_bytes(32) and keep it out of the code.
DEMO_SECRET = Base64.urlsafe_decode64("KtLmK9zCqZO7R_SmDO2hDLiT2NsfGEJ1NpcvXQ7zSN8").unwrap!

def main() -> Void
  key = Jwt.hs256(DEMO_SECRET, "k1").unwrap!
  claims = JSON.parse("{\"sub\":\"agent:7\",\"exp\":1900000000}").unwrap!
  token = Jwt.encode(claims, key).unwrap!
  puts(token)
  puts(Jwt.decode(token, [key], 1_800_000_000_000).unwrap!)
  puts(kind(Jwt.decode(token, [key], 1_900_000_030_000)))
end

def kind(result: Result[JSON.Value]) -> String
  case result
    ok(_) -> "accepted"
    error(e) -> e.kind
  end
end
```

```output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImsxIn0.eyJzdWIiOiJhZ2VudDo3IiwiZXhwIjoxOTAwMDAwMDAwfQ.g6rZHthOmb_JS-96vuHukZwKGSboKctr8ElnDlyjm5s
{"sub":"agent:7","exp":1900000000}
jwt.expired
```

## Secrets

A secret is random bytes, at least as long as the hash: 32 bytes for HS256 and 64 for HS512 (RFC 7518 §3.2). Make one with `OpenSSL.Random.random_bytes(32)` (the hash of a password is not a secret: it passes the length check with the strength of the password), keep it out of the code, for example as base64url text in an environment variable, and read it back with `Base64.urlsafe_decode64`. A `Key` holds its secret in a function, so a key cannot be printed, compared or written as JSON: a log line or an error report never shows it.

## Rotating keys

Give each key a `kid`. `encode` writes it in the header, and `decode` picks the key of that `kid` from its list. To rotate, sign with the new key and keep the old one in the list of `decode` until the last token it signed has expired, then drop it. A token with no `kid` takes the key with no `kid`, and a key with a `kid` takes only tokens that name it; two keys with the same `kid` in one list are refused.

```agentica
import Jwt from "pkg/jwt/jwt"

# Demo keys; make yours with OpenSSL.Random.random_bytes and keep them out of the code.
OLD_SECRET = Base64.urlsafe_decode64("EKT2ECKgxVXRdezg-DcyIed8ClydPS0r2PlKwb-3Bk4").unwrap!
NEW_SECRET = Base64.urlsafe_decode64("JwvyCRpjrrmwWtFlSNFliEmS2AmTjrikTm7cIc85x4CkNf22KB7mzBr1Z9EoVAgdH-tODIRiemoxww_xeOphrw").unwrap!

def main() -> Void
  old = Jwt.hs256(OLD_SECRET, "2026-11").unwrap!
  new = Jwt.hs512(NEW_SECRET, "2026-12").unwrap!
  claims = JSON.parse("{\"sub\":\"ana\",\"exp\":1900000000}").unwrap!
  from_old = Jwt.encode(claims, old).unwrap!
  from_new = Jwt.encode(claims, new).unwrap!
  keys = [new, old]
  puts(kind(Jwt.decode(from_old, keys, 1_800_000_000_000)))
  puts(kind(Jwt.decode(from_new, keys, 1_800_000_000_000)))
  puts(kind(Jwt.decode(from_old, [new], 1_800_000_000_000)))
end

def kind(result: Result[JSON.Value]) -> String
  case result
    ok(_) -> "accepted"
    error(e) -> e.kind
  end
end
```

```output
accepted
accepted
jwt.key
```

## Untrusted tokens

`decode` treats the token as hostile. In order, it refuses:

- a token longer than `max_bytes` (8192 by default), before any other work;
- a token that is not three parts of unpadded base64url (no `=`, no `+` or `/`, no spare bits), or whose header or payload is not a JSON object, or repeats a member at its top level (nested objects are not checked, since only the signer writes them), or has `crit` in the header;
- a token whose `kid` names no key of the list, or names two;
- a token whose `alg` is not the one of its key, `none` included;
- a signature that does not match, compared in constant time;
- and then the claims, which are read only now, and the header `typ`: see `Rules`.

An error never holds the token or the secret, so it can be logged. Do not send the kind or the message back to the sender: before the signature is checked they tell whether a `kid` exists, so answer every failure the same way (an HTTP 401, say).

## API

### `Jwt.hs256(secret, kid = "") -> Result[Key]`

A key that signs with HMAC-SHA256. `kid` names it in the header of its tokens; `""` leaves `kid` out. A secret of fewer than 32 bytes is an `argument` error.

```agentica
import Jwt from "pkg/jwt/jwt"

def main() -> Void
  puts(Jwt.hs256(OpenSSL.Random.random_bytes(32)).ok?)
  puts(Jwt.hs256("password".bytes).message)
end
```

```output
true
jwt: an HS256 secret needs at least 32 bytes
```

### `Jwt.hs512(secret, kid = "") -> Result[Key]`

A key that signs with HMAC-SHA512. A secret of fewer than 64 bytes is an `argument` error.

```agentica
import Jwt from "pkg/jwt/jwt"

def main() -> Void
  key = Jwt.hs512(OpenSSL.Random.random_bytes(64), "k2").unwrap!
  puts(Jwt.algorithm(key))
  puts(Jwt.kid(key))
end
```

```output
Algorithm.HS512
k2
```

### `Jwt.encode(claims, key, typ = "JWT") -> Result[String]`

The compact token of `claims`, a JSON object, signed with `key`. The header holds `alg`, `typ` (`""` leaves it out) and the key's `kid` when it has one. It adds no claim: put `exp`, and `iss`, `aud`, `iat` or `jti` when you need them, in `claims`. Claims that are not a JSON object are an `argument` error.

```agentica
import Jwt from "pkg/jwt/jwt"

# A demo key; make yours with OpenSSL.Random.random_bytes(32) and keep it out of the code.
DEMO_SECRET = Base64.urlsafe_decode64("KtLmK9zCqZO7R_SmDO2hDLiT2NsfGEJ1NpcvXQ7zSN8").unwrap!

def main() -> Void
  key = Jwt.hs256(DEMO_SECRET).unwrap!
  claims = JSON.parse("{\"iss\":\"https://auth.test\",\"exp\":1900000000}").unwrap!
  token = Jwt.encode(claims, key, "at+jwt").unwrap!
  header = Base64.urlsafe_decode64(token.split(".")[0]).unwrap!
  puts(String.from_bytes(header).unwrap!)
  puts(Jwt.encode(JSON.parse("[1]").unwrap!, key).message)
end
```

```output
{"alg":"HS256","typ":"at+jwt"}
jwt: the claims must be a JSON object
```

### `Jwt.decode(token, keys, now_ms, rules = Rules()) -> Result[JSON.Value]`

The claims of `token` when one of `keys` signed it and it meets `rules` at `now_ms`, the time in milliseconds since the epoch. The token's `kid` picks the key, and a token with no `kid` takes the key with no `kid`. Each failure is an error with one of the kinds of [Errors](https://www.agentica-lang.com/packages/jwt/index.md#errors).

```agentica
import Jwt from "pkg/jwt/jwt"

# A demo key; make yours with OpenSSL.Random.random_bytes(32) and keep it out of the code.
DEMO_SECRET = Base64.urlsafe_decode64("KtLmK9zCqZO7R_SmDO2hDLiT2NsfGEJ1NpcvXQ7zSN8").unwrap!

def main() -> Void
  key = Jwt.hs256(DEMO_SECRET, "k1").unwrap!
  claims = JSON.parse("{\"sub\":\"ana\",\"exp\":1900000000}").unwrap!
  token = Jwt.encode(claims, key).unwrap!
  forged = token.split(".")[0] + "." + Base64.urlsafe_encode64("{\"sub\":\"admin\"}".bytes, false) + ".x"
  puts(kind(Jwt.decode(token, [key], 1_800_000_000_000)))
  puts(kind(Jwt.decode(forged, [key], 1_800_000_000_000)))
  unsigned = Base64.urlsafe_encode64("{\"alg\":\"none\",\"kid\":\"k1\"}".bytes, false)
  puts(kind(Jwt.decode(unsigned + "." + token.split(".")[1] + ".", [key], 1_800_000_000_000)))
end

def kind(result: Result[JSON.Value]) -> String
  case result
    ok(_) -> "accepted"
    error(e) -> e.kind
  end
end
```

```output
accepted
jwt.malformed
jwt.algorithm
```

### `Jwt.Rules`

What `decode` checks besides the signature. Each field has a default, so a caller names only what differs.

| Field | Default | What it checks |
|---|---|---|
| `issuer` | `none` | `iss` must be this text. |
| `audience` | `none` | `aud` must be this text, or a list that holds it. With `none`, a token that has `aud` is refused (RFC 7519 §4.1.3). |
| `typ` | `none` | The header `typ` must be this, without case and with an optional `application/` in front, so `at+jwt` takes `application/AT+JWT`. With `none`, any `typ` passes, so tokens of two purposes signed with one key are interchangeable. |
| `leeway_s` | `30` | The seconds of clock skew allowed for `exp`, `nbf` and `iat`. |
| `max_bytes` | `8192` | The longest token, in bytes. |
| `require_exp` | `true` | A token with no `exp` is refused. |

`exp`, `nbf` and `iat` are numbers of seconds, integer or not. A token has expired once `now >= exp + leeway_s`; it is not valid yet while `nbf` or `iat` is later than `now + leeway_s`. A time that is not a number, or an integer too large for an `Int`, is a `jwt.claim` error. A service that checks its own access tokens should set `issuer`, `audience` and `typ`, so a token made for another purpose with the same key is refused.

```agentica
import Jwt from "pkg/jwt/jwt"

# A demo key; make yours with OpenSSL.Random.random_bytes(32) and keep it out of the code.
DEMO_SECRET = Base64.urlsafe_decode64("KtLmK9zCqZO7R_SmDO2hDLiT2NsfGEJ1NpcvXQ7zSN8").unwrap!

def main() -> Void
  key = Jwt.hs256(DEMO_SECRET).unwrap!
  rules = Jwt.Rules(issuer: some("https://auth.test"), audience: some("https://api.test/mcp"), typ: some("at+jwt"))
  claims = JSON.parse("{\"iss\":\"https://auth.test\",\"aud\":\"https://api.test/mcp\",\"exp\":1900000000}").unwrap!
  token = Jwt.encode(claims, key, "at+jwt").unwrap!
  puts(kind(Jwt.decode(token, [key], 1_800_000_000_000, rules)))
  other = Jwt.encode(claims, key).unwrap!
  puts(kind(Jwt.decode(other, [key], 1_800_000_000_000, rules)))
end

def kind(result: Result[JSON.Value]) -> String
  case result
    ok(_) -> "accepted"
    error(e) -> e.kind
  end
end
```

```output
accepted
jwt.claim
```

### `Jwt.algorithm(key) -> Algorithm` and `Jwt.kid(key) -> String`

The algorithm a key signs with and its `kid` (`""` for none), as the `hs512` example above shows.

### `Jwt.Key` and `Jwt.Algorithm`

A `Key` has only private fields, so its secret, its algorithm and its `kid` cannot be changed apart: make one with `hs256` or `hs512`, and read it with `Jwt.algorithm(key)` (a `Jwt.Algorithm`: `HS256` or `HS512`) and `Jwt.kid(key)`.

### Errors

`decode` fails with one of these kinds, which are constants of the module too (`Jwt.EXPIRED`). Branch on the kind, never on the message.

| Kind | When |
|---|---|
| `jwt.malformed` | Too long, not three parts of base64url, not JSON objects, a repeated member, `crit`, a `kid` or `typ` that is not text. |
| `jwt.key` | No key of the list has the token's `kid`, or two have it. |
| `jwt.algorithm` | The token's `alg` is not the one of its key (`none` included). |
| `jwt.signature` | The signature does not match. |
| `jwt.expired` | `exp` has passed. |
| `jwt.not_yet_valid` | `nbf` or `iat` is in the future. |
| `jwt.claim` | No `exp` when it is required, a time that is not a number, `iss`, `aud` or `typ` is not the one of the rules, or an `aud` when the rules name no audience. |

`hs256`, `hs512` and `encode` fail with `argument`, and so does `decode` when `leeway_s` or `max_bytes` is negative.

## Tests

The specs check the example of RFC 7515 A.1 (the one of RFC 7519 §3.1) with its key, and run against `specs/fixtures/jwt_peer.py`, a JWT on Python's standard library (`hmac`, `hashlib`, `base64`, `json`) that shares nothing with the package. The peer checks the tokens of the package, and signs tokens the package must accept or refuse: `alg: none`, an algorithm swap, a lowercase `alg`, an unknown `kid`, a repeated member, `crit`, and a changed signature or payload, padding, a spare bit set, the standard alphabet, two or four parts, expired and future tokens, a wrong issuer, audience or `typ`, and a token over `max_bytes`.

## Pages in this section


