Phase 8 abgeschlossen: Export als PDF, Wasserzeichen, Vier-Augen-Freigabe
Die Druckansicht ist die einzige Vorlage für den Export: kein zweites Layout von Hand in einer PDF-Bibliothek. Der Playwright-Dienst ruft genau diese Seite auf und bekommt dafür ein signiertes, kurzlebiges Zeichen statt eines Sitzungscookies. Es gilt nur, solange der Auftrag läuft, ist an den Anfragenden gebunden, und die Stufe wird beim Einlösen frisch aufgelöst und auf die im Zeichen vermerkte gedeckelt. Der Export darf nie sauberer aussehen als die Akte: gesperrte Felder erscheinen als Balken mit Vermerk statt zu fehlen, geänderte Einträge tragen ihre Version, zurückgezogene stehen als Grabstein. Wasserzeichen mit Name, Zeitstempel und Stufe auf jeder Seite. Die Stufe steckt im Zwischenspeicherschlüssel. Ohne sie bekäme ein Leser der Stufe 1 das PDF, das für Stufe 4 gerendert wurde. Ab Stufe 3 wartet der Auftrag auf Freigabe durch ein zweites Augenpaar — und der Anfragende darf sich nicht selbst freigeben, auch nicht mit dem Recht dazu. Offene Freigaben stehen auf der Übersicht. Dazu Einzeldokumente als PDF (Aktenblatt bleibt Aktenblatt), ZIP-Sammelexport mit eigenem achtzigzeiligem Schreiber statt einer Abhängigkeit, und der JSON-Vollabzug ohne Stufenfilterung — die einzige Stelle, an der die Klassifizierung nicht greift, deshalb hinter einem eigenen Admin-Endpunkt. Zwei Funde unterwegs, beide in docs/13 festgehalten: Die Druckansicht warf notFound(), und das Skelett aus dem Wurzel-loading.tsx blieb im Browser stehen — der PDF-Dienst hätte leere Blätter gedruckt. Gefunden nur, weil der e2e-Test auf den Inhalt prüft und nicht auf den Statuscode. Sie rendert die Auskunft jetzt selbst. Und die Entdopplung der Anhänge verwies auf Dateien, ohne nachzusehen, ob sie noch daliegen. Nach einem geleerten /tmp zeigte jeder weitere Upload desselben Inhalts stumm ins Leere. 178 Tests im Web-Paket, 17 in der Datenbank, 7 im Worker, 44 e2e. Fallakte bei 119,8 von 120 kB — das Budget ist aufgebraucht. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
71c20f4b95
commit
d0adcd7795
@@ -47,6 +47,10 @@ export type AuditAction =
|
||||
| 'channel.create'
|
||||
| 'roles.update'
|
||||
| 'export.pdf'
|
||||
| 'export.approve'
|
||||
| 'export.reject'
|
||||
| 'export.download'
|
||||
| 'export.database'
|
||||
|
||||
export type AuditInput = {
|
||||
actorId: string
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* Der Zwischenspeicherschlüssel eines Exports.
|
||||
*
|
||||
* `sha256(Ziel + Stand + Stufe + Vorlagenversion)`, siehe docs/08. Die
|
||||
* **Stufe gehört hinein**: zwei Abrufer verschiedener Stufen bekommen nicht
|
||||
* dasselbe PDF, und ein Treffer im Zwischenspeicher darf niemandem ein
|
||||
* Dokument geben, das für eine höhere Stufe gerendert wurde.
|
||||
*
|
||||
* Der Stand (`updatedAt`) sorgt dafür, dass eine geänderte Akte neu gerendert
|
||||
* wird — ein Export darf nie einen älteren Stand zeigen, als die Akte hat.
|
||||
*/
|
||||
export function exportCacheKey(input: {
|
||||
kind: string
|
||||
targetId: string
|
||||
updatedAt: Date
|
||||
clearanceLevel: number
|
||||
templateVersion: number | string
|
||||
}): string {
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
[
|
||||
input.kind,
|
||||
input.targetId,
|
||||
input.updatedAt.toISOString(),
|
||||
String(input.clearanceLevel),
|
||||
String(input.templateVersion),
|
||||
].join('|'),
|
||||
)
|
||||
.digest('hex')
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { db } from '@/lib/db'
|
||||
import { writeAudit } from '@/lib/audit'
|
||||
import { AccessError } from '@/lib/errors'
|
||||
import type { EffectivePermissions } from '@/lib/auth/permissions'
|
||||
|
||||
/**
|
||||
* Vollständiger JSON-Abzug als Umzugs- und Notfallformat.
|
||||
*
|
||||
* **Ohne Stufenfilterung**, nur mit Recht `admin`, immer protokolliert — so
|
||||
* steht es in docs/08-suche-und-export.md. Das ist die eine Stelle im System,
|
||||
* an der die Klassifizierung nicht greift, und sie ist deshalb absichtlich
|
||||
* unbequem: kein Knopf an einer Akte, sondern eine eigene Seite im
|
||||
* Adminbereich.
|
||||
*
|
||||
* Ausgelassen wird, was Zugang verschafft statt ihn zu dokumentieren:
|
||||
* Sitzungen. Sie gehören niemandem ausser dem Browser, aus dem sie stammen.
|
||||
*/
|
||||
export async function exportDatabase(p: EffectivePermissions): Promise<Uint8Array> {
|
||||
if (!p.isAdmin) throw new AccessError('no-permission')
|
||||
|
||||
const [
|
||||
users,
|
||||
roleMappings,
|
||||
clearanceLevels,
|
||||
foundationClearances,
|
||||
statusTags,
|
||||
templates,
|
||||
cases,
|
||||
caseSections,
|
||||
caseSectionVersions,
|
||||
caseEntries,
|
||||
caseEntryVersions,
|
||||
participants,
|
||||
exclusions,
|
||||
links,
|
||||
personnel,
|
||||
assignments,
|
||||
documents,
|
||||
documentSections,
|
||||
documentSectionVersions,
|
||||
attachments,
|
||||
channels,
|
||||
messages,
|
||||
reactions,
|
||||
auditLog,
|
||||
] = await Promise.all([
|
||||
db.user.findMany(),
|
||||
db.roleMapping.findMany(),
|
||||
db.clearanceLevelConfig.findMany(),
|
||||
db.foundationClearance.findMany(),
|
||||
db.personnelStatusTag.findMany(),
|
||||
db.documentTemplate.findMany(),
|
||||
db.case.findMany(),
|
||||
db.caseSection.findMany(),
|
||||
db.caseSectionVersion.findMany(),
|
||||
db.caseEntry.findMany(),
|
||||
db.caseEntryVersion.findMany(),
|
||||
db.caseParticipant.findMany(),
|
||||
db.caseExclusion.findMany(),
|
||||
db.caseLink.findMany(),
|
||||
db.personnelFile.findMany(),
|
||||
db.personnelAssignment.findMany(),
|
||||
db.document.findMany(),
|
||||
db.documentSection.findMany(),
|
||||
db.documentSectionVersion.findMany(),
|
||||
db.attachment.findMany(),
|
||||
db.channel.findMany(),
|
||||
db.chatMessage.findMany(),
|
||||
db.chatReaction.findMany(),
|
||||
// Das Protokoll gehört dazu: ein Abzug ohne die Zugriffsspur wäre als
|
||||
// Notfallformat wertlos.
|
||||
db.auditLog.findMany({ orderBy: { id: 'desc' }, take: 50_000 }),
|
||||
])
|
||||
|
||||
const abzug = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
exportedBy: p.userId,
|
||||
note: 'Vollstaendiger Abzug ohne Stufenfilterung. Vertraulich behandeln.',
|
||||
users,
|
||||
roleMappings,
|
||||
clearanceLevels,
|
||||
foundationClearances,
|
||||
statusTags,
|
||||
templates,
|
||||
cases,
|
||||
caseSections,
|
||||
caseSectionVersions,
|
||||
caseEntries,
|
||||
caseEntryVersions,
|
||||
participants,
|
||||
exclusions,
|
||||
links,
|
||||
personnel,
|
||||
assignments,
|
||||
documents,
|
||||
documentSections,
|
||||
documentSectionVersions,
|
||||
attachments,
|
||||
channels,
|
||||
messages,
|
||||
reactions,
|
||||
auditLog,
|
||||
}
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await writeAudit(tx, {
|
||||
actorId: p.userId,
|
||||
action: 'export.database',
|
||||
targetType: 'Database',
|
||||
targetId: 'all',
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
meta: { cases: cases.length, entries: caseEntries.length, users: users.length },
|
||||
})
|
||||
})
|
||||
|
||||
// `BigInt` kommt in AuditLog.id vor und ist in JSON nicht vorgesehen.
|
||||
return new TextEncoder().encode(
|
||||
JSON.stringify(abzug, (_key, wert: unknown) =>
|
||||
typeof wert === 'bigint' ? wert.toString() : wert,
|
||||
2),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { getCurrentUser } from '@/lib/auth/current'
|
||||
import { permissionsFromRenderToken } from '@/lib/export/renderAccess'
|
||||
import type { EffectivePermissions } from '@/lib/auth/permissions'
|
||||
|
||||
/**
|
||||
* Die Druckansicht dient zwei Aufrufern: dem PDF-Dienst mit Zeichen und einem
|
||||
* Menschen, der sie sich ansieht. Diese Funktion steht in einer eigenen Datei,
|
||||
* weil sie `next-auth` lädt — der Zeichenpfad soll das nicht müssen.
|
||||
*/
|
||||
export async function permissionsForPrint(
|
||||
token: string | null | undefined,
|
||||
): Promise<{ permissions: EffectivePermissions; displayName: string } | null> {
|
||||
if (token) return permissionsFromRenderToken(token)
|
||||
|
||||
const user = await getCurrentUser()
|
||||
if (!user) return null
|
||||
return { permissions: user.permissions, displayName: user.displayName }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { db } from '@/lib/db'
|
||||
import { verifyRenderToken } from '@/lib/export/token'
|
||||
import { resolvePermissions } from '@/lib/auth/effective'
|
||||
import type { EffectivePermissions } from '@/lib/auth/permissions'
|
||||
|
||||
/**
|
||||
* Wer die Druckansicht sehen darf.
|
||||
*
|
||||
* Zwei Wege: die angemeldete Person selbst, oder der PDF-Dienst mit einem
|
||||
* kurzlebigen Zeichen, das für **genau diesen Auftrag** ausgestellt wurde.
|
||||
*
|
||||
* Die Stufe kommt dabei nicht aus dem Zeichen, sondern wird frisch aufgelöst
|
||||
* und dann auf die im Zeichen vermerkte **gedeckelt**. Damit kann ein Zeichen
|
||||
* nie mehr zeigen, als der Abrufer beim Anfragen sehen durfte — und auch nicht
|
||||
* mehr, als er jetzt noch darf, falls ihm inzwischen Rechte entzogen wurden.
|
||||
*/
|
||||
export async function permissionsFromRenderToken(
|
||||
token: string | null | undefined,
|
||||
): Promise<{ permissions: EffectivePermissions; displayName: string } | null> {
|
||||
const claim = verifyRenderToken(token)
|
||||
|
||||
{
|
||||
if (!claim) return null
|
||||
const auftrag = await db.exportJob.findUnique({
|
||||
where: { id: claim.jobId },
|
||||
select: { status: true, requestedById: true },
|
||||
})
|
||||
// Nur solange der Auftrag wirklich läuft. Ein Zeichen aus einem
|
||||
// abgeschlossenen oder abgelehnten Auftrag taugt zu nichts.
|
||||
if (!auftrag || auftrag.status !== 'RUNNING') return null
|
||||
if (auftrag.requestedById !== claim.userId) return null
|
||||
|
||||
const nutzer = await db.user.findUnique({
|
||||
where: { id: claim.userId },
|
||||
select: { displayName: true, isActive: true },
|
||||
})
|
||||
if (!nutzer?.isActive) return null
|
||||
|
||||
const aktuell = await resolvePermissions(claim.userId)
|
||||
return {
|
||||
permissions: {
|
||||
...aktuell,
|
||||
clearanceLevel: Math.min(aktuell.clearanceLevel, claim.clearanceLevel),
|
||||
},
|
||||
displayName: nutzer.displayName,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { db } from '@/lib/db'
|
||||
import { getEnv } from '@/lib/env'
|
||||
import { writeAudit, READ_AUDIT_FROM_LEVEL } from '@/lib/audit'
|
||||
import { AccessError } from '@/lib/errors'
|
||||
import { loadVisibleCase } from '@/lib/cases/service'
|
||||
import { loadVisibleDocument } from '@/lib/documents/service'
|
||||
import { ensureDirFor, storageKeyFor } from '@/lib/files/paths'
|
||||
import { exportCacheKey } from '@/lib/export/cacheKey'
|
||||
import { createRenderToken } from '@/lib/export/token'
|
||||
import { publish, userTopic } from '@/lib/realtime/publish'
|
||||
import type { EffectivePermissions } from '@/lib/auth/permissions'
|
||||
|
||||
/**
|
||||
* Exportaufträge.
|
||||
*
|
||||
* Drei Regeln aus docs/08-suche-und-export.md, und alle drei stecken hier:
|
||||
*
|
||||
* 1. **Der Export respektiert die Stufe des Abrufers.** Die Druckansicht
|
||||
* rendert mit seinen Rechten, gesperrte Felder erscheinen als Schwärzung
|
||||
* mit Vermerk — nicht weggelassen, sonst merkt der Empfänger nicht, dass
|
||||
* er eine gekürzte Fassung hat.
|
||||
* 2. **Wasserzeichen** auf jeder Seite: Name, Zeitstempel, Stufe.
|
||||
* 3. **Jeder Export wird protokolliert**, und ab Stufe 3 braucht er die
|
||||
* Freigabe durch ein zweites Augenpaar.
|
||||
*/
|
||||
|
||||
/** Ab dieser Klassifizierung braucht ein Export eine zweite Unterschrift. */
|
||||
export const APPROVAL_FROM_LEVEL = READ_AUDIT_FROM_LEVEL
|
||||
|
||||
export type ExportTarget =
|
||||
| { kind: 'CASE'; caseNumber: string }
|
||||
| { kind: 'DOCUMENT'; documentNumber: string }
|
||||
|
||||
/**
|
||||
* Legt einen Auftrag an — oder gibt einen fertigen zurück, wenn genau dieser
|
||||
* Stand schon einmal für diese Stufe gerendert wurde.
|
||||
*/
|
||||
export async function requestExport(
|
||||
p: EffectivePermissions,
|
||||
target: ExportTarget,
|
||||
): Promise<{ jobId: string; status: string }> {
|
||||
const ziel = await aufloesen(p, target)
|
||||
|
||||
const cacheKey = exportCacheKey({
|
||||
kind: target.kind,
|
||||
targetId: ziel.id,
|
||||
updatedAt: ziel.updatedAt,
|
||||
clearanceLevel: p.clearanceLevel,
|
||||
templateVersion: ziel.templateVersion,
|
||||
})
|
||||
|
||||
// Derselbe Stand, dieselbe Stufe: das PDF liegt schon da.
|
||||
const fertig = await db.exportJob.findFirst({
|
||||
where: { cacheKey, status: 'READY' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (fertig) {
|
||||
await protokolliere(p, 'export.pdf', ziel.id, { cached: true, kind: target.kind })
|
||||
return { jobId: fertig.id, status: 'READY' }
|
||||
}
|
||||
|
||||
// Läuft schon einer für denselben Stand? Dann daran hängen.
|
||||
const laufend = await db.exportJob.findFirst({
|
||||
where: { cacheKey, status: { in: ['QUEUED', 'RUNNING', 'PENDING_APPROVAL'] } },
|
||||
select: { id: true, status: true },
|
||||
})
|
||||
if (laufend) return { jobId: laufend.id, status: laufend.status }
|
||||
|
||||
const brauchtFreigabe = ziel.classification >= APPROVAL_FROM_LEVEL
|
||||
|
||||
const auftrag = await db.$transaction(async (tx) => {
|
||||
const angelegt = await tx.exportJob.create({
|
||||
data: {
|
||||
kind: target.kind,
|
||||
targetId: ziel.id,
|
||||
requestedById: p.userId,
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
cacheKey,
|
||||
status: brauchtFreigabe ? 'PENDING_APPROVAL' : 'QUEUED',
|
||||
},
|
||||
select: { id: true, status: true },
|
||||
})
|
||||
|
||||
await writeAudit(tx, {
|
||||
actorId: p.userId,
|
||||
action: 'export.pdf',
|
||||
targetType: target.kind === 'CASE' ? 'Case' : 'Document',
|
||||
targetId: ziel.id,
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
meta: {
|
||||
jobId: angelegt.id,
|
||||
label: ziel.label,
|
||||
classification: ziel.classification,
|
||||
needsApproval: brauchtFreigabe,
|
||||
},
|
||||
})
|
||||
|
||||
return angelegt
|
||||
})
|
||||
|
||||
return { jobId: auftrag.id, status: auftrag.status }
|
||||
}
|
||||
|
||||
async function aufloesen(p: EffectivePermissions, target: ExportTarget) {
|
||||
if (target.kind === 'CASE') {
|
||||
const akte = await loadVisibleCase(p, target.caseNumber)
|
||||
if (!akte) throw new AccessError('not-found')
|
||||
const vorlage = await db.documentTemplate.findUnique({
|
||||
where: { id: akte.templateId },
|
||||
select: { version: true },
|
||||
})
|
||||
return {
|
||||
id: akte.id,
|
||||
label: akte.caseNumber,
|
||||
classification: akte.classification,
|
||||
updatedAt: akte.updatedAt,
|
||||
templateVersion: vorlage?.version ?? 0,
|
||||
printPath: `/faelle/${akte.caseNumber}/druck`,
|
||||
}
|
||||
}
|
||||
|
||||
const doc = await loadVisibleDocument(p, target.documentNumber)
|
||||
if (!doc) throw new AccessError('not-found')
|
||||
return {
|
||||
id: doc.id,
|
||||
label: doc.documentNumber,
|
||||
classification: doc.classification,
|
||||
updatedAt: doc.updatedAt,
|
||||
templateVersion: doc.templateVersion,
|
||||
printPath: `/dokumente/${doc.documentNumber}/druck`,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Freigabe durch ein zweites Augenpaar.
|
||||
*
|
||||
* **Nicht durch den Anfragenden selbst** — sonst wäre es keins. Das ist der
|
||||
* einzige Grund, warum es die Prüfung überhaupt gibt.
|
||||
*/
|
||||
export async function approveExport(
|
||||
p: EffectivePermissions,
|
||||
jobId: string,
|
||||
): Promise<void> {
|
||||
if (!p.isAdmin && !p.permissions.has('export.approve')) {
|
||||
throw new AccessError('no-permission')
|
||||
}
|
||||
|
||||
const auftrag = await db.exportJob.findUnique({
|
||||
where: { id: jobId },
|
||||
select: { id: true, status: true, requestedById: true, targetId: true, kind: true },
|
||||
})
|
||||
if (!auftrag) throw new AccessError('not-found')
|
||||
if (auftrag.status !== 'PENDING_APPROVAL') throw new AccessError('export-not-pending')
|
||||
if (auftrag.requestedById === p.userId) throw new AccessError('export-self-approval')
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.exportJob.update({
|
||||
where: { id: jobId },
|
||||
data: { status: 'QUEUED', approvedById: p.userId, approvedAt: new Date() },
|
||||
})
|
||||
await writeAudit(tx, {
|
||||
actorId: p.userId,
|
||||
action: 'export.approve',
|
||||
targetType: 'ExportJob',
|
||||
targetId: jobId,
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
meta: { requestedBy: auftrag.requestedById, kind: auftrag.kind },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function rejectExport(
|
||||
p: EffectivePermissions,
|
||||
jobId: string,
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
if (!p.isAdmin && !p.permissions.has('export.approve')) {
|
||||
throw new AccessError('no-permission')
|
||||
}
|
||||
const begruendung = reason.trim()
|
||||
if (begruendung.length < 10) throw new AccessError('reason-required')
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.exportJob.updateMany({
|
||||
where: { id: jobId, status: 'PENDING_APPROVAL' },
|
||||
data: { status: 'REJECTED', rejectedById: p.userId, rejectReason: begruendung },
|
||||
})
|
||||
await writeAudit(tx, {
|
||||
actorId: p.userId,
|
||||
action: 'export.reject',
|
||||
targetType: 'ExportJob',
|
||||
targetId: jobId,
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
meta: { reason: begruendung },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt einen freigegebenen Auftrag aus: Druckansicht rendern lassen, ablegen,
|
||||
* melden.
|
||||
*
|
||||
* Läuft im Hintergrund, nach der Antwort. Der PDF-Dienst bekommt ein
|
||||
* kurzlebiges Zeichen statt eines Sitzungscookies, siehe `token.ts`.
|
||||
*/
|
||||
export async function runExport(jobId: string): Promise<void> {
|
||||
const auftrag = await db.exportJob.findUnique({ where: { id: jobId } })
|
||||
if (!auftrag || auftrag.status !== 'QUEUED') return
|
||||
|
||||
await db.exportJob.update({
|
||||
where: { id: jobId },
|
||||
data: { status: 'RUNNING', startedAt: new Date() },
|
||||
})
|
||||
|
||||
try {
|
||||
const pfad = await druckPfad(auftrag.kind, auftrag.targetId)
|
||||
if (!pfad) throw new Error('Ziel nicht mehr vorhanden')
|
||||
|
||||
const env = getEnv()
|
||||
if (!env.PDF_SERVICE_URL) throw new Error('PDF_SERVICE_URL ist nicht gesetzt')
|
||||
|
||||
const nutzer = await db.user.findUnique({
|
||||
where: { id: auftrag.requestedById },
|
||||
select: { displayName: true },
|
||||
})
|
||||
|
||||
const token = createRenderToken({
|
||||
jobId,
|
||||
userId: auftrag.requestedById,
|
||||
clearanceLevel: auftrag.clearanceAtTime,
|
||||
})
|
||||
const url = `${env.APP_URL.replace(/\/$/, '')}${pfad}?token=${encodeURIComponent(token)}`
|
||||
|
||||
const antwort = await fetch(`${env.PDF_SERVICE_URL.replace(/\/$/, '')}/render`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
// Wasserzeichen auf jeder Seite, siehe docs/08. Es steht im
|
||||
// Seitenkopf, damit es nicht im Inhalt untergeht.
|
||||
headerHtml: wasserzeichen(
|
||||
nutzer?.displayName ?? auftrag.requestedById,
|
||||
auftrag.clearanceAtTime,
|
||||
),
|
||||
footerHtml:
|
||||
'<div style="width:100%;font-size:7pt;font-family:monospace;padding:0 16mm;' +
|
||||
'display:flex;justify-content:space-between;color:#444">' +
|
||||
'<span class="date"></span><span><span class="pageNumber"></span>/<span class="totalPages"></span></span>' +
|
||||
'</div>',
|
||||
}),
|
||||
})
|
||||
|
||||
if (!antwort.ok) {
|
||||
throw new Error(`PDF-Dienst antwortete mit ${antwort.status}`)
|
||||
}
|
||||
|
||||
const inhalt = new Uint8Array(await antwort.arrayBuffer())
|
||||
const storageKey = storageKeyFor('store', `export-${jobId}`)
|
||||
await writeFile(await ensureDirFor(storageKey), inhalt)
|
||||
|
||||
await db.exportJob.update({
|
||||
where: { id: jobId },
|
||||
data: {
|
||||
status: 'READY',
|
||||
storageKey,
|
||||
sizeBytes: inhalt.byteLength,
|
||||
finishedAt: new Date(),
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
await db.exportJob.update({
|
||||
where: { id: jobId },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
error: error instanceof Error ? error.message.slice(0, 300) : 'unbekannt',
|
||||
finishedAt: new Date(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await publish(userTopic(auftrag.requestedById), 'export.ready', jobId)
|
||||
}
|
||||
|
||||
function wasserzeichen(name: string, stufe: number): string {
|
||||
const sicher = name.replace(/[<>&]/g, '')
|
||||
return (
|
||||
'<div style="width:100%;font-size:7pt;font-family:monospace;padding:0 16mm;' +
|
||||
'display:flex;justify-content:space-between;color:#666">' +
|
||||
`<span>${sicher} · Stufe ${stufe}</span>` +
|
||||
'<span class="date"></span>' +
|
||||
'</div>'
|
||||
)
|
||||
}
|
||||
|
||||
async function druckPfad(kind: string, targetId: string | null): Promise<string | null> {
|
||||
if (!targetId) return null
|
||||
if (kind === 'CASE') {
|
||||
const akte = await db.case.findUnique({
|
||||
where: { id: targetId },
|
||||
select: { caseNumber: true },
|
||||
})
|
||||
return akte ? `/faelle/${akte.caseNumber}/druck` : null
|
||||
}
|
||||
const doc = await db.document.findUnique({
|
||||
where: { id: targetId },
|
||||
select: { documentNumber: true },
|
||||
})
|
||||
return doc ? `/dokumente/${doc.documentNumber}/druck` : null
|
||||
}
|
||||
|
||||
async function protokolliere(
|
||||
p: EffectivePermissions,
|
||||
action: 'export.pdf',
|
||||
targetId: string,
|
||||
meta: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
await db.$transaction(async (tx) => {
|
||||
await writeAudit(tx, {
|
||||
actorId: p.userId,
|
||||
action,
|
||||
targetType: 'ExportJob',
|
||||
targetId,
|
||||
clearanceAtTime: p.clearanceLevel,
|
||||
meta: meta as never,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Der Auftrag, sofern er dem Abrufer gehört. */
|
||||
export async function loadJob(p: EffectivePermissions, jobId: string) {
|
||||
return db.exportJob.findFirst({
|
||||
where: { id: jobId, requestedById: p.userId },
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
sizeBytes: true,
|
||||
error: true,
|
||||
rejectReason: true,
|
||||
createdAt: true,
|
||||
finishedAt: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Offene Freigaben für das Dashboard des Leiters. */
|
||||
export async function pendingApprovals(p: EffectivePermissions) {
|
||||
if (!p.isAdmin && !p.permissions.has('export.approve')) return []
|
||||
|
||||
return db.exportJob.findMany({
|
||||
where: { status: 'PENDING_APPROVAL', requestedById: { not: p.userId } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 20,
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
targetId: true,
|
||||
requestedById: true,
|
||||
clearanceAtTime: true,
|
||||
createdAt: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto'
|
||||
import { getEnv } from '@/lib/env'
|
||||
|
||||
/**
|
||||
* Kurzlebiges Zeichen für den Druckabruf.
|
||||
*
|
||||
* Der PDF-Dienst ruft die Druckansicht selbst auf und braucht dafür die Rechte
|
||||
* des Abrufers. Ihm dafür das **Sitzungscookie** mitzugeben wäre der bequeme
|
||||
* Weg und der falsche: ein Cookie ist der volle Zugang zum Konto, und es läge
|
||||
* dann im Speicher eines zweiten Prozesses und in dessen Protokollen.
|
||||
*
|
||||
* Stattdessen ein signiertes Zeichen, das genau eines erlaubt: diese eine
|
||||
* Ansicht, für diesen einen Auftrag, für ein paar Minuten. Es taugt zu nichts
|
||||
* anderem. Vergleichbar mit der signierten Datei-URL aus docs/07.
|
||||
*/
|
||||
|
||||
/** Lange genug für einen langsamen Rendervorgang, kurz genug zum Wegwerfen. */
|
||||
const GUELTIG_MS = 10 * 60_000
|
||||
|
||||
export type RenderClaim = {
|
||||
jobId: string
|
||||
userId: string
|
||||
clearanceLevel: number
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
function signieren(nutzlast: string): string {
|
||||
return createHmac('sha256', getEnv().AUTH_SECRET).update(nutzlast).digest('base64url')
|
||||
}
|
||||
|
||||
export function createRenderToken(claim: Omit<RenderClaim, 'expiresAt'>): string {
|
||||
const vollstaendig: RenderClaim = { ...claim, expiresAt: Date.now() + GUELTIG_MS }
|
||||
const nutzlast = Buffer.from(JSON.stringify(vollstaendig)).toString('base64url')
|
||||
return `${nutzlast}.${signieren(nutzlast)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft das Zeichen. Gibt `null` zurück, wenn irgendetwas nicht stimmt — der
|
||||
* Aufrufer macht daraus 404, nicht 403: dass es die Druckansicht gibt, geht
|
||||
* niemanden etwas an, der kein gültiges Zeichen hat.
|
||||
*/
|
||||
export function verifyRenderToken(token: string | null | undefined): RenderClaim | null {
|
||||
if (!token) return null
|
||||
|
||||
const [nutzlast, unterschrift] = token.split('.')
|
||||
if (!nutzlast || !unterschrift) return null
|
||||
|
||||
const erwartet = signieren(nutzlast)
|
||||
// Zeitkonstanter Vergleich: ein Längenvergleich vorweg, weil timingSafeEqual
|
||||
// bei ungleicher Länge wirft.
|
||||
if (erwartet.length !== unterschrift.length) return null
|
||||
if (!timingSafeEqual(Buffer.from(erwartet), Buffer.from(unterschrift))) return null
|
||||
|
||||
try {
|
||||
const claim = JSON.parse(Buffer.from(nutzlast, 'base64url').toString('utf8')) as RenderClaim
|
||||
if (typeof claim.expiresAt !== 'number' || claim.expiresAt < Date.now()) return null
|
||||
if (typeof claim.userId !== 'string' || typeof claim.jobId !== 'string') return null
|
||||
return claim
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* Ein winziger ZIP-Schreiber, nur „gespeichert" ohne Kompression.
|
||||
*
|
||||
* Eigener Code statt einer Abhängigkeit, weil der Inhalt eines Sammelexports
|
||||
* PDFs und bereits neu kodierte Bilder sind — beides ist komprimiert, ein
|
||||
* Deflate darüber bringt nichts und kostet nur CPU auf einem Heimserver. Was
|
||||
* bleibt, ist das Behälterformat, und das sind achtzig Zeilen.
|
||||
*
|
||||
* Aufbau nach der ZIP-Spezifikation: je Eintrag ein lokaler Kopf mit den
|
||||
* Daten, danach das zentrale Verzeichnis und dessen Abschluss.
|
||||
*/
|
||||
|
||||
type Eintrag = { name: string; content: Uint8Array }
|
||||
|
||||
/** DOS-Zeitstempel. Die Auflösung beträgt zwei Sekunden, das reicht hier. */
|
||||
function dosZeit(datum: Date): { zeit: number; datum: number } {
|
||||
return {
|
||||
zeit:
|
||||
(datum.getHours() << 11) | (datum.getMinutes() << 5) | Math.floor(datum.getSeconds() / 2),
|
||||
datum:
|
||||
((datum.getFullYear() - 1980) << 9) | ((datum.getMonth() + 1) << 5) | datum.getDate(),
|
||||
}
|
||||
}
|
||||
|
||||
function crc32(daten: Uint8Array): number {
|
||||
// Tabelle einmal je Aufruf: bei einer Handvoll Dateien je Export ist das
|
||||
// billiger als eine Konstante, die immer im Speicher liegt.
|
||||
let c: number
|
||||
const tabelle = new Int32Array(256)
|
||||
for (let n = 0; n < 256; n++) {
|
||||
c = n
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
||||
tabelle[n] = c
|
||||
}
|
||||
|
||||
let crc = -1
|
||||
for (const byte of daten) crc = (crc >>> 8) ^ tabelle[(crc ^ byte) & 0xff]!
|
||||
return (crc ^ -1) >>> 0
|
||||
}
|
||||
|
||||
export function createZip(eintraege: Eintrag[], now: Date = new Date()): Uint8Array {
|
||||
const { zeit, datum } = dosZeit(now)
|
||||
const teile: Buffer[] = []
|
||||
const verzeichnis: Buffer[] = []
|
||||
let offset = 0
|
||||
|
||||
for (const eintrag of eintraege) {
|
||||
const name = Buffer.from(eintrag.name, 'utf8')
|
||||
const inhalt = Buffer.from(eintrag.content)
|
||||
const pruefsumme = crc32(eintrag.content)
|
||||
|
||||
const lokal = Buffer.alloc(30)
|
||||
lokal.writeUInt32LE(0x04034b50, 0)
|
||||
lokal.writeUInt16LE(20, 4) // benötigte Version
|
||||
lokal.writeUInt16LE(0x0800, 6) // Bit 11: Name ist UTF-8
|
||||
lokal.writeUInt16LE(0, 8) // Verfahren: gespeichert
|
||||
lokal.writeUInt16LE(zeit, 10)
|
||||
lokal.writeUInt16LE(datum, 12)
|
||||
lokal.writeUInt32LE(pruefsumme, 14)
|
||||
lokal.writeUInt32LE(inhalt.length, 18)
|
||||
lokal.writeUInt32LE(inhalt.length, 22)
|
||||
lokal.writeUInt16LE(name.length, 26)
|
||||
lokal.writeUInt16LE(0, 28)
|
||||
|
||||
teile.push(lokal, name, inhalt)
|
||||
|
||||
const zentral = Buffer.alloc(46)
|
||||
zentral.writeUInt32LE(0x02014b50, 0)
|
||||
zentral.writeUInt16LE(20, 4)
|
||||
zentral.writeUInt16LE(20, 6)
|
||||
zentral.writeUInt16LE(0x0800, 8)
|
||||
zentral.writeUInt16LE(0, 10)
|
||||
zentral.writeUInt16LE(zeit, 12)
|
||||
zentral.writeUInt16LE(datum, 14)
|
||||
zentral.writeUInt32LE(pruefsumme, 16)
|
||||
zentral.writeUInt32LE(inhalt.length, 20)
|
||||
zentral.writeUInt32LE(inhalt.length, 24)
|
||||
zentral.writeUInt16LE(name.length, 28)
|
||||
zentral.writeUInt32LE(offset, 42)
|
||||
verzeichnis.push(zentral, name)
|
||||
|
||||
offset += lokal.length + name.length + inhalt.length
|
||||
}
|
||||
|
||||
const verzeichnisBytes = Buffer.concat(verzeichnis)
|
||||
const abschluss = Buffer.alloc(22)
|
||||
abschluss.writeUInt32LE(0x06054b50, 0)
|
||||
abschluss.writeUInt16LE(eintraege.length, 8)
|
||||
abschluss.writeUInt16LE(eintraege.length, 10)
|
||||
abschluss.writeUInt32LE(verzeichnisBytes.length, 12)
|
||||
abschluss.writeUInt32LE(offset, 16)
|
||||
|
||||
return new Uint8Array(Buffer.concat([...teile, verzeichnisBytes, abschluss]))
|
||||
}
|
||||
|
||||
/** Für das Protokoll: worüber genau wurde ausgeleitet. */
|
||||
export function digestOf(daten: Uint8Array): string {
|
||||
return createHash('sha256').update(daten).digest('hex')
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { access, readFile, writeFile } from 'node:fs/promises'
|
||||
import { db } from '@/lib/db'
|
||||
import { getEnv } from '@/lib/env'
|
||||
import { scanBuffer } from '@/lib/files/clamav'
|
||||
@@ -155,22 +155,26 @@ async function freigeben(
|
||||
const sha256 = sha256Of(neu.content)
|
||||
|
||||
// Gleicher Inhalt schon da: nur verweisen, nicht ein zweites Mal ablegen.
|
||||
//
|
||||
// Der Verweis gilt aber nur, wenn die Datei auch wirklich noch liegt. Eine
|
||||
// Zeile in der Datenbank ist kein Beweis dafür: geht die Ablage verloren —
|
||||
// ein geleertes Verzeichnis, ein nicht eingehängtes Volume —, zeigten sonst
|
||||
// alle künftigen Uploads desselben Inhalts stumm ins Leere.
|
||||
const vorhanden = await db.attachment.findFirst({
|
||||
where: { sha256, scanStatus: 'CLEAN', id: { not: attachmentId } },
|
||||
select: { storageKey: true, thumbKey: true, blurhash: true, width: true, height: true },
|
||||
})
|
||||
const wiederverwendbar = vorhanden !== null && (await liegtDa(vorhanden.storageKey))
|
||||
|
||||
let storageKey = vorhanden?.storageKey ?? storageKeyFor(STORE, attachmentId)
|
||||
let thumbKey = vorhanden?.thumbKey ?? null
|
||||
const storageKey = wiederverwendbar ? vorhanden!.storageKey : storageKeyFor(STORE, attachmentId)
|
||||
let thumbKey = wiederverwendbar ? vorhanden!.thumbKey : null
|
||||
|
||||
if (!vorhanden) {
|
||||
if (!wiederverwendbar) {
|
||||
await writeFile(await ensureDirFor(storageKey), neu.content)
|
||||
if (neu.thumb) {
|
||||
thumbKey = `${storageKey}.thumb`
|
||||
await writeFile(await ensureDirFor(thumbKey), neu.thumb)
|
||||
}
|
||||
} else {
|
||||
storageKey = vorhanden.storageKey
|
||||
}
|
||||
|
||||
await db.attachment.update({
|
||||
@@ -183,15 +187,25 @@ async function freigeben(
|
||||
sha256,
|
||||
storageKey,
|
||||
thumbKey,
|
||||
blurhash: neu.blurhash ?? vorhanden?.blurhash ?? null,
|
||||
width: neu.width ?? vorhanden?.width ?? null,
|
||||
height: neu.height ?? vorhanden?.height ?? null,
|
||||
blurhash: neu.blurhash ?? (wiederverwendbar ? vorhanden!.blurhash : null),
|
||||
width: neu.width ?? (wiederverwendbar ? vorhanden!.width : null),
|
||||
height: neu.height ?? (wiederverwendbar ? vorhanden!.height : null),
|
||||
},
|
||||
})
|
||||
|
||||
await notifyAttachmentScanned(attachmentId, thema)
|
||||
}
|
||||
|
||||
/** Liegt die Datei zu diesem Schlüssel wirklich noch da? */
|
||||
async function liegtDa(storageKey: string): Promise<boolean> {
|
||||
try {
|
||||
await access(absolutePath(storageKey))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Endgültig abgelehnt: die Datei ist als gefährlich oder unzulässig erkannt. */
|
||||
async function blockieren(attachmentId: string, grund: string, thema: Topic): Promise<void> {
|
||||
await db.attachment.update({
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
import { chatText, channelText } from '@/lib/i18n/chat'
|
||||
import { personnelText, assignmentText } from '@/lib/i18n/people'
|
||||
import { documentText, attachmentText } from '@/lib/i18n/documents'
|
||||
import { exportText } from '@/lib/i18n/export'
|
||||
import { roleAdminText, templateAdminText, settingsText } from '@/lib/i18n/admin'
|
||||
|
||||
export const de = {
|
||||
@@ -55,6 +56,7 @@ export const de = {
|
||||
channel: channelText,
|
||||
document: documentText,
|
||||
attachment: attachmentText,
|
||||
export: exportText,
|
||||
common: commonText,
|
||||
actionErrors: actionErrorsText,
|
||||
errors: errorsText,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Export und Druck.
|
||||
*
|
||||
* Eigene Datei und nicht bei den Dokumenten: die Fallakte lädt die
|
||||
* Dokumenttexte sofort, den Export nie — er hat eine eigene Seite. Lägen sie
|
||||
* zusammen, käme er doch mit. Siehe docs/13-entscheidungen.md.
|
||||
*/
|
||||
export const exportText = {
|
||||
heading: 'Export',
|
||||
asPdf: 'Als PDF exportieren',
|
||||
print: 'Druckansicht',
|
||||
asOf: 'Stand',
|
||||
retrievedBy: 'Abgerufen von',
|
||||
coverNote:
|
||||
'Dieser Ausdruck gibt den Stand zum oben genannten Zeitpunkt wieder und ist auf die Freigabestufe des Abrufers gekürzt. Ein späterer Stand kann abweichen.',
|
||||
editedAt: (version: number, datum: string) => `bearbeitet, v${version}, ${datum}`,
|
||||
redactedAt: (stufe: number, name: string) => `Geschwärzt, Stufe ${stufe} ${name}`.trim(),
|
||||
fileName: 'Datei',
|
||||
fileSize: 'Bytes',
|
||||
fileHash: 'SHA-256',
|
||||
preparing: 'Wird erzeugt',
|
||||
ready: 'Fertig',
|
||||
download: 'Herunterladen',
|
||||
failed: 'Nicht erzeugt',
|
||||
waitingApproval: 'Wartet auf Freigabe',
|
||||
waitingApprovalHint:
|
||||
'Ab Stufe 3 gibt ein zweites Augenpaar den Export frei. Die Anfrage steht auf der Übersicht.',
|
||||
rejected: 'Abgelehnt',
|
||||
approvals: 'Offene Exportfreigaben',
|
||||
approvalsEmpty: 'Keine offenen Freigaben.',
|
||||
approve: 'Freigeben',
|
||||
reject: 'Ablehnen',
|
||||
rejectReason: 'Begründung der Ablehnung',
|
||||
requestedBy: 'Angefragt von',
|
||||
kinds: {
|
||||
CASE: 'Fallakte',
|
||||
DOCUMENT: 'Dokument',
|
||||
BUNDLE: 'Sammelexport',
|
||||
DATABASE: 'Datenbankabzug',
|
||||
} as Record<string, string>,
|
||||
database: 'Datenbankabzug als JSON',
|
||||
databaseHint:
|
||||
'Vollständig und ohne Stufenfilterung, als Umzugs- und Notfallformat. Nur für Administratoren, immer protokolliert.',
|
||||
bundle: 'Sammelexport als ZIP',
|
||||
} as const
|
||||
@@ -26,6 +26,7 @@ export type EventKind =
|
||||
| 'entry.updated'
|
||||
| 'case.update'
|
||||
| 'attachment.scanned'
|
||||
| 'export.ready'
|
||||
|
||||
/** Wer das Ereignis angeht. */
|
||||
export type Topic = `case:${string}` | `channel:${string}` | `user:${string}`
|
||||
|
||||
Reference in New Issue
Block a user