Webhooks
Chastify sends extension webhooks as JSON POST requests to your backend. Use them to update your integration when supported lock events occur. They are notifications, not an authoritative event ledger or a replacement for API authorization.
Configure and test delivery
- Open your extension's editor and expand Advanced: webhooks.
- Enable webhook posts, enter your endpoint URL, and save. Use a public HTTPS endpoint that accepts POST directly. URL validation rejects HTTP, embedded credentials, and private/internal hosts outside local development, and removes fragments. Redirects are not followed. Existing HTTP destinations are also blocked at delivery time.
- On the saved app, use Rotate token to generate a token, or Set token to supply one you control. Custom tokens must be 16–256 characters after trimming. Copy a generated token while it is displayed and store it on your backend.
- Save URL changes before testing. Paste the raw token, choose a test event, and select Send test.
When you create an app with webhooks enabled, the success screen shows its generated token once. Copy it before selecting Done or closing the screen. Reopening the editor cannot retrieve it; rotate or set a replacement if needed. Enabling webhooks later also requires setting or rotating a token if none exists.
Tests support session.created, session.updated, and session.deleted. An optional lock ID provides more context, but you must be that lock's wearer or current keyholder and the app must be enabled on it. Without a lock ID, lock, session, and user fields are null. Tests do not populate extension or event-specific eventData, even with a lock ID.
The test result's ok: true means the test request ran. Check delivered and status to see whether your endpoint accepted it. A test is sent immediately and does not exercise queued retries. There is no dedicated test flag in the webhook payload, so use a test receiver or safe test configuration before choosing an event that your backend treats as an action.
Authenticate requests
Deliveries contain these headers:
Content-Type: application/json
x-webhook-event: lock.time_changed
x-webhook-id: b973c37a-d484-4283-9e25-f20cf5b249f8
x-webhook-timestamp: 1791115200
x-webhook-signature: v1=HMAC_SHA256_HEX
The signing key is the lowercase SHA-256 hex string of your raw webhook token, used as UTF-8 text (64 ASCII bytes, not 32 decoded bytes). This secret is separate from a Developer API key or iframe launch token and is never transmitted in webhook headers.
The signature is lowercase HMAC-SHA256 hex over the concatenation of the delivery timestamp, a period, the event ID, another period, and the exact raw request body bytes:
HMAC_SHA256(key, timestamp + "." + eventId + "." + rawBody)
The timestamp header is Unix seconds generated for each delivery attempt. Accept only timestamps within 300 seconds of your clock, including future timestamps. The body timestamp remains the original event time, so old queued events can arrive with a fresh signature. Do not reserialize parsed JSON before checking the signature: whitespace, Unicode encoding, and field order are covered.
For example, this Node.js function verifies authentication against a bounded raw body:
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
const token = process.env.CHASTIFY_WEBHOOK_TOKEN;
if (!token) throw new Error("Configure CHASTIFY_WEBHOOK_TOKEN");
const key = createHash("sha256").update(token).digest("hex");
export function validWebhookSignature(headers, rawBody) {
const timestamp = headers["x-webhook-timestamp"];
const id = headers["x-webhook-id"];
const signature = headers["x-webhook-signature"];
if (typeof timestamp !== "string" || !/^\d{10}$/.test(timestamp)) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) return false;
if (typeof id !== "string" || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(id)) return false;
if (typeof signature !== "string" || !/^v1=[a-f0-9]{64}$/.test(signature)) return false;
const expected = createHmac("sha256", key)
.update(`${timestamp}.${id}.`).update(rawBody).digest();
return timingSafeEqual(Buffer.from(signature.slice(3), "hex"), expected);
}
After signature verification, parse JSON, require the body id and event to match their headers, and validate fields your application uses. Atomically claim app.id plus id in a replay store before event work. Reject or acknowledge duplicates without running that work again. Store only authenticated, validated events; fail closed if your replay store is unavailable or full. Keep both the raw token and derived signing key out of logs and browser code.
The Node and Go sample receivers in apps/extension/server verify exact bytes, enforce a five-minute signature window, and reject duplicates with 409 webhook_replayed. Their caches hold up to 10,000 entries for 24 hours and return 503 when full instead of evicting active entries. These caches are local to a running process. For multiple instances or restart protection, use a shared durable store with atomic claims and a retry-safe processing state; extend retention to cover your reconciliation needs. Webhooks remain notifications, not an exactly-once event ledger.
Receivers that compare x-webhook-token-hash must migrate to signatures; there is no legacy-header fallback. Move HTTP endpoints to HTTPS and coordinate receiver, proxy Worker, and Chastify server updates. Rotate previously used webhook tokens and update the receiver's configured raw token: a previously exposed hash is also a signing key. Already queued direct-app jobs or in-flight requests can carry an older key and be rejected after rotation; reconcile missed events through the API as needed. This protocol change does not repair previously exposed data or credentials automatically.
For local development only, the Chastify server can use HTTP when both NODE_ENV=development and EXTENSION_WEBHOOK_ALLOW_HTTP_LOOPBACK=true are set. Only localhost, IPv4 loopback (127.0.0.0/8), or IPv6 loopback (::1) qualifies; LAN and public HTTP destinations remain blocked. The proxy Worker always requires a public HTTPS destination, and its own configured URL must also pass public HTTPS validation. Use direct development delivery when testing loopback HTTP.
Payload envelope
A lock event can look like this:
{
"id": "b973c37a-d484-4283-9e25-f20cf5b249f8",
"event": "lock.time_changed",
"eventData": {
"source": "keyholder",
"requestedDeltaSeconds": 3600,
"appliedDeltaSeconds": 3600
},
"timestamp": "2026-10-04T12:00:00.000Z",
"app": {
"id": "64b000000000000000000001",
"slug": "my-app",
"displayName": "My App"
},
"sessionId": "64b000000000000000000002",
"extension": {
"sessionId": "64b000000000000000000002",
"enabled": true,
"config": {}
},
"wearer": { "id": "64b000000000000000000003", "username": "wearer_name" },
"keyholder": { "id": "64b000000000000000000004", "username": "keyholder_name" },
"lock": {
"id": "64b000000000000000000005",
"title": "Lock title",
"releaseAt": "2026-10-05T12:00:00.000Z",
"remainingSeconds": 86400,
"isLocked": true,
"isFrozen": false
}
}
sessionId identifies the installed extension session, not the lock or app. eventData, extension, wearer, keyholder, and lock can be null; individual fields can also be null or absent. In particular, direct session.updated notifications can omit the extension and user objects. Accept additional fields and safely ignore event names your integration does not use.
Normal lock-event dispatch includes that extension's saved configuration. A real session.created event can therefore carry configuration saved with the lock, rather than unsaved setup drafts. Webhooks do not supply a Developer API key or launch token for calling back into Chastify; use the authentication flow in Developer API Overview.
The lock object is a limited snapshot. Queued events capture remainingSeconds when enqueued, using the shared countdown rules: a frozen timer preserves its remaining value, including zero, and running timers respect applicable minimum durations. Accumulated changes deferred until unfreezing are not added to the paused countdown. The captured value stays unchanged across retries; it is not a live countdown. Older queued snapshots without enough historical timing data return remainingSeconds: null and isLocked: null. Immediate tests calculate the value when sent.
isLocked only means that this countdown is greater than zero. It is not a comprehensive unlock-eligibility flag, particularly for card locks or other requirements. Use the normal unlock checks to decide whether a lock may be unlocked.
Delivery, Retries, and Ordering
Normal events are queued in Redis and processed in the background. The worker is scheduled approximately once per second, but backlog and processing time affect delivery latency. An in-flight list allows recovery on worker restart. Returning a delayed job to the waiting queue moves its receipt atomically; a failed move leaves the receipt recoverable. These mechanisms do not make delivery loss-free.
| Result | Normal queued behavior |
|---|---|
HTTP 2xx | Accepted; no retry. |
| Timeout or network/delivery error | Retry while attempts remain. |
HTTP 429 or 5xx | Retry while attempts remain. |
Other 4xx, or 3xx redirect | No retry. Redirects are not followed. |
| Webhook disabled, missing configuration, or rejected target URL | Skipped. |
The target request timeout is approximately 3 seconds. Retry delays are 15, 60, 150, and 600 seconds, allowing up to five normal attempts including the first. Delays are minimum scheduling waits, not delivery deadlines, and the endpoint's Retry-After header does not control them. Crash recovery can produce additional duplicate attempts.
Return a fast 2xx after your own durable acceptance step and process expensive work asynchronously. Duplicate, late, missing, and out-of-order notifications are possible. The queue has finite capacity and finite retries; do not describe this as guaranteed at-least-once delivery. Reconcile important state through available authenticated APIs.
The top-level id identifies one queued source event. Its deliveries to multiple apps share that ID, and retries and worker recovery preserve it. Deduplicate deliveries using app.id plus id. Separately queued events receive different IDs even when their contents are identical. Each immediate test send also receives a fresh ID.
The timestamp is the original enqueue/capture time, not the retry attempt time or necessarily the exact time of the underlying action. It remains unchanged on retry. Immediate tests use their send time. Jobs queued before stable IDs were introduced receive an ID durably before their next delivery; this cannot correlate attempts delivered before the upgrade.
Some producers also provide domain identifiers such as eventData.id, runId, or verificationId. These can help reconcile state, but one task can undergo several distinct transitions. Do not deduplicate separate events just because their payloads or domain IDs match.
Queued lock data and configuration can describe an earlier state. Do not assume an older delivery should overwrite a newer state. There is no per-event subscription selector in the current webhook settings; filter supported event names in your receiver.
Event Data
The sections below describe common payloads. Fields vary by the action that produced an event; examples are not closed schemas or promises that every field is always present.
Other current event families include:
| Events | Context |
|---|---|
session.created, session.deleted, session.updated | Session creation/deletion and selected extension or delegated-control updates. session.updated is not emitted for every possible lock change. |
lock.timer_hidden, lock.timer_revealed | Timer visibility changes, with beforeVisible and afterVisible. |
lock.keyholder_trusted | Keyholder trust enabled. |
lock.max_date_increased, lock.max_date_removed | Changes to the maximum unlock date; relevant before/after fields vary by event. |
public_voting.vote_received, share_link.time_changed | Public votes and share-link time changes. |
pillory.vote_received, pillory.entered, pillory.left | Pillory votes and state changes. |
task.canceled, task.vote_ended, task.verification_approved, task.verification_rejected | Task cancellation and photo-review decisions. A verified completion can emit multiple event types. |
quiz.passed, quiz.failed, quiz.expired | Lock-linked quiz outcomes, with quiz run/task identifiers and result details. |
hygiene.granted, hygiene.grant_revoked | Permission to start a hygiene break, distinct from actually starting it. Includes grantId, expiry, window, and penalty information. |
verification.approved, verification.rejected | Submitted daily verification decisions; not every hygiene or task-photo decision uses these names. |
cage_check.submitted | Cage-check submission, including request ID and photo information. |
device.shocked | Reported shock-command outcome, with success, strength, duration, and source. Read success; the name alone is not proof of delivery. |
geofence.zone_entered, geofence.zone_exited, geofence.allowed_area_entered, geofence.allowed_area_exited, geofence.penalty_active, geofence.penalty_inactive | Zone/allowed-area transitions and changes in penalty state. |
coach.enabled, coach.disabled | AI or bot coach status changes. |
parental_control.app_blocked, parental_control.website_blocked | Device Control blocked-action telemetry, including app/package or domain information. |
parental_control.self_lock_expired, parental_control.self_lock_below, parental_control.screen_time_expired, parental_control.screen_time_below, hardcore_mode.expired, hardcore_mode.below | Threshold crossings generated by configured Programmable Lock timer triggers. Do not assume these are emitted for every device timer without those triggers. |
wheel.result, wheel.text_action | Wheel outcome and text-action details. |
Calendar event names also exist in the internal event model, but the calendar queue delivers calendar.event_active, calendar.event_ended, and calendar.event_changed directly to Programmable Lock. Their presence in that model is not a promise of external webhook delivery.
lock.time_changed
{
"event": "lock.time_changed",
"eventData": {
"source": "keyholder",
"beforeReleaseAt": "2026-10-05T12:00:00.000Z",
"afterReleaseAt": "2026-10-05T13:00:00.000Z",
"requestedDeltaSeconds": 3600,
"appliedDeltaSeconds": 3600
}
}
Requested and applied amounts may differ. Some producers derive the applied amount from release timestamps; it can be null when that calculation is unavailable. Frozen/card-lock behavior and additional fields vary by source. Newer producers can include eventData.id, source time, before/after freeze flags, and cappedByMinimum. Do not apply a time-changing action again merely because this notification arrives.
lock.frozen / lock.unfrozen
{
"event": "lock.frozen",
"eventData": {
"source": "keyholder",
"durationSeconds": 3600,
"beforeFrozen": false,
"afterFrozen": true
}
}
{
"event": "lock.unfrozen",
"eventData": {
"source": "dice",
"durationSeconds": 900,
"beforeFrozen": true,
"afterFrozen": false
}
}
durationSeconds describes the producing action and may be null. Use the explicit transition flags rather than interpreting every duration as a new freeze.
task.* events
Task producers can include runId, taskId, taskTitle, taskDescription, taskPoints, and status. Some assignment paths also include the task object. Use runId to distinguish repeat assignments of the same task; do not infer review approval from an assignment notification.
task.assigned
{
"event": "task.assigned",
"eventData": {
"runId": "tr_example",
"taskId": "task_123",
"taskTitle": "Example task",
"taskDescription": "Instructions for this task",
"taskPoints": 10,
"status": "queued",
"source": "keyholder",
"queued": true
}
}
An assignment can be queued rather than active. queued and overriddenRunId are source-dependent, not required fields.
task.completed
{
"event": "task.completed",
"eventData": {
"runId": "tr_example",
"taskId": "task_123",
"status": "completed",
"pointsAwarded": 10,
"timeReducedSeconds": 300
}
}
Some writing/quiz producers use points instead of pointsAwarded. A verified task may emit task.vote_ended and task.verification_approved before task.completed; these are separate notifications about the same run.
Task-run payloads include taskSubmittedAt when a verification submission exists. It is the original submission date serialized as an ISO timestamp, which may be earlier than approval or completion. Verification-decision payloads also include their review time as eventData.timestamp; verified completion payloads use the recorded completion time. The envelope's timestamp remains the original enqueue time. Programmable Lock exposes the submission date separately as task submission timestamp (Unix seconds) for calendar entries that should be dated to the submitted work.
task.failed
{
"event": "task.failed",
"eventData": {
"runId": "tr_example",
"taskId": "task_123",
"status": "failed",
"penaltyApplied": true,
"outcomeDescription": "1 hour added"
}
}
Failure payloads can instead include a reason or quiz context. The webhook reports an outcome; it does not ask your receiver to reapply its penalty.
hygiene.* events
A hygiene grant, the start of a break, and resuming the lock are different events. See Hygienic Unlock for the user workflow.
hygiene.started
{
"event": "hygiene.started",
"eventData": {
"startedAt": "2026-10-04T12:00:00.000Z",
"expiresAt": "2026-10-04T12:30:00.000Z",
"windowSeconds": 1800,
"penaltySeconds": 3600
}
}
hygiene.resumed
{
"event": "hygiene.resumed",
"eventData": {
"completedAt": "2026-10-04T12:20:00.000Z",
"lateMinutes": 0,
"penaltyApplied": false,
"punishmentSeconds": 0,
"penaltyMode": null,
"cardsAdjusted": 0,
"actualDeltaSeconds": null
}
}
hygiene.resumed_late
{
"event": "hygiene.resumed_late",
"eventData": {
"completedAt": "2026-10-04T12:45:00.000Z",
"lateMinutes": 15,
"penaltyApplied": true,
"punishmentSeconds": 3600,
"penaltyMode": "time",
"cardsAdjusted": 0,
"actualDeltaSeconds": 3600
}
}
Resumed payloads can also include hygiene timing and a change of relock method. Lateness and applied punishment are separate facts; inspect penaltyApplied, penaltyMode, and the actual adjustment fields instead of assuming every late return added time.
verification.picture_submitted
{
"event": "verification.picture_submitted",
"eventData": {
"verificationId": "64b000000000000000000006",
"date": "2026-10-04",
"submittedAt": "2026-10-04T12:10:00.000Z",
"photoUrl": "https://storage.example/verification-photo?signature=EXAMPLE",
"photoSource": "camera"
}
}
Daily submissions can include date; post-hygiene submissions instead identify verificationKind: "hygienic_unlock". Other producers can include additional context. Submission is not approval. Treat a photo link as sensitive and potentially expiring, and do not assume queued retries refresh it.
dice.rolled
{
"event": "dice.rolled",
"eventData": {
"diceCount": 3,
"diceTypes": "d6, d8",
"d4Count": 0,
"d6Count": 2,
"d8Count": 1,
"d10Count": 0,
"d12Count": 0,
"d20Count": 0,
"userDiceValues": "6, 2, 6",
"botDiceValues": "1, 3, 4",
"userTotalScore": 14,
"botTotalScore": 8,
"difference": 6,
"requestedAdjustmentSeconds": -3600,
"appliedAdjustmentSeconds": -3600,
"cardGameEnabled": false
}
}
The dice counts describe the player’s dice in one roll, using the configuration saved when that roll started. They exclude the bot’s dice and available roll credits. diceTypes lists the types with nonzero counts in ascending order; the example uses two d6 and one d8. Programmable locks expose these as “number of dice”, “dice types”, and the individual per-type counts in the “When dice rolled” event variables.
userDiceValues and botDiceValues contain the saved individual results as comma-separated text, ordered by type (d4, d6, d8, d10, d12, d20). Both lists use the same order. Programmable locks expose these text values and a numeric “player/bot die at position … value” block under Lock Data. Positions start at 1: in the example, player die 2 returns 2 and bot die 3 returns 4. Use a number or loop variable as the position. Missing dice, unavailable legacy results, and invalid positions return 0. Draft and event tests accept the same comma-separated lists.
The Lists category also provides rolled dice [player/bot], which returns a numeric array: the example produces [6, 2, 6] for the player and [1, 3, 4] for the bot. It reads the same saved server outcome; it does not roll again. Existing text event variables and single-die blocks remain available.
Connect the result to item … of list, length / sum / maximum of list, or for each … in list. A Number list variable can store the result, including in persistent memory. For example:
When dice rolled
set rolls to rolled dice [player]
set sixes to 0
for each die in list rolls
if die = 6
change sixes by 1
set total to sum of list rolls
Here sixes becomes 2 and total becomes 14; selecting bot gives 0 and 8. Those numbers can feed ordinary comparisons, arithmetic, and action blocks. Lists contain at most 100 finite numbers. Starting values and draft variable overrides use JSON, such as [6, 2, 6]; dice event test inputs continue to use comma-separated text. Missing dice results produce an empty list. Empty-list statistics and missing items return 0. Each loop captures its list at the start, so changing the source variable inside the loop does not change its remaining iterations.
A dice outcome can also generate time-change or unfreeze notifications. They describe related effects, not independent requests to apply rewards again.
lock.archive_removal
{
"event": "lock.archive_removal",
"eventData": {
"source": "archive",
"actorRole": "wearer",
"lockId": "64b000000000000000000005"
}
}
source is delete or archive; actorRole is wearer or keyholder. Archiving from one participant's view is not necessarily physical deletion of the lock or every related file. Some lifecycle paths also emit session.deleted; consumers must tolerate both notifications.
Privacy and receiver responsibilities
Webhook payloads can contain user IDs/usernames, lock titles and release times, the extension's saved config, task instructions, verification/cage-check photo links, and Device Control app/domain information. Timer visibility in Chastify's UI is not used to redact releaseAt from the webhook envelope. Normal dispatch targets enabled extensions with active, configured webhook apps; REST read/write scopes are not per-field webhook privacy filters.
Store only what the integration needs, restrict access to payloads and logs, and explain the data your endpoint receives to its users. A signed photo URL, shared credential hash, or event name should not be exposed as public debugging data. Use a controlled test lock to inspect the specific feature payloads your integration depends on.