Skip to main content

API Examples

Use this page for an installed extension. For a personal script using a user-wide key, follow External API & Programs; those endpoints have different authorization and limits.

The runtime iframe bridge reads session context, state, metadata, and files. Your backend performs mutations with an app-scoped Developer API key and the launch's x-chastify-main-token. A Developer key never belongs in browser code.

Request and Response Format​

A runtime bridge request uses this envelope:

{
"type": "chastify:ext:req",
"v": 1,
"id": "req-123",
"nonce": "FROM_LAUNCH_PAYLOAD",
"action": "session.get",
"payload": {}
}

A successful response echoes the request ID:

{
"type": "chastify:ext:resp",
"v": 1,
"id": "req-123",
"ok": true,
"data": {}
}

For failures, inspect error.code and error.message. Validate the parent window, parent origin, protocol version, and pending request ID before accepting a response. The nonce correlates a launch; it is not a secret or proof of completion. See the iframe quickstart for the bridge helper and launch parsing.

The bridge.request(...) snippets below assume that helper is already initialized. HTTP examples instead run on your backend.

Session and Context​

session.get​

const context = await bridge.request('session.get', {});
const commands = context.deviceControl?.supportedCommands ?? [];

Use the returned role, scopes, extension configuration, lock data, and device capabilities to build the UI. Capability information is a snapshot; Chastify checks permissions and device state again when an action is requested.

Timing and status fields are not a complete unlock decision. Preserve the lock's hidden-time settings when displaying data, and use Chastify's normal unlock flow. Last-seen timestamps can be null when a participant hides online status.

Backend Extension Flows​

  1. The iframe reads mainToken and sessionId from the launch payload and sends them to your own backend over HTTPS.
  2. Your backend requests the session context with both credentials.
  3. It binds its game/activity record to the returned session, lock, and user, and validates the requested operation.
  4. It performs the permitted Chastify mutation and records the outcome.
Completion must be verified

A session ID is not authentication, and a launch token does not prove that a game was won. Do not turn your backend into a general proxy for browser-supplied action names, rewards, or device parameters. Validate outcomes and choose the allowed effect on your server.

Fetch Session Context Safely​

This server-side helper is shared by the examples below. Store CHASTIFY_APP_DEVELOPER_KEY in your server environment. launch contains the session ID and main token from the current launch.

type Launch = { sessionId: string; mainToken: string };

