Token VaultDocs
ReferenceWebhook Protocol

Webhook Endpoint Reference

Request and response schemas for every /v1 endpoint of the webhook protocol, with sequence diagrams for bind, store, credential fetch and proxy.

Your webhook exposes these endpoints. Token Vault calls seven of them with HMAC-signed requests. Five are called by browsers and agents directly, with Token Vault out of the request path. See Authentication and Tickets and capabilities for how each is secured.

EndpointCallerAuthCapability
POST /v1/exchangeToken VaultOne-time codealways
GET|HEAD|POST /v1/healthToken Vault, monitorsHMAC (POST)always
POST /v1/storageToken VaultHMACstorage
POST /v1/proxyToken VaultHMAC + ticketproxy
POST /v1/refresh-notifyToken VaultHMACrefresh
POST /v1/admin/migrateToken VaultHMACticketConstraints
POST /v1/refreshToken VaultHMACtv-refresh (legacy)
GET|POST /v1/credentialAgent, CLI, browserTicketcredential
POST /v1/storeBrowser, CLITicketstore
GET|POST /v1/totp-codeBrowserTickettotp
GET /v1/oauth/start, GET /v1/oauth/callbackBrowserState ticketoauth-callback (own page)
GET /v1/register-url, GET /bindOperatornone (sealed after bind)none

Token Vault to webhook

Every endpoint in this section except /v1/exchange is HMAC-authenticated. Verify X-TokenVault-Signature before you read the body, and reject with 401 auth_failed on a mismatch.

POST /v1/exchange

Called once to bind. The one-time code is the authentication.

Loading diagram...
POST /v1/exchange HTTP/1.1
Content-Type: application/json

{"code":"550e8400-e29b-41d4-a716-446655440000"}
200 OK
{
  "hmacSecret": "<base64-encoded 256-bit secret>",
  "webhookId": "wh_abc123",
  "version": "1.0.0",
  "capabilities": ["store", "credential", "proxy", "refresh", "storage", "totp"]
}
FieldNotes
hmacSecretBase64 of a 256-bit secret
webhookIdYour webhook's id
versionYour implementation version, any semver
capabilitiesSee capabilities

Errors: 410 code_expired ("Registration code expired or not found"), 410 code_used ("Registration code already used"). A webhook that sealed itself after its first bind answers 403 forbidden unless the request carries a valid x-tv-admin-secret (see Security). Token Vault never sends that header.

GET|HEAD|POST /v1/health

POST /v1/health HTTP/1.1
X-TokenVault-Signature: sha256=...
X-TokenVault-Timestamp: 1708300000
X-TokenVault-Request-Id: req_xyz789abc012

{"requestId":"req_xyz789abc012"}
200 OK
{
  "status": "healthy",
  "version": "1.0.0",
  "keyConfigured": true,
  "capabilities": ["store", "credential", "proxy", "refresh", "storage", "totp"],
  "uptime": 86400,
  "tokenCount": 5
}
FieldNotes
statushealthy, degraded or unreachable
versionYour implementation version
keyConfiguredWhether an encryption key exists. false is valid: encryption is optional
capabilitiesSame list as /v1/exchange
uptimeSeconds since the process started
tokenCountCredentials currently stored

GET needs no authentication (monitors, load balancers, and the setup wizard, which fetches it from the browser, so return CORS headers on it). HEAD needs none and returns 200 with an empty body and no storage I/O. Token Vault sends HEAD to warm the connection before a credential fetch and on dashboard loads, so answer it explicitly: some frameworks do not derive it from GET.

POST /v1/storage

Metadata only. This endpoint never returns a credential value. One endpoint handles get, list, set, delete and list_batch over four collections.

CollectionHolds
tokensToken documents, keyed by service name. list returns metadata only
proxy_configsLegacy MCP proxy configs, keyed by proxy id
auditActivity events, keyed by a unique time-sortable string, newest first by data.timestamp
vault_configSettings (single key settings)

MCP servers on a credential are not stored here. Token Vault keeps them in its own database and sends the MCP server URL and header templates in each /v1/proxy call.

list tokens: request
{ "requestId": "req_list_tokens456", "operation": "list", "collection": "tokens" }
200 OK
{
  "requestId": "req_list_tokens456",
  "items": [
    {
      "key": "github",
      "meta": {
        "serviceName": "github",
        "tokenType": "JWT",
        "expiryTime": 1720003600000,
        "createdAt": "2026-02-01T10:00:00Z"
      }
    }
  ]
}

