summary refs log tree commit diff
path: root/src/activitypub/federation/utils.ts
blob: e879e863116d507cba7c7b8b825d63521f3e2252 (plain) (blame)
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
import { DEFAULT_FETCH_OPTIONS } from "@spacebar/api";
import {
	ActorType,
	BaseClass,
	ChannelCreateEvent,
	Config,
	Debug,
	FederationActivity,
	FederationCache,
	FederationKey,
	Guild,
	OrmUtils,
	Snowflake,
	User,
	UserSettings,
	WebfingerResponse,
	emitEvent,
} from "@spacebar/util";
import {
	APObject,
	APOrderedCollection,
	APPerson,
	AnyAPObject,
	ObjectIsGroup,
	ObjectIsOrganization,
	ObjectIsPerson,
} from "activitypub-types";
import { HTTPError } from "lambert-server";
import fetch from "node-fetch";
import { ProxyAgent } from "proxy-agent";
import TurndownService from "turndown";
import { federationQueue } from "./queue";
import { transformGroupToChannel } from "./transforms";
import { APFollowWithInvite } from "./types";

export const ACTIVITYSTREAMS_CONTEXT = "https://www.w3.org/ns/activitystreams";
export const LOG_NAMES = {
	webfinger: "Webfinger",
	remote: "Remote",
};

export const fetchOpts = Object.freeze(
	OrmUtils.mergeDeep(DEFAULT_FETCH_OPTIONS, {
		headers: {
			Accept: "application/activity+json",
			"Content-Type": "application/activity+json",
		},
	}),
);

export class APError extends HTTPError {}

export const hasAPContext = (data: object): data is APObject => {
	if (!("@context" in data)) return false;
	const context = data["@context"];
	if (Array.isArray(context))
		return !!context.find((x) => x == ACTIVITYSTREAMS_CONTEXT);
	return context == ACTIVITYSTREAMS_CONTEXT;
};

export const resolveAPObject = async <T extends AnyAPObject>(
	data: string | T,
): Promise<T> => {
	// we were already given an object
	if (typeof data != "string") return data;

	const cache = await FederationCache.findOne({ where: { id: data } });
	if (cache) return cache.toJSON() as T;

	Debug(LOG_NAMES.remote, `Fetching from remote ${data}`);

	const agent = new ProxyAgent();
	const ret = await fetch(data, {
		...fetchOpts,
		agent,
	});

	const json = await ret.json();

	if (!hasAPContext(json)) throw new APError("Object is not APObject");

	setImmediate(async () => {
		await FederationCache.create({ id: json.id, data: json }).save();
	});

	return json as T;
};

export const splitQualifiedMention = (lookup: string) => {
	let domain: string, user: string;
	if (lookup.includes("@")) {
		// lookup a @handle@domain

		if (lookup[0] == "@") lookup = lookup.slice(1);
		[user, domain] = lookup.split("@");
	} else {
		// lookup was a URL ( hopefully )
		try {
			const url = new URL(lookup);
			domain = url.hostname;
			user = url.pathname.split("/").reverse()[0];
		} catch (e) {
			domain = "";
			user = "";
		}
	}

	return {
		domain,
		user,
	};
};

export const resolveWebfinger = async (
	lookup: string,
): Promise<AnyAPObject> => {
	const { domain } = splitQualifiedMention(lookup);

	Debug(LOG_NAMES.webfinger, `Performing lookup ${lookup}`);

	const agent = new ProxyAgent();
	const wellknown = (await fetch(
		`https://${domain}/.well-known/webfinger?resource=${lookup}`,
		{
			agent,
			...fetchOpts,
		},
	).then((x) => x.json())) as WebfingerResponse;

	if (!("links" in wellknown))
		throw new APError(
			`webfinger did not return any links for actor ${lookup}`,
		);

	const link = wellknown.links.find((x) => x.rel == "self");
	if (!link) throw new APError(".well-known did not contain rel=self link");

	return await resolveAPObject<AnyAPObject>(link.href);
};

export const tryResolveWebfinger = async (lookup: string) => {
	try {
		return await resolveWebfinger(lookup);
	} catch (e) {
		console.error(`Error resolving webfinger ${lookup}`, e);
		return null;
	}
};

