|
1 | 1 | /** |
2 | | - * Comment spam moderation — pure scoring logic. |
| 2 | + * Comment spam moderation — scoring logic + orchestration. |
3 | 3 | * |
4 | | - * Extracted from .github/workflows/squad-comment-moderation.yml so the |
5 | | - * scoring heuristics can be unit-tested independently of the GitHub |
6 | | - * Actions runtime. All functions are pure (no API calls) — the workflow |
7 | | - * remains the thin orchestrator that fetches data and acts on results. |
| 4 | + * All scoring heuristics are pure functions (no API calls). The `run()` |
| 5 | + * function is the orchestrator: it reads context from environment |
| 6 | + * variables, calls the GitHub API via `fetch`, scores the comment, and |
| 7 | + * takes action (minimize + post notice) when the score exceeds the |
| 8 | + * threshold. |
| 9 | + * |
| 10 | + * The workflow invokes this script via `node scripts/comment-moderation.mjs`. |
8 | 11 | * |
9 | 12 | * Issue: #751 |
10 | 13 | */ |
11 | 14 |
|
| 15 | +import { fileURLToPath } from 'node:url'; |
| 16 | + |
12 | 17 | // --------------------------------------------------------------------------- |
13 | 18 | // Constants |
14 | 19 | // --------------------------------------------------------------------------- |
@@ -145,3 +150,146 @@ export function buildModerationNotice(signals, repoOwner, repoName) { |
145 | 150 | `*This check is automated. See [comment-spam-protection proposal](https://github.com/${repoOwner}/${repoName}/blob/dev/docs/proposals/comment-spam-protection.md) for details.*`, |
146 | 151 | ].join('\n'); |
147 | 152 | } |
| 153 | + |
| 154 | +// --------------------------------------------------------------------------- |
| 155 | +// Orchestration |
| 156 | +// --------------------------------------------------------------------------- |
| 157 | + |
| 158 | +/** |
| 159 | + * Full moderation orchestrator. Reads context, scores the comment, |
| 160 | + * and takes action when the spam threshold is met. |
| 161 | + * |
| 162 | + * Dependencies (`env` and `fetchFn`) are injectable for testing. |
| 163 | + * |
| 164 | + * @param {object} [opts] |
| 165 | + * @param {Record<string,string>} [opts.env] - Environment variables |
| 166 | + * (defaults to `process.env`). |
| 167 | + * @param {typeof globalThis.fetch} [opts.fetchFn] - Fetch implementation |
| 168 | + * (defaults to global `fetch`). |
| 169 | + * @returns {Promise<{ action: string, score?: number, signals?: string[], reason?: string }>} |
| 170 | + */ |
| 171 | +export async function run({ env = process.env, fetchFn = globalThis.fetch } = {}) { |
| 172 | + const token = env.GITHUB_TOKEN; |
| 173 | + const commentBody = env.COMMENT_BODY || ''; |
| 174 | + const commentUser = env.COMMENT_USER; |
| 175 | + const commentUserType = env.COMMENT_USER_TYPE; |
| 176 | + const commentAssoc = env.COMMENT_ASSOCIATION; |
| 177 | + const commentNodeId = env.COMMENT_NODE_ID; |
| 178 | + const repoOwner = env.REPO_OWNER; |
| 179 | + const repoName = env.REPO_NAME; |
| 180 | + const issueNumber = env.ISSUE_NUMBER; |
| 181 | + |
| 182 | + // --- Skip trusted / bot authors --- |
| 183 | + if (shouldSkipComment(commentAssoc, commentUserType)) { |
| 184 | + console.log(`Skipping: author_association=${commentAssoc}, sender.type=${commentUserType}`); |
| 185 | + return { action: 'skipped', reason: 'trusted_or_bot' }; |
| 186 | + } |
| 187 | + |
| 188 | + // --- Fetch account age --- |
| 189 | + let userAgeDays = null; |
| 190 | + let userLookupFailed = false; |
| 191 | + try { |
| 192 | + const res = await fetchFn(`https://api.github.com/users/${encodeURIComponent(commentUser)}`, { |
| 193 | + headers: { |
| 194 | + Authorization: `token ${token}`, |
| 195 | + Accept: 'application/vnd.github+json', |
| 196 | + 'User-Agent': 'squad-comment-moderation', |
| 197 | + }, |
| 198 | + }); |
| 199 | + if (res.ok) { |
| 200 | + const user = await res.json(); |
| 201 | + userAgeDays = (Date.now() - new Date(user.created_at).getTime()) / (1000 * 60 * 60 * 24); |
| 202 | + } else { |
| 203 | + userLookupFailed = true; |
| 204 | + } |
| 205 | + } catch { |
| 206 | + userLookupFailed = true; |
| 207 | + } |
| 208 | + |
| 209 | + // --- Score --- |
| 210 | + const { score, signals } = scoreComment({ |
| 211 | + body: commentBody, |
| 212 | + authorAssociation: commentAssoc, |
| 213 | + userAgeDays, |
| 214 | + userLookupFailed, |
| 215 | + }); |
| 216 | + |
| 217 | + console.log(`Spam score: ${score}/${SPAM_THRESHOLD} threshold | Signals: ${signals.join(', ') || 'none'}`); |
| 218 | + |
| 219 | + if (score < SPAM_THRESHOLD) { |
| 220 | + console.log('Below threshold — no action taken.'); |
| 221 | + return { action: 'none', score, signals }; |
| 222 | + } |
| 223 | + |
| 224 | + // --- Act: minimize comment --- |
| 225 | + console.log(`⚠️ Spam detected (score=${score}). Minimizing comment.`); |
| 226 | + try { |
| 227 | + const gqlRes = await fetchFn('https://api.github.com/graphql', { |
| 228 | + method: 'POST', |
| 229 | + headers: { |
| 230 | + Authorization: `bearer ${token}`, |
| 231 | + 'Content-Type': 'application/json', |
| 232 | + 'User-Agent': 'squad-comment-moderation', |
| 233 | + }, |
| 234 | + body: JSON.stringify({ |
| 235 | + query: `mutation($id: ID!) { |
| 236 | + minimizeComment(input: { subjectId: $id, classifier: SPAM }) { |
| 237 | + minimizedComment { isMinimized } |
| 238 | + } |
| 239 | + }`, |
| 240 | + variables: { id: commentNodeId }, |
| 241 | + }), |
| 242 | + }); |
| 243 | + if (!gqlRes.ok) { |
| 244 | + console.error(`GraphQL request failed: ${gqlRes.status}`); |
| 245 | + } else { |
| 246 | + console.log('Comment minimized successfully.'); |
| 247 | + } |
| 248 | + } catch (e) { |
| 249 | + console.error(`Failed to minimize comment: ${e.message}`); |
| 250 | + } |
| 251 | + |
| 252 | + // --- Act: post moderation notice --- |
| 253 | + const notice = buildModerationNotice(signals, repoOwner, repoName); |
| 254 | + if (issueNumber) { |
| 255 | + try { |
| 256 | + const noticeRes = await fetchFn( |
| 257 | + `https://api.github.com/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/issues/${issueNumber}/comments`, |
| 258 | + { |
| 259 | + method: 'POST', |
| 260 | + headers: { |
| 261 | + Authorization: `token ${token}`, |
| 262 | + 'Content-Type': 'application/json', |
| 263 | + Accept: 'application/vnd.github+json', |
| 264 | + 'User-Agent': 'squad-comment-moderation', |
| 265 | + }, |
| 266 | + body: JSON.stringify({ body: notice }), |
| 267 | + }, |
| 268 | + ); |
| 269 | + if (!noticeRes.ok) { |
| 270 | + console.error(`Failed to post notice: ${noticeRes.status}`); |
| 271 | + } else { |
| 272 | + console.log('Moderation notice posted.'); |
| 273 | + } |
| 274 | + } catch (e) { |
| 275 | + console.error(`Failed to post notice: ${e.message}`); |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + return { action: 'moderated', score, signals }; |
| 280 | +} |
| 281 | + |
| 282 | +// --------------------------------------------------------------------------- |
| 283 | +// CLI entry point — run when invoked directly via `node scripts/comment-moderation.mjs` |
| 284 | +// --------------------------------------------------------------------------- |
| 285 | + |
| 286 | +if (process.argv[1] === fileURLToPath(import.meta.url)) { |
| 287 | + run().then((result) => { |
| 288 | + if (result.action === 'moderated') { |
| 289 | + process.exitCode = 0; |
| 290 | + } |
| 291 | + }).catch((err) => { |
| 292 | + console.error('Moderation script failed:', err); |
| 293 | + process.exitCode = 1; |
| 294 | + }); |
| 295 | +} |
0 commit comments