Global

Members

(constant) ASYMMETRIC_JWS_ALGS

Asymmetric JWS algorithms this library can verify (via jose, in browsers and Node.js): SETs and id_token assertions.

Source:

(constant) CAEP

OpenID CAEP 1.0 event types.

Source:

(constant) CLIENT_KEY_ALGS

Client key algorithms this library can sign HTTP messages with, in preference order.

Source:

(constant) DEFINITE_JOSE_ERRORS

jose errors that say the SET itself is bad. Anything else (fetching the JWKS, a key it doesn't hold yet) may pass.

Source:

(constant) DELIVERY

SSF delivery methods.

Source:

(constant) FATAL_ROTATION_ERRORS

GNAP errors that say a token can never be rotated again: the grant is gone.

Source:

(constant) FRONT_CHANNEL_TOKENS

Parameters that never arrive at a redirect finish URI: GNAP never sends a token through the browser.

Source:

(constant) HASH_METHODS

Interaction hash methods (RFC 9635 section 4.2.3) this library computes, and their WebCrypto names.

Source:

(constant) LIST_MEMBERS

Members of the RFC 9635 section 9 discovery document that are lists of strings.

Source:

(constant) NAMED_HANDLERS

Named handler slots. Each maps to one event type URI and gets a matching on<Name>(handler) method.

Source:

(constant) PROFILE_CLAIMS

Identity claims an account record keeps, for display and for matching security events. No tokens.

Source:

(constant) PROFILE_CLAIMS

Claims of a verified id_token assertion this client keeps in claims, for display and matching.

Source:

(constant) RESERVED_REQUEST_MEMBERS

Grant request members extra may not set: the client sets them, and the callback relies on them.

Source:

(constant) RISC

OpenID RISC 1.0 event types (receivable through onEvent(RISC.X, handler)).

Source:

(constant) SIGNAL_RIGHTS

Rights dropped from a grant when signals is false. A string is matched after trim; an object's type is exact.

Source:

(constant) SIGN_PARAMS

WebCrypto parameters for signing with each JWS algorithm (RFC 9421 section 3.3.7).

Source:

(constant) SSF

OpenID Shared Signals Framework 1.0 stream-control event types.

Source:

(constant) SSF_URL_MEMBERS

SSF transmitter metadata members that are URLs, all of which must use TLS.

Source:

(constant) Subject

Helpers for RFC 9493 Subject Identifiers, as carried in the SET sub_id claim and in a GNAP grant response's subject.sub_ids.

Source:

Methods

accountKey(iss, sub) → {Promise.<string>}

The account key for an iss and sub: stable, opaque, and safe in a storage key or a URL.

Parameters:
Name Type Description
iss string
sub string
Source:
Returns:
Type
Promise.<string>

base64()

Standard base64 (with padding), as RFC 8941 byte sequences use.

Source:

base64url()

base64url without padding.

Source:

clearDiscoveryCache()

Clears the in-process metadata cache (mostly useful in tests).

Source:

complex()

SSF complex subject, e.g. { user: Subject.issSub(...), session: Subject.opaque('gnap-grant:…') }

Source:

contentDigest(body) → {Promise.<string>}

RFC 9530 section 2: sha-256=:<base64 of SHA-256 over the content>:.

Parameters:
Name Type Description
body string | Uint8Array
Source:
Returns:
Type
Promise.<string>

digest()

SHA-256/384/512 digest of a string.

Source:

discoverGrantServer(grantEndpoint, optsopt) → {Promise.<Record.<string, any>>}

Discovers a GNAP authorization server: an HTTP OPTIONS request to its grant endpoint (RFC 9635 section 9), validated with validateGrantServerMetadata().

Parameters:
Name Type Attributes Description
grantEndpoint string
opts Object <optional>

(TypeScript: { timeoutMs?: number, fetch?: typeof fetch, cacheTtlMs?: number })

Source:
Returns:
Type
Promise.<Record.<string, any>>

discoverOpenIdProvider(issuer, optsopt)

Retrieves OpenID Provider metadata, for the jwks_uri that verifies an id_token assertion.

Parameters:
Name Type Attributes Description
issuer string
opts Object <optional>

(TypeScript: { timeoutMs?: number, fetch?: typeof fetch, cacheTtlMs?: number })

Source:

discoverSSFTransmitter(issuer, optsopt)

Retrieves SSF 1.0 transmitter metadata from /.well-known/ssf-configuration (RFC 8414-style path insertion first, then the appended form).

Parameters:
Name Type Attributes Description
issuer string
opts Object <optional>

(TypeScript: { timeoutMs?: number, fetch?: typeof fetch, cacheTtlMs?: number })

Source:

eventName()

Short name ("session-revoked") for an event type URI.

Source:

(async) fetchMetadata(urls, check, optsopt)

Fetches metadata from the first URL that answers 2xx and checks that check accepts it.

Parameters:
Name Type Attributes Description
urls Array.<string>
check function

(TypeScript: (metadata: Record<string, any>, url: string) => void)

opts Object <optional>

(TypeScript: { timeoutMs?: number, fetch?: typeof fetch, cacheTtlMs?: number, method?: string })

Source:

gnapErrorOf(body, status) → {GNAPError|undefined}

The GNAP error a parsed body carries, if any: RFC 9635 section 3.6's object form { error: { code, description } }, or the string form { error: "code" }.

Parameters:
Name Type Description
body any
status number
Source:
Returns:
Type
GNAPError | undefined

httpRequest(url, optsopt)

Thin fetch wrapper with timeout and consistent error handling. Redirects are never followed: a GNAP request is signed over its target URI, and a redirect would carry the signature somewhere else.

Parameters:
Name Type Attributes Description
url string | URL
opts * <optional>

(TypeScript: RequestInit & { timeoutMs?: number, fetch?: typeof fetch })

Source:

interactionHash()

RFC 9635 section 4.2.3: base64url(H(client nonce \n server nonce \n interact_ref \n grant endpoint)).

Source:

isLoopback()

Loopback hosts, where plain http is acceptable (RFC 8252 §7.3, RFC 9700 §2.6).

Source:

isSecureUrl()

https, or plain http to a loopback host. Anything unparseable is not secure.

Source:

logEventReceived(event) → {void}

The default onEventReceived hook: prints one line per accepted event to the console, naming the event and its jti only. The payload and subject can carry personal data (email, phone, session id, IP address), and a console is read by extensions and error reporters, so they are left out. Call it from your own hook to keep the line.

Parameters:
Name Type Description
event SecurityEvent
Source:
Returns:
Type
void

norm()

Trailing slashes off, so https://as/gnap and https://as/gnap/ compare equal.

Source:

oidcDiscoveryUrl(issuer)

Builds the OpenID Connect Discovery 1.0 §4 URL: the well-known suffix is appended to the issuer. Used to find the JWKS that verifies an id_token subject assertion.

Parameters:
Name Type Description
issuer string
Source:

onceEvent()

Resolves when emitter next emits event, with the event's arguments.

Source:

opaqueIs()

An opaque identifier naming exactly id (or one of id, an array): both non-empty strings.

Source:

randomToken()

A cryptographically random base64url string (default 256 bits).

Source:

readJson(res, ErrorClassopt)

Reads a JSON body; turns GNAP error bodies and non-2xx responses into errors. A 204 or an empty body answers undefined.

Parameters:
Name Type Attributes Description
res Response
ErrorClass * <optional>

(TypeScript: typeof GNAPClientError)

Source:

rotationLock()

The lock one key's rotations and deletes share, across this origin's tabs.

Source:

sfString()

RFC 8941 section 4.1.6: a String.

Source:

signRequest(req) → {Promise.<Record.<string, string>>}

Signs a request for GNAP's httpsig proof (RFC 9635 section 7.3.1). The signature covers @method, @target-uri, content-digest when there is content, and authorization when an access token is presented, with created, a fresh nonce, the key's keyid and the gnap tag.

Parameters:
Name Type Description
req Object

(TypeScript: { method: string, url: string, headers?: Record<string, string>, body?: string|Uint8Array, key: { thumbprint: string, sign(data: Uint8Array): Promise<Uint8Array> }, created?: number, nonce?: string, label?: string })

Source:
Returns:

the headers to add: signature, signature-input, and content-digest when there is content

Type
Promise.<Record.<string, string>>

signatureBase(components, message, serialisedParams)

The RFC 9421 section 2.5 signature base.

Parameters:
Name Type Description
components Array.<string>
message Object

headers with lower-case names

serialisedParams string
Source:

signatureParams(components, params)

The covered components and the @signature-params value for one signature.

Parameters:
Name Type Description
components Array.<string>

component identifiers without quotes, e.g. @method, content-digest

params Object

(TypeScript: { created: number, nonce?: string, keyid: string, tag?: string })

Source:

subjectMatches(subId, identity) → {boolean}

Tests whether a subject identifier refers to a known identity.

identity fields: iss, sub, sid (a session id, or an array of them), email and email_verified, phone_number and phone_number_verified, plus any of device/application/tenant/org_unit/group as opaque ids.

A GNAP grant is a session of its own: iya-sts names a revoked grant gnap-grant:<id> and a revoked access token gnap-token:<jti> as the session of a complex subject. An account's sid is therefore an array holding both, and a session-scoped event matches when it names either.

  • An email or phone number identifies somebody only when the AS said it was verified (email_verified / phone_number_verified true): neither is a stable or unique identifier, and an unverified one may be anybody's.
  • A top-level opaque id is compared with sub. A session is named inside a complex subject.
  • In a complex subject every member must match, and the members this identity can't be checked against count as a non-match: an event about one session matches only an identity holding it.
Parameters:
Name Type Description
subId Record.<string, any>

An RFC 9493 subject identifier, e.g. a SET's sub_id

identity Record.<string, any>
Source:
Returns:
Type
boolean

timingSafeEqual()

Compares two strings in time independent of where they differ, so an interaction hash or a continuation token cannot be guessed byte by byte from timing. Both sides are hashed first so their lengths match.

Source:

trimTrailingSlashes(s)

s without its trailing slashes. A loop, not replace(/\/+$/, ''): that regex is retried at every slash of a run that is not at the end, so a long run followed by any other character is quadratic.

Parameters:
Name Type Description
s string
Source:

validateGrantServerMetadata(metadata, expectedGrantEndpointopt) → {Record.<string, any>}

Validates a GNAP authorization server discovery document (RFC 9635 section 9). grant_request_endpoint is required and, when expectedGrantEndpoint is given, must be that endpoint: a document naming another grant endpoint is a mix-up (section 11.12), as an OpenID Provider's issuer would be.

Parameters:
Name Type Attributes Description
metadata Record.<string, any>
expectedGrantEndpoint string <optional>
Source:
Returns:

the same metadata

Type
Record.<string, any>

wellKnownUrls(issuer, suffix)

Builds RFC 8414 §3-style well-known URLs: the suffix is inserted between host and path. Some deployments instead append it (OIDC style), so both are returned in preference order.

Parameters:
Name Type Description
issuer string
suffix string

e.g. "ssf-configuration"

Source:

withLock(name, fn) → {Promise.<T>}

Runs fn holding the lock name: across every tab of this origin where the Web Locks API exists (navigator.locks), otherwise within this JavaScript realm only.

Parameters:
Name Type Description
name string
fn function

(TypeScript: () => Promise<T>)

Source:
Returns:
Type
Promise.<T>

Type Definitions

Account

One person signed in through this client in this browser. Holds no token.

Type:
  • object
Properties:
Name Type Attributes Description
key string

Stable id derived from iss and sub.

iss string
sub string
sessions Array.<string> <optional>

The session ids iya-sts names this account's grant by in a CAEP event: gnap-grant:<id> and gnap-token:<jti>.

grantId string <optional>
uid string <optional>

The person's username at the AS, from an account subject identifier.

name string <optional>
email string <optional>
preferred_username string <optional>
status 'signed-in' | 'tokens-missing' | 'signed-out' | 'ended'

signed-in: its grant is in the cache. tokens-missing: not signed out, but its access token expired and could not be rotated; reauthenticate() asks for a new grant. ended: ended by the AS, a security event or a refused rotation; see endedReason.

endedReason string <optional>
addedAt number
lastUsedAt number
changedAt number <optional>

When the status last left signed-in.

Source:

Account

(TypeScript: import('./accounts.js').Account)

Type:
  • *
Source:

AccountHook(account, access) → {unknown}

Parameters:
Name Type Description
account Account
access function

(TypeScript: { getTokenSet: (opts?: { forceRefresh?: boolean }) => Promise<GrantSet> }) Reaches this account's grant during the hook (and, for onActivate, for as long as it stays active).

Source:
Returns:

Anything; a promise is awaited.

Type
unknown

AccountHook

(TypeScript: import('./accounts.js').AccountHook)

Type:
  • *
Source:

AccountManagerOptions

Type:
  • object
Properties:
Name Type Attributes Description
store * <optional>

(TypeScript: import('./stores.js').TokenStore) The cache shared by every tab: the account list and each account's grant. Default: IndexedDB (IndexedDBTokenStore) when tokens are key-bound (requireBoundTokens, the default), else memory.

tabStore * <optional>

(TypeScript: import('./stores.js').TokenStore) Where this tab remembers its active account. Default: sessionStorage where it exists, else memory.

storeKey string <optional>

Default "accounts".

refreshSkewSec number <optional>

Default 60.

maxAccounts number <optional>

Default 10.

rememberSignedOutDays number <optional>

How long a signed-out account stays listed. Default 30.

onActivate AccountHook <optional>

Runs when an account is about to become this tab's active account, after its token is rotated if due and before "activated" is emitted — e.g. to poll its CAEP stream and act on the signals queued while it was dormant. Throwing aborts the activation.

onDeactivate function <optional>

(TypeScript: (account: Account) => void|Promise<void>) Runs when an account stops being this tab's active account (e.g. to stop polling its stream).

onLeave AccountHook <optional>

Runs before an account's grant is dropped by signOut() or end() (e.g. to delete its CAEP stream while its token still works).

broadcast boolean <optional>

Tell this origin's other tabs about changes (BroadcastChannel). Default true.

Source:

AccountManagerOptions

(TypeScript: import('./accounts.js').AccountManagerOptions)

Type:
  • *
Source:

GNAPClientConfig

Type:
  • object
Properties:
Name Type Attributes Description
grantEndpoint string <optional>

The AS's grant endpoint, e.g. https://as.example.com/gnap. Its discovery document is read with an OPTIONS request (RFC 9635 section 9).

metadata Record.<string, any> <optional>

A discovery document to use instead of discovering one.

finishUri string <optional>

Where the AS sends the browser back after interaction (the redirect finish URI, section 2.5.2). Required for a redirect interaction.

access Array.<(string|Record.<string, any>)> <optional>

The access rights to request by default (section 8): reference strings such as "ssf.read", or objects with type, actions, ...

signals boolean <optional>

CAEP and RISC. Omitted or true is on. false removes ssf.read and ssf.manage from the grant request. The subject request is unchanged.

subject Object <optional>

(TypeScript: { subIdFormats?: string[], assertionFormats?: string[] }|false) Who the resource owner is (section 2.2). Default { subIdFormats: ['iss_sub', 'opaque'] }. false asks for nothing.

display Object <optional>

(TypeScript: { name?: string, uri?: string, logo_uri?: string }) What the approval page shows about this client (section 2.3.2): self-declared, never a reason for more trust.

classId string <optional>

The client's class_id (section 2.3): the identifier of the registered application this key is an instance of. An AS that accepts unregistered instances (iya-sts: gnap.unregisteredInstances, the default) then accepts a browser's key with no registration of its own.

key ClientKey <optional>

The client key. Default: loaded from, or created in, keyStore.

keyStore * <optional>

(TypeScript: import('./keys.js').KeyStore) Where the key is kept (default memory: a new client instance every page load). Use new IndexedDBKeyStore() to keep a non-extractable key.

alg string <optional>

Client key algorithm (default ES256).

useInstanceId boolean <optional>

Send the instance_id the AS handed out (section 3.5) instead of the key by value in later requests. Default false.

instanceStore * <optional>

(TypeScript: import('./stores.js').TokenStore) Where an instance_id is remembered.

requireBoundTokens boolean <optional>

Refuse an access token issued with the bearer flag (section 3.2.1): this client asks for key-bound tokens. Default true.

hashMethod 'sha-256' | 'sha-512' <optional>

The interaction hash method to ask for (default sha-256).

idToken Object <optional>

(TypeScript: { issuer: string, jwksUri?: string, audience?: string|string[], algorithms?: string[] }) Verify an id_token subject assertion against this issuer's keys. Without it, an assertion is kept as received and never decoded.

transactionStore TransactionStore <optional>

Where pending grants wait for the callback (default sessionStorage).

transactionTtlSec number <optional>

How long a pending grant stays redeemable (default 600).

maxWaitSec number <optional>

The longest wait (section 3.1) the client sleeps for a too_fast continuation before giving up (default 10).

allowInsecureRequests boolean <optional>

Allow non-TLS endpoints and finish URIs other than loopback (default false).

clockToleranceSec number <optional>

Allowed clock skew for an id_token assertion (default 30).

httpTimeoutMs number <optional>

Per-request timeout (default 10000).

discoveryCacheTtlMs number <optional>

How long a discovery document is cached (default 1h).

fetch * <optional>

(TypeScript: typeof fetch) Custom fetch implementation.

Source:

GNAPClientConfig

(TypeScript: import('./gnap-client.js').GNAPClientConfig)

Type:
  • *
Source:

KeyStore

(TypeScript: import('./keys.js').KeyStore)

Type:
  • *
Source:

KeyStore

Where the client key pair is kept between page loads. extractable: true says the store can only hold an extractable key (Web Storage holds strings), so ClientKey.loadOrCreate generates one.

Type:
  • object
Properties:
Name Type Attributes Description
get function

(TypeScript: () => Promise<StoredKey|undefined>)

set function

(TypeScript: (value: StoredKey) => Promise<void>)

delete function

(TypeScript: () => Promise<void>)

extractable boolean <optional>
Source:

SSFErrorContext

Where an error came from.

Type:
  • object
Properties:
Name Type Attributes Description
phase 'poll' | 'handler' | 'hook' | 'stop' | 'error'

poll: polling or validating a SET; handler: a handler threw; hook: onEventReceived threw; stop: sending the last acknowledgements failed.

jti string <optional>

The SET concerned, when there is one.

event SecurityEvent <optional>

The event whose handler threw.

willRetry boolean <optional>

The SET was left for the transmitter to send again.

Source:

SSFErrorContext

(TypeScript: import('./caep/ssf-receiver.js').SSFErrorContext)

Type:
  • *
Source:

SSFErrorHandler(error, context) → {void}

Parameters:
Name Type Description
error *

(TypeScript: Error & { code?: string })

context SSFErrorContext
Source:
Returns:
Type
void

SSFErrorHandler

(TypeScript: import('./caep/ssf-receiver.js').SSFErrorHandler)

Type:
  • *
Source:

SSFReceiverConfig

Type:
  • object
Properties:
Name Type Attributes Description
transmitterIssuer string

SSF transmitter issuer; metadata is loaded from its /.well-known/ssf-configuration. Delivery is RFC 8936 POLL: a browser cannot receive a push. (SETs obtained any other way can still be handed to receiveSet().)

audience string | Array.<string> <optional>

Expected SET aud. Defaults to the aud in the stream configuration.

eventsRequested Array.<string> <optional>

Default: all CAEP event types.

authorizationHeaders function <optional>

(TypeScript: (req: { method: string, url: string, body?: string }) => Promise<Record<string,string>>|Record<string,string>) Returns the Authorization headers for one request — for a GNAP access token, the token and the HTTP message signature over the method, URI, token and body digest: (r) => gnapClient.resourceHeaders(grantSet, r). body is the exact JSON text sent.

accessToken function <optional>

(TypeScript: () => Promise<string>|string) Alternative to authorizationHeaders: an access token sent with no key proof (<accessTokenScheme> <token>), for a bearer token.

accessTokenScheme string <optional>

The scheme accessToken is sent with. Default "GNAP".

streamId string <optional>

Use an existing stream instead of creating one.

description string <optional>
pollIntervalMs number <optional>

Default 5000.

maxEvents number <optional>

Max SETs per poll. Default 25.

clockToleranceSec number <optional>

Default 60.

maxSetAgeSec number <optional>

Reject SETs whose iat is older than this (seconds). Default 0: no limit. A polled SET waits at the transmitter until it is read, so an age limit would throw away the signals a stopped receiver catches up on. A replay is caught by its jti whatever its age.

maxDeliveryAttempts number <optional>

How many times a SET whose handlers throw is left for the transmitter to send again before it is acknowledged anyway (onError gets handler_failed). Default 5. A SET that can't be checked for a reason that may pass (a network error, a signing key not yet in the JWKS) is never reported as an error: it is left for redelivery until it can.

allowInsecureRequests boolean <optional>

Allow non-TLS SSF URLs other than loopback. Default false.

deleteOnPageHide boolean <optional>

Delete the stream, best effort, when the page is unloaded for good (pagehide that is not entering the back/forward cache). Default false: a stream kept across visits holds the events that arrive while no tab is open, which start({ catchUp: true }) delivers, and a browser may drop a request sent while a page unloads. Leave it off and let the transmitter time an abandoned stream out (iya-sts: ssf.personStreamInactivityTimeoutS).

pageEvents Object <optional>

Where pagehide is listened for. Default globalThis (the window).

trustedPollOrigins Array.<string> <optional>

Origins besides the transmitter's issuer and configuration_endpoint that the stream's poll endpoint_url may be at. The poll request carries the access token, so it is refused anywhere else.

requireTyp boolean <optional>

Require the typ: secevent+jwt header (SSF §4.1.9). Default true.

jtiCacheSize number <optional>

Replay-protection window size. Default 10000.

httpTimeoutMs number <optional>
fetch * <optional>

(TypeScript: typeof fetch)

handlers * <optional>

(TypeScript: Partial<Record<keyof typeof NAMED_HANDLERS, SecurityEventHandler>>)

onEventReceived SecurityEventHandler | null <optional>

Your logic for every accepted event: called once per event, before the typed handlers, and awaited. Default logEventReceived, which prints the event to the console. null turns it off. A throw goes to onError with phase: 'hook', and the typed handlers still run.

Source:

SSFReceiverConfig

(TypeScript: import('./caep/ssf-receiver.js').SSFReceiverConfig)

Type:
  • *
Source:

SecurityEvent

What every handler receives.

Type:
  • object
Properties:
Name Type Description
type string

Event type URI.

name string

Short name, e.g. "session-revoked".

payload Record.<string, any>

The event-specific object from the SET events claim.

subject Record.<string, any> | undefined

RFC 9493 subject identifier (sub_id, or legacy subject inside the event).

eventTimestamp number | undefined

CAEP event_timestamp (seconds), falling back to SET toe/iat.

initiatingEntity string | undefined

"admin" | "user" | "policy" | "system"

reasonAdmin Record.<string, string> | undefined
reasonUser Record.<string, string> | undefined
jti string
iss string
aud string | Array.<string>
iat number
txn string | undefined
set Record.<string, any>

All validated SET claims.

raw string

The SET as received (compact JWS).

Source:

SecurityEvent

(TypeScript: import('./caep/ssf-receiver.js').SecurityEvent)

Type:
  • *
Source:

SecurityEventHandler(event) → {unknown}

Parameters:
Name Type Description
event SecurityEvent
Source:
Returns:

Anything; a promise is awaited before the SET is acknowledged.

Type
unknown

SecurityEventHandler

(TypeScript: import('./caep/ssf-receiver.js').SecurityEventHandler)

Type:
  • *
Source:

StoredKey

(TypeScript: import('./keys.js').StoredKey)

Type:
  • *
Source:

StoredKey

Type:
  • object
Properties:
Name Type Description
alg string
keyPair CryptoKeyPair
Source:

StoredTokens

(TypeScript: import('./stores.js').StoredTokens)

Type:
  • *
Source:

StoredTokens

A token set as a store keeps it (TokenSet#toJSON()).

Type:
  • Record.<string, any>
Source:

TokenStore

(TypeScript: import('./stores.js').TokenStore)

Type:
  • *
Source:

TokenStore

Storage for tokens and for in-flight authorization transactions.

Token store interface (async or sync methods):

Type:
  • object
Properties:
Name Type Description
get function

(TypeScript: (key: string) => Promise<object|undefined>|object|undefined)

set function

(TypeScript: (key: string, value: object) => Promise<void>|void)

delete function

(TypeScript: (key: string) => Promise<void>|void)

Source: