Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
comment-moderation.test.ts11.5 KB · 374 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
 * Comment moderation tests — the anti-impersonation gate.
 *
 * Two halves:
 *   1. Pure-decision tests (`shouldRequireApproval`) — set up a repo
 *      with a fixed owner + a couple of commenters and assert each
 *      branch of the decision matrix (owner / write collab / read-only
 *      stranger / trusted / banned / thread-author).
 *   2. End-to-end POST → render flow — submit a comment as a stranger
 *      via `app.request`, confirm it lands as 'pending', isn't shown in
 *      the JSON API list, and that the approve flow promotes it.
 *
 * Every DB-touching test sits behind `describe.skipIf(!HAS_DB)` so the
 * suite stays green on machines without Postgres (mirroring the
 * established pattern across the repo's other test files).
 */

import { describe, it, expect } from "bun:test";

const HAS_DB = Boolean(process.env.DATABASE_URL);

describe.skipIf(!HAS_DB)("comment-moderation — shouldRequireApproval", () => {
  it("returns false for the repo owner", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const fx = await seed();
    const r = await shouldRequireApproval({
      commenterUserId: fx.ownerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(r.requireApproval).toBe(false);
  });

  it("returns false for a write collaborator", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const fx = await seed();
    await addCollaborator(fx.repoId, fx.writerId, "write");
    const r = await shouldRequireApproval({
      commenterUserId: fx.writerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(r.requireApproval).toBe(false);
  });

  it("returns true for a read-only stranger on a public repo", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const fx = await seed();
    const r = await shouldRequireApproval({
      commenterUserId: fx.strangerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(r.requireApproval).toBe(true);
    expect(r.autoReject).toBe(false);
  });

  it("returns false when the commenter has a 'trusted' trust row", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const { db } = await import("../db");
    const { repoCommenterTrust } = await import("../db/schema");
    const fx = await seed();
    await db.insert(repoCommenterTrust).values({
      repositoryId: fx.repoId,
      commenterUserId: fx.strangerId,
      status: "trusted",
      grantedByUserId: fx.ownerId,
    });
    const r = await shouldRequireApproval({
      commenterUserId: fx.strangerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(r.requireApproval).toBe(false);
  });

  it("returns false when the commenter is the original issue author", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const { db } = await import("../db");
    const { issues } = await import("../db/schema");
    const fx = await seed();
    // Open a SECOND issue authored by the stranger themselves so they
    // are the thread author (the seed issue is opened by `ownerId`).
    const [strangerIssue] = await db
      .insert(issues)
      .values({
        repositoryId: fx.repoId,
        authorId: fx.strangerId,
        title: "stranger-issue",
      })
      .returning({ id: issues.id });
    const r = await shouldRequireApproval({
      commenterUserId: fx.strangerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: strangerIssue!.id,
    });
    expect(r.requireApproval).toBe(false);
    expect(r.reason).toContain("opened this issue");
  });

  it("auto-rejects when the commenter is banned", async () => {
    const { shouldRequireApproval } = await import(
      "../lib/comment-moderation"
    );
    const { db } = await import("../db");
    const { repoCommenterTrust } = await import("../db/schema");
    const fx = await seed();
    await db.insert(repoCommenterTrust).values({
      repositoryId: fx.repoId,
      commenterUserId: fx.strangerId,
      status: "banned",
      grantedByUserId: fx.ownerId,
    });
    const r = await shouldRequireApproval({
      commenterUserId: fx.strangerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(r.requireApproval).toBe(true);
    expect(r.autoReject).toBe(true);
  });
});

describe.skipIf(!HAS_DB)("comment-moderation — POST + render flow", () => {
  it("inserts a stranger's comment as 'pending' and hides it from the public API", async () => {
    const app = (await import("../app")).default;
    const { db } = await import("../db");
    const { issueComments, sessions } = await import("../db/schema");
    const { eq } = await import("drizzle-orm");
    const { randomBytes } = await import("crypto");

    const fx = await seed();
    // Mint a stranger session.
    const token = randomBytes(32).toString("hex");
    await db.insert(sessions).values({
      userId: fx.strangerId,
      token,
      expiresAt: new Date(Date.now() + 60_000),
    });

    const res = await app.request(
      `/${fx.ownerUsername}/${fx.repoName}/issues/${fx.issueNumber}/comment`,
      {
        method: "POST",
        headers: {
          cookie: `session=${token}`,
          "content-type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({ body: "Hi from a stranger!" }),
      }
    );
    // Hono's c.redirect → 302
    expect([200, 302]).toContain(res.status);

    const inserted = await db
      .select()
      .from(issueComments)
      .where(eq(issueComments.authorId, fx.strangerId));
    expect(inserted.length).toBe(1);
    expect(inserted[0]!.moderationStatus).toBe("pending");

    // Public API hides pending.
    const apiRes = await app.request(
      `/api/v2/repos/${fx.ownerUsername}/${fx.repoName}/issues/${fx.issueNumber}`
    );
    if (apiRes.status === 200) {
      const json = (await apiRes.json()) as { comments: unknown[] };
      expect(Array.isArray(json.comments)).toBe(true);
      // The stranger's comment must not leak.
      const bodies = (json.comments as Array<{ body: string }>).map(
        (c) => c.body
      );
      expect(bodies.includes("Hi from a stranger!")).toBe(false);
    }
  });

  it("approve flow flips status to 'approved' and notifies the author", async () => {
    const { approveComment } = await import("../lib/comment-moderation");
    const { db } = await import("../db");
    const { issueComments, notifications } = await import("../db/schema");
    const { eq, and } = await import("drizzle-orm");

    const fx = await seed();
    // Seed a pending comment from the stranger directly.
    const [c] = await db
      .insert(issueComments)
      .values({
        issueId: fx.issueId,
        authorId: fx.strangerId,
        body: "Approve me please",
        moderationStatus: "pending",
      })
      .returning({ id: issueComments.id });

    const res = await approveComment({
      commentId: c!.id,
      kind: "issue",
      moderatorUserId: fx.ownerId,
    });
    expect(res.ok).toBe(true);

    const [after] = await db
      .select({ status: issueComments.moderationStatus })
      .from(issueComments)
      .where(eq(issueComments.id, c!.id));
    expect(after!.status).toBe("approved");

    // Notification fired.
    const notif = await db
      .select()
      .from(notifications)
      .where(
        and(
          eq(notifications.userId, fx.strangerId),
          eq(notifications.kind, "comment.approved")
        )
      );
    expect(notif.length).toBeGreaterThanOrEqual(1);
  });

  it("markAsSpam flow inserts a 'banned' trust row and auto-rejects next comment", async () => {
    const {
      markAsSpam,
      decideInitialStatus,
    } = await import("../lib/comment-moderation");
    const { db } = await import("../db");
    const { issueComments, repoCommenterTrust } = await import("../db/schema");
    const { eq, and } = await import("drizzle-orm");

    const fx = await seed();
    const [c] = await db
      .insert(issueComments)
      .values({
        issueId: fx.issueId,
        authorId: fx.strangerId,
        body: "Spammy stuff",
        moderationStatus: "pending",
      })
      .returning({ id: issueComments.id });

    const res = await markAsSpam({
      commentId: c!.id,
      kind: "issue",
      moderatorUserId: fx.ownerId,
    });
    expect(res.ok).toBe(true);

    // Banned trust row exists.
    const trust = await db
      .select({ status: repoCommenterTrust.status })
      .from(repoCommenterTrust)
      .where(
        and(
          eq(repoCommenterTrust.repositoryId, fx.repoId),
          eq(repoCommenterTrust.commenterUserId, fx.strangerId)
        )
      );
    expect(trust.length).toBe(1);
    expect(trust[0]!.status).toBe("banned");

    // Next comment auto-rejects.
    const decision = await decideInitialStatus({
      commenterUserId: fx.strangerId,
      repositoryId: fx.repoId,
      kind: "issue",
      threadId: fx.issueId,
    });
    expect(decision.status).toBe("rejected");
  });
});

// ─── seed helpers ─────────────────────────────────────────────────────

async function seed(): Promise<{
  ownerId: string;
  ownerUsername: string;
  writerId: string;
  strangerId: string;
  repoId: string;
  repoName: string;
  issueId: string;
  issueNumber: number;
}> {
  const { db } = await import("../db");
  const { users, repositories, issues } = await import("../db/schema");
  const { randomBytes } = await import("crypto");
  const tag = randomBytes(4).toString("hex");

  const [owner] = await db
    .insert(users)
    .values({
      username: `modq_owner_${tag}`,
      email: `modq_owner_${tag}@test.local`,
      passwordHash: "x",
    })
    .returning({ id: users.id, username: users.username });
  const [writer] = await db
    .insert(users)
    .values({
      username: `modq_writer_${tag}`,
      email: `modq_writer_${tag}@test.local`,
      passwordHash: "x",
    })
    .returning({ id: users.id });
  const [stranger] = await db
    .insert(users)
    .values({
      username: `modq_stranger_${tag}`,
      email: `modq_stranger_${tag}@test.local`,
      passwordHash: "x",
    })
    .returning({ id: users.id });
  const [repo] = await db
    .insert(repositories)
    .values({
      ownerId: owner!.id,
      name: `modq-repo-${tag}`,
      diskPath: `/tmp/modq/${tag}`,
      defaultBranch: "main",
      isPrivate: false,
    })
    .returning({ id: repositories.id, name: repositories.name });
  const [issue] = await db
    .insert(issues)
    .values({
      repositoryId: repo!.id,
      authorId: owner!.id,
      title: "Seed issue for moderation tests",
    })
    .returning({ id: issues.id, number: issues.number });

  return {
    ownerId: owner!.id,
    ownerUsername: owner!.username,
    writerId: writer!.id,
    strangerId: stranger!.id,
    repoId: repo!.id,
    repoName: repo!.name,
    issueId: issue!.id,
    issueNumber: issue!.number,
  };
}

async function addCollaborator(
  repoId: string,
  userId: string,
  role: "read" | "write" | "admin"
): Promise<void> {
  const { db } = await import("../db");
  const { repoCollaborators } = await import("../db/schema");
  await db.insert(repoCollaborators).values({
    repositoryId: repoId,
    userId,
    role,
    invitedBy: userId,
    acceptedAt: new Date(),
  });
}