# Webhooks, Shares & High Availability

Deliver signed run and suite verdicts to Slack, Microsoft Teams, or your own receiver, share read-only run links safely outside your workspace, and run CircuitTwin across multiple Postgres-backed replicas.

## Outbound HMAC-SHA256 webhooks

Configure workspace webhooks in Settings, via `ct cloud webhook` (`list`, `create`, `delete`, `test`), via the REST API, or through the [Python and TypeScript SDKs](https://circuittwin.ai/docs/sdks) (`client.webhooks` in Python; `createWebhook` / `rotateWebhookSecret` in TypeScript) to receive real-time notifications when runs, test suites, or fault matrices finish.

| Format | Payload structure                                                                    | Typical destination                                          |
| ------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| json   | Canonical CircuitTwin event envelope with verdict, counts, run/suite IDs, and links. | Custom CI receivers, PagerDuty bridges, internal dashboards. |
| slack  | Slack Block Kit message with pass/fail summary, top failure reasons, and run link.   | Slack Incoming Webhook URLs.                                 |
| teams  | Microsoft Teams Adaptive Card payload with verdict facts and action link.            | Microsoft Teams Workflows / Power Automate webhook URLs.     |

### Verifying X-CircuitTwin-Signature

Every delivery carries an `X-CircuitTwin-Signature` header formatted as `t=<unix_seconds>,v1=<hex_hmac_sha256>`. The signature is computed as `HMAC-SHA256(secret, "{t}.{raw_body}")` over the exact UTF-8 request bytes. Reject requests whose timestamp is older than your replay window (for example 300 seconds) and compare digests in constant time. Both official SDKs also export ready-to-use helpers: `verify_webhook_signature` in Python and `verifyWebhookSignature` in TypeScript ([SDKs reference](https://circuittwin.ai/docs/sdks)).

verify\_webhook.py

```
from circuittwin import verify_webhook_signature

# Pass the full X-CircuitTwin-Signature header ("t=<unix>,v1=<hex>") with timestamp=None,
# or pass timestamp and signature separately.
valid = verify_webhook_signature(
    secret=WEBHOOK_SECRET,
    timestamp=None,
    signature=request.headers["X-CircuitTwin-Signature"],
    body=request.raw_body,
    tolerance_seconds=300,
)
```

verify-webhook.ts

```
import { verifyWebhookSignature } from '@circuittwin-ai/sdk';

// Uses Web Crypto HMAC-SHA256 with constant-time comparison and replay-window checking.
const valid = await verifyWebhookSignature({
  secret: process.env.WEBHOOK_SECRET!,
  signature: req.headers['x-circuittwin-signature'] as string,
  body: rawBody, // Buffer / Uint8Array or exact UTF-8 string
  toleranceSeconds: 300,
});
```

### Secret rotation, SSRF/IPv6 pinning & audit logs

- **Immediate secret rotation**: rotate a webhook signing secret in Settings or via API (`POST /api/v1/webhooks/{id}/rotate-secret`); the new secret is revealed once and takes effect immediately for subsequent deliveries (update your receiver with the new secret right away).
- **SSRF protection & IPv6 DNS pinning**: outbound webhook delivery resolves DNS once, blocks loopback, link-local, RFC 1918 private IPv4, unique-local IPv6 (`fc00::/7`), IPv4-mapped IPv6, and cloud metadata addresses, pins the validated socket IP for the HTTPS connection, and disables unsafe redirects.
- **Organization audit logs**: webhook creation, target updates, secret rotations, revocations, and share-link grants write immutable entries into the organization audit log (available for export on Enterprise).

## Read-only shareable permalinks (/s/{token})

Create time-bounded or revocable read-only links to a hosted run, run comparison, test suite, or fault matrix so teammates, silicon vendors, or external reviewers can inspect sanitized results without joining your workspace.

- **256-bit cryptographically random tokens**: links resolve at `https://app.circuittwin.ai/s/<token>` with 256 bits of entropy stored hashed at rest.
- **Strict caching & indexing headers**: share responses always emit `Cache-Control: no-store` and `X-Robots-Tag: noindex, nofollow` so links are never cached by intermediaries or indexed by search engines.
- **Sanitized read-only view & redacted firmware downloads**: public `/s/{token}` links render the sanitized run verdict, execution stats, source-symbolized crash & backtrace summary, assertions, issues, and console output while withholding raw firmware binary downloads (`.elf`/`.bin`) and workspace-private artifacts. Create, list, or revoke links in Settings, via `ct cloud share` (`list`, `create`, `revoke`), or via the Python and TypeScript SDKs.

create-share.ts

```
import { createClientFromEnv, createShare } from '@circuittwin-ai/sdk';

const client = createClientFromEnv(); // reads CT_SERVER and CT_TOKEN
const share = await createShare(client, {
  kind: 'run',
  targetId: 'run_01J...',
  expiresIn: '24h', // '24h' | '7d' | '30d' | 'never'
});
console.log('Read-only link:', share.url); // https://app.circuittwin.ai/s/...
```

## Multi-replica Postgres High Availability (self-hosted & enterprise)

Self-hosted and dedicated Enterprise deployments scale horizontally across multiple `ct-server` replicas backed by PostgreSQL using `CT_HA_BACKEND=postgres`.

| Component           | Behavior under CT\_HA\_BACKEND=postgres                                                                                                                                                                                      |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Event broker        | Uses PostgreSQL LISTEN/NOTIFY to fan out live run SSE updates, suite progress, and job completions across all API replicas without an external Redis dependency.                                                             |
| Rate-limit store    | Atomic PostgreSQL token-bucket / sliding-window counters enforce consistent per-token and per-org quotas across replicas.                                                                                                    |
| Reference topology  | deploy/rust/compose.ha.yml layers redundant ct-server replicas on top of deploy/rust/compose.vps.yml with PostgreSQL primary storage and pre-wired health checks.                                                            |
| Monitoring & alerts | Exposes Prometheus /metrics endpoints paired with ready-to-import Grafana dashboards and Alertmanager rules covering queue latency, replica liveness, DB pool saturation, webhook failure rates, and sandbox execution time. |

terminal (self-hosted HA stack)

```
export CT_HA_BACKEND=postgres
export DATABASE_URL=postgres://circuittwin:<password>@pg-primary:5432/circuittwin
docker compose -f deploy/rust/compose.vps.yml -f deploy/rust/compose.ha.yml up -d
```

> **Enterprise self-hosted deployments**
>
> Multi-replica HA configuration, SSO/SCIM directory sync, and audit log exports are part of the [Enterprise](https://circuittwin.ai/pricing) plan. See [Security](https://circuittwin.ai/security) for our sandbox and disclosure policy.

## Next

- [Test in CI](https://circuittwin.ai/docs/ci): post share links in PR comments and export GitLab Code Quality reports
- [Python & TypeScript SDKs](https://circuittwin.ai/docs/sdks): manage webhooks, shares, and SSE event streams from Python or Node.js
- [Waveforms, RTOS & Crash Analysis](https://circuittwin.ai/docs/observability): inspect workspace waveforms, decoded bus frames, RTOS telemetry, and symbolized crash backtraces
