
# Utilities

> Encode bytes as base64url and read them back strictly, make secure random values, and tell what kind of key a value is.

`unjwt/utils` holds the small pieces the token functions are built on, for the moments you need one on its own: putting random bytes in a URL, publishing only the public half of your keys, or checking a value before you hand it to `verify`. None of them checks a signature, so none of them can tell you a token is genuine. Every name here is also exported from `unjwt`.

## Before you start

- These functions run in any runtime with the Web Crypto API.
- Base64url is an encoding, not encryption: anyone who sees the text can decode it.
- The codec and random functions throw an `UnsecureError`, not a `JWTError`: [Handle errors](/safety/errors#the-second-error-class) explains the second class.

## Put random bytes in a URL

Make a value with `secureRandomBytes`, write it as base64url, and read it back strictly, so the only text that decodes is text you could have written:

<!-- automd:region src="../../examples/safety/utils.ts" -->

```ts [utils.ts]
import {
  base64UrlParse,
  base64UrlStringify,
  isUnsecureError,
  secureRandomBytes,
} from "unjwt/utils";

/** 32 random bytes as URL-safe text, for an OAuth `state` or a CSRF value. */
export function createState() {
  return base64UrlStringify(secureRandomBytes(32));
}

/** The bytes back, or `null` for anything but text `createState` could have written. */
export function readState(text: string | null) {
  if (text === null) return null;
  try {
    const bytes = base64UrlParse(text, { returnAs: "bytes" });
    return bytes.length === 32 ? bytes : null;
  } catch (error) {
    if (isUnsecureError(error, "MALFORMED")) return null;
    throw error;
  }
}
```

<!-- /automd -->

- **Secure random**: `secureRandomBytes(length)` returns that many bytes from the platform's cryptographic generator. Use it for salts, state values and raw secrets, never `Math.random()`.
- **URL-safe**: base64url uses `-` and `_` instead of `+` and `/` and writes no `=`, so the text goes into a URL, a cookie or a header as it is.
- **Strict reading**: `base64UrlParse` throws `MALFORMED` for anything but the one canonical spelling of some bytes. Two texts that decode to the same bytes are how a check gets bypassed, so there is no lenient mode.
- **Length check**: a clean decode proves the text is well formed, not that it holds 32 bytes.

## Encode and decode

There are two pairs, one per alphabet. Each `Stringify` takes a string, which it encodes as UTF-8 first, or a `Uint8Array`. Each `Parse` takes the encoded string and returns UTF-8 text, or the bytes with `{ returnAs: "bytes" }`:

```ts
import { base64Parse, base64Stringify, base64UrlParse, base64UrlStringify } from "unjwt/utils";

base64UrlStringify("hello"); // "aGVsbG8"
base64UrlStringify(new Uint8Array([255, 255])); // "__8"
base64Stringify("hello"); // "aGVsbG8="

base64UrlParse("aGVsbG8"); // "hello"
base64UrlParse("__8", { returnAs: "bytes" }); // Uint8Array(2) [255, 255]
base64Parse("aGVsbG8="); // "hello"
```

| Function                                | Alphabet                                                                                             | Padding                            |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `base64UrlStringify` / `base64UrlParse` | URL-safe `-` `_` ([RFC 7515 §2](https://www.rfc-editor.org/rfc/rfc7515#section-2))                   | never written, refused when read   |
| `base64Stringify` / `base64Parse`       | standard `+` `/` ([RFC 4648 §4](https://www.rfc-editor.org/rfc/rfc4648#section-4)), as in PEM bodies | always written, required when read |

Ask for bytes whenever the value isn't text: `base64UrlParse("__8")` throws, because the bytes `ff ff` aren't UTF-8.

## Tell what kind of key a value is

The type guards return `true` or `false` and never throw, so they're safe on anything, including parsed JSON. Here they keep a JWK Set endpoint from ever publishing a secret:

<!-- automd:region src="../../examples/safety/utils.ts" name="guards" -->

```ts [utils.ts]
import type { JWK, JWKSet } from "unjwt/jwk";
import { isJWKSet, isPublicJWK } from "unjwt/utils";

/** The body of `/.well-known/jwks.json`: only the keys that are safe to publish. */
export function publishableKeys(stored: unknown): JWKSet {
  if (!isJWKSet(stored)) throw new TypeError("Stored keys are not a JWK Set.");
  return { keys: stored.keys.filter((key): key is JWK => isPublicJWK(key)) };
}
```

<!-- /automd -->

| Guard                    | `true` for                                                                                     |
| ------------------------ | ---------------------------------------------------------------------------------------------- |
| `isJWK(value)`           | A JWK whose `kty` is `oct`, `RSA`, `EC` or `OKP`.                                              |
| `isJWKSet(value)`        | An object with a `keys` array.                                                                 |
| `isSymmetricJWK(value)`  | An `oct` JWK with its `k`: a shared secret.                                                    |
| `isAsymmetricJWK(value)` | An `RSA`, `EC` or `OKP` JWK, private or public.                                                |
| `isPrivateJWK(value)`    | An asymmetric JWK that holds its private part `d`.                                             |
| `isPublicJWK(value)`     | An asymmetric JWK with its public members and no private part: the one that's safe to publish. |
| `isCryptoKey(value)`     | A `CryptoKey`.                                                                                 |
| `isCryptoKeyPair(value)` | An object whose `publicKey` and `privateKey` are both `CryptoKey`s.                            |

::warning
`!isPrivateJWK(key)` doesn't mean safe to publish: an `oct` key is a secret, and `isPrivateJWK` returns `false` for it. Filter with `isPublicJWK`.
::

`assertCryptoKey(value)` is the one guard that throws: `ERR_JWK_INVALID` when the value isn't a `CryptoKey`.

## When it fails

| Situation                                                                               | What happens                                                     |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| Text holds a character outside the alphabet, whitespace included                        | `UnsecureError` `MALFORMED`, naming the character and its index. |
| Wrong `=` padding, a length that can't hold whole bytes, or bits set past the last byte | `UnsecureError` `MALFORMED`.                                     |
| A string result requested, and the bytes aren't UTF-8                                   | `UnsecureError` `MALFORMED`. Pass `{ returnAs: "bytes" }`.       |
| A value that isn't a string (for `Parse`) or a string or `Uint8Array` (for `Stringify`) | `UnsecureError` `INVALID_TYPE`.                                  |
| `secureRandomBytes` with a negative, fractional or too large length                     | `UnsecureError` `OUT_OF_RANGE`.                                  |

## Going further

- **Untrusted JSON**: `safeJsonParse`, `sanitizeObject` and `sanitizeObjectCopy` parse or clean JSON without the `__proto__`, `prototype` and `constructor` keys that cause prototype pollution. The token functions already parse every header and payload this way.
- **Digests**: `digestUrl(data, hash?)` returns the base64url SHA-256 (or `"SHA-384"`, `"SHA-512"`) of text or bytes, the value a DPoP `ath` holds.
- **Claims and durations**: `validateJwtClaims` and `computeDurationInSeconds` are covered in [Validate claims](/safety/claims#check-claims-that-arrived-another-way).
- **Allowlists**: `inferJWSAllowedAlgorithms(key)` and `inferJWEAllowedAlgorithms(key)` return the algorithms a key stands for, the list `verify` and `decrypt` use when you pass no `algorithms`, or `undefined` when the key doesn't say.
- **`unjwt/internal`**: an entry for tooling and tests, with no stability promise: any export can change in any release.
