feat: attachments on tickets and comments

Files are uploaded over REST, stored on disk (a volume in Docker) and
recorded on the ticket as events; the bytes are written first, so no
attachment ever points at a missing file. Only images, video, audio, PDF
and plain text are shown inline, everything with nosniff and a sandbox CSP.
The web shows thumbnails, uploads by drag and drop or by pasting a
screenshot, and attaches files to new comments.

Also adds `nx run api:contracts`, which writes schema.gql and
openapi.json without starting the API or any database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 08:35:33 +02:00
parent 80d9bee6e0
commit 0b65c1c912
72 changed files with 6766 additions and 4297 deletions

View File

@@ -0,0 +1,57 @@
import { randomUUID } from 'node:crypto';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { BusinessRuleError } from '@task-stream/api/shared/domain';
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
import { AttachFileCommand } from './attach-file.command';
import { CommandResult, ack } from './command-result';
import { WriteAccess } from './write-access';
/**
* Stores the bytes first and records them on the ticket after: a file with no
* record is cleaned up here, never a record with no file.
*/
@CommandHandler(AttachFileCommand)
export class AttachFileCommandHandler
implements ICommandHandler<AttachFileCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly storage: AttachmentStorage,
) {}
async execute(command: AttachFileCommand): Promise<CommandResult> {
const { issue } = await this.access.issueForContributor(
command.issueId,
command.actorId,
);
if (command.commentId) {
const comment = await this.access.comment(command.commentId);
if (comment.issueId !== issue.id) {
throw new BusinessRuleError(
`That comment belongs to another ticket, not ${issue.key}`,
);
}
}
const id = randomUUID();
const key = attachmentKey(issue.projectId, issue.id, id);
issue.attach(command.actorId, {
id,
fileName: command.file.fileName,
mimeType: command.file.mimeType,
size: command.file.content.length,
uploadedBy: command.actorId,
uploadedAt: new Date().toISOString(),
commentId: command.commentId,
});
await this.storage.put(key, command.file.content);
try {
await issue.commitAndWait();
} catch (error) {
await this.storage.remove(key);
throw error;
}
return ack(issue);
}
}

View File

@@ -0,0 +1,20 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
export interface IncomingFile {
fileName: string;
mimeType: string;
content: Buffer;
}
export class AttachFileCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly file: IncomingFile,
/** Places it under one of the ticket's comments. */
public readonly commentId: string | null = null,
) {
super();
}
}

View File

