Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

account-id.ts

77 lines · 3.2 KB · TypeScript
/**
 * Pure account-id resolution (no runtime imports) so it can be unit tested.
 * Order: explicit `accountId`, then the id stored for the alias in
 * `./settings`, then `GET /accounts` when the token sees exactly one account.
 */
import { CLOUDFLARE_ACCOUNT_ALIASES, type CloudflareAccount } from './auth.ts'

export type AccessibleAccount = { id: string; name: string }

/** Account ids stored per token alias in this package's storage. */
export type StoredAccountIds = Partial<Record<CloudflareAccount, string>>

/** `alias` means the id stored for the alias in `./settings`. */
export type AccountIdSource = 'param' | 'alias' | 'discovered'

export const ACCOUNT_ID_PATTERN = /^[a-f0-9]{32}$/

/** Validate and normalize a Cloudflare account id (32 lowercase hex characters). */
export function normalizeAccountId(value: unknown, what = 'accountId'): string {
	const id = typeof value === 'string' ? value.trim().toLowerCase() : ''
	if (!ACCOUNT_ID_PATTERN.test(id)) {
		throw new Error(`${what} must be a 32-character hex Cloudflare account id.`)
	}
	return id
}

/** Keep only valid ids for known aliases (storage may hold anything). */
export function sanitizeStoredAccountIds(value: unknown): StoredAccountIds {
	const out: StoredAccountIds = {}
	if (!value || typeof value !== 'object' || Array.isArray(value)) return out
	const record = value as Record<string, unknown>
	for (const alias of CLOUDFLARE_ACCOUNT_ALIASES) {
		const id = typeof record[alias] === 'string' ? (record[alias] as string).trim().toLowerCase() : ''
		if (ACCOUNT_ID_PATTERN.test(id)) out[alias] = id
	}
	return out
}

/** One-line instructions for storing an account id for an alias. */
export function settingsHint(alias: CloudflareAccount): string {
	return (
		`Store it once with kody:@kentcdodds/cloudflare/settings ({ accountIds: { ${alias}: '<accountId>' } }), ` +
		'or pass accountId on the call. Copy the id from the Cloudflare dashboard URL (dash.cloudflare.com/<accountId>/...).'
	)
}

export type ResolveAccountIdDeps = {
	readStored: () => Promise<StoredAccountIds>
	listAccounts: () => Promise<AccessibleAccount[]>
}

/**
 * Resolve the Cloudflare account id for an account-scoped call. Throws a clear
 * error (with how to set it) when nothing resolves or the token is ambiguous.
 */
export async function resolveAccountIdWith(
	input: { accountId?: unknown; alias: CloudflareAccount; label: string },
	deps: ResolveAccountIdDeps,
): Promise<{ accountId: string; source: AccountIdSource }> {
	if (typeof input.accountId === 'string' && input.accountId.trim()) {
		return { accountId: normalizeAccountId(input.accountId), source: 'param' }
	}
	const stored = (await deps.readStored())[input.alias]
	if (stored) return { accountId: stored, source: 'alias' }
	const listed = await deps.listAccounts()
	if (listed.length === 1) return { accountId: listed[0].id, source: 'discovered' }
	if (listed.length > 1) {
		throw new Error(
			`accountId is required: ${input.label} can access ${listed.length} accounts (` +
				listed.map((account) => `${account.name} ${account.id}`).join(', ') +
				`). ${settingsHint(input.alias)}`,
		)
	}
	throw new Error(
		`accountId is required: ${input.label} has no stored account id and GET /accounts returned none. ${settingsHint(input.alias)}`,
	)
}