Adds Pet.nickname (nullable, max 30 chars) and a shared formatPetName()
helper so the display format ("Rex (Rexi)") stays consistent across
feed, admin panel, messages, sidebar/nav, and mentions instead of
duplicating the formatting logic at each read site.
316 lines
11 KiB
TypeScript
316 lines
11 KiB
TypeScript
import "server-only";
|
||
import { z } from "zod";
|
||
import { TRPCError } from "@trpc/server";
|
||
import { router, protectedProcedure, rateLimited } from "@/trpc/init";
|
||
import {
|
||
createSignedUploadUrl,
|
||
ALLOWED_CONTENT_TYPES,
|
||
MAX_FILE_SIZE,
|
||
} from "@/lib/supabase-storage";
|
||
import { redis } from "@/lib/redis";
|
||
import { fanOutPost } from "@/lib/feed-helpers";
|
||
import { randomUUID } from "crypto";
|
||
import type { PrismaClient } from "@prisma/client";
|
||
import { extractHashtags, saveHashtags } from "@/lib/hashtag-helpers";
|
||
import { checkAgainstBlacklist } from "@/lib/blacklist";
|
||
import { createMentionNotifications } from "@/lib/mention-helpers";
|
||
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
|
||
|
||
/**
|
||
* Posts tRPC router — photo post creation, caption edit, deletion, feed hydration.
|
||
*
|
||
* Security (T-02-30 to T-02-35):
|
||
* - All mutations assert pet ownership via ctx.userId before any write
|
||
* - images[].key validated with .startsWith('posts/') — prevents path traversal (T-02-31)
|
||
* - images.max(10) — prevents carousel injection (T-02-32)
|
||
* - getPresignedUrl scopes key to posts/{ownerId}/{petId}/ (T-02-31)
|
||
* - supabase-storage.ts is server-only — client only receives signed URL (T-02-33)
|
||
* - updateCaption/delete assert ownership via post→pet→ownerId (T-02-34)
|
||
*/
|
||
|
||
/**
|
||
* Shared ownership helper for post-level checks.
|
||
* Loads post with pet relation and throws FORBIDDEN if ctx.userId doesn't own the pet.
|
||
*/
|
||
async function assertPostOwnership(
|
||
prisma: PrismaClient,
|
||
postId: string,
|
||
userId: string
|
||
) {
|
||
const post = await prisma.post.findUnique({
|
||
where: { id: postId },
|
||
select: {
|
||
id: true,
|
||
petId: true,
|
||
pet: { select: { id: true, ownerId: true } },
|
||
},
|
||
});
|
||
|
||
if (!post || post.pet.ownerId !== userId) {
|
||
throw new TRPCError({ code: "FORBIDDEN" });
|
||
}
|
||
|
||
return post;
|
||
}
|
||
|
||
export const postsRouter = router({
|
||
/**
|
||
* Generate a presigned PUT URL for direct upload to Supabase Storage.
|
||
* Key scoped to posts/{ownerId}/{petId}/{uuid}.ext (T-02-31).
|
||
* Ownership assertion prevents non-owners from getting URLs for another pet (T-02-30).
|
||
*/
|
||
getPresignedUrl: protectedProcedure
|
||
.input(
|
||
z.object({
|
||
petId: z.string().min(1),
|
||
contentType: z.enum(ALLOWED_CONTENT_TYPES),
|
||
fileSize: z
|
||
.number()
|
||
.max(MAX_FILE_SIZE, "Photo must be under 10 MB"),
|
||
})
|
||
)
|
||
.mutation(async ({ ctx, input }) => {
|
||
// Ownership assertion (T-02-30)
|
||
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
|
||
|
||
const ext = input.contentType.split("/")[1].replace("jpeg", "jpg");
|
||
// Key scoped to posts/{ownerId}/{petId}/ (T-02-31 path-traversal prevention)
|
||
const key = `posts/${ctx.userId}/${input.petId}/${randomUUID()}.${ext}`;
|
||
|
||
const { signedUrl } = await createSignedUploadUrl(key);
|
||
return { presignedUrl: signedUrl, key };
|
||
}),
|
||
|
||
/**
|
||
* Create a photo post with 1–10 images + fan-out to follower feeds.
|
||
*
|
||
* imageKeys validated:
|
||
* - .startsWith('posts/') — path-traversal prevention (T-02-31, RESEARCH Pitfall 4)
|
||
* - .min(1).max(10) — PHOTO-02 carousel limit (T-02-32)
|
||
*
|
||
* Fan-out: fanOutPost adds this post to every follower's Redis sorted set.
|
||
*/
|
||
create: protectedProcedure
|
||
.use(rateLimited("posts.create", 10, 600))
|
||
.input(
|
||
z.object({
|
||
petId: z.string().min(1),
|
||
caption: z.string().max(500).nullable().optional(),
|
||
aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]).default("NONE"),
|
||
images: z
|
||
.array(
|
||
z.object({
|
||
key: z.string().startsWith("posts/"),
|
||
blurhash: z.string().max(100).nullable().optional(),
|
||
})
|
||
)
|
||
.min(1)
|
||
.max(10),
|
||
})
|
||
)
|
||
.mutation(async ({ ctx, input }) => {
|
||
// Ownership assertion (T-02-30): posting as another pet blocked
|
||
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
|
||
|
||
// Create Post + PostImage[] in one nested write
|
||
const post = await ctx.prisma.post.create({
|
||
data: {
|
||
petId: input.petId,
|
||
type: "PHOTO",
|
||
caption: input.caption ?? null,
|
||
aiDisclosure: input.aiDisclosure,
|
||
images: {
|
||
create: input.images.map((img, position) => ({
|
||
storageKey: img.key,
|
||
blurhash: img.blurhash ?? null,
|
||
position,
|
||
})),
|
||
},
|
||
},
|
||
include: {
|
||
images: { orderBy: { position: "asc" } },
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
milestone: true,
|
||
},
|
||
});
|
||
|
||
// Fan-out to all followers' Redis feed inboxes (PHOTO-01)
|
||
// Wrapped so Redis failure never rolls back an already-created post
|
||
await fanOutPost(redis, post.id, input.petId, post.createdAt, ctx.prisma).catch((err) =>
|
||
console.error("[posts] feed fan-out failed", err)
|
||
);
|
||
|
||
// Index hashtags — never fails post creation
|
||
const tags = extractHashtags(input.caption ?? null);
|
||
await saveHashtags(ctx.prisma, post.id, tags).catch((err) =>
|
||
console.error("[posts] hashtag indexing failed", err)
|
||
);
|
||
|
||
// Notify @mentioned pets in caption
|
||
createMentionNotifications(ctx.prisma, input.caption ?? null, input.petId, post.id).catch((err) =>
|
||
console.error("[posts] mention notifications failed", err)
|
||
);
|
||
|
||
// Auto-hide on blacklist match (Gitea #10 Phase 3) — never blocks
|
||
// creation, just hides it immediately after, same as a manual
|
||
// moderator hide (reversible via admin.unhidePost).
|
||
const blacklist = await ctx.prisma.blacklistEntry.findMany();
|
||
const blacklistResult = checkAgainstBlacklist(input.caption ?? null, tags, blacklist);
|
||
if (blacklistResult.matched) {
|
||
await ctx.prisma.$transaction([
|
||
ctx.prisma.post.update({ where: { id: post.id }, data: { hiddenAt: new Date() } }),
|
||
ctx.prisma.moderationLog.create({
|
||
data: {
|
||
action: "HIDE_POST",
|
||
targetType: "POST",
|
||
targetId: post.id,
|
||
reason: `Auto-hidden: ${blacklistResult.reason}`,
|
||
moderatorId: "SYSTEM",
|
||
moderatorRole: null,
|
||
ipAddress: null,
|
||
},
|
||
}),
|
||
]);
|
||
return { ...post, hiddenAt: new Date() };
|
||
}
|
||
|
||
return post;
|
||
}),
|
||
|
||
/**
|
||
* Edit the caption on a post the caller owns (PHOTO-03).
|
||
* Ownership asserted via post→pet→ownerId.
|
||
*/
|
||
updateCaption: protectedProcedure
|
||
.input(
|
||
z.object({
|
||
postId: z.string().min(1),
|
||
caption: z.string().max(500).nullable(),
|
||
})
|
||
)
|
||
.mutation(async ({ ctx, input }) => {
|
||
// Ownership assertion (T-02-34)
|
||
await assertPostOwnership(ctx.prisma, input.postId, ctx.userId);
|
||
|
||
const updated = await ctx.prisma.post.update({
|
||
where: { id: input.postId },
|
||
data: { caption: input.caption },
|
||
include: {
|
||
images: { orderBy: { position: "asc" } },
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
milestone: true,
|
||
},
|
||
});
|
||
|
||
return updated;
|
||
}),
|
||
|
||
/**
|
||
* Delete a post + cascade PostImages (PHOTO-04).
|
||
* Ownership asserted via post→pet→ownerId.
|
||
* Note: feed cleanup (ZREM across follower sets) is best-effort in Phase 2.
|
||
* feed.getFeed already filters deleted post IDs since findMany won't return them.
|
||
*/
|
||
delete: protectedProcedure
|
||
.input(z.object({ postId: z.string().min(1) }))
|
||
.mutation(async ({ ctx, input }) => {
|
||
// Ownership assertion (T-02-34)
|
||
await assertPostOwnership(ctx.prisma, input.postId, ctx.userId);
|
||
|
||
// PostImages cascade via schema onDelete: Cascade
|
||
await ctx.prisma.post.delete({ where: { id: input.postId } });
|
||
|
||
return { deleted: true };
|
||
}),
|
||
|
||
/**
|
||
* List posts for a given pet, ordered newest first.
|
||
* Includes images and milestone relation for rendering PostCard.
|
||
*/
|
||
byPetId: protectedProcedure
|
||
.input(
|
||
z.object({
|
||
petId: z.string().min(1),
|
||
cursor: z.string().nullish(),
|
||
limit: z.number().min(1).max(50).default(20),
|
||
})
|
||
)
|
||
.query(async ({ ctx, input }) => {
|
||
const posts = await ctx.prisma.post.findMany({
|
||
where: {
|
||
petId: input.petId,
|
||
hiddenAt: null,
|
||
pet: { OR: [{ ownerId: ctx.userId }, { owner: { shadowban: null } }] },
|
||
...(input.cursor
|
||
? { createdAt: { lt: new Date(input.cursor) } }
|
||
: {}),
|
||
},
|
||
orderBy: { createdAt: "desc" },
|
||
take: input.limit + 1,
|
||
include: {
|
||
images: { orderBy: { position: "asc" } },
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
milestone: true,
|
||
videoPost: { select: { status: true, muxPlaybackId: true } },
|
||
repost: {
|
||
include: {
|
||
originalPost: {
|
||
include: {
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
images: { orderBy: { position: "asc" } },
|
||
milestone: true,
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
});
|
||
|
||
const hasNextPage = posts.length > input.limit;
|
||
const items = hasNextPage ? posts.slice(0, input.limit) : posts;
|
||
const nextCursor = hasNextPage
|
||
? items[items.length - 1].createdAt.toISOString()
|
||
: null;
|
||
|
||
return { posts: items, nextCursor };
|
||
}),
|
||
|
||
/**
|
||
* Fetch a single post by id, for deep-linking (e.g. notifications) into the
|
||
* detail dialog without requiring the post to be among the pet's most
|
||
* recently loaded posts. Same visibility rule as byPetId.
|
||
*/
|
||
getById: protectedProcedure
|
||
.input(z.object({ postId: z.string().min(1) }))
|
||
.query(async ({ ctx, input }) => {
|
||
const post = await ctx.prisma.post.findFirst({
|
||
where: {
|
||
id: input.postId,
|
||
hiddenAt: null,
|
||
pet: { OR: [{ ownerId: ctx.userId }, { owner: { shadowban: null } }] },
|
||
},
|
||
include: {
|
||
images: { orderBy: { position: "asc" } },
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
milestone: true,
|
||
videoPost: { select: { status: true, muxPlaybackId: true } },
|
||
repost: {
|
||
include: {
|
||
originalPost: {
|
||
include: {
|
||
pet: { select: { id: true, name: true, nickname: true, avatarKey: true } },
|
||
images: { orderBy: { position: "asc" } },
|
||
milestone: true,
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
});
|
||
|
||
if (!post) throw new TRPCError({ code: "NOT_FOUND" });
|
||
|
||
return post;
|
||
}),
|
||
});
|