async function extensionRequest(
launch: Launch,
path = '',
method = 'GET',
body?: unknown,
) {
const response = await fetch(
`https://chastify.net/api/extensions/sessions/${encodeURIComponent(launch.sessionId)}${path}`,
{
method,
headers: {
Authorization: `Bearer ${process.env.CHASTIFY_APP_DEVELOPER_KEY}`,
'x-chastify-main-token': launch.mainToken,
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
},
);
const data = await response.json();
if (!response.ok) {
throw Object.assign(new Error(data.message ?? data.error ?? 'Chastify request failed'), {
status: response.status,
data,
});
}
return data;
}

const context = await extensionRequest(launch);

Handle errors in your own HTTP handler or job boundary. The helper deliberately makes one request: a timeout after a mutation leaves its outcome uncertain, so silently retrying could duplicate time, progress, tasks, or commands.

Apply Time From An Extension Backend​

After your backend has verified the activity and selected the effect:

await extensionRequest(launch, '/action', 'POST', {
name: 'add_time',
params: 300,
});

Use remove_time to subtract time. The action name determines the sign: add_time with -300 still adds 300 seconds. remove_time needs a keyholder launch; on shared locks, adding time also requires the keyholder. The Developer key does not upgrade the launch user's role.

Server-Verified Game Completion​

Keep game results and effect amounts on your backend. For each completion, verify that the run belongs to the authenticated extension session, is still valid, satisfies your game rules, and has not already been processed. Record which effects succeeded before starting another effect.

A local “processed” flag alone cannot make an external HTTP mutation exactly-once: the server can apply an action while your connection fails before you receive its response. Do not resend an uncertain reward or punishment automatically. Reconcile the result before another attempt, and let users see when an outcome needs checking.

Scheduled Requirements​

For recurring activities, configure extensionRequirements and report verified progress:

await extensionRequest(launch, '/requirements/progress', 'POST', {
metric: 'completion',
amount: 1,
});

amount is an integer from 1 to 1,000. metric defaults to the configured metric, or completion. An optional ISO occurredAt should come from your verified event record, not an unchecked browser timestamp. Repeated submissions count again; this endpoint does not accept an event ID for deduplication.

See Extension Requirements below and Features for cadence, attempts, regular actions, and their separate responsibilities.

Notifications​

notifications.custom​

Backend endpoint: POST /api/extensions/sessions/:sessionId/notifications/custom.

await extensionRequest(launch, '/notifications/custom', 'POST', {
title: 'Challenge complete',
message: 'Your verified completion has been recorded.',
target: 'wearer',
showPageOverlay: false,
});

title allows 1–100 characters; message allows 1–500. target is wearer (default), keyholder, or both; showPageOverlay defaults to false. The route requires locks:write and reports queued dispatch, not that the recipient has received or read the message. There is no runtime bridge notification mutation.

Extension State​

State belongs to an installed extension session. Reads require locks:read; writes require backend credentials and locks:write. The app can define a state schema and size limit; the default limit is 64 KiB.

state.put​

PUT /state replaces the entire data value:

await extensionRequest(launch, '/state', 'PUT', {
data: { puzzle: { round: 1, imageFileId: 'FILE_ID' } },
});

Use this only when you own the complete replacement. Requirement and attempt services also store data in this state; replacing it can erase their progress. Do not overwrite their managed fields. Store file IDs instead of binary content or expiring signed URLs.

state.patch​

PATCH /state applies JSON Merge Patch:

await extensionRequest(launch, '/state', 'PATCH', {
data: { puzzle: { round: 2, temporaryHint: null } },
});

Objects merge, null deletes a key, and arrays are replaced. This sets an absolute value; it is not an atomic increment or a concurrency-safe counter API. Use your own durable server records for authoritative game counters and preserve unrelated state.

state.get​

const state = await bridge.request('state.get', {});
console.log(state.data);

The result contains { data, updatedAt }; an uninitialized session has empty data and a null timestamp. Backend reads use GET /state.

File Storage​

Use Extension File Storage for upload policy, quota, file ownership, and the separate setup staging flow. Runtime writes are backend-only; the runtime bridge exposes file reads.

files.capabilities​

Check the current policy before offering an upload:

const capabilities = await bridge.request('files.capabilities', {});

Runtime files.upload​

Upload through POST /api/extensions/sessions/:sessionId/files from your backend using multipart form data and both credentials. There is no runtime files.upload bridge action. Follow the storage guide's upload example instead of sending multipart data through the JSON helper above.

files.get​

Resolve a stable file ID to a fresh signed URL when displaying it:

const result = await bridge.request('files.get', { fileId: 'FILE_ID' });
image.src = result.file.signedUrl;

files.list​

const result = await bridge.request('files.list', {});

Use the storage guide for the list response and filtering. Runtime deletion also requires your backend; it is not a bridge command.

Lock Actions​

The following bodies are for POST /api/extensions/sessions/:sessionId/action, using both credentials and locks:write. Lock activity, feature settings, role, trust, and time limits can reject otherwise valid requests. See Features for the role table.

Add time​

{ "name": "add_time", "params": 300 }

Use { "name": "remove_time", "params": 300 } to remove five minutes. The magnitude must not exceed 365 days in seconds. Maximum-time and untrusted-keyholder budgets can further restrict additions.

Freeze​

{ "name": "freeze", "params": { "durationSeconds": 1800 } }

The installed-extension endpoint accepts 60 seconds to 7 days, defaulting to one hour. Shared-lock freezes require the keyholder. toggle_freeze needs a keyholder launch and, on a shared lock, trusted-keyholder access.

Unfreeze​

{ "name": "unfreeze" }

Requires a keyholder launch. A hygienic opening can keep the timer paused even after an ordinary freeze is removed; inspect the returned lock.frozen instead of assuming the countdown resumed.

Pillory​

{
"name": "pillory",
"params": { "durationSeconds": 3600, "reason": "Verified missed challenge" }
}

Pillory must be enabled. Duration accepts 60 seconds to 30 days and otherwise defaults to the configured initial duration, or one hour. Untrusted shared-keyholder requests must use that configured duration and obey cooldown restrictions.

End pillory​

{ "name": "pillory.end" }

On a shared lock this requires a trusted keyholder. It is not an unlock action.

Assign task​

{
"name": "task.assign",
"params": {
"actor": "extension",
"title": "Complete your check-in",
"description": "Record the result in this extension.",
"points": 2,
"durationMinutes": 10,
"verificationRequired": false
}
}

Tasks must be enabled. actor is required: extension, wearer, or keyholder; the latter two must match the launch role. Titles are required and limited to 120 characters; points are clamped to 0–100 and duration to 0–1,440 minutes. The legacy durationSeconds field is converted to whole minutes rounded up.

Assignment creates another task run subject to queue/selection limits; it does not cancel existing open tasks. See Tasks & Task Queue.

Start task timer​

{ "name": "task.start_timer" }

This targets the most recently created open task run for the lock/session, not an ID in your request. It requires a timed task and sets its completion time from now. Calling it again restarts that timer. Avoid using it when you cannot establish which task it will affect.

Complete task​

{ "name": "task.complete", "params": { "successful": true } }

This also targets the most recently created open task run and requires a keyholder launch. Successful completion requires a started and finished timer where applicable, and a valid task deadline. Photo-verification tasks must use the task verification flow; this endpoint rejects successful completion for them.

To record failure, send { "successful": false, "reason": "Reason" }. Failure does not award the task's points.

Trigger temporary opening​

{ "name": "hygienic_unlock.start", "params": { "durationSeconds": 1800 } }

Requires a keyholder launch, Hygienic Opening enabled, and no existing hygienic opening or soft emergency release; shared locks also require a trusted keyholder. This begins the lock's hygienic-opening workflow. It is not a general command to physically unlock a device. See Hygienic Unlock.

Metadata and Home Actions​

metadata.patch​

Backend endpoint: PATCH /api/extensions/sessions/:sessionId/metadata.

await extensionRequest(launch, '/metadata', 'PATCH', {
unlockBlockers: ['Finish the verified challenge'],
homeActions: [
{
slug: 'open-challenge',
title: 'Open challenge',
description: 'Continue your current round',
intent: { type: 'open_panel', payload: { panel: 'challenge' } },
},
],
});

Only include fields you intend to replace. Supplied arrays replace their existing values; [] clears that field. There are up to 25 unlockBlockers, up to 25 unlockRequirements, and up to 50 homeActions, with a combined metadata limit of 16 KiB. Backend writes require locks:write; metadata.get is available through the read-only bridge.

For a count-based unlock condition, use unlockRequirements with a stable metric, requiredCount, and optional blocker message. The Features guide explains its relationship to recurring requirements and progress.

Intents: developer app example​

A home-action launch can include homeActionSlug and intent in the iframe payload. They select a view; they do not authorize or prove completion of an action.

// launchPayload was decoded using the iframe quickstart.
if (
launchPayload.homeActionSlug === 'open-challenge' &&
launchPayload.intent?.type === 'open_panel' &&
launchPayload.intent?.payload?.panel === 'challenge'
) {
showChallengePanel();
}

Allow only panels your UI supports. Reopening a home action should reopen the view; do not use persistent “already handled” flags to suppress future legitimate clicks.

Device Command​

device.command​

Backend endpoint: POST /api/extensions/sessions/:sessionId/device-command.

await extensionRequest(launch, '/device-command', 'POST', {
command: 'vibration.start',
params: { durationSeconds: 5, intensityPct: 20, frequencyPct: 50 },
});

Read session.get and deviceControl.supportedCommands before offering controls. Submit the user's permitted request to your own backend, which validates it and makes this HTTP call. bridge.request('device.command', ...) is not supported.

Supported command names are shock.start, shock.stop, vibration.start, vibration.stop, all.stop, shock.random.set, and shock.berserk.set. Random and berserk modes require Lockink AA-A1012 and are timed requests. See command parameters; the installed-extension endpoint uses the same parameter shapes, but the credentials and queue context differ.

A successful response can mean the request was queued. Inspect result.queued, any delivery event ID, expiry, and message rather than presenting “delivered” immediately. Active flags alone are not proof of physical execution. Do not repeat a start command because its response was lost: a repeat can create another delivery. Device policies may adjust the requested duration/intensity or route supported effects differently; capability presence does not bypass consent or keyholder policy.

A stop requests stopping the current effect; it does not promise to erase every outstanding mandatory delivery. See Shock Delivery & Queues for delivery and recovery behavior.

Extension Requirements​

Use recurring requirements for verified activities such as one completed puzzle per day. These differ from lifetime unlock requirements and regular-action availability.

Configuration shape​

Store this in the extension session's configuration:

{
"extensionRequirements": {
"enabled": true,
"metric": "completion",
"requiredCount": 1,
"cadence": { "every": 1, "unit": "day" },
"punishment": {
"type": "add_time",
"seconds": 900,
"reason": "Missed extension requirement"
}
}
}

Cadence units are day or week. Windows use the wearer's configured timezone, falling back to UTC. Punishment types are none, add_time, freeze, and pillory; the applicable lock settings and policy still matter.

Progress model​

Record verified events with POST /requirements/progress using { metric, amount, occurredAt? }. The service updates the metric's lifetime unlock progress and, when recurring requirements are enabled, progress for the relevant cadence window.

Generic state writes are not a completion API, but they can overwrite the same stored data. Preserve service-managed requirement/attempt fields and use the dedicated endpoint. Keep metric names stable; changing one changes which progress is counted.

Runtime behavior​

Configured requirements can appear in Today Progress. A scheduled job evaluates elapsed windows and applies configured consequences for missed requirements. Do not build a second penalty scheduler on top of it or assume exactly-once processing across failures and concurrent work. Progress submissions themselves are also additive rather than deduplicated.

  1. Configure the requirement during setup and read the installed configuration at runtime.
  2. Verify the user's activity on your backend against a durable activity record.
  3. Submit one progress event for the verified completion and track the result.
  4. Refresh state/context for the UI; reconcile uncertain submissions before retrying.

Use Features when combining recurring requirements with unlock blockers, attempt limits, or regular actions. Completing one mechanism does not automatically complete all the others.

  1. Read context and state, then check the current role, configuration, and capabilities.
  2. Validate the activity on your backend and choose its permitted effect.
  3. Apply each necessary mutation once, checking its response before the next step.
  4. Persist the outcome, refresh the UI, and send an optional notification after successful completion.
  5. If a response is lost, investigate the uncertain result instead of repeating the whole sequence.