Files
CapaKraken/packages/api/src/router/comment-procedure-support.ts
T
Hartmut 435c871e1f security: implement tickets #28-#35 + architecture decision #30
#28 - TOTP rate limiting (verifyTotp): added totpRateLimiter (10 req/30s),
  throws TOO_MANY_REQUESTS before DB hit; 16 unit tests including rate-limit
  exceeded + userId key isolation.

#29 - /api/reports/allocations role check: only ADMIN/MANAGER/CONTROLLER may
  access; returns 403 otherwise; 9 unit tests (401 unauthenticated, 403 for
  USER/VIEWER, 200 for allowed roles + xlsx format).

#31 - pgAdmin credentials moved out of docker-compose.yml into env vars;
  PGADMIN_PASSWORD is now required (:?) to prevent accidental plaintext
  exposure in committed files.

#34 - Server-side HTML sanitization for comment bodies via stripHtml():
  strips all tags + decodes safe entities before persistence; 16 unit tests
  covering passthrough, injection patterns, entity decoding.

#35 - MFA setup prompt banner (MfaPromptBanner): shown to ADMIN/MANAGER users
  without TOTP enabled; user-scoped localStorage snooze (7 days); links to
  /account/security; accessibility role=alert; 7 structural unit tests.

#33 - Auth anomaly alerting cron (/api/cron/auth-anomaly-check): detects
  HIGH_GLOBAL_FAILURE_RATE and CONCENTRATED_FAILURES in 30-minute window;
  CRITICAL notification to ADMINs; fail-closed via verifyCronSecret;
  10 unit tests.

#32 - MFA enforcement policy: added requireMfaForRoles field to SystemSettings
  schema + Prisma migration; auth.ts blocks login with MFA_REQUIRED_SETUP
  signal if role is enforced but TOTP not set up; signin page redirects to
  /account/security?mfa_required=1; settings schema + view model updated;
  11 unit tests.

#30 - API keys architecture decision documented in LEARNINGS.md; no code
  written — product decision required before implementation.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-01 23:25:06 +02:00

257 lines
6.9 KiB
TypeScript

