Skip to content

createImpersonationManager

createImpersonationManager(d1, options?): object

Defined in: packages/auth/src/impersonation.ts:118

Creates an impersonation manager backed by a Cloudflare D1 database.

Manages an audit trail of impersonation sessions, allowing admins to temporarily act as another user for debugging and support. Each session is logged with start and end timestamps.

Graceful fallback when the table is missing

Section titled “Graceful fallback when the table is missing”

If the impersonation_logs table does not exist yet (e.g. the consumer upgraded @cfast/auth from 0.2.x to 0.3.x without running the new migration), getActiveImpersonation() returns null instead of throwing. This keeps authenticated requests working — they simply behave as if no admin is impersonating anyone — and logs a one-time warning pointing the operator at the migration they need to run. See cfast issue #172.

impersonate() and stopImpersonating() still propagate the underlying error because silently swallowing a write would pretend an admin is impersonating someone when the audit row was never recorded.

D1Database

The Cloudflare D1 database binding.

ImpersonationManagerOptions

Optional configuration for table and column names.

object

An object with impersonate, stopImpersonating, and getActiveImpersonation methods.

getActiveImpersonation(adminUserId): Promise<{ targetUserId: string; } | null>

string

Promise<{ targetUserId: string; } | null>

impersonate(adminUserId, targetUserId): Promise<void>

string

string

Promise<void>

stopImpersonating(adminUserId): Promise<void>

string

Promise<void>

import { createImpersonationManager } from "@cfast/auth";
const impersonation = createImpersonationManager(env.DB);
// Start impersonating a user
await impersonation.impersonate(adminUserId, targetUserId);
// Check if admin is currently impersonating someone
const active = await impersonation.getActiveImpersonation(adminUserId);
// active?.targetUserId
// Stop impersonating
await impersonation.stopImpersonating(adminUserId);