Scopes and permissions
Limit what a key may do with scopes, and let broad scopes grant narrower ones.
A scope is a string naming something a key may do, such as 'read' or 'deploy:production'. You choose the names. keypal stores them on the key and gives you checks to run after verify succeeds.
Give a key scopes
const { key, record } = await keys.create({
ownerId: 'user_123',
scopes: ['projects:read', 'projects:write'],
})
The manager has no method that edits a key in place. To change scopes, rotate the key with new ones, which issues a new secret: keys.rotate(record.id, { scopes: ['projects:read'] }). To keep the same secret, call update(id, { scopes }) on your storage adapter.
Check them
const result = await keys.verify(request.headers)
if (!result.record) {
return Response.json({ error: result.errorCode }, { status: 401 })
}
keys.hasScope(result.record, 'projects:write') // has this one
keys.hasAnyScope(result.record, ['projects:write', 'admin']) // has at least one
keys.hasAllScopes(result.record, ['projects:read', 'projects:write']) // has every one
Matching is exact and case-sensitive. keypal gives no meaning to the names: 'admin' grants nothing beyond 'admin', '*' is not a wildcard, and 'projects' does not include 'projects:read'. If you want one scope to cover others, say so with impliedScopes.
Scopes that grant other scopes
impliedScopes maps a scope to the scopes it also grants:
import { createKeys } from 'keypal'
const keys = createKeys({
impliedScopes: {
admin: ['projects:write', 'billing:read'],
'projects:write': ['projects:read'],
},
})
keys.hasScope({ scopes: ['admin'] }, 'projects:read') // true, through projects:write
Implications are followed transitively, and cycles are safe. They are applied when the manager checks scopes, not stored on keys, so changing the map changes what existing keys may do on their next request.
The common use is splitting a scope. Say manage:websites used to cover deleting visitor data and you add a separate delete:visitor_data scope for it. Keys issued before the split hold only manage:websites, so they would lose access. Add { 'manage:websites': ['delete:visitor_data'] } and they keep it, while new keys can be given the narrow scope alone.
The standalone hasScope, hasAnyScope, and hasAllScopes functions take a scope array instead of a record and do not read the manager’s configuration; pass { impliedScopes } as their last argument. See Standalone functions.
Choosing scope names
- Name the resource and the action, such as
projects:read. Each endpoint can then check exactly one scope. - Give each new key the fewest scopes it needs. Broad scopes are easy to grant and hard to take back.
- Keep the list of valid scopes in one place in your code, and validate requested scopes against it before calling
create, since keypal accepts any string.
To limit a key to one project or site instead of all of them, use resource scopes.