Files
indiekit-endpoint-activitypub/lib/batch-broadcast.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

99 lines
3.0 KiB
JavaScript

/**
* Shared batch broadcast for delivering activities to all followers.
* Deduplicates by shared inbox and delivers in batches with delay.
* @module batch-broadcast
*/
import { logActivity } from "./activity-log.js";
const BATCH_SIZE = 25;
const BATCH_DELAY_MS = 5000;
/**
* Broadcast an activity to all followers via batch delivery.
*
* @param {object} options
* @param {object} options.federation - Fedify Federation instance
* @param {object} options.collections - MongoDB collections (needs ap_followers, ap_activities)
* @param {string} options.publicationUrl - Our publication URL
* @param {string} options.handle - Our actor handle
* @param {object} options.activity - Fedify activity object to send
* @param {string} options.label - Human-readable label for logging (e.g. "Update(Person)")
* @param {string} [options.objectUrl] - URL of the object being broadcast about
*/
export async function batchBroadcast({
federation,
collections,
publicationUrl,
handle,
activity,
label,
objectUrl,
}) {
const ctx = federation.createContext(new URL(publicationUrl), {
handle,
publicationUrl,
});
const followers = await collections.ap_followers
.find({})
.project({ actorUrl: 1, inbox: 1, sharedInbox: 1 })
.toArray();
// Deduplicate by shared inbox
const inboxMap = new Map();
for (const f of followers) {
const key = f.sharedInbox || f.inbox;
if (key && !inboxMap.has(key)) {
inboxMap.set(key, f);
}
}
const uniqueRecipients = [...inboxMap.values()];
let delivered = 0;
let failed = 0;
console.info(
`[ActivityPub] Broadcasting ${label} to ${uniqueRecipients.length} ` +
`unique inboxes (${followers.length} followers) in batches of ${BATCH_SIZE}`,
);
for (let i = 0; i < uniqueRecipients.length; i += BATCH_SIZE) {
const batch = uniqueRecipients.slice(i, i + BATCH_SIZE);
const recipients = batch.map((f) => ({
id: new URL(f.actorUrl),
inboxId: new URL(f.inbox || f.sharedInbox),
endpoints: f.sharedInbox
? { sharedInbox: new URL(f.sharedInbox) }
: undefined,
}));
try {
await ctx.sendActivity({ identifier: handle }, recipients, activity, {
preferSharedInbox: true,
});
delivered += batch.length;
} catch (error) {
failed += batch.length;
console.warn(
`[ActivityPub] ${label} batch ${Math.floor(i / BATCH_SIZE) + 1} failed: ${error.message}`,
);
}
if (i + BATCH_SIZE < uniqueRecipients.length) {
await new Promise((resolve) => setTimeout(resolve, BATCH_DELAY_MS));
}
}
console.info(
`[ActivityPub] ${label} broadcast complete: ${delivered} delivered, ${failed} failed`,
);
await logActivity(collections.ap_activities, {
direction: "outbound",
type: label.includes("(") ? label.split("(")[0] : label,
actorUrl: publicationUrl,
objectUrl: objectUrl || "",
summary: `Sent ${label} to ${delivered}/${uniqueRecipients.length} inboxes`,
}).catch(() => {});
}