// engine/figma/webhook-manager.ts — Figma webhook registration & HMAC validation (SPEC-425)
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
const FIGMA_WEBHOOKS_API = 'https://api.figma.com/v2/webhooks';
// ---------------------------------------------------------------------------
// registerFigmaWebhook — register a FILE_VERSION_UPDATE webhook with Figma
// ---------------------------------------------------------------------------
export async function registerFigmaWebhook(teamId, callbackUrl, accessToken) {
    const passcode = randomUUID();
    const response = await fetch(FIGMA_WEBHOOKS_API, {
        method: 'POST',
        headers: {
            'X-Figma-Token': accessToken,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            event_type: 'FILE_VERSION_UPDATE',
            team_id: teamId,
            endpoint: callbackUrl,
            passcode,
        }),
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Failed to register Figma webhook: ${response.status} ${body}`);
    }
    const data = (await response.json());
    return {
        webhookId: data.id,
        passcode,
        endpoint: callbackUrl,
        registeredAt: new Date().toISOString(),
    };
}
// ---------------------------------------------------------------------------
// deregisterFigmaWebhook — delete an existing Figma webhook by ID
// ---------------------------------------------------------------------------
export async function deregisterFigmaWebhook(webhookId, accessToken) {
    const response = await fetch(`${FIGMA_WEBHOOKS_API}/${webhookId}`, {
        method: 'DELETE',
        headers: {
            'X-Figma-Token': accessToken,
        },
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Failed to deregister Figma webhook ${webhookId}: ${response.status} ${body}`);
    }
}
// ---------------------------------------------------------------------------
// validateWebhookSignature — verify HMAC-SHA256 from X-Figma-Signature header
// ---------------------------------------------------------------------------
export function validateWebhookSignature(body, signature, passcode) {
    if (signature === '' || signature.length === 0) {
        return false;
    }
    let receivedBuffer;
    try {
        receivedBuffer = Buffer.from(signature, 'hex');
    }
    catch {
        return false;
    }
    const computed = createHmac('sha256', passcode).update(body).digest();
    if (computed.length !== receivedBuffer.length) {
        return false;
    }
    return timingSafeEqual(computed, receivedBuffer);
}
// ---------------------------------------------------------------------------
// generateWebhookPasscode — returns a unique, hard-to-guess passcode
// ---------------------------------------------------------------------------
export function generateWebhookPasscode() {
    return randomUUID();
}
//# sourceMappingURL=webhook-manager.js.map