# Verena Presence: developer reference

Verena Presence proves that a real person is present on a real device, without a CAPTCHA. The visitor taps once on their phone, with Face ID or a fingerprint. It has two parts: a widget on your page, which gives you a proof token, and one API call on your server, which says whether the token is good. Your site learns nothing else about the visitor.

- Human-readable docs: https://presence.verena.se/docs
- Dashboard (keys and events): https://verena.se/account/keys
- API base URL: `https://verena.se`
- Widget script: `https://widget.verena.se/js/verena.min.js`

## Instructions for AI agents integrating Verena Presence

Verena Presence proves that a real person is present on a real device, as a replacement for a CAPTCHA. It has two parts: a widget on the page, and one API call on the server. Follow these rules when you add it to an application.

### Integration

1. Load the widget with a script tag: `<script src="https://widget.verena.se/js/verena.min.js"></script>`. Do not install `@verena/js` from npm: it is not published.
2. Call `Verena.init({ siteKey, onVerified, onError })` once, then `Verena.mount(container)`. The whole client API is `init`, `mount`, `status` and `reset`. There is no `Verena.verify()`, no modal, and no `onDismiss` or `externalStyles` option. Do not invent other functions or options.
3. The site key (`site_…`) goes in frontend code. The secret key (`sk_…`) goes only in a server-side environment variable, such as `VERENA_SECRET_KEY`: never in client code, logs or version control. If the user has no keys yet, tell them to create a key pair at https://verena.se/account/keys.
4. Pass `proof.token` from `onVerified` to the backend with the request it protects, as a form field or a header.
5. On the server, before acting on the request, `POST https://verena.se/v1/verify` with the header `Authorization: Bearer <secret key>` and the JSON body `{ "token": "<token>" }`. Proceed only if the status is 200 and the response has `"valid": true`. Set a timeout on the call (about 10 seconds), and treat a network error, a timeout or a non-200 status as not verified: fail closed.
6. Never trust `onVerified`, `Verena.status()` or `sessionStorage` on the server. Only the answer from `/v1/verify` counts.
7. A plain token can be verified any number of times within its hour. If the action must happen once per check (a sign-up, a vote, a purchase), store the token, or its SHA-256 hash, after the first use and refuse it the second time.
8. Keep the protected submit button disabled until `onVerified` fires. To ask again, empty the container and call `Verena.mount` again.
9. Give the widget's container `min-height: 88px`, so the page doesn't shift while it loads. The widget is at most 380 px wide.

### Redirects

- In some cases the check sends the visitor away from the page and brings them back through a redirect to `returnUrl` (by default the current page), which can open in a **new tab**. The application must handle this.
- Mount the widget on the `returnUrl` page on load: it picks up the proof there and calls `onVerified(proof, { returned: true })`. Don't rely on the original tab receiving the proof.
- If the page has a form or other state, save it to `localStorage` on input and restore it in `onVerified` when `returned` is `true`, because the new tab starts empty. The saved state can be missing, since the visitor may return in a different browser: then keep the proof and ask the visitor to fill in the form again. Don't save passwords or other secrets.
- In a single-page app, make sure the router keeps the `verena_session` query parameter until the widget has read it.
- `returnUrl` must be on the page's own origin; other values are ignored.
- Leave `appClipRedirect` at its default; do not set it.

### Configuration

- If the site has a Content Security Policy, add `https://widget.verena.se` to `script-src` and `frame-src`. Nothing else is needed: the widget talks to Verena through a privacy relay from inside its own frame.
- Tell the user to set the key's allowed origins in the dashboard to the production origins, written as scheme and host, like `https://example.com`. Handle `onError` with `err.code === "origin_not_allowed"` by logging a clear message for the developer.
- Use events only if the user wants one entry per device, such as a queue or a vote. Any site key works: the user creates the event in the dashboard (it works at once), and the app passes the event's slug as `event` to both `Verena.init` and `/v1/verify` (without it, `/v1/verify` would also accept a plain token from a page that left `event` out), and uses the `entry` id from the response to recognise a device that comes back. Event tokens work once, and `/v1/verify` spends them before the app saves anything, so decide by the app's own records keyed by `entry`, not by `repeat`: if the save fails, a later check reports `repeat: true` with nothing stored. On a failed save, have the page empty the widget's container and mount it again for a new token.

### Do not

