Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e5c65d5
feat(graphql): add lookupWebFinger query for remote follow
dodok8 Mar 2, 2026
e68ab2d
feat(web-next): add ViewerContext for auth state
dodok8 Mar 2, 2026
1af4801
feat(web-next): add RemoteFollowButton and onFollowed callback
dodok8 Mar 2, 2026
f0d5098
feat(web-next): add authorize_interaction page
dodok8 Mar 2, 2026
fdd9f70
feat(i18n): add translations for remote follow UI
dodok8 Mar 2, 2026
f747249
fix: apply codereview
dodok8 Mar 2, 2026
cec4eae
format: authorize-interaction
dodok8 Mar 2, 2026
d798b88
fix: add missing generated file
dodok8 Mar 2, 2026
2a99d49
Change Regex pattern to match client
dodok8 Mar 2, 2026
abccda9
Add protocol validation before open
dodok8 Mar 2, 2026
a2bb9bf
fix: add per-emoji try/catch in tag extraction loop
dodok8 Mar 2, 2026
c3f4f0f
Split authorize_interaction into two components to avoid unnecessary …
dodok8 Mar 2, 2026
e9b6c7f
Add isLoaded to ViewerContext to prevent FollowButton flash
dodok8 Mar 2, 2026
2bee533
Use named ViewerProviderProps interface
dodok8 Mar 2, 2026
380a354
Use URL scalar for WebFingerResult and add explicit return types
dodok8 Mar 2, 2026
33b0093
Remove extra text from zh-TW follow translation
dodok8 Mar 2, 2026
b942ddd
Rename lookupWebFinger query to lookupRemoteFollower with stronger types
dodok8 Mar 2, 2026
3f85acc
Tighten ActivityPub link matching in WebFinger lookup
dodok8 Mar 2, 2026
20f4608
Add acct: prefix strip
dodok8 Mar 2, 2026
460bb6d
Update translation source references after code changes
dodok8 Mar 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions graphql/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import "./reactable.ts";
import "./search.ts";
import "./signup.ts";
import "./timeline.ts";
import "./webfinger.ts";
export type { UserContext as Context } from "./builder.ts";
export { createYogaServer } from "./server.ts";

