import * as fs from 'node:fs'; import * as path from 'node:path'; import { INestApplication } from '@nestjs/common'; import * as bcrypt from 'bcryptjs'; import request from 'supertest'; import { App } from 'supertest/types'; import { PrismaService } from '../src/prisma/prisma.service'; import { sealTranscript } from '../src/voice/core/transcript'; import { createTestApp } from './utils/create-test-app'; import { login } from './utils/api'; interface SearchResultBody { type: string; id: string; label: string; } interface ColonyBody { id: string; status: string; } describe('Search and filters (e2e)', () => { let app: INestApplication; let prisma: PrismaService; const readonlyEmail = `search-e2e-readonly-${Date.now()}@example.com`; const password = 'SuperSecret123!'; let readonlyId: string; let readonlyToken: string; let apiaryId: string; let colonyId: string; let dissolvedColonyId: string; const uniqueCode = `SRCH-${Date.now()}`; beforeAll(async () => { app = await createTestApp(); prisma = app.get(PrismaService); const passwordHash = await bcrypt.hash(password, 12); const readonly = await prisma.user.create({ data: { email: readonlyEmail, passwordHash, name: 'Readonly', role: { connect: { key: 'READONLY' } }, }, }); readonlyId = readonly.id; readonlyToken = (await login(app, readonlyEmail, password)).accessToken; const apiary = await prisma.apiary.create({ data: { name: `Stand ${Date.now()}` }, }); apiaryId = apiary.id; const colony = await prisma.colony.create({ data: { code: uniqueCode, apiaryId, colonyType: 'PRODUCTION_COLONY' }, }); colonyId = colony.id; const dissolvedColony = await prisma.colony.create({ data: { code: `${uniqueCode}-DISSOLVED`, apiaryId, colonyType: 'PRODUCTION_COLONY', status: 'DISSOLVED', }, }); dissolvedColonyId = dissolvedColony.id; }); afterAll(async () => { await prisma.voiceCapture.deleteMany({ where: { ownerUserId: readonlyId }, }); await prisma.colony.deleteMany({ where: { id: { in: [colonyId, dissolvedColonyId] } }, }); await prisma.apiary.deleteMany({ where: { id: apiaryId } }); await prisma.refreshToken.deleteMany({ where: { userId: readonlyId } }); await prisma.auditLog.deleteMany({ where: { userId: readonlyId } }); await prisma.user.deleteMany({ where: { id: readonlyId } }); await app.close(); }); it('finds a colony by its code across entity types', async () => { const response = await request(app.getHttpServer()) .get(`/api/v1/search?q=${uniqueCode}`) .set('Authorization', `Bearer ${readonlyToken}`) .expect(200); const results = response.body as SearchResultBody[]; expect( results.some((entry) => entry.type === 'Colony' && entry.id === colonyId), ).toBe(true); }); it('returns nothing of a voice capture, neither by its text nor by its id', async () => { const spoken = `Stifte${Date.now()}x`; const capture = await prisma.voiceCapture.create({ data: { ownerUserId: readonlyId, colonyId, inspectionDate: new Date(), source: 'TEXT', status: 'TRANSCRIBED', contentExpiresAt: new Date(Date.now() + 86_400_000), }, }); await prisma.voiceCapture.update({ where: { id: capture.id }, data: { transcriptEnc: sealTranscript(capture.id, { v: 1, text: `${spoken} Koenigin gesehen`, }), lastErrorCode: 'EXTRACT_DISABLED', }, }); // The colony code is found (so the colony is in play), the capture never. for (const term of [spoken, capture.id, 'EXTRACT_DISABLED', uniqueCode]) { const response = await request(app.getHttpServer()) .get(`/api/v1/search?q=${term}`) .set('Authorization', `Bearer ${readonlyToken}`) .expect(200); const results = response.body as SearchResultBody[]; const text = JSON.stringify(results); expect(text).not.toContain(capture.id); expect(text).not.toContain(spoken); for (const entry of results) { expect(Object.keys(entry).sort()).toEqual(['id', 'label', 'type']); expect(['Apiary', 'Colony', 'Queen', 'Task', 'HoneyBatch']).toContain( entry.type, ); } } }); it('filters colonies by status', async () => { const response = await request(app.getHttpServer()) .get(`/api/v1/colonies?status=DISSOLVED&apiaryId=${apiaryId}`) .set('Authorization', `Bearer ${readonlyToken}`) .expect(200); const colonies = response.body as ColonyBody[]; expect(colonies.map((entry) => entry.id)).toEqual([dissolvedColonyId]); }); }); describe('Voice capture content guard', () => { // VoiceCapture holds personal data that is deleted after at most 7 days. It // must never be reachable through search or any export/report builder. const srcRoot = path.resolve(__dirname, '../src'); // Every place that builds a document or a list for the user or another // system, by directory: nothing here may touch the voice tables. const builderDirs = [ 'search', 'export', 'erp-export', 'compliance', 'label-templates', 'statistics', 'dashboard', 'public', 'qr', 'calendar', 'calendar-sync', 'webhooks', 'shop-sync', 'documents', 'import', ]; // Files that build a PDF, CSV or download wherever they live. Found by // content, so a new report builder in any folder is covered without an // edit here. src/voice itself and src/backup (which lists the voice models // as excluded) are the only places allowed to name the model. const builderMarkers = /PDFDocument|pdf-lib|pdfkit|application\/pdf|text\/csv|spreadsheetml|Content-Disposition|toCsv|csv-stringify/; function sourceFiles(dir: string): string[] { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const full = path.join(dir, entry.name); if (entry.isDirectory()) return sourceFiles(full); return entry.name.endsWith('.ts') && !entry.name.endsWith('.spec.ts') ? [full] : []; }); } function mentionsVoiceCapture(file: string): boolean { return /voiceCapture|VoiceCapture/.test(fs.readFileSync(file, 'utf8')); } function relative(file: string): string { return path.relative(srcRoot, file).split(path.sep).join('/'); } it('VoiceCapture appears in no search provider, export or report directory', () => { const files = builderDirs.flatMap((dir) => sourceFiles(path.join(srcRoot, dir)), ); expect(files.length).toBeGreaterThan(0); for (const file of files) { expect({ file: relative(file), mentions: mentionsVoiceCapture(file), }).toEqual({ file: relative(file), mentions: false, }); } }); it('VoiceCapture appears in no file that builds a PDF, CSV or download, wherever it lives', () => { const builders = sourceFiles(srcRoot).filter((file) => { const name = relative(file); return ( !name.startsWith('voice/') && !name.startsWith('backup/') && builderMarkers.test(fs.readFileSync(file, 'utf8')) ); }); // The scan must find the known builders, or it checks nothing. expect(builders.map(relative)).toEqual( expect.arrayContaining([ expect.stringMatching(/^export\//), expect.stringMatching(/^compliance\/pdf\//), ]), ); for (const file of builders) { expect({ file: relative(file), mentions: mentionsVoiceCapture(file), }).toEqual({ file: relative(file), mentions: false, }); } }); it('SearchService names no voice type, field or table', () => { const service = fs.readFileSync( path.join(srcRoot, 'search/search.service.ts'), 'utf8', ); expect(service).not.toMatch(/voice|transcript|suggestionEnc/i); }); });