Skip to content

@lastshotlabs/slingshot-admin

npm install @lastshotlabs/slingshot-admin

Zod schema for AdminPluginConfig. Used by createAdminPlugin to validate raw config at startup.

Remarks: Validation behavior: Each provider field uses z.object({...}).passthrough() which validates the value is a proper object whose required methods exist at schema-parse time. This provides stronger validation than z.custom<T>() (which only checked for a non-null object). Method signature details are checked separately via validateAdapterShape(), which throws with a descriptive message if a required method is missing.

Remarks: Validate your config object against this schema early (e.g. at module load time) to surface misconfiguration before any HTTP traffic arrives. If you are composing config dynamically (e.g. from environment variables), prefer safeParse() over parse() so you can handle errors without an uncaught exception.

Remarks: Optional fields: mailRenderer and auditLog may be omitted. When mailRenderer is absent, admin email endpoints return 501 Not Implemented. When auditLog is absent, admin actions are not recorded.

Source: packages/slingshot-admin/src/types/config.ts

Construct a circuit breaker for admin provider calls.

State machine: closed — normal operation; failures increment a counter. open — fail fast; reject every request until cooldown elapses. half-open — let exactly one probe through; success resets, failure re-opens.

function createAdminCircuitBreaker(opts: AdminCircuitBreakerOptions): AdminCircuitBreaker

Source: packages/slingshot-admin/src/lib/circuitBreaker.ts

Create a metrics collector for the admin plugin.

function createAdminMetricsCollector(): AdminMetricsCollector

Source: packages/slingshot-admin/src/lib/metrics.ts

Creates the Slingshot admin plugin, which mounts user-management, permissions, and (optionally) mail-preview routes under a configurable path.

All routes are protected by a single access-guard middleware that calls config.accessProvider.verifyRequest(). The resolved principal is stored on the Hono context as adminPrincipal for downstream handlers.

Circuit breaker: The access provider is wrapped in a circuit breaker (default: open after 5 consecutive failures, 30 s cooldown). When the breaker is open, admin requests return 503 immediately instead of timing out against a degraded upstream.

Health & metrics: GET <mountPath>/health and GET <mountPath>/metrics are mounted before the auth guard so monitoring systems can reach them.

Teardown: Calls teardown() to reset internal counters and state. Register this with your server’s shutdown handler.

function createAdminPlugin(rawConfig: AdminPluginConfig,): SlingshotPlugin &

Source: packages/slingshot-admin/src/plugin.ts

Creates an AdminAccessProvider that verifies RS256 JWTs issued by Auth0.

Remarks: JWKS caching: jose’s createRemoteJWKSet() returns a function that lazily fetches the JWKS from https://<domain>/.well-known/jwks.json on the first jwtVerify call. Subsequent calls reuse the in-memory keyset until the JWT references an unknown kid, at which point jose automatically re-fetches the JWKS to pick up any key rotation. The JWKS function (JWKS) is created once at provider construction time and shared across all requests.

Remarks: Token caching: Individual JWT verification results are not cached. Every request re-verifies the token’s signature, expiry (exp), aud claim, and iss (issuer, expected to be https://<domain>/). This is intentional — admin tokens should be short-lived (< 1 hour) and individual token revocation is not supported by the JWKS approach.

Remarks: Error handling: Any verification failure (expired token, wrong audience, bad signature, network error, missing sub claim) causes verifyRequest to return null. The admin middleware translates null into a 401 response. No error details are surfaced to the caller to avoid leaking validation state.

function createAuth0AccessProvider(config: Auth0AccessProviderConfig, deps: Auth0Deps = { createRemoteJWKSet, jwtVerify },): AdminAccessProvider

Source: packages/slingshot-admin/src/providers/auth0Access.ts

Create a console-backed admin audit logger.

Writes each event as a structured JSON log line via the provided logger (defaults to a console logger with { plugin: 'slingshot-admin' } base).

function createConsoleAuditLogger(baseLogger?: Logger): AdminAuditLogger

Source: packages/slingshot-admin/src/lib/auditLogger.ts

Create an in-memory admin audit logger.

Events are stored in an array and never persisted. Useful for testing and single-instance deployments where a durable audit trail is not required.

The returned object includes getEvents() and clear() helpers for test assertions and state reset.

function createMemoryAuditLogger(): AdminAuditLogger &

Source: packages/slingshot-admin/src/lib/auditLogger.ts

Build an in-process rate-limit store. Suitable for single-instance deploys and tests. State is stored in a plain Map; no eviction other than the window-expiry check on each hit.

function createMemoryRateLimitStore(): AdminRateLimitStore

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Build a Redis-backed rate-limit store. Uses MULTI + INCR + PEXPIRE NX so the counter increment and TTL initialisation happen atomically and the window cannot be silently extended by concurrent hits.

function createRedisRateLimitStore(opts: CreateRedisRateLimitStoreOptions,): AdminRateLimitStore

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Registers all admin resource types and their role-to-action mappings into a PermissionRegistry.

Call this once during application bootstrap, before createApp(). Registries become immutable after the server starts.

Registered resource types:

  • admin:user - read / write / suspend / delete
  • admin:session - read / revoke
  • admin:role - read / write
  • admin:audit - read
  • admin:permission - read / write
  • admin:mail - read

Remarks: The super-admin role is not listed in any roles map. The permission registry handles super-admin specially: getActionsForRole(*, 'super-admin') always returns ['*'].

Remarks: Only resource types with implemented route handlers are registered here. Do not add resource types until the corresponding routes exist.

function registerAdminResourceTypes(registry: PermissionRegistry): void

Source: packages/slingshot-admin/src/lib/resourceTypes.ts

Invoke fn with retries on failure.

The function is called immediately. If it rejects and the error passes shouldRetry, up to maxRetries additional attempts are made with exponential backoff. Non-retryable errors and errors that persist after all retries are exhausted are thrown to the caller.

async function withRetry<T>(fn: () => Promise<T>, opts: RetryOptions = {}): Promise<T>

Source: packages/slingshot-admin/src/lib/retry.ts

Raised when an admin request is authenticated but not authorized for the requested action.

Source: packages/slingshot-admin/src/errors.ts

Raised when an admin audit-log operation fails.

Source: packages/slingshot-admin/src/errors.ts

Thrown when the breaker is open and refuses to invoke the provider.

retryAfterMs is the time remaining until the breaker enters half-open state. Callers can surface this as a backoff hint.

Source: packages/slingshot-admin/src/lib/circuitBreaker.ts

Errors thrown by the admin plugin.

Source: packages/slingshot-admin/src/errors.ts

Raised when an admin request exceeds the configured destructive-action rate limit.

Source: packages/slingshot-admin/src/errors.ts

An audit event emitted by the admin plugin for CRUD operations.

Designed for admin-specific use — provides a higher-level view of who did what to which resource and whether it succeeded. The core AuditLogProvider interface used elsewhere in the plugin remains available for apps that need the full request-level event detail.

Source: packages/slingshot-admin/src/lib/auditLogger.ts

Pluggable audit logger for admin operations.

Implementations may write to an in-memory store, a structured logger, or forward events to an external audit backend.

Source: packages/slingshot-admin/src/lib/auditLogger.ts

Runtime circuit breaker guarding admin provider calls.

Source: packages/slingshot-admin/src/lib/circuitBreaker.ts

Snapshot of breaker state — useful for health endpoints and metrics.

Source: packages/slingshot-admin/src/lib/circuitBreaker.ts

Tunable options used to construct a circuit breaker.

Source: packages/slingshot-admin/src/lib/circuitBreaker.ts

Collector interface for admin plugin metrics.

Source: packages/slingshot-admin/src/lib/metrics.ts

Snapshot of admin plugin metrics.

Source: packages/slingshot-admin/src/lib/metrics.ts

Configuration object for the Slingshot admin plugin.

All provider fields map directly to injectable provider interfaces. The plugin itself has no persistence of its own; storage is delegated to these providers.

Source: packages/slingshot-admin/src/types/config.ts

Aggregated health snapshot for slingshot-admin.

slingshot-admin does not own a database or cache; this snapshot reflects configured providers and circuit breaker state without performing I/O.

Source: packages/slingshot-admin/src/types/health.ts

Options accepted by AdminRateLimitStore.hit.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Result returned by AdminRateLimitStore.hit.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Pluggable counter store backing the admin destructive-mutation rate limiter.

Implementations must atomically increment the counter for key and (re)set the TTL when the key is first created in a window so that concurrent calls cannot mint two windows for the same key.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Configuration for the Auth0-backed AdminAccessProvider.

Source: packages/slingshot-admin/src/providers/auth0Access.ts

Options for creating a Redis-backed rate-limit store used by admin endpoints.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Minimal structural Redis client used by createRedisRateLimitStore.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Chainable transaction builder structurally compatible with ioredis.

Source: packages/slingshot-admin/src/lib/rateLimitStore.ts

Options for withRetry.

Source: packages/slingshot-admin/src/lib/retry.ts

Hono environment type for admin routes. Extends AppEnv with adminPrincipal. Uses intersection to add the admin variable while keeping AppEnv compatibility. The defaultHook cast (Hook<AppEnv> → Hook<AdminEnv>) is safe because AdminEnv only adds variables; existing AppEnv variables remain accessible.

Source: packages/slingshot-admin/src/types/env.ts

Extra Hono context variables injected by the admin access-guard middleware. After the guard runs, c.get('adminPrincipal') is always a valid AdminPrincipal — the middleware rejects the request with 401 before reaching a route handler if the principal cannot be resolved.

Source: packages/slingshot-admin/src/types/env.ts