Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/producthunt

src/auth.ts

152 lines · 4.8 KB · TypeScript
import { createAuthenticatedFetch, kody } from 'kody:runtime'
import type { ProductHuntAuthInput, ProductHuntAuthMode } from './types.ts'
import { optionalString, requireString } from './types.ts'
import {
	DEFAULT_ACCESS_TOKEN_SECRET,
	PRODUCTHUNT_GRAPHQL_URL,
	missingCredentialsMessage,
	resolveIntegrationName,
	resolveSecretName,
} from './setup.ts'

export { resolveIntegrationName, resolveSecretName }

const authenticatedFetches = new Map<string, typeof fetch>()

export type ResolvedProductHuntAuth = {
	mode: ProductHuntAuthMode
	integrationName: string
	secretName: string
}

function secretEntries(result: unknown): Array<{ name?: string; scope?: string }> {
	if (result && typeof result === 'object' && Array.isArray((result as { secrets?: unknown }).secrets)) {
		return (result as { secrets: Array<{ name?: string; scope?: string }> }).secrets
	}
	return Array.isArray(result) ? result : []
}

export async function listUserSecretNames(): Promise<Set<string>> {
	const listed = await kody.secret_list({ scope: 'user' })
	const names = new Set<string>()
	for (const entry of secretEntries(listed)) {
		if (entry?.name && (entry.scope === 'user' || !entry.scope)) {
			names.add(entry.name)
		}
	}
	return names
}

export async function listProductHuntIntegrationNames(): Promise<Array<string>> {
	const listed = await kody.integration_list({})
	const integrations =
		listed && typeof listed === 'object' && Array.isArray((listed as { integrations?: unknown }).integrations)
			? (listed as { integrations: Array<{ name?: string }> }).integrations
			: Array.isArray(listed)
				? listed
				: []
	return integrations
		.map((item) => (typeof item?.name === 'string' ? item.name : ''))
		.filter((name) => name === 'producthunt' || name.startsWith('producthunt-'))
}

export async function resolveProductHuntAuth(
	input: ProductHuntAuthInput = {},
): Promise<ResolvedProductHuntAuth> {
	const integrationName = resolveIntegrationName(input)
	const secretName = resolveSecretName(input)
	const forced = input.auth
	if (forced !== undefined && forced !== 'oauth' && forced !== 'token') {
		throw new Error('auth must be "oauth" or "token".')
	}

	const [secrets, integrations] = await Promise.all([
		listUserSecretNames(),
		listProductHuntIntegrationNames(),
	])
	const hasOauth = integrations.includes(integrationName)
	const hasToken = secrets.has(secretName)

	let mode: ProductHuntAuthMode
	if (forced === 'oauth') {
		if (!hasOauth) {
			throw new Error(missingCredentialsMessage({ integrationName, secretName }))
		}
		mode = 'oauth'
	} else if (forced === 'token') {
		if (!hasToken) {
			throw new Error(missingCredentialsMessage({ integrationName, secretName }))
		}
		mode = 'token'
	} else if (hasOauth) {
		mode = 'oauth'
	} else if (hasToken) {
		mode = 'token'
	} else {
		throw new Error(missingCredentialsMessage({ integrationName, secretName }))
	}

	return { mode, integrationName, secretName }
}

async function getOauthFetch(integrationName: string): Promise<typeof fetch> {
	let authedFetch = authenticatedFetches.get(integrationName)
	if (!authedFetch) {
		try {
			authedFetch = await createAuthenticatedFetch(integrationName)
		} catch (error) {
			const message = error instanceof Error ? error.message : String(error)
			throw new Error(
				[
					`Product Hunt OAuth integration "${integrationName}" is not usable: ${message}`,
					missingCredentialsMessage({
						integrationName,
						secretName: DEFAULT_ACCESS_TOKEN_SECRET,
					}),
				].join(' '),
			)
		}
		authenticatedFetches.set(integrationName, authedFetch)
	}
	return authedFetch
}

export async function productHuntFetch(
	auth: ResolvedProductHuntAuth,
	init: RequestInit,
): Promise<Response> {
	switch (auth.mode) {
		case 'oauth': {
			const authedFetch = await getOauthFetch(auth.integrationName)
			return authedFetch(PRODUCTHUNT_GRAPHQL_URL, init)
		}
		case 'token': {
			const headers = new Headers(init.headers)
			headers.set('Authorization', `Bearer {{secret:${auth.secretName}}}`)
			return fetch(PRODUCTHUNT_GRAPHQL_URL, { ...init, headers })
		}
		default: {
			const exhaustive: never = auth.mode
			throw new Error(`Unsupported Product Hunt auth mode: ${String(exhaustive)}`)
		}
	}
}

export function requireAuthMode(value: unknown): ProductHuntAuthMode | undefined {
	if (value === undefined) return undefined
	const mode = requireString(value, 'auth')
	if (mode !== 'oauth' && mode !== 'token') {
		throw new Error('auth must be "oauth" or "token".')
	}
	return mode
}

export function parseAuthInput(input: Record<string, unknown>): ProductHuntAuthInput {
	return {
		integrationName: optionalString(input.integrationName, 'integrationName'),
		integration: optionalString(input.integration, 'integration'),
		account: optionalString(input.account, 'account'),
		secretName: optionalString(input.secretName, 'secretName'),
		auth: requireAuthMode(input.auth),
	}
}