Each item must have key and a meta object with at least serviceName. The meta comes from the stored document's plaintext metadata, never from a decrypted value.

list with options. options is optional; a webhook that ignores it returns all items and Token Vault filters in memory.

Request
{
  "requestId": "req_list_audit789",
  "operation": "list",
  "collection": "audit",
  "options": {
    "limit": 50,
    "after": "2026-02-15T10:30:00Z",
    "filters": { "event_type": "AGENT_CREDENTIAL_ACCESS", "source": "agent" }
  }
}
OptionTypeNotes
limitintMax items. At most 200
afterstringCursor. Token Vault sends back the nextCursor of the previous page, unchanged. For audit, return older items; the reference webhook uses <timestamp>|<key> (spec 2.11.0), and a plain timestamp still works. For tokens, a service-name cursor
filtersobjectKey-value matches against item data. AND-ed
Response with pagination (all fields optional)
{
  "requestId": "req_list_audit789",
  "items": [],
  "pagination": { "hasMore": true, "nextCursor": "2026-02-14T08:00:00.123Z|2026-02-14T08:00:00.123Z-9f2c1a", "totalCount": 1234 }
}

Several audit events can share one timestamp. A nextCursor that is only a timestamp skips the rest of that instant on the next page, so name the last event's timestamp and key.

If pagination is absent, Token Vault assumes there are no more pages.

get

{ "requestId": "req_get_config123", "operation": "get", "collection": "vault_config", "key": "settings" }

Response {"requestId": "...", "data": { ... }}; data is null when missing.

get on the tokens collection must return metadata only (spec 2.12.0): the same object that a list item carries in meta. Never return the stored document: no fields, no ciphertext, and no plaintext value of a document stored without encryption. A credential leaves your webhook only through /v1/credential and /v1/proxy.

set and delete

{ "requestId": "req_set_1", "operation": "set", "collection": "vault_config", "key": "settings", "data": { } }
{ "requestId": "req_del_1", "operation": "delete", "collection": "tokens", "key": "github" }

Both respond {"requestId": "...", "status": "ok"}.

list_batch reads several collections in one round trip. collection is ignored; send collections. Unknown names are skipped.

Request
{ "requestId": "req_batch_abc123", "operation": "list_batch", "collections": ["tokens", "audit"] }
200 OK
{
  "requestId": "req_batch_abc123",
  "results": {
    "tokens": { "items": [ { "key": "github", "meta": { "serviceName": "github" } } ] },
    "audit": { "items": [ { "key": "2026-02-15T10:30:00.123Z-9f2c1a", "data": { } } ] }
  }
}

Activity events (collection audit)

Token Vault writes activity events with set and reads them back with list. Store each event as given and return them newest first by data.timestamp. The key is unique per event (spec 2.9.0): the UTC time to the millisecond plus six hex characters, for example 2026-02-15T10:30:00.123Z-9f2c1a. Treat it as an opaque string and never parse it. Older keys that are a plain one-second timestamp can sit in the same collection. An event looks like this:

{
  "event_type": "AGENT_CREDENTIAL_ACCESS",
  "source": "agent",
  "service_name": "github",
  "agent_id": "agent-abc123",
  "actor": { "type": "agent", "id": "agent-abc123", "name": "ci-bot" },
  "client_ip": "203.0.113.42",
  "zero_knowledge": true,
  "timestamp": "2026-02-15T10:30:00Z"
}

Token Vault forwards most event types (credential access, TOTP code access, credential and agent changes, policy changes, API key events, access changes). It does not forward denials, lock events, bind events, label events or MCP server events. Treat event_type as an open set and the data as opaque. The actor object is {type: user|api_key|agent|session, id, name?}. For API-key callers source is api_key and agent_id is absent.

POST /v1/proxy

Forwards one MCP tool call. The webhook injects the credential and calls the upstream service.

Loading diagram...
Request body
{
  "requestId": "req_proxy_abc123",
  "ticket": "<signed proxy ticket>",
  "service": "github",
  "upstream": {
    "url": "https://api.github.com/mcp",
    "method": "POST",
    "headers": { "Content-Type": "application/json" },
    "body": "<base64-encoded request body>"
  },
  "headerTemplates": { "Authorization": "Bearer ${TOKEN}" }
}
FieldNotes
ticketpur: "proxy". pid is an audit-trail entity id (a legacy proxy's id, or service:server for a credential's MCP server), never checked
serviceService whose credential to use
upstreamurl, method, headers, and body (base64, or null)
headerTemplatesHeader values with ${TOKEN} placeholders

