@fedify/relay

中文文档
2.1.32发布于 2026/11/17MITTypeScriptESM + CJS构建来源已验证近 30 天下载 1.2万

ActivityPub relay support for Fedify

原始使用文档
文档目录18 节
  1. What is an ActivityPub relay?
  2. Relay protocols
  3. Mastodon-style relay
  4. LitePub-style relay
  5. Installation
  6. Usage
  7. Creating a relay
  8. Subscription handling
  9. Managing followers
  10. Integration with web frameworks
  11. How it works
  12. Storage requirements
  13. API reference
  14. createRelay()
  15. Relay
  16. RelayOptions
  17. SubscriptionRequestHandler
  18. RelayFollower

@fedify/relay: ActivityPub relay for Fedify

JSR npm Follow @fedify@hollo.social

This package is available since Fedify 2.0.0.

This package provides ActivityPub relay functionality for the Fedify ecosystem, enabling the creation and management of relay servers that can forward activities between federated instances.

For comprehensive documentation on building and operating relay servers, see the Relay server section in the Fedify manual.

What is an ActivityPub relay?

ActivityPub relays are infrastructure components that help small instances participate effectively in the federated social network by acting as intermediary servers that distribute public content without requiring individual actor-following relationships. When an instance subscribes to a relay, all public posts from that instance are forwarded to all other subscribed instances, creating a shared pool of federated content.

Relay protocols

This package supports two popular relay protocols used in the fediverse:

Mastodon-style relay

The Mastodon-style relay protocol uses LD signatures for activity verification and follows the Public collection. This protocol is widely supported by Mastodon and many other ActivityPub implementations.

Key features:

  • Direct activity relaying with proper content types (Create, Update, Delete, Move)
  • LD signature verification and generation
  • Follows the ActivityPub Public collection
  • Simple subscription mechanism via Follow activities

LitePub-style relay

The LitePub-style relay protocol uses bidirectional following relationships and wraps activities in Announce activities for distribution.

Key features:

  • Reciprocal following between relay and subscribers
  • Activities wrapped in Announce for distribution
  • Two-phase subscription (pending → accepted)
  • Enhanced federation capabilities

Installation

::: code-group

deno add jsr:@fedify/relay
npm add @fedify/relay
pnpm add @fedify/relay
yarn add @fedify/relay
bun add @fedify/relay

:::

Usage

Creating a relay

Here's a simple example of creating a relay server using the factory function:

import { createRelay } from "@fedify/relay";
import { MemoryKvStore } from "@fedify/fedify";

// Create a Mastodon-style relay
const relay = createRelay("mastodon", {
  kv: new MemoryKvStore(),
  origin: "https://relay.example.com",
  // Required: Set a subscription handler to approve/reject subscriptions
  subscriptionHandler: async (ctx, actor) => {
    // For an open relay, simply return true
    // return true;

    // Or implement custom approval logic:
    const domain = new URL(actor.id!).hostname;
    const blockedDomains = ["spam.example", "blocked.example"];
    return !blockedDomains.includes(domain);
  },
});

// Serve the relay
Deno.serve((request) => relay.fetch(request));

You can also create a LitePub-style relay by changing the type:

const relay = createRelay("litepub", {
  kv: new MemoryKvStore(),
  origin: "https://relay.example.com",
  subscriptionHandler: async (ctx, actor) => true,
});

Subscription handling

The subscriptionHandler is required and determines whether to approve or reject subscription requests. For an open relay that accepts all subscriptions:

const relay = createRelay("mastodon", {
  kv: new MemoryKvStore(),
  origin: "https://relay.example.com",
  subscriptionHandler: async (ctx, actor) => true,  // Accept all
});

You can also implement custom approval logic:

const relay = createRelay("mastodon", {
  kv: new MemoryKvStore(),
  origin: "https://relay.example.com",
  subscriptionHandler: async (ctx, actor) => {
    // Example: Only allow subscriptions from specific domains
    const domain = new URL(actor.id!).hostname;
    const allowedDomains = ["mastodon.social", "fosstodon.org"];
    return allowedDomains.includes(domain);
  },
});

Managing followers

The relay provides methods to query and manage followers without exposing internal storage details.

Listing all followers

for await (const follower of relay.listFollowers()) {
  console.log(`Follower: ${follower.actorId}`);
  console.log(`State: ${follower.state}`);
  console.log(`Actor name: ${follower.actor.name}`);
  console.log(`Actor type: ${follower.actor.constructor.name}`);
}

Getting a specific follower

const follower = await relay.getFollower("https://mastodon.example.com/users/alice");
if (follower) {
  console.log(`Found follower in state: ${follower.state}`);
  console.log(`Actor username: ${follower.actor.preferredUsername}`);
  console.log(`Inbox: ${follower.actor.inboxId?.href}`);
} else {
  console.log("Follower not found");
}

Integration with web frameworks

The relay's fetch() method returns a standard Response object, making it compatible with any web framework that supports the Fetch API. Here's an example with Hono:

import { Hono } from "hono";
import { createRelay } from "@fedify/relay";
import { MemoryKvStore } from "@fedify/fedify";

const app = new Hono();
const relay = createRelay("mastodon", {
  kv: new MemoryKvStore(),
  origin: "https://relay.example.com",
  subscriptionHandler: async (ctx, actor) => true,
});

