Skip to content

Latest commit

 

History

History
701 lines (495 loc) · 66.7 KB

setup.md

File metadata and controls

701 lines (495 loc) · 66.7 KB

Activity.next Setup Guide

This guide provides an overview of how to set up Activity.next for development or production.

Just want to try it locally? See the Quickstart for the fastest minimal setup (SQLite and the three core settings: host, secret phrase, and a database). This guide covers the full set of configuration options.

Prerequisites

  • Node.js 26 (the repo pins engines.node to 26.x)
  • Yarn 4 package manager via Corepack (npm install -g corepack && corepack enable; the exact Yarn version is pinned by the packageManager field in package.json)
  • Git (to clone the repository)
  • A domain name (required for federation with other servers)

Database Setup

Activity.next supports multiple SQL database backends. Choose the one that best suits your needs:

General Configuration

Activity.next is configured through environment variables prefixed with ACTIVITIES_. Top-level options use ACTIVITIES_<KEY> (e.g., ACTIVITIES_HOST); nested options use ACTIVITIES_<SECTION>_<KEY> (e.g., ACTIVITIES_DATABASE_PG_HOST).

For a complete reference of all configuration options, see the Environment Variables Guide.

Required Configuration

At minimum, you need to configure these settings:

Domain Name

Set your instance's domain name (without protocol or trailing slash):

ACTIVITIES_HOST=your-domain.tld

Authentication Secret

Set a secret phrase for signing cookies and tokens:

# Generate with: openssl rand -base64 32
ACTIVITIES_SECRET_PHASE=your-random-secret-for-sessions

Note: The production runtime rejects an ACTIVITIES_SECRET_PHASE shorter than 32 characters.

Access Control

Restrict who can sign up to your instance by specifying allowed email addresses:

ACTIVITIES_ALLOW_EMAILS='["your_email@example.com"]'

Tip: If allowEmails is set, only users with matching email addresses can register. This is recommended for personal or small-group instances.

Serving more than one domain (Optional)

One server can serve profiles on several domains (social.example, run.example, …). Each domain needs its own route to this server before the app can use it:

  1. DNS: point the domain (an A/AAAA record or a CNAME) at the same public address as ACTIVITIES_HOST.
  2. TLS: issue a certificate for the domain on whatever terminates HTTPS (your proxy, load balancer or hosting platform).
  3. Proxy: route the domain to this server and keep the original Host header (or set X-Forwarded-Host to it). A proxy that rewrites the host to the primary domain makes every request look like it arrived on ACTIVITIES_HOST. Strip any client-supplied X-Activity-Next-Host header at the reverse proxy unless the proxy itself sets it, and overwrite or strip client-supplied X-Forwarded-Host — the application reads X-Activity-Next-Host and X-Forwarded-Host ahead of Host, so forwarding an untrusted value lets callers spoof the request host (including routing to an embedded Bluesky PDS hostname).
  4. Add it in the app: open Admin › Served domains › Add domain and enter the domain. The server asks https://<domain>/.well-known/activities-domain-check for a proof only it can sign, and shows which of DNS, TLS and the Host header still needs work. The domain is saved as Off; Turn on runs the check again and only turns it on when it passes.
  5. Sign-ups: on the domain's page, open sign-ups (with an optional list of allowed email addresses) and choose whether people who already have an account can add a profile there. A new domain starts with sign-ups closed.
  6. Identity and policies (optional): on the same page, give the domain its own name, description and contact email, and its own terms of service and privacy policy (Markdown). Each field says Same as server until you set it, and then falls back to Admin › Server settings. They apply only while the domain is on (an ACTIVITIES_TRUSTED_HOSTS domain: always); other server instances pick a change up within 15 seconds. The primary domain always uses the server's own, set on Admin › Server settings.

Domains can still be pinned in the environment with ACTIVITIES_TRUSTED_HOSTS; those show in Admin › Served domains as always on, and only their sign-up settings, identity and policies can be changed there. Existing users can always add a profile on them, except someone who joined through another domain's sign-ups: they need that domain's own sign-ups open to their address, or a profile there already (the same holds for the primary). A wildcard entry such as *.vercel.app stays environment-only: it lets forwarded preview hosts sign in, but never serves profiles or sign-ups.

Authentication Methods

Activity.next uses better-auth for authentication and supports local email/password accounts, passkeys, and two-factor authentication.

Media Storage (Optional)

By default, media files are not stored (uploads are disabled). To enable media uploads, configure a storage backend:

Local Filesystem

ACTIVITIES_MEDIA_STORAGE_TYPE=fs
ACTIVITIES_MEDIA_STORAGE_PATH=./uploads

S3 / S3-Compatible Object Storage

