@oauth-spa-kit/core 1.0.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/LICENSE +21 -0
- package/dist/base64url.d.ts +11 -0
- package/dist/base64url.js +27 -0
- package/dist/clientAssertion.d.ts +14 -0
- package/dist/clientAssertion.js +35 -0
- package/dist/discovery.d.ts +7 -0
- package/dist/discovery.js +28 -0
- package/dist/dpop.d.ts +51 -0
- package/dist/dpop.js +62 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +24 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/jwks.d.ts +2 -0
- package/dist/jwks.js +20 -0
- package/dist/jwt.d.ts +45 -0
- package/dist/jwt.js +80 -0
- package/dist/par.d.ts +25 -0
- package/dist/par.js +21 -0
- package/dist/pkce.d.ts +20 -0
- package/dist/pkce.js +33 -0
- package/dist/sessionClient.d.ts +30 -0
- package/dist/sessionClient.js +57 -0
- package/dist/tokenExchange.d.ts +35 -0
- package/dist/tokenExchange.js +100 -0
- package/dist/types.d.ts +88 -0
- package/dist/types.js +1 -0
- package/package.json +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ehncraft
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function base64UrlEncode(bytes: Uint8Array): string;
|
|
2
|
+
/**
|
|
3
|
+
* Return type is deliberately the concrete `Uint8Array<ArrayBuffer>`, not
|
|
4
|
+
* the bare `Uint8Array` (which TS's dom lib now type-parameterizes over
|
|
5
|
+
* `ArrayBufferLike`, including `SharedArrayBuffer`) -- Web Crypto's
|
|
6
|
+
* `sign`/`verify`/`decrypt` require an actual `ArrayBuffer`-backed view,
|
|
7
|
+
* and a wider annotation here would silently erase that at every call site.
|
|
8
|
+
*/
|
|
9
|
+
export declare function base64UrlDecode(value: string): Uint8Array<ArrayBuffer>;
|
|
10
|
+
export declare function base64UrlEncodeJson(value: unknown): string;
|
|
11
|
+
export declare function base64UrlDecodeJson<T>(value: string): T;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export function base64UrlEncode(bytes) {
|
|
2
|
+
let binary = "";
|
|
3
|
+
for (const b of bytes)
|
|
4
|
+
binary += String.fromCharCode(b);
|
|
5
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Return type is deliberately the concrete `Uint8Array<ArrayBuffer>`, not
|
|
9
|
+
* the bare `Uint8Array` (which TS's dom lib now type-parameterizes over
|
|
10
|
+
* `ArrayBufferLike`, including `SharedArrayBuffer`) -- Web Crypto's
|
|
11
|
+
* `sign`/`verify`/`decrypt` require an actual `ArrayBuffer`-backed view,
|
|
12
|
+
* and a wider annotation here would silently erase that at every call site.
|
|
13
|
+
*/
|
|
14
|
+
export function base64UrlDecode(value) {
|
|
15
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
16
|
+
const binary = atob(padded);
|
|
17
|
+
const bytes = new Uint8Array(binary.length);
|
|
18
|
+
for (let i = 0; i < binary.length; i++)
|
|
19
|
+
bytes[i] = binary.charCodeAt(i);
|
|
20
|
+
return bytes;
|
|
21
|
+
}
|
|
22
|
+
export function base64UrlEncodeJson(value) {
|
|
23
|
+
return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)));
|
|
24
|
+
}
|
|
25
|
+
export function base64UrlDecodeJson(value) {
|
|
26
|
+
return JSON.parse(new TextDecoder().decode(base64UrlDecode(value)));
|
|
27
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ClientAuthentication } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* RFC 7523 `private_key_jwt` client assertion -- the form params to attach
|
|
4
|
+
* alongside `client_id` when authenticating to the token endpoint or the
|
|
5
|
+
* PAR endpoint. This is the *only* client authentication method this kit
|
|
6
|
+
* supports; there is no client_secret fallback (see the comment on
|
|
7
|
+
* `ClientAuthentication` in types.ts for why).
|
|
8
|
+
*
|
|
9
|
+
* `audience` is conventionally the URL of the endpoint being authenticated
|
|
10
|
+
* to (OIDC Core section 9); a few authorization servers expect the issuer
|
|
11
|
+
* identifier instead regardless of which endpoint is called -- check your
|
|
12
|
+
* AS's docs if it rejects the assertion with an audience error.
|
|
13
|
+
*/
|
|
14
|
+
export declare function buildClientAssertionParams(clientId: string, clientAuth: ClientAuthentication, audience: string): Promise<Record<string, string>>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { signJwt } from "./jwt";
|
|
2
|
+
import { generateRandomString } from "./pkce";
|
|
3
|
+
/**
|
|
4
|
+
* RFC 7523 `private_key_jwt` client assertion -- the form params to attach
|
|
5
|
+
* alongside `client_id` when authenticating to the token endpoint or the
|
|
6
|
+
* PAR endpoint. This is the *only* client authentication method this kit
|
|
7
|
+
* supports; there is no client_secret fallback (see the comment on
|
|
8
|
+
* `ClientAuthentication` in types.ts for why).
|
|
9
|
+
*
|
|
10
|
+
* `audience` is conventionally the URL of the endpoint being authenticated
|
|
11
|
+
* to (OIDC Core section 9); a few authorization servers expect the issuer
|
|
12
|
+
* identifier instead regardless of which endpoint is called -- check your
|
|
13
|
+
* AS's docs if it rejects the assertion with an audience error.
|
|
14
|
+
*/
|
|
15
|
+
export async function buildClientAssertionParams(clientId, clientAuth, audience) {
|
|
16
|
+
const now = Math.floor(Date.now() / 1000);
|
|
17
|
+
const lifetimeSeconds = clientAuth.assertionLifetimeSeconds ?? 60;
|
|
18
|
+
const assertion = await signJwt({
|
|
19
|
+
header: clientAuth.keyId ? { kid: clientAuth.keyId } : {},
|
|
20
|
+
payload: {
|
|
21
|
+
iss: clientId,
|
|
22
|
+
sub: clientId,
|
|
23
|
+
aud: audience,
|
|
24
|
+
jti: generateRandomString(16),
|
|
25
|
+
iat: now,
|
|
26
|
+
exp: now + lifetimeSeconds,
|
|
27
|
+
},
|
|
28
|
+
privateKey: clientAuth.privateKey,
|
|
29
|
+
alg: clientAuth.alg ?? "ES256",
|
|
30
|
+
});
|
|
31
|
+
return {
|
|
32
|
+
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
|
|
33
|
+
client_assertion: assertion,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { OidcDiscoveryDocument } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* Fetch and cache `${issuer}/.well-known/openid-configuration`.
|
|
4
|
+
* Prefer passing a static `discoveryDocument` in config for providers whose
|
|
5
|
+
* metadata you already know, to shave a round trip off the first navigation.
|
|
6
|
+
*/
|
|
7
|
+
export declare function discoverOidcConfiguration(issuer: string, fetchImpl?: typeof fetch): Promise<OidcDiscoveryDocument>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { DiscoveryError } from "./errors";
|
|
2
|
+
const cache = new Map();
|
|
3
|
+
const CACHE_TTL_MS = 60 * 60 * 1000; // 1h -- discovery docs change essentially never, but don't cache forever
|
|
4
|
+
/**
|
|
5
|
+
* Fetch and cache `${issuer}/.well-known/openid-configuration`.
|
|
6
|
+
* Prefer passing a static `discoveryDocument` in config for providers whose
|
|
7
|
+
* metadata you already know, to shave a round trip off the first navigation.
|
|
8
|
+
*/
|
|
9
|
+
export async function discoverOidcConfiguration(issuer, fetchImpl = fetch) {
|
|
10
|
+
const cached = cache.get(issuer);
|
|
11
|
+
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
|
|
12
|
+
return cached.doc;
|
|
13
|
+
}
|
|
14
|
+
const url = `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
15
|
+
let response;
|
|
16
|
+
try {
|
|
17
|
+
response = await fetchImpl(url);
|
|
18
|
+
}
|
|
19
|
+
catch (cause) {
|
|
20
|
+
throw new DiscoveryError(`Failed to fetch discovery document from ${url}`, cause);
|
|
21
|
+
}
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
throw new DiscoveryError(`Discovery endpoint ${url} returned ${response.status}`);
|
|
24
|
+
}
|
|
25
|
+
const doc = (await response.json());
|
|
26
|
+
cache.set(issuer, { doc, fetchedAt: Date.now() });
|
|
27
|
+
return doc;
|
|
28
|
+
}
|
package/dist/dpop.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DPoP (RFC 9449) -- sender-constrained tokens. Required by default in this
|
|
3
|
+
* kit (FAPI 2.0 requires DPoP or mTLS for confidential clients; DPoP is the
|
|
4
|
+
* one that doesn't need a client-certificate PKI). Every token request/use
|
|
5
|
+
* is bound to a private key.
|
|
6
|
+
*
|
|
7
|
+
* Keys are generated **extractable**: in the original in-browser design for
|
|
8
|
+
* this kit, non-extractable was the point (an XSS payload executing as the
|
|
9
|
+
* page couldn't exfiltrate the key even with full JS execution). Once
|
|
10
|
+
* everything moved server-side for the BFF pattern, key generation happens
|
|
11
|
+
* in this process, not in a browser tab an attacker's script can run in --
|
|
12
|
+
* the actual risk here is a compromised session store, which encrypting the
|
|
13
|
+
* exported key at rest (via the same AES-256-GCM sealing already used for
|
|
14
|
+
* the session cookie) already covers. Extractability is required in
|
|
15
|
+
* practice anyway: a DPoP-bound refresh token must be renewed with the
|
|
16
|
+
* *same* key that obtained it, and a `CryptoKey` object cannot itself
|
|
17
|
+
* survive across stateless HTTP requests -- only its exported JWK can.
|
|
18
|
+
*
|
|
19
|
+
* This mirrors the server-side verification already done by
|
|
20
|
+
* apisix/custom-plugins/apisix/plugins/dpop-verify.lua in this workspace's
|
|
21
|
+
* rd-infra-lab gateway -- same RFC, opposite end of the connection.
|
|
22
|
+
*/
|
|
23
|
+
export interface DpopKeyPair {
|
|
24
|
+
publicKey: CryptoKey;
|
|
25
|
+
privateKey: CryptoKey;
|
|
26
|
+
}
|
|
27
|
+
export declare function generateDpopKeyPair(): Promise<DpopKeyPair>;
|
|
28
|
+
export interface SerializedDpopKeyPair {
|
|
29
|
+
privateJwk: JsonWebKey;
|
|
30
|
+
publicJwk: JsonWebKey;
|
|
31
|
+
}
|
|
32
|
+
/** For persisting a key pair across requests (PKCE cookie during the redirect, session cookie thereafter) -- see the module comment for why extractability is unavoidable here. */
|
|
33
|
+
export declare function exportDpopKeyPair(keyPair: DpopKeyPair): Promise<SerializedDpopKeyPair>;
|
|
34
|
+
export declare function importDpopKeyPair(serialized: SerializedDpopKeyPair): Promise<DpopKeyPair>;
|
|
35
|
+
/**
|
|
36
|
+
* RFC 7638 JWK SHA-256 thumbprint, used as the `dpop_jkt` authorization
|
|
37
|
+
* request parameter (RFC 9449 section 10) -- binds the authorization code
|
|
38
|
+
* itself to this DPoP key, before any token is even issued, so a stolen
|
|
39
|
+
* code can't be redeemed with a different key pair.
|
|
40
|
+
*/
|
|
41
|
+
export declare function computeJwkThumbprint(publicKey: CryptoKey): Promise<string>;
|
|
42
|
+
export interface CreateDpopProofArgs {
|
|
43
|
+
keyPair: DpopKeyPair;
|
|
44
|
+
htm: string;
|
|
45
|
+
htu: string;
|
|
46
|
+
/** Access token being presented alongside this proof (resource requests only, not the initial token request). */
|
|
47
|
+
accessToken?: string;
|
|
48
|
+
/** `DPoP-Nonce` value the server previously returned, if any. */
|
|
49
|
+
nonce?: string;
|
|
50
|
+
}
|
|
51
|
+
export declare function createDpopProof({ keyPair, htm, htu, accessToken, nonce, }: CreateDpopProofArgs): Promise<string>;
|
package/dist/dpop.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { base64UrlEncode } from "./base64url";
|
|
2
|
+
import { signJwt } from "./jwt";
|
|
3
|
+
import { generateRandomString } from "./pkce";
|
|
4
|
+
export async function generateDpopKeyPair() {
|
|
5
|
+
const { publicKey, privateKey } = await globalThis.crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" },
|
|
6
|
+
/* extractable */ true, ["sign", "verify"]);
|
|
7
|
+
return { publicKey, privateKey };
|
|
8
|
+
}
|
|
9
|
+
/** For persisting a key pair across requests (PKCE cookie during the redirect, session cookie thereafter) -- see the module comment for why extractability is unavoidable here. */
|
|
10
|
+
export async function exportDpopKeyPair(keyPair) {
|
|
11
|
+
const [privateJwk, publicJwk] = await Promise.all([
|
|
12
|
+
globalThis.crypto.subtle.exportKey("jwk", keyPair.privateKey),
|
|
13
|
+
globalThis.crypto.subtle.exportKey("jwk", keyPair.publicKey),
|
|
14
|
+
]);
|
|
15
|
+
return { privateJwk, publicJwk };
|
|
16
|
+
}
|
|
17
|
+
export async function importDpopKeyPair(serialized) {
|
|
18
|
+
const params = { name: "ECDSA", namedCurve: "P-256" };
|
|
19
|
+
const [privateKey, publicKey] = await Promise.all([
|
|
20
|
+
globalThis.crypto.subtle.importKey("jwk", serialized.privateJwk, params, true, ["sign"]),
|
|
21
|
+
globalThis.crypto.subtle.importKey("jwk", serialized.publicJwk, params, true, ["verify"]),
|
|
22
|
+
]);
|
|
23
|
+
return { privateKey, publicKey };
|
|
24
|
+
}
|
|
25
|
+
function publicJwkClaims(jwk) {
|
|
26
|
+
// Only the fields the RFC actually requires in a DPoP proof's `jwk` header.
|
|
27
|
+
return { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* RFC 7638 JWK SHA-256 thumbprint, used as the `dpop_jkt` authorization
|
|
31
|
+
* request parameter (RFC 9449 section 10) -- binds the authorization code
|
|
32
|
+
* itself to this DPoP key, before any token is even issued, so a stolen
|
|
33
|
+
* code can't be redeemed with a different key pair.
|
|
34
|
+
*/
|
|
35
|
+
export async function computeJwkThumbprint(publicKey) {
|
|
36
|
+
const jwk = publicJwkClaims(await globalThis.crypto.subtle.exportKey("jwk", publicKey));
|
|
37
|
+
// RFC 7638 section 3: lexicographic member order, no insignificant whitespace.
|
|
38
|
+
const canonical = `{"crv":"${jwk.crv}","kty":"${jwk.kty}","x":"${jwk.x}","y":"${jwk.y}"}`;
|
|
39
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
|
|
40
|
+
return base64UrlEncode(new Uint8Array(digest));
|
|
41
|
+
}
|
|
42
|
+
export async function createDpopProof({ keyPair, htm, htu, accessToken, nonce, }) {
|
|
43
|
+
const payload = {
|
|
44
|
+
jti: generateRandomString(16),
|
|
45
|
+
htm,
|
|
46
|
+
htu,
|
|
47
|
+
iat: Math.floor(Date.now() / 1000),
|
|
48
|
+
};
|
|
49
|
+
if (nonce)
|
|
50
|
+
payload.nonce = nonce;
|
|
51
|
+
if (accessToken) {
|
|
52
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
|
|
53
|
+
payload.ath = base64UrlEncode(new Uint8Array(digest));
|
|
54
|
+
}
|
|
55
|
+
const publicJwk = publicJwkClaims(await globalThis.crypto.subtle.exportKey("jwk", keyPair.publicKey));
|
|
56
|
+
return signJwt({
|
|
57
|
+
header: { typ: "dpop+jwt", jwk: publicJwk },
|
|
58
|
+
payload,
|
|
59
|
+
privateKey: keyPair.privateKey,
|
|
60
|
+
alg: "ES256",
|
|
61
|
+
});
|
|
62
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare class OAuthError extends Error {
|
|
2
|
+
readonly cause?: unknown | undefined;
|
|
3
|
+
constructor(message: string, cause?: unknown | undefined);
|
|
4
|
+
}
|
|
5
|
+
export declare class TokenExchangeError extends OAuthError {
|
|
6
|
+
readonly error?: string | undefined;
|
|
7
|
+
readonly errorDescription?: string | undefined;
|
|
8
|
+
constructor(message: string, error?: string | undefined, errorDescription?: string | undefined);
|
|
9
|
+
}
|
|
10
|
+
export declare class DiscoveryError extends OAuthError {
|
|
11
|
+
constructor(message: string, cause?: unknown);
|
|
12
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export class OAuthError extends Error {
|
|
2
|
+
cause;
|
|
3
|
+
constructor(message, cause) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.cause = cause;
|
|
6
|
+
this.name = "OAuthError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export class TokenExchangeError extends OAuthError {
|
|
10
|
+
error;
|
|
11
|
+
errorDescription;
|
|
12
|
+
constructor(message, error, errorDescription) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.error = error;
|
|
15
|
+
this.errorDescription = errorDescription;
|
|
16
|
+
this.name = "TokenExchangeError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class DiscoveryError extends OAuthError {
|
|
20
|
+
constructor(message, cause) {
|
|
21
|
+
super(message, cause);
|
|
22
|
+
this.name = "DiscoveryError";
|
|
23
|
+
}
|
|
24
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "./types";
|
|
2
|
+
export * from "./errors";
|
|
3
|
+
export * from "./base64url";
|
|
4
|
+
export * from "./pkce";
|
|
5
|
+
export * from "./discovery";
|
|
6
|
+
export * from "./dpop";
|
|
7
|
+
export * from "./jwt";
|
|
8
|
+
export * from "./jwks";
|
|
9
|
+
export * from "./clientAssertion";
|
|
10
|
+
export * from "./par";
|
|
11
|
+
export * from "./tokenExchange";
|
|
12
|
+
export * from "./sessionClient";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "./types";
|
|
2
|
+
export * from "./errors";
|
|
3
|
+
export * from "./base64url";
|
|
4
|
+
export * from "./pkce";
|
|
5
|
+
export * from "./discovery";
|
|
6
|
+
export * from "./dpop";
|
|
7
|
+
export * from "./jwt";
|
|
8
|
+
export * from "./jwks";
|
|
9
|
+
export * from "./clientAssertion";
|
|
10
|
+
export * from "./par";
|
|
11
|
+
export * from "./tokenExchange";
|
|
12
|
+
export * from "./sessionClient";
|
package/dist/jwks.d.ts
ADDED
package/dist/jwks.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { DiscoveryError } from "./errors";
|
|
2
|
+
const cache = new Map();
|
|
3
|
+
const CACHE_TTL_MS = 60 * 60 * 1000;
|
|
4
|
+
export async function fetchJwks(jwksUri, fetchImpl = fetch) {
|
|
5
|
+
const cached = cache.get(jwksUri);
|
|
6
|
+
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS)
|
|
7
|
+
return cached.jwks;
|
|
8
|
+
let response;
|
|
9
|
+
try {
|
|
10
|
+
response = await fetchImpl(jwksUri);
|
|
11
|
+
}
|
|
12
|
+
catch (cause) {
|
|
13
|
+
throw new DiscoveryError(`Failed to fetch JWKS from ${jwksUri}`, cause);
|
|
14
|
+
}
|
|
15
|
+
if (!response.ok)
|
|
16
|
+
throw new DiscoveryError(`JWKS endpoint ${jwksUri} returned ${response.status}`);
|
|
17
|
+
const jwks = (await response.json());
|
|
18
|
+
cache.set(jwksUri, { jwks, fetchedAt: Date.now() });
|
|
19
|
+
return jwks;
|
|
20
|
+
}
|
package/dist/jwt.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { OAuthError } from "./errors";
|
|
2
|
+
/**
|
|
3
|
+
* PS256 (RSA-PSS) and ES256 (ECDSA P-256) only -- no RS256. FAPI 2.0
|
|
4
|
+
* Security Profile requires PS256 or ES256 for asymmetric client/request
|
|
5
|
+
* signing; RS256's PKCS#1 v1.5 padding is legacy and excluded. Both
|
|
6
|
+
* remaining algorithms are FIPS 140-approved (FIPS 186-4/186-5) given
|
|
7
|
+
* approved parameters (RSA >=2048-bit for PS256, P-256 for ES256).
|
|
8
|
+
*/
|
|
9
|
+
export type JwtAlgorithm = "PS256" | "ES256";
|
|
10
|
+
export declare class JwtVerificationError extends OAuthError {
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
13
|
+
export interface SignJwtArgs {
|
|
14
|
+
/** Merged over `{ alg, typ: "JWT" }` -- pass `typ`/`kid`/`jwk` etc. here to override or extend. */
|
|
15
|
+
header?: Record<string, unknown>;
|
|
16
|
+
payload: Record<string, unknown>;
|
|
17
|
+
privateKey: CryptoKey;
|
|
18
|
+
alg: JwtAlgorithm;
|
|
19
|
+
}
|
|
20
|
+
export declare function signJwt({ header, payload, privateKey, alg }: SignJwtArgs): Promise<string>;
|
|
21
|
+
export interface Jwks {
|
|
22
|
+
keys: (JsonWebKey & {
|
|
23
|
+
kid?: string;
|
|
24
|
+
alg?: string;
|
|
25
|
+
})[];
|
|
26
|
+
}
|
|
27
|
+
export interface VerifyJwtArgs {
|
|
28
|
+
token: string;
|
|
29
|
+
jwks: Jwks;
|
|
30
|
+
expectedIssuer: string;
|
|
31
|
+
expectedAudience: string;
|
|
32
|
+
expectedNonce?: string;
|
|
33
|
+
/** Seconds of leeway on `exp`/`iat` checks, to tolerate clock skew between this server and the IdP. */
|
|
34
|
+
clockToleranceSeconds?: number;
|
|
35
|
+
}
|
|
36
|
+
export interface VerifiedJwt {
|
|
37
|
+
header: Record<string, unknown>;
|
|
38
|
+
payload: Record<string, unknown>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Verify a JWT's signature against a JWKS and its standard claims. Used to
|
|
42
|
+
* verify `id_token`s (RFC 9449 has nothing to do with this -- this is plain
|
|
43
|
+
* OIDC core section 3.1.3.7) before any of its claims are trusted.
|
|
44
|
+
*/
|
|
45
|
+
export declare function verifyJwt({ token, jwks, expectedIssuer, expectedAudience, expectedNonce, clockToleranceSeconds, }: VerifyJwtArgs): Promise<VerifiedJwt>;
|
package/dist/jwt.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { base64UrlDecode, base64UrlDecodeJson, base64UrlEncode, base64UrlEncodeJson } from "./base64url";
|
|
2
|
+
import { OAuthError } from "./errors";
|
|
3
|
+
export class JwtVerificationError extends OAuthError {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "JwtVerificationError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function signVerifyParams(alg) {
|
|
10
|
+
switch (alg) {
|
|
11
|
+
case "PS256": return { name: "RSA-PSS", saltLength: 32 }; // salt length = SHA-256 digest size, per RFC 7518 section 3.5
|
|
12
|
+
case "ES256": return { name: "ECDSA", hash: "SHA-256" };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function importParams(alg) {
|
|
16
|
+
switch (alg) {
|
|
17
|
+
case "PS256": return { name: "RSA-PSS", hash: "SHA-256" };
|
|
18
|
+
case "ES256": return { name: "ECDSA", namedCurve: "P-256" };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function signJwt({ header = {}, payload, privateKey, alg }) {
|
|
22
|
+
const fullHeader = { alg, typ: "JWT", ...header };
|
|
23
|
+
const signingInput = `${base64UrlEncodeJson(fullHeader)}.${base64UrlEncodeJson(payload)}`;
|
|
24
|
+
const signature = await globalThis.crypto.subtle.sign(signVerifyParams(alg), privateKey, new TextEncoder().encode(signingInput));
|
|
25
|
+
return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
|
|
26
|
+
}
|
|
27
|
+
async function importVerificationKey(jwk, alg) {
|
|
28
|
+
return globalThis.crypto.subtle.importKey("jwk", jwk, importParams(alg), false, ["verify"]);
|
|
29
|
+
}
|
|
30
|
+
function algFromJwtHeader(header) {
|
|
31
|
+
if (header.alg === "PS256" || header.alg === "ES256")
|
|
32
|
+
return header.alg;
|
|
33
|
+
throw new JwtVerificationError(`Unsupported or missing JWT "alg": ${String(header.alg)} (only PS256/ES256 are accepted -- RS256 and HMAC algs are rejected for FAPI/FIPS compliance)`);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Verify a JWT's signature against a JWKS and its standard claims. Used to
|
|
37
|
+
* verify `id_token`s (RFC 9449 has nothing to do with this -- this is plain
|
|
38
|
+
* OIDC core section 3.1.3.7) before any of its claims are trusted.
|
|
39
|
+
*/
|
|
40
|
+
export async function verifyJwt({ token, jwks, expectedIssuer, expectedAudience, expectedNonce, clockToleranceSeconds = 60, }) {
|
|
41
|
+
const parts = token.split(".");
|
|
42
|
+
if (parts.length !== 3)
|
|
43
|
+
throw new JwtVerificationError("Malformed JWT: expected 3 dot-separated parts");
|
|
44
|
+
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
|
45
|
+
const header = base64UrlDecodeJson(encodedHeader);
|
|
46
|
+
const payload = base64UrlDecodeJson(encodedPayload);
|
|
47
|
+
const alg = algFromJwtHeader(header);
|
|
48
|
+
const candidates = header.kid
|
|
49
|
+
? jwks.keys.filter((key) => key.kid === header.kid)
|
|
50
|
+
: jwks.keys.filter((key) => !key.alg || key.alg === alg);
|
|
51
|
+
if (candidates.length === 0) {
|
|
52
|
+
throw new JwtVerificationError(`No matching JWKS key found for kid=${String(header.kid)} alg=${alg}`);
|
|
53
|
+
}
|
|
54
|
+
let verified = false;
|
|
55
|
+
for (const jwk of candidates) {
|
|
56
|
+
const key = await importVerificationKey(jwk, alg);
|
|
57
|
+
const ok = await globalThis.crypto.subtle.verify(signVerifyParams(alg), key, base64UrlDecode(encodedSignature), new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`));
|
|
58
|
+
if (ok) {
|
|
59
|
+
verified = true;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!verified)
|
|
64
|
+
throw new JwtVerificationError("JWT signature verification failed against all candidate JWKS keys");
|
|
65
|
+
const now = Math.floor(Date.now() / 1000);
|
|
66
|
+
if (typeof payload.exp === "number" && now > payload.exp + clockToleranceSeconds) {
|
|
67
|
+
throw new JwtVerificationError("JWT has expired");
|
|
68
|
+
}
|
|
69
|
+
if (payload.iss !== expectedIssuer) {
|
|
70
|
+
throw new JwtVerificationError(`JWT "iss" mismatch: expected ${expectedIssuer}, got ${String(payload.iss)}`);
|
|
71
|
+
}
|
|
72
|
+
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
73
|
+
if (!audiences.includes(expectedAudience)) {
|
|
74
|
+
throw new JwtVerificationError(`JWT "aud" does not include expected client_id ${expectedAudience}`);
|
|
75
|
+
}
|
|
76
|
+
if (expectedNonce !== undefined && payload.nonce !== expectedNonce) {
|
|
77
|
+
throw new JwtVerificationError("JWT \"nonce\" does not match the nonce sent in the authorization request");
|
|
78
|
+
}
|
|
79
|
+
return { header, payload };
|
|
80
|
+
}
|
package/dist/par.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ClientAuthentication } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* RFC 9126 Pushed Authorization Requests -- required by FAPI 2.0. Instead
|
|
4
|
+
* of redirecting the browser to `/authorize` with every parameter
|
|
5
|
+
* (state, PKCE challenge, scope, ...) sitting in the URL -- visible in
|
|
6
|
+
* browser history, the `Referer` header, and server access logs -- the
|
|
7
|
+
* client POSTs those parameters directly to the AS, authenticated, and
|
|
8
|
+
* gets back a short-lived, single-use `request_uri` that the browser
|
|
9
|
+
* redirect then carries instead.
|
|
10
|
+
*/
|
|
11
|
+
export interface PushAuthorizationRequestArgs {
|
|
12
|
+
parEndpoint: string;
|
|
13
|
+
clientId: string;
|
|
14
|
+
clientAuthentication: ClientAuthentication;
|
|
15
|
+
/** Authorization server issuer identifier -- used to look up a client assertion audience if your AS expects it instead of the endpoint URL. Prefer passing the PAR endpoint URL itself unless your AS's docs say otherwise. */
|
|
16
|
+
assertionAudience: string;
|
|
17
|
+
/** Authorization request parameters (response_type, redirect_uri, scope, state, nonce, code_challenge, code_challenge_method, and any extras) -- everything that would otherwise go on the `/authorize` query string. */
|
|
18
|
+
params: Record<string, string>;
|
|
19
|
+
fetchImpl?: typeof fetch;
|
|
20
|
+
}
|
|
21
|
+
export interface PushedAuthorizationResponse {
|
|
22
|
+
request_uri: string;
|
|
23
|
+
expires_in: number;
|
|
24
|
+
}
|
|
25
|
+
export declare function pushAuthorizationRequest(args: PushAuthorizationRequestArgs): Promise<PushedAuthorizationResponse>;
|
package/dist/par.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { buildClientAssertionParams } from "./clientAssertion";
|
|
2
|
+
import { OAuthError } from "./errors";
|
|
3
|
+
export async function pushAuthorizationRequest(args) {
|
|
4
|
+
const fetchImpl = args.fetchImpl ?? fetch;
|
|
5
|
+
const assertionParams = await buildClientAssertionParams(args.clientId, args.clientAuthentication, args.assertionAudience);
|
|
6
|
+
const body = new URLSearchParams({
|
|
7
|
+
client_id: args.clientId,
|
|
8
|
+
...args.params,
|
|
9
|
+
...assertionParams,
|
|
10
|
+
});
|
|
11
|
+
const response = await fetchImpl(args.parEndpoint, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
14
|
+
body,
|
|
15
|
+
});
|
|
16
|
+
const json = await response.json().catch(() => ({}));
|
|
17
|
+
if (!response.ok) {
|
|
18
|
+
throw new OAuthError(`PAR endpoint returned ${response.status}: ${json.error ?? "unknown_error"} ${json.error_description ?? ""}`.trim());
|
|
19
|
+
}
|
|
20
|
+
return json;
|
|
21
|
+
}
|
package/dist/pkce.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PKCE (RFC 7636) and nonce/state generation.
|
|
3
|
+
*
|
|
4
|
+
* Uses only Web Crypto (`globalThis.crypto`), so this file runs unmodified in
|
|
5
|
+
* browsers, Node >=18, and edge runtimes (Workers/Deno/Vercel Edge) -- no
|
|
6
|
+
* Node-only `crypto` module import. OAuth 2.1 makes PKCE mandatory for all
|
|
7
|
+
* authorization-code clients, public or confidential, so this always runs,
|
|
8
|
+
* never treated as optional.
|
|
9
|
+
*/
|
|
10
|
+
/** Cryptographically random, URL-safe string for `state`, `nonce`, or a PKCE code_verifier. */
|
|
11
|
+
export declare function generateRandomString(length?: number): string;
|
|
12
|
+
export declare function generateCodeChallenge(codeVerifier: string): Promise<string>;
|
|
13
|
+
export interface PkceParams {
|
|
14
|
+
codeVerifier: string;
|
|
15
|
+
codeChallenge: string;
|
|
16
|
+
codeChallengeMethod: "S256";
|
|
17
|
+
state: string;
|
|
18
|
+
nonce: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function createPkceParams(): Promise<PkceParams>;
|
package/dist/pkce.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PKCE (RFC 7636) and nonce/state generation.
|
|
3
|
+
*
|
|
4
|
+
* Uses only Web Crypto (`globalThis.crypto`), so this file runs unmodified in
|
|
5
|
+
* browsers, Node >=18, and edge runtimes (Workers/Deno/Vercel Edge) -- no
|
|
6
|
+
* Node-only `crypto` module import. OAuth 2.1 makes PKCE mandatory for all
|
|
7
|
+
* authorization-code clients, public or confidential, so this always runs,
|
|
8
|
+
* never treated as optional.
|
|
9
|
+
*/
|
|
10
|
+
import { base64UrlEncode } from "./base64url";
|
|
11
|
+
function randomBytes(length) {
|
|
12
|
+
const bytes = new Uint8Array(length);
|
|
13
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
14
|
+
return bytes;
|
|
15
|
+
}
|
|
16
|
+
/** Cryptographically random, URL-safe string for `state`, `nonce`, or a PKCE code_verifier. */
|
|
17
|
+
export function generateRandomString(length = 32) {
|
|
18
|
+
return base64UrlEncode(randomBytes(length));
|
|
19
|
+
}
|
|
20
|
+
export async function generateCodeChallenge(codeVerifier) {
|
|
21
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
|
|
22
|
+
return base64UrlEncode(new Uint8Array(digest));
|
|
23
|
+
}
|
|
24
|
+
export async function createPkceParams() {
|
|
25
|
+
const codeVerifier = generateRandomString(32);
|
|
26
|
+
return {
|
|
27
|
+
codeVerifier,
|
|
28
|
+
codeChallenge: await generateCodeChallenge(codeVerifier),
|
|
29
|
+
codeChallengeMethod: "S256",
|
|
30
|
+
state: generateRandomString(16),
|
|
31
|
+
nonce: generateRandomString(16),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { SessionState } from "./types";
|
|
2
|
+
/**
|
|
3
|
+
* Browser-side session client for the BFF pattern: the SPA never sees an
|
|
4
|
+
* access or refresh token, only a same-origin `/auth/session` JSON endpoint
|
|
5
|
+
* backed by the server package's sealed HttpOnly cookie. This is
|
|
6
|
+
* deliberately as thin as nuxt-auth-utils' `useUserSession` composable --
|
|
7
|
+
* that simplicity is worth keeping -- but framework-agnostic so React/Vue/
|
|
8
|
+
* vanilla adapters can all wrap the same object instead of reimplementing
|
|
9
|
+
* fetch/cache/sync logic three times.
|
|
10
|
+
*
|
|
11
|
+
* Cross-tab sync uses BroadcastChannel instead of nuxt-auth-utils' storage-
|
|
12
|
+
* event trick: it's purpose-built for this (no localStorage key squatting)
|
|
13
|
+
* and is now supported in every evergreen browser.
|
|
14
|
+
*/
|
|
15
|
+
export interface SessionClientOptions {
|
|
16
|
+
/** Same-origin prefix the server package's handlers are mounted under. */
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
fetchImpl?: typeof fetch;
|
|
19
|
+
channelName?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface SessionClient {
|
|
22
|
+
getState(): SessionState;
|
|
23
|
+
subscribe(callback: (state: SessionState) => void): () => void;
|
|
24
|
+
/** Re-fetch `/auth/session`. Call after mount and after `login`/`logout` round trips. */
|
|
25
|
+
refresh(): Promise<void>;
|
|
26
|
+
/** Full-page navigation to the login handler -- there is no silent/iframe path in BFF mode. */
|
|
27
|
+
login(returnTo?: string): void;
|
|
28
|
+
logout(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare function createSessionClient(options?: SessionClientOptions): SessionClient;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const initialState = { ready: false, loggedIn: false, user: null };
|
|
2
|
+
export function createSessionClient(options = {}) {
|
|
3
|
+
const baseUrl = options.baseUrl ?? "";
|
|
4
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
5
|
+
const channel = typeof BroadcastChannel !== "undefined"
|
|
6
|
+
? new BroadcastChannel(options.channelName ?? "oauth-spa-kit")
|
|
7
|
+
: null;
|
|
8
|
+
let state = initialState;
|
|
9
|
+
const listeners = new Set();
|
|
10
|
+
function setState(next) {
|
|
11
|
+
state = next;
|
|
12
|
+
for (const listener of listeners)
|
|
13
|
+
listener(state);
|
|
14
|
+
}
|
|
15
|
+
async function refresh() {
|
|
16
|
+
try {
|
|
17
|
+
const response = await fetchImpl(`${baseUrl}/auth/session`, {
|
|
18
|
+
headers: { accept: "application/json" },
|
|
19
|
+
credentials: "same-origin",
|
|
20
|
+
});
|
|
21
|
+
if (response.status === 401) {
|
|
22
|
+
setState({ ready: true, loggedIn: false, user: null });
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (!response.ok)
|
|
26
|
+
throw new Error(`/auth/session returned ${response.status}`);
|
|
27
|
+
const body = await response.json();
|
|
28
|
+
setState({ ready: true, loggedIn: Boolean(body.user), user: body.user ?? null });
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
setState({ ready: true, loggedIn: false, user: null });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
channel?.addEventListener("message", (event) => {
|
|
35
|
+
if (event.data === "session-changed")
|
|
36
|
+
void refresh();
|
|
37
|
+
});
|
|
38
|
+
return {
|
|
39
|
+
getState: () => state,
|
|
40
|
+
subscribe(callback) {
|
|
41
|
+
listeners.add(callback);
|
|
42
|
+
return () => listeners.delete(callback);
|
|
43
|
+
},
|
|
44
|
+
refresh,
|
|
45
|
+
login(returnTo) {
|
|
46
|
+
const url = new URL(`${baseUrl}/auth/login`, window.location.origin);
|
|
47
|
+
if (returnTo)
|
|
48
|
+
url.searchParams.set("returnTo", returnTo);
|
|
49
|
+
window.location.assign(url.toString());
|
|
50
|
+
},
|
|
51
|
+
async logout() {
|
|
52
|
+
await fetchImpl(`${baseUrl}/auth/logout`, { method: "POST", credentials: "same-origin" });
|
|
53
|
+
setState({ ready: true, loggedIn: false, user: null });
|
|
54
|
+
channel?.postMessage("session-changed");
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type DpopKeyPair } from "./dpop";
|
|
2
|
+
import type { OAuthClientConfig, TokenResponse, TokenSet } from "./types";
|
|
3
|
+
export declare function toTokenSet(response: TokenResponse): TokenSet;
|
|
4
|
+
export interface ExchangeAuthorizationCodeArgs {
|
|
5
|
+
config: OAuthClientConfig;
|
|
6
|
+
tokenEndpoint: string;
|
|
7
|
+
code: string;
|
|
8
|
+
codeVerifier: string;
|
|
9
|
+
/** Reuse the same key pair used to bind the authorization request, if DPoP was used there too. A fresh one is generated if omitted and `config.dpop !== false`. */
|
|
10
|
+
dpopKeyPair?: DpopKeyPair;
|
|
11
|
+
fetchImpl?: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
/** RFC 6749 section 4.1.3 -- authorization_code grant, PKCE-verified, private_key_jwt-authenticated. */
|
|
14
|
+
export declare function exchangeAuthorizationCode(args: ExchangeAuthorizationCodeArgs): Promise<TokenSet>;
|
|
15
|
+
export interface ExchangeRefreshTokenArgs {
|
|
16
|
+
config: OAuthClientConfig;
|
|
17
|
+
tokenEndpoint: string;
|
|
18
|
+
refreshToken: string;
|
|
19
|
+
dpopKeyPair?: DpopKeyPair;
|
|
20
|
+
fetchImpl?: typeof fetch;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* RFC 6749 section 6 -- refresh_token grant.
|
|
24
|
+
*
|
|
25
|
+
* Always prefer this over a fresh interactive login when a refresh token
|
|
26
|
+
* is available (same choice `oidc-client-ts`'s `signinSilent()` makes) --
|
|
27
|
+
* one round trip instead of a full redirect, and no dependency on
|
|
28
|
+
* third-party-cookie access, which browsers increasingly restrict for
|
|
29
|
+
* `prompt=none` iframe flows. If your authorization server rotates refresh
|
|
30
|
+
* tokens (expected for public/BFF clients per OAuth 2.1), always persist
|
|
31
|
+
* the *new* `refresh_token` from the response -- the old one is
|
|
32
|
+
* invalidated on use, and reuse of an already-consumed refresh token is a
|
|
33
|
+
* signal of theft, not a retry-safe condition.
|
|
34
|
+
*/
|
|
35
|
+
export declare function exchangeRefreshToken(args: ExchangeRefreshTokenArgs): Promise<TokenSet>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { buildClientAssertionParams } from "./clientAssertion";
|
|
2
|
+
import { createDpopProof, generateDpopKeyPair } from "./dpop";
|
|
3
|
+
import { TokenExchangeError } from "./errors";
|
|
4
|
+
export function toTokenSet(response) {
|
|
5
|
+
return {
|
|
6
|
+
accessToken: response.access_token,
|
|
7
|
+
tokenType: response.token_type,
|
|
8
|
+
expiresAt: response.expires_in !== undefined ? Date.now() + response.expires_in * 1000 : null,
|
|
9
|
+
refreshToken: response.refresh_token,
|
|
10
|
+
idToken: response.id_token,
|
|
11
|
+
scope: response.scope,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
async function postTokenOnce({ tokenEndpoint, params, dpopKeyPair, fetchImpl }, dpopNonce) {
|
|
15
|
+
const headers = {
|
|
16
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
17
|
+
};
|
|
18
|
+
if (dpopKeyPair) {
|
|
19
|
+
headers["DPoP"] = await createDpopProof({
|
|
20
|
+
keyPair: dpopKeyPair,
|
|
21
|
+
htm: "POST",
|
|
22
|
+
htu: tokenEndpoint,
|
|
23
|
+
nonce: dpopNonce,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const response = await fetchImpl(tokenEndpoint, { method: "POST", headers, body: params });
|
|
27
|
+
const body = await response.json().catch(() => ({}));
|
|
28
|
+
return { response, body };
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* POSTs a token request, retrying exactly once if the server challenges
|
|
32
|
+
* with `error: "use_dpop_nonce"` + a `DPoP-Nonce` response header (RFC 9449
|
|
33
|
+
* section 8) -- a server-provided nonce the proof must echo back. Servers
|
|
34
|
+
* that don't require a nonce never trigger this path.
|
|
35
|
+
*/
|
|
36
|
+
async function postToken(args) {
|
|
37
|
+
let { response, body } = await postTokenOnce(args);
|
|
38
|
+
if (!response.ok && body.error === "use_dpop_nonce" && args.dpopKeyPair) {
|
|
39
|
+
const nonce = response.headers.get("DPoP-Nonce");
|
|
40
|
+
if (!nonce) {
|
|
41
|
+
throw new TokenExchangeError("Server returned use_dpop_nonce but no DPoP-Nonce header to retry with", body.error, body.error_description);
|
|
42
|
+
}
|
|
43
|
+
({ response, body } = await postTokenOnce(args, nonce));
|
|
44
|
+
}
|
|
45
|
+
if (!response.ok || !body.access_token || !body.token_type) {
|
|
46
|
+
throw new TokenExchangeError(`Token endpoint returned ${response.status}: ${body.error ?? "unknown_error"}`, body.error, body.error_description);
|
|
47
|
+
}
|
|
48
|
+
// Narrowed by the access_token/token_type check above.
|
|
49
|
+
return body;
|
|
50
|
+
}
|
|
51
|
+
/** RFC 6749 section 4.1.3 -- authorization_code grant, PKCE-verified, private_key_jwt-authenticated. */
|
|
52
|
+
export async function exchangeAuthorizationCode(args) {
|
|
53
|
+
const fetchImpl = args.fetchImpl ?? fetch;
|
|
54
|
+
const assertionParams = await buildClientAssertionParams(args.config.clientId, args.config.clientAuthentication, args.tokenEndpoint);
|
|
55
|
+
const params = new URLSearchParams({
|
|
56
|
+
grant_type: "authorization_code",
|
|
57
|
+
client_id: args.config.clientId,
|
|
58
|
+
code: args.code,
|
|
59
|
+
redirect_uri: args.config.redirectUri,
|
|
60
|
+
code_verifier: args.codeVerifier,
|
|
61
|
+
...assertionParams,
|
|
62
|
+
});
|
|
63
|
+
const dpopKeyPair = args.config.dpop === false
|
|
64
|
+
? undefined
|
|
65
|
+
: args.dpopKeyPair ?? await generateDpopKeyPair();
|
|
66
|
+
const response = await postToken({ tokenEndpoint: args.tokenEndpoint, params, dpopKeyPair, fetchImpl });
|
|
67
|
+
return toTokenSet(response);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* RFC 6749 section 6 -- refresh_token grant.
|
|
71
|
+
*
|
|
72
|
+
* Always prefer this over a fresh interactive login when a refresh token
|
|
73
|
+
* is available (same choice `oidc-client-ts`'s `signinSilent()` makes) --
|
|
74
|
+
* one round trip instead of a full redirect, and no dependency on
|
|
75
|
+
* third-party-cookie access, which browsers increasingly restrict for
|
|
76
|
+
* `prompt=none` iframe flows. If your authorization server rotates refresh
|
|
77
|
+
* tokens (expected for public/BFF clients per OAuth 2.1), always persist
|
|
78
|
+
* the *new* `refresh_token` from the response -- the old one is
|
|
79
|
+
* invalidated on use, and reuse of an already-consumed refresh token is a
|
|
80
|
+
* signal of theft, not a retry-safe condition.
|
|
81
|
+
*/
|
|
82
|
+
export async function exchangeRefreshToken(args) {
|
|
83
|
+
const fetchImpl = args.fetchImpl ?? fetch;
|
|
84
|
+
const assertionParams = await buildClientAssertionParams(args.config.clientId, args.config.clientAuthentication, args.tokenEndpoint);
|
|
85
|
+
const params = new URLSearchParams({
|
|
86
|
+
grant_type: "refresh_token",
|
|
87
|
+
client_id: args.config.clientId,
|
|
88
|
+
refresh_token: args.refreshToken,
|
|
89
|
+
...assertionParams,
|
|
90
|
+
});
|
|
91
|
+
const dpopKeyPair = args.config.dpop === false
|
|
92
|
+
? undefined
|
|
93
|
+
: args.dpopKeyPair ?? await generateDpopKeyPair();
|
|
94
|
+
const response = await postToken({ tokenEndpoint: args.tokenEndpoint, params, dpopKeyPair, fetchImpl });
|
|
95
|
+
const tokenSet = toTokenSet(response);
|
|
96
|
+
// Some servers omit refresh_token on renewal, meaning "unchanged" -- carry the old one forward.
|
|
97
|
+
if (!tokenSet.refreshToken)
|
|
98
|
+
tokenSet.refreshToken = args.refreshToken;
|
|
99
|
+
return tokenSet;
|
|
100
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static or discovered OIDC provider metadata (subset of the discovery doc
|
|
3
|
+
* we actually use -- see https://openid.net/specs/openid-connect-discovery-1_0.html).
|
|
4
|
+
*/
|
|
5
|
+
export interface OidcDiscoveryDocument {
|
|
6
|
+
issuer: string;
|
|
7
|
+
authorization_endpoint: string;
|
|
8
|
+
token_endpoint: string;
|
|
9
|
+
end_session_endpoint?: string;
|
|
10
|
+
jwks_uri?: string;
|
|
11
|
+
userinfo_endpoint?: string;
|
|
12
|
+
pushed_authorization_request_endpoint?: string;
|
|
13
|
+
require_pushed_authorization_requests?: boolean;
|
|
14
|
+
}
|
|
15
|
+
import type { JwtAlgorithm } from "./jwt";
|
|
16
|
+
/**
|
|
17
|
+
* Confidential-client authentication to the token endpoint, via a signed
|
|
18
|
+
* JWT assertion (RFC 7523 `private_key_jwt`) -- never a shared
|
|
19
|
+
* `client_secret`. This kit is built for FAPI 2.0 Security Profile and FIPS
|
|
20
|
+
* 140 compliance, both of which rule out shared-secret client
|
|
21
|
+
* authentication entirely: a `client_secret` is a long-lived bearer value
|
|
22
|
+
* that has to be transmitted and stored, where a private key signs an
|
|
23
|
+
* assertion without ever leaving this server.
|
|
24
|
+
*/
|
|
25
|
+
export interface ClientAuthentication {
|
|
26
|
+
method: "private_key_jwt";
|
|
27
|
+
/** Non-extractable if generated via `crypto.subtle.generateKey`; imported keys should be non-extractable too. */
|
|
28
|
+
privateKey: CryptoKey;
|
|
29
|
+
/** `kid` header claim, if your JWKS exposes more than one key. */
|
|
30
|
+
keyId?: string;
|
|
31
|
+
/** PS256 (RSA-PSS) or ES256 (ECDSA P-256) only -- see jwt.ts for why RS256 is excluded. Defaults to "ES256". */
|
|
32
|
+
alg?: JwtAlgorithm;
|
|
33
|
+
/** Assertion validity window. Keep short -- this is a bearer credential for its lifetime. Defaults to 60s. */
|
|
34
|
+
assertionLifetimeSeconds?: number;
|
|
35
|
+
}
|
|
36
|
+
export interface OAuthClientConfig {
|
|
37
|
+
/** Issuer base URL. Used for discovery unless `discoveryDocument` is provided directly. */
|
|
38
|
+
authority: string;
|
|
39
|
+
clientId: string;
|
|
40
|
+
clientAuthentication: ClientAuthentication;
|
|
41
|
+
redirectUri: string;
|
|
42
|
+
postLogoutRedirectUri?: string;
|
|
43
|
+
scope: string;
|
|
44
|
+
/** Pre-fetched discovery document, to skip the discovery round trip. */
|
|
45
|
+
discoveryDocument?: OidcDiscoveryDocument;
|
|
46
|
+
/**
|
|
47
|
+
* RFC 9449 DPoP sender-constrained tokens. **Defaults to `true`** --
|
|
48
|
+
* required by FAPI 2.0 for confidential clients (DPoP or mTLS; this kit
|
|
49
|
+
* only implements DPoP). Set explicitly to `false` only if your
|
|
50
|
+
* authorization server does not support DPoP at all.
|
|
51
|
+
*/
|
|
52
|
+
dpop?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* RFC 9126 Pushed Authorization Requests. **Defaults to `true`** --
|
|
55
|
+
* required by FAPI 2.0. Set explicitly to `false` only if your
|
|
56
|
+
* authorization server has no `pushed_authorization_request_endpoint`.
|
|
57
|
+
*/
|
|
58
|
+
par?: boolean;
|
|
59
|
+
extraAuthorizationParams?: Record<string, string>;
|
|
60
|
+
}
|
|
61
|
+
/** Raw token endpoint response (RFC 6749 section 5.1). */
|
|
62
|
+
export interface TokenResponse {
|
|
63
|
+
access_token: string;
|
|
64
|
+
token_type: string;
|
|
65
|
+
expires_in?: number;
|
|
66
|
+
refresh_token?: string;
|
|
67
|
+
id_token?: string;
|
|
68
|
+
scope?: string;
|
|
69
|
+
}
|
|
70
|
+
/** Normalized token set with an absolute expiry, as stored server-side (BFF) or in memory (public client). */
|
|
71
|
+
export interface TokenSet {
|
|
72
|
+
accessToken: string;
|
|
73
|
+
tokenType: string;
|
|
74
|
+
/** Epoch milliseconds. Absolute, so it survives serialization/storage without recomputation drift. */
|
|
75
|
+
expiresAt: number | null;
|
|
76
|
+
refreshToken?: string;
|
|
77
|
+
idToken?: string;
|
|
78
|
+
scope?: string;
|
|
79
|
+
}
|
|
80
|
+
export interface AuthenticatedUser {
|
|
81
|
+
sub: string;
|
|
82
|
+
[claim: string]: unknown;
|
|
83
|
+
}
|
|
84
|
+
export interface SessionState {
|
|
85
|
+
ready: boolean;
|
|
86
|
+
loggedIn: boolean;
|
|
87
|
+
user: AuthenticatedUser | null;
|
|
88
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oauth-spa-kit/core",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Framework- and runtime-agnostic OAuth 2.1 / OIDC primitives (PKCE, discovery, token exchange, DPoP) plus a fetch-based session client. Runs in the browser, Node, and edge runtimes -- no DOM or Node-only APIs.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ehncraft/oauth-spa-kit.git",
|
|
9
|
+
"directory": "packages/core"
|
|
10
|
+
},
|
|
11
|
+
"sideEffects": false,
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"typescript": "^5.6.0",
|
|
26
|
+
"vitest": "^2.1.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.json",
|
|
30
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
31
|
+
"test": "vitest run --root ../.. packages/core/test"
|
|
32
|
+
}
|
|
33
|
+
}
|