Your webhook must:

  1. Verify the HMAC signature and the proxy ticket.
  2. Read the credential for service.
  3. If the ticket has cid and the stored meta.creationId is missing or differs, answer 409 stale_creation without decrypting or calling upstream. Token Vault reports 403 GRANT_REQUIRED.
  4. Decrypt if you encrypt at rest.
  5. Replace ${TOKEN} in headerTemplates and merge with upstream.headers.
  6. Call upstream.url.
  7. Return the upstream response as a raw HTTP passthrough.

Where the credential may go. Token Vault names upstream.url and the header templates, and your webhook puts the credential into them. Do not rely on Token Vault's checks alone:

  • Do not let your HTTP client follow a redirect. You may follow a 3xx to the same scheme, host and port yourself (a few hops). Return any other 3xx as it is. Never send the merged headers or the body to another origin.

  • upstream.url must be an http or https URL (400 invalid_request).

  • Refuse a private target (spec 2.12.0): an address in a loopback, private, link-local, carrier-grade NAT, multicast or reserved range, localhost, a single-label name, or a name under .local, .internal, .lan or .home.arpa. If your runtime can resolve names, also refuse a name that resolves to such an address. An operator setting may allow private targets (the reference webhook: TV_PROXY_ALLOW_PRIVATE=true).

  • You may keep an operator-set allowlist of origins for each credential (the reference webhook: TV_PROXY_ALLOWED_ORIGINS). With a list set, refuse an origin that is not on it. Nothing in a request may change the list.

  • Never send a Host, Forwarded or X-Forwarded-Host header upstream. Drop one that arrives in upstream.headers, and refuse a header template that sets one (400 invalid_request).

A refusal is 403 upstream_not_allowed, with no upstream call.

The response is not a JSON envelope. Return the upstream status, Content-Type and body unchanged, plus X-Upstream-Status with the upstream's numeric status. Token Vault streams it to the caller. Per-MCP-server calls also forward the MCP session header. Timeout: 30 seconds.

Optionally (spec 2.9.0), add Server-Timing: tv-up;dur=<ms>: the milliseconds from sending the upstream request to the upstream's first response byte (0 to 600000). Token Vault shows it on the Performance page so the user can tell their webhook's time from the upstream's. Token Vault removes every tv-up and tv-wh* entry, so they never reach the caller. Send a number only.

POST /v1/refresh-notify

The webhook refreshes its own OAuth tokens. Your webhook must do this on its own timer, with client credentials it holds locally. Token Vault sends this notice only when someone presses Refresh on a credential (reason: "manual_request"). It carries no credential. Token Vault's hourly sweep does not call it.

Request
{
  "requestId": "req_refresh_abc123",
  "service": "google",
  "reason": "manual_request",
  "refreshHint": {
    "provider": "google",
    "tokenUrl": "https://oauth2.googleapis.com/token",
    "clientId": "your_client_id"
  }
}

refreshHint is sent only when the service name is google, github or spotify. For any other service it is omitted, and your webhook uses the stored meta.oauth hint or its local config.

200 OK
{ "requestId": "req_refresh_abc123", "status": "refreshed", "newExpiresAt": "2026-02-17T16:30:00Z" }
statusMeaning
refreshedRefreshed now. newExpiresAt set
acknowledgedNot a refresh (spec 2.8.0). The webhook has no OAuth client for this provider and did nothing. Token Vault reports "not refreshed" and tells the user to add the provider to OAUTH_PROVIDERS_JSON
no_tokenNo token stored for the service
no_refresh_tokenToken has no refresh token
refresh_failedThe provider returned an error. May carry error and reconnectRequired
errorUnexpected internal error

refresh_failed has two optional, additive fields (spec 2.8.0):

200 OK, refresh failed
{ "requestId": "req_refresh_abc123", "status": "refresh_failed", "error": "invalid_grant", "reconnectRequired": true }
FieldNotes
errorA short reason in plain text, such as invalid_grant or provider_timeout. No secret and no provider response body. Token Vault shows it to the user
reconnectRequiredtrue only when retrying can never work because the provider revoked the grant. Token Vault then stops refreshing that credential, posts an inbox message (and an email, if enabled) and shows Reconnect needed. Omit it or send false for anything transient

