Rayfin

@microsoft/rayfin-auth

Auth client reference for browserSession, session options, refresh, claims, sign-out, events, errors, and provider integration points in Rayfin apps.

@microsoft/rayfin-auth manages Rayfin session lifecycle, token refresh, event listeners, claims, and sign-out. Most apps use it through browserSession(), which gives a RayfinClient its client.auth, rather than constructing Auth directly.

Microsoft Entra sign-in is provided by @microsoft/rayfin-auth-provider-fabric, which installs sessions on this same Auth instance.

Installation

npm install @microsoft/rayfin-auth

Install it directly: @microsoft/rayfin-client no longer depends on it, and your code imports browserSession from it. Changed in 2.0 Add @microsoft/rayfin-lib when you construct Auth with your own ApiClient. The package declares an exports map, so import from @microsoft/rayfin-auth only, never from a dist/ path.

browserSession

New in 2.0

function browserSession(options?: AuthOptions): ClientAuthFactory<Auth>;

Selects browser-session authentication for RayfinClient.create(). The factory creates an Auth on the client's shared transport, attaches it before any registered service initializes, and exposes it as client.auth.

src/services/rayfinClient.ts
import { RayfinClient } from '@microsoft/rayfin-client';
import { browserSession } from '@microsoft/rayfin-auth';
import { dataService } from '@microsoft/rayfin-data';
import type { AppSchema } from '../../rayfin/data/schema';

export const client = RayfinClient.create({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
  auth: browserSession({ storage: true }),
  services: {
    data: dataService<AppSchema>(),
  },
});
  • options is the same AuthOptions object the Auth constructor takes.
  • client.auth is an ordinary Auth instance. Pass it to every @microsoft/rayfin-auth-provider-fabric function.
  • client.dispose() calls Auth.destroy(). It does not sign out, revoke tokens, or delete the persisted session.
  • In Rayfin 1.x, authStorage, persistSession, autoRefreshToken, and multiTabSync were top-level client options. Pass them to browserSession() instead, with authStorage renamed to storage; RayfinClient.create() rejects them with INVALID_AUTH_CONFIG.
  • A client created with suppliedToken() from @microsoft/rayfin-client has no client.auth.
  • The adapter also works in Node.js. Pass { storage: false } for a memory-only session.

Auth constructor

class Auth {
  constructor(apiClient: ApiClient, options?: AuthOptions);
}

Use the constructor for integrations that do not use RayfinClient. Rayfin's auth SDK detects browser and non-browser runtimes. When window is unavailable, it skips browser-only APIs such as localStorage unless you supply custom storage. Use { storage: false } for Node.js scripts or server code where no browser storage should be touched.

scripts/createAuth.ts
import { Auth } from '@microsoft/rayfin-auth';
import { ApiClient } from '@microsoft/rayfin-lib';

const apiClient = new ApiClient({
  baseUrl: process.env.RAYFIN_API_URL!,
  publishableKey: process.env.RAYFIN_PUBLISHABLE_KEY!,
});

const auth = new Auth(apiClient, { storage: false });
auth.attachToClient(apiClient);

try {
  console.log('Authenticated:', auth.getSession().isAuthenticated);
} finally {
  auth.destroy();
}

AuthOptions

interface AuthOptions {
  storage?: AuthStorage | boolean;
  storageKeyPrefix?: string;
  persistSession?: boolean;
  autoRefreshToken?: boolean;
  multiTabSync?: boolean;
  refreshTimeout?: number;
}

interface AuthStorage {
  getItem(key: string): string | null | Promise<string | null>;
  setItem(key: string, value: string): void | Promise<void>;
  removeItem(key: string): void | Promise<void>;
  clear?(): void | Promise<void>;
  keys?(prefix: string): string[] | Promise<string[]>;
}
OptionTypeDefaultDescription
storageAuthStorage | booleanBrowser localStorage when availableStorage implementation, true for default storage, or false for memory-only sessions.
storageKeyPrefixstringNonePrefix for the stored session and PKCE keys.
persistSessionbooleantrueWhen false, skips all storage I/O and keeps sessions in memory.
autoRefreshTokenbooleantrueWhen false, disables refresh timers and automatic refresh on 401.
multiTabSyncbooleanAuto-detected in browsersWhen false, disables StorageEvent cross-tab session sync.
refreshTimeoutnumber10000Milliseconds allowed for the renewal that runs before a request whose access token expires within 60 seconds. Independent of per-request timeouts. New in 2.0

Session management

