API Tokens

Version 0.3.0 · Owners: @benallfree

Walkthrough for app owners: API tokens. This page is the technical reference.

Long-lived API tokens for your app: secrets that start with pbt_, for CI, deploys, scripts and agents. Each token belongs to an account and acts as that account. It can be limited to scopes, given an expiry, and revoked on its own. Send one as Authorization: Bearer pbt_…. Ordinary PocketBase auth tokens keep working unchanged.

Install · Configure · Use · Integrations · Example

Install

Tokens is built into pocketone and always on. There's nothing to install or turn on.

In your own Go build, register it before the app starts:

app := pocketbase.New()
tokens.MustRegister(app, apitokens.Config{})
app.Start()

To use $apiTokens in pb_hooks, bind it in jsvm's OnInit (the stock binary does):

jsvm.MustRegister(app, jsvm.Config{OnInit: func(rt js.Runtime) { tokens.BindJS(app, rt) }})

The module is pocketone.dev/ext/api-tokens.

Configure

There is no pocketone.yaml section, flag or environment variable for Tokens. In pocketone:

  • any account (a superuser, or a record of any auth collection) can own tokens;
  • a token never expires unless you give it an expiry.

A Go build can narrow both (see Go config).

Scopes

A token without scopes has its owner's full rights. A token with scopes works only on the requests its scopes cover, plus remote/v1's whoami (/api/_c/remote/v1); anywhere else it gets 403. Extensions, contracts and your own pb_hooks register the scopes. In pocketone they are:

Scope From Allows Who can hold it
deploy Deploy Deploy code (hooks, migrations, pages, public files, packages), read files and logs superusers
deploy:read Deploy Read deployed files and stream logs superusers
<name>, <name>:read each contract the app provides That contract's operations under /api/_c/<id>/: remote and remote:read, restore and restore:read, settings and settings:read, bulkmail:read, cache, ... per contract

Contract scopes are registered when the app serves, so Settings → API tokens on the running app lists every scope. The pocketone token command works offline and doesn't see them: token scopes lists only deploy and deploy:read, and token create --scope restore fails with unknown scope "restore". Create a token with a contract scope from the dashboard or the REST API.

Your own scopes

Declare a scope at the top level of a pb_hooks file. It then shows up in Settings → API tokens and on the OAuth server's consent page:

// pb_hooks/scopes.pb.js
$apiTokens.registerScope({
  name: 'notes:read',                        // lower-case letters, digits, ":" and "_"
  description: 'Read notes',                 // shown in the token screen and on the consent page
  paths: ['/api/collections/notes/records'], // URL prefixes where a token holding it works
  methods: ['GET'],                          // optional: only these methods (GET covers HEAD)
})
$apiTokens.registerScope({ name: 'notes:write', description: 'Change notes', paths: ['/api/collections/notes/records'] })
  • collections: ['users'] limits which accounts may hold the scope.
  • Registering a name again merges its paths, methods and collections, so reloading hooks is safe.
  • Two names whose headers would be the same (notes:write and notes_write) can't both be registered.

Check a scope on your own route:

routerAdd('POST', '/api/notes/archive', (e) => { /* ... */ }, $apis.requireAuth(), $apiTokens.requireScope('notes:write'))

$apiTokens.requireScope refuses a signed-out request, and a token that doesn't hold the scope. Inside a handler, $apiTokens.hasScope(e, 'notes:write') tells you the same.

Check a scope in a collection API rule. Every signed-in request carries X-Token-Scope-<Name>: 1 for each scope it holds, and rules read it as @request.headers.x_token_scope_<name> (: becomes _):