Account archive exports and imports use the same bucket and credentials as media. They need these permissions in addition to the media policy: s3:PutObject, s3:GetObject, s3:DeleteObject and s3:AbortMultipartUpload (to clean up an unfinished upload) on both archives/* and imports/*; s3:ListBucket on the bucket, limited to both prefixes with a condition; and optionally s3:ListMultipartUploadParts on both prefixes. Without the last permission an export still completes, with a warning in the logs, but cannot double-check its part ETags. Add a bucket lifecycle rule that aborts incomplete multipart uploads after a day or two.

This is an extra IAM identity policy for the app's S3 credentials, added alongside the existing media policy (not a replacement for it, and not a bucket policy). If S3 answers 403 instead of 404 for missing keys, the s3:prefix condition on s3:ListBucket may be left off.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:AbortMultipartUpload",
        "s3:ListMultipartUploadParts"
      ],
      "Resource": [
        "arn:aws:s3:::my-bucket/archives/*",
        "arn:aws:s3:::my-bucket/imports/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::my-bucket",
      "Condition": {
        "StringLike": { "s3:prefix": ["archives/*", "imports/*"] }
      }
    }
  ]
}
ACTIVITIES_MEDIA_STORAGE_TYPE=s3          # or 'object' for S3-compatible
ACTIVITIES_MEDIA_STORAGE_BUCKET=my-bucket
ACTIVITIES_MEDIA_STORAGE_REGION=us-east-1
# Optional: public CDN/custom domain used to serve media files.
# Account archives live in the same bucket under archives/ (exports) and
# imports/ (staged uploads), and embedded Bluesky PDS blobs live under
# pds-blobs/. The hostname must not serve any of these prefixes (or the bucket
# root) publicly. Exports are protected by a secret key segment plus the
# owner-checked download endpoint, not by the bucket; PDS blobs are served only
# through com.atproto.sync.getBlob with repo-status checks and sandbox headers.
# With this variable set, exports are streamed through the app instead of
# redirecting to a signed bucket URL. A streamed download lasts as long as the
# transfer, so on a host with a short request duration limit (serverless) a
# large export may be cut off; a client can resume it with a `Range: bytes=n-`
# request.
ACTIVITIES_MEDIA_STORAGE_HOSTNAME=media.example.com
# Optional: S3-compatible API endpoint for uploads/storage operations
ACTIVITIES_MEDIA_STORAGE_ENDPOINT=https://s3.example.com

Optional storage limits:

ACTIVITIES_MEDIA_STORAGE_MAX_FILE_SIZE=209715200       # 200 MiB in bytes
ACTIVITIES_MEDIA_STORAGE_QUOTA_PER_ACCOUNT=1073741824  # 1 GiB in bytes

Account archive imports have a separate upload-size limit of 10 GiB by default. Set ACTIVITIES_ACCOUNT_IMPORT_MAX_FILE_SIZE to a byte count to change it; see the Environment Variables Guide.

Some uploads stream through the app as multipart/form-data: every media upload on local (fs) media storage; the sync media endpoints (POST /api/v1/media and /api/v2/media, which Mastodon clients use) and custom emojis on any media backend; and fitness-file uploads and fitness-activity imports on any fitness storage backend. Strava archive imports on S3/object fitness storage go straight to the bucket through a presigned URL and fall back to multipart only if that fails. The Next.js proxy (proxy.ts) is skipped for multipart /api requests, so its 10 MB request-body buffer does not apply. The per-file limit is ACTIVITIES_MEDIA_STORAGE_MAX_FILE_SIZE (or, when that is unset, the admin media.maxFileSize setting) for media and ACTIVITIES_FITNESS_STORAGE_MAX_FILE_SIZE for fitness files, on top of the per-account quota. A reverse proxy in front of the app has its own request-body limit (nginx's client_max_body_size defaults to 1 MB), which must be raised to match.

Email Configuration (Optional)

Email is optional. Leave the email variables unset when the instance should not send account verification or notification messages. When email is configured, notification delivery is best effort: errors are logged, with no durable retries or delivery-status tracking.

The supported providers are SMTP, Resend, and AWS SES. If an explicit provider value is unknown, including the removed lambda value, configuration fails instead of silently disabling email. Before upgrading an instance that used Lambda, migrate its configuration to one of the retained providers and remove the Lambda-specific variables. No replacement provider is selected automatically. See the Environment Variables Guide for JSON precedence, malformed-JSON fallback behavior, and the requirement that individual email variables include ACTIVITIES_EMAIL_TYPE.

SMTP

ACTIVITIES_EMAIL_TYPE=smtp
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_SMTP_HOST=smtp.example.com
ACTIVITIES_EMAIL_SMTP_PORT=587
ACTIVITIES_EMAIL_SMTP_USER=your-username
ACTIVITIES_EMAIL_SMTP_PASSWORD=your-password
ACTIVITIES_EMAIL_SMTP_SECURE=false

Resend

ACTIVITIES_EMAIL_TYPE=resend
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_RESEND_TOKEN=re_xxxxxxxxxxxx

AWS SES

ACTIVITIES_EMAIL_TYPE=ses
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_SES_REGION=us-east-1

Queue Configuration (Optional)

Background jobs (sending ActivityPub activities, processing uploads) use a queue. Without a queue configured, jobs run synchronously.

Wahoo webhook synchronization and date-range history import require a durable queue (database, QStash, or Cloud Tasks). The default synchronous mode cannot acknowledge a webhook before its FIT download and activity processing finish, or schedule delayed retries, so the Wahoo settings page disables automatic/history import in that mode. With ACTIVITIES_QUEUE_TYPE=database, run the database queue worker described in maintenance.md if the application process does not run the queue runner.

Note: Client libraries for queue providers (@upstash/qstash and @google-cloud/tasks) are optional dependencies packaged as Yarn workspaces (@activities/qstash and @activities/cloudtasks). They are dynamically imported when the respective queue is enabled.

Upstash QStash

ACTIVITIES_QUEUE_TYPE=qstash
ACTIVITIES_QUEUE_URL=https://your-domain.tld/api/v1/queue/qstash
ACTIVITIES_QUEUE_TOKEN=your-qstash-token
ACTIVITIES_QUEUE_CURRENT_SIGNING_KEY=your-signing-key
ACTIVITIES_QUEUE_NEXT_SIGNING_KEY=your-next-signing-key

Google Cloud Tasks

ACTIVITIES_QUEUE_TYPE=cloudtasks
ACTIVITIES_QUEUE_NAME=activities-queue
ACTIVITIES_QUEUE_URL=https://your-domain.tld/api/v1/queue/cloudtasks
ACTIVITIES_QUEUE_CLOUDTASKS_LOCATION=europe-west1
ACTIVITIES_QUEUE_CLOUDTASKS_PROJECT_ID=your-gcp-project-id
# Optional authentication:
ACTIVITIES_QUEUE_CLOUDTASKS_SERVICE_ACCOUNT=service-account@project.iam.gserviceaccount.com
ACTIVITIES_QUEUE_CLOUDTASKS_AUDIENCE=https://your-domain.tld
ACTIVITIES_QUEUE_CLOUDTASKS_SECRET=your-shared-webhook-secret

Push Notifications (Optional)

Web push notifications require a VAPID key pair:

ACTIVITIES_PUSH_VAPID_PUBLIC_KEY=your-public-key
ACTIVITIES_PUSH_VAPID_PRIVATE_KEY=your-private-key
ACTIVITIES_PUSH_VAPID_EMAIL=mailto:admin@your-domain.tld

Starting the Application

Development Environment

To run the service locally:

yarn dev

The app will be available at http://localhost:3000.

To communicate with other servers in the Fediverse while running locally, you'll need a tunnel service to expose your local server to the internet:

  1. Set up a tunnel using Cloudflare Tunnel or ngrok
  2. Point the tunnel to localhost:3000
  3. Use your tunnel's domain as the host in your configuration

First-Time Setup

After starting the application:

  1. Navigate to https://your-domain.tld/auth/signup (if you set ACTIVITIES_ALLOW_EMAILS, your email must be in it; any email works if you left it unset)
  2. Create your account with email and password
  3. Log in and start interacting with the Fediverse

Deployment Options

Vercel Deployment

To deploy on Vercel:

  1. Fork this repository
  2. Connect it to your Vercel account
  3. Add the required environment variables (see Environment Variables Guide)

Note: Vercel deployments require an external PostgreSQL database and S3-compatible storage since Vercel has no persistent filesystem.

Docker Deployment

Activity.next provides official minimal Docker images at ghcr.io/llun/activities.next:main (the image is published with the main tag; there is no latest tag). The official image includes only the core application and SQLite dependencies to keep the image slim.

Basic Docker run command (uses SQLite by default):

docker run -p 3000:3000 \
  -e ACTIVITIES_HOST=your.domain.tld \
  -e ACTIVITIES_SECRET_PHASE=change-me-to-a-random-secret-at-least-32-chars \
  -e ACTIVITIES_DATABASE_SQLITE_FILENAME=/opt/activities.next/data/data.sqlite \
  -e ACTIVITIES_MEDIA_STORAGE_TYPE=fs \
  -e ACTIVITIES_MEDIA_STORAGE_PATH=/opt/activities.next/data/uploads \
  -v /path/to/local/storage:/opt/activities.next/data \
  ghcr.io/llun/activities.next:main

Important: Mount persistent data under /opt/activities.next/data as above — do not bind-mount /opt/activities.next itself. That directory contains the application (the standalone server.js, static assets, etc.), so a host-path mount would shadow it and the container cannot start. See the SQLite Docker guide for preparing the mounted database file.

Custom Docker Builds with Optional Workspaces

Docker image builds, including the migration step, do not need a production ACTIVITIES_SECRET_PHASE. Set a real, stable secret of at least 32 characters when running the image; the production runtime enforces that minimum.

Optional dependencies (such as PostgreSQL, Cloud Tasks, QStash, and optional email providers) are isolated in Yarn workspaces under packages/:

  • @activities/pg — PostgreSQL driver (pg)
  • @activities/cloudtasks — Google Cloud Tasks client (@google-cloud/tasks)
  • @activities/qstash — Upstash QStash client (@upstash/qstash)
  • @activities/nodemailer — SMTP transport (nodemailer, included by default in Docker builds)
  • @activities/resend — Resend client (resend)
  • @activities/ses — AWS SES client (@aws-sdk/client-ses)

The Dockerfile includes @activities/nodemailer by default (ARG WORKSPACES="activities.next @activities/nodemailer"). Email delivery is disabled only when no ACTIVITIES_EMAIL_* provider is configured. If a provider is configured but its workspace is missing from the build (for example resend or ses on the default image), every send fails with a logged error instead of silently succeeding, so password reset, registration confirmation and email change report the failure and roll back; add the matching workspace to WORKSPACES.

Docker installs the selected workspaces from the root manifest, lockfile, Yarn configuration, every workspace manifest, and the Yarn patches in patches/ before copying application source. Source-only edits can therefore reuse the dependency layer; changes to those dependency files or WORKSPACES invalidate it. The install stays immutable and includes development dependencies needed by the build. When adding a workspace, add its manifest to the Dockerfile's COPY list at the same path under packages/. Dependency patches (yarn patch) live in patches/, not .yarn/patches/ (Docker builds ignore .yarn/): commit one with YARN_PATCH_FOLDER=./patches yarn patch-commit -s <folder>, check that the resolution it writes to package.json matches only the range you meant, and add a test that fails without the patch (see test/zodPatch.test.ts, which guards the zod 3 copy @atproto/* uses).

Docker builds require BuildKit and mount .next/cache during compilation to preserve Turbopack's compiler cache on a persistent builder. The cache is isolated by target platform, UID, GID, and WORKSPACES, with concurrent access locked, and is not copied into the runtime image. Ordinary GitHub Actions layer-cache export does not export cache-mount contents, so a fresh builder starts without this compiler cache; the application's CI build job caches .next/cache separately. Cache retention depends on the builder and its garbage collection.

To customize optional workspaces when building a Docker container, pass the WORKSPACES build argument:

# Example: Build with PostgreSQL, QStash, and default Nodemailer support
docker build --build-arg WORKSPACES="activities.next @activities/nodemailer @activities/pg @activities/qstash" -t activities.next:custom .

# Example: Build with all optional workspaces
docker build --build-arg WORKSPACES="activities.next @activities/nodemailer @activities/resend @activities/ses @activities/pg @activities/cloudtasks @activities/qstash" -t activities.next:full .

To verify built Docker images locally:

node scripts/run.cjs scripts/maintenance/verifyDockerImages.ts

Pass --only <minimal|full> to verify just one of the two images; CI runs the verifier as two jobs (Docker Images Smoke Test (minimal) and Docker Images Smoke Test (full)), one per image.

For database-specific Docker deployment instructions:

Embedded Bluesky PDS

Activity.next can host Bluesky accounts on a PDS embedded in the app, with one PDS hostname per served domain. It is off by default and preview-quality: accounts are always created fresh here, and moving an existing Bluesky account in is not supported (moving one out is).

Enabling it

Set ACTIVITIES_BLUESKY_PDS to a JSON object keyed by served domain:

ACTIVITIES_BLUESKY_PDS='{
  "social.example": {
    "enabled": true,
    "hostname": "pds.social.example",
    "allowEmails": ["alex@social.example"],
    "allowActors": ["alex"],
    "relays": ["https://bsky.network"]
  }
}'
  • enabled turns the domain's PDS on (default false).
  • hostname is the PDS's own hostname; it must not collide with a served domain or another PDS hostname, and yields did:web:<hostname>.
  • allowEmails and allowActors decide who may create an account when the domain has no saved setting of its own; empty lists allow nobody. See Who can host below.
  • relays is an optional list of HTTPS relay origins to ask for a crawl at start-up (default https://bsky.network; [] disables crawl requests).
  • clientSignIn (default false) lets members sign in to Bluesky apps with app passwords while the domain has no saved setting of its own. See Signing in from Bluesky apps below.

Unset or blank turns the PDS off; malformed JSON or an invalid entry turns it off and logs a warning, and a hostname used twice or equal to a served domain drops only that domain. See Environment Variables for the full schema.

Who can host

The environment's allowEmails and allowActors are the fallback: they decide only while the domain has no saved setting. An admin can set it per domain in Admin › Served domains › Bluesky hosting, which shows when that domain has an enabled PDS entry:

  • Nobody — no one may host an account on the domain.
  • Listed accounts — only the email addresses and username@domain profiles entered there.
  • Everyone on this domain — any profile on the domain whose account is approved and confirmed. Suspended, unconfirmed, unapproved, disabled and deleting accounts are still refused.

The setting only decides who. An existing hosted account it no longer allows keeps its repo and posts and can still be turned off or deleted, but can't be turned back on or have its handle or recovery key changed. The PDS hostname, relays and whether the domain's PDS is on stay in ACTIVITIES_BLUESKY_PDS. Clearing the setting returns the domain to the environment's lists. The bare-domain handle stays admin-only, and <name>.<PDS hostname> handles need the wildcard DNS record and certificate below.

Signing in from Bluesky apps

A member with an active hosted account can sign in to the official Bluesky app (and other apps that sign in with app passwords) once the domain's Sign in from Bluesky apps switch is on. It is off by default; an admin sets it per domain in Admin › Served domains › Bluesky hosting, and while the domain has no saved setting clientSignIn decides. The switch is read on every request, so turning it off, or turning the domain off in Admin, stops new sign-ins and every app call at once (the methods answer 501); an Admin save that turns the switch off also ends every app session on the domain (app passwords stay, and members can still revoke them in Settings). Turning the account off, suspending or deleting it ends its app sessions too.

Turn the switch on only where the app sees each client's address: behind the PDS gateway (its X-Activity-Next-Client-IP is used), or behind a proxy you trust with ACTIVITIES_TRUST_PROXY_IP_HEADERS=true and ACTIVITIES_TRUST_PROXY_IP_HEADER pinned to the header it overwrites: sign-in, and the upload tokens the video service calls back with, are limited per client IP, and without a trusted address every client shares one bucket per domain (a one-time warning says so), which one caller can fill for everyone.

The server needs ACTIVITIES_BLUESKY_PDS_SESSION_KEYS, the HMAC keys that sign app session tokens (see Environment Variables). Generate a secret with openssl rand -base64 32, keep it in your secret store, and put a new key first when rotating. Without it app sign-in is refused.

The member then:

  1. Opens Settings › Other networks, and under the hosted account creates an app password: a name, Allow direct messages (off by default), and their current site password (a profile with only a passkey signs out and back in first: a sign-in from the last 10 minutes confirms it instead).
  2. In the Bluesky app taps Sign in, chooses Custom under Hosting provider and pastes https://<PDS hostname>, then enters @<handle> and the app password.

The app password is shown once. Revoking it signs out every app it signed in. The site password is never accepted by the PDS, and an app password cannot list, create or revoke app passwords.

Signed in, the app can browse: timelines, profiles, notifications, search, settings and, for an app password with Allow direct messages, chats. The PDS forwards those calls to the services configured below, and a few moderation and feed-feedback calls to the labeler or feed generator the app names (see Embedded Bluesky PDS). The app can also post, reply, quote, like, repost, follow, block, manage lists and starter packs, edit the profile and upload images and video; those records go into the hosted repo and out on the firehose, but they do not show in activities.next itself yet. Account settings (email, handle, password, deleting or moving the account) stay in Settings › Other networks on the website.

Limits per account (media storage and the 24-hour clean-up apply to the website's own uploads too):

  • Writes cost points (a create 3, an update 2, a delete 1): 5,000 points an hour and 35,000 a day. Uploads: 100 an hour and 500 a day. Record writes also share the 3,000 calls per 5 minutes the app's other calls use. Over a limit the app gets 429 with Retry-After.
  • Addresses of labelers and feed generators the app names: 60 lookups per 5 minutes (an address is remembered for 10 minutes); past that the app gets 429.
  • One upload is at most 50 MiB; one request body of records at most 2 MiB. Uploads running at once may declare 200 MiB together (one without a Content-Length counts as 50 MiB); past that the app gets 429.
  • Media storage: 10 GiB of blobs in all, of which at most 1 GiB may be uploads no post uses yet. An upload past either is refused.
  • An upload no record uses is private (never served) and is deleted with its file after 24 hours by the retention sweep that also prunes old firehose events.
  • No writes are accepted while a move out is under way or after it.
  • An upload token the app got for the video service (getServiceAuth) keeps working until it expires, at most 30 minutes, even if the app password that asked for it is revoked first, as on Bluesky's own PDS.

The profile's display name, bio, avatar and banner still follow the fediverse profile: a profile edit on the website replaces those four fields of the Bluesky profile and keeps everything else the app set (pinned post, pronouns, website, labels).

Rotation key

ACTIVITIES_BLUESKY_PDS_ROTATION_KEY is the instance-wide secp256k1 private key (64 hex characters) that signs the did:plc operations for every hosted account. Generate one and keep it backed up:

openssl rand -hex 32

Losing it means this server can no longer update the DIDs it hosts; the owner's recovery key is the way back. Creating a hosted account is refused while the key is unset or invalid. Never commit it or log it.

PLC directory, AppView and other Bluesky services

  • ACTIVITIES_BLUESKY_PLC_DIRECTORY_URL is the PLC directory the PDS submits did:plc operations to and reads the address of a did:plc labeler or feed generator from (an https origin with no path, query, fragment or credentials; default https://plc.directory).
  • ACTIVITIES_BLUESKY_APPVIEW_URL and ACTIVITIES_BLUESKY_APPVIEW_DID are the AppView a hosted account's app.bsky.* calls go to (default https://api.bsky.app and did:web:api.bsky.app#bsky_appview). Set both together: another AppView refuses tokens addressed to Bluesky's.
  • ACTIVITIES_BLUESKY_CHAT_URL and ACTIVITIES_BLUESKY_CHAT_DID are the chat service a signed-in app's direct messages go to (default https://api.bsky.chat and did:web:api.bsky.chat#bsky_chat).
  • ACTIVITIES_BLUESKY_MODERATION_URL and ACTIVITIES_BLUESKY_MODERATION_DID are the moderation service an app's reports and moderation inbox go to (default https://mod.bsky.app and did:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler); a report, and a read or an appeal of a labeler's decision, that the app addresses to another labeler goes to that labeler instead.
  • ACTIVITIES_BLUESKY_VIDEO_DID is the video service an app may get an upload token for (default did:web:video.bsky.app).

Besides these, an app reaches through the PDS only a labeler or a feed generator it names, at the address that service's DID document gives. Each URL is an https origin with no path, query, fragment or credentials; an invalid value warns once and uses the default. Set each URL together with its DID (an overridden URL without its DID warns once), or leave both unset to use Bluesky's.

DNS

Point the PDS hostname at this server, and add a wildcard record for the handles it offers:

Record Name Value
A/AAAA pds.social.example this server
A/AAAA *.pds.social.example this server

A hosted account's handle is <username>.<PDS hostname> (for example alex.pds.social.example), so the wildcard record is what makes those handles resolve. An admin's profile may also claim the bare served domain as its handle, which needs no extra record. By default that is an admin's profile on the domain itself; Admin › Served domains › Bluesky handle can name one admin's profile, on any served domain, as the only holder instead; it takes the domain as a hosted account's handle. Naming a holder is refused while another profile's hosted account uses the domain as its handle: change that account's handle first.

TLS and the proxy

Serve the PDS hostname over HTTPS with a certificate that covers both the hostname and its wildcard (pds.social.example and *.pds.social.example). The app routes by the request's Host header, so the reverse proxy must keep the original Host (or set X-Forwarded-Host to it) rather than rewriting it to the primary domain; a rewritten host makes every PDS request look like it arrived on ACTIVITIES_HOST. Strip any client-supplied X-Activity-Next-Host and X-Forwarded-Host at the proxy unless the proxy sets them itself.

Bluesky PDS Firehose Start Command

The default container command (node server.js) runs the stock Next.js standalone server, which does not accept WebSockets. To expose the embedded Bluesky PDS firehose (com.atproto.sync.subscribeRepos), start the standalone build or Docker image with node pds-server.js on hosting that keeps long-lived WebSocket connections open:

docker run -p 3000:3000 \
  ... \
  ghcr.io/llun/activities.next:main node pds-server.js

pds-server.js passes every normal HTTP request to Next.js unchanged, answers any other WebSocket upgrade with 404, and accepts WebSocket upgrades on /xrpc/com.atproto.sync.subscribeRepos only for enabled PDS hostnames in ACTIVITIES_BLUESKY_PDS (all other hosts receive 404). At start-up it calls com.atproto.sync.requestCrawl on each domain's configured relays (defaulting to https://bsky.network), retrying with backoff for up to an hour; set "relays": [] on a domain entry to disable crawl requests. See Embedded Bluesky PDS (preview).

Production routing: the PDS gateway

A deployment can split the PDS: the PDS hostname points at a host running node pds-server.js with a read-only database role, which serves the public reads and the firehose, while its reverse proxy (the gateway) forwards every XRPC request that writes or signs in to the web app, which has write access. Give that role SELECT on every table the public reads and the firehose read, bluesky_profile_merges included: a repo's status is read through it (the hosted account's owner and its merged profile), and a missing grant fails those reads. The gateway sends the web app any XRPC request that carries an Authorization header, plus com.atproto.server.createSession; the public reads and com.atproto.sync.subscribeRepos stay on the PDS process.

Set the same ACTIVITIES_PDS_GATEWAY_SECRET (at least 32 characters, for example openssl rand -hex 32; never commit or log it) on the web app, and have the gateway, on each request it forwards:

  • set Host to the web app's own hostname (for example its Cloud Run URL), which must not be a served domain or a PDS hostname, and X-Activity-Next-Host (and X-Forwarded-Host, if it sets one) to the PDS hostname;
  • set X-Activity-Next-Gateway to the secret;
  • set X-Activity-Next-Client-IP to the client's address, one IPv4 or IPv6 literal, replacing any value the client sent.

With the secret set, the web app handles a PDS request only with a valid X-Activity-Next-Gateway, whatever its Host (the gateway always rewrites Host to the web app's own name); without it the XRPC routes, /.well-known/did.json and the firehose answer 404, so calling the web app directly, or through any later domain mapping, gets no PDS handling. The served-domain, comma-list and X-Forwarded-Host conflict refusals still apply first. With a valid proof, X-Activity-Next-Client-IP is the client address for the PDS rate limits, ahead of the ACTIVITIES_TRUST_PROXY_IP_HEADER setting; without one it is ignored, and no other route ever reads either header. A secret that is set but blank or shorter than 32 characters logs a warning (never the value) and refuses every PDS request. A gateway request whose client address is missing or malformed falls back to the proxy address for its rate limits, and logs a warning once. Unset, nothing changes: a single self-hosted process handles the PDS hostname directly.

Creating an account

Settings › Other networks › "Host my Bluesky account here" creates a fresh did:plc account on the domain's PDS for an allowed, confirmed, approved profile that has no linked outside account. The offered handles are <username>.<PDS hostname> and, for an admin's profile that could claim its served domain (or that a served domain names as its bare-handle holder), the bare domain. Accounts are always created fresh here; moving an existing Bluesky account in is not supported.

The account's app.bsky.actor.profile record is written when it is created and kept in step with the profile: the display name, the bio as plain text with a link back to the fediverse profile, and the avatar and banner as blobs. A profile edit queues the update, which replaces only those fields and keeps the rest of the record a Bluesky app wrote, and opening Settings › Other networks repairs an account whose record is missing.

Moving an account out

The owner can move a hosted account to another PDS from the same card. They enter the new server's https address, the handle and email to create there, and a password for the new account (sent once to that server's createAccount and never stored or logged), plus an invite code if the server asks for one, and confirm with the profile's current password. The page then copies the repo, the blobs and the preferences in resumable batches, and the switch asks for the profile's current password again before chaining a PLC operation that takes the directory's last operation's rotation keys except this server's, then the new server's recommended keys, takes the new server's signing key and PDS endpoint, and drops this server's rotation key. The new server must identify itself with the did:web of the address the owner typed. After the switch the copy left here is switched off, its local handle is cleared, it cannot be turned back on, and it can be deleted; the moved account can be linked again under "Your Bluesky account". Cancelling before the switch removes the stored move and leaves the account here working. Starting a move is limited to 3 a day.

Upgrading hosted Bluesky accounts to account-owned identities

The migrate_hosted_bluesky_ownership migration moves every live hosted account from its fediverse profile to the Bluesky actor row of its DID, which then carries the profile's account and is joined to the profile by a bluesky_profile_merges row (see Who a hosted account belongs to). It changes no repo content, signing key, PLC identity, publicId, post, Home row or notification.

The release that ships it runs safely on data that is not migrated yet: its readers fall back to the profile when no merge row exists, and up skips a repo already on a Bluesky actor, so accounts created after the deploy are left as they are. The release before it is not safe on migrated data: its profile deletion and hosted-account delete look the account up under the profile, so on migrated data its deletion would leave the Bluesky actor's live repo behind for good and its delete would leave a stale merge row. Upgrade only from the release that adds bluesky_profile_merges, and only once that release runs on every runner (the web app, the queue workers and any standalone pds-server.js).

Before deploying, take a database backup, and you can already save and review a first snapshot by running the snapshot script from the new release's checkout against the live database (it only reads).

On a platform that deploys the new release before migrations run, and with hosted accounts on the instance:

  1. Deploy the new release.
  2. Confirm that no instance of the previous release serves or runs jobs anywhere, a standalone pds-server.js included.
  3. Quiesce background work: pause the job queue so Home and notification syncs, cross-posts and actor deletions do not run, keep Bluesky apps from signing in or writing to the hosted accounts, and keep hosted-account owners out of Settings › Other networks until step 8 (opening it repairs the account row, which can race the migration on PostgreSQL).
  4. Take a database backup.
  5. Check that no cross-post is in flight: select count(*) from bluesky_crossposts where state in ('pending', 'posting') answers 0.
  6. Save the snapshot: node scripts/run.cjs scripts/maintenance/hostedBlueskyIdentitySnapshot.ts > before.json (read-only; see Hosted Bluesky Identity Snapshot). Review it before going on.
  7. Run yarn migrate. It prints one line per moved DID and per skipped repo with the reason.
  8. Save the snapshot again as after.json and diff before.json after.json. Only these may change: ownership (profile → bluesky, or bluesky-no-account-row for an account whose row was never written, which the Settings card writes later; tombstone keyed <profile id> → tombstone for a deleted repo still keyed by its profile) and, for a Bluesky actor row the migration created, blueskyActorPublicId (null → an id). Anything that still ran between the two snapshots shows up as well: lastSyncedAt and notificationsSeenAt, the home and notifications digests, the pds_* counts, maxEventSeq, rootCid and rev. If the diff shows a broken: … ownership state, do not resume: restore the backup, or roll back as below, and find the cause first.
  9. Resume the job queue.
  10. Run yarn search:reindex: the migration writes no search document for the Bluesky actor rows it creates, nor for a row that gave up its handle to one of them.

On a platform that runs migrations before the new release starts (yarn migrate while the previous release is stopped): take a backup, stop the previous release on every runner (web app, queue workers, any standalone pds-server.js), check that no cross-post is in flight as in step 5, save and review the snapshot from the new release's checkout, run yarn migrate, save the snapshot again and diff as in step 8, then start the new release and run yarn search:reindex. Do not let the previous release run on the migrated data.

To roll back, run yarn migrate:down while only the new release serves, then roll the release back. down moves every merged account back to its profile, including accounts created since; the Bluesky actor rows it created stay, without an account, and a row that gave up its handle keeps its DID as username until a sync stores its profile again. To go back past the release that added bluesky_profile_merges, run yarn migrate:down a second time to drop the empty table.

Storing the account's own Bluesky posts

Each Home sync stores the newest 50 of the account's own Bluesky posts as Bluesky statuses here: for a hosted account every post record of its repo (written here or in a Bluesky app), for an outside link the copies of its cross-posts posted to the DID it holds now. Older ones are filled once by scripts/maintenance/reconcileBlueskyNativeCopies.ts, which reads every such post from the public AppView (25 per call, half a second apart) and stores it the way the Home sync does, for the accounts the Home sync serves (an actor that may act; a hosted repo that is on, or an outside link with a session) and only while the server allows Bluesky. It is a dry run unless given --apply, prints one line per post (would store or stored, not returned by the AppView, not stored, already stored, tombstoned, or AppView error for a batch whose call failed, after which it goes on) and a total, and a second run changes nothing (an AppView error or a post not returned yet is asked for again):

node scripts/run.cjs scripts/maintenance/reconcileBlueskyNativeCopies.ts           # dry run
node scripts/run.cjs scripts/maintenance/reconcileBlueskyNativeCopies.ts --apply

The same script then repairs rows written before Bluesky replies and notifications named the copy, each only when the cross-post proves it (posted, with a DID, and its copy stored; --apply stores copies first, while a dry run reports a copy it would store as not stored): a Bluesky reply stored under the fediverse post now replies to the copy; a like or repost notification from a Bluesky account on the post, for its author, moves to the copy and its group; a reply or quote notification from a Bluesky account grouped under the post is grouped under the copy. A like or repost on the post whose same like or repost is already on the copy (synced after the change, before the repair) is a duplicate and is removed. It prints would repair … / repaired …, would remove duplicate … / removed duplicate …, or left … (<why>) (no DID, copy not stored, not the author's notification) per row, touches no counter or timestamp, and a second run repairs nothing. Rows it leaves keep working as before: an unrepaired reply still shows under the post, an unrepaired notification still names it.

Run yarn migrate before the release starts (it adds bluesky_record_tombstones). A release running before the table exists fails to store new Bluesky posts (the next sync retries), and worse: every cross-post that Bluesky accepts is rolled back and marked failed although it is on Bluesky (recording it also clears the URI's tombstone), and deleting your own Bluesky post here fails after it was already deleted on Bluesky. Take a backup, read the dry run, then apply.

Public Endpoint Protection

Public fitness route-data responses are cacheable for 60 seconds when the source status is public or unlisted and the request is anonymous. Self-hosted deployments that expose public fitness route data should put Activity.next behind an upstream cache and rate limiter, such as nginx limit_req, Cloudflare, or an equivalent reverse proxy rule for /api/v1/fitness-files/*/route-data. The application does not keep process-local anonymous rate-limit buckets for this endpoint because client IP headers are deployment-specific, spoofable unless normalized by a trusted proxy, and not shared across serverless instances.


