S1: Einrichtungs-Assistent, Twitch-Auth, Datenbank und Chat-Aufnahme

Zugangsdaten kommen jetzt aus der App statt aus einer .env: ein
Einrichtungs-Assistent auf http://localhost:4792/setup nimmt Client-ID,
Secret und OBS-Passwort entgegen, der OAuth-Rueckruf laeuft auf denselben
Server. Gespeichert wird verschlueselt (AES-256-GCM) in einem Volume,
bewusst nicht in der Datenbank - die wird auf die Windows-Seite gesichert.
Siehe ADR-0005.

Technikbasis vereinfacht: Node 24 bringt node:sqlite, WebSocket, fetch und
die Ausfuehrung von TypeScript mit. Das Projekt hat damit null
Laufzeitabhaengigkeiten und keinen Build-Schritt; pnpm-Workspaces und die
Paketmanifeste sind entfallen, Importe laufen ueber die imports-Map der
Wurzel-package.json. erasableSyntaxOnly verhindert Syntax, die das Type
Stripping stillschweigend entfernen wuerde. Siehe Nachtrag 2 in ADR-0001.

Enthalten:
- packages/core: Config, Layout, Logger mit Secret-Maskierung, Retry, YAML
- packages/db: Migrationen, Repositories, alle SQL-Anweisungen an einem Ort
- packages/twitch: Secret-Speicher, OAuth, Helix mit Token-Bucket, IRC
- apps/ingest: Daemon, Einrichtungsseite, Spike-Erkennung
- 20 Tests (IRC-Parser, Spike-Detektor, Datenbankschicht)

Der Chat verbindet sich anonym, solange nichts hinterlegt ist - damit laesst
sich die Datenaufnahme pruefen, bevor die Twitch-Apps existieren.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013VTGjd92LsDDWF3frd9FTB
This commit is contained in:
ZeasyAlexandClaude Opus 5 committed 2026-09-09 09:56:55 +02:00
1 parent 4ceb61f095
commit d07c18441b
82 files changed
+2775 -838

No files matched your search

