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

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/src/config.js ADDED
@@ -0,0 +1,196 @@
1
+ import { ArkConfigError } from './errors.js';
2
+ import { normalizeAccountSwitch } from './access.js';
3
+
4
+ /**
5
+ * Normalises and checks what the application configured.
6
+ *
7
+ * Everything that can be caught without the network is caught here, when the client is created,
8
+ * because the alternative is finding out from a user's failed sign-in. A client secret shipped to
9
+ * a browser, an authority that is really a base URL with the tenant id missing, a redirect URI with
10
+ * a fragment: each produces an `invalid_request` page later and an afternoon of reading server
11
+ * logs, or one sentence here.
12
+ *
13
+ * Nothing in here touches `window`, so a client can be created during server-side rendering
14
+ * (Next.js, Nuxt, Angular SSR). Relative URIs are resolved against the page's origin later, in the
15
+ * browser.
16
+ */
17
+
18
+ export const DEFAULT_SCOPES = Object.freeze(['openid', 'profile', 'email', 'offline_access']);
19
+ export const DEFAULT_REDIRECT_PATH = '/signin-oidc';
20
+ export const DEFAULT_POST_LOGOUT_PATH = '/signout-callback-oidc';
21
+
22
+ function isLoopback(url) {
23
+ return ['localhost', '127.0.0.1', '[::1]', '::1'].includes(url.hostname);
24
+ }
25
+
26
+ function parseAbsolute(value, setting) {
27
+ let url;
28
+ try {
29
+ url = new URL(value);
30
+ } catch {
31
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an absolute URL, but is '${value}'.`);
32
+ }
33
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
34
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an http or https URL, but is '${value}'.`);
35
+ }
36
+ return url;
37
+ }
38
+
39
+ /**
40
+ * A redirect target: an absolute URL, or a path starting with `/` that is resolved against the
41
+ * page's origin at runtime. The server matches redirect URIs byte for byte, so what is registered
42
+ * must be exactly what this resolves to.
43
+ */
44
+ function checkRedirect(value, setting) {
45
+ if (value === null || value === undefined || value === '') return null;
46
+ const text = String(value);
47
+ if (text.startsWith('/') && !text.startsWith('//')) {
48
+ if (text.includes('#')) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);
49
+ return text;
50
+ }
51
+ const url = parseAbsolute(text, setting);
52
+ if (url.hash) throw new ArkConfigError(`ark_oauth_client: '${setting}' must not contain a fragment: ${text}`);
53
+ if (url.protocol !== 'https:' && !isLoopback(url)) {
54
+ throw new ArkConfigError(`ark_oauth_client: '${setting}' is ${text}. The server accepts http only for loopback addresses (RFC 8252 §7.3).`);
55
+ }
56
+ return text;
57
+ }
58
+
59
+ function normalizeOrigins(list) {
60
+ return Object.freeze(
61
+ [...(list ?? [])].map((value) => {
62
+ if (value === '*') {
63
+ throw new ArkConfigError("ark_oauth_client: 'apiOrigins' cannot be '*'. List the exact origins the access token may be sent to.");
64
+ }
65
+ return parseAbsolute(String(value), 'apiOrigins').origin;
66
+ })
67
+ );
68
+ }
69
+
70
+ export function normalizeConfig(options = {}) {
71
+ const {
72
+ authority,
73
+ authServerUrl,
74
+ tenantId,
75
+ clientId,
76
+ clientSecret,
77
+ privateKeyJwt,
78
+ tokenEndpointAuthMethod,
79
+ usePar,
80
+ redirectUri = DEFAULT_REDIRECT_PATH,
81
+ postLogoutRedirectUri = DEFAULT_POST_LOGOUT_PATH,
82
+ scopes,
83
+ responseMode = 'query',
84
+ prompt = null,
85
+ acrValues = null,
86
+ extraAuthorizationParams = null,
87
+ storage = 'session',
88
+ automaticRefresh = true,
89
+ refreshBeforeSeconds = 60,
90
+ apiOrigins = [],
91
+ syncTabs = true,
92
+ accountSwitch,
93
+ onEvaluateAccess = null,
94
+ onRedirectCallback = null,
95
+ navigate = null,
96
+ redirect = null,
97
+ popup = {},
98
+ transactionTtlSeconds = 600,
99
+ clockToleranceSeconds = 60,
100
+ requireHttps = true,
101
+ requireTokenHashes = true,
102
+ idTokenSigningAlgorithms = null,
103
+ timeoutMs = 10_000,
104
+ metadataTtlMs = 5 * 60_000,
105
+ jwksTtlMs = 5 * 60_000,
106
+ jwksMinRefreshIntervalMs = 10_000,
107
+ fetch: fetchImpl = undefined
108
+ } = options;
109
+
110
+ // The .NET client accepts AuthServerUrl + TenantId as well as Authority, so the values already in
111
+ // an appsettings.json or a .env can be used as they are.
112
+ let resolvedAuthority = String(authority ?? '').trim();
113
+ if (!resolvedAuthority && authServerUrl && tenantId) resolvedAuthority = `${String(authServerUrl).replace(/\/+$/, '')}/${tenantId}`;
114
+ if (!resolvedAuthority) {
115
+ throw new ArkConfigError(
116
+ "ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant, {BaseUrl}/{TenantId}, e.g. " +
117
+ 'https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and they are joined for you.)'
118
+ );
119
+ }
120
+ resolvedAuthority = resolvedAuthority.replace(/\/+$/, '');
121
+ const authorityUrl = parseAbsolute(resolvedAuthority, 'authority');
122
+ if (requireHttps && authorityUrl.protocol !== 'https:' && !isLoopback(authorityUrl)) {
123
+ throw new ArkConfigError(
124
+ `ark_oauth_client: 'authority' is ${resolvedAuthority}, which is plain http. Tokens would cross the network in the clear. ` +
125
+ 'Use https, or set requireHttps:false, only ever for local development.'
126
+ );
127
+ }
128
+
129
+ if (!clientId || typeof clientId !== 'string') {
130
+ throw new ArkConfigError("ark_oauth_client: 'clientId' is required: the client id registered with the tenant.");
131
+ }
132
+
133
+ // Everything shipped to a browser is public. A secret in a bundle is a secret on every visitor's
134
+ // disk, and the server cannot tell the app from anyone who copied it. Register the SPA as a
135
+ // public client (token_endpoint_auth_method "none"); keep confidential clients on a server.
136
+ if (clientSecret || privateKeyJwt || (tokenEndpointAuthMethod && tokenEndpointAuthMethod !== 'none')) {
137
+ throw new ArkConfigError(
138
+ 'ark_oauth_client: a browser app cannot keep a client secret or a private key: anything in the bundle is readable by ' +
139
+ "every visitor. Register this app as a public client (token endpoint auth method 'none'; PKCE protects the code), " +
140
+ 'or keep the confidential client on a server with ark-oauth-client (Node), ark-oauth-client (Python) or Ark.oAuth.Client (.NET).'
141
+ );
142
+ }
143
+
144
+ // The pushed authorization request endpoint needs client authentication and grants no CORS, so a
145
+ // browser cannot use it. Said now rather than as a failed preflight later.
146
+ if (usePar) {
147
+ throw new ArkConfigError(
148
+ "ark_oauth_client: 'usePar' is not available in a browser app: /oauth2/par needs client authentication and serves no CORS. " +
149
+ 'Leave PAR to a server-side client.'
150
+ );
151
+ }
152
+
153
+ if (!['query', 'fragment'].includes(responseMode)) {
154
+ throw new ArkConfigError(
155
+ `ark_oauth_client: 'responseMode' is '${responseMode}'. A browser app reads the response from its own URL, so use 'query' or 'fragment'` +
156
+ (responseMode === 'form_post' ? '; form_post POSTs to a server, which a single-page app does not have.' : '.')
157
+ );
158
+ }
159
+
160
+ if (!Number.isFinite(refreshBeforeSeconds) || refreshBeforeSeconds < 0) {
161
+ throw new ArkConfigError(`ark_oauth_client: 'refreshBeforeSeconds' must be a number of seconds, not '${refreshBeforeSeconds}'.`);
162
+ }
163
+
164
+ return Object.freeze({
165
+ authority: resolvedAuthority,
166
+ clientId,
167
+ redirectUri: checkRedirect(redirectUri, 'redirectUri') ?? DEFAULT_REDIRECT_PATH,
168
+ postLogoutRedirectUri: checkRedirect(postLogoutRedirectUri, 'postLogoutRedirectUri'),
169
+ scopes: Object.freeze(scopes?.length ? [...scopes] : [...DEFAULT_SCOPES]),
170
+ responseMode,
171
+ prompt,
172
+ acrValues,
173
+ extraAuthorizationParams: extraAuthorizationParams ? Object.freeze({ ...extraAuthorizationParams }) : null,
174
+ storage,
175
+ automaticRefresh: Boolean(automaticRefresh),
176
+ refreshBeforeSeconds,
177
+ apiOrigins: normalizeOrigins(apiOrigins),
178
+ syncTabs: Boolean(syncTabs),
179
+ accountSwitch: normalizeAccountSwitch(accountSwitch),
180
+ onEvaluateAccess,
181
+ onRedirectCallback,
182
+ navigate,
183
+ redirect,
184
+ popup: Object.freeze({ width: 520, height: 680, timeoutMs: 5 * 60_000, ...popup }),
185
+ transactionTtlSeconds,
186
+ clockToleranceSeconds,
187
+ requireHttps,
188
+ requireTokenHashes,
189
+ idTokenSigningAlgorithms: idTokenSigningAlgorithms ? Object.freeze([...idTokenSigningAlgorithms]) : null,
190
+ timeoutMs,
191
+ metadataTtlMs,
192
+ jwksTtlMs,
193
+ jwksMinRefreshIntervalMs,
194
+ fetch: fetchImpl
195
+ });
196
+ }
package/src/crypto.js ADDED
@@ -0,0 +1,121 @@
1
+ import { ArkConfigError, ArkTokenError } from './errors.js';
2
+
3
+ /**
4
+ * The small cryptographic primitives the protocol is built from, on the Web Crypto API.
5
+ *
6
+ * No dependency supplies any of it: nothing in the chain that mints a PKCE verifier or checks an
7
+ * ID token signature can be swapped out by a typosquatted package on install.
8
+ *
9
+ * `crypto.subtle` exists only in a secure context, meaning https, or http on localhost/127.0.0.1.
10
+ * A page served over plain http from a LAN address has no SubtleCrypto at all. That is reported
11
+ * by name here, because otherwise it surfaces as "cannot read properties of undefined" deep inside
12
+ * a sign-in.
13
+ */
14
+
15
+ function webCrypto() {
16
+ const c = globalThis.crypto;
17
+ if (!c?.getRandomValues) {
18
+ throw new ArkConfigError('ark_oauth_client: this environment has no Web Crypto API (globalThis.crypto).');
19
+ }
20
+ return c;
21
+ }
22
+
23
+ export function subtle() {
24
+ const s = webCrypto().subtle;
25
+ if (!s) {
26
+ throw new ArkConfigError(
27
+ 'ark_oauth_client: crypto.subtle is unavailable because this page is not a secure context. ' +
28
+ 'Serve the app over https, or over http only on localhost / 127.0.0.1 during development.'
29
+ );
30
+ }
31
+ return s;
32
+ }
33
+
34
+ const encoder = new TextEncoder();
35
+ const decoder = new TextDecoder();
36
+
37
+ function toBytes(input) {
38
+ if (input instanceof Uint8Array) return input;
39
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
40
+ if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
41
+ return encoder.encode(String(input));
42
+ }
43
+
44
+ /** base64url without padding (RFC 7515 §2). Accepts bytes or a string (encoded as UTF-8). */
45
+ export function base64UrlEncode(input) {
46
+ const bytes = toBytes(input);
47
+ let binary = '';
48
+ // Chunked, so a large input cannot overflow the argument list of String.fromCharCode.
49
+ for (let i = 0; i < bytes.length; i += 0x8000) {
50
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
51
+ }
52
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
53
+ }
54
+
55
+ /** Decodes base64url to bytes, tolerating the padding some encoders leave on. */
56
+ export function base64UrlDecode(value) {
57
+ const normalized = String(value).replace(/-/g, '+').replace(/_/g, '/');
58
+ const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
59
+ let binary;
60
+ try {
61
+ binary = atob(padded);
62
+ } catch (cause) {
63
+ throw new ArkTokenError('a token segment is not valid base64url.', { cause });
64
+ }
65
+ const bytes = new Uint8Array(binary.length);
66
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
67
+ return bytes;
68
+ }
69
+
70
+ /** base64url to a UTF-8 string. */
71
+ export function base64UrlDecodeToString(value) {
72
+ return decoder.decode(base64UrlDecode(value));
73
+ }
74
+
75
+ /**
76
+ * Cryptographically random bytes as base64url.
77
+ *
78
+ * Every unguessable value in the flow (`state`, `nonce`, the PKCE verifier) comes from here and
79
+ * only from here. The .NET client this family descends from was rewritten because its predecessor
80
+ * derived the PKCE verifier from a timestamp, which made it guessable and PKCE worthless.
81
+ */
82
+ export function randomToken(bytes = 32) {
83
+ const buffer = new Uint8Array(bytes);
84
+ webCrypto().getRandomValues(buffer);
85
+ return base64UrlEncode(buffer);
86
+ }
87
+
88
+ /** A digest as bytes. `hash` is a Web Crypto name: SHA-256, SHA-384 or SHA-512. */
89
+ export async function digest(input, hash = 'SHA-256') {
90
+ return new Uint8Array(await subtle().digest(hash, toBytes(input)));
91
+ }
92
+
93
+ export function sha256(input) {
94
+ return digest(input, 'SHA-256');
95
+ }
96
+
97
+ /**
98
+ * The left-most half of a digest, base64url encoded: the construction OIDC Core §3.1.3.6 uses for
99
+ * `at_hash` and `c_hash`. The hash follows the ID token's `alg` (SHA-256 for RS256, which is what
100
+ * Ark signs with).
101
+ */
102
+ export async function leftHalfHash(value, hash = 'SHA-256') {
103
+ const full = await digest(value, hash);
104
+ return base64UrlEncode(full.subarray(0, full.length / 2));
105
+ }
106
+
107
+ /**
108
+ * Compares two strings without returning early on the first difference.
109
+ *
110
+ * Used for `state`. A browser comparing its own state is not much of a timing oracle, but the
111
+ * comparison costs nothing to get right, and it keeps this check the same shape as the server
112
+ * clients'.
113
+ */
114
+ export function constantTimeEqual(a, b) {
115
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
116
+ const x = encoder.encode(a);
117
+ const y = encoder.encode(b);
118
+ let diff = x.length ^ y.length;
119
+ for (let i = 0; i < Math.max(x.length, y.length); i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
120
+ return diff === 0;
121
+ }
package/src/denied.js ADDED
@@ -0,0 +1,119 @@
1
+ import { VERSION } from './version.js';
2
+
3
+ /**
4
+ * The built-in dead end for a refused sign-in, for apps without a framework (or that want one
5
+ * ready-made). The same wording as the access-denied page of the .NET, Python and Node clients.
6
+ *
7
+ * Built with DOM calls and `textContent` only (no innerHTML, so nothing from a token can become
8
+ * markup) and styled through the CSSOM, which a strict Content-Security-Policy allows where an
9
+ * injected <style> element or a `style` attribute would be blocked. Pass `unstyled: true` and style
10
+ * the `ark-denied*` classes yourself to match the app.
11
+ *
12
+ * ark.subscribe((s) => { if (s.status === 'denied') renderAccessDenied(document.body, ark); });
13
+ */
14
+
15
+ const PALETTE = {
16
+ light: { bg: '#f7f7f8', surface: '#ffffff', border: '#e2e2e6', fg: '#17171a', muted: '#6a6a73', accent: '#4f46e5', accentFg: '#ffffff' },
17
+ dark: { bg: '#111114', surface: '#1a1a1f', border: '#313139', fg: '#ececf1', muted: '#9a9aa5', accent: '#8b85ff', accentFg: '#16161c' }
18
+ };
19
+
20
+ function el(doc, tag, className, text) {
21
+ const node = doc.createElement(tag);
22
+ if (className) node.className = className;
23
+ if (text !== undefined) node.textContent = text;
24
+ return node;
25
+ }
26
+
27
+ function css(node, styles) {
28
+ for (const [key, value] of Object.entries(styles)) node.style.setProperty(key, value);
29
+ }
30
+
31
+ /**
32
+ * Renders the access-denied card into `container`, replacing its content.
33
+ *
34
+ * @param {Element} container
35
+ * @param {import('./client.js').ArkBrowserClient} client
36
+ * @param {{ unstyled?: boolean, appName?: string }} [options]
37
+ * @returns {() => void} removes the card again
38
+ */
39
+ export function renderAccessDenied(container, client, options = {}) {
40
+ const doc = container.ownerDocument ?? globalThis.document;
41
+ const config = client.config.accountSwitch;
42
+ const denial = client.getSnapshot().denial;
43
+ const appName = (options.appName ?? config.appDisplayName ?? '').trim() || client.clientId || 'this application';
44
+ const account = config.showSignedInAccount ? (denial?.email ?? denial?.name ?? denial?.subject ?? null) : null;
45
+ const dark = Boolean(doc.defaultView?.matchMedia?.('(prefers-color-scheme: dark)').matches);
46
+ const c = PALETTE[dark ? 'dark' : 'light'];
47
+ const styled = !options.unstyled;
48
+
49
+ const root = el(doc, 'main', 'ark-denied');
50
+ root.setAttribute('role', 'alert');
51
+ const card = el(doc, 'div', 'ark-denied__card');
52
+ root.append(card);
53
+
54
+ card.append(el(doc, 'h1', 'ark-denied__title', `You do not have access to ${appName}`));
55
+
56
+ const lede = el(doc, 'p', 'ark-denied__lede');
57
+ if (account) {
58
+ lede.append('You are signed in as ', el(doc, 'strong', null, account), `, and that account does not have access to ${appName}.`);
59
+ } else {
60
+ lede.textContent = `The account you are signed in with does not have access to ${appName}.`;
61
+ }
62
+ card.append(lede);
63
+ card.append(
64
+ el(
65
+ doc,
66
+ 'p',
67
+ 'ark-denied__hint',
68
+ `If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${appName}. ` +
69
+ 'Choose “Sign in as a different user” to enter your own credentials.'
70
+ )
71
+ );
72
+
73
+ const actions = el(doc, 'div', 'ark-denied__actions');
74
+ const switchButton = el(doc, 'button', 'ark-denied__switch', 'Sign in as a different user');
75
+ switchButton.type = 'button';
76
+ switchButton.addEventListener('click', () => client.switchUser({ returnTo: denial?.returnTo ?? undefined }));
77
+ actions.append(switchButton);
78
+
79
+ let signOutButton = null;
80
+ if (config.allowFullSignOut) {
81
+ signOutButton = el(doc, 'button', 'ark-denied__signout', 'Sign out completely');
82
+ signOutButton.type = 'button';
83
+ signOutButton.addEventListener('click', () => client.signoutRedirect({ returnTo: config.homePath }));
84
+ actions.append(signOutButton);
85
+ }
86
+ card.append(actions);
87
+
88
+ let foot = null;
89
+ if (config.supportUrl || config.supportEmail) {
90
+ foot = el(doc, 'p', 'ark-denied__foot', `Need access to ${appName}? `);
91
+ const link = el(doc, 'a', null, config.supportUrl ? 'Request it here' : config.supportEmail);
92
+ link.href = config.supportUrl ? config.supportUrl : `mailto:${config.supportEmail}`;
93
+ foot.append(link);
94
+ card.append(foot);
95
+ }
96
+ const version = el(doc, 'p', 'ark-denied__version', `ark-oauth-client-js ${VERSION}`);
97
+ card.append(version);
98
+
99
+ if (styled) {
100
+ const font = 'ui-sans-serif, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
101
+ css(root, { 'min-height': '100vh', display: 'flex', 'align-items': 'center', 'justify-content': 'center', padding: '24px', 'box-sizing': 'border-box', background: c.bg, color: c.fg, font: `15px/1.55 ${font}` });
102
+ css(card, { width: '100%', 'max-width': '480px', background: c.surface, border: `1px solid ${c.border}`, 'border-radius': '12px', padding: '28px', 'box-sizing': 'border-box' });
103
+ for (const p of card.querySelectorAll('p')) css(p, { margin: '0 0 14px', color: c.muted });
104
+ css(lede, { color: c.fg });
105
+ css(card.querySelector('h1'), { margin: '0 0 10px', 'font-size': '19px', 'font-weight': '640' });
106
+ css(actions, { display: 'flex', 'flex-direction': 'column', gap: '10px', 'margin-top': '20px' });
107
+ const button = { width: '100%', padding: '11px 14px', 'border-radius': '8px', font: 'inherit', 'font-weight': '560', cursor: 'pointer' };
108
+ css(switchButton, { ...button, border: `1px solid ${c.accent}`, background: c.accent, color: c.accentFg });
109
+ if (signOutButton) css(signOutButton, { ...button, border: `1px solid ${c.border}`, background: 'transparent', color: c.fg });
110
+ if (foot) {
111
+ css(foot, { 'margin-top': '18px', 'padding-top': '14px', 'border-top': `1px solid ${c.border}`, 'font-size': '13px' });
112
+ css(foot.querySelector('a'), { color: c.accent });
113
+ }
114
+ css(version, { margin: '18px 0 0', 'padding-top': '14px', 'border-top': foot ? '0' : `1px solid ${c.border}`, 'font-size': '12px', 'text-align': 'center' });
115
+ }
116
+
117
+ container.replaceChildren(root);
118
+ return () => root.remove();
119
+ }
@@ -0,0 +1,84 @@
1
+ import { getJson } from './http.js';
2
+ import { ArkConfigError, ArkOAuthError } from './errors.js';
3
+
4
+ /**
5
+ * The discovery document (OpenID Connect Discovery 1.0 / RFC 8414).
6
+ *
7
+ * The issuer is the only URL an Ark app is told. Every endpoint comes from here, which is what lets
8
+ * the provider move an endpoint or rotate a key without a single SPA being rebuilt.
9
+ */
10
+
11
+ const DEFAULT_TTL_MS = 5 * 60_000; // the server sends Cache-Control: max-age=300
12
+
13
+ /** Both spellings of the metadata URL: OIDC appends the well-known path, RFC 8414 inserts it. */
14
+ export function discoveryUrls(authority) {
15
+ const base = authority.replace(/\/+$/, '');
16
+ const url = new URL(base);
17
+ const path = url.pathname.replace(/\/+$/, '');
18
+ return [`${base}/.well-known/openid-configuration`, `${url.origin}/.well-known/oauth-authorization-server${path}`];
19
+ }
20
+
21
+ /** Fetches and caches provider metadata for one authority. Concurrent callers share one request. */
22
+ export class MetadataResolver {
23
+ #authority;
24
+ #ttlMs;
25
+ #http;
26
+ #entry = null;
27
+
28
+ constructor(authority, { ttlMs = DEFAULT_TTL_MS, ...http } = {}) {
29
+ this.#authority = authority.replace(/\/+$/, '');
30
+ this.#ttlMs = ttlMs;
31
+ this.#http = http;
32
+ }
33
+
34
+ get(force = false) {
35
+ const hit = this.#entry;
36
+ if (hit && !force && (hit.pending || Date.now() - hit.fetchedAt <= this.#ttlMs)) return hit.promise;
37
+
38
+ const entry = { fetchedAt: Date.now(), pending: true };
39
+ entry.promise = this.#fetch(force).then(
40
+ (metadata) => {
41
+ entry.pending = false;
42
+ return metadata;
43
+ },
44
+ (error) => {
45
+ // A failed lookup is not cached, or one bad moment would wedge the page for the whole TTL.
46
+ if (this.#entry === entry) this.#entry = null;
47
+ throw error;
48
+ }
49
+ );
50
+ this.#entry = entry;
51
+ return entry.promise;
52
+ }
53
+
54
+ clear() {
55
+ this.#entry = null;
56
+ }
57
+
58
+ async #fetch(force) {
59
+ const [primary, fallback] = discoveryUrls(this.#authority);
60
+ // `default` lets the browser's HTTP cache answer within the server's max-age, which saves a
61
+ // round trip on every page load; a forced read revalidates instead.
62
+ const options = { ...this.#http, cache: force ? 'no-cache' : 'default' };
63
+ let metadata;
64
+ try {
65
+ metadata = await getJson(primary, options);
66
+ } catch (error) {
67
+ if (error instanceof ArkOAuthError && error.status === 404) metadata = await getJson(fallback, options);
68
+ else throw error;
69
+ }
70
+
71
+ if (!metadata.issuer) {
72
+ throw new ArkOAuthError('server_error', `${primary} returned a document with no 'issuer'.`, { endpoint: primary });
73
+ }
74
+ // OIDC Discovery §4.3: the document's issuer must equal the one used to look it up. A mismatch
75
+ // is the shape of a mix-up attack, and far more often a missing tenant id in configuration.
76
+ if (metadata.issuer.replace(/\/+$/, '') !== this.#authority) {
77
+ throw new ArkConfigError(
78
+ `the provider at ${primary} identifies itself as '${metadata.issuer}', but this client is configured for ` +
79
+ `'${this.#authority}'. Set 'authority' to exactly the issuer value: for Ark that is {BaseUrl}/{TenantId}.`
80
+ );
81
+ }
82
+ return Object.freeze(metadata);
83
+ }
84
+ }
package/src/errors.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The error types this library throws.
3
+ *
4
+ * Every failure that came from the authorization server arrives as an ArkOAuthError carrying the
5
+ * `error` code the spec defines, because that code is the only part a caller can branch on. A
6
+ * library that collapses `invalid_grant` and a CORS failure into one thrown string forces the
7
+ * application to parse English to decide whether to retry, sign the user in again, or give up.
8
+ *
9
+ * The names and fields match `ark-oauth-client` for Node, so code that handles errors from one
10
+ * reads the same against the other.
11
+ */
12
+
13
+ /** Base class, so `catch (e) { if (e instanceof ArkError) ... }` covers everything from here. */
14
+ export class ArkError extends Error {
15
+ constructor(message, options) {
16
+ super(message, options);
17
+ this.name = new.target.name;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * The client is misconfigured: a missing authority, a client secret handed to a browser, a
23
+ * redirect URI with a fragment. Thrown at construction wherever possible, so the mistake shows up
24
+ * the first time the page loads and not on a user's failed sign-in.
25
+ */
26
+ export class ArkConfigError extends ArkError {}
27
+
28
+ /**
29
+ * An RFC 6749 §5.2 error: the server (or the authorization response) said `error=...`.
30
+ *
31
+ * `error` is the machine-readable code (`invalid_grant`, `access_denied`, `login_required`, ...),
32
+ * `status` the HTTP status it came with (0 for a redirect), and `endpoint` the URL that produced
33
+ * it, which tells "the token endpoint refused the code" apart from "userinfo refused the token".
34
+ */
35
+ export class ArkOAuthError extends ArkError {
36
+ constructor(error, description, { status = 0, endpoint = null, errorUri = null, body = null } = {}) {
37
+ super(description ? `${error}: ${description}` : error);
38
+ this.error = error;
39
+ this.errorDescription = description ?? null;
40
+ this.errorUri = errorUri;
41
+ this.status = status;
42
+ this.endpoint = endpoint;
43
+ this.body = body;
44
+ }
45
+
46
+ /** Builds the error from a parsed response body, falling back to the HTTP status. */
47
+ static fromResponse(status, body, endpoint) {
48
+ if (body && typeof body === 'object' && typeof body.error === 'string') {
49
+ return new ArkOAuthError(body.error, body.error_description, {
50
+ status,
51
+ endpoint,
52
+ errorUri: body.error_uri ?? null,
53
+ body
54
+ });
55
+ }
56
+ return new ArkOAuthError('server_error', `the endpoint returned HTTP ${status}.`, { status, endpoint, body });
57
+ }
58
+ }
59
+
60
+ /**
61
+ * A token arrived but did not survive validation: a bad signature, the wrong issuer or audience,
62
+ * an expired `exp`, a `nonce` that is not the one sent, an `at_hash` that does not cover the
63
+ * access token beside it.
64
+ *
65
+ * Separate from ArkOAuthError on purpose. An OAuth error means the server refused; this means the
66
+ * server answered and the answer cannot be trusted, which is worse and must never be retried.
67
+ */
68
+ export class ArkTokenError extends ArkError {
69
+ constructor(message, { claim = null } = {}) {
70
+ super(message);
71
+ this.claim = claim;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * The authorization response could not be tied to a sign-in this page started: an unknown or
77
+ * missing `state`, an expired transaction, an `iss` that is not the provider the user was sent to
78
+ * (RFC 9207). Treat it as an attempted CSRF or mix-up attack, not as a user error.
79
+ */
80
+ export class ArkCallbackError extends ArkError {}
81
+
82
+ /**
83
+ * The request did not complete: offline, DNS, timeout, aborted, or (in a browser, and much more
84
+ * often than the others) refused by CORS. A browser reports all of those as the same opaque
85
+ * `TypeError: Failed to fetch`, so the message says which one is likely and what to change.
86
+ */
87
+ export class ArkNetworkError extends ArkError {}
88
+
89
+ /**
90
+ * The action needs a signed-in user and there is none, or the session can no longer be renewed.
91
+ * `ark.fetch()` throws it; the remedy is `ark.signinRedirect()`.
92
+ */
93
+ export class ArkLoginRequiredError extends ArkError {
94
+ constructor(message = 'no user is signed in, or the session has ended. Call signinRedirect() to sign in.') {
95
+ super(message);
96
+ this.error = 'login_required';
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The popup sign-in did not finish. `reason` is `blocked` (the browser refused to open it, almost
102
+ * always because `signinPopup()` was not called straight from a click), `closed` (the user closed
103
+ * it) or `timeout`.
104
+ */
105
+ export class ArkPopupError extends ArkError {
106
+ constructor(reason, message) {
107
+ super(message);
108
+ this.reason = reason;
109
+ }
110
+ }