Skip to content

visa ​

@c9up/visa: an OAuth 2.1 authorization server that issues tokens to other applications on a user's behalf: authorization code with PKCE, refresh rotation, client credentials, revocation, introspection and client registration, on a store contract. Guide: OAuth server.

Installation ​

bash
pnpm add @c9up/visa

ream configure @c9up/visa registers the provider, writes config/visa.ts, adds VISA_ISSUER to the environment files and writes the migrations of the tables AtlasStore uses. It writes neither a production store nor the /authorize route: both are yours.

Entry points ​

ImportContents
@c9up/visaVisaManager, the protocol functions, VisaGuard, both stores, errors and types
@c9up/visa/configdefineConfig, VisaConfigInput
@c9up/visa/providerVisaProvider (default export)
@c9up/visa/services/mainThe application's VisaManager (default export)
@c9up/visa/configureconfigure(), run by ream configure @c9up/visa
@c9up/visa/stores/memoryMemoryStore
@c9up/visa/stores/atlasAtlasStore and its database types
@c9up/visa/typesThe record types (Client, AccessToken, …)
@c9up/visa/testingtestVisa(), a real server on a memory store with a registered client

Exports ​

@c9up/visa ​

The server:

ExportKindDescription
VisaManagerclassThe authorization server: clients, authorize, consent, token, introspection, revocation, verification
VisaConfiginterfaceVisaManager options (see Configuration)
AuthorizationOutcometype{ type: 'redirect'; url } | { type: 'consent'; request: ValidatedRequest } | { type: 'error'; error: errors.E_VISA_OAUTH_ERROR }
ConsentTicketinterface{ id: string; userId: string; expiresAt: number; request: AuthorizationRequest }, kept in the session between the consent page and its answer
defineConfigfunctionSame as @c9up/visa/config
VisaConfigInputinterfaceSame as @c9up/visa/config
visaconstSame as the default export of @c9up/visa/services/main
setVisafunctionsetVisa(manager: VisaManager): void, seat the manager behind visa without the provider
getVisafunctiongetVisa(): VisaManager | undefined
clearVisafunctionclearVisa(): void, forget the seated manager

Protocol functions, each also reachable through VisaManager:

ExportKindDescription
validateAuthorizationRequestfunctionvalidateAuthorizationRequest(request: UntrustedAuthorizationRequest, store: VisaStore, options?: AuthorizeOptions): Promise<ValidatedRequest>; throws errors.E_VISA_UNREDIRECTABLE or errors.E_VISA_OAUTH_ERROR
issueAuthorizationCodefunctionissueAuthorizationCode(validated: ValidatedRequest, userId: string, store: VisaStore, options?: AuthorizeOptions, now?: Date): Promise<string>; the code lives codeTtlSeconds (30 s)
successRedirectfunctionsuccessRedirect(validated: ValidatedRequest, code: string, issuer: string): string; adds code, state and iss (RFC 9207)
errorRedirectfunctionerrorRedirect(redirectUri: string, error: errors.E_VISA_OAUTH_ERROR, options: { issuer: string; state?: string }): string; adds error, error_description, state and iss (RFC 9207)
tokenfunctiontoken(request: TokenRequest, credentials: ClientCredentials, store: VisaStore, options?: TokenOptions, now?: Date): Promise<TokenResponse>
introspectfunctionintrospect(request, credentials, store, now?, issuer?, options?: IntrospectionOptions): Promise<IntrospectionResponse>
revokefunctionrevoke(request, credentials, store, now?): Promise<void>
verifyAccessTokenfunctionverifyAccessToken(presented: string, store: Pick<VisaStore, 'findAccessToken'>, now?: Date, resource?: string): { clientId, userId?, scopes, expiresAt, lastUsedAt?, audience? } or null
validateRegistrationfunctionvalidateRegistration(request: ClientRegistrationRequest, options: RegistrationOptions, presentedToken?: string): the client's redirectUris, grantTypes, scopes, tokenEndpointAuthMethod and name
registrationResponsefunctionregistrationResponse(client: Client, issuedAt: Date, secret: string | undefined): ClientRegistrationResponse
readCredentialsfunctionreadCredentials(input: { authorization?: string; body: Record<string, unknown> }): ClientCredentials; refuses a request using two methods
authenticateClientfunctionauthenticateClient(credentials: ClientCredentials, load: (id: string) => Promise<Client | null>, now?: Date): Promise<Client>; every failure is invalid_client
assertGrantAllowedfunctionassertGrantAllowed(client: Client, grant: GrantType): void
resolveScopesfunctionresolveScopes(requested: string | undefined, client: Client): string[]; absent gives the client's scopes, an unregistered one is refused
redirectUriMatchesfunctionredirectUriMatches(candidate: string, registered: readonly string[]): boolean; exact match, port free on loopback
readResourceParameterfunctionreadResourceParameter(value: unknown): string[]
validateResourcesfunctionvalidateResources(requested: readonly string[], accepted?: readonly string[]): string[]; refuses with invalid_target
narrowResourcesfunctionnarrowResources(requested: readonly string[], granted: readonly string[]): string[]
audienceAllowsfunctionaudienceAllows(audience: readonly string[] | undefined, resource: string | undefined): boolean
protectedResourceMetadatafunctionprotectedResourceMetadata(options: ProtectedResourceOptions): ProtectedResourceMetadata
protectedResourceMetadataUrlfunctionprotectedResourceMetadataUrl(resource: string): string, the well-known URL of a resource
wwwAuthenticatefunctionwwwAuthenticate(options?: ChallengeOptions): string, the WWW-Authenticate value of a 401
assertResourceIdentifierfunctionassertResourceIdentifier(resource: string): void; an absolute URI without fragment
PROTECTED_RESOURCE_PATHconst'/.well-known/oauth-protected-resource'
randomTokenfunctionrandomToken(bytes?: number): string, 32 random bytes in base64url by default
sha256functionsha256(value: string): string, base64url, the PKCE S256 transform
hashSecretfunctionhashSecret(secret: string): string, what the store keeps for a token or a secret
secretMatchesfunctionsecretMatches(candidate: string, stored: string): boolean, constant time

