Index: src/config/database.js
===================================================================
--- src/config/database.js	(revision 69815b232bc91b7504ea8b28d3e2f66949f216ed)
+++ src/config/database.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
@@ -295,4 +295,26 @@
     CREATE INDEX IF NOT EXISTS idx_post_likes_post ON post_likes(post_id);
   `);
+
+  // ── ActivityPub (fediverse bridge) ──────────────────────────
+  // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
+  // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
+  db.exec(`
+    CREATE TABLE IF NOT EXISTS ap_keys (
+      slug TEXT PRIMARY KEY,
+      public_pem TEXT NOT NULL,
+      private_pem TEXT NOT NULL,
+      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+    );
+    CREATE TABLE IF NOT EXISTS ap_followers (
+      id INTEGER PRIMARY KEY AUTOINCREMENT,
+      slug TEXT NOT NULL,
+      actor_uri TEXT NOT NULL,
+      inbox TEXT,
+      shared_inbox TEXT,
+      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+      UNIQUE(slug, actor_uri)
+    );
+    CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
+  `);
 }
 
Index: src/routes/activitypub.js
===================================================================
--- src/routes/activitypub.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
+++ src/routes/activitypub.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
@@ -0,0 +1,89 @@
+/**
+ * ActivityPub — public endpoints (Phase 1: discover + fetch).
+ *
+ *   GET /.well-known/webfinger?resource=acct:<slug>@<host>
+ *   GET /ap/users/:slug            actor (content-negotiated: AP-JSON vs redirect to HTML profile)
+ *   GET /ap/users/:slug/outbox     OrderedCollection of Create(Note)
+ *   GET /ap/users/:slug/followers  count-only OrderedCollection
+ *   GET /ap/notes/:id              a single Note
+ *   POST /ap/users/:slug/inbox, /ap/inbox  → 202 (Follow/Accept + signature verify: next step)
+ *
+ * Mounted before resolveSite; resolves the site by slug itself.
+ */
+import express from 'express';
+import db from '../config/database.js';
+import AP from '../services/ActivityPubService.js';
+
+const router = express.Router();
+
+const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
+const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
+const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
+const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
+
+// ── WebFinger ─────────────────────────────────────────────────────
+router.get('/.well-known/webfinger', (req, res) => {
+  const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
+  if (!m) return res.status(400).type('text/plain').send('bad resource');
+  const site = publicSite(m[1]);
+  if (!site) return res.status(404).end();
+  res.type('application/jrd+json; charset=utf-8');
+  res.set('Cache-Control', 'public, max-age=300');
+  res.send(JSON.stringify({
+    subject: `acct:${site.slug}@${hostOf(req)}`,
+    links: [{ rel: 'self', type: 'application/activity+json', href: AP.actorId(baseUrl(req), site.slug) }],
+  }));
+});
+
+// ── Actor ─────────────────────────────────────────────────────────
+router.get('/ap/users/:slug', (req, res) => {
+  const site = publicSite(req.params.slug);
+  if (!site) return res.status(404).end();
+  if (!AP.apWants(req)) {
+    // A browser hit the AP actor URL → send them to the human profile.
+    const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
+    return res.redirect(302, baseUrl(req) + human);
+  }
+  site.primary_slug = primarySlug();
+  AP.sendAP(res, AP.buildActor(baseUrl(req), site));
+});
+
+// ── Outbox ────────────────────────────────────────────────────────
+router.get('/ap/users/:slug/outbox', (req, res) => {
+  const site = publicSite(req.params.slug);
+  if (!site) return res.status(404).end();
+  const posts = db.prepare(
+    `SELECT id, slug, title, content, published_at, created_at
+     FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
+     ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
+  ).all(site.id);
+  AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
+});
+
+// ── Followers (count only) ────────────────────────────────────────
+router.get('/ap/users/:slug/followers', (req, res) => {
+  const site = publicSite(req.params.slug);
+  if (!site) return res.status(404).end();
+  const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
+  AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
+});
+
+// ── Note ──────────────────────────────────────────────────────────
+router.get('/ap/notes/:id', (req, res) => {
+  const post = db.prepare(
+    "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
+  ).get(req.params.id);
+  if (!post) return res.status(404).end();
+  const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
+  if (!site) return res.status(404).end();
+  AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...AP.buildNote(baseUrl(req), site, post) });
+});
+
+// ── Inbox (Phase 1 stub: accept; Follow/Accept + sig verify next step) ──
+const apJson = express.json({ type: ['application/activity+json', 'application/ld+json', 'application/json'], limit: '1mb' });
+router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, (req, res) => {
+  try { console.log('[AP inbox]', (req.body && req.body.type) || 'unknown', '→', req.params.slug || 'shared'); } catch { /* ignore */ }
+  res.status(202).end();
+});
+
+export default router;
Index: src/server.js
===================================================================
--- src/server.js	(revision 69815b232bc91b7504ea8b28d3e2f66949f216ed)
+++ src/server.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
@@ -64,4 +64,5 @@
 import changelogRoutes from './routes/changelog.js';
 import ogRoutes from './routes/og.js';
