ark-oauth-client-node 0.0.0-stage → 2.2.0
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 +84 -0
- package/LICENSE +21 -0
- package/README.md +528 -2
- package/package.json +64 -4
- package/src/access.js +234 -0
- package/src/app-config.js +73 -0
- package/src/client.js +780 -0
- package/src/config.js +164 -0
- package/src/crypto.js +59 -0
- package/src/denied-page.js +83 -0
- package/src/discovery.js +101 -0
- package/src/errors.js +88 -0
- package/src/express.js +820 -0
- package/src/http.js +153 -0
- package/src/index.js +42 -0
- package/src/jwks.js +122 -0
- package/src/jwt.js +294 -0
- package/src/pkce.js +42 -0
- package/src/session.js +135 -0
- package/src/tokens.js +120 -0
- package/src/version.js +10 -0
- package/types/index.d.ts +672 -0
package/src/config.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { ArkConfigError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Normalises and checks what the application configured.
|
|
5
|
+
*
|
|
6
|
+
* Everything that can be caught without talking to the network is caught here, at construction,
|
|
7
|
+
* because the alternative is finding out from a user's failed sign-in. A redirect_uri with a
|
|
8
|
+
* fragment, an authority that is really a base URL with the tenant id missing, `private_key_jwt`
|
|
9
|
+
* with no key: all of those produce an `invalid_request` page hours later and half a day of
|
|
10
|
+
* reading server logs, or one sentence here.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const DEFAULT_SCOPES = ['openid', 'profile', 'email', 'offline_access'];
|
|
14
|
+
|
|
15
|
+
const AUTH_METHODS = new Set(['client_secret_basic', 'client_secret_post', 'private_key_jwt', 'none']);
|
|
16
|
+
|
|
17
|
+
function isLoopback(url) {
|
|
18
|
+
return ['localhost', '127.0.0.1', '::1', '[::1]'].includes(url.hostname);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function requireAbsoluteUrl(value, setting) {
|
|
22
|
+
let url;
|
|
23
|
+
try {
|
|
24
|
+
url = new URL(value);
|
|
25
|
+
} catch {
|
|
26
|
+
throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an absolute URL, but is '${value}'.`);
|
|
27
|
+
}
|
|
28
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
29
|
+
throw new ArkConfigError(`ark_oauth_client: '${setting}' must be an http or https URL, but is '${value}'.`);
|
|
30
|
+
}
|
|
31
|
+
return url;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function normalizeConfig(options = {}) {
|
|
35
|
+
const {
|
|
36
|
+
authority,
|
|
37
|
+
authServerUrl,
|
|
38
|
+
tenantId,
|
|
39
|
+
clientId,
|
|
40
|
+
clientSecret = null,
|
|
41
|
+
tokenEndpointAuthMethod,
|
|
42
|
+
privateKeyJwt = null,
|
|
43
|
+
redirectUri = null,
|
|
44
|
+
postLogoutRedirectUri = null,
|
|
45
|
+
scopes,
|
|
46
|
+
audience = null,
|
|
47
|
+
responseMode = 'query',
|
|
48
|
+
usePar = false,
|
|
49
|
+
prompt = null,
|
|
50
|
+
acrValues = null,
|
|
51
|
+
extraAuthorizationParams = null,
|
|
52
|
+
clockToleranceSeconds = 60,
|
|
53
|
+
requireHttps = true,
|
|
54
|
+
requireTokenHashes = true,
|
|
55
|
+
idTokenSigningAlgorithms = null,
|
|
56
|
+
timeoutMs = 10_000,
|
|
57
|
+
metadataTtlMs = 5 * 60_000,
|
|
58
|
+
jwksTtlMs = 5 * 60_000,
|
|
59
|
+
jwksMinRefreshIntervalMs = 10_000,
|
|
60
|
+
fetch: fetchImpl = undefined,
|
|
61
|
+
roleClaim = 'role'
|
|
62
|
+
} = options;
|
|
63
|
+
|
|
64
|
+
// The .NET client accepts AuthServerUrl + TenantId as well as Authority; the same two-part form
|
|
65
|
+
// is honoured here so a Node app can be configured from the values already in appsettings.json.
|
|
66
|
+
let resolvedAuthority = (authority ?? '').trim();
|
|
67
|
+
if (!resolvedAuthority && authServerUrl && tenantId) {
|
|
68
|
+
resolvedAuthority = `${String(authServerUrl).replace(/\/+$/, '')}/${tenantId}`;
|
|
69
|
+
}
|
|
70
|
+
if (!resolvedAuthority) {
|
|
71
|
+
throw new ArkConfigError(
|
|
72
|
+
"ark_oauth_client: set 'authority' to the issuer URL of your Ark tenant — {BaseUrl}/{TenantId}, " +
|
|
73
|
+
'e.g. https://idp.example.com/my_idp. (Or set authServerUrl + tenantId and it will be joined for you.)'
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
resolvedAuthority = resolvedAuthority.replace(/\/+$/, '');
|
|
77
|
+
const authorityUrl = requireAbsoluteUrl(resolvedAuthority, 'authority');
|
|
78
|
+
if (requireHttps && authorityUrl.protocol !== 'https:' && !isLoopback(authorityUrl)) {
|
|
79
|
+
throw new ArkConfigError(
|
|
80
|
+
`ark_oauth_client: 'authority' is ${resolvedAuthority}, which is plain http. Tokens would cross the network in the clear. ` +
|
|
81
|
+
'Use https, or set requireHttps:false — only ever for local development.'
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!clientId || typeof clientId !== 'string') {
|
|
86
|
+
throw new ArkConfigError("ark_oauth_client: 'clientId' is required — the client id registered with the tenant.");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let method = tokenEndpointAuthMethod;
|
|
90
|
+
if (!method) {
|
|
91
|
+
// Match what the server expects by default: a client with a secret authenticates with it, a
|
|
92
|
+
// public client (SPA, native, CLI) has nothing to present and says so.
|
|
93
|
+
method = privateKeyJwt ? 'private_key_jwt' : clientSecret ? 'client_secret_basic' : 'none';
|
|
94
|
+
}
|
|
95
|
+
if (!AUTH_METHODS.has(method)) {
|
|
96
|
+
throw new ArkConfigError(
|
|
97
|
+
`ark_oauth_client: 'tokenEndpointAuthMethod' is '${method}'; the server supports ${[...AUTH_METHODS].join(', ')}.`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if ((method === 'client_secret_basic' || method === 'client_secret_post') && !clientSecret) {
|
|
101
|
+
throw new ArkConfigError(`ark_oauth_client: '${method}' needs a 'clientSecret'.`);
|
|
102
|
+
}
|
|
103
|
+
if (method === 'private_key_jwt' && !privateKeyJwt?.privateKey) {
|
|
104
|
+
throw new ArkConfigError(
|
|
105
|
+
"ark_oauth_client: 'private_key_jwt' needs privateKeyJwt.privateKey (a PEM string, a JWK, or a node:crypto KeyObject) " +
|
|
106
|
+
'and the matching public key published at the jwks_uri registered for this client.'
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
if (method === 'none' && clientSecret) {
|
|
110
|
+
throw new ArkConfigError(
|
|
111
|
+
"ark_oauth_client: a 'clientSecret' was given but tokenEndpointAuthMethod is 'none'. The server matches the registered " +
|
|
112
|
+
'method exactly, so pick the one this client is registered for.'
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let redirect = null;
|
|
117
|
+
if (redirectUri) {
|
|
118
|
+
const url = requireAbsoluteUrl(redirectUri, 'redirectUri');
|
|
119
|
+
// The server validates all three of these at registration and matches the value exactly at
|
|
120
|
+
// /authorize, so a mismatch here can never be recovered from at runtime.
|
|
121
|
+
if (url.hash) throw new ArkConfigError(`ark_oauth_client: 'redirectUri' must not contain a fragment: ${redirectUri}`);
|
|
122
|
+
if (url.protocol !== 'https:' && !isLoopback(url)) {
|
|
123
|
+
throw new ArkConfigError(
|
|
124
|
+
`ark_oauth_client: 'redirectUri' is ${redirectUri}. The server accepts http only for loopback addresses (RFC 8252 §7.3).`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
redirect = url.toString();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (postLogoutRedirectUri) requireAbsoluteUrl(postLogoutRedirectUri, 'postLogoutRedirectUri');
|
|
131
|
+
|
|
132
|
+
if (!['query', 'fragment', 'form_post'].includes(responseMode)) {
|
|
133
|
+
throw new ArkConfigError(`ark_oauth_client: 'responseMode' is '${responseMode}'; the server supports query, fragment and form_post.`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return Object.freeze({
|
|
137
|
+
authority: resolvedAuthority,
|
|
138
|
+
clientId,
|
|
139
|
+
clientSecret,
|
|
140
|
+
tokenEndpointAuthMethod: method,
|
|
141
|
+
privateKeyJwt: privateKeyJwt ? Object.freeze({ alg: 'RS256', ...privateKeyJwt }) : null,
|
|
142
|
+
redirectUri: redirect,
|
|
143
|
+
postLogoutRedirectUri,
|
|
144
|
+
scopes: Object.freeze(scopes?.length ? [...scopes] : [...DEFAULT_SCOPES]),
|
|
145
|
+
audience,
|
|
146
|
+
responseMode,
|
|
147
|
+
usePar,
|
|
148
|
+
prompt,
|
|
149
|
+
acrValues,
|
|
150
|
+
extraAuthorizationParams: extraAuthorizationParams ? Object.freeze({ ...extraAuthorizationParams }) : null,
|
|
151
|
+
clockToleranceSeconds,
|
|
152
|
+
requireHttps,
|
|
153
|
+
requireTokenHashes,
|
|
154
|
+
idTokenSigningAlgorithms: idTokenSigningAlgorithms ? Object.freeze([...idTokenSigningAlgorithms]) : null,
|
|
155
|
+
timeoutMs,
|
|
156
|
+
metadataTtlMs,
|
|
157
|
+
jwksTtlMs,
|
|
158
|
+
jwksMinRefreshIntervalMs,
|
|
159
|
+
fetch: fetchImpl,
|
|
160
|
+
roleClaim
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { DEFAULT_SCOPES };
|
package/src/crypto.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The small cryptographic primitives the protocol is built out of.
|
|
5
|
+
*
|
|
6
|
+
* All of it comes from `node:crypto` — this package has no runtime dependencies, so nothing in
|
|
7
|
+
* the chain that mints a PKCE verifier or compares a `state` can be replaced by a typosquatted
|
|
8
|
+
* package on install.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** base64url without padding (RFC 7515 §2). */
|
|
12
|
+
export function base64UrlEncode(input) {
|
|
13
|
+
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, 'utf8');
|
|
14
|
+
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Decodes base64url to a Buffer, tolerating the padding some encoders leave on. */
|
|
18
|
+
export function base64UrlDecode(value) {
|
|
19
|
+
const padded = value.replace(/-/g, '+').replace(/_/g, '/');
|
|
20
|
+
return Buffer.from(padded, 'base64');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Cryptographically random bytes as base64url.
|
|
25
|
+
*
|
|
26
|
+
* Every unguessable value in the protocol — `state`, `nonce`, the PKCE verifier, a session id —
|
|
27
|
+
* comes from here and only from here. The .NET client this one mirrors exists because its
|
|
28
|
+
* predecessor derived the PKCE verifier from a timestamp, which made it predictable and meant
|
|
29
|
+
* PKCE protected nothing at all.
|
|
30
|
+
*/
|
|
31
|
+
export function randomToken(bytes = 32) {
|
|
32
|
+
return base64UrlEncode(randomBytes(bytes));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function sha256(input) {
|
|
36
|
+
return createHash('sha256').update(input, typeof input === 'string' ? 'utf8' : undefined).digest();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Constant-time string comparison.
|
|
41
|
+
*
|
|
42
|
+
* Used for `state` and for the session cookie signature. A length-dependent early return would
|
|
43
|
+
* leak how much of a guess was right, which is enough to reconstruct a value one character at a
|
|
44
|
+
* time; hashing both sides first keeps the compared buffers equal-length so the comparison itself
|
|
45
|
+
* cannot be timed either.
|
|
46
|
+
*/
|
|
47
|
+
export function fixedTimeEqual(a, b) {
|
|
48
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
49
|
+
return timingSafeEqual(sha256(a), sha256(b));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The left-most half of the SHA-256 of a value, base64url encoded — the construction OIDC Core
|
|
54
|
+
* §3.1.3.6 uses for `at_hash` and `c_hash`.
|
|
55
|
+
*/
|
|
56
|
+
export function leftHalfHash(value) {
|
|
57
|
+
const digest = sha256(value);
|
|
58
|
+
return base64UrlEncode(digest.subarray(0, digest.length / 2));
|
|
59
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { localOrDefault } from './access.js';
|
|
2
|
+
import { VERSION } from './version.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The built-in dead end, at `accountSwitch.accessDeniedPath`.
|
|
6
|
+
*
|
|
7
|
+
* Self-contained HTML with inlined styles and no script: it has to render in an application with no
|
|
8
|
+
* views, no static files and a strict Content-Security-Policy, and it is the one page a stuck user
|
|
9
|
+
* sees, so it cannot itself depend on anything. The markup is the Python and .NET clients' page.
|
|
10
|
+
*
|
|
11
|
+
* Replace it by pointing `accessDeniedPath` at a route of your own and turning `serveDefaultPage`
|
|
12
|
+
* off; `req.ark.deniedAccount()` gives that route the same information.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const STYLE =
|
|
16
|
+
':root{--bg:#f7f7f8;--surface:#fff;--border:#e2e2e6;--fg:#17171a;--muted:#6a6a73;--accent:#4f46e5;--accent-fg:#fff}' +
|
|
17
|
+
'@media(prefers-color-scheme:dark){:root{--bg:#111114;--surface:#1a1a1f;--border:#313139;--fg:#ececf1;--muted:#9a9aa5;--accent:#8b85ff;--accent-fg:#16161c}}' +
|
|
18
|
+
'*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;' +
|
|
19
|
+
'background:var(--bg);color:var(--fg);font:15px/1.55 ui-sans-serif,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}' +
|
|
20
|
+
'.card{width:100%;max-width:480px;background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:28px}' +
|
|
21
|
+
'h1{margin:0 0 10px;font-size:19px;font-weight:640}p{margin:0 0 14px;color:var(--muted)}p.lede{color:var(--fg)}' +
|
|
22
|
+
'form{margin:0}.actions{display:flex;flex-direction:column;gap:10px;margin-top:20px}' +
|
|
23
|
+
'button{width:100%;padding:11px 14px;border-radius:8px;border:1px solid var(--accent);background:var(--accent);color:var(--accent-fg);' +
|
|
24
|
+
'font:inherit;font-weight:560;cursor:pointer}button.secondary{background:transparent;color:var(--fg);border-color:var(--border)}' +
|
|
25
|
+
'.foot{margin-top:18px;padding-top:14px;border-top:1px solid var(--border);font-size:13px;color:var(--muted)}.foot a{color:var(--accent)}' +
|
|
26
|
+
'.ver{margin:18px 0 0;padding-top:14px;border-top:1px solid var(--border);font-size:12px;color:var(--muted);text-align:center}' +
|
|
27
|
+
'.foot+.ver{margin-top:8px;padding-top:0;border-top:0}';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* No script, no frames, nothing fetched. `form-action` is left out on purpose: Chrome applies it to
|
|
31
|
+
* the redirect that follows a submission, and the switch-user POST redirects to the provider.
|
|
32
|
+
*/
|
|
33
|
+
export const DENIED_PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'";
|
|
34
|
+
|
|
35
|
+
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
36
|
+
export const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ENTITIES[c]);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {ReturnType<import('./access.js').normalizeAccountSwitch>} options
|
|
40
|
+
* @param {{ app?: string|null, account?: string|null, returnUrl: string }} model
|
|
41
|
+
*/
|
|
42
|
+
export function renderAccessDeniedPage(options, { app, account = null, returnUrl }) {
|
|
43
|
+
const appName = escapeHtml(app?.trim() || 'this application');
|
|
44
|
+
const lede = account
|
|
45
|
+
? `You are signed in as <strong>${escapeHtml(account)}</strong>, and that account does not have access to ${appName}.`
|
|
46
|
+
: `The account you are signed in with does not have access to ${appName}.`;
|
|
47
|
+
|
|
48
|
+
const parts = [
|
|
49
|
+
'<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">',
|
|
50
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
51
|
+
`<title>No access — ${appName}</title><style>${STYLE}</style></head>`,
|
|
52
|
+
'<body><main class="card">',
|
|
53
|
+
`<h1>You do not have access to ${appName}</h1>`,
|
|
54
|
+
`<p class="lede">${lede}</p>`,
|
|
55
|
+
`<p>If somebody else was using this browser, their sign-in is still active and it is the one being offered to ${appName}. ` +
|
|
56
|
+
'Choose “Sign in as a different user” to enter your own credentials.</p>',
|
|
57
|
+
'<div class="actions">',
|
|
58
|
+
`<form method="post" action="${escapeHtml(options.switchUserPath)}">`,
|
|
59
|
+
`<input type="hidden" name="returnUrl" value="${escapeHtml(returnUrl)}">`,
|
|
60
|
+
'<button type="submit">Sign in as a different user</button></form>'
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
if (options.allowFullSignOut) {
|
|
64
|
+
parts.push(
|
|
65
|
+
`<form method="post" action="${escapeHtml(options.signOutPath)}">`,
|
|
66
|
+
`<input type="hidden" name="returnUrl" value="${escapeHtml(localOrDefault(options.homePath))}">`,
|
|
67
|
+
'<button class="secondary" type="submit">Sign out completely</button></form>'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
parts.push('</div>');
|
|
71
|
+
|
|
72
|
+
if (options.supportUrl || options.supportEmail) {
|
|
73
|
+
const link = options.supportUrl
|
|
74
|
+
? `<a href="${escapeHtml(options.supportUrl)}">Request it here</a>`
|
|
75
|
+
: `<a href="mailto:${escapeHtml(options.supportEmail)}">${escapeHtml(options.supportEmail)}</a>`;
|
|
76
|
+
parts.push(`<p class="foot">Need access to ${appName}? ${link}</p>`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Which client library drew this page: it is the one screen a stuck user is looking at while
|
|
80
|
+
// somebody else works out why the account is wrong, and they cannot run `npm ls` on the host.
|
|
81
|
+
parts.push(`<p class="ver">ark-oauth-client-node ${escapeHtml(VERSION)}</p>`, '</main></body></html>');
|
|
82
|
+
return parts.join('');
|
|
83
|
+
}
|
package/src/discovery.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
* There is one URL to configure — the issuer — and every endpoint this client uses comes from
|
|
8
|
+
* here. That is not indirection for its own sake: it is what lets the provider move an endpoint,
|
|
9
|
+
* turn PAR on, or start advertising the device grant without every application redeploying, and
|
|
10
|
+
* it is why the issuer is the only thing an Ark application has to be told.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const DEFAULT_TTL_MS = 5 * 60_000; // the server sends Cache-Control: max-age=300
|
|
14
|
+
|
|
15
|
+
/** Both spellings of the metadata URL: OIDC appends the well-known path, RFC 8414 inserts it. */
|
|
16
|
+
export function discoveryUrls(authority) {
|
|
17
|
+
const base = authority.replace(/\/+$/, '');
|
|
18
|
+
const url = new URL(base);
|
|
19
|
+
const path = url.pathname.replace(/\/+$/, '');
|
|
20
|
+
return [
|
|
21
|
+
`${base}/.well-known/openid-configuration`,
|
|
22
|
+
`${url.origin}/.well-known/oauth-authorization-server${path}`
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Fetches and caches provider metadata, one entry per authority.
|
|
28
|
+
*
|
|
29
|
+
* Instances are shared through the client, so an application that creates one ArkOAuthClient makes
|
|
30
|
+
* one discovery request per five minutes no matter how many sign-ins it serves.
|
|
31
|
+
*/
|
|
32
|
+
export class MetadataResolver {
|
|
33
|
+
#cache = new Map();
|
|
34
|
+
#ttlMs;
|
|
35
|
+
#http;
|
|
36
|
+
|
|
37
|
+
constructor({ ttlMs = DEFAULT_TTL_MS, ...http } = {}) {
|
|
38
|
+
this.#ttlMs = ttlMs;
|
|
39
|
+
this.#http = http;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async get(authority, { force = false } = {}) {
|
|
43
|
+
if (!authority) throw new ArkConfigError('no authority was given; set `authority` to the issuer URL of your Ark tenant.');
|
|
44
|
+
const key = authority.replace(/\/+$/, '');
|
|
45
|
+
|
|
46
|
+
const hit = this.#cache.get(key);
|
|
47
|
+
if (hit && !force) {
|
|
48
|
+
if (Date.now() - hit.fetchedAt <= this.#ttlMs) return hit.promise;
|
|
49
|
+
if (hit.pending) return hit.promise;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const entry = { fetchedAt: Date.now(), pending: true };
|
|
53
|
+
entry.promise = this.#fetch(key).then(
|
|
54
|
+
(metadata) => {
|
|
55
|
+
entry.pending = false;
|
|
56
|
+
return metadata;
|
|
57
|
+
},
|
|
58
|
+
(error) => {
|
|
59
|
+
// A failed lookup must not be cached, or one restart during a provider outage would
|
|
60
|
+
// wedge the application for the whole TTL.
|
|
61
|
+
this.#cache.delete(key);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
);
|
|
65
|
+
this.#cache.set(key, entry);
|
|
66
|
+
return entry.promise;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
clear() {
|
|
70
|
+
this.#cache.clear();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async #fetch(authority) {
|
|
74
|
+
const [primary, fallback] = discoveryUrls(authority);
|
|
75
|
+
let metadata;
|
|
76
|
+
try {
|
|
77
|
+
metadata = await getJson(primary, this.#http);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
// Ark serves the OIDC spelling. The RFC 8414 form is tried second so the same client can be
|
|
80
|
+
// pointed at a provider that only publishes that one.
|
|
81
|
+
if (error instanceof ArkOAuthError && error.status === 404) metadata = await getJson(fallback, this.#http);
|
|
82
|
+
else throw error;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!metadata.issuer) {
|
|
86
|
+
throw new ArkOAuthError('server_error', `${primary} returned a document with no 'issuer'.`, { endpoint: primary });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// OIDC Discovery §4.3: the issuer in the document must equal the one used to look it up.
|
|
90
|
+
// A mismatch means the URL is not the authority it claims to be — the shape of a mix-up
|
|
91
|
+
// attack, and much more often a stray /auth or a missing tenant id in configuration.
|
|
92
|
+
if (metadata.issuer.replace(/\/+$/, '') !== authority) {
|
|
93
|
+
throw new ArkConfigError(
|
|
94
|
+
`the provider at ${primary} identifies itself as '${metadata.issuer}', but this client is configured for '${authority}'. ` +
|
|
95
|
+
'Set `authority` to exactly the issuer value — for Ark that is {BaseUrl}/{TenantId}.'
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return Object.freeze(metadata);
|
|
100
|
+
}
|
|
101
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
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 DNS failure into one thrown string forces the
|
|
7
|
+
* application to parse English to decide whether to retry, re-authenticate, or give up.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Base class, so `catch (e) { if (e instanceof ArkError) ... }` covers everything from here. */
|
|
11
|
+
export class ArkError extends Error {
|
|
12
|
+
constructor(message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.name = new.target.name;
|
|
15
|
+
Error.captureStackTrace?.(this, new.target);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The client is misconfigured — a missing authority, a redirect_uri that is not absolute, a
|
|
21
|
+
* private_key_jwt method with no key. Thrown at construction time wherever possible, so the
|
|
22
|
+
* mistake surfaces at startup rather than on the first user's sign-in.
|
|
23
|
+
*/
|
|
24
|
+
export class ArkConfigError extends ArkError {}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* An RFC 6749 §5.2 error response: a JSON body with `error` and, usually, `error_description`.
|
|
28
|
+
*
|
|
29
|
+
* `error` is the machine-readable code (`invalid_grant`, `invalid_client`, `slow_down`, …);
|
|
30
|
+
* `status` is the HTTP status it arrived with; `endpoint` is the URL that produced it, which is
|
|
31
|
+
* what makes the difference between "the token endpoint rejected the code" and "the userinfo
|
|
32
|
+
* endpoint rejected the token" readable in a log.
|
|
33
|
+
*/
|
|
34
|
+
export class ArkOAuthError extends ArkError {
|
|
35
|
+
constructor(error, description, { status = 0, endpoint = null, errorUri = null, body = null } = {}) {
|
|
36
|
+
super(description ? `${error}: ${description}` : error);
|
|
37
|
+
this.error = error;
|
|
38
|
+
this.errorDescription = description ?? null;
|
|
39
|
+
this.errorUri = errorUri;
|
|
40
|
+
this.status = status;
|
|
41
|
+
this.endpoint = endpoint;
|
|
42
|
+
this.body = body;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Builds the error from a parsed response body, falling back to the HTTP status. */
|
|
46
|
+
static fromResponse(status, body, endpoint) {
|
|
47
|
+
if (body && typeof body === 'object' && typeof body.error === 'string') {
|
|
48
|
+
return new ArkOAuthError(body.error, body.error_description, {
|
|
49
|
+
status,
|
|
50
|
+
endpoint,
|
|
51
|
+
errorUri: body.error_uri ?? null,
|
|
52
|
+
body
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return new ArkOAuthError('server_error', `the endpoint returned HTTP ${status}.`, {
|
|
56
|
+
status,
|
|
57
|
+
endpoint,
|
|
58
|
+
body
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A token was received but did not survive validation: a bad signature, the wrong issuer or
|
|
65
|
+
* audience, an expired `exp`, a `nonce` that does not match the one sent, an `at_hash` that does
|
|
66
|
+
* not cover the access token that came with it.
|
|
67
|
+
*
|
|
68
|
+
* Kept separate from ArkOAuthError on purpose. An OAuth error means the server refused; this
|
|
69
|
+
* means the server answered and the answer cannot be trusted, which is the more serious of the
|
|
70
|
+
* two and should never be retried.
|
|
71
|
+
*/
|
|
72
|
+
export class ArkTokenError extends ArkError {
|
|
73
|
+
constructor(message, { claim = null, token = null } = {}) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.claim = claim;
|
|
76
|
+
this.token = token;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The authorization response could not be tied back to a request this client started — an unknown
|
|
82
|
+
* or missing `state`, an expired login transaction, an `iss` that is not the provider we sent the
|
|
83
|
+
* user to (RFC 9207). Treat it as an attempted CSRF or mix-up attack rather than a user error.
|
|
84
|
+
*/
|
|
85
|
+
export class ArkCallbackError extends ArkError {}
|
|
86
|
+
|
|
87
|
+
/** The remote call did not complete: connection refused, DNS failure, timeout, aborted. */
|
|
88
|
+
export class ArkNetworkError extends ArkError {}
|