Skip to content
← Public packages

@kody/doppler

Use Doppler secrets in secret-aware fetch through a read-only service token, without the agent ever seeing the values.

FollowFork

Files

secret-provider.ts

292 lines · 10.8 KB · TypeScript
// Sealed Doppler secret provider for Kody. See the JSDoc on the default export.

const DOPPLER_API = 'https://api.doppler.com'
const RESOLVE_BUDGET_MS = 7500

/** Doppler secret names: letters, digits, underscores; not starting with a digit. */
const SECRET_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/
/** Exact DNS hostname, lowercase, at least one dot. No scheme, port, path, or wildcard. */
const HOSTNAME_RE =
	/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/
/** Doppler project and config slugs. */
const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/

/** Token prefixes this provider accepts. Personal and CLI tokens are refused (read/write on the whole account). */
const ACCEPTED_TOKEN_PREFIXES = ['dp.st.', 'dp.sa.']

type SecretProviderInvokeInput = {
	action: 'canonicalize' | 'resolve'
	providerId?: string
	ref: string
	canonicalRef?: string | null
	doorSecretName?: string
	doorSecretValue?: string
	config?: Record<string, string>
}

type Field = 'computed' | 'raw'

type ParsedRef = { name: string; field: Field }

function fail(message: string): never {
	throw new Error(message)
}

/**
 * Parse a Doppler ref. Accepted forms (one canonical form per meaning):
 * - `s/<NAME>` (canonical, computed value) and the synonyms `<NAME>`, `s/<NAME>/computed`
 * - `s/<NAME>/raw` (canonical, raw value with references unexpanded)
 */
function parseRef(raw: unknown): ParsedRef {
	const ref = typeof raw === 'string' ? raw.trim() : ''
	if (!ref) fail('Doppler ref is empty. Use s/<SECRET_NAME>, for example s/STRIPE_API_KEY.')
	if (SECRET_NAME_RE.test(ref)) return { name: ref, field: 'computed' }
	const m = /^s\/([^/]+)(?:\/([^/]+))?$/.exec(ref)
	if (!m) {
		fail(
			'Unrecognized Doppler ref. Use s/<SECRET_NAME> (computed value) or s/<SECRET_NAME>/raw (raw value).',
		)
	}
	const name = m[1]!
	if (!SECRET_NAME_RE.test(name)) {
		fail(
			'Doppler secret names use letters, digits, and underscores and cannot start with a digit.',
		)
	}
	const fieldRaw = (m[2] ?? 'computed').toLowerCase()
	if (fieldRaw !== 'computed' && fieldRaw !== 'raw') {
		fail('Unknown Doppler ref field. Use s/<SECRET_NAME> or s/<SECRET_NAME>/raw.')
	}
	return { name, field: fieldRaw }
}

function toCanonicalRef(parsed: ParsedRef): string {
	return parsed.field === 'raw' ? `s/${parsed.name}/raw` : `s/${parsed.name}`
}

function parseHostList(raw: string, key: string): string[] {
	const hosts: string[] = []
	for (const part of raw.split(',')) {
		const host = part.trim().toLowerCase()
		if (!host) continue
		if (!HOSTNAME_RE.test(host)) {
			fail(
				`Binding config "${key}" has an entry that is not a plain hostname. Use comma-separated hostnames such as api.example.com (no scheme, port, path, or wildcard).`,
			)
		}
		if (!hosts.includes(host)) hosts.push(host)
	}
	return hosts
}

/**
 * Host allowlist for one secret: `hosts.<NAME>` wins over `hosts`.
 * Empty fails closed so a value is never released without a destination list.
 */
function hostsFor(config: Record<string, string>, name: string): string[] {
	const perSecretKey = `hosts.${name}`
	const perSecret = config[perSecretKey]
	if (typeof perSecret === 'string' && perSecret.trim()) {
		const hosts = parseHostList(perSecret, perSecretKey)
		if (hosts.length) return hosts
	}
	const shared = typeof config.hosts === 'string' ? parseHostList(config.hosts, 'hosts') : []
	if (shared.length) return shared
	fail(
		`No destination hosts are configured for Doppler secret ${name}. Rebind with config {"hosts":"api.example.com"} or {"hosts.${name}":"api.example.com"}. Empty hosts fail closed.`,
	)
}

/** Optional project/config scoping. Both or neither. */
function projectAndConfig(
	config: Record<string, string>,
): { project: string; config: string } | null {
	const project = typeof config.project === 'string' ? config.project.trim() : ''
	const cfg = typeof config.config === 'string' ? config.config.trim() : ''
	if (!project && !cfg) return null
	if (!project || !cfg) {
		fail('Binding config must set both "project" and "config", or neither (a service token already implies its config).')
	}
	if (!SLUG_RE.test(project) || !SLUG_RE.test(cfg)) {
		fail('Binding config "project" and "config" must be Doppler slugs (letters, digits, dashes, underscores).')
	}
	return { project, config: cfg }
}

function assertToken(token: string | undefined): string {
	const value = typeof token === 'string' ? token.trim() : ''
	if (!value) {
		fail('The Doppler door secret is empty. Save a Doppler service token as the bound user secret and rebind.')
	}
	if (!ACCEPTED_TOKEN_PREFIXES.some((p) => value.startsWith(p))) {
		fail(
			'The Doppler door secret is not a service token or service account token. Use a read-only service token scoped to one config (it starts with dp.st.). Personal and CLI tokens are refused.',
		)
	}
	return value
}

function retryAfterSeconds(res: Response): number | null {
	const header = res.headers.get('retry-after')
	if (!header) return null
	const n = Number(header.trim())
	return Number.isFinite(n) && n >= 0 ? Math.ceil(n) : null
}

/** Map a non-OK Doppler response to a clear error. Never includes the token, response body, or any value. */
function dopplerHttpError(res: Response, name: string): Error {
	const status = res.status
	switch (status) {
		case 400:
			return new Error(
				`Doppler rejected the request for ${name} (HTTP 400). Check the binding config project/config values and the secret name.`,
			)
		case 401:
			return new Error(
				'Doppler rejected the service token (HTTP 401). It may be revoked, expired, or mistyped. Create a new service token and update the door secret.',
			)
		case 403:
			return new Error(
				`Doppler denied access to ${name} (HTTP 403). The service token is scoped to a different project/config, or the binding config points at a config it cannot read.`,
			)
		case 404:
			return new Error(
				`Doppler secret ${name} was not found (HTTP 404). Check the secret name and that the token's config contains it.`,
			)
		case 429: {
			const wait = retryAfterSeconds(res)
			return new Error(
				`Doppler rate limit reached (HTTP 429).${wait !== null ? ` Retry after ${wait}s.` : ' Retry later.'} Limits are per token per minute.`,
			)
		}
		default:
			if (status >= 500) {
				return new Error(`Doppler API is unavailable (HTTP ${status}). Retry later.`)
			}
			return new Error(`Doppler API request for ${name} failed (HTTP ${status}).`)
	}
}

async function dopplerGet(url: URL, token: string, signal: AbortSignal): Promise<Response> {
	try {
		return await fetch(url.toString(), {
			method: 'GET',
			headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
			signal,
		})
	} catch (err) {
		if (err instanceof Error && err.name === 'AbortError') throw err
		// Do not forward the underlying message; it can carry request details.
		fail('Could not reach api.doppler.com. Retry later.')
	}
}

async function readJson(res: Response): Promise<unknown> {
	try {
		return await res.json()
	} catch {
		fail('Doppler returned a response that is not JSON.')
	}
}

