Files
indiekit-endpoint-activitypub/lib/controllers/interactions-boost.js
Ricardo 12454749ad fix: comprehensive security, performance, and architecture audit fixes
27 issues fixed from multi-dimensional code review (4 Critical, 6 High, 11 Medium, 6 Low):

Security (Critical):
- Escape HTML in OAuth authorization page to prevent XSS (C1)
- Add CSRF protection to OAuth authorize flow (C2)
- Replace bypassable regex sanitizer with sanitize-html library (C3)
- Enforce OAuth scopes on all Mastodon API routes (C4)

Security (Medium/Low):
- Fix SSRF via DNS resolution before private IP check (M1)
- Add rate limiting to API, auth, and app registration endpoints (M2)
- Validate redirect_uri on POST /oauth/authorize (M4)
- Fix custom emoji URL injection with scheme validation + escaping (M5)
- Remove data: scheme from allowed image sources (L6)
- Add access token expiry (1hr) and refresh token rotation (90d) (M3)
- Hash client secrets before storage (L3)

Architecture:
- Extract batch-broadcast.js — shared delivery logic (H1a)
- Extract init-indexes.js — MongoDB index creation (H1b)
- Extract syndicator.js — syndication logic (H1c)
- Create federation-actions.js facade for controllers (M6)
- index.js reduced from 1810 to ~1169 lines (35%)

Performance:
- Cache moderation data with 30s TTL + write invalidation (H6)
- Increase inbox queue throughput to 10 items/sec (H5)
- Make account enrichment non-blocking with fire-and-forget (H4)
- Remove ephemeral getReplies/getLikes/getShares from ingest (M11)
- Fix LRU caches to use true LRU eviction (L1)
- Fix N+1 backfill queries with batch $in lookup (L2)

UI/UX:
- Split 3441-line reader.css into 15 feature-scoped files (H2)
- Extract inline Alpine.js interaction component (H3)
- Reduce sidebar navigation from 7 to 3 items (M7)
- Add ARIA live regions for dynamic content updates (M8)
- Extract shared CW/non-CW content partial (M9)
- Document form handling pattern convention (M10)
- Add accessible labels to functional emoji icons (L4)
- Convert profile editor to Alpine.js (L5)

Audit: documentation-central/audits/2026-03-24-activitypub-code-review.md
Plan: documentation-central/plans/2026-03-24-activitypub-audit-fixes.md
2026-03-25 07:41:20 +01:00

226 lines
6.1 KiB
JavaScript

/**
* Boost/Unboost interaction controllers.
* Sends Announce and Undo(Announce) activities via Fedify.
*/
import { validateToken } from "../csrf.js";
import { resolveAuthor } from "../resolve-author.js";
import { createContext, getHandle, getPublicationUrl, isFederationReady } from "../federation-actions.js";
/**
* POST /admin/reader/boost — send an Announce activity to followers.
*/
export function boostController(mountPath, plugin) {
return async (request, response, next) => {
try {
if (!validateToken(request)) {
return response.status(403).json({
success: false,
error: "Invalid CSRF token",
});
}
const { url } = request.body;
if (!url) {
return response.status(400).json({
success: false,
error: "Missing post URL",
});
}
if (!isFederationReady(plugin)) {
return response.status(503).json({
success: false,
error: "Federation not initialized",
});
}
const { Announce } = await import("@fedify/fedify/vocab");
const handle = getHandle(plugin);
const ctx = createContext(plugin);
const uuid = crypto.randomUUID();
const baseUrl = getPublicationUrl(plugin).replace(/\/$/, "");
const activityId = `${baseUrl}/activitypub/boosts/${uuid}`;
const publicAddress = new URL(
"https://www.w3.org/ns/activitystreams#Public",
);
const followersUri = ctx.getFollowersUri(handle);
// Construct Announce activity
const announce = new Announce({
id: new URL(activityId),
actor: ctx.getActorUri(handle),
object: new URL(url),
to: publicAddress,
cc: followersUri,
});
// Send to followers via shared inbox
await ctx.sendActivity({ identifier: handle }, "followers", announce, {
preferSharedInbox: true,
syncCollection: true,
orderingKey: url,
});
// Also send directly to the original post author
const documentLoader = await ctx.getDocumentLoader({
identifier: handle,
});
const { application } = request.app.locals;
const rsaKey = await plugin._loadRsaPrivateKey();
const recipient = await resolveAuthor(
url,
ctx,
documentLoader,
application?.collections,
{
privateKey: rsaKey,
keyId: `${ctx.getActorUri(handle).href}#main-key`,
},
);
if (recipient) {
try {
await ctx.sendActivity(
{ identifier: handle },
recipient,
announce,
{ orderingKey: url },
);
console.info(
`[ActivityPub] Sent boost directly to ${recipient.id?.href || "author"}`,
);
} catch (error) {
console.warn(
`[ActivityPub] Direct boost delivery to author failed:`,
error.message,
);
}
}
// Track the interaction
const interactions = application?.collections?.get("ap_interactions");
if (interactions) {
await interactions.updateOne(
{ objectUrl: url, type: "boost" },
{
$set: {
objectUrl: url,
type: "boost",
activityId,
createdAt: new Date().toISOString(),
},
},
{ upsert: true },
);
}
console.info(`[ActivityPub] Sent Announce (boost) for ${url}`);
return response.json({
success: true,
type: "boost",
objectUrl: url,
});
} catch (error) {
console.error("[ActivityPub] Boost failed:", error.message);
return response.status(500).json({
success: false,
error: "Boost failed. Please try again later.",
});
}
};
}
/**
* POST /admin/reader/unboost — send an Undo(Announce) to followers.
*/
export function unboostController(mountPath, plugin) {
return async (request, response, next) => {
try {
if (!validateToken(request)) {
return response.status(403).json({
success: false,
error: "Invalid CSRF token",
});
}
const { url } = request.body;
if (!url) {
return response.status(400).json({
success: false,
error: "Missing post URL",
});
}
if (!isFederationReady(plugin)) {
return response.status(503).json({
success: false,
error: "Federation not initialized",
});
}
const { application } = request.app.locals;
const interactions = application?.collections?.get("ap_interactions");
const existing = interactions
? await interactions.findOne({ objectUrl: url, type: "boost" })
: null;
if (!existing) {
return response.status(404).json({
success: false,
error: "No boost found for this post",
});
}
const { Announce, Undo } = await import("@fedify/fedify/vocab");
const handle = getHandle(plugin);
const ctx = createContext(plugin);
// Construct Undo(Announce)
const announce = new Announce({
id: existing.activityId ? new URL(existing.activityId) : undefined,
actor: ctx.getActorUri(handle),
object: new URL(url),
});
const undo = new Undo({
actor: ctx.getActorUri(handle),
object: announce,
});
// Send to followers
await ctx.sendActivity({ identifier: handle }, "followers", undo, {
preferSharedInbox: true,
syncCollection: true,
orderingKey: url,
});
// Remove the interaction record
if (interactions) {
await interactions.deleteOne({ objectUrl: url, type: "boost" });
}
console.info(`[ActivityPub] Sent Undo(Announce) for ${url}`);
return response.json({
success: true,
type: "unboost",
objectUrl: url,
});
} catch (error) {
console.error("[ActivityPub] Unboost failed:", error.message);
return response.status(500).json({
success: false,
error: "Unboost failed. Please try again later.",
});
}
};
}