import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createAuditEntry } from "../lib/audit.js";
import { assertCommentEntityAccess, CommentEntityTypeSchema } from "../lib/comment-entity-registry.js";
import { stripHtml } from "../lib/strip-html.js";
import { createNotification } from "../lib/create-notification.js";
import type { TRPCContext } from "../trpc.js";
import {
assertCommentManageableByActor,
buildCommentCreateData,
buildCommentMentionNotifications,
commentBelongsToEntity,
commentThreadInclude,
commentWithAuthorInclude,
parseCommentMentions,
} from "./comment-support.js";
export const CommentEntityInputSchema = z.object({
entityType: CommentEntityTypeSchema,
entityId: z.string(),
});
export const CommentMentionCandidatesInputSchema = CommentEntityInputSchema.extend({
query: z.string().trim().max(100).optional(),
});
export const CreateCommentInputSchema = CommentEntityInputSchema.extend({
parentId: z.string().optional(),
body: z.string().min(1).max(10_000),
});
export const ResolveCommentInputSchema = z.object({
id: z.string(),
resolved: z.boolean().default(true),
});
export const DeleteCommentInputSchema = z.object({
id: z.string(),
});
type CommentProcedureContext = Pick<TRPCContext, "db" | "dbUser" | "roleDefaults">;
type CreateCommentProcedureContext = Pick<TRPCContext, "db" | "dbUser" | "roleDefaults">;
export async function listComments(
ctx: CommentProcedureContext,
input: z.infer<typeof CommentEntityInputSchema>,
) {
await assertCommentEntityAccess(ctx, input.entityType, input.entityId);
return ctx.db.comment.findMany({
where: {
entityType: input.entityType,
entityId: input.entityId,
parentId: null,
},
include: commentThreadInclude,
orderBy: { createdAt: "asc" },
});
}
export async function countComments(
ctx: CommentProcedureContext,
input: z.infer<typeof CommentEntityInputSchema>,
) {
await assertCommentEntityAccess(ctx, input.entityType, input.entityId);
return ctx.db.comment.count({
where: {
entityType: input.entityType,
entityId: input.entityId,
},
});
}
export async function listCommentMentionCandidates(
ctx: CommentProcedureContext,
input: z.infer<typeof CommentMentionCandidatesInputSchema>,
) {
const normalizedQuery = input.query && input.query.length > 0 ? input.query : undefined;
const policy = await assertCommentEntityAccess(ctx, input.entityType, input.entityId);
return policy.listMentionCandidates(ctx, input.entityId, normalizedQuery);
}
export async function createComment(
ctx: CreateCommentProcedureContext,
input: z.infer<typeof CreateCommentInputSchema>,
) {
const policy = await assertCommentEntityAccess(ctx, input.entityType, input.entityId);
const authorId = ctx.dbUser?.id;
if (!authorId) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
const sanitizedBody = stripHtml(input.body);
const mentions = parseCommentMentions(sanitizedBody);
if (input.parentId) {
const parent = await ctx.db.comment.findUnique({
where: { id: input.parentId },
select: { id: true, entityType: true, entityId: true },
});
if (!parent) {
throw new TRPCError({ code: "NOT_FOUND", message: "Parent comment not found" });
}
if (!commentBelongsToEntity({
comment: parent,
entityType: input.entityType,
entityId: input.entityId,
})) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Parent comment does not belong to the requested entity",
});
}
}
const comment = await ctx.db.comment.create({
data: buildCommentCreateData({
entityType: input.entityType,
entityId: input.entityId,
parentId: input.parentId,
authorId,
body: sanitizedBody,
mentions,
}),
include: commentWithAuthorInclude,
});
const mentionedUserIds = mentions.filter((id) => id !== authorId);
if (mentionedUserIds.length > 0) {
const authorName = comment.author.name ?? comment.author.email;
const notifications = buildCommentMentionNotifications({
mentionedUserIds,
authorName,
body: sanitizedBody,
entityId: input.entityId,
entityType: input.entityType,
senderId: authorId,
link: policy.buildLink(input.entityId),
});
await Promise.all(
notifications.map((notification) =>
createNotification({
db: ctx.db,
...notification,
})),
);
}
void createAuditEntry({
db: ctx.db,
entityType: "Comment",
entityId: comment.id,
entityName: sanitizedBody.slice(0, 50),
action: "CREATE",
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
after: comment as unknown as Record<string, unknown>,
source: "ui",
});
return comment;
}
async function findManageableComment(
ctx: CommentProcedureContext,
id: string,
) {
const existing = await ctx.db.comment.findUnique({
where: { id },
select: { id: true, authorId: true, entityType: true, entityId: true },
});
if (!existing) {
throw new TRPCError({ code: "NOT_FOUND", message: "Comment not found" });
}
await assertCommentEntityAccess(ctx, existing.entityType, existing.entityId);
return existing;
}
export async function resolveComment(
ctx: CommentProcedureContext,
input: z.infer<typeof ResolveCommentInputSchema>,
) {
const userId = ctx.dbUser?.id;
if (!userId) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
const existing = await findManageableComment(ctx, input.id);
assertCommentManageableByActor({
authorId: existing.authorId,
actorUserId: userId,
isAdmin: ctx.dbUser?.systemRole === "ADMIN",
action: "resolve",
});
const updated = await ctx.db.comment.update({
where: { id: input.id },
data: { resolved: input.resolved },
include: commentWithAuthorInclude,
});
void createAuditEntry({
db: ctx.db,
entityType: "Comment",
entityId: input.id,
action: "UPDATE",
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
summary: input.resolved ? "Resolved comment" : "Unresolved comment",
after: updated as unknown as Record<string, unknown>,
source: "ui",
});
return updated;
}
export async function deleteComment(
ctx: CommentProcedureContext,
input: z.infer<typeof DeleteCommentInputSchema>,
) {
const userId = ctx.dbUser?.id;
if (!userId) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
const existing = await findManageableComment(ctx, input.id);
assertCommentManageableByActor({
authorId: existing.authorId,
actorUserId: userId,
isAdmin: ctx.dbUser?.systemRole === "ADMIN",
action: "delete",
});
await ctx.db.comment.deleteMany({
where: { parentId: input.id },
});
await ctx.db.comment.delete({
where: { id: input.id },
});
void createAuditEntry({
db: ctx.db,
entityType: "Comment",
entityId: input.id,
action: "DELETE",
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
before: existing as unknown as Record<string, unknown>,
source: "ui",
});
}