# Pontive: auth.md

> Pontive is one platform for a product's identity and access: sign-in and sessions, organizations,
> roles and permissions, apps, APIs and AI agents, subscriptions and billing. **A coding agent may
> start without a Pontive account**: it creates an unclaimed development instance, the app runs on the
> developer's machine at once, and the developer claims the instance into their own Pontive workspace
> whenever they choose. Docs: https://www.pontive.com/docs (every page is Markdown at `<page>.md`), index
> for agents: https://www.pontive.com/llms.txt.

## 1. Prefer the CLI

With Node 20 or later, in the app's directory:

```sh
npx pontive@latest init
```

`init` detects the framework (Next.js, Vite + React, Express, plain Node), installs the pontkit
package, writes the auth route and middleware, and, when nobody is signed in to Pontive, creates an
unclaimed development instance and writes its credentials (section 4). It always uses the encrypted
handoff, so no secret passes through your transcript.

**Agent mode is automatic** when `CLAUDECODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `GEMINI_CLI` or `CI`
is set, or with `--json`: no prompts, one JSON object on stdout, the claim link printed instead of a
browser opened. Writes outside `.env.local`, `.pontive/` and the files `init` scaffolds need `--yes`.
`--region us|eu|au` (or `PONTIVE_REGION`) chooses the region.

| Exit code | Meaning |
| --- | --- |
| `0` | Success |
| `1` | Error |
| `2` | Cancelled |
| `3` | Rate limited; the JSON carries `retry_after` in seconds |
| `4` | Sign-in required |
| `5` | The unclaimed instance expired or was claimed away; stop and ask the user (section 7) |

Other commands: `npx pontive claim` (section 6), `npx pontive status` (the instance, its region, its
deletion date or claimed, and which variables are set), `npx pontive init --reset` (a new unclaimed
instance, after confirmation or `--yes`).

## 2. Without the CLI

One unauthenticated call creates the instance:
`POST https://api.pontive.com/v1/unclaimed-instances`. Send a public key with it and the secrets come
back encrypted to that key, so they never appear in plain text in a tool result or a transcript.

**Step 1: keep the files out of git, and make a one-time P-256 key.**

```sh
mkdir -p .pontive
grep -qxF '.env.local' .gitignore 2>/dev/null || echo '.env.local' >> .gitignore
grep -qxF '.pontive/' .gitignore 2>/dev/null || echo '.pontive/' >> .gitignore
openssl ecparam -name prime256v1 -genkey -noout -out .pontive/handoff.pem
```

**Step 2: write the request body**, with the key's public half as a JWK:

```sh
node -e '
const { createPublicKey } = require("node:crypto"); const fs = require("node:fs");
const { kty, crv, x, y } = createPublicKey(fs.readFileSync(".pontive/handoff.pem")).export({ format: "jwk" });
fs.writeFileSync(".pontive/request.json", JSON.stringify({
  name: "Acme Notes",                       // the project name the developer will see
  tenancy_mode: "b2c",                      // or "b2b"; never changes
  app: { type: "web" },                     // "web" (server sessions, client secret), "spa" or "native"
  encryption_key: { kty, crv, x, y },
  client: { name: "auth.md", agent: "claude-code" }, // free text: your tool and agent
}));'
```

All fields are optional:

| Field | Default | Notes |
| --- | --- | --- |
| `name` | `Untitled app` | The project's name; the claimer may rename it |
| `region` | the region nearest the caller, by country | `us`, `eu` or `au`. Immutable, also after the claim. The response says which was chosen |
| `tenancy_mode` | `b2c` | `b2b` (customers are organizations) or `b2c`. Immutable |
| `app.type` | `web` | `web`: a confidential app with a client secret. `spa`: a public app with PKCE. `native`: a public native app |
| `app.redirect_uris` | `http://localhost/api/auth/callback`, `http://127.0.0.1/api/auth/callback` | Loopback only. A URI without a port matches any port |
| `encryption_key` | none | A public JWK, `EC` P-256 or `OKP` X25519, never a private part. Without it the secrets are in the body in plain text |
| `client` | none | `{ name, version, agent }`, for Pontive's metrics |

