Events, and a receiver that verifies.
Read what changed in a project with a cursor, and write the one function every webhook receiver needs: the check that a delivery really comes from STARCO and is not a replay.
STARCO_KEY it runs as it is. The TypeScript and CLI tabs use the SDK and the command line, which are not published yet.The idea#
Every change is an event with a seq that only grows: ask for the events after the last one you processed. A webhook pushes the same events to your https address with X-Starco-Signature: t=<unix time>,v1=<hex>, where v1 is the HMAC-SHA256 of <t>.<raw body> under the secret shown once when the webhook was created. The receiver must check the signature on the raw body, in constant time, and reject old timestamps.
Subscribing a webhook needs a public https address, so this example signs a sample delivery itself, with a made-up secret, to exercise the verification. The events part talks to the API.
The whole program#
export API="https://api.starco.dev/v1"
AUTH="Authorization: Bearer $STARCO_KEY"
JSON="Content-Type: application/json"
TWIN=$(curl -s -X POST "$API/twins" -H "$AUTH" -H "$JSON" \
-d '{"template": "daily_movement", "layers": ["wellness"], "label": "events"}' | jq -r .twin.id)
curl -s -X PUT "$API/twins/$TWIN/state/wellness.mood_level" -H "$AUTH" -H "$JSON" -d '{"value": 4}' > /dev/null
curl -s "$API/events?after=0&twin_id=$TWIN" -H "$AUTH" | jq -r '.data[] | "\(.type) \(.measure) \(.version)"'
# The check a receiver makes, with openssl: recompute v1 from t and the raw body, then compare.
SECRET="whsec_example"; BODY='{"type":"state.changed"}'; T=$(date +%s)
SIG="t=$T,v1=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')"
T2=${SIG#t=}; T2=${T2%%,*}; V1=${SIG##*v1=}
MINE=$(printf '%s.%s' "$T2" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')
AGE=$(( $(date +%s) - T2 ))
if [ "$MINE" = "$V1" ] && [ "$AGE" -ge -300 ] && [ "$AGE" -le 300 ]; then echo "signature ok"; else echo "signature refused"; fiimport hashlib, hmac, os, time, requests
API = "https://api.starco.dev/v1"
H = {"Authorization": f"Bearer {os.environ['STARCO_KEY']}"}
twin = requests.post(f"{API}/twins", headers=H, json={
"template": "daily_movement", "layers": ["wellness"], "label": "events"}).json()["twin"]["id"]
requests.put(f"{API}/twins/{twin}/state/wellness.mood_level", headers=H, json={"value": 4}).raise_for_status()
for e in requests.get(f"{API}/events", headers=H, params={"after": 0, "twin_id": twin}).json()["data"]:
print(e["type"], e["measure"], e["version"])
def verify(secret: bytes, raw_body: bytes, header: str, tolerance: int = 300) -> bool:
"""True only if the delivery was signed with the secret and is recent. Call it BEFORE parsing the body."""
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
if not parts.get("t", "").isdigit() or abs(time.time() - int(parts["t"])) > tolerance:
return False
mine = hmac.new(secret, parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(mine, parts.get("v1", ""))
secret, body, t = b"whsec_example", b'{"type":"state.changed"}', str(int(time.time()))
header = f"t={t},v1=" + hmac.new(secret, t.encode() + b"." + body, hashlib.sha256).hexdigest()
print(verify(secret, body, header), verify(secret, body + b" ", header), verify(b"another", body, header))import { Client, signWebhook, verifyWebhookSignature } from '@starco/sdk';
const c = new Client({ baseUrl: "https://api.starco.dev/v1", apiKey: process.env.STARCO_KEY });
const twin = (await c.twins.create({ template: "daily_movement", layers: ["wellness"], label: "events" })).id;
await c.state.set(twin, "wellness.mood_level", 4);
for await (const e of c.events.iter({ twinId: twin })) console.log(e.type, e.measure, e.version);
// In your receiver: verify the RAW body before parsing it (secret = the whsec_… shown once when the webhook was created).
const secret = "whsec_example", body = '{"type":"state.changed"}';
const header = await signWebhook(secret, body); // what STARCO sends as X-Starco-Signature
const accepts = (s, b) => verifyWebhookSignature(s, b, header).then(() => true, () => false); // it throws when it does not verify
console.log(await accepts(secret, body), await accepts(secret, body + " "), await accepts("another", body));export STARCO_BASE_URL="https://api.starco.dev/v1" STARCO_API_KEY="$STARCO_KEY"
TWIN=$(starco --json twins create --template daily_movement --layers wellness --label events | jq -r .id)
starco twin set $TWIN wellness.mood_level 4
starco events --after 0 --twin $TWIN
# The check a receiver makes: the raw body in a file, the header as it arrived, the secret in the environment.
printf '%s' '{"type":"state.changed"}' > delivery.json
T=$(date +%s)
SIG="t=$T,v1=$(printf '%s.%s' "$T" "$(cat delivery.json)" | openssl dgst -sha256 -hmac whsec_example | sed 's/^.* //')"
STARCO_WEBHOOK_SECRET=whsec_example starco webhooks verify delivery.json --signature "$SIG"twin.created null null
state.changed wellness.mood_level 1
True False FalseThe other tabs print the same facts in their own format. Ids, hashes and counts depend on your project.
What just happened
The cursor returned the two events of the twin in order. The verification accepted the delivery signed with the secret, and refused the same signature over a changed body and over another secret.