ark-oauth-client-js 0.0.0-stage → 2.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,56 @@
1
+ # Changelog
2
+
3
+ ## 2.1.1
4
+
5
+ The first release of the browser client, at the version the .NET, Python and Node clients carry.
6
+ It is the fourth port in the family: the same names wherever the concepts are shared (`TokenSet`,
7
+ `ArkOAuthError`, `accountSwitch`, `ArkChallengeProperties`, `checkSetup()`), for single-page apps
8
+ that sign in from the browser.
9
+
10
+ **The client.** `ArkBrowserClient`, framework-agnostic, with no runtime dependencies.
11
+
12
+ * Authorization code + PKCE (S256) as a public client, by redirect or popup. `state` is per tab,
13
+ single use and compared in constant time; `iss` is checked (RFC 9207).
14
+ * The ID token is verified in the browser with Web Crypto: signature (RS/PS/ES), issuer,
15
+ audience, `azp`, times, `nonce`, `at_hash`, `c_hash`, `max_age`, and the same `sub` on refresh.
16
+ JWKS rotation is followed, with a rate-limited refetch for an unknown `kid`.
17
+ * Rotating refresh tokens renew the session before expiry, or half-way through a short token's
18
+ life. Ark revokes the whole family on a replay, so the client never presents a spent token:
19
+ * refreshes are serialised across tabs (Web Locks) and across instances on one page, which
20
+ re-read storage first;
21
+ * a rotated token is stored before the response is validated;
22
+ * a duplicated tab recognises a refresh token its twin has already redeemed, from hashes kept in
23
+ localStorage.
24
+ * `fetch()` attaches the bearer token to the app's origin and `apiOrigins` only, and retries a 401
25
+ once after a refresh.
26
+ * `signoutRedirect()` revokes and ends the provider session with `id_token_hint`, so there is no
27
+ confirmation page. `signoutLocal()` ends only this app's session. Other tabs are signed out too.
28
+ * Account switching, off by default as in the other clients: `accountSwitch.requireArkClaims` and
29
+ `requiredClaims` refuse an account at the callback without storing a token. `switchUser()`
30
+ signs in with `prompt=login`. `renderAccessDenied()` draws the dead end, with CSP-safe DOM.
31
+ * `checkSetup()` proves CORS from the page: it fetches discovery and JWKS and sends a harmless
32
+ token-endpoint probe.
33
+ * Safe to create during server-side rendering. Nothing touches `window` until `init()`.
34
+ `isBrowser` tells the two apart. The Angular and Vue route guards cancel on the server instead
35
+ of starting a sign-in, and the Angular one names the fix (`RenderMode.Client`) once.
36
+ * Configuration that a browser cannot use safely is refused when the client is created: a client
37
+ secret, `private_key_jwt`, PAR, `form_post` and a plain-http authority. The error explains why.
38
+
39
+ **Adapters.**
40
+
41
+ * `ark-oauth-client-js/react`: `ArkProvider`, `useArk`, `useArkUser`, `RequireArk`,
42
+ `ArkCallback`, `ArkAccessDenied`. React 18/19, StrictMode and SSR safe.
43
+ * `ark-oauth-client-js/next`: the React adapter plus `ArkNextProvider` (App Router navigation).
44
+ * `ark-oauth-client-js/vue`: `createArk` plugin, `useArk` composable and the `createArkGuard`
45
+ router guard.
46
+ * `ark-oauth-client-js/angular`: `provideArk`, `injectArk` (signals), `arkAuthGuard`,
47
+ `arkClaimsGuard`, `createArkGuard` and `arkInterceptor`. Angular 16+, no compilation step.
48
+ * `client.state` is a Svelte store. `subscribe` / `getSnapshot` serve every other framework.
49
+ * `dist/ark-oauth-client.global.min.js` provides `window.ArkOAuth` for a plain `<script>` tag.
50
+
51
+ **Server behaviour this client is built around**, all checked against `Ark.oAuth.Oidc`:
52
+
53
+ * CORS is granted on discovery, JWKS, token and userinfo only. Revocation is therefore sent
54
+ `no-cors`, and PAR is unavailable.
55
+ * `/authorize` sends `frame-ancestors 'self'`, so renewal uses refresh tokens, not hidden iframes.
56
+ * `id_token_hint` is accepted past ID-token expiry, so sign-out keeps the last one.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Immanuel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,579 @@
1
- # Temporary Holding Version
1
+ # ark-oauth-client-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The OpenID Connect client for **browser apps** signing in against an
4
+ [ARK Identity Server](../README.md): React, Next.js, Vue, Angular, Svelte, or plain JavaScript.
5
+
6
+ One framework-agnostic client does the protocol; thin adapters bind it to each framework. There
7
+ are two settings, the issuer (`{BaseUrl}/{TenantId}`) and the client id. Endpoints and signing keys
8
+ come from the provider's discovery document, so nothing is rebuilt when a key rotates.
9
+
10
+ No runtime dependencies: Web Crypto, `fetch`, Web Storage, BroadcastChannel and Web Locks.
11
+
12
+ ```bash
13
+ npm install ark-oauth-client-js
14
+ ```
15
+
16
+ It is the browser sibling of `ark-oauth-client` (Node), `ark-oauth-client` (Python) and
17
+ `Ark.oAuth.Client` (.NET), carries the same version number, and uses the same names wherever the
18
+ concepts are shared (`TokenSet`, `ArkOAuthError`, `accountSwitch`, `checkSetup()`, ...).
19
+
20
+ ---
21
+
22
+ ## Contents
23
+
24
+ - [Before you start: register the app](#before-you-start-register-the-app)
25
+ - [Quick start (plain JavaScript)](#quick-start-plain-javascript)
26
+ - [React](#react) · [Next.js](#nextjs) · [Vue](#vue) · [Angular](#angular) · [Svelte, Solid and the rest](#svelte-solid-and-the-rest) · [A plain `<script>` tag](#a-plain-script-tag)
27
+ - [The state and events](#the-state-and-events)
28
+ - [Signing in](#signing-in)
29
+ - [Calling your API](#calling-your-api)
30
+ - [Signing out](#signing-out)
31
+ - [Account switching on a shared browser](#account-switching-on-a-shared-browser)
32
+ - [Configuration](#configuration)
33
+ - [Where tokens live, and how the session is renewed](#where-tokens-live-and-how-the-session-is-renewed)
34
+ - [Checking the setup](#checking-the-setup)
35
+ - [Errors](#errors)
36
+ - [Troubleshooting](#troubleshooting)
37
+ - [What it implements](#what-it-implements)
38
+ - [Development](#development)
39
+
40
+ ---
41
+
42
+ ## Before you start: register the app
43
+
44
+ A browser app is a **public client**: it has no secret (anything in a bundle is readable by every
45
+ visitor), and PKCE protects its authorization code instead. On the Ark tenant (admin console →
46
+ Clients, or the provisioning API):
47
+
48
+ | Setting | Value |
49
+ |---|---|
50
+ | Token endpoint auth method | `none` (public client) |
51
+ | Grant types | `authorization_code`, `refresh_token` |
52
+ | Redirect URI | `https://your.app/signin-oidc`, **byte for byte** what the app sends |
53
+ | Post-logout redirect URI | `https://your.app/signout-callback-oidc` |
54
+ | Scopes | `openid profile email offline_access` (`offline_access` is what produces a refresh token) |
55
+
56
+ Then two things on the server that cost real time when they are missed:
57
+
58
+ 1. **CORS.** The app redeems its code from the browser, so the provider must list the app's origin
59
+ in `ark_oauth_server:Oidc:CorsOrigins` (the setup wizard's Protocol step), e.g.
60
+ `"CorsOrigins": ["https://your.app"]`. Without it every token request dies in the browser as
61
+ `Failed to fetch`. [`checkSetup()`](#checking-the-setup) tells you if it is missing.
62
+ 2. **Map the user to the client.** Ark maps users to clients explicitly; with no mapping the sign-in
63
+ fails with something that reads like a wrong password. The claims you give the mapping arrive
64
+ as `ark_claims`, which is what you authorise against.
65
+
66
+ The callback paths are the Ark defaults, and are relative to the page's origin unless you give
67
+ absolute URLs. A single-page app needs its host to answer `/signin-oidc` and
68
+ `/signout-callback-oidc` with the app (history fallback, which Vite, Next.js, Angular CLI and
69
+ every SPA host do).
70
+
71
+ ---
72
+
73
+ ## Quick start (plain JavaScript)
74
+
75
+ ```js
76
+ import { ArkBrowserClient } from 'ark-oauth-client-js';
77
+
78
+ const ark = new ArkBrowserClient({
79
+ authority: 'https://idp.example.com/my_idp', // the issuer: {BaseUrl}/{TenantId}
80
+ clientId: 'my-spa'
81
+ });
82
+
83
+ ark.subscribe((state) => {
84
+ // state.status: 'loading' | 'authenticated' | 'unauthenticated' | 'denied'
85
+ document.querySelector('#who').textContent = state.isAuthenticated ? state.user.email : 'signed out';
86
+ });
87
+
88
+ document.querySelector('#sign-in').onclick = () => ark.signinRedirect();
89
+ document.querySelector('#sign-out').onclick = () => ark.signoutRedirect();
90
+
91
+ await ark.init(); // completes /signin-oidc, or restores the session from the last visit
92
+
93
+ const orders = await (await ark.fetch('/api/orders')).json(); // bearer token attached, refreshed when due
94
+ ```
95
+
96
+ `init()` is the one call every app makes once at start-up. On the redirect URI it finishes the
97
+ sign-in and sends the user back to the page they started from; anywhere else it restores the
98
+ stored session, refreshing it if the access token expired while the page was closed. It never
99
+ rejects: failures land in `state.error`.
100
+
101
+ [`examples/vanilla`](examples/vanilla) is a complete app with no build step:
102
+ `ARK_AUTHORITY=… ARK_CLIENT_ID=… node examples/serve.mjs`.
103
+
104
+ ---
105
+
106
+ ## React
107
+
108
+ ```jsx
109
+ // ark.js, module scope: one client for the app
110
+ import { ArkBrowserClient } from 'ark-oauth-client-js';
111
+ export const ark = new ArkBrowserClient({ authority: import.meta.env.VITE_ARK_AUTHORITY, clientId: import.meta.env.VITE_ARK_CLIENT_ID });
112
+ ```
113
+
114
+ ```jsx
115
+ import { ArkProvider, ArkCallback, RequireArk, useArk } from 'ark-oauth-client-js/react';
116
+ import { BrowserRouter, Routes, Route, useNavigate } from 'react-router';
117
+
118
+ function AuthRoot() {
119
+ const navigate = useNavigate(); // the return after sign-in goes through the router
120
+ return (
121
+ <ArkProvider client={ark} onRedirectCallback={(to) => navigate(to, { replace: true })}>
122
+ <Routes>
123
+ <Route path="/" element={<Home />} />
124
+ <Route path="/billing" element={<RequireArk claims={['billing.admin']} fallback={<Spinner />}><Billing /></RequireArk>} />
125
+ <Route path="/signin-oidc" element={<ArkCallback><Spinner /></ArkCallback>} />
126
+ </Routes>
127
+ </ArkProvider>
128
+ );
129
+ }
130
+
131
+ function Home() {
132
+ const { isAuthenticated, user, signinRedirect, signoutRedirect } = useArk();
133
+ return isAuthenticated
134
+ ? <button onClick={() => signoutRedirect()}>Sign out {user.email}</button>
135
+ : <button onClick={() => signinRedirect()}>Sign in</button>;
136
+ }
137
+ ```
138
+
139
+ - `useArk()` returns the [state](#the-state-and-events) plus `signinRedirect`, `signinPopup`,
140
+ `signoutRedirect`, `signoutLocal`, `switchUser`, `getAccessToken`, `fetch`, `hasArkClaims`,
141
+ `hasAnyArkClaim` and the `client`. `useArkUser()` re-renders only when the user changes.
142
+ - `<RequireArk>` renders its children for a signed-in user (holding `claims` / `anyClaims`), starts
143
+ the sign-in for a signed-out one, shows `fallback` meanwhile, and shows `<ArkAccessDenied>` (the
144
+ account-switch page) to a user missing a claim. After a failed sign-in it shows the error with a
145
+ retry instead of signing in again, so a misconfigured client cannot loop.
146
+ - `<ArkCallback>` is the element for the redirect URI's route: a single-page app needs a route
147
+ there or its router shows "not found" during the exchange. (A *server-side* client must not have
148
+ one, because it would shadow the handler; in a SPA the provider does the work and the route only
149
+ renders progress.)
150
+ - React 18 and 19, StrictMode-safe (start-up is idempotent), SSR-safe.
151
+
152
+ [`examples/react-vite`](examples/react-vite) is a complete Vite + React Router app.
153
+
154
+ ## Next.js
155
+
156
+ `ark-oauth-client-js/next` is the React adapter plus `<ArkNextProvider>`, which returns the user
157
+ through `next/navigation` after sign-in. App Router:
158
+
159
+ ```tsx
160
+ // lib/ark.ts: safe to import from server code; on the server the state is always 'loading'
161
+ export const ark = new ArkBrowserClient({ authority: process.env.NEXT_PUBLIC_ARK_AUTHORITY!, clientId: process.env.NEXT_PUBLIC_ARK_CLIENT_ID! });
162
+
163
+ // app/providers.tsx
164
+ 'use client';
165
+ import { ArkNextProvider } from 'ark-oauth-client-js/next';
166
+ export default function Providers({ children }) { return <ArkNextProvider client={ark}>{children}</ArkNextProvider>; }
167
+
168
+ // app/layout.tsx (server component): <body><Providers>{children}</Providers></body>
169
+
170
+ // app/signin-oidc/page.tsx
171
+ 'use client';
172
+ import { ArkCallback } from 'ark-oauth-client-js/next';
173
+ export default function Callback() { return <ArkCallback><p>Signing you in…</p></ArkCallback>; }
174
+ ```
175
+
176
+ Every component that calls `useArk()` is a client component (`'use client'`). The client is never
177
+ created per request and holds no state on the server, so there is nothing to leak between users;
178
+ the server render and the first browser render both show `loading`, so hydration matches. Use
179
+ `<ArkProvider onRedirectCallback={(to) => router.push(to)}>` with `next/router` on the Pages Router.
180
+ [`examples/nextjs`](examples/nextjs) is a complete App Router app (it builds and prerenders with
181
+ `next build`).
182
+
183
+ Signing in happens in the browser; the access token is not available to server components or
184
+ route handlers. If your Next.js server itself must call APIs as the user, use a server-side
185
+ client (`ark-oauth-client` for Node) behind the app instead.
186
+
187
+ ## Vue
188
+
189
+ ```js
190
+ import { createApp } from 'vue';
191
+ import { createArk, createArkGuard } from 'ark-oauth-client-js/vue';
192
+
193
+ const ark = createArk({ authority: 'https://idp.example.com/my_idp', clientId: 'my-spa' });
194
+
195
+ createApp(App)
196
+ .use(router) // router first: ark finds it and returns the user through router.replace()
197
+ .use(ark)
198
+ .mount('#app');
199
+
200
+ router.beforeEach(createArkGuard(ark, { requireMeta: true })); // guards routes with meta.requiresAuth
201
+ // { path: '/billing', component: Billing, meta: { requiresAuth: true, arkClaims: ['billing.admin'] } }
202
+ ```
203
+
204
+ ```vue
205
+ <script setup>
206
+ import { useArk } from 'ark-oauth-client-js/vue';
207
+ const { isAuthenticated, user, signinRedirect, signoutRedirect } = useArk();
208
+ </script>
209
+
210
+ <template>
211
+ <button v-if="!isAuthenticated" @click="signinRedirect()">Sign in</button>
212
+ <button v-else @click="signoutRedirect()">Sign out {{ user.email }}</button>
213
+ </template>
214
+ ```
215
+
216
+ `useArk()` (or `$ark` in templates) gives computed refs (`status`, `isLoading`, `isAuthenticated`,
217
+ `user`, `arkClaims`, `scopes`, `error`, `denial`), the whole `state` as a shallow ref, and the
218
+ client's actions. Add a route for `/signin-oidc` that renders a "signing in" message. In Nuxt,
219
+ install the plugin from a client-only plugin file (`plugins/ark.client.ts`); on the server it
220
+ installs without starting, and the guard cancels rather than start a sign-in.
221
+ [`examples/vue`](examples/vue) is a complete Vite + vue-router app (it passes `vue-tsc` under `strict`).
222
+
223
+ ## Angular
224
+
225
+ Angular 16+, standalone or NgModule, with or without zone.js:
226
+
227
+ ```ts
228
+ // app.config.ts
229
+ import { provideArk, arkInterceptor } from 'ark-oauth-client-js/angular';
230
+
231
+ export const appConfig: ApplicationConfig = {
232
+ providers: [
233
+ provideArk({ authority: 'https://idp.example.com/my_idp', clientId: 'my-spa', apiOrigins: ['https://api.example.com'] }),
234
+ provideHttpClient(withInterceptors([arkInterceptor])), // bearer token on your API calls only
235
+ provideRouter(routes)
236
+ ]
237
+ };
238
+
239
+ // app.routes.ts
240
+ import { arkAuthGuard, arkClaimsGuard, createArkGuard } from 'ark-oauth-client-js/angular';
241
+ export const routes: Routes = [
242
+ { path: 'signin-oidc', component: SigningInComponent },
243
+ { path: 'orders', canActivate: [arkAuthGuard], component: OrdersComponent },
244
+ { path: 'billing', canActivate: [arkClaimsGuard('billing.admin')], component: BillingComponent },
245
+ { path: 'payroll', canActivate: [createArkGuard({ claims: ['payroll'], onDenied: () => inject(Router).parseUrl('/no-access') })], component: PayrollComponent }
246
+ ];
247
+ ```
248
+
249
+ ```ts
250
+ @Component({
251
+ selector: 'app-header',
252
+ template: `@if (ark.isAuthenticated()) { {{ ark.user()?.email }} <button (click)="ark.signoutRedirect()">Sign out</button> }
253
+ @else { <button (click)="ark.signinRedirect()">Sign in</button> }`
254
+ })
255
+ export class HeaderComponent {
256
+ ark = injectArk(); // signals: state(), status(), isAuthenticated(), user(), arkClaims(), error(), denial()
257
+ }
258
+ ```
259
+
260
+ `provideArk` starts the client in an app initializer, so the sign-in callback is complete, and the
261
+ address bar already shows the page the user started from, before the router reads the URL. The
262
+ interceptor sends the token only to the app's origin and `apiOrigins`, and retries a 401 once
263
+ after a refresh. The adapter is plain JavaScript with functional guards and `inject()`, so it needs
264
+ no Angular compilation step.
265
+
266
+ With SSR (`ng new --ssr`), render the guarded routes on the client, since who is signed in is
267
+ known only in the browser: `{ path: 'billing', renderMode: RenderMode.Client }` in
268
+ `app.routes.server.ts`. A guard that does run on the server cancels the navigation without starting
269
+ a sign-in, and says so once in the server log. Angular itself then reports a prerendered route as
270
+ "The content returned was empty". [`examples/angular`](examples/angular) is a complete standalone
271
+ app.
272
+
273
+ ## Svelte, Solid and the rest
274
+
275
+ The client is the integration. `client.state` is a Svelte store; `subscribe` / `getSnapshot` is
276
+ the contract every other framework's external-store hook takes.
277
+
278
+ ```svelte
279
+ <script>
280
+ import { ark } from './ark.js'; // new ArkBrowserClient({...}); ark.init();
281
+ const state = ark.state;
282
+ </script>
283
+
284
+ {#if $state.isAuthenticated}
285
+ Hello {$state.user.email} <button on:click={() => ark.signoutRedirect()}>Sign out</button>
286
+ {:else}
287
+ <button on:click={() => ark.signinRedirect()}>Sign in</button>
288
+ {/if}
289
+ ```
290
+
291
+ Solid: `const state = from((set) => ark.subscribe(set))`. Lit, Alpine, htmx, web components: call
292
+ `ark.subscribe(render)` and read `ark.getSnapshot()`.
293
+
294
+ ## A plain `<script>` tag
295
+
296
+ No modules and no bundler: the IIFE build defines `window.ArkOAuth`.
297
+
298
+ ```html
299
+ <script src="https://cdn.jsdelivr.net/npm/ark-oauth-client-js@2.1.1/dist/ark-oauth-client.global.min.js"></script>
300
+ <script>
301
+ const ark = new ArkOAuth.ArkBrowserClient({ authority: 'https://idp.example.com/my_idp', clientId: 'my-spa' });
302
+ ark.subscribe((s) => (document.title = s.isAuthenticated ? s.user.email : 'Signed out'));
303
+ ark.init();
304
+ </script>
305
+ ```
306
+
307
+ `dist/ark-oauth-client.esm.min.js` is the same as one ES module, for an import map. About 19 KB gzipped.
308
+
309
+ ---
310
+
311
+ ## The state and events
312
+
313
+ `ark.getSnapshot()` returns one immutable object, the same object until something changes:
314
+
315
+ | Field | |
316
+ |---|---|
317
+ | `status` | `'loading'` until `init()` finishes, then `'authenticated'`, `'unauthenticated'` or `'denied'` |
318
+ | `isLoading`, `isAuthenticated` | shorthands for the two statuses UIs branch on |
319
+ | `user` | the validated ID token claims (`sub`, `name`, `email`, ...) or `null` |
320
+ | `arkClaims` | the user's Ark authorization claims for this client, from the access token |
321
+ | `scopes` | the granted scopes |
322
+ | `expiresAt` | access token expiry, epoch seconds |
323
+ | `error` | the last failure (an `ArkError`), or `null` |
324
+ | `denial` | who was refused and why, when `status` is `'denied'` ([account switching](#account-switching-on-a-shared-browser)) |
325
+
326
+ There is deliberately no access token in it: read it per call with `getAccessToken()`, because the
327
+ client replaces it underneath you on every refresh.
328
+
329
+ `ark.on(event, handler)` returns an unsubscribe function. Events: `signedIn`, `signedOut`,
330
+ `tokensRefreshed`, `refreshFailed` (a network failure; the session is kept and retried),
331
+ `sessionExpired` (the refresh token was refused; the user must sign in again), `accessDenied`
332
+ and `error`.
333
+
334
+ `hasArkClaims(...claims)` (all) and `hasAnyArkClaim(...claims)` (any) are for showing and hiding
335
+ UI. They are not security: the API must check the token itself (`verifyAccessToken` in the Node
336
+ client, `RequireArkClaims` in .NET).
337
+
338
+ ---
339
+
340
+ ## Signing in
341
+
342
+ ```js
343
+ await ark.signinRedirect(); // back to this page afterwards
344
+ await ark.signinRedirect({ returnTo: '/billing' }); // a local path; off-site values are ignored
345
+ await ark.signinRedirect({ prompt: 'login', loginHint: 'alice@example.com', maxAge: 300 });
346
+ const { user } = await ark.signinPopup(); // the page never navigates
347
+ ```
348
+
349
+ `signinPopup()` must be called straight from a click handler, before any `await`, or the browser
350
+ blocks the window (`ArkPopupError` with `reason: 'blocked'`). The popup lands on the redirect URI,
351
+ whose page is your app calling `init()`: it hands the response to the opener and closes. Fall back
352
+ to `signinRedirect()` when it is blocked.
353
+
354
+ What `init()` / `handleRedirectCallback()` check, in order: an `error` response becomes an
355
+ `ArkOAuthError`; `state` must match a sign-in this tab started (single use, ten minutes); `iss` must
356
+ be the provider (RFC 9207); the code is redeemed with the PKCE verifier only this tab holds; the ID
357
+ token is verified against the provider's published keys (Web Crypto), its issuer, audience, `exp`,
358
+ `iat`, `nonce`, `at_hash` and `c_hash`. The response parameters are removed from the address bar
359
+ either way, so a reload cannot replay them.
360
+
361
+ Afterwards the user is sent to the page they started from: through `onRedirectCallback(returnTo)`
362
+ when you pass one (your router's navigate), otherwise with `history.replaceState` and a `popstate`
363
+ event, which React Router and the Angular router follow. The Vue plugin and `ArkNextProvider` wire
364
+ their routers for you.
365
+
366
+ ## Calling your API
367
+
368
+ ```js
369
+ const res = await ark.fetch('/api/orders'); // the app's own origin
370
+ const res2 = await ark.fetch('https://api.example.com/v1/orders', { method: 'POST', body }); // listed in apiOrigins
371
+ ```
372
+
373
+ `ark.fetch` attaches `Authorization: Bearer …`, refreshes the token first when it is about to
374
+ expire, and retries a `401` with `error="invalid_token"` once after a refresh. It sends the token
375
+ **only** to the page's origin and to `apiOrigins`; any other URL throws rather than leak a bearer
376
+ token to a third party. Without a session it throws `ArkLoginRequiredError`.
377
+
378
+ With another HTTP library, ask for the token per request:
379
+
380
+ ```js
381
+ axios.interceptors.request.use(async (config) => {
382
+ if (ark.isApiUrl(config.url)) {
383
+ const token = await ark.getAccessToken(); // null when signed out
384
+ if (token) config.headers.Authorization = `Bearer ${token}`;
385
+ }
386
+ return config;
387
+ });
388
+ ```
389
+
390
+ `ark.userInfo()` calls the provider's userinfo endpoint. The API itself validates the access token
391
+ (an RS256 `at+jwt` with `ark_claims`) with one of the server-side Ark clients.
392
+
393
+ ## Signing out
394
+
395
+ ```js
396
+ await ark.signoutRedirect(); // this app and the provider; back to accountSwitch.homePath ('/')
397
+ await ark.signoutRedirect({ returnTo: '/bye' });
398
+ await ark.signoutLocal(); // this app only; the provider session (and SSO) stays
399
+ ```
400
+
401
+ `signoutRedirect()` drops the tokens, revokes the refresh token, and sends the browser to the
402
+ provider's end-session endpoint with `id_token_hint` (so Ark ends its session without asking) and
403
+ `post_logout_redirect_uri`. Both halves matter: drop only the local tokens and the provider's
404
+ session survives, so the next sign-in is silent, as the same person. Other tabs of the app are
405
+ signed out too.
406
+
407
+ ## Account switching on a shared browser
408
+
409
+ Single sign-on is browser-wide. On a shared machine the next person opens the app, is signed in
410
+ as the previous one, and sees "no access", for an account that is not theirs, with no way out:
411
+ signing in again returns the same session. This is the same feature as `AccountSwitch` in .NET
412
+ and `accountSwitch` in Node, and it is **off by default**:
413
+
414
+ ```js
415
+ const ark = new ArkBrowserClient({
416
+ authority, clientId,
417
+ accountSwitch: {
418
+ requireArkClaims: true,
419
+ requiredClaims: ['billing.admin'], // recommended: Ark puts identity names (email, sub) in ark_claims too
420
+ appDisplayName: 'Billing'
421
+ }
422
+ });
423
+ ```
424
+
425
+ With it on, the access check moves to the callback: an account without the claims gets no stored
426
+ token, its refresh token is revoked, and the state becomes `denied` with `state.denial` naming the
427
+ account. Render the way out with `<ArkAccessDenied />` (React, and the default inside
428
+ `<RequireArk>`), `renderAccessDenied(element, ark)` (no framework; CSP-safe DOM, no innerHTML), or
429
+ your own page calling:
430
+
431
+ - `ark.switchUser()`: drops the local session and signs in with `prompt=login`, so the provider draws
432
+ its sign-in form instead of answering from its session. With `endProviderSessionOnSwitch: true`
433
+ the provider session is ended first (right for a kiosk).
434
+ - `ark.signoutRedirect()`: sign out completely.
435
+
436
+ `onEvaluateAccess({ claims, arkClaims, allowedByConfiguration })` replaces the rule with your own.
437
+ `ArkChallengeProperties.switchUser(returnTo)` / `.selectAccount()` build the sign-in options by hand.
438
+
439
+ ---
440
+
441
+ ## Configuration
442
+
443
+ | Option | Default | |
444
+ |---|---|---|
445
+ | `authority` | (required) | The issuer, `{BaseUrl}/{TenantId}`. Or `authServerUrl` + `tenantId`. |
446
+ | `clientId` | (required) | A public client. A `clientSecret` is refused: a browser cannot keep one. |
447
+ | `redirectUri` | `'/signin-oidc'` | A path on this origin, or an absolute URL. Matched byte for byte. |
448
+ | `postLogoutRedirectUri` | `'/signout-callback-oidc'` | `null` to leave it out (the provider then shows its own "signed out" page). |
449
+ | `scopes` | `openid profile email offline_access` | Unregistered scopes are rejected, not dropped. |
450
+ | `storage` | `'session'` | `'session'`, `'local'`, `'memory'` or a Storage-like object. See below. |
451
+ | `automaticRefresh` | `true` | Renew with the refresh token before expiry. |
452
+ | `refreshBeforeSeconds` | `60` | |
453
+ | `apiOrigins` | `[]` | Origins besides the app's own that may receive the access token. |
454
+ | `responseMode` | `'query'` | Or `'fragment'`. (`form_post` needs a server.) |
455
+ | `prompt`, `acrValues`, `extraAuthorizationParams` | | Sent on every sign-in. |
456
+ | `accountSwitch` | off | See [above](#account-switching-on-a-shared-browser). |
457
+ | `onRedirectCallback(returnTo)` | | Where to go after sign-in: your router's navigate. |
458
+ | `syncTabs` | `true` | Sign-out and token sync across tabs (BroadcastChannel). |
459
+ | `popup` | `{ width: 520, height: 680, timeoutMs: 300000 }` | |
460
+ | `requireHttps` | `true` | Refuses a plain-http authority except on localhost. |
461
+ | `clockToleranceSeconds` | `60` | |
462
+ | `timeoutMs` | `10000` | Per request. |
463
+ | `fetch`, `window`, `navigate`, `redirect` | browser globals | Seams for tests and for unusual hosts (Electron, Capacitor). |
464
+
465
+ Everything that can be checked without the network is checked when the client is created, with
466
+ an `ArkConfigError` that says what to change.
467
+
468
+ ## Where tokens live, and how the session is renewed
469
+
470
+ **Storage.** `session` (the default) keeps tokens in sessionStorage: they survive a reload, stay
471
+ private to the tab, and go when it closes; each new tab signs in silently through the provider's
472
+ session. `local` shares one session across tabs and browser restarts. `memory` writes nothing,
473
+ so every reload goes back to the provider (silently, while its session lasts). The sign-in
474
+ transaction (state, nonce, PKCE verifier) always lives in sessionStorage, for ten minutes, single use.
475
+
476
+ Whichever you choose, script running on the page can use the session: storage changes how long a
477
+ stolen token is good for, not whether XSS can reach it. A strict Content-Security-Policy is what
478
+ stops XSS, and the library works under one: it uses no inline script and no `eval`, and the
479
+ built-in denied page styles itself through the CSSOM (verified under `script-src 'self';
480
+ style-src 'self'`). Keep access
481
+ tokens short-lived on the client record. If tokens must never reach the browser at all, put a
482
+ server-side client (a "backend for frontend") in front of the API.
483
+
484
+ **Renewal uses refresh tokens**, `refreshBeforeSeconds` before expiry, or half-way through the
485
+ token's life when that is shorter (so a client record with 30-second tokens does not refresh in a
486
+ loop). Ark rotates refresh tokens: each refresh returns a new one and retires the old, and
487
+ presenting a retired one is treated as theft, so the whole family is revoked. The client is built
488
+ around that:
489
+
490
+ - refreshes are serialised across tabs (Web Locks) and across instances on one page, and the one
491
+ that waited re-reads storage and adopts the new tokens rather than replaying the old ones;
492
+ - the new refresh token is stored the moment the server returns it, before the ID token that came
493
+ with it is checked, so a failure after that point (JWKS unreachable) cannot lead to a replay;
494
+ - "Duplicate tab" copies sessionStorage, refresh token included. The client keeps hashes of spent
495
+ refresh tokens in localStorage, so the copy that comes second signs in afresh (silently, while
496
+ SSO lasts) instead of presenting the token the other tab already redeemed.
497
+
498
+ Hidden-iframe renewal (`prompt=none` in an iframe) is not used: Ark's authorization endpoint sends
499
+ `Content-Security-Policy: frame-ancestors 'self'`, which refuses to be framed by another origin, and
500
+ third-party cookie blocking defeats it in Safari and Firefox anyway. Without `offline_access` there
501
+ is no refresh token, and the session ends when the access token does.
502
+
503
+ Revocation (`/oauth2/revoke`) grants no CORS on the Ark server, so the client sends it as a
504
+ CORS-safelisted `no-cors` POST: delivered, response unread (RFC 7009 answers 200 either way).
505
+ Sign-out does not depend on it: ending the provider session also ends every refresh token issued
506
+ under it.
507
+
508
+ ## Checking the setup
509
+
510
+ ```js
511
+ const report = await ark.checkSetup();
512
+ // { discoveryOk, jwksOk, tokenEndpointCorsOk, redirectUri, provider: {...}, signingKeys: [...], problems: [...] }
513
+ ```
514
+
515
+ It fetches discovery and JWKS and probes the token endpoint with a refresh token that cannot exist
516
+ (an OAuth error back proves the endpoint answers this origin; a network error means CORS). It also
517
+ checks the secure context, S256, scopes, response mode, `none` auth and PAR. `problems` is in
518
+ sentences; render it on a setup page.
519
+
520
+ ## Errors
521
+
522
+ Everything thrown is an `ArkError`; the same names as the Node client.
523
+
524
+ | Class | When |
525
+ |---|---|
526
+ | `ArkConfigError` | Misconfiguration: thrown when the client is created, or naming the setting to change. |
527
+ | `ArkOAuthError` | The server (or the authorization response) said `error=…`. `.error` is the code (`access_denied`, `invalid_grant`, `login_required`, ...), plus `.errorDescription`, `.status`, `.endpoint`. |
528
+ | `ArkTokenError` | A token came back but did not validate (`.claim` names which check). Never retry. |
529
+ | `ArkCallbackError` | The response cannot be tied to a sign-in from this tab (state, iss). |
530
+ | `ArkNetworkError` | No response: offline, timeout, or (in a browser, most often) CORS. The message says which. |
531
+ | `ArkLoginRequiredError` | `ark.fetch()` with nobody signed in. |
532
+ | `ArkPopupError` | `.reason`: `blocked`, `closed` or `timeout`. |
533
+
534
+ ## Troubleshooting
535
+
536
+ | Symptom | Cause |
537
+ |---|---|
538
+ | `Failed to fetch` / `ArkNetworkError` mentioning CorsOrigins | The app's origin is not in `ark_oauth_server:Oidc:CorsOrigins`. |
539
+ | "redirect_uri does not match" on the provider | The registered URI differs by a character: scheme, port, trailing slash, path. Compare `checkSetup().redirectUri`. |
540
+ | The password "is wrong" but it is right | The user is not mapped to this client. |
541
+ | `invalid_scope` | A scope the client record does not list (they are a whitelist). |
542
+ | Signed out after every reload | `storage: 'memory'`, blocked storage, or no `offline_access` and an expired token. |
543
+ | Signed out in all tabs at once, randomly | Something presented a retired refresh token (a copy of the tokens used elsewhere). The client never does; check for code reading the stored token set. |
544
+ | "crypto.subtle is unavailable" | The page is not a secure context: use https, or http only on localhost. |
545
+ | The callback route shows "not found" | Add a route at the redirect path (`<ArkCallback>`), and history fallback on the host. |
546
+ | Sign-in loops between the app and the provider | Not from this library's guards (they stop on errors). Check that nothing calls `signinRedirect()` while `state.error` is set. |
547
+ | "the tenant requires pushed authorization requests" | PAR needs client authentication; a browser cannot do it. Turn it off for this client. |
548
+
549
+ ## What it implements
550
+
551
+ - Authorization code flow with PKCE (S256) as a public client (OAuth 2.1), redirect or popup
552
+ - `state` (constant-time, single use, per tab), `nonce`, RFC 9207 `iss`
553
+ - ID token validation in the browser: RS/PS/ES 256/384/512 via Web Crypto, issuer, audience,
554
+ `azp`, `exp`/`nbf`/`iat` with tolerance, `nonce`, `at_hash`, `c_hash`, `auth_time` for `max_age`,
555
+ same `sub` on refresh (OIDC Core §12.2); `alg: none` and HMAC never accepted
556
+ - Discovery (both well-known spellings) with the issuer check; JWKS caching with rotation and a
557
+ rate-limited refetch for an unknown `kid`
558
+ - Refresh token rotation, coordinated across tabs (Web Locks) and instances; automatic renewal
559
+ - RP-initiated logout with `id_token_hint`; token revocation (RFC 7009)
560
+ - UserInfo; `fetch` with origin allow-list and 401 retry
561
+ - Account switching (`prompt=login`), access check at the callback
562
+ - Cross-tab sign-out (BroadcastChannel); SSR-safe construction
563
+
564
+ ## Development
565
+
566
+ ```bash
567
+ npm install
568
+ npm test # node --test: the client against a stub Ark IdP, plus the React, Vue and Angular adapters
569
+ npm run typecheck # the .d.ts files, against real React, Vue and Angular types
570
+ npm run build # dist/ (IIFE + ESM bundles); runs on npm pack
571
+ ```
572
+
573
+ The tests run against `test/stub-idp.js`, which mirrors the real server's wire behaviour (CORS only
574
+ where Ark grants it, rotation with family revocation, `iss`, `at_hash`/`c_hash`), in a fake browser
575
+ window (`test/browser-env.js`) so redirect and popup flows run end to end in Node. The library has
576
+ also been run against a real `Ark.oAuth.Oidc.Host` in Chrome and WebKit; [`examples/`](examples)
577
+ holds the apps used for that.
578
+
579
+ MIT licensed.