mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-03 14:34:40 +00:00
Merge commit from fork
* fix(share): only return share-visible field values on public share links The public share children and file detail endpoints returned every custom field value on an asset, while the share's field settings only hid them in the share UI. Filter fieldValues server-side to the fields turned on for the share, matching what GET /shares/:shareId/fields already returns. * fix(share): stop returning share passwords and compare them in constant time Share link responses included the saved password in plain text. Remove it from ShareLinkInfo; clients already get hasPassword. Check the password a guest enters with a constant-time comparison of SHA-256 digests instead of a string comparison. The share settings panel no longer pre-fills the saved password. When a password is set, the field starts empty with a hint, Save stays disabled until a new password is typed, and the field clears after saving. Turning the password off still removes it. * fix(kanban): limit task lists and task reads to the caller's projects Kanban checked only team membership for task reads, so a member invited to one project could list every task in the team and open any task, its linked files, comments and activity. - Task lists and the tasks linked to a file now include, for project-scoped members, only tasks in projects they belong to plus tasks they created, report, or are assigned to. Team-scoped members see every task as before. - Reading a task, its files, comments and activity follows the same rule: a project-scoped member outside the task's project needs to be its creator, reporter or assignee. - Linking a file to a task (create, update, or the link endpoints) now requires Read on that file, since linked files are shown to everyone who can read the task. * fix(security): sign only issued comment attachments and keep files on comment delete Kanban comment attachments: - Upload keys now include the team and the uploader: kanban/attachments/<teamId>/<userId>/<ulid>/<file name>. - addComment rejects any attachment key that was not issued to the comment author for the task's team, so a client can no longer store an arbitrary storage key in a comment. - When comments are read, only keys of kanban comment attachments for the task's team (or the previous kanban/attachments/<ulid>/<name> form) are presigned. Keys stored earlier that point anywhere else are dropped. Asset comment attachments: - createComment only links attachment uploads made by the commenter in the same project that are not linked to another comment. Project files can no longer be linked as comment attachments. - deleteComment deletes the stored object and asset only for attachment uploads not linked elsewhere; anything else linked to the comment is only unlinked. Upload keys: - Sanitize the file name in kanban and project attachment upload keys, as regular uploads already do, so a name cannot add path segments. - The local storage backend rejects keys with a '..' segment instead of resolving them into another object's path. * fix(security): enforce visibility and protect comment attachments --------- Co-authored-by: phj1081 <5908832+phj1081@users.noreply.github.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority, KanbanTaskEventType } from '@shumai/db/enums'
|
||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
import { kanbanService } from './kanban'
|
||||
|
||||
@@ -646,7 +646,7 @@ describe('KanbanService', () => {
|
||||
)
|
||||
|
||||
// Create attachment
|
||||
const att = await kanbanService.createAttachment(team.id, {
|
||||
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: 'design.png',
|
||||
size: 1024,
|
||||
contentType: 'image/png',
|
||||
@@ -688,6 +688,119 @@ describe('KanbanService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Comment attachment keys', () => {
|
||||
function payload(key: string) {
|
||||
return [{ id: 'att-1', name: 'file.txt', key, sizeByte: 1, contentType: 'text/plain' }]
|
||||
}
|
||||
|
||||
it('rejects attachment keys that were not issued to the author for the task team', async () => {
|
||||
const { team, editor, reviewer } = await setupTeamAndUsers()
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
|
||||
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||
|
||||
const foreignTeam = await kanbanService.createAttachment(otherTeam.id, editor.id, {
|
||||
fileName: 'other.png',
|
||||
size: 1,
|
||||
})
|
||||
const otherUser = await kanbanService.createAttachment(team.id, reviewer.id, {
|
||||
fileName: 'theirs.png',
|
||||
size: 1,
|
||||
})
|
||||
const own = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: 'own.png',
|
||||
size: 1,
|
||||
})
|
||||
const ownDir = own.key.slice(0, own.key.lastIndexOf('/'))
|
||||
|
||||
for (const key of [
|
||||
'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
'avatars/someone.png',
|
||||
'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/old.png',
|
||||
foreignTeam.key,
|
||||
otherUser.key,
|
||||
`${ownDir}/../../../../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov`,
|
||||
`kanban/attachments/${team.id}/${editor.id}/not-a-ulid/own.png`,
|
||||
]) {
|
||||
await expect(
|
||||
kanbanService.addComment(task.id, editor.id, 'see attached', payload(key)),
|
||||
).rejects.toThrow(/Invalid attachment/)
|
||||
}
|
||||
|
||||
const comments = await kanbanService.listComments(task.id)
|
||||
expect(comments).toHaveLength(0)
|
||||
|
||||
const accepted = await kanbanService.addComment(
|
||||
task.id,
|
||||
editor.id,
|
||||
'see attached',
|
||||
payload(own.key),
|
||||
)
|
||||
expect(accepted.attachments.map((a) => a.id)).toEqual(['att-1'])
|
||||
})
|
||||
|
||||
it('does not sign stored attachment keys outside kanban attachments', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor')
|
||||
const legacyKey = 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/notes.txt'
|
||||
|
||||
await prisma.kanbanTaskComment.create({
|
||||
data: {
|
||||
taskId: task.id,
|
||||
authorId: editor.id,
|
||||
body: 'stored before validation',
|
||||
attachments: [
|
||||
{
|
||||
id: 'a',
|
||||
name: 'secret',
|
||||
key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
sizeByte: 1,
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
name: 'escape',
|
||||
key: 'kanban/attachments/../files/x/master.mov',
|
||||
sizeByte: 1,
|
||||
},
|
||||
{ id: 'c', name: 'notes.txt', key: legacyKey, sizeByte: 1 },
|
||||
{
|
||||
id: 'd',
|
||||
name: 'other-team.txt',
|
||||
key: `kanban/attachments/other-team/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/x.txt`,
|
||||
sizeByte: 1,
|
||||
},
|
||||
{
|
||||
id: 'e',
|
||||
name: 'current.txt',
|
||||
key: `kanban/attachments/${team.id}/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/y.txt`,
|
||||
sizeByte: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const [comment] = await kanbanService.listComments(task.id)
|
||||
expect(comment.attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||
|
||||
const detail = await kanbanService.getTask(task.id)
|
||||
expect(detail.comments[0].attachments.map((a) => a.id)).toEqual(['c', 'e'])
|
||||
})
|
||||
|
||||
it('keeps attachment uploads inside the team attachment folder', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
|
||||
const att = await kanbanService.createAttachment(team.id, editor.id, {
|
||||
fileName: '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov',
|
||||
size: 1,
|
||||
})
|
||||
|
||||
const parts = att.key.split('/')
|
||||
expect(parts.slice(0, 4)).toEqual(['kanban', 'attachments', team.id, editor.id])
|
||||
expect(parts).toHaveLength(6)
|
||||
expect(parts).not.toContain('..')
|
||||
expect(att.name).toBe('../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Task Ordering & Fractional Indexing
|
||||
// --------------------------------------------------------------------------
|
||||
@@ -1139,4 +1252,185 @@ describe('KanbanService', () => {
|
||||
expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp')
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Project membership
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Project membership', () => {
|
||||
async function setupProjectScopedMember() {
|
||||
const { team, owner, reviewer } = await setupTeamAndUsers()
|
||||
const client = await prisma.user.create({
|
||||
data: { name: 'Client Reviewer', email: 'client@example.com' },
|
||||
})
|
||||
const ownProject = await prisma.project.create({
|
||||
data: { name: 'Client Project', teamId: team.id },
|
||||
})
|
||||
const otherProject = await prisma.project.create({
|
||||
data: { name: 'Internal Project', teamId: team.id },
|
||||
})
|
||||
const clientMember = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const ownTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Client task', projectId: ownProject.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const otherTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Internal task', projectId: otherProject.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const teamTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Team task' },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
const assignedTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Assigned internal task', projectId: otherProject.id, assigneeId: client.id },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
return {
|
||||
team,
|
||||
owner,
|
||||
reviewer,
|
||||
client,
|
||||
otherProject,
|
||||
ownTask,
|
||||
otherTask,
|
||||
teamTask,
|
||||
assignedTask,
|
||||
}
|
||||
}
|
||||
|
||||
it('lists only tasks in their projects, or that they take part in, for project-scoped members', async () => {
|
||||
const { team, client, otherProject, ownTask, assignedTask } = await setupProjectScopedMember()
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, client.id)
|
||||
expect(list.data.map((t) => t.id).sort()).toEqual([ownTask.id, assignedTask.id].sort())
|
||||
expect(list.pageInfo.total).toBe(2)
|
||||
|
||||
const filtered = await kanbanService.listTasks(
|
||||
team.id,
|
||||
{ projectId: otherProject.id },
|
||||
client.id,
|
||||
)
|
||||
expect(filtered.data.map((t) => t.id)).toEqual([assignedTask.id])
|
||||
})
|
||||
|
||||
it('lists every team task for team-scoped members', async () => {
|
||||
const { team, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, reviewer.id)
|
||||
expect(list.data.map((t) => t.id).sort()).toEqual(
|
||||
[ownTask.id, otherTask.id, teamTask.id, assignedTask.id].sort(),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows only readable dependencies, dependents, and dependency events', async () => {
|
||||
const { owner, team, client, reviewer, ownTask, otherTask, teamTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
|
||||
await kanbanService.setDependencies(
|
||||
ownTask.id,
|
||||
[otherTask.id, assignedTask.id, teamTask.id],
|
||||
owner.id,
|
||||
)
|
||||
await kanbanService.setDependencies(ownTask.id, [otherTask.id, assignedTask.id], owner.id)
|
||||
await kanbanService.setDependencies(teamTask.id, [ownTask.id], owner.id)
|
||||
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||
|
||||
const detail = await kanbanService.getTask(ownTask.id, client.id)
|
||||
expect(detail.dependencies.map((task) => task.id)).toEqual([assignedTask.id])
|
||||
expect(detail.dependents).toEqual([])
|
||||
expect(detail.dependencyCount).toBe(1)
|
||||
expect(detail.dependentCount).toBe(0)
|
||||
|
||||
const events = await kanbanService.listEvents(ownTask.id, client.id)
|
||||
for (const history of [detail.events, events]) {
|
||||
expect(
|
||||
history.filter((event) => event.type === KanbanTaskEventType.DEPENDENCY_ADDED),
|
||||
).toEqual([expect.objectContaining({ data: { parentId: assignedTask.id } })])
|
||||
expect(history).toContainEqual(
|
||||
expect.objectContaining({ type: KanbanTaskEventType.CREATED }),
|
||||
)
|
||||
expect(history).not.toContainEqual(
|
||||
expect.objectContaining({ type: KanbanTaskEventType.DEPENDENCY_REMOVED }),
|
||||
)
|
||||
}
|
||||
|
||||
const teamDetail = await kanbanService.getTask(ownTask.id, reviewer.id)
|
||||
expect(teamDetail.dependencies.map((task) => task.id).sort()).toEqual(
|
||||
[otherTask.id, assignedTask.id].sort(),
|
||||
)
|
||||
expect(teamDetail.dependents.map((task) => task.id)).toEqual([teamTask.id])
|
||||
expect(teamDetail.events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: KanbanTaskEventType.DEPENDENCY_REMOVED,
|
||||
data: { parentId: teamTask.id },
|
||||
}),
|
||||
)
|
||||
|
||||
const summary = await kanbanService.listTasks(team.id, {}, client.id)
|
||||
expect(summary.data).toContainEqual(
|
||||
expect.objectContaining({ id: ownTask.id, dependencyCount: 1, dependentCount: 0 }),
|
||||
)
|
||||
|
||||
const updated = await kanbanService.updateTask(
|
||||
assignedTask.id,
|
||||
{ title: 'Updated assigned task' },
|
||||
client.id,
|
||||
null,
|
||||
)
|
||||
expect(updated).toMatchObject({ dependencyCount: 0, dependentCount: 1 })
|
||||
})
|
||||
|
||||
it('lists no tasks for users outside the team', async () => {
|
||||
const { team } = await setupProjectScopedMember()
|
||||
const outsider = await prisma.user.create({
|
||||
data: { name: 'Outsider', email: 'outsider@example.com' },
|
||||
})
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, {}, outsider.id)
|
||||
expect(list.data).toEqual([])
|
||||
})
|
||||
|
||||
it('lists only readable tasks linked to an asset', async () => {
|
||||
const { team, owner, client, reviewer, otherProject, otherTask, assignedTask } =
|
||||
await setupProjectScopedMember()
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'internal.mp4',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
projectId: otherProject.id,
|
||||
creatorId: owner.id,
|
||||
},
|
||||
})
|
||||
await kanbanService.linkAsset(team.id, otherTask.id, asset.id)
|
||||
await kanbanService.linkAsset(team.id, assignedTask.id, asset.id)
|
||||
await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id)
|
||||
|
||||
const forClient = await kanbanService.listTasksForAsset(team.id, asset.id, client.id)
|
||||
expect(forClient.map((t) => t.id)).toEqual([assignedTask.id])
|
||||
expect(forClient[0].dependencyCount).toBe(0)
|
||||
|
||||
const forReviewer = await kanbanService.listTasksForAsset(team.id, asset.id, reviewer.id)
|
||||
expect(forReviewer.map((t) => t.id).sort()).toEqual([otherTask.id, assignedTask.id].sort())
|
||||
expect(forReviewer).toContainEqual(
|
||||
expect.objectContaining({ id: assignedTask.id, dependencyCount: 1 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import { paginateQuery } from '../pagination'
|
||||
import { getAvatarUrl } from '../user/avatar'
|
||||
import { s3Service } from '../s3/s3'
|
||||
import { getProxyType } from '../utils/mime'
|
||||
import { sanitizeFilename } from '../utils/filename'
|
||||
import { assetService } from '../asset/asset'
|
||||
import type {
|
||||
CreateKanbanGoalRequest,
|
||||
@@ -28,6 +29,73 @@ import type {
|
||||
} from '@shumai/dtos'
|
||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
|
||||
type TaskEventWithActor = Prisma.KanbanTaskEventGetPayload<{ include: { actor: true } }>
|
||||
|
||||
function dependencyEventParentId(event: TaskEventWithActor): string | undefined {
|
||||
if (
|
||||
event.type === KanbanTaskEventType.DEPENDENCY_ADDED ||
|
||||
event.type === KanbanTaskEventType.DEPENDENCY_REMOVED
|
||||
) {
|
||||
const parentId = event.data?.parentId
|
||||
if (typeof parentId === 'string') return parentId
|
||||
}
|
||||
}
|
||||
|
||||
function taskRelationCountSelect(
|
||||
taskFilter: Prisma.KanbanTaskWhereInput | undefined,
|
||||
): Prisma.KanbanTaskCountOutputTypeSelect {
|
||||
return {
|
||||
comments: true,
|
||||
assets: true,
|
||||
dependencies: taskFilter ? { where: { parent: taskFilter } } : true,
|
||||
dependents: taskFilter ? { where: { child: taskFilter } } : true,
|
||||
}
|
||||
}
|
||||
|
||||
const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/
|
||||
|
||||
function isSafeKeySegment(segment: string): boolean {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return segment !== '' && segment !== '.' && segment !== '..' && !/[\\\x00-\x1f\x7f]/.test(segment)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a comment attachment key issued by `createAttachment`:
|
||||
* `kanban/attachments/<teamId>/<uploaderId>/<ulid>/<file name>`.
|
||||
*/
|
||||
function parseAttachmentKey(key: string): { teamId: string; uploaderId: string } | null {
|
||||
const parts = key.split('/')
|
||||
if (
|
||||
parts.length !== 6 ||
|
||||
parts[0] !== 'kanban' ||
|
||||
parts[1] !== 'attachments' ||
|
||||
!isSafeKeySegment(parts[2]) ||
|
||||
!isSafeKeySegment(parts[3]) ||
|
||||
!ULID_PATTERN.test(parts[4]) ||
|
||||
!isSafeKeySegment(parts[5])
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { teamId: parts[2], uploaderId: parts[3] }
|
||||
}
|
||||
|
||||
/** Keys of comment attachments stored before keys carried the team and uploader. */
|
||||
function isLegacyAttachmentKey(key: string): boolean {
|
||||
const parts = key.split('/')
|
||||
return (
|
||||
parts.length === 4 &&
|
||||
parts[0] === 'kanban' &&
|
||||
parts[1] === 'attachments' &&
|
||||
ULID_PATTERN.test(parts[2]) &&
|
||||
isSafeKeySegment(parts[3])
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether a stored attachment key may be signed for a comment on a task in `teamId`. */
|
||||
function isReadableAttachmentKey(key: string, teamId: string): boolean {
|
||||
return parseAttachmentKey(key)?.teamId === teamId || isLegacyAttachmentKey(key)
|
||||
}
|
||||
|
||||
export class KanbanService {
|
||||
// --------------------------------------------------------------------------
|
||||
// Goal CRUD
|
||||
@@ -314,7 +382,7 @@ export class KanbanService {
|
||||
})
|
||||
}
|
||||
|
||||
async getTask(taskId: string): Promise<KanbanTaskDetail> {
|
||||
async getTask(taskId: string, viewerId?: string): Promise<KanbanTaskDetail> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
include: {
|
||||
@@ -354,27 +422,38 @@ export class KanbanService {
|
||||
throw new HTTPException(404, { message: 'Task not found' })
|
||||
}
|
||||
|
||||
const readableIds = await this.readableRelatedTaskIds(task.teamId, viewerId, [
|
||||
...task.dependencies.map((link) => link.parentId),
|
||||
...task.dependents.map((link) => link.childId),
|
||||
...task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||
])
|
||||
const dependencies = task.dependencies.filter(
|
||||
(link) => !readableIds || readableIds.has(link.parentId),
|
||||
)
|
||||
const dependents = task.dependents.filter(
|
||||
(link) => !readableIds || readableIds.has(link.childId),
|
||||
)
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status)
|
||||
const resolvedAssets = await this.resolveTaskAssetInfos(task.assets)
|
||||
|
||||
const baseInfo = await this.toTaskInfo(task, {
|
||||
latestStatusEvent,
|
||||
dependencyCount: task.dependencies.length,
|
||||
dependentCount: task.dependents.length,
|
||||
dependencyCount: dependencies.length,
|
||||
dependentCount: dependents.length,
|
||||
commentCount: task.comments.length,
|
||||
assetCount: task.assets.length,
|
||||
})
|
||||
|
||||
return {
|
||||
...baseInfo,
|
||||
dependencies: task.dependencies.map((d) => ({
|
||||
dependencies: dependencies.map((d) => ({
|
||||
id: d.parent.id,
|
||||
title: d.parent.title,
|
||||
isAgentTask: d.parent.isAgentTask,
|
||||
status: d.parent.status,
|
||||
priority: d.parent.priority,
|
||||
})),
|
||||
dependents: task.dependents.map((d) => ({
|
||||
dependents: dependents.map((d) => ({
|
||||
id: d.child.id,
|
||||
title: d.child.title,
|
||||
isAgentTask: d.child.isAgentTask,
|
||||
@@ -392,29 +471,12 @@ export class KanbanService {
|
||||
image: await getAvatarUrl(c.author.image),
|
||||
},
|
||||
body: c.body,
|
||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
||||
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
})),
|
||||
),
|
||||
events: await Promise.all(
|
||||
task.events.map(async (e) => ({
|
||||
id: e.id,
|
||||
taskId: e.taskId,
|
||||
actor: e.actor
|
||||
? {
|
||||
id: e.actor.id,
|
||||
name: e.actor.name,
|
||||
image: await getAvatarUrl(e.actor.image),
|
||||
}
|
||||
: null,
|
||||
type: e.type,
|
||||
fromStatus: e.fromStatus,
|
||||
toStatus: e.toStatus,
|
||||
data: (e.data as Record<string, unknown>) ?? null,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
),
|
||||
events: await this.resolveTaskEvents(task.events, readableIds),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -659,7 +721,8 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status)
|
||||
const counts = await this.getTaskCounts(taskId)
|
||||
const taskFilter = await this.readableTaskFilter(updated.teamId, actorId)
|
||||
const counts = await this.getTaskCounts(taskId, taskFilter)
|
||||
|
||||
return await this.toTaskInfo(updated, {
|
||||
latestStatusEvent,
|
||||
@@ -704,10 +767,54 @@ export class KanbanService {
|
||||
return taskInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits kanban tasks to those a user may read. Team-scoped members see every
|
||||
* task in the team; project-scoped members see tasks in the projects they
|
||||
* belong to and tasks they created, report, or are assigned to.
|
||||
*/
|
||||
private async readableTaskFilter(
|
||||
teamId: string,
|
||||
userId: string | undefined,
|
||||
): Promise<Prisma.KanbanTaskWhereInput | undefined> {
|
||||
if (!userId) return
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: { teamIdUserId: { teamId, userId } },
|
||||
})
|
||||
if (!member) return { id: { in: [] } }
|
||||
if (member.scope === 'team') return
|
||||
return {
|
||||
teamId,
|
||||
OR: [
|
||||
{ project: { members: { some: { teamMemberId: member.id } } } },
|
||||
{ creatorId: userId },
|
||||
{ reporterId: userId },
|
||||
{ assigneeId: userId },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
private async readableRelatedTaskIds(
|
||||
teamId: string,
|
||||
viewerId: string | undefined,
|
||||
relatedIds: string[],
|
||||
): Promise<Set<string> | undefined> {
|
||||
if (relatedIds.length === 0) return
|
||||
const filter = await this.readableTaskFilter(teamId, viewerId)
|
||||
if (!filter) return
|
||||
|
||||
const tasks = await prisma.kanbanTask.findMany({
|
||||
where: { id: { in: [...new Set(relatedIds)] }, AND: [filter] },
|
||||
select: { id: true },
|
||||
})
|
||||
return new Set(tasks.map((task) => task.id))
|
||||
}
|
||||
|
||||
async listTasks(
|
||||
teamId: string,
|
||||
params: ListKanbanTasksRequest,
|
||||
viewerId?: string,
|
||||
): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> {
|
||||
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||
const where: Prisma.KanbanTaskWhereInput = {
|
||||
teamId,
|
||||
...(params.status && { status: params.status }),
|
||||
@@ -721,6 +828,7 @@ export class KanbanService {
|
||||
...(params.priority && { priority: params.priority }),
|
||||
...(params.assigneeId && { assigneeId: params.assigneeId }),
|
||||
...(params.reporterId && { reporterId: params.reporterId }),
|
||||
...(taskFilter && { AND: [taskFilter] }),
|
||||
}
|
||||
|
||||
return await paginateQuery(
|
||||
@@ -732,14 +840,7 @@ export class KanbanService {
|
||||
reporter: true,
|
||||
assignee: true,
|
||||
goal: true,
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
dependencies: true,
|
||||
dependents: true,
|
||||
assets: true,
|
||||
},
|
||||
},
|
||||
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||
},
|
||||
orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }],
|
||||
skip,
|
||||
@@ -869,9 +970,10 @@ export class KanbanService {
|
||||
|
||||
async createAttachment(
|
||||
teamId: string,
|
||||
uploaderId: string,
|
||||
req: { fileName: string; size: number; contentType?: string },
|
||||
): Promise<PostKanbanAttachmentResponse> {
|
||||
const key = `kanban/attachments/${ulid()}/${req.fileName}`
|
||||
const key = `kanban/attachments/${teamId}/${uploaderId}/${ulid()}/${sanitizeFilename(req.fileName)}`
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
const proxyType = getProxyType(req.contentType, req.fileName)
|
||||
|
||||
@@ -895,6 +997,16 @@ export class KanbanService {
|
||||
const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } })
|
||||
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||
|
||||
// Attachments are uploaded through createAttachment. Only keys it issued to the
|
||||
// comment author for this task's team may be stored and signed later.
|
||||
const isOwnUpload = (key: string) => {
|
||||
const parsed = parseAttachmentKey(key)
|
||||
return parsed?.teamId === task.teamId && parsed.uploaderId === authorId
|
||||
}
|
||||
if (attachments?.some((att) => !isOwnUpload(att.key))) {
|
||||
throw new HTTPException(400, { message: 'Invalid attachment' })
|
||||
}
|
||||
|
||||
const comment = await prisma.$transaction(async (tx) => {
|
||||
const c = await tx.kanbanTaskComment.create({
|
||||
data: {
|
||||
@@ -917,7 +1029,10 @@ export class KanbanService {
|
||||
return c
|
||||
})
|
||||
|
||||
const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments)
|
||||
const resolvedAttachments = await this.resolveCommentAttachments(
|
||||
comment.attachments,
|
||||
task.teamId,
|
||||
)
|
||||
|
||||
return {
|
||||
id: comment.id,
|
||||
@@ -935,6 +1050,12 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
async listComments(taskId: string): Promise<KanbanCommentInfo[]> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!task) throw new HTTPException(404, { message: 'Task not found' })
|
||||
|
||||
const comments = await prisma.kanbanTaskComment.findMany({
|
||||
where: { taskId },
|
||||
include: { author: true },
|
||||
@@ -951,7 +1072,7 @@ export class KanbanService {
|
||||
image: await getAvatarUrl(c.author.image),
|
||||
},
|
||||
body: c.body,
|
||||
attachments: await this.resolveCommentAttachments(c.attachments),
|
||||
attachments: await this.resolveCommentAttachments(c.attachments, task.teamId),
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
})),
|
||||
@@ -981,7 +1102,8 @@ export class KanbanService {
|
||||
}
|
||||
|
||||
private async resolveCommentAttachments(
|
||||
attachments?: PrismaJson.KanbanCommentAttachmentList | null,
|
||||
attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined,
|
||||
teamId: string,
|
||||
): Promise<KanbanAttachmentInfo[]> {
|
||||
if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
|
||||
return []
|
||||
@@ -989,29 +1111,50 @@ export class KanbanService {
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
return await Promise.all(
|
||||
attachments.map(async (att) => {
|
||||
const url = await s3Service.presign(bucket, att.key, 'GET')
|
||||
return {
|
||||
id: att.id,
|
||||
name: att.name,
|
||||
sizeByte: att.sizeByte,
|
||||
contentType: att.contentType,
|
||||
url,
|
||||
proxyType: att.proxyType,
|
||||
}
|
||||
}),
|
||||
attachments
|
||||
.filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId))
|
||||
.map(async (att) => {
|
||||
const url = await s3Service.presign(bucket, att.key, 'GET')
|
||||
return {
|
||||
id: att.id,
|
||||
name: att.name,
|
||||
sizeByte: att.sizeByte,
|
||||
contentType: att.contentType,
|
||||
url,
|
||||
proxyType: att.proxyType,
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async listEvents(taskId: string): Promise<KanbanEventInfo[]> {
|
||||
const events = await prisma.kanbanTaskEvent.findMany({
|
||||
where: { taskId },
|
||||
include: { actor: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: {
|
||||
teamId: true,
|
||||
events: { include: { actor: true }, orderBy: { createdAt: 'desc' } },
|
||||
},
|
||||
})
|
||||
if (!task) return []
|
||||
const readableIds = await this.readableRelatedTaskIds(
|
||||
task.teamId,
|
||||
viewerId,
|
||||
task.events.map(dependencyEventParentId).filter((id) => id !== undefined),
|
||||
)
|
||||
return await this.resolveTaskEvents(task.events, readableIds)
|
||||
}
|
||||
|
||||
private async resolveTaskEvents(
|
||||
events: TaskEventWithActor[],
|
||||
readableIds: Set<string> | undefined,
|
||||
): Promise<KanbanEventInfo[]> {
|
||||
const visibleEvents = events.filter((event) => {
|
||||
const parentId = dependencyEventParentId(event)
|
||||
return !readableIds || parentId === undefined || readableIds.has(parentId)
|
||||
})
|
||||
|
||||
return await Promise.all(
|
||||
events.map(async (e) => ({
|
||||
visibleEvents.map(async (e) => ({
|
||||
id: e.id,
|
||||
taskId: e.taskId,
|
||||
actor: e.actor
|
||||
@@ -1024,7 +1167,7 @@ export class KanbanService {
|
||||
type: e.type,
|
||||
fromStatus: e.fromStatus,
|
||||
toStatus: e.toStatus,
|
||||
data: (e.data as Record<string, unknown>) ?? null,
|
||||
data: e.data ?? null,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
)
|
||||
@@ -1115,9 +1258,17 @@ export class KanbanService {
|
||||
return await this.resolveTaskAssetInfos(links)
|
||||
}
|
||||
|
||||
async listTasksForAsset(teamId: string, assetId: string): Promise<KanbanTaskInfo[]> {
|
||||
async listTasksForAsset(
|
||||
teamId: string,
|
||||
assetId: string,
|
||||
viewerId?: string,
|
||||
): Promise<KanbanTaskInfo[]> {
|
||||
const taskFilter = await this.readableTaskFilter(teamId, viewerId)
|
||||
const links = await prisma.kanbanTaskAsset.findMany({
|
||||
where: { assetId },
|
||||
where: {
|
||||
assetId,
|
||||
task: { teamId, ...taskFilter },
|
||||
},
|
||||
include: {
|
||||
task: {
|
||||
include: {
|
||||
@@ -1125,24 +1276,15 @@ export class KanbanService {
|
||||
reporter: true,
|
||||
assignee: true,
|
||||
goal: true,
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
dependencies: true,
|
||||
dependents: true,
|
||||
assets: true,
|
||||
},
|
||||
},
|
||||
_count: { select: taskRelationCountSelect(taskFilter) },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
|
||||
const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId)
|
||||
|
||||
return await Promise.all(
|
||||
matchingLinks.map(async (l) => {
|
||||
links.map(async (l) => {
|
||||
const t = l.task
|
||||
const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status)
|
||||
return await this.toTaskInfo(t, {
|
||||
@@ -1195,19 +1337,25 @@ export class KanbanService {
|
||||
}
|
||||
}
|
||||
|
||||
private async getTaskCounts(taskId: string): Promise<{
|
||||
private async getTaskCounts(
|
||||
taskId: string,
|
||||
taskFilter?: Prisma.KanbanTaskWhereInput,
|
||||
): Promise<{
|
||||
commentCount: number
|
||||
dependencyCount: number
|
||||
dependentCount: number
|
||||
assetCount: number
|
||||
}> {
|
||||
const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([
|
||||
prisma.kanbanTaskComment.count({ where: { taskId } }),
|
||||
prisma.kanbanTaskLink.count({ where: { childId: taskId } }),
|
||||
prisma.kanbanTaskLink.count({ where: { parentId: taskId } }),
|
||||
prisma.kanbanTaskAsset.count({ where: { taskId } }),
|
||||
])
|
||||
return { commentCount, dependencyCount, dependentCount, assetCount }
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: taskId },
|
||||
select: { _count: { select: taskRelationCountSelect(taskFilter) } },
|
||||
})
|
||||
return {
|
||||
commentCount: task?._count.comments ?? 0,
|
||||
dependencyCount: task?._count.dependencies ?? 0,
|
||||
dependentCount: task?._count.dependents ?? 0,
|
||||
assetCount: task?._count.assets ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveTaskAssetInfos(
|
||||
|
||||
Reference in New Issue
Block a user