auth-js
@seek-services/auth-js is the browser core that auth-react is built on: PKCE, DPoP, token storage and refresh, the challenge client of the embedded login, and the account API. It has no runtime dependencies and ships as an ES module only. Use it directly in an app that is not written in React: npm install @seek-services/auth-js. See Installing.
import { AuthClient } from '@seek-services/auth-js'
const auth = new AuthClient({ issuer: 'https://your-app.auth.dev.seek.services', clientId: 'your-app-spa', redirectUri: window.location.origin + '/callback',})
// On page load: finish a login that came back, or pick the stored session up.let user = auth.hasRedirectResponse() ? await auth.handleRedirectCallback() : await auth.restore()auth.subscribe((next) => { user = next})
document.querySelector('#login')?.addEventListener('click', () => auth.loginWithRedirect())document.querySelector('#logout')?.addEventListener('click', () => auth.logout())
// Calls to your API carry the access token and a fresh DPoP proof.const res = await auth.authFetch('https://api.your-app.com/orders')AuthClient
Section titled “AuthClient”The client of a single-page app: the access token lives in memory, the refresh token in storage, and both are bound to a DPoP key that cannot leave the browser.
Options
Section titled “Options”| Option | Type | Default |
|---|---|---|
issuer |
string |
Required. A trailing / is removed. |
clientId |
string |
Required. |
scope |
string |
openid profile email offline_access |
resource |
string |
None: the client’s default API (RFC 8707). |
redirectUri |
string |
The current page, without its query string. |
postLogoutRedirectUri |
string |
The current page. It must be registered for the client. |
storage |
AuthStorage |
IndexedDB (database seek-auth), falling back to memory for the rest of the page if IndexedDB fails. |
sessionStorage |
Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> |
window.sessionStorage |
locks |
LockManagerLike | null |
The Web Locks API. null turns locking across tabs off. |
fetch |
typeof fetch |
The global fetch, looked up at each call. |
now |
() => number |
Date.now |
Properties
Section titled “Properties”issuer, clientId, user (the current AuthUser or null), and the account API clients passkeys, twoStep and identities (see below).
Methods
Section titled “Methods”| Method | What it does |
|---|---|
subscribe(listener) |
Calls listener(user | null) on every change: login, refresh, logout, a session that was lost. Returns the function that unsubscribes. |
restore() |
Picks up the stored session after a page load. Resolves null when there is none, or when the server refuses it (invalid_grant). |
loginWithRedirect(options?) |
Sends the browser to the hosted login page. |
createAuthorizeUrl(options?) |
The /authorize URL loginWithRedirect goes to, with PKCE, state and nonce saved in sessionStorage. |
hasRedirectResponse(url?) |
Whether the URL is a return from the hosted page: state with code or error. |
handleRedirectCallback(url?) |
Checks state (state_mismatch) and iss (issuer_mismatch, RFC 9207), removes the response from the address bar, and exchanges the code. |
beginLogin(options?) |
Starts an embedded login. Resolves { challenge, complete(code) }, where challenge is a ChallengeClient. Nothing is sent before the first step. |
completeLogin({ code, codeVerifier, nonce?, redirectUri? }) |
Exchanges an authorization code at /token. |
getAccessToken(options?) |
The access token, refreshed first when it ends within 30 seconds. { resource } gives a token for another API (kept in memory per API). Rejects login_required without a session. |
refresh() |
Rotates the refresh token now. |
authFetch(input, init?) |
fetch with Authorization: DPoP <token> and a fresh DPoP proof. On a 401 that says invalid_token it refreshes once and tries again (not for a ReadableStream body). init.resource picks the API. It is an arrow function, safe to pass around on its own. |
createSessionTicket(targetClientId) |
A session ticket for another app of the group: one use, within a minute. |
logout(options?) |
Deletes the stored tokens and revokes the refresh token at /revoke. A session that came through the hosted page then goes to the issuer’s /logout, so its cookie ends too. |
deleteAccount() |
Deletes the signed-in user’s account at once (DELETE /account/v1/me), with a token for the account audience; there is no undo. Then forgets the session here and tells subscribe listeners null: the service ended every session of the account, so nothing is revoked and the browser goes nowhere. Rejects with StepUpRequiredError when the login is older than ten minutes or below the user’s highest level, and with an AuthError for a refusal (code sole_owner, status 409, for a developer account that is the only owner of a workspace); the session stays then. |
uiConfig() |
What the login UI shows for this client (GET /ui/config), cached. |
proof(method, url, accessToken?) |
A DPoP proof from the device key, for a request authFetch does not make. |
Option types:
interface RedirectLoginOptions { provider?: string // go straight to this social or custom provider acrValues?: string // 'aal2' asks for a second factor maxAge?: number // seconds; 0 asks for a fresh login prompt?: 'login' | 'none' redirectUri?: string sessionTicket?: string}
interface LoginOptions { // beginLogin acrValues?: string maxAge?: number stepUp?: boolean // raise the current session instead of starting a new one}AuthUser
Section titled “AuthUser”Built from the ID token (or from the access token when the scope has no openid):
interface AuthUser { id: string // sub email?: string emailVerified?: boolean name?: string picture?: string acr: string // 'aal1' or 'aal2' amr: string[] authTime: number}The ID token’s iss, aud and nonce are checked. Its signature is not, since it came straight from the issuer over TLS; your backend must verify the access token itself.
Where things are kept
Section titled “Where things are kept”| What | Where |
|---|---|
| Access token, and tokens for other APIs | Memory only. |
| Refresh token | storage, key refresh-token:{issuer}|{clientId}. |
| DPoP key pair | storage, key dpop-key:{issuer}|{clientId}: a non-extractable P-256 key, made once and shared by the tabs. |
| ID token of a hosted-page session (for logout) | storage, key redirect-session:{issuer}|{clientId}. |
| A redirect in progress | sessionStorage, seek-auth-redirect:{clientId}; a logout in progress, seek-auth-logout:{clientId}. |
| Device id | localStorage, seek-auth-device. Sent with a login attempt so that a known device gets codes of its own under the rate limits. |
Refresh
Section titled “Refresh”Tokens are refreshed on demand, never on a timer: when a token is asked for and ends within 30 seconds. One refresh runs at a time, in a tab and across tabs (a Web Lock named seek-auth:refresh-token:{issuer}|{clientId}), and the stored refresh token is read only once the lock is held, because SeekAuth has no grace window: a refresh token presented twice ends the whole session. A refresh refused with invalid_grant forgets the session and tells the listeners null.
Every proof is an ES256 JWT with typ: dpop+jwt, the public key in jwk, and jti, htm, htu (without query or fragment), iat and, with an access token, ath. The SDK sends one to /token, /userinfo, with every authFetch, and with the first step of a step-up. See DPoP.
Embedded login
Section titled “Embedded login”beginLogin() returns a ChallengeClient on the /authorize-challenge endpoint:
const attempt = await auth.beginLogin()let out = await attempt.challenge.submit({ step: 'identify', email })if (out.status === 'challenge' && out.challenge.type === 'credentials') { out = await attempt.challenge.submit({ step: 'email_code' }) // send the code}// ... the user types the code ...out = await attempt.challenge.submit({ step: 'email_code', code })if (out.status === 'complete') { user = await attempt.complete(out.authorizationCode!)}// otherwise render out.challenge (mfa, totp_enroll, terms, add_email, ...) and submit the next stepChallengeClient member |
Meaning |
|---|---|
challenge, rejected |
The challenge the server last returned, and why the last step was refused, if it was. |
start(options?) |
Asks for the first challenge. |
submit(step, options?) |
Sends one step. Resolves { status: 'challenge', challenge, rejected? } or { status: 'complete', authorizationCode?, redirectTo? }. options.turnstileToken carries a solved captcha. |
passkeyChallenge() |
Passkey request options, without changing the current challenge (for autofill). |
reset() |
Starts over. An invalid_session answer resets the attempt by itself. |
EmbeddedTransport (the default) posts JSON to {issuer}/authorize-challenge without cookies; HostedTransport is what the hosted page uses. A challenge type the SDK does not know is an UnknownChallenge, which a UI should answer with a fallback such as loginWithRedirect().
Account API clients
Section titled “Account API clients”All three call the account API with a token for the account audience. Changes ask for a recent login and reject with StepUpRequiredError without one.
| Client | Methods |
|---|---|
auth.passkeys |
list() ({ passkeys, rp_id, max }), add({ name?, signal? }) ({ passkey, recovery_codes? }), rename(id, name), remove(id) |
auth.twoStep |
status() ({ totp, passkeys, recovery_codes_left }), start() ({ secret, otpauth_uri, enrollment_token }), confirm(setup, code) (the recovery codes), remove(), newRecoveryCodes() |
auth.identities |
list(), startLink(provider, returnTo) (the provider’s URL), confirmLink(linkCode), unlink(id) |
AccountApi is the account as a whole on any transport, as the three clients are: new AccountApi(request), where request(path, { method, body }) sends one call to /account/v1 and resolves with the Response. Its one method, delete(), is DELETE /me; auth.deleteAccount() uses it with the client’s own token, and a web client’s page uses it with its backend ((path, init) => fetch('/auth/account' + path, { ...init, credentials: 'include' })), which is what @seek-services/auth-react does.
Errors
Section titled “Errors”| Class | error |
Meaning |
|---|---|---|
AuthError |
any | The base class: error, message, and code, status, retryAfter when the server said so. |
StepUpRequiredError |
step_up_required |
A stronger or more recent login is needed. acrValues and maxAge say what for, from the WWW-Authenticate header or the body. |
NotAvailableError |
not_available |
The call cannot work here, such as getAccessToken for a web client. |
Errors the client raises itself (ClientErrors): login_required, state_mismatch, issuer_mismatch, invalid_id_token, network_error, unexpected_response, not_available, passkey_cancelled, passkey_exists, passkey_not_allowed, passkey_error. errorFromResponse(response, body) turns either error shape the server answers with (OAuth’s or { code, message }) into an AuthError.
Lower-level exports
Section titled “Lower-level exports”| Export | What it is |
|---|---|
TokenClient |
/token, /revoke and /userinfo calls with a DPoP proof function: exchangeCode, refresh(refreshToken, resource?), revoke(token), userinfo(accessToken). |
createPkce, createVerifier, challengeFor |
PKCE (S256). |
DpopKeyStore, generateDpopKeyPair, createDpopProof, exportPublicJwk, jwkThumbprint, htuOf |
DPoP keys and proofs. |
MemoryStorage, IndexedDbStorage, FallbackStorage, defaultStorage |
AuthStorage implementations. |
passkeysSupported(), passkeyAllowedHere(rpId, hostname?), conditionalMediationAvailable(), getPasskey, createPasskey, suggestPasskeyName() |
WebAuthn helpers. passkeyAllowedHere applies the browser’s rule: the host must be the passkey domain or under it. |
buildAuthorizeUrl, buildEndSessionUrl, parseIdToken, decodeJwtPayload |
URL and token helpers. |
DEFAULT_SCOPE, ACCOUNT_AUDIENCE, REFRESH_MARGIN_MS |
openid profile email offline_access, account, 30000. |