All docsEnterprise access controlsSpec (Markdown)TOKENLOCK

Self-verify

Run “Sign in with your Token” entirely on your server. You issue the challenge, keep the nonce, verify the sign-in and read holdings from a source you choose. We do the Token check only if you ask us to.

Checked on your server

No call to our API for the check itself. If two holdings sources disagree, access fails closed.

Local01

The check stays on your server

Self-verify

You verify the pass locally. For registered keys, your server evaluates a signed policy bundle it has cached. We do not host your pages.

Self-verify guide →
Fail closed02

Disagree, and access stops

Two sources

Two holdings sources can be required to agree. If they disagree, or a source fails, the check fails closed.

Holdings providers →

Preview. Spec v1, SDK @tokenlock/sdk 0.5.3 (self-verify since 0.3.0) and PHP drop-in 0.4.4 (0.4.4 enforces every policy's validity window wherever it is used, validates evaluate() input before any mode branch and checks the pass secret on verify; 0.4.2 rejects malformed policies with policy_invalid and non-boolean holdings answers; 0.4.3 refuses malformed resource values and unknown options with bad_resource and needs identityOnly: true / 'identity_only' => true for identity-only checks). See security advisory 2026-11-18. Enterprise. A pass proves a signed claim and a holding at sign-in time, not legal ownership.

Quick start

Node

import { createChallenge, verifySignIn, verifyLocalPass, fileNonceStore, tokenscanProvider } from '@tokenlock/sdk/self-verify';

const store = fileNonceStore('/var/lib/tokenlock-nonces');
const cfg = { store, holdings: tokenscanProvider(), passSecret: process.env.MY_PASS_SECRET };

// 1. challenge: show c.message to the wallet (XCP Wallet, Horizon, Unisat, Xverse or Leather)
const c = await createChallenge({ site: 'https://shop.example', assets: ['CLUBTOKEN'], store });
// 2. sign-in: the wallet's signature comes back with the challenge id
const r = await verifySignIn({ challenge_id, address, signature }, cfg);   // r.valid, r.pass, r.code
// 3. every request
const v = await verifyLocalPass(pass, { passSecret: process.env.MY_PASS_SECRET, identityOnly: true }); // identity only (explicit since 0.4.3)

PHP

require __DIR__ . '/tokenlock/self-verify.php';   // needs the GMP extension

$store = tokenlock_sv_file_store('/var/lib/tokenlock-nonces');
$c = tokenlock_sv_create_challenge(array('site' => 'https://shop.example', 'assets' => array('CLUBTOKEN'), 'store' => $store));
$r = tokenlock_sv_verify_sign_in($_POST, array('store' => $store, 'holdings' => tokenlock_sv_tokenscan_provider(), 'pass_secret' => getenv('MY_PASS_SECRET')));
$v = tokenlock_sv_verify_local_pass($pass, array('pass_secret' => getenv('MY_PASS_SECRET'), 'identity_only' => true));

Registered keys, offline

import { signedPolicy } from '@tokenlock/sdk/self-verify';
const policy = signedPolicy({ siteId: 'site_…', secretKey: process.env.TOKENLOCK_SECRET_KEY,
  publicKeys: { '<kid>': '<x-only key from /.well-known/tokenlock-policy-keys.json>' }, refreshSeconds: 60, ttlSeconds: 600 });
// refreshSeconds: pull a fresh bundle every 60 s. A failed load backs off 5 s, 10 s, 20 s … (max 60 s); calls in between don't hit the network.
const v = await verifyLocalPass(pass, { passSecret, policy, resource: { path: req.path, method: req.method, environment: 'production' } });
// v.valid false → 401, v.valid true + v.allowed false → 403
// A resource needs a registered-keys policy: without one, or with a token-mode policy, the answer is
// { valid: false, allowed: false, code: 'policy_required', identity_valid } (SDK 0.4.0+, PHP 0.4.0+).

Self-verify lets your server run "Sign in with your Token" from start to finish. You issue the challenge and keep the nonce. You check the wallet signature locally, and you read holdings from a source you pick. For the sign-in itself, nothing has to call our API. Our API is only involved if you choose our holdings provider or pull a signed policy bundle for registered keys.

A pass proves a wallet signed a claim and held a token at sign-in time. It does not prove legal ownership of anything.

1. Modes and what you still trust

Mode Who checks the signature Who reads holdings Who decides access (keys, revocation) What you trust us for
Hosted (default) our API our API our API, live on every verify signature check, holdings, policy, uptime
Self-verify + our holdings your server our /holdings endpoint your policy, or our signed bundle the holdings reading only (plus the bundle, if used)
Self-verify + tokenscan / your node your server tokenscan.io, your node, or any HTTP JSON source your policy, or our signed bundle nothing, or the bundle signer (if used)
Self-verify + localPolicy + your node your server your node/indexer you No TOKENLOCK-hosted verification or external holdings provider required. You still depend on your own software and node infrastructure.

Whatever mode you use, you also trust: - The holdings source you pick. A wrong balance means a wrong decision. requireAgreement([a, b]) asks two independent sources and fails closed if they disagree. - Your nonce store. Replay protection is yours (§3). - Your pass secret. Anyone holding it can mint passes (§6). - The code: this SDK (MIT) and the noble cryptography libraries bundled in it (Node), or the GMP-based verifier (PHP). Both are tested against the same 396 signature vectors, whose expected answers come from the hosted check.

2. Challenge message

Sign in with your Token
Site: <origin>
Requires: <ASSET1 or ASSET2 …>[ or any name on Bitcoin]
Via: self-verify
Nonce: <32 lowercase hex>
Issued: <ISO-8601 UTC, milliseconds>
Expires: <ISO-8601 UTC, milliseconds>
Signing proves you control this address. It moves no funds.

Lines are joined with \n and there is no trailing newline. Site is the origin only: scheme, host and a port only if it is non-default. Via: self-verify keeps a self-verify signature from being replayed against the hosted check, and the other way round. Lifetime is 60 s to 30 min (default 10 min).

Accepted signatures are the same as the hosted check: - BIP-322 "simple" (a base64 witness) for P2WPKH (bc1q…), P2SH-P2WPKH (3…) and single-key P2TR (bc1p…). - Legacy "Bitcoin Signed Message" (BIP-137 / Electrum, 65 bytes) for P2PKH (1…), P2SH-P2WPKH, P2WPKH and P2TR (BIP-86 tweak of the recovered key). The address-type flag in the header byte is ignored, like the hosted check.

Wallets tested: XCP Wallet, Horizon, Unisat, Xverse and Leather. Testnet and signet addresses (tb1…, m/n/2…) are also accepted.

3. Nonce store (replay)

A store has put(nonce, record, expiresAtMs) and take(nonce). take must be atomic fetch-and-delete, and must return null when the nonce is unknown or already taken. The nonce is taken before anything else is checked, so a failed attempt still uses it up.

Built in: memoryNonceStore (one process only), fileNonceStore(dir) (atomic rename; safe for servers that share a folder), and redisNonceStore(client) (SET NX PX + GETDEL). PHP has tokenlock_sv_file_store, tokenlock_sv_redis_store and tokenlock_sv_memory_store. If you run more than one server, use a shared store.

4. Holdings providers

A provider is holdings(address, assets) → { [asset]: { held, how?, quantity?, exists? } }. It throws on any error, and a throw is always read as "deny" (lookup_failed).

5. Policy bundles (registered keys)

You need this only if you use registered keys: per-wallet permissions, orgs and revocation.

bundle  = { v:1, typ:"tokenlock.policy-bundle", alg:"BIP340", kid, payload, sig }
payload = base64url(JSON policy)          sig = hex(BIP-340 Schnorr over taggedHash("TOKENLOCK/policy/v1", payload bytes))
policy  = { v:1, typ:"tokenlock.policy", site_id, seq, state_version, issued_at, expires_at, mode, assets, any_name,
            origins, settings, orgs:[{id,status}], revoked_assets, keys:[{id,address,status,owner_type,org_id,assets,
            permissions:{routes,methods,environments}, expires_at, pass_ttl_s}] }

Revocation freshness

A revocation reaches your server on its next successful refresh.

Setting Default Effect
refreshSeconds (refresh_seconds) 60 How often a fresh bundle is pulled. This is the normal worst case for key revocation and permission changes.
retryMinSeconds / retryMaxSeconds 5 / refreshSeconds After a failed load, the next attempt waits 5 s, then 10 s, 20 s … up to the max. Calls in between don't hit the network; concurrent calls share one in-flight load. A success resets the backoff (SDK 0.3.3+).
bundle ttl 600 s (60–3600) If refreshes fail, the cached bundle is used until it expires. This is the worst case during an outage.
after expiry — Every sign-in and pass check fails closed (policy_expired) until a refresh works.

Holdings changes are a separate clock. Holdings are read at sign-in, and verifyLocalPass does not re-read them, so an existing pass keeps working after a token transfer until it expires (pass_ttl_s, default 900 s). The bundle carries key status, not live holdings, and the hosted recheck_holdings_s re-check does not apply to self-verify.

The hosted mode checks revocation on every verify. Self-verify trades that for not depending on us; choose ttl to match how quickly a revoked key must stop working.

6. Local passes

tl3.<base64url(JSON {v,sub,h,k,n,s,i,e})>.<base64url(HMAC-SHA256(passSecret, "tl3." + body))>

The pass secret is yours: at least 32 characters, and never sent to us. A pass is a bearer token, so send it over HTTPS in an HttpOnly cookie or an Authorization header. Lifetime is the challenge's pass_ttl_s (default 900 s), capped by the key's pass_ttl_s and the agent/default TTLs in the policy, and by the key's expires_at. verifyLocalPass(token, { passSecret, policy?, resource | identityOnly: true }) gives one of these results (0.4.3: exactly one of resource or identityOnly: true): - valid:false, code:"bad_secret": passSecret missing or shorter than 32 characters (0.4.4). - valid:false, code:"bad_resource": unknown option, no resource and no identityOnly, or a malformed resource (unknown field, path without method, empty/whitespace/padded/null/non-string value). Never treated as identity-only. bad_path for a relative or non-canonical path (always valid:false: the pass was not checked; 0.4.3 answered valid:true here). - valid:false: forged, expired, revoked, or the policy is unavailable, expired or not yet valid. Answer 401. - valid:false, allowed:false, code:"policy_required": a resource was given without a policy, or with a token-mode policy (no route rules). This is a configuration error (answer 500, or 403 in middleware, and fix the config): route, method and environment rules live in a registered-keys policy. identity_valid is true when the pass itself is authentic and unexpired. For an identity-only check pass identityOnly: true (no resource), which needs no policy. (No policy: Node SDK 0.3.3+, PHP 0.4.0+. Token-mode policy: Node SDK 0.4.0+, PHP 0.4.0+. Earlier versions answered allowed: true; see advisory 2026-11-18.) - valid:true, allowed:false: authentic but outside this route, method or environment (route_not_allowed, …). Answer 403. - valid:true, allowed:true: allow.

In registered_keys mode a pass is bound to its key id, so re-registering the same address under a new key does not bring an old pass back to life. Passes are the same in Node and PHP: one side can verify what the other issued.

7. Paths

Resources use TOKENLOCK path rules v1.1, the same as the hosted API and every adapter: - ? and # are stripped. - These are rejected: backslash, control bytes, any ;, %2f, %5c, %00, %25, %2e and %3b. - The path is decoded once and empty segments are dropped. Any . or .. segment is rejected (not resolved). - Matching ignores case; the resource is compared in lowercase.

The shared test vectors are in test/fixtures/path-vectors.json.

8. Fail closed

Every one of these means deny: an unknown or reused nonce, an expired challenge, a bad signature, an unsupported address, any holdings error or disagreement, a policy that is unavailable or expired, a bad bundle signature, an unknown kid, the wrong site, a rollback, a bad path, a bad pass, or a resource check with no policy configured. No option turns any of these into "allow".

9. Test vectors