/** Computed value through the download endpoint, limited to one secret. */
async function fetchComputed(
	name: string,
	token: string,
	scope: { project: string; config: string } | null,
	signal: AbortSignal,
): Promise<string> {
	const url = new URL('/v3/configs/config/secrets/download', DOPPLER_API)
	if (scope) {
		url.searchParams.set('project', scope.project)
		url.searchParams.set('config', scope.config)
	}
	url.searchParams.set('format', 'json')
	url.searchParams.set('secrets', name)
	const res = await dopplerGet(url, token, signal)
	if (!res.ok) throw dopplerHttpError(res, name)
	const body = await readJson(res)
	if (!body || typeof body !== 'object' || Array.isArray(body)) {
		fail('Doppler download returned an unexpected body shape.')
	}
	const value = (body as Record<string, unknown>)[name]
	if (value === undefined) {
		fail(`Doppler secret ${name} was not found in the token's config.`)
	}
	if (typeof value !== 'string') {
		fail(`Doppler secret ${name} did not download as a string.`)
	}
	return value
}

/** Raw value through the single-secret endpoint. */
async function fetchRaw(
	name: string,
	token: string,
	scope: { project: string; config: string } | null,
	signal: AbortSignal,
): Promise<string> {
	const url = new URL('/v3/configs/config/secret', DOPPLER_API)
	if (scope) {
		url.searchParams.set('project', scope.project)
		url.searchParams.set('config', scope.config)
	}
	url.searchParams.set('name', name)
	const res = await dopplerGet(url, token, signal)
	if (!res.ok) throw dopplerHttpError(res, name)
	const body = (await readJson(res)) as { value?: { raw?: unknown } } | null
	const raw = body && typeof body === 'object' ? body.value?.raw : undefined
	if (typeof raw !== 'string') {
		fail(`Doppler secret ${name} has no readable raw value (it may be restricted).`)
	}
	return raw
}

/**
 * Sealed Doppler secret provider handler for Kody secret-aware fetch.
 * The platform fetch boundary calls it with action "canonicalize" (map a ref
 * to its grant key, no network) or "resolve" (read one secret value from
 * Doppler with the bound service token). Ordinary execute or kody:@ imports
 * of this export are refused by the platform. Use placeholders instead.
 *
 * @param input - action, ref, canonicalRef, door secret name/value, and the non-secret binding config (hosts, optional project/config)
 * @returns For canonicalize, `{ canonicalRef }`. For resolve, `{ value, hosts, canonicalRef }`.
 *
 * @example
 * // Not callable from execute. Reference a Doppler secret in a fetch instead:
 * // headers: { Authorization: 'Bearer {{secret/doppler:s/<SECRET_NAME>}}' }
 */
export default async function secretProvider(
	input: SecretProviderInvokeInput,
): Promise<{ canonicalRef: string } | { value: string; hosts: string[]; canonicalRef: string }> {
	const action = input?.action
	if (action !== 'canonicalize' && action !== 'resolve') {
		fail(`Unknown secret provider action "${String(action)}". Expected "canonicalize" or "resolve".`)
	}
	const parsed = parseRef(input.canonicalRef || input.ref)
	const canonicalRef = toCanonicalRef(parsed)
	if (action === 'canonicalize') return { canonicalRef }

	const token = assertToken(input.doorSecretValue)
	const config = input.config ?? {}
	const hosts = hostsFor(config, parsed.name)
	const scope = projectAndConfig(config)

	const controller = new AbortController()
	const timer = setTimeout(() => controller.abort(), RESOLVE_BUDGET_MS)
	try {
		const value =
			parsed.field === 'raw'
				? await fetchRaw(parsed.name, token, scope, controller.signal)
				: await fetchComputed(parsed.name, token, scope, controller.signal)
		if (value.length === 0) fail(`Doppler secret ${parsed.name} is empty.`)
		return { value, hosts, canonicalRef }
	} catch (err) {
		if (err instanceof Error && err.name === 'AbortError') {
			fail('Doppler resolve timed out. Check api.doppler.com reachability and retry.')
		}
		throw err
	} finally {
		clearTimeout(timer)
	}
}