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/package.json CHANGED
@@ -1,6 +1,124 @@
1
1
  {
2
2
  "name": "ark-oauth-client-js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.1.1",
4
+ "description": "The OpenID Connect client for browser apps signing in against Ark.oAuth.Oidc. Framework-agnostic, with adapters for React, Next.js, Vue and Angular (and a Svelte-compatible store). Authorization code + PKCE as a public client, ID token verification in the browser (signature, nonce, at_hash, c_hash, iss), rotating refresh tokens coordinated across tabs, popup or redirect sign-in, RP-initiated logout, account switching on a shared browser, and an authorised fetch. No runtime dependencies.",
5
+ "keywords": [
6
+ "oauth",
7
+ "oauth2",
8
+ "oidc",
9
+ "openid-connect",
10
+ "pkce",
11
+ "spa",
12
+ "browser",
13
+ "react",
14
+ "nextjs",
15
+ "vue",
16
+ "angular",
17
+ "svelte",
18
+ "authentication",
19
+ "ark"
20
+ ],
21
+ "license": "MIT",
22
+ "author": "Immanuel R",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/ir-dev/ark-oauth-oidc.git",
26
+ "directory": "ark_oauth_client_js"
27
+ },
28
+ "homepage": "https://github.com/ir-dev/ark-oauth-oidc/tree/main/ark_oauth_client_js#readme",
29
+ "bugs": "https://github.com/ir-dev/ark-oauth-oidc/issues",
30
+ "type": "module",
31
+ "main": "./src/index.js",
32
+ "module": "./src/index.js",
33
+ "types": "./types/index.d.ts",
34
+ "sideEffects": false,
35
+ "exports": {
36
+ ".": {
37
+ "types": "./types/index.d.ts",
38
+ "default": "./src/index.js"
39
+ },
40
+ "./react": {
41
+ "types": "./types/react.d.ts",
42
+ "default": "./src/react.js"
43
+ },
44
+ "./next": {
45
+ "types": "./types/next.d.ts",
46
+ "default": "./src/next.js"
47
+ },
48
+ "./vue": {
49
+ "types": "./types/vue.d.ts",
50
+ "default": "./src/vue.js"
51
+ },
52
+ "./angular": {
53
+ "types": "./types/angular.d.ts",
54
+ "default": "./src/angular.js"
55
+ },
56
+ "./dist/*": "./dist/*",
57
+ "./package.json": "./package.json"
58
+ },
59
+ "unpkg": "./dist/ark-oauth-client.global.min.js",
60
+ "jsdelivr": "./dist/ark-oauth-client.global.min.js",
61
+ "files": [
62
+ "src",
63
+ "types",
64
+ "dist",
65
+ "README.md",
66
+ "CHANGELOG.md",
67
+ "LICENSE"
68
+ ],
69
+ "publishConfig": {
70
+ "access": "public"
71
+ },
72
+ "scripts": {
73
+ "test": "node --test \"test/*.test.js\"",
74
+ "test:watch": "node --test --watch \"test/*.test.js\"",
75
+ "typecheck": "tsc -p test/types/tsconfig.json",
76
+ "build": "node scripts/build.mjs",
77
+ "prepack": "node scripts/build.mjs",
78
+ "e2e": "node e2e/real-idp.mjs",
79
+ "example": "node examples/serve.mjs",
80
+ "check": "npm run build && npm test && npm run typecheck"
81
+ },
82
+ "peerDependencies": {
83
+ "@angular/core": ">=16.0.0",
84
+ "next": ">=13.4.0",
85
+ "react": ">=18.0.0",
86
+ "rxjs": ">=7.4.0",
87
+ "vue": ">=3.3.0"
88
+ },
89
+ "peerDependenciesMeta": {
90
+ "@angular/core": {
91
+ "optional": true
92
+ },
93
+ "next": {
94
+ "optional": true
95
+ },
96
+ "react": {
97
+ "optional": true
98
+ },
99
+ "rxjs": {
100
+ "optional": true
101
+ },
102
+ "vue": {
103
+ "optional": true
104
+ }
105
+ },
106
+ "devDependencies": {
107
+ "@angular/common": "^21.2.26",
108
+ "@angular/compiler": "^21.2.26",
109
+ "@angular/core": "^21.2.26",
110
+ "@angular/platform-browser": "^21.2.26",
111
+ "@angular/router": "^21.2.26",
112
+ "@types/react": "^19.3.0",
113
+ "@types/react-dom": "^19.3.0",
114
+ "esbuild": "^0.28.2",
115
+ "happy-dom": "^21.0.4",
116
+ "playwright-core": "^1.65.1",
117
+ "react": "^19.3.1",
118
+ "react-dom": "^19.3.1",
119
+ "rxjs": "^7.8.2",
120
+ "typescript": "^7.0.2",
121
+ "vue": "^3.5.45",
122
+ "vue-router": "^4.6.5"
123
+ }
124
+ }
package/src/access.js ADDED
@@ -0,0 +1,141 @@
1
+ import { ArkConfigError } from './errors.js';
2
+
3
+ /**
4
+ * Account switching on a shared browser.
5
+ *
6
+ * Single sign-on is browser-wide: once one person signs in anywhere, the provider's session answers
7
+ * every other app's sign-in in that browser. The next person opens this app, is signed in as the
8
+ * previous one, and is told they have no access, for an account that is not even theirs. Signing in
9
+ * again goes back to the same provider session and gives the same answer.
10
+ *
11
+ * Breaking that loop needs two things: a dead end that is honest about whose session it is, and a
12
+ * sign-in that sends `prompt=login`, the one parameter a provider must honour by ignoring its
13
+ * session and drawing the sign-in form (OIDC Core §3.1.2.1).
14
+ *
15
+ * The same feature, under the same names, as `AccountSwitch` in the .NET client, `account_switch`
16
+ * in Python and `accountSwitch` in Node. Off by default, as there.
17
+ */
18
+
19
+ export const ArkAccessDeniedReasons = Object.freeze({
20
+ /** The provider authenticated them, but they hold no authorization claims for this client. */
21
+ NO_APP_ACCESS: 'no_app_access',
22
+ /** They are signed in, but a guard refused the page they asked for. */
23
+ FORBIDDEN: 'forbidden'
24
+ });
25
+
26
+ export const ACCOUNT_SWITCH_DEFAULTS = Object.freeze({
27
+ /**
28
+ * Refuse the sign-in when the access token carries no `ark_claims` for this client. Off, the wrong
29
+ * account is signed in and every guarded view says "forbidden". On, the callback stops before any
30
+ * token is stored and the state becomes `denied`, from where the user can switch.
31
+ *
32
+ * Ark issues the user's whole claim mapping as `ark_claims`, identity names like `email`
33
+ * included, so this check alone admits a user with an identity-only mapping. Name the claims
34
+ * that mean "may use this app" in `requiredClaims`.
35
+ */
36
+ requireArkClaims: false,
37
+ /** Narrow that check: at least one of these. Empty means any `ark_claims` will do. */
38
+ requiredClaims: Object.freeze([]),
39
+ /** Where to send the browser after a refused sign-in. Null stays on the page the user asked for. */
40
+ accessDeniedPath: null,
41
+ /** Sent as `prompt` when switching. `login` is the one every provider honours. */
42
+ prompt: 'login',
43
+ /**
44
+ * Make switching a full RP-initiated logout first. Off, only this app's tokens are dropped and
45
+ * the previous user's other apps are left alone; on, they are signed out everywhere (right for a
46
+ * kiosk, heavy-handed for a laptop).
47
+ */
48
+ endProviderSessionOnSwitch: false,
49
+ /** The app's name on the built-in page. Defaults to the client id. */
50
+ appDisplayName: null,
51
+ /** Name the refused account on the page. On a shared browser it is somebody else's address. */
52
+ showSignedInAccount: true,
53
+ /** Offer "Sign out completely" beside "Sign in as a different user". */
54
+ allowFullSignOut: true,
55
+ /** Where "Sign out completely" lands, and the fallback for an absent or off-site return URL. */
56
+ homePath: '/',
57
+ supportUrl: null,
58
+ supportEmail: null
59
+ });
60
+
61
+ /**
62
+ * Keeps a return URL inside this app. Echoing an arbitrary one would make sign-in an open redirect:
63
+ * a phishing link that keeps your domain in the address bar until it hands the user to somebody else.
64
+ */
65
+ export function localOrDefault(url, fallback = '/') {
66
+ const home = typeof fallback === 'string' && fallback.trim() ? fallback : fallback === null ? null : '/';
67
+ if (typeof url !== 'string' || !url.trim()) return home;
68
+ const candidate = url.trim();
69
+ if (!candidate.startsWith('/') || candidate.startsWith('//')) return home;
70
+ // Browsers read `\` as `/`, so `/\evil.example` is `//evil.example`, another host. They also
71
+ // strip tabs and newlines before parsing, so `/\t/evil.example` collapses to the same thing.
72
+ if (candidate.startsWith('/\\')) return home;
73
+ // eslint-disable-next-line no-control-regex
74
+ if (/[\u0000-\u001f\u007f]/.test(candidate)) return home;
75
+ return candidate;
76
+ }
77
+
78
+ /** Fills in the defaults and refuses what could only fail later, in front of a user. */
79
+ export function normalizeAccountSwitch(options = {}) {
80
+ const merged = { ...ACCOUNT_SWITCH_DEFAULTS };
81
+ for (const [key, value] of Object.entries(options ?? {})) {
82
+ if (Object.prototype.hasOwnProperty.call(ACCOUNT_SWITCH_DEFAULTS, key) && value !== undefined) merged[key] = value;
83
+ }
84
+ for (const key of ['accessDeniedPath', 'homePath']) {
85
+ if (merged[key] !== null && localOrDefault(merged[key], null) !== merged[key]) {
86
+ throw new ArkConfigError(`ark_oauth_client: accountSwitch.${key} must be a local path starting with '/', but is '${merged[key]}'.`);
87
+ }
88
+ }
89
+ if (merged.supportUrl && !/^https?:\/\//i.test(merged.supportUrl)) {
90
+ throw new ArkConfigError(`ark_oauth_client: accountSwitch.supportUrl must be an http(s) URL, but is '${merged.supportUrl}'.`);
91
+ }
92
+ merged.requiredClaims = Object.freeze([...(merged.requiredClaims ?? [])].map(String));
93
+ return Object.freeze(merged);
94
+ }
95
+
96
+ /**
97
+ * The sign-in options that make "sign in as a different user" work. Without `prompt=login` the
98
+ * provider answers from the session it already has, and the wrong person is signed in again.
99
+ * The result is what `signinRedirect()` and `signinPopup()` accept.
100
+ */
101
+ export const ArkChallengeProperties = Object.freeze({
102
+ switchUser(returnTo = null, loginHint = null, prompt = 'login') {
103
+ return { returnTo: returnTo || '/', prompt: prompt || 'login', ...(loginHint ? { loginHint } : {}) };
104
+ },
105
+
106
+ /** The provider's account picker. A provider without one falls back to its sign-in form. */
107
+ selectAccount(returnTo = null) {
108
+ return ArkChallengeProperties.switchUser(returnTo, null, 'select_account');
109
+ }
110
+ });
111
+
112
+ /**
113
+ * The entitlement decision, made once per sign-in at the callback: not "may this user open that
114
+ * view" but "may this user use this app at all". Refusing there means no token is ever stored.
115
+ *
116
+ * `onEvaluateAccess` replaces the configured rule rather than being ANDed with it; a handler that
117
+ * wants both reads `allowedByConfiguration` and says so.
118
+ */
119
+ export async function evaluateAccess(options, onEvaluateAccess, { claims = {}, arkClaims = [], tokens = null } = {}) {
120
+ const required = options.requiredClaims.map((c) => c.toLowerCase());
121
+ const allowedByConfiguration =
122
+ !options.requireArkClaims || (required.length ? arkClaims.some((c) => required.includes(String(c).toLowerCase())) : arkClaims.length > 0);
123
+ if (typeof onEvaluateAccess !== 'function') return allowedByConfiguration;
124
+ return Boolean(await onEvaluateAccess({ claims: { ...claims }, arkClaims: [...arkClaims], allowedByConfiguration, tokens }));
125
+ }
126
+
127
+ /** What is known about a refused account, read off whatever identity there is. */
128
+ export function describeDenial(reason, claims, arkClaims, returnTo) {
129
+ const first = (...names) => {
130
+ for (const name of names) if (claims?.[name]) return String(claims[name]);
131
+ return null;
132
+ };
133
+ return {
134
+ reason,
135
+ subject: first('sub'),
136
+ email: first('email', 'preferred_username'),
137
+ name: first('name'),
138
+ arkClaims: [...(arkClaims ?? [])],
139
+ returnTo: returnTo ?? null
140
+ };
141
+ }
package/src/angular.js ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Angular bindings (Angular 16+, standalone or NgModule, zone.js or zoneless): providers, signals,
3
+ * functional guards and an HttpClient interceptor.
4
+ *
5
+ * // app.config.ts
6
+ * providers: [
7
+ * provideArk({ authority, clientId, apiOrigins: ['https://api.example.com'] }),
8
+ * provideHttpClient(withInterceptors([arkInterceptor])),
9
+ * provideRouter(routes)
10
+ * ]
11
+ *
12
+ * // routes
13
+ * { path: 'billing', canActivate: [arkClaimsGuard('billing.admin')], component: BillingComponent }
14
+ *
15
+ * // a component
16
+ * ark = injectArk(); // ark.isAuthenticated(), ark.user(), ark.signinRedirect()
17
+ *
18
+ * Plain JavaScript with no decorators: everything is a factory, `inject()` and functional APIs, so
19
+ * the package needs no Angular compilation step and works with any Angular CLI builder.
20
+ */
21
+ import * as ng from '@angular/core';
22
+ import { catchError, from, switchMap, throwError } from 'rxjs';
23
+ import { ArkBrowserClient } from './client.js';
24
+
25
+ /** The ArkBrowserClient. */
26
+ export const ARK_CLIENT = new ng.InjectionToken('ark-oauth-client-js: ArkBrowserClient');
27
+ /** The signal-based facade returned by `injectArk()`. */
28
+ export const ARK = new ng.InjectionToken('ark-oauth-client-js: Ark');
29
+
30
+ function createFacade(client) {
31
+ const state = ng.signal(client.getSnapshot());
32
+ client.subscribe((snapshot) => state.set(snapshot));
33
+ return {
34
+ client,
35
+ state: state.asReadonly(),
36
+ status: ng.computed(() => state().status),
37
+ isLoading: ng.computed(() => state().isLoading),
38
+ isAuthenticated: ng.computed(() => state().isAuthenticated),
39
+ user: ng.computed(() => state().user),
40
+ arkClaims: ng.computed(() => state().arkClaims),
41
+ scopes: ng.computed(() => state().scopes),
42
+ error: ng.computed(() => state().error),
43
+ denial: ng.computed(() => state().denial),
44
+ signinRedirect: (options) => client.signinRedirect(options),
45
+ signinPopup: (options) => client.signinPopup(options),
46
+ signoutRedirect: (options) => client.signoutRedirect(options),
47
+ signoutLocal: (options) => client.signoutLocal(options),
48
+ switchUser: (options) => client.switchUser(options),
49
+ getAccessToken: client.getAccessToken,
50
+ fetch: client.fetch,
51
+ hasArkClaims: (...claims) => claims.flat().every((c) => state().arkClaims.includes(c)),
52
+ hasAnyArkClaim: (...claims) => claims.flat().some((c) => state().arkClaims.includes(c))
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Registers the client and starts it before the app's first navigation.
58
+ *
59
+ * Starting it in an app initializer means the sign-in callback is completed, and the address bar
60
+ * already reads the page the user started from, by the time the router reads the URL. Guards then
61
+ * see the final state on their first run.
62
+ *
63
+ * @param {object|ArkBrowserClient} optionsOrClient
64
+ * @param {{ autoInit?: boolean, onRedirectCallback?: (returnTo: string) => unknown }} [settings]
65
+ */
66
+ export function provideArk(optionsOrClient, { autoInit = true, onRedirectCallback } = {}) {
67
+ // inject() runs in the factory, which is always an injection context; the function it returns
68
+ // only starts the client. Older Angular does not run APP_INITIALIZER functions in one.
69
+ const prepare = () => {
70
+ const client = ng.inject(ARK_CLIENT);
71
+ ng.inject(ARK); // the facade subscribes before the first state change
72
+ return () => (autoInit ? client.init(onRedirectCallback ? { onRedirectCallback } : {}) : undefined);
73
+ };
74
+ // provideAppInitializer arrived in Angular 19 and APP_INITIALIZER is deprecated from then on;
75
+ // use whichever this Angular has.
76
+ const initializer =
77
+ typeof ng.provideAppInitializer === 'function'
78
+ ? ng.provideAppInitializer(() => prepare()())
79
+ : { provide: ng.APP_INITIALIZER, multi: true, useFactory: prepare };
80
+
81
+ return ng.makeEnvironmentProviders([
82
+ {
83
+ provide: ARK_CLIENT,
84
+ useFactory: () => (optionsOrClient instanceof ArkBrowserClient ? optionsOrClient : new ArkBrowserClient(optionsOrClient))
85
+ },
86
+ { provide: ARK, useFactory: () => createFacade(ng.inject(ARK_CLIENT)) },
87
+ initializer
88
+ ]);
89
+ }
90
+
91
+ /** The facade: signals for the state, plus the client's actions. Call in an injection context. */
92
+ export function injectArk() {
93
+ return ng.inject(ARK);
94
+ }
95
+
96
+ let warnedServerGuard = false;
97
+
98
+ /**
99
+ * A guarded route rendered on the server can only be cancelled, and Angular reports a cancelled
100
+ * prerender as "The content returned was empty", which says nothing about why. Said once, here.
101
+ */
102
+ function warnServerGuard(url) {
103
+ if (warnedServerGuard) return;
104
+ warnedServerGuard = true;
105
+ console.warn(
106
+ `ark-oauth-client-js: an Ark route guard ran during server rendering${url ? ` (${url})` : ''}. Who is signed in is known only ` +
107
+ "in the browser, so the guard cancelled. Render routes behind an Ark guard on the client: { path: '…', renderMode: RenderMode.Client } " +
108
+ 'in app.routes.server.ts.'
109
+ );
110
+ }
111
+
112
+ function guard({ claims = [], anyClaims = [], onDenied = null } = {}) {
113
+ return async (route, routerState) => {
114
+ const client = ng.inject(ARK_CLIENT);
115
+ // Server rendering knows nobody: cancel without starting a sign-in (which needs a window).
116
+ // The browser runs the guard again after hydration and decides there.
117
+ if (!client.isBrowser) {
118
+ warnServerGuard(routerState?.url);
119
+ return false;
120
+ }
121
+ const state = await client.init();
122
+ // Still loading after start-up means the browser is already on its way to the provider (the
123
+ // second half of an account switch): starting another sign-in would replace that one.
124
+ if (state.isLoading) return false;
125
+ if (!state.isAuthenticated) {
126
+ if (state.status === 'denied' || state.error) return onDenied ? onDenied(route, routerState) : false;
127
+ await client.signinRedirect({ returnTo: routerState?.url ?? undefined });
128
+ return false;
129
+ }
130
+ const held = state.arkClaims;
131
+ const missing = claims.some((c) => !held.includes(c)) || (anyClaims.length > 0 && !anyClaims.some((c) => held.includes(c)));
132
+ if (missing) return onDenied ? onDenied(route, routerState) : false;
133
+ return true;
134
+ };
135
+ }
136
+
137
+ /** CanActivateFn: a signed-out user is sent to sign in and returns to the route they asked for. */
138
+ export const arkAuthGuard = guard();
139
+
140
+ /** CanActivateFn requiring every one of these Ark authorization claims. */
141
+ export function arkClaimsGuard(...claims) {
142
+ return guard({ claims: claims.flat() });
143
+ }
144
+
145
+ /**
146
+ * A configurable CanActivateFn. `onDenied(route, state)` decides what a refused navigation does;
147
+ * return `inject(Router).parseUrl('/no-access')` from it to redirect.
148
+ */
149
+ export function createArkGuard(options) {
150
+ return guard(options);
151
+ }
152
+
153
+ /**
154
+ * HttpInterceptorFn: attaches the access token to requests for the app's own origin and the
155
+ * origins in `apiOrigins` (never to anything else), and retries a 401 once after a refresh.
156
+ */
157
+ export const arkInterceptor = (req, next) => {
158
+ const client = ng.inject(ARK_CLIENT);
159
+ if (!client.isApiUrl(req.url)) return next(req);
160
+ const withToken = (token) => (token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
161
+ return from(client.getAccessToken()).pipe(
162
+ switchMap((token) =>
163
+ next(withToken(token)).pipe(
164
+ catchError((error) => {
165
+ if (!token || error?.status !== 401) return throwError(() => error);
166
+ return from(client.getAccessToken({ forceRefresh: true }).catch(() => null)).pipe(
167
+ switchMap((renewed) => (renewed ? next(withToken(renewed)) : throwError(() => error)))
168
+ );
169
+ })
170
+ )
171
+ )
172
+ );
173
+ };
174
+
175
+ export { ArkBrowserClient };