@kokuin/oauth 0.7.4 → 0.7.6

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/README.md CHANGED
@@ -9,6 +9,39 @@ A true leaf package — depends only on `@sozai/runtime`, `@noble/hashes`, and
9
9
  wrapping, no connector registry, no MCP resource discovery, no provider-specific
10
10
  authorization policy).
11
11
 
12
+ ## Client credentials (private_key_jwt)
13
+
14
+ `createClientAssertion` builds a signed JWT client assertion (EdDSA or ES256) and
15
+ `requestClientCredentialsToken` sends it to the token endpoint with the
16
+ `client_credentials` grant. The assertion `audience` is the authorisation
17
+ server's `issuer`. `createWebCryptoAssertionSigner` provides a signer backed by
18
+ `crypto.subtle`; any `ClientAssertionSigner` works. Algorithms other than `EdDSA`
19
+ and `ES256` are rejected at runtime with `Unsupported client assertion algorithm`.
20
+
21
+ ```ts
22
+ import {
23
+ createClientAssertion,
24
+ createWebCryptoAssertionSigner,
25
+ requestClientCredentialsToken,
26
+ } from '@kokuin/oauth'
27
+
28
+ const signer = createWebCryptoAssertionSigner({ alg: 'ES256', privateKey, kid: 'key-1' })
29
+ const assertion = await createClientAssertion({
30
+ signer,
31
+ clientID: 'my-client',
32
+ audience: 'https://auth.example.com', // the authorisation server issuer
33
+ runtime, // optional, source of randomness for `jti`, defaults to `globalThis.crypto`
34
+ })
35
+ const token = await requestClientCredentialsToken({
36
+ runtime,
37
+ tokenEndpoint: 'https://auth.example.com/token',
38
+ clientID: 'my-client',
39
+ assertion,
40
+ scope: 'read',
41
+ extraParams: { resource: 'https://mcp.example.com/' },
42
+ })
43
+ ```
44
+
12
45
  ## Named params migration
13
46
 
14
47
  | Export | Named params type | Fields |
@@ -1,9 +1,11 @@
1
1
  import type { OAuthProviderDefinition } from './types.js';
2
- export declare function buildAuthorizationURL(params: {
2
+ export type BuildAuthorizationURLParams = {
3
3
  definition: OAuthProviderDefinition;
4
4
  redirectURL: string;
5
5
  scopes: Array<string>;
6
6
  state: string;
7
- codeChallenge: string;
7
+ /** PKCE S256 challenge. When absent, no `code_challenge` params are set. */
8
+ codeChallenge?: string;
8
9
  authorizationParams?: Record<string, string>;
9
- }): string;
10
+ };
11
+ export declare function buildAuthorizationURL(params: BuildAuthorizationURLParams): string;
@@ -27,7 +27,9 @@ export function buildAuthorizationURL(params) {
27
27
  search.set('scope', scopes.join(' '));
28
28
  }
29
29
  search.set('state', state);
30
- search.set('code_challenge', codeChallenge);
31
- search.set('code_challenge_method', 'S256');
30
+ if (codeChallenge != null) {
31
+ search.set('code_challenge', codeChallenge);
32
+ search.set('code_challenge_method', 'S256');
33
+ }
32
34
  return url.toString();
33
35
  }
package/lib/broker.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { OAuthBrokerTransport } from './types.js';
2
2
  export type CreateHTTPBrokerTransportParams = {
3
- baseURL: string;
3
+ /** A resolver runs on every request, so the URL can change after the transport is created. */
4
+ baseURL: string | (() => string | Promise<string>);
4
5
  fetch: typeof globalThis.fetch;
5
6
  };
6
7
  export declare function createHTTPBrokerTransport(params: CreateHTTPBrokerTransportParams): OAuthBrokerTransport;
