Forlabs Vault docs

forlabs-vault (Python)

Python SDK for Forlabs Vault: your agent proposes a spending mandate, the user signs it once with a passkey, and the vault enforces it on every charge and keeps a tamper-evident record.

Included:

receipts.verify and evidence.verify run the same code as the offline verifier (vault_core and verifier ship inside the wheel). They are not a reimplementation.

Requires Python 3.12 or later.

Install

pip install forlabs-vault
# from this repo (gate 0): build a wheel, then install it
cd sdk/python && uv build --wheel && pip install dist/forlabs_vault-*.whl

Sandbox quickstart

The public sandbox needs no PG account and no card. Sandbox tenants may send user={"sub": ...} instead of a signed user token, and they get a test card automatically.

from datetime import date, timedelta
from forlabs_vault import Vault, PolicyError, evidence, krw, receipts

keys = Vault.sandbox.create_key()            # POST /v1/sandbox/keys, no auth
vault = Vault(keys["api_key"])               # base_url defaults to the sandbox

m = vault.mandates.create(
    user={"sub": "me"},                      # sandbox only; production sends user_token=
    limits={"total": krw(300_000), "per_charge": krw(50_000),
            "approval_threshold": krw(30_000)},
    merchants=[("coupang", "쿠팡")],
    valid_until=date.today() + timedelta(days=30),
)
print("Open and sign with a passkey:", m["sign_url"])
input("Press Enter after signing… ")
assert vault.mandates.get(m["id"])["status"] == "active"

charge = vault.charges.create(
    mandate_id=m["id"], amount=krw(12_000), merchant_id="coupang",
    description="생수 2L × 24", idempotency_key="order-1042",
)
print(charge["status"])                      # "succeeded"

jwks = vault.receipt_keys()                  # pin this: see "Pinning" below
receipts.verify(charge["receipt"], jwks)     # keep charge["receipt"]: it is your witness

bundle = vault.mandates.evidence(m["id"])
report = evidence.verify(bundle, receipt_jwks=jwks,
                         origin="https://sandbox.vault.forlabs.io",
                         rp_id="sandbox.vault.forlabs.io",
                         customer_receipts=[charge["receipt"]])
for c in report.checks:
    print(c.status, c.name, c.detail)
assert report.ok

The async client works the same way, with await on every call:

async with AsyncVault(api_key) as vault:
    m = await vault.mandates.create(...)

Production: user tokens

Outside the sandbox, your backend signs a short-lived token for each user. The token is an EdDSA JWT with iss set to your tenant id and aud set to forlabs-vault. Its lifetime can be at most 600 seconds. Register the public key with us once.

from forlabs_vault import users

private_pem, public_pem = users.generate_keypair()   # send public_pem to Forlabs
token = users.sign_token(private_pem, tenant_id, sub="user-8812", email="a@example.com")

inst = vault.instruments.create(user_token=token, rail="toss",
                                auth_key=auth_key, customer_key=customer_key)
m = vault.mandates.create(user_token=token, instrument_id=inst["id"], limits=..., ...)

sub must be your stable user id and must never be reassigned, because the user's passkey is bound to it. sign_token raises ValueError if ttl is greater than 600 seconds, so the mistake shows up in your code and not as an API error.

Idempotency keys are required

charges.create requires idempotency_key and never generates one for you. A request can time out after the vault has already charged the card. The vault can tell a retry from a new purchase only when the retry sends the same key. A key generated inside the SDK would change on every attempt.

To get this right, derive the key from your own order id, store it before calling, and reuse it on every retry:

Errors

Every API error is a VaultError with the full error envelope as attributes: status, type, code, message, param, doc_url, request_id, next_action. Messages follow accept_language ("ko" by default, or "en").

Exception When
AuthenticationError 401: missing or invalid API key
InvalidRequestError 400: bad input, invalid user token, mandate over the tenant cap
PolicyError 402: the mandate denied the charge
NotFoundError 404
IdempotencyError 409: key reused with a different request
RateLimitError 429
APIError anything else, including 5xx
APIConnectionError no response; retry with the same idempotency key
try:
    vault.charges.create(mandate_id=mid, amount=krw(60_000), merchant_id="coupang",
                         description="TV", idempotency_key="order-1043")
except PolicyError as e:
    print(e.code)              # "per_charge_limit_exceeded"
    print(e.next_action)       # "request_new_mandate" | "request_approval" | "none"
    receipt = e.charge["receipt"]  # denials are recorded and signed too

Webhooks

Each webhook delivery carries this header:

Forlabs-Vault-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, f"{t}." + body)>

During secret rotation the header holds several v1= entries. One match is enough. Always verify the raw request body, never JSON you parsed and serialized again.

from fastapi import FastAPI, HTTPException, Request
from forlabs_vault import SignatureVerificationError, webhooks

app = FastAPI()

@app.post("/vault/webhook")
async def vault_webhook(request: Request):
    try:
        event = webhooks.verify(
            await request.body(),
            request.headers.get("Forlabs-Vault-Signature", ""),
            secret=WEBHOOK_SECRET,          # tolerance defaults to 300 s
        )
    except SignatureVerificationError:
        raise HTTPException(status_code=400)
    # Deliveries may repeat: dedupe on event["id"].
    handle(event)
    return {"ok": True}

webhooks.sign(payload, secret, t) builds a valid header for your own tests.

Pinning: receipts and evidence

Verification proves something only if you supply the trust inputs:

evidence.verify returns a Report (report.ok, report.checks, report.charges). evidence.verify_or_raise raises EvidenceVerificationError instead, with the report attached. A WARN check (for example "no time anchor") does not fail the verification.

API surface

SDK HTTP
Vault.sandbox.create_key() POST /v1/sandbox/keys
instruments.create(user_token, rail, …) POST /v1/instruments
mandates.create(…) / .get(id) / .evidence(id) POST /v1/mandates, GET /v1/mandates/{id}, GET /v1/mandates/{id}/evidence
charges.create(…, idempotency_key) / .get(id) POST /v1/charges, GET /v1/charges/{id}
receipt_keys() GET /v1/receipt-keys
reconcile.charges() / .ledger(start, end) POST /v1/reconcile/charges, POST /v1/reconcile/ledger

Amounts are {"amount_minor", "currency", "exponent"} dicts with integer fields, or any object with those attributes. Use krw(12_000) for won.