- Do not self-host, proxy or bundle the widget script, wrap the widget in your own iframe, or call the `/widget/*` endpoints directly.
- Do not use the old hosts `api.verena.dev` or `cdn.verena.dev`.
- Do not try to decode the token. It is a random string with no claims.
- Do not add a fallback that skips verification when Verena can't be reached, unless the user asks for one.
- Do not collect personal data to go with the check. Verena is designed so that the site learns nothing about the visitor.

Full reference: https://presence.verena.se/docs.md

## Quickstart

1. Sign in at https://verena.se/login and create a key pair in the dashboard. You get a site key (`site_…`) for the page and a secret key (`sk_…`) for your server. The secret key is shown once.
2. Add the widget to the page.
3. Check the token on your server with `POST /v1/verify` before you act on the request.

```html
<div id="verena" style="min-height: 88px"></div>
<script src="https://widget.verena.se/js/verena.min.js"></script>
<script>
  Verena.init({
    siteKey: "site_your_key",
    onVerified: (proof) => {
      // Send proof.token with the request you want to protect
      form.elements.verenaToken.value = proof.token;
    },
  });
  Verena.mount("#verena");
</script>
```

```js
// Node.js (Express)
app.post("/signup", async (req, res) => {
  let valid = false;
  try {
    const check = await fetch("https://verena.se/v1/verify", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.VERENA_SECRET_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ token: req.body.verenaToken }),
      signal: AbortSignal.timeout(10_000),
    });
    valid = check.ok && (await check.json()).valid === true;
  } catch {
    // Network error or timeout: fail closed
  }
  if (!valid) return res.status(403).send("Verify you're human first.");
  // A real person is here: go ahead
});
```

```python
# Python (Flask)
@app.post("/signup")
def signup():
    try:
        check = requests.post(
            "https://verena.se/v1/verify",
            headers={"Authorization": f"Bearer {VERENA_SECRET_KEY}"},
            json={"token": request.form.get("verenaToken", "")},
            timeout=10,
        )
        valid = (check.status_code == 200
                 and check.json().get("valid") is True)
    except (requests.RequestException, ValueError):
        valid = False  # error or timeout: fail closed
    if not valid:
        return "Verify you're human first.", 403
```

Always check on the server. The widget's callback runs in the visitor's browser, and a bot can skip it.

## How a check works

- **1.** Your page calls `Verena.mount()`. The widget runs in a frame on Verena's domain.
- **2. The Verena check:** the visitor confirms with their device, Verena checks that interaction with local device attestation, and the widget gets a proof token.
- **3.** The widget calls your `onVerified(proof)`.
- **4.** Your page sends the token to your server with its request.
- **5.** Your server calls `POST /v1/verify` and gets `{ "valid": true }`.

Local device attestation means the device's own secure hardware vouches that a real person used it. How the check runs differs per platform and device, and can change over time; nothing in your integration depends on it.

The token is the same whichever way the visitor verified.

## Widget

### Install

```html
<script src="https://widget.verena.se/js/verena.min.js"></script>
```

This defines a global `Verena`. The npm package `@verena/js` is not published yet. The widget is a 380 × 88 frame that fills its container up to 380 px wide. It works on HTTPS pages and on `localhost`.

### Verena.init(config)

Call once, before `mount`. Throws if `siteKey` is missing.

| Option | Type | Description |
|---|---|---|
| `siteKey` | string, required | Your public site key, `site_…`. |
| `onVerified` | `(proof, context) => void` | Called when the visitor has verified. `proof.token`: the token. `proof.expiresAt`: Unix seconds, one hour after issue. `proof.repeat`: at an event, the device had entered before. `context.returned`: `true` when the visitor came back through a redirect, on a new tab (see Handling redirect URLs). |
| `onError` | `(error) => void` | Called with an `Error` when the widget can't start or the check fails. May carry a `code` (see Errors). |
| `theme` | `"light" \| "dark" \| "auto"` | Default `"light"`. `"auto"` follows the system. |
| `event` | string | Slug of one of your events, made on this site key. With it the check is an entry to that event; without it, plain verification. Any key does both. |
| `returnUrl` | string | Where the visitor returns after verifying, when the check sends them away from your page, as on iPhone or in an in-app browser. Same origin as the page, or ignored. Default: the current page. |
| `appClipRedirect` | boolean | Default `true`. `false` keeps iPhones on a web form on which a new iPhone can't verify: for testing only. Ignored at events. |

