Connected apps with 3rd-party data hosts jsr.io/@civility
14 kB · 338 lines
Markdown
at main

Admin Panel #

The operator interface: inspect usage, manage users, revoke grants, and adjust per-user limits without touching the database.

All routes live under /admin/, and aren't mounted at all unless you configure at least one access mode — admin users (adminEmails) for the browser path, a static token (adminToken) for scripts. Either grants full access, and they combine freely.


1. Enabling the panel #

List the operator accounts by email. An account whose verified email is listed reaches /admin/ with its ordinary dashboard sign-in — no separate credential, and the dashboard home links to the panel. Matching is case-insensitive; signed-in users who aren't listed get a 404, so the panel isn't advertised to them.

CIVILITY_ADMIN_EMAILS=you@example.org civ api start

Comma-separate multiple operators. Designation is config-only, so nothing a user can do in-band (signup, profile edits, API calls) grants admin. Enable MFA on operator accounts — the panel controls the email transport, which mediates password resets for every user. /admin/ reminds you until a second factor is enrolled.

Static token (for scripts and reverse proxies) #

Set the CIVILITY_ADMIN_TOKEN environment variable before starting the server:

CIVILITY_ADMIN_TOKEN=mysecrettoken civ api start

The token is a machine credential, sent as Authorization: Bearer <token>, and the only way to authenticate the JSON API non-interactively. It is not a browser login — HTTP Basic is not accepted. Use admin users for people, the token for CI, cron, and reverse proxies.

The server prints the admin URL on startup:

Admin panel: http://localhost:8080/admin/
  Operators: you@example.org (dashboard sign-in)
  Scripts: Authorization: Bearer <your admin token>

Via createManager #

import { createManager } from '@civility/hono'

const manager = await createManager({
  options: {
    backend: { dialect: 'sqlite', dbPath: './.data/civility.db' },
    adminEmails: ['you@example.org'],
    adminToken: Deno.env.get('CIVILITY_ADMIN_TOKEN'),
  },
})
Deno.serve(manager.buildApp().fetch)

When both options are omitted, all /admin/* routes return 404.


2. Generating a token #

openssl rand -hex 32

Store it in a secret manager or environment variable, not in source control.


3. Accessing the panel #

Browser #

Sign in to the dashboard as an operator account and follow the Admin panel link (or go to http://your-server/admin/). This is the only browser path — a deployment with CIVILITY_ADMIN_TOKEN alone has no panel login, and signed-out requests get a plain 401 with no credential dialog.

Behind a reverse proxy you can restrict the panel to an internal network and inject the bearer token for machine callers:

# nginx — internal network only, token injected for scripted calls
location /admin/ {
    allow 10.0.0.0/8;
    deny all;
    proxy_set_header Authorization "Bearer $http_x_admin_token";
    proxy_pass http://localhost:8080;
}

API / scripting #

All HTML pages also accept Authorization: Bearer <token> and return JSON when the request carries Content-Type: application/json:

curl -H "Authorization: Bearer mysecrettoken" \
     http://localhost:8080/admin/users

4. What's available #

Dashboard — /admin/ #

Summary stats: total users, total registered apps, aggregate change-data stored, aggregate blob storage used.

User list — /admin/users #

Table of all registered users with their change-data usage, blob usage, active grant count, and registration date. Each row links to the per-user detail page.

Server limits — /admin/limits #

Set server-wide storage/upload quotas, app and share caps, retention/GC grace, bundle allowances, and rate limits. Saved overrides take precedence over startup configuration without a restart; blank fields restore individual startup defaults. The page shows effective values and sources, supports a full reset, warns before shortening retention, and audits changes. Tier and per-user limits still take precedence. See Server-wide limits.

User detail — /admin/users/:id #

  • Storage — usage bars for change data and blob storage, each measured against the effective limit for that user (server default or per-user override)
  • Active grants — table of all active permission grants issued to third-party apps, with a revoke button per row
  • Apps — list of apps the user has registered
  • Limit overrides — form to set a custom DB or blob quota for the user, and an optional tier label (e.g. pro, unlimited)

App list — /admin/apps #

All apps across all users, with owner ID and creation date. Each row has a delete button. Deleting an app removes all its sync data and frees the associated storage quota from its owner's counter.

Email — /admin/email #

Configure the email transport used for password-reset, verification, and login-code messages — without restarting. Pick a provider (SMTP, Resend, or disabled), set the from-address and credentials, and save; changes take effect on the next email. Credentials are encrypted at rest (sealed with CIVILITY_AUTH_SECRET) and never shown back in plaintext. A "send test email" box confirms delivery. Save settings before testing: the test uses stored values, not unsaved form edits. It shows the saved provider and sender and stays disabled until a complete configuration is saved. Resend requires an explicit From address on a verified domain and an API key; SMTP requires a host (with an optional sender defaulting to noreply@<host>). Incomplete configurations are rejected on save with specific guidance. Available on the built-in SQLite/PostgreSQL backend.

Until email is configured here, new accounts are auto-verified and reset/verification links are logged to the server console — so a fresh deployment is usable before you set this up. Startup-injected email adapters are used only when no saved config exists; explicitly selecting disabled overrides them. SMTP password whitespace is preserved. Advanced Resend options exposes a trusted API base URL, per-request timeout (1–120000 ms), and transient retry count (0–5). Blank values restore transport defaults; zero retries disables retrying. Custom endpoints receive the API key, so HTTPS is required except for loopback development. URL credentials/query strings/fragments are rejected. Save these options before testing, just like the standard fields.

Billing — /admin/billing #

Configure Stripe API/webhook credentials and tier/add-on price mappings without restarting. Blank secrets keep their stored values; blank price fields remove mappings. Stored mappings remain visible even when absent from the startup catalog. Explicitly disabling billing overrides startup-injected providers. The Billing tiers section creates, edits, and deletes plan IDs, labels, paid status, quota/retention presets and per-user rate limits. Saved catalogs override startup tiers and take effect without a restart. An unpaid free tier is required for non-empty catalogs. Acknowledgement is required for changes; removing tiers is blocked while users are assigned to them or their price maps remain configured. A reset restores startup tiers. Changes are audited. Add-on definitions and Stripe products/prices/webhook registration still live outside this panel (the latter can use civ api billing init). See Billing tiers and Billing.

Maintenance — /admin/maintenance #

Control change-history/housekeeping pruning, blob GC, storage snapshots, scheduled downgrades, and expired/stalled account archives. Each job has a persisted automatic-run switch and UTC cron schedule with startup fallback/reset. Pause-all preserves individual policies; manual runs remain available while paused. Runs use current limits and tiers, require acknowledgement, and record status, timestamps and counters. Settings and runs are audited.

Automatic dispatch requires Deno.cron (e.g. --unstable-cron); manual runs do not. Capability gaps are displayed instead of exposing dead run buttons. Scheduling and overlap protection are process-local: operate one scheduler per database. See Maintenance.

Services — /admin/services #

Manage the global outbound proxy switch, provider bundle keys, and per-service execution modes. Each service can use startup mode defaults, be disabled, or allow only selected implementation-supported modes. Disabled services keep credentials and grants; server calls are blocked immediately. Mode changes are persisted and audited. See Services.

Invites — /admin/invites #

Signup gating for a closed beta. A toggle controls whether signup requires an invite token — off by default. Mint invites with an optional note and expiry; the raw token is shown exactly once, with a ready-to-share /signup?invite=<token> link, so copy it before leaving the page.

The table lists every invite with its status (active / used / revoked / expired) and which account redeemed it. Deleting an account releases the invite it redeemed — revoke it too if the removal was an expulsion. The lifecycle is recorded in the audit log.

Available only when signup runs on the built-in auth handlers (or custom ones that implement invite support); otherwise the page reports "not available".


5. JSON API reference #

All endpoints accept Authorization: Bearer <token>. Responses follow the standard Civility envelope ({ status, data, message }).

Method Path Description
DELETE /admin/users/:id/grants/:grantId Revoke a specific grant
PATCH /admin/users/:id/limits Set per-user limit overrides
DELETE /admin/apps/:id Delete an app and free its storage quota
POST /admin/invites Mint an invite ({ note?, expiresInDays? })
DELETE /admin/invites/:token Revoke an invite (raw token or invite id)
POST /admin/invites/config Toggle the invite gate ({ required })

Send Content-Type: application/json on every call, including bodyless DELETEs — the CSRF middleware rejects requests without a content type as browser form posts.

Invite-endpoint validation is strict: expiresInDays must be a positive number and required must be a JSON boolean ("true" is rejected rather than silently coercing to off). Prefer revoking by invite id — a raw token in the request path lands in access logs.

PATCH /admin/users/:id/limits #

{
  "tier": "pro",
  "limits": {
    "maxDbBytesPerUser": 52428800,
    "maxBlobBytesPerUser": 5368709120
  }
}

Both tier and limits are optional. Pass only the dimensions you want to override; omitted fields keep their server defaults. Set limits to {} to clear all overrides.


6. PostgreSQL setup #

The PostgreSQL adapter is planned but is not currently a published @civility/hono/postgres entrypoint. For the currently supported SQLite deployment, use the SQLite adapter example from the package README and construct the admin handlers from those instances:

import { Hono } from 'hono'
import {
  createSqlAdminHandlers,
  createSqlAuth,
  SqlDatabase,
} from '@civility/hono'
import { createDb, runMigrations } from '@civility/hono/db/sqlite'
import { createAdminRouter } from '@civility/hono/admin'
import { resolveLimits } from '@civility/hono'

const db = createDb('./.data/civility.db')
await runMigrations(db)

const secret = Deno.env.get('CIVILITY_AUTH_SECRET')!
const auth = await createSqlAuth({ db, secret })
const pgDb = new SqlDatabase(db)

const adminToken = Deno.env.get('CIVILITY_ADMIN_TOKEN')
const app = new Hono()

if (adminToken) {
  // Pass `secret` so the /admin/email page can seal stored credentials at
  // rest. Without it, email config still saves but credentials are sealed
  // with an empty key — always pass it so operators can safely enter
  // credentials through the UI.
  const adminHandlers = createSqlAdminHandlers(auth, pgDb, { secret })
  app.route(
    '/admin',
    createAdminRouter({
      adminToken,
      handlers: adminHandlers,
      limits: resolveLimits(),
    }),
  )
}

7. Security notes #

  • Keep the token secret. It grants full read/write access to all user data — usage, limits, and grant revocation.
  • Protect operator accounts. An admin user's password is a server-level credential — enable MFA on every listed account. Removing an email from CIVILITY_ADMIN_EMAILS revokes access on the next request, no session cleanup needed. Only the dashboard session cookie opens the panel; an operator's API keys and app tokens deliberately don't.
  • Restrict network access. On a public-facing server, put /admin/* behind a firewall rule or reverse-proxy allow block.
  • Rotate on compromise. Restarting with a new adminToken invalidates the old one immediately; no database change needed.
  • No rate limiting on admin routes. Keep the panel off the public internet rather than relying on rate limits.