Expand Down
31 changes: 30 additions & 1 deletion graphql/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,19 @@ type Query {

"""Returns all accounts as a flat array for building the invitation tree."""
invitationTree: [InvitationTreeNode!]!

"""
Look up a remote Fediverse user by their handle, fetching their ActivityPub profile and constructing a remote follow URL for the given actor.
"""
lookupRemoteFollower(
"""The Relay global ID of the Hackers' Pub actor to be followed."""
actorId: ID!

"""
The Fediverse handle of the remote user who wants to follow (e.g., @user@mastodon.social).
"""
followerHandle: String!
): WebFingerResult
markdownGuide(
"""The locale for the Markdown guide."""
locale: Locale!
Expand Down Expand Up @@ -1367,4 +1380,20 @@ type UploadMediaPayload {
width: Int!
}

union UploadMediaResult = InvalidInputError | NotAuthenticatedError | UploadMediaPayload
union UploadMediaResult = InvalidInputError | NotAuthenticatedError | UploadMediaPayload

"""
Result of looking up a remote follower via WebFinger, including their ActivityPub profile and remote follow URL.
"""
type WebFingerResult {
domain: String
emojis: JSON
handle: String
iconUrl: URL
name: String
preferredUsername: String
remoteFollowUrl: URL
software: String
summary: String
url: URL
}
277 changes: 277 additions & 0 deletions graphql/webfinger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
import { getNodeInfo } from "@fedify/fedify";
import * as vocab from "@fedify/vocab";
import { isActor } from "@fedify/vocab";
import type { Actor as FedifyActor } from "@fedify/vocab";
import { validateUuid } from "@hackerspub/models/uuid";
import { getLogger } from "@logtape/logtape";
import { Actor } from "./actor.ts";
import { builder, type UserContext } from "./builder.ts";

const logger = getLogger(["hackerspub", "graphql", "webfinger"]);

const FEDIVERSE_ID_REGEX =
/^@?([a-zA-Z0-9_.-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;

interface WebfingerLink {
rel?: string;
type?: string;
href?: string;
template?: string;
}

interface WebFingerResultData {
preferredUsername: string | null;
name: string | null;
summary: string | null;
url: URL | null;
iconUrl: URL | null;
handle: string | null;
domain: string | null;
software: string | null;
emojis: Record<string, string> | null;
remoteFollowUrl: URL | null;
}

const WebFingerResult = builder.simpleObject("WebFingerResult", {
description: "Result of looking up a remote follower via WebFinger, " +
"including their ActivityPub profile and remote follow URL.",
fields: (t) => ({
preferredUsername: t.string({ nullable: true }),
name: t.string({ nullable: true }),
summary: t.string({ nullable: true }),
url: t.field({ type: "URL", nullable: true }),
iconUrl: t.field({ type: "URL", nullable: true }),
handle: t.string({ nullable: true }),
domain: t.string({ nullable: true }),
software: t.string({ nullable: true }),
emojis: t.field({ type: "JSON", nullable: true }),
remoteFollowUrl: t.field({ type: "URL", nullable: true }),
}),
});

async function buildWebFingerResult(
actorObject: FedifyActor,
normalizedId: string,
domain: string,
remoteFollowUrl?: URL,
): Promise<WebFingerResultData> {
let software = "unknown";
try {
const nodeInfo = await getNodeInfo(`https://${domain}`);
if (nodeInfo?.software?.name) {
software = nodeInfo.software.name.toLowerCase();
}
} catch (error) {
logger.warn("Failed to get nodeinfo for {domain}: {error}", {
domain,
error: error instanceof Error ? error.message : String(error),
});
}

let iconUrl: URL | null = null;
const icon = await actorObject.getIcon();
if (icon) {
const raw = icon.url instanceof URL
? icon.url.href
: icon.url?.href?.href ?? null;
if (raw) iconUrl = new URL(raw);
}
if (!iconUrl && actorObject.iconId) {
iconUrl = new URL(actorObject.iconId.href);
}

const emojis: Record<string, string> = {};
try {
for await (const tag of actorObject.getTags()) {
if (!(tag instanceof vocab.Emoji)) continue;
try {
if (tag.name == null) continue;
const emojiIcon = await tag.getIcon();
if (
emojiIcon?.url == null ||
emojiIcon.url instanceof vocab.Link && emojiIcon.url.href == null
) {
continue;
}
const emojiName = tag.name.toString();
const raw = emojiIcon.url instanceof vocab.Link
? emojiIcon.url.href!.href
: emojiIcon.url.href;
const u = new URL(raw);
if (
(u.protocol === "http:" || u.protocol === "https:") &&
!/[\'\"]/.test(raw)
) {
emojis[emojiName] = u.href;
}
} catch (error) {
logger.warn("Failed to extract emoji {name}: {error}", {
name: tag.name?.toString() ?? "unknown",
error: error instanceof Error ? error.message : String(error),
});
}
}
} catch (error) {
logger.warn("Failed to iterate tags: {error}", {
error: error instanceof Error ? error.message : String(error),
});
}

return {
preferredUsername: actorObject.preferredUsername?.toString() ?? null,
name: actorObject.name?.toString() ?? null,
summary: actorObject.summary?.toString() ?? null,
url: actorObject.url instanceof URL
? actorObject.url
: actorObject.url?.toString()
? new URL(actorObject.url.toString())
: null,
iconUrl,
handle: normalizedId,
domain,
software,
emojis: Object.keys(emojis).length > 0 ? emojis : null,
remoteFollowUrl: remoteFollowUrl ?? null,
};
}

async function lookupRemoteFollowerImpl(
ctx: UserContext,
followerHandle: string,
actorHandle: string,
): Promise<WebFingerResultData | null> {
const match = followerHandle.trim().match(FEDIVERSE_ID_REGEX);
if (!match) return null;

const [, username, domain] = match;
const normalizedId = `${username}@${domain}`;

logger.info("Looking up remote follower {followerHandle}", {
followerHandle: normalizedId,
});

const webfingerResult = await ctx.fedCtx.lookupWebFinger(
`acct:${normalizedId}`,
);
if (webfingerResult == null) return null;

const activityPubLink = webfingerResult.links?.find((link) =>
link.type === "application/activity+json" ||
(link.rel === "self" && link.type?.includes("activity"))
) as WebfingerLink | undefined;

if (!activityPubLink?.href) return null;

const remoteFollowLink = webfingerResult.links?.find((link) =>
link.rel === "http://ostatus.org/schema/1.0/subscribe"
) as WebfingerLink | undefined;

let remoteFollowUrl: URL | undefined;
if (remoteFollowLink?.template?.includes("{uri}")) {
const candidate = remoteFollowLink.template.replace(
"{uri}",
encodeURIComponent(actorHandle),
);
try {
const u = new URL(candidate);
if (u.protocol === "http:" || u.protocol === "https:") {
remoteFollowUrl = u;
}
} catch {
// invalid URL template, ignore
}
}

try {
const documentLoader = ctx.account == null
? ctx.fedCtx.documentLoader
: await ctx.fedCtx.getDocumentLoader({ identifier: ctx.account.id });

const actorObject = await ctx.fedCtx.lookupObject(activityPubLink.href, {
documentLoader,
});

if (!isActor(actorObject)) {
throw new Error("Object is not an actor");
}

return await buildWebFingerResult(
actorObject,
normalizedId,
domain,
remoteFollowUrl,
);
} catch (error) {
logger.warn(
"ActivityPub lookup failed, using fallback: {error}",
{
error: error instanceof Error ? error.message : String(error),
},
);

return {
preferredUsername: username,
name: username,
summary: null,
url: new URL(activityPubLink.href),
iconUrl: null,
handle: normalizedId,
domain,
software: "unknown",
emojis: null,
remoteFollowUrl: remoteFollowUrl ?? null,
};
}
}

builder.queryFields((t) => ({
lookupRemoteFollower: t.field({
description: "Look up a remote Fediverse user by their handle, " +
"fetching their ActivityPub profile and constructing " +
"a remote follow URL for the given actor.",
type: WebFingerResult,
nullable: true,
args: {
followerHandle: t.arg.string({
required: true,
description:
"The Fediverse handle of the remote user who wants to follow " +
"(e.g., @user@mastodon.social).",
}),
actorId: t.arg.globalID({
required: true,
for: [Actor],
description:
"The Relay global ID of the Hackers' Pub actor to be followed.",
}),
},
async resolve(_, args, ctx) {
try {
if (
args.actorId.typename !== "Actor" ||
!validateUuid(args.actorId.id)
) {
return null;
}

const actor = await ctx.db.query.actorTable.findFirst({
where: { id: args.actorId.id },
columns: { handle: true },
});

if (!actor) return null;

return await lookupRemoteFollowerImpl(
ctx,
args.followerHandle,
actor.handle,
);
} catch (error) {
logger.error("Remote follower lookup error: {error}", {
error: error instanceof Error ? error.message : String(error),
});
return null;
}
},
}),
}));
Loading
Loading