import { createAuthenticatedFetch, kody } from 'kody:runtime'
import type { TrelloAuthInput, TrelloAuthMode } from './types.ts'
import { optionalString, requireString } from './types.ts'
import {
DEFAULT_API_KEY_SECRET,
DEFAULT_TOKEN_SECRET,
missingCredentialsMessage,
resolveApiKeySecretName,
resolveIntegrationName,
resolveTokenSecretName,
} from './setup.ts'
const authenticatedFetches = new Map<string, typeof fetch>()
export type ResolvedTrelloAuth = {
mode: TrelloAuthMode
integrationName: string
apiKeySecretName: string
tokenSecretName: 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>> {
try {
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
} catch {
return new Set()
}
}
export async function listTrelloIntegrationNames(): Promise<Array<string>> {
try {
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 === 'trello' || name.startsWith('trello-'))
} catch {
return []
}
}
export { resolveApiKeySecretName, resolveIntegrationName, resolveTokenSecretName }
export async function resolveTrelloAuth(
input: TrelloAuthInput = {},
): Promise<ResolvedTrelloAuth> {
const integrationName = resolveIntegrationName(input)
const apiKeySecretName = resolveApiKeySecretName(input)
const tokenSecretName = resolveTokenSecretName(input)
const forced = input.auth
if (forced !== undefined && forced !== 'oauth' && forced !== 'keyToken') {
throw new Error('auth must be "oauth" or "keyToken".')
}
const [secrets, integrations] = await Promise.all([
listUserSecretNames(),
listTrelloIntegrationNames(),
])
const hasOauth = integrations.includes(integrationName)
const hasKeyToken = secrets.has(apiKeySecretName) && secrets.has(tokenSecretName)
let mode: TrelloAuthMode
if (forced === 'oauth') {
if (!hasOauth) {
throw new Error(
missingCredentialsMessage({ integrationName, apiKeySecretName, tokenSecretName }),
)
}
mode = 'oauth'
} else if (forced === 'keyToken') {
if (!hasKeyToken) {
throw new Error(
missingCredentialsMessage({ integrationName, apiKeySecretName, tokenSecretName }),
)
}
mode = 'keyToken'
} else if (hasKeyToken) {
mode = 'keyToken'
} else if (hasOauth) {
mode = 'oauth'
} else {
throw new Error(
missingCredentialsMessage({ integrationName, apiKeySecretName, tokenSecretName }),
)
}
switch (mode) {
case 'oauth':
case 'keyToken':
return { mode, integrationName, apiKeySecretName, tokenSecretName }
default: {
const exhaustive: never = mode
throw new Error(`Unsupported Trello 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(
[
`Trello OAuth integration "${integrationName}" is not usable: ${message}`,
missingCredentialsMessage({
integrationName,
apiKeySecretName: DEFAULT_API_KEY_SECRET,
tokenSecretName: DEFAULT_TOKEN_SECRET,
}),
].join(' '),
)
}
authenticatedFetches.set(integrationName, authedFetch)
}
return authedFetch
}
export async function trelloFetch(
auth: ResolvedTrelloAuth,
url: string,
init: RequestInit,
): Promise<Response> {
switch (auth.mode) {
case 'oauth': {
const authedFetch = await getOauthFetch(auth.integrationName)
return authedFetch(url, init)
}
case 'keyToken': {
const signed = new URL(url)
signed.searchParams.set('key', `{{secret:${auth.apiKeySecretName}}}`)
signed.searchParams.set('token', `{{secret:${auth.tokenSecretName}}}`)
return fetch(signed.toString(), init)
}
default: {
const exhaustive: never = auth.mode
throw new Error(`Unsupported Trello auth mode: ${String(exhaustive)}`)
}
}
}
export function requireAuthMode(value: unknown): TrelloAuthMode | undefined {
if (value === undefined) return undefined
const mode = requireString(value, 'auth')
if (mode !== 'oauth' && mode !== 'keyToken') {
throw new Error('auth must be "oauth" or "keyToken".')
}
return mode
}
export function parseAuthInput(
input: TrelloAuthInput & Record<string, unknown> = {},
): TrelloAuthInput {
return {
integrationName: optionalString(input.integrationName, 'integrationName'),
integration: optionalString(input.integration, 'integration'),
account: optionalString(input.account, 'account'),
secretName: optionalString(input.secretName, 'secretName'),
apiKeySecretName: optionalString(input.apiKeySecretName, 'apiKeySecretName'),
auth: requireAuthMode(input.auth),
}
}