> ## Documentation Index
> Fetch the complete documentation index at: https://docs.near-intents.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Workload Identity

> Let a CI job, cloud workload or server act under a grant without a long-lived secret: OIDC identity tokens from GitHub, GitLab, Google Cloud, AWS, Kubernetes, Entra ID or Vercel, or a private key that never leaves the workload

A [grant token](https://docs.near-intents.org/integration/agent-api/grants.md) (`ngt_…`) is a bearer secret: whoever holds it can act for the agent, within its policy, for up to 365 days. That is fine for a backend that already keeps secrets. A CI job, a cloud function or a server often has something better: its platform vouches for it with a short-lived identity token, or it can hold a private key that never leaves it.

With **workload identity**, the owner signs that identity into the grant instead of a token's fingerprint. The workload then proves who it is, trades the proof for a short-lived session token, and acts as before. No long-lived secret sits on the workload or crosses the wire.

> [!NOTE]
>
> **At a glance**
>
> * **Credentials:** a grant's `credential` is one of three things the owner signs: a token's SHA-256 commitment (as before), `{ type: "oidc", issuer, claims }`, or `{ type: "public_key", jwk }`. Grant views report which as `credential_type`: `token`, `oidc` or `public_key`.
> * **Exchange:** `POST /v1/agents/{agent_id}/grants/token` trades the workload's OIDC identity token, or a single-use assertion signed with its key, for an `ngs_…` session token. Send it as `X-Grant-Token`.
> * **Sessions:** 15 minutes by default (at most 60), never past the grant. Revoking the grant ends them all.
> * **Per request:** a `public_key` grant can sign every request and send `X-Grant-Proof` instead, so no bearer token exists at all.
> * **Still needed:** your partner API key on every call, the exchange included. The owner's policy, timelock, approvals and budget apply exactly as before.

> [!NOTE]
>
> Workload identity needs an API with workload identity federation. In the TypeScript SDK, `exchangeGrantToken`, `forGrantSession`, `forGrantProof` and the key helpers are in SDK 0.9.2 and later. Existing token grants keep working unchanged.

***

## Choose a credential

| `credential` | The workload holds | It sends | Use it for |
| - | - | - | - |
| SHA-256 hex of an `ngt_…` token | The token, for the grant's lifetime | The token, as `X-Grant-Token` | A quick start, or a backend that already keeps secrets |
| `{ type: "oidc", issuer, claims }` | Nothing. Its platform issues short-lived identity tokens. | An `ngs_…` session token, as `X-Grant-Token` | GitHub Actions, GitLab CI, Google Cloud, AWS, Kubernetes, Microsoft Entra ID, Vercel |
| `{ type: "public_key", jwk }` | A private key that never leaves it: a file, a TPM, an HSM or a cloud KMS | An `ngs_…` session token as `X-Grant-Token`, or a proof it signs for each request as `X-Grant-Proof` | Self-hosted servers, VPS, bare metal, laptops |

* **The platform already issues identity tokens?** Use `oidc`. There is no key or token to store anywhere. See [OIDC grants](#oidc-grants).
* **No identity provider?** Use `public_key`. Generate the key where the workload runs and keep it there. See [Key-bound grants](#key-bound-grants).
* **Want no bearer token at all?** Use `public_key` and [sign every request](#sign-every-request). A proof is good for one request and cannot be replayed.
* **Many requests, and a key that is slow or billed per signature (a cloud KMS)?** Use a session: one signature covers 15 minutes.
* **A backend that is the only caller, and the simplest setup?** A [token grant](https://docs.near-intents.org/integration/agent-api/grants.md) is still the right choice.

Only the credential changes. A federated grant has the same label, expiry, 50-grant limit and revocation as any grant, and it follows the same [policy](https://docs.near-intents.org/integration/agent-api/policies-and-limits.md). Idempotency keys are scoped to the grant, never to the token or session.

***

## How it works

**1. The owner signs the binding**

Your backend generates a `grant_issue` intent whose `credential` names the identity, and the owner signs it. For `oidc`, the signed message names the issuer, the audience its tokens must carry (the API fills it in; only Entra ID grants name it) and the claims that pin one workload. For `public_key`, it names the key.

**2. The workload gets a proof of identity**

An identity token from its platform for exactly the grant's audience, or an assertion it signs with its key. Both are JWTs that live minutes.

**3. It exchanges the proof for a session**

`POST /v1/agents/{agent_id}/grants/token` verifies the signature, issuer, audience and lifetime, matches the pinned claims to a live grant, and returns an `ngs_…` session token.

**4. It acts with the session**

The workload sends the session token as `X-Grant-Token`, exactly where a grant token goes, and exchanges again shortly before `expires_at`.

```mermaid theme={null}
sequenceDiagram
  participant O as Owner wallet
  participant A as Agent API
  participant W as Workload
  participant P as Its platform (GitHub, GCP…)
  O->>A: grant_issue signed over { issuer, audience, claims } or { jwk }
  W->>P: identity token for audience {API URL}/v1/agents/{agent_id}
  P-->>W: JWT that lives minutes
  W->>A: POST /v1/agents/{agent_id}/grants/token
  A->>A: verify signature, iss, aud, lifetime; match the signed claims
  A-->>W: ngs_… (15 minutes, never past the grant)
  W->>A: POST …/transfer with X-Grant-Token: ngs_…
```

The policy, timelock, owner approvals, USD budget, idempotency and dispatch commitment see the grant, never the credential.

> [!WARNING]
>
> Federation replaces only the grant token. Your partner API key is still required on every call, the exchange included. It identifies the partner, carries the rate limits and quotas, and revoking it stops the requests it sends. Give each workload its own key from the [partner portal](https://partners.near-intents.org/), so its limits and its revocation are its own. See [Partner API Key](https://docs.near-intents.org/integration/agent-api/authentication.md).

***

## Issue a federated grant

Issuing works like [any grant](https://docs.near-intents.org/integration/agent-api/grants.md#issue-a-grant): generate a `grant_issue` intent, have the owner sign `intent.payload`, submit it, then read the status. Only `credential` differs.

```bash cURL theme={null}
curl -X POST "$NEAR_INTENTS_AGENT_API_URL/v1/generate-intent" \
  -H "X-API-Key: $NEAR_INTENTS_AGENT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "grant_issue",
    "agent_id": "'"$AGENT_ID"'",
    "label": "Deploy bot",
    "credential": {
      "type": "oidc",
      "issuer": "https://token.actions.githubusercontent.com",
      "claims": {
        "repository_owner_id": "1234567",
        "repository_id": "7654321",
        "environment": "production"
      }
    },
    "expires_at": "2027-01-01T00:00:00Z"
  }'
```

```typescript TypeScript SDK theme={null}
const generated = await api.generateIntent({
  type: "grant_issue",
  agent_id: agentId,
  label: "Deploy bot",
  credential: {
    type: "oidc",
    issuer: "https://token.actions.githubusercontent.com",
    claims: {
      repository_owner_id: "1234567",
      repository_id: "7654321",
      environment: "production",
    },
  },
  expires_at: new Date(Date.now() + 30 * 24 * 3600 * 1000).toISOString(),
});
// The owner signs generated.intent.payload. See Owner Signing → The signing flow.
```

* **Show `preview.summary` to the owner.** It names everything the grant trusts: the issuer's exact URL, the pinned claims, a signed audience (Entra ID only) and the thumbprint of each signed issuer key. For example: `workloads of https://token.actions.githubusercontent.com (GitHub Actions) with ref=refs/heads/main, repository_id=…, repository_owner_id=…`.
* **Keep `grant_id`.** When the status is `SUCCESS`, `details.grant.grant_id` is the new grant. A key-bound workload signs it into every proof.
* **Signed text is ASCII.** Claim names and values are printable ASCII, like the label, because some wallets re-encode other characters in a signed message.
* **The API checks the credential before the owner signs it.** A credential that could never exchange, such as an untrusted issuer, missing required claims or a weak key, is refused at `generate-intent` with `grant_credential_invalid` (400). `submit-intent` checks the signed credential again.

```bash cURL theme={null}
curl "$NEAR_INTENTS_AGENT_API_URL/v1/agents/$AGENT_ID/grants" \
  -H "X-API-Key: $NEAR_INTENTS_AGENT_API_KEY"
```

```typescript TypeScript SDK theme={null}
const grants = await api.listGrants(agentId);
for (const grant of grants)
  console.log(grant.grant_id, grant.credential_type, grant.label); // token, oidc or public_key
```

The grant's `owner_message.credential` holds exactly what the owner signed: the commitment string for a token grant, or the `oidc` or `public_key` object. Revoke a federated grant with `grant_revoke`, like any grant.

***

## OIDC grants

The API trusts the issuers below. The list is part of the server and is attested with it: no request or setting adds an issuer or changes where its keys come from. Any other issuer works only when the owner signs its public keys into the grant (see [Kubernetes](#kubernetes)).

| Platform | `issuer` | Must pin | And one of | Longest lifetime accepted |
| - | - | - | - | - |
| [GitHub Actions](#github-actions) | `https://token.actions.githubusercontent.com` | `repository_owner_id`, `repository_id` | `ref`, `environment`, `job_workflow_ref`, `workflow_ref` | 1 hour |
| [GitLab CI](#gitlab-ci) (gitlab.com) | `https://gitlab.com` | `namespace_id`, `project_id`, and `ref_type` whenever `ref` is pinned | `ref`, `environment`, `ci_config_ref_uri` | 1 day |
| [Google Cloud](#google-cloud) | `https://accounts.google.com` | `sub` (the service account's unique id) | None | 1 hour |
| [AWS IAM](#aws) (outbound identity federation) | `https://<uuid>.tokens.sts.global.api.aws`, one per account | `sub` (the role ARN) | None | 1 hour |
| [Amazon EKS](#kubernetes) | `https://oidc.eks.<region>.amazonaws.com/id/<id>` or `https://oidc-eks.<region>.api.aws/id/<id>` | `sub`, `/kubernetes.io/serviceaccount/uid` | None | 1 day |
| [Google Kubernetes Engine](#kubernetes) | `https://container.googleapis.com/v1/projects/<p>/locations/<l>/clusters/<c>` | `sub`, `/kubernetes.io/serviceaccount/uid` | None | 1 day |
| [Azure Kubernetes Service](#kubernetes) | `https://<region>.oic.prod-aks.azure.com/<tenant>/<cluster>/` | `sub`, `/kubernetes.io/serviceaccount/uid` | None | 1 day |
| [Microsoft Entra ID](#microsoft-entra-id) | `https://login.microsoftonline.com/<tenant>/v2.0` or `https://sts.windows.net/<tenant>/` | `oid` (the identity's object id) | None | 1 day |
| [Vercel](#vercel) | `https://oidc.vercel.com/<team_slug>` | `owner_id`, `project_id` | `environment` | 12 hours |
| [Any other issuer](#kubernetes), such as a self-hosted Kubernetes cluster | Any `https` issuer | `sub` (for a cluster, `/kubernetes.io/serviceaccount/uid` too) | None | 1 day |

"Must pin" claims are required in every grant for that issuer. "And one of" means at least one more claim from the list. The last column is the longest `exp - iat` the API accepts, not a promise about what a platform issues.

> [!NOTE]
>
> No platform has been tested live. The issuer settings follow each vendor's documentation. Not yet confirmed: the GKE key host, the EKS dual-stack key host (`oidc-eks.<region>.api.aws`), GitHub's token lifetime and the Entra managed identity token lifetime. A wrong host fails closed with `issuer_unavailable`. Try an exchange on your own platform before you depend on it.

### Pinning claims

A shared issuer signs tokens for every one of its customers: any repository on GitHub can get a token from GitHub's issuer. So a grant pins **immutable ids**, never names. A repository or organization can be renamed, and its old name registered by someone else.

* `claims` holds 1 to 16 entries. Each value is a printable-ASCII string compared exactly with the token's claim. A number or boolean compares as its JSON text (`4242`, `true`).
* A plain name pins a top-level claim (`repository_id`). A JSON Pointer (RFC 6901), at most four levels deep, pins a nested one: `/kubernetes.io/serviceaccount/uid`. Inside a name, `~1` stands for `/`, so AWS's account is `/https:~1~1sts.amazonaws.com~1/aws_account`.
* A claim the token does not state, or states as an array or object, never matches. Every pinned claim must match, and you may pin more than the issuer requires.
* `iss`, `aud`, `exp`, `nbf`, `iat` and `jti` are checked by the API and cannot be pinned.
* For GitHub and GitLab, also pin a branch, an environment or a workflow. Prefer `environment` with protection rules for production: reviewers gate it.
* GitLab's `ref` is a short name (`main`) that a branch and a tag can share, so pinning it needs `ref_type` (`branch` or `tag`). GitHub's `ref` is already the full ref (`refs/heads/main`).

An identity token must:

* be signed by one of the issuer's keys (or the owner-signed keys); `none` and HMAC algorithms never verify;
* carry `iss` equal to the issuer and `aud` equal to the grant's audience;
* carry `iat` and `exp`, live no longer than the table allows and be current (30 seconds of clock skew);
* match every pinned claim.

A token may be exchanged more than once while it lives, because platforms cache them. Its audience binds it to this API and one agent, so no other service can replay it here.

### The audience

The audience is `{API URL}/v1/agents/{agent_id}`: `https://api.agentsonintents.com/v1/agents/<agent_id>` on the hosted API. It has two sides:

* **In the grant: leave `audience` out.** For every issuer except Microsoft Entra ID, the API fills it in when it builds the intent, and it refuses an explicit `audience` (`grant_credential_invalid`: "This API chooses the audience for this issuer's tokens; leave audience out."). The owner signs the audience the API chose.
* **In the workload: request the token for exactly this audience.** That is the value your platform's token request takes (`audience` for GitHub, `aud` for a GitLab ID token, `audience` for a Kubernetes projected token). `oidcGrantAudience` builds it.

[Microsoft Entra ID](#microsoft-entra-id) is the one exception: its grant **must** name `audience`, because Entra issues tokens only for audiences registered in the tenant.

```typescript theme={null}
import { DEFAULT_BASE_URL, oidcGrantAudience } from "@near-intents-agent-api/sdk";

// For the workload, when it requests its identity token. Not part of the grant.
const audience = oidcGrantAudience(DEFAULT_BASE_URL, agentId);
// "https://api.agentsonintents.com/v1/agents/<agent_id>"
```

> [!WARNING]
>
> The audience is the URL the API publishes as its own (`servers[0]` in its OpenAPI document). An alias that reaches the same host does not match. If a deployment's public URL ever changes, every OIDC grant signed for the old audience stops working and must be issued again.

### GitHub Actions

Let the job request an identity token with `id-token: write`, and name an environment so the grant can pin it.

```yaml theme={null}
permissions:
  id-token: write # lets the job request an OIDC token
jobs:
  act:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - run: node act.ts
        env:
          AGENT_ID: ${{ vars.AGENT_ID }}
          NEAR_INTENTS_AGENT_API_KEY: ${{ secrets.NEAR_INTENTS_AGENT_API_KEY }}
```

The grant pins the repository's and owner's numeric ids and the environment: `{ "type": "oidc", "issuer": "https://token.actions.githubusercontent.com", "claims": { "repository_owner_id": "…", "repository_id": "…", "environment": "production" } }`. Read the ids from `GET https://api.github.com/repos/{owner}/{repo}` (`owner.id` and `id`).

```typescript act.ts theme={null}
import { createAgentApi, DEFAULT_BASE_URL, oidcGrantAudience } from "@near-intents-agent-api/sdk";

const agentId = process.env.AGENT_ID!;
const api = createAgentApi({ apiKey: process.env.NEAR_INTENTS_AGENT_API_KEY! });

async function githubIdentityToken(audience: string): Promise<string> {
  const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL!);
  url.searchParams.set("audience", audience);
  const response = await fetch(url, {
    headers: { Authorization: `bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` },
  });
  if (!response.ok) throw new Error(`GitHub refused the identity token: ${response.status}`);
  return ((await response.json()) as { value: string }).value;
}

const bot = api.forGrantSession(agentId, {
  subjectToken: () => githubIdentityToken(oidcGrantAudience(DEFAULT_BASE_URL, agentId)),
});
await bot.transfer(agentId, { asset: "nep141:wrap.near", amount: "1", recipient: "bob.near" });
```

### GitLab CI

Declare an ID token for the job with this API's audience. GitLab puts it in the variable you name.

```yaml theme={null}
act:
  id_tokens:
    NEAR_INTENTS_ID_TOKEN:
      aud: https://api.agentsonintents.com/v1/agents/<agent_id>
  script:
    - node act.ts # reads $NEAR_INTENTS_ID_TOKEN
```

The grant pins `namespace_id` and `project_id` (numeric ids), and one of `ref` (with `ref_type`), `environment` or `ci_config_ref_uri`. A GitLab ID token lives for its job's timeout (five minutes when none is set). Tokens up to a day are accepted, so a job whose timeout exceeds a day cannot exchange.

### Google Cloud

From Compute Engine, Cloud Run, GKE Workload Identity or any service account you can impersonate, ask the metadata server for an identity token:

```bash theme={null}
curl -sSf -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://api.agentsonintents.com/v1/agents/$AGENT_ID&format=full"
```

The grant pins `sub`, the service account's **unique id** (`gcloud iam service-accounts describe <email> --format='value(uniqueId)'`). A grant that pins `email` alone is refused: a deleted account's email can be reused, its unique id cannot.

### AWS

Turn on outbound identity federation in IAM (Account settings). It shows the account's issuer URL. The workload's role then calls `sts:GetWebIdentityToken` on a regional STS endpoint:

```bash theme={null}
aws sts get-web-identity-token --region us-east-1 \
  --audience "https://api.agentsonintents.com/v1/agents/$AGENT_ID" \
  --signing-algorithm RS256 --duration-seconds 900
```

The grant: `{ "type": "oidc", "issuer": "https://<uuid>.tokens.sts.global.api.aws", "claims": { "sub": "arn:aws:iam::123456789012:role/agent" } }`. This works wherever the workload has AWS credentials: Lambda, EC2, ECS and EKS.

The issuer pins the account and `sub` pins the role's name. A role deleted and recreated with the same name in the same account matches the grant, so revoke the grant when you delete the role.

### Kubernetes

Project a service account token with this API's audience into the pod:

```yaml theme={null}
volumes:
  - name: agent-token
    projected:
      sources:
        - serviceAccountToken:
            audience: https://api.agentsonintents.com/v1/agents/<agent_id>
            expirationSeconds: 3600
            path: token
```

Read the file before each exchange, because the kubelet rotates it. Keep `expirationSeconds` at a day (86400) or less: longer-lived tokens are refused.

The grant pins `sub` (`system:serviceaccount:<namespace>:<name>`) and `/kubernetes.io/serviceaccount/uid`, so a service account deleted and recreated under the same name does not inherit the grant. Read the uid with `kubectl get serviceaccount <name> -o jsonpath='{.metadata.uid}'`.

> [accordion] Amazon EKS, Google GKE and Azure AKS
>
> Use the cluster's issuer URL as the grant's `issuer`. The API discovers the cluster's keys.
>
> | Platform | Read the issuer with |
> | - | - |
> | EKS | `aws eks describe-cluster --name <cluster> --query cluster.identity.oidc.issuer` |
> | GKE | `gcloud container clusters describe <cluster> --location <l> --format 'value(selfLink)'`, with `https://container.googleapis.com/v1/` in front |
> | AKS | `az aks show -n <cluster> -g <group> --query oidcIssuerProfile.issuerUrl` |
>
> The grant must pin both `sub` and `/kubernetes.io/serviceaccount/uid`.

> [accordion] Self-hosted clusters (k3s, kubeadm, kind, on-premises)
>
> The cluster's issuer is often unreachable from the internet. Instead of fetching keys, the API verifies tokens against public keys the **owner signs into the grant**. Get them with `kubectl get --raw /openid/v1/jwks`, and set `issuer` to the cluster's `--service-account-issuer`:
>
> ```json theme={null}
> {
>   "type": "oidc",
>   "issuer": "https://kubernetes.example.internal",
>   "claims": {
>     "sub": "system:serviceaccount:agents:trader",
>     "/kubernetes.io/serviceaccount/uid": "2b1c…"
>   },
>   "jwks": { "keys": [ { "kty": "RSA", "kid": "…", "n": "…", "e": "AQAB" } ] }
> }
> ```
>
> * Up to four keys: RSA of at least 2048 bits, P-256, P-384 or Ed25519. Public members only, each with the `kid` the issuer's tokens name. Nothing is fetched.
> * **Signed keys are frozen** into the grant. When the cluster rotates its signing key, or a key leaks, revoke the grant and issue a new one with the current keys.
> * Keys cannot be signed for an issuer on a vendor's domain (GitHub, GitLab, Google, AWS, Azure, Microsoft, Vercel, Terraform), even one the list above does not name. Those issuers are verified with their published keys only.
>
> The same `jwks` field works for any other `https` issuer whose keys the API does not fetch.

### Microsoft Entra ID

Entra issues tokens only for audiences registered in the tenant, so this is the one platform where the grant **must** name its own `audience`, and the owner signs it. Every other issuer refuses an explicit `audience`.

1. Create an app registration in your tenant to stand for this API. Keep it for this API alone: any service that receives its tokens could present them here. Give it an Application ID URI such as `api://near-intents-agents`.

2. A VM, App Service, Functions or Container Apps workload asks its managed identity endpoint for a token for that resource. On AKS, Entra Workload ID does the same.

   ```bash theme={null}
   curl -sSf -H Metadata:true \
     "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=api://near-intents-agents"
   ```

3. Issue the grant. What `audience` and `issuer` must be depends on the token version:

| Token | `issuer` | `audience` is the `aud` its tokens carry |
| - | - | - |
| v1.0 (the default for an app registration) | `https://sts.windows.net/<tenant>/` | The Application ID URI (`api://…`) or the client id, whatever the workload asked for as `resource` |
| v2.0 (the manifest sets `accessTokenAcceptedVersion` to 2) | `https://login.microsoftonline.com/<tenant>/v2.0` | Always the app registration's **client id** |

```json theme={null}
{
  "type": "oidc",
  "issuer": "https://sts.windows.net/<tenant>/",
  "audience": "api://near-intents-agents",
  "claims": { "oid": "<the identity's object id>", "idtyp": "app" }
}
```

A grant whose audience its tokens can never carry is refused at `generate-intent`.

Every principal in the tenant, users included, can request a token for the app registration's audience. The grant accepts one only if it carries the pinned `oid`. Add the `idtyp` optional claim to the app registration's access tokens (Token configuration) so the grant can also pin `"idtyp": "app"`. Entra emits that claim only in app-only tokens, so a user's token can then never match.

### Vercel

Vercel's custom-audience exchange sets the issuer to the team that owns the deployment, so the grant uses that team-scoped issuer. Request a token for this API's audience at runtime:

```typescript theme={null}
import { getVercelOidcToken } from "@vercel/oidc";

const jwt = await getVercelOidcToken({
  audience: `https://api.agentsonintents.com/v1/agents/${agentId}`,
});
```

The grant: `{ "type": "oidc", "issuer": "https://oidc.vercel.com/<team_slug>", "claims": { "owner_id": "team_…", "project_id": "prj_…", "environment": "production" } }`.

***

## Key-bound grants

For a server with no identity provider. Generate an Ed25519 or P-256 key on it, keep the private key there, and have the owner sign a grant to the **public** JWK. Private members (`d`) and any other curve are refused.

* **Ed25519** suits a key file: `{ "kty": "OKP", "crv": "Ed25519", "x": "…" }`.
* **P-256** suits a TPM, an HSM, AWS KMS or Google Cloud KMS: `{ "kty": "EC", "crv": "P-256", "x": "…", "y": "…" }`.

```typescript theme={null}
import { createWorkloadKey, localJwkSigner } from "@near-intents-agent-api/sdk";

const { privateJwk, publicJwk } = createWorkloadKey("Ed25519"); // or "P-256"
// Keep privateJwk on the workload. It never goes anywhere else.

const generated = await api.generateIntent({
  type: "grant_issue",
  agent_id: agentId,
  label: "Trading server",
  credential: { type: "public_key", jwk: publicJwk },
  expires_at: new Date(Date.now() + 30 * 24 * 3600 * 1000).toISOString(),
});
// The owner signs it. Save the grant_id of the issued grant.

const signer = localJwkSigner(privateJwk);
```

A **signer** is `{ publicJwk, sign(signingInput) }`. The SDK never needs the private key, only the public key and a signature, so the key may live anywhere. `sign` receives the JWS signing input as UTF-8 bytes and returns the raw 64-byte signature. For Ed25519 that is the signature over the bytes. For P-256 it is ECDSA over their SHA-256, encoded as `r || s`, **not** the ASN.1 DER that a KMS returns. See [With a cloud KMS key](#with-a-cloud-kms-key).

### Exchange a key assertion

The workload signs a short assertion (RFC 7523) and exchanges it like an identity token.

| Claim | Value |
| - | - |
| header `alg` | `EdDSA` (Ed25519) or `ES256` (P-256) |
| `iss`, `sub` | The key's thumbprint URI (RFC 9278): `urn:ietf:params:oauth:jwk-thumbprint:sha-256:` plus the RFC 7638 thumbprint |
| `aud` | The exchange URL, `{API URL}/v1/agents/{agent_id}/grants/token` |
| `iat`, `exp` | `exp` at most 5 minutes after `iat` |
| `jti` | Unique, 16 to 256 characters. Each assertion exchanges once. |

With the SDK, `forGrantSession(agentId, { signer })` signs one for every exchange (see [Sessions](#sessions)). To build one yourself:

```typescript theme={null}
import { calculateJwkThumbprintUri, importJWK, SignJWT } from "jose";

const iss = await calculateJwkThumbprintUri(publicJwk); // same as jwkThumbprintUri() in the SDK
const assertion = await new SignJWT({ jti: crypto.randomUUID() })
  .setProtectedHeader({ alg: "EdDSA" })
  .setIssuer(iss)
  .setSubject(iss)
  .setAudience(`https://api.agentsonintents.com/v1/agents/${agentId}/grants/token`)
  .setIssuedAt()
  .setExpirationTime("2m")
  .sign(await importJWK(privateJwk, "EdDSA"));
```

***

## Exchange a token for a session

The body follows RFC 8693 token exchange, as JSON like every other route. `subject_token` is the identity token or the key assertion.

```bash cURL theme={null}
curl -X POST "$NEAR_INTENTS_AGENT_API_URL/v1/agents/$AGENT_ID/grants/token" \
  -H "X-API-Key: $NEAR_INTENTS_AGENT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
    "subject_token": "'"$SUBJECT_TOKEN"'",
    "subject_token_type": "urn:ietf:params:oauth:token-type:jwt"
  }'
```

```typescript TypeScript SDK theme={null}
const session = await api.exchangeGrantToken(agentId, {
  subject_token: subjectToken,
  // subject_token_type defaults to urn:ietf:params:oauth:token-type:jwt
  // grant_id: only when the token matches more than one live grant
});
console.log(session.access_token, session.expires_at, session.grant_id, session.label);
```

```json theme={null}
{
  "access_token": "ngs_…",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "N_A",
  "expires_in": 900,
  "expires_at": "2026-10-31T12:15:00.000Z",
  "grant_id": "…",
  "label": "Deploy bot"
}
```

| Field | Description |
| - | - |
| `subject_token` | The identity token or key assertion: a compact JWT of at most 16,384 characters |
| `subject_token_type` | `urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token` |
| `grant_id` | Optional. Send it only when the token matches more than one live grant on the agent (`grant_ambiguous`). |
| `access_token` | The `ngs_…` session token. Send it as `X-Grant-Token`. |
| `token_type` | Always `N_A`: the token goes in `X-Grant-Token`, not in `Authorization`. |
| `expires_in`, `expires_at` | Seconds and time until the session ends |

Then call any agent action with it:

```bash theme={null}
curl -X POST "$NEAR_INTENTS_AGENT_API_URL/v1/agents/$AGENT_ID/transfer" \
  -H "X-API-Key: $NEAR_INTENTS_AGENT_API_KEY" \
  -H "X-Grant-Token: $SESSION_TOKEN" \
  -H "Idempotency-Key: transfer-bot-1" \
  -H "Content-Type: application/json" \
  -d '{ "asset": "nep141:wrap.near", "amount": "1", "recipient": "bob.near" }'
```

***

## Sessions

* A session token is `ngs_` plus 32 random bytes. The API stores only its SHA-256.
* It lives 15 minutes by default and never more than 60, and **never past the grant's expiry**.
* Every request re-reads the grant. Revoking the grant, an owner change or the grant's expiry ends all its sessions at once. Work that had already reached its [dispatch commitment](https://docs.near-intents.org/integration/agent-api/executions.md#the-dispatch-commitment) cannot be recalled, as with a grant token.
* A grant holds at most 100 live sessions. The next exchange fails with `grant_session_limit_reached` (429, retryable at `meta.available_at`, when the oldest session ends). Reuse a session until it nears its end instead of exchanging on every request.
* An identity token may be exchanged again while it lives. A key assertion exchanges once.

### Let the SDK manage the session

`forGrantSession` returns a client that exchanges on its first delegated call and keeps the session. Keep one client per grant and reuse it: a client per invocation burns the grant's 100 sessions.

* **Refresh in the background.** From `refreshBeforeSeconds` (60 by default) before the session ends, and never before its mid-life, the client starts one background exchange. Meanwhile it keeps serving the current session, so a short issuer outage costs nothing. It retries until 5 seconds before the end.
* **After a failure,** it waits 5 seconds before it tries another exchange, so an outage costs one exchange, not one per call.
* **Only an ended session waits.** A call made after the session has ended waits for an exchange, or fails with that exchange's error.
* **Concurrent calls share one exchange.**
* **A refused session is dropped.** If the API answers `agent_grant_required` (401 or 403), for example because the grant was revoked, the call throws that error and is not retried. The client forgets the session, and the next call exchanges again.

```typescript OIDC theme={null}
import { DEFAULT_BASE_URL, oidcGrantAudience } from "@near-intents-agent-api/sdk";

const audience = oidcGrantAudience(DEFAULT_BASE_URL, agentId);

const bot = api.forGrantSession(agentId, {
  // Called for every exchange. Ask the platform again: do not cache the token.
  subjectToken: () => requestPlatformToken(audience),
  // grantId: "…",            only when several live grants accept the identity
  // refreshBeforeSeconds: 60,
});
await bot.transfer(agentId, { asset: "nep141:wrap.near", amount: "1", recipient: "bob.near" });
```

```typescript Key theme={null}
import { localJwkSigner } from "@near-intents-agent-api/sdk";

const bot = api.forGrantSession(agentId, {
  signer: localJwkSigner(privateJwk), // signs a new assertion for every exchange
});
await bot.transfer(agentId, { asset: "nep141:wrap.near", amount: "1", recipient: "bob.near" });
```

`api.forGrant(token)` also accepts an `ngs_…` session token, if you exchange yourself and keep the token. The client's `baseUrl` must be the URL the API publishes as `servers[0]` (`https://api.agentsonintents.com` on the hosted API), because audiences are built from it.

### Renew a federated grant

To renew a grant before it ends, issue the same credential again. Grants that bind the same credential are one identity, and an exchange opens its session on the one that lives longest. Unlike a token, a federated credential may back more than one grant, so `grant_credential_reused` does not apply.

Other overlapping grants on one agent are allowed too. A token that several of them accept needs `grant_id` (`grantId` in the SDK), or the exchange fails with `grant_ambiguous`.

Idempotency keys are scoped to the grant. A renewal is a new grant, so retry an unresolved request under the grant that sent it.

***

## Sign every request

A `public_key` grant can skip the session. Instead of `X-Grant-Token`, the workload sends `X-Grant-Proof`, a JWT its key signs for that one request, on any endpoint that takes a grant token. `X-API-Key` is still required.

* **Proof or session?** Both rest on the same grant and key, and everything after admission is the same. Choose a proof when no bearer token should exist anywhere: not in the workload's memory, its logs or a proxy. Each proof binds one grant, method, URL, body and `Idempotency-Key`, and works once. Choose a session when signing is slow or costly (a cloud KMS signs over the network and bills per operation) and the workload sends many requests. The API keeps no session state for proofs.
* **One header.** Sending both grant headers is refused with `validation_failed` (400, pointer `/header/x-grant-proof`). Sending neither reads `agent_grant_required`.
* **Retries.** Every attempt signs a new proof, with a new `jti`, and keeps the same grant ID and `Idempotency-Key`. The API spends the `jti` before the operation runs, so a retry with the same proof is refused. The stored operation comes back for the same `Idempotency-Key`, including after a renewal. `recover` also uses the original grant ID.

```typescript theme={null}
const strict = api.forGrantProof({ grantId, signer });
await strict.transfer(agentId, { asset: "nep141:wrap.near", amount: "1", recipient: "bob.near" });
```

`grantId` is the ID of the issued grant, from the `grant_issue` status or `listGrants`. Keep it fixed. The SDK signs the exact body bytes it sends, signs a new proof for every attempt, and repeats the same `Idempotency-Key`. The signer runs once per attempt.

### What a proof signs

A proof carries the claims of an exchange assertion, with the request in place of the exchange.

| Claim | Value |
| - | - |
| header `alg` | `EdDSA` (Ed25519) or `ES256` (P-256) |
| `iss`, `sub` | The key's thumbprint URI (RFC 9278), as for an assertion |
| `grant_id` | The ID of the live `public_key` grant that binds this key. Keep it fixed on retries. |
| `aud` | One string: the request URL without query or fragment, the API's configured URL plus the path, for example `https://api.agentsonintents.com/v1/agents/{agent_id}/transfer`. Never the `Host` the request came through. |
| `htm` | The request method, uppercase |
| `body_sha256` | Lowercase hex SHA-256 of the exact body bytes sent. For no body, of zero bytes. |
| `idempotency_key` | The `Idempotency-Key` header exactly as sent. Omit the claim when the request sends none. |
| `iat`, `exp` | `exp` at most 5 minutes after `iat` (the SDK uses one minute); 30 seconds of clock skew allowed |
| `jti` | Unique, 16 to 256 characters. Spent on first use. |

Serialize the body once, hash that string and send the same bytes. The proof must name a live `public_key` grant on the agent and be signed by the key that grant binds. A malformed path, query, body or `Idempotency-Key` is rejected before the proof is spent. A missing required `Idempotency-Key` is rejected after.

With the SDK's `createGrantProof`, for a client you build yourself:

```typescript theme={null}
import { createGrantProof } from "@near-intents-agent-api/sdk";

const url = `https://api.agentsonintents.com/v1/agents/${agentId}/transfer`;
const body = JSON.stringify({ asset: "nep141:wrap.near", amount: "1", recipient: "bob.near" });
const idempotencyKey = "transfer-bot-1"; // keep it on retries, sign a new proof each time

await fetch(url, {
  method: "POST",
  headers: {
    "X-API-Key": process.env.NEAR_INTENTS_AGENT_API_KEY!,
    "X-Grant-Proof": await createGrantProof(signer, { grantId, method: "POST", url, body, idempotencyKey }),
    "Idempotency-Key": idempotencyKey,
    "Content-Type": "application/json",
  },
  body, // the same string that was hashed
});
```

Or without the SDK, with `jose`:

```typescript theme={null}
import { createHash, randomUUID } from "node:crypto";
import { calculateJwkThumbprintUri, importJWK, SignJWT } from "jose";

const server = "https://api.agentsonintents.com";
const iss = await calculateJwkThumbprintUri(publicJwk);
const key = await importJWK(privateJwk, "EdDSA");

async function grantProof(grantId: string, method: string, path: string, body: string, idempotencyKey?: string) {
  return new SignJWT({
    grant_id: grantId,
    htm: method,
    body_sha256: createHash("sha256").update(body).digest("hex"),
    idempotency_key: idempotencyKey, // omitted when the request sends no Idempotency-Key
    jti: randomUUID(),
  })
    .setProtectedHeader({ alg: "EdDSA" })
    .setIssuer(iss)
    .setSubject(iss)
    .setAudience(`${server}${path}`)
    .setIssuedAt()
    .setExpirationTime("1m")
    .sign(key);
}
```

### With a cloud KMS key

Create the key with purpose `ASYMMETRIC_SIGN` and algorithm `EC_SIGN_P256_SHA256`. Cloud KMS never releases the private key, so the signer asks KMS to sign. Three things differ from a local key:

1. **The public key.** Read it once (`getPublicKey` returns a PEM) and convert it to the JWK the owner signs into the grant.
2. **The digest.** For this algorithm KMS takes the SHA-256 digest of the signing input, not the data.
3. **The signature format.** KMS returns the ECDSA signature DER-encoded (`SEQUENCE { INTEGER r, INTEGER s }`). A JWS (RFC 7518) needs the raw 64 bytes `r || s`, each left-padded to 32 bytes. The SDK refuses any other length.

```typescript theme={null}
import { createHash, createPublicKey } from "node:crypto";
import { KeyManagementServiceClient } from "@google-cloud/kms";
import type { GrantPublicKeyJwk, WorkloadSigner } from "@near-intents-agent-api/sdk";

const kms = new KeyManagementServiceClient();
const name = "projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>/cryptoKeyVersions/1";

// Once: the JWK for the grant, { kty: "EC", crv: "P-256", x, y }.
const [{ pem }] = await kms.getPublicKey({ name });
const { kty, crv, x, y } = createPublicKey(pem!).export({ format: "jwk" });
const publicJwk = { kty, crv, x, y } as GrantPublicKeyJwk;

/** DER ECDSA signature to the raw r || s that a JWS carries. */
function derToJoseSignature(der: Uint8Array): Uint8Array {
  // SEQUENCE { INTEGER r, INTEGER s }; a P-256 signature's lengths each fit in one byte.
  if (der[0] !== 0x30) throw new Error("not a DER ECDSA signature");
  const raw = new Uint8Array(64);
  let offset = 2;
  for (const half of [0, 32]) {
    if (der[offset] !== 0x02) throw new Error("not a DER ECDSA signature");
    const length = der[offset + 1] ?? 0;
    let value = der.subarray(offset + 2, offset + 2 + length);
    offset += 2 + length;
    // DER prefixes 0x00 to a value whose high bit is set and drops leading zero bytes.
    while (value.length > 32 && value[0] === 0) value = value.subarray(1);
    if (value.length > 32) throw new Error("not a P-256 signature");
    raw.set(value, half + 32 - value.length);
  }
  return raw;
}

const signer: WorkloadSigner = {
  publicJwk,
  async sign(signingInput) {
    const [{ signature }] = await kms.asymmetricSign({
      name,
      digest: { sha256: createHash("sha256").update(signingInput).digest() },
    });
    return derToJoseSignature(signature as Uint8Array);
  },
};

// A proof for every request ...
const strict = api.forGrantProof({ grantId, signer });
// ... or one signature per session, for many requests.
const session = api.forGrantSession(agentId, { signer });
```

Each `asymmetricSign` is a network call and a billed operation. At high request rates, prefer a session: one signature then covers 15 minutes. Cloud KMS also offers `EC_SIGN_ED25519`, but only at the software protection level. The example above uses P-256, which every protection level supports, HSM included. The same shape works for AWS KMS (`Sign` with `ECDSA_SHA_256`, which also returns DER) and any other signer.

***

## Errors

| Code | Status | Meaning |
| - | - | - |
| `subject_token_invalid` | 401 | The subject token was refused: a bad signature, issuer, audience, lifetime or format, a token no live grant on the agent names, or a key assertion already exchanged. Every refusal of an unverified token reads the same. Get a fresh identity token, or sign a new assertion with a new `jti`. Missing or non-string fields return `validation_failed` (400). |
| `grant_proof_invalid` | 401 | The proof has an invalid grant ID, signature, key, audience, method, body hash, idempotency key, lifetime or format, or its `jti` was spent. Sign a fresh proof for the live grant and the exact request. |
| `agent_grant_required` | 403 | Neither `X-Grant-Token` nor `X-Grant-Proof` was sent. At the exchange, it also means an identity token verified against a live grant naming its issuer, but no live grant accepts both its claims and its audience. |
| `grant_ambiguous` | 409 | Live grants with different credentials accept the token. Send `grant_id`. |
| `grant_session_limit_reached` | 429 | The grant already holds its 100 live sessions. Retry at `meta.available_at`, and reuse a session until it nears its end. |
| `issuer_unavailable` | 503 | The issuer's keys could not be read. Retryable with the same request. Cached keys keep verifying for up to an hour. |
| `grant_credential_invalid` | 400 | At `generate-intent`: an untrusted issuer without signed keys, signed keys for a trusted issuer or for one on a vendor's domain, a signed key without a `kid` or two sharing one, missing required claims, a missing or extra audience, or a weak or invalid key. |

The SDK throws `AgentApiError` with the same `code`. See [Status & Errors](https://docs.near-intents.org/integration/agent-api/status-and-errors.md#grants) for every code and [Error layers](https://docs.near-intents.org/integration/agent-api/status-and-errors.md#error-layers) for who acts next.

> [!TIP]
>
> A brief `issuer_unavailable` after a platform rotates its keys is normal. Keys are read at most once every 30 seconds, so a token signed with a key the API has not read yet is refused until then. Send the same request again.

***

## Security model

* **The owner still decides.** The API cannot create or widen a federated grant. The owner signs the issuer, the audience and the claims, or the key. They are checked on every use, exactly as for token grants.
* **No secret to steal at rest.** The API stores the hash of a session token and the signed binding. The workload keeps nothing long-lived (OIDC) or a private key it never sends (key-bound).
* **Verify before matching.** A token is verified before its claims are compared with any grant, and every refusal of an unverified token reads the same, so it cannot probe which grants exist.
* **Keys are fetched only for named issuers.** An issuer's keys are read only when a live grant on the agent names it. A token from any other issuer reads `subject_token_invalid` without a network call. Retrieval has no redirects, a 64 KiB body cap and a 5-second timeout, and it fails closed.
* **Signed keys are frozen.** Keys the owner signs into a grant verify for the grant's lifetime and are never refreshed. They are refused for any issuer on a vendor's domain, so a vendor's issuers are always verified with their own published keys.
* **What federation trusts.** An `oidc` grant trusts its issuer to sign only for the workload its claims name. A compromised issuer, or a compromised pinned workload (a malicious commit on the pinned branch), can act within the grant until it is revoked, as a leaked grant token could. The policy, timelock, approvals and budget still bound it. A key-bound grant trusts the machine that holds the key: a compromised host can ask its key, file, TPM or KMS to sign whatever it wants, so a proof protects the request on the wire, not the host.
* **Per-account issuers trust the account.** An Entra ID tenant issues tokens for the app registration's audience to any of its principals, so a grant must pin `oid`, and `idtyp` = `app` rules out users. An AWS grant pins the account and the role's name, so a role deleted and recreated under the same name matches the grant.
* **Timing.** An exchange for an issuer that a grant names takes a key read, while any other is refused at once. Response time can therefore reveal whether some grant names an issuer. The partner already lists its agents' grants, so this is accepted.
* **Audit.** Each exchange is written to the API's audit log (`agent.grant_session_opened`), with the agent, grant and subject (`issuer#sub`, or the key's thumbprint URI). An accepted proof is recorded in the server's own log, not the audit log.

### Limits

| Limit | Value |
| - | - |
| Session lifetime | 15 minutes by default, at most 60, never past the grant |
| Live sessions per grant | 100 |
| Live grants per agent | 50 |
| Grant expiry | At most 365 days ahead |
| `claims` in an `oidc` credential | 1 to 16 |
| Signed issuer keys (`jwks`) | Up to 4 |
| Subject token | At most 16,384 characters |
| Assertion or proof `exp` | At most 5 minutes after `iat` |
| `jti` | 16 to 256 characters, spent on first use |
| Kubernetes token `expirationSeconds` | At most 86,400 |

> [card] [Grants](https://docs.near-intents.org/integration/agent-api/grants.md)
>
> Issue, list and revoke grants, and what a grant does and does not decide.

> [card] [Owner Signing](https://docs.near-intents.org/integration/agent-api/owner-signing.md)
>
> How the owner's wallet signs the `grant_issue` intent.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.