Files
indiekit-endpoint-activitypub/lib/mastodon/routes/search.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

161 lines
5.5 KiB
JavaScript

/**
* Search endpoint for Mastodon Client API.
*
* GET /api/v2/search — search accounts, statuses, and hashtags
*/
import express from "express";
import { serializeStatus } from "../entities/status.js";
import { serializeAccount } from "../entities/account.js";
import { parseLimit } from "../helpers/pagination.js";
import { resolveRemoteAccount } from "../helpers/resolve-account.js";
import { tokenRequired } from "../middleware/token-required.js";
import { scopeRequired } from "../middleware/scope-required.js";
const router = express.Router(); // eslint-disable-line new-cap
// ─── GET /api/v2/search ─────────────────────────────────────────────────────
router.get("/api/v2/search", tokenRequired, scopeRequired("read", "read:search"), async (req, res, next) => {
try {
const collections = req.app.locals.mastodonCollections;
const baseUrl = `${req.protocol}://${req.get("host")}`;
const query = (req.query.q || "").trim();
const type = req.query.type; // "accounts", "statuses", "hashtags", or undefined (all)
const limit = parseLimit(req.query.limit);
const offset = Math.max(0, Number.parseInt(req.query.offset, 10) || 0);
const resolve = req.query.resolve === "true";
const pluginOptions = req.app.locals.mastodonPluginOptions || {};
if (!query) {
return res.json({ accounts: [], statuses: [], hashtags: [] });
}
const results = { accounts: [], statuses: [], hashtags: [] };
// ─── Account search ──────────────────────────────────────────────────
if (!type || type === "accounts") {
const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const nameRegex = new RegExp(escapedQuery, "i");
// Search followers and following by display name or handle
const accountDocs = [];
if (collections.ap_followers) {
const followers = await collections.ap_followers
.find({
$or: [
{ name: nameRegex },
{ preferredUsername: nameRegex },
{ url: nameRegex },
],
})
.limit(limit)
.toArray();
accountDocs.push(...followers);
}
if (collections.ap_following) {
const following = await collections.ap_following
.find({
$or: [
{ name: nameRegex },
{ preferredUsername: nameRegex },
{ url: nameRegex },
],
})
.limit(limit)
.toArray();
accountDocs.push(...following);
}
// Deduplicate by URL
const seen = new Set();
for (const doc of accountDocs) {
const url = doc.url || doc.id;
if (url && !seen.has(url)) {
seen.add(url);
results.accounts.push(
serializeAccount(doc, { baseUrl, isRemote: true }),
);
}
if (results.accounts.length >= limit) break;
}
// If no local results and resolve=true, try remote lookup
if (results.accounts.length === 0 && resolve && query.includes("@")) {
const resolved = await resolveRemoteAccount(query, pluginOptions, baseUrl);
if (resolved) {
results.accounts.push(resolved);
}
}
}
// ─── Status search ───────────────────────────────────────────────────
if (!type || type === "statuses") {
const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const contentRegex = new RegExp(escapedQuery, "i");
const items = await collections.ap_timeline
.find({
isContext: { $ne: true },
$or: [
{ "content.text": contentRegex },
{ "content.html": contentRegex },
],
})
.sort({ _id: -1 })
.skip(offset)
.limit(limit)
.toArray();
results.statuses = items.map((item) =>
serializeStatus(item, {
baseUrl,
favouritedIds: new Set(),
rebloggedIds: new Set(),
bookmarkedIds: new Set(),
pinnedIds: new Set(),
}),
);
}
// ─── Hashtag search ──────────────────────────────────────────────────
if (!type || type === "hashtags") {
const escapedQuery = query
.replace(/^#/, "")
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const tagRegex = new RegExp(escapedQuery, "i");
// Find distinct category values matching the query
const allCategories = await collections.ap_timeline.distinct("category", {
category: tagRegex,
});
// Flatten and deduplicate (category can be string or array)
const tagSet = new Set();
for (const cat of allCategories) {
if (Array.isArray(cat)) {
for (const c of cat) {
if (typeof c === "string" && tagRegex.test(c)) tagSet.add(c);
}
} else if (typeof cat === "string" && tagRegex.test(cat)) {
tagSet.add(cat);
}
}
results.hashtags = [...tagSet].slice(0, limit).map((name) => ({
name,
url: `${baseUrl}/tags/${encodeURIComponent(name)}`,
history: [],
}));
}
res.json(results);
} catch (error) {
next(error);
}
});
export default router;