-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
inbox.tsx
416 lines (393 loc) · 12.6 KB
/
inbox.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { colors } from "@cliffy/ansi";
import { Command } from "@cliffy/command";
import { Cell, Table } from "@cliffy/table";
import {
Accept,
Activity,
type Actor,
Application,
type Context,
createFederation,
Delete,
Endpoints,
Follow,
generateCryptoKeyPair,
getActorHandle,
Image,
isActor,
lookupObject,
MemoryKvStore,
PUBLIC_COLLECTION,
type Recipient,
} from "@fedify/fedify";
import { getLogger } from "@logtape/logtape";
import { parse } from "@std/semver";
import { Hono } from "hono";
import ora from "ora";
import metadata from "./deno.json" with { type: "json" };
import { getDocumentLoader } from "./docloader.ts";
import type { ActivityEntry } from "./inbox/entry.ts";
import { ActivityEntryPage, ActivityListPage } from "./inbox/view.tsx";
import { recordingSink } from "./log.ts";
import { tableStyle } from "./table.ts";
import { spawnTemporaryServer, type TemporaryServer } from "./tempserver.ts";
const logger = getLogger(["fedify", "cli", "inbox"]);
export const command = new Command()
.description(
"Spins up an ephemeral server that serves the ActivityPub inbox with " +
"an one-time actor, through a short-lived public DNS with HTTPS. " +
"You can monitor the incoming activities in real-time.",
)
.option(
"-f, --follow=<uri:string>",
"Follow the given actor. The argument can be either an actor URI or " +
"a handle. Can be specified multiple times.",
{ collect: true },
)
.option(
"-a, --accept-follow=<uri:string>",
"Accept follow requests from the given actor. The argument can be " +
"either an actor URI or a handle, or a wildcard (*). Can be " +
"specified multiple times. If a wildcard is specified, all follow " +
"requests will be accepted.",
{ collect: true },
)
.option(
"-T, --no-tunnel",
"Do not tunnel the ephemeral ActivityPub server to the public Internet.",
)
.action(async (options) => {
const spinner = ora({
text: "Spinning up an ephemeral ActivityPub server...",
discardStdin: false,
}).start();
const server = await spawnTemporaryServer(fetch, {
noTunnel: !options.tunnel,
});
spinner.succeed(
`The ephemeral ActivityPub server is up and running: ${
colors.green(
server.url.href,
)
}`,
);
Deno.addSignalListener("SIGINT", () => {
spinner.stop();
const peersCnt = Object.keys(peers).length;
spinner.start(
`Sending Delete(Application) activities to the ${peersCnt} ${
peersCnt === 1 ? "peer" : "peers"
}...`,
);
sendDeleteToPeers(server).then(() => {
spinner.text = "Stopping server...";
server.close().then(() => {
spinner.succeed("Server stopped.");
Deno.exit(0);
});
});
});
spinner.start();
const fedCtx = federation.createContext(server.url, -1);
if (options.acceptFollow != null && options.acceptFollow.length > 0) {
acceptFollows.push(...(options.acceptFollow ?? []));
}
if (options.follow != null && options.follow.length > 0) {
spinner.text = "Following actors...";
const documentLoader = await fedCtx.getDocumentLoader({
identifier: "i",
});
for (const uri of options.follow) {
spinner.text = `Following ${colors.green(uri)}...`;
const actor = await lookupObject(uri, { documentLoader });
if (!isActor(actor)) {
spinner.fail(`Not an actor: ${colors.red(uri)}`);
spinner.start();
continue;
}
if (actor.id != null) peers[actor.id?.href] = actor;
await fedCtx.sendActivity(
{ identifier: "i" },
actor,
new Follow({
id: new URL(`#follows/${actor.id?.href}`, fedCtx.getActorUri("i")),
actor: fedCtx.getActorUri("i"),
object: actor.id,
}),
);
spinner.succeed(`Sent follow request to ${colors.green(uri)}.`);
spinner.start();
}
}
spinner.stop();
printServerInfo(fedCtx);
});
const federation = createFederation<number>({
kv: new MemoryKvStore(),
documentLoader: await getDocumentLoader(),
});
const time = Temporal.Now.instant();
let actorKeyPairs: CryptoKeyPair[] | undefined = undefined;
federation
.setActorDispatcher("/{identifier}", async (ctx, identifier) => {
if (identifier !== "i") return null;
return new Application({
id: ctx.getActorUri(identifier),
preferredUsername: identifier,
name: "Fedify Ephemeral Inbox",
summary: "An ephemeral ActivityPub inbox for testing purposes.",
inbox: ctx.getInboxUri(identifier),
endpoints: new Endpoints({
sharedInbox: ctx.getInboxUri(),
}),
followers: ctx.getFollowersUri(identifier),
following: ctx.getFollowingUri(identifier),
outbox: ctx.getOutboxUri(identifier),
manuallyApprovesFollowers: true,
published: time,
icon: new Image({
url: new URL("https://fedify.dev/logo.png"),
mediaType: "image/png",
}),
publicKey: (await ctx.getActorKeyPairs(identifier))[0].cryptographicKey,
assertionMethods: (await ctx.getActorKeyPairs(identifier))
.map((pair) => pair.multikey),
url: ctx.getActorUri(identifier),
});
})
.setKeyPairsDispatcher(async (_ctxData, identifier) => {
if (identifier !== "i") return [];
if (actorKeyPairs == null) {
actorKeyPairs = [
await generateCryptoKeyPair("RSASSA-PKCS1-v1_5"),
await generateCryptoKeyPair("Ed25519"),
];
}
return actorKeyPairs;
});
const activities: ActivityEntry[] = [];
const acceptFollows: string[] = [];
async function acceptsFollowFrom(actor: Actor): Promise<boolean> {
const actorUri = actor.id;
let actorHandle: string | undefined = undefined;
if (actorUri == null) return false;
for (let uri of acceptFollows) {
if (uri === "*") return true;
if (uri.startsWith("http:") || uri.startsWith("https:")) {
uri = new URL(uri).href; // normalize
if (uri === actorUri.href) return true;
}
if (actorHandle == null) actorHandle = await getActorHandle(actor);
if (actorHandle === uri) return true;
}
return false;
}
const peers: Record<string, Actor> = {};
async function sendDeleteToPeers(server: TemporaryServer): Promise<void> {
const ctx = federation.createContext(new Request(server.url), -1);
const actor = (await ctx.getActor("i"))!;
try {
await ctx.sendActivity(
{ identifier: "i" },
Object.values(peers),
new Delete({
id: new URL(`#delete`, actor.id!),
actor: actor.id!,
to: PUBLIC_COLLECTION,
object: actor,
}),
);
} catch (error) {
logger.error(
"Failed to send Delete(Application) activities to peers:\n{error}",
{ error },
);
}
}
const followers: Record<string, Actor> = {};
federation
.setInboxListeners("/{identifier}/inbox", "/inbox")
.setSharedKeyDispatcher((_) => ({ identifier: "i" }))
.on(Activity, async (ctx, activity) => {
activities[ctx.data].activity = activity;
for await (const actor of activity.getActors()) {
if (actor.id != null) peers[actor.id.href] = actor;
}
for await (const actor of activity.getAttributions()) {
if (actor.id != null) peers[actor.id.href] = actor;
}
if (activity instanceof Follow) {
if (acceptFollows.length < 1) return;
const objectId = activity.objectId;
if (objectId == null) return;
const parsed = ctx.parseUri(objectId);
if (parsed?.type !== "actor" || parsed.identifier !== "i") return;
const { identifier } = parsed;
const follower = await activity.getActor();
if (!isActor(follower)) return;
const accepts = await acceptsFollowFrom(follower);
if (!accepts || activity.id == null) {
logger.debug("Does not accept follow from {actor}.", {
actor: follower.id?.href,
});
return;
}
logger.debug("Accepting follow from {actor}.", {
actor: follower.id?.href,
});
followers[activity.id.href] = follower;
await ctx.sendActivity(
{ identifier },
follower,
new Accept({
id: new URL(`#accepts/${follower.id?.href}`, ctx.getActorUri("i")),
actor: ctx.getActorUri(identifier),
object: activity.id,
}),
);
}
});
federation
.setFollowersDispatcher("/{identifier}/followers", (_ctx, identifier) => {
if (identifier !== "i") return null;
const items: Recipient[] = [];
for (const follower of Object.values(followers)) {
if (follower.id == null) continue;
items.push(follower);
}
return { items };
})
.setCounter((_ctx, identifier) => {
if (identifier !== "i") return null;
return Object.keys(followers).length;
});
federation
.setFollowingDispatcher(
"/{identifier}/following",
(_ctx, _identifier) => null,
)
.setCounter((_ctx, _identifier) => 0);
federation
.setOutboxDispatcher("/{identifier}/outbox", (_ctx, _identifier) => null)
.setCounter((_ctx, _identifier) => 0);
federation.setNodeInfoDispatcher("/nodeinfo/2.1", (_ctx) => {
return {
software: {
name: "fedify-cli",
version: parse(metadata.version),
repository: new URL("https://github.com/dahlia/fedify"),
},
protocols: ["activitypub"],
usage: {
users: {
total: 1,
activeMonth: 1,
activeHalfyear: 1,
},
localComments: 0,
localPosts: 0,
},
};
});
function printServerInfo(fedCtx: Context<number>): void {
new Table(
[
new Cell("Actor handle:").align("right"),
colors.green(`i@${fedCtx.getActorUri("i").host}`),
],
[
new Cell("Actor URI:").align("right"),
colors.green(fedCtx.getActorUri("i").href),
],
[
new Cell("Actor inbox:").align("right"),
colors.green(fedCtx.getInboxUri("i").href),
],
[
new Cell("Shared inbox:").align("right"),
colors.green(fedCtx.getInboxUri().href),
],
)
.chars(tableStyle)
.border()
.render();
}
function printActivityEntry(idx: number, entry: ActivityEntry): void {
const request = entry.request.clone();
const response = entry.response?.clone();
const url = new URL(request.url);
const activity = entry.activity;
new Table(
[new Cell("Request #:").align("right"), colors.bold(idx.toString())],
[
new Cell("Activity type:").align("right"),
activity == null
? colors.red("failed to parse")
: colors.green(activity.constructor.name),
],
[
new Cell("HTTP request:").align("right"),
`${
request.method === "POST"
? colors.green("POST")
: colors.red(request.method)
} ${url.pathname + url.search}`,
],
...(response == null ? [] : [
[
new Cell("HTTP response:").align("right"),
`${
response.ok
? colors.green(response.status.toString())
: colors.red(response.status.toString())
} ${response.statusText}`,
],
]),
[new Cell("Details").align("right"), new URL(`/r/${idx}`, url).href],
)
.chars(tableStyle)
.border()
.render();
}
const app = new Hono();
app.get("/", (c) => c.redirect("/r"));
app.get("/r", (c) => c.html(<ActivityListPage entries={activities} />));
app.get("/r/:idx{[0-9]+}", (c) => {
const idx = parseInt(c.req.param("idx"));
const tab = c.req.query("tab") ?? "request";
const activity = activities[idx];
if (activity == null) return c.notFound();
if (
tab !== "request" && tab !== "response" && tab !== "raw-activity" &&
tab !== "compact-activity" && tab !== "expanded-activity" && tab !== "logs"
) {
return c.notFound();
}
return c.html(<ActivityEntryPage idx={idx} entry={activity} tabPage={tab} />);
});
async function fetch(request: Request): Promise<Response> {
const timestamp = Temporal.Now.instant();
const idx = activities.length;
const pathname = new URL(request.url).pathname;
if (pathname === "/r" || pathname.startsWith("/r/")) {
return app.fetch(request);
}
const inboxRequest = pathname === "/inbox" || pathname.startsWith("/i/inbox");
if (inboxRequest) {
recordingSink.startRecording();
activities.push({ timestamp, request: request.clone(), logs: [] });
}
const response = await federation.fetch(request, {
contextData: inboxRequest ? idx : -1,
onNotAcceptable: app.fetch.bind(app),
onNotFound: app.fetch.bind(app),
onUnauthorized: app.fetch.bind(app),
});
if (inboxRequest) {
recordingSink.stopRecording();
activities[idx].response = response.clone();
activities[idx].logs = recordingSink.getRecords();
printActivityEntry(idx, activities[idx]);
}
return response;
}