/** Fetch from local db, if not found fetch from remote instance and save */
export const fetchFederatedUser = async (
	actorId: string,
): Promise<{ keys: FederationKey; entity: BaseClass }> => {
	// if we were given webfinger, resolve that first
	const mention = splitQualifiedMention(actorId);
	const cache = await FederationKey.findOne({
		where: { username: mention.user, domain: mention.domain },
	});
	if (cache) {
		return {
			keys: cache,
			entity: await User.findOneOrFail({ where: { id: cache.actorId } }),
		};
	}

	// if we don't already have it, resolve webfinger
	const remoteActor = await resolveWebfinger(actorId);

	let type: ActorType;
	if (ObjectIsPerson(remoteActor)) type = ActorType.USER;
	else if (ObjectIsGroup(remoteActor)) type = ActorType.CHANNEL;
	else if (ObjectIsOrganization(remoteActor)) type = ActorType.GUILD;
	else
		throw new APError(
			`The remote actor '${actorId}' is not a Person, Group, or Organisation`,
		);

	if (
		typeof remoteActor.inbox != "string" ||
		typeof remoteActor.outbox != "string"
	)
		throw new APError("Actor inbox/outbox must be string");

	const keys = FederationKey.create({
		actorId: Snowflake.generate(),
		federatedId: actorId,
		username: remoteActor.name,
		// this is technically not correct
		// but it's slightly more difficult to go from actor url -> handle
		// so thats a problem for future me
		domain: mention.domain,
		publicKey: remoteActor.publicKey?.publicKeyPem,
		type,
		inbox: remoteActor.inbox,
		outbox: remoteActor.outbox,
	});

	let entity: BaseClass | undefined = undefined;
	if (type == ActorType.USER)
		entity = User.create({
			id: keys.actorId,
			username: remoteActor.name,
			discriminator: "0",
			bio: new TurndownService().turndown(remoteActor.summary), // html -> markdown
			email: `${remoteActor.preferredUsername}@${keys.domain}`,
			data: {
				hash: "#",
				valid_tokens_since: new Date(),
			},
			extended_settings: "{}",
			settings: UserSettings.create(),
			premium: false,

			premium_since: Config.get().defaults.user.premium
				? new Date()
				: undefined,
			rights: Config.get().register.defaultRights,
			premium_type: Config.get().defaults.user.premiumType ?? 0,
			verified: Config.get().defaults.user.verified ?? true,
			created_at: new Date(),
		});

	if (type == ActorType.GUILD)
		entity = Guild.create({
			id: keys.actorId,
			name: remoteActor.name,
			owner_id: (
				await fetchFederatedUser(remoteActor.attributedTo!.toString())
			).entity.id,
		});

	if (!entity) throw new APError("not possible :3");

	await Promise.all([keys.save(), entity.save()]);
	return {
		keys,
		entity,
	};
};

export const tryFederatedGuildJoin = async (code: string, user_id: string) => {
	const guild = await tryResolveWebfinger(code);
	if (!guild || !ObjectIsOrganization(guild))
		throw new APError(
			`Invite code did not produce Guild on remote server ${code}`,
		);

	const { host } = Config.get().federation;

	const follow = await FederationActivity.create({
		data: {
			"@context": ACTIVITYSTREAMS_CONTEXT,
			type: "Follow",
			actor: `https://${host}/federation/users/${user_id}`,
			object: guild.id,
			invite: code,
		} as APFollowWithInvite,
	}).save();

	await federationQueue.distribute(follow.toJSON());
};

export const createChannelsFromGuildFollows = async (
	endpoint: string,
	guild_id: string,
) => {
	const collection = (await resolveAPObject(endpoint)) as APOrderedCollection; // TODO: validation
	if (!collection.orderedItems)
		throw new APError("Guild followers did not contain orderedItems");

	// resolve every channel
	for (const channel of collection.orderedItems) {
		if (typeof channel == "string" || !ObjectIsGroup(channel)) continue;

		const guildchannel = await transformGroupToChannel(channel, guild_id);

		await emitEvent({
			event: "CHANNEL_CREATE",
			data: guildchannel,
			guild_id: guildchannel.guild_id,
		} as ChannelCreateEvent);
	}
};

export const APObjectIsSpacebarActor = (
	object: AnyAPObject,
): object is APPerson => {
	return (
		ObjectIsPerson(object) ||
		ObjectIsGroup(object) ||
		ObjectIsOrganization(object)
	);
};