@kokuin/oauth 0.1.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/README.md ADDED
@@ -0,0 +1,10 @@
1
+ # @kokuin/oauth
2
+
3
+ Generic OAuth 2.0 client primitives for kokuin: PKCE, hardened HTTP with
4
+ structured OAuth errors, the authorization-code and refresh-token exchanges, and
5
+ a pending-authorization orchestration + store port.
6
+
7
+ A true leaf package — depends only on `@sozai/runtime`, `@noble/hashes`, and
8
+ `@sozai/codec`. It owns no application-specific concern (no DID/credential
9
+ wrapping, no connector registry, no MCP resource discovery, no provider-specific
10
+ authorization policy).
@@ -0,0 +1,9 @@
1
+ import type { OAuthProviderDefinition } from './types.js';
2
+ export declare function buildAuthorizationURL(params: {
3
+ definition: OAuthProviderDefinition;
4
+ redirectURL: string;
5
+ scopes: Array<string>;
6
+ state: string;
7
+ codeChallenge: string;
8
+ authorizationParams?: Record<string, string>;
9
+ }): string;
@@ -0,0 +1,31 @@
1
+ import { assertSecureURL } from './secure-url.js';
2
+ const PROTECTED_PARAMS = new Set([
3
+ 'client_id',
4
+ 'redirect_uri',
5
+ 'response_type',
6
+ 'scope',
7
+ 'state',
8
+ 'code_challenge',
9
+ 'code_challenge_method'
10
+ ]);
11
+ export function buildAuthorizationURL(params) {
12
+ const { definition, redirectURL, scopes, state, codeChallenge, authorizationParams } = params;
13
+ assertSecureURL(definition.authorizationEndpoint);
14
+ const url = new URL(definition.authorizationEndpoint);
15
+ const search = url.searchParams;
16
+ if (authorizationParams != null) {
17
+ for (const [key, value] of Object.entries(authorizationParams)){
18
+ if (!PROTECTED_PARAMS.has(key)) {
19
+ search.set(key, value);
20
+ }
21
+ }
22
+ }
23
+ search.set('client_id', definition.clientID);
24
+ search.set('redirect_uri', redirectURL);
25
+ search.set('response_type', 'code');
26
+ search.set('scope', scopes.join(' '));
27
+ search.set('state', state);
28
+ search.set('code_challenge', codeChallenge);
29
+ search.set('code_challenge_method', 'S256');
30
+ return url.toString();
31
+ }
@@ -0,0 +1,14 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ import type { OAuthProviderDefinition, RequestOptions, TokenResponse } from './types.js';
3
+ export declare function exchangeCode(params: {
4
+ definition: OAuthProviderDefinition;
5
+ runtime: Runtime;
6
+ code: string;
7
+ redirectURL: string;
8
+ codeVerifier: string;
9
+ } & RequestOptions): Promise<TokenResponse>;
10
+ export declare function refreshToken(params: {
11
+ definition: OAuthProviderDefinition;
12
+ runtime: Runtime;
13
+ refreshToken: string;
14
+ } & RequestOptions): Promise<TokenResponse>;
@@ -0,0 +1,88 @@
1
+ import { fetchOAuthJSON } from './http.js';
2
+ export async function exchangeCode(params) {
3
+ const { definition, runtime, code, redirectURL, codeVerifier, signal, timeoutMs, maxBytes } = params;
4
+ if (definition.mode === 'broker') {
5
+ throw new Error('broker token exchange is not implemented');
6
+ }
7
+ assertExchangeableConfig(definition);
8
+ const form = new URLSearchParams();
9
+ form.set('grant_type', 'authorization_code');
10
+ form.set('code', code);
11
+ form.set('redirect_uri', redirectURL);
12
+ form.set('client_id', definition.clientID);
13
+ form.set('code_verifier', codeVerifier);
14
+ if (definition.clientSecret != null) {
15
+ form.set('client_secret', definition.clientSecret);
16
+ }
17
+ const raw = await fetchOAuthJSON({
18
+ runtime,
19
+ url: definition.tokenEndpoint,
20
+ body: form.toString(),
21
+ contentType: 'application/x-www-form-urlencoded',
22
+ signal,
23
+ timeoutMs,
24
+ maxBytes
25
+ });
26
+ return validateTokenResponse(raw);
27
+ }
28
+ export async function refreshToken(params) {
29
+ const { definition, runtime, refreshToken, signal, timeoutMs, maxBytes } = params;
30
+ if (definition.mode === 'broker') {
31
+ throw new Error('broker token refresh is not implemented');
32
+ }
33
+ assertExchangeableConfig(definition);
34
+ const form = new URLSearchParams();
35
+ form.set('grant_type', 'refresh_token');
36
+ form.set('refresh_token', refreshToken);
37
+ form.set('client_id', definition.clientID);
38
+ if (definition.clientSecret != null) {
39
+ form.set('client_secret', definition.clientSecret);
40
+ }
41
+ const raw = await fetchOAuthJSON({
42
+ runtime,
43
+ url: definition.tokenEndpoint,
44
+ body: form.toString(),
45
+ contentType: 'application/x-www-form-urlencoded',
46
+ signal,
47
+ timeoutMs,
48
+ maxBytes
49
+ });
50
+ return validateTokenResponse(raw);
51
+ }
52
+ function assertExchangeableConfig(definition) {
53
+ if (definition.mode !== 'confidential' && definition.mode !== 'native') {
54
+ throw new Error(`unsupported OAuth client mode: ${String(definition.mode)}`);
55
+ }
56
+ if (typeof definition.clientID !== 'string' || definition.clientID.length === 0) {
57
+ throw new Error('OAuth definition requires a non-empty clientID');
58
+ }
59
+ if (definition.mode === 'confidential') {
60
+ if (typeof definition.clientSecret !== 'string' || definition.clientSecret.length === 0) {
61
+ throw new Error('confidential OAuth client requires a non-empty clientSecret');
62
+ }
63
+ }
64
+ }
65
+ function validateTokenResponse(value) {
66
+ if (typeof value !== 'object' || value === null) {
67
+ throw new Error('OAuth token response was not an object');
68
+ }
69
+ const record = value;
70
+ if (typeof record.access_token !== 'string' || record.access_token.length === 0) {
71
+ throw new Error('OAuth token response is missing a valid access_token');
72
+ }
73
+ if (typeof record.token_type !== 'string') {
74
+ throw new Error('OAuth token response is missing a valid token_type');
75
+ }
76
+ if (record.expires_in !== undefined) {
77
+ if (typeof record.expires_in !== 'number' || !Number.isFinite(record.expires_in) || record.expires_in < 0) {
78
+ throw new Error('OAuth token response has an invalid expires_in');
79
+ }
80
+ }
81
+ if (record.refresh_token !== undefined && typeof record.refresh_token !== 'string') {
82
+ throw new Error('OAuth token response has an invalid refresh_token');
83
+ }
84
+ if (record.scope !== undefined && typeof record.scope !== 'string') {
85
+ throw new Error('OAuth token response has an invalid scope');
86
+ }
87
+ return value;
88
+ }
package/lib/http.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ import { type RequestOptions } from './types.js';
3
+ export type FetchOAuthJSONParams = {
4
+ runtime: Pick<Runtime, 'fetch'>;
5
+ url: string;
6
+ body: string;
7
+ contentType: string;
8
+ } & RequestOptions;
9
+ export declare function fetchOAuthJSON(params: FetchOAuthJSONParams): Promise<unknown>;
package/lib/http.js ADDED
@@ -0,0 +1,91 @@
1
+ import { assertSecureURL } from './secure-url.js';
2
+ import { OAuthTokenError } from './types.js';
3
+ const DEFAULT_MAX_BYTES = 1024 * 1024;
4
+ const DEFAULT_TIMEOUT_MS = 30_000;
5
+ export async function fetchOAuthJSON(params) {
6
+ const { runtime, url, body, contentType, signal, maxBytes = DEFAULT_MAX_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = params;
7
+ assertSecureURL(url);
8
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
9
+ const combinedSignal = signal ? AbortSignal.any([
10
+ signal,
11
+ timeoutSignal
12
+ ]) : timeoutSignal;
13
+ const response = await runtime.fetch(url, {
14
+ method: 'POST',
15
+ headers: {
16
+ 'content-type': contentType,
17
+ accept: 'application/json'
18
+ },
19
+ body,
20
+ redirect: 'error',
21
+ signal: combinedSignal
22
+ });
23
+ const text = await readCappedText(response, maxBytes);
24
+ if (!response.ok) {
25
+ throw parseOAuthError(response.status, text);
26
+ }
27
+ try {
28
+ return JSON.parse(text);
29
+ } catch {
30
+ // biome-ignore lint/style/useErrorCause: no parsed error object to attach as cause
31
+ throw new Error('OAuth response was not valid JSON');
32
+ }
33
+ }
34
+ function parseOAuthError(status, text) {
35
+ let code;
36
+ let description;
37
+ try {
38
+ const parsed = JSON.parse(text);
39
+ if (parsed != null && typeof parsed === 'object') {
40
+ const record = parsed;
41
+ if (typeof record.error === 'string') {
42
+ code = record.error;
43
+ }
44
+ if (typeof record.error_description === 'string') {
45
+ description = record.error_description;
46
+ }
47
+ }
48
+ } catch {
49
+ // non-JSON / empty error body → code undefined (treated as transient by callers)
50
+ }
51
+ return new OAuthTokenError(status, code, description);
52
+ }
53
+ async function readCappedText(response, maxBytes) {
54
+ const reader = response.body?.getReader();
55
+ if (reader == null) {
56
+ const text = await response.text();
57
+ if (byteLength(text) > maxBytes) {
58
+ throw new Error(`OAuth response exceeded ${maxBytes} bytes`);
59
+ }
60
+ return text;
61
+ }
62
+ const chunks = [];
63
+ let total = 0;
64
+ for(;;){
65
+ const { done, value } = await reader.read();
66
+ if (done) {
67
+ break;
68
+ }
69
+ if (value != null) {
70
+ total += value.byteLength;
71
+ if (total > maxBytes) {
72
+ await reader.cancel();
73
+ throw new Error(`OAuth response exceeded ${maxBytes} bytes`);
74
+ }
75
+ chunks.push(value);
76
+ }
77
+ }
78
+ return new TextDecoder().decode(concat(chunks, total));
79
+ }
80
+ function concat(chunks, total) {
81
+ const out = new Uint8Array(total);
82
+ let offset = 0;
83
+ for (const chunk of chunks){
84
+ out.set(chunk, offset);
85
+ offset += chunk.byteLength;
86
+ }
87
+ return out;
88
+ }
89
+ function byteLength(text) {
90
+ return new TextEncoder().encode(text).byteLength;
91
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { buildAuthorizationURL } from './authorization.js';
2
+ export { exchangeCode, refreshToken } from './exchange.js';
3
+ export { type FetchOAuthJSONParams, fetchOAuthJSON } from './http.js';
4
+ export { completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, type PendingAuthRecord, type PendingAuthStore, startAuthorization, } from './pending-auth.js';
5
+ export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
6
+ export { type OAuthClientMode, type OAuthErrorCode, type OAuthProviderDefinition, OAuthTokenError, type RequestOptions, type TokenResponse, } from './types.js';
package/lib/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { buildAuthorizationURL } from './authorization.js';
2
+ export { exchangeCode, refreshToken } from './exchange.js';
3
+ export { fetchOAuthJSON } from './http.js';
4
+ export { completeAuthorization, createMemoryPendingAuthStore, DEFAULT_TTL_MS, startAuthorization } from './pending-auth.js';
5
+ export { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
6
+ export { OAuthTokenError } from './types.js';
@@ -0,0 +1,44 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ import type { OAuthProviderDefinition, RequestOptions, TokenResponse } from './types.js';
3
+ export type PendingAuthRecord<TExtra> = {
4
+ state: string;
5
+ codeVerifier: string;
6
+ provider: string;
7
+ redirectURL: string;
8
+ scopes: Array<string>;
9
+ createdAt: number;
10
+ expiresAt: number;
11
+ extra: TExtra;
12
+ };
13
+ export type PendingAuthStore<TExtra> = {
14
+ create(record: PendingAuthRecord<TExtra>): Promise<void>;
15
+ consume(state: string): Promise<PendingAuthRecord<TExtra> | null>;
16
+ /** Deletes records whose stored `expiresAt` is at or before `nowMs`. */
17
+ deleteExpired(nowMs: number): Promise<void>;
18
+ };
19
+ export declare const DEFAULT_TTL_MS: number;
20
+ export declare function createMemoryPendingAuthStore<TExtra>(): PendingAuthStore<TExtra>;
21
+ export declare function startAuthorization<TExtra>(params: {
22
+ runtime: Runtime;
23
+ definition: OAuthProviderDefinition;
24
+ store: PendingAuthStore<TExtra>;
25
+ redirectURL: string;
26
+ scopes: Array<string>;
27
+ extra: TExtra;
28
+ ttlMs?: number;
29
+ authorizationParams?: Record<string, string>;
30
+ }): Promise<{
31
+ url: string;
32
+ state: string;
33
+ }>;
34
+ export declare function completeAuthorization<TExtra>(params: {
35
+ runtime: Runtime;
36
+ definition: OAuthProviderDefinition;
37
+ store: PendingAuthStore<TExtra>;
38
+ state: string;
39
+ code: string;
40
+ redirectURL: string;
41
+ } & RequestOptions): Promise<{
42
+ tokens: TokenResponse;
43
+ record: PendingAuthRecord<TExtra>;
44
+ }>;
@@ -0,0 +1,98 @@
1
+ import { buildAuthorizationURL } from './authorization.js';
2
+ import { exchangeCode } from './exchange.js';
3
+ import { deriveCodeChallenge, generateCodeVerifier, generateState } from './pkce.js';
4
+ export const DEFAULT_TTL_MS = 10 * 60 * 1000;
5
+ export function createMemoryPendingAuthStore() {
6
+ const records = new Map();
7
+ return {
8
+ async create (record) {
9
+ if (records.has(record.state)) {
10
+ throw new Error('duplicate authorization state');
11
+ }
12
+ records.set(record.state, structuredClone(record));
13
+ },
14
+ async consume (state) {
15
+ const record = records.get(state);
16
+ if (record == null) {
17
+ return null;
18
+ }
19
+ records.delete(state);
20
+ return structuredClone(record);
21
+ },
22
+ async deleteExpired (nowMs) {
23
+ for (const [state, record] of records){
24
+ if (record.expiresAt <= nowMs) {
25
+ records.delete(state);
26
+ }
27
+ }
28
+ }
29
+ };
30
+ }
31
+ export async function startAuthorization(params) {
32
+ const { runtime, definition, store, redirectURL, scopes, extra, authorizationParams } = params;
33
+ const ttlMs = params.ttlMs ?? DEFAULT_TTL_MS;
34
+ const now = Date.now();
35
+ const expiresAt = now + ttlMs;
36
+ try {
37
+ await store.deleteExpired(now);
38
+ } catch {
39
+ // best-effort cleanup: a sweep failure must not block starting a new flow
40
+ }
41
+ const state = generateState(runtime);
42
+ const codeVerifier = generateCodeVerifier(runtime);
43
+ const codeChallenge = deriveCodeChallenge(codeVerifier);
44
+ // build (and thereby validate the authorization endpoint, fix #4) BEFORE create,
45
+ // so a bad endpoint does not leave a stale pending record
46
+ const url = buildAuthorizationURL({
47
+ definition,
48
+ redirectURL,
49
+ scopes,
50
+ state,
51
+ codeChallenge,
52
+ authorizationParams
53
+ });
54
+ await store.create({
55
+ state,
56
+ codeVerifier,
57
+ provider: definition.name,
58
+ redirectURL,
59
+ scopes,
60
+ createdAt: now,
61
+ expiresAt,
62
+ extra
63
+ });
64
+ return {
65
+ url,
66
+ state
67
+ };
68
+ }
69
+ export async function completeAuthorization(params) {
70
+ const { runtime, definition, store, state, code, redirectURL, signal, timeoutMs, maxBytes } = params;
71
+ const record = await store.consume(state);
72
+ if (record == null) {
73
+ throw new Error('unknown or already-used authorization state');
74
+ }
75
+ if (record.expiresAt < Date.now()) {
76
+ throw new Error('authorization state expired');
77
+ }
78
+ if (record.provider !== definition.name) {
79
+ throw new Error('authorization provider mismatch');
80
+ }
81
+ if (record.redirectURL !== redirectURL) {
82
+ throw new Error('redirect URI mismatch');
83
+ }
84
+ const tokens = await exchangeCode({
85
+ definition,
86
+ runtime,
87
+ code,
88
+ redirectURL: record.redirectURL,
89
+ codeVerifier: record.codeVerifier,
90
+ signal,
91
+ timeoutMs,
92
+ maxBytes
93
+ });
94
+ return {
95
+ tokens,
96
+ record
97
+ };
98
+ }
package/lib/pkce.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { Runtime } from '@sozai/runtime';
2
+ export declare function generateCodeVerifier(runtime: Pick<Runtime, 'getRandomValues'>): string;
3
+ export declare function deriveCodeChallenge(codeVerifier: string): string;
4
+ export declare function generateState(runtime: Pick<Runtime, 'getRandomValues'>): string;
package/lib/pkce.js ADDED
@@ -0,0 +1,11 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ import { toB64U } from '@sozai/codec';
3
+ export function generateCodeVerifier(runtime) {
4
+ return toB64U(runtime.getRandomValues(new Uint8Array(32)));
5
+ }
6
+ export function deriveCodeChallenge(codeVerifier) {
7
+ return toB64U(sha256(new TextEncoder().encode(codeVerifier)));
8
+ }
9
+ export function generateState(runtime) {
10
+ return toB64U(runtime.getRandomValues(new Uint8Array(32)));
11
+ }
@@ -0,0 +1,2 @@
1
+ export declare function assertSecureURL(rawURL: string): void;
2
+ export declare function isLoopbackHost(hostname: string): boolean;
@@ -0,0 +1,13 @@
1
+ export function assertSecureURL(rawURL) {
2
+ const url = new URL(rawURL);
3
+ if (url.protocol === 'https:') {
4
+ return;
5
+ }
6
+ if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) {
7
+ return;
8
+ }
9
+ throw new Error(`OAuth endpoint must use https: ${rawURL}`);
10
+ }
11
+ export function isLoopbackHost(hostname) {
12
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
13
+ }
package/lib/types.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export type OAuthClientMode = {
2
+ mode: 'confidential';
3
+ clientID: string;
4
+ clientSecret: string;
5
+ } | {
6
+ mode: 'native';
7
+ clientID: string;
8
+ clientSecret?: string;
9
+ } | {
10
+ mode: 'broker';
11
+ clientID: string;
12
+ };
13
+ export type OAuthProviderDefinition = {
14
+ name: string;
15
+ authorizationEndpoint: string;
16
+ tokenEndpoint: string;
17
+ baseScopes?: Array<string>;
18
+ } & OAuthClientMode;
19
+ export type TokenResponse = {
20
+ access_token: string;
21
+ refresh_token?: string;
22
+ expires_in?: number;
23
+ token_type: string;
24
+ scope?: string;
25
+ };
26
+ export type OAuthErrorCode = 'invalid_grant' | 'invalid_client' | 'invalid_request' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string;
27
+ export declare class OAuthTokenError extends Error {
28
+ status: number;
29
+ code?: OAuthErrorCode;
30
+ description?: string;
31
+ constructor(status: number, code?: OAuthErrorCode, description?: string);
32
+ }
33
+ export type RequestOptions = {
34
+ signal?: AbortSignal;
35
+ timeoutMs?: number;
36
+ maxBytes?: number;
37
+ };
package/lib/types.js ADDED
@@ -0,0 +1,12 @@
1
+ export class OAuthTokenError extends Error {
2
+ status;
3
+ code;
4
+ description;
5
+ constructor(status, code, description){
6
+ super(description ?? code ?? `OAuth token request failed with status ${status}`);
7
+ this.name = 'OAuthTokenError';
8
+ this.status = status;
9
+ this.code = code;
10
+ this.description = description;
11
+ }
12
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@kokuin/oauth",
3
+ "version": "0.1.0",
4
+ "description": "Generic OAuth 2.0 client primitives for kokuin",
5
+ "keywords": [
6
+ "oauth",
7
+ "oauth2",
8
+ "pkce"
9
+ ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/TairuFramework/kokuin",
13
+ "directory": "packages/oauth"
14
+ },
15
+ "license": "MIT",
16
+ "sideEffects": false,
17
+ "type": "module",
18
+ "exports": {
19
+ ".": "./lib/index.js"
20
+ },
21
+ "main": "lib/index.js",
22
+ "types": "lib/index.d.ts",
23
+ "files": [
24
+ "lib/*"
25
+ ],
26
+ "dependencies": {
27
+ "@noble/hashes": "^2.4.0",
28
+ "@sozai/codec": "^0.4.0",
29
+ "@sozai/runtime": "^0.1.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "scripts": {
35
+ "build": "pnpm run build:clean && pnpm run build:js && pnpm run build:types",
36
+ "build:clean": "del-cli lib",
37
+ "build:js": "del-cli 'lib/**/*.js' && swc src -d ./lib --config-file ../../node_modules/@kigu/dev/swc.json --strip-leading-paths",
38
+ "build:types": "del-cli 'lib/**/*.d.ts' 'lib/**/*.d.ts.map' && tsc --emitDeclarationOnly --skipLibCheck",
39
+ "test": "pnpm run test:types && pnpm run test:unit",
40
+ "test:types": "tsc --noEmit --skipLibCheck -p tsconfig.test.json",
41
+ "test:unit": "vitest run"
42
+ }
43
+ }