MethodSignatureDescription
getSession() => OpaqueSessionReturns the current public session synchronously.
onSessionChange(callback: (session: OpaqueSession | null) => void) => () => voidSubscribes to session changes and returns an unsubscribe function.
getClaims() => Promise<ClientClaims>Validates the current access token and returns its claims without exposing the token. See Claims. New in 2.0
hasRefreshToken() => booleanReturns whether a refresh token is available.
refreshSession(options?: { timeout?: number; signal?: AbortSignal }) => Promise<TokenResponse>Refreshes the session; concurrent refreshes share one in-flight request. timeout (milliseconds) and signal bound the call. Changed in 2.0
attachToClient(client: ApiClient) => voidAdds authorization injection and refresh on 401 to another ApiClient, and renews a token that expires within 60 seconds before sending a request. Changed in 2.0
destroy() => voidRemoves timers and listeners. New or queued refreshes then reject with AUTH_DESTROYED; it does not sign out. Changed in 2.0
startAutoRefresh() => Promise<void>Restarts scheduled refresh when autoRefreshToken: false is used.
stopAutoRefresh() => voidStops scheduled refresh when autoRefreshToken: false is used.
src/auth/sessionLog.ts
import { client } from '../services/rayfinClient';

const session = client.auth.getSession();
console.log('Authenticated now:', session.isAuthenticated);

const unsubscribe = client.auth.onSessionChange((nextSession) => {
  console.log('Authenticated:', nextSession?.isAuthenticated ?? false);
});

// Later:
unsubscribe();

Warning

The session-change callback is onSessionChange. onAuthStateChange is not part of this SDK.

Rayfin renews the access token up to 60 seconds before it expires and retries transient renewal failures after 5 seconds, doubling up to 60 seconds. Changed in 2.0 See Sessions for the full renewal, multi-tab, and sign-out behavior.

OpaqueSession

Session objects are opaque by design. Gate UI logic on isAuthenticated or the presence of user, not on internal fields.

interface OpaqueSession {
  user: User | null;
  role?: string;
  expiresAt?: Date;
  isAuthenticated: boolean;
  isAnonymous: boolean;
}

interface User {
  id: string;
  email: string;
  role?: string;
  emailVerified?: boolean;
  emailVerifiedAt?: string | null;
}

isAuthenticated is true only while the session holds an access token that has not expired. Changed in 2.0 While an expired token waits to be renewed — for example after the device slept or was offline — it is false, user stays set, and hasRefreshToken() returns true; Rayfin renews the token automatically and emits AUTH_REFRESH.

Claims

New in 2.0

getClaims(): Promise<ClientClaims>;

Validates the current access token's signature and claims, then returns them: the base claims sub, email, and role, plus any dynamic claims your app mints. Tokens carry every app-defined claim as a string, so ClientClaims types each one as string; a provider's false arrives as 'false'. Server-side policies and a function's ctx.getClaims() see the declared types.

The claims types are exported from @microsoft/rayfin-core:

interface RayfinBaseClaims {
  sub: string;
  email: string;
  role: string;
}

// Empty by default. The generated rayfin/auth/claims.generated.d.ts merges your claims in.
interface RayfinCustomClaims {}

type AllClaims = RayfinBaseClaims & RayfinCustomClaims;

type ClientClaims = RayfinBaseClaims & {
  [K in keyof RayfinCustomClaims]: string;
};

getClaims() rejects with NO_SESSION, CLAIMS_VALIDATION_FAILED, or CLAIMS_DECODE_FAILED. Use the result for UI hints and keep authorization in entity policies.

TokenResponse

interface TokenResponse {
  accessToken: string;
  tokenType: string;
  expiresIn: number;
  refreshToken?: string | null;
  scope?: string | null;
}

Provider packages consume TokenResponse internally to install a public OpaqueSession. Application code should not copy Rayfin tokens between clients.

Sign-out methods

MethodSignatureDescription
signOut() => Promise<void>Revokes the current access token and clears the local session. Renews a lapsed access token first so the revocation is accepted. Changed in 2.0
signOutAll() => Promise<SignOutAllResponse>Revokes every active session for the user and returns { count }.

signOut() clears the local session even when the server call fails, then rethrows the error. A refresh that completes after sign-out no longer restores the session. Changed in 2.0

src/auth/signOutEverywhere.ts
import { client } from '../services/rayfinClient';

export async function signOutEverywhere(): Promise<number> {
  const result = await client.auth.signOutAll();
  return result.count;
}

Verification and settings methods

MethodSignatureDescription
getJwks() => Promise<JwksResponse>Fetches public signing keys for services that validate Rayfin-issued JWTs themselves.
getAuthSettings() => Promise<AuthSettingsConfig>Fetches public auth settings from the backend.

Events

Use onSessionChange for UI state. For narrower lifecycle handling, subscribe to session events with on(event, handler). The signature uses the exported AuthEvent union:

import type { AuthEvent, OpaqueSession } from '@microsoft/rayfin-auth';

function on(event: AuthEvent, handler: (session: OpaqueSession) => void): () => void;

The exported union contains every auth event emitted by the SDK. Fabric apps usually care about these session lifecycle events, which also trigger onSessionChange:

