@plinthjs/api-tokens
Lightweight API token authentication for Plinth. Issue personal access tokens with abilities and optional expiry, store only a SHA-256 hash of each secret, and authenticate id|secret bearer tokens with a constant-time TokenGuard. Persistence sits behind a small TokenStore interface with an in-memory ArrayTokenStore default, and the clock and id/secret generators are injectable for deterministic tests.
Install
npm install @plinthjs/api-tokensUsage
import { ArrayTokenStore, hasApiTokens, TokenGuard } from '@plinthjs/api-tokens'
const store = new ArrayTokenStore()
// Issue a token for a user (the HasApiTokens trait equivalent).
const user = hasApiTokens(store, { id: 42, type: 'User' })
const { plainTextToken, accessToken } = await user.createToken({
name: 'cli',
abilities: ['servers:read', 'servers:deploy'],
expiresAt: Date.now() + 30 * 24 * 3_600_000, // optional
})
// plainTextToken ('id|secret') is shown to the user exactly once; only the hash is stored.
// Authenticate an incoming request.
const guard = new TokenGuard(store)
const bearer = request.headers.authorization?.replace(/^Bearer /, '') ?? ''
const token = await guard.authenticate(bearer) // PersonalAccessToken | null
if (token?.can('servers:deploy')) {
// ...
}
await guard.check(bearer) // boolean
await guard.authenticateToken(bearer) // the owner id (42), or nullauthenticate returns null for a malformed, unknown, mismatched or expired token, and stamps lastUsedAt on success.
Abilities
Tokens default to the wildcard ability '*' (WILDCARD_ABILITY), which grants everything.
token.can('servers:read') // true
token.cant('billing:write') // true
token.isExpired(Date.now()) // false
await user.tokens() // every token this owner holds
await user.tokenCan('servers:deploy') // true if any of the owner's tokens grants itIssuing tokens directly
import { createToken, parseToken } from '@plinthjs/api-tokens'
const { plainTextToken } = await createToken(store, {
name: 'deploy-bot',
abilities: ['servers:deploy'],
tokenableId: 'bot-1',
tokenableType: 'Bot',
})
parseToken(plainTextToken) // { id, secret }, or null when malformedissueToken is an alias of createToken. Revoke a token by deleting it from the store: await store.delete(accessToken.id). TokenStore methods may return values or promises, so a database-backed store works as is.
Stores and deterministic tests
Implement TokenStore (find, save, delete, all) to persist tokens elsewhere; a record round-trips through token.toAttributes() and PersonalAccessToken.from(attributes).
let now = 1_000
let n = 0
const { plainTextToken } = await createToken(
store,
{ name: 'test', expiresAt: 2_000 },
{ now: () => now, generateId: () => `id-${n++}`, generateSecret: () => 'secret' },
)
const guard = new TokenGuard(store, () => now)
await guard.check(plainTextToken) // true
now = 2_000
await guard.check(plainTextToken) // false: expired