Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔒 fix(acceptance): close the holes the open discussion opened (#19448)

Arvin Xu1eacff997eca
diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
index 02ee9132524..271e7a8e930 100644
--- a/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
@@ -2,8 +2,15 @@
import { randomUUID } from 'node:crypto';
import { type LobeChatDatabase } from '@lobechat/database';
-import { acceptances, verifyRuns } from '@lobechat/database/schemas';
+import {
+ acceptances,
+ agents,
+ verifyRuns,
+ workspaceMembers,
+ workspaces,
+} from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { acceptanceCommentRouter } from '../acceptanceComment';
@@ -134,9 +141,211 @@ describe('acceptanceCommentRouter access', () => {
expect(data.resolvedAt).not.toBeNull();
});
+ it("lets the creator take down a visitor's remark", async () => {
+ const { data: theirs } = await comment(visitorId, publicAcceptanceId, 'buy my thing');
+
+ const { data } = await caller(ownerId).delete({ id: theirs.id });
+
+ expect(data.deleted).toBe(true);
+ });
+
+ it("refuses a visitor taking down the creator's remark", async () => {
+ const { data: owned } = await comment(ownerId, publicAcceptanceId, 'round 1 is up');
+
+ await expect(caller(visitorId).delete({ id: owned.id })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+
+ // The discussion is open to whoever holds the link, so the cost of flooding
+ // it has to land somewhere.
+ it('refuses a visitor who floods the discussion', async () => {
+ for (let index = 0; index < 10; index++)
+ await comment(visitorId, publicAcceptanceId, `remark ${index}`);
+
+ await expect(comment(visitorId, publicAcceptanceId, 'and one more')).rejects.toMatchObject({
+ code: 'TOO_MANY_REQUESTS',
+ });
+ });
+
+ // The ceiling is charged where the row is written, so a lost response that
+ // gets retried answers with the row it already wrote.
+ it('lets a visitor retry the remark that reached the ceiling', async () => {
+ let lastClientId = '';
+ for (let index = 0; index < 10; index++) {
+ lastClientId = `c-${randomUUID()}`;
+ await caller(visitorId).create({
+ acceptanceId: publicAcceptanceId,
+ clientId: lastClientId,
+ content: `remark ${index}`,
+ });
+ }
+
+ const { data } = await caller(visitorId).create({
+ acceptanceId: publicAcceptanceId,
+ clientId: lastClientId,
+ content: 'remark 9',
+ });
+
+ expect(data.content).toBe('remark 9');
+ });
+
+ // The refusal rolls the write back with it: a rejected remark must not be
+ // half-written, or the next window starts already over the line.
+ it('writes nothing when the ceiling refuses a remark', async () => {
+ for (let index = 0; index < 10; index++)
+ await comment(visitorId, publicAcceptanceId, `remark ${index}`);
+ const before = await caller(visitorId).list({ acceptanceId: publicAcceptanceId });
+
+ await expect(comment(visitorId, publicAcceptanceId, 'one too many')).rejects.toMatchObject({
+ code: 'TOO_MANY_REQUESTS',
+ });
+
+ const after = await caller(visitorId).list({ acceptanceId: publicAcceptanceId });
+ expect(after.items).toHaveLength(before.items.length);
+ });
+
+ it('does not throttle the creator publishing a round', async () => {
+ for (let index = 0; index < 12; index++)
+ await comment(ownerId, publicAcceptanceId, `note ${index}`);
+
+ await expect(comment(ownerId, publicAcceptanceId, 'still fine')).resolves.toBeTruthy();
+ });
+
it('keeps a private acceptance invisible to a visitor', async () => {
await expect(comment(visitorId, privateAcceptanceId, 'hello?')).rejects.toMatchObject({
code: 'NOT_FOUND',
});
});
});
+
+/**
+ * An acceptance filed in a workspace carries that workspace's agents in its
+ * discussion payload. Opening the link hands a stranger those ids; it must not
+ * hand them the right to post under them.
+ */
+describe('acceptanceCommentRouter workspace scoping', () => {
+ let serverDB: LobeChatDatabase;
+ let ownerId: string;
+ let viewerId: string;
+ let visitorId: string;
+ let workspaceId: string;
+ let workspaceAgentId: string;
+ let openAcceptanceId: string;
+ let closedAcceptanceId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ ownerId = await createTestUser(serverDB);
+ viewerId = await createTestUser(serverDB);
+ visitorId = await createTestUser(serverDB);
+
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'Delivery team', primaryOwnerId: ownerId, slug: `ws-${ownerId}` })
+ .returning();
+ workspaceId = workspace.id;
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId: ownerId, workspaceId },
+ { role: 'viewer', userId: viewerId, workspaceId },
+ ]);
+
+ workspaceAgentId = `agt_${randomUUID()}`;
+ await serverDB.insert(agents).values({
+ id: workspaceAgentId,
+ slug: workspaceAgentId,
+ title: 'Delivery Bot',
+ userId: ownerId,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ const [open, closed] = await serverDB
+ .insert(acceptances)
+ .values([
+ {
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ])
+ .returning();
+ openAcceptanceId = open.id;
+ closedAcceptanceId = closed.id;
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await cleanupTestUser(serverDB, visitorId);
+ await cleanupTestUser(serverDB, viewerId);
+ await cleanupTestUser(serverDB, ownerId);
+ vi.clearAllMocks();
+ });
+
+ const caller = (userId: string) =>
+ acceptanceCommentRouter.createCaller({ jwtPayload: { userId }, userId } as any);
+
+ it("refuses a visitor signing as the workspace's agent", async () => {
+ await expect(
+ caller(visitorId).create({
+ acceptanceId: openAcceptanceId,
+ authorAgentId: workspaceAgentId,
+ clientId: `c-${randomUUID()}`,
+ content: 'looks done to me',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it("lets the creator sign as the workspace's agent", async () => {
+ const { data } = await caller(ownerId).create({
+ acceptanceId: openAcceptanceId,
+ authorAgentId: workspaceAgentId,
+ clientId: `c-${randomUUID()}`,
+ content: 'round 1 delivered',
+ });
+
+ expect(data.author).toMatchObject({ id: workspaceAgentId, type: 'agent' });
+ });
+
+ it('still lets a visitor remark under their own name', async () => {
+ const { data } = await caller(visitorId).create({
+ acceptanceId: openAcceptanceId,
+ clientId: `c-${randomUUID()}`,
+ content: 'the export path is missing',
+ });
+
+ expect(data.authorUserId).toBe(visitorId);
+ });
+
+ // Read-only in the workspace means read-only on its private deliveries, the
+ // same rule topic and document comments enforce.
+ it('keeps a workspace viewer read-only on a private delivery', async () => {
+ await expect(
+ caller(viewerId).create({
+ acceptanceId: closedAcceptanceId,
+ clientId: `c-${randomUUID()}`,
+ content: 'can I write here?',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('lets a workspace viewer remark once the delivery is public', async () => {
+ const { data } = await caller(viewerId).create({
+ acceptanceId: openAcceptanceId,
+ clientId: `c-${randomUUID()}`,
+ content: 'reading it from the link like everyone else',
+ });
+
+ expect(data.authorUserId).toBe(viewerId);
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
index 5c8533e7bd1..67ef88a89ed 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
@@ -10,14 +10,17 @@ import { isUuid } from '@/database/utils/uuid';
export interface AcceptanceCommentAccess {
acceptance: AcceptanceItem;
/**
- * May speak for the delivery itself — approve a round, or post the round's
- * own introduction. The creator, or a non-viewer member of the acceptance's
- * workspace.
+ * May speak for the delivery itself — approve a round, post the round's own
+ * introduction, sign as one of the workspace's agents, close someone else's
+ * thread, or remove a remark that does not belong here. The creator, or a
+ * non-viewer member of the acceptance's workspace.
*/
canApprove: boolean;
- /** May write comments, annotations and reactions: anyone signed in who can read it. */
+ /** May write comments, annotations and reactions. */
canComment: boolean;
isOwner: boolean;
+ /** The workspace whose agents this caller may sign as — only their own. */
+ memberOfWorkspaceId?: string;
}
/**
@@ -25,9 +28,15 @@ export interface AcceptanceCommentAccess {
*
* Reading follows the bundle: the creator, anyone when the acceptance is
* `public`, or a member of the acceptance's OWN workspace (not the caller's
- * active one). Remarking is as wide as reading, minus anonymity — whoever was
+ * active one).
+ *
+ * Remarking is as wide as READING A PUBLIC LINK, minus anonymity — whoever was
* handed the link can answer the evidence in front of them, and a shared
- * delivery nobody outside the team may reply to is a report, not a review.
+ * delivery nobody outside the team may reply to is a report, not a review. It
+ * is NOT as wide as reading in general: a `viewer` of the acceptance's own
+ * workspace stays read-only on a private delivery, the same role rule topic and
+ * document comments enforce. Opening the link is the owner's decision to be
+ * answered; being given read-only access to an org's internal work is not.
*
* Speaking FOR the delivery stays narrow. An approval and a round introduction
* are the delivery's own voice, so they need the creator or a workspace
@@ -55,12 +64,20 @@ export async function resolveAcceptanceCommentAccess(
const canRead = isOwner || acceptance.visibility === 'public' || Boolean(member);
if (!canRead) throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
+ const canApprove = isOwner || (Boolean(member) && member!.role !== 'viewer');
+
return {
acceptance,
- canApprove: isOwner || (Boolean(member) && member!.role !== 'viewer'),
- // Read access is already settled above, so a signed-in caller here is a
- // caller the acceptance was shared with.
- canComment: Boolean(userId),
+ canApprove,
+ canComment: Boolean(userId) && (canApprove || acceptance.visibility === 'public'),
isOwner,
+ /*
+ * Membership of the acceptance's workspace is what earns the right to speak
+ * as one of its agents — the creator counts, they filed it there. The
+ * acceptance being public does not: that hands out read access, and the
+ * agent ids ride along in the discussion payload, so a visitor could read
+ * one off the page and post under that agent's name and face.
+ */
+ memberOfWorkspaceId: isOwner || member ? (acceptance.workspaceId ?? undefined) : undefined,
};
}
diff --git a/apps/server/src/routers/lambda/acceptanceComment.ts b/apps/server/src/routers/lambda/acceptanceComment.ts
index 6589810d1ef..db6d876e5da 100644
--- a/apps/server/src/routers/lambda/acceptanceComment.ts
+++ b/apps/server/src/routers/lambda/acceptanceComment.ts
@@ -11,6 +11,7 @@ import { z } from 'zod';
import {
ACCEPTANCE_COMMENT_PARENT_NOT_FOUND,
+ ACCEPTANCE_COMMENT_RATE_LIMITED,
AcceptanceCommentModel,
acceptanceReactionClientId,
} from '@/database/models/acceptanceComment';
@@ -23,6 +24,7 @@ import {
workspaceMembers,
} from '@/database/schemas';
import type { AcceptanceCommentRow } from '@/database/schemas/acceptanceComment';
+import type { AcceptanceItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { assertAgentUsableBy } from '@/database/utils/agent-access';
import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
@@ -106,11 +108,24 @@ const deactivatedAuthor: AcceptanceCommentAuthor = {
* Join author profiles and round indexes onto raw rows. Membership status is
* read against the acceptance's own workspace so a departed teammate renders
* as `former` rather than vanishing from the discussion.
+ *
+ * That inference only holds on a delivery nobody outside could write on. Once
+ * the link is public, most people in the discussion never had a seat in that
+ * workspace and "left" would be a lie about every one of them, so the label is
+ * dropped there rather than guessed.
*/
const enrich = async (
db: LobeChatDatabase,
rows: AcceptanceCommentRow[],
- scope: { ownerUserId: string; userId?: string | null; workspaceId: string | null },
+ scope: {
+ /** Whether this reader may take down a remark that is not theirs. */
+ canModerate?: boolean;
+ ownerUserId: string;
+ userId?: string | null;
+ /** Only a private delivery can prove a non-member once had a seat. */
+ visibility: AcceptanceItem['visibility'];
+ workspaceId: string | null;
+ },
): Promise<AcceptanceCommentItem[]> => {
const authorIds = [
...new Set(rows.flatMap((row) => (row.authorUserId ? [row.authorUserId] : []))),
@@ -204,8 +219,10 @@ const enrich = async (
};
const profile = authorUserId ? profileById.get(authorUserId) : undefined;
if (!profile) return deactivatedAuthor;
- // Without a workspace there is no membership to lapse from.
- const active = !scope.workspaceId || activeIds.has(profile.id);
+ // Without a workspace there is no membership to lapse from, and on a public
+ // delivery a non-member is an invited reader rather than a departed one.
+ const active =
+ !scope.workspaceId || scope.visibility !== 'private' || activeIds.has(profile.id);
return { ...profile, status: active ? 'active' : 'former', type: 'user' as const };
};
@@ -247,7 +264,10 @@ const enrich = async (
author: getAuthor(row.authorUserId, row.authorAgentId),
authorAgentId: row.authorAgentId,
authorUserId: row.authorUserId,
- canDelete: !row.deletedAt && Boolean(scope.userId) && row.authorUserId === scope.userId,
+ canDelete:
+ !row.deletedAt &&
+ Boolean(scope.userId) &&
+ (row.authorUserId === scope.userId || Boolean(scope.canModerate)),
checkItemId: row.checkItemId,
clientId: row.clientId,
content: row.content,
@@ -292,9 +312,14 @@ const requireComment = async (
*
* `author_agent_id` decides whose name, title and avatar the discussion shows,
* and a public acceptance shows it to anyone with the link. Without this gate a
- * participant could name any agent id that exists and impersonate it. The scope
- * is the acceptance's own workspace, because that is the audience the agent is
- * being presented to.
+ * participant could name any agent id that exists and impersonate it.
+ *
+ * The scope is the acceptance's workspace ONLY for callers who belong to it.
+ * The workspace scope answers "is this agent visible in that workspace", not
+ * "may this caller use it", so handing it to a visitor who merely opened a
+ * public link would let them post under any agent of that workspace — and the
+ * discussion payload hands them the ids to pick from. A visitor falls back to
+ * personal scope, where they can only sign as their own agents.
*/
const assertAuthorAgentUsable = async (
db: LobeChatDatabase,
@@ -345,6 +370,20 @@ const assertReferencesBelongToAcceptance = async (
}
};
+/**
+ * What a visitor may land on one acceptance in one minute. The discussion is
+ * open to whoever holds the link, so the cost of flooding it has to sit
+ * somewhere; a reader answering evidence writes a handful of remarks, and a
+ * flood writes hundreds. Reviewers are exempt — the round-publishing tools post
+ * on their behalf in bursts.
+ *
+ * A retry of a remark that already landed is not a new remark: the ceiling is
+ * charged where the row is written, so an idempotent replay of the tenth one
+ * still answers with that row instead of a refusal.
+ */
+const VISITOR_COMMENT_WINDOW_MS = 60_000;
+const VISITOR_COMMENTS_PER_WINDOW = 10;
+
export const acceptanceCommentRouter = router({
create: writeProcedure.input(createSchema).mutation(async ({ ctx, input }) => {
const access = await resolveAcceptanceCommentAccess(
@@ -360,7 +399,7 @@ export const acceptanceCommentRouter = router({
await assertAuthorAgentUsable(
ctx.serverDB,
- { userId: ctx.userId, workspaceId: access.acceptance.workspaceId ?? undefined },
+ { userId: ctx.userId, workspaceId: access.memberOfWorkspaceId },
input.authorAgentId,
);
await assertReferencesBelongToAcceptance(ctx.serverDB, access.acceptance.id, {
@@ -381,11 +420,26 @@ export const acceptanceCommentRouter = router({
editorData: input.editorData as never,
kind: input.kind,
parentCommentId: input.parentCommentId,
+ /*
+ * The ceiling travels INTO the write so it is counted and charged in
+ * one transaction: checked out here it would be advisory only, and a
+ * burst of parallel requests would each read the same under-limit
+ * count. Reactions take another path, and each (comment, emoji) pair is
+ * one idempotent row per person anyway.
+ */
+ rateLimit: access.canApprove
+ ? undefined
+ : {
+ max: VISITOR_COMMENTS_PER_WINDOW,
+ since: new Date(Date.now() - VISITOR_COMMENT_WINDOW_MS),
+ },
workspaceId: access.acceptance.workspaceId,
});
const [item] = await enrich(ctx.serverDB, [comment], {
+ canModerate: access.canApprove,
ownerUserId: access.acceptance.userId,
userId: ctx.userId,
+ visibility: access.acceptance.visibility,
workspaceId: access.acceptance.workspaceId,
});
return { data: item, success: true };
@@ -393,6 +447,11 @@ export const acceptanceCommentRouter = router({
if (error instanceof TRPCError) throw error;
if (error instanceof Error && error.message === ACCEPTANCE_COMMENT_PARENT_NOT_FOUND)
throw new TRPCError({ code: 'NOT_FOUND', message: error.message });
+ if (error instanceof Error && error.message === ACCEPTANCE_COMMENT_RATE_LIMITED)
+ throw new TRPCError({
+ code: 'TOO_MANY_REQUESTS',
+ message: 'Too many comments on this acceptance, try again in a minute',
+ });
console.error('[acceptanceComment:create]', error);
throw new TRPCError({
cause: error,
@@ -402,13 +461,26 @@ export const acceptanceCommentRouter = router({
}
}),
+ /**
+ * Take a remark down. Its author always may; the acceptance's reviewers may
+ * take down anyone's, because the discussion is open to whoever holds the
+ * link and the author of an unwanted remark is exactly who will not remove
+ * it. The row becomes the same tombstone either way.
+ */
delete: writeProcedure
.input(z.object({ id: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
- const { comment } = await requireComment(ctx, input.id);
- if (comment.authorUserId !== ctx.userId)
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Only the author may delete' });
- const result = await ctx.acceptanceCommentModel.delete(comment.id, ctx.userId);
+ const { access, comment } = await requireComment(ctx, input.id);
+ const own = comment.authorUserId === ctx.userId;
+ if (!own && !access.canApprove)
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the author or a reviewer of this acceptance may delete',
+ });
+ const result = await ctx.acceptanceCommentModel.delete(
+ comment.id,
+ own ? { authorUserId: ctx.userId } : { moderator: true },
+ );
return { data: { deleted: result !== false }, success: true };
}),
@@ -422,8 +494,10 @@ export const acceptanceCommentRouter = router({
);
const rows = await ctx.acceptanceCommentModel.listByAcceptance(access.acceptance.id);
const items = await enrich(ctx.serverDB, rows, {
+ canModerate: access.canApprove,
ownerUserId: access.acceptance.userId,
userId: ctx.userId,
+ visibility: access.acceptance.visibility,
workspaceId: access.acceptance.workspaceId,
});
return { canApprove: access.canApprove, canComment: access.canComment, items };
diff --git a/apps/workbench/app/stubs/electronStore.ts b/apps/workbench/app/stubs/electronStore.ts
index 8ba30264df2..3fb6d064d3b 100644
--- a/apps/workbench/app/stubs/electronStore.ts
+++ b/apps/workbench/app/stubs/electronStore.ts
@@ -1,4 +1,12 @@
-const emptyState = {};
+interface GatewayDeviceInfo {
+ deviceId?: string;
+}
+
+// Desktop-only state the shared stores read while resolving a working
+// directory; SSR has no gateway device, so every reader takes its web branch.
+const emptyState = {
+ gatewayDeviceInfo: undefined as GatewayDeviceInfo | undefined,
+};
// Renderable stand-in, not a throwing proxy: shared components may call the
// hook during SSR and must see "desktop features off", not a crash.
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 7323bf8cddf..2c4a82fd650 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -116,6 +116,8 @@
"acceptance.comments.regionHint": "Drag a box on the image, then write your note.",
"acceptance.comments.regionMissing": "Circle a region first.",
"acceptance.comments.regionModalTitle": "Circle the spot you mean",
+ "acceptance.comments.removeOthers": "Remove",
+ "acceptance.comments.removeOthersConfirm": "Remove someone else's comment? It disappears from the discussion.",
"acceptance.comments.reopen": "Reopen",
"acceptance.comments.reply": "Reply",
"acceptance.comments.replyPlaceholder": "Reply…",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index c968f26ce0d..a2792fdd339 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -116,6 +116,8 @@
"acceptance.comments.regionHint": "在图上拖一个框,然后写下你的意见。",
"acceptance.comments.regionMissing": "先在图上圈出一处。",
"acceptance.comments.regionModalTitle": "在截图上圈出要说的位置",
+ "acceptance.comments.removeOthers": "移除",
+ "acceptance.comments.removeOthersConfirm": "移除这条别人写的评论?它会从讨论里消失。",
"acceptance.comments.reopen": "重新打开",
"acceptance.comments.reply": "回复",
"acceptance.comments.replyPlaceholder": "回复…",
diff --git a/packages/database/src/models/__tests__/acceptanceComment.test.ts b/packages/database/src/models/__tests__/acceptanceComment.test.ts
index b311796f707..fb36569e1f0 100644
--- a/packages/database/src/models/__tests__/acceptanceComment.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceComment.test.ts
@@ -234,8 +234,8 @@ describe('AcceptanceCommentModel', () => {
clientId: 'd',
content: 'd',
});
- expect(await model.delete(comment.id, owner)).toBe(false);
- expect(await model.delete(comment.id, reviewer)).toBe('hard');
+ expect(await model.delete(comment.id, { authorUserId: owner })).toBe(false);
+ expect(await model.delete(comment.id, { authorUserId: reviewer })).toBe('hard');
expect(await model.findById(comment.id)).toBeUndefined();
});
@@ -254,14 +254,14 @@ describe('AcceptanceCommentModel', () => {
parentCommentId: root.id,
});
- expect(await model.delete(root.id, reviewer)).toBe('soft');
+ expect(await model.delete(root.id, { authorUserId: reviewer })).toBe('soft');
const tombstone = await model.findById(root.id);
expect(tombstone?.deletedAt).not.toBeNull();
expect(tombstone?.content).toBe('');
// Already deleted: a second delete is a no-op.
- expect(await model.delete(root.id, reviewer)).toBe(false);
+ expect(await model.delete(root.id, { authorUserId: reviewer })).toBe(false);
- expect(await model.delete(reply.id, owner)).toBe('hard');
+ expect(await model.delete(reply.id, { authorUserId: owner })).toBe('hard');
expect(await model.findById(root.id)).toBeUndefined();
});
@@ -282,7 +282,7 @@ describe('AcceptanceCommentModel', () => {
parentCommentId: root.id,
});
- expect(await model.delete(root.id, reviewer)).toBe('soft');
+ expect(await model.delete(root.id, { authorUserId: reviewer })).toBe('soft');
// The tombstone exists to hold the reply up. Leaving the editor tree or
// the attached files behind would keep a deleted remark readable.
@@ -414,7 +414,7 @@ describe('AcceptanceCommentModel', () => {
});
await react(root.id, '👍', reviewer);
- expect(await model.delete(root.id, owner)).toBe('hard');
+ expect(await model.delete(root.id, { authorUserId: owner })).toBe('hard');
expect(await model.listByAcceptance(acceptanceId)).toHaveLength(0);
});
});
diff --git a/packages/database/src/models/acceptanceComment.ts b/packages/database/src/models/acceptanceComment.ts
index 4a685cb26d2..315ba7693c2 100644
--- a/packages/database/src/models/acceptanceComment.ts
+++ b/packages/database/src/models/acceptanceComment.ts
@@ -4,13 +4,14 @@ import type {
AcceptanceReviewAnnotation,
DocumentCommentJson,
} from '@lobechat/types';
-import { and, count, desc, eq, isNull, ne } from 'drizzle-orm';
+import { and, count, desc, eq, gte, isNull, ne, sql } from 'drizzle-orm';
import type { AcceptanceCommentRow } from '../schemas/acceptanceComment';
import { acceptanceComments } from '../schemas/acceptanceComment';
import type { LobeChatDatabase } from '../type';
export const ACCEPTANCE_COMMENT_PARENT_NOT_FOUND = 'Parent comment not found in this acceptance';
+export const ACCEPTANCE_COMMENT_RATE_LIMITED = 'Too many comments in the window';
/**
* One person's emoji on one comment is one row, and the idempotency key is
@@ -43,6 +44,13 @@ export interface CreateAcceptanceCommentParams {
editorData?: DocumentCommentJson;
kind?: AcceptanceCommentKind;
parentCommentId?: string;
+ /**
+ * Ceiling for this author on this acceptance, enforced inside the write's own
+ * transaction. Counting outside it would be advisory only: a handful of
+ * parallel requests all read the same under-limit count before any of them
+ * commits, which is exactly how a flood arrives.
+ */
+ rateLimit?: { max: number; since: Date };
workspaceId?: string | null;
}
@@ -70,6 +78,14 @@ export class AcceptanceCommentModel {
params: CreateAcceptanceCommentParams,
): Promise<CreateAcceptanceCommentResult> => {
return this.db.transaction(async (tx) => {
+ if (params.rateLimit)
+ // One author on one acceptance is the contended pair, and the lock is
+ // released when this transaction ends either way. Everybody else writes
+ // in parallel exactly as before.
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(hashtext(${params.acceptanceId}), hashtext(${params.authorUserId}))`,
+ );
+
let parentCommentId: string | undefined;
if (params.parentCommentId) {
const [parent] = await tx
@@ -122,7 +138,26 @@ export class AcceptanceCommentModel {
})
.returning();
- if (inserted) return { comment: inserted, isDuplicate: false };
+ if (inserted) {
+ if (params.rateLimit) {
+ const [recent] = await tx
+ .select({ total: count() })
+ .from(acceptanceComments)
+ .where(
+ and(
+ eq(acceptanceComments.acceptanceId, params.acceptanceId),
+ eq(acceptanceComments.authorUserId, params.authorUserId),
+ ne(acceptanceComments.kind, 'reaction'),
+ gte(acceptanceComments.createdAt, params.rateLimit.since),
+ ),
+ );
+ // The row just written is part of this count, so the first one over
+ // the ceiling rolls itself back and nothing lands.
+ if ((recent?.total ?? 0) > params.rateLimit.max)
+ throw new Error(ACCEPTANCE_COMMENT_RATE_LIMITED);
+ }
+ return { comment: inserted, isDuplicate: false };
+ }
const [existing] = await tx
.select()
@@ -169,11 +204,26 @@ export class AcceptanceCommentModel {
};
/**
- * Delete the author's own comment. A root that still has replies becomes a
- * tombstone so the replies keep their context; a reply whose tombstoned root
- * has no other replies takes the root with it.
+ * Remove one comment. A root that still has replies becomes a tombstone so
+ * the replies keep their context; a reply whose tombstoned root has no other
+ * replies takes the root with it.
+ *
+ * `by.authorUserId` scopes the removal to that author's own row — the normal
+ * case. `by.moderator` skips the author check for someone the caller has
+ * already established may moderate this acceptance: since the discussion is
+ * open to anyone holding a public link, its owner needs a way to take a
+ * remark down, and the author of an unwanted remark is exactly who will not
+ * remove it. The router decides who that is; the model only obeys.
*/
- delete = async (id: string, authorUserId: string): Promise<'hard' | 'soft' | false> => {
+ delete = async (
+ id: string,
+ by: { authorUserId: string } | { moderator: true },
+ ): Promise<'hard' | 'soft' | false> => {
+ const authorUserId = 'authorUserId' in by ? by.authorUserId : undefined;
+ const ownRow = (rowId: string) =>
+ authorUserId
+ ? and(eq(acceptanceComments.id, rowId), eq(acceptanceComments.authorUserId, authorUserId))
+ : eq(acceptanceComments.id, rowId);
return this.db.transaction(async (tx) => {
const [target] = await tx
.select({
@@ -182,9 +232,7 @@ export class AcceptanceCommentModel {
parentCommentId: acceptanceComments.parentCommentId,
})
.from(acceptanceComments)
- .where(
- and(eq(acceptanceComments.id, id), eq(acceptanceComments.authorUserId, authorUserId)),
- )
+ .where(ownRow(id))
.limit(1);
if (!target) return false;
@@ -216,9 +264,7 @@ export class AcceptanceCommentModel {
parentCommentId: acceptanceComments.parentCommentId,
})
.from(acceptanceComments)
- .where(
- and(eq(acceptanceComments.id, id), eq(acceptanceComments.authorUserId, authorUserId)),
- )
+ .where(ownRow(id))
.limit(1)
.for('update')
: [{ ...target, deletedAt: root.deletedAt }];
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index e92e4bccb78..695ff017b05 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -184,6 +184,9 @@ export default {
'acceptance.comments.title': 'Discussion',
'acceptance.comments.moreActions': 'More actions',
'acceptance.comments.placeholder': 'Say something about this delivery…',
+ 'acceptance.comments.removeOthers': 'Remove',
+ 'acceptance.comments.removeOthersConfirm':
+ "Remove someone else's comment? It disappears from the discussion.",
'acceptance.comments.replyPlaceholder': 'Reply…',
'acceptance.comments.send': 'Send',
'acceptance.comments.reply': 'Reply',
diff --git a/packages/types/src/acceptanceComment.ts b/packages/types/src/acceptanceComment.ts
index c876118a241..6e4dc94d249 100644
--- a/packages/types/src/acceptanceComment.ts
+++ b/packages/types/src/acceptanceComment.ts
@@ -84,6 +84,11 @@ export interface AcceptanceCommentItem extends AcceptanceCommentAnchor {
/** The agent that signed it, when an agent wrote the row. */
authorAgentId: string | null;
authorUserId: string | null;
+ /**
+ * Whether THIS reader may remove the row: its author, or someone who may
+ * moderate the acceptance. Never a stand-in for "I wrote this" — compare
+ * `authorUserId` for that.
+ */
canDelete: boolean;
clientId: string;
content: string;
diff --git a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
index 1216723b024..ee279ce5e14 100644
--- a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
+++ b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { AcceptanceCommentThread } from '@lobechat/types';
import { copyToClipboard, Flexbox, Icon, TextArea, Tooltip } from '@lobehub/ui';
import { ActionIcon, Button, Tag, Text } from '@lobehub/ui/base-ui';
import { cssVar, cx, useResponsive } from 'antd-style';
@@ -20,9 +21,12 @@ import {
Repeat,
Route,
} from 'lucide-react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
import { hasRenderableEvidence, readVisualizationManifest } from '../../Report/visualization';
import { VisualizationDeltaBadge, VisualizationRenderer } from '../../Report/VisualizationRenderer';
import { checkDisplayTitle } from '../../utils';
@@ -149,6 +153,23 @@ export const AcceptanceCheckRow = memo<{
const scope = useOptionalAcceptanceScope();
const { data: bundle } = useAcceptanceBundle(scope?.acceptanceId ?? '');
const comments = useAcceptanceComments(scope?.acceptanceId);
+ const viewerId = useUserStore(userProfileSelectors.userId);
+ /**
+ * Closing a note is a verdict on it: whoever raised it may close their own,
+ * and the acceptance's reviewers may close anyone's. Ownership is read from
+ * the author, not from `canDelete` — that flag also turns on for a
+ * moderator, and borrowing it would silently hand the same power out.
+ *
+ * Memoized on the identity it reads: the profile arrives after the first
+ * paint, and the overlay memo below would otherwise keep handing its
+ * threads the answer computed while nobody was signed in.
+ */
+ const canResolveThread = useCallback(
+ (thread: AcceptanceCommentThread) =>
+ comments.canApprove ||
+ (Boolean(viewerId) && thread.root.authorUserId === viewerId && !thread.root.deletedAt),
+ [comments.canApprove, viewerId],
+ );
const checkThreads = useMemo(
() => threadsForCheck(comments.threads, check.id),
[comments.threads, check.id],
@@ -189,9 +210,7 @@ export const AcceptanceCheckRow = memo<{
panel: (
<CommentThread
canComment={comments.canComment}
- // `canDelete` is only ever true on the caller's own live rows, so
- // it doubles as "I raised this one".
- canResolve={comments.canApprove || thread.root.canDelete}
+ canResolve={canResolveThread(thread)}
thread={thread}
{...commentActions}
/>
@@ -203,7 +222,7 @@ export const AcceptanceCheckRow = memo<{
});
return map.size > 0 ? map : undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [proposalOverlays, checkThreads, comments.canComment, comments.canApprove]);
+ }, [proposalOverlays, checkThreads, comments.canComment, canResolveThread]);
const canCommentEvidence =
comments.canComment && Boolean(check.result) && hasAnnotatableEvidence(check);
const openEvidenceComment = () =>
@@ -653,7 +672,7 @@ export const AcceptanceCheckRow = memo<{
<Flexbox flex={1} style={{ minWidth: 200 }}>
<CommentThread
canComment={comments.canComment}
- canResolve={comments.canApprove || thread.root.canDelete}
+ canResolve={canResolveThread(thread)}
thread={thread}
{...commentActions}
/>
diff --git a/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
index 6c38a4179ab..5e554ee4fa2 100644
--- a/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
+++ b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import { useActivityTime } from '@/hooks/useActivityTime';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { buildAuthReturnUrl, currentReturnPath } from '@/utils/authReturnUrl';
import { useAcceptanceScope } from '../AcceptanceScope';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
@@ -26,12 +27,6 @@ import { styles, TIMELINE_NODE } from './styles';
/** Enough room to start writing without the box dominating the column. */
const COMPOSER_MIN_HEIGHT = 80;
-/** Where a visitor lands after signing in: back on the page they were reading. */
-const authPath = (route: 'signin' | 'signup') =>
- `/${route}?callbackUrl=${encodeURIComponent(
- typeof window === 'undefined' ? '/' : window.location.pathname + window.location.search,
- )}`;
-
/**
* The end of a discussion a signed-out reader cannot join. A bare line of grey
* text states the rule and leaves them there; the way in belongs in the same
@@ -47,10 +42,12 @@ const SignInPrompt = memo(() => {
{t('acceptance.comments.signInDescription')}
</Text>
<Flexbox horizontal gap={8}>
- <Button href={authPath('signin')} type={'primary'}>
+ <Button href={buildAuthReturnUrl('signin', currentReturnPath())} type={'primary'}>
{t('acceptance.comments.signIn')}
</Button>
- <Button href={authPath('signup')}>{t('acceptance.comments.signUp')}</Button>
+ <Button href={buildAuthReturnUrl('signup', currentReturnPath())}>
+ {t('acceptance.comments.signUp')}
+ </Button>
</Flexbox>
</Flexbox>
);
@@ -310,7 +307,7 @@ const AcceptanceDiscussion = memo(() => {
<Text fontSize={13} type={'secondary'}>
{t('acceptance.comments.loadFailed')}
</Text>
- ) : isSignedIn ? (
+ ) : isLoading ? null : isSignedIn ? ( // Neither line below is true yet while the answer is in flight.
<Text fontSize={13} type={'secondary'}>
{t('acceptance.comments.readOnly')}
</Text>
diff --git a/src/features/Acceptance/Viewer/Comments/CommentCard.tsx b/src/features/Acceptance/Viewer/Comments/CommentCard.tsx
index 7cd9831331b..1c04e8b1ce6 100644
--- a/src/features/Acceptance/Viewer/Comments/CommentCard.tsx
+++ b/src/features/Acceptance/Viewer/Comments/CommentCard.tsx
@@ -17,6 +17,8 @@ import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActivityTime } from '@/hooks/useActivityTime';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { AttachmentThumbs } from '../Evidence/attachments';
import { commentAnchorUrl } from './anchor';
@@ -83,6 +85,8 @@ const CommentCard = memo<CommentCardProps>(
const time = useActivityTime(comment.createdAt);
const [deleting, setDeleting] = useState(false);
const name = nameOverride ?? commentAuthorName(comment.author);
+ const viewerId = useUserStore(userProfileSelectors.userId);
+ const own = Boolean(viewerId) && comment.authorUserId === viewerId;
const menuItems: DropdownItem[] = [
...(anchored
@@ -109,12 +113,18 @@ const CommentCard = memo<CommentCardProps>(
danger: true,
icon: <Icon icon={Trash2} />,
key: 'delete',
- label: t('acceptance.comments.delete'),
+ // Taking down someone else's remark is a different act from
+ // deleting your own, and the confirm says which one this is.
+ label: own ? t('acceptance.comments.delete') : t('acceptance.comments.removeOthers'),
onClick: () =>
confirmModal({
- content: t('acceptance.comments.deleteConfirm'),
+ content: own
+ ? t('acceptance.comments.deleteConfirm')
+ : t('acceptance.comments.removeOthersConfirm'),
okButtonProps: { danger: true },
- okText: t('acceptance.comments.delete'),
+ okText: own
+ ? t('acceptance.comments.delete')
+ : t('acceptance.comments.removeOthers'),
onOk: async () => {
setDeleting(true);
try {
diff --git a/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx b/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx
index 85d1ba2461e..58564d15c98 100644
--- a/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx
+++ b/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx
@@ -8,6 +8,9 @@ import { nanoid } from 'nanoid';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
import { useAcceptanceScope } from '../AcceptanceScope';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import { canReviewAcceptance } from '../visibility';
@@ -45,6 +48,7 @@ const ReviewerApprovalBar = memo(() => {
const { acceptanceId } = useAcceptanceScope();
const { data } = useAcceptanceBundle(acceptanceId);
const { canApprove, create, items, remove } = useAcceptanceComments(acceptanceId);
+ const viewerId = useUserStore(userProfileSelectors.userId);
const [summary, setSummary] = useState('');
const [pending, setPending] = useState(false);
@@ -58,9 +62,18 @@ const ReviewerApprovalBar = memo(() => {
const currentRound = data.rounds.at(-1)?.run;
if (!currentRound) return null;
- // `canDelete` is only ever true on the caller's own live rows, so it doubles
- // as "mine" without a user store lookup.
- const mine = [...items].reverse().find((item) => item.kind === 'approval' && item.canDelete);
+ // Read ownership from the author. `canDelete` also turns on for someone who
+ // may moderate this acceptance, so borrowing it here would show a reviewer
+ // their teammate's approval as their own and let them withdraw it.
+ const mine = [...items]
+ .reverse()
+ .find(
+ (item) =>
+ item.kind === 'approval' &&
+ !item.deletedAt &&
+ Boolean(viewerId) &&
+ item.authorUserId === viewerId,
+ );
const approvedCurrentRound = mine?.contextRoundIndex === currentRound.roundIndex;
const run = async (action: () => Promise<unknown>) => {
diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceSharedNotice.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceSharedNotice.tsx
index dbb7837e14e..ff42dbc957a 100644
--- a/src/features/Acceptance/Viewer/Header/AcceptanceSharedNotice.tsx
+++ b/src/features/Acceptance/Viewer/Header/AcceptanceSharedNotice.tsx
@@ -26,7 +26,7 @@ const AcceptanceSharedNotice = ({ style }: { style?: CSSProperties }) => {
const { acceptanceId } = useAcceptanceScope();
const { data } = useAcceptanceBundle(acceptanceId);
const author = useAuthorInfo(data?.acceptance.userId ?? undefined);
- const { canComment } = useAcceptanceComments(acceptanceId);
+ const { canComment, isLoading: permissionLoading } = useAcceptanceComments(acceptanceId);
if (!data || data.isOwner) return null;
@@ -40,7 +40,10 @@ const AcceptanceSharedNotice = ({ style }: { style?: CSSProperties }) => {
description={t(
canReviewAcceptance(data)
? 'acceptance.sharedNotice.reviewableDescription'
- : canComment
+ : // Until the discussion answers, the wider line is the safe guess:
+ // telling a reader they may join and then taking it away reads as a
+ // bug, while the reverse reads as the page changing its mind.
+ canComment || permissionLoading
? 'acceptance.sharedNotice.commentableDescription'
: 'acceptance.sharedNotice.readOnlyDescription',
)}
diff --git a/src/features/AgentShareVisitor/visitorPath.ts b/src/features/AgentShareVisitor/visitorPath.ts
index d044feadb5b..cb3d5e5bd47 100644
--- a/src/features/AgentShareVisitor/visitorPath.ts
+++ b/src/features/AgentShareVisitor/visitorPath.ts
@@ -1,3 +1,5 @@
+import { buildAuthReturnUrl } from '@/utils/authReturnUrl';
+
/**
* Route prefix of the agent-share visitor page. `/a/<slug>` on purpose — short
* enough to read aloud, and not `/agent/…`, which the marketing site already
@@ -10,13 +12,9 @@ export const AGENT_SHARE_VISITOR_PATH = '/a';
export const buildAgentShareVisitorPath = (slugOrId: string, topicId?: string) =>
`${AGENT_SHARE_VISITOR_PATH}/${slugOrId}${topicId ? `/${topicId}` : ''}`;
-/**
- * Sign-in URL that returns the visitor to the same share once signed in.
- * `/signin` is an auth shell outside the SPA router, so callers navigate to it
- * with a full document load.
- */
+/** Sign-in URL that returns the visitor to the same share once signed in. */
export const buildAgentShareSignInUrl = (slugOrId: string, topicId?: string) =>
- `/signin?callbackUrl=${encodeURIComponent(buildAgentShareVisitorPath(slugOrId, topicId))}`;
+ buildAuthReturnUrl('signin', buildAgentShareVisitorPath(slugOrId, topicId));
/**
* Where the CREATOR lands when they open their own share link: the share
diff --git a/src/utils/authReturnUrl.ts b/src/utils/authReturnUrl.ts
new file mode 100644
index 00000000000..d8acc4ccdae
--- /dev/null
+++ b/src/utils/authReturnUrl.ts
@@ -0,0 +1,20 @@
+/**
+ * Sign-in and sign-up URLs that bring the reader back where they were.
+ *
+ * `/signin` and `/signup` are auth shells outside the SPA router, so callers
+ * navigate to them with a full document load rather than a router push. The
+ * return path is encoded once here so every entry point agrees on the query
+ * name the auth shell reads (`callbackUrl`).
+ */
+export type AuthReturnRoute = 'signin' | 'signup';
+
+export const buildAuthReturnUrl = (route: AuthReturnRoute, returnPath: string) =>
+ `/${route}?callbackUrl=${encodeURIComponent(returnPath)}`;
+
+/**
+ * The page the reader is on, path and query only. The host is dropped on
+ * purpose: the auth shell sanitizes the callback to a same-origin path, and an
+ * absolute URL would be thrown away there.
+ */
+export const currentReturnPath = () =>
+ typeof window === 'undefined' ? '/' : window.location.pathname + window.location.search;