| title | Gestionar secretos |
|---|---|
| description | Rotar secretos de consumidor y validar cada entrega de Chainhooks |
:::objectives
- Crear/rotar un secreto de consumidor de Chainhooks.
- Valida las solicitudes de webhook verificando el
Authorizationcabecera. :::
:::prerequisites
- Clave API de Hiro
- Node.js (el ejemplo del servidor usa Fastify). :::
Cuando creas un secreto, nuestro servicio Chainhooks adjunta un Authorization: Bearer <secret> encabezado a cada intento de webhook, proporcionándote un simple apretón de manos de secreto compartido. Así es como empezar:
- Rota el secreto con
rotateConsumerSecret(o el/chainhooks/{uuid}/secretAPI) siempre que necesites inicializar o crear un nuevo token. - Rechazar entregas de webhook cuyas
Authorizationheader no es igualBearer <current-secret>.
import { ChainhooksClient, CHAINHOOKS_BASE_URL } from '@hirosystems/chainhooks-client';
const client = new ChainhooksClient({
baseUrl: CHAINHOOKS_BASE_URL.mainnet, // or .testnet / custom URL
apiKey: process.env.HIRO_API_KEY!,
});
// Store this value securely and use it to validate webhook requests
const secret = await client.rotateConsumerSecret().secret;server.post('/webhook', async (request, reply) => {
if (!secret) {
reply.code(503).send({ error: 'consumer secret unavailable' });
return;
}
const authHeader = request.headers.authorization;
if (authHeader !== `Bearer ${secret}`) {
reply.code(401).send({ error: 'invalid consumer secret' });
return;
}
const event = request.body;
console.log(`received chainhook ${event.chainhook.uuid}`);
reply.code(204).send();
});
await server.listen({ port: Number(process.env.PORT) || 3000 });