Skip to content

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

Package listing

@kody/hubspot

src/auth.ts

190 lines · 5.6 KB · TypeScript
import { createAuthenticatedFetch, kody } from 'kody:runtime'
import type { HubSpotAuthInput, HubSpotAuthMode } from './types.ts'
import { optionalString, requireString } from './types.ts'
import {
	DEFAULT_INTEGRATION_NAME,
	DEFAULT_TOKEN_SECRET,
	missingCredentialsMessage,
} from './setup.ts'

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

export type ResolvedHubSpotAuth = {
	mode: HubSpotAuthMode
	integrationName: string
	secretName: string
	authorization: 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 listHubSpotIntegrationNames(): 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 === 'hubspot' || name.startsWith('hubspot-'))
}

export function resolveIntegrationName(input: HubSpotAuthInput = {}): string {
	const explicit =
		optionalString(input.integrationName, 'integrationName') ??
		optionalString(input.integration, 'integration')
	if (explicit) return explicit

	const account = optionalString(input.account, 'account')
	if (!account || account === 'default' || account === 'hubspot') {
		return DEFAULT_INTEGRATION_NAME
	}
	if (account.startsWith('hubspot-')) return account
	return `hubspot-${account}`
}

export function resolveSecretName(input: HubSpotAuthInput = {}): string {
	const explicit = optionalString(input.secretName, 'secretName')
	if (explicit) return explicit
	const integrationName = resolveIntegrationName(input)
	if (integrationName === DEFAULT_INTEGRATION_NAME) return DEFAULT_TOKEN_SECRET
	const suffix = integrationName.startsWith('hubspot-')
		? integrationName.slice('hubspot-'.length)
		: integrationName
	return `hubspotPrivateAppToken-${suffix}`
}

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

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

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

	switch (mode) {
		case 'oauth':
			return {
				mode,
				integrationName,
				secretName,
				authorization: `[managed ${integrationName} OAuth integration]`,
			}
		case 'privateApp':
			return {
				mode,
				integrationName,
				secretName,
				authorization: `Bearer {{secret:${secretName}}}`,
			}
		default: {
			const exhaustive: never = mode
			throw new Error(`Unsupported HubSpot auth mode: ${String(exhaustive)}`)
		}
	}
}

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(
				[
					`HubSpot OAuth integration "${integrationName}" is not usable: ${message}`,
					missingCredentialsMessage({
						integrationName,
						secretName: DEFAULT_TOKEN_SECRET,
					}),
				].join(' '),
			)
		}
		authenticatedFetches.set(integrationName, authedFetch)
	}
	return authedFetch
}

export async function hubspotFetch(
	auth: ResolvedHubSpotAuth,
	url: string,
	init: RequestInit,
): Promise<Response> {
	switch (auth.mode) {
		case 'oauth': {
			const authedFetch = await getOauthFetch(auth.integrationName)
			return authedFetch(url, init)
		}
		case 'privateApp': {
			const headers = new Headers(init.headers)
			headers.set('Authorization', `Bearer {{secret:${auth.secretName}}}`)
			return fetch(url, { ...init, headers })
		}
		default: {
			const exhaustive: never = auth.mode
			throw new Error(`Unsupported HubSpot auth mode: ${String(exhaustive)}`)
		}
	}
}

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