@kokuin/oauth 0.7.5 → 0.7.7

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 |
@@ -0,0 +1,32 @@
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
+ /** Seconds from `iat` to `exp`: a positive integer, default `60`. */
24
+ lifetimeSeconds?: number;
25
+ /** Current time in seconds since epoch. */
26
+ now?: () => number;
27
+ typ?: string;
28
+ /** Source of randomness for the `jti` claim, defaults to `globalThis.crypto`. */
29
+ runtime?: Pick<Runtime, 'getRandomValues'>;
30
+ };
31
+ /** Build a signed JWT client assertion for `private_key_jwt` client authentication. */
32
+ export declare function createClientAssertion(params: CreateClientAssertionParams): Promise<string>;
@@ -0,0 +1,58 @@
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
+ // Anything else gives an assertion that is already expired or has a malformed `exp`.
35
+ if (!Number.isInteger(lifetimeSeconds) || lifetimeSeconds <= 0) {
36
+ throw new Error(`Client assertion lifetimeSeconds must be a positive integer, got: ${lifetimeSeconds}`);
37
+ }
38
+ const randomBytes = (length)=>runtime == null ? globalThis.crypto.getRandomValues(new Uint8Array(length)) : runtime.getRandomValues(new Uint8Array(length));
39
+ const iat = now();
40
+ const header = {
41
+ alg: signer.alg,
42
+ typ
43
+ };
44
+ if (signer.kid != null) {
45
+ header.kid = signer.kid;
46
+ }
47
+ const claims = {
48
+ iss: clientID,
49
+ sub: clientID,
50
+ aud: audience,
51
+ iat,
52
+ exp: iat + lifetimeSeconds,
53
+ jti: toB64U(randomBytes(16))
54
+ };
55
+ const signingInput = `${toB64U(fromUTF(JSON.stringify(header)))}.${toB64U(fromUTF(JSON.stringify(claims)))}`;
56
+ const signature = await signer.sign(fromUTF(signingInput));
57
+ return `${signingInput}.${toB64U(signature)}`;
58
+ }
@@ -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/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
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
7
  export { type FetchOAuthJSONParams, fetchOAuthJSON, type OAuthJSONResponse, type RequestOAuthJSONParams, requestOAuthJSON, } from './http.js';
package/lib/index.js CHANGED
@@ -1,5 +1,7 @@
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
7
  export { fetchOAuthJSON, requestOAuthJSON } from './http.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kokuin/oauth",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "description": "Generic OAuth 2.0 client primitives for kokuin",
5
5
  "keywords": [
6
6
  "oauth",