Skip to content

Commit 6a94226

Browse files
diberryCopilot
andcommitted
refactor(ci): remove all inline JS from moderation workflow
Move orchestration logic (user lookup, scoring, comment minimize, notice posting) from inline actions/github-script block into the standalone scripts/comment-moderation.mjs module. The workflow now uses a plain \ un: node scripts/comment-moderation.mjs\ step with env vars. - Add run() orchestrator with injectable fetch for testability - Use native fetch (Node 18+) for GitHub REST + GraphQL API calls - Add 11 orchestration tests (skip, threshold, minimize, notice, errors) - Workflow YAML now has ZERO JavaScript — only YAML with run: steps All 46 tests pass. Closes #753 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 4eacfaf commit 6a94226

3 files changed

Lines changed: 336 additions & 93 deletions

File tree

‎.github/workflows/squad-comment-moderation.yml‎

Lines changed: 14 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -33,88 +33,17 @@ jobs:
3333
sparse-checkout: scripts/comment-moderation.mjs
3434
sparse-checkout-cone-mode: false
3535

36-
- name: Check comment for spam signals
37-
uses: actions/github-script@v7
38-
with:
39-
script: |
40-
const {
41-
shouldSkipComment,
42-
scoreComment,
43-
buildModerationNotice,
44-
SPAM_THRESHOLD,
45-
} = await import(`${process.env.GITHUB_WORKSPACE}/scripts/comment-moderation.mjs`);
46-
47-
const comment = context.payload.comment;
48-
const sender = context.payload.sender;
49-
50-
// --- Skip trusted / bot authors ---
51-
if (shouldSkipComment(comment.author_association, sender.type)) {
52-
console.log(`Skipping: author_association=${comment.author_association}, sender.type=${sender.type}`);
53-
return;
54-
}
55-
56-
// --- Fetch account age (not available in webhook payload) ---
57-
let userAgeDays = null;
58-
let userLookupFailed = false;
59-
try {
60-
const { data: user } = await github.rest.users.getByUsername({
61-
username: sender.login,
62-
});
63-
userAgeDays = (Date.now() - new Date(user.created_at).getTime()) / (1000 * 60 * 60 * 24);
64-
} catch (e) {
65-
userLookupFailed = true;
66-
}
67-
68-
// --- Score ---
69-
const { score, signals } = scoreComment({
70-
body: comment.body || '',
71-
authorAssociation: comment.author_association,
72-
userAgeDays,
73-
userLookupFailed,
74-
});
75-
76-
console.log(`Spam score: ${score}/${SPAM_THRESHOLD} threshold | Signals: ${signals.join(', ') || 'none'}`);
77-
78-
if (score < SPAM_THRESHOLD) {
79-
console.log('Below threshold — no action taken.');
80-
return;
81-
}
82-
83-
// --- Act: minimize comment ---
84-
console.log(`⚠️ Spam detected (score=${score}). Minimizing comment.`);
85-
86-
try {
87-
await github.graphql(`
88-
mutation($id: ID!) {
89-
minimizeComment(input: { subjectId: $id, classifier: SPAM }) {
90-
minimizedComment { isMinimized }
91-
}
92-
}
93-
`, { id: comment.node_id });
94-
console.log('Comment minimized successfully.');
95-
} catch (e) {
96-
console.error(`Failed to minimize comment: ${e.message}`);
97-
}
98-
99-
// --- Act: post moderation notice ---
100-
const notice = buildModerationNotice(
101-
signals,
102-
context.repo.owner,
103-
context.repo.repo,
104-
);
105-
106-
try {
107-
const issueNumber = context.payload.issue?.number
108-
?? context.payload.pull_request?.number;
109-
if (issueNumber) {
110-
await github.rest.issues.createComment({
111-
owner: context.repo.owner,
112-
repo: context.repo.repo,
113-
issue_number: issueNumber,
114-
body: notice,
115-
});
116-
}
117-
console.log('Moderation notice posted.');
118-
} catch (e) {
119-
console.error(`Failed to post notice: ${e.message}`);
120-
}
36+
- name: Moderate comment
37+
env:
38+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
39+
COMMENT_ID: ${{ github.event.comment.id }}
40+
COMMENT_NODE_ID: ${{ github.event.comment.node_id }}
41+
COMMENT_BODY: ${{ github.event.comment.body }}
42+
COMMENT_USER: ${{ github.event.comment.user.login }}
43+
COMMENT_USER_TYPE: ${{ github.event.comment.user.type }}
44+
COMMENT_ASSOCIATION: ${{ github.event.comment.author_association }}
45+
COMMENT_CREATED: ${{ github.event.comment.created_at }}
46+
REPO_OWNER: ${{ github.repository_owner }}
47+
REPO_NAME: ${{ github.event.repository.name }}
48+
ISSUE_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}
49+
run: node scripts/comment-moderation.mjs

‎scripts/comment-moderation.mjs‎

Lines changed: 153 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
11
/**
2-
* Comment spam moderation — pure scoring logic.
2+
* Comment spam moderation — scoring logic + orchestration.
33
*
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`.
811
*
912
* Issue: #751
1013
*/
1114

15+
import { fileURLToPath } from 'node:url';
16+
1217
// ---------------------------------------------------------------------------
1318
// Constants
1419
// ---------------------------------------------------------------------------
@@ -145,3 +150,146 @@ export function buildModerationNotice(signals, repoOwner, repoName) {
145150
`*This check is automated. See [comment-spam-protection proposal](https://github.com/${repoOwner}/${repoName}/blob/dev/docs/proposals/comment-spam-protection.md) for details.*`,
146151
].join('\n');
147152
}
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

Comments
 (0)