ark-oauth-client-node 0.0.0-stage → 2.2.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 +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/http.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { ArkNetworkError, ArkOAuthError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The HTTP layer: one place that knows how this server answers, so nothing above it has to.
|
|
5
|
+
*
|
|
6
|
+
* Two rules are worth stating because the rest of the library depends on them. Every non-2xx
|
|
7
|
+
* response is turned into an ArkOAuthError carrying the server's own `error` code — the Ark
|
|
8
|
+
* server never answers a protocol failure with HTTP 200 and a message in the body, so there is no
|
|
9
|
+
* "success that is really an error" case to unpick. And every request is bounded by a timeout,
|
|
10
|
+
* because a token endpoint that accepts a connection and then stops talking would otherwise hang
|
|
11
|
+
* a request thread until the client gives up, which it never does.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
15
|
+
|
|
16
|
+
/** Merges the caller's abort signal with our own timeout, on whichever Node version is running. */
|
|
17
|
+
function withTimeout(signal, timeoutMs) {
|
|
18
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
19
|
+
if (!signal) return timeout;
|
|
20
|
+
if (typeof AbortSignal.any === 'function') return AbortSignal.any([signal, timeout]);
|
|
21
|
+
|
|
22
|
+
// Node 20.0–20.2 has no AbortSignal.any; forward the first abort by hand.
|
|
23
|
+
const controller = new AbortController();
|
|
24
|
+
const abort = (reason) => controller.abort(reason);
|
|
25
|
+
if (signal.aborted) abort(signal.reason);
|
|
26
|
+
else signal.addEventListener('abort', () => abort(signal.reason), { once: true });
|
|
27
|
+
timeout.addEventListener('abort', () => abort(timeout.reason), { once: true });
|
|
28
|
+
return controller.signal;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function readBody(response) {
|
|
32
|
+
const text = await response.text();
|
|
33
|
+
if (!text) return null;
|
|
34
|
+
const type = response.headers.get('content-type') ?? '';
|
|
35
|
+
if (type.includes('json') || text.trimStart().startsWith('{') || text.trimStart().startsWith('[')) {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(text);
|
|
38
|
+
} catch {
|
|
39
|
+
return text;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return text;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Performs one request and returns the parsed body.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} url
|
|
49
|
+
* @param {object} [options]
|
|
50
|
+
* @param {'GET'|'POST'|'DELETE'} [options.method]
|
|
51
|
+
* @param {Record<string,string|undefined|null>} [options.form] form-urlencoded body; null/undefined entries are dropped
|
|
52
|
+
* @param {object} [options.json] JSON body
|
|
53
|
+
* @param {Record<string,string>} [options.headers]
|
|
54
|
+
* @param {number} [options.timeoutMs]
|
|
55
|
+
* @param {AbortSignal} [options.signal]
|
|
56
|
+
* @param {typeof fetch} [options.fetch]
|
|
57
|
+
*/
|
|
58
|
+
export async function request(url, options = {}) {
|
|
59
|
+
const {
|
|
60
|
+
method = 'GET',
|
|
61
|
+
form,
|
|
62
|
+
json,
|
|
63
|
+
headers = {},
|
|
64
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
65
|
+
signal,
|
|
66
|
+
fetch: fetchImpl = globalThis.fetch
|
|
67
|
+
} = options;
|
|
68
|
+
|
|
69
|
+
if (typeof fetchImpl !== 'function') {
|
|
70
|
+
throw new ArkNetworkError(
|
|
71
|
+
'no fetch implementation is available. Node 20 or newer provides one globally; otherwise pass `fetch` in the client options.'
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const init = {
|
|
76
|
+
method,
|
|
77
|
+
headers: { Accept: 'application/json', ...headers },
|
|
78
|
+
signal: withTimeout(signal, timeoutMs),
|
|
79
|
+
// A token response must never be cached, and neither must a userinfo response keyed on a
|
|
80
|
+
// bearer token that will be a different user's tomorrow.
|
|
81
|
+
cache: 'no-store',
|
|
82
|
+
// A GET of metadata or keys may follow a redirect — an http-to-https hop is common, and the
|
|
83
|
+
// issuer check on the document is what actually establishes trust. A POST may not: it carries
|
|
84
|
+
// a client secret or an authorization code, and a redirect would forward them somewhere else.
|
|
85
|
+
redirect: method === 'GET' ? 'follow' : 'manual'
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
if (form) {
|
|
89
|
+
const body = new URLSearchParams();
|
|
90
|
+
for (const [key, value] of Object.entries(form)) {
|
|
91
|
+
if (value === undefined || value === null || value === '') continue;
|
|
92
|
+
body.set(key, String(value));
|
|
93
|
+
}
|
|
94
|
+
init.body = body;
|
|
95
|
+
init.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
96
|
+
} else if (json !== undefined) {
|
|
97
|
+
init.body = JSON.stringify(json);
|
|
98
|
+
init.headers['Content-Type'] = 'application/json';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let response;
|
|
102
|
+
try {
|
|
103
|
+
response = await fetchImpl(url, init);
|
|
104
|
+
} catch (cause) {
|
|
105
|
+
const timedOut = cause?.name === 'TimeoutError' || cause?.cause?.name === 'TimeoutError';
|
|
106
|
+
throw new ArkNetworkError(
|
|
107
|
+
timedOut ? `${method} ${url} timed out after ${timeoutMs}ms.` : `${method} ${url} failed: ${cause?.message ?? cause}`,
|
|
108
|
+
{ cause }
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const body = await readBody(response);
|
|
113
|
+
if (!response.ok) throw ArkOAuthError.fromResponse(response.status, body, url);
|
|
114
|
+
return { status: response.status, body, headers: response.headers };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** GET returning a JSON object. */
|
|
118
|
+
export async function getJson(url, options) {
|
|
119
|
+
const { body } = await request(url, { ...options, method: 'GET' });
|
|
120
|
+
if (!body || typeof body !== 'object') {
|
|
121
|
+
throw new ArkOAuthError('server_error', `${url} did not return a JSON object.`, { endpoint: url, body });
|
|
122
|
+
}
|
|
123
|
+
return body;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** POST a form-urlencoded body, returning the JSON response. */
|
|
127
|
+
export async function postForm(url, form, options) {
|
|
128
|
+
const { body, status } = await request(url, { ...options, method: 'POST', form });
|
|
129
|
+
// Revocation answers 200 with an empty body (RFC 7009 §2.2) — that is a success, not a shape error.
|
|
130
|
+
if (body === null) return {};
|
|
131
|
+
if (typeof body !== 'object') {
|
|
132
|
+
throw new ArkOAuthError('server_error', `${url} returned HTTP ${status} with a non-JSON body.`, {
|
|
133
|
+
endpoint: url,
|
|
134
|
+
status,
|
|
135
|
+
body
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return body;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The `Authorization: Basic` value for `client_secret_basic`.
|
|
143
|
+
*
|
|
144
|
+
* RFC 6749 §2.3.1 requires both halves to be form-urlencoded *before* they are joined and
|
|
145
|
+
* base64'd, which matters the moment a generated client secret contains a `+` or a `:`. The Ark
|
|
146
|
+
* server URL-decodes both halves on the way in, so a client that skips the encoding authenticates
|
|
147
|
+
* fine until the day it is issued a secret with a reserved character in it.
|
|
148
|
+
*/
|
|
149
|
+
export function basicAuthHeader(clientId, clientSecret) {
|
|
150
|
+
const encode = (value) => encodeURIComponent(value).replace(/%20/g, '+');
|
|
151
|
+
const raw = `${encode(clientId)}:${encode(clientSecret ?? '')}`;
|
|
152
|
+
return `Basic ${Buffer.from(raw, 'utf8').toString('base64')}`;
|
|
153
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ark-oauth-client-node — the OAuth 2.1 / OpenID Connect client for Node applications talking to an
|
|
3
|
+
* Ark identity server.
|
|
4
|
+
*
|
|
5
|
+
* There is one URL to configure: the issuer, `{BaseUrl}/{TenantId}`. Every endpoint, signing key
|
|
6
|
+
* and capability is read from the provider's discovery document, so an application does not need
|
|
7
|
+
* to be redeployed when the provider rotates a key or moves an endpoint.
|
|
8
|
+
*
|
|
9
|
+
* import { ArkOAuthClient, arkExpress } from 'ark-oauth-client-node';
|
|
10
|
+
*
|
|
11
|
+
* const auth = arkExpress({
|
|
12
|
+
* authority: 'https://idp.example.com/my_idp',
|
|
13
|
+
* clientId: 'my-app',
|
|
14
|
+
* redirectUri: 'https://app.example.com/signin-oidc',
|
|
15
|
+
* secret: process.env.ARK_SESSION_SECRET
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* app.use(auth);
|
|
19
|
+
* app.get('/billing', auth.requireClaims('billing.admin'), handler);
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export { VERSION } from './version.js';
|
|
23
|
+
export { ArkOAuthClient, createArkClient } from './client.js';
|
|
24
|
+
export { arkExpress, arkBearer } from './express.js';
|
|
25
|
+
export { ArkAuthConfig } from './app-config.js';
|
|
26
|
+
export {
|
|
27
|
+
ArkAccessDeniedReasons,
|
|
28
|
+
ArkChallengeProperties,
|
|
29
|
+
ACCOUNT_SWITCH_DEFAULTS,
|
|
30
|
+
normalizeAccountSwitch,
|
|
31
|
+
localOrDefault
|
|
32
|
+
} from './access.js';
|
|
33
|
+
export { renderAccessDeniedPage } from './denied-page.js';
|
|
34
|
+
export { TokenSet } from './tokens.js';
|
|
35
|
+
export { MetadataResolver, discoveryUrls } from './discovery.js';
|
|
36
|
+
export { JwksCache } from './jwks.js';
|
|
37
|
+
export { MemorySessionStore, createSessionId, parseCookies, serializeCookie, signSessionId, unsignSessionId } from './session.js';
|
|
38
|
+
export { createCodeVerifier, codeChallengeFor, createPkcePair, createState, createNonce } from './pkce.js';
|
|
39
|
+
export { decodeJwt, verifyJwt, signJwt, validateClaims, validateTokenHashes, verifySignature } from './jwt.js';
|
|
40
|
+
export { base64UrlDecode, base64UrlEncode, leftHalfHash, randomToken } from './crypto.js';
|
|
41
|
+
export { normalizeConfig, DEFAULT_SCOPES } from './config.js';
|
|
42
|
+
export { ArkError, ArkConfigError, ArkOAuthError, ArkTokenError, ArkCallbackError, ArkNetworkError } from './errors.js';
|
package/src/jwks.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { getJson } from './http.js';
|
|
2
|
+
import { ArkTokenError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
const KTY_FOR_ALG = { RS: 'RSA', PS: 'RSA', ES: 'EC' };
|
|
5
|
+
const MAX_REMEMBERED_MISSES = 256;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The provider's signing keys, cached and refreshed on rotation.
|
|
9
|
+
*
|
|
10
|
+
* Ark rotates in two phases: the new key becomes `active` and starts signing, the previous one
|
|
11
|
+
* moves to `rollover` and stays published until the last token it signed has expired. Both are in
|
|
12
|
+
* the JWKS at once, so a client that caches the document keeps validating tokens across the
|
|
13
|
+
* change — provided it refreshes when it meets a `kid` it has never seen. That refresh is the
|
|
14
|
+
* whole point of this class, and it is what the old Ark client could not do at all: its public key
|
|
15
|
+
* was a base64 string pasted into appsettings.json, so a rotation broke every deployment by hand.
|
|
16
|
+
*
|
|
17
|
+
* The refresh is rate-limited. Without a cooldown, a stream of tokens bearing a bogus `kid` would
|
|
18
|
+
* turn into a stream of requests to the provider's JWKS endpoint — a denial-of-service amplifier
|
|
19
|
+
* pointed at your own identity server.
|
|
20
|
+
*/
|
|
21
|
+
export class JwksCache {
|
|
22
|
+
#uri;
|
|
23
|
+
#ttlMs;
|
|
24
|
+
#cooldownMs;
|
|
25
|
+
#http;
|
|
26
|
+
#keys = null;
|
|
27
|
+
#fetchedAt = 0;
|
|
28
|
+
#inFlight = null;
|
|
29
|
+
#missing = new Set();
|
|
30
|
+
|
|
31
|
+
constructor(jwksUri, { ttlMs = 5 * 60_000, minRefreshIntervalMs = 10_000, ...http } = {}) {
|
|
32
|
+
this.#uri = jwksUri;
|
|
33
|
+
this.#ttlMs = ttlMs;
|
|
34
|
+
this.#cooldownMs = minRefreshIntervalMs;
|
|
35
|
+
this.#http = http;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get uri() {
|
|
39
|
+
return this.#uri;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Every published key, fetching or refreshing as needed. */
|
|
43
|
+
async keys({ force = false } = {}) {
|
|
44
|
+
const stale = Date.now() - this.#fetchedAt > this.#ttlMs;
|
|
45
|
+
if (this.#keys && !force && !stale) return this.#keys;
|
|
46
|
+
return this.#load();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The key that signed a token, chosen by `kid` and constrained to the algorithm's key type.
|
|
51
|
+
*
|
|
52
|
+
* A token with no `kid` is resolved only when the provider publishes exactly one usable key —
|
|
53
|
+
* guessing among several would mean trying each until one verifies, which turns an
|
|
54
|
+
* unauthenticated caller into an oracle for which keys are live.
|
|
55
|
+
*/
|
|
56
|
+
async getSigningKey(kid, alg) {
|
|
57
|
+
let candidates = this.#select(await this.keys(), kid, alg);
|
|
58
|
+
|
|
59
|
+
if (candidates.length === 0) {
|
|
60
|
+
// An unknown kid is the normal signal that the provider has rotated, so the first sight of
|
|
61
|
+
// one earns a refetch. The second sight of the *same* unknown kid does not: it is either a
|
|
62
|
+
// token from another provider or a probe, and re-reading JWKS for each one would point a
|
|
63
|
+
// request amplifier at the identity server. The rate limit covers the remaining case, a
|
|
64
|
+
// flood of tokens each carrying a different invented kid.
|
|
65
|
+
const marker = kid ?? '\u0000none';
|
|
66
|
+
if (!this.#missing.has(marker) && Date.now() - this.#fetchedAt >= this.#cooldownMs) {
|
|
67
|
+
candidates = this.#select(await this.keys({ force: true }), kid, alg);
|
|
68
|
+
}
|
|
69
|
+
if (candidates.length === 0) {
|
|
70
|
+
// Bounded, because every entry is a string an unauthenticated caller chose. Forgetting
|
|
71
|
+
// them costs at most one more refetch, and the cooldown still caps those.
|
|
72
|
+
if (this.#missing.size >= MAX_REMEMBERED_MISSES) this.#missing.clear();
|
|
73
|
+
this.#missing.add(marker);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (candidates.length === 0) {
|
|
78
|
+
throw new ArkTokenError(
|
|
79
|
+
kid
|
|
80
|
+
? `no key with kid '${kid}' is published at ${this.#uri}; the token may have been signed by a different provider.`
|
|
81
|
+
: `the token carries no 'kid' and ${this.#uri} publishes more than one key, so the signing key is ambiguous.`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return candidates[0];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Drops the cache — for tests, and for a deployment that knows a rotation just happened. */
|
|
88
|
+
clear() {
|
|
89
|
+
this.#keys = null;
|
|
90
|
+
this.#fetchedAt = 0;
|
|
91
|
+
this.#missing.clear();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#select(keys, kid, alg) {
|
|
95
|
+
const wantedKty = KTY_FOR_ALG[String(alg ?? '').slice(0, 2)];
|
|
96
|
+
const usable = keys.filter(
|
|
97
|
+
(k) => (!k.use || k.use === 'sig') && (!wantedKty || k.kty === wantedKty) && (!k.alg || !alg || k.alg === alg)
|
|
98
|
+
);
|
|
99
|
+
if (kid) return usable.filter((k) => k.kid === kid);
|
|
100
|
+
return usable.length === 1 ? usable : [];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async #load() {
|
|
104
|
+
// Collapse concurrent misses into one request: a burst of traffic arriving just after a
|
|
105
|
+
// rotation should cost the provider one JWKS fetch, not one per request.
|
|
106
|
+
this.#inFlight ??= (async () => {
|
|
107
|
+
try {
|
|
108
|
+
const document = await getJson(this.#uri, this.#http);
|
|
109
|
+
const keys = Array.isArray(document.keys) ? document.keys : [];
|
|
110
|
+
if (keys.length === 0) throw new ArkTokenError(`${this.#uri} published no keys.`);
|
|
111
|
+
this.#keys = keys;
|
|
112
|
+
this.#fetchedAt = Date.now();
|
|
113
|
+
// A fresh document may well contain the kid that was missing a moment ago.
|
|
114
|
+
this.#missing.clear();
|
|
115
|
+
return keys;
|
|
116
|
+
} finally {
|
|
117
|
+
this.#inFlight = null;
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
return this.#inFlight;
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/jwt.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { constants, createPrivateKey, createPublicKey, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto';
|
|
2
|
+
import { base64UrlDecode, base64UrlEncode, leftHalfHash } from './crypto.js';
|
|
3
|
+
import { ArkTokenError } from './errors.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* JWT decoding, signature verification and claim validation.
|
|
7
|
+
*
|
|
8
|
+
* The Ark server signs with RS256 and publishes its keys at `jwks_uri`, so that is the path this
|
|
9
|
+
* is tuned for; the other JWS families are accepted so the same client can be pointed at Entra ID,
|
|
10
|
+
* Okta or Auth0 without a second implementation.
|
|
11
|
+
*
|
|
12
|
+
* The one algorithm deliberately not supported is `none`. An unsigned token is a token anyone can
|
|
13
|
+
* write, and every historical JWT library vulnerability of note comes from honouring the `alg`
|
|
14
|
+
* header without first deciding which algorithms are acceptable.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const SUPPORTED_ALGORITHMS = new Map([
|
|
18
|
+
['RS256', { hash: 'sha256', kty: 'RSA' }],
|
|
19
|
+
['RS384', { hash: 'sha384', kty: 'RSA' }],
|
|
20
|
+
['RS512', { hash: 'sha512', kty: 'RSA' }],
|
|
21
|
+
['PS256', { hash: 'sha256', kty: 'RSA', pss: true }],
|
|
22
|
+
['PS384', { hash: 'sha384', kty: 'RSA', pss: true }],
|
|
23
|
+
['PS512', { hash: 'sha512', kty: 'RSA', pss: true }],
|
|
24
|
+
['ES256', { hash: 'sha256', kty: 'EC' }],
|
|
25
|
+
['ES384', { hash: 'sha384', kty: 'EC' }],
|
|
26
|
+
['ES512', { hash: 'sha512', kty: 'EC' }]
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Splits a compact JWS without verifying anything.
|
|
31
|
+
*
|
|
32
|
+
* Useful for reading `kid` before a key is chosen, or for logging a token's `sub` while
|
|
33
|
+
* diagnosing a failure — never for deciding anything. Nothing in this library authorises on the
|
|
34
|
+
* result of a decode.
|
|
35
|
+
*/
|
|
36
|
+
export function decodeJwt(token) {
|
|
37
|
+
if (typeof token !== 'string') throw new ArkTokenError('the token is not a string.');
|
|
38
|
+
const parts = token.split('.');
|
|
39
|
+
if (parts.length !== 3) {
|
|
40
|
+
throw new ArkTokenError(`the token is not a compact JWS: expected 3 segments, found ${parts.length}.`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let header;
|
|
44
|
+
let payload;
|
|
45
|
+
try {
|
|
46
|
+
header = JSON.parse(base64UrlDecode(parts[0]).toString('utf8'));
|
|
47
|
+
payload = JSON.parse(base64UrlDecode(parts[1]).toString('utf8'));
|
|
48
|
+
} catch (cause) {
|
|
49
|
+
throw new ArkTokenError('the token header or payload is not valid JSON.', { cause });
|
|
50
|
+
}
|
|
51
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
52
|
+
if (!isObject(header) || !isObject(payload)) {
|
|
53
|
+
throw new ArkTokenError('the token header and payload must both be JSON objects.');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
header,
|
|
58
|
+
payload,
|
|
59
|
+
signature: base64UrlDecode(parts[2]),
|
|
60
|
+
signingInput: `${parts[0]}.${parts[1]}`
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Verifies the signature of an already-decoded token against one JWK. */
|
|
65
|
+
export function verifySignature(decoded, jwk, { algorithms } = {}) {
|
|
66
|
+
const alg = decoded.header.alg;
|
|
67
|
+
if (!alg || alg === 'none') {
|
|
68
|
+
throw new ArkTokenError(`the token declares alg '${alg ?? 'missing'}'; unsigned tokens are never accepted.`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const allowed = algorithms ?? [...SUPPORTED_ALGORITHMS.keys()];
|
|
72
|
+
if (!allowed.includes(alg)) {
|
|
73
|
+
throw new ArkTokenError(`the token is signed with ${alg}, which this client does not accept (allowed: ${allowed.join(', ')}).`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const spec = SUPPORTED_ALGORITHMS.get(alg);
|
|
77
|
+
if (!spec) throw new ArkTokenError(`unsupported signing algorithm '${alg}'.`);
|
|
78
|
+
if (jwk.kty !== spec.kty) {
|
|
79
|
+
throw new ArkTokenError(`the signing key is a ${jwk.kty} key but the token declares ${alg}.`);
|
|
80
|
+
}
|
|
81
|
+
if (jwk.alg && jwk.alg !== alg) {
|
|
82
|
+
throw new ArkTokenError(`the key published for kid '${jwk.kid}' is registered for ${jwk.alg}, not ${alg}.`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let key;
|
|
86
|
+
try {
|
|
87
|
+
key = createPublicKey({ key: jwk, format: 'jwk' });
|
|
88
|
+
} catch (cause) {
|
|
89
|
+
throw new ArkTokenError(`the published key for kid '${jwk.kid}' could not be imported: ${cause.message}`, { cause });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const keyOptions = { key };
|
|
93
|
+
if (spec.pss) {
|
|
94
|
+
keyOptions.padding = constants.RSA_PKCS1_PSS_PADDING; // gitleaks:allow: an RSA padding constant, not a key
|
|
95
|
+
keyOptions.saltLength = constants.RSA_PSS_SALTLEN_DIGEST;
|
|
96
|
+
}
|
|
97
|
+
if (spec.kty === 'EC') {
|
|
98
|
+
// JWS carries an EC signature as raw r||s, not the DER sequence Node verifies by default.
|
|
99
|
+
keyOptions.dsaEncoding = 'ieee-p1363';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const ok = cryptoVerify(spec.hash, Buffer.from(decoded.signingInput, 'utf8'), keyOptions, decoded.signature);
|
|
103
|
+
if (!ok) throw new ArkTokenError('the token signature does not verify against the published key.');
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Validates the registered claims.
|
|
109
|
+
*
|
|
110
|
+
* Order matters less than completeness here: skipping any single one of these is how a token
|
|
111
|
+
* meant for a different application, a different provider or a different moment ends up
|
|
112
|
+
* authorising a request.
|
|
113
|
+
*/
|
|
114
|
+
export function validateClaims(payload, options = {}) {
|
|
115
|
+
const {
|
|
116
|
+
issuer,
|
|
117
|
+
audience,
|
|
118
|
+
subject,
|
|
119
|
+
nonce,
|
|
120
|
+
maxAgeSeconds,
|
|
121
|
+
clockToleranceSeconds = 60,
|
|
122
|
+
requireExp = true,
|
|
123
|
+
requireIat = false,
|
|
124
|
+
now = Math.floor(Date.now() / 1000)
|
|
125
|
+
} = options;
|
|
126
|
+
|
|
127
|
+
const fail = (message, claim) => {
|
|
128
|
+
throw new ArkTokenError(message, { claim });
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
if (issuer) {
|
|
132
|
+
if (!payload.iss) fail('the token has no `iss` claim.', 'iss');
|
|
133
|
+
if (payload.iss !== issuer) {
|
|
134
|
+
fail(`the token was issued by '${payload.iss}', not by '${issuer}'.`, 'iss');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (audience) {
|
|
139
|
+
const auds = Array.isArray(payload.aud) ? payload.aud : payload.aud ? [payload.aud] : [];
|
|
140
|
+
if (auds.length === 0) fail('the token has no `aud` claim.', 'aud');
|
|
141
|
+
if (!auds.includes(audience)) {
|
|
142
|
+
fail(`the token is addressed to ${auds.map((a) => `'${a}'`).join(', ')}, not to '${audience}'.`, 'aud');
|
|
143
|
+
}
|
|
144
|
+
// OIDC Core §3.1.3.7: with several audiences, `azp` must name the party the token is for.
|
|
145
|
+
if (auds.length > 1 && payload.azp && payload.azp !== audience) {
|
|
146
|
+
fail(`the token names '${payload.azp}' as its authorized party, not '${audience}'.`, 'azp');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (subject && payload.sub !== subject) {
|
|
151
|
+
fail(`the token belongs to subject '${payload.sub}', not '${subject}'.`, 'sub');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (payload.exp === undefined) {
|
|
155
|
+
if (requireExp) fail('the token has no `exp` claim.', 'exp');
|
|
156
|
+
} else if (typeof payload.exp !== 'number' || now >= payload.exp + clockToleranceSeconds) {
|
|
157
|
+
fail(`the token expired at ${new Date((payload.exp ?? 0) * 1000).toISOString()}.`, 'exp');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// A time claim that is not a number compares false against everything, so it would pass every
|
|
161
|
+
// check below unnoticed. RFC 7519 §2 makes them NumericDate; anything else is a malformed token.
|
|
162
|
+
for (const claim of ['nbf', 'iat']) {
|
|
163
|
+
if (payload[claim] !== undefined && (typeof payload[claim] !== 'number' || !Number.isFinite(payload[claim]))) {
|
|
164
|
+
fail(`the token's \`${claim}\` is not a NumericDate.`, claim);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (payload.nbf !== undefined && now + clockToleranceSeconds < payload.nbf) {
|
|
169
|
+
fail(`the token is not valid before ${new Date(payload.nbf * 1000).toISOString()}.`, 'nbf');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (payload.iat === undefined) {
|
|
173
|
+
if (requireIat) fail('the token has no `iat` claim.', 'iat');
|
|
174
|
+
} else if (now + clockToleranceSeconds < payload.iat) {
|
|
175
|
+
fail(`the token was issued in the future, at ${new Date(payload.iat * 1000).toISOString()}.`, 'iat');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (nonce !== undefined && nonce !== null) {
|
|
179
|
+
// A missing nonce is as bad as a wrong one: it means the ID token was not bound to our
|
|
180
|
+
// authorization request and could have been minted for someone else's session.
|
|
181
|
+
if (!payload.nonce) fail('the ID token has no `nonce`, so it cannot be tied to this sign-in.', 'nonce');
|
|
182
|
+
if (payload.nonce !== nonce) fail('the ID token `nonce` does not match the one sent with the authorization request.', 'nonce');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (maxAgeSeconds !== undefined && maxAgeSeconds !== null) {
|
|
186
|
+
if (typeof payload.auth_time !== 'number') {
|
|
187
|
+
fail('`max_age` was requested but the ID token carries no `auth_time`.', 'auth_time');
|
|
188
|
+
}
|
|
189
|
+
if (now - payload.auth_time > maxAgeSeconds + clockToleranceSeconds) {
|
|
190
|
+
fail(`the user authenticated ${now - payload.auth_time}s ago, beyond the requested max_age of ${maxAgeSeconds}s.`, 'auth_time');
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return payload;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Checks `at_hash` / `c_hash` (OIDC Core §3.1.3.6).
|
|
199
|
+
*
|
|
200
|
+
* These are what stop an attacker swapping in an access token or an authorization code of their
|
|
201
|
+
* own alongside a genuine ID token — the substitution attack the hashes exist for. The Ark server
|
|
202
|
+
* always issues both, so a missing one is worth surfacing rather than skipping quietly.
|
|
203
|
+
*/
|
|
204
|
+
export function validateTokenHashes(payload, { accessToken, code, require: required = true } = {}) {
|
|
205
|
+
const check = (claim, value) => {
|
|
206
|
+
if (!value) return;
|
|
207
|
+
const present = payload[claim];
|
|
208
|
+
if (!present) {
|
|
209
|
+
if (required) throw new ArkTokenError(`the ID token has no \`${claim}\`, so the ${claim === 'at_hash' ? 'access token' : 'authorization code'} it arrived with cannot be tied to it.`, { claim });
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (present !== leftHalfHash(value)) {
|
|
213
|
+
throw new ArkTokenError(`the ID token \`${claim}\` does not cover the value it arrived with — it may have been substituted.`, { claim });
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
check('at_hash', accessToken);
|
|
218
|
+
check('c_hash', code);
|
|
219
|
+
return payload;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The whole check for one token: signature against the provider's published keys, then claims.
|
|
224
|
+
*
|
|
225
|
+
* @param {string} token
|
|
226
|
+
* @param {{getSigningKey(kid: string|undefined, alg: string): Promise<object>}} jwks
|
|
227
|
+
*/
|
|
228
|
+
export async function verifyJwt(token, jwks, options = {}) {
|
|
229
|
+
const decoded = decodeJwt(token);
|
|
230
|
+
|
|
231
|
+
if (options.typ) {
|
|
232
|
+
// RFC 9068 §4: an access token declares `at+jwt`, which is how a resource server refuses an
|
|
233
|
+
// ID token presented in its place. Both spellings are seen in the wild.
|
|
234
|
+
const typ = String(decoded.header.typ ?? '').toLowerCase();
|
|
235
|
+
const expected = String(options.typ).toLowerCase();
|
|
236
|
+
if (typ !== expected && typ !== `application/${expected}`) {
|
|
237
|
+
throw new ArkTokenError(`expected a token of type '${options.typ}' but the header declares '${decoded.header.typ ?? 'none'}'.`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const jwk = await jwks.getSigningKey(decoded.header.kid, decoded.header.alg);
|
|
242
|
+
verifySignature(decoded, jwk, { algorithms: options.algorithms });
|
|
243
|
+
validateClaims(decoded.payload, options);
|
|
244
|
+
if (options.accessToken || options.code) {
|
|
245
|
+
validateTokenHashes(decoded.payload, {
|
|
246
|
+
accessToken: options.accessToken,
|
|
247
|
+
code: options.code,
|
|
248
|
+
require: options.requireTokenHashes !== false
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return decoded.payload;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Signs a compact JWS.
|
|
256
|
+
*
|
|
257
|
+
* Needed for exactly one thing on the client side: the `private_key_jwt` client assertion (OIDC
|
|
258
|
+
* Core §9), where the client proves who it is with a signature instead of a shared secret that
|
|
259
|
+
* has to be stored, rotated and kept out of logs on both ends.
|
|
260
|
+
*
|
|
261
|
+
* @param {object} payload
|
|
262
|
+
* @param {object} options
|
|
263
|
+
* @param {import('node:crypto').KeyObject|string|object} options.key PEM, JWK or KeyObject
|
|
264
|
+
* @param {string} [options.alg] RS256 by default — what the Ark server accepts
|
|
265
|
+
* @param {string} [options.kid] published in the header so the verifier can pick the right key
|
|
266
|
+
* @param {string} [options.typ]
|
|
267
|
+
*/
|
|
268
|
+
export function signJwt(payload, { key, alg = 'RS256', kid, typ = 'JWT', header: extraHeader } = {}) {
|
|
269
|
+
const spec = SUPPORTED_ALGORITHMS.get(alg);
|
|
270
|
+
if (!spec) throw new ArkTokenError(`cannot sign with '${alg}'; supported: ${[...SUPPORTED_ALGORITHMS.keys()].join(', ')}.`);
|
|
271
|
+
|
|
272
|
+
let privateKey;
|
|
273
|
+
try {
|
|
274
|
+
privateKey =
|
|
275
|
+
typeof key === 'object' && key !== null && !Buffer.isBuffer(key) && key.asymmetricKeyType
|
|
276
|
+
? key
|
|
277
|
+
: createPrivateKey(typeof key === 'object' && !Buffer.isBuffer(key) ? { key, format: 'jwk' } : key);
|
|
278
|
+
} catch (cause) {
|
|
279
|
+
throw new ArkTokenError(`the signing key could not be imported: ${cause.message}`, { cause });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const head = { alg, typ, ...(kid ? { kid } : {}), ...extraHeader };
|
|
283
|
+
const signingInput = `${base64UrlEncode(JSON.stringify(head))}.${base64UrlEncode(JSON.stringify(payload))}`;
|
|
284
|
+
|
|
285
|
+
const keyOptions = { key: privateKey };
|
|
286
|
+
if (spec.pss) {
|
|
287
|
+
keyOptions.padding = constants.RSA_PKCS1_PSS_PADDING; // gitleaks:allow: an RSA padding constant, not a key
|
|
288
|
+
keyOptions.saltLength = constants.RSA_PSS_SALTLEN_DIGEST;
|
|
289
|
+
}
|
|
290
|
+
if (spec.kty === 'EC') keyOptions.dsaEncoding = 'ieee-p1363';
|
|
291
|
+
|
|
292
|
+
const signature = cryptoSign(spec.hash, Buffer.from(signingInput, 'utf8'), keyOptions);
|
|
293
|
+
return `${signingInput}.${base64UrlEncode(signature)}`;
|
|
294
|
+
}
|
package/src/pkce.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { base64UrlEncode, randomToken, sha256 } from './crypto.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* PKCE (RFC 7636), `state` and `nonce`.
|
|
5
|
+
*
|
|
6
|
+
* The Ark server requires PKCE for every public client and accepts `S256` only — `plain` is not
|
|
7
|
+
* implemented, because a plain challenge is the verifier and protects nothing once the
|
|
8
|
+
* authorization request has been observed.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A code verifier: 32 random bytes as base64url, which lands at 43 characters — the minimum
|
|
13
|
+
* RFC 7636 §4.1 allows, and entirely within its unreserved character set.
|
|
14
|
+
*/
|
|
15
|
+
export function createCodeVerifier() {
|
|
16
|
+
return randomToken(32);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** BASE64URL(SHA256(verifier)) — the `code_challenge` for `code_challenge_method=S256`. */
|
|
20
|
+
export function codeChallengeFor(verifier) {
|
|
21
|
+
return base64UrlEncode(sha256(verifier));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A `state` value: CSRF protection for the authorization response, and the key a login transaction is stored under. */
|
|
25
|
+
export function createState() {
|
|
26
|
+
return randomToken(24);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A `nonce`: binds the ID token to this authorization request so a captured one cannot be replayed. */
|
|
30
|
+
export function createNonce() {
|
|
31
|
+
return randomToken(24);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Verifier, challenge and method in one object, for callers driving the flow by hand. */
|
|
35
|
+
export function createPkcePair() {
|
|
36
|
+
const codeVerifier = createCodeVerifier();
|
|
37
|
+
return {
|
|
38
|
+
codeVerifier,
|
|
39
|
+
codeChallenge: codeChallengeFor(codeVerifier),
|
|
40
|
+
codeChallengeMethod: 'S256'
|
|
41
|
+
};
|
|
42
|
+
}
|