Rules:

  • refreshHint has no secret. The clientSecret comes from your webhook's own provider config (reference webhook: the OAUTH_PROVIDERS_JSON secret, {"google":{"clientId":"...","clientSecret":"..."}}).
  • Send the client secret only to a token URL from that config or the built-in table (google, github, spotify). Treat refreshHint.tokenUrl and a stored hint as a cross-check: if it differs from the resolved URL, refuse.
  • A token connected with your own OAuth app stores an oauth hint ({provider, tokenUrl, clientId}) in its meta, so refresh works under any service name. Keep the hint when you rewrite the document.
  • Refresh timeout on the provider call: 10 seconds.
  • Refresh on your own schedule (spec 2.8.0). A token connected with your own OAuth app is refreshed by your webhook on its own timer, and also when a credential or proxy fetch finds it within about 5 minutes of expiry or already expired. Refresh once per service at a time, because a one-shot refresh token cannot be spent twice.
  • Failure markers in the token's meta (spec 2.8.0). When your own refresh fails, write refreshError (short reason, 200 characters at most), refreshFailedAt (ISO 8601) and, if the provider revoked the grant, refreshReconnect: true into the token's plaintext meta. Remove all three on the next success. Storing a new token replaces the document, so a reconnect clears them too. Token Vault reads them from the token list and, for refreshReconnect, raises the reconnect state within the hour. Never put a token, a secret or a provider response body in them.

POST /v1/admin/migrate

Capability ticketConstraints. A one-shot sweep, run when the owner asks (POST /api/vault/webhook/migrate). Any token whose plaintext meta holds a totpUri and no encrypted totpSecret is rewritten: encrypt the secret, add totpIssuer, totpAccountName, totpAlgorithm, totpDigits, totpPeriod, drop totpUri. Never return or log the URI or the secret.

POST /v1/admin/migrate HTTP/1.1
X-TokenVault-Signature: sha256=...
X-TokenVault-Timestamp: 1708300000
X-TokenVault-Request-Id: req_a1b2c3d4e5f6

{}
200 OK
{ "status": "ok", "totp": { "scanned": 12, "migrated": 3, "failed": 0 } }

Only counts come back.

POST /v1/refresh (legacy)

Capability tv-refresh. This is a two-phase flow for tokens that were minted with Token Vault's old OAuth clients. Tokens stored by ticket never use it, and Token Vault's own OAuth connect is turned off. Do not build this for a new webhook. It is the one exception to the rule that no value passes through Token Vault: the refresh token transits Token Vault and is never stored. The reference webhook advertises tv-refresh only when TV_REFRESH_ENABLED=true is set; see Token refresh for how it is used.

{"action":"get","service":"google"} returns {"status":"ok","refreshToken":"...","meta":{...}}, or no_token or no_refresh_token. {"action":"update","service":"google","tokens":{"accessToken":"...","refreshToken":"...","expiryTime":1720007200000}} returns {"status":"updated","newExpiresAt":"..."} or no_token.


Direct access

These endpoints are called by browsers, the CLI and agents. Authentication is a ticket, not HMAC headers. Token Vault is not in the request path.

CORS

