---
url: /docs/api/submissions.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Accept submissions
The public submission endpoint is:
```text
POST /s/v1/{environment}/{publicSubmissionId}
```
Supported media types are `application/json`, `application/x-www-form-urlencoded`, and `multipart/form-data` without file parts. Any multipart file rejects the entire request; files are never silently discarded.
## Browser and server boundaries
- Browser `fetch` requests use the sandbox draft or production published origin allowlist. Use `credentials: 'omit'`; account cookies do not authenticate submissions.
- Production public-browser requests require an allowed `Origin`.
- Production server requests without `Origin` require `Authorization: Bearer ...` (see [Server API keys](/docs/api/keys.md)).
- Sandbox permits documented no-origin development tools such as `curl`.
- Native HTML forms may use optional preconfigured success and error redirects.
- JSON requests receive structured API responses. URL-encoded or multipart requests with `Accept: text/html` are treated as browser navigation and can receive an HTML result page or configured redirect.
An `Origin` header selects origin validation, even if a bearer key is also supplied. Origin checks are not authentication; non-browser clients can forge this header. Opaque `null` origins fail the allowlist check.
## HTML field normalization
Repeated names become ordered arrays. A constrained bracket grammar supports `contact[email]`, `tags[]`, and `items[0][name]`. Dot notation remains literal. Ambiguous scalar/container conflicts and unsafe property names are rejected.
Strict schemas may coerce canonical numeric strings and exact `true` or `false` strings. Flexible forms preserve HTML values as strings.
## Idempotency
Server integrations send `Idempotency-Key`. Native HTML forms may send the exact reserved field `_fr_idempotency_key`. Records remain valid for 24 hours. Replaying identical content returns the original receipt with `replay: true`; different content returns `409`.
## Reserved anti-spam fields
- `_gotcha` is the default honeypot. Keep it visually hidden from people but available to unsophisticated bots. A non-empty value is quarantined.
- `_fr_started_at` is a Unix timestamp in milliseconds. When minimum-completion timing is enabled, submissions completed implausibly quickly are quarantined.
- `_fr_turnstile_token` carries a Cloudflare Turnstile response when customer-configured Turnstile validation is enabled.
These fields are consumed by FormRoost and never appear in stored customer fields. A form may configure a different honeypot field name. Production spam quarantine lasts 14 days; sandbox spam is purged with other sandbox records after 7 days. Quarantine consumes no submission unit, and emits no webhook unless the account owner restores the lead.
---
url: /docs/api/reference.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Generated Submission API reference
The public contract is generated from the same Fastify route schemas used by the running API and validated as OpenAPI 3.1.2 during generation.
[Download the Submission API OpenAPI document](/docs/openapi/submission-v1.json)
The public document includes only `/s/v1` submission operations. FormRoost's private `/api/v1` management document is generated separately and is not published as a customer integration surface.
Clients should treat stable Problem Details `code` values as machine-readable. Human-readable titles and details may improve without a contract version change.
---
url: /docs/webhooks.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Signed webhooks
Every Phase 1 endpoint can subscribe to any combination of:
- `submission.created`
- `submission.status_changed`
- `submission.archived`
- `submission.restored` — sent when a lead returns from archive, spam, or recovery storage; `data.restoredFrom` is `archive`, `spam`, or `trash`
- `submission.deleted`
Creation and restoration events include available submission fields. Status, archive, and deletion events contain identifiers and change metadata without retransmitting the entire lead payload.
## Delivery contract
Webhook envelopes use CloudEvents 1.0.2 structured JSON. Requests include Standard Webhooks `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers.
Delivery is at least once and not ordered. Deduplicate using the stable `webhook-id`. A failed event never blocks newer events.
Only `2xx` succeeds. FormRoost does not follow redirects. Receivers should acknowledge quickly and perform expensive work asynchronously.
Automatic attempts occur immediately, then approximately 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 24 hours, 48 hours, and 72 hours after the first attempt.
Production destinations require HTTPS. FormRoost revalidates the destination on every attempt, applies a three-second connection timeout and ten-second total timeout, and never follows redirects. Endpoint health becomes degraded after failures; a bounded circuit breaker protects both systems without permanently disabling the endpoint.
Destination validation rejects credentials in URLs and private, loopback, link-local, reserved, multicast, documentation, and cloud-metadata addresses for IPv4 and IPv6. DNS is resolved again for every attempt, and the connection is pinned to the validated address while retaining the original hostname for TLS verification. Sandbox permits HTTP only for explicit local-development destinations in a local deployment.
`429` and `503` responses may include `Retry-After`; a valid bounded value delays the next attempt without extending delivery beyond the 72-hour retry window. Twenty failed attempts across five events opens the circuit for 15 minutes. A single probe then runs; continued failure increases probe spacing up to six hours.
## Operations and secret rotation
The portal can pause, resume, or delete an endpoint, inspect delivery attempts, and manually replay an immutable event. Replay keeps the original event ID and payload but creates a fresh signature and audited attempt. Replay is disabled after a submission enters its paid-history retention archive.
Rotating a signing secret reveals the replacement once. For 24 hours, deliveries include valid signatures from both the new and previous secrets so a receiver can deploy safely; the previous secret then expires automatically.
Delivery diagnostics retain status, duration, time, and a small allowlist of response headers. Failed text-like response snippets are bounded to 4 KB and removed after 30 days; successful response bodies are discarded immediately.
---
url: /docs/recipes/browser.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Submit from a browser
Use your form's public submission ID, not its management ID. The hosts and IDs below are placeholders.
## Sandbox first
Add your site's origin, such as `http://localhost:3000`, to **Allowed origins** on the form. Sandbox reads the draft configuration. Serve the page over HTTP; opening a file directly produces an opaque `null` origin and fails the allowlist check.
```html
```
The default encoding is `application/x-www-form-urlencoded`. With `Accept: text/html`, a successful navigation shows an HTML result page with status `200`, or uses a configured success redirect with status `303`. File uploads are rejected.
## Use fetch
This example sends JSON and receives JSON. Match the fields to your form's schema.
```js
const response = await fetch(
'https://forms.example.com/s/v1/sandbox/sub_REPLACE_ME',
{
method: 'POST',
credentials: 'omit',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'visitor@example.com', message: 'Hello' }),
},
);
if (response.status !== 201) throw new Error(`Submission failed: ${response.status}`);
const receipt = await response.json();
console.log(receipt.receiptId);
```
The browser sends `Origin` and handles the JSON preflight. An allowed preflight returns `204`. Do not set `Origin` yourself or embed a server API key.
## Move to production
Add the HTTPS origin of your live site, such as `https://www.example.com`, and publish the configuration. Replace `sandbox` with `production` in either example. Production must be enabled and uses the published configuration. Production ignores HTTP allowlist entries, except the deployment's own origin when FormRoost itself runs locally over HTTP.
Origins match scheme, hostname, and port. A rule such as `https://*.example.com` matches subdomains, not the bare `example.com`. An unlisted origin returns `403`. A bearer key cannot bypass this check.
These minimal examples assume Turnstile and minimum-completion timing are off. If enabled, include the [reserved anti-spam fields](/docs/api/submissions.md#reserved-anti-spam-fields). See [configuration and publish](/docs/concepts/configuration.md) and [server submissions](/docs/recipes/server.md).
---
url: /docs/agents.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# AI coding agents
FormRoost ships a hosted **Remote MCP server** (`https://formroost.com/mcp`) over Streamable HTTP with OAuth 2.1, a portable [Agent Skills](https://agentskills.io) workflow (`SKILL.md`), and machine-readable documentation (`llms.txt`).
Coding agents — including **Claude Code**, **Cursor**, **OpenAI Codex**, **Windsurf**, **Cline**, and **Zed** — can create FormRoost projects and forms, configure sandbox origins and JSON Schema validation, wire your site's frontend form, and verify a real sandbox submission without leaving your editor.
## Your first form in 2 minutes
1. **Create a FormRoost account** at [/app/register](/app/register) (the Free plan needs no card and includes unlimited sandbox testing).
2. **Connect your editor to `https://formroost.com/mcp`** using one of the client configs below. On first connection, your browser opens `/app/oauth/consent` so you can approve sandbox permissions with one click.
3. **Ask your agent to wire and test your form.** Example prompt:
```text
Using FormRoost, create a "Marketing Site" project and a "Contact" form with
strict validation for name, email, and message. Add http://localhost:3000 to
sandbox allowed origins, wire it into my existing contact form component with
honeypot protection, and send a sandbox test submission to verify it lands in Inbox.
```
4. **Review and publish to production yourself:** Open your form in the FormRoost portal, add your live `https://` origin, inspect the configuration diff, and click **Publish** when you are ready to go live.
## Connect Remote MCP (`https://formroost.com/mcp`)
FormRoost's MCP server uses **OAuth 2.1 with PKCE** (RFC 9728 / RFC 8414 / RFC 7591). Production access stays unchecked by default on the consent screen, and you can revoke any connected app anytime in **Settings → Account → AI agents & MCP access**.
### Claude Code
**Recommended — install the official FormRoost plugin** (bundles both the Remote MCP server and the `/formroost` skill in one step from [`codeviewshq/formroost-plugin`](https://github.com/codeviewshq/formroost-plugin)):
```text
/plugin marketplace add codeviewshq/formroost-plugin
/plugin install formroost@formroost-plugin
```
Then run `/mcp` inside Claude Code and choose **formroost** to complete the browser login.
Or register the Remote MCP server directly via CLI (use `-s user` to make it available across all projects):
```bash
claude mcp add --transport http -s user formroost https://formroost.com/mcp
```
### OpenAI Codex
```bash
codex mcp add formroost --url https://formroost.com/mcp
codex mcp login formroost
```
### Cursor (`.cursor/mcp.json`)
Add FormRoost to `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global):
```json
{
"mcpServers": {
"formroost": {
"url": "https://formroost.com/mcp"
}
}
}
```
### Windsurf or other Streamable HTTP clients
Point your client's remote MCP configuration at `https://formroost.com/mcp`. For clients that only support `stdio`, bridge with `mcp-remote`:
```json
{
"mcpServers": {
"formroost": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://formroost.com/mcp"]
}
}
}
```
### Headless / CI tokens (`frp_…`)
For non-interactive scripts or clients without OAuth support, create a scoped personal access token in **Settings → Account → AI agents & MCP access** and send `Authorization: Bearer frp_…`.
## Permissions & production guard
FormRoost separates everyday sandbox setup from production data and live changes:
- **Enabled by default (sandbox & setup):** `projects:read`, `projects:write`, `forms:read`, `forms:write`, `sandbox:submit`, `sandbox:read`, and `webhooks:write` (sandbox webhook destinations only).
- **Opt-in only (unchecked by default):**
- `production:read` — read live customer leads or register production webhook destinations.
- `production:publish` — promote sandbox draft configuration to production. Without this scope, `publish_form` never modifies production; it returns `{ published: false, requiresApproval: true, diff, reviewUrl }` with a direct link for human approval.
- **Never exposed to MCP:** account deletion, billing or plan changes, password or 2FA settings, and platform admin routes.
### Available MCP tools
| Tool | Purpose | Required scope |
| ----------------------- | ----------------------------------------------------------------------------------- | --------------------------------------- |
| `list_projects` | List your projects and form counts | `projects:read` |
| `create_project` | Create a new project | `projects:write` |
| `list_forms` | List forms in a project with sandbox/production endpoint URLs | `forms:read` |
| `get_form` | Read a form's sandbox draft and published production configuration | `forms:read` |
| `create_form` | Create a form inside an existing project | `forms:write` |
| `update_sandbox_config` | Update allowed origins, strict JSON Schema, redirects, or anti-spam in sandbox | `forms:write` |
| `send_sandbox_test` | Send a real test submission through the sandbox submission pipeline | `sandbox:submit` |
| `list_submissions` | Inspect sandbox leads (or production leads if `production:read` was opted into) | `sandbox:read` (or `production:read`) |
| `get_publish_diff` | Preview configuration changes between sandbox draft and live production | `forms:read` |
| `publish_form` | Publish sandbox draft to production, or return a human review diff + portal link | `forms:read` (`production:publish` opt) |
| `list_webhooks` | List configured webhook endpoints (with path/query redacted) | `forms:read` |
| `create_webhook` | Register a sandbox webhook (production destinations also require `production:read`) | `webhooks:write` (+ `production:read`) |
The MCP server also exposes the `formroost://skill` resource and a `setup_form` prompt template.
## Install the portable `SKILL.md` (optional)
If you use a coding agent without MCP — or want FormRoost's sandbox-first integration checklist loaded directly into your editor — install the portable `agentskills.io` skill directly from `formroost.com`:
### Using `npx skills`
```bash
npx skills add https://formroost.com
```
You can also install from the public [`codeviewshq/formroost-plugin`](https://github.com/codeviewshq/formroost-plugin) repository or the direct Markdown URL:
```bash
npx skills add codeviewshq/formroost-plugin
# or:
npx skills add https://formroost.com/docs/skill/SKILL.md
```
### Manual install (any agent or repository)
Download [`/docs/skill/SKILL.md`](/docs/skill/SKILL.md) into your project's skill directory:
```bash
mkdir -p .agents/skills/formroost
curl -fsSL https://formroost.com/docs/skill/SKILL.md -o .agents/skills/formroost/SKILL.md
```
For Claude Code project skills, place the same file at `.claude/skills/formroost/SKILL.md`.
## Machine-readable documentation (`llms.txt`)
Point any agent or documentation loader at these plain-text Markdown endpoints:
| Resource | URL | Use |
| ---------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Root index | [`/llms.txt`](https://formroost.com/llms.txt) | High-level map of FormRoost docs, OpenAPI spec, and agent skill |
| Docs index | [`/docs/llms.txt`](/docs/llms.txt) | Generated Markdown index of every documentation page |
| Full docs bundle | [`/docs/llms-full.txt`](/docs/llms-full.txt) | Complete documentation text in a single file |
| Submission OpenAPI 3.1 | [`/docs/openapi/submission-v1.json`](/docs/openapi/submission-v1.json) | Exact public submission request and response schemas |
| Portable Agent Skill | [`/docs/skill/SKILL.md`](/docs/skill/SKILL.md) | Step-by-step sandbox-first integration workflow |
| Agent Skills Discovery | [`/.well-known/agent-skills/index.json`](https://formroost.com/.well-known/agent-skills/index.json) | Standard well-known manifest for `npx skills add https://formroost.com` |
Every page in this documentation also provides a **Copy Markdown** control and a `.md` version for low-token context loading.
## Security boundaries for agent-generated code
- **Keep server keys out of client bundles.** Browser forms use the public submission ID (`fpub_...`) with `credentials: 'omit'` and origin allowlists. Server API keys (`fr_production_key_...` / `fr_sandbox_key_...`) belong only in server-side environment variables.
- **Branch on RFC 9457 `code`, not `detail`.** Tell agents to handle stable codes from [Error responses](/docs/api/errors.md) (`submission_schema_invalid`, `origin_not_allowed`, `submission_rate_limited`, `idempotency_conflict`).
- **Verify webhook signatures on raw bytes.** When an agent writes a webhook receiver, ensure it uses the `standardwebhooks` package against the unparsed raw request body and deduplicates by `webhook-id`. See [Signed webhooks](/docs/webhooks.md).
---
url: /docs/release-notes.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# What's new
New features and improvements to help you collect and manage form submissions.
## November 23, 2026
### Connect AI coding agents over Remote MCP
Connect Claude Code, Cursor, OpenAI Codex, Windsurf, and other MCP-compatible editors directly to `https://formroost.com/mcp` using one-click OAuth 2.1 + PKCE login or scoped personal access tokens (`frp_…`) in **Settings → Account**.
Agents can create projects and forms, configure sandbox origins and JSON Schema validation, send sandbox test submissions, and preview publish diffs while production leads and publishing remain opt-in by default. Machine-readable docs (`/llms.txt`), a portable `SKILL.md` (`npx skills add https://formroost.com`), and the public [`codeviewshq/formroost-plugin`](https://github.com/codeviewshq/formroost-plugin) repository are also live.
See [AI coding agents](/docs/agents.md).
## November 12, 2026
### Explore your submission activity
Choose the last 7, 30, or 90 days in Analytics, or enter a custom number of days. Switch between form and traffic-source breakdowns to see where submissions come from.
You can also count values in a selected top-level field. Field counts cover retained submissions in the selected environment, independently of the date range.
See [Analytics and exports](/docs/portal/analytics-exports.md).
### Copy-and-adapt integration recipes
New step-by-step recipes show how to send submissions from a browser form or your own server, receive signed webhooks, and forward submissions to Slack or Google Sheets.
Start with [Browser submissions](/docs/recipes/browser.md).
### Plan prices published
Starter is $9, Growth is $29, and Agency is $99 per month, with annual billing at $90, $290, and $990. The pricing page and the portal's billing screen now show the same prices you pay at checkout.
See [Billing and usage](/docs/portal/billing.md).
## November 11, 2026
### Replace an API key without interrupting submissions
Choose **Rotate** on a working API key and give yourself 1 hour, 24 hours, or 7 days to update your integration. Both keys work during the overlap, and the portal shows when the old key will stop working. Rotation also works when you have reached your active-key limit.
See [Rotating a key](/docs/api/keys.md#rotating-a-key) for the steps and expiry rules.
---
url: /docs/api/errors.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Error responses
Submission and management errors use RFC 9457 Problem Details with `application/problem+json`.
```json
{
"type": "https://formroost.com/docs/api/errors#origin_not_allowed",
"title": "Origin not allowed",
"status": 403,
"detail": "https://shop.example is not in this form's allowed origins. Add it under Allowed origins on the form page, then retry from that site.",
"code": "origin_not_allowed",
"requestId": "...",
"instance": "/s/v1/production/..."
}
```
Clients must branch on the stable `code`, not the human-readable `detail`. Each problem `type` links directly to the matching code anchor below.
| Status | Baseline meaning |
| -----: | ------------------------------------------------- |
| 400 | Malformed request |
| 401 | Missing or invalid credential |
| 403 | Disallowed origin or operation |
| 404 | Unknown form or resource |
| 409 | Conflicting idempotency reuse or state transition |
| 410 | Expired resource |
| 413 | Payload or field limit exceeded |
| 415 | Unsupported media type or file part |
| 422 | Schema or input validation failure |
| 429 | Traffic limit or exhausted allowance |
| 502 | Upstream billing provider error |
| 503 | Temporary unavailability |
Validation errors include no more than 20 JSON Pointer paths and never echo rejected values. Public browser errors do not disclose plan or account usage.
## Problem codes
### Submission API
- allowance\_exhausted (`429`)
The account has used its production submission allowance and top-up balance for the current period.
- form\_configuration\_invalid (`503`)
The form's published strict JSON Schema is missing or cannot be compiled.
- idempotency\_conflict (`409`)
The supplied idempotency key was already used with a different submission payload.
- invalid\_field\_name (`422`)
A submission field name is empty or exceeds 128 characters.
- invalid\_idempotency\_key (`422`)
The idempotency key must contain between 8 and 200 characters.
- malformed\_request (`400`)
The submission request body is not a key-value object.
- origin\_not\_allowed (`403`)
The request `Origin` header is not in the form's allowed origins, or is not HTTPS in production.
- payload\_too\_large (`413`)
The submission exceeds the plan's payload size limit.
- server\_authentication\_required (`401`)
Requests without an `Origin` header require a valid project API key for the target environment.
- submission\_endpoint\_not\_found (`404`)
The submission endpoint does not exist, is disabled, or is not published for that environment.
- submission\_rate\_limited (`429`)
Submissions exceeded the per-IP, form, project, or account rate limit.
- submission\_schema\_invalid (`422`)
The submitted fields failed validation against the form's strict JSON Schema.
- too\_many\_fields (`413`)
The submission contains more than 100 top-level fields.
- turnstile\_verification\_failed (`403`)
Cloudflare Turnstile rejected the submitted verification token.
- turnstile\_verification\_required (`403`)
The form requires a Cloudflare Turnstile token, which was missing or unconfigured.
### Authentication and sessions
- account\_unavailable (`403`)
The account is suspended or scheduled for deletion and cannot be accessed.
- authentication\_required (`401`)
The request requires an authenticated account session.
- current\_session (`409`)
You cannot revoke the session currently making the request; sign out instead.
- email\_verification\_required (`403`)
Verify the account email address before calling this endpoint.
- invalid\_email\_preferences (`400`)
Choose an optional email category; security emails cannot be disabled.
- invalid\_unsubscribe\_link (`400`)
The email unsubscribe link is malformed, expired, or no longer valid.
- password\_attempts\_limited (`429`)
Too many password verification or change attempts; wait before trying again.
- password\_change\_failed (`401`)
The current password could not be verified when changing the password.
- password\_confirmation\_failed (`401`)
The supplied password did not match the account password.
- password\_policy\_failed (`400`)
The chosen password does not meet FormRoost's password policy.
- recent\_authentication\_required (`403`)
Re-confirm your password before performing this sensitive action.
- session\_not\_found (`404`)
The requested session does not exist for this account.
- customer\_token\_not\_found (`404`)
The requested personal access token does not exist or is already revoked.
- oauth\_grant\_not\_found (`404`)
The requested connected OAuth application does not exist or is already revoked.
- oauth\_invalid\_client (`400`)
The OAuth client identifier or redirect URI is not registered.
- oauth\_invalid\_request (`400`, `422`)
The OAuth authorization or consent request is missing required parameters or permissions.
- unsubscribe\_confirmation\_required (`400`)
Explicit confirmation is required to turn off optional emails.
### Projects, forms, configuration, and API keys
- api\_key\_already\_rotated (`409`)
This API key already has a replacement key issued.
- api\_key\_expiration\_before\_retirement (`422`)
The replacement API key's expiration must be later than the old key's retirement time.
- api\_key\_expiration\_in\_past (`422`)
An API key expiration timestamp must be in the future.
- api\_key\_inactive (`409`)
Only active, non-expired, non-revoked API keys can be rotated.
- api\_key\_limit\_reached (`409`)
The project has reached its maximum number of active API keys.
- api\_key\_not\_found (`404`)
The requested API key does not exist or is already revoked.
- api\_key\_overlap\_active (`409`)
Wait for the previous key rotation overlap to end or revoke the previous key first.
- configuration\_revision\_conflict (`409`)
The form draft was modified elsewhere; reload and retry with the latest revision.
- configuration\_version\_not\_found (`404`)
The requested published production configuration version does not exist.
- form\_not\_found (`404`)
The requested form does not exist or is in the trash.
- invalid\_aggregate\_field (`422`)
Analytics aggregation requires a top-level, non-sensitive field name.
- invalid\_form\_configuration (`422`)
The form configuration document failed validation.
- milestone\_not\_achieved (`409`)
A milestone can only be marked celebrated after the account achieves it.
- milestone\_not\_found (`404`)
The requested onboarding milestone name is unknown.
- project\_not\_found (`404`)
The requested project does not exist or is in the trash.
- submission\_id\_confirmation\_mismatch (`409`)
Rotating a form's public submission identifier requires confirming the current identifier.
### Inbox, leads, and exports
- export\_artifact\_missing (`410`)
The generated export file has expired and is no longer available for download.
- export\_not\_found (`404`)
The requested lead export does not exist.
- export\_not\_ready (`409`)
The export job is not ready or failed to produce a file.
- field\_not\_found (`404`)
The requested field does not exist on that submission.
- invalid\_cursor (`400`, `422`)
The pagination cursor is malformed or invalid for this query.
- invalid\_date\_filter (`400`)
The `from` or `to` date query parameter is not a valid date.
- invalid\_status\_transition (`409`)
The requested lead status transition is not allowed from the current status.
- note\_not\_found (`404`)
The requested submission note does not exist.
- production\_allowance\_exhausted (`429`)
Restoring a quarantined production submission requires remaining production allowance.
- saved\_view\_not\_found (`404`)
The requested inbox saved view does not exist.
- submission\_not\_found (`404`)
The requested submission does not exist in this account.
- submission\_retention\_archived (`409`)
Historical archived submissions are read-only and cannot be modified or replayed.
### Webhooks
- invalid\_webhook\_destination (`422`)
The webhook destination URL is not allowed.
- webhook\_endpoint\_limit\_reached (`409`)
The form has reached its maximum number of webhook endpoints.
- webhook\_endpoint\_not\_found (`404`)
The requested webhook endpoint does not exist.
- webhook\_event\_not\_found (`404`)
The requested webhook event does not exist for this account.
- webhook\_not\_found (`404`)
The requested webhook endpoint does not exist for this form.
### Billing and plans
- already\_subscribed (`409`)
The account already has a paid plan; switch plans from billing settings instead of starting checkout.
- billing\_simulator\_unavailable (`404`)
The billing simulator is only enabled in development when live Stripe billing is off.
- billing\_state\_unavailable (`409`)
Account subscription or usage-period state is missing and cannot be simulated.
- comp\_checkout\_blocked (`409`)
Self-serve checkout and plan changes are unavailable while FormRoost provides a complimentary plan.
- invalid\_billing\_webhook\_signature (`401`)
The billing webhook signature header failed verification.
- invalid\_proration\_date (`422`)
The plan change quote timestamp is stale or out of range; refresh the plan change preview and confirm again.
- invalid\_stripe\_signature (`400`)
The `Stripe-Signature` header is missing or invalid.
- live\_billing\_unavailable (`404`)
Live Stripe billing is not configured on this server.
- no\_billing\_account (`409`)
A paid plan must be chosen before opening the billing portal.
- no\_paid\_plan (`409`)
The account does not have an active paid Stripe subscription to change.
- payment\_declined (`402`)
The card payment for the plan change was declined and the plan was not changed.
- price\_not\_configured (`503`)
The selected plan does not have a configured Stripe price yet.
- stripe\_unavailable (`502`)
Stripe could not be reached to complete the billing request; retry shortly.
- usage\_period\_unavailable (`503`)
No active usage period was found for the account; retry shortly.
### Platform administration
- account\_exists (`409`)
An account with that email address already exists.
- account\_not\_found (`404`)
The target account does not exist.
- admin\_token\_not\_found (`404`)
The requested admin token does not exist.
- catalog\_plan\_missing (`422`)
No active catalog version exists for the selected plan.
- catalog\_version\_not\_found (`404`)
The requested plan catalog version does not exist.
- confirmation\_mismatch (`422`)
The confirmation value did not match the required account email, receipt, or confirmation phrase.
- email\_in\_use (`409`)
Another account already uses that email address.
- email\_not\_allowed (`409`)
That operational email type cannot be resent from the platform console.
- email\_not\_verified (`422`)
Platform roles can only be granted to accounts with a verified email address.
- empty\_apply\_scope (`422`)
Choose at least one account when applying a plan catalog version.
- enterprise\_limits\_required (`422`)
Enterprise plans require every explicit limit field to be provided.
- enterprise\_revert\_unsupported (`422`)
Enterprise cannot be used as the revert plan after a complimentary plan expires.
- insufficient\_scope (`403`)
The admin token is missing a scope required for this endpoint.
- invalid\_account\_filter (`422`)
The account filter value is not recognized.
- invalid\_admin\_token (`401`)
The admin bearer token is invalid, expired, or revoked.
- invalid\_audit\_filter (`422`)
One or more audit log query filters or limits are invalid.
- invalid\_comp\_end (`422`)
The complimentary plan end date must be a valid timestamp in the future.
- last\_super\_admin (`409`)
The last active super admin role cannot be revoked.
- operational\_email\_not\_found (`404`)
The requested operational email log entry does not exist.
- operator\_access\_denied (`403`)
The signed-in account does not hold the required platform operator role.
- operator\_authentication\_required (`401`)
An authenticated operator session or valid admin token is required.
- recent\_operator\_authentication\_required (`403`)
Re-confirm operator credentials before performing this sensitive admin action.
- role\_already\_granted (`409`)
The account already holds that active platform role.
- role\_grant\_not\_found (`404`)
The requested platform role grant does not exist.
- role\_holder\_protected (`409`)
Platform role holders cannot be suspended, deleted, or have their email changed via this route.
- self\_role\_change (`422`)
Operators cannot grant platform roles to their own account.
- super\_admin\_required (`403`)
This endpoint requires the super admin role.
- support\_rate\_limited (`429`)
The account exceeded the rate limit of 5 support or feedback messages per 10 minutes.
- support\_request\_not\_found (`404`)
The requested support or feedback message does not exist.
- token\_expiry\_invalid (`422`)
The admin token expiration timestamp must be in the future.
- token\_expiry\_too\_long (`422`)
Admin tokens can last at most 90 days.
- token\_not\_allowed (`403`)
Admin tokens cannot be used on this route; use an interactive session instead.
- token\_rate\_limited (`429`)
The admin token exceeded the 120 requests per minute rate limit.
- two\_factor\_required (`403`)
Two-factor authentication must be enabled before accessing operator routes.
- view\_as\_blocked (`403`)
This action is not available while viewing as a customer.
- view\_as\_read\_only (`403`)
Customer routes are read-only while viewing as a customer.
- view\_as\_role\_holder (`409`)
Platform role holders cannot be viewed as.
- view\_as\_self (`422`)
Operators cannot start a view-as session for their own account.
- view\_as\_skip\_reason\_required (`422`)
An allowlisted skip reason is required when suppressing customer view-as notification.
### General
- request\_error (`4xx`)
The request failed framework validation or parsing before a route handler ran.
- validation\_failed (`400`)
One or more submitted fields failed route-level validation rules.
- internal\_error (`500`)
An unexpected server error occurred; include `requestId` when reporting the issue.
---
url: /docs/api/keys.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Server API keys
Production submissions without an `Origin` require a project/environment API key. Sandbox development tools may omit both `Origin` and the key. If a syntactically valid sandbox bearer key is supplied, it must be valid for the target project and environment.
```http
Authorization: Bearer fr_production_key_ID.SECRET
```
Keys are submission-write-only. They cannot read leads, export data, alter forms, manage webhooks, access billing, or call the management API.
- A key belongs to exactly one project and one environment.
- The secret appears only once. FormRoost stores a digest, not the original secret.
- Free permits two active keys per project and environment. Starter, Growth, and Agency permit ten. Revoked and expired keys do not consume the active limit; Enterprise is negotiated.
- Expiration is optional and must be in the future. Configured expirations receive warnings at 30, 14, 7, 3, and 1 day before expiry.
## Rotating a key
Choose **Rotate** on a working key and pick an overlap of 1 hour, 24 hours (the default), or 7 days. FormRoost creates a replacement with the same name, project, and environment and shows its secret once. Both keys work during the overlap. The old key stops working when the overlap ends, or at its own expiry if that is sooner; the portal shows the exact time.
- The replacement has no expiry unless you set one, and that expiry must be after the old key stops.
- Rotation works at the active-key limit: the retiring key and its replacement count as one.
- A second rotate request for the same key returns a conflict. It never creates another key or shows the secret again.
- If you lose the replacement's secret, the old key still works until the overlap ends. Revoke the old key to rotate the replacement straight away, or wait for the overlap to end.
- A retiring key gets no expiry warning email. A replacement with an expiry you set does.
## Browser submission IDs
The public browser submission ID is an address, not a secret. It normally remains stable. The form settings expose a recent-authentication-protected emergency regeneration action; it invalidates the old address immediately and therefore requires updating every deployed browser form.
- Never place a server key in browser JavaScript, HTML, a mobile application, a public repository, or a URL.
Browser submissions use the selected environment’s origin allowlist instead of API keys. An `Origin` selects that browser path even when an Authorization header is present; a key does not bypass a rejected origin. Origin checks are not authentication: non-browser clients can forge that header. Send server keys only over HTTPS and omit `Origin` for server authentication.
---
url: /docs/concepts/abuse.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Spam and abuse controls
FormRoost applies layered controls without requiring every customer to configure a challenge. Origin validation and short-lived network/form/project/account rate limits are always active. The default `_gotcha` honeypot, optional minimum-completion timing, repeated-content detection, and configurable email/domain/content blocklists add low-friction signals.
Customers may enable Cloudflare Turnstile per form by storing a site key and secret. The secret is application-encrypted, never returned by the API, and sent only to Cloudflare's verification endpoint when a token is supplied.
Suspicious submissions enter a 14-day quarantine. They do not consume allowance, appear in the explicit Spam inbox, and do not produce webhooks. Restoring a production submission consumes one production unit and emits `submission.restored`; restoration stops with the same hard allowance limit as ordinary ingestion.
Duplicate-content detection uses a bounded HMAC-derived fingerprint and time window. FormRoost does not store raw submitter IP addresses for rate limiting.
Deployments behind a reverse proxy must set `TRUSTED_PROXY_CIDRS` to the proxy's IP addresses or CIDR ranges. Direct deployments leave it empty. The supplied Compose setup assigns Nginx `172.30.0.10` and trusts only that address; Nginx replaces incoming forwarding headers with the visitor's address. Adapt the network and trusted address together when deploying on a different network.
---
url: /docs/concepts/configuration.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Configure, review, and publish
Every form begins with one editable **sandbox draft**. Production does not exist until you publish explicitly.
The draft controls schema mode, JSON Schema, exact browser origins, redirects, and basic visitor-metadata collection. Draft writes use a server revision; a stale tab receives a conflict instead of overwriting newer work.
## Flexible and strict modes
Flexible mode accepts any valid field map within the platform limits. Strict mode validates a documented JSON Schema Draft 2020-12 subset: objects, arrays, required fields, primitive types, formats, enums, length/range constraints, nested structures, and controlled additional properties.
Do not configure fields for passwords, credentials, payment-card or bank data, national identifiers, protected health information, children's data, or illegal content.
## Browser origins
Use exact HTTPS origins such as `https://www.example.com`, including the port when non-default. Paths, queries, and userinfo are rejected. Case is normalized and fragments are dropped.
A wildcard rule such as `https://*.example.com` matches subdomains only, not the apex. The wildcard must be the whole leftmost label, and it cannot target an IP address or a top-level domain: `https://*.com` is rejected. Multi-label public suffixes such as `co.uk` are not recognised yet, so do not rely on that check for them.
`http://` origins are for local testing only. Saving accepts one only for `localhost` or a loopback address with an explicit port, such as `http://localhost:3000` or `http://127.0.0.1:5173`. Sandbox requests use the current draft allowlist and match those entries. Production uses the published allowlist and ignores every entry that is not HTTPS, so a local entry never blocks publishing and never authorises production traffic. The one exception is a self-hosted deployment that is itself served over HTTP, which still trusts its own origin.
An `http://` entry saved before these rules keeps working in sandbox until the configuration is next saved. Origin checks are not authentication: a non-browser caller can forge the header.
Browser requests should omit credentials. Account cookies do not authenticate submissions, and bearer keys do not bypass an origin check. Production requests without `Origin` require a server key; sandbox tools such as curl may omit both. Origin validation runs again on the submission even after a successful CORS preflight. See [submission authentication](/docs/api/submissions.md).
## Publishing
Saving validates the draft. Publishing copies that saved draft into a new immutable production version. Existing submissions remain tied to the exact version that accepted them. A later rollback creates another immutable production version; it never rewrites history.
Strict mode supports a bounded JSON Schema Draft 2020-12 subset: local `$ref`/`$defs`, object properties and requirements, arrays, scalar bounds, formats and patterns, enums/constants, and standard composition keywords. Remote references, executable/custom keywords, unknown keywords, more than 500 schema nodes, or more than 20 schema levels are rejected before save or publish.
Implemented control names such as `_fr_idempotency_key`, `_gotcha`, `_fr_started_at`, `_fr_turnstile_token`, and a configured custom honeypot name cannot also be customer schema fields. FormRoost reports the collision instead of silently changing the schema.
Sandbox records are disposable and are deleted after 7 days on every plan.
---
url: /docs/concepts/limits.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Limits and quota
A unit is consumed only after a valid submission is accepted and durably stored. Validation failures, blocked requests, rate-limited requests, spam, webhook attempts, and idempotent replays do not consume production allowance.
| Plan | Production / month | Maximum payload |
| ---------- | -----------------: | --------------: |
| Free | 50 | 256 KB |
| Starter | 1,000 | 256 KB |
| Growth | 10,000 | 512 KB |
| Agency | 50,000 | 1 MB |
| Enterprise | Negotiated | Negotiated |
Sandbox is unlimited on every plan. In exchange, sandbox records are deleted 7 days after they arrive. Rate limits still apply.
When production allowance is exhausted, production acceptance stops. Usage warnings begin at 70%, then repeat at 75%, 80%, 85%, 90%, 95%, and 100%. Optional production top-ups expire with the current monthly usage period and do not roll over. Sandbox top-ups are not sold.
Every submission is also bounded to 100 fields, 128 characters per field name, 64 KB per individual text value, and 20 nested object/array levels.
Independent one-minute abuse limits apply to the submitter network key, form, project, and account. The API returns `429` with an RFC 9457 problem body when a limit is reached. These controls protect ingestion capacity and do not consume quota. Exact thresholds are operational safeguards and may be tuned without changing plan allowances.
---
url: /docs/concepts/resources.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Projects, forms, and environments
An account owns any number of projects. A project owns any number of forms. Each form has exactly two environments in Phase 1: sandbox and production.
| Resource | Responsibility |
| ---------- | ------------------------------------------------------------------------- |
| Account | Subscription, pooled allowance, and all owned data |
| Project | Related forms and environment-scoped server credentials |
| Form | Submission endpoint, schema, origins, redirects, and webhook destinations |
| Sandbox | Unlimited disposable integration data, deleted after 7 days |
| Production | Published immutable configuration and customer lead data |
Sandbox and production data never blend silently. Sandbox traffic never consumes production allowance or production analytics.
Configuration is edited as a sandbox draft. Publishing creates a new immutable production configuration version after showing a diff and receiving explicit confirmation.
---
url: /docs/concepts/retention.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Retention and deletion
| Data | Retention |
| ---------------------------------- | ------------------------------------- |
| Free production submissions | Rolling 90 days |
| Active paid production submissions | While the paid subscription is active |
| Sandbox submissions on every plan | 7 days, then deleted |
| Spam quarantine | 14 days |
| Lead trash | 7 days |
| Deleted project or form recovery | 30 days |
| Background export artifact | 24 hours |
| Failed webhook response snippet | 30 days |
When a paid subscription ends, its existing production submissions enter a one-year read/export-only archive. Notes, tags, status, archive/spam state, read state, and webhook replay cannot change. Viewing, CSV/NDJSON export, explicit redaction, and confirmed permanent deletion remain available. Operational warnings are sent at 180, 90, 60, 30, 14, 7, 3, and 1 day before archive deletion.
Account deletion disables all submission endpoints immediately and starts a 30-day recovery window. It requires recent password confirmation and sends confirmation plus reminder emails. Recovering in time re-enables the account; after purge, active-system recovery is unavailable. Backup-media deletion timing is intentionally not promised until the deployment backup policy is finalized.
Permanent deletion and retention expiry also remove webhook events containing the lead's fields, including their delivery attempts. Identifier-only deletion notifications remain deliverable. Usage history retains its counted units without retaining a reference to the deleted lead.
---
url: /docs/index.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Make your first sandbox submission
FormRoost is a form backend. Your website sends contact or lead fields to a FormRoost endpoint; FormRoost stores the accepted record in your Inbox and delivers a signed webhook event.
You create every resource explicitly. FormRoost never creates a project or form automatically.
> **Building with Claude Code, Cursor, or Codex?** Connect our [Remote MCP server](/docs/agents.md) (`https://formroost.com/mcp`) to create forms, configure sandbox origins, and verify test submissions straight from your editor.
## 1. Create and verify an account
Open [/app/register](/app/register). The Free plan requires no card and includes **50 production submissions per monthly usage period** plus **unlimited sandbox testing** (sandbox records are kept for 7 days).
You can also choose **Continue with Google** or **Continue with GitHub**. Your provider must have verified your email address, and the account starts already verified.
If you signed up with an email and password, verify your email before continuing. Unverified accounts cannot create projects, forms, endpoints, or billing state.
## 2. Create a project, then a form
In the portal:
1. Open **Projects** and choose **Create project**.
2. Open that project and choose **Create form**.
3. Copy the sandbox endpoint shown on the form.
The order is required: `account → project → form → environment`.
## 3. Send JSON
Replace the URL with the sandbox endpoint you copied. The localhost address below is for a local deployment only. This no-origin sandbox request needs no API key; production without an Origin requires a [server key](/docs/api/keys.md). Do not add an Origin header unless it is in the sandbox draft allowlist.
```bash
curl -X POST 'http://localhost:8080/s/v1/sandbox/YOUR_SUBMISSION_ID' \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: quickstart-0001' \
-d '{"name":"Ada Lovelace","email":"ada@example.com","topic":"Integration review"}'
```
A new acceptance returns `201 Created`:
```json
{
"receiptId": "sub_...",
"acceptedAt": "2026-08-25T12:00:00.000Z",
"environment": "sandbox",
"requestId": "...",
"replay": false
}
```
The response never echoes submitted fields.
## 4. Inspect the Inbox
Open **Inbox**, select **Sandbox**, then open the accepted row. The readable field view appears first; canonical JSON and approved request metadata are separate views.
## 5. Add delivery
Configure a sandbox webhook for `submission.created`. FormRoost uses a CloudEvents 1.0.2 JSON envelope and Standard Webhooks HMAC-SHA256 headers. Store the signing secret when it is shown; it is not displayed again.
Production remains disabled until you review and explicitly publish configuration.
---
url: /docs/portal/analytics-exports.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Analytics and exports
Analytics are calculated in-house from accepted submissions, rejected outcomes, lead status activity, and webhook attempts. FormRoost does not send lead content to a third-party analytics or search service.
The dashboard reports hourly and daily submission trends, spam and rejection counts, project/form/environment breakdowns, lead-status counts, status-change timing, webhook success and latency, and referrer/UTM source when those values were explicitly supplied. It does not claim page-view conversion because FormRoost does not install view tracking.
Selected top-level fields can be aggregated only when the account owner requests that field. High-cardinality values are bounded in the response.
Exports use the same explicit inbox selection or filters the user can see. CSV is optimized for spreadsheets; NDJSON is the lossless nested format. Large exports run asynchronously, show their state in the portal, require the account session for download, and are deleted after 24 hours.
---
url: /docs/portal/billing.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Plans, usage, and top-ups
One subscription covers the account and every project. Production allowances are pooled account-wide and reset on the billing/signup anniversary.
Free includes 50 production submissions per usage period. Sandbox is unlimited on every plan, and sandbox records are deleted after 7 days. Starter costs 9 USD a month or 90 USD a year, Growth 29 or 290, and Agency 99 or 990. Tax is added at checkout where it applies.
Acceptance hard-stops when an allowance finishes. The portal and operational email warn at 70%, then 75%, 80%, 85%, 90%, 95%, and 100%.
## Top-ups
The development simulator can add production packs equal to 25%, 50%, or 100% of a paid plan's base monthly allowance. They expire with the current monthly usage period and never roll over. Sandbox top-ups are not sold.
Buying a top-up through Stripe and automatic top-ups are not available yet, so the simulator adds units without taking payment. When they are sold, a top-up unit costs 20% more than the plan's base per-submission price.
## Stripe billing
Stripe Checkout, subscription changes, the Customer Portal, and signed Stripe webhooks are implemented. Billing requires a verified account session; submission API keys cannot access it. The portal offers monthly and annual Starter, Growth, and Agency plans. Enterprise pricing is negotiated.
For a deployment to enable Stripe billing, both `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` must be set; supplying only one fails configuration loading. Active Stripe prices use lookup keys `formroost__`, for example `formroost_starter_monthly`. The billing screen additionally gates purchase controls on finalized monthly and annual prices in the active local catalog. That catalog flag is separate from the API's Stripe-price lookup.
Without Stripe configuration, Checkout returns a `404` Problem Details response with code `live_billing_unavailable`. A missing Stripe price returns `503 price_not_configured`; a handled Stripe transport failure returns `502 stripe_unavailable`. A comp plan blocks checkout until it ends.
Upgrades preview a prorated charge and apply immediately after payment; consumed usage carries over. Downgrades and cancellation take effect at renewal. **Card and invoices** opens Stripe's Customer Portal. Stripe webhooks confirm subscription changes; returning from Checkout alone does not prove activation. A failed payment starts a seven-day grace period; unrecovered accounts move to Free and paid history becomes a one-year read/export-only archive.
## Local verification without Stripe
With `NODE_ENV=development` and neither Stripe setting present, the portal exposes the billing simulator. It requires password confirmation within the last ten minutes and covers checkout, upgrades, scheduled downgrades, renewals, payment failure/recovery, grace expiry, cancellation, and top-up purchase/expiry without charging a card. Simulator records are labeled, and the route is unavailable outside development or when Stripe is configured.
The separate signed-adapter webhook intake verifies an HMAC and deduplicates event IDs, but only records normalized events; it does not apply subscription transitions. Stripe's webhook route separately verifies `Stripe-Signature` and applies supported subscription events.
A local stack without Stripe cannot demonstrate hosted Checkout, card payment, invoices, Customer Portal, or actual Stripe webhook delivery. The simulator demonstrates local state changes only. Development also supports a `STRIPE_API_BASE` override for a fake provider; production ignores that override. Never use real Stripe credentials for local documentation checks.
---
url: /docs/portal/leads.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Manage accepted leads
The account-wide Inbox keeps sandbox and production data visibly separate. A submission opens in a readable field view; canonical JSON and approved transport metadata remain separate tabs.
The lightweight status workflow is enforced:
```text
new → in progress → qualified or unqualified → closed
closed → in progress
```
You can add internal notes and tags, inspect the activity history, mark records read, archive and restore leads, and move a lead to recoverable trash. Ordinary deletion retains the record for the documented recovery window; permanent deletion is a separate destructive action.
Submitted fields are immutable. FormRoost renders customer field names and values as inert text, never executable HTML.
Search covers receipts, available submitted fields, notes, and tags. Filters include project, form, environment, status, tag, date, spam, archive, and trash, and can be saved as reusable views. Bulk actions support read state, status, tags, and archive state; ineligible workflow transitions are reported per receipt.
CSV exports flatten nested fields with deterministic paths and neutralize spreadsheet-formula prefixes. NDJSON preserves canonical nested data. Results up to 10,000 records download immediately. Larger exports run in the background, remain authenticated, and expire after 24 hours.
Redaction replaces an explicit field path in both the submission and retained webhook event content. Permanent deletion is a separately confirmed action. Removed content is not retained in search or exports.
---
url: /docs/portal/playground.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Sandbox playground
The authenticated playground sends requests only to a form's sandbox endpoint. It is for validating field normalization, schema behavior, idempotency, and webhook delivery before publishing.
[Open the sandbox playground](/app/playground)
The playground never selects or creates resources automatically. Create a project and form first, then choose that existing form. Sandbox submissions are unlimited, never use production allowance, and are deleted after 7 days.
---
url: /docs/recipes/forwarding.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Forward to Slack or Google Sheets
These are examples you host yourself. FormRoost does not provide native Slack or Google Sheets connectors. Start with either [signed receiver](/docs/recipes/receivers.md). Run forwarding separately so a slow destination does not delay the webhook acknowledgment.
## Slack incoming webhook
Create an incoming webhook for your Slack workspace. Store its URL as `SLACK_WEBHOOK_URL` on the forwarding server. Treat that URL as a secret. Do not use it as the FormRoost webhook destination: Slack does not verify FormRoost signatures or consume its event envelope.
## Google Sheets with Apps Script
Create a sheet with columns `Event ID`, `Receipt ID`, `Email`, and `Message`. In its Apps Script project, set script properties `SHEET_ID` and `FORWARD_TOKEN` (a long random secret). Replace `Sheet1` below if needed. Deploy as a web app that runs as you and accepts requests from your forwarding server. Keep the deployment URL in `SHEETS_WEB_APP_URL`, and the same token in `SHEETS_FORWARD_TOKEN` on that server.
```js
function doPost(e) {
const properties = PropertiesService.getScriptProperties();
const input = JSON.parse(e.postData.contents);
const token = properties.getProperty('FORWARD_TOKEN');
if (!token || input.token !== token) throw new Error('Unauthorized');
const lock = LockService.getScriptLock();
lock.waitLock(10000);
try {
const sheet = SpreadsheetApp.openById(properties.getProperty('SHEET_ID'))
.getSheetByName('Sheet1');
const ids = sheet.getLastRow() > 1
? sheet.getRange(2, 1, sheet.getLastRow() - 1, 1).getValues().flat() : [];
if (!ids.includes(input.id)) {
// Treat visitor values as text, never spreadsheet formulas.
const text = (value) => "'" + String(value ?? '');
sheet.appendRow([input.id, input.receiptId, text(input.email), text(input.message)]);
}
return ContentService.createTextOutput(JSON.stringify({ ok: true }))
.setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}
```
The lock and event ID check prevent repeated rows in this small-sheet example. A large sheet needs a more efficient deduplication store. The token belongs only in the server-to-script request; never include it in browser submissions.
## Forward saved events
Save as `forward.mjs` next to the Node receiver, or run it against the Python receiver's inbox. Node's built-in fetch is enough. Set `INBOX` to the same persistent directory. Set one or both destinations. Run `node forward.mjs` from a scheduler, with only one forwarding process at a time.
```js
import { readdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const inbox = process.env.INBOX || './inbox';
const slack = process.env.SLACK_WEBHOOK_URL;
const sheets = process.env.SHEETS_WEB_APP_URL;
if (!slack && !sheets) throw new Error('Configure a destination');
if (sheets && !process.env.SHEETS_FORWARD_TOKEN) throw new Error('Set SHEETS_FORWARD_TOKEN');
async function deliver(file, destination, url, body) {
const marker = `${file}.${destination}.done`;
if (existsSync(marker)) return;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000),
});
if (!response.ok) throw new Error(`${destination}: HTTP ${response.status}`);
if (destination === 'sheets' && (await response.json()).ok !== true) {
throw new Error('Sheets did not confirm the write');
}
writeFileSync(marker, '', { mode: 0o600, flush: true });
}
for (const name of readdirSync(inbox).filter((name) => name.endsWith('.json'))) {
const file = join(inbox, name);
const event = JSON.parse(readFileSync(file, 'utf8'));
if (event.type !== 'com.formroost.submission.created.v1') continue;
const { receiptId, fields } = event.data;
try {
if (slack) await deliver(file, 'slack', slack, {
text: `New submission ${receiptId}`,
blocks: [{ type: 'section', text: {
type: 'plain_text',
text: `Email: ${String(fields.email ?? '').slice(0, 500)}\nMessage: ${String(fields.message ?? '').slice(0, 2000)}`,
} }],
});
if (sheets) await deliver(file, 'sheets', sheets, {
token: process.env.SHEETS_FORWARD_TOKEN,
id: event.id, receiptId, email: fields.email, message: fields.message,
});
} catch {
console.error(`Forward failed for ${event.id}; retry on the next run`);
process.exitCode = 1;
}
}
```
This uses only the `email` and `message` fields; adapt them to your schema. It sends visitor text to Slack as plain text to avoid interpreting mentions or formatting.
A failed destination has no completion marker and is retried on the next run. Preserve inbox files and completion markers. Slack may receive a duplicate if the process stops after Slack accepts a message but before the marker is saved. The Sheets example deduplicates by event ID. This is not an exactly-once delivery guarantee.
FormRoost sees the receiver's `204`, not downstream failures. Monitor this forwarding job and retry locally. Replaying an already saved FormRoost event will not re-run a completed destination. To intentionally forward it again, remove only that destination's completion marker; Sheets will still suppress its existing event ID.
---
url: /docs/recipes/receivers.md
---
> For AI agents: the complete documentation index is available at /docs/llms.txt, the full documentation bundle is available at /docs/llms-full.txt.
# Receive signed webhooks
These are receivers you host yourself. No SDK or framework is needed. Create an endpoint on the form, subscribe to `submission.created`, and store its signing secret as `WEBHOOK_SECRET`. Do not use a submission API key here.
Production destinations need public HTTPS. Put these loopback listeners behind your HTTPS reverse proxy. Local development permits sandbox HTTP loopback destinations. Other private destinations are rejected.
## Verify before parsing
The worker sends `Content-Type: application/cloudevents+json` and three signature headers:
- `webhook-id`: the stable event ID.
- `webhook-timestamp`: Unix seconds for this delivery attempt.
- `webhook-signature`: space-separated `v1,` signatures.
Remove `whsec_` from the secret and base64-decode the rest. Compute HMAC-SHA256 over `webhook-id + "." + webhook-timestamp + "." + raw body`. Compare the base64 signature in constant time. Accept any matching `v1` signature; rotation sends both secrets' signatures for 24 hours.
The installed Standard Webhooks verifier allows 300 seconds in either direction. These examples use that same tolerance and require an integer timestamp. Keep your clock synchronized. Never parse and reserialize JSON before checking its signature.
## Node receiver
Save as `receiver.mjs` and run `node receiver.mjs`. Set `WEBHOOK_SECRET` to your signing secret. Optional `PORT` defaults to `9000`; `INBOX` defaults to `./inbox`.
```js
import { createServer } from 'node:http';
import { createHmac, timingSafeEqual, randomUUID } from 'node:crypto';
import { mkdirSync, openSync, writeFileSync, fsyncSync, closeSync,
linkSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
const secret = process.env.WEBHOOK_SECRET;
if (!secret?.startsWith('whsec_')) throw new Error('Set WEBHOOK_SECRET');
const key = Buffer.from(secret.slice(6), 'base64');
const inbox = process.env.INBOX || './inbox';
mkdirSync(inbox, { recursive: true, mode: 0o700 });
createServer(async (req, res) => {
const answer = (status) => res.writeHead(status).end();
if (req.method !== 'POST' || req.url !== '/webhooks') return answer(404);
try {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 2 * 1024 * 1024) return answer(413);
chunks.push(chunk);
}
const raw = Buffer.concat(chunks);
const id = req.headers['webhook-id'];
const stamp = req.headers['webhook-timestamp'];
const signatures = req.headers['webhook-signature'];
if (typeof id !== 'string' || !/^evt_[A-Za-z0-9_-]+$/.test(id) ||
typeof stamp !== 'string' || !/^\d+$/.test(stamp) ||
typeof signatures !== 'string' ||
Math.abs(Math.floor(Date.now() / 1000) - Number(stamp)) > 300) {
return answer(401);
}
const expected = Buffer.from(createHmac('sha256', key)
.update(`${id}.${stamp}.`).update(raw).digest('base64'));
const valid = signatures.split(' ').some((part) => {
const [version, signature] = part.split(',');
if (version !== 'v1' || !signature) return false;
const candidate = Buffer.from(signature);
return candidate.length === expected.length && timingSafeEqual(candidate, expected);
});
if (!valid) return answer(401);
let event;
try { event = JSON.parse(raw.toString('utf8')); } catch { return answer(400); }
if (event?.id !== id) return answer(400);
// Publish a complete, flushed inbox file atomically; its name deduplicates retries.
const temp = join(inbox, `${randomUUID()}.tmp`);
const fd = openSync(temp, 'wx', 0o600);
try { writeFileSync(fd, raw); fsyncSync(fd); } finally { closeSync(fd); }
try {
try { linkSync(temp, join(inbox, `${id}.json`)); }
catch (error) { if (error.code !== 'EEXIST') throw error; }
} finally { unlinkSync(temp); }
const directory = openSync(inbox, 'r');
try { fsyncSync(directory); } finally { closeSync(directory); }
answer(204);
} catch {
if (!res.headersSent) answer(503);
}
}).listen(Number(process.env.PORT || 9000), '127.0.0.1');
```
## Python receiver
Save as `receiver.py` and run `python3 receiver.py`. It uses the same environment variables and inbox format.
```python
import base64
import hashlib
import hmac
import json
import os
import re
import tempfile
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
secret = os.environ['WEBHOOK_SECRET']
assert secret.startswith('whsec_')
key = base64.b64decode(secret[6:], validate=True)
inbox = Path(os.environ.get('INBOX', './inbox'))
inbox.mkdir(parents=True, exist_ok=True, mode=0o700)
class Receiver(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def answer(self, status):
self.send_response(status)
self.end_headers()
def do_POST(self):
if self.path != '/webhooks':
return self.answer(404)
# This stdlib server requires Content-Length. Preserve it at the proxy.
length = self.headers.get('Content-Length', '')
if not length.isdecimal():
return self.answer(411)
if int(length) > 2 * 1024 * 1024:
return self.answer(413)
self.connection.settimeout(10)
try:
raw = self.rfile.read(int(length))
if len(raw) != int(length):
return self.answer(400)
event_id = self.headers.get('webhook-id', '')
stamp = self.headers.get('webhook-timestamp', '')
signatures = self.headers.get('webhook-signature', '')
if (not re.fullmatch(r'evt_[A-Za-z0-9_-]+', event_id)
or not re.fullmatch(r'[0-9]+', stamp)
or abs(int(time.time()) - int(stamp)) > 300):
return self.answer(401)
signed = (event_id + '.' + stamp + '.').encode() + raw
expected = base64.b64encode(hmac.digest(key, signed, hashlib.sha256))
valid = False
for part in signatures.split(' '):
version, _, signature = part.partition(',')
if version == 'v1' and hmac.compare_digest(signature.encode(), expected):
valid = True
if not valid:
return self.answer(401)
try:
event = json.loads(raw)
except (ValueError, UnicodeDecodeError):
return self.answer(400)
if not isinstance(event, dict) or event.get('id') != event_id:
return self.answer(400)
fd, temp = tempfile.mkstemp(dir=inbox, suffix='.tmp')
try:
with os.fdopen(fd, 'wb') as file:
file.write(raw)
file.flush()
os.fsync(file.fileno())
try:
os.link(temp, inbox / (event_id + '.json'))
except FileExistsError:
pass
finally:
os.unlink(temp)
directory = os.open(inbox, os.O_RDONLY)
try:
os.fsync(directory)
finally:
os.close(directory)
self.answer(204)
except (OSError, ValueError):
self.answer(503)
HTTPServer(('127.0.0.1', int(os.environ.get('PORT', '9000'))), Receiver).serve_forever()
```
These Linux examples acknowledge with `204` after saving the event, before any downstream request. Invalid signatures and stale timestamps get `401`; receiver storage failures get `503`. These are receiver choices, not submission API statuses. The 2 MiB body cap is also a receiver policy; adjust it to your form's payload needs. Keep inbox files private. Use persistent storage, monitor disk space, and retain event IDs when archiving processed payloads. Deleting an inbox file removes its deduplication record. Multiple hosts need a shared transactional inbox with a unique event ID.
## Event fields
A creation event has `specversion: "1.0"`, `id`, `source: "/forms/