### Verena.mount(container)

Renders the widget into `container`, a CSS selector or an element. Throws if `init` wasn't called or the container doesn't exist. To ask again, empty the container and call `mount` again.

### Verena.status()

Returns `{ verified: boolean, expiresAt?: number }`: whether this tab holds an unexpired proof (kept in `sessionStorage`). Useful to skip the widget for a visitor who just verified. Not proof for your server.

### Verena.reset()

Forgets the stored proof. Tokens already issued stay valid on the server until they expire.

### Errors

`onError` receives an `Error` with a readable `message`. Setup problems are also logged to the console with the prefix `[verena]`.

| `code` | Meaning | Fix |
|---|---|---|
| `invalid_key` | The site key doesn't exist. | Check `siteKey`. |
| `origin_not_allowed` | The page's origin isn't in the key's allowed origins. | Add it in the dashboard. |
| `unknown_event` | No event with that slug on this key. | Check the slug, and that the event is on the key in `siteKey`. |
| `bad_event` | `event` isn't a string. | Pass the slug as a string, or leave `event` out. |

Errors without a `code` come from the check itself, like a cancelled fingerprint prompt. The widget shows them and lets the visitor retry.

### Content Security Policy

```
Content-Security-Policy:
  script-src 'self' https://widget.verena.se;
  frame-src https://widget.verena.se
```

No `connect-src` entry is needed: your page makes no requests to Verena.

## Server API

### Authentication

Send the secret key as a bearer token: `Authorization: Bearer sk_…`. Each secret key belongs to one site key, and verifies only the tokens issued for it. A missing or wrong key returns `401` with `{ "valid": false, "error": "…" }`.

### POST /v1/verify

Checks a proof token. A token that isn't valid returns `200` with `"valid": false` and an `error`. `401` and `400` mean the call itself was wrong.

Body:

| Field | Type | Description |
|---|---|---|
| `token` | string, required | The token from `onVerified`. |
| `event` | string | For event tokens: the slug you expect. Always pass it when you expect an entry: a key gives plain tokens too, and with `event` those are refused (`not_event_token`). A token for another event of the same key is refused and stays unused. |

Response:

