try-works/role-model / .agents/skills/turnstile-spin
turnstile-spin
VerifiedSet up Cloudflare Turnstile end-to-end in a project — scan the codebase, create the widget via the Cloudflare API, deploy the managed siteverify Worker, write the frontend snippets, validate, and persist the skill. Load this when a user asks to add Turnstile, set up CAPTCHA, protect a form from bots, or fix a Turnstile integration. Mirrors developers.cloudflare.com/turnstile/spin.
templates/worker/src/validate.ts
View on GitHub/**
* Calls Cloudflare's siteverify endpoint. One retry on transient (5xx + network)
* failures, with a tight timeout. Returns the upstream JSON unmodified plus
* Worker metadata.
*/
import { SiteverifyError } from './errors.js';
import type { Env, SiteverifyRequest, SiteverifyResponse } from './types.js';
const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
const UPSTREAM_TIMEOUT_MS = 5000;
const RETRY_ON_STATUSES = new Set([500, 502, 503, 504]);
export interface ValidateResult {
response: SiteverifyResponse;
upstreamStatus: number;
durationMs: number;
}
/**
* Validate a Turnstile token against Cloudflare's siteverify endpoint.
*
* @throws SiteverifyError on Worker-level failures (missing secret, unreachable upstream, timeout)
*/
export async function validate(req: SiteverifyRequest, env: Env, workerVersion: string): Promise<ValidateResult> {
if (!env.TURNSTILE_SECRET_KEY) {
throw new SiteverifyError(500, 'missing-input-secret', 'TURNSTILE_SECRET_KEY not configured');
}
if (!req.token) {
throw new SiteverifyError(400, 'missing-token', 'token is required');
}
const body = new FormData();
body.append('secret', env.TURNSTILE_SECRET_KEY);
body.append('response', req.token);
if (req.remoteip) body.append('remoteip', req.remoteip);
if (req.idempotency_key) body.append('idempotency_key', req.idempotency_key);
const start = Date.now();
let lastErr: unknown = null;
for (let attempt = 0; attempt < 2; attempt++) {
try {
const result = await fetchWithTimeout(SITEVERIFY_URL, body, UPSTREAM_TIMEOUT_MS);
const durationMs = Date.now() - start;
if (result.status >= 200 && result.status < 300) {
const data = (await result.json()) as SiteverifyResponse;
data._worker = {
duration_ms: durationMs,
worker_version: workerVersion,
};
// Hostname-mismatch defense. If the customer set EXPECTED_HOSTNAME,
// reject responses whose hostname doesn't match — defends against
// cross-site token replay even if a token leaks.
if (data.success && env.EXPECTED_HOSTNAME && data.hostname && data.hostname !== env.EXPECTED_HOSTNAME) {
const rejected: SiteverifyResponse = {
...data,
success: false,
'error-codes': ['hostname-mismatch'],
};
return { response: rejected, upstreamStatus: result.status, durationMs };
}
return { response: data, upstreamStatus: result.status, durationMs };
}
if (!RETRY_ON_STATUSES.has(result.status) || attempt === 1) {
// Don't retry on 4xx, return the upstream body as-is so customers
// see exactly what siteverify said.
const data = (await result.json().catch(() => ({}))) as Partial<SiteverifyResponse>;
const response: SiteverifyResponse = {
success: false,
'error-codes': data['error-codes'] ?? ['bad-request'],
...data,
_worker: { duration_ms: durationMs, worker_version: workerVersion },
};
return { response, upstreamStatus: result.status, durationMs };
}
// 5xx + first attempt: retry
} catch (err) {
lastErr = err;
if (attempt === 1) break;
}
}
if (lastErr instanceof DOMException && lastErr.name === 'AbortError') {
throw new SiteverifyError(504, 'upstream-timeout', `Upstream timeout after ${UPSTREAM_TIMEOUT_MS}ms`);
}
throw new SiteverifyError(502, 'upstream-unreachable', `Upstream siteverify unreachable: ${String(lastErr)}`);
}
async function fetchWithTimeout(url: string, body: FormData, timeoutMs: number): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, {
method: 'POST',
body,
signal: controller.signal,
});
} finally {
clearTimeout(timer);
}
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |