Skip to content

Latest commit

 

History

History

administration

README.md

Relay administration

TECH-588 introduces a separate Svelte/Tailwind application and Node management service. It talks only to versioned private Relay and Jetstream APIs. It never opens their databases, inherits their Basic-auth UI, or implements ingestion.

For Railway containers, volumes, networking and administrator bootstrap, see the Railway runbook.

Run locally

Use Node 24.18 or later, Go versions required by each module, and npm. From this directory:

npm ci
npm run build
# Set the configuration below, including ADMIN_SEED_DID for first access, then:
npm run server
Variable Meaning
ADMIN_PUBLIC_ORIGIN Exact externally visible HTTPS origin; local development uses http://127.0.0.1:3000.
ADMIN_SEED_DID Optional full DID to grant ordinary administrator access once, on an uninitialized database.
ADMIN_DATABASE Dedicated SQLite file on durable local storage.
ADMIN_ENCRYPTION_KEY_FILE File containing a random secret of at least 32 bytes, used to encrypt OAuth tokens and handshake state.
ADMIN_BIND / PORT Listener, default 127.0.0.1:3000. Put an HTTPS proxy in front for remote use.
RELAY_CONTROL_URL Private Relay origin, without /hypercerts/v1.
RELAY_CONTROL_TOKEN_FILE Mounted Relay service credential, at least 32 bytes.
JETSTREAM_CONTROL_URL Private Jetstream operations origin.
JETSTREAM_CONTROL_TOKEN_FILE Mounted Jetstream service credential, at least 32 bytes.
RELAY_PUBLIC_ORIGIN Optional public Relay HTTPS origin displayed on the Overview page; never use the control URL.
RAINBOW_PUBLIC_ORIGIN Optional public Rainbow HTTPS origin displayed on the Overview page.
JETSTREAM_PUBLIC_ORIGIN Optional public Jetstream HTTPS origin displayed on the Overview page; never use the control URL.
ADMIN_DISCOVERY_TOKEN_FILE Optional machine token, at least 32 bytes, for cmd/pdsdiscovery. When unset, the discovery state and operations routes are not mounted.
COLLECTIONDIR_CONTROL_URL Optional private collection directory origin, such as http://collectiondir.railway.internal:2510. Unset disables crawls.
COLLECTIONDIR_CONTROL_TOKEN_FILE File containing the collection directory's COLLECTIONS_ADMIN_TOKEN, at least 32 bytes. Required with the URL.

The Relay independently uses JETSTREAM_CONTROL_URL and JETSTREAM_CONTROL_TOKEN for its durable source-lifecycle handoff to Jetstream. Configure both on the Relay process to enable handoffs; if both are absent, Relay keeps durable rows queued and does not send them. If exactly one is absent, Relay fails startup. This outbound Relay token is distinct from Jetstream's JETSTREAM_CONTROL_TOKEN_FILE, which configures Jetstream's inbound private API.

Run one administration process per database. Use a process supervisor; this is a stateful Node service, not a stateless function. Keep the database directory and secret files accessible only to its service account. SQLite uses WAL and FULL synchronization. OAuth values are AES-256-GCM encrypted; retain the encryption key with the database for restart. Replacing that key requires signing in again and clearing the old OAuth state through the access-revocation command.

In Relay, set RELAY_CONTROL_ADDR and RELAY_CONTROL_TOKEN_FILE together. This starts a separate bearer-authenticated listener. It is never mounted on the public API. In Jetstream, configure JETSTREAM_DEBUG_ADDR and JETSTREAM_CONTROL_TOKEN_FILE as documented in ../jetstream/README.md. Use TLS between services, or Railway private service origins with HC_RAILWAY_STARTUP=1. Control URLs reject plaintext HTTP except loopback and single-service *.railway.internal origins in Railway startup mode. The three optional *_PUBLIC_ORIGIN values accept only HTTPS origins (or loopback HTTP for local development) and are display-only; they must not expose private management/debug listeners. No component is deployed by this change.

COLLECTIONDIR_CONTROL_URL and COLLECTIONDIR_CONTROL_TOKEN_FILE are optional and must be set together; if exactly one is set, startup fails. The URL follows the same transport rules as the other control URLs and must not equal the Relay or Jetstream control origin or any *_PUBLIC_ORIGIN. The collection directory itself accepts any nonempty token, but Administration requires at least 32 bytes, so set a COLLECTIONS_ADMIN_TOKEN of that length before enabling crawls.

/oauth-client-metadata.json must be reachable by authorization servers at the public origin. OAuth uses the maintained AT Protocol Node client for discovery, PAR, PKCE, DPoP and callback validation; only the atproto scope is requested. The browser receives an opaque HTTP-only session cookie and a separate CSRF token, never OAuth or service credentials. Login binds the callback to its initiating browser. Sessions expire after eight hours. Unsafe API requests require the exact Origin and session CSRF token; protected reads also require current administrator membership. All responses prohibit caching.

Administrator access

Set ADMIN_SEED_DID to the initial operator's full DID at runtime. It is not a handle, password, or special superadministrator. An invalid or empty configured value fails startup. Omit the variable when not needed.

On an uninitialized database, startup atomically grants this DID, records an administrator_seed audit event and saves a durable initialization marker. Restarts and changes to the variable never grant it again. Existing administrator membership or recorded access history also prevents seeding. Removing every administrator does not reset initialization; retain the database across deploys.

After signing in, use Administrators to grant access to another DID or remove another administrator, including the seed DID. Removal immediately invalidates all their local sessions and stored OAuth tokens, and records the acting admin in the audit history. Admins cannot remove their own access through this API or UI; another administrator must do that. Normal OAuth sign-in is still required.

The CLI is the recovery path when administrator access is lost. An operator with filesystem access to the control-plane host can grant/remove DIDs:

ADMIN_DATABASE=/data/control.db npx tsx server/access.ts grant did:plc:...
ADMIN_DATABASE=/data/control.db npx tsx server/access.ts remove did:plc:...
ADMIN_DATABASE=/data/control.db npx tsx server/access.ts revoke did:plc:...

remove revokes access and all local sessions immediately; revoke retains membership but invalidates sessions. These commands write local-operator audit events. Membership is checked for every request. Sign out revokes the current session; “Revoke my sessions” invalidates every local session for that DID and removes stored OAuth tokens. This does not claim to revoke third-party sessions at the user's PDS. No administrators or credentials are shipped in the application.

Management contract

At sign-in, administration refreshes the account's verified handle and display name, preferring app.certified.actor.profile and falling back to app.bsky.actor.profile. Presentation is stored in the administration database and shown beside the DID in Administrators with the last recorded login time. Lookups are bounded to four seconds; unavailable metadata does not block sign-in or erase the last successful values. Accounts without stored profiles display their DID. Removing an administrator also removes their cached profile. Authorization and audit attribution always use the immutable DID, never a handle or display name.

The browser-facing API is /api/v1; all endpoints below require authorization.

Endpoint Contract
GET /administrators Paginated current administrator DIDs with cached presentation and last login.
POST /administrators {did, action} with grant or remove; actor audited, CSRF protected; cannot remove oneself.
GET /session Current DID, CSRF token, expiry.
POST /signout, /revoke-sessions Revoke the current or all local sessions.
POST /operations Validated command plus UUID Idempotency-Key (version 8 is reserved for server-derived IDs and returns HTTP 400 reserved_idempotency_key); returns durable operation and HTTP 202.
GET /operations, /operations/{id} Requested command, actor, state, observed result and bounded failure code.
POST /operations/{id}/retry, /cancel Retry failed/incomplete work or cancel work not yet applying; actor audited.
GET /sources, /source?pds=… Relay's desired, validation, connection, admission-quota, Relay-observed-account and durable-cursor state.
GET /policy Jetstream's applied collection-policy revision.
GET /jobs, /coverage Jetstream job state, bounded execution diagnostics, last progress and inventory-failure details, and source/policy-scoped current-state coverage; optional exact pds filter. Jobs are listed newest created first across pages, in the order Jetstream returns. GET /jobs also accepts an optional state filter (active, pending, running, incomplete, failed, canceled or complete); another value returns 400 invalid_input. A job without a recorded creation time omits createdAt.
GET /jobs/{id}/repositories Lazy, cursor-paginated unresolved repository details from Jetstream's frozen inventory, including recorded failure times.
GET /limits, /status, /audit Applied policies, bounded service health, durable actor-attributed history. /status includes collectiondir: available, unavailable or not_configured.
GET, POST /sources/discovery/settings Automatic PDS discovery settings: {maxAccountLimit}, a whole number of at least 1,000 (default 100,000). Changes are CSRF protected and audited as discovery_settings_changed.
GET /collection-directory/status Always HTTP 200: configured, available, bounded error code, active crawls and recent crawl results.
GET /collection-directory/crawls Newest-first crawl requests with actor, times, trigger (cause: manual or source_added), the enabling sourceOperation, submission, state and result; optional exact pds and crawl-row ids filters.
GET /collection-directory/bootstraps Newest-first automatic initial crawls with the enabling operation and actor, outcome, phase, follow-up request state, attempts and next retry time, and the crawl row once accepted; optional exact pds filter, which also matches http:// sources. Optional phase=open selects only waiting, retrying, needs_attention and accepted before the same after/limit cursor paging; any other filter value is rejected, and omitting it returns all phases.

Commands are discriminated by kind: source (pds, state), collections (expectedRevision, exact collections), job (pds, reason), job_action (id, action), account_quota (pds, expectedLimit, accountLimit), limit (scope, eventsPerSecond), and collection_crawl (scope: all or a PDS origin). Bodies are limited to 64 KiB. Lists use bounded pages and opaque after cursors; restart pagination to include newly added items that sort before the current cursor. Collection lists are limited to 1,000 exact NSIDs per request.

The transactional journal records requested before contacting either service, then applying, and finally applied, failed, canceled or incomplete. applied acknowledges configuration/job submission, never archive completeness. Partial source updates retain their observed service acknowledgment. On restart, applying operations return to requested; source updates reconcile desired state, collection revisions detect stale writes, and Jetstream persists request receipts for job submission and retry/cancel so lost responses cannot duplicate work. Unavailable services remain incomplete until an explicit retry. Source removal stops acquisition without deleting archives. Job progress remains owned by Jetstream.

Sources show the latest Jetstream job's progress beside Relay-observed accounts. Coverage describes current records, not complete event history. Unknown totals stay unknown; older jobs keep saved counts but cannot show repository details without a saved inventory. If Jetstream is unavailable, Relay source information stays visible. Account quotas limit Relay admission, not Jetstream backfill.

Job state records the outcome; diagnostics.execution shows whether work is queued, running, waiting, stopped or complete. Ready work keeps a job queued; retry delays do not make a stopped job active. Job rows show the last recorded successful progress and bounded inventory-listing failure stage, category, HTTP status when available, and time. Repository details load on request, keep the same snapshot across pages, and show safe failure information and recorded failure times, never raw response bodies. Job rows omit the last-progress and listing-failure lines when Jetstream has not recorded them, as for older jobs. Repository details show “Not recorded” for a failure without a recorded time. No time is inferred from job creation or retry activity. Restart the listing if its snapshot expires. UI labels use “repository list” for the saved PDS listing and “attempts per repository” for download retries. “Job runs” counts scheduler runs, not repository download attempts. Job rows show the run count only above one, and the unresolved count and per-repository attempt limit only while repositories remain unresolved. The page notice, not each row, states that diagnostics describe current state rather than historical coverage; API field names and error codes are unchanged.

Each job row shows “Created:” with the recorded creation time in the browser's locale and time zone, or “Not recorded” when Jetstream has none; this is when the job was created, not when it last made progress. The status links above the table (All, Active, Pending, Running, Incomplete, Failed, Canceled, Complete) reload the list at its first page, showing only jobs in that durable state; Active means pending or running. Jetstream applies the filter across all pages, and it combines with the PDS filter.

Viewing does not change jobs. Retry is an audited action that preserves completed work, resets eligible retries for incomplete jobs, and refreshes the inventory for failed jobs. The Backfill jobs table offers no Retry action for complete jobs.

The administration UI presents the authoritative aggregate for all enabled sources under the current policy, independent of page and exact-source filters. It shows nullable initial inventory, verified scanned, matching, successful no-match, unresolved and attributable-record counts as job-wide evidence—not per-collection progress. Null remains Unknown while zero is a measured value. Failure category, last progress timestamp, attempts, affected repository DID and explicit retry action are shown only when supplied; throttling and incomplete work do not imply a retry countdown or ETA. History and live freshness remain independently unknown; completed acquisition does not establish either. Acquisition diagnostics show recorded repository retry and PDS cooldown deadlines and the current wait reason when supplied. Retry-waiting evidence without either deadline explicitly reports unknown timing; no countdown or ETA is inferred. Stopped work still requires the explicit job retry action when reported.

Machine API for PDS discovery

When ADMIN_DISCOVERY_TOKEN_FILE is set, administration also serves the state and operations routes below under /api/v1/sources/discovery, which the optional PDS discovery service uses. These two routes require Authorization: Bearer <token>. They do not use OAuth sessions or CSRF. The token grants no access to any other /api/v1 route, and a browser session cannot use these two routes. The discovery settings route under the same prefix is part of the browser API above and is always mounted.

Endpoint Contract
GET /state {policyRevision, collections, sources: [{pds, state, accountLimit}], maxAccountLimit}, covering every Relay source in any state.
POST /operations Only a source command with state enabled, or an account_quota command that raises the limit. Requires a UUID Idempotency-Key that is not version 8 (HTTP 400 reserved_idempotency_key) and returns HTTP 202. Any other command returns HTTP 403. A source enable for a PDS that Relay reports as disabled or removed returns HTTP 409 source_disabled_by_operator. An account limit above the discovery maximum returns HTTP 403 account_limit_above_discovery_maximum.

Before applying a discovery operation, the worker checks again. An account limit above the current discovery maximum fails with account_limit_above_discovery_maximum. For a source enable, it checks Relay again. If an operator disabled or removed the source in the meantime, the operation fails with source_disabled_by_operator and nothing is changed. Machine operations use the normal journal and worker. They are recorded and audited under the actor service:pds-discovery and are shown on the Operations screen, where they can be retried or cancelled like any other operation.

Collection directory crawls

When the collection directory is configured, PDS sources offers Crawl collection directory for each enabled, validation-passed HTTPS source, and Collection directory offers Crawl all enabled sources after a confirmation. Without configuration, or while the directory is unreachable, the actions are disabled with an explanation; source management keeps working.

Each request is a collection_crawl journal operation. When it is applied, the service checks each source against Relay, sends https://<Relay hostname> to the collection directory, and records one crawl row per source with the actor and time, and an audit entry. A source that is disabled, unvalidated, unknown to Relay or plaintext fails the operation without contacting the directory. An unreachable directory leaves the operation incomplete for an explicit retry. When crawling all sources, each batch of 100 accepted sources is recorded as soon as the directory accepts it, so a later failed batch keeps the earlier records; retries and restart recovery skip sources already recorded for that operation, even if their crawls have finished, and report their count as alreadySubmitted. If Administration stops after the directory accepts a batch but before that batch is recorded, submission is at-least-once: a retry sends those sources again. The directory drops the duplicate only if the earlier crawl is still running; if it has ended, the retry starts another crawl.

applied means the directory accepted the request, not that the crawl finished. If a crawl of that source was already running, the request is still applied, no second crawl starts, and the page explains this. The service then polls the directory every five seconds while crawls are open, and the browser refreshes every five seconds while anything is running:

State Meaning
accepted The directory took the request; the crawl is running or not yet observed.
finished The repository listing ended. Repositories that could not be described are counted separately.
failed The listing stopped early; a bounded category and HTTP status are shown, never raw response text.
unknown The directory restarted, no longer reports the result, or is no longer configured, so the outcome cannot be known.

Load more keeps older requests visible. Refreshes also update loaded requests that are still open, so their final outcomes appear and polling stops when all crawls have ended. GET /api/v1/collection-directory/crawls accepts an optional ids filter: a comma-separated list of 1–100 UUID crawl-row IDs. It returns their current states, combines with pds, after and limit, and uses the same {items, next} cursor pagination. Invalid or empty lists are rejected with HTTP 400. Without ids, the endpoint's behavior is unchanged.

Crawl results are candidate DID/collection pairs for com.atproto.sync.listReposByCollection, not an authoritative inventory. A crawl does not admit a source to Relay and is not a Jetstream backfill. See the collection directory guide. The PDS discovery machine API cannot request crawls; it rejects collection_crawl with HTTP 403.

Automatic initial crawl

When a source operation with state enabled is applied, administration also asks the collection directory to crawl that source. This applies to sources added or re-enabled by an operator and to sources enabled by PDS discovery. It needs no extra configuration beyond the two collection directory settings above.

  • What triggers it. Only an applied enable that Relay reports as enabled and validated. A source operation that fails or is left incomplete, and any disable or remove, requests nothing. An enable that leaves the source unchanged does not request a crawl if one was already queued at that source revision; disabling and then re-enabling does request one.
  • How it is recorded. In the same transaction that marks the source operation applied, administration queues a follow-up collection_crawl operation for https://<Relay hostname>, owned by the same actor. The source operation's result gains collectionDirectory.bootstrap: queued, not_configured, not_https, conflict or unchanged. The crawl appears under Crawl requests with the trigger Source added. The follow-up ID is a version 8 UUID; both operation routes refuse client Idempotency-Key values of that version with HTTP 400 reserved_idempotency_key. If an operation nevertheless already holds the ID, the crawl is skipped as conflict, audited as collection_bootstrap_conflict, and the source still applies.
  • The source is added whatever happens to the crawl. The source operation stays applied. The crawl's progress is shown as Initial crawl in the source's detail panel. Crawls not yet accepted by the directory are listed under Initial crawls awaiting submission on the Collection directory page.
  • Retries. If the directory is unavailable or refuses the request, the follow-up operation is left incomplete and retried automatically after 30 seconds, doubling up to every 10 minutes, for 24 hours after the source was enabled. Retries are audited under system:collection-bootstrap. After 24 hours the source detail shows Retry initial crawl, and the operation can also be retried from the Operations screen. A follow-up that failed, for example because the source was disabled before it ran, is never retried automatically.
  • Not configured or plaintext. Without a collection directory, or for an http:// source, nothing is requested and the skip is recorded and shown. Configuring the directory later does not automatically crawl those sources.
  • Sources enabled before this feature are not crawled automatically. Use Crawl all enabled sources once.

The phase reported by GET /collection-directory/bootstraps:

Phase Meaning
waiting The crawl request is queued and has not yet been sent.
retrying The directory was unavailable or refused; an automatic retry is scheduled.
needs_attention Automatic retries stopped after 24 hours; retry manually.
not_requested The request failed or was canceled, for example source_not_enabled.
accepted, finished, failed, unknown The crawl row's state, as for manual crawls.
skipped_not_configured No collection directory was configured when the source was enabled.
skipped_not_https The source is plaintext; the directory only crawls HTTPS sources.
skipped_conflict Another operation already held the follow-up ID; nothing was requested.

Each crawl is limited by the collection directory's per-PDS rate, --crawl-qps or COLLECTIONS_CRAWL_QPS (default 100 requests per second). The directory does not limit how many crawls run at once, so enabling many sources at once starts that many crawls.

Rate policy

Global and per-PDS values are integer events/second, inclusive range 1–1,000,000, with a one-second token-bucket burst. Both constraints must admit an event before it enters the scheduler. They cover every source frame, including repository, info, label and error frames. Waiting pauses further socket reads and is cancelable. Policy changes wake waiting connections; persistence precedes the applied acknowledgment. Buckets refill on restart; configured values persist. Existing host limits and account-admission quotas remain independently enforced.

The UI reports waiting connections, not an invented total upstream backlog. Reconnect resumes the last durable source cursor. If upstream replay has expired, a Jetstream quota-recovery job can acquire current records but cannot reconstruct unknown historical events. Inspect the source's recovery flag and actual job state.

Verification

npm run check
npm test
npm run test:components
npm run build
npx playwright install chromium
npm run test:browser

npm test includes the real Go private management endpoints over loopback using disposable databases. These fixtures simulate source validation and unavailable PDS acquisition; Relay and Jetstream's own suites cover their actual ingestion and backfill engines. Browser tests use the real control-plane HTTP API with explicit test-only OAuth double. T13 and T14 compile and launch the real loopback Relay and Jetstream private-control handlers; no browser test substitutes a service-owner API. The OAuth double only provides a deterministic local callback and is not a live external-PDS OAuth qualification. Production server/main.ts cannot select the double or fixture. T13 proves DID authorization, CSRF, session revocation and an administration journal entry that survives reopen; T14 proves accessible desktop/mobile browser workflows through those local owners. Run them with ./tests/acceptance/run T13 and ./tests/acceptance/run T14. The root verification scripts remain required for Go service changes.

Brand assets

The UI uses the Hypercerts theme, logo and fonts. See the brand source notes for asset provenance and licensing, and DESIGN.md for the operator UI conventions. The built application serves its fonts locally.

Proxy and storage boundaries

Direct connections ignore forwarded client-IP headers. Behind a reverse proxy, set ADMIN_TRUST_PROXY to a comma-separated list of its exact addresses or CIDRs; the proxy must overwrite forwarded headers. Do not trust arbitrary internet clients. With HC_RAILWAY_STARTUP=1, the application trusts loopback, link-local and private network peers and uses Railway's overwritten X-Real-IP header. That mode assumes all private-environment peers are trusted; use explicit CIDRs to narrow the peer set where available. Sign-in limits are per observed client (10 attempts/minute), with a bounded 10,000-client cache that evicts the oldest entry at capacity.

Use a dedicated directory owned by the runtime UID for ADMIN_DATABASE. New folders are mode 0700; the database and existing WAL/SHM files are secured to 0600 before opening. Existing parent directories are never chmod-ed because a volume or directory may be shared. Restrict write access to the parent through deployment ownership and permissions.

Operation pages use creation time and UUID as a stable tie-breaker. Their next cursor is opaque; clients should pass it unchanged as after. Worker claims, cancellation and retries compare the current journal state in one transaction.