@@ -25,6 +25,8 @@ import { PurgeCommentCommandHandler } from './purge-comment.command-handler';
import { DropLinksToIssueCommandHandler } from './drop-links-to-issue.command-handler';
import { DetachIssueFromReleaseCommandHandler } from './detach-issue-from-release.command-handler';
import { UnassignIssueCommandHandler } from './unassign-issue.command-handler';
import { AttachFileCommandHandler } from './attach-file.command-handler';
import { DetachFileCommandHandler } from './detach-file.command-handler';
export const COMMAND_HANDLERS = [
CreateProjectCommandHandler,
@@ -55,4 +57,6 @@ export const COMMAND_HANDLERS = [
DropLinksToIssueCommandHandler,
DetachIssueFromReleaseCommandHandler,
UnassignIssueCommandHandler,
AttachFileCommandHandler,
DetachFileCommandHandler,
];

View File

@@ -12,6 +12,7 @@ import {
} from '@task-stream/api/shared/domain';
import {
Comment,
Issue,
IssueStatus,
Project,
IssueType,
@@ -20,6 +21,7 @@ import {
} from '@task-stream/api/tracker/domain';
import {
FakeUserDirectory,
InMemoryAttachmentStorage,
InMemoryEventStore,
InMemoryEventStorePublisher,
InMemoryIssueNumbers,
@@ -32,9 +34,12 @@ import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
import { ProjectKeysRepository } from '../ports/project-keys.repository';
import { ReleaseNamesRepository } from '../ports/release-names.repository';
import { UserDirectory } from '../ports/user-directory';
import { AttachmentStorage } from '../ports/attachment-storage';
import { AddCommentCommand } from './add-comment.command';
import { AddProjectMemberCommand } from './add-project-member.command';
import { AssignIssueCommand } from './assign-issue.command';
import { AttachFileCommand } from './attach-file.command';
import { DetachFileCommand } from './detach-file.command';
import { ChangeIssueStatusCommand } from './change-issue-status.command';
import { COMMAND_HANDLERS } from './command-handlers';
import { CommandResult } from './command-result';
@@ -48,6 +53,7 @@ import { WriteAccess } from './write-access';
async function setup() {
const store = new InMemoryEventStore();
const files = new InMemoryAttachmentStorage();
const users = new FakeUserDirectory()
.add('owner')
.add('dev')
@@ -62,6 +68,7 @@ async function setup() {
WriteAccess,
AggregateRehydrator,
{ provide: EventStore, useValue: store },
{ provide: AttachmentStorage, useValue: files },
{ provide: UserDirectory, useValue: users },
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
{ provide: IssueNumbersRepository, useClass: InMemoryIssueNumbers },
@@ -78,7 +85,12 @@ async function setup() {
const commandBus = moduleRef.get(CommandBus);
const run = (command: object): Promise<CommandResult> =>
commandBus.execute(command as never);
return { store, run, rehydrator: moduleRef.get(AggregateRehydrator) };
return {
store,
files,
run,
rehydrator: moduleRef.get(AggregateRehydrator),
};
}
async function projectWithTeam(run: (c: object) => Promise<CommandResult>) {
@@ -178,6 +190,74 @@ describe('tracker commands (event sourced)', () => {
).rejects.toThrow(BusinessRuleError);
});
describe('attachments', () => {
const png = {
fileName: 'captura.png',
mimeType: 'image/png',
content: Buffer.from('fake png'),
};
it('stores the file and records it on the ticket', async () => {
const { run, files, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
);
await run(new AttachFileCommand('qa', issue.id, png));
const rebuilt = await rehydrator.rehydrate(issue.id, Issue);
expect(rebuilt.attachments).toHaveLength(1);
expect(rebuilt.attachments[0]).toMatchObject({
fileName: 'captura.png',
size: 8,
uploadedBy: 'qa',
});
expect([...files.files.keys()]).toEqual([
`${projectId}/${issue.id}/${rebuilt.attachments[0].id}`,
]);
});
it('keeps no file when the ticket cannot take it', async () => {
const { run, files } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
);
await expect(
run(new AttachFileCommand('pm', issue.id, png)),
).rejects.toThrow(ForbiddenError);
await expect(
run(
new AttachFileCommand('qa', issue.id, {
...png,
content: Buffer.alloc(0),
}),
),
).rejects.toThrow();
expect(files.files.size).toBe(0);
});
it('lets the uploader or an admin remove it, and deletes the bytes', async () => {
const { run, files, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
);
await run(new AttachFileCommand('qa', issue.id, png));
const [attachment] = (await rehydrator.rehydrate(issue.id, Issue))
.attachments;
await expect(
run(new DetachFileCommand('dev', issue.id, attachment.id)),
).rejects.toThrow(ForbiddenError);
await run(new DetachFileCommand('owner', issue.id, attachment.id));
expect(files.files.size).toBe(0);
});
});
it('does not let viewers modify tickets', async () => {
const { run } = await setup();
const projectId = await projectWithTeam(run);

View File

@@ -0,0 +1,35 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { ProjectRole } from '@task-stream/api/tracker/domain';
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
import { CommandResult, ack } from './command-result';
import { DetachFileCommand } from './detach-file.command';
import { WriteAccess } from './write-access';
/** Removes the record first; the bytes go once nothing points at them. */
@CommandHandler(DetachFileCommand)
export class DetachFileCommandHandler
implements ICommandHandler<DetachFileCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly storage: AttachmentStorage,
) {}
async execute(command: DetachFileCommand): Promise<CommandResult> {
const { issue, project } = await this.access.issueForContributor(
command.issueId,
command.actorId,
);
const role = project.roleOf(command.actorId);
issue.detach(
command.actorId,
command.attachmentId,
role === ProjectRole.OWNER || role === ProjectRole.ADMIN,
);
await issue.commitAndWait();
await this.storage.remove(
attachmentKey(issue.projectId, issue.id, command.attachmentId),
);
return ack(issue);
}
}

View File

@@ -0,0 +1,12 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
export class DetachFileCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly attachmentId: string,
) {
super();
}
}

View File

@@ -26,3 +26,5 @@ export * from './purge-comment.command';
export * from './drop-links-to-issue.command';
export * from './detach-issue-from-release.command';
export * from './unassign-issue.command';
export * from './attach-file.command';
export * from './detach-file.command';