Skip to content
keypal
Esc
↑↓navigate↵open⌘Jpreview
On this page

Permissions

Check a key's scopes, resource scopes and expiry

These methods take a record (anything with scopes and resources, such as result.record from verify) and return a boolean. They don’t check revocation, expiry or enabled; verify does that.

A key holds its global scopes, plus, when a resource is checked, the scopes in resources[resource], plus everything those imply through impliedScopes.

ScopeCheckOptions

PropType
resource?string

Resource being accessed, as "type:id", e.g. "project:123". Its scopes from resources are added to the global scopes.

Typestring
resources?Record<string, string[]>

Scopes per resource. Defaults to the record's resources.

TypeRecord<string, string[]>
impliedScopes?Record<string, string[]>

Scopes that grant other scopes, applied transitively. Defaults to the manager's impliedScopes.

TypeRecord<string, string[]>

hasScope(), hasAnyScope(), hasAllScopes()

hasScope(record: ScopedKey, scope: string, options?: ScopeCheckOptions): boolean
hasAnyScope(record: ScopedKey, scopes: string[], options?: ScopeCheckOptions): boolean
hasAllScopes(record: ScopedKey, scopes: string[], options?: ScopeCheckOptions): boolean

ScopedKey is { scopes?: string[]; resources?: Record<string, string[]> }. hasAnyScope with an empty list returns false; hasAllScopes with an empty list returns true.

const keys = createKeys({
  impliedScopes: { admin: ['read', 'write'] },
})

keys.hasScope({ scopes: ['admin'] }, 'write')                         // true
keys.hasAllScopes(record, ['read', 'write'], { resource: 'project:123' })

checkResourceScope(), checkResourceAnyScope(), checkResourceAllScopes()

checkResourceScope(record: ScopedKey | null, resourceType: string, resourceId: string, scope: string): boolean
checkResourceAnyScope(record: ScopedKey | null, resourceType: string, resourceId: string, scopes: string[]): boolean
checkResourceAllScopes(record: ScopedKey | null, resourceType: string, resourceId: string, scopes: string[]): boolean

Shorthand for the checks above with resource set to "resourceType:resourceId". Global scopes count too, so a key with global read passes checkResourceScope(record, 'project', '123', 'read'). A null record returns false, so you can pass verifyFromHeaders’s result directly.

const record = await keys.verifyFromHeaders(request.headers)

if (!keys.checkResourceScope(record, 'project', params.id, 'deploy')) {
  return new Response('Forbidden', { status: 403 })
}

To build resources maps, see ResourceBuilder. For the model behind them, see Resource scopes.

isExpired()

isExpired(record: { expiresAt?: Date | string | null }): boolean

true when expiresAt is now or in the past, or can’t be parsed. false when it is unset or null.

Functions without a manager

hasScope, hasAnyScope and hasAllScopes are also exported as functions that take a scope array instead of a record. See Standalone functions.

Was this page helpful?