Repository Public
1import crypto from "node:crypto";2import { env } from "./env";34// Provider credentials at rest: AES-256-GCM with a key derived from APP_SECRET. They are decrypted only inside the5// server, at the moment a provider is called or a stream address is resolved; they are never sent to the browser as6// data, never written to the journal, and never returned by the administration API.7const key = () => Buffer.from(crypto.hkdfSync("sha256", env.appSecret, "sp-tv", "provider-credentials", 32));89export function seal(plain: string): string {10 const iv = crypto.randomBytes(12); const c = crypto.createCipheriv("aes-256-gcm", key(), iv);11 const body = Buffer.concat([c.update(plain, "utf8"), c.final()]);12 return `v1.${iv.toString("base64url")}.${c.getAuthTag().toString("base64url")}.${body.toString("base64url")}`;13}14export function open(sealed: string | null | undefined): string | null {15 if (!sealed) return null;16 const [v, iv, tag, body] = sealed.split("."); if (v !== "v1" || !iv || !tag || !body) return null;17 try {18 const d = crypto.createDecipheriv("aes-256-gcm", key(), Buffer.from(iv, "base64url")); d.setAuthTag(Buffer.from(tag, "base64url"));19 return Buffer.concat([d.update(Buffer.from(body, "base64url")), d.final()]).toString("utf8");20 } catch { return null; }21}22/** Removes anything that looks like a credential from a message before it is logged or shown. */23export function redact(message: string, ...secrets: (string | null | undefined)[]): string {24 let out = message;25 for (const s of secrets) if (s && s.length >= 3) out = out.split(s).join("•••").split(encodeURIComponent(s)).join("•••");26 return out.replace(/(password|api_key|apikey|token)=[^&\s"']+/gi, "$1=•••");27}28