@lastshotlabs/slingshot-admin
npm install @lastshotlabs/slingshot-admin
Functions
Section titled “Functions”adminPluginConfigSchema
Section titled “adminPluginConfigSchema”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
createAdminCircuitBreaker
Section titled “createAdminCircuitBreaker”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): AdminCircuitBreakerSource: packages/slingshot-admin/src/lib/circuitBreaker.ts
createAdminMetricsCollector
Section titled “createAdminMetricsCollector”Create a metrics collector for the admin plugin.
function createAdminMetricsCollector(): AdminMetricsCollectorSource: packages/slingshot-admin/src/lib/metrics.ts
createAdminPlugin
Section titled “createAdminPlugin”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
createAuth0AccessProvider
Section titled “createAuth0AccessProvider”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 },): AdminAccessProviderSource: packages/slingshot-admin/src/providers/auth0Access.ts
createConsoleAuditLogger
Section titled “createConsoleAuditLogger”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): AdminAuditLoggerSource: packages/slingshot-admin/src/lib/auditLogger.ts
createMemoryAuditLogger
Section titled “createMemoryAuditLogger”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
createMemoryRateLimitStore
Section titled “createMemoryRateLimitStore”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(): AdminRateLimitStoreSource: packages/slingshot-admin/src/lib/rateLimitStore.ts
createRedisRateLimitStore
Section titled “createRedisRateLimitStore”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,): AdminRateLimitStoreSource: packages/slingshot-admin/src/lib/rateLimitStore.ts
registerAdminResourceTypes
Section titled “registerAdminResourceTypes”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 / deleteadmin:session- read / revokeadmin:role- read / writeadmin:audit- readadmin:permission- read / writeadmin: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): voidSource: packages/slingshot-admin/src/lib/resourceTypes.ts
withRetry
Section titled “withRetry”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
Classes
Section titled “Classes”AdminAccessDeniedError
Section titled “AdminAccessDeniedError”Raised when an admin request is authenticated but not authorized for the requested action.
Source: packages/slingshot-admin/src/errors.ts
AdminAuditLogError
Section titled “AdminAuditLogError”Raised when an admin audit-log operation fails.
Source: packages/slingshot-admin/src/errors.ts
AdminCircuitOpenError
Section titled “AdminCircuitOpenError”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
AdminConfigError
Section titled “AdminConfigError”Errors thrown by the admin plugin.
Source: packages/slingshot-admin/src/errors.ts
AdminRateLimitExceededError
Section titled “AdminRateLimitExceededError”Raised when an admin request exceeds the configured destructive-action rate limit.
Source: packages/slingshot-admin/src/errors.ts
Interfaces
Section titled “Interfaces”AdminAuditEvent
Section titled “AdminAuditEvent”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
AdminAuditLogger
Section titled “AdminAuditLogger”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
AdminCircuitBreaker
Section titled “AdminCircuitBreaker”Runtime circuit breaker guarding admin provider calls.
Source: packages/slingshot-admin/src/lib/circuitBreaker.ts
AdminCircuitBreakerHealth
Section titled “AdminCircuitBreakerHealth”Snapshot of breaker state — useful for health endpoints and metrics.
Source: packages/slingshot-admin/src/lib/circuitBreaker.ts
AdminCircuitBreakerOptions
Section titled “AdminCircuitBreakerOptions”Tunable options used to construct a circuit breaker.
Source: packages/slingshot-admin/src/lib/circuitBreaker.ts
AdminMetricsCollector
Section titled “AdminMetricsCollector”Collector interface for admin plugin metrics.
Source: packages/slingshot-admin/src/lib/metrics.ts
AdminMetricsSnapshot
Section titled “AdminMetricsSnapshot”Snapshot of admin plugin metrics.
Source: packages/slingshot-admin/src/lib/metrics.ts
AdminPluginConfig
Section titled “AdminPluginConfig”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
AdminPluginHealth
Section titled “AdminPluginHealth”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
AdminRateLimitHitOptions
Section titled “AdminRateLimitHitOptions”Options accepted by AdminRateLimitStore.hit.
Source: packages/slingshot-admin/src/lib/rateLimitStore.ts
AdminRateLimitHitResult
Section titled “AdminRateLimitHitResult”Result returned by AdminRateLimitStore.hit.
Source: packages/slingshot-admin/src/lib/rateLimitStore.ts
AdminRateLimitStore
Section titled “AdminRateLimitStore”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
Auth0AccessProviderConfig
Section titled “Auth0AccessProviderConfig”Configuration for the Auth0-backed AdminAccessProvider.
Source: packages/slingshot-admin/src/providers/auth0Access.ts
CreateRedisRateLimitStoreOptions
Section titled “CreateRedisRateLimitStoreOptions”Options for creating a Redis-backed rate-limit store used by admin endpoints.
Source: packages/slingshot-admin/src/lib/rateLimitStore.ts
RedisRateLimitClientLike
Section titled “RedisRateLimitClientLike”Minimal structural Redis client used by createRedisRateLimitStore.
Source: packages/slingshot-admin/src/lib/rateLimitStore.ts
RedisRateLimitMultiLike
Section titled “RedisRateLimitMultiLike”Chainable transaction builder structurally compatible with ioredis.
Source: packages/slingshot-admin/src/lib/rateLimitStore.ts
RetryOptions
Section titled “RetryOptions”Options for withRetry.
Source: packages/slingshot-admin/src/lib/retry.ts
AdminEnv
Section titled “AdminEnv”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
AdminVariables
Section titled “AdminVariables”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