package/lib/broker.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import { fetchOAuthJSON } from './http.js';
2
2
  export function createHTTPBrokerTransport(params) {
3
- const baseURL = params.baseURL.replace(/\/+$/, '');
3
+ const resolveBaseURL = async ()=>{
4
+ const value = typeof params.baseURL === 'function' ? await params.baseURL() : params.baseURL;
5
+ return value.replace(/\/+$/, '');
6
+ };
4
7
  const runtime = {
5
8
  fetch: params.fetch
6
9
  };
7
10
  return {
8
11
  async authorize ({ provider, appRedirect, codeChallenge, scopes, authorizationParams, ...options }) {
12
+ const baseURL = await resolveBaseURL();
9
13
  const raw = await fetchOAuthJSON({
10
14
  runtime,
11
15
  url: `${baseURL}/oauth/${encodeURIComponent(provider)}/authorize`,
@@ -20,7 +24,8 @@ export function createHTTPBrokerTransport(params) {
20
24
  });
21
25
  return validateBrokerAuthorizeResult(raw);
22
26
  },
23
- token ({ provider, body, ...options }) {
27
+ async token ({ provider, body, ...options }) {
28
+ const baseURL = await resolveBaseURL();
24
29
  return fetchOAuthJSON({
25
30
  runtime,
26
31
  url: `${baseURL}/oauth/${encodeURIComponent(provider)}/token`,
@@ -0,0 +1,31 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ export declare const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
3
+ export type ClientAssertionAlgorithm = 'EdDSA' | 'ES256';
4
+ export type ClientAssertionSigner = {
5
+ alg: ClientAssertionAlgorithm;
6
+ kid?: string;
7
+ sign(data: Uint8Array): Promise<Uint8Array>;
8
+ };
9
+ export type CreateWebCryptoAssertionSignerParams = {
10
+ alg: ClientAssertionAlgorithm;
11
+ privateKey: CryptoKey;
12
+ kid?: string;
13
+ };
14
+ /**
15
+ * Signer backed by `crypto.subtle`: Ed25519 for `EdDSA`, ECDSA P-256 with SHA-256 for `ES256`
16
+ * (WebCrypto returns the raw r||s signature JWS expects).
17
+ */
18
+ export declare function createWebCryptoAssertionSigner(params: CreateWebCryptoAssertionSignerParams): ClientAssertionSigner;
19
+ export type CreateClientAssertionParams = {
20
+ signer: ClientAssertionSigner;
21
+ clientID: string;
22
+ audience: string;
23
+ lifetimeSeconds?: number;
24
+ /** Current time in seconds since epoch. */
25
+ now?: () => number;
26
+ typ?: string;
27
+ /** Source of randomness for the `jti` claim, defaults to `globalThis.crypto`. */
28
+ runtime?: Pick<Runtime, 'getRandomValues'>;
29
+ };
30
+ /** Build a signed JWT client assertion for `private_key_jwt` client authentication. */
31
+ export declare function createClientAssertion(params: CreateClientAssertionParams): Promise<string>;
@@ -0,0 +1,54 @@
1
+ import { fromUTF, toB64U } from '@sozai/codec';
2
+ export const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
3
+ const DEFAULT_TYP = 'client-authentication+jwt';
4
+ const DEFAULT_LIFETIME_SECONDS = 60;
5
+ function assertSupportedAlgorithm(alg) {
6
+ if (alg !== 'EdDSA' && alg !== 'ES256') {
7
+ throw new Error(`Unsupported client assertion algorithm: ${alg}`);
8
+ }
9
+ }
10
+ /**
11
+ * Signer backed by `crypto.subtle`: Ed25519 for `EdDSA`, ECDSA P-256 with SHA-256 for `ES256`
12
+ * (WebCrypto returns the raw r||s signature JWS expects).
13
+ */ export function createWebCryptoAssertionSigner(params) {
14
+ const { alg, privateKey, kid } = params;
15
+ assertSupportedAlgorithm(alg);
16
+ const algorithm = alg === 'EdDSA' ? {
17
+ name: 'Ed25519'
18
+ } : {
19
+ name: 'ECDSA',
20
+ hash: 'SHA-256'
21
+ };
22
+ return {
23
+ alg,
24
+ kid,
25
+ async sign (data) {
26
+ const signature = await globalThis.crypto.subtle.sign(algorithm, privateKey, data);
27
+ return new Uint8Array(signature);
28
+ }
29
+ };
30
+ }
31
+ /** Build a signed JWT client assertion for `private_key_jwt` client authentication. */ export async function createClientAssertion(params) {
32
+ const { signer, clientID, audience, lifetimeSeconds = DEFAULT_LIFETIME_SECONDS, now = ()=>Math.floor(Date.now() / 1000), typ = DEFAULT_TYP, runtime } = params;
33
+ assertSupportedAlgorithm(signer.alg);
34
+ const randomBytes = (length)=>runtime == null ? globalThis.crypto.getRandomValues(new Uint8Array(length)) : runtime.getRandomValues(new Uint8Array(length));
35
+ const iat = now();
36
+ const header = {
37
+ alg: signer.alg,
38
+ typ
39
+ };
40
+ if (signer.kid != null) {
41
+ header.kid = signer.kid;
42
+ }
43
+ const claims = {
44
+ iss: clientID,
45
+ sub: clientID,
46
+ aud: audience,
47
+ iat,
48
+ exp: iat + lifetimeSeconds,
49
+ jti: toB64U(randomBytes(16))
50
+ };
51
+ const signingInput = `${toB64U(fromUTF(JSON.stringify(header)))}.${toB64U(fromUTF(JSON.stringify(claims)))}`;
52
+ const signature = await signer.sign(fromUTF(signingInput));
53
+ return `${signingInput}.${toB64U(signature)}`;
54
+ }
@@ -0,0 +1,17 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ import type { RequestOptions, TokenResponse } from './types.js';
3
+ export type RequestClientCredentialsTokenParams = RequestOptions & {
4
+ runtime: Runtime;
5
+ tokenEndpoint: string;
6
+ clientID: string;
7
+ /** Signed client assertion, see `createClientAssertion`. */
8
+ assertion: string;
9
+ scope?: string;
10
+ /**
11
+ * Additional form fields, such as `resource` (RFC 8707). They never override the grant's own
12
+ * fields (`grant_type`, `client_id`, `client_assertion_type`, `client_assertion`, `scope`).
13
+ */
14
+ extraParams?: Record<string, string>;
15
+ };
16
+ /** Request an access token with the client credentials grant, authenticating via `private_key_jwt`. */
17
+ export declare function requestClientCredentialsToken(params: RequestClientCredentialsTokenParams): Promise<TokenResponse>;
@@ -0,0 +1,31 @@
1
+ import { CLIENT_ASSERTION_TYPE } from './client-assertion.js';
2
+ import { extraForm, validateTokenResponse } from './exchange.js';
3
+ import { fetchOAuthJSON } from './http.js';
4
+ const CLIENT_CREDENTIALS_FIELDS = new Set([
5
+ 'grant_type',
6
+ 'client_id',
7
+ 'client_assertion_type',
8
+ 'client_assertion',
9
+ 'scope'
10
+ ]);
11
+ /** Request an access token with the client credentials grant, authenticating via `private_key_jwt`. */ export async function requestClientCredentialsToken(params) {
12
+ const { runtime, tokenEndpoint, clientID, assertion, scope, extraParams, signal, timeoutMs, maxBytes } = params;
13
+ const form = extraForm(extraParams, CLIENT_CREDENTIALS_FIELDS);
14
+ form.set('grant_type', 'client_credentials');
15
+ form.set('client_id', clientID);
16
+ form.set('client_assertion_type', CLIENT_ASSERTION_TYPE);
17
+ form.set('client_assertion', assertion);
18
+ if (scope != null) {
19
+ form.set('scope', scope);
20
+ }
21
+ const raw = await fetchOAuthJSON({
22
+ runtime,
23
+ url: tokenEndpoint,
24
+ body: form.toString(),
25
+ contentType: 'application/x-www-form-urlencoded',
26
+ signal,
27
+ timeoutMs,
28
+ maxBytes
29
+ });
30
+ return validateTokenResponse(raw);
31
+ }
package/lib/exchange.d.ts CHANGED
@@ -25,4 +25,6 @@ export type RefreshTokenParams = {
25
25
  extraParams?: Record<string, string>;
26
26
  } & RequestOptions;
27
27
  export declare function refreshToken(params: RefreshTokenParams): Promise<TokenResponse>;
28
+ /** A form holding the caller's extra fields, minus the fields the grant itself owns. */
29
+ export declare function extraForm(extraParams: Record<string, string> | undefined, protectedFields: ReadonlySet<string>): URLSearchParams;
28
30
  export declare function validateTokenResponse(value: unknown): TokenResponse;
package/lib/exchange.js CHANGED
@@ -76,7 +76,7 @@ const REFRESH_GRANT_FIELDS = new Set([
76
76
  'client_id',
77
77
  'client_secret'
78
78
  ]);
79
- /** A form holding the caller's extra fields, minus the fields the grant itself owns. */ function extraForm(extraParams, protectedFields) {
79
+ /** A form holding the caller's extra fields, minus the fields the grant itself owns. */ export function extraForm(extraParams, protectedFields) {
80
80
  const form = new URLSearchParams();
81
81
  for (const [key, value] of Object.entries(extraParams ?? {})){
82
82
  if (!protectedFields.has(key)) form.set(key, value);
package/lib/http.d.ts CHANGED
@@ -20,4 +20,22 @@ export type FetchOAuthJSONParams = {
20
20
  body?: undefined;
21
21
  contentType?: undefined;
22
22
  }) & RequestOptions;
23
+ export type RequestOAuthJSONParams = FetchOAuthJSONParams & {
24
+ /**
25
+ * Extra request headers, such as `authorization: Basic …`. `accept` and, when there is a body,
26
+ * `content-type` are always set from the other params and win over the same names here
27
+ * (case-insensitive).
28
+ */
29
+ headers?: Record<string, string>;
30
+ };
31
+ export type OAuthJSONResponse = {
32
+ status: number;
33
+ /** The parsed JSON body, or `undefined` for an empty body or a non-JSON non-2xx body. */
34
+ body: unknown;
35
+ };
36
+ /**
37
+ * Send an OAuth request and return the status with the parsed JSON body. Unlike `fetchOAuthJSON`,
38
+ * it does not throw on a non-2xx status.
39
+ */
40
+ export declare function requestOAuthJSON(params: RequestOAuthJSONParams): Promise<OAuthJSONResponse>;
23
41
  export declare function fetchOAuthJSON(params: FetchOAuthJSONParams): Promise<unknown>;
package/lib/http.js CHANGED
@@ -2,56 +2,73 @@ import { assertSecureURL } from './secure-url.js';
2
2
  import { OAuthTokenError } from './types.js';
3
3
  const DEFAULT_MAX_BYTES = 1024 * 1024;
4
4
  const DEFAULT_TIMEOUT_MS = 30_000;
5
- export async function fetchOAuthJSON(params) {
6
- const { runtime, url, method = 'POST', allowEmpty = true, body, contentType, signal, maxBytes = DEFAULT_MAX_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = params;
5
+ /**
6
+ * Send an OAuth request and return the status with the parsed JSON body. Unlike `fetchOAuthJSON`,
7
+ * it does not throw on a non-2xx status.
8
+ */ export async function requestOAuthJSON(params) {
9
+ const { runtime, url, method = 'POST', allowEmpty = true, body, contentType, headers, signal, maxBytes = DEFAULT_MAX_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = params;
7
10
  assertSecureURL(url);
8
11
  const timeoutSignal = AbortSignal.timeout(timeoutMs);
9
12
  const combinedSignal = signal ? AbortSignal.any([
10
13
  signal,
11
14
  timeoutSignal
12
15
  ]) : timeoutSignal;
16
+ const requestHeaders = new Headers(headers);
17
+ requestHeaders.set('accept', 'application/json');
18
+ if (contentType != null) {
19
+ requestHeaders.set('content-type', contentType);
20
+ }
13
21
  const response = await runtime.fetch(url, {
14
22
  method,
15
- headers: contentType == null ? {
16
- accept: 'application/json'
17
- } : {
18
- 'content-type': contentType,
19
- accept: 'application/json'
20
- },
23
+ headers: Object.fromEntries(requestHeaders),
21
24
  body,
22
25
  redirect: 'error',
23
26
  signal: combinedSignal
24
27
  });
25
28
  const text = await readCappedText(response, maxBytes);
26
- if (!response.ok) {
27
- throw parseOAuthError(response.status, text);
28
- }
29
- if (allowEmpty && text.trim() === '') {
30
- return undefined;
29
+ if (text.trim() === '') {
30
+ if (response.ok && !allowEmpty) {
31
+ throw new Error('OAuth response was not valid JSON');
32
+ }
33
+ return {
34
+ status: response.status,
35
+ body: undefined
36
+ };
31
37
  }
32
38
  try {
33
- return JSON.parse(text);
39
+ return {
40
+ status: response.status,
41
+ body: JSON.parse(text)
42
+ };
34
43
  } catch {
44
+ if (!response.ok) {
45
+ return {
46
+ status: response.status,
47
+ body: undefined
48
+ };
49
+ }
35
50
  // biome-ignore lint/style/useErrorCause: no parsed error object to attach as cause
36
51
  throw new Error('OAuth response was not valid JSON');
37
52
  }
38
53
  }
39
- function parseOAuthError(status, text) {
54
+ export async function fetchOAuthJSON(params) {
55
+ const { status, body } = await requestOAuthJSON(params);
56
+ if (status < 200 || status > 299) {
57
+ throw toOAuthError(status, body);
58
+ }
59
+ return body;
60
+ }
61
+ function toOAuthError(status, body) {
40
62
  let code;
41
63
  let description;
42
- try {
43
- const parsed = JSON.parse(text);
44
- if (parsed != null && typeof parsed === 'object') {
45
- const record = parsed;
46
- if (typeof record.error === 'string') {
47
- code = record.error;
48
- }
49
- if (typeof record.error_description === 'string') {
50
- description = record.error_description;
51
- }
64
+ if (body != null && typeof body === 'object') {
65
+ const record = body;
66
+ if (typeof record.error === 'string') {
67
+ code = record.error;
68
+ }
69
+ if (typeof record.error_description === 'string') {
70
+ description = record.error_description;
52
71
  }
53
- } catch {
54
- // non-JSON / empty error body → code undefined (treated as transient by callers)
55
72
  }
56
73
  return new OAuthTokenError({
57
74
  status,
package/lib/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
- export { buildAuthorizationURL } from './authorization.js';
1
+ export { type BuildAuthorizationURLParams, buildAuthorizationURL } from './authorization.js';
2
2
  export { type CreateHTTPBrokerTransportParams, createHTTPBrokerTransport } from './broker.js';
3
+ export { CLIENT_ASSERTION_TYPE, type ClientAssertionAlgorithm, type ClientAssertionSigner, type CreateClientAssertionParams, type CreateWebCryptoAssertionSignerParams, createClientAssertion, createWebCryptoAssertionSigner, } from './client-assertion.js';
4
+ export { type RequestClientCredentialsTokenParams, requestClientCredentialsToken, } from './client-credentials.js';
3
5
  export { type DeviceAuthorization, pollDeviceToken, startDeviceAuthorization } from './device.js';
4
6
  export { exchangeCode, type RefreshTokenParams, refreshToken } from './exchange.js';
5
- export { type FetchOAuthJSONParams, fetchOAuthJSON } from './http.js';
7
+ export { type FetchOAuthJSONParams, fetchOAuthJSON, type OAuthJSONResponse, type RequestOAuthJSONParams, requestOAuthJSON, } from './http.js';
6
8
  export { type CompleteAuthorizationParams, completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, type PendingAuthRecord, type PendingAuthStore, type StartAuthorizationParams, startAuthorization, } from './pending-auth.js';
7
9
  export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
8
10
  export type { OAuthTokenErrorParams } from './types.js';
package/lib/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  export { buildAuthorizationURL } from './authorization.js';
2
2
  export { createHTTPBrokerTransport } from './broker.js';
3
+ export { CLIENT_ASSERTION_TYPE, createClientAssertion, createWebCryptoAssertionSigner } from './client-assertion.js';
4
+ export { requestClientCredentialsToken } from './client-credentials.js';
3
5
  export { pollDeviceToken, startDeviceAuthorization } from './device.js';
4
6
  export { exchangeCode, refreshToken } from './exchange.js';
5
- export { fetchOAuthJSON } from './http.js';
7
+ export { fetchOAuthJSON, requestOAuthJSON } from './http.js';
6
8
  export { completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, startAuthorization } from './pending-auth.js';
7
9
  export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
8
10
  export { OAuthTokenError } from './types.js';
@@ -1,2 +1 @@
1
1
  export declare function assertSecureURL(rawURL: string): void;
2
- export declare function isLoopbackHost(hostname: string): boolean;
package/lib/secure-url.js CHANGED
@@ -1,13 +1,11 @@
1
+ import { isLoopbackHost, normalizeHostname } from '@sozai/http-util';
1
2
  export function assertSecureURL(rawURL) {
2
3
  const url = new URL(rawURL);
3
4
  if (url.protocol === 'https:') {
4
5
  return;
5
6
  }
6
- if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) {
7
+ if (url.protocol === 'http:' && isLoopbackHost(normalizeHostname(url))) {
7
8
  return;
8
9
  }
9
10
  throw new Error(`OAuth endpoint must use https: ${rawURL}`);
10
11
  }
11
- export function isLoopbackHost(hostname) {
12
- return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]' || hostname.endsWith('.localhost');
13
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kokuin/oauth",
3
- "version": "0.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "Generic OAuth 2.0 client primitives for kokuin",
5
5
  "keywords": [
6
6
  "oauth",
@@ -26,6 +26,7 @@
26
26
  "dependencies": {
27
27
  "@noble/hashes": "^2.4.0",
28
28
  "@sozai/codec": "^0.4.4",
29
+ "@sozai/http-util": "^0.1.0",
29
30
  "@sozai/runtime": "^0.1.0"
30
31
  },
31
32
  "publishConfig": {