|
| 1 | +import crypto from 'crypto'; |
| 2 | +import fs from 'fs/promises'; |
| 3 | +import path from 'path'; |
| 4 | + |
| 5 | +export type ConsentAction = 'persist_on' | 'persist_off' | 'export'; |
| 6 | +export type ConsentEvent = { userId: string; sessionId?: string; action: ConsentAction; ts: string; prevHash?: string; hash?: string }; |
| 7 | + |
| 8 | +const DATA_DIR = path.join(process.cwd(), 'next-app', '.data', 'consent'); |
| 9 | + |
| 10 | +export async function appendConsentEvent(e: Omit<ConsentEvent, 'hash' | 'prevHash'>) { |
| 11 | + await fs.mkdir(DATA_DIR, { recursive: true }); |
| 12 | + const chainFile = path.join(DATA_DIR, `${e.userId}.jsonl`); |
| 13 | + let prevHash: string | undefined; |
| 14 | + try { |
| 15 | + const last = await tailLastLine(chainFile); |
| 16 | + if (last) prevHash = JSON.parse(last).hash; |
| 17 | + } catch {} |
| 18 | + const event: ConsentEvent = { ...e, prevHash, ts: e.ts ?? new Date().toISOString() }; |
| 19 | + event.hash = hashEvent(event); |
| 20 | + await fs.appendFile(chainFile, JSON.stringify(event) + '\n', 'utf8'); |
| 21 | + return event; |
| 22 | +} |
| 23 | + |
| 24 | +export function hashEvent(e: ConsentEvent) { |
| 25 | + const s = `${e.userId}|${e.sessionId ?? ''}|${e.action}|${e.ts}|${e.prevHash ?? ''}`; |
| 26 | + return crypto.createHash('sha256').update(s).digest('hex'); |
| 27 | +} |
| 28 | + |
| 29 | +export async function exportConsent(userId: string) { |
| 30 | + const chainFile = path.join(DATA_DIR, `${userId}.jsonl`); |
| 31 | + try { |
| 32 | + const raw = await fs.readFile(chainFile, 'utf8'); |
| 33 | + const events = raw.trim().split('\n').map((l) => JSON.parse(l) as ConsentEvent); |
| 34 | + return { events, root: events.at(-1)?.hash }; |
| 35 | + } catch (e: any) { |
| 36 | + if (e.code === 'ENOENT') return { events: [], root: undefined }; |
| 37 | + throw e; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +async function tailLastLine(file: string): Promise<string | null> { |
| 42 | + try { |
| 43 | + const data = await fs.readFile(file, 'utf8'); |
| 44 | + const lines = data.trim().split('\n'); |
| 45 | + return lines.length ? lines[lines.length - 1] : null; |
| 46 | + } catch (e: any) { |
| 47 | + if (e.code === 'ENOENT') return null; |
| 48 | + throw e; |
| 49 | + } |
| 50 | +} |
0 commit comments