@axa-fr/oidc-client 7.29.3 → 7.29.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,659 +1,396 @@
1
1
  # @axa-fr/oidc-client
2
2
 
3
- [![Continuous Integration](https://github.com/AxaGuilDEv/react-oidc/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/AxaGuilDEv/react-oidc/actions/workflows/npm-publish.yml)
4
- [![npm downloads](https://img.shields.io/npm/dw/@axa-fr/oidc-client)](https://www.npmjs.com/package/@axa-fr/oidc-client)
3
+ A framework-independent OpenID Connect (OIDC) client for browser applications, written in TypeScript. It supports Authorization Code Flow with PKCE, session restoration, token renewal, multiple named configurations, optional service-worker token isolation, Pushed Authorization Requests (PAR), and DPoP.
5
4
 
6
- **@axa-fr/oidc-client** the lightest and securest library to manage authentication with OpenID Connect (OIDC) and OAuth2 protocol. It is compatible with all OIDC providers.
7
- **@axa-fr/oidc-client** is a pure javascript library. It works with any JavaScript framework or library.
5
+ For React applications, use [`@axa-fr/react-oidc`](../react-oidc/README.md).
8
6
 
9
- We provide a wrapper **@axa-fr/react-oidc** for **React** (compatible next.js) and we expect soon to provide one for **Vue**, **Angular** and **Svelte**.
7
+ - [Quick start](#quick-start)
8
+ - [Service worker](#service-worker)
9
+ - [Configuration](#configuration)
10
+ - [Token renewal](#token-renewal)
11
+ - [Pushed Authorization Requests (PAR)](#pushed-authorization-requests-par)
12
+ - [DPoP](#dpop)
13
+ - [API](#api)
14
+ - [Errors and events](#errors-and-events)
15
+ - [Named configurations and routing](#named-configurations-and-routing)
16
+ - [Service-worker protocol](#service-worker-protocol)
17
+ - [Examples and further reading](#examples-and-further-reading)
10
18
 
11
- - Try the react demo at https://black-rock-0dc6b0d03.1.azurestaticapps.net/ (most advanced)
12
- - Try the pure javascript demo at https://icy-glacier-004ab4303.2.azurestaticapps.net/
19
+ <a id="getting-started"></a>
13
20
 
14
- <p align="center">
15
- <img src="https://raw.githubusercontent.com/AxaFrance/oidc-client/main/docs/img/introduction.gif"
16
- alt="Sample React Oicd"
17
- />
18
- </p>
21
+ ## Quick start
19
22
 
20
- - [About](#about)
21
- - [Getting Started](#getting-started)
22
- - [Run The Demo](#run-the-demo)
23
- - [How It Works](#how-it-works)
24
- - [Hash route](#Hash-route)
25
- - [Service Worker Support](#service-worker-support)
23
+ ```sh
24
+ npm install @axa-fr/oidc-client
25
+ ```
26
26
 
27
- ## About
27
+ Register a **public browser client** with your identity provider:
28
28
 
29
- @axa-fr/oidc-client is:
29
+ 1. Enable Authorization Code Flow with PKCE.
30
+ 2. Register your application's exact callback URL, such as `https://app.example.com/authentication/callback`, and its post-logout URL.
31
+ 3. Allow your application's origin to call the provider's browser-accessible endpoints through CORS.
32
+ 4. Choose the scopes your application needs. Request `offline_access` only if your provider uses it to issue refresh tokens.
30
33
 
31
- - **Secure** :
32
- - With Demonstrating Proof of Possession (DPoP), your access_token and refresh_token are not usable outside your browser context (big protection)
33
- - With the use of Service Worker, your tokens (refresh_token and/or access_token) are not accessible to the JavaScript client code (if you follow good practices from [`FAQ`](https://github.com/AxaFrance/oidc-client/blob/main/FAQ.md) section)
34
- - OIDC using client side Code Credential Grant with pkce only
35
- - **Lightweight** : Unpacked Size on npm is **274 kB**
36
- - **Simple**
37
- - refresh_token and access_token are auto refreshed in background
38
- - with the use of the Service Worker, you do not need to inject the access_token in every fetch, you have only to configure OidcTrustedDomains.js file
39
- - **Multiple Authentication** :
40
- - You can authenticate many times to the same provider with different scope (for example you can acquire a new 'payment' scope for a payment)
41
- - You can authenticate to multiple different providers inside the same SPA (single page application) website
42
- - **Flexible** :
43
- - Work with Service Worker (more secure) and without for older browser (less secure).
44
- - You can disable Service Worker if you want (but less secure) and just use SessionStorage or LocalStorage mode.
34
+ Never put a client secret in browser code. Replace the example issuer and client ID below with your own values. Configure your web server to serve the application on the callback route as well as `/`.
45
35
 
46
- ![](https://github.com/AxaGuilDEv/react-oidc/blob/master/docs/img/schema_pcke_client_side_with_service_worker.png?raw=true)
36
+ Add these elements to your page:
47
37
 
48
- The service worker catch **access_token** and **refresh_token** that will never be accessible to the client.
38
+ ```html
39
+ <p id="session-status" role="status">Loading session…</p>
40
+ <button id="login" type="button" hidden>Sign in</button>
41
+ <button id="logout" type="button" hidden>Sign out</button>
42
+ ```
49
43
 
50
- ### Getting Started
44
+ Run this module when those elements are available, including on the callback route:
51
45
 
52
- ```sh
53
- npm install @axa-fr/oidc-client --save
46
+ ```javascript
47
+ import { OidcClient } from '@axa-fr/oidc-client';
54
48
 
55
- # To install or update OidcServiceWorker.js file, you can run
56
- node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public
49
+ const configuration = {
50
+ client_id: 'your-public-client',
51
+ authority: 'https://issuer.example.com',
52
+ redirect_uri: `${window.location.origin}/authentication/callback`,
53
+ scope: 'openid profile',
54
+ };
57
55
 
58
- # If you have a "public" folder, the 2 files will be created :
59
- # ./public/OidcServiceWorker.js <-- will be updated at each "npm install"
60
- # ./public/OidcTrustedDomains.js <-- won't be updated if already exist
61
- ```
56
+ const oidcClient = OidcClient.getOrCreate(() => fetch)(configuration);
57
+ const status = document.getElementById('session-status');
58
+ const loginButton = document.getElementById('login');
59
+ const logoutButton = document.getElementById('logout');
62
60
 
63
- WARNING : If you use Service Worker mode, the OidcServiceWorker.js file should always be up to date with the version of the library. You may setup a postinstall script in your package.json file to update it at each npm install. For example :
61
+ function showError() {
62
+ status.textContent = 'Authentication could not be completed. Please try again.';
63
+ }
64
64
 
65
- ```sh
66
- "scripts": {
67
- ...
68
- "postinstall": "node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public"
69
- },
70
- ```
65
+ loginButton.addEventListener('click', () => {
66
+ oidcClient.loginAsync('/').catch(showError);
67
+ });
68
+ logoutButton.addEventListener('click', () => {
69
+ oidcClient.logoutAsync('/').catch(showError);
70
+ });
71
71
 
72
- If you need a very secure mode where refresh_token and access_token will be hide behind a service worker that will proxify requests.
73
- The only file you should edit is "OidcTrustedDomains.js".
72
+ async function start() {
73
+ if (window.location.pathname === new URL(configuration.redirect_uri).pathname) {
74
+ const { callbackPath } = await oidcClient.loginCallbackAsync();
75
+ window.history.replaceState(null, '', callbackPath || '/');
76
+ } else {
77
+ await oidcClient.tryKeepExistingSessionAsync();
78
+ }
74
79
 
75
- ```javascript
76
- // OidcTrustedDomains.js
80
+ const isAuthenticated = oidcClient.tokens != null;
81
+ status.textContent = isAuthenticated ? 'Signed in' : 'Not signed in';
82
+ loginButton.hidden = isAuthenticated;
83
+ logoutButton.hidden = !isAuthenticated;
84
+ }
77
85
 
78
- // Add bellow trusted domains, access tokens will automatically injected to be send to
79
- // trusted domain can also be a path like https://www.myapi.com/users,
80
- // then all subroute like https://www.myapi.com/useers/1 will be authorized to send access_token to.
86
+ start().catch(showError);
87
+ ```
81
88
 
82
- // Domains used by OIDC server must be also declared here
83
- const trustedDomains = {
84
- default: {
85
- oidcDomains: ['https://demo.duendesoftware.com'],
86
- accessTokenDomains: ['https://www.myapi.com/users'],
87
- },
88
- };
89
+ This minimal example uses browser storage, not a service worker. Read the next section before choosing a token-storage strategy for production.
89
90
 
90
- // Service worker will continue to give access token to the JavaScript client
91
- // Ideal to hide refresh token from client JavaScript, but to retrieve access_token for some
92
- // scenarios which require it. For example, to send it via websocket connection.
93
- trustedDomains.config_show_access_token = {
94
- oidcDomains: ['https://demo.duendesoftware.com'],
95
- accessTokenDomains: ['https://www.myapi.com/users'],
96
- showAccessToken: false,
97
- // convertAllRequestsToCorsExceptNavigate: false, // default value is false
98
- // setAccessTokenToNavigateRequests: true, // default value is true
99
- // bypassAllNonOidcRequests: false, // default value is false; when true, requests outside OIDC and accessTokenDomains are handled by the browser
100
- };
91
+ ### Call a protected API
101
92
 
102
- // DPoP (Demonstrating Proof of Possession) will be activated for the following domains
103
- trustedDomains.config_with_dpop = {
104
- domains: ['https://demo.duendesoftware.com'],
105
- demonstratingProofOfPossession: true,
106
- demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent: true, // default value is false, inject DPOP token only when DPOP header is present
107
- // Optional, more details bellow
108
- /*demonstratingProofOfPossessionConfiguration: {
109
- importKeyAlgorithm: {
110
- name: 'ECDSA',
111
- namedCurve: 'P-256',
112
- hash: {name: 'ES256'}
113
- },
114
- signAlgorithm: {name: 'ECDSA', hash: {name: 'SHA-256'}},
115
- generateKeyAlgorithm: {
116
- name: 'ECDSA',
117
- namedCurve: 'P-256'
118
- },
119
- digestAlgorithm: { name: 'SHA-256' },
120
- jwtHeaderAlgorithm : 'ES256'
121
- }*/
122
- };
93
+ Use the client's fetch wrapper after authentication:
123
94
 
124
- // Setting allowMultiTabLogin to true will enable storing login-specific parameters (state, nonce, code verifier)
125
- // separately for each tab. This will prevent errors when logins are initiated from multiple tabs.
126
- // IMPORTANT: When allowMultiTabLogin is true, you MUST use the OIDC fetch provided by
127
- // oidcClient.fetchWithTokens(fetch) for API requests. The service worker embeds a tab-specific
128
- // token placeholder in the Authorization header, which it then replaces with the real access token.
129
- // Using a plain fetch or axios without the OIDC fetch wrapper will result in requests being sent
130
- // without an Authorization header (401 errors), because the service worker cannot determine which
131
- // tab's token to inject without the placeholder.
132
- // Example with axios: configure it to use the OIDC fetch as its adapter or use the OIDC fetch directly.
133
- trustedDomains.config_multi_tab_login = {
134
- domains: ['https://demo.duendesoftware.com'],
135
- allowMultiTabLogin: true,
136
- };
95
+ ```javascript
96
+ const oidcFetch = oidcClient.fetchWithTokens(fetch);
97
+ const response = await oidcFetch('https://api.example.com/profile');
98
+
99
+ if (!response.ok) {
100
+ throw new Error(`API request failed with status ${response.status}`);
101
+ }
102
+ const profile = await response.json();
137
103
  ```
138
104
 
139
- The code of the demo :
105
+ The wrapper attaches an access token, or a token placeholder when the service worker hides it, and integrates with token renewal. Only use it for API URLs you trust: the wrapper itself is not a destination allowlist. HTTP error responses still need an explicit `response.ok` check.
106
+
107
+ <a id="service-worker-support"></a>
108
+
109
+ ## Service worker
110
+
111
+ The optional service worker can keep access and refresh tokens outside the application's JavaScript context and attach access tokens to configured API requests. It does **not** prevent XSS: injected code can still act through your application and make requests. Continue to use normal XSS defenses, carefully restrict trusted destinations, and avoid rendering or logging raw tokens.
112
+
113
+ ```mermaid
114
+ sequenceDiagram
115
+ participant App as Browser application
116
+ participant IdP as Identity provider
117
+ participant SW as OIDC service worker
118
+ participant API as Trusted API
119
+ App->>IdP: Authorization request with PKCE
120
+ IdP-->>App: Redirect with authorization code
121
+ App->>SW: Token request
122
+ SW->>IdP: Exchange code and verifier
123
+ IdP-->>SW: Tokens
124
+ SW-->>App: Token placeholders and session information
125
+ App->>SW: Protected API request
126
+ SW->>API: Request with access token
127
+ API-->>App: Response through service worker
128
+ ```
140
129
 
141
- ```js
142
- import { OidcClient } from '@axa-fr/oidc-client';
130
+ The diagram shows worker mode with access-token hiding enabled. The ID token and decoded claims may still be available to application code.
143
131
 
144
- export const configuration = {
145
- client_id: 'interactive.public.short',
146
- redirect_uri: window.location.origin + '/#/authentication/callback',
147
- silent_redirect_uri: window.location.origin + '/#/authentication/silent-callback',
148
- scope: 'openid profile email api offline_access',
149
- authority: 'https://demo.duendesoftware.com',
150
- par: 'auto',
151
- service_worker_relative_url: '/OidcServiceWorker.js', // just comment that line to disable service worker mode
152
- service_worker_only: false,
153
- demonstrating_proof_of_possession: false,
154
- };
132
+ ### Install and update the worker
155
133
 
156
- const href = window.location.href;
157
- const oidcClient = OidcClient.getOrCreate()(configuration);
134
+ ```sh
135
+ node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public
136
+ ```
158
137
 
159
- // Use the fetch bellow to inject access_token and DPOP tokens automatically
160
- const oidcFetch = oidcClient.fetchWithTokens(fetch);
138
+ Replace `public` with your application's static-assets directory, and ensure that directory exists before running the command. This creates or updates `OidcServiceWorker.js` and creates `OidcTrustedDomains.js` if it does not already exist. Keep the worker version aligned with the client package; for example, merge this script into your `package.json`:
161
139
 
162
- // You can inject you own fetch (default Fetch Interface) function and location object (respecting IOidcLocation interface)
163
- // import {OidcLocation} from '@axa-fr/oidc-client'
164
- // const oidcClient = OidcClient.getOrCreate(() => fetch, new OidcLocation())(configuration);
165
-
166
- console.log(href);
167
-
168
- oidcClient.tryKeepExistingSessionAsync().then(() => {
169
- if (href.includes(configuration.redirect_uri)) {
170
- oidcClient.loginCallbackAsync().then(() => {
171
- window.location.href = '/';
172
- });
173
- document.body.innerHTML = `<div>
174
- <h1>@axa-fr/oidc-client demo</h1>
175
- <h2>Loading</h2>
176
- </div>`;
177
- return;
140
+ ```json
141
+ {
142
+ "scripts": {
143
+ "postinstall": "node ./node_modules/@axa-fr/oidc-client/bin/copy-service-worker-files.mjs public"
178
144
  }
145
+ }
146
+ ```
179
147
 
180
- let tokens = oidcClient.tokens;
181
-
182
- if (tokens) {
183
- // @ts-ignore
184
- window.logout = () => oidcClient.logoutAsync();
185
- document.body.innerHTML = `<div>
186
- <h1>@axa-fr/oidc-client demo</h1>
187
- <button onclick="window.logout()">Logout</button>
188
- <h2>Authenticated</h2>
189
- <pre>${JSON.stringify(tokens, null, '\t')}</pre>
190
- </div>`;
191
- } else {
192
- // @ts-ignore
193
- window.login = () => oidcClient.loginAsync('/');
194
- document.body.innerHTML = `<div>
195
- <h1>@axa-fr/oidc-client demo</h1>
196
- <button onclick="window.login()">Login</button>
197
- </div>`;
198
- }
199
- });
148
+ Edit `public/OidcTrustedDomains.js`, not the generated worker:
149
+
150
+ ```javascript
151
+ const trustedDomains = {
152
+ default: {
153
+ oidcDomains: [/^https:\/\/issuer\.example\.com(?:\/|$)/],
154
+ accessTokenDomains: [/^https:\/\/api\.example\.com\//],
155
+ },
156
+ };
200
157
  ```
201
158
 
202
- ## Configuration
159
+ Include the provider's endpoint origins if they differ from its issuer URL. Keep access-token destinations as narrow as possible; patterns can include paths. String entries are interpreted as regular-expression prefixes, not exact origin matches. The example uses anchored regular expressions with escaped dots and hostname boundaries to avoid unintended matches. The `default` key must match the OIDC configuration name.
160
+
161
+ Add these options to your client configuration:
203
162
 
204
163
  ```javascript
164
+ service_worker_relative_url: '/OidcServiceWorker.js',
165
+ service_worker_only: true,
166
+ ```
205
167
 
206
- const configuration = {
207
- client_id: String.isRequired, // oidc client id
208
- redirect_uri: String.isRequired, // oidc redirect url
209
- silent_redirect_uri: String, // Optional activate silent-signin that use cookies between OIDC server and client javascript to restore sessions
210
- silent_login_uri: String, // Optional, route that triggers the signin
211
- silent_login_timeout: Number, // Optional, default is 12000 milliseconds
212
- scope: String.isRequired, // oidc scope (you need to set "offline_access")
213
- authority: String.isRequired,
214
- storage: Storage, // Default sessionStorage, you can set localStorage, but it is not secure
215
- login_state_storage: Storage, // Optional. Storage used only for authorization flow state (state, code_verifier, nonce, login params). Defaults to the value of `storage`. Set to sessionStorage when using storage: localStorage to prevent race conditions when multiple tabs start the login flow simultaneously.
216
- authority_configuration: {
217
- // Optional for providers that do not implement OIDC server auto-discovery via a .wellknown URL
218
- authorization_endpoint: String,
219
- token_endpoint: String,
220
- userinfo_endpoint: String,
221
- end_session_endpoint: String,
222
- revocation_endpoint: String,
223
- pushed_authorization_request_endpoint: String,
224
- require_pushed_authorization_requests: Boolean,
225
- check_session_iframe: String,
226
- issuer: String,
227
- },
228
- refresh_time_before_tokens_expiration_in_second: Number, // default is 120 seconds
229
- service_worker_relative_url: String,
230
- service_worker_keep_alive_path: String, // default is "/"
231
- service_worker_only: Boolean, // default false, if true, the user will not be able to login if the service worker is not available on its browser
232
- service_worker_activate: () => boolean, // you can take the control of the service worker default activation which use user agent string, if return false, the service worker mode will not be used
233
- service_worker_register: (url: string) => Promise<ServiceWorkerRegistration>, // Optional, you can take the control of the service worker registration
234
- extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that is sent to the OIDC server (more info: https://github.com/openid/AppAuth-JS)
235
- token_request_extras: StringMap | undefined, // ex: {'prompt': 'consent', 'access_type': 'offline'} list of key/value that is sent to the OIDC server during token request (more info: https://github.com/openid/AppAuth-JS)
236
- authority_time_cache_wellknowurl_in_second: 60 * 60, // Time to cache in seconds of the openid well-known URL, default is 1 hour
237
- authority_timeout_wellknowurl_in_millisecond: 10000, // Timeout in milliseconds of the openid well-known URL, default is 10 seconds, then an error is thrown
238
- par: 'disabled' | 'auto' | 'required', // Pushed Authorization Requests mode, default is 'disabled'
239
- par_request_timeout: Number, // PAR endpoint timeout in milliseconds, default is 10000
240
- monitor_session: Boolean, // Add OpenID monitor session, default is false (more information https://openid.net/specs/openid-connect-session-1_0.html), if you need to set it to true consider https://infi.nl/nieuws/spa-necromancy/
241
- token_renew_mode: String, // Optional, update tokens based on the selected token(s) lifetime: "access_token_or_id_token_invalid" (default), "access_token_invalid", "id_token_invalid"
242
- token_automatic_renew_mode: TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted, // Optional, default is TokenAutomaticRenewMode.AutomaticBeforeTokensExpiration
243
- // TokenAutomaticRenewMode.AutomaticBeforeTokensExpiration: renew tokens automatically before they expire
244
- // TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted: renew tokens automatically only when fetch is executed
245
- // It requires you to use fetch given by oidcClient.fetchWithTokens(fetch) or to use oidcClient.getValidTokenAsync()
246
- logout_tokens_to_invalidate: Array<string>, // Optional tokens to invalidate during logout, default: ['access_token', 'refresh_token']
247
- location: ILOidcLocation, // Optional, default is window.location, you can inject your own location object respecting the ILOidcLocation interface
248
- demonstrating_proof_of_possession: Boolean, // Optional, default is false, if true, the the Demonstrating Proof of Possession will be activated //https://www.rfc-editor.org/rfc/rfc9449.html#name-protected-resource-access
249
- demonstrating_proof_of_possession_configuration: DemonstratingProofOfPossessionConfiguration // Optional, more details bellow
250
- };
168
+ Serve the worker from a URL whose scope covers your application, using HTTPS (or localhost for development). With `service_worker_only: true`, login requires an available service worker. With `false` (the default), the client can fall back to browser storage when worker mode is unavailable. Choose that fallback deliberately.
251
169
 
170
+ ### Trusted-domain options
252
171
 
253
- interface DemonstratingProofOfPossessionConfiguration {
254
- generateKeyAlgorithm: RsaHashedKeyGenParams | EcKeyGenParams,
255
- digestAlgorithm: AlgorithmIdentifier,
256
- importKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm,
257
- signAlgorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
258
- jwtHeaderAlgorithm: string
259
- };
172
+ These options belong in each named entry in `OidcTrustedDomains.js`, not in `OidcConfiguration`.
260
173
 
261
- // default value of demonstrating_proof_of_possession_configuration
262
- const defaultDemonstratingProofOfPossessionConfiguration: DemonstratingProofOfPossessionConfiguration ={
263
- importKeyAlgorithm: {
264
- name: 'ECDSA',
265
- namedCurve: 'P-256',
266
- hash: {name: 'ES256'}
267
- },
268
- signAlgorithm: {name: 'ECDSA', hash: {name: 'SHA-256'}},
269
- generateKeyAlgorithm: {
270
- name: 'ECDSA',
271
- namedCurve: 'P-256'
272
- },
273
- digestAlgorithm: { name: 'SHA-256' },
274
- jwtHeaderAlgorithm : 'ES256'
275
- };
174
+ | Option | Purpose |
175
+ | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
176
+ | `oidcDomains` | Provider URLs the worker is allowed to handle. |
177
+ | `accessTokenDomains` | API URLs to which the worker may attach an access token. |
178
+ | `domains` | Shorthand for a shared provider/API destination list; separate lists give finer control. |
179
+ | `showAccessToken` | Defaults to `false`. Set to `true` only when an integration requires the real access token in application JavaScript; refresh tokens remain hidden in worker mode. |
180
+ | `allowMultiTabLogin` | Isolates login state, nonce, and PKCE verifier by tab. Requires the OIDC fetch wrapper for protected API requests; see below. |
181
+ | `convertAllRequestsToCorsExceptNavigate` | Defaults to `false`; optionally changes non-navigation requests to CORS mode. |
182
+ | `setAccessTokenToNavigateRequests` | Defaults to `true`; controls token attachment to matching navigation requests. |
183
+ | `bypassAllNonOidcRequests` | Defaults to `false`. When enabled for all initialized worker configurations, requests outside OIDC and access-token destinations are left to the browser. |
184
+ | `demonstratingProofOfPossession` | Enables worker-side DPoP for this configuration. |
185
+ | `demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent` | Defaults to `true` when worker DPoP is enabled. Requires a DPoP header before worker-side DPoP injection; set to `false` to remove that condition. |
186
+ | `demonstratingProofOfPossessionConfiguration` | Overrides the worker's cryptographic algorithms; see [DPoP](#dpop). |
276
187
 
188
+ With `allowMultiTabLogin: true`, **use `oidcClient.fetchWithTokens(fetch)` for protected API requests**. Its tab-specific token placeholder tells the worker which session to use. Plain `fetch` or a default Axios request does not provide that marker, so automatic token attachment cannot select the tab's token and requests may receive HTTP 401. Use the OIDC fetch directly, or an integration that actually routes requests through it.
277
189
 
190
+ ## Configuration
191
+
192
+ The public [`OidcConfiguration` type](./src/types.ts) is the complete reference. Required fields are `client_id`, `authority`, `redirect_uri`, and `scope`.
193
+
194
+ | Option | Default / behavior |
195
+ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
196
+ | `authority_configuration` | Supply endpoint metadata instead of discovery. See `AuthorityConfiguration` in the type reference, including PAR metadata. |
197
+ | `storage` | `sessionStorage` when worker storage is not used. `localStorage` persists across tabs and browser sessions, but both are accessible to application JavaScript. |
198
+ | `login_state_storage` | Defaults to `storage`; separates authorization state, verifier, nonce, and login parameters from token storage. If tokens use `localStorage`, consider `sessionStorage` here to avoid cross-tab login races. |
199
+ | `silent_redirect_uri` | Enables the iframe-based silent-login flow. Must differ from `redirect_uri`; register it with the provider. |
200
+ | `silent_login_uri` | Page that starts silent login; derived from `silent_redirect_uri` if omitted. |
201
+ | `silent_login_timeout` | `12000` milliseconds. |
202
+ | `refresh_time_before_tokens_expiration_in_second` | `120` seconds; the client applies random jitter when this setting is greater than 60. |
203
+ | `token_renew_mode` | `'access_token_or_id_token_invalid'`; alternatives are `'access_token_invalid'` and `'id_token_invalid'`. |
204
+ | `token_automatic_renew_mode` | `TokenAutomaticRenewMode.AutomaticBeforeTokenExpiration`; see [token renewal](#token-renewal). |
205
+ | `token_request_timeout` | Token-request timeout in milliseconds. |
206
+ | `extras` | Additional authorization-request parameters, such as `{ prompt: 'consent' }`. |
207
+ | `token_request_extras` | Additional token-request parameters. Never use this to embed a browser client secret. |
208
+ | `par`, `par_request_timeout` | `'disabled'` and `10000` milliseconds; see [PAR](#pushed-authorization-requests-par). |
209
+ | `authority_time_cache_wellknowurl_in_second` | Discovery-cache lifetime; defaults to one hour. |
210
+ | `authority_timeout_wellknowurl_in_millisecond` | Discovery timeout; defaults to `10000` milliseconds. |
211
+ | `monitor_session` | `false`; enables OIDC session monitoring when supported by the provider and browser. |
212
+ | `logout_tokens_to_invalidate` | `['access_token', 'refresh_token']`; token types to revoke during standard logout. |
213
+ | `preload_user_info` | `false`; fetch user information during login/session restoration instead of waiting for a consumer. |
214
+ | `demonstrating_proof_of_possession` | `false`; see [DPoP](#dpop). |
215
+ | `demonstrating_proof_of_possession_configuration` | Cryptographic settings for client-side DPoP. |
216
+ | `service_worker_relative_url` | URL of the worker; omit to disable worker mode. |
217
+ | `service_worker_only` | `false`; disallows browser-storage fallback when `true`. |
218
+ | `service_worker_keep_alive_path` | `'/'`; path used by worker keep-alive requests. |
219
+ | `service_worker_activate` | Function to override the default browser-based activation decision. |
220
+ | `service_worker_register` | Custom `(url) => Promise<ServiceWorkerRegistration>` registration function. |
221
+ | `loading_timeout_ms` | Used by the React provider's loading watchdog; see the [React guide](../react-oidc/README.md#custom-components-and-provider-options). |
222
+
223
+ ### Silent login
224
+
225
+ Silent login uses an iframe and the provider's existing session. It depends on provider support and browser cookie/privacy policies; it is not a guaranteed replacement for refresh tokens.
226
+
227
+ For a vanilla application, implement both the `silent_login_uri` page and the `silent_redirect_uri` callback page. The login page starts `loginAsync` with `isSilentSignin: true` (the third argument); the callback page calls `silentLoginCallbackAsync()`. Keep these routes separate from the interactive callback. The React provider handles these routes for you; its [silent-login route implementation](../react-oidc/src/core/default-component/SilentLogin.component.tsx) is also a reference for forwarding silent-login parameters.
228
+
229
+ ## Token renewal
230
+
231
+ By default, the client schedules renewal before tokens expire. It uses a refresh token when available, or the configured silent-login flow. Refresh-token issuance and lifetime remain provider decisions.
232
+
233
+ For renewal only when an API request needs it:
234
+
235
+ ```typescript
236
+ import { TokenAutomaticRenewMode } from '@axa-fr/oidc-client';
237
+
238
+ const renewalOptions = {
239
+ token_automatic_renew_mode: TokenAutomaticRenewMode.AutomaticOnlyWhenFetchExecuted,
240
+ };
278
241
  ```
279
242
 
280
- ## Pushed Authorization Requests (PAR)
243
+ Merge this option into your configuration and use `fetchWithTokens(fetch)` or `getValidTokenAsync()` before protected requests. Plain fetch does not trigger this renewal mode.
281
244
 
282
- The client supports [OAuth 2.0 Pushed Authorization Requests (RFC 9126)](https://www.rfc-editor.org/rfc/rfc9126.html).
283
- Enable it with the `par` configuration option:
284
-
285
- - `'disabled'` (default) preserves the existing front-channel authorization
286
- request. PAR metadata is ignored in this mode.
287
- - `'auto'` uses PAR when discovery (or `authority_configuration`) provides a
288
- `pushed_authorization_request_endpoint`. It keeps the existing front-channel
289
- flow when the endpoint is absent, unless the server metadata says
290
- `require_pushed_authorization_requests: true`.
291
- - `'required'` always requires PAR and fails before browser navigation when no
292
- PAR endpoint is available.
293
-
294
- ```ts
295
- import {
296
- isPushedAuthorizationRequestError,
297
- OidcClient,
298
- PushedAuthorizationRequestErrorCode,
299
- } from '@axa-fr/oidc-client';
300
-
301
- const oidcClient = OidcClient.getOrCreate()({
302
- client_id: 'spa-client',
303
- redirect_uri: `${window.location.origin}/authentication/callback`,
304
- scope: 'openid profile',
305
- authority: 'https://issuer.example.com',
306
- par: 'auto',
307
- par_request_timeout: 10000,
308
- });
245
+ - `renewTokensAsync(extras?, scope?)` requests renewal and preserves the non-throwing behavior for terminal OIDC failures.
246
+ - `renewTokensOrThrowAsync(extras?, scope?)` returns tokens or rejects, for callers that need explicit failure handling.
247
+ - Automatic renewal reports failures through [events](#errors-and-events).
309
248
 
310
- try {
311
- await oidcClient.loginAsync('/');
312
- } catch (error) {
313
- if (
314
- isPushedAuthorizationRequestError(error) &&
315
- error.code === PushedAuthorizationRequestErrorCode.ENDPOINT_UNAVAILABLE
316
- ) {
317
- // PAR was required locally or by server metadata, but no endpoint was provided.
318
- }
319
- }
320
- ```
249
+ ## Pushed Authorization Requests (PAR)
321
250
 
322
- When PAR is selected, all authorization parameters, including `state`, `nonce`,
323
- PKCE and login `extras`, are sent as
324
- `application/x-www-form-urlencoded` data to the PAR endpoint. The browser is
325
- then redirected with only `client_id` and the returned `request_uri`.
251
+ [PAR (RFC 9126)](https://www.rfc-editor.org/rfc/rfc9126.html) sends authorization parameters to the provider before navigating the browser.
326
252
 
327
- If the PAR endpoint returns an error or an invalid response, the login rejects
328
- with `PushedAuthorizationRequestError`; the client does not silently downgrade
329
- to a front-channel request. The error exposes a stable `code` and, when
330
- available, `status`, `oauthError`, and `oauthErrorDescription`.
253
+ | `par` mode | Behavior |
254
+ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
255
+ | `'disabled'` (default) | Uses the normal front-channel request and ignores PAR metadata. |
256
+ | `'auto'` | Uses a discovered or configured `pushed_authorization_request_endpoint`. Falls back only when no endpoint exists and the server does not require PAR. |
257
+ | `'required'` | Requires a PAR endpoint; fails before navigation if none is available. |
331
258
 
332
- For a browser-based client, the authorization server must allow CORS requests
333
- from the application origin to its PAR endpoint. Public SPA clients must also
334
- be allowed to call PAR without a client secret; never embed a client secret in
335
- browser code. If discovery is not available, set
336
- `pushed_authorization_request_endpoint` (and optionally
337
- `require_pushed_authorization_requests`) in `authority_configuration`.
259
+ If metadata says `require_pushed_authorization_requests: true`, `'auto'` also fails when the endpoint is missing. Set `par_request_timeout` to adjust the default 10-second timeout.
338
260
 
339
- ## API
261
+ Once PAR is selected, the client sends authorization parameters (including state, nonce, PKCE, and login extras) as `application/x-www-form-urlencoded` data. The subsequent browser redirect carries `client_id` and the returned `request_uri`. An endpoint failure or invalid response **never silently downgrades** to the front-channel flow.
340
262
 
341
- ```javascript
342
- /**
343
- * OidcClient is a class that acts as a wrapper around the `Oidc` object. It provides methods to handle event subscriptions, logins, logouts, token renewals, user information, etc.
344
- */
345
- export class OidcClient {
346
- /**
347
- * Creates an instance of OidcClient using a provided `Oidc` object.
348
- * @param oidc The instance of the underlying Oidc object to use.
349
- */
350
- constructor(oidc: Oidc);
351
-
352
- /**
353
- * Subscribes a function to events emitted by the underlying Oidc object.
354
- * @param func The function to be called when an event is emitted.
355
- * @returns A string that identifies the subscription and can be used to unsubscribe later.
356
- */
357
- subscribeEvents(func: EventSubscriber): string;
358
-
359
- /**
360
- * Removes a subscription to a specified event.
361
- * @param id The identifier of the subscription to remove, obtained during the initial subscription.
362
- */
363
- removeEventSubscription(id: string): void;
364
-
365
- /**
366
- * Publishes an event with the specified name and associated data.
367
- * @param eventName The name of the event to publish.
368
- * @param data The data associated with the event.
369
- */
370
- publishEvent(eventName: string, data: any): void;
371
-
372
- /**
373
- * Creates a new instance of OidcClient using a fetch retrieval function `getFetch`, with a given OIDC configuration and an optional name.
374
- * @param getFetch The function to retrieve the `Fetch` object.
375
- * @param configuration The OIDC configuration to use for creating the OidcClient instance.
376
- * @param name The optional name for the created OidcClient instance.
377
- * @returns A new instance of OidcClient with the specified configuration.
378
- */
379
- static getOrCreate(getFetch: () => Fetch)(configuration: OidcConfiguration, name?: string): OidcClient;
380
-
381
- /**
382
- * Retrieves an existing OidcClient instance with the specified name.
383
- * Since issue #1679, this returns `null` when no instance has been
384
- * initialized for the given name (instead of throwing). Use
385
- * `OidcClient.getOrThrow` to preserve the previous fail-fast behaviour.
386
- * @param name The name of the OidcClient instance to retrieve.
387
- * @returns The existing OidcClient instance, or null if none exists.
388
- */
389
- static get(name?: string): OidcClient | null;
390
-
391
- /**
392
- * Same as `OidcClient.get` but throws an explicit error when no instance
393
- * has been initialized for the given name. Useful when you want to fail
394
- * fast on misconfiguration.
395
- * @param name The name of the OidcClient instance to retrieve.
396
- * @returns The existing OidcClient instance.
397
- */
398
- static getOrThrow(name?: string): OidcClient;
399
-
400
- /**
401
- * The names of the events supported by the Oidc class.
402
- */
403
- static eventNames: Oidc.eventNames;
404
-
405
- /**
406
- * Attempts to keep the existing user session by calling the function of the underlying Oidc object.
407
- * @returns A promise resolved with `true` if the user session was kept, otherwise `false`.
408
- */
409
- tryKeepExistingSessionAsync(): Promise<boolean>;
410
-
411
- /**
412
- * Starts the OIDC login process with specified options.
413
- * @param callbackPath The callback path for authentication.
414
- * @param extras Additional parameters to send to the OIDC server during the login request.
415
- * @param isSilentSignin Indicates if the login is silent.
416
- * @param scope The OIDC scope for the login request.
417
- * @param silentLoginOnly Indicates if only silent login is allowed.
418
- * @returns A promise resolved with the login information, or rejected with an error.
419
- */
420
- loginAsync(callbackPath?: string, extras?: StringMap, isSilentSignin?: boolean, scope?: string, silentLoginOnly?: boolean): Promise<unknown>;
421
-
422
- /**
423
- * Starts the OIDC logout process with specified options.
424
- * @param callbackPathOrUrl The callback path or URL to use after logout.
425
- * @param extras Additional parameters to send to the OIDC server during the logout request.
426
- * {"no_reload:oidc":"true"} to avoid the page reload after logout.
427
- * you can add extras like {"client_secret:revoke_refresh_token":"secret"} to revoke the refresh token with extra client secret. Any key ending with ":revoke_refresh_token" will be used to revoke the refresh token.
428
- * you can add extras like {"client_secret:revoke_access_token":"secret"} to revoke the access token with extra client secret. Any key ending with ":revoke_access_token" will be used to revoke the access token.
429
- * @returns A promise resolved when the logout is completed.
430
- */
431
- logoutAsync(callbackPathOrUrl?: string | null | undefined, extras?: StringMap): Promise<void>;
432
-
433
- /**
434
- * Performs the silent login process and retrieves user information.
435
- * @returns A promise resolved when the silent login process is completed.
436
- */
437
- silentLoginCallbackAsync(): Promise<void>;
438
-
439
- /**
440
- * Renews the user's OIDC tokens.
441
- * @param extras Additional parameters to send to the OIDC server during the token renewal request.
442
- * @returns A promise resolved when the token renewal is completed.
443
- */
444
- renewTokensAsync(extras?: StringMap): Promise<void>;
445
-
446
- /**
447
- * Performs the callback process after a successful login and automatically renews tokens.
448
- * @returns A promise resolved with the callback information, or rejected with an error.
449
- */
450
- loginCallbackAsync(): Promise<LoginCallback>;
451
-
452
- /**
453
- * Retrieves the current OIDC tokens for the user.
454
- */
455
- get tokens(): Tokens;
456
-
457
- /**
458
- * Retrieves the current OIDC configuration used by the OidcClient instance.
459
- */
460
- get configuration(): OidcConfiguration;
461
-
462
- /**
463
- * Retrieves the valid OIDC token for the user.
464
- * @param waitMs The maximum wait time in milliseconds to obtain a valid token.
465
- * @param numberWait The number of attempts to obtain a valid token.
466
- * @returns A promise resolved with the valid token, or rejected with an error.
467
- */
468
- async getValidTokenAsync(waitMs = 200, numberWait = 50): Promise<ValidToken>;
469
-
470
- /**
471
- * Retrieves a new fetch function that inject bearer tokens (also DPOP tokens).
472
- * @param fetch The current fetch function to use
473
- * @param demonstrating_proof_of_possession Indicates whether the demonstration of proof of possession should be used.
474
- * @returns Fetch A new fectch function that inject bearer tokens (also DPOP tokens).
475
- */
476
- fetchWithTokens(fetch: Fetch, demonstrating_proof_of_possession=false): Fetch;
477
-
478
- /**
479
- * Retrieves OIDC user information.
480
- * @param noCache Indicates whether user information should be retrieved bypassing the cache.
481
- * @param demonstrating_proof_of_possession Indicates whether the demonstration of proof of possession should be used.
482
- * @returns A promise resolved with the user information, or rejected with an error.
483
- */
484
- async userInfoAsync<T extends OidcUserInfo = OidcUserInfo>(noCache = false, demonstrating_proof_of_possession=false): Promise<T>;
485
-
486
- /**
487
- * Generate Demonstration of proof of possession.
488
- * @param accessToken The access token to use.
489
- * @param url The url to use.
490
- * @param method The method to use.
491
- * @param extras Additional parameters to send to the OIDC server during the demonstration of proof of possession request.
492
- * @returns A promise resolved with the proof of possession.
493
- */
494
- async generateDemonstrationOfProofOfPossessionAsync(accessToken:string, url:string, method:string, extras:StringMap= {}): Promise<string>;
495
- }
263
+ Failures use `PushedAuthorizationRequestError`, with codes from `PushedAuthorizationRequestErrorCode`: `ENDPOINT_UNAVAILABLE`, `REQUEST_FAILED`, or `INVALID_RESPONSE`. Use `isPushedAuthorizationRequestError(error)` and inspect `code`, plus `status`, `oauthError`, and `oauthErrorDescription` when available.
496
264
 
497
- ```
265
+ The PAR endpoint must allow CORS from your application and accept public clients without a client secret. If discovery is unavailable, configure `pushed_authorization_request_endpoint` and, where applicable, `require_pushed_authorization_requests` in `authority_configuration`.
498
266
 
499
- ## Run The Demo
267
+ ## DPoP
500
268
 
501
- ```sh
502
- git clone https://github.com/AxaFrance/oidc-client.git
503
- cd oidc-client
269
+ [Demonstrating Proof of Possession (RFC 9449)](https://www.rfc-editor.org/rfc/rfc9449.html) binds supported tokens to a key and uses signed proofs for requests. It requires support from the authorization server and resource server. It reduces the usefulness of a stolen token without its key; it does not make an application immune to XSS.
504
270
 
505
- # oidc client demo
506
- cd /examples/oidc-client-demo
507
- pnpm install
508
- pnpm start
509
- # then navigate to http://localhost:5174
271
+ For client-side DPoP, set `demonstrating_proof_of_possession: true` in the OIDC configuration and opt in for protected requests:
510
272
 
273
+ ```javascript
274
+ const dpopFetch = oidcClient.fetchWithTokens(fetch, true);
275
+ const response = await dpopFetch('https://api.example.com/profile', { method: 'GET' });
511
276
  ```
512
277
 
513
- ## Strongly typed OIDC errors
278
+ Similarly, pass `true` as the second argument to `userInfoAsync(false, true)` if the user-info endpoint requires DPoP. For worker-side DPoP, configure `demonstratingProofOfPossession` in the matching trusted-domain entry and review `demonstratingProofOfPossessionOnlyWhenDpopHeaderPresent`.
279
+
280
+ The default cryptographic configuration uses ECDSA P-256, SHA-256, and the `ES256` JWT algorithm. Override algorithms through `demonstrating_proof_of_possession_configuration` (client) or `demonstratingProofOfPossessionConfiguration` (worker). See [`DemonstratingProofOfPossessionConfiguration`](./src/types.ts).
514
281
 
515
- Known authentication, callback, refresh and network failures are exposed as
516
- `OidcError`. Its stable `code` and `phase` fields can be inspected without
517
- matching the human-readable `message`; existing messages remain unchanged.
282
+ ## API
518
283
 
519
- ```ts
284
+ See [`OidcClient`](./src/oidcClient.ts) for full TypeScript signatures.
285
+
286
+ | API | Use |
287
+ | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
288
+ | `OidcClient.getOrCreate(getFetch, location?)(configuration, name?)` | Create or reuse a named client. Pass `() => fetch` for the browser fetch implementation; the default name is `'default'`. |
289
+ | `OidcClient.get(name?)` | Retrieve an existing client, or `null` if it has not been initialized. |
290
+ | `OidcClient.getOrThrow(name?)` | Retrieve an existing client, or throw on missing initialization. |
291
+ | `tryKeepExistingSessionAsync()` | Restore an existing session; returns whether it was kept. |
292
+ | `loginAsync(callbackPath?, extras?, isSilentSignin?, scope?, silentLoginOnly?)` | Start authentication. `callbackPath` is the application destination after the callback, not the registered `redirect_uri`. |
293
+ | `loginCallbackAsync()` | Complete interactive authentication, start automatic renewal, and return `{ callbackPath }`. |
294
+ | `silentLoginCallbackAsync()` | Complete the iframe silent-login callback. |
295
+ | `logoutAsync(callbackPathOrUrl?, extras?)` | Clear the session, revoke configured tokens, and use the provider's logout endpoint when available. |
296
+ | `clearSessionAsync()` | Clear the local session without provider logout or token revocation. |
297
+ | `isLoggingOut` | Indicates logout is in progress; avoid starting a competing login flow. |
298
+ | `renewTokensAsync(extras?, scope?)` | Request token renewal. |
299
+ | `renewTokensOrThrowAsync(extras?, scope?)` | Request renewal with a rejected promise on failure. |
300
+ | `getValidTokenAsync(waitMs?, numberWait?)` | Wait for usable tokens; also supports on-demand renewal. |
301
+ | `fetchWithTokens(fetch, demonstratingProofOfPossession?)` | Wrap fetch for protected API requests. |
302
+ | `userInfoAsync<T>(noCache?, demonstratingProofOfPossession?)` | Load user information, optionally bypassing the cache. |
303
+ | `userInfo<T>()` | Read cached user information. |
304
+ | `tokens`, `configuration` | Inspect current session data and effective configuration. Tokens can contain worker placeholders; do not display or log them. |
305
+ | `subscribeEvents(handler)` | Subscribe to `(eventName, data)` and receive a subscription ID. |
306
+ | `removeEventSubscription(id)` | Remove an event subscription. |
307
+ | `OidcClient.eventNames` | Discover supported event names. |
308
+ | `publishEvent(name, data)` | Publish an event to the client's subscribers. |
309
+ | `generateDemonstrationOfProofOfPossessionAsync(accessToken, url, method, extras?)` | Low-level proof generation; prefer the fetch wrapper for normal requests. |
310
+ | `signalServiceWorker(message, options?)` | Send a typed worker-protocol message. |
311
+
312
+ You can inject a custom location adapter as the second argument to `getOrCreate`, using the exported `ILOidcLocation` interface and `OidcLocation` implementation.
313
+
314
+ ## Errors and events
315
+
316
+ Known authentication, callback, renewal, and network failures use `OidcError`. Inspect stable `code` and `phase` fields rather than parsing messages. Other fields include `retryable`, optional `status`, `oauthError`, `oauthErrorDescription`, and `cause`.
317
+
318
+ ```typescript
520
319
  import { OidcError, OidcErrorCode } from '@axa-fr/oidc-client';
521
320
 
522
321
  try {
523
- await oidcClient.loginCallbackAsync();
322
+ await oidcClient.renewTokensOrThrowAsync();
524
323
  } catch (error) {
525
324
  if (error instanceof OidcError && error.code === OidcErrorCode.LOGIN_REQUIRED) {
526
- await oidcClient.loginAsync();
325
+ await oidcClient.loginAsync('/');
326
+ } else {
327
+ throw error;
527
328
  }
528
329
  }
529
330
  ```
530
331
 
531
- Automatic renewal and the existing `renewTokensAsync` method remain
532
- non-throwing for terminal OIDC failures. Use the strict variant when the caller
533
- needs a rejected promise:
332
+ `retryable` means a retry without user interaction may succeed, not that one is always performed automatically. Network failures, HTTP 408/429/5xx responses, and DPoP nonce challenges can be retryable; `LOGIN_REQUIRED` needs an interactive login.
534
333
 
535
- ```ts
536
- try {
537
- const tokens = await oidcClient.renewTokensOrThrowAsync();
538
- } catch (error) {
539
- if (error instanceof OidcError) {
540
- console.error(error.code, error.phase, error.retryable);
541
- }
542
- }
543
- ```
334
+ Non-throwing flows also expose errors through events. Refresh event payloads include an `error` field; user-info, logout, and protected API requests have dedicated error events. Log only selected diagnostic fields, not complete event payloads:
544
335
 
545
- Failures from intentionally non-throwing flows are also provided to event
546
- subscribers. Existing event payload fields are preserved; refresh payloads add
547
- an `error` field, while user-info, logout and protected API failures use their
548
- dedicated error events.
549
-
550
- ```ts
551
- oidcClient.subscribeEvents((name, data) => {
336
+ ```typescript
337
+ const subscriptionId = oidcClient.subscribeEvents((name, data) => {
552
338
  const error = data instanceof OidcError ? data : data?.error;
553
339
  if (error instanceof OidcError) {
554
- console.error(name, error.code, error.status);
340
+ console.warn(name, error.code, error.phase, error.status);
555
341
  }
556
342
  });
343
+
344
+ // When the subscriber is no longer needed:
345
+ oidcClient.removeEventSubscription(subscriptionId);
557
346
  ```
558
347
 
559
- `retryable` means that retrying automatically, without user interaction, may
560
- succeed. For example, network failures, HTTP 408/429/5xx responses and DPoP
561
- nonce challenges are retryable; `login_required` requires an interactive
562
- login and is therefore not.
348
+ ### Missing or mismatched login state
563
349
 
564
- ## Handling missing or corrupted login state
350
+ `OidcStateError` extends `OidcError` and identifies callback-state failures:
565
351
 
566
- When the OIDC state or nonce is missing from storage at callback time (for
567
- example because the user is in a private browsing tab, cleared storage
568
- manually, or because the browser evicted the entry between the authorize
569
- redirect and the callback), the library now throws a typed
570
- `OidcStateError` instead of letting a generic `TypeError` escape.
352
+ - `OidcStateErrorCode.STATE_MISSING`: stored authorization state is missing.
353
+ - `OidcStateErrorCode.STATE_MISMATCH`: returned state does not match stored state.
354
+ - `OidcStateErrorCode.NONCE_MISSING`: stored nonce is missing.
571
355
 
572
- ```ts
573
- import { isOidcStateError, OidcStateError, OidcStateErrorCode } from '@axa-fr/oidc-client';
356
+ Use `isOidcStateError(error)` and inspect `error.code`, especially for errors passed through silent-login handling. Storage clearing, eviction, and competing login attempts can cause these failures. Do not bypass state or nonce checks; offer a fresh login. During silent renewal, a missing nonce is reported through the session-lost flow.
574
357
 
575
- try {
576
- await oidcClient.loginCallbackAsync();
577
- } catch (error) {
578
- if (isOidcStateError(error)) {
579
- switch (error.code) {
580
- case OidcStateErrorCode.STATE_MISSING:
581
- // The stored state was not found at callback time.
582
- break;
583
- case OidcStateErrorCode.STATE_MISMATCH:
584
- // The state returned by the server does not match the stored one.
585
- break;
586
- case OidcStateErrorCode.NONCE_MISSING:
587
- // The stored nonce was not found at callback time.
588
- break;
589
- }
590
- }
591
- }
358
+ ## Named configurations and routing
359
+
360
+ Use distinct names for separate providers or sessions with different scopes:
361
+
362
+ ```javascript
363
+ const paymentsClient = OidcClient.getOrCreate(() => fetch)(paymentsConfiguration, 'payments');
364
+ const existingClient = OidcClient.get('payments');
592
365
  ```
593
366
 
594
- `OidcStateError` is an `Error` subclass, exposes a stable `code` field, and is
595
- also re-exported from `@axa-fr/react-oidc`. When errors cross the silent-renew
596
- iframe boundary, prefer `isOidcStateError(error)` plus `error.code` over a
597
- plain `instanceof` check. For silent renewal, a missing nonce no longer throws
598
- a `TypeError` — it is reported through the existing `SESSION_LOST` status so
599
- consumers can recover via the normal re-login flow.
600
-
601
- ## Service worker protocol
602
-
603
- The `postMessage` protocol used between `OidcClient` and the service worker
604
- is publicly documented and versioned. Typed message constants, payload
605
- helpers and storage key conventions are exported from
606
- `@axa-fr/oidc-client` (and from
607
- `@axa-fr/oidc-client-service-worker/protocol`):
608
-
609
- ```ts
610
- import {
611
- OidcClient,
612
- PROTOCOL_VERSION,
613
- ServiceWorkerMessageType,
614
- buildSecuredTokenPlaceholder,
615
- TOKEN_PLACEHOLDERS,
616
- } from '@axa-fr/oidc-client';
617
-
618
- const oidcClient = OidcClient.get();
619
-
620
- const { state } = await oidcClient.signalServiceWorker<{ state: string }>({
367
+ Each name reuses its initialized configuration. Give configurations distinct callback routes and matching keys in `OidcTrustedDomains.js`.
368
+
369
+ The library retains hash-route callback matching for legacy integrations. However, OAuth redirect URIs must not contain a fragment: use path-based callback URLs, as in the quick start, for new deployments. Existing hash-callback setups depend on provider-specific behavior and need matching application routing. Interactive and silent callback URLs must be different.
370
+
371
+ ## Service-worker protocol
372
+
373
+ The worker's versioned `postMessage` protocol is documented in [`PROTOCOL.md`](../oidc-client-service-worker/PROTOCOL.md). Constants and helpers such as `PROTOCOL_VERSION`, `ServiceWorkerMessageType`, `TOKEN_PLACEHOLDERS`, and `buildSecuredTokenPlaceholder` are exported from `@axa-fr/oidc-client` and `@axa-fr/oidc-client-service-worker/protocol`.
374
+
375
+ ```typescript
376
+ import { OidcClient, ServiceWorkerMessageType } from '@axa-fr/oidc-client';
377
+
378
+ const client = OidcClient.getOrThrow();
379
+ const result = await client.signalServiceWorker<{ state: string }>({
621
380
  type: ServiceWorkerMessageType.GET_STATE,
622
381
  configurationName: 'default',
623
382
  data: null,
624
383
  });
625
384
  ```
626
385
 
627
- See [`PROTOCOL.md`](../oidc-client-service-worker/PROTOCOL.md) in the
628
- service-worker package for the full specification, including stability
629
- guarantees and per-message payload shapes.
386
+ This requires an active worker. See the protocol reference for payloads, timeouts, and compatibility guarantees; avoid logging protocol responses containing session state.
630
387
 
631
- ## How It Works
388
+ ## Examples and further reading
632
389
 
633
- This component is a pure vanilla JS OIDC client library agnostic to any framework.
634
- It is a real alternative to existing oidc-client libraries.
390
+ - [Vanilla JavaScript demo](../../examples/oidc-client-demo/README.md) — complete application and local development instructions.
391
+ - [React guide](../react-oidc/README.md) and [React demo](../../examples/react-oidc-demo/README.md).
392
+ - [FAQ and deployment guidance](../../FAQ.md).
393
+ - [Service-worker source and protocol](../oidc-client-service-worker/PROTOCOL.md).
394
+ - [Service-worker package guide](../oidc-client-service-worker/README.md).
635
395
 
636
- More information about OIDC
637
-
638
- - [French : Augmentez la sécurité et la simplicité de votre Système d’Information OpenID Connect](https://medium.com/just-tech-it-now/augmentez-la-s%C3%A9curit%C3%A9-et-la-simplicit%C3%A9-de-votre-syst%C3%A8me-dinformation-avec-oauth-2-0-cf0732d71284)
639
- - [English : Increase the security and simplicity of your information system with openid connect](https://medium.com/just-tech-it-now/increase-the-security-and-simplicity-of-your-information-system-with-openid-connect-fa8c26b99d6d)
640
- - [English: youtube OIDC](https://www.youtube.com/watch?v=frIJfavZkUE&list=PL8EMdIH6Mzxy2kHtsVOEWqNz-OaM_D_fB&index=1)
641
- - [French: youtube OIDC](https://www.youtube.com/watch?v=H-mLMGzQ_y0&list=PL8EMdIH6Mzxy2kHtsVOEWqNz-OaM_D_fB&index=2)
642
-
643
- ## Hash route
644
-
645
- `@axa-fr/oidc-client` work also with hash route.
646
-
647
- ```javascript
648
- export const configurationIdentityServerWithHash = {
649
- client_id: 'interactive.public.short',
650
- redirect_uri: window.location.origin + '#authentication-callback',
651
- silent_redirect_uri: window.location.origin + '#authentication-silent-callback',
652
- scope: 'openid profile email api offline_access',
653
- authority: 'https://demo.duendesoftware.com',
654
- par: 'auto',
655
- refresh_time_before_tokens_expiration_in_second: 70,
656
- service_worker_relative_url: '/OidcServiceWorker.js',
657
- service_worker_only: false,
658
- };
659
- ```
396
+ The demos belong to the pnpm monorepo. Follow their READMEs rather than installing each workspace independently.