Guard, stores and errors:

ExportKindDescription
visaGuardfunctionvisaGuard(config: VisaGuardConfig): VisaGuard, a warden guard that authenticates visa access tokens
VisaGuardclassThe guard (see below)
VisaAccessTokenclassThe token a guard puts on user.currentAccessToken
VisaGuardConfiginterfaceOptions of visaGuard()
GuardUserinterface{ id: string; roles?; permissions?; currentAccessToken?: VisaAccessToken; [key: string]: unknown }
GuardResultinterface{ authenticated: boolean; user?: GuardUser; error?: string }
GuardClientResponseinterface{ headers?: Record<string, string>; session?: Record<string, unknown> }
GuardStoretypePick<VisaStore, 'findAccessToken' | 'touchAccessToken' | 'saveAccessToken' | 'revokeAccessToken'>
VisaStoreinterfaceThe store contract (see below)
MemoryStoreclassSame as @c9up/visa/stores/memory
AtlasStoreclassSame as @c9up/visa/stores/atlas
AtlasDb, AtlasQuery, AtlasStoreTablesinterfaceSame as @c9up/visa/stores/atlas
errorsnamespaceThe package's errors, one class per code, see Errors
ProtocolErrorCodetypeUnion of the four code types below
AuthorizationErrorCodetype'invalid_request' | 'unauthorized_client' | 'access_denied' | 'unsupported_response_type' | 'invalid_scope' | 'invalid_target' | 'server_error' | 'temporarily_unavailable'
TokenErrorCodetype'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | 'invalid_target'
RegistrationErrorCodetype'invalid_redirect_uri' | 'invalid_client_metadata' | 'invalid_software_statement' | 'unapproved_software_statement'
BearerErrorCodetype'invalid_token'

Request and option types:

