Skip to content

station ​

@c9up/station: an admin panel for a ream application, built from a declarative catalogue of resources (defineResource) that mounts list, show, create, edit and destroy routes under /admin, behind a sign-in, per-action permissions, CSRF checks and an audit trail. Guide: Admin panel.

Installation ​

bash
pnpm add @c9up/station

Add () => import('@c9up/station/provider') to the providers in reamrc.ts, and optionally a config/station.ts. The peers are optional for the package but needed for an admin surface: @c9up/ream (router), @c9up/atlas (the entities and the db connection), @c9up/inker (the views, required once a resource is declared), @c9up/rune (body validation, required when a resource mounts create or edit), and @c9up/warden (the sign-in and permission gate; without it the admin stays open).

Entry points ​

ImportContents
@c9up/stationdefineResource, defineConfig, ResourceRegistry, the provider class, the resource and audit types, and the casing helpers.
@c9up/station/providerStationProvider (default export) and its config types.
@c9up/station/services/mainThe application's ResourceRegistry (default export).

Exports ​

@c9up/station ​

ExportKindDescription
defineResourcefunctionDeclares one admin resource from an entity class.
defineConfigfunctionTypes config/station.ts; identity at runtime.
ResourceRegistryclassThe catalogue of declared resources.
StationProviderproviderAlso the default export of @c9up/station/provider.
StationConfiginterfaceThe station config.
StationAppContextinterfaceWhat the provider reads of the application.
StationLoginRateLimitConfiginterfaceThe sign-in throttle.
StationLoginLimiterinterfaceA limiter shared across instances.
ResourceinterfaceA declared resource, as defineResource returns it.
ResourceOptionsinterfaceWhat defineResource takes.
ResourceActiontype'list' | 'show' | 'create' | 'edit' | 'destroy'.
RESOURCE_ACTIONSconstThe five actions, frozen.
FormFieldOverrideinterfacePer-field form overrides.
AuditEvent, AuditSinktypeA write's audit record and its sink.
SecurityAuditEvent, SecurityAuditAction, SecurityAuditSinktypeSign-in, logout, denial and CSRF events and their sink.
kebabCase, titleCase, pluralisefunction(input: string): string: the casing used to derive slugs and labels.
errorsnamespaceThe package's errors, one class per code, see Errors.

defineResource ​

FunctionSignatureDescription
defineResourcedefineResource<T>(options: ResourceOptions<T>): Resource<T>Throws when entity is not a class or actions is empty.
ResourceOptions fieldTypeDefaultDescription
entitynew (...args: never[]) => TrequiredThe atlas entity class.
labelstringderived from the classShown in the admin sidebar.
actionsReadonlyArray<ResourceAction>all fiveThe actions mounted.
namestringderived from the classThe URL slug.
auditAuditSinka once-per-process warningCalled after each successful write.
auditSecretsbooleanfalseHand secret column values to the sink as they are; otherwise they are "[redacted]".
onAuditError(event: AuditEvent, error: unknown) => voidlogged at errorCalled when the sink throws; the write has already committed.
formFieldsReadonly<Record<string, FormFieldOverride>>Overrides keyed by property name: hidden, inputType, label, placeholder, required.
list, show{ columns?: ReadonlyArray<string> }every non-secret columnThe columns each view renders, in order.
editableReadonlyArray<string>every column except framework-managed ones, secrets and hidden fieldsThe columns a create or edit may set; a secret listed here is write-only.

FormFieldOverride.inputType is 'text' | 'number' | 'email' | 'password' | 'date' | 'datetime-local' | 'checkbox' | 'textarea'.

ResourceRegistry ​

MemberSignatureDescription
registerregister<T>(resource: Resource<T>): voidAdds a resource and mounts its routes once the provider started; a duplicate name throws.
getget(name: string): Resource | undefined
getOrThrowgetOrThrow(name: string): Resource
hashas(name: string): boolean
countcount(): number
allall(): ReadonlyArray<Resource>In registration order.
useMounteruseMounter(mounter: ResourceMounter): voidSet by the provider; mounts what was already registered.

Audit events ​

AuditEvent fieldType
actionResourceAction
resourcestring
recordId, userIdunknown
before, afterReadonly<Record<string, unknown>>
redactedChangesReadonlyArray<string>
ip, userAgent, requestIdstring
atDate

SecurityAuditEvent carries action ('login' | 'login_failed' | 'login_throttled' | 'logout' | 'denied' | 'csrf_denied'), userId, identifier, resource, resourceAction, permission, path, ip, userAgent, requestId and at. A sink is (event) => void | Promise<void>.

@c9up/station/provider ​

ExportKindDescription
StationProviderprovider (default)register() binds the ResourceRegistry; boot() publishes it; start() reads the station config, loads the peers, mounts the sign-in surface and every resource as it is registered, and stops silently when a peer it needs is not installed.
StationConfig, StationAppContextinterface

The routes, under the configured middleware:

RouteAction
GET /adminRedirects to the first listable resource, or the sign-in page.
GET /admin/login, POST /admin/login, POST /admin/logoutSign-in and logout (with the auth gate).
GET /admin/<slug>list
GET /admin/<slug>/new, POST /admin/<slug>create
GET /admin/<slug>/:idshow
GET /admin/<slug>/:id/edit, PUT /admin/<slug>/:idedit
DELETE /admin/<slug>/:iddestroy

A form posting to POST /admin/<slug>/:id chooses the method with _method.

@c9up/station/services/main ​

ExportKindDescription
defaultconstThe application's ResourceRegistry. Any property access before the provider booted throws.
ts
// start/admin.ts
import station from '@c9up/station/services/main'
import { defineResource } from '@c9up/station'
import User from '#models/user'

station.register(defineResource({ entity: User, label: 'Users' }))

Configuration ​

config/station.ts, through defineConfig. Every key is optional.

OptionTypeDefaultDescription
requireAuthbooleantrue when @c9up/warden is installedMount the sign-in surface and gate every /admin/* route.
requireRolestringA role required on top of accessPermission.
permissionPrefixstring'station'Actions need <prefix>.<resource>.<action>, entry needs <prefix>.access.
accessPermissionstring | false<prefix>.accessThe permission to enter /admin/*; false removes this gate.
loginPathstring'/admin/login'Where a failed auth check redirects.
cookieNamestring'station_auth'The cookie carrying the auth token.
cookieSecurebooleanon, except a development or test process over plain HTTPThe cookie's Secure flag.
loginRateLimitStationLoginRateLimitConfig | false5 attempts per IP and per identifier every 15 minutes, in memorymaxAttempts, windowSeconds, or a shared limiter; false turns it off.
middlewareReadonlyArray<string>Named router middleware attached to every station route.
guardstringthe auth manager's defaultThe warden guard; it must be a token guard, a session guard is refused at boot.
auditSecurityAuditSinkSink for the admin's security events.

StationLoginLimiter is { attempt(...keys: string[]): Promise<{ allowed: boolean; retryAfterSeconds: number }>; clear(...keys: string[]): Promise<void> }.

Container bindings ​

TokenResolves to
ResourceRegistryThe registry singleton.
'station'The same instance; declared on ContainerBindings.

Errors ​

A refusal raised at boot or by the registry is a class of the errors namespace and a @c9up/flare Exception (status 500): branch on error.code or on error instanceof errors.E_STATION_*, with import { errors } from '@c9up/station'. The sign-in and CSRF codes are not thrown: they are the code of the refused HTTP response.

CodeRaised when
E_STATION_LOGIN_CREDENTIALS_REQUIREDThe sign-in form was sent without an email or a password (400).
E_STATION_LOGIN_IDENTIFIER_TOO_LONGThe sign-in email is longer than 254 characters (400).
E_STATION_INVALID_CREDENTIALSInvalid email or password (401).
E_STATION_TOO_MANY_LOGIN_ATTEMPTSToo many sign-in attempts (429).
E_STATION_LOGIN_UNAVAILABLESign-in is temporarily unavailable (503).
E_STATION_CSRF_REQUIREDAn admin action lacks an active, verified CSRF token (403).
E_VALIDATION_ERRORAn admin form failed validation (422 for JSON clients; a browser is redirected back).
E_STATION_NOT_BOOTEDThe services/main registry was used before StationProvider booted, or before setStation().
E_STATION_INVALID_RESOURCEdefineResource() was given an invalid declaration (entity, name, actions, column lists, formFields, audit, onAuditError).
E_STATION_DUPLICATE_RESOURCETwo resources were registered under the same name.
E_STATION_UNKNOWN_RESOURCEgetOrThrow() named a resource that is not registered.
E_STATION_UNKNOWN_COLUMNA resource's list.columns, show.columns or editable names a property that is not a column of the entity.
E_STATION_COLUMN_NOT_EDITABLEeditable names a column the framework manages (primary key, timestamp, relation, soft delete) or one formFields hides.
E_STATION_PRIMARY_KEY_MISSINGAn admin entity declares no @PrimaryKey() column.
E_STATION_INVALID_CONFIGA station option is invalid (audit, permissionPrefix, guard, loginRateLimit).
E_STATION_UNKNOWN_GUARDstation.guard names a guard warden does not know.
E_STATION_GUARD_NOT_JWTThe admin guard does not issue a bearer token; Station needs a JWT guard.
E_STATION_AUTH_REQUIREDNo working auth binding is registered while requireAuth: true is set, or outside development and test.
E_STATION_DATABASE_REQUIREDNo db connection is registered for the admin (register @c9up/atlas/provider).
E_STATION_RUNE_REQUIREDA resource with write forms needs @c9up/rune, which is not installed.
E_STATION_INKER_REQUIREDNo @c9up/inker view engine is registered to render the admin.
E_STATION_INKER_UNUSABLE@c9up/inker is registered but does not resolve to a usable view renderer; see cause.
E_STATION_ROUTE_MIDDLEWARE_UNSUPPORTEDstation.middleware is set but the router's routes have no middleware() method.
E_STATION_INTERNALAn internal invariant broke (the view engine was not initialised); report it as a bug.

Migration ​

  • @c9up/station/provider exports the provider and its two config types only. resourcesNeedValidation, deriveWritableSchema, validateWritableBody, isModuleNotFound, isPackageMissing and resetStationProviderFlags are gone: they were the package's test seams, not an application API. An import of one of them must go.
  • A refusal is no longer a plain Error or TypeError: test error.code, or error instanceof errors.E_STATION_*. The ones that were a TypeError (a defineResource() option or station.audit of the wrong type) no longer are: replace instanceof TypeError with error.code === 'E_STATION_INVALID_RESOURCE' or 'E_STATION_INVALID_CONFIG'.
  • A successful admin sign-in now clears the identifier's throttle key only (id:<digest>), not the IP's (ip:<address>). A limiter you pass as loginRateLimit.limiter now receives clear() with that one key; an address that keeps failing stays throttled until its window ends.

See also ​