Contributor rules

Read the applicable rules and review checks below before changing this subsystem. The mandatory workflow remains in AGENTS.md and CONTRIBUTING.md.

Build, Test, and Development Commands

  • Agents: MUST use Node.js version 26 for running any node commands in this project.
  • Always use yarn for all package management. Never use npm install, npm ci, or any other npm commands to install or manage packages.
  • Optional dependencies are modularized into Yarn workspaces (packages/*). External database drivers, queue SDKs, and email providers (pg, @google-cloud/tasks, @upstash/qstash, nodemailer, resend, @aws-sdk/client-ses) live in isolated packages (@activities/pg, @activities/cloudtasks, @activities/qstash, @activities/nodemailer, @activities/resend, @activities/ses). yarn install at the repo root installs all workspaces by default for development and test execution. The Dockerfile builds minimal images using yarn workspaces focus ${WORKSPACES} (defaulting to activities.next @activities/nodemailer), and core code imports optional modules dynamically (dynamicImport / dynamic import()) with type stubs in lib/types/optional-modules.d.ts so the application runs without optional packages installed when those features are unconfigured.
  • yarn dev runs the local Next.js development server. The package script binds Next.js to 0.0.0.0, so the dev server is reachable from the local network — only run it on trusted networks.
  • yarn build builds the production app; yarn start serves it.
  • yarn analyze runs Next's Turbopack bundle analyzer (next analyze) and serves an interactive UI on port 4000; add --output (yarn analyze --output) to write the results to .next/diagnostics/analyze without serving. For per-page numbers, run yarn build, then yarn bundle:report: it prints each route's first-load JavaScript (uncompressed and gzip, largest first) and the size of the chunks every route shares. Save a baseline with yarn bundle:report --json before.json before a change and run yarn bundle:report --compare before.json after rebuilding to see the gzip change per route (see Bundle Size Report).
  • yarn lint runs Oxlint over the app and lib code, then a second pass, oxlint -c lint/oxlintrc.scripts.json scripts. .oxlintrc.json ignores scripts/**, migrations/**, plans/**, and *.config.* files; the second pass exists because exactly one rule has to reach the otherwise-unlinted scripts tree (see A stored path is confined to the storage root in docs/maintenance.md), and keeping it to one rule is what avoids putting the whole rule set onto files that have never satisfied it. Several repository conventions are lint-enforced: no console.*, no ../ imports, no Response.json()/NextResponse.json() or Zod .parse() in app/api routes (agents/api-response-helpers, agents/zod-safe-parse), no direct fetch() in component files (agents/no-component-fetch, whose allowFiles option in .oxlintrc.json is a frozen legacy-offender list — never add a file to it; shrink it by migrating callers to lib/client.ts), no path.resolve/path.join in a local storage driver (agents/no-storage-path-builder), no startsWith against a resolved path anywhere (agents/no-resolved-path-prefix-check), no direct cookie-session read in a route or server action (agents/no-direct-cookie-session), and no stored history.state passed to a replaceState/pushState that writes a URL (agents/no-history-state-address-write). The agents/* rules are a local Oxlint JS plugin, lint/agentsRules.mjs, because Oxlint has no no-restricted-syntax; lint/agentsRules.test.ts runs the linter against fixtures so an Oxlint upgrade that stopped loading the plugin fails yarn test instead of silently un-enforcing them, and also runs the repo's own configs over fixtures so a rule that stopped being pointed at anything fails too. Reach for a rule there rather than a raw-text Vitest scan whenever the convention depends on what a NAME refers to — aliases, destructuring, renamed imports — which a text scan decides wrongly in both directions. Suppress one line with // oxlint-disable-next-line <rule> (the eslint-disable-next-line spelling still works), but note Oxlint does not honor /* global … */ block directives — declare globals in .oxlintrc.json instead, as the public/sw.js override does. That override carries more weight than it looks: the service worker is a static asset in no tsconfig and imported by nothing, so lint is the only thing that reads it at all — and no-undef is its only check for an undeclared global, which is what a typo there looks like. The no-env-reads-outside-lib/config/ rule is enforced by lib/config/envAccess.test.ts; every ACTIVITIES_*/OTEL_* variable read in lib/config/ must have a row in docs/environment-variables.md (lib/config/envDocumentation.test.ts fails otherwise); and server-only trees must not import a runtime value from a 'use client' module (lib/clientModuleBoundary.test.ts — see Server/Client Module Boundary in docs/architecture.md). Three more repo-wide guards live as tests: test/next.config.test.ts (the build config must not consume runtime deployment values), app/globals.contrast.test.ts (the WCAG contrast floor), and lib/components/tailwindCssVariableSyntax.test.ts (see Tailwind CSS variables below). The remaining conventions in this file are review-enforced.
  • yarn test runs the full Vitest suite (all tests run in parallel with SQLite in-memory databases). Each test file belongs to one of three sizes — small (no real I/O, 2s), medium (test database, tmpdir filesystem, short real waits, 15s) or large (child processes and everything else, 30s; timeouts doubled on CI) — which picks its guard and timeout; the size is inferred from the file's source and a /** @vitest-size … */ docblock overrides it (see Test sizes in CONTRIBUTING.md).
  • yarn run prettier always writes ("prettier": "prettier --write app migrations lib lint test" in package.json, so even yarn prettier --check overwrites files); pass a trailing . (yarn run prettier --write .) to format the whole tree, or run yarn prettier:check for a read-only check.
  • yarn typecheck type-checks the whole project; yarn build type-checks everything except tests. TypeScript 7 has no compiler API, so next build type-checks by running the tsc CLI (experimental.useTypeScriptCli), which checks every file its tsconfig includes rather than only the app's module graph — the build therefore reads tsconfig.build.json (inherits tsconfig.json, drops *.test.ts(x)) and catches type errors in scripts/ and in unimported lib/ modules, which the old checker missed. yarn typecheck runs tsc --noEmit directly against tsconfig.json covering all files in the repository (production code, scripts, and all *.test.ts(x) files) with zero exclusions or ratchets. The base exclude drops test/setup/ (the Vitest setup files). And silently, TypeScript resolves a wildcard include to one extension per basename, so a foo.test.tsx sitting beside a foo.test.ts is dropped from every program while Vitest still runs it — a live test file no compiler reads. lib/testFileTypeCoverage.test.ts guards that last one. incremental is false in every tsconfig on purpose: TypeScript 7.0's tsc serves stale diagnostics from .tsbuildinfo after a global .d.ts changes (the microsoft/typescript-go#4664 class of bug), and a full check takes ~2s.
  • TypeScript is on the 7.x line — the native compiler, which ships a CLI and no JavaScript compiler API (require('typescript') exposes only { version }; a new, different API is expected in 7.1). Nothing in the repo may depend on that API, which is why lint is Oxlint rather than ESLint + typescript-eslint (peer <6.1.0, and it throws on load under 7.x — typescript-eslint#10940), scripts/run.cjs boots with tsx rather than @swc-node/register (peer <7), lib/clientModuleBoundary.test.ts parses with @swc/core, and next build type-checks through the tsc CLI (see the yarn typecheck bullet above). Two traps worth knowing before changing any of this: Next resolves the CLI from the package named typescript and needs its bin.tsc, so aliasing that package for a side-by-side TypeScript 6 install (typescript: npm:@typescript/typescript6) makes next build run yarn add --dev typescript itself and rewrite package.json mid-build; and TypeScript 7.0's tsc serves stale diagnostics from .tsbuildinfo after a global .d.ts changes (the microsoft/typescript-go#4664 class of bug), so incremental stays false everywhere. Type-aware lint rules were never enabled here; if they are ever wanted, the TypeScript 7-native route is oxlint --type-aware (tsgolint), not a return to typescript-eslint.
  • yarn migrate applies every pending migration with Kysely's migrator (scripts/database/migrate.ts, which prints the database it resolved before it does anything); yarn migrate:status lists the applied and pending migrations, the Knex handover state and a held SQLite migration lock without writing anything (it creates no table and no SQLite file); yarn migrate:down rolls back the last migration, never the baseline; yarn migrate:unlock releases the SQLite migration lock a killed run left held; yarn migrate:make <name> creates migrations/<timestamp>_<name>.ts from migrations/migration.stub. Always create migrations with yarn migrate:make, then register the new module in migrations/index.ts and its name in migrations/names.ts — the runner reads that static map, not the directory, the startup check reads the names without loading the modules, yarn typecheck fails when the map and the names disagree, and lib/database/migrate/index.test.ts fails when they and the files do. A migration exports up(db) (and down(db)) taking a Kysely<any>; each runs in its own transaction on both backends unless it exports config = { transaction: false }. The first migration, 20261014000000_baseline, is the Knex handover (see Keeping the reference schema dumps in sync below and the handover section in docs/maintenance.md); the 181 Knex migrations it stands for ran in v1.192.34 and earlier releases and are not in this checkout.
  • Local database is local-only. For development and tests, use either SQLite on localhost (ACTIVITIES_DATABASE_CLIENT=better-sqlite3 with a local *.sqlite3 file, or the ACTIVITIES_DATABASE JSON equivalent) or the PostgreSQL in the docker-compose stack at activities.local. Never run the dev server, migrations, or tests against a remote/shared/production database (e.g. a non-local ACTIVITIES_DATABASE_PG_HOST such as <remote-db-host>). Verify the resolved database target is local before migrating or starting the app. When working in a git worktree, do not copy a main-checkout .env.local that points at a remote DB; create a worktree-local SQLite config instead.
  • Creating test/mock users is allowed for local verification (for example, to log in and check UI changes), but only against a local database as defined above — never against a remote/shared/production database.

Database Backends & Local Setup

  • Supported backends: SQLite (docs/sqlite-setup.md) and PostgreSQL (docs/postgresql-setup.md). The clients are better-sqlite3 and pg; no other client is supported.
  • Local SQLite is the simplest for development; run yarn migrate after updating schema or migrations.

Keeping the reference schema dumps in sync

There are two committed reference schema dumps, one per supported backend. Use the one that matches the database you are reasoning about:

  • migrations/schema.sql — the PostgreSQL schema (a pg_dump). Use it when inspecting the schema for PostgreSQL deployments.
  • migrations/schema.sqlite.sql — the SQLite schema (a sqlite3 .schema dump). Use it when inspecting the schema for SQLite — which is what local dev and the Vitest test suite use (tests run against in-memory SQLite). Because the two backends use different SQL dialects (e.g. character varying/jsonb/timestamp with time zone vs varchar/json/datetime), the Postgres dump cannot be loaded into SQLite and vice versa — always read the file for the right backend.

"In lockstep" means they describe the same migration set, not that every column has the same type in both. A migration may deliberately be backend-conditional, and then the dumps legitimately disagree: the 20260207223000_fix_attachments_media_id_type migration returned early unless the client was pg, so for a while attachments.mediaId was integer on PostgreSQL and varchar(255) on SQLite. That is not drift — do not "reconcile" it or regenerate the dumps over it. Check the migration before treating a per-column difference as a bug. (The 20261012100000_attachments_media_id_integer_sqlite migration has since rebuilt the SQLite table with mediaId integer, so the two dumps agree on that column now.)

The app (yarn migrate) runs the migrations, but the test suite does not — createTestDatabase (lib/database/testing/) builds every test database directly from these dumps (see Testing Guidelines in CONTRIBUTING.md). If the dumps drift from the migrations, tests run against a stale schema, so keeping them in lockstep is load-bearing, not just hygiene. They are gitignored by the blanket *.sql rule and re-included by explicit ! negations in .gitignore.

  • The baseline is frozen. migrations/baseline/postgres.sql and migrations/baseline/sqlite.sql are the schema the 181 Knex migrations built (the dumps at the handover, without the Knex bookkeeping tables); yarn migrate loads the right one into an empty database. Never edit or regenerate them — a schema change is a new migration on top. The PostgreSQL baseline must keep loading on PostgreSQL 14 (CI loads it on postgres:14).

  • Any PR that adds, edits, or removes a migration in migrations/ MUST regenerate BOTH migrations/schema.sql and migrations/schema.sqlite.sql in the same PR, and then the Kysely DB types (see Regenerating the Kysely DB types below). Keep them in lockstep — they must always describe the same migration set. CI's schema drift checks (run in the first PostgreSQL test shard) regenerate both reference dumps from the migrations on every pull request and push to main and fail on drift.

  • Regenerate them canonically rather than hand-editing — run every migration against a fresh database of each type and dump the result. In both cases verify SELECT count(*) FROM kysely_migration equals the number of migrations/[0-9]*_*.ts files first (the baseline is one of them). The dumps include the migrator's own kysely_migration and kysely_migration_lock tables; the Knex tables appear only in a database the Knex migrations built, never in a fresh one.

    Pass the DB settings inline on the yarn migrate line — do not write a .env.local (you'd clobber an existing one, and the cleanup would delete it). Because yarn migrate loads .env* files with dotenv-flow, which never overrides variables already in the environment, each inline value wins over the same variable in .env.local — but only that one: .env.local still supplies whatever the line leaves unset, and an ACTIVITIES_DATABASE JSON configuration wins over every individual ACTIVITIES_DATABASE_* variable. So start every line with an empty ACTIVITIES_DATABASE=, or a JSON configuration in .env.local would redirect yarn migrate to that database. For the same reason, run in a shell with no other ACTIVITIES_DATABASE* vars exported (a stray one would be merged in and could target a remote DB — check env | grep ACTIVITIES_DATABASE).

    PostgreSQL (migrations/schema.sql):

    1. Start a local PostgreSQL 17 — e.g. a throwaway postgres:17 Docker container — and wait until it accepts connections (docker run -d returns before initdb finishes; loop on pg_isready). Never point at a remote/shared/production DB. To use the docker-compose stack's PostgreSQL instead (at activities.local; its port and credentials come from your local, gitignored docker-compose.yml), substitute its host/port/credentials in the step-2 environment variables, run psql/pg_dump via the compose service (e.g. docker compose exec postgres …) rather than docker exec anext-schema-pg, and skip the cleanup step.

      docker run -d --name anext-schema-pg \
        -e POSTGRES_USER=activities \
        -e POSTGRES_PASSWORD=activities \
        -e POSTGRES_DB=activities \
        -p 127.0.0.1:55432:5432 postgres:17
      
      # Wait for readiness before continuing.
      until docker exec anext-schema-pg pg_isready -U activities -q; do sleep 1; done
    2. Run migrations with the settings inline (the leading empty ACTIVITIES_DATABASE= neutralises a JSON configuration in .env.local):

      ACTIVITIES_DATABASE= \
      ACTIVITIES_DATABASE_CLIENT=pg \
      ACTIVITIES_DATABASE_PG_HOST=127.0.0.1 \
      ACTIVITIES_DATABASE_PG_PORT=55432 \
      ACTIVITIES_DATABASE_PG_USER=activities \
      ACTIVITIES_DATABASE_PG_PASSWORD=activities \
      ACTIVITIES_DATABASE_PG_DATABASE=activities \
        yarn migrate

      Sanity check that every migration ran — the kysely_migration row count must equal the number of migrations/[0-9]*_*.ts files:

      docker exec anext-schema-pg \
        psql -U activities -d activities -tAc 'SELECT count(*) FROM kysely_migration;'
      ls migrations/[0-9]*_*.ts | wc -l
    3. Dump schema only, without ownership/grants, from the PG 17 server so the dump matches that version:

      docker exec anext-schema-pg \
        pg_dump -U activities -d activities --schema-only --no-owner --no-privileges \
        > /tmp/schema_raw.sql
    4. Strip pg_dump's noise to match the existing pure-DDL file: the \restrict/\unrestrict session token (non-deterministic — never commit it), the -- … comment headers, and the SET default_tablespace / SET default_table_access_method lines. Keep the leading SET/SELECT pg_catalog.set_config(...) block and all CREATE/ALTER DDL.

      awk '
        /^SET statement_timeout/ { started = 1 }
        !started { next }
        /^--/ { next }
        /^\\(un)?restrict/ { next }
        /^SET default_tablespace/ { next }
        /^SET default_table_access_method/ { next }
        { print }
      ' /tmp/schema_raw.sql | cat -s > migrations/schema.sql
    5. Clean up the throwaway container: docker rm -f anext-schema-pg.

    SQLite (migrations/schema.sqlite.sql):

    1. Run migrations against a throwaway file DB with the settings inline, then sanity check that every migration ran — the kysely_migration row count must equal the number of migrations/[0-9]*_*.ts files:

      ACTIVITIES_DATABASE= \
      ACTIVITIES_DATABASE_CLIENT=better-sqlite3 \
      ACTIVITIES_DATABASE_SQLITE_FILENAME=./schema-dump.sqlite3 \
        yarn migrate
      sqlite3 schema-dump.sqlite3 'SELECT count(*) FROM kysely_migration;'  # == ls migrations/[0-9]*_*.ts | wc -l
    2. Dump the schema and strip SQLite's auto-managed internal tables, which it recreates on its own and which must NOT be in the file: the CREATE TABLE sqlite_sequence(...) line, and the FTS5 shadow tables (CREATE TABLE IF NOT EXISTS '<name>_fts_(data|idx|docsize|config|content)'). Keep the CREATE VIRTUAL TABLE … USING fts5(…) statement and its triggers — those are real.

      sqlite3 schema-dump.sqlite3 '.schema' \
        | grep -vE "^CREATE TABLE sqlite_sequence" \
        | grep -vE "^CREATE TABLE IF NOT EXISTS '[A-Za-z_]+_fts_(data|idx|docsize|config|content)'" \
        > migrations/schema.sqlite.sql

      The committed dump is what CI's sqlite3 prints, which keeps CREATE TABLE IF NOT EXISTS for a table a migration created with .ifNotExists(). The sqlite3 on macOS (and Homebrew's) prints those as plain CREATE TABLE and rewrites older rows the same way, so on a Mac compare the new lines with the existing ones and keep the IF NOT EXISTS spelling rather than committing the whole re-dump.

    3. Sanity-check that the result loads cleanly into a fresh database:

      rm -f /tmp/roundtrip.sqlite3
      sqlite3 /tmp/roundtrip.sqlite3 < migrations/schema.sqlite.sql && echo OK
    4. Clean up the throwaway files: rm -f schema-dump.sqlite3 /tmp/roundtrip.sqlite3.

    After both dumps, only migrations/schema.sql and migrations/schema.sqlite.sql should be left changed (plus lib/database/kysely/db.ts once you regenerate the Kysely DB types).

  • A Postgres regeneration is a full re-dump, so its diff can be large even for unchanged tables (formatting differs from older dumps). That is expected — do not try to reproduce the old line-by-line formatting by hand. Commit the schema regeneration as none: when it is the only change (they are reference artifacts and ship nothing).

  • Use only a local database for local dev/tests: SQLite on localhost, or the docker-compose PostgreSQL at activities.local. Never connect local dev, tests, or user creation to a remote/shared/production database.

  • Tests use isolated SQLite in-memory databases for fast, parallel execution.

  • Docker users should persist data under /opt/activities.next/data (bind-mount a host directory there and point the SQLite/media env vars into it). Do not bind-mount /opt/activities.next itself — that directory contains the application (standalone server.js, .next/static, …), so a host-path mount shadows the app and the container cannot start (see docs/setup.md and the database setup guides).

Regenerating the Kysely DB types

lib/database/kysely/db.ts is the Kysely DB interface for every application table. It is generated, never hand-edited, by scripts/maintenance/generateDatabaseTypes.ts, which introspects a PostgreSQL database migrated to the latest migration (step 2 of the PostgreSQL dump above, before you remove the container) and the committed migrations/schema.sqlite.sql, so regenerate the SQLite dump first. Pass the same inline settings as yarn migrate; the script only reads the schema:

ACTIVITIES_DATABASE= ACTIVITIES_DATABASE_CLIENT=pg ACTIVITIES_DATABASE_PG_HOST=… ACTIVITIES_DATABASE_PG_PORT=… ACTIVITIES_DATABASE_PG_USER=… ACTIVITIES_DATABASE_PG_PASSWORD=… ACTIVITIES_DATABASE_PG_DATABASE=… node scripts/run.cjs scripts/maintenance/generateDatabaseTypes.ts

Timestamp columns are typed as the branded EpochMs on read, so compare them only through timestampValue() from lib/database/kysely/dialect.ts; the brand stops bare numbers, not read-back values, which must also go through it. It types each column for what the Kysely driver returns on both backends and prints any column whose type differs between the two dumps in a way that changes what is read back (typed as either, and marked Mismatch in the file). CI's PostgreSQL schema drift check (run in the first PostgreSQL test shard) regenerates the file with --output and fails on drift.