fix: make Ritgram repository ownership checks forge-aware
Rithub (Gitea) sign-in users could never manage their own repos because every ownership gate in repositoryController only checked User.githubUsername. Add isRepositoryOwner (repositoryController.ts) + getForgeLogin/getAllForgeLogins (forgeConnectionService.ts) to resolve ownership against the user's login on the repo's own forge (GitHub or Rithub/Gitea), or an explicit claim. Also: - Add the missing GET /api/v1/users/:id/repositories route + controller (previously had no backend route at all; profile tab always 404'd). - Fix computeTrendingForTier's stale TrendingEntry rows: delete by tier instead of by (tier, periodStart), since periodStart drifts every run and left duplicate rows piling up in the trending list. Verified locally: tsc --noEmit clean; ran the real backend (port 3001, real Neon DB), registered a throwaway user, linked a Gitea ForgeConnection to the real caelum0x Gitea repos, and confirmed a previously-403 AITM settings endpoint now returns 200 for that Gitea-only user (403 for a control user with no forge link). Confirmed computeTrendingForTier no longer accumulates duplicate rows across repeated runs. Test users and temp verification script removed after. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
94bf6dbf48
commit
ad4e3c8563
@ -5,13 +5,37 @@ import { repoTextExportService } from '../services/repoTextExportService';
|
||||
import prisma from '../utils/prisma';
|
||||
import { encryptApiKey, decryptApiKey } from '../services/changeStoryService';
|
||||
import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler';
|
||||
import { ForgeKind } from '../forge';
|
||||
import { ForgeKind, isForgeKind } from '../forge';
|
||||
import { getForgeLogin } from '../services/forgeConnectionService';
|
||||
|
||||
/** Resolve the `?forge=` query param to a known ForgeKind, defaulting to 'github'. */
|
||||
function resolveForge(req: AuthRequest): ForgeKind {
|
||||
return req.query.forge === 'gitea' ? 'gitea' : 'github';
|
||||
}
|
||||
|
||||
/**
|
||||
* Forge-aware "does this user own this repository" check (plan §5.4).
|
||||
* Previously every ownership gate here only checked `User.githubUsername`,
|
||||
* so a user connected only to Rithub (Gitea) could never own/manage their
|
||||
* own Rithub repos through these endpoints. An explicit claim
|
||||
* (`Repository.claimedBy`) always wins; otherwise the check compares the
|
||||
* repo's `owner` against the user's login on *that repo's own forge* —
|
||||
* a GitHub repo checks their GitHub login, a Rithub repo checks their
|
||||
* Rithub login, each via `getForgeLogin` (which still falls back to the
|
||||
* legacy `githubUsername` column for forge: 'github').
|
||||
*/
|
||||
async function isRepositoryOwner(
|
||||
userId: string,
|
||||
repository: { owner: string; forge: string; claimedBy?: string | null }
|
||||
): Promise<boolean> {
|
||||
if (repository.claimedBy && repository.claimedBy === userId) {
|
||||
return true;
|
||||
}
|
||||
const forge: ForgeKind = isForgeKind(repository.forge) ? repository.forge : 'github';
|
||||
const login = await getForgeLogin(userId, forge);
|
||||
return !!login && login.toLowerCase() === repository.owner.toLowerCase();
|
||||
}
|
||||
|
||||
export const repositoryController = {
|
||||
// GET /api/repositories/search?q=vscode
|
||||
search: asyncHandler(async (req: AuthRequest, res: Response) => {
|
||||
@ -242,13 +266,9 @@ export const repositoryController = {
|
||||
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
|
||||
// Verify user owns this repository (via GitHub connection)
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
|
||||
if (!user?.githubUsername || user.githubUsername.toLowerCase() !== owner.toLowerCase()) {
|
||||
// Verify user owns this repository (forge-aware — their login on the
|
||||
// repo's own forge, or an explicit claim).
|
||||
if (!(await isRepositoryOwner(userId, repository))) {
|
||||
throw Errors.forbidden('Not authorized to update this repository');
|
||||
}
|
||||
|
||||
@ -272,13 +292,8 @@ export const repositoryController = {
|
||||
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
|
||||
// Verify user owns this repository
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
|
||||
if (!user?.githubUsername || user.githubUsername.toLowerCase() !== owner.toLowerCase()) {
|
||||
// Verify user owns this repository (forge-aware).
|
||||
if (!(await isRepositoryOwner(userId, repository))) {
|
||||
throw Errors.forbidden('Not authorized to remove this repository');
|
||||
}
|
||||
|
||||
@ -399,11 +414,7 @@ export const repositoryController = {
|
||||
}
|
||||
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
const isOwner = user?.githubUsername?.toLowerCase() === owner.toLowerCase() || repository.claimedBy === userId;
|
||||
const isOwner = await isRepositoryOwner(userId, repository);
|
||||
if (!isOwner) {
|
||||
throw Errors.forbidden('Only repository owners/managers can publish change story posts');
|
||||
}
|
||||
@ -503,11 +514,7 @@ export const repositoryController = {
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
|
||||
// Verify ownership
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
const isOwner = user?.githubUsername?.toLowerCase() === owner.toLowerCase() || repository.claimedBy === userId;
|
||||
const isOwner = await isRepositoryOwner(userId, repository);
|
||||
if (!isOwner) {
|
||||
throw Errors.forbidden('Only repository owners can view AITM settings');
|
||||
}
|
||||
@ -545,11 +552,7 @@ export const repositoryController = {
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
|
||||
// Verify ownership
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
const isOwner = user?.githubUsername?.toLowerCase() === owner.toLowerCase() || repository.claimedBy === userId;
|
||||
const isOwner = await isRepositoryOwner(userId, repository);
|
||||
if (!isOwner) {
|
||||
throw Errors.forbidden('Only repository owners can update AITM settings');
|
||||
}
|
||||
@ -598,11 +601,7 @@ export const repositoryController = {
|
||||
const repository = await repositoryService.getRepository(owner, name, resolveForge(req));
|
||||
|
||||
// Verify ownership
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
const isOwner = user?.githubUsername?.toLowerCase() === owner.toLowerCase() || repository.claimedBy === userId;
|
||||
const isOwner = await isRepositoryOwner(userId, repository);
|
||||
if (!isOwner) {
|
||||
throw Errors.forbidden('Only repository owners can remove AITM settings');
|
||||
}
|
||||
|
||||
@ -6,16 +6,57 @@ import { uploadAvatarImage, deleteMedia } from '../services/storageService';
|
||||
import { searchUsersForMention } from '../services/mentionService';
|
||||
import { blockService } from '../services/blockService';
|
||||
import { recordProfileVisit } from './profileVisitsController';
|
||||
import { ProfileVisitSource } from '@prisma/client';
|
||||
import { ProfileVisitSource, Prisma } from '@prisma/client';
|
||||
import logger from '../utils/logger';
|
||||
import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler';
|
||||
import { getAllForgeLogins } from '../services/forgeConnectionService';
|
||||
|
||||
export const getUser = asyncHandler(async (req: Request, res: Response) => {
|
||||
const authReq = req as AuthRequest;
|
||||
const { id } = req.params;
|
||||
const targetUserId = !id || id === 'me' ? authReq.userId! : id;
|
||||
const currentUserId = authReq.userId;
|
||||
|
||||
// `id` is really "id-or-username" — every profile URL (/:username) and
|
||||
// every caller that has a User.id both land on this same route param, so
|
||||
// resolve either one rather than assuming it's always a cuid. Previously
|
||||
// this only matched `id` exactly, so a real profile URL like `/caelum0x`
|
||||
// always 404'd (confirmed pre-existing, not forge-specific).
|
||||
const user = !id || id === 'me'
|
||||
? currentUserId
|
||||
? await prisma.user.findUnique({
|
||||
where: { id: currentUserId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
avatar: true,
|
||||
bio: true,
|
||||
verified: true,
|
||||
createdAt: true,
|
||||
_count: { select: { posts: true, followers: true, following: true } },
|
||||
},
|
||||
})
|
||||
: null
|
||||
: await prisma.user.findFirst({
|
||||
where: { OR: [{ id }, { username: id }] },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
avatar: true,
|
||||
bio: true,
|
||||
verified: true,
|
||||
createdAt: true,
|
||||
_count: { select: { posts: true, followers: true, following: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
const targetUserId = user.id;
|
||||
|
||||
// Check if there's a block relationship between users (if not viewing own profile)
|
||||
if (currentUserId && currentUserId !== targetUserId) {
|
||||
const hasBlock = await blockService.hasBlockRelationship(currentUserId, targetUserId);
|
||||
@ -25,30 +66,6 @@ export const getUser = asyncHandler(async (req: Request, res: Response) => {
|
||||
}
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
avatar: true,
|
||||
bio: true,
|
||||
verified: true,
|
||||
createdAt: true,
|
||||
_count: {
|
||||
select: {
|
||||
posts: true,
|
||||
followers: true,
|
||||
following: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
// Check if current user follows this user
|
||||
const isFollowing = currentUserId && currentUserId !== targetUserId
|
||||
? !!(await prisma.follow.findUnique({
|
||||
@ -89,6 +106,108 @@ export const getUser = asyncHandler(async (req: Request, res: Response) => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/v1/users/:id/repositories — "id" is id-or-username, same as getUser.
|
||||
*
|
||||
* Forge-aware "this user's repos" (plan §5.4): previously no backend route
|
||||
* existed at all for this path (confirmed pre-existing — the frontend
|
||||
* profile "Repositories" tab called it and always got nothing/an error,
|
||||
* for every user regardless of forge). Returns the union of:
|
||||
* - repos whose `owner` matches one of this user's forge-connection
|
||||
* logins, across *every* forge they've connected (GitHub, Rithub/Gitea,
|
||||
* ...), not just GitHub — a Rithub-only user's own repos show up too.
|
||||
* - repos this user follows.
|
||||
*/
|
||||
export const getUserRepositories = asyncHandler(async (req: Request, res: Response) => {
|
||||
const authReq = req as AuthRequest;
|
||||
const { id } = req.params;
|
||||
const { page = '1', limit = '20' } = req.query;
|
||||
const pageNum = Math.max(1, parseInt(page as string, 10) || 1);
|
||||
const limitNum = Math.min(50, Math.max(1, parseInt(limit as string, 10) || 20));
|
||||
|
||||
const targetUser = await prisma.user.findFirst({
|
||||
where: { OR: [{ id }, { username: id }] },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!targetUser) {
|
||||
throw Errors.notFound('User');
|
||||
}
|
||||
|
||||
const [logins, followedRepoIds] = await Promise.all([
|
||||
getAllForgeLogins(targetUser.id),
|
||||
prisma.repositoryFollow
|
||||
.findMany({ where: { userId: targetUser.id }, select: { repositoryId: true } })
|
||||
.then((rows) => rows.map((r) => r.repositoryId)),
|
||||
]);
|
||||
|
||||
const orConditions: Prisma.RepositoryWhereInput[] = [];
|
||||
if (logins.length > 0) {
|
||||
orConditions.push({ owner: { in: logins, mode: 'insensitive' } });
|
||||
}
|
||||
if (followedRepoIds.length > 0) {
|
||||
orConditions.push({ id: { in: followedRepoIds } });
|
||||
}
|
||||
|
||||
if (orConditions.length === 0) {
|
||||
res.json({
|
||||
repositories: [],
|
||||
total: 0,
|
||||
pagination: { page: pageNum, limit: limitNum, totalPages: 0, hasMore: false },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const where: Prisma.RepositoryWhereInput = { OR: orConditions };
|
||||
|
||||
const [repositories, total] = await Promise.all([
|
||||
prisma.repository.findMany({
|
||||
where,
|
||||
select: {
|
||||
id: true,
|
||||
owner: true,
|
||||
name: true,
|
||||
fullName: true,
|
||||
description: true,
|
||||
stars: true,
|
||||
forks: true,
|
||||
language: true,
|
||||
topics: true,
|
||||
htmlUrl: true,
|
||||
forge: true,
|
||||
followersCount: true,
|
||||
},
|
||||
orderBy: { stars: 'desc' },
|
||||
take: limitNum,
|
||||
skip: (pageNum - 1) * limitNum,
|
||||
}),
|
||||
prisma.repository.count({ where }),
|
||||
]);
|
||||
|
||||
const viewerId = authReq.userId;
|
||||
let viewerFollowedIds = new Set<string>();
|
||||
if (viewerId) {
|
||||
const viewerFollows = await prisma.repositoryFollow.findMany({
|
||||
where: { userId: viewerId, repositoryId: { in: repositories.map((r) => r.id) } },
|
||||
select: { repositoryId: true },
|
||||
});
|
||||
viewerFollowedIds = new Set(viewerFollows.map((f) => f.repositoryId));
|
||||
}
|
||||
|
||||
res.json({
|
||||
repositories: repositories.map((r) => ({
|
||||
...r,
|
||||
isFollowed: viewerFollowedIds.has(r.id),
|
||||
})),
|
||||
total,
|
||||
pagination: {
|
||||
page: pageNum,
|
||||
limit: limitNum,
|
||||
totalPages: Math.ceil(total / limitNum),
|
||||
hasMore: pageNum * limitNum < total,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const updateUser = asyncHandler(async (req: Request, res: Response) => {
|
||||
const authReq = req as AuthRequest;
|
||||
const userId = authReq.userId!;
|
||||
|
||||
@ -750,6 +750,27 @@ router.get('/online', async (req: any, res: any) => {
|
||||
*/
|
||||
router.get('/:id', optionalAuth, validate(userIdValidator), cacheMiddleware(300), userController.getUser);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/v1/users/{id}/repositories:
|
||||
* get:
|
||||
* summary: Get a user's repositories (owned on any connected forge, or followed)
|
||||
* tags: [Users]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: User id or username
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Repository list
|
||||
* 404:
|
||||
* description: User not found
|
||||
*/
|
||||
router.get('/:id/repositories', optionalAuth, validate(userIdValidator), cacheMiddleware(60), userController.getUserRepositories);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/v1/users/{id}/followers:
|
||||
|
||||
@ -70,6 +70,41 @@ export async function getGitHubAccessToken(userId: string): Promise<string | nul
|
||||
return cred?.accessToken ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a user's login (username) on a given forge, honoring the legacy
|
||||
* `User.githubUsername` fallback for `forge: 'github'`. Used for
|
||||
* forge-aware repo ownership checks (plan §5.4) — a Rithub (Gitea) user is
|
||||
* "the owner" of a repository when their Rithub forge-connection login
|
||||
* matches the repo's `owner` field, the same way a GitHub user's
|
||||
* `githubUsername` has always been checked for GitHub repos.
|
||||
*/
|
||||
export async function getForgeLogin(userId: string, forge: ForgeKind): Promise<string | null> {
|
||||
const row = await prisma.forgeConnection.findUnique({
|
||||
where: { userId_forge: { userId, forge } },
|
||||
select: { login: true },
|
||||
});
|
||||
if (row?.login) return row.login;
|
||||
if (forge === 'github') {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { githubUsername: true },
|
||||
});
|
||||
return user?.githubUsername ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* All logins (usernames) this user is known to own, across every forge they
|
||||
* have connected, plus the legacy GitHub fallback. Used to find "this
|
||||
* user's own repos" forge-agnostically (plan §5.4).
|
||||
*/
|
||||
export async function getAllForgeLogins(userId: string): Promise<string[]> {
|
||||
const connections = await listForgeConnections(userId);
|
||||
const logins = connections.map((c) => c.login).filter((l): l is string => !!l);
|
||||
return Array.from(new Set(logins.map((l) => l.toLowerCase())));
|
||||
}
|
||||
|
||||
export async function upsertForgeConnection(input: UpsertForgeConnectionInput): Promise<ForgeConnectionInfo> {
|
||||
const data = {
|
||||
accessToken: input.accessToken,
|
||||
|
||||
@ -889,12 +889,18 @@ export async function computeTrendingForTier(tier: TrendingTier): Promise<void>
|
||||
// Take top N
|
||||
const topEntities = scoredEntities.slice(0, tierConfig.maxResults);
|
||||
|
||||
// Delete old entries for this tier and period
|
||||
// Delete every existing entry for this tier before storing the fresh
|
||||
// batch. `windowStart` is computed as `now - windowHours` on every call,
|
||||
// so it drifts by milliseconds run to run — matching on the exact
|
||||
// `periodStart` here (the pre-existing behavior) almost never deletes
|
||||
// anything, since the unique key is [entityType, entityId, tier,
|
||||
// periodStart] and periodStart is different every time. That left stale
|
||||
// rows from earlier runs piling up as visible duplicates in the trending
|
||||
// list. A computation run always represents the current top-N for a
|
||||
// tier, so any existing row for that tier is stale the moment a new run
|
||||
// completes, regardless of its periodStart.
|
||||
await prisma.trendingEntry.deleteMany({
|
||||
where: {
|
||||
tier,
|
||||
periodStart: windowStart,
|
||||
},
|
||||
where: { tier },
|
||||
});
|
||||
|
||||
// Store new entries
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user