-12
View File
@@ -1,12 +0,0 @@
{
"name": "@abdulive/twitch",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --test"
}
}
+118
View File
@@ -0,0 +1,118 @@
// Helix-Client mit eigenem Token-Bucket. Twitch erlaubt 800 Punkte pro Minute
// je Client-ID; wir drosseln selbst, statt uns auf 429 zu verlassen, und
// werten `Ratelimit-Remaining` aus dem Antwortkopf aus.
import { logger } from '#core/logger.ts';
import { retry, sleep } from '#core/retry.ts';
import { accessToken } from './oauth.ts';
import { readSecrets, type Role } from './secrets.ts';
const log = logger('helix');
const BASE = 'https://api.twitch.tv/helix';
class Bucket {
// Keine Parameter-Properties: Node fuehrt die .ts-Datei direkt aus und
// entfernt nur Typen; `constructor(private x)` waere zur Laufzeit weg.
private tokens: number;
private last = Date.now();
private capacity: number;
private perMinute: number;
constructor(capacity = 700, perMinute = 700) {
this.capacity = capacity;
this.perMinute = perMinute;
this.tokens = capacity;
}
async take(cost = 1): Promise<void> {
for (;;) {
const now = Date.now();
this.tokens = Math.min(this.capacity, this.tokens + ((now - this.last) / 60_000) * this.perMinute);
this.last = now;
if (this.tokens >= cost) { this.tokens -= cost; return; }
await sleep(Math.ceil(((cost - this.tokens) / this.perMinute) * 60_000) + 50);
}
}
/** Uebernimmt den echten Stand aus dem Antwortkopf. */
sync(remaining: number | null): void {
if (remaining !== null && remaining < this.tokens) this.tokens = remaining;
}
}
const bucket = new Bucket();
export type HelixStream = {
id: string; user_id: string; user_login: string; game_id: string; game_name: string;
title: string; viewer_count: number; started_at: string; language: string; thumbnail_url: string;
};
export type HelixUser = { id: string; login: string; display_name: string };
async function call<T>(role: Role, endpoint: string, init: RequestInit = {}): Promise<T> {
const app = readSecrets().apps[role];
if (!app?.clientId) throw new Error(`Fuer "${role}" ist keine Client-ID hinterlegt.`);
return await retry(async () => {
await bucket.take();
const token = await accessToken(role);
const res = await fetch(`${BASE}${endpoint}`, {
...init,
headers: {
'Client-Id': app.clientId,
Authorization: `Bearer ${token}`,
...(init.body ? { 'content-type': 'application/json' } : {}),
...init.headers,
},
});
const remaining = res.headers.get('ratelimit-remaining');
bucket.sync(remaining === null ? null : Number(remaining));
if (res.status === 429) {
const reset = Number(res.headers.get('ratelimit-reset') || 0) * 1000 - Date.now();
await sleep(Math.max(1000, Math.min(60_000, reset)));
throw new Error('Rate Limit erreicht');
}
if (!res.ok) {
const text = await res.text();
throw new Error(`Helix ${endpoint}: HTTP ${res.status} ${text.slice(0, 200)}`);
}
if (res.status === 204) return undefined as T;
return await res.json() as T;
}, { attempts: 4, onRetry: (err, n, ms) => log.warn(`Wiederhole ${endpoint} (${n}) in ${ms} ms`, { err: String(err) }) });
}
export const helix = {
async userByLogin(login: string): Promise<HelixUser | null> {
const r = await call<{ data: HelixUser[] }>('broadcaster', `/users?login=${encodeURIComponent(login)}`);
return r.data[0] ?? null;
},
async streamByUserId(userId: string): Promise<HelixStream | null> {
const r = await call<{ data: HelixStream[] }>('broadcaster', `/streams?user_id=${userId}`);
return r.data[0] ?? null;
},
async chatters(broadcasterId: string, moderatorId: string): Promise<string[]> {
const out: string[] = [];
let cursor = '';
do {
const q = `/chat/chatters?broadcaster_id=${broadcasterId}&moderator_id=${moderatorId}&first=1000` +
(cursor ? `&after=${cursor}` : '');
const r = await call<{ data: Array<{ user_id: string }>; pagination?: { cursor?: string } }>(
'broadcaster', q);
for (const c of r.data) out.push(c.user_id);
cursor = r.pagination?.cursor ?? '';
} while (cursor);
return out;
},
async createClip(broadcasterId: string): Promise<{ id: string; edit_url: string }> {
const r = await call<{ data: Array<{ id: string; edit_url: string }> }>(
'broadcaster', `/clips?broadcaster_id=${broadcasterId}`, { method: 'POST' });
const clip = r.data[0];
if (!clip) throw new Error('Twitch hat keinen Clip zurueckgegeben');
return clip;
},
};
-2
View File
@@ -1,2 +0,0 @@
// @abdulive/twitch — siehe docs/02-twitch-integration.md
export {};
+59
View File
@@ -0,0 +1,59 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseLine, toChatMessage } from './irc.ts';
const LINE =
'@badge-info=subscriber/8;badges=broadcaster/1,subscriber/6;color=#1E90FF;' +
'display-name=Nic_OOo;emotes=25:0-4/1902:6-10;first-msg=0;id=abc-123;mod=0;' +
'returning-chatter=0;subscriber=1;tmi-sent-ts=1757404800000;user-id=98765 ' +
':nic_ooo!nic_ooo@nic_ooo.tmi.twitch.tv PRIVMSG #abdulive_ :Kappa Keepo mehr Rost als Farbe';
test('zerlegt eine PRIVMSG mit Tags', () => {
const m = parseLine(LINE);
assert.ok(m);
assert.equal(m.command, 'PRIVMSG');
assert.equal(m.params[0], '#abdulive_');
assert.equal(m.params[1], 'Kappa Keepo mehr Rost als Farbe');
assert.equal(m.tags['user-id'], '98765');
assert.equal(m.tags['display-name'], 'Nic_OOo');
});
test('entschluesselt escapte Tag-Werte', () => {
const m = parseLine('@system-msg=Ein\\sTest\\szur\\sSache;id=x :tmi.twitch.tv USERNOTICE #k');
assert.equal(m?.tags['system-msg'], 'Ein Test zur Sache');
});
test('uebersetzt in eine ChatMessage', () => {
const msg = toChatMessage(parseLine(LINE)!);
assert.ok(msg);
assert.equal(msg.userId, '98765');
assert.equal(msg.login, 'nic_ooo');
assert.equal(msg.displayName, 'Nic_OOo');
assert.equal(msg.isBroadcaster, true);
assert.equal(msg.isSub, true);
assert.equal(msg.isFirst, false);
assert.equal(msg.isCommand, false);
assert.equal(msg.ts, new Date(1757404800000).toISOString());
// Emote-Namen werden aus den Positionsangaben zurueckgelesen
assert.deepEqual(msg.emotes.map((e) => e.name).sort(), ['Kappa', 'Keepo']);
});
test('erkennt Befehle und Erstchatter', () => {
const line =
'@first-msg=1;id=y;tmi-sent-ts=1757404800000;user-id=42;display-name=Neu ' +
':neu!neu@neu.tmi.twitch.tv PRIVMSG #abdulive_ :!clip';
const msg = toChatMessage(parseLine(line)!)!;
assert.equal(msg.isFirst, true);
assert.equal(msg.isCommand, true);
});
test('ignoriert Nachrichten ohne user-id', () => {
const line = ':tmi.twitch.tv PRIVMSG #abdulive_ :ohne Tags';
assert.equal(toChatMessage(parseLine(line)!), null);
});
test('PING wird als solches erkannt', () => {
const m = parseLine('PING :tmi.twitch.tv');
assert.equal(m?.command, 'PING');
assert.equal(m?.params[0], 'tmi.twitch.tv');
});
+202
View File
@@ -0,0 +1,202 @@
// Twitch-Chat ueber IRC (WebSocket). Warum IRC und nicht EventSub: die
// IRCv3-Tags enthalten first-msg, returning-chatter, msg-id, badges und
// Emote-Positionen - genau das, woran Community-Gedaechtnis und
// Spike-Erkennung haengen. Siehe ADR-0003.
//
// Ohne Zugangsdaten wird anonym verbunden (justinfan). Dann kann man mitlesen,
// aber nicht schreiben - reicht, um die Datenaufnahme zu pruefen, bevor die
// Twitch-Apps eingerichtet sind.
import { logger } from '#core/logger.ts';
import { forever } from '#core/retry.ts';
import type { ChatMessage } from '#shared/events.ts';
import { accessToken } from './oauth.ts';
import { readSecrets } from './secrets.ts';
const log = logger('irc');
const URL_WS = 'wss://irc-ws.chat.twitch.tv:443';
export type IrcMessage = { tags: Record<string, string>; prefix: string; command: string; params: string[] };
/** IRCv3-Zeile zerlegen: `@tags :prefix COMMAND params :trailing` */
export function parseLine(line: string): IrcMessage | null {
if (!line) return null;
let rest = line;
const tags: Record<string, string> = {};
if (rest.startsWith('@')) {
const sp = rest.indexOf(' ');
for (const pair of rest.slice(1, sp).split(';')) {
const eq = pair.indexOf('=');
const k = eq === -1 ? pair : pair.slice(0, eq);
const v = eq === -1 ? '' : pair.slice(eq + 1);
tags[k] = v
.replace(/\\s/g, ' ').replace(/\\n/g, '\n').replace(/\\r/g, '\r')
.replace(/\\:/g, ';').replace(/\\\\/g, '\\');
}
rest = rest.slice(sp + 1);
}
let prefix = '';
if (rest.startsWith(':')) {
const sp = rest.indexOf(' ');
prefix = rest.slice(1, sp);
rest = rest.slice(sp + 1);
}
const trailingAt = rest.indexOf(' :');
const head = trailingAt === -1 ? rest : rest.slice(0, trailingAt);
const parts = head.split(' ').filter(Boolean);
const command = parts.shift() ?? '';
if (trailingAt !== -1) parts.push(rest.slice(trailingAt + 2));
return { tags, prefix, command, params: parts };
}
function parseEmotes(tag: string | undefined, text: string): ChatMessage['emotes'] {
if (!tag) return [];
const out: ChatMessage['emotes'] = [];
const chars = [...text];
for (const part of tag.split('/')) {
const [id, ranges] = part.split(':');
if (!id || !ranges) continue;
const spans = ranges.split(',');
const first = spans[0]?.split('-');
const name = first && first[0] !== undefined && first[1] !== undefined
? chars.slice(Number(first[0]), Number(first[1]) + 1).join('')
: id;
out.push({ id, name, count: spans.length });
}
return out;
}
export function toChatMessage(m: IrcMessage): ChatMessage | null {
if (m.command !== 'PRIVMSG') return null;
const text = m.params[1] ?? '';
const login = m.prefix.split('!')[0] ?? '';
const userId = m.tags['user-id'];
if (!userId) return null;
const badges = m.tags['badges'] ?? '';
return {
id: m.tags['id'] ?? `${userId}-${Date.now()}`,
ts: new Date(Number(m.tags['tmi-sent-ts'] ?? Date.now())).toISOString(),
userId,
login,
displayName: m.tags['display-name'] || login,
text,
emotes: parseEmotes(m.tags['emotes'], text),
isFirst: m.tags['first-msg'] === '1',
isReturning: m.tags['returning-chatter'] === '1',
isCommand: text.startsWith('!'),
isMod: m.tags['mod'] === '1' || badges.includes('broadcaster'),
isSub: m.tags['subscriber'] === '1',
isBroadcaster: badges.includes('broadcaster'),
bits: Number(m.tags['bits'] ?? 0),
color: m.tags['color'] || null,
};
}
export type IrcHandlers = {
onMessage: (msg: ChatMessage) => void;
onNotice?: (text: string) => void;
onConnected?: (anonymous: boolean) => void;
};
export type IrcClient = {
/** Haelt die Verbindung dauerhaft; kehrt erst bei `signal.abort` zurueck. */
run: (signal: AbortSignal) => Promise<void>;
/** Sendet in den Chat. Anonym verbundene Clients koennen nicht senden. */
say: (text: string) => boolean;
isAnonymous: () => boolean;
};
export function createIrc(channel: string, handlers: IrcHandlers): IrcClient {
let send: ((text: string) => boolean) | null = null;
let anonymous = true;
return {
run: (signal) => forever(
async (sig) => {
const conn = await connectOnce(channel, handlers, sig, (fn, anon) => {
send = fn; anonymous = anon;
});
void conn;
},
{
signal,
onWait: (ms, n) =>
log.warn(`Chat getrennt, neuer Versuch in ${Math.round(ms / 1000)} s (${n}.)`),
}
),
say: (text) => (send ? send(text) : false),
isAnonymous: () => anonymous,
};
}
function connectOnce(
channel: string,
handlers: IrcHandlers,
signal: AbortSignal,
ready: (say: (text: string) => boolean, anonymous: boolean) => void
): Promise<void> {
return new Promise<void>((_resolve, reject) => {
const ws = new WebSocket(URL_WS);
let anonymous = true;
let joined = false;
let alive: ReturnType<typeof setInterval> | null = null;
const shutdown = (why: string) => {
if (alive) clearInterval(alive);
try { ws.close(); } catch { /* schon zu */ }
reject(new Error(why));
};
signal.addEventListener('abort', () => shutdown('abgebrochen'), { once: true });
ws.addEventListener('open', () => {
void (async () => {
ws.send('CAP REQ :twitch.tv/tags twitch.tv/commands');
const bot = readSecrets().tokens.bot;
if (bot) {
try {
ws.send(`PASS oauth:${await accessToken('bot')}`);
ws.send(`NICK ${bot.login}`);
anonymous = false;
} catch (err) {
log.warn(`Bot-Token nicht nutzbar, lese anonym mit: ${(err as Error).message}`);
}
}
if (anonymous) ws.send(`NICK justinfan${10_000 + Math.floor(Math.random() * 80_000)}`);
ws.send(`JOIN #${channel.toLowerCase()}`);
})();
});
ws.addEventListener('message', (ev) => {
for (const line of String(ev.data).split('\r\n')) {
const m = parseLine(line);
if (!m) continue;
if (m.command === 'PING') { ws.send(`PONG :${m.params[0] ?? 'tmi.twitch.tv'}`); continue; }
if (m.command === 'JOIN' && !joined) {
joined = true;
log.info(`Chat verbunden mit #${channel}${anonymous ? ' (anonym, nur lesend)' : ''}`);
ready((text) => {
if (anonymous || ws.readyState !== WebSocket.OPEN) return false;
ws.send(`PRIVMSG #${channel.toLowerCase()} :${text}`);
return true;
}, anonymous);
handlers.onConnected?.(anonymous);
// Twitch schliesst stille Verbindungen; alle 4 Minuten ein Lebenszeichen
alive = setInterval(() => { try { ws.send('PING :keepalive'); } catch { /* egal */ } }, 240_000);
continue;
}
if (m.command === 'NOTICE') { handlers.onNotice?.(m.params[1] ?? ''); continue; }
if (m.command === 'PRIVMSG') {
const msg = toChatMessage(m);
if (msg) handlers.onMessage(msg);
}
}
});
ws.addEventListener('error', () => shutdown('WebSocket-Fehler'));
ws.addEventListener('close', (ev) => shutdown(`Verbindung geschlossen (${ev.code})`));
});
}
+130
View File
@@ -0,0 +1,130 @@
// OAuth-Autorisierungscode-Flow gegen Twitch. Rueckruf laeuft auf denselben
// Server wie die Einrichtungsseite (Port 4792) - siehe ADR-0005.
import crypto from 'node:crypto';
import { logger } from '#core/logger.ts';
import { readSecrets, updateSecrets, type Role, type TokenSet } from './secrets.ts';
const log = logger('oauth');
const AUTH = 'https://id.twitch.tv/oauth2/authorize';
const TOKEN = 'https://id.twitch.tv/oauth2/token';
const VALIDATE = 'https://id.twitch.tv/oauth2/validate';
export const SCOPES: Record<Role, string[]> = {
broadcaster: [
'clips:edit',
'channel:manage:broadcast',
'channel:read:subscriptions',
'moderator:read:followers',
'moderator:read:chatters',
'channel:manage:raids',
'channel:read:redemptions',
'bits:read',
],
bot: ['chat:read', 'chat:edit'],
};
/** Kurzlebige, einmalig einloesbare `state`-Werte gegen CSRF. */
const pending = new Map<string, { role: Role; created: number }>();
export function redirectUri(port: number): string {
// Muss exakt so in der Twitch-App hinterlegt sein.
return `http://localhost:${port}/callback`;
}
export function authorizeUrl(role: Role, port: number): string {
const app = readSecrets().apps[role];
if (!app?.clientId) throw new Error(`Fuer "${role}" ist noch keine Client-ID hinterlegt.`);
const state = crypto.randomBytes(16).toString('hex');
pending.set(state, { role, created: Date.now() });
for (const [k, v] of pending) if (Date.now() - v.created > 600_000) pending.delete(k);
const u = new URL(AUTH);
u.searchParams.set('client_id', app.clientId);
u.searchParams.set('redirect_uri', redirectUri(port));
u.searchParams.set('response_type', 'code');
u.searchParams.set('scope', SCOPES[role].join(' '));
u.searchParams.set('state', state);
u.searchParams.set('force_verify', 'true');
return u.toString();
}
export async function handleCallback(code: string, state: string, port: number): Promise<Role> {
const entry = pending.get(state);
if (!entry) throw new Error('Unbekannter oder abgelaufener state - bitte erneut verbinden.');
pending.delete(state);
const { role } = entry;
const app = readSecrets().apps[role];
if (!app) throw new Error(`Fuer "${role}" fehlen die App-Daten.`);
const res = await fetch(TOKEN, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: app.clientId,
client_secret: app.clientSecret,
code,
grant_type: 'authorization_code',
redirect_uri: redirectUri(port),
}),
});
if (!res.ok) throw new Error(`Token-Tausch fehlgeschlagen: HTTP ${res.status} ${await res.text()}`);
const body = await res.json() as { access_token: string; refresh_token: string; expires_in: number };
const who = await validate(body.access_token);
const tokens: TokenSet = {
accessToken: body.access_token,
refreshToken: body.refresh_token,
expiresAt: new Date(Date.now() + body.expires_in * 1000).toISOString(),
scopes: who.scopes,
userId: who.user_id,
login: who.login,
};
updateSecrets((s) => { s.tokens[role] = tokens; });
log.info(`${role} verbunden als ${who.login} (${who.scopes.length} Scopes)`);
return role;
}
export async function validate(accessToken: string) {
const res = await fetch(VALIDATE, { headers: { Authorization: `OAuth ${accessToken}` } });
if (!res.ok) throw new Error(`Token ungueltig: HTTP ${res.status}`);
return await res.json() as { user_id: string; login: string; scopes: string[]; expires_in: number };
}
/** Liefert ein gueltiges Access-Token, erneuert bei Bedarf. */
export async function accessToken(role: Role): Promise<string> {
const s = readSecrets();
const t = s.tokens[role];
if (!t) throw new Error(`"${role}" ist nicht verbunden - Einrichtung unter /setup.`);
// Fuenf Minuten Puffer, damit kein Aufruf mitten im Ablauf landet
if (Date.parse(t.expiresAt) - Date.now() > 300_000) return t.accessToken;
const app = s.apps[role];
if (!app) throw new Error(`Fuer "${role}" fehlen die App-Daten.`);
const res = await fetch(TOKEN, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: app.clientId,
client_secret: app.clientSecret,
grant_type: 'refresh_token',
refresh_token: t.refreshToken,
}),
});
if (!res.ok) {
throw new Error(`Token-Erneuerung fuer "${role}" fehlgeschlagen (HTTP ${res.status}). ` +
'Neu verbinden unter /setup.');
}
const body = await res.json() as { access_token: string; refresh_token: string; expires_in: number };
const next: TokenSet = {
...t,
accessToken: body.access_token,
refreshToken: body.refresh_token || t.refreshToken,
expiresAt: new Date(Date.now() + body.expires_in * 1000).toISOString(),
};
updateSecrets((st) => { st.tokens[role] = next; });
log.info(`Token fuer ${role} erneuert`);
return next.accessToken;
}
+122
View File
@@ -0,0 +1,122 @@
// Verschluesselter Speicher fuer Zugangsdaten. Siehe ADR-0005.
//
// Bewusst NICHT in der SQLite-Datenbank: die wird per VACUUM INTO auf die
// Windows-Seite gesichert, wo sie in einer Cloud-Synchronisation landen kann.
//
// Der Schluessel liegt im selben Volume wie die Daten. Das schuetzt nicht
// gegen jemanden mit Zugriff auf das Volume, und tut auch nicht so. Es
// schuetzt gegen versehentliche Anzeige im Stream, gegen verirrte Kopien und
// gegen Grep-Unfaelle - und genau darum geht es hier.
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { paths } from '#core/config.ts';
import { logger } from '#core/logger.ts';
const log = logger('secrets');
const FILE = path.join(paths.db, 'secrets.json');
const KEYFILE = path.join(paths.db, '.secret-key');
export type Role = 'broadcaster' | 'bot';
export type TokenSet = {
accessToken: string;
refreshToken: string;
expiresAt: string; // ISO
scopes: string[];
userId: string;
login: string;
};
export type SecretStore = {
apps: Partial<Record<Role, { clientId: string; clientSecret: string }>>;
tokens: Partial<Record<Role, TokenSet>>;
obs?: { password: string };
discord?: { goLiveWebhook?: string; recapWebhook?: string };
bluesky?: { handle: string; appPassword: string };
};
const EMPTY: SecretStore = { apps: {}, tokens: {} };
function key(): Buffer {
fs.mkdirSync(paths.db, { recursive: true });
if (fs.existsSync(KEYFILE)) return Buffer.from(fs.readFileSync(KEYFILE, 'utf8').trim(), 'base64');
const k = crypto.randomBytes(32);
fs.writeFileSync(KEYFILE, k.toString('base64'), { mode: 0o600 });
log.info('Neuer Verschluesselungsschluessel erzeugt');
return k;
}
function encrypt(plain: string): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key(), iv);
const body = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return [iv.toString('base64'), cipher.getAuthTag().toString('base64'), body.toString('base64')]
.join('.');
}
function decrypt(blob: string): string {
const [ivB64, tagB64, bodyB64] = blob.split('.');
if (!ivB64 || !tagB64 || !bodyB64) throw new Error('secrets.json ist beschaedigt');
const decipher = crypto.createDecipheriv('aes-256-gcm', key(), Buffer.from(ivB64, 'base64'));
decipher.setAuthTag(Buffer.from(tagB64, 'base64'));
return Buffer.concat([decipher.update(Buffer.from(bodyB64, 'base64')), decipher.final()])
.toString('utf8');
}
let cache: SecretStore | null = null;
export function readSecrets(): SecretStore {
if (cache) return cache;
if (!fs.existsSync(FILE)) { cache = structuredClone(EMPTY); return cache; }
try {
cache = JSON.parse(decrypt(fs.readFileSync(FILE, 'utf8'))) as SecretStore;
} catch (err) {
log.error(`secrets.json nicht lesbar (${(err as Error).message}) - starte mit leerem Speicher`);
cache = structuredClone(EMPTY);
}
return cache;
}
export function writeSecrets(next: SecretStore): void {
fs.mkdirSync(paths.db, { recursive: true });
fs.writeFileSync(FILE, encrypt(JSON.stringify(next)), { mode: 0o600 });
cache = next;
}
export function updateSecrets(fn: (s: SecretStore) => void): SecretStore {
const s = structuredClone(readSecrets());
fn(s);
writeSecrets(s);
return s;
}
/** Zustand fuer die Einrichtungsseite - enthaelt nie einen Geheimwert. */
export type SecretStatus = {
apps: Record<Role, { clientId: string; hasSecret: boolean }>;
tokens: Record<Role, { connected: boolean; login?: string; expiresAt?: string; scopes?: number }>;
obs: boolean;
ready: boolean;
};
export function secretStatus(): SecretStatus {
const s = readSecrets();
const roles: Role[] = ['broadcaster', 'bot'];
const apps = {} as SecretStatus['apps'];
const tokens = {} as SecretStatus['tokens'];
for (const r of roles) {
// Die Client-ID ist kein Geheimnis und wird angezeigt, damit man sieht,
// welche App hinterlegt ist. Das Secret nie.
apps[r] = { clientId: s.apps[r]?.clientId ?? '', hasSecret: Boolean(s.apps[r]?.clientSecret) };
const t = s.tokens[r];
tokens[r] = t
? { connected: true, login: t.login, expiresAt: t.expiresAt, scopes: t.scopes.length }
: { connected: false };
}
return {
apps, tokens,
obs: Boolean(s.obs?.password),
ready: Boolean(s.apps.broadcaster?.clientId && s.tokens.broadcaster),
};
}
-5
View File
@@ -1,5 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
"include": ["src"]
}