@request.auth.id = owner && @request.headers.x_token_scope_notes_write = "1"
  • A PocketBase auth token or an unscoped API token holds every registered scope (except ones its collection can't hold).
  • A scoped token holds only its own scopes. A signed-out request holds none.
  • Headers a client sends with that prefix are always dropped, so they can't be forged.

$apiTokens.ruleField('notes:write') returns the rule field for a name, and $apiTokens.scopes() lists every registered scope with its header and rule field.

Scopes with values

A scope can let a token hold it for some values only, such as some record ids. The token's scope list then says name=value, once per value (notes=abc123, notes=def456). The bare name still means every value. Declare the values when you register the scope:

$apiTokens.registerScope({
  name: 'notes',
  description: 'Your notes',
  paths: ['/api/notes/'],
  values: { description: 'a note id' }, // shown in the token screen
})

Paths and methods don't look at values: a token holding notes=abc123 authenticates on every path notes covers. Your route checks the value:

routerAdd('GET', '/api/notes/{id}', (e) => {
  if (!$apiTokens.hasScope(e, 'notes', e.request.pathValue('id'))) throw new ForbiddenError('Not this note.')
  // ...
}, $apis.requireAuth())
  • $apiTokens.hasScope(e, name, value) is true for the bare scope, for name=value, and for a PocketBase auth token or an unscoped token. Without a value it's true when the request holds the scope for any value.
  • $apiTokens.scopeValues(e, name) returns { all: true } for every value, or { all: false, values: [...] }.
  • The scope's header carries the values instead of 1 (X-Token-Scope-Notes: abc123,def456), so a rule's = "1" still means every value.
  • A value is 1–200 letters, digits and . _ : @ / + -. A scope registered without values refuses name=value.
  • In Go, Values: &apitokens.ScopeValues{Description: "...", Check: func(owner, value) error} adds a check when a token is created (for example, that the owner owns that record).

Use

From the dashboard

  1. Open Settings → API tokens (under Access). Only superusers see this screen.
  2. Fill in a Name. Optionally set Expires in (days), and tick any Scopes (none means full rights). A scope that takes values shows a box when ticked: leave it empty for every value, or list some, comma-separated.
  3. By default the token is yours. To make one for another account, fill in Owner collection (default _superusers) and Owner (id or email).
  4. Click Create token. Copy the token now: it's shown only once and never stored.

The list shows each token's name, its first characters, owner, scopes, expiry and when it was last used (time and IP). Tokens issued by the OAuth server carry an oauth: <client id> label. Click Revoke and confirm to delete one; anything using it stops working at once.

App users who aren't superusers manage their own tokens through the REST API.

From the command line

The token command works on the local data dir, like superuser, so you can set up tokens before the first serve:

pocketone token create --superuser [email protected] --name ci --scope deploy --ttl 720h   # prints the secret
pocketone token create --collection users --record [email protected] --name script
pocketone token list                                    # every token, or one owner's with an owner flag
pocketone token revoke <id> [<id>...]
pocketone token revoke --all --superuser [email protected]
pocketone token scopes

Pick the owner with --superuser <email>, or --collection <name> --record <id or email>. --scope can be repeated, and takes name=value for a scope with values; without --ttl the token never expires.

Using a token

curl -H "Authorization: Bearer pbt_…" https://myapp.example.com/api/collections/notes/records
  • An invalid, revoked or expired token leaves the request signed out, like an invalid PocketBase token.
  • A scoped token used outside its scopes gets 403 ("This API token's scopes (…) don't allow this request.").
  • A token can't be exchanged for a PocketBase auth token (auth-refresh and impersonate refuse it), so revoking a token really ends its access.
  • Expired tokens are deleted once a day. Deleting an account deletes its tokens.

In the logs

  • A rejected token is logged at debug level: tokens: rejected API token.
  • The daily cleanup logs tokens: deleted expired tokens with a count when it deletes any, and tokens: delete expired as a warning if it fails.

Commands and APIs

Generated from the pocketone binary and the contracts this extension provides.

Commands

What it adds to the pocketone binary (CLI reference):

Command
pocketone oauth clients add Registers a client (prints its id, and its secret once for a confidential client)
pocketone oauth clients list Lists registered clients
pocketone oauth clients rm <client_id> Removes a client
pocketone token create Creates an API token and prints its secret (shown once)
pocketone token list Lists API tokens (all, or one owner's)
pocketone token revoke [id...] Revokes API tokens by id, or all of one owner's (--all)
pocketone token scopes Lists the scopes extensions registered

api-tokens.verify/v1

Operation CLI REST MCP
verify pocketone remote api-tokens verify --token <value> --ip <value> POST /api/_c/api-tokens.verify/v1 api-tokens_verify_verify

api-tokens/v1

Its HTTP API under /api/_c/api-tokens/v1/, as the contract describes.

oauth/v1

Its HTTP API under /api/_c/oauth/v1/, as the contract describes.

JavaScript API

What it adds to pb_hooks and page code: API Tokens JavaScript API.

Integrations

Works with

Extension How they fit
OAuth (in Tokens) Its access tokens are API tokens, issued with the client's id, the granted scopes and, when asked for, an audience. They show up under Settings → API tokens and can be revoked there. The OAuth server needs Tokens on the app.
MCP An agent's OAuth sign-in to /mcp is an API token bound to /mcp that never expires; revoke it to disconnect the agent. Tool calls run as the token's owner. A full-access token's calls hold every registered scope; a token limited to scopes on the consent page has its calls checked like requests with those scopes (WithScopes).
Deploy Registers deploy and deploy:read; a deploy token is what CI uses.
Remotes pocketone login takes a pasted API token when the remote has no OAuth server. In CI, put a token in P1_TOKEN. remote/v1's whoami (/api/_c/remote/v1) reports a token's id and scopes, whatever its scopes.
Multisite It's a standard member, so every instance gets its own tokens, routes and screen; reconfigure it on the host's set with set.APITokens = apitokens.New(apitokens.Config{...}). With Pocker, per instance, extensions: {api-tokens: {enabled: false}} turns it off and collections: [...] picks who may own tokens.

Building on Tokens

Register a scope from Go. Extensions register their scopes on the app, usually on bootstrap, and guard their routes:

tk := tokens.For(app)
tk.MustRegisterScope(tokens.Scope{
    Name:        "notes:write",
    Description: "Change notes",
    Paths:       []string{"/api/collections/notes/records"},
    Methods:     []string{"POST", "PATCH", "DELETE"}, // optional
    Collections: []string{"users"},                   // optional: who may hold it
})
se.Router.POST("/api/notes/archive", h).Bind(apis.RequireAuth(), tokens.RequireScope("notes:write"))
  • Guards. A Go scope can add Match func(*core.RequestEvent) bool: a token with the scope also works on any request it returns true for. It runs before the owner is loaded, so it may look only at the request.
  • Shared scopes. Registering a name again merges its paths, methods, guards and collections, so several extensions can share one scope.
  • Scope values. Values: &tokens.ScopeValues{Description, Check} lets a token hold a scope for some values only (notes=abc123). Check(owner, value) runs when a token is created; an error refuses it. Routes check the value with tokens.HasScopeFor(e, "notes", id), or list them with tokens.ValuesFor(e, "notes") (all is true for every value). Through the contract: grant.HasScopeFor, grant.ScopeValues, and apitokensv1.SplitScope / JoinScope for the name=value form.
  • Read the token on a request. tokens.FromRequest(e) returns the token a request used (nil for a PocketBase auth token), with its Owner, Scopes and Audience. tokens.HasScope(e, "x") is true for PocketBase auth tokens and unscoped API tokens.
  • Without importing this package. Other extensions use the api-tokens/v1 contract instead: tokensv1.Contract.Of(app) registers scopes (RegisterScope), lists them and checks Reaches; tokensv1.FromRequest(e) is the request's token (its Grant: owner, scopes, audience, client id); tokensv1.WithScopes limits in-process requests. Deploy and MCP work this way. The X-Token-Scope-* headers work for rules and JS.
  • Audience. A token created with CreateOptions.Audience (the OAuth server sets it from the RFC 8707 resource parameter) only works under that URL's path, plus remote/v1's whoami (/api/_c/remote/v1); elsewhere it gets 403. When the audience has a path (like https://host/mcp), the token works there whatever its scopes: the scopes limit what that endpoint does on the token's behalf (MCP passes them on with WithScopes), not the endpoint itself.
  • Limit in-process requests. tokens.WithScopes(ctx, scopes) returns a context whose requests are checked like a token limited to scopes, whatever credential they carry: 403 where the scopes don't reach, and only those scopes in the X-Token-Scope-* headers and HasScope. Requests made inside them with the same context inherit the limit, and a nested WithScopes only narrows it. No client value can set it. tokens.ScopesFromContext(ctx) reads it. Reaches(scopes, method, pattern) says whether scopes could cover a route pattern ({name} segments match anything), and Scope.Infrastructure() whether a scope only reaches contract APIs (/api/_c/).

Go API. tokens.For(app) returns the service: Create(owner, CreateOptions{Name, Scopes, Expires, ClientId, Audience}) returns the secret and record; also Verify(secret), List(owner), Get(id), Revoke(id), RevokeAll(owner), DeleteExpired(), RegisterScope, MustRegisterScope, Scopes(), Collections() and AllowedCollection(c). tokens.BindJS(vm, app) adds $apiTokens; the extkit extension (tokens.New) also binds it.

JS. $apiTokens.registerScope({name, description, paths, methods, collections}), $apiTokens.requireScope(name), $apiTokens.hasScope(e, name), $apiTokens.ruleField(name) and $apiTokens.scopes().

REST API (api-tokens/v1)

The api-tokens/v1 contract, at /api/_c/api-tokens/v1. Any signed-in account; superusers see and manage everyone's.

Route What
GET /api/_c/api-tokens/v1 Your tokens. Superusers see all, or one owner's with ?ownerCollection=&owner=.
POST /api/_c/api-tokens/v1 {name, scopes, ttl | expires} (ttl in seconds, expires RFC 3339); superusers may add ownerCollection and owner. Returns the secret once. A scoped token can only create tokens within its own scopes.
DELETE /api/_c/api-tokens/v1/{id} Revoke one.
POST /api/_c/api-tokens/v1/revoke-all Revoke all of yours (superusers: {ownerCollection, owner}).
GET /api/_c/api-tokens/v1/scopes The registered scopes, who may own tokens, and whether you can.

Owners can also list, view and delete their own tokens through the records API of _api_tokens_tokens.

Checking a token from another server (api-tokens.verify/v1)

A server that a client hands one of this app's tokens to (a host in front of the app's accounts) asks the app what the token allows with the api-tokens.verify/v1 contract: POST /api/_c/api-tokens.verify/v1 with {"token": "pbt_...", "ip": "<client address>"}, as a superuser (scope api_tokens_verify). The answer is {"valid": true, "grant": {...}} with the owner and the scopes (values included), or {"valid": false, "reason": "invalid" | "expired"}. In Go, verifyv1.NewClient(appURL, superuserToken, nil).

Example

example/main.go runs one app with API tokens: Settings → API tokens, the token API (/api/_c/api-tokens/v1) and the token command.

// Command example runs one PocketOne app with API tokens: Settings → API tokens in the dashboard, the token API (/api/_c/api-tokens/v1)
// and the `token` command.
//
//	go run ./example serve
//	go run ./example token create --superuser [email protected] --name ci
//	curl -H "Authorization: Bearer pbt_..." http://127.0.0.1:8090/api/collections
//
// Logins (ext/devusers, local testing only): dashboard [email protected] / password, app user [email protected] / password.
package main

import (
	"log"
	"net/http"

	"ganigeorgiev.com/pocketbase/pocketbase"
	"ganigeorgiev.com/pocketbase/pocketbase/apis"
	"ganigeorgiev.com/pocketbase/pocketbase/core"
	"pocketone.dev/ext/api-tokens"
	"pocketone.dev/ext/devusers"
)

func main() {
	app := pocketbase.New()
	devusers.Register(app) // local testing: superuser [email protected] and user [email protected], password "password"

	tk := apitokens.MustRegister(app, apitokens.Config{
		Collections: []string{"_superusers", "users"}, // who may own tokens
	})
	// an extension's scope: a token limited to "hello" only authenticates under /api/hello; a JWT or unscoped token
	// holds it too, and every request that holds it carries X-Token-Scope-Hello: 1 for rules and hooks
	tk.MustRegisterScope(apitokens.Scope{Name: "hello", Description: "Say hello", Paths: []string{"/api/hello"}, Methods: []string{"GET"}})

	app.OnServe().BindFunc(func(se *core.ServeEvent) error {
		se.Router.GET("/api/hello", func(e *core.RequestEvent) error {
			return e.JSON(http.StatusOK, map[string]any{"hello": e.Auth.Email()})
		}).Bind(apis.RequireAuth(), apitokens.RequireScope("hello"))
		return se.Next()
	})

	if err := app.Start(); err != nil {
		log.Fatal(err)
	}
}

Go config

tokens.MustRegister(app, apitokens.Config{
    Collections: []string{"_superusers", "users"}, // who may own tokens (default: every auth collection)
    MaxTTL:      0,                                // cap on a token's lifetime (0: none)
})

With MaxTTL set, a token asked for with no expiry or a later one gets the cap instead. If you narrow Collections, The OAuth server can only sign in accounts of those collections.

Bringing tokens from another system

To keep tokens another system issued working (their owners already hold the secrets), register their prefix and store each one with Import, which keeps only its hash, as Create does:

tk.RegisterPrefix("ph_pat_") // pbt_ is always registered
rec, err := tk.Import(owner, "ph_pat_…", apitokens.CreateOptions{Name: "ci", Scopes: []string{"deploy"}})

Every registered prefix is checked the same way: a secret starts with one and has at least 32 characters after it. Import takes a pbt_ secret too (a token moving from another app). The one difference: tokens the app creates always start with pbt_. A prefix is lower-case letters, digits and _, ends with _, and can't overlap one already registered. The old system's hash is usually of something else, so import a secret when it's next used (check it the old way, then Import it), not ahead of time.

How it works

  • Tokens live in the _api_tokens_tokens collection: owner (collection id and record id), name, hash (SHA-256 of the secret; the secret itself is never stored), display prefix, scopes, expiry, last use (time and IP), OAuth client id and audience.
  • The bearer check is a middleware that runs just before PocketBase's own auth middleware; a second one, right after it, sets the scope headers. Last use is written at most once a minute per token.
  • example/main.go runs one app where superusers and users may own tokens, with a hello scope for GET /api/hello. Try it with go run ./example serve and go run ./example token create --superuser [email protected] --name ci (logins from devusers: [email protected] / password, [email protected] / password).

License

MIT