# revoke()

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

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

Apris una chiave per bene. Prende effetto sulla proxima richiesta fatta con ella.

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

## Parâmetros {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `id` | string | obrigatório | De [list()](/pt/sdk/ref/keys/list). E' il único lugar in cui un id apare. |

## Retorno {#returns}

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

## Erros {#errors}

| Código | Status | Quando |
| --- | --- | --- |
| not_found | 404 | Nessuna chiave attiva di questo cont porta que id — incluso un ya revocat. |

Revocando donc due volte le risposte `404` la seconda volta. Quando l'obiettivo era semplicemente che la chiave s'è partit, trate ca il successo.

```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;
  }
}
```

## Ce s'imprime, e ce no {#effect}

| Dopo rivocazione | Stato |
| --- | --- |
| Un nuovo scambio con la tecla | - Negati |
| Una sessione ya trocata da essa | ancora valida fino a che sia revocata o caduca |
| Una richiesta in volo | non afectata; era già autorizzata |
| Altre chiues da conta | intotche |
| Lavore ya facturato | inalterat — revocare non è restituzion |

Revoking una chiave chiude la porta e lascia chi è già dentro. Per una macchina tu non confidè, che non è suficiente por si.

```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);
```

Inversat, c'è una finestra in cui la chiave ancora valida intercambia una sessione fresca, e la macchina è di volta prima di aver terminat la seconda chiamata.

## Una chiave che credete ha filtrat {#leaked}

Velocitès batí tidinesss aqui. Revoke prima e soluçòre le conseqüènces dopo — una chave che is out è gastar il budget di qualcun altro in sua conta.

| Passo | Fa |
| --- | --- |
| 1 | Revoca la chiave. Non attende per un substituto. |
| 2 | Revoca la sessione che trocava, se registrava l'identit. |
| 3 | Crea e implementa un substitut per quelli ligitly usò. |
| 4 | Legî list() e verifica lastUsedAt in ogni tecla restante. |
| 5 | Legî il balance, e vedî ce era spendit mentre la chiave era fora. |

> **Este è l'unu caso in cui rompere il tuo programma è corret**
>
> La rotazione ordinaria dispiega prima la sostituzione. Una fuga inverte che: il costo di alcuni minuti di inactiùn è notificat, e il costo di lasciare una chiave solta non è.

## Retirando il chen ozi {#cleanup}

Le chiavi non expira, quindi un conto le accumula. La barrella di sicurezza è ristretta: solo chiavi che non hanno mai sido usate, e solo uns aveu a sufficienza que un déploiement pendente non è la explicazion.

```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);
}
```

> **Non vars la tecla che tenes**
>
> Il loop sopra lo esclude per prefijo. Senza quel guardia, un lavoro di pulizia revoca il suo proprio credencial e le rimanent calls fail — inclusa quelle che ti avrebbe dicit ce era accaduto.

> **Non c'è non-revore**
>
> A meno che non si risponda a un furat, s'implemente il suo sostitutizion prima de revocar.

- [list()](/pt/sdk/ref/keys/list): De dove viene l'identificat, e que ultimaUsedAt te dice.
- [revokeSession()](/pt/sdk/ref/auth/revoke-session): Finendo la sessione una chiave scambiata.

```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"])
```