**Step 3: call the API.** Keep the idempotency key: a retry with the same key returns the same
instance and is not counted twice.

```sh
IDEMPOTENCY_KEY=$(node -e 'console.log(crypto.randomUUID())')
curl -sS -X POST https://api.pontive.com/v1/unclaimed-instances \
  -H "Content-Type: application/json" -H "X-Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data @.pontive/request.json -o .pontive/response.json -w '%{http_code}\n'
```

Any status but `201` leaves an error envelope, with no secret, in `.pontive/response.json`: read it
and see section 7. `201` answers:

```json
{
  "object": "unclaimed_instance",
  "instance_id": "inst_01jf…",
  "project_id": "proj_01jf…",
  "name": "Acme Notes",
  "region": "us",
  "environment": "non_production",
  "tenancy_mode": "b2c",
  "issuer": "https://acme-notes-k3x9q2pa-dev.auth.us.pontive.dev",
  "app_id": "app_01jf…",
  "encrypted_secrets": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIs…",
  "expires_at": "2026-12-09T10:00:00Z",
  "limits_url": "https://www.pontive.com/docs/unclaimed-instances#limits"
}
```

`encrypted_secrets` is a compact JWE (RFC 7516): `alg` `ECDH-ES`, `enc` `A256GCM`, its plaintext
`{ "client_secret", "secret_key", "claim_token" }` (`client_secret` for a `web` app only). Without
`encryption_key` those three fields are in the body instead. Do not print `.pontive/response.json`.

**Step 4: decrypt and write the files.** Save this as `.pontive/handoff.mjs` and run
`node .pontive/handoff.mjs`. It uses only Node's own `crypto`, writes section 4's files without
printing a secret, and deletes the response and the private key.

```js
// Reads .pontive/response.json; writes .env.local and .pontive/keyless.json; prints no secret.
import { createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, randomBytes } from "node:crypto";
import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";

const b64 = (s) => Buffer.from(s ?? "", "base64url");
const lp = (buf) => { const n = Buffer.alloc(4); n.writeUInt32BE(buf.length); return Buffer.concat([n, buf]); };

// Compact JWE, alg ECDH-ES (direct key agreement, Concat KDF with SHA-256), enc A256GCM.
function decrypt(jwe, privateKeyPem) {
  const [h, , iv, ct, tag] = jwe.split(".");
  const header = JSON.parse(b64(h));
  if (header.alg !== "ECDH-ES" || header.enc !== "A256GCM") throw new Error(`unexpected JWE ${header.alg}/${header.enc}`);
  const z = diffieHellman({ privateKey: createPrivateKey(privateKeyPem), publicKey: createPublicKey({ key: header.epk, format: "jwk" }) });
  const otherInfo = Buffer.concat([lp(Buffer.from("A256GCM")), lp(b64(header.apu)), lp(b64(header.apv)), Buffer.from([0, 0, 1, 0])]);
  const cek = createHash("sha256").update(Buffer.concat([Buffer.from([0, 0, 0, 1]), z, otherInfo])).digest();
  const decipher = createDecipheriv("aes-256-gcm", cek, b64(iv)).setAAD(Buffer.from(h)).setAuthTag(b64(tag));
  return JSON.parse(Buffer.concat([decipher.update(b64(ct)), decipher.final()]));
}

const res = JSON.parse(readFileSync(".pontive/response.json", "utf8"));
const secrets = res.encrypted_secrets ? decrypt(res.encrypted_secrets, readFileSync(".pontive/handoff.pem")) : res;

const env = existsSync(".env.local") ? readFileSync(".env.local", "utf8") : "";
const vars = {
  PONTIVE_ISSUER: res.issuer,
  PONTIVE_CLIENT_ID: res.app_id,
  PONTIVE_CLIENT_SECRET: secrets.client_secret, // web apps only
  PONTIVE_SESSION_SECRET: randomBytes(32).toString("base64url"), // generated here, never by Pontive
  PONTIVE_SECRET_KEY: secrets.secret_key,
  PONTIVE_INSTANCE_ID: res.instance_id,
};
const lines = Object.entries(vars).filter(([k, v]) => v && !new RegExp(`^${k}=`, "m").test(env)); // never overwrite
if (lines.length) appendFileSync(".env.local", `${env && !env.endsWith("\n") ? "\n" : ""}${lines.map(([k, v]) => `${k}=${v}`).join("\n")}\n`);

const { instance_id, issuer, app_id, expires_at, region } = res;
writeFileSync(".pontive/keyless.json", JSON.stringify({ instance_id, issuer, app_id, claim_token: secrets.claim_token, expires_at, region }, null, 2) + "\n", { mode: 0o600 });
rmSync(".pontive/response.json"); rmSync(".pontive/handoff.pem", { force: true }); rmSync(".pontive/request.json", { force: true });
console.log(`Unclaimed development instance ${instance_id} (${region}), deleted on ${expires_at} unless claimed. Wrote .env.local and .pontive/keyless.json.`);
```

