# revoke()

Canonical URL: https://developers.iagenify.com/sdk/ref/keys/revoke/
Language: en

`api.keys.revoke(id) → Promise<{ ok: true }>`

Stops a key for good. It takes effect on the very next request made with it.

Status: DELETE /api/keys/:id · immediate · not reversible

## Parameters {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `id` | string | required | From [list()](/sdk/ref/keys/list). It is the only place an id appears. |

## Returns {#returns}

```javascript
{ ok: true }
```

## Errors {#errors}

| Code | Status | When |
| --- | --- | --- |
| not_found | 404 | No active key of this account carries that id — including one already revoked. |

So revoking twice answers `404` the second time. When the goal was simply that the key be gone, treat that as success.

```javascript
import { IaGenifyError } from "iagenify";

async function ensureRevoked(api, id) {
  try {
    await api.keys.revoke(id);
    return "revoked";
  } catch (err) {
    if (err instanceof IaGenifyError && err.status === 404) return "already gone";
    throw err;
  }
}
```

## What it stops, and what it does not {#effect}

| After revoking | State |
| --- | --- |
| A new exchange with that key | refused |
| A session already exchanged from it | still valid until it is revoked or expires |
| A request in flight | unaffected; it was already authorised |
| Other keys on the account | untouched |
| Work already billed | unchanged — revoking is not a refund |

Revoking a key closes the door and leaves whoever is already inside. For a machine you no longer trust, that is not enough on its own.

```javascript
// Key first: it closes the door.
await api.keys.revoke(keyId);

// Session second: it removes whoever is already inside.
await api.auth.revokeSession(sessionId);
```

Reversed, there is a window in which the still-valid key exchanges a fresh session, and the machine is back before you have finished the second call.

## A key you think has leaked {#leaked}

Speed beats tidiness here. Revoke first and sort out the consequences after — a key that is out is spending someone else's budget on your account.

| Step | Do |
| --- | --- |
| 1 | Revoke the key. Do not wait for a replacement. |
| 2 | Revoke the session it exchanged, if you recorded the id. |
| 3 | Create and deploy a replacement for whatever legitimately used it. |
| 4 | Read list() and check lastUsedAt on every remaining key. |
| 5 | Read the balance, and look at what was spent while the key was out. |

> **This is the one case where breaking your own program is correct**
>
> The ordinary rotation deploys the replacement first. A leak reverses that: the cost of a few minutes of downtime is known, and the cost of leaving a loose key is not.

## Retiring what is idle {#cleanup}

Keys do not expire, so an account accumulates them. The safe sweep is narrow: only keys that have never been used, and only ones old enough that a pending deployment is not the explanation.

```javascript
const { keys } = await api.keys.list();
const week = Date.now() - 7 * 24 * 60 * 60 * 1000;

const unused = keys.filter(
  (k) => !k.lastUsedAt && Date.parse(k.createdAt) < week && k.prefix !== mine,
);

for (const k of unused) {
  console.log(`revoking ${k.name} (${k.prefix}) — created ${k.createdAt}, never used`);
  await api.keys.revoke(k.id);
}
```

> **Do not sweep the key you are holding**
>
> The loop above excludes it by prefix. Without that guard, a cleanup job revokes its own credential and the remaining calls fail — including the ones that would have told you what happened.

> **There is no un-revoke**
>
> The key is not recoverable and not reusable. Unless you are responding to a leak, deploy its replacement before revoking it.

- [list()](/sdk/ref/keys/list): Where the id comes from, and what lastUsedAt tells you.
- [revokeSession()](/sdk/ref/auth/revoke-session): Ending the session a key exchanged.

```python
{"ok": True}
```

```python
from iagenify import IaGenifyError

def ensure_revoked(api, key_id):
    try:
        api.keys.revoke(key_id)
        return "revoked"
    except IaGenifyError as error:
        if error.status == 404:
            return "already gone"
        raise
```

```python
# Key first: it closes the door.
api.keys.revoke(key_id)

# Session second: it removes whoever is already inside.
api.auth.revoke_session(session_id)
```

```python
from datetime import datetime, timedelta, timezone

keys = api.keys.list()["keys"]
week = datetime.now(timezone.utc) - timedelta(days=7)

unused = [k for k in keys
          if not k.get("lastUsedAt")
          and datetime.fromisoformat(k["createdAt"].replace("Z", "+00:00")) < week
          and k["prefix"] != mine]

for k in unused:
    print(f"revoking {k['name']} ({k['prefix']}) — created {k['createdAt']}, never used")
    api.keys.revoke(k["id"])
```
