Events and signed webhooks.
Goal: know when a twin changes, either by asking (events with a cursor) or by being told (a webhook), and prove that each delivery comes from STARCO and was not changed on the way.
STEP 1 Read the project's events Beta#
Every change writes an event with a seq in commit order. The types are twin.created, twin.deleted, schema.created, state.changed and series.appended. Events are kept 30 days.
export API="https://api.starco.dev/v1"
export STARCO_KEY="starco_dk_…"
curl "$API/events?after=0&limit=5" -H "Authorization: Bearer $STARCO_KEY"import os, requests
API = "https://api.starco.dev/v1"
H = {"Authorization": f"Bearer {os.environ['STARCO_KEY']}"}
page = requests.get(f"{API}/events", headers=H, params={"after": 0, "limit": 5}).json()
for e in page["data"]:
print(e["seq"], e["type"], e["twin_id"], e["measure"], e["version"])
print("next_after:", page["next_after"]){ "project_id": "207387f6-…",
"data": [
{ "id": "a28e13ab-…", "seq": 1, "type": "twin.created", "twin_id": "c7829b47-…", "measure": null, "version": null,
"data": { "template": "daily_movement", "layers": ["wellness"] }, "created_at": "2026-11-20T22:10:13Z" },
{ "id": "41cce423-…", "seq": 2, "type": "state.changed", "twin_id": "c7829b47-…", "measure": "wellness.mood_level", "version": 1,
"data": { "op": "set", "value": 3, "previous_version": 0, "transaction_id": "5c26527e-…" }, "created_at": "…" },
… ],
"next_after": 5, "head_seq": 11, "oldest_seq": 1, "retention_days": 30 }Filter with types=state.changed,series.appended and twin_id=…. A wrong cursor is 422 cursor_invalid; an unknown type, 422 types_invalid with the list in expected.
STEP 2 Follow them with a cursor Beta#
Keep next_after and ask again from there. wait (0 to 10 seconds) holds the request open until something arrives: a simple long-poll. Server-sent events are not offered.
curl "$API/events?after=11&wait=10" -H "Authorization: Bearer $STARCO_KEY"after = page["next_after"]
while True:
page = requests.get(f"{API}/events", headers=H, params={"after": after, "wait": 10}).json()
for e in page["data"]:
print(e["seq"], e["type"], e["measure"], e["data"])
after = page["next_after"]STEP 3 Subscribe a webhook Beta#
STARCO sends each event to your endpoint as a POST. Only https:// on port 443 to a host whose every address is public is accepted (checked when you subscribe and before each attempt; redirects are never followed). Up to 5 webhooks per project. The secret is shown only now.
RESP=$(curl -s -X POST "$API/webhooks" -H "Authorization: Bearer $STARCO_KEY" -H "Content-Type: application/json" \
-d '{"url": "https://hooks.example.test/twin", "event_types": ["state.changed"]}')
echo "$RESP" # copy the secret into your receiver's environment now
WEBHOOK=$(echo "$RESP" | jq -r .webhook.id)hook = requests.post(f"{API}/webhooks", headers=H, json={
"url": "https://hooks.example.test/twin", "event_types": ["state.changed"]}).json()
SECRET = hook["secret"] # keep it in your receiver's environment, never in code
print(hook["webhook"]["id"], hook["webhook"]["secret_prefix"]){ "webhook": { "id": "a2a6333a-…", "url": "https://hooks.example.test/twin", "event_types": ["state.changed"],
"secret_prefix": "whsec_jO0VmP", "created_at": "…", "disabled_at": null, "active": true },
"secret": "whsec_…",
"note": "The secret is shown only now. Check every delivery: X-Starco-Signature = t=<unix>,v1=hex(HMAC-SHA256(secret, \"<t>.<raw body>\"))." }Replace hooks.example.test (a reserved name that never resolves) with your own endpoint. An address that is not https, or that resolves to a private network, is refused with a reason such as url_not_https.
STEP 4 Verify every delivery#
A delivery carries X-Starco-Event, X-Starco-Delivery, X-Starco-Timestamp and X-Starco-Signature: t=<unix>,v1=<hex>. Recompute the HMAC over the timestamp, a dot and the raw body, compare in constant time and reject old timestamps so a delivery cannot be replayed. This receiver uses only the Python standard library.
import hashlib, hmac, os, time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["STARCO_WEBHOOK_SECRET"].encode()
TOLERANCE = 300 # seconds; your choice
def verify(signature: str, body: bytes) -> bool:
parts = dict(p.split("=", 1) for p in signature.split(",") if "=" in p)
t, v1 = parts.get("t", ""), parts.get("v1", "")
if not t.isdigit() or abs(time.time() - int(t)) > TOLERANCE:
return False
expected = hmac.new(SECRET, t.encode() + b"." + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
class Hook(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if not verify(self.headers.get("X-Starco-Signature", ""), body):
self.send_response(400); self.end_headers(); return
print(self.headers["X-Starco-Event"], body.decode())
self.send_response(200); self.end_headers()
HTTPServer(("127.0.0.1", 8080), Hook).serve_forever() # put it behind your https endpoint# Change a value: the subscribed webhook receives one state.changed delivery.
TWIN=$(curl -s "$API/twins?limit=1" -H "Authorization: Bearer $STARCO_KEY" | jq -r '.data[0].id')
curl -X PUT "$API/twins/$TWIN/state/wellness.mood_level" -H "Authorization: Bearer $STARCO_KEY" \
-H "Content-Type: application/json" -d '{"value": 2}'X-Starco-Event: state.changed
X-Starco-Delivery: 7e843c2e-…
X-Starco-Timestamp: 1795212613
X-Starco-Signature: t=1795212613,v1=74be7872…20bf5
{"id":"7741935e-…","seq":11,"type":"state.changed","project_id":"207387f6-…","twin_id":"c7829b47-…",
"measure":"wellness.mood_level","version":3,"data":{"op":"set","value":2,"previous_version":2,"transaction_id":"936f1145-…"},
"created_at":"2026-11-20T22:10:13Z"}STEP 5 Read the delivery log Beta#
Each delivery shows its status, attempts and the HTTP code your endpoint answered (never the body). A failed attempt is retried with a growing delay; every attempt is also a row of the audit chain (webhook.delivery).
curl "$API/webhooks/$WEBHOOK/deliveries" -H "Authorization: Bearer $STARCO_KEY"log = requests.get(f"{API}/webhooks/{hook['webhook']['id']}/deliveries", headers=H).json()
for d in log["data"]:
print(d["event_type"], d["status"], d["attempts"], d["last_http_status"], d["last_error"])state.changed delivered 1 200 NoneSTEP 6 Rotate the secret Beta#
If the secret may have leaked, or on the schedule you choose, replace it. The answer shows the new secret once. The old one stops signing for every send that starts after the rotation: there is no period with two valid secrets. A request already on the wire at that instant still carries the old signature. Deliveries your receiver rejects while it still holds the old secret are not lost: they are retried (after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours) and each retry is signed with the secret of that moment, so they pass once your receiver holds the new one.
RESP=$(curl -s -X POST "$API/webhooks/$WEBHOOK/secret/rotate" -H "Authorization: Bearer $STARCO_KEY")
echo "$RESP" | jq '{id: .webhook.id, secret_prefix: .webhook.secret_prefix}' # .secret is the new whsec_…: put it in your receiverrotated = requests.post(f"{API}/webhooks/{hook['webhook']['id']}/secret/rotate", headers=H).json()
SECRET = rotated["secret"] # replace it in your receiver's environment
print(rotated["webhook"]["id"], rotated["webhook"]["secret_prefix"]){ "id": "a2a6333a-…", "secret_prefix": "whsec_Qm3xT1" }The webhook keeps its id, its URL and its delivery log. A webhook that was deleted cannot be rotated (409 webhook_disabled). If you lose the answer, rotate again: a secret cannot be read back.
To stop, DELETE /v1/webhooks/{webhook}: the webhook stays listed with "active": false and pending deliveries are cancelled.
What just happened
The project keeps an ordered list of what changed. You can read it at your pace with a cursor, or let STARCO push each event to you. The signature ties each body to your secret and a time: if a single byte changes, or the delivery is replayed later, your receiver says no.