app.use("*", async (c) => {
  return await relay.fetch(c.req.raw);
});

export default app;

How it works

The relay operates by:

  1. Actor registration: The relay presents itself as a Service actor at /users/relay
  2. Subscription: Instances subscribe to the relay by sending a Follow activity
  3. Approval: The relay's subscription handler determines whether to approve the subscription (responds with Accept or Reject)
  4. Forwarding: When a subscribed instance sends activities (Create, Update, Delete, Move) to the relay's inbox, the relay forwards them to all other subscribed instances
  5. Unsubscription: Instances can unsubscribe by sending an Undo activity wrapping their original Follow activity

Storage requirements

The relay requires a key–value store to persist:

  • Subscriber list and their Follow activity IDs
  • Subscriber actor information
  • Relay's cryptographic key pairs (RSA and Ed25519)

Any KvStore implementation from Fedify can be used, including:

  • MemoryKvStore (for development/testing)
  • DenoKvStore (Deno KV)
  • RedisKvStore (Redis)
  • PostgresKvStore (PostgreSQL)
  • MysqlKvStore (MySQL/MariaDB)
  • SqliteKvStore (SQLite)

For production use, choose a persistent storage backend like Redis, PostgreSQL, or MySQL/MariaDB. See the Fedify documentation on key–value stores for more details.

API reference

createRelay()

Factory function to create a relay instance.

function createRelay(
  type: "mastodon" | "litepub",
  options: RelayOptions
): Relay

Parameters:

  • type: The type of relay to create ("mastodon" or "litepub")
  • options: Configuration options for the relay

Returns: A Relay instance

Relay

Public interface for ActivityPub relay implementations.

Methods

  • fetch(request: Request): Promise<Response>: Handle incoming HTTP requests
  • listFollowers(): AsyncIterableIterator<RelayFollower>: Lists all followers of the relay
  • getFollower(actorId: string): Promise<RelayFollower | null>: Gets a specific follower by actor ID
  • getActorUri(): Promise<URL>: Gets the URI of the relay actor
  • getSharedInboxUri(): Promise<URL>: Gets the shared inbox URI of the relay

Relay types

The relay type is specified when calling createRelay():

  • "mastodon": Mastodon-compatible relay using direct activity forwarding, immediate subscription approval, and LD signatures
  • "litepub": LitePub-compatible relay using bidirectional following, activities wrapped in Announce, and two-phase subscription

RelayOptions

Configuration options for the relay:

  • kv: KvStore (required): Key–value store for persisting relay data
  • origin: string (required): Relay's origin URL (e.g., "https://relay.example.com")
  • name?: string: Relay's display name (defaults to "ActivityPub Relay")
  • subscriptionHandler: SubscriptionRequestHandler (required): Handler for subscription approval/rejection
  • documentLoaderFactory?: DocumentLoaderFactory: Custom document loader factory
  • authenticatedDocumentLoaderFactory?: AuthenticatedDocumentLoaderFactory: Custom authenticated document loader factory
  • queue?: MessageQueue: Message queue for background activity processing

SubscriptionRequestHandler

A function that determines whether to approve a subscription request:

type SubscriptionRequestHandler = (
  ctx: Context<RelayOptions>,
  clientActor: Actor,
) => Promise<boolean>

Parameters:

  • ctx: The Fedify context object with relay options
  • clientActor: The actor requesting to subscribe

Returns:

  • true to approve the subscription
  • false to reject the subscription

RelayFollower

A follower of the relay with validated Actor instance:

interface RelayFollower {
  readonly actorId: string;
  readonly actor: Actor;
  readonly state: "pending" | "accepted";
}

Properties:

  • actorId: The actor ID (URL) of the follower
  • actor: The validated Actor object
  • state: The follower's state ("pending" or "accepted")

版本与发布记录

@fedify/relay 共发布 575 个版本,首次发布于 2025/11/13;过去 12 个月发布了 570 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.1.32latest2026/11/17今天
2.0.362026/11/17今天
2.3.16-dev.28452026/11/17今天
2.5.0-dev.28442026/11/17今天
2.0.36-dev.28432026/11/17今天
2.3.16-dev.28412026/11/17今天

其他发布通道:pr-478 → 2.0.0-pr.478.1918,pr-479 → 2.0.0-pr.479.1922,pr-490 → 2.0.0-pr.490.2,pr-559 → 2.0.0-pr.559.6,pr-633 → 2.0.6-pr.633.9,pr-639 → 2.0.7-pr.639.14。

关于 @fedify/relay 的常见问题

@fedify/relay 是什么?

ActivityPub relay support for Fedify

如何安装 @fedify/relay?

在项目目录运行 npm install @fedify/relay,或使用 pnpm add / yarn add / bun add。

@fedify/relay 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fedify/relay 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@fedify/relay 可以商用吗?

@fedify/relay 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fedify/relay 的下载量有多少?

根据 npm 官方下载统计,@fedify/relay 在 2026/10/15 – 2026/11/13 这 30 天内被下载 12,261 次,日均约 409 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fedify/relay 还在维护吗?

最新版本 2.1.32 发布于 2026/11/17(今天);至今共发布 575 个版本,其中过去 12 个月发布了 570 个;首次发布于 2025/11/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。