Files
skrift-directus/extensions/directus-extension-skrift-apikey/dist/index.js
2026-08-24 12:13:58 +02:00

38 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Skrift – API-Key-Hook
* ---------------------------------------------------------------------------
* Beim Anlegen eines api_clients-Eintrags wird automatisch ein API-Key erzeugt:
* - key_hash = SHA-256 des Keys (dauerhaft; nur damit authentifiziert die API)
* - key_prefix = Erkennungspräfix (Anzeige)
* - key_plain = Klartext-Key, EINMALIG sichtbar (jetzt kopieren)
*
* Bei der nächsten Änderung des Eintrags wird key_plain wieder geleert
* („reveal once"). Der Klartext wird also nie dauerhaft gespeichert.
*/
import crypto from 'node:crypto';
const sha256 = (s) => crypto.createHash('sha256').update(String(s)).digest('hex');
export default (register) => {
// Anlegen: Key erzeugen, sofern noch keiner gesetzt ist.
register.filter('api_clients.items.create', (payload) => {
if (payload && typeof payload === 'object' && !payload.key_hash) {
const key = `sk_live_${crypto.randomBytes(24).toString('base64url')}`;
payload.key_hash = sha256(key);
payload.key_prefix = key.slice(0, 14);
payload.key_plain = key; // einmalige Anzeige
if (payload.active === undefined) payload.active = true;
}
return payload;
});
// Jede spätere Änderung entfernt den Klartext (nur direkt nach Anlage sichtbar),
// außer er wird gerade explizit gesetzt.
register.filter('api_clients.items.update', (payload) => {
if (payload && typeof payload === 'object' && payload.key_plain === undefined) {
payload.key_plain = null;
}
return payload;
});
};