Browsers call /v1/credential, /v1/store and /v1/totp-code from the Token Vault origin. Answer OPTIONS preflight with 204 and return Access-Control-Allow-Origin (the Token Vault origin, for example https://tokenvault.uk), Access-Control-Allow-Methods: GET, POST, OPTIONS and Access-Control-Allow-Headers: Content-Type. Return CORS headers only on these endpoints.

GET|POST /v1/credential

Loading diagram...
The redirect from Token Vault
HTTP/1.1 307 Temporary Redirect
Location: https://webhook.example.com/v1/credential?ticket=eyJzdWIi...<elided>.9f2c...<elided>&service=github

HTTP clients drop the Authorization header on a cross-origin redirect, so the agent's key never reaches your webhook. Browsers send a POST:

{ "ticket": "<signed-ticket>", "service": "github" }

Your webhook must:

  1. Read ticket and service from the query (GET) or body (POST).
  2. Verify the ticket signature, exp, and that svc equals service.
  3. Read the token for service.
  4. With ticketConstraints and a ticket cid: answer 409 stale_creation unless meta.creationId equals it, before decrypting.
  5. Decrypt if you encrypt at rest.
  6. For an agent_credential ticket, remove refreshToken (spec 2.10.0). An agent gets the credential and your webhook does the refreshing, so stopping an agent's access also stops any renewals. A user_reveal ticket, a person's own reveal, keeps the field.
  7. Return the credential.
200 OK (agent_credential)
{
  "token": {
    "accessToken": "ghp_...",
    "serviceName": "github",
    "tokenType": "JWT",
    "createdAt": "2026-02-01T10:00:00Z"
  }
}

A TOTP token returns a generated code as accessToken with tokenType: "TOTP", never the secret. Errors: 401 ticket_invalid, 401 ticket_expired, 404 token_not_found, 409 stale_creation.

POST /v1/store

Loading diagram...
POST /v1/store HTTP/1.1
Host: webhook.example.com
Content-Type: application/json

{
  "ticket": "<signed-store-ticket>",
  "service": "github",
  "tokenData": {
    "accessToken": "ghp_...",
    "refreshToken": "ghr_...",
    "tokenType": "JWT",
    "expiresAt": "2026-02-17T15:30:00Z"
  }
}

Your webhook must:

  1. Verify the ticket (pur: "store", signature, exp) and that svc equals service.
  2. With ticketConstraints: if mode is create and the service exists, answer 409 already_exists and store nothing. Another mode value is 400 invalid_request. If cid is present, store it as meta.creationId.
  3. Take the credential fields from tokenData. A totpUri (otpauth://...?secret=...) is sensitive: parse it into totpSecret plus the plaintext descriptors, and never store the URI. A malformed URI is 400.
  4. Encrypt the credential fields if you encrypt at rest. The reference webhook does; your webhook, your choice.
  5. Persist the token document, with plaintext metadata beside the fields. Set meta.createdAt on first store. On a re-store keep createdAt and set meta.updatedAt.
  6. Return metadata, not the credential.
200 OK
{
  "status": "stored",
  "service": "github",
  "meta": { "serviceName": "github", "tokenType": "JWT", "createdAt": "2026-02-15T10:00:00Z" }
}

GET|POST /v1/totp-code

Capability totp. Returns the current code for a stored TOTP secret, never the secret.

GET /v1/totp-code?ticket=<ticket>&service=github HTTP/1.1
200 OK
{ "code": "492071", "remainingSeconds": 17, "period": 30, "digits": 6 }

Accepted ticket purposes: totp_code, agent_credential, user_reveal. Refuse store and proxy, or the endpoint becomes a TOTP oracle. Read the secret from the token, compute the RFC 6238 code with the stored parameters (defaults SHA1, 6 digits, 30 s), and return only the code. Do not log the secret or the code.

ErrorHTTPWhen
invalid_request400ticket or service missing
not_totp400The stored token has no usable totpSecret
ticket_invalid401Signature failed, or purpose not accepted
ticket_expired401exp in the past
setup_required403Webhook has no encryption key or is unconfigured
token_not_found404Nothing stored for the service
stale_creation409Ticket cid does not match meta.creationId
totp_failed500The secret is not valid base32, or generation failed

GET /v1/oauth/start and GET /v1/oauth/callback

Capability oauth-callback. The full contract, including the state ticket, derived PKCE, the cookie and the result codes, is on OAuth callback.


Token document format

Credential fields are plaintext or encrypted. Metadata is always plaintext.

Encrypted (the reference webhook's choice)
{
  "v": 1,
  "alg": "AES-256-GCM",
  "fields": {
    "accessToken": "<base64(12B iv || ciphertext || 16B tag)>",
    "refreshToken": "<base64(12B iv || ciphertext || 16B tag)>"
  },
  "meta": {
    "serviceName": "github",
    "tokenType": "JWT",
    "createdAt": "2026-02-01T10:00:00Z",
    "expiryTime": 1720003600000,
    "hasRefreshToken": true
  }
}

alg is none (fields are plaintext strings) or AES-256-GCM (key 32 bytes, IV 12 random bytes prepended, 16-byte tag appended, no AAD). Token Vault never reads fields.

A TOTP token stores totpSecret in fields and totpAlgorithm, totpDigits, totpPeriod, optional totpIssuer and totpAccountName in meta. A Composite token carries a JSON object in accessToken that only the consumer parses; treat it as opaque.

Operator helpers

Not called by Token Vault. Both are sealed after the first bind unless TV_ADMIN_SECRET is set (see Security).

GET /v1/register-url generates a one-time bind URL for headless setup:

200 OK
{
  "registrationUrl": "https://tokenvault.uk/vault/webhook-bind?code=...&webhook_url=...&hmac_hash=...",
  "code": "550e8400-e29b-41d4-a716-446655440000",
  "expiresIn": 300,
  "webhookUrl": "https://webhook.example.com"
}

GET /bind is an HTML page with a Connect to Token Vault button that generates a one-time code and redirects to the Token Vault frontend. On a sealed webhook it answers 403 forbidden unless the request carries a valid x-tv-admin-secret.

Ready to try it?

Sign in with Google or email. Your credentials stay on your own webhook, and the quickstart gets Claude Code making its first MCP tool call in about 15 minutes.

On this page