Any JOSE library does the same: `jose`'s `compactDecrypt` in JavaScript, `go-jose` in Go, `joserfc` or
`jwcrypto` in Python.

## 3. Use it

The app's server reads the variables of section 4. With pontkit (`@pontive/pontkit-nextjs`,
`@pontive/pontkit-server`) nothing more is needed: `pontiveAuth()` reads them when its config leaves
them out. Pass the client id to browser code from the server; never copy a secret into a
`NEXT_PUBLIC_` or `VITE_` variable. The quickstarts: https://www.pontive.com/docs/quickstart/nextjs.md and
https://www.pontive.com/docs/quickstart/react.md.

To configure the instance (apps, roles, organizations, users), connect the Pontive MCP server,
`https://mcp.pontive.com/mcp`, with the secret key: https://www.pontive.com/docs/guides/pontive-mcp-server.md.

To search and read these docs from your MCP client, connect the docs MCP server,
`https://www.pontive.com/docs/mcp` (no sign-in): `search_docs`, `get_doc`, `list_docs` and
`get_integration_guide`, which returns the documented setup for a framework. Setup:
https://www.pontive.com/docs/guides/docs-mcp-server.md.

## 4. What to write where

| Where | What |
| --- | --- |
| `.env.local` | `PONTIVE_ISSUER` (the `issuer`), `PONTIVE_CLIENT_ID` (the `app_id`), `PONTIVE_CLIENT_SECRET` (`web` only), `PONTIVE_SESSION_SECRET` (32 or more random characters you generate, never Pontive), `PONTIVE_SECRET_KEY`, `PONTIVE_INSTANCE_ID` |
| `.pontive/keyless.json` | `{ "instance_id", "issuer", "app_id", "claim_token", "expires_at", "region" }` |

- Both are gitignored: `.env.local` and `.pontive/` are in `.gitignore` before anything is written.
- Append to `.env.local`; never overwrite a `PONTIVE_*` line that is already there.
- **Never log, print, paste or commit** the secret key, the client secret, the session secret or the
  claim token. Never put the claim token in a URL or show it to the user: the claim token is the
  instance's ownership. Show the user a claim link (section 6) instead.

## 5. Limits

Details: https://www.pontive.com/docs/unclaimed-instances.md

- **7 days.** An unclaimed instance is deleted, with its users and everything else in it, at
  `expires_at`, 7 days after creation. It is never extended; claiming is the only way to keep it.
  Until then every API response for it carries `Sunset: <date>`.
- **3 per IP per day** (an IPv6 /64 counts as one address), plus a daily ceiling per network. Beyond
  that, `429 unclaimed_instance_limit` with `Retry-After`.
