---
title: "Server helpers | IdentityHound SDK"
description: "Find out who a request acts for on your server with the IdentityHound SDK's createVerifier, and keep each principal's session in an HTTP-only cookie with createSessions and errorBody."
url: "https://agentpost.tools/docs/identityhound/sdk/server"
kind: sdk
---

# Server helpers

`@agentpost-tools/identityhound-sdk/server` has the helpers for your server: `createVerifier` finds out who a request acts for, and `createSessions` and `errorBody` keep a principal’s session on your server. They take your project’s secret key, so they run only on your server.

## Check requests

Before your server acts on a request, `createVerifier` reads the request’s bearer token and asks IdentityHound who it acts for, with your secret key. It checks a session token (`agp_st_…`), an API key (`agp_ak_…`), or a delegated token (`agp_dt_…`). It doesn’t check a user token (`ut_…`), which only Agentpost’s services accept, and returns `null` for one. For a page’s request, check the principal’s session token instead: with [`serverSession`](/docs/identityhound/sdk/session-strategies.md#serversession), read it from the cookie and pass it to `verifyToken`.

```ts
import { createVerifier } from '@agentpost-tools/identityhound-sdk/server';

const verifier = createVerifier({ secretKey: key });
const who = await verifier.verifyRequest(request);
```

-   **`request`** is a Fetch API `Request`, or anything with its headers, such as Node’s `IncomingMessage`. `verifyToken(token)` checks a token you already hold.
-   **`who`** is `null` when the request has no active token: an unknown, expired, or revoked one, a user token, one too short or too long to be a token (under 16 or over 512 characters, answered with no lookup), or none. Refuse the request with a 401. Otherwise `who` names the `actor`, the principal that holds the token, and its `credential`, whose `kind` is `session`, `api_key`, or `delegated_token`; for a session or a delegated token, the `session`; for a delegated token, the delegator it acts for, `onBehalfOf`, and its `delegation`, as [Who acted](/docs/platform/concepts/principals.md#who-acted) describes; and the API key’s `restrictions`, if set, for an API key or a delegated token issued from one.
-   **Kept answers:** each answer is kept for 10 seconds by default (`cacheTtlMs`, from 0, which turns it off, to 60,000 milliseconds), and never past the session’s recorded idle or absolute expiry, or the delegation’s expiry, so a burst of requests costs one lookup. A revoked token can keep working until its kept answer expires. `clear()` forgets every kept answer, such as after signing someone out, including the answer of a lookup still running, so a session revoked at sign-out is never honored from it.
-   **Failures:** `verifyRequest` throws when IdentityHound can’t be reached, or rejects with [`secret_key_invalid`](/docs/errors.md#secret_key_invalid) when Agentpost refuses the secret key. That code means your server’s configuration, never a visitor’s ended session, so answer 503 and fix the key rather than signing anyone out.

Without the SDK, send the token to [Introspect a token](/docs/identityhound/reference/auth.md#introspect-a-token), `POST /auth/introspect`, with your secret key. An inactive token answers `{ active: false }`. Keep each answer for up to 10 seconds, keyed by a hash of the token.

## Keep sessions in a cookie

`createSessions({ secretKey, baseUrl, userTokenExpiresIn, profileFromProvider, fetch })` is IdentityHound’s side of a web app whose server keeps the session in an HTTP-only cookie: the endpoints that [`serverSession`](/docs/identityhound/sdk/session-strategies.md#serversession) posts to call it. `userTokenExpiresIn` is how long each user token lasts, from `1m` to `1h`, and `15m` by default; a user token never outlasts its session. `profileFromProvider`, off unless set, starts a principal that `completeOAuth` just created with the provider’s name and picture, as [`createIdentity`’s option](/docs/identityhound/sdk/clients.md#createidentity) of the same name does, calling as the new session. It returns:

| Method | What it does |
| --- | --- |
| `requestCode(input, visitor)` | Emails a sign-in code, `POST /auth/email-code` with the address the page sent. Resolves to `{ verificationId, resendAfter }` for the page. Rejects with `throttled` and `details.retryAfter` when too many were asked for. |
| `verifyEmailCode(input, visitor)` | Checks an emailed code, `POST /auth/email-code/verify` with the fields the page sent, and starts the session. Resolves to `{ token, expiresAt, session, signedIn }`: the token and its end go in the cookie, `session` is the new session’s record, whose `id` keys any data you keep per session, and `signedIn`, `{ principal, signedUp }`, goes to the page. |
| `completeOAuth(providerKey, input, visitor)` | Finishes an OAuth sign-in the page started, `POST /auth/oauth/:providerKey/callback` with the provider’s `code` and `state`, and starts the session. Resolves the same way. Rejects with `oauth_failed` when the flow wasn’t a sign-in. |
| `principal(sessionToken)` | Who the session signs in, `GET /me` with the session as the bearer. Resolves to the `Principal`, or `null` when there is no session or it has ended: clear the cookie then. Mints no user token, so a page that only shows who is signed in never holds a credential. Rejects when IdentityHound can’t be reached; keep the cookie then. |
| `userToken(sessionToken)` | Mints a user token with the session as the bearer. Resolves to `{ token, expiresAt }`, or `null` when there is no session or it has ended: clear the cookie then. Rejects when IdentityHound can’t be reached; keep the cookie then. |
| `signOut(sessionToken)` | Revokes the session. A session that already ended counts as signed out. Rejects when IdentityHound can’t be reached: keep the cookie, so the principal stays signed in and can try again. |

### The visitor

The optional `visitor` describes the browser signing in, as your server sees the request:

-   **`ip`:** the visitor’s IP address, sent in the `X-Agentpost-Visitor-IP` header, exported as `VISITOR_IP_HEADER` for a server that calls the API another way. IdentityHound limits code requests and verification calls per IP and records the address on the session. Without this header, your visitors share the limit for your server’s IP. Agentpost reads the header only on a request made with a secret key, so a browser can’t use it to change the address its own guesses count against, and refuses one that isn’t a single IP address with `invalid_request`. Behind a proxy or a load balancer, pass the visitor’s address that your proxy reports, never a header the visitor could have set.
-   **`userAgent`:** the browser’s `User-Agent`, recorded on the session so the principal can tell its sessions apart.
-   **`session`:** the session token the visitor’s cookie already holds. Once the new session starts, the helper asks IdentityHound to revoke the old one in the background.

### Check access before the old session ends

A server that lets only some principals in leaves `visitor.session` out, so a refused visitor keeps the session they had. It checks the new principal, then revokes whichever session loses:

```ts
const started = await sessions.verifyEmailCode(input, { ip, userAgent });
if (!(await mayUseApp(started.signedIn.principal))) {
  await sessions.signOut(started.token);
  return Response.json({ error: { code: 'forbidden' } }, { status: 403 });
}
await sessions.signOut(previousCookie);
// Set the cookie to started.token, with started.expiresAt as its end.
```

`mayUseApp` is your own check. `signOut` with no token does nothing, so this works whether or not the visitor had a session.

### Look up sessions

A server that keeps data per session, such as a phone’s push token, checks its copies with the secret key: `client.sessions.get(id)` answers one session, live or ended, with `revokedAt` once it ends, and `client.principals.sessions(id)` lists a principal’s live sessions. Follow [`session.revoked` and `auth.signed_out`](/docs/identityhound/concepts/change-feed.md#sessions-that-end) on the change feed to hear of an end as it happens. A session that runs out records no event, so keep its `expiresAt` too.

### Types

`/server` exports every type its functions take and return, such as `Session`, `Principal`, `StartedSession`, `Verified`, and `IdentityhoundApiError`, so a server imports from it alone.

### Errors

When IdentityHound refuses, such as a wrong code, a method rejects with `IdentityhoundApiError`. `errorBody(error)` turns it into IdentityHound’s standard error body, `{ error: { code, message } }` with `details` and `docs` when present. Answer the page with it at `error.status`, and the page’s sign-in shows the same message as with no server.