+import apRoutes from './routes/activitypub.js';
 
 // SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
@@ -223,4 +224,7 @@
 app.use(federationRoutes);
 
+// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
+app.use(apRoutes);
+
 // Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
 // run before resolveSite and need no site context.
Index: src/services/ActivityPubService.js
===================================================================
--- src/services/ActivityPubService.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
+++ src/services/ActivityPubService.js	(revision 6bd25d164a42c0ff47b98ae2f2e006233dcd5efa)
@@ -0,0 +1,158 @@
+/**
+ * ActivityPubService — Klonkt as a real ActivityPub actor (fediverse bridge).
+ *
+ * Phase 1 (this file): the PUBLISH/discoverable side.
+ *   - per-site RSA keypair (Mastodon-compatible HTTP Signatures; separate from
+ *     the Ed25519 keys used by the lighter Cirkels v1)
+ *   - builders for the Actor document, Note objects and the Outbox collection
+ *   - apWants(): HTTP content-negotiation helper (activity+json vs HTML)
+ *
+ * The interactive side (inbox: Follow/Accept, signature verify, delivery to
+ * followers) lands in the next step and is tested live against Mastodon.
+ *
+ * AP actor URLs live under /ap/* so they never clash with the human pages:
+ *   actor   = <base>/ap/users/<slug>
+ *   inbox   = <actor>/inbox      outbox = <actor>/outbox
+ *   note    = <base>/ap/notes/<postId>
+ */
+import crypto from 'crypto';
+import db from '../config/database.js';
+
+const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
+const MAX_OUTBOX = 20;
+
+// ── RSA keys per actor (lazy, cached in DB) ───────────────────────
+// Prepared lazily (NOT at module load) — the ap_keys table is created in
+// initializeDatabase(), which runs after this module is imported.
+let _sel, _ins;
+function keyStmts() {
+  if (!_sel) {
+    _sel = db.prepare('SELECT public_pem, private_pem FROM ap_keys WHERE slug = ?');
+    _ins = db.prepare('INSERT OR IGNORE INTO ap_keys (slug, public_pem, private_pem, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)');
+  }
+  return { sel: _sel, ins: _ins };
+}
+
+export function getOrCreateKeys(slug) {
+  const { sel, ins } = keyStmts();
+  const row = sel.get(slug);
+  if (row) return row;
+  const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
+    modulusLength: 2048,
+    publicKeyEncoding: { type: 'spki', format: 'pem' },
+    privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+  });
+  ins.run(slug, publicKey, privateKey);
+  return sel.get(slug) || { public_pem: publicKey, private_pem: privateKey };
+}
+
+// ── content negotiation ───────────────────────────────────────────
+// True when the caller wants ActivityPub JSON rather than the HTML page.
+export function apWants(req) {
+  const a = String(req.headers.accept || '').toLowerCase();
+  return a.includes('application/activity+json') ||
+         (a.includes('application/ld+json') && a.includes('activitystreams'));
+}
+
+const AP_CONTENT_TYPE = 'application/activity+json; charset=utf-8';
+export function sendAP(res, obj) {
+  res.type(AP_CONTENT_TYPE);
+  res.set('Cache-Control', 'public, max-age=120');
+  res.send(JSON.stringify(obj));
+}
+
+// ── document builders ─────────────────────────────────────────────
+export function actorId(base, slug) { return `${base}/ap/users/${encodeURIComponent(slug)}`; }
+export function noteId(base, postId) { return `${base}/ap/notes/${encodeURIComponent(postId)}`; }
+
+export function buildActor(base, site) {
+  const id = actorId(base, site.slug);
+  const keys = getOrCreateKeys(site.slug);
+  const actor = {
+    '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'],
+    id,
+    type: 'Person',
+    preferredUsername: site.slug,
+    name: site.title || site.slug,
+    summary: site.tagline || site.description || '',
+    url: `${base}/${site.slug === site.primary_slug ? '' : 'user/' + encodeURIComponent(site.slug)}`,
+    manuallyApprovesFollowers: false,
+    discoverable: true,
+    inbox: `${id}/inbox`,
+    outbox: `${id}/outbox`,
+    followers: `${id}/followers`,
+    endpoints: { sharedInbox: `${base}/ap/inbox` },
+    publicKey: {
+      id: `${id}#main-key`,
+      owner: id,
+      publicKeyPem: keys.public_pem,
+    },
+  };
+  if (site.profile_photo) {
+    const u = /^https?:/.test(site.profile_photo) ? site.profile_photo : `${base}${site.profile_photo.startsWith('/') ? '' : '/'}${site.profile_photo}`;
+    actor.icon = { type: 'Image', url: u };
+  }
+  return actor;
+}
+
+// A single post as an AS2 Note (the object), and as a Create activity (for outbox/delivery).
+export function buildNote(base, site, post) {
+  const id = noteId(base, post.id);
+  const aId = actorId(base, site.slug);
+  const human = `${base}/${encodeURIComponent(post.slug)}`;
+  const html = post.content || ''; // posts store sanitized HTML
+  return {
+    id,
+    type: 'Note',
+    attributedTo: aId,
+    content: html,
+    name: post.title || undefined,
+    url: human,
+    published: new Date(post.published_at || post.created_at || Date.now()).toISOString(),
+    to: [PUBLIC],
+    cc: [`${aId}/followers`],
+    tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [],
+  };
+}
+
+export function buildCreate(base, site, post) {
+  const note = buildNote(base, site, post);
+  return {
+    '@context': 'https://www.w3.org/ns/activitystreams',
+    id: note.id + '#create',
+    type: 'Create',
+    actor: actorId(base, site.slug),
+    published: note.published,
+    to: note.to,
+    cc: note.cc,
+    object: note,
+  };
+}
+
+export function buildOutbox(base, site, posts) {
+  const id = `${actorId(base, site.slug)}/outbox`;
+  const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p));
+  return {
+    '@context': 'https://www.w3.org/ns/activitystreams',
+    id,
+    type: 'OrderedCollection',
+    totalItems: items.length,
+    orderedItems: items,
+  };
+}
+
+export function buildFollowers(base, site, count) {
+  const id = `${actorId(base, site.slug)}/followers`;
+  return {
+    '@context': 'https://www.w3.org/ns/activitystreams',
+    id,
+    type: 'OrderedCollection',
+    totalItems: count || 0,
+    orderedItems: [], // hidden for privacy; count only
+  };
+}
+
+export default {
+  getOrCreateKeys, apWants, sendAP, actorId, noteId,
+  buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
+};
