Skip to content
← Public packages

@kentcdodds/x

X API v2 helpers for posts, search, DMs, and encrypted X Chat. Generic Activity CRC/HMAC utilities only — @kodykoala Pam wake lives in @kentcdodds/kodykoala-activity.

FollowFork

Files

auth.ts

101 lines · 3.6 KB · TypeScript
import { createAuthenticatedFetch, credential, kody } from 'kody:runtime'

/**
 * Declared X OAuth integration slots (see package.json#kody.credentials).
 * Add a case + credential slot together when connecting another account.
 */
export const DECLARED_X_INTEGRATIONS = ['x', 'x-kodykoala'] as const

export type DeclaredXIntegration = (typeof DECLARED_X_INTEGRATIONS)[number]

export function normalizeIntegrationName(name: string): string {
	return name.trim().toLowerCase()
}

export function assertDeclaredXIntegration(name: string): DeclaredXIntegration {
	const normalized = normalizeIntegrationName(name)
	if (normalized === 'x' || normalized === 'x-kodykoala') {
		return normalized
	}
	throw new Error(
		`Undeclared X OAuth integration "${name}". Connect it and add a literal case in src/auth.ts plus a kody.credentials oauth slot (currently: ${DECLARED_X_INTEGRATIONS.join(', ')}).`,
	)
}

/** createAuthenticatedFetch with a stampable literal name per declared account. */
export async function authenticatedFetchFor(integrationName: string) {
	const name = assertDeclaredXIntegration(integrationName)
	switch (name) {
		case 'x':
			return createAuthenticatedFetch('x')
		case 'x-kodykoala':
			return createAuthenticatedFetch('x-kodykoala')
		default: {
			const _exhaustive: never = name
			throw new Error(`Unhandled X integration: ${String(_exhaustive)}`)
		}
	}
}

let lastCredentialFetchError: string | null = null

/** Why the credential() client could not be opened (diagnostics only; never secret values). */
export function getLastCredentialFetchError(): string | null {
	return lastCredentialFetchError
}

function clientFetch(client: unknown): typeof fetch | null {
	return client && typeof (client as { fetch?: unknown }).fetch === 'function'
		? (client as { fetch: typeof fetch }).fetch
		: null
}

async function openCredentialFetch(name: DeclaredXIntegration): Promise<typeof fetch | null> {
	const errors: string[] = []
	// Literal need keys only (stamped packages). Under `kody execute --local` from a
	// checkout pass `--credential x=x` so the key is not ambiguous.
	try {
		const viaKey = clientFetch(
			name === 'x-kodykoala' ? await credential('x-kodykoala') : await credential('x'),
		)
		if (viaKey) return viaKey
	} catch (error) {
		errors.push(String((error as Error)?.message ?? error))
	}
	lastCredentialFetchError = errors.join(' | ').slice(0, 500) || 'credential client has no fetch'
	return null
}

/** Credential-bound fetch for media. CLI >=3.33.1 streams binary bodies at every size.
 * Ambiguous/unavailable credentials fail closed; never select another auth path implicitly. */
const binaryFetchCache = new Map<DeclaredXIntegration, Promise<typeof fetch>>()

export async function binaryFetchFor(integrationName: string): Promise<typeof fetch> {
	const name = assertDeclaredXIntegration(integrationName)
	let cached = binaryFetchCache.get(name)
	if (!cached) {
		cached = (async () => {
			const client = await openCredentialFetch(name)
			if (!client) throw new Error('Explicit X credential mapping required for ' + name)
			return client
		})()
		binaryFetchCache.set(name, cached)
		cached.catch(() => binaryFetchCache.delete(name))
	}
	return cached
}

/** integrationTokenRefresh with a stampable literal name per declared account. */
export async function refreshIntegrationToken(integrationName: string) {
	const name = assertDeclaredXIntegration(integrationName)
	switch (name) {
		case 'x':
			return kody.integrationTokenRefresh({ name: 'x' })
		case 'x-kodykoala':
			return kody.integrationTokenRefresh({ name: 'x-kodykoala' })
		default: {
			const _exhaustive: never = name
			throw new Error(`Unhandled X integration: ${String(_exhaustive)}`)
		}
	}
}