- **Loopback redirects only**: `localhost`, `127.0.0.1` or `[::1]`, `http` or `https`; anything else
  is `422 redirect_uri_not_loopback`. On a development instance a loopback redirect URI or origin
  registered without a port matches any port, so the dev server may change ports.
- **Free's features and caps**: for example 10,000 monthly active users, 2 apps, 5 organizations.
- **While unclaimed**: no custom domains, no webhooks, no generic OIDC or SAML connections, Pontive's
  default branding, and sign-in email only (verification codes and links, password resets: 100 a day,
  5 an hour to one address); invitations are created but not emailed. These refusals are
  `403 instance_unclaimed`. All of it lifts at the claim.

## 6. Claiming

The developer claims the instance into a Pontive workspace (signing up if they have no account). The
instance id, issuer, app, users, keys and secrets do not change, so nothing in the app needs editing.

**With the CLI:** `npx pontive claim` mints a link, opens it (prints it in agent mode), waits until
the developer has claimed, then removes `claim_token` from `.pontive/keyless.json`.

**Without the CLI:** mint a claim link with the claim token, read from the file without printing it:

```sh
INSTANCE_ID=$(node -p 'require("./.pontive/keyless.json").instance_id')
curl -sS -X POST "https://api.pontive.com/v1/unclaimed-instances/$INSTANCE_ID/claim-links" \
  -H "X-Pontive-Claim-Token: $(node -p 'require("./.pontive/keyless.json").claim_token')"
```

```json
{ "object": "claim_link", "url": "https://app.pontive.com/claim/inst_01jf…#code=…", "expires_at": "2026-12-02T11:00:00Z" }
```

Give the user the `url`. It lasts **one hour** and works **once**; mint another whenever needed.

Then poll the instance every 5 seconds, for at most 5 minutes, until `status` is `claimed`:

```sh
for i in $(seq 60); do
  STATUS=$(curl -sS "https://api.pontive.com/v1/unclaimed-instances/$INSTANCE_ID" \
    -H "X-Pontive-Claim-Token: $(node -p 'require("./.pontive/keyless.json").claim_token')" \
    | node -p 'JSON.parse(require("fs").readFileSync(0, "utf8")).status')
  [ "$STATUS" = "claimed" ] && break
  sleep 5
done
echo "$STATUS"
# once claimed, the claim token is dead: drop it from the file
[ "$STATUS" = "claimed" ] && node -e '
const fs = require("node:fs"); const j = JSON.parse(fs.readFileSync(".pontive/keyless.json", "utf8"));
delete j.claim_token; fs.writeFileSync(".pontive/keyless.json", JSON.stringify(j, null, 2) + "\n");'
```

- `claimed`: the block above removes `claim_token` from `.pontive/keyless.json`; it no longer works.
- Still `unclaimed` after 5 minutes: stop polling and leave the link with the user. The instance keeps
  working meanwhile; check again later with the same call.
- `404 unclaimed_instance_not_found`: the instance expired (or the token is wrong).
  `409 instance_claimed` on a link mint: it is already claimed.

## 7. Errors

Errors use one envelope: `{ "error": { "type", "code", "message", "param"? } }`.

| Status | Do |
| --- | --- |
| `429` | Back off: wait `Retry-After` seconds before trying again. Do not switch networks to get around it |
| `401` from a secret key that worked before | The instance expired, or whoever claimed it revoked the key. **Stop and ask the user.** Never create a replacement instance silently: it would have none of the users the developer created |
| `403 caller_blocked` | Stop and tell the user |
| `422` | Fix the field named in `param` (`redirect_uri_not_loopback`, `invalid_region`, `invalid_encryption_key`, `field_invalid_format`) |
| `5xx`, or `503 unclaimed_instances_unavailable` | Retry the same request with the **same** `X-Idempotency-Key`, after `Retry-After` when it is set |