ExportKindDescription
AuthorizationRequestinterface{ response_type?, client_id?, redirect_uri?, scope?, state?, code_challenge?, code_challenge_method?, nonce?, prompt?, resource?: string | string[] }
UntrustedAuthorizationRequesttypeThe same keys, each unknown, as a query parser hands them
ValidatedRequestinterface{ client, redirectUri, redirectUriProvided, scopes, state, codeChallenge, codeChallengeMethod, nonce, resources }
AuthorizeOptionsinterface{ codeTtlSeconds?, resourcesSupported?, allowPlainChallenge? }
TokenOptionsinterface{ accessTokenTtlSeconds?, refreshTokenTtlSeconds?, issueRefreshTokens?, resourcesSupported? }
TokenRequesttypeRecord<string, unknown>, the token request body
ClientCredentialsinterface{ clientId?, clientSecret?, method?: ClientAuthMethod, … }
IntrospectionOptionsinterface{ resourceServers?: readonly string[] }
RegistrationOptionsinterface{ enabled?, initialAccessToken?, scopes?, grantTypes?, secretTtlSeconds? }
ClientRegistrationRequestinterfaceThe registration body: redirect_uris, token_endpoint_auth_method, grant_types, client_name, scope, …
ClientRegistrationResponseinterfaceThe 201 body: client_id, client_secret?, client_id_issued_at, client_secret_expires_at?, …
ProtectedResourceOptionsinterface{ resource, authorizationServers?, scopesSupported?, bearerMethodsSupported?, resourceName?, resourceDocumentation? }
ProtectedResourceMetadatainterfaceThe metadata document: resource, authorization_servers?, scopes_supported?, …
ChallengeOptionsinterface{ resourceMetadata?, resource?, error?, errorDescription?, scope? }
Client, AuthorizationCode, AccessToken, RefreshToken, Consent, AuthorizedApplication, TokenResponse, IntrospectionResponse, ClientAuthMethod, GrantTypetypeSame as @c9up/visa/types

VisaManager ​

new VisaManager(config: VisaConfig). The constructor checks the issuer and the registration settings.

MemberSignatureDescription
issuerreadonly issuer: stringThe issuer, trailing slashes removed
storereadonly store: VisaStoreThe configured store
registerClientregisterClient(input: { id: string; name: string; redirectUris: string[]; grantTypes?: GrantType[]; scopes?: string[]; tokenEndpointAuthMethod?: ClientAuthMethod; trusted?: boolean; secretExpiresAt?: Date }): Promise<{ client: Client; secret?: string }>Register a client; the secret is returned once and only its hash is stored. none creates a public client without a secret
registerregister(request: ClientRegistrationRequest, presentedToken?: string, now?: Date): Promise<ClientRegistrationResponse>A client registering itself; refused unless registration.enabled
authorizeauthorize(request: UntrustedAuthorizationRequest, userId: string | undefined): Promise<AuthorizationOutcome>Check an authorization request and decide: redirect, ask consent, or show an error. A remembered consent, or trusted, skips the consent screen, except for a public client whose redirect URI is loopback, localhost or a private-use scheme: that client gets the screen every time (RFC 8252 §8.6)
grantgrant(validated: ValidatedRequest, userId: string, now?: Date): Promise<string>The user agreed: record the consent, mint the code, return the redirect URL
denydeny(validated: ValidatedRequest): stringThe redirect URL carrying access_denied
consentTicketconsentTicket(validated: ValidatedRequest, userId: string, now?: Date): ConsentTicketA ticket for the consent page, valid consentTicketTtlSeconds
redeemConsentTicketredeemConsentTicket(ticket: unknown, presentedId: unknown, userId: string, now?: Date): Promise<ValidatedRequest | null>The request the ticket was shown for, validated again; null for anything wrong
tokentoken(body: Record<string, unknown>, credentials: ClientCredentials, now?: Date): Promise<TokenResponse>The token endpoint
introspectintrospect(body: Record<string, unknown>, credentials: ClientCredentials, now?: Date): Promise<IntrospectionResponse>The introspection endpoint; an inactive token is only { active: false }
revokerevoke(body: Record<string, unknown>, credentials: ClientCredentials, now?: Date): Promise<void>The revocation endpoint
verifyverify(presented: string, now?: Date, resource?: string)What a resource server calls per request; same result as verifyAccessToken
listAuthorizationslistAuthorizations(userId: string, now?: Date): Promise<AuthorizedApplication[]>Every application the user authorised, expired ones included
revokeAuthorizationrevokeAuthorization(userId: string, clientId: string, now?: Date): Promise<void>Revoke the application's tokens for the user, then forget the consent
readCredentialsreadCredentials(input: { authorization?: string; body: Record<string, unknown> }): ClientCredentialsClient credentials from the Authorization header or the body

VisaGuard ​

visaGuard(config) builds it. It authenticates a bearer access token and never a password.

MemberSignatureDescription
namereadonly name: stringGuard name, 'visa' by default
verifyverify(presented: string): Promise<GuardResult>Authenticate an access token; the user comes from findUser, or findClientSubject for a client-credentials token
authenticateauthenticate(): Promise<GuardResult>Throws: this guard takes no credentials
createTokencreateToken(user: { id: string } | string, abilities?: string[], options?: { name?: string; expiresInSeconds?: number }): Promise<VisaAccessToken>Mint a token for user under tokenClientId; abilities defaults to ['*']; an expiresInSeconds that is not a positive whole number throws E_VISA_INVALID_TTL
invalidateTokeninvalidateToken(presented: string): Promise<boolean>Revoke a token; true when it existed
authenticateAsClientauthenticateAsClient(user, abilities?, options?): Promise<GuardClientResponse>The Authorization header a test client sends to be user
challengechallenge(options?: { error?: string; scope?: readonly string[] }): stringThe WWW-Authenticate value of a 401 from this guard

VisaAccessToken carries clientId, userId?, abilities, name, expiresAt, lastUsedAt and value? (the plaintext, only right after createToken), with allows(ability), denies(ability), authorize(ability) (throws E_UNAUTHORIZED_ACCESS), isExpired() and toJSON(). * allows every ability.

VisaGuardConfig:

OptionTypeDefaultDescription
storeGuardStore | (() => GuardStore)—Where the tokens live; a function is read when needed
findUser(userId: string) => Promise<GuardUser | null>—Called on every request; null refuses it
findClientSubject(clientId: string) => Promise<GuardUser | null>—What a client-credentials token authenticates as; without it such a token is refused
namestring'visa'Guard name
tokenClientIdstring—The first-party client a token from createToken belongs to
expiresInSecondsnumber3600Lifetime of a token from createToken; a positive whole number, else visaGuard() throws E_VISA_INVALID_TTL
resourcestring—The protected resource this guard serves; challenge() then names its metadata

VisaStore ​

Every method that takes a credential takes its hash (hashSecret).

MemberSignature
findClientfindClient(id: string): Promise<Client | null>
saveClient (optional)saveClient?(client: Client): Promise<void>
saveAuthorizationCodesaveAuthorizationCode(code: AuthorizationCode): Promise<void>
findAuthorizationCodefindAuthorizationCode(codeHash: string): Promise<AuthorizationCode | null>
consumeAuthorizationCodeconsumeAuthorizationCode(codeHash: string, at: Date): Promise<boolean>; atomic, false when already consumed
saveAccessTokensaveAccessToken(token: AccessToken): Promise<void>
findAccessTokenfindAccessToken(tokenHash: string): Promise<AccessToken | null>
revokeAccessTokenrevokeAccessToken(tokenHash: string, at: Date): Promise<void>
saveRefreshTokensaveRefreshToken(token: RefreshToken): Promise<void>
findRefreshTokenfindRefreshToken(tokenHash: string): Promise<RefreshToken | null>
consumeRefreshTokenconsumeRefreshToken(tokenHash: string, at: Date): Promise<boolean>; atomic, false when already consumed or revoked
revokeFamilyrevokeFamily(familyId: string, at: Date): Promise<void>; every token of a family that exists when it runs, when a spent code or refresh token comes back or loses the race to be spent
findConsentfindConsent(userId: string, clientId: string): Promise<Consent | null>
saveConsentsaveConsent(consent: Consent): Promise<void>
listConsentslistConsents(userId: string): Promise<Consent[]>
listAccessTokenslistAccessTokens(userId: string): Promise<AccessToken[]>; expired ones included
revokeAccessForrevokeAccessFor(userId: string, clientId: string, at: Date): Promise<void>
deleteConsentdeleteConsent(userId: string, clientId: string): Promise<void>
touchAccessToken (optional)touchAccessToken?(tokenHash: string, at: Date): Promise<void>; records the last use
prune (optional)prune?(now: Date): Promise<void>; drops what expired

@c9up/visa/config ​

ExportKindDescription
defineConfigfunctiondefineConfig(config: VisaConfigInput): VisaConfigInput
VisaConfigInputinterfaceconfig/visa.ts options (see Configuration)

@c9up/visa/provider ​

ExportKindDescription
defaultproviderVisaProvider: binds the VisaManager built from the visa config, fills @c9up/visa/services/main, mounts the machine endpoints when a router is bound
VisaAppContextinterface{ container, config }, what the provider needs from the application

Routes the provider mounts (prefix defaults to /oauth):

Method and pathMounted whenAnswers
POST {prefix}/tokenalwaysTokenResponse, cache-control: no-store
POST {prefix}/introspectalwaysIntrospectionResponse
POST {prefix}/revokealways200 with an empty body
POST {prefix}/registerregistration.enabled201 with ClientRegistrationResponse
GET /.well-known/oauth-authorization-server{issuer path}alwaysThe authorization server metadata, with authorization_response_iss_parameter_supported: true
GET /.well-known/oauth-protected-resource[/{resource path}]protectedResource is setProtectedResourceMetadata

These endpoints read their parameters from the body only; an OAuth parameter in the query string is refused with invalid_request. An E_VISA_OAUTH_ERROR becomes its status and toResponse() body, with WWW-Authenticate on a 401. {prefix}/authorize is not mounted: build it with visa.authorize(), consentTicket(), redeemConsentTicket(), grant() and deny().

@c9up/visa/services/main ​

ExportKindDescription
defaultconstvisa: VisaManager, the application's manager once VisaProvider booted; a member read before throws
setVisa, getVisa, clearVisafunctionSeat, read and forget the manager behind it

@c9up/visa/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: adds VISA_ISSUER, registers @c9up/visa/provider, writes config/visa.ts and the migrations 9000_create_visa_tables, 9001_add_visa_client_secret_expiry and 9002_add_visa_code_redirect_uri_omitted

@c9up/visa/stores/memory ​

ExportKindDescription
MemoryStoreclassnew MemoryStore(clients?: readonly Client[]), a VisaStore in process memory, for tests and a single-process development server

@c9up/visa/stores/atlas ​

ExportKindDescription
AtlasStoreclassnew AtlasStore(db: AtlasDb, tables?: AtlasStoreTables), a VisaStore on a database
AtlasDbinterface{ from(table): AtlasQuery; table(table): AtlasQuery }, what @c9up/atlas's db provides
AtlasQueryinterfaceThe query builder methods the store calls
AtlasStoreTablesinterfaceTable names: clients (visa_clients), authorizationCodes (visa_authorization_codes), accessTokens (visa_access_tokens), refreshTokens (visa_refresh_tokens), consents (visa_consents)

@c9up/visa/types ​

ExportKindDescription
Clientinterface{ id, name, secretHash?, secretExpiresAt?, redirectUris, grantTypes, scopes, tokenEndpointAuthMethod, trusted? }
AuthorizationCodeinterface{ codeHash, clientId, userId, redirectUri, redirectUriOmitted?, scopes, codeChallenge, codeChallengeMethod, expiresAt, consumedAt?, resources?, nonce? }
AccessTokeninterface{ tokenHash, clientId, userId?, scopes, expiresAt, revokedAt?, lastUsedAt?, audience?, familyId? }
RefreshTokeninterface{ tokenHash, familyId, clientId, userId?, scopes, expiresAt, consumedAt?, revokedAt?, resources? }
Consentinterface{ userId, clientId, scopes, grantedAt }
AuthorizedApplicationinterface{ clientId, name, scopes, grantedAt, lastUsedAt?, active }
TokenResponseinterface{ access_token, token_type: 'Bearer', expires_in, refresh_token?, scope? }
IntrospectionResponseinterface{ active, iss?, scope?, client_id?, username?, sub?, exp?, iat?, token_type?, aud? }
ClientAuthMethodtype'client_secret_basic' | 'client_secret_post' | 'none'
GrantTypetype'authorization_code' | 'refresh_token' | 'client_credentials'

@c9up/visa/testing ​

ExportKindDescription
testVisafunctiontestVisa(options?: TestVisaOptions): Promise<TestVisa>, a real VisaManager on a MemoryStore with one registered client
TestVisainterface{ visa, store, client, secret, credentials, pkce(): { verifier; challenge }, tokensFor(userId, scope?): Promise<TokenResponse> }
TestVisaOptionsinterface{ issuer?, clientId?, redirectUri?, scopes?, grantTypes?, publicClient?, config? }; defaults https://auth.test, test-client, https://app.test/callback, ['profile', 'email']

tokensFor(userId) goes through authorize, consent and the code exchange.

Configuration ​

config/visa.ts, read under the visa key. The provider refuses to build the manager without it.

ts
import { defineConfig } from '@c9up/visa/config'
import { AtlasStore } from '@c9up/visa/stores/atlas'
import db from '@c9up/atlas/services/db'
import env from '#start/env'

export default defineConfig({
  issuer: env.get('VISA_ISSUER'),
  store: new AtlasStore(db),
  accessTokenTtlSeconds: 3600,
})
OptionTypeDefaultDescription
issuerstring—Public URL of this server, the iss of every token; https unless the host is localhost, no query, no fragment
storeVisaStore—Where clients, codes, tokens and consents live
accessTokenTtlSecondsnumber3600Access token lifetime
refreshTokenTtlSecondsnumber30 daysRefresh token lifetime
codeTtlSecondsnumber30Authorization code lifetime
consentTicketTtlSecondsnumber600How long a consent page may stay open before its answer is refused
issueRefreshTokensbooleantrueIssue refresh tokens
allowPlainChallengebooleanfalseAccept the plain PKCE method; only S256 otherwise
prefixstring'/oauth'Where the endpoints are mounted
resourcesSupportedstring[]—Resources tokens may be issued for; set, any other is refused with invalid_target
registrationRegistrationOptions—Client self-registration (see below)
introspection.resourceServersstring[]—Confidential clients allowed to introspect any access token; otherwise only the token's own client
protectedResource{ resource: string; scopesSupported?: string[]; resourceName?: string; resourceDocumentation?: string }—The protected resource; set, its metadata document is served

registration:

OptionTypeDefaultDescription
enabledbooleanfalseMount {prefix}/register
initialAccessTokenstring—Bearer token a registration must carry; left out, registration is open
scopesstring[][]Scopes a self-registered client may ask for
grantTypesGrantType[]['authorization_code', 'refresh_token']Grants it may use
secretTtlSecondsnumber—Seconds until an issued secret expires; left out, it does not

Container bindings ​

TokenResolves to
VisaManager (class)The manager built from the visa config
'visa'The same VisaManager

'visa' is declared in ContainerBindings.

Errors ​

CodeRaised when
E_VISA_MISSING_ISSUERNo issuer is configured
E_VISA_INVALID_ISSUERThe issuer is not a URL, or carries a query or a fragment
E_VISA_INSECURE_ISSUERThe issuer is not https and not localhost
E_VISA_NO_REDIRECT_URIregisterClient() got no redirect URI
E_VISA_INVALID_REDIRECT_URIA redirect URI given to registerClient() is not a complete URL
E_VISA_INVALID_INITIAL_ACCESS_TOKENregistration.initialAccessToken is the empty string
E_VISA_INVALID_TTLaccessTokenTtlSeconds, refreshTokenTtlSeconds, codeTtlSeconds or consentTicketTtlSeconds is not a positive whole number; checked when the VisaManager is built, and by token() and issueAuthorizationCode() called directly. Also the guard's expiresInSeconds, checked by visaGuard() and on each createToken()
E_VISA_INVALID_SECRET_TTLregistration.secretTtlSeconds is not a positive whole number
E_VISA_STORE_READ_ONLYThe store has no saveClient, and registerClient() was called or registration is enabled
E_VISA_MISSING_CONFIGVisaProvider found no config/visa.ts
E_VISA_NOT_BOOTED@c9up/visa/services/main was read before the provider booted, or before setVisa()
E_VISA_CREDENTIALS_UNSUPPORTEDauthenticate() with credentials on the visa guard; send the bearer token to verify()
E_VISA_NO_TOKEN_CLIENTcreateToken() on a guard built without tokenClientId
E_VISA_INVALID_RESOURCEA resource identifier is not an absolute URI, or carries a fragment
E_VISA_INVALID_CHALLENGE_PARAMETERA wwwAuthenticate() parameter holds a quote, a backslash or a control character
E_VISA_CORRUPT_ROWThe Atlas store read a column it cannot decode (a list, a date, a string, an auth method)
E_VISA_TEST_AUTHORIZE_FAILEDThe testing helper's authorization request was refused; the message carries the OAuth error
E_VISA_INTERNALAn internal invariant broke (a bug in visa)
E_UNAUTHORIZED_ACCESScurrentAccessToken.authorize(ability) on a token without that ability (403)
E_VISA_OAUTH_ERRORA client's mistake, answered on the wire: oauthCode is the protocol string (invalid_grant, invalid_client…), with description, challenge and toResponse(); status 401 for invalid_client and invalid_token, else 400
E_VISA_UNREDIRECTABLEAn authorization failure to show the user, never to redirect (unknown client or redirect URI); error is the E_VISA_OAUTH_ERROR to show (400)

Each one is a class of the errors namespace and a @c9up/flare Exception, with status 500 unless stated: branch on error.code or on error instanceof errors.E_VISA_*. A configuration mistake's advice is in help.

Migration ​

  • A public client (tokenEndpointAuthMethod: 'none') whose redirect URI is a loopback address, localhost or a private-use scheme (com.example.app:/callback) now gets the consent screen on every authorization. A remembered consent and trusted: true no longer skip it: any other program on the machine can present that client's id, so nothing proves the request comes from your application. Keep your consent page reachable for these clients. A confidential client, or a public client on an https redirect URI, keeps the silent path.
  • successRedirect(validated, code) becomes successRedirect(validated, code, issuer), and errorRedirect(uri, error, state) becomes errorRedirect(uri, error, { issuer, state }). Pass visa.issuer. Every authorization response, success or error, now carries iss (RFC 9207), and the metadata announces authorization_response_iss_parameter_supported: true. A client that reads the metadata then rejects a response without iss.
  • The guard's expiresInSeconds must be a positive whole number of seconds. Any other value now makes visaGuard() throw E_VISA_INVALID_TTL, and createToken() rejects with it. Until now NaN or Infinity minted tokens that never expired.
  • A code or a refresh token presented twice at the same time now ends its whole family, the winner's new tokens included. Until now only a presentation that arrived after the first one did. A client must not send the same refresh token in parallel: send one refresh, and let the other requests wait for its result.
  • A store you wrote yourself: consumeRefreshToken must answer false for a revoked token too, in the same atomic write (… WHERE consumed_at IS NULL AND revoked_at IS NULL). The token endpoint now saves the new pair before it calls consumeRefreshToken or consumeAuthorizationCode, and calls revokeFamily when the consume answers false.
  • accessTokenTtlSeconds, refreshTokenTtlSeconds, codeTtlSeconds and consentTicketTtlSeconds must be positive whole numbers of seconds. Any other value now stops the boot with E_VISA_INVALID_TTL. Until now NaN or Infinity gave codes and tokens that never expired, and 0 or a fraction were used as they were.
  • VisaError is gone: test error.code, or error instanceof errors.E_VISA_* with import { errors } from '@c9up/visa'. Its hint is now help.
  • OAuthError becomes errors.E_VISA_OAUTH_ERROR: its code is now 'E_VISA_OAUTH_ERROR', and the protocol string moved to oauthCode (error.code === 'invalid_grant' becomes error.oauthCode === 'invalid_grant'). The constructor, description, status, challenge and toResponse() are unchanged.
  • UnredirectableError becomes errors.E_VISA_UNREDIRECTABLE, still carrying error.
  • UnauthorizedAccessError becomes errors.E_UNAUTHORIZED_ACCESS; its code and status 403 are unchanged.

An application on AtlasStore whose tables came from an earlier version runs ream configure @c9up/visa again before upgrading, then its migrations. The existing 9000_create_visa_tables is left alone; the command adds 9001_add_visa_client_secret_expiry (the secret_expires_at column of visa_clients, missing up to 0.1.3) and 9002_add_visa_code_redirect_uri_omitted (the redirect_uri_omitted column of visa_authorization_codes).

See also ​