MicProtocol / apps /api /dist /documents /documents.service.js
Benaah's picture
Upload folder using huggingface_hub
303c85f verified
Raw History Blame Contribute Delete
19.2 kB
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var DocumentsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DocumentsService = void 0;
const common_1 = require("@nestjs/common");
const prisma_service_1 = require("../prisma/prisma.service");
const file_security_service_1 = require("../common/file-security/file-security.service");
const r2_storage_service_1 = require("../common/storage/r2-storage.service");
const audit_service_1 = require("../audit/audit.service");
const events_gateway_1 = require("../websocket/events.gateway");
const shared_types_1 = require("@micprotocol/shared-types");
let DocumentsService = DocumentsService_1 = class DocumentsService {
prisma;
fileSecurity;
storage;
audit;
eventsGateway;
logger = new common_1.Logger(DocumentsService_1.name);
constructor(prisma, fileSecurity, storage, audit, eventsGateway) {
this.prisma = prisma;
this.fileSecurity = fileSecurity;
this.storage = storage;
this.audit = audit;
this.eventsGateway = eventsGateway;
}
async uploadDocument(input) {
const validation = this.fileSecurity.validate({
buffer: input.file.buffer,
originalname: input.file.originalname,
mimetype: input.file.mimetype,
size: input.file.size,
}, {
maxSizeBytes: 50 * 1024 * 1024,
allowedMimeTypes: [
"application/pdf",
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
],
});
const existing = await this.prisma.document.findFirst({
where: {
workspaceId: input.workspaceId,
sha256: validation.sha256,
},
select: { id: true, title: true, createdAt: true },
});
const safeKey = `documents/${input.workspaceId}/${validation.sha256}/${validation.safeFilename}`;
await this.storage.uploadBuffer(safeKey, input.file.buffer, validation.detectedMimeType);
const result = await this.prisma.$transaction(async (tx) => {
const document = await tx.document.create({
data: {
workspaceId: input.workspaceId,
ownerId: input.userId,
title: input.title,
description: input.description ?? null,
mimeType: validation.detectedMimeType,
sizeBytes: validation.size,
sha256: validation.sha256,
storageKey: safeKey,
status: shared_types_1.DocumentStatus.ACTIVE,
},
});
const version = await tx.documentVersion.create({
data: {
documentId: document.id,
versionNo: 1,
mimeType: validation.detectedMimeType,
sizeBytes: validation.size,
sha256: validation.sha256,
storageKey: safeKey,
uploadedById: input.userId,
},
});
await tx.documentAccessLog.create({
data: {
documentId: document.id,
workspaceId: input.workspaceId,
userId: input.userId,
action: shared_types_1.DocumentAction.UPLOAD,
},
});
return { document, version };
});
await this.audit.log({
userId: input.userId,
workspaceId: input.workspaceId,
action: "document.upload",
entityType: "Document",
entityId: result.document.id,
metadata: {
title: input.title,
mimeType: validation.detectedMimeType,
sizeBytes: validation.size,
sha256: validation.sha256,
duplicate: !!existing,
},
}).catch(() => { });
this.eventsGateway.notifyDocumentUploaded(input.workspaceId, {
id: result.document.id,
title: result.document.title,
mimeType: result.document.mimeType,
sizeBytes: result.document.sizeBytes,
createdAt: result.document.createdAt,
});
return this.mapDocument(result.document, result.version);
}
async listDocuments(workspaceId, options = {}) {
const page = Math.max(1, options.page ?? 1);
const limit = Math.min(100, Math.max(1, options.limit ?? 20));
const skip = (page - 1) * limit;
const where = { workspaceId };
if (options.status)
where.status = options.status;
if (options.search) {
where.OR = [
{ title: { contains: options.search, mode: "insensitive" } },
{ description: { contains: options.search, mode: "insensitive" } },
];
}
const [items, total] = await Promise.all([
this.prisma.document.findMany({
where,
include: {
versions: {
orderBy: { versionNo: "desc" },
take: 1,
include: {
uploadedBy: { select: { id: true, name: true } },
},
},
_count: { select: { versions: true, shares: true } },
},
orderBy: { updatedAt: "desc" },
skip,
take: limit,
}),
this.prisma.document.count({ where }),
]);
return {
items: items.map((d) => this.mapDocument(d, d.versions[0] ?? undefined)),
total,
page,
limit,
};
}
async getDocument(documentId, workspaceId) {
const document = await this.prisma.document.findFirst({
where: { id: documentId, workspaceId },
include: {
versions: {
orderBy: { versionNo: "desc" },
},
shares: {
where: { isRevoked: false },
},
_count: { select: { versions: true, accessLogs: true } },
},
});
if (!document)
return null;
return this.mapDocumentWithShares(document);
}
async createShare(input) {
const document = await this.prisma.document.findFirst({
where: { id: input.documentId, workspaceId: input.workspaceId },
select: { id: true, title: true, status: true },
});
if (!document) {
throw new common_1.NotFoundException(`Document ${input.documentId} not found`);
}
if (document.status === shared_types_1.DocumentStatus.REVOKED || document.status === shared_types_1.DocumentStatus.QUARANTINED) {
throw new common_1.ForbiddenException("Cannot share a revoked or quarantined document");
}
const share = await this.prisma.documentShare.create({
data: {
documentId: input.documentId,
workspaceId: input.workspaceId,
shareType: input.shareType ?? shared_types_1.ShareType.PUBLIC,
accessCode: input.accessCode ?? null,
expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,
maxDownloads: input.maxDownloads ?? null,
},
});
await this.audit.log({
workspaceId: input.workspaceId,
action: "document.share.create",
entityType: "DocumentShare",
entityId: share.id,
metadata: {
documentId: input.documentId,
shareType: input.shareType,
expiresAt: input.expiresAt,
maxDownloads: input.maxDownloads,
},
}).catch(() => { });
this.eventsGateway.notifyDocumentShared(input.workspaceId, {
shareId: share.id,
documentId: input.documentId,
documentTitle: document.title,
shareType: share.shareType,
});
return this.mapShare(share);
}
async revokeShare(shareId, workspaceId) {
const share = await this.prisma.documentShare.findFirst({
where: { id: shareId, workspaceId },
include: { document: { select: { id: true, title: true } } },
});
if (!share) {
throw new common_1.NotFoundException(`Share ${shareId} not found`);
}
await this.prisma.documentShare.update({
where: { id: shareId },
data: { isRevoked: true },
});
await this.audit.log({
workspaceId,
action: "document.share.revoke",
entityType: "DocumentShare",
entityId: shareId,
metadata: {
documentId: share.document.id,
documentTitle: share.document.title,
},
}).catch(() => { });
this.eventsGateway.notifyDocumentRevoked(workspaceId, shareId);
}
async getDownloadUrl(documentId, workspaceId, shareId, userId, ipAddress, userAgent) {
const document = await this.prisma.document.findFirst({
where: { id: documentId, workspaceId },
});
if (!document) {
throw new common_1.NotFoundException(`Document ${documentId} not found`);
}
if (document.status !== shared_types_1.DocumentStatus.ACTIVE) {
throw new common_1.ForbiddenException(`Document is ${document.status}`);
}
if (shareId) {
const share = await this.prisma.documentShare.findFirst({
where: { id: shareId, documentId, isRevoked: false },
});
if (!share) {
throw new common_1.NotFoundException("Share link not found or revoked");
}
if (share.expiresAt && share.expiresAt < new Date()) {
throw new common_1.ForbiddenException("Share link has expired");
}
if (share.maxDownloads !== null && share.downloadCount >= share.maxDownloads) {
throw new common_1.ForbiddenException("Share link download limit reached");
}
}
const url = await this.storage.getPresignedUrl(document.storageKey, 900);
await this.prisma.documentAccessLog.create({
data: {
documentId,
shareId,
userId,
workspaceId,
action: shared_types_1.DocumentAction.DOWNLOAD,
ipAddress,
userAgent,
},
});
if (shareId) {
await this.prisma.documentShare.update({
where: { id: shareId },
data: { downloadCount: { increment: 1 } },
});
}
return {
url,
document: this.mapDocument(document),
};
}
async verifyIntegrity(documentId, workspaceId) {
const document = await this.prisma.document.findFirst({
where: { id: documentId, workspaceId },
});
if (!document) {
throw new common_1.NotFoundException(`Document ${documentId} not found`);
}
let computedSha256;
try {
const buffer = await this.storage.getObjectBuffer(document.storageKey);
const crypto = require("crypto");
computedSha256 = crypto.createHash("sha256").update(buffer).digest("hex");
}
catch (err) {
throw new common_1.BadRequestException(`Unable to retrieve document from storage: ${err instanceof Error ? err.message : String(err)}`);
}
const integrityValid = computedSha256 === document.sha256;
const tampered = !integrityValid;
if (tampered) {
await this.prisma.document.update({
where: { id: documentId },
data: { isForgeryFlagged: true, status: shared_types_1.DocumentStatus.FLAGGED },
});
await this.audit.log({
workspaceId,
action: "document.tampering_detected",
entityType: "Document",
entityId: documentId,
metadata: {
storedSha256: document.sha256,
computedSha256,
},
}).catch(() => { });
this.eventsGateway.notifyDocumentTamperingDetected(workspaceId, documentId);
}
return {
documentId,
storedSha256: document.sha256,
computedSha256,
integrityValid,
tampered,
};
}
async listAccessLogs(documentId, workspaceId, options = {}) {
const page = Math.max(1, options.page ?? 1);
const limit = Math.min(100, Math.max(1, options.limit ?? 50));
const skip = (page - 1) * limit;
const document = await this.prisma.document.findFirst({
where: { id: documentId, workspaceId },
select: { id: true },
});
if (!document) {
throw new common_1.NotFoundException(`Document ${documentId} not found`);
}
const [items, total] = await Promise.all([
this.prisma.documentAccessLog.findMany({
where: { documentId },
include: {
user: { select: { id: true, name: true, email: true } },
},
orderBy: { createdAt: "desc" },
skip,
take: limit,
}),
this.prisma.documentAccessLog.count({ where: { documentId } }),
]);
return {
items: items.map((l) => ({
id: l.id,
documentId: l.documentId,
shareId: l.shareId,
userId: l.userId,
workspaceId: l.workspaceId,
action: l.action,
ipAddress: l.ipAddress,
userAgent: l.userAgent,
createdAt: l.createdAt,
userName: l.user ? (l.user.name ?? l.user.email) : null,
})),
total,
};
}
async deleteDocument(documentId, workspaceId, userId) {
const document = await this.prisma.document.findFirst({
where: { id: documentId, workspaceId },
include: { shares: true },
});
if (!document) {
throw new common_1.NotFoundException(`Document ${documentId} not found`);
}
await this.prisma.documentShare.updateMany({
where: { documentId },
data: { isRevoked: true },
});
try {
await this.storage.deleteObject(document.storageKey);
}
catch {
}
await this.prisma.document.delete({
where: { id: documentId },
});
await this.audit.log({
userId,
workspaceId,
action: "document.delete",
entityType: "Document",
entityId: documentId,
metadata: { title: document.title },
}).catch(() => { });
}
mapDocument(document, latestVersion) {
return {
id: document.id,
workspaceId: document.workspaceId,
ownerId: document.ownerId,
title: document.title,
description: document.description,
mimeType: document.mimeType,
sizeBytes: document.sizeBytes,
sha256: document.sha256,
storageKey: document.storageKey,
status: document.status,
isForgeryFlagged: document.isForgeryFlagged,
isSanctionBlocked: document.isSanctionBlocked,
createdAt: document.createdAt,
updatedAt: document.updatedAt,
versionCount: document._count?.versions ?? (latestVersion ? 1 : 0),
latestVersion: latestVersion ? this.mapVersion(latestVersion) : undefined,
};
}
mapDocumentWithShares(document) {
return {
id: document.id,
workspaceId: document.workspaceId,
ownerId: document.ownerId,
title: document.title,
description: document.description,
mimeType: document.mimeType,
sizeBytes: document.sizeBytes,
sha256: document.sha256,
storageKey: document.storageKey,
status: document.status,
isForgeryFlagged: document.isForgeryFlagged,
isSanctionBlocked: document.isSanctionBlocked,
createdAt: document.createdAt,
updatedAt: document.updatedAt,
versionCount: document.versions.length,
latestVersion: document.versions[0] ? this.mapVersion(document.versions[0]) : undefined,
};
}
mapVersion(version) {
return {
id: version.id,
documentId: version.documentId,
versionNo: version.versionNo,
mimeType: version.mimeType,
sizeBytes: version.sizeBytes,
sha256: version.sha256,
storageKey: version.storageKey,
uploadedAt: version.uploadedAt,
uploadedById: version.uploadedById,
uploadedByName: version.uploadedBy?.name ?? null,
};
}
mapShare(share) {
return {
id: share.id,
documentId: share.documentId,
workspaceId: share.workspaceId,
shareType: share.shareType,
accessCode: share.accessCode,
expiresAt: share.expiresAt,
maxDownloads: share.maxDownloads,
downloadCount: share.downloadCount,
isRevoked: share.isRevoked,
createdAt: share.createdAt,
updatedAt: share.updatedAt,
shareUrl: `/documents/shared/${share.id}`,
};
}
};
exports.DocumentsService = DocumentsService;
exports.DocumentsService = DocumentsService = DocumentsService_1 = __decorate([
(0, common_1.Injectable)(),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
file_security_service_1.FileSecurityService,
r2_storage_service_1.R2StorageService,
audit_service_1.AuditService,
events_gateway_1.EventsGateway])
], DocumentsService);
//# sourceMappingURL=documents.service.js.map