import crypto from 'crypto'; import { keyId } from './config.js'; // Token-Verschlüsselung (ADR 0003 §3): AES-256-GCM, Format v1.... (base64url), // AAD = `git-connection:`. const b64 = (buf)=>buf.toString('base64url'); const unb64 = (s)=>Buffer.from(s, 'base64url'); export const createTokenCrypto = ({ key, oldKeys = [] })=>{ if(!key) throw new Error('Kein Schlüssel für die Token-Verschlüsselung konfiguriert'); const current = { kid: keyId(key), key }; const all = new Map([[current.kid, key], ...oldKeys.map((k)=>[keyId(k), k])]); return { encrypt(token, connectionId) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(Buffer.from(`git-connection:${connectionId}`)); const ct = Buffer.concat([cipher.update(String(token), 'utf8'), cipher.final()]); return ['v1', current.kid, b64(iv), b64(ct), b64(cipher.getAuthTag())].join('.'); }, // → { token, rotate } (rotate: mit altem Schlüssel entschlüsselt, bitte neu verschlüsseln) decrypt(enc, connectionId) { const parts = String(enc).split('.'); if(parts.length !== 5 || parts[0] !== 'v1') throw new Error('Unbekanntes Token-Format'); const k = all.get(parts[1]); if(!k) throw new Error('Schlüssel zum Entschlüsseln nicht vorhanden'); const decipher = crypto.createDecipheriv('aes-256-gcm', k, unb64(parts[2])); decipher.setAAD(Buffer.from(`git-connection:${connectionId}`)); decipher.setAuthTag(unb64(parts[4])); const token = Buffer.concat([decipher.update(unb64(parts[3])), decipher.final()]).toString('utf8'); return { token, rotate: parts[1] !== current.kid }; } }; };