| Field | Type | Description |
|---|---|---|
| `valid` | boolean | Whether to let the request through. |
| `scope` | `"personhood"` \| `"device-entry"` | `"device-entry"` for event tokens. |
| `error` | string | Why not valid, in words. |
| `code` | string | The same, for code: `token_invalid` (unknown, expired, or an event token already spent), `wrong_key` (issued for another site key), `not_event_token` (you passed `event`, the page didn't), `other_event`, `token_used`. The event's dashboard page counts each. |
| `event` | string | Event tokens: the event's slug. |
| `entry` | string | Event tokens: 32 hex characters, the same every time this device enters this event. |
| `repeat` | boolean | Event tokens: the device had entered before. |

```json
{ "valid": true, "scope": "personhood" }
```

```json
{ "valid": true, "scope": "device-entry", "event": "spring-sale", "entry": "9b2e41c07d5fa3e8c16b0f42d97a5e13", "repeat": false }
```

```json
{ "valid": false, "code": "token_invalid", "error": "Token is invalid or expired." }
```

### Proof tokens

- A random 64-character hex string with no claims. Only `/v1/verify` can check it. Verena stores only its hash.
- Valid for one hour, and only with the secret key of the key pair it was issued for.
- A plain token can be verified any number of times until it expires. Mark it used on your side if an action should happen once.
- Event tokens are spent by the first successful `/v1/verify`.
- No revocation: let tokens expire.

## Guides

### Allowed origins

Each key has a list of allowed origins, set in the dashboard as a comma-separated list, like `https://example.com, https://www.example.com`. The widget then starts only on those origins, and anywhere else `onError` gets `origin_not_allowed`.

- Write an origin as scheme and host, plus a port if it isn't the default: `https://example.com`, `http://localhost:3000`. No path, no trailing slash.
- `https://example.com` also allows the same host on another port, but not subdomains: list `https://www.example.com` separately.
- An empty list allows any origin. Convenient while developing; set the list before going live.
- Use separate keys for production and for development, so their origins and traffic stay apart. Every key does plain verification and any of its events.
- The first key's allowed origin defaults to the website given at sign-up. Change a key's origins any time with Edit in the dashboard.

### Handling redirect URLs

Most checks finish inside the widget, on your page. In some cases, depending on the device and on how the visitor moves through the check, Verena sends them back to your site through a redirect instead, and that can land in a **new tab**. Your site must handle it.

The two common cases:

- **iOS.** The check runs in the Verena App Clip, and when it's done, iOS opens your page again in a new Safari tab rather than returning to the one the visitor left.
- **In-app browsers**, the browser views inside apps like Instagram, TikTok or Gmail. The check can't finish there, so it continues in the device's regular browser, and the visitor comes back to your page in a new tab there, not in the app they started in.

1. The visitor leaves your page, for example to the App Clip, or from an in-app browser to the regular browser.
2. They verify, and Verena issues the token for the session.
3. They land on `returnUrl` (by default the page they came from), possibly in a new tab, with a `verena_session` query parameter.
4. The widget on that page picks up the proof, removes the parameter from the address bar, scrolls back to where the visitor was, shows as verified and calls `onVerified(proof, { returned: true })`.

What your site must do:

- Mount the widget on the `returnUrl` page, on load. Without it the proof isn't picked up, and the visitor has to verify again.
- Restore state when `returned` is `true`. The new tab starts fresh, so anything typed or chosen before verifying is gone unless you saved it, for example to `localStorage`.
- Handle a missing draft. `localStorage` is shared only within one browser. When an in-app browser hands over to the regular browser, the visitor returns in a different browser and the draft isn't there. The proof still counts: tell the visitor and let them fill in the form again.
- Single-page apps: point `returnUrl` at a route that mounts the widget, and don't let the router drop `verena_session` before the widget reads it.
- Don't rely on the original tab. It may still be open, but it won't receive the proof.

`returnUrl` must be on the page's own origin; other values are ignored, so a session can't become an open redirect.

```js
const KEY = "signup-draft";
form.addEventListener("input", () => {
  const draft = Object.fromEntries(new FormData(form));
  delete draft.password; // never store secrets
  try {
    localStorage.setItem(KEY, JSON.stringify(draft));
  } catch {} // private mode or full: the fallback below covers it
});
form.addEventListener("submit", () => {
  localStorage.removeItem(KEY);
});

Verena.init({
  siteKey: "site_your_key",
  returnUrl: "/signup",
  onVerified(proof, { returned }) {
    form.elements.verenaToken.value = proof.token;
    if (!returned) return;
    let draft = null;
    try {
      draft = JSON.parse(localStorage.getItem(KEY));
    } catch {} // storage blocked, or not valid JSON
    if (draft) {
      for (const [k, v] of Object.entries(draft)) {
        if (form.elements[k]) form.elements[k].value = v;
      }
    } else {
      // Back in another browser, without the draft.
      // The proof still counts: ask for the form again.
      notice.textContent =
        "You're verified. Please fill in the form again.";
    }
  },
});
Verena.mount("#verena");
```

### Events

An event lets each device in once: a ticket queue, a drop, a vote, a sign-up. A device that comes back gets its same entry, so a visitor who reloads keeps their place.

1. Create an event under Events in the dashboard. Name it, and the dashboard suggests the slug you pass as `event`. Put it on any of your keys (they keep doing plain verification), or let the dashboard make a new one. You can give it an opening time, from which the dashboard charts entries, and an image (PNG, JPEG or WebP, up to 512 KB) that the App Clip shows as the visitor enters.
2. Pass `event` to `Verena.init` and to `/v1/verify`. Store `entry`, and look it up in your own records to recognise a returning device; `repeat: true` says it entered before.

```js
// Page
Verena.init({
  siteKey: "site_your_key",
  event: "spring-sale",
  async onVerified(proof) {
    const res = await fetch("/signup", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        token: proof.token,
        ...Object.fromEntries(new FormData(form)),
      }),
      signal: AbortSignal.timeout(15_000),
    }).catch(() => null); // network error or timeout
    if (res?.ok) return showDone(await res.json());

    // Not saved. The token may be spent, so get a new one.
    // The server accepts the retry: it has no record of
    // this entry yet, whatever `repeat` says.
    notice.textContent = "That didn't go through. Verify again.";
    const box = document.querySelector("#verena");
    box.innerHTML = "";
    Verena.mount(box);
  },
});
Verena.mount("#verena");
```

```js
// Server (Node.js, Express)
// The /v1/verify call, failing closed. `unavailable`:
// Verena couldn't answer, so ask for a new check later.
async function verify(body) {
  try {
    const res = await fetch("https://verena.se/v1/verify", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.VERENA_SECRET_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(10_000),
    });
    if (!res.ok) return { valid: false, unavailable: res.status >= 500 };
    return await res.json();
  } catch {
    return { valid: false, unavailable: true }; // network error, timeout
  }
}

app.post("/signup", async (req, res) => {
  const result = await verify({ token: req.body.token, event: "spring-sale" });
  if (result.unavailable) return res.status(503).end();
  if (!result.valid) return res.status(403).end();

  // The token is now spent. Decide by your own record of
  // this entry, never by `repeat`: if an earlier save failed,
  // this retry says repeat: true and you have nothing stored.
  // signups.entry has a unique index.
  const saved = await signups.findByEntry(result.entry);
  if (saved) return res.json({ id: saved.id, already: true });
  try {
    const { id } = await signups.insert({ entry: result.entry, email: req.body.email });
    res.json({ id });
  } catch (e) {
    if (isUniqueViolation(e)) return res.json({ already: true }); // a parallel retry won
    console.error("signup not saved", e);
    res.status(503).end(); // the page asks for a new check, and we accept it
  }
});
```

- Entering needs a phone: the Verena app on iPhone, or Chrome on Android. A computer shows a QR code.
- Event tokens work once.
- **A failed save.** `/v1/verify` spends the token before your app saves anything. If the save then fails, the visitor needs a new token, and that check reports `repeat: true` though you never recorded the sign-up. So look the `entry` up in your own records: none there means accept the retry, one there means they already signed up. Put a unique index on `entry`, so two retries at once save one row.
- **Timeouts and errors.** A timeout, a network error or a non-200 from `/v1/verify` is never a pass. Answer `503` and let the page ask for a new check.
- The dashboard counts **devices entered**: one per device, at its first entry; a device that comes back isn't counted again. Next to it, the **last server verification**: when `/v1/verify` last answered `valid: true` for the event. Verena can't see your database: count the sign-ups you saved and compare, to measure completion.
- When nothing comes in, the event's dashboard page shows each stage as Verena saw it, as counts only: checks your page started, refusals (`origin_not_allowed`, `unknown_event`), QR handoffs no phone finished, phones turned away, and `/v1/verify` answers by `code`. It shows by platform and over time, never which device.
- **Clear entries** lets every device enter again: a device keeps its `entry` id but comes back with `repeat: false`, and tokens not verified yet stop working. **Remove** deletes the event; a new one with the same slug gives devices new `entry` ids. Neither touches what your app saved. A key can't be deleted while it has events.
- **Anonymous events (coming soon):** entries counted in zero knowledge, up to a number of uses per device that you choose.

### Privacy relay

The widget never talks to Verena's servers directly. Its requests are encrypted with Oblivious HTTP (RFC 9458) and sent through an independent relay run by Oblivious Network (`relay.oblivious.network`).

- The relay sees the visitor's IP address, but only encrypted content.
- Verena sees the content, but only the relay's address.
- The widget's page and script load from `widget.verena.se`, a static host, so the page load doesn't reach Verena's servers either.
- Your page makes no requests to Verena at all. That is why a CSP needs only `script-src` and `frame-src`.
- It fails closed: if the relay can't be reached, the widget shows an error and never falls back to a direct connection.
- On by default. For debugging only, `?verena_ohttp=0` in the page's address turns it off for that page load.

## Privacy and security

- Your site learns `valid: true`, and at events an `entry` id. No name, email, device id or biometrics.
- For a standard check Verena learns that a registered device proved itself, not which one. The device looks up its place in the set of keys with private information retrieval, so the lookup doesn't single it out either.
- Every check answers a fresh, single-use challenge. The widget runs in a cross-origin frame that page scripts can't read or click. Tokens are bound to the key pair, expire after an hour and are stored as hashes.

## Testing

- The widget works on `http://localhost`. Leave allowed origins empty, or add `http://localhost:3000`.
- Use a real phone: an iPhone, or an Android phone with Chrome. From a computer, scan the QR code with your phone.
- Test the server path with a real token from `onVerified`.
- Demos: https://verena.se/demo/contact, https://verena.se/demo/queue, https://verena.se/demo/article
