Skip to content
← Public packages

@kody/api-research

Research third-party APIs: registry search, provider discovery, OpenAPI summarize, and client scaffold.

src/auth.ts

64 lines · 2.1 KB · TypeScript
export type OpenApiBoundAuth =
	| { kind: 'integration'; provider: string }
	| { kind: 'bearerSecret'; secretName: string }
	| { kind: 'headerSecret'; headerName: string; secretName: string }
	| { kind: 'basicSecrets'; usernameSecret: string; passwordSecret: string }
	| { kind: 'none' }

export function assertOpenApiBoundAuth(value: unknown): OpenApiBoundAuth {
	if (typeof value !== 'object' || value === null) {
		throw new Error('auth must be an object with a kind')
	}
	const auth = value as Record<string, unknown>
	const kind = auth.kind
	if (kind === 'none') {
		return { kind: 'none' }
	}
	if (kind === 'integration') {
		if (typeof auth.provider !== 'string' || auth.provider.length === 0) {
			throw new Error('auth.provider is required for integration auth')
		}
		return { kind: 'integration', provider: auth.provider }
	}
	if (kind === 'bearerSecret') {
		if (typeof auth.secretName !== 'string' || auth.secretName.length === 0) {
			throw new Error('auth.secretName is required for bearerSecret auth')
		}
		return { kind: 'bearerSecret', secretName: auth.secretName }
	}
	if (kind === 'headerSecret') {
		if (typeof auth.headerName !== 'string' || auth.headerName.length === 0) {
			throw new Error('auth.headerName is required for headerSecret auth')
		}
		if (typeof auth.secretName !== 'string' || auth.secretName.length === 0) {
			throw new Error('auth.secretName is required for headerSecret auth')
		}
		return {
			kind: 'headerSecret',
			headerName: auth.headerName,
			secretName: auth.secretName,
		}
	}
	if (kind === 'basicSecrets') {
		if (
			typeof auth.usernameSecret !== 'string' ||
			auth.usernameSecret.length === 0
		) {
			throw new Error('auth.usernameSecret is required for basicSecrets auth')
		}
		if (
			typeof auth.passwordSecret !== 'string' ||
			auth.passwordSecret.length === 0
		) {
			throw new Error('auth.passwordSecret is required for basicSecrets auth')
		}
		return {
			kind: 'basicSecrets',
			usernameSecret: auth.usernameSecret,
			passwordSecret: auth.passwordSecret,
		}
	}
	throw new Error(
		'auth.kind must be integration, bearerSecret, headerSecret, basicSecrets, or none',
	)
}