@kokuin/oauth 0.7.4 → 0.7.5

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.
@@ -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`,
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,8 @@
1
- export { buildAuthorizationURL } from './authorization.js';
1
+ export { type BuildAuthorizationURLParams, buildAuthorizationURL } from './authorization.js';
2
2
  export { type CreateHTTPBrokerTransportParams, createHTTPBrokerTransport } from './broker.js';
3
3
  export { type DeviceAuthorization, pollDeviceToken, startDeviceAuthorization } from './device.js';
4
4
  export { exchangeCode, type RefreshTokenParams, refreshToken } from './exchange.js';
5
- export { type FetchOAuthJSONParams, fetchOAuthJSON } from './http.js';
5
+ export { type FetchOAuthJSONParams, fetchOAuthJSON, type OAuthJSONResponse, type RequestOAuthJSONParams, requestOAuthJSON, } from './http.js';
6
6
  export { type CompleteAuthorizationParams, completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, type PendingAuthRecord, type PendingAuthStore, type StartAuthorizationParams, startAuthorization, } from './pending-auth.js';
7
7
  export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
8
8
  export type { OAuthTokenErrorParams } from './types.js';
package/lib/index.js CHANGED
@@ -2,7 +2,7 @@ export { buildAuthorizationURL } from './authorization.js';
2
2
  export { createHTTPBrokerTransport } from './broker.js';
3
3
  export { pollDeviceToken, startDeviceAuthorization } from './device.js';
4
4
  export { exchangeCode, refreshToken } from './exchange.js';
5
- export { fetchOAuthJSON } from './http.js';
5
+ export { fetchOAuthJSON, requestOAuthJSON } from './http.js';
6
6
  export { completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, startAuthorization } from './pending-auth.js';
7
7
  export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
8
8
  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.5",
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": {