Skip to content
GitHub

Strutvane 0.2 is still being built. These pages describe how it will work; anything marked "Coming in 0.2" doesn't exist yet. Release notes and support policy.

API Tokens

View as Markdownllms.txt

Your React UI signs in with a cookie session. But a nightly script, a mobile app or a partner’s server has no browser. For them, a user creates a personal access token: a long secret string they paste into the other program, which sends it with every request. The token acts as that user, limited to the abilities (permissions) chosen when it was made, until it expires or is revoked (switched off).

In Strutvane, tokens are the apiTokens feature in config/auth.ts. The installer turns it on by default (question 9, “API access for other apps”: personal access tokens).

  1. Create a token while signed in (the settings screen will do this; here with curl):

    Terminal window
    curl -X POST http://localhost:3000/user/api-tokens \
    -H "Content-Type: application/json" \
    -H "Origin: http://localhost:3000" \
    -H "Cookie: strutvane_session=<your session>" \
    -d '{"name":"Nightly export"}'

    What you’ll see:

    {
    "plainText": "svp_3fKq9ZbX0aLmN2pQrS7tUvWx4yZ1Ab2Cd3Ef5Gh6Ij7k9QxA1b",
    "token": {
    "id": "0193a1d4-2b7e-7f10-8c3d-1e2f3a4b5c6d",
    "name": "Nightly export",
    "abilities": ["*"],
    "createdAt": 1763198521000,
    "lastUsedAt": null,
    "expiresAt": 1794734521000
    }
    }
  2. Copy plainText now. It’s shown this one time; only a digest is stored, so nobody can show it again.

  3. Use it from the other program:

    Terminal window
    curl http://localhost:3000/api/posts -H "Authorization: Bearer svp_3fKq9ZbX0aLmN2pQrS7tUvWx4yZ1Ab2Cd3Ef5Gh6Ij7k9QxA1b"

    What you’ll see: the same posts list the user would see in the browser, filtered by your policies.

With no abilities given, the token gets every ability the app allows (["*"] by default), like Sanctum.

svp_3fKq9ZbX0aLmN2pQrS7tUvWx4yZ1Ab2Cd3Ef5Gh6Ij7k9QxA1b
└┬─┘└──────────────── 40 random ───────────────┘└ 6 ┘
prefix checksum
Part Why it’s there
svp_ a fixed prefix, so GitHub, GitLab and other secret scanners can recognise a leaked Strutvane token. Change it with tokens.prefix (2–8 lowercase letters and _)
40 random characters about 238 bits of randomness: impossible to guess
6-character checksum a CRC-32 of the rest. A mistyped or truncated token is refused before any database lookup

The database stores only an HMAC-SHA-256 of the token, made with a key derived from your APP_KEY. A leaked database (a backup, a read-only SQL bug) doesn’t leak usable tokens.

An ability is a short name for one kind of action: post.view, post.create, invoice.export. A token carries a list of them.

Pattern Grants
post.view exactly post.view
post.* every ability starting with post.: post.view, post.create, post.comment.create
* everything

Create a narrow token:

Terminal window
curl -X POST http://localhost:3000/user/api-tokens \
-H "Content-Type: application/json" -H "Origin: http://localhost:3000" -H "Cookie: strutvane_session=<your session>" \
-d '{"name":"CI deploy","abilities":["post.view","post.create"],"expiresInDays":90}'

What you’ll see: a token whose abilities are ["post.view","post.create"] and whose expiresAt is 90 days away.

A token never gives a user more than they already have. A request with a token is allowed only when:

  1. the token has the ability, and
  2. your policy allows the user.

So a token with post.* held by Bob still can’t edit Alice’s post, because PostPolicy.update() says no. And Alice’s post.view token can’t create posts even though Alice can. See Authorization.

You decide which abilities tokens may carry at all, in config/auth.ts. The default is ['*'] (anything). A tighter app:

config/auth.ts
import { defineAuthConfig } from '@strutvane/auth'
export default defineAuthConfig({
appUrl: process.env.APP_URL ?? 'http://localhost:3000',
features: { apiTokens: true },
tokens: {
abilities: ['post.*', 'tag.view', 'invoice.export'],
defaultExpiryDays: 90,
maxExpiryDays: 180,
},
})

What you’ll see: asking for user.delete or * now fails:

{"type":"about:blank","title":"Some fields are missing or invalid.","status":422,"code":"validation_failed","issues":[{"path":["abilities"],"field":"abilities","code":"not_allowed","message":"This token may not get that ability."}]}

A badly written pattern in the config stops the app at start-up:

TypeError: auth config: invalid token ability "post:view"

(Abilities use dots, not Sanctum’s colons.)

Use the abilities: middleware, Laravel’s name:

routes/api.ts
import { defineRoutes, Route } from '@strutvane/framework'
import { ExportController } from '../app/http/controllers/export.controller.ts'
import { PostController } from '../app/http/controllers/post.controller.ts'
export default defineRoutes([
Route.apiResource('posts', PostController).middleware('auth'),
Route.post('/exports/invoices', [ExportController, 'invoices']).middleware('auth', 'abilities:invoice.export'),
])

In your own code, the prototype’s tokens.authenticate(header) gives back an object with can():

app/http/controllers/export.controller.ts
// The prototype's engine API; how a controller reaches it in the framework isn't final.
const token = await auth.tokens.authenticate(ctx.header('authorization'))
if (token === undefined) throw new UnauthenticatedError()
if (!token.can('invoice.export')) throw new ForbiddenError('This token may not export invoices.')

token.user is the user, and token.token the token’s public details (never the secret).

List your tokens (the secret is never included):

Terminal window
curl http://localhost:3000/user/api-tokens -H "Cookie: strutvane_session=<your session>"

What you’ll see:

[
{"id":"0193a1d4-2b7e-7f10-8c3d-1e2f3a4b5c6d","name":"Nightly export","abilities":["*"],"createdAt":1763198521000,"lastUsedAt":1763284921000,"expiresAt":1794734521000},
{"id":"0193a1d5-9c0a-7b21-8d4e-2f3a4b5c6d7e","name":"CI deploy","abilities":["post.view","post.create"],"createdAt":1763198600000,"lastUsedAt":null,"expiresAt":1770974600000}
]

lastUsedAt is updated at most once a minute, so a busy script doesn’t write to the database on every request. A token that was never used shows null: a good hint that it can go.

Revoke one:

Terminal window
curl -i -X DELETE http://localhost:3000/user/api-tokens/0193a1d5-9c0a-7b21-8d4e-2f3a4b5c6d7e \
-H "Origin: http://localhost:3000" -H "Cookie: strutvane_session=<your session>"

What you’ll see: 204 No Content. The next request with that token gets 401. Someone else’s token id answers exactly like an unknown one, 404 not_found, so ids can’t be probed.

Setting in config/auth.ts Default Meaning
tokens.defaultExpiryDays 365 life of a token created without expiresInDays
tokens.maxExpiryDays 365 the longest life a user may ask for
tokens.abilities ['*'] the patterns tokens may carry
tokens.prefix svp_ the prefix secret scanners look for

expiresInDays must be a whole number from 1 to maxExpiryDays; anything else is validation_failed with an issue whose field is expiresInDays and code is invalid.

Tokens also die when:

  • the user resets their password (all tokens);
  • an admin runs node strut token:revoke --all after an incident (every token of every user);
  • the user is deleted;

Rotating APP_KEY does not kill tokens: a token’s digest is checked against APP_KEY and then every key in APP_PREVIOUS_KEYS, and re-digested under the current key on success (decided for 0.2; the prototype checks APP_KEY only, see Encryption).

Expired tokens stay in the table until node strut tokens:prune deletes them (usually from the scheduler).

A request with Authorization: Bearer skips the CSRF check. That’s safe because browsers never attach a bearer header on their own, so another site can’t make a victim’s browser send it.

The flip side: a bearer request never falls back to the cookie. A wrong or expired token gets 401, even if the same browser also has a valid session cookie. Mixing the two would let a broken token silently act as whoever is signed in.

From Node (another server, a script):

scripts/export-posts.ts
const token = process.env.MY_APP_TOKEN
if (token === undefined) throw new Error('Set MY_APP_TOKEN first')
const response = await fetch('https://app.example.com/api/posts?filter[status]=published', {
headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
})
if (response.status === 401) throw new Error('The token is invalid, expired or revoked: create a new one.')
console.log(await response.json())

Set the variable for one run:

macOS / Linux:

Terminal window
MY_APP_TOKEN=svp_3fKq… node scripts/export-posts.ts

Windows (PowerShell):

Terminal window
$env:MY_APP_TOKEN='svp_3fKq…'; node scripts/export-posts.ts

Keep tokens in your CI’s secret settings or a password manager, never in a committed file.

Every invalid token answers the same 401, whatever the reason, so nobody can tell a revoked token from a made-up one:

HTTP/1.1 401 Unauthorized
content-type: application/problem+json
{"type":"about:blank","title":"You need to sign in.","status":401,"code":"unauthenticated"}
Reason What the caller sees
typo, missing characters, wrong prefix 401 (refused by the checksum, no database lookup)
expired 401
revoked, or revoked by a password reset 401
the owner was deleted 401
apiTokens switched off in config/auth.ts 401: a disabled feature authenticates nothing
header isn’t Bearer <token> 401

To find out which one it was, look at the token list in settings (is it there? is expiresAt in the past?).

  • Tokens can’t be created while someone impersonates a user (impersonating needs the impersonate ability), because the token would outlive the impersonation.
  • Creating and revoking tokens emits token.created and token.revoked events for the audit log, with ids only.
  • No token value ever reaches a log line or an event; a test runs every feature and checks.
  • The Authorization header is parsed strictly (at most 200 characters, Bearer then one token).

Tokens behave the same. In Docker mode the app answers on the same http://localhost:3000 from your computer, so scripts on your machine use the same URL. Commands like node strut tokens:prune are forwarded into the container as usual.

Why: plainText is shown once. Only a digest is stored, so it can’t be shown again, by anyone. Fix: revoke it and create a new one:

Terminal window
curl -X DELETE http://localhost:3000/user/api-tokens/<id> -H "Origin: http://localhost:3000" -H "Cookie: strutvane_session=<your session>"
{"type":"about:blank","title":"You need to sign in.","status":401,"code":"unauthenticated"}

Why: the token expired (one year by default), was revoked, or the owner reset their password, which revokes all their tokens. Fix: create a new token and update the script’s secret. Put the expiresAt date in your calendar.

{"code":"validation_failed","issues":[{"path":["abilities"],"field":"abilities","code":"not_allowed","message":"This token may not get that ability."}]}

Why: you asked for an ability outside the app’s tokens.abilities list, or wrote it with a colon (post:view). Fix: use dots and stay inside the list, or widen the list:

config/auth.ts
tokens: { abilities: ['post.*', 'tag.view', 'invoice.export'] },

The token works but the request is still 403 or 404

Section titled “The token works but the request is still 403 or 404”

Why: the token has the ability, but your policy refuses the user (403), or the user may not even see that record (404). Abilities never widen what the user may do. Fix: check the policy for that user. In local debug mode the 403 body has a hint naming the policy method. See Authorization.

My browser code sends the token and also gets CSRF errors on other calls

Section titled “My browser code sends the token and also gets CSRF errors on other calls”

Why: some requests go out with the bearer header and some with only the cookie. Cookie requests need CSRF protection; bearer requests don’t. Fix: in your own React UI, don’t use tokens at all: the session cookie and the CSRF header are handled for you. Tokens are for programs outside the browser.

{"type":"about:blank","title":"Not found.","status":404,"code":"not_found"}

Why: the apiTokens feature is off. Fix:

config/auth.ts
features: { apiTokens: true },