EventFires when
AUTH_LOGINA session is established. Subscribing while a session exists calls the handler immediately.
AUTH_LOGOUTThe session is cleared — by sign-out in this tab or another tab, or because it ended.
AUTH_REFRESHThe access token is renewed, or this tab adopts a session renewed in another tab.
AUTH_SESSION_EXPIREDThe session ends because its token lapsed and could not be renewed.
src/auth/onExpired.ts
import { client } from '../services/rayfinClient';

client.auth.on('AUTH_SESSION_EXPIRED', () => {
  window.location.assign('/sign-in');
});

Error codes

Methods reject with AuthError from @microsoft/rayfin-lib, which @microsoft/rayfin-client re-exports.

CodeRaised byMeaning
NO_SESSIONrefreshSession(), getClaims(), signOutAll()No session is active.
NO_REFRESH_TOKENrefreshSession()The session has no refresh token.
REFRESH_BACKOFFrefreshSession()A recent renewal failed transiently; try again after the backoff window.
SESSION_EXPIREDrefreshSession()The refresh token was rejected and the session ended.
AUTH_DESTROYEDrefreshSession()The Auth instance was destroyed, for example by client.dispose(). New in 2.0
CLAIMS_VALIDATION_FAILEDgetClaims()The current access token could not be validated. New in 2.0
CLAIMS_DECODE_FAILEDgetClaims()The current access token's claims could not be decoded. New in 2.0
SIGN_IN_DENIEDrefreshSession(), provider sign-inThe app's dynamic claims function denied the user; on refresh the session also ends. New in 2.0
AUTH_CLAIMS_UNAVAILABLE, AUTH_CLAIMS_FAILED, AUTH_CLAIMS_INVALID_OUTPUTrefreshSession(), provider sign-inThe app's dynamic claims function timed out, failed, or returned claims that do not match its contract. See Dynamic auth claims. New in 2.0

React usage

src/hooks/useSession.ts
import { useEffect, useState } from 'react';
import type { OpaqueSession } from '@microsoft/rayfin-auth';
import { client } from '../services/rayfinClient';

export function useSession() {
  const [session, setSession] = useState<OpaqueSession | null>(null);

  useEffect(() => {
    setSession(client.auth.getSession());
    return client.auth.onSessionChange(setSession);
  }, []);

  return {
    session,
    isAuthenticated: session?.isAuthenticated ?? false,
    signOut: () => client.auth.signOut(),
  };
}

Wire sign-in separately with ensureSignedInWithFabric, signInWithEntraToken, or the local development helper that installs a brokered token. For Fabric apps, await initEmbeddedAuth() before trusting the first session; see React integration.

AuthApi provider integration

auth.getAuthApi() returns the lower-level AuthApi used by companion provider packages. Rayfin 1.36 adds getBrokeredAuthorizeExternalUrl() so the external embed flow can tell the parent host which endpoint to call. New in 1.36

class AuthApi {
  getBrokeredAuthorizeExternalUrl(): string;
  exchangeVerificationCode(request: VerificationCodeExchangeRequest): Promise<TokenResponse>;
  getAuthSettings(): Promise<AuthSettingsConfig>;
}

Builders using ensureSignedInWithFabric() or createEmbedHost() do not call getBrokeredAuthorizeExternalUrl() directly. The provider SDK includes it in the external-embed handshake.

Internal provider exports

The package also exposes @microsoft/rayfin-auth/_internal/index for first-party provider packages; in 1.x the path was @microsoft/rayfin-auth/_internal. Changed in 2.0 Do not use these helpers in application code:

function getAuthProviderClient(auth: Auth): ApiClient;
function runProviderSignIn<T>(auth: Auth, operation: () => Promise<T>): Promise<T>;
function createSessionFromTokenResponse(
  auth: Auth,
  tokenResponse: TokenResponse,
  options?: { persistBeforeCommit?: boolean }
): Promise<OpaqueSession>;
function authClaimsErrorForServerCode(
  serverCode: string | null | undefined,
  message?: string
): AuthError | undefined;
function authClaimsErrorForCode(code: string | undefined): AuthError | undefined;
function perfMark(name: string): void;
function perfMeasure(name: string, startMark: string, endMark: string): void;

Performance marks

New in 2.0

Token renewal records rayfin:refresh-start and rayfin:refresh-end User Timing marks and a rayfin:refresh measure. They appear in the browser's performance tools and can be collected with a PerformanceObserver for the mark and measure entry types. The marks never contain tokens and are skipped where the User Timing API is unavailable.

PKCE helper exports

The root package exports PKCE utilities used by auth providers:

function generateCodeVerifier(): string;
function generateCodeChallenge(verifier: string): Promise<string>;
function generateState(): string;

Configuration and restart behavior

Auth is configured in rayfin.yml under services.auth. After changing values such as enabled, allowedRedirectUris, fabric.enabled, fabric.externalEntraExchange, or dynamicClaims.enabled, apply the updated runtime settings with npm run dev or npx rayfin up. A running backend does not infer local config changes until they are applied.

Something wrong on this page?Report an issueEdit this page

On this page