Harden renderer account IPC boundary

Move secret-bearing account and settings state behind main-process boundaries for Task 1B. Renderer snapshots now expose RendererSettings plus safe account metadata instead of full AppSettings, with provider tokens, passwords, API keys, archive passwords, and notification URLs excluded from renderer-bound state. Add write-only account create, replace, update-secret, and delete IPC commands, validate renderer settings updates against the safe shape, and keep account command results limited to safe settings, safe accounts, and stable account IDs.

Preserve existing account behavior while removing renderer secret access: blank replace secrets retain stored main-process secrets, Mega-Debrid API/Web pools stay mode-specific, Debrid-Link key metadata migrates by stable key ID, and delete/enable operations target stable account or provider identities. Remove obsolete renderer-side account status helpers from the old settings snapshot flow.

Add focused coverage for all supported renderer account kinds, secret-free UiSnapshot serialization, preload account command forwarding, malformed payload error sanitization, Mega-Debrid preferApi preservation, Debrid-Link key metadata migration, account edit safety, settings UI, debug server settings payloads, link export, and visual fixtures.
This commit is contained in:
Sucukdeluxe
2026-08-11 23:22:44 +02:00
parent 1cb381fa50
commit 26d62a9337
24 changed files with 2240 additions and 1700 deletions
+466
View File
@@ -0,0 +1,466 @@
import { getDebridLinkApiKeyId, parseDebridLinkApiKeys } from "../shared/debrid-link-keys";
import {
getMegaDebridAccountId,
getMegaDebridAccountsForMode,
getMegaDebridCredentialsForMode,
getMegaDebridDisabledAccountIdsForMode,
mergeMegaDebridCredentialPools,
parseMegaDebridAccounts,
serializeMegaDebridAccounts,
type MegaDebridAccountMode
} from "../shared/mega-debrid-accounts";
import type { AccountCommand, AccountCredentialCheckInput, AppSettings, DebridProvider, RendererAccountKind } from "../shared/types";
export interface AppliedAccountCommand {
settings: AppSettings;
response: { accountId: string | null };
}
const ACCOUNT_KINDS = new Set<RendererAccountKind>([
"realdebrid-api",
"realdebrid-web",
"megadebrid-api",
"megadebrid-web",
"bestdebrid-api",
"bestdebrid-web",
"alldebrid-api",
"alldebrid-web",
"ddownload-login",
"onefichier-api",
"debridlink-api",
"linksnappy-login"
]);
const ACTION_FIELDS: Record<AccountCommand["action"], ReadonlySet<string>> = {
create: new Set(["action", "kind", "identity", "secret", "dailyLimitBytes"]),
replace: new Set(["action", "kind", "accountId", "identity", "secret", "dailyLimitBytes"]),
"update-secret": new Set(["action", "kind", "accountId", "secret"]),
delete: new Set(["action", "kind", "accountId"])
};
function invalid(): never {
throw new Error("Account-Payload ist ungültig");
}
function optionalString(value: unknown, maxLength: number): string | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value !== "string" || value.length > maxLength) {
invalid();
}
return value;
}
function requiredString(value: unknown, maxLength: number): string {
const result = optionalString(value, maxLength);
if (result === undefined || !result.trim()) {
invalid();
}
return result;
}
function optionalLimit(value: unknown): number | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
invalid();
}
return value;
}
export function validateAccountCommand(value: unknown): AccountCommand {
if (!value || typeof value !== "object" || Array.isArray(value)) {
invalid();
}
const raw = value as Record<string, unknown>;
const action = raw.action;
if (action !== "create" && action !== "replace" && action !== "update-secret" && action !== "delete") {
invalid();
}
if (Object.keys(raw).some((key) => !ACTION_FIELDS[action].has(key))) {
invalid();
}
if (typeof raw.kind !== "string" || !ACCOUNT_KINDS.has(raw.kind as RendererAccountKind)) {
invalid();
}
const kind = raw.kind as RendererAccountKind;
if (action === "create") {
return {
action,
kind,
identity: optionalString(raw.identity, 512),
secret: optionalString(raw.secret, 100_000),
dailyLimitBytes: optionalLimit(raw.dailyLimitBytes)
};
}
const accountId = requiredString(raw.accountId, 256).trim();
if (action === "replace") {
return {
action,
kind,
accountId,
identity: optionalString(raw.identity, 512),
secret: optionalString(raw.secret, 100_000),
dailyLimitBytes: optionalLimit(raw.dailyLimitBytes)
};
}
if (action === "update-secret") {
return {
action,
kind,
accountId,
secret: requiredString(raw.secret, 100_000)
};
}
return { action, kind, accountId };
}
export function validateAccountCredentialCheckInput(value: unknown): AccountCredentialCheckInput {
if (!value || typeof value !== "object" || Array.isArray(value)) invalid();
const raw = value as Record<string, unknown>;
if (Object.keys(raw).some((key) => !new Set(["kind", "accountId", "identity", "secret"]).has(key))) invalid();
if (raw.kind !== "megadebrid-api" && raw.kind !== "megadebrid-web" && raw.kind !== "debridlink-api") invalid();
return {
kind: raw.kind,
accountId: optionalString(raw.accountId, 256),
identity: optionalString(raw.identity, 512),
secret: optionalString(raw.secret, 100_000)
};
}
function withoutKeys<T>(record: Record<string, T>, ...keys: string[]): Record<string, T> {
const removed = new Set(keys);
return Object.fromEntries(Object.entries(record).filter(([key]) => !removed.has(key)));
}
function migrateIdList(values: readonly string[], oldId: string, newId: string): string[] {
const retained = values.filter((value) => value !== oldId && value !== newId);
if (values.includes(oldId)) {
retained.push(newId);
}
return retained;
}
function setLimit(record: Record<string, number>, id: string, value: number | undefined): Record<string, number> {
const result = { ...record };
if (value === undefined) {
return result;
}
if (value > 0) {
result[id] = value;
} else {
delete result[id];
}
return result;
}
function migrateLimit(record: Record<string, number>, oldId: string, newId: string, value: number | undefined): Record<string, number> {
const result = withoutKeys(record, oldId, newId);
const resolved = value === undefined ? record[oldId] : value;
if (resolved && resolved > 0) {
result[newId] = resolved;
}
return result;
}
function validateIdentity(identity: string): string {
const trimmed = identity.trim();
if (!trimmed || /[:\r\n]/.test(trimmed)) {
invalid();
}
return trimmed;
}
function validateSecret(secret: string): string {
if (!secret.trim() || /[\r\n]/.test(secret)) {
invalid();
}
return secret;
}
function megaMode(kind: RendererAccountKind): MegaDebridAccountMode {
return kind === "megadebrid-web" ? "web" : "api";
}
function writeMegaPools(settings: AppSettings, apiCredentials: string, webCredentials: string): AppSettings {
const mergedCredentials = mergeMegaDebridCredentialPools(apiCredentials, webCredentials);
const first = parseMegaDebridAccounts(mergedCredentials)[0];
return {
...settings,
megaCredentials: mergedCredentials,
megaLogin: first?.login || "",
megaPassword: first?.password || "",
megaDebridApiCredentials: apiCredentials,
megaDebridWebCredentials: webCredentials,
megaDebridApiEnabled: settings.megaDebridApiEnabled && Boolean(apiCredentials),
megaDebridWebEnabled: settings.megaDebridWebEnabled && Boolean(webCredentials)
};
}
function createMega(settings: AppSettings, command: Extract<AccountCommand, { action: "create" }>): AppliedAccountCommand {
const mode = megaMode(command.kind);
const identity = validateIdentity(command.identity || "");
const secret = validateSecret(command.secret || "");
const accounts = getMegaDebridAccountsForMode(settings, mode);
if (accounts.some((account) => account.login.toLowerCase() === identity.toLowerCase())) {
invalid();
}
const selectedCredentials = serializeMegaDebridAccounts([...accounts, { login: identity, password: secret }]);
const apiCredentials = mode === "api" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "api");
const webCredentials = mode === "web" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "web");
const accountId = getMegaDebridAccountId(identity);
const next = writeMegaPools(settings, apiCredentials, webCredentials);
if (mode === "api") {
next.megaDebridApiEnabled = true;
} else {
next.megaDebridWebEnabled = true;
}
next.megaDebridAccountDailyLimitBytes = setLimit(settings.megaDebridAccountDailyLimitBytes, accountId, command.dailyLimitBytes);
return { settings: next, response: { accountId } };
}
function replaceMega(settings: AppSettings, command: Extract<AccountCommand, { action: "replace" }>): AppliedAccountCommand {
const mode = megaMode(command.kind);
const accounts = getMegaDebridAccountsForMode(settings, mode);
const index = accounts.findIndex((account) => account.id === command.accountId);
if (index < 0) {
invalid();
}
const current = accounts[index];
const identity = command.identity === undefined ? current.login : validateIdentity(command.identity);
const secret = command.secret?.trim() ? validateSecret(command.secret) : current.password;
if (accounts.some((account, accountIndex) => accountIndex !== index && account.login.toLowerCase() === identity.toLowerCase())) {
invalid();
}
const accountId = getMegaDebridAccountId(identity);
const selectedCredentials = serializeMegaDebridAccounts(accounts.map((account, accountIndex) => accountIndex === index
? { login: identity, password: secret }
: { login: account.login, password: account.password }));
const apiCredentials = mode === "api" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "api");
const webCredentials = mode === "web" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "web");
const next = writeMegaPools(settings, apiCredentials, webCredentials);
const selectedDisabled = migrateIdList(getMegaDebridDisabledAccountIdsForMode(settings, mode), command.accountId, accountId);
if (mode === "api") {
next.megaDebridApiDisabledAccountIds = selectedDisabled;
} else {
next.megaDebridWebDisabledAccountIds = selectedDisabled;
}
next.megaDebridDisabledAccountIds = [...new Set([...next.megaDebridApiDisabledAccountIds, ...next.megaDebridWebDisabledAccountIds])];
next.megaDebridAccountDailyLimitBytes = migrateLimit(settings.megaDebridAccountDailyLimitBytes, command.accountId, accountId, command.dailyLimitBytes);
if (command.accountId !== accountId) {
next.megaDebridAccountDailyUsageBytes = withoutKeys(settings.megaDebridAccountDailyUsageBytes, command.accountId, accountId);
next.megaDebridAccountTotalUsageBytes = withoutKeys(settings.megaDebridAccountTotalUsageBytes, command.accountId, accountId);
next.debridAccountStatuses = withoutKeys(settings.debridAccountStatuses, command.accountId, accountId);
}
return { settings: next, response: { accountId } };
}
function deleteMega(settings: AppSettings, command: Extract<AccountCommand, { action: "delete" }>): AppliedAccountCommand {
const mode = megaMode(command.kind);
const selected = getMegaDebridAccountsForMode(settings, mode);
if (!selected.some((account) => account.id === command.accountId)) {
invalid();
}
const selectedCredentials = serializeMegaDebridAccounts(selected.filter((account) => account.id !== command.accountId));
const apiCredentials = mode === "api" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "api");
const webCredentials = mode === "web" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "web");
const accountStillUsed = parseMegaDebridAccounts(mode === "api" ? webCredentials : apiCredentials).some((account) => account.id === command.accountId);
const next = writeMegaPools(settings, apiCredentials, webCredentials);
next.megaDebridApiDisabledAccountIds = mode === "api"
? settings.megaDebridApiDisabledAccountIds.filter((id) => id !== command.accountId)
: [...settings.megaDebridApiDisabledAccountIds];
next.megaDebridWebDisabledAccountIds = mode === "web"
? settings.megaDebridWebDisabledAccountIds.filter((id) => id !== command.accountId)
: [...settings.megaDebridWebDisabledAccountIds];
next.megaDebridDisabledAccountIds = [...new Set([...next.megaDebridApiDisabledAccountIds, ...next.megaDebridWebDisabledAccountIds])];
if (!accountStillUsed) {
next.megaDebridAccountDailyLimitBytes = withoutKeys(settings.megaDebridAccountDailyLimitBytes, command.accountId);
next.megaDebridAccountDailyUsageBytes = withoutKeys(settings.megaDebridAccountDailyUsageBytes, command.accountId);
next.megaDebridAccountTotalUsageBytes = withoutKeys(settings.megaDebridAccountTotalUsageBytes, command.accountId);
next.debridAccountStatuses = withoutKeys(settings.debridAccountStatuses, command.accountId);
}
const remaining = getMegaDebridAccountsForMode(next, mode)[0]?.id || null;
return { settings: next, response: { accountId: remaining } };
}
function createDebridLink(settings: AppSettings, command: Extract<AccountCommand, { action: "create" }>): AppliedAccountCommand {
const secret = validateSecret(command.secret || "");
if (/[,\r\n]/.test(secret)) {
invalid();
}
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys);
if (keys.some((key) => key.token === secret)) {
invalid();
}
const accountId = getDebridLinkApiKeyId(secret);
return {
settings: {
...settings,
debridLinkApiKeys: [...keys.map((key) => key.token), secret].join("\n"),
debridLinkApiKeyDailyLimitBytes: setLimit(settings.debridLinkApiKeyDailyLimitBytes, accountId, command.dailyLimitBytes)
},
response: { accountId }
};
}
function replaceDebridLink(settings: AppSettings, command: Extract<AccountCommand, { action: "replace" }>): AppliedAccountCommand {
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys);
const index = keys.findIndex((key) => key.id === command.accountId);
if (index < 0) {
invalid();
}
const secret = command.secret?.trim() ? validateSecret(command.secret) : keys[index].token;
if (/[,\r\n]/.test(secret) || keys.some((key, keyIndex) => keyIndex !== index && key.token === secret)) {
invalid();
}
const accountId = getDebridLinkApiKeyId(secret);
const tokens = keys.map((key, keyIndex) => keyIndex === index ? secret : key.token);
const idChanged = accountId !== command.accountId;
return {
settings: {
...settings,
debridLinkApiKeys: tokens.join("\n"),
debridLinkDisabledKeyIds: idChanged ? migrateIdList(settings.debridLinkDisabledKeyIds, command.accountId, accountId) : [...settings.debridLinkDisabledKeyIds],
debridLinkApiKeyDailyLimitBytes: migrateLimit(settings.debridLinkApiKeyDailyLimitBytes, command.accountId, accountId, command.dailyLimitBytes),
debridLinkApiKeyDailyUsageBytes: idChanged ? withoutKeys(settings.debridLinkApiKeyDailyUsageBytes, command.accountId, accountId) : { ...settings.debridLinkApiKeyDailyUsageBytes },
debridLinkApiKeyTotalUsageBytes: idChanged ? withoutKeys(settings.debridLinkApiKeyTotalUsageBytes, command.accountId, accountId) : { ...settings.debridLinkApiKeyTotalUsageBytes },
debridAccountStatuses: idChanged ? withoutKeys(settings.debridAccountStatuses, command.accountId, accountId) : { ...settings.debridAccountStatuses }
},
response: { accountId }
};
}
function deleteDebridLink(settings: AppSettings, command: Extract<AccountCommand, { action: "delete" }>): AppliedAccountCommand {
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys);
if (!keys.some((key) => key.id === command.accountId)) {
invalid();
}
const remaining = keys.filter((key) => key.id !== command.accountId);
return {
settings: {
...settings,
debridLinkApiKeys: remaining.map((key) => key.token).join("\n"),
debridLinkDisabledKeyIds: settings.debridLinkDisabledKeyIds.filter((id) => id !== command.accountId),
debridLinkApiKeyDailyLimitBytes: withoutKeys(settings.debridLinkApiKeyDailyLimitBytes, command.accountId),
debridLinkApiKeyDailyUsageBytes: withoutKeys(settings.debridLinkApiKeyDailyUsageBytes, command.accountId),
debridLinkApiKeyTotalUsageBytes: withoutKeys(settings.debridLinkApiKeyTotalUsageBytes, command.accountId),
debridAccountStatuses: withoutKeys(settings.debridAccountStatuses, command.accountId)
},
response: { accountId: remaining[0]?.id || null }
};
}
function singleProvider(kind: RendererAccountKind): DebridProvider {
if (kind.startsWith("realdebrid")) return "realdebrid";
if (kind.startsWith("bestdebrid")) return "bestdebrid";
if (kind.startsWith("alldebrid")) return "alldebrid";
if (kind === "ddownload-login") return "ddownload";
if (kind === "onefichier-api") return "onefichier";
if (kind === "linksnappy-login") return "linksnappy";
invalid();
}
function singleConfigured(settings: AppSettings, kind: RendererAccountKind): boolean {
if (kind === "realdebrid-api") return Boolean(settings.token.trim());
if (kind === "realdebrid-web") return settings.realDebridUseWebLogin;
if (kind === "bestdebrid-api") return Boolean(settings.bestToken.trim());
if (kind === "bestdebrid-web") return settings.bestDebridUseWebLogin;
if (kind === "alldebrid-api") return Boolean(settings.allDebridToken.trim());
if (kind === "alldebrid-web") return settings.allDebridUseWebLogin;
if (kind === "ddownload-login") return Boolean(settings.ddownloadLogin.trim() && settings.ddownloadPassword);
if (kind === "onefichier-api") return Boolean(settings.oneFichierApiKey.trim());
if (kind === "linksnappy-login") return Boolean(settings.linkSnappyLogin.trim() && settings.linkSnappyPassword);
return false;
}
function setSingle(settings: AppSettings, kind: RendererAccountKind, identity: string | undefined, secret: string | undefined): AppSettings {
if (kind === "realdebrid-api") return { ...settings, token: validateSecret(secret || ""), realDebridUseWebLogin: false };
if (kind === "realdebrid-web") return { ...settings, token: "", realDebridUseWebLogin: true };
if (kind === "bestdebrid-api") return { ...settings, bestToken: validateSecret(secret || ""), bestDebridUseWebLogin: false };
if (kind === "bestdebrid-web") return { ...settings, bestToken: "", bestDebridUseWebLogin: true };
if (kind === "alldebrid-api") return { ...settings, allDebridToken: validateSecret(secret || ""), allDebridUseWebLogin: false };
if (kind === "alldebrid-web") return { ...settings, allDebridToken: "", allDebridUseWebLogin: true };
if (kind === "ddownload-login") return { ...settings, ddownloadLogin: validateIdentity(identity || ""), ddownloadPassword: validateSecret(secret || "") };
if (kind === "onefichier-api") return { ...settings, oneFichierApiKey: validateSecret(secret || "") };
if (kind === "linksnappy-login") return { ...settings, linkSnappyLogin: validateIdentity(identity || ""), linkSnappyPassword: validateSecret(secret || "") };
invalid();
}
function replaceSingle(settings: AppSettings, command: Extract<AccountCommand, { action: "replace" }>): AppliedAccountCommand {
if (!singleConfigured(settings, command.kind) || command.accountId !== `svc-${singleProvider(command.kind)}`) {
invalid();
}
let identity = command.identity;
let secret = command.secret?.trim() ? command.secret : undefined;
if (command.kind === "realdebrid-api") secret ||= settings.token;
if (command.kind === "bestdebrid-api") secret ||= settings.bestToken;
if (command.kind === "alldebrid-api") secret ||= settings.allDebridToken;
if (command.kind === "ddownload-login") {
identity = identity?.trim() ? identity : settings.ddownloadLogin;
secret ||= settings.ddownloadPassword;
}
if (command.kind === "onefichier-api") secret ||= settings.oneFichierApiKey;
if (command.kind === "linksnappy-login") {
identity = identity?.trim() ? identity : settings.linkSnappyLogin;
secret ||= settings.linkSnappyPassword;
}
const provider = singleProvider(command.kind);
const next = setSingle(settings, command.kind, identity, secret);
next.providerDailyLimitBytes = setLimit(settings.providerDailyLimitBytes as Record<string, number>, provider, command.dailyLimitBytes);
return { settings: next, response: { accountId: command.accountId } };
}
function deleteSingle(settings: AppSettings, command: Extract<AccountCommand, { action: "delete" }>): AppliedAccountCommand {
const provider = singleProvider(command.kind);
if (!singleConfigured(settings, command.kind) || command.accountId !== `svc-${provider}`) {
invalid();
}
let next = { ...settings };
if (provider === "realdebrid") next = { ...next, token: "", realDebridUseWebLogin: false };
if (provider === "bestdebrid") next = { ...next, bestToken: "", bestDebridUseWebLogin: false };
if (provider === "alldebrid") next = { ...next, allDebridToken: "", allDebridUseWebLogin: false };
if (provider === "ddownload") next = { ...next, ddownloadLogin: "", ddownloadPassword: "" };
if (provider === "onefichier") next = { ...next, oneFichierApiKey: "" };
if (provider === "linksnappy") next = { ...next, linkSnappyLogin: "", linkSnappyPassword: "" };
next.providerDailyLimitBytes = withoutKeys(settings.providerDailyLimitBytes as Record<string, number>, provider);
next.providerDailyUsageBytes = withoutKeys(settings.providerDailyUsageBytes as Record<string, number>, provider);
next.providerTotalUsageBytes = withoutKeys(settings.providerTotalUsageBytes as Record<string, number>, provider);
return { settings: next, response: { accountId: null } };
}
function createSingle(settings: AppSettings, command: Extract<AccountCommand, { action: "create" }>): AppliedAccountCommand {
if (singleConfigured(settings, command.kind)) {
invalid();
}
const provider = singleProvider(command.kind);
const next = setSingle(settings, command.kind, command.identity, command.secret);
next.providerDailyLimitBytes = setLimit(settings.providerDailyLimitBytes as Record<string, number>, provider, command.dailyLimitBytes);
return { settings: next, response: { accountId: `svc-${provider}` } };
}
export function applyAccountCommand(settings: AppSettings, command: AccountCommand): AppliedAccountCommand {
if (command.action === "update-secret") {
const replace: Extract<AccountCommand, { action: "replace" }> = {
action: "replace",
kind: command.kind,
accountId: command.accountId,
secret: command.secret
};
return applyAccountCommand(settings, replace);
}
if (command.kind === "megadebrid-api" || command.kind === "megadebrid-web") {
if (command.action === "create") return createMega(settings, command);
if (command.action === "replace") return replaceMega(settings, command);
return deleteMega(settings, command);
}
if (command.kind === "debridlink-api") {
if (command.action === "create") return createDebridLink(settings, command);
if (command.action === "replace") return replaceDebridLink(settings, command);
return deleteDebridLink(settings, command);
}
if (command.action === "create") return createSingle(settings, command);
if (command.action === "replace") return replaceSingle(settings, command);
return deleteSingle(settings, command);
}
+60 -25
View File
@@ -6,6 +6,9 @@ import {
AddLinksPayload,
AllDebridHostInfo,
AppSettings,
AccountCommand,
AccountCommandResult,
AccountCredentialCheckInput,
DebridAccountStatus,
DebridProvider,
DuplicatePolicy,
@@ -27,8 +30,12 @@ import { importDlcContainers } from "./container";
import { APP_VERSION, ONLINE_BACKUP_API_URL } from "./constants";
import { DownloadManager } from "./download-manager";
import { fetchAllDebridHostInfo, fetchDebridLinkHostLimits } from "./debrid";
import { checkAllDebridAccounts, checkMegaDebridAccount } from "./account-check";
import { checkAllDebridAccounts, checkDebridLinkKey, checkMegaDebridAccount } from "./account-check";
import { parseMegaDebridAccounts } from "../shared/mega-debrid-accounts";
import { getMegaDebridAccountsForMode } from "../shared/mega-debrid-accounts";
import { parseDebridLinkApiKeys } from "../shared/debrid-link-keys";
import { applyAccountCommand } from "./account-commands";
import { createRendererState } from "./renderer-state";
import { parseCollectorInput } from "./link-parser";
import { configureLogger, getLogFilePath, logger } from "./logger";
import { AllDebridWebFallback } from "./all-debrid-web";
@@ -59,7 +66,6 @@ import { getTraceConfig, getTraceLogPath, initTraceLog, logTraceEvent, setTraceE
import type { DebugSetupCheckResult, SupportTraceConfig } from "../shared/types";
import { createOnlineBackup, downloadOnlineBackup, uploadOnlineBackup } from "./online-backup";
import { overlayLiveUsageCounters } from "./settings-live-overlay";
import { canPersistExpectedAccountStatus } from "./account-status-persistence";
function sanitizeSettingsPatch(partial: Partial<AppSettings>): Partial<AppSettings> {
const entries = Object.entries(partial || {}).filter(([, value]) => value !== undefined);
@@ -475,6 +481,50 @@ export class AppController {
return this.settings;
}
public async executeAccountCommand(command: AccountCommand): Promise<AccountCommandResult> {
const applied = applyAccountCommand(this.settings, command);
let checkedStatus: DebridAccountStatus | null = null;
if (command.action !== "delete" && applied.response.accountId && (command.kind === "megadebrid-api" || command.kind === "megadebrid-web")) {
const mode = command.kind === "megadebrid-web" ? "web" : "api";
const account = getMegaDebridAccountsForMode(applied.settings, mode).find((entry) => entry.id === applied.response.accountId);
if (!account) throw new Error("Account-Payload ist ungültig");
checkedStatus = await checkMegaDebridAccount(account);
}
if (command.action !== "delete" && applied.response.accountId && command.kind === "debridlink-api") {
const key = parseDebridLinkApiKeys(applied.settings.debridLinkApiKeys).find((entry) => entry.id === applied.response.accountId);
if (!key) throw new Error("Account-Payload ist ungültig");
checkedStatus = await checkDebridLinkKey(key);
}
if (checkedStatus && !checkedStatus.valid) {
const submittedSecret = "secret" in command ? command.secret : undefined;
const safeMessage = submittedSecret ? checkedStatus.message.split(submittedSecret).join("[geschützt]") : checkedStatus.message;
throw new Error(safeMessage || "Zugangsdaten ungültig");
}
this.updateSettings(applied.settings);
if (checkedStatus) this.manager.applyDebridAccountStatuses([checkedStatus]);
const state = createRendererState(this.settings);
this.audit("INFO", "Account aktualisiert", { action: command.action, kind: command.kind, accountId: applied.response.accountId });
return { ...applied.response, ...state };
}
public async checkAccountCredentials(input: AccountCredentialCheckInput): Promise<DebridAccountStatus> {
if (input.kind === "megadebrid-api" || input.kind === "megadebrid-web") {
const mode = input.kind === "megadebrid-web" ? "web" : "api";
const account = input.identity?.trim() && input.secret
? parseMegaDebridAccounts(`${input.identity.trim()}:${input.secret}`)[0]
: getMegaDebridAccountsForMode(this.settings, mode).find((entry) => entry.id === input.accountId);
if (!account) throw new Error("Account-Payload ist ungültig");
const status = await checkMegaDebridAccount(account);
return { ...status, message: input.secret ? status.message.split(input.secret).join("[geschützt]") : status.message };
}
const key = input.secret?.trim()
? parseDebridLinkApiKeys(input.secret)[0]
: parseDebridLinkApiKeys(this.settings.debridLinkApiKeys).find((entry) => entry.id === input.accountId);
if (!key) throw new Error("Account-Payload ist ungültig");
const status = await checkDebridLinkKey(key);
return { ...status, message: input.secret ? status.message.split(input.secret).join("[geschützt]") : status.message };
}
public resetProviderDailyUsage(provider: DebridProvider): AppSettings {
const liveSettings = this.manager.getSettings();
const nextSettings = normalizeSettings({
@@ -535,31 +585,16 @@ export class AppController {
return fetchDebridLinkHostLimits(this.settings.debridLinkApiKeys, host);
}
public async checkDebridAccounts(settingsOverride?: AppSettings, persistValidOverride = false, expectedAccountId?: string): Promise<DebridAccountStatus[]> {
const statuses = await checkAllDebridAccounts(settingsOverride ? normalizeSettings(settingsOverride) : this.settings);
if (!settingsOverride || (persistValidOverride && canPersistExpectedAccountStatus(statuses, expectedAccountId))) {
this.manager.applyDebridAccountStatuses(statuses);
}
if (!settingsOverride) {
this.audit("INFO", "Debrid-Accounts geprueft", {
total: statuses.length,
valid: statuses.filter((s) => s.valid).length,
premium: statuses.filter((s) => s.isPremium).length
});
}
public async checkDebridAccounts(): Promise<DebridAccountStatus[]> {
const statuses = await checkAllDebridAccounts(this.settings);
this.manager.applyDebridAccountStatuses(statuses);
this.audit("INFO", "Debrid-Accounts geprueft", {
total: statuses.length,
valid: statuses.filter((s) => s.valid).length,
premium: statuses.filter((s) => s.isPremium).length
});
return statuses;
}
public async checkSingleMegaDebridAccount(login: string, password: string): Promise<DebridAccountStatus | null> {
const entry = parseMegaDebridAccounts(`${login.trim()}:${password.trim()}`)[0];
if (!entry) {
return null;
}
const status = await checkMegaDebridAccount(entry);
this.manager.applyDebridAccountStatuses([status]);
this.audit("INFO", "Mega-Debrid-Account einzeln geprueft", { valid: status.valid, premium: status.isPremium });
return status;
}
public async checkUpdates(): Promise<UpdateCheckResult> {
const result = await checkGitHubUpdate(this.settings.updateRepo);
if (!result.error) {
+8 -19
View File
@@ -71,6 +71,7 @@ import { logDesktopRename, verifyRename, verifyRenameAsync, type RenameVerificat
import { StoragePaths, saveSession, saveSessionAsync, saveSettings, saveSettingsAsync } from "./storage";
import { compactErrorText, ensureDirPath, filenameFromUrl, formatEta, humanSize, looksLikeOpaqueFilename, nowMs, sanitizeFilename, sleep } from "./utils";
import { mergeKnownTotalBytes } from "./download-size";
import { createRendererState } from "./renderer-state";
type ActiveTask = {
itemId: string;
@@ -407,19 +408,6 @@ function cloneSession(session: SessionState): SessionState {
};
}
function cloneSettings(settings: AppSettings): AppSettings {
return {
...settings,
bandwidthSchedules: (settings.bandwidthSchedules || []).map((entry) => ({ ...entry })),
providerDailyLimitBytes: { ...(settings.providerDailyLimitBytes || {}) },
providerDailyUsageBytes: { ...(settings.providerDailyUsageBytes || {}) },
providerTotalUsageBytes: { ...(settings.providerTotalUsageBytes || {}) },
debridLinkApiKeyDailyLimitBytes: { ...(settings.debridLinkApiKeyDailyLimitBytes || {}) },
debridLinkApiKeyDailyUsageBytes: { ...(settings.debridLinkApiKeyDailyUsageBytes || {}) },
debridLinkApiKeyTotalUsageBytes: { ...(settings.debridLinkApiKeyTotalUsageBytes || {}) }
};
}
type ParsedContentRange = {
start: number;
end: number;
@@ -1782,7 +1770,7 @@ export class DownloadManager extends EventEmitter {
private statsCacheAt = 0;
private settingsSnapshotCache: AppSettings | null = null;
private settingsSnapshotCache: ReturnType<typeof createRendererState> | null = null;
private settingsSnapshotCacheAt = 0;
private invalidateSettingsSnapshotCache(): void {
this.settingsSnapshotCache = null;
@@ -2490,12 +2478,12 @@ export class DownloadManager extends EventEmitter {
const reconnectMs = Math.max(0, this.session.reconnectUntil - now);
const snapshotSession = cloneSession(this.session);
let snapshotSettings: AppSettings;
let rendererState: ReturnType<typeof createRendererState>;
if (this.settingsSnapshotCache && now - this.settingsSnapshotCacheAt < 400) {
snapshotSettings = this.settingsSnapshotCache;
rendererState = this.settingsSnapshotCache;
} else {
snapshotSettings = cloneSettings(this.settings);
this.settingsSnapshotCache = snapshotSettings;
rendererState = createRendererState(this.settings);
this.settingsSnapshotCache = rendererState;
this.settingsSnapshotCacheAt = now;
}
const snapshotSummary = this.summary
@@ -2504,7 +2492,8 @@ export class DownloadManager extends EventEmitter {
return {
rotationEvents: getRecentRotationEvents(40),
settings: snapshotSettings,
settings: rendererState.settings,
accounts: rendererState.accounts,
session: snapshotSession,
summary: snapshotSummary,
stats: this.getStats(now),
+37 -10
View File
@@ -1,7 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { app, BrowserWindow, clipboard, dialog, ipcMain, IpcMainInvokeEvent, Menu, safeStorage, shell, Tray } from "electron";
import { AddLinksPayload, AppSettings, DebridProvider, EnableRemoteDiagnosticsInput, UpdateInstallProgress } from "../shared/types";
import { AddLinksPayload, AppSettings, DebridProvider, EnableRemoteDiagnosticsInput, RendererSettingsUpdate, UpdateInstallProgress } from "../shared/types";
import { AppController } from "./app-controller";
import { IPC_CHANNELS } from "../shared/ipc";
import { getLogFilePath, logger } from "./logger";
@@ -15,6 +15,9 @@ import { DEV_SERVER_URL } from "./dev-server-url";
import { resolveAppIconPath } from "./app-icon";
import { configureCredentialProtector } from "./credential-protection";
import { isMdd2Backup } from "./backup-crypto";
import { validateAccountCommand, validateAccountCredentialCheckInput } from "./account-commands";
import { createRendererSettings } from "./renderer-state";
import { validateRendererSettingsUpdate } from "./renderer-settings";
function validateString(value: unknown, name: string): string {
if (typeof value !== "string") {
@@ -358,27 +361,51 @@ function registerIpcHandlers(): void {
return false;
}
});
ipcMain.handle(IPC_CHANNELS.UPDATE_SETTINGS, (_event: IpcMainInvokeEvent, partial: Partial<AppSettings>) => {
const validated = validatePlainObject(partial ?? {}, "partial");
ipcMain.handle(IPC_CHANNELS.UPDATE_SETTINGS, (_event: IpcMainInvokeEvent, partial: RendererSettingsUpdate) => {
const validated = validateRendererSettingsUpdate(partial ?? {}, controller.getSettings());
const result = controller.updateSettings(validated as Partial<AppSettings>);
updateClipboardWatcher();
updateTray();
armScheduledStart(result.scheduledStartEpochMs || 0, { startOnPast: true });
return result;
return createRendererSettings(result);
});
ipcMain.handle(IPC_CHANNELS.RESET_PROVIDER_DAILY_USAGE, (_event: IpcMainInvokeEvent, provider: string) => {
const validatedProvider = validateString(provider, "provider") as DebridProvider;
if (!RESETTABLE_PROVIDER_KEYS.has(validatedProvider)) {
throw new Error("provider ist ungültig");
}
return controller.resetProviderDailyUsage(validatedProvider);
return createRendererSettings(controller.resetProviderDailyUsage(validatedProvider));
});
ipcMain.handle(IPC_CHANNELS.RESET_DEBRID_LINK_API_KEY_DAILY_USAGE, (_event: IpcMainInvokeEvent, keyId: string) => {
const validatedKeyId = validateString(keyId, "keyId").trim();
if (!validatedKeyId) {
throw new Error("keyId ist ungültig");
}
return controller.resetDebridLinkApiKeyDailyUsage(validatedKeyId);
return createRendererSettings(controller.resetDebridLinkApiKeyDailyUsage(validatedKeyId));
});
ipcMain.handle(IPC_CHANNELS.CREATE_ACCOUNT, (_event: IpcMainInvokeEvent, rawCommand: unknown) => {
const command = validateAccountCommand(rawCommand);
if (command.action !== "create") throw new Error("Account-Payload ist ungültig");
return controller.executeAccountCommand(command);
});
ipcMain.handle(IPC_CHANNELS.REPLACE_ACCOUNT, (_event: IpcMainInvokeEvent, rawCommand: unknown) => {
const command = validateAccountCommand(rawCommand);
if (command.action !== "replace") throw new Error("Account-Payload ist ungültig");
return controller.executeAccountCommand(command);
});
ipcMain.handle(IPC_CHANNELS.UPDATE_ACCOUNT_SECRET, (_event: IpcMainInvokeEvent, rawCommand: unknown) => {
const command = validateAccountCommand(rawCommand);
if (command.action !== "update-secret") throw new Error("Account-Payload ist ungültig");
return controller.executeAccountCommand(command);
});
ipcMain.handle(IPC_CHANNELS.DELETE_ACCOUNT, (_event: IpcMainInvokeEvent, rawCommand: unknown) => {
const command = validateAccountCommand(rawCommand);
if (command.action !== "delete") throw new Error("Account-Payload ist ungültig");
return controller.executeAccountCommand(command);
});
ipcMain.handle(IPC_CHANNELS.ADD_LINKS, (_event: IpcMainInvokeEvent, payload: AddLinksPayload) => {
validatePlainObject(payload ?? {}, "payload");
@@ -761,12 +788,12 @@ function registerIpcHandlers(): void {
return controller.getDebridLinkHostLimits();
});
ipcMain.handle(IPC_CHANNELS.CHECK_DEBRID_ACCOUNTS, async (_event, settings?: AppSettings, persistValidOverride = false, expectedAccountId?: string) => {
return controller.checkDebridAccounts(settings, persistValidOverride === true, expectedAccountId);
ipcMain.handle(IPC_CHANNELS.CHECK_DEBRID_ACCOUNTS, async () => {
return controller.checkDebridAccounts();
});
ipcMain.handle(IPC_CHANNELS.CHECK_MEGA_DEBRID_ACCOUNT, async (_event, login: string, password: string) => {
return controller.checkSingleMegaDebridAccount(String(login || ""), String(password || ""));
ipcMain.handle(IPC_CHANNELS.CHECK_ACCOUNT_CREDENTIALS, async (_event, rawInput: unknown) => {
return controller.checkAccountCredentials(validateAccountCredentialCheckInput(rawInput));
});
ipcMain.handle(IPC_CHANNELS.SELECT_BACKUP_IMPORT, async () => {
+83
View File
@@ -0,0 +1,83 @@
import type { AppSettings, RendererSettingsUpdate } from "../shared/types";
import { createRendererSettings } from "./renderer-state";
const DERIVED_KEYS = new Set(["archivePasswordListConfigured", "notifyUrlConfigured", "configuredProviders"]);
const WRITE_ONLY_KEYS = new Set(["archivePasswordList", "notifyUrl"]);
const MAX_SETTINGS_PAYLOAD_BYTES = 1_000_000;
function invalid(): never {
throw new Error("Settings-Payload ist ungültig");
}
function validateJsonValue(value: unknown, depth = 0): void {
if (depth > 8) {
invalid();
}
if (value === null || typeof value === "string" || typeof value === "boolean") {
return;
}
if (typeof value === "number") {
if (!Number.isFinite(value)) invalid();
return;
}
if (Array.isArray(value)) {
if (value.length > 10_000) invalid();
value.forEach((entry) => validateJsonValue(entry, depth + 1));
return;
}
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
invalid();
}
const entries = Object.entries(value as Record<string, unknown>);
if (entries.length > 10_000) invalid();
entries.forEach(([, entry]) => validateJsonValue(entry, depth + 1));
}
function validateTopLevelType(value: unknown, expected: unknown): void {
if (Array.isArray(expected)) {
if (!Array.isArray(value)) invalid();
return;
}
if (expected && typeof expected === "object") {
if (!value || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) invalid();
return;
}
if (typeof value !== typeof expected) {
invalid();
}
}
export function validateRendererSettingsUpdate(value: unknown, current: AppSettings): RendererSettingsUpdate {
if (!value || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype) {
invalid();
}
let serialized = "";
try {
serialized = JSON.stringify(value);
} catch {
invalid();
}
if (Buffer.byteLength(serialized, "utf8") > MAX_SETTINGS_PAYLOAD_BYTES) {
invalid();
}
const safe = createRendererSettings(current) as unknown as Record<string, unknown>;
const input = value as Record<string, unknown>;
const output: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(input)) {
if (DERIVED_KEYS.has(key)) {
continue;
}
if (WRITE_ONLY_KEYS.has(key)) {
if (typeof entry !== "string" || entry.length > 100_000) invalid();
output[key] = entry;
continue;
}
if (!(key in safe)) {
invalid();
}
validateTopLevelType(entry, safe[key]);
validateJsonValue(entry);
output[key] = entry;
}
return output as RendererSettingsUpdate;
}
+264
View File
@@ -0,0 +1,264 @@
import { parseDebridLinkApiKeys } from "../shared/debrid-link-keys";
import { getMegaDebridAccountsForMode, getMegaDebridDisabledAccountIdsForMode, parseMegaDebridAccounts } from "../shared/mega-debrid-accounts";
import type { AppSettings, DebridAccountStatus, DebridProvider, RendererAccount, RendererAccountKind, RendererSettings } from "../shared/types";
function maskValue(value: string, keepStart = 3, keepEnd = 3): string {
const trimmed = value.trim();
if (!trimmed) {
return "";
}
if (trimmed.length <= keepStart + keepEnd) {
return "*".repeat(trimmed.length);
}
return `${trimmed.slice(0, keepStart)}${"*".repeat(Math.max(4, trimmed.length - keepStart - keepEnd))}${trimmed.slice(-keepEnd)}`;
}
function getSecrets(settings: AppSettings): string[] {
const megaSecrets = [settings.megaCredentials, settings.megaDebridApiCredentials, settings.megaDebridWebCredentials]
.flatMap((credentials) => parseMegaDebridAccounts(credentials, settings.megaPassword))
.map((account) => account.password);
const debridLinkSecrets = parseDebridLinkApiKeys(settings.debridLinkApiKeys).map((key) => key.token);
return [...new Set([
settings.token,
settings.megaPassword,
settings.megaCredentials,
settings.megaDebridApiCredentials,
settings.megaDebridWebCredentials,
...megaSecrets,
settings.bestToken,
settings.allDebridToken,
settings.ddownloadPassword,
settings.oneFichierApiKey,
settings.debridLinkApiKeys,
...debridLinkSecrets,
settings.linkSnappyPassword,
settings.archivePasswordList,
settings.notifyUrl
].map((value) => value.trim()).filter(Boolean))].sort((left, right) => right.length - left.length);
}
function redact(value: string, secrets: readonly string[]): string {
return secrets.reduce((result, secret) => result.split(secret).join("[geschützt]"), value);
}
function safeStatus(status: DebridAccountStatus | undefined, secrets: readonly string[]): DebridAccountStatus | null {
if (!status) {
return null;
}
return {
...status,
label: redact(status.label, secrets),
maskedLogin: redact(status.maskedLogin, secrets),
email: status.email ? redact(status.email, secrets) : undefined,
message: redact(status.message, secrets)
};
}
function providerEnabled(settings: AppSettings, provider: DebridProvider): boolean {
return !settings.disabledProviders.includes(provider);
}
function singleAccount(
settings: AppSettings,
kind: RendererAccountKind,
provider: DebridProvider,
identity: string,
maskedIdentity: string,
hasSecret: boolean
): RendererAccount {
return {
accountId: `svc-${provider}`,
kind,
provider,
identity,
maskedIdentity,
hasSecret,
enabled: providerEnabled(settings, provider),
dailyLimitBytes: settings.providerDailyLimitBytes[provider] || 0,
dailyUsageBytes: settings.providerDailyUsageBytes[provider] || 0,
totalUsageBytes: settings.providerTotalUsageBytes[provider] || 0,
status: null
};
}
export function createRendererAccounts(settings: AppSettings): RendererAccount[] {
const accounts: RendererAccount[] = [];
const secrets = getSecrets(settings);
if (settings.realDebridUseWebLogin || settings.token.trim()) {
accounts.push(singleAccount(
settings,
settings.realDebridUseWebLogin ? "realdebrid-web" : "realdebrid-api",
"realdebrid",
"",
settings.realDebridUseWebLogin ? "Browser-Login" : maskValue(settings.token),
true
));
}
for (const mode of ["api", "web"] as const) {
const kind: RendererAccountKind = mode === "api" ? "megadebrid-api" : "megadebrid-web";
const provider: DebridProvider = kind;
const modeEnabled = mode === "api" ? settings.megaDebridApiEnabled : settings.megaDebridWebEnabled;
const disabledIds = new Set(getMegaDebridDisabledAccountIdsForMode(settings, mode));
for (const account of getMegaDebridAccountsForMode(settings, mode)) {
accounts.push({
accountId: account.id,
kind,
provider,
identity: account.login,
maskedIdentity: account.maskedLogin,
hasSecret: Boolean(account.password),
enabled: modeEnabled && providerEnabled(settings, provider) && !disabledIds.has(account.id),
dailyLimitBytes: settings.megaDebridAccountDailyLimitBytes[account.id] || 0,
dailyUsageBytes: settings.megaDebridAccountDailyUsageBytes[account.id] || 0,
totalUsageBytes: settings.megaDebridAccountTotalUsageBytes[account.id] || 0,
status: safeStatus(settings.debridAccountStatuses[account.id], secrets)
});
}
}
if (settings.bestDebridUseWebLogin || settings.bestToken.trim()) {
accounts.push(singleAccount(
settings,
settings.bestDebridUseWebLogin ? "bestdebrid-web" : "bestdebrid-api",
"bestdebrid",
"",
settings.bestDebridUseWebLogin ? "Cookie-Import" : maskValue(settings.bestToken),
true
));
}
if (settings.allDebridUseWebLogin || settings.allDebridToken.trim()) {
accounts.push(singleAccount(
settings,
settings.allDebridUseWebLogin ? "alldebrid-web" : "alldebrid-api",
"alldebrid",
"",
settings.allDebridUseWebLogin ? "Browser-Login" : maskValue(settings.allDebridToken),
true
));
}
if (settings.ddownloadLogin.trim() && settings.ddownloadPassword) {
accounts.push(singleAccount(settings, "ddownload-login", "ddownload", settings.ddownloadLogin.trim(), maskValue(settings.ddownloadLogin, 2, 4), true));
}
if (settings.oneFichierApiKey.trim()) {
accounts.push(singleAccount(settings, "onefichier-api", "onefichier", "", maskValue(settings.oneFichierApiKey), true));
}
for (const key of parseDebridLinkApiKeys(settings.debridLinkApiKeys)) {
accounts.push({
accountId: key.id,
kind: "debridlink-api",
provider: "debridlink",
identity: "",
maskedIdentity: key.masked,
hasSecret: true,
enabled: providerEnabled(settings, "debridlink") && !settings.debridLinkDisabledKeyIds.includes(key.id),
dailyLimitBytes: settings.debridLinkApiKeyDailyLimitBytes[key.id] || 0,
dailyUsageBytes: settings.debridLinkApiKeyDailyUsageBytes[key.id] || 0,
totalUsageBytes: settings.debridLinkApiKeyTotalUsageBytes[key.id] || 0,
status: safeStatus(settings.debridAccountStatuses[key.id], secrets)
});
}
if (settings.linkSnappyLogin.trim() && settings.linkSnappyPassword) {
accounts.push(singleAccount(settings, "linksnappy-login", "linksnappy", settings.linkSnappyLogin.trim(), maskValue(settings.linkSnappyLogin, 2, 4), true));
}
return accounts;
}
export function createRendererSettings(settings: AppSettings): RendererSettings {
const configuredProviders = [...new Set(createRendererAccounts(settings).map((account) => account.provider))];
return {
language: settings.language,
realDebridUseWebLogin: settings.realDebridUseWebLogin,
megaDebridApiEnabled: settings.megaDebridApiEnabled,
megaDebridWebEnabled: settings.megaDebridWebEnabled,
megaDebridPreferApi: settings.megaDebridPreferApi,
bestDebridUseWebLogin: settings.bestDebridUseWebLogin,
allDebridUseWebLogin: settings.allDebridUseWebLogin,
debridLinkDisabledKeyIds: [...settings.debridLinkDisabledKeyIds],
rememberToken: settings.rememberToken,
configuredProviders,
providerOrder: [...settings.providerOrder],
providerPrimary: settings.providerPrimary,
providerSecondary: settings.providerSecondary,
providerTertiary: settings.providerTertiary,
autoProviderFallback: settings.autoProviderFallback,
outputDir: settings.outputDir,
packageName: settings.packageName,
autoExtract: settings.autoExtract,
autoRename4sf4sj: settings.autoRename4sf4sj,
keepGermanAudioOnly: settings.keepGermanAudioOnly,
germanAudioMode: settings.germanAudioMode,
extractDir: settings.extractDir,
collectMkvToLibrary: settings.collectMkvToLibrary,
mkvLibraryDir: settings.mkvLibraryDir,
createExtractSubfolder: settings.createExtractSubfolder,
hybridExtract: settings.hybridExtract,
cleanupMode: settings.cleanupMode,
extractConflictMode: settings.extractConflictMode,
removeLinkFilesAfterExtract: settings.removeLinkFilesAfterExtract,
removeSamplesAfterExtract: settings.removeSamplesAfterExtract,
enableIntegrityCheck: settings.enableIntegrityCheck,
autoResumeOnStart: settings.autoResumeOnStart,
autoReconnect: settings.autoReconnect,
reconnectWaitSeconds: settings.reconnectWaitSeconds,
completedCleanupPolicy: settings.completedCleanupPolicy,
maxParallel: settings.maxParallel,
maxParallelExtract: settings.maxParallelExtract,
retryLimit: settings.retryLimit,
speedLimitEnabled: settings.speedLimitEnabled,
speedLimitKbps: settings.speedLimitKbps,
speedLimitMode: settings.speedLimitMode,
updateRepo: settings.updateRepo,
autoUpdateCheck: settings.autoUpdateCheck,
clipboardWatch: settings.clipboardWatch,
minimizeToTray: settings.minimizeToTray,
theme: settings.theme,
collapseNewPackages: settings.collapseNewPackages,
historyRetentionMode: settings.historyRetentionMode,
historyMaxEntries: settings.historyMaxEntries,
historyMaxAgeDays: settings.historyMaxAgeDays,
accountListShowDetailedDebridLinkKeys: settings.accountListShowDetailedDebridLinkKeys,
autoSortPackagesByProgress: settings.autoSortPackagesByProgress,
autoSkipExtracted: settings.autoSkipExtracted,
hideExtractedItems: settings.hideExtractedItems,
confirmDeleteSelection: settings.confirmDeleteSelection,
backupIncludeDownloads: settings.backupIncludeDownloads,
backupIncludeRemoteDiagnostics: settings.backupIncludeRemoteDiagnostics,
archivePasswordListConfigured: Boolean(settings.archivePasswordList.trim()),
notifyUrlConfigured: Boolean(settings.notifyUrl.trim()),
notifyMention: settings.notifyMention,
notifyOnPackageCompleted: settings.notifyOnPackageCompleted,
notifyOnPackageFailed: settings.notifyOnPackageFailed,
notifyOnRunFinished: settings.notifyOnRunFinished,
totalDownloadedAllTime: settings.totalDownloadedAllTime,
totalCompletedFilesAllTime: settings.totalCompletedFilesAllTime,
totalRuntimeAllTimeMs: settings.totalRuntimeAllTimeMs,
bandwidthSchedules: settings.bandwidthSchedules.map((entry) => ({ ...entry })),
columnOrder: [...settings.columnOrder],
columnOrderVersion: settings.columnOrderVersion,
extractCpuPriority: settings.extractCpuPriority,
autoExtractWhenStopped: settings.autoExtractWhenStopped,
disabledProviders: [...settings.disabledProviders],
hosterRouting: { ...settings.hosterRouting },
providerDailyLimitBytes: { ...settings.providerDailyLimitBytes },
providerDailyUsageBytes: { ...settings.providerDailyUsageBytes },
providerTotalUsageBytes: { ...settings.providerTotalUsageBytes },
debridLinkApiKeyDailyLimitBytes: { ...settings.debridLinkApiKeyDailyLimitBytes },
debridLinkApiKeyDailyUsageBytes: { ...settings.debridLinkApiKeyDailyUsageBytes },
debridLinkApiKeyTotalUsageBytes: { ...settings.debridLinkApiKeyTotalUsageBytes },
megaDebridDisabledAccountIds: [...settings.megaDebridDisabledAccountIds],
megaDebridApiDisabledAccountIds: [...settings.megaDebridApiDisabledAccountIds],
megaDebridWebDisabledAccountIds: [...settings.megaDebridWebDisabledAccountIds],
megaDebridAccountDailyLimitBytes: { ...settings.megaDebridAccountDailyLimitBytes },
megaDebridAccountDailyUsageBytes: { ...settings.megaDebridAccountDailyUsageBytes },
megaDebridAccountTotalUsageBytes: { ...settings.megaDebridAccountTotalUsageBytes },
debridAccountStatuses: Object.fromEntries(Object.entries(settings.debridAccountStatuses).map(([id, status]) => [id, safeStatus(status, getSecrets(settings))])),
providerDailyUsageDay: settings.providerDailyUsageDay,
scheduledStartEpochMs: settings.scheduledStartEpochMs
} as RendererSettings;
}
export function createRendererState(settings: AppSettings): { settings: RendererSettings; accounts: RendererAccount[] } {
return {
settings: createRendererSettings(settings),
accounts: createRendererAccounts(settings)
};
}
+17 -6
View File
@@ -1,8 +1,13 @@
import { contextBridge, ipcRenderer } from "electron";
import {
AddLinksPayload,
AccountCommandResult,
AccountCredentialCheckInput,
AccountCreateCommand,
AccountDeleteCommand,
AccountReplaceCommand,
AccountUpdateSecretCommand,
AllDebridHostInfo,
AppSettings,
DebridAccountStatus,
DebridLinkHostLimitInfo,
DebridProvider,
@@ -12,6 +17,8 @@ import {
HistoryRevealResult,
PackagePriority,
RemoteDiagnosticsInfo,
RendererSettings,
RendererSettingsUpdate,
RendererErrorReport,
SessionStats,
StartConflictEntry,
@@ -29,9 +36,13 @@ const api: ElectronApi = {
checkUpdates: (): Promise<UpdateCheckResult> => ipcRenderer.invoke(IPC_CHANNELS.CHECK_UPDATES),
installUpdate: () => ipcRenderer.invoke(IPC_CHANNELS.INSTALL_UPDATE),
openExternal: (url: string): Promise<boolean> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_EXTERNAL, url),
updateSettings: (settings: Partial<AppSettings>): Promise<AppSettings> => ipcRenderer.invoke(IPC_CHANNELS.UPDATE_SETTINGS, settings),
resetProviderDailyUsage: (provider: DebridProvider): Promise<AppSettings> => ipcRenderer.invoke(IPC_CHANNELS.RESET_PROVIDER_DAILY_USAGE, provider),
resetDebridLinkApiKeyDailyUsage: (keyId: string): Promise<AppSettings> => ipcRenderer.invoke(IPC_CHANNELS.RESET_DEBRID_LINK_API_KEY_DAILY_USAGE, keyId),
updateSettings: (settings: RendererSettingsUpdate): Promise<RendererSettings> => ipcRenderer.invoke(IPC_CHANNELS.UPDATE_SETTINGS, settings),
resetProviderDailyUsage: (provider: DebridProvider): Promise<RendererSettings> => ipcRenderer.invoke(IPC_CHANNELS.RESET_PROVIDER_DAILY_USAGE, provider),
resetDebridLinkApiKeyDailyUsage: (keyId: string): Promise<RendererSettings> => ipcRenderer.invoke(IPC_CHANNELS.RESET_DEBRID_LINK_API_KEY_DAILY_USAGE, keyId),
createAccount: (command: AccountCreateCommand): Promise<AccountCommandResult> => ipcRenderer.invoke(IPC_CHANNELS.CREATE_ACCOUNT, command),
replaceAccount: (command: AccountReplaceCommand): Promise<AccountCommandResult> => ipcRenderer.invoke(IPC_CHANNELS.REPLACE_ACCOUNT, command),
updateAccountSecret: (command: AccountUpdateSecretCommand): Promise<AccountCommandResult> => ipcRenderer.invoke(IPC_CHANNELS.UPDATE_ACCOUNT_SECRET, command),
deleteAccount: (command: AccountDeleteCommand): Promise<AccountCommandResult> => ipcRenderer.invoke(IPC_CHANNELS.DELETE_ACCOUNT, command),
addLinks: (payload: AddLinksPayload): Promise<{ addedPackages: number; addedLinks: number; invalidCount: number }> =>
ipcRenderer.invoke(IPC_CHANNELS.ADD_LINKS, payload),
addContainers: (filePaths: string[]): Promise<{ addedPackages: number; addedLinks: number }> =>
@@ -90,8 +101,8 @@ const api: ElectronApi = {
importBestDebridCookies: (): Promise<number> => ipcRenderer.invoke(IPC_CHANNELS.IMPORT_BESTDEBRID_COOKIES),
getAllDebridHostInfo: (): Promise<AllDebridHostInfo> => ipcRenderer.invoke(IPC_CHANNELS.GET_ALLDEBRID_HOST_INFO),
getDebridLinkHostLimits: (): Promise<DebridLinkHostLimitInfo[]> => ipcRenderer.invoke(IPC_CHANNELS.GET_DEBRIDLINK_HOST_LIMITS),
checkDebridAccounts: (settings?: AppSettings, persistValidOverride = false, expectedAccountId?: string): Promise<DebridAccountStatus[]> => ipcRenderer.invoke(IPC_CHANNELS.CHECK_DEBRID_ACCOUNTS, settings, persistValidOverride, expectedAccountId),
checkMegaDebridAccount: (login: string, password: string): Promise<DebridAccountStatus | null> => ipcRenderer.invoke(IPC_CHANNELS.CHECK_MEGA_DEBRID_ACCOUNT, login, password),
checkDebridAccounts: (): Promise<DebridAccountStatus[]> => ipcRenderer.invoke(IPC_CHANNELS.CHECK_DEBRID_ACCOUNTS),
checkAccountCredentials: (input: AccountCredentialCheckInput): Promise<DebridAccountStatus> => ipcRenderer.invoke(IPC_CHANNELS.CHECK_ACCOUNT_CREDENTIALS, input),
retryExtraction: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RETRY_EXTRACTION, packageId),
extractNow: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.EXTRACT_NOW, packageId),
resetPackage: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.RESET_PACKAGE, packageId),
+199 -606
View File
File diff suppressed because it is too large Load Diff
+51 -457
View File
@@ -1,47 +1,13 @@
import { parseDebridLinkApiKeys, getDebridLinkApiKeyId } from "../shared/debrid-link-keys";
import { getMegaDebridAccountId, getMegaDebridAccountsForMode, getMegaDebridCredentialsForMode, getMegaDebridDisabledAccountIdsForMode, mergeMegaDebridCredentialPools, parseMegaDebridAccounts, serializeMegaDebridAccounts, type MegaDebridAccountMode } from "../shared/mega-debrid-accounts";
import type { AppSettings, DebridAccountStatus, DebridProvider } from "../shared/types";
import type { AccountDeleteCommand, AccountReplaceCommand, DebridProvider, RendererAccount, RendererAccountKind } from "../shared/types";
export type AccountService = "realdebrid" | "megadebrid-api" | "megadebrid-web" | "bestdebrid" | "alldebrid" | "ddownload" | "onefichier" | "debridlink" | "linksnappy";
export type AccountKind =
| "realdebrid-api"
| "realdebrid-web"
| "megadebrid-api"
| "megadebrid-web"
| "bestdebrid-api"
| "bestdebrid-web"
| "alldebrid-api"
| "alldebrid-web"
| "ddownload-login"
| "onefichier-api"
| "debridlink-api"
| "linksnappy-login";
export type AccountKind = RendererAccountKind;
export type SingleAccountKind = Exclude<AccountKind, "megadebrid-api" | "megadebrid-web" | "debridlink-api">;
export type AccountEditTarget =
| {
type: "single";
rowKey: string;
kind: SingleAccountKind;
service: AccountService;
provider: DebridProvider;
}
| {
type: "mega";
rowKey: string;
kind: "megadebrid-api" | "megadebrid-web";
service: "megadebrid-api" | "megadebrid-web";
accountId: string;
}
| {
type: "debridlink";
rowKey: string;
kind: "debridlink-api";
service: "debridlink";
keyId: string;
};
| { type: "single"; rowKey: string; kind: SingleAccountKind; service: AccountService; provider: DebridProvider }
| { type: "mega"; rowKey: string; kind: "megadebrid-api" | "megadebrid-web"; service: "megadebrid-api" | "megadebrid-web"; accountId: string }
| { type: "debridlink"; rowKey: string; kind: "debridlink-api"; service: "debridlink"; keyId: string };
export interface AccountEditState {
target: AccountEditTarget;
@@ -54,452 +20,80 @@ export interface AccountEditState {
const BYTES_PER_GIB = 1024 * 1024 * 1024;
function getMegaTargetMode(target: Extract<AccountEditTarget, { type: "mega" }>): MegaDebridAccountMode {
return target.kind === "megadebrid-web" ? "web" : "api";
}
function formatDailyLimit(limitBytes: number): string {
if (!Number.isFinite(limitBytes) || limitBytes <= 0) {
return "";
}
if (!Number.isFinite(limitBytes) || limitBytes <= 0) return "";
const gib = limitBytes / BYTES_PER_GIB;
const precision = gib >= 100 ? 0 : gib >= 10 ? 1 : 2;
return gib.toFixed(precision).replace(/\.0+$/, "").replace(/(\.\d*?)0+$/, "$1");
}
function parseDailyLimit(value: string): number | null {
function parseDailyLimit(value: string, originalBytes: number): number {
if (value === formatDailyLimit(originalBytes)) return originalBytes;
const normalized = value.trim().replace(",", ".");
if (!normalized) {
return null;
if (!normalized) return 0;
return Math.floor(Number(normalized) * BYTES_PER_GIB);
}
function targetAccountId(target: AccountEditTarget): string {
if (target.type === "mega") return target.accountId;
if (target.type === "debridlink") return target.keyId;
return `svc-${target.provider}`;
}
export function createAccountEditState(target: AccountEditTarget, accounts: readonly RendererAccount[]): AccountEditState {
const account = accounts.find((entry) => entry.accountId === targetAccountId(target) && entry.kind === target.kind);
if (!account) {
throw new Error("Der ausgewählte Account wurde nicht gefunden.");
}
const parsed = Number(normalized);
if (!Number.isFinite(parsed) || parsed < 0) {
return null;
}
return Math.floor(parsed * BYTES_PER_GIB);
}
function withoutRecordKeys<T>(record: Record<string, T>, ...keys: string[]): Record<string, T> {
const blocked = new Set(keys);
return Object.fromEntries(Object.entries(record || {}).filter(([key]) => !blocked.has(key)));
}
function resolveDailyLimit(value: string, originalBytes: number): number | null {
return value === formatDailyLimit(originalBytes) ? (originalBytes > 0 ? originalBytes : null) : parseDailyLimit(value);
}
function updateTargetLimit(record: Record<string, number>, oldId: string, newId: string, value: string, originalBytes: number): Record<string, number> {
const next = withoutRecordKeys(record || {}, oldId, newId);
const limit = resolveDailyLimit(value, originalBytes);
if (limit && limit > 0) {
next[newId] = limit;
}
return next;
}
function migrateDisabledId(ids: readonly string[], oldId: string, newId: string): string[] {
const wasDisabled = ids.includes(oldId);
const next = ids.filter((id) => id !== oldId && id !== newId);
if (wasDisabled) {
next.push(newId);
}
return next;
}
function updateProviderLimit(settings: AppSettings, provider: DebridProvider, value: string, originalBytes: number): AppSettings["providerDailyLimitBytes"] {
const next = { ...(settings.providerDailyLimitBytes || {}) };
const limit = resolveDailyLimit(value, originalBytes);
if (limit && limit > 0) {
next[provider] = limit;
} else {
delete next[provider];
}
return next;
}
function createSingleEditState(target: Extract<AccountEditTarget, { type: "single" }>, settings: AppSettings): AccountEditState {
const originalDailyLimitBytes = settings.providerDailyLimitBytes?.[target.provider] || 0;
const base = {
return {
target,
login: "",
login: account.identity,
password: "",
token: "",
dailyLimitGb: formatDailyLimit(originalDailyLimitBytes),
originalDailyLimitBytes
};
switch (target.kind) {
case "realdebrid-api":
return { ...base, token: settings.token };
case "bestdebrid-api":
return { ...base, token: settings.bestToken };
case "alldebrid-api":
return { ...base, token: settings.allDebridToken };
case "onefichier-api":
return { ...base, token: settings.oneFichierApiKey };
case "ddownload-login":
return { ...base, login: settings.ddownloadLogin, password: settings.ddownloadPassword };
case "linksnappy-login":
return { ...base, login: settings.linkSnappyLogin, password: settings.linkSnappyPassword };
default:
return base;
}
}
export function createAccountEditState(target: AccountEditTarget, settings: AppSettings): AccountEditState {
if (target.type === "single") {
return createSingleEditState(target, settings);
}
if (target.type === "mega") {
const account = getMegaDebridAccountsForMode(settings, getMegaTargetMode(target))
.find((entry) => entry.id === target.accountId);
if (!account) {
throw new Error("Der ausgewählte Mega-Debrid-Account wurde nicht gefunden.");
}
return {
target,
login: account.login,
password: account.password,
token: "",
dailyLimitGb: formatDailyLimit(settings.megaDebridAccountDailyLimitBytes?.[account.id] || 0),
originalDailyLimitBytes: settings.megaDebridAccountDailyLimitBytes?.[account.id] || 0
};
}
const key = parseDebridLinkApiKeys(settings.debridLinkApiKeys || "").find((entry) => entry.id === target.keyId);
if (!key) {
throw new Error("Der ausgewählte Debrid-Link-Key wurde nicht gefunden.");
}
return {
target,
login: "",
password: "",
token: key.token,
dailyLimitGb: formatDailyLimit(settings.debridLinkApiKeyDailyLimitBytes?.[key.id] || 0),
originalDailyLimitBytes: settings.debridLinkApiKeyDailyLimitBytes?.[key.id] || 0
dailyLimitGb: formatDailyLimit(account.dailyLimitBytes),
originalDailyLimitBytes: account.dailyLimitBytes
};
}
function validateDailyLimit(value: string): string | null {
const normalized = value.trim().replace(",", ".");
if (!normalized) {
return null;
export function validateAccountEdit(state: AccountEditState, accounts: readonly RendererAccount[]): string | null {
const normalizedLimit = state.dailyLimitGb.trim().replace(",", ".");
if (normalizedLimit && (!Number.isFinite(Number(normalizedLimit)) || Number(normalizedLimit) < 0)) {
return "Das Tageslimit muss eine positive Zahl oder 0 sein.";
}
const parsed = Number(normalized);
return Number.isFinite(parsed) && parsed >= 0 ? null : "Das Tageslimit muss eine positive Zahl oder 0 sein.";
}
export function validateAccountEdit(state: AccountEditState, settings: AppSettings): string | null {
const limitError = validateDailyLimit(state.dailyLimitGb);
if (limitError) {
return limitError;
const accountId = targetAccountId(state.target);
if (!accounts.some((entry) => entry.accountId === accountId && entry.kind === state.target.kind)) {
return "Der ausgewählte Account wurde nicht gefunden.";
}
if (state.target.type === "mega") {
const target = state.target;
const login = state.login.trim();
if (!login || !state.password.trim()) {
return "Login und Passwort werden benötigt.";
}
if (/[:\r\n]/.test(login)) {
return "Der Login darf keinen Doppelpunkt oder Zeilenumbruch enthalten.";
}
if (/[\r\n]/.test(state.password)) {
return "Das Passwort darf keinen Zeilenumbruch enthalten.";
}
const accounts = getMegaDebridAccountsForMode(settings, getMegaTargetMode(target));
if (!accounts.some((entry) => entry.id === target.accountId)) {
return "Der ausgewählte Mega-Debrid-Account wurde nicht gefunden.";
}
if (accounts.some((entry) => entry.id !== target.accountId && entry.login.toLowerCase() === login.toLowerCase())) {
if (!login) return "Der Login wird benötigt.";
if (/[:\r\n]/.test(login)) return "Der Login darf keinen Doppelpunkt oder Zeilenumbruch enthalten.";
if (/[\r\n]/.test(state.password)) return "Das Passwort darf keinen Zeilenumbruch enthalten.";
if (accounts.some((entry) => entry.kind === state.target.kind && entry.accountId !== accountId && entry.identity.toLowerCase() === login.toLowerCase())) {
return "Dieser Mega-Debrid-Login ist bereits vorhanden.";
}
return null;
}
if (state.target.type === "debridlink") {
const target = state.target;
const token = state.token.trim();
if (!token) {
return "Der API-Key wird benötigt.";
}
if (/[,\r\n]/.test(token)) {
return "Beim Bearbeiten ist genau ein API-Key erlaubt.";
}
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys || "");
if (!keys.some((entry) => entry.id === target.keyId)) {
return "Der ausgewählte Debrid-Link-Key wurde nicht gefunden.";
}
if (keys.some((entry) => entry.id !== target.keyId && entry.token === token)) {
return "Dieser Debrid-Link-Key ist bereits vorhanden.";
}
return null;
if (state.target.type === "debridlink" && /[,\r\n]/.test(state.token)) {
return "Beim Bearbeiten ist genau ein API-Key erlaubt.";
}
if (["realdebrid-api", "bestdebrid-api", "alldebrid-api", "onefichier-api"].includes(state.target.kind) && !state.token.trim()) {
return "Der Zugangstoken wird benötigt.";
}
if (["ddownload-login", "linksnappy-login"].includes(state.target.kind)) {
if (!state.login.trim() || !state.password.trim()) {
return "Login und Passwort werden benötigt.";
}
if (state.target.type === "single" && (state.target.kind === "ddownload-login" || state.target.kind === "linksnappy-login")) {
if (!state.login.trim()) return "Der Login wird benötigt.";
if (/[\r\n]/.test(state.password)) return "Das Passwort darf keinen Zeilenumbruch enthalten.";
}
return null;
}
function applySingleEdit(settings: AppSettings, state: AccountEditState & { target: Extract<AccountEditTarget, { type: "single" }> }): AppSettings {
const providerDailyLimitBytes = updateProviderLimit(settings, state.target.provider, state.dailyLimitGb, state.originalDailyLimitBytes);
const token = state.token.trim();
const login = state.login.trim();
switch (state.target.kind) {
case "realdebrid-api":
return { ...settings, token, realDebridUseWebLogin: false, providerDailyLimitBytes };
case "realdebrid-web":
return { ...settings, token: "", realDebridUseWebLogin: true, providerDailyLimitBytes };
case "bestdebrid-api":
return { ...settings, bestToken: token, bestDebridUseWebLogin: false, providerDailyLimitBytes };
case "bestdebrid-web":
return { ...settings, bestToken: "", bestDebridUseWebLogin: true, providerDailyLimitBytes };
case "alldebrid-api":
return { ...settings, allDebridToken: token, allDebridUseWebLogin: false, providerDailyLimitBytes };
case "alldebrid-web":
return { ...settings, allDebridToken: "", allDebridUseWebLogin: true, providerDailyLimitBytes };
case "ddownload-login":
return { ...settings, ddownloadLogin: login, ddownloadPassword: state.password, providerDailyLimitBytes };
case "onefichier-api":
return { ...settings, oneFichierApiKey: token, providerDailyLimitBytes };
case "linksnappy-login":
return { ...settings, linkSnappyLogin: login, linkSnappyPassword: state.password, providerDailyLimitBytes };
}
}
function applyMegaEdit(settings: AppSettings, state: AccountEditState & { target: Extract<AccountEditTarget, { type: "mega" }> }): AppSettings {
const mode = getMegaTargetMode(state.target);
const otherMode: MegaDebridAccountMode = mode === "api" ? "web" : "api";
const accounts = getMegaDebridAccountsForMode(settings, mode);
const index = accounts.findIndex((entry) => entry.id === state.target.accountId);
if (index < 0) {
throw new Error("Der ausgewählte Mega-Debrid-Account wurde nicht gefunden.");
}
const oldId = state.target.accountId;
const login = state.login.trim();
const newId = getMegaDebridAccountId(login);
const nextAccounts = accounts.map((entry, accountIndex) => accountIndex === index
? { login, password: state.password }
: { login: entry.login, password: entry.password });
const idChanged = oldId !== newId;
const selectedCredentials = serializeMegaDebridAccounts(nextAccounts);
const apiCredentials = mode === "api" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "api");
const webCredentials = mode === "web" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "web");
const mergedCredentials = mergeMegaDebridCredentialPools(apiCredentials, webCredentials);
const first = parseMegaDebridAccounts(mergedCredentials)[0];
const oldIdStillUsed = idChanged && getMegaDebridAccountsForMode(settings, otherMode).some((entry) => entry.id === oldId);
const selectedDisabledIds = idChanged
? migrateDisabledId(getMegaDebridDisabledAccountIdsForMode(settings, mode), oldId, newId)
: getMegaDebridDisabledAccountIdsForMode(settings, mode);
const otherDisabledIds = getMegaDebridDisabledAccountIdsForMode(settings, otherMode);
const apiDisabledIds = mode === "api" ? selectedDisabledIds : otherDisabledIds;
const webDisabledIds = mode === "web" ? selectedDisabledIds : otherDisabledIds;
const nextDailyLimits = updateTargetLimit(settings.megaDebridAccountDailyLimitBytes || {}, oldId, newId, state.dailyLimitGb, state.originalDailyLimitBytes);
if (oldIdStillUsed && settings.megaDebridAccountDailyLimitBytes?.[oldId]) {
nextDailyLimits[oldId] = settings.megaDebridAccountDailyLimitBytes[oldId];
}
const retainOldMetadata = <T,>(record: Record<string, T>): Record<string, T> => idChanged
? oldIdStillUsed ? withoutRecordKeys(record, newId) : withoutRecordKeys(record, oldId, newId)
: { ...record };
export function buildAccountReplaceCommand(state: AccountEditState): AccountReplaceCommand {
return {
...settings,
megaCredentials: mergedCredentials,
megaLogin: first?.login || "",
megaPassword: first?.password || "",
megaDebridApiCredentials: apiCredentials,
megaDebridWebCredentials: webCredentials,
megaDebridApiEnabled: settings.megaDebridApiEnabled && parseMegaDebridAccounts(apiCredentials).length > 0,
megaDebridWebEnabled: settings.megaDebridWebEnabled && parseMegaDebridAccounts(webCredentials).length > 0,
megaDebridDisabledAccountIds: [...new Set([...apiDisabledIds, ...webDisabledIds])],
megaDebridApiDisabledAccountIds: apiDisabledIds,
megaDebridWebDisabledAccountIds: webDisabledIds,
megaDebridAccountDailyLimitBytes: nextDailyLimits,
megaDebridAccountDailyUsageBytes: retainOldMetadata(settings.megaDebridAccountDailyUsageBytes || {}),
megaDebridAccountTotalUsageBytes: retainOldMetadata(settings.megaDebridAccountTotalUsageBytes || {}),
debridAccountStatuses: retainOldMetadata(settings.debridAccountStatuses || {})
action: "replace",
kind: state.target.kind,
accountId: targetAccountId(state.target),
identity: state.target.type === "debridlink" ? undefined : state.login.trim(),
secret: state.target.type === "debridlink" ? state.token : state.target.type === "single" && !["ddownload-login", "linksnappy-login"].includes(state.target.kind) ? state.token : state.password,
dailyLimitBytes: parseDailyLimit(state.dailyLimitGb, state.originalDailyLimitBytes)
};
}
function applyDebridLinkEdit(settings: AppSettings, state: AccountEditState & { target: Extract<AccountEditTarget, { type: "debridlink" }> }): AppSettings {
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys || "");
const index = keys.findIndex((entry) => entry.id === state.target.keyId);
if (index < 0) {
throw new Error("Der ausgewählte Debrid-Link-Key wurde nicht gefunden.");
}
const oldId = state.target.keyId;
const token = state.token.trim();
const newId = getDebridLinkApiKeyId(token);
const tokens = keys.map((entry, keyIndex) => keyIndex === index ? token : entry.token);
const idChanged = oldId !== newId;
return {
...settings,
debridLinkApiKeys: tokens.join("\n"),
debridLinkDisabledKeyIds: idChanged
? migrateDisabledId(settings.debridLinkDisabledKeyIds || [], oldId, newId)
: [...(settings.debridLinkDisabledKeyIds || [])],
debridLinkApiKeyDailyLimitBytes: updateTargetLimit(settings.debridLinkApiKeyDailyLimitBytes || {}, oldId, newId, state.dailyLimitGb, state.originalDailyLimitBytes),
debridLinkApiKeyDailyUsageBytes: idChanged
? withoutRecordKeys(settings.debridLinkApiKeyDailyUsageBytes || {}, oldId, newId)
: { ...(settings.debridLinkApiKeyDailyUsageBytes || {}) },
debridLinkApiKeyTotalUsageBytes: idChanged
? withoutRecordKeys(settings.debridLinkApiKeyTotalUsageBytes || {}, oldId, newId)
: { ...(settings.debridLinkApiKeyTotalUsageBytes || {}) },
debridAccountStatuses: idChanged
? withoutRecordKeys(settings.debridAccountStatuses || {}, oldId, newId)
: { ...(settings.debridAccountStatuses || {}) }
};
}
export function applyAccountEdit(settings: AppSettings, state: AccountEditState): AppSettings {
if (state.target.type === "single") {
return applySingleEdit(settings, state as AccountEditState & { target: Extract<AccountEditTarget, { type: "single" }> });
}
if (state.target.type === "mega") {
return applyMegaEdit(settings, state as AccountEditState & { target: Extract<AccountEditTarget, { type: "mega" }> });
}
return applyDebridLinkEdit(settings, state as AccountEditState & { target: Extract<AccountEditTarget, { type: "debridlink" }> });
}
function clearSingleAccount(settings: AppSettings, target: Extract<AccountEditTarget, { type: "single" }>): AppSettings {
const providerDailyLimitBytes = { ...(settings.providerDailyLimitBytes || {}) };
const providerDailyUsageBytes = { ...(settings.providerDailyUsageBytes || {}) };
const providerTotalUsageBytes = { ...(settings.providerTotalUsageBytes || {}) };
delete providerDailyLimitBytes[target.provider];
delete providerDailyUsageBytes[target.provider];
delete providerTotalUsageBytes[target.provider];
const base = { ...settings, providerDailyLimitBytes, providerDailyUsageBytes, providerTotalUsageBytes };
switch (target.service) {
case "realdebrid":
return { ...base, token: "", realDebridUseWebLogin: false };
case "bestdebrid":
return { ...base, bestToken: "", bestDebridUseWebLogin: false };
case "alldebrid":
return { ...base, allDebridToken: "", allDebridUseWebLogin: false };
case "ddownload":
return { ...base, ddownloadLogin: "", ddownloadPassword: "" };
case "onefichier":
return { ...base, oneFichierApiKey: "" };
case "linksnappy":
return { ...base, linkSnappyLogin: "", linkSnappyPassword: "" };
default:
return base;
}
}
export function removeAccountTarget(settings: AppSettings, target: AccountEditTarget): AppSettings {
if (target.type === "single") {
return clearSingleAccount(settings, target);
}
if (target.type === "mega") {
const mode = getMegaTargetMode(target);
const selectedAccounts = getMegaDebridAccountsForMode(settings, mode)
.filter((entry) => entry.id !== target.accountId)
.map((entry) => ({ login: entry.login, password: entry.password }));
const selectedCredentials = serializeMegaDebridAccounts(selectedAccounts);
const apiCredentials = mode === "api" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "api");
const webCredentials = mode === "web" ? selectedCredentials : getMegaDebridCredentialsForMode(settings, "web");
const mergedCredentials = mergeMegaDebridCredentialPools(apiCredentials, webCredentials);
const first = parseMegaDebridAccounts(mergedCredentials)[0];
const accountStillUsed = parseMegaDebridAccounts(mode === "api" ? webCredentials : apiCredentials).some((entry) => entry.id === target.accountId);
const apiDisabledIds = (mode === "api" ? getMegaDebridDisabledAccountIdsForMode(settings, "api").filter((id) => id !== target.accountId) : getMegaDebridDisabledAccountIdsForMode(settings, "api"));
const webDisabledIds = (mode === "web" ? getMegaDebridDisabledAccountIdsForMode(settings, "web").filter((id) => id !== target.accountId) : getMegaDebridDisabledAccountIdsForMode(settings, "web"));
const keepOrRemoveMetadata = <T,>(record: Record<string, T>): Record<string, T> => accountStillUsed ? { ...record } : withoutRecordKeys(record, target.accountId);
return {
...settings,
megaCredentials: mergedCredentials,
megaLogin: first?.login || "",
megaPassword: first?.password || "",
megaDebridApiCredentials: apiCredentials,
megaDebridWebCredentials: webCredentials,
megaDebridApiEnabled: parseMegaDebridAccounts(apiCredentials).length > 0 && settings.megaDebridApiEnabled,
megaDebridWebEnabled: parseMegaDebridAccounts(webCredentials).length > 0 && settings.megaDebridWebEnabled,
megaDebridDisabledAccountIds: [...new Set([...apiDisabledIds, ...webDisabledIds])],
megaDebridApiDisabledAccountIds: apiDisabledIds,
megaDebridWebDisabledAccountIds: webDisabledIds,
megaDebridAccountDailyLimitBytes: keepOrRemoveMetadata(settings.megaDebridAccountDailyLimitBytes || {}),
megaDebridAccountDailyUsageBytes: keepOrRemoveMetadata(settings.megaDebridAccountDailyUsageBytes || {}),
megaDebridAccountTotalUsageBytes: keepOrRemoveMetadata(settings.megaDebridAccountTotalUsageBytes || {}),
debridAccountStatuses: keepOrRemoveMetadata(settings.debridAccountStatuses || {})
};
}
const keys = parseDebridLinkApiKeys(settings.debridLinkApiKeys || "").filter((entry) => entry.id !== target.keyId);
return {
...settings,
debridLinkApiKeys: keys.map((entry) => entry.token).join("\n"),
debridLinkDisabledKeyIds: (settings.debridLinkDisabledKeyIds || []).filter((id) => id !== target.keyId),
debridLinkApiKeyDailyLimitBytes: withoutRecordKeys(settings.debridLinkApiKeyDailyLimitBytes || {}, target.keyId),
debridLinkApiKeyDailyUsageBytes: withoutRecordKeys(settings.debridLinkApiKeyDailyUsageBytes || {}, target.keyId),
debridLinkApiKeyTotalUsageBytes: withoutRecordKeys(settings.debridLinkApiKeyTotalUsageBytes || {}, target.keyId),
debridAccountStatuses: withoutRecordKeys(settings.debridAccountStatuses || {}, target.keyId)
};
}
export function buildAccountEditCheckSettings(settings: AppSettings, state: AccountEditState): AppSettings {
if (state.target.type === "mega") {
const login = state.login.trim();
const credentials = serializeMegaDebridAccounts([{ login, password: state.password }]);
const mode = getMegaTargetMode(state.target);
return {
...settings,
megaCredentials: credentials,
megaLogin: login,
megaPassword: state.password,
megaDebridApiCredentials: mode === "api" ? credentials : "",
megaDebridWebCredentials: mode === "web" ? credentials : "",
megaDebridApiEnabled: mode === "api",
megaDebridWebEnabled: mode === "web",
megaDebridApiDisabledAccountIds: [],
megaDebridWebDisabledAccountIds: [],
debridLinkApiKeys: ""
};
}
if (state.target.type === "debridlink") {
return {
...settings,
megaCredentials: "",
megaLogin: "",
megaPassword: "",
megaDebridApiCredentials: "",
megaDebridWebCredentials: "",
debridLinkApiKeys: state.token.trim()
};
}
return {
...settings,
megaCredentials: "",
megaLogin: "",
megaPassword: "",
megaDebridApiCredentials: "",
megaDebridWebCredentials: "",
debridLinkApiKeys: ""
};
}
export function validateAccountEditStatuses(state: AccountEditState, statuses: readonly DebridAccountStatus[]): string | null {
if (state.target.type === "single") {
return null;
}
if (statuses.length === 0) {
return "Die Prüfung hat keinen Account zurückgegeben.";
}
if (statuses.length !== 1) {
return "Die Prüfung hat mehr als den ausgewählten Account zurückgegeben.";
}
const expectedId = getAccountEditExpectedStatusId(state);
const status = statuses[0];
if (status.accountId !== expectedId) {
return "Die Prüfung hat den falschen Account zurückgegeben.";
}
return status.valid ? null : status.message || "Zugangsdaten ungültig";
}
export function getAccountEditExpectedStatusId(state: AccountEditState): string | null {
if (state.target.type === "mega") {
return getMegaDebridAccountId(state.login);
}
if (state.target.type === "debridlink") {
return getDebridLinkApiKeyId(state.token);
}
return null;
export function buildAccountDeleteCommand(target: AccountEditTarget): AccountDeleteCommand {
return { action: "delete", kind: target.kind, accountId: targetAccountId(target) };
}
@@ -1,4 +1,4 @@
import type { AppSettings } from "../../../shared/types";
import type { RendererSettings } from "../../../shared/types";
import type { AccountService } from "../../account-edit";
import { ACCOUNT_SERVICE_ICONS } from "../../account-service-icons";
@@ -49,10 +49,10 @@ export function getSettingsSelectNavigationIndex(currentIndex: number, optionCou
}
export function resolveHistoryRetentionSelection(
currentMode: AppSettings["historyRetentionMode"],
currentMode: RendererSettings["historyRetentionMode"],
currentMaxEntries: number,
value: string
): Pick<AppSettings, "historyRetentionMode" | "historyMaxEntries"> {
): Pick<RendererSettings, "historyRetentionMode" | "historyMaxEntries"> {
const preset = /^permanent-(100|250)$/.exec(value);
if (preset) {
return {
@@ -69,7 +69,7 @@ export function resolveHistoryRetentionSelection(
};
}
return {
historyRetentionMode: value as AppSettings["historyRetentionMode"],
historyRetentionMode: value as RendererSettings["historyRetentionMode"],
historyMaxEntries: currentMaxEntries
};
}
@@ -208,7 +208,7 @@ export interface SettingsFormViewModel {
}
export interface SettingsFormProjectionInput {
settings: AppSettings;
settings: RendererSettings & { archivePasswordList: string; notifyUrl: string };
section: SettingsSection;
speedLimitInput: string;
scheduleSpeedInputs: Readonly<Record<string, string>>;
@@ -289,7 +289,7 @@ export function buildSettingsFormViewModel({
id: "extract-passwords",
title: "Passwörter",
fields: [
{ id: "archivePasswordList", kind: "textarea", label: "Passwortliste für Archive", value: settings.archivePasswordList, placeholder: "Ein Passwort pro Zeile" }
{ id: "archivePasswordList", kind: "textarea", label: "Passwortliste für Archive", value: settings.archivePasswordList, placeholder: settings.archivePasswordListConfigured ? "Gespeichert; leer lassen zum Beibehalten" : "Ein Passwort pro Zeile" }
]
}
]
@@ -528,7 +528,7 @@ export function buildSettingsFormViewModel({
id: "general-notifications",
title: "Discord-Benachrichtigungen",
fields: [
{ id: "notifyUrl", kind: "text", label: "Webhook-Adresse", value: settings.notifyUrl, placeholder: "https://discord.com/api/webhooks/…", actionLabel: "Testen" },
{ id: "notifyUrl", kind: "text", label: "Webhook-Adresse", value: settings.notifyUrl, placeholder: settings.notifyUrlConfigured ? "Gespeichert; leer lassen zum Beibehalten" : "https://discord.com/api/webhooks/…", actionLabel: "Testen" },
{ id: "notifyMention", kind: "text", label: "Discord-Erwähnung (optional)", value: settings.notifyMention },
{ id: "notifyOnPackageCompleted", kind: "switch", label: "Melden, wenn ein Paket fertig ist", value: settings.notifyOnPackageCompleted },
{ id: "notifyOnPackageFailed", kind: "switch", label: "Melden, wenn ein Paket fehlschlägt", value: settings.notifyOnPackageFailed },
+5 -1
View File
@@ -6,6 +6,10 @@ export const IPC_CHANNELS = {
UPDATE_INSTALL_PROGRESS: "app:update-install-progress",
OPEN_EXTERNAL: "app:open-external",
UPDATE_SETTINGS: "app:update-settings",
CREATE_ACCOUNT: "app:create-account",
REPLACE_ACCOUNT: "app:replace-account",
UPDATE_ACCOUNT_SECRET: "app:update-account-secret",
DELETE_ACCOUNT: "app:delete-account",
RESET_PROVIDER_DAILY_USAGE: "app:reset-provider-daily-usage",
RESET_DEBRID_LINK_API_KEY_DAILY_USAGE: "app:reset-debrid-link-api-key-daily-usage",
ADD_LINKS: "queue:add-links",
@@ -66,7 +70,7 @@ export const IPC_CHANNELS = {
GET_ALLDEBRID_HOST_INFO: "app:get-alldebrid-host-info",
GET_DEBRIDLINK_HOST_LIMITS: "app:get-debridlink-host-limits",
CHECK_DEBRID_ACCOUNTS: "app:check-debrid-accounts",
CHECK_MEGA_DEBRID_ACCOUNT: "app:check-mega-debrid-account",
CHECK_ACCOUNT_CREDENTIALS: "app:check-account-credentials",
RETRY_EXTRACTION: "queue:retry-extraction",
EXTRACT_NOW: "queue:extract-now",
RESET_PACKAGE: "queue:reset-package",
+17 -6
View File
@@ -1,7 +1,12 @@
import type {
AddLinksPayload,
AccountCommandResult,
AccountCredentialCheckInput,
AccountCreateCommand,
AccountDeleteCommand,
AccountReplaceCommand,
AccountUpdateSecretCommand,
AllDebridHostInfo,
AppSettings,
DebridAccountStatus,
DebugSetupCheckResult,
DebridLinkHostLimitInfo,
@@ -12,6 +17,8 @@ import type {
HistoryRevealResult,
PackagePriority,
RemoteDiagnosticsInfo,
RendererSettings,
RendererSettingsUpdate,
RendererErrorReport,
SessionStats,
StartConflictEntry,
@@ -29,9 +36,13 @@ export interface ElectronApi {
checkUpdates: () => Promise<UpdateCheckResult>;
installUpdate: () => Promise<UpdateInstallResult>;
openExternal: (url: string) => Promise<boolean>;
updateSettings: (settings: Partial<AppSettings>) => Promise<AppSettings>;
resetProviderDailyUsage: (provider: DebridProvider) => Promise<AppSettings>;
resetDebridLinkApiKeyDailyUsage: (keyId: string) => Promise<AppSettings>;
updateSettings: (settings: RendererSettingsUpdate) => Promise<RendererSettings>;
resetProviderDailyUsage: (provider: DebridProvider) => Promise<RendererSettings>;
resetDebridLinkApiKeyDailyUsage: (keyId: string) => Promise<RendererSettings>;
createAccount: (command: AccountCreateCommand) => Promise<AccountCommandResult>;
replaceAccount: (command: AccountReplaceCommand) => Promise<AccountCommandResult>;
updateAccountSecret: (command: AccountUpdateSecretCommand) => Promise<AccountCommandResult>;
deleteAccount: (command: AccountDeleteCommand) => Promise<AccountCommandResult>;
addLinks: (payload: AddLinksPayload) => Promise<{ addedPackages: number; addedLinks: number; invalidCount: number }>;
addContainers: (filePaths: string[]) => Promise<{ addedPackages: number; addedLinks: number }>;
getStartConflicts: () => Promise<StartConflictEntry[]>;
@@ -87,8 +98,8 @@ export interface ElectronApi {
importBestDebridCookies: () => Promise<number>;
getAllDebridHostInfo: () => Promise<AllDebridHostInfo>;
getDebridLinkHostLimits: () => Promise<DebridLinkHostLimitInfo[]>;
checkDebridAccounts: (settings?: AppSettings, persistValidOverride?: boolean, expectedAccountId?: string) => Promise<DebridAccountStatus[]>;
checkMegaDebridAccount: (login: string, password: string) => Promise<DebridAccountStatus | null>;
checkDebridAccounts: () => Promise<DebridAccountStatus[]>;
checkAccountCredentials: (input: AccountCredentialCheckInput) => Promise<DebridAccountStatus>;
retryExtraction: (packageId: string) => Promise<void>;
extractNow: (packageId: string) => Promise<void>;
resetPackage: (packageId: string) => Promise<void>;
+171 -1
View File
@@ -171,6 +171,175 @@ export interface AppSettings {
scheduledStartEpochMs: number;
}
export type RendererAccountKind =
| "realdebrid-api"
| "realdebrid-web"
| "megadebrid-api"
| "megadebrid-web"
| "bestdebrid-api"
| "bestdebrid-web"
| "alldebrid-api"
| "alldebrid-web"
| "ddownload-login"
| "onefichier-api"
| "debridlink-api"
| "linksnappy-login";
export interface RendererAccount {
accountId: string;
kind: RendererAccountKind;
provider: DebridProvider;
identity: string;
maskedIdentity: string;
hasSecret: boolean;
enabled: boolean;
dailyLimitBytes: number;
dailyUsageBytes: number;
totalUsageBytes: number;
status: DebridAccountStatus | null;
}
export interface RendererSettings {
language: AppLanguage;
realDebridUseWebLogin: boolean;
megaDebridApiEnabled: boolean;
megaDebridWebEnabled: boolean;
megaDebridPreferApi: boolean;
bestDebridUseWebLogin: boolean;
allDebridUseWebLogin: boolean;
debridLinkDisabledKeyIds: string[];
rememberToken: boolean;
configuredProviders: DebridProvider[];
providerOrder: readonly DebridProvider[];
providerPrimary: DebridProvider;
providerSecondary: DebridFallbackProvider;
providerTertiary: DebridFallbackProvider;
autoProviderFallback: boolean;
outputDir: string;
packageName: string;
autoExtract: boolean;
autoRename4sf4sj: boolean;
keepGermanAudioOnly: boolean;
germanAudioMode: "tag" | "first";
extractDir: string;
collectMkvToLibrary: boolean;
mkvLibraryDir: string;
createExtractSubfolder: boolean;
hybridExtract: boolean;
cleanupMode: CleanupMode;
extractConflictMode: ConflictMode;
removeLinkFilesAfterExtract: boolean;
removeSamplesAfterExtract: boolean;
enableIntegrityCheck: boolean;
autoResumeOnStart: boolean;
autoReconnect: boolean;
reconnectWaitSeconds: number;
completedCleanupPolicy: FinishedCleanupPolicy;
maxParallel: number;
maxParallelExtract: number;
retryLimit: number;
speedLimitEnabled: boolean;
speedLimitKbps: number;
speedLimitMode: SpeedMode;
updateRepo: string;
autoUpdateCheck: boolean;
clipboardWatch: boolean;
minimizeToTray: boolean;
theme: AppTheme;
collapseNewPackages: boolean;
historyRetentionMode: HistoryRetentionMode;
historyMaxEntries: number;
historyMaxAgeDays: number;
accountListShowDetailedDebridLinkKeys: boolean;
autoSortPackagesByProgress: boolean;
autoSkipExtracted: boolean;
hideExtractedItems: boolean;
confirmDeleteSelection: boolean;
backupIncludeDownloads: boolean;
backupIncludeRemoteDiagnostics: boolean;
archivePasswordListConfigured: boolean;
notifyUrlConfigured: boolean;
notifyMention: string;
notifyOnPackageCompleted: boolean;
notifyOnPackageFailed: boolean;
notifyOnRunFinished: boolean;
totalDownloadedAllTime: number;
totalCompletedFilesAllTime: number;
totalRuntimeAllTimeMs: number;
bandwidthSchedules: BandwidthScheduleEntry[];
columnOrder: string[];
columnOrderVersion?: number;
extractCpuPriority: ExtractCpuPriority;
autoExtractWhenStopped: boolean;
disabledProviders: DebridProvider[];
hosterRouting: Record<string, DebridProvider>;
providerDailyLimitBytes: Partial<Record<DebridProvider, number>>;
providerDailyUsageBytes: Partial<Record<DebridProvider, number>>;
providerTotalUsageBytes: Partial<Record<DebridProvider, number>>;
debridLinkApiKeyDailyLimitBytes: Record<string, number>;
debridLinkApiKeyDailyUsageBytes: Record<string, number>;
debridLinkApiKeyTotalUsageBytes: Record<string, number>;
megaDebridDisabledAccountIds: string[];
megaDebridApiDisabledAccountIds: string[];
megaDebridWebDisabledAccountIds: string[];
megaDebridAccountDailyLimitBytes: Record<string, number>;
megaDebridAccountDailyUsageBytes: Record<string, number>;
megaDebridAccountTotalUsageBytes: Record<string, number>;
debridAccountStatuses: Record<string, DebridAccountStatus>;
providerDailyUsageDay: string;
scheduledStartEpochMs: number;
}
export type RendererSettingsUpdate = Partial<RendererSettings> & {
archivePasswordList?: string;
notifyUrl?: string;
};
export interface AccountCreateCommand {
action: "create";
kind: RendererAccountKind;
identity?: string;
secret?: string;
dailyLimitBytes?: number;
}
export interface AccountReplaceCommand {
action: "replace";
kind: RendererAccountKind;
accountId: string;
identity?: string;
secret?: string;
dailyLimitBytes?: number;
}
export interface AccountUpdateSecretCommand {
action: "update-secret";
kind: RendererAccountKind;
accountId: string;
secret: string;
}
export interface AccountDeleteCommand {
action: "delete";
kind: RendererAccountKind;
accountId: string;
}
export type AccountCommand = AccountCreateCommand | AccountReplaceCommand | AccountUpdateSecretCommand | AccountDeleteCommand;
export interface AccountCommandResult {
accountId: string | null;
settings: RendererSettings;
accounts: RendererAccount[];
}
export interface AccountCredentialCheckInput {
kind: "megadebrid-api" | "megadebrid-web" | "debridlink-api";
accountId?: string;
identity?: string;
secret?: string;
}
export interface DownloadItem {
id: string;
packageId: string;
@@ -288,7 +457,8 @@ export interface RotationEvent {
}
export interface UiSnapshot {
settings: AppSettings;
settings: RendererSettings;
accounts: RendererAccount[];
session: SessionState;
summary: DownloadSummary | null;
stats: DownloadStats;
+350
View File
@@ -0,0 +1,350 @@
import { describe, expect, it } from "vitest";
import { applyAccountCommand, validateAccountCommand } from "../src/main/account-commands";
import { defaultSettings } from "../src/main/constants";
import { getDebridLinkApiKeyId } from "../src/shared/debrid-link-keys";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
import type { AppSettings, RendererAccountKind } from "../src/shared/types";
const ORIGINAL_SECRET = "fixture-original-secret-4qV8";
const REPLACEMENT_SECRET = "fixture-replacement-secret-6nC2";
const GIB = 1024 * 1024 * 1024;
const SECRET_RETAIN_CASES: Array<{
kind: RendererAccountKind;
identity: string;
secret: string;
retained: (settings: AppSettings) => boolean;
}> = [
{ kind: "realdebrid-api", identity: "", secret: "fixture-retain-rd-1aC3", retained: (settings) => settings.token === "fixture-retain-rd-1aC3" },
{ kind: "megadebrid-api", identity: "retain-mega-api@example.test", secret: "fixture-retain-mega-api-2bD4", retained: (settings) => settings.megaDebridApiCredentials === "retain-mega-api@example.test:fixture-retain-mega-api-2bD4" },
{ kind: "megadebrid-web", identity: "retain-mega-web@example.test", secret: "fixture-retain-mega-web-3cE5", retained: (settings) => settings.megaDebridWebCredentials === "retain-mega-web@example.test:fixture-retain-mega-web-3cE5" },
{ kind: "bestdebrid-api", identity: "", secret: "fixture-retain-best-4dF6", retained: (settings) => settings.bestToken === "fixture-retain-best-4dF6" },
{ kind: "alldebrid-api", identity: "", secret: "fixture-retain-all-5eG7", retained: (settings) => settings.allDebridToken === "fixture-retain-all-5eG7" },
{ kind: "ddownload-login", identity: "retain-dd@example.test", secret: "fixture-retain-dd-6fH8", retained: (settings) => settings.ddownloadPassword === "fixture-retain-dd-6fH8" },
{ kind: "onefichier-api", identity: "", secret: "fixture-retain-one-7gJ9", retained: (settings) => settings.oneFichierApiKey === "fixture-retain-one-7gJ9" },
{ kind: "debridlink-api", identity: "", secret: "fixture-retain-dl-8hK1", retained: (settings) => settings.debridLinkApiKeys === "fixture-retain-dl-8hK1" },
{ kind: "linksnappy-login", identity: "retain-ls@example.test", secret: "fixture-retain-ls-9jL2", retained: (settings) => settings.linkSnappyPassword === "fixture-retain-ls-9jL2" }
];
const ACCOUNT_KINDS: RendererAccountKind[] = [
"realdebrid-api",
"realdebrid-web",
"megadebrid-api",
"megadebrid-web",
"bestdebrid-api",
"bestdebrid-web",
"alldebrid-api",
"alldebrid-web",
"ddownload-login",
"onefichier-api",
"debridlink-api",
"linksnappy-login"
];
describe("write-only account commands", () => {
it.each([
["realdebrid-api", "", "fixture-rd-provider-secret-1fA4", "token"],
["realdebrid-web", "", "", "realDebridUseWebLogin"],
["bestdebrid-api", "", "fixture-best-provider-secret-2gB5", "bestToken"],
["bestdebrid-web", "", "", "bestDebridUseWebLogin"],
["alldebrid-api", "", "fixture-ad-provider-secret-3hC6", "allDebridToken"],
["alldebrid-web", "", "", "allDebridUseWebLogin"],
["ddownload-login", "dd-safe@example.test", "fixture-dd-provider-secret-4jD7", "ddownloadPassword"],
["onefichier-api", "", "fixture-one-provider-secret-5kE8", "oneFichierApiKey"],
["linksnappy-login", "ls-safe@example.test", "fixture-ls-provider-secret-6mF9", "linkSnappyPassword"]
] as const)("preserves create and delete behavior for %s", (kind, identity, secret, configuredKey) => {
const created = applyAccountCommand(defaultSettings(), validateAccountCommand({
action: "create",
kind,
identity,
secret,
dailyLimitBytes: 4_294_967_296
}));
expect(created.settings[configuredKey]).toBe(secret || true);
expect(JSON.stringify(created.response)).not.toContain(secret || "fixture-never-present");
const deleted = applyAccountCommand(created.settings, validateAccountCommand({
action: "delete",
kind,
accountId: created.response.accountId
}));
expect(deleted.settings[configuredKey]).toBe(secret ? "" : false);
});
it("creates an account without returning submitted secrets", () => {
const command = validateAccountCommand({
action: "create",
kind: "megadebrid-api",
identity: "new-account@example.test",
secret: ORIGINAL_SECRET,
dailyLimitBytes: 12_884_901_888
});
const result = applyAccountCommand(defaultSettings(), command);
expect(result.settings.megaDebridApiCredentials).toContain(ORIGINAL_SECRET);
expect(JSON.stringify(result.response)).not.toContain(ORIGINAL_SECRET);
expect(result.response.accountId).toBe(getMegaDebridAccountId("new-account@example.test"));
});
it("adds a Web Mega-Debrid account without copying it into the API pool or changing preferApi", () => {
const result = applyAccountCommand({
...defaultSettings(),
megaCredentials: "api@example.test:fixture-api-secret-1aM2",
megaDebridApiCredentials: "api@example.test:fixture-api-secret-1aM2",
megaDebridWebCredentials: "",
megaDebridApiEnabled: true,
megaDebridWebEnabled: false,
megaDebridPreferApi: false
}, validateAccountCommand({
action: "create",
kind: "megadebrid-web",
identity: "web@example.test",
secret: "fixture-web-secret-3bN4",
dailyLimitBytes: 0
}));
expect(result.settings.megaDebridApiCredentials).toBe("api@example.test:fixture-api-secret-1aM2");
expect(result.settings.megaDebridWebCredentials).toBe("web@example.test:fixture-web-secret-3bN4");
expect(result.settings.megaDebridApiEnabled).toBe(true);
expect(result.settings.megaDebridWebEnabled).toBe(true);
expect(result.settings.megaDebridPreferApi).toBe(false);
expect(JSON.stringify(result.response)).not.toContain("fixture-web-secret-3bN4");
});
it("retains a stored secret when replace receives a blank secret", () => {
const identity = "existing-account@example.test";
const accountId = getMegaDebridAccountId(identity);
const settings = {
...defaultSettings(),
megaCredentials: `${identity}:${ORIGINAL_SECRET}`,
megaDebridApiCredentials: `${identity}:${ORIGINAL_SECRET}`,
megaDebridApiEnabled: true
};
const command = validateAccountCommand({
action: "replace",
kind: "megadebrid-api",
accountId,
identity: "renamed-account@example.test",
secret: "",
dailyLimitBytes: 8_589_934_592
});
const result = applyAccountCommand(settings, command);
expect(result.settings.megaDebridApiCredentials).toBe(`renamed-account@example.test:${ORIGINAL_SECRET}`);
expect(JSON.stringify(result.response)).not.toContain(ORIGINAL_SECRET);
});
it.each(SECRET_RETAIN_CASES)("retains the stored $kind secret when replace receives a blank secret", ({ kind, identity, secret, retained }) => {
const created = applyAccountCommand(defaultSettings(), validateAccountCommand({
action: "create",
kind,
identity,
secret,
dailyLimitBytes: 1
}));
const replaced = applyAccountCommand(created.settings, validateAccountCommand({
action: "replace",
kind,
accountId: created.response.accountId,
identity,
secret: "",
dailyLimitBytes: 1
}));
expect(retained(replaced.settings)).toBe(true);
expect(JSON.stringify(replaced.response)).not.toContain(secret);
});
it("replaces a Mega-Debrid account while preserving sibling accounts and mode-specific state", () => {
const firstId = getMegaDebridAccountId("first@example.test");
const oldId = getMegaDebridAccountId("second@example.test");
const newId = getMegaDebridAccountId("renamed@example.test");
const webId = getMegaDebridAccountId("web@example.test");
const settings = {
...defaultSettings(),
megaCredentials: "first@example.test:first-secret\nsecond@example.test:second-secret\nweb@example.test:web-secret",
megaDebridApiCredentials: "first@example.test:first-secret\nsecond@example.test:second-secret",
megaDebridWebCredentials: "web@example.test:web-secret",
megaDebridApiEnabled: true,
megaDebridWebEnabled: true,
megaDebridPreferApi: false,
megaDebridDisabledAccountIds: [oldId, firstId, webId],
megaDebridApiDisabledAccountIds: [oldId, firstId],
megaDebridWebDisabledAccountIds: [webId],
megaDebridAccountDailyLimitBytes: { [oldId]: 15 * GIB, [firstId]: 9 * GIB },
megaDebridAccountDailyUsageBytes: { [oldId]: 4 * GIB, [firstId]: 2 * GIB },
megaDebridAccountTotalUsageBytes: { [oldId]: 40 * GIB, [firstId]: 20 * GIB },
debridAccountStatuses: {
[oldId]: { accountId: oldId, provider: "megadebrid" as const, label: "Account 2", maskedLogin: "se***st", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 },
[firstId]: { accountId: firstId, provider: "megadebrid" as const, label: "Account 1", maskedLogin: "fi***st", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
}
};
const result = applyAccountCommand(settings, validateAccountCommand({
action: "replace",
kind: "megadebrid-api",
accountId: oldId,
identity: "renamed@example.test",
secret: "renamed-secret",
dailyLimitBytes: Math.floor(25.5 * GIB)
}));
expect(result.settings.megaDebridApiCredentials).toBe("first@example.test:first-secret\nrenamed@example.test:renamed-secret");
expect(result.settings.megaDebridWebCredentials).toBe("web@example.test:web-secret");
expect(result.settings.megaDebridPreferApi).toBe(false);
expect(result.settings.megaDebridDisabledAccountIds).toEqual([firstId, newId, webId]);
expect(result.settings.megaDebridApiDisabledAccountIds).toEqual([firstId, newId]);
expect(result.settings.megaDebridWebDisabledAccountIds).toEqual([webId]);
expect(result.settings.megaDebridAccountDailyLimitBytes).toEqual({ [firstId]: 9 * GIB, [newId]: Math.floor(25.5 * GIB) });
expect(result.settings.megaDebridAccountDailyUsageBytes).toEqual({ [firstId]: 2 * GIB });
expect(result.settings.megaDebridAccountTotalUsageBytes).toEqual({ [firstId]: 20 * GIB });
expect(result.settings.debridAccountStatuses).toEqual({
[firstId]: { accountId: firstId, provider: "megadebrid", label: "Account 1", maskedLogin: "fi***st", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
});
expect(JSON.stringify(result.response)).not.toContain("renamed-secret");
});
it("replaces only the selected Debrid-Link key and migrates its own metadata", () => {
const keyA = "fixture-dl-key-a-1aB2";
const keyB = "fixture-dl-key-b-3cD4";
const keyC = "fixture-dl-key-c-5eF6";
const newKey = "fixture-dl-key-b-new-7gH8";
const idA = getDebridLinkApiKeyId(keyA);
const idB = getDebridLinkApiKeyId(keyB);
const idNew = getDebridLinkApiKeyId(newKey);
const result = applyAccountCommand({
...defaultSettings(),
debridLinkApiKeys: `${keyA}\n${keyB}\n${keyC}`,
debridLinkDisabledKeyIds: [idB, idA],
debridLinkApiKeyDailyLimitBytes: { [idA]: 5 * GIB, [idB]: 10 * GIB },
debridLinkApiKeyDailyUsageBytes: { [idA]: 2 * GIB, [idB]: 4 * GIB },
debridLinkApiKeyTotalUsageBytes: { [idA]: 12 * GIB, [idB]: 24 * GIB }
}, validateAccountCommand({
action: "replace",
kind: "debridlink-api",
accountId: idB,
secret: newKey,
dailyLimitBytes: 12 * GIB
}));
expect(result.settings.debridLinkApiKeys).toBe(`${keyA}\n${newKey}\n${keyC}`);
expect(result.settings.debridLinkDisabledKeyIds).toEqual([idA, idNew]);
expect(result.settings.debridLinkApiKeyDailyLimitBytes).toEqual({ [idA]: 5 * GIB, [idNew]: 12 * GIB });
expect(result.settings.debridLinkApiKeyDailyUsageBytes).toEqual({ [idA]: 2 * GIB });
expect(result.settings.debridLinkApiKeyTotalUsageBytes).toEqual({ [idA]: 12 * GIB });
expect(JSON.stringify(result.response)).not.toContain(newKey);
});
it("keeps a matching Web identity disabled when its API identity is deleted", () => {
const identity = "shared-mode@example.test";
const accountId = getMegaDebridAccountId(identity);
const settings = {
...defaultSettings(),
megaCredentials: `${identity}:fixture-api-mode-secret-1mN3`,
megaDebridApiCredentials: `${identity}:fixture-api-mode-secret-1mN3`,
megaDebridWebCredentials: `${identity}:fixture-web-mode-secret-2nP4`,
megaDebridApiEnabled: true,
megaDebridWebEnabled: true,
megaDebridDisabledAccountIds: [accountId],
megaDebridApiDisabledAccountIds: [accountId],
megaDebridWebDisabledAccountIds: [accountId]
};
const deleted = applyAccountCommand(settings, validateAccountCommand({
action: "delete",
kind: "megadebrid-api",
accountId
}));
expect(deleted.settings.megaDebridApiCredentials).toBe("");
expect(deleted.settings.megaDebridWebCredentials).toBe(`${identity}:fixture-web-mode-secret-2nP4`);
expect(deleted.settings.megaDebridApiDisabledAccountIds).toEqual([]);
expect(deleted.settings.megaDebridWebDisabledAccountIds).toEqual([accountId]);
expect(deleted.settings.megaDebridDisabledAccountIds).toEqual([accountId]);
});
it("updates only the selected secret and deletes only the selected account", () => {
const firstIdentity = "first-account@example.test";
const secondIdentity = "second-account@example.test";
const firstId = getMegaDebridAccountId(firstIdentity);
const secondId = getMegaDebridAccountId(secondIdentity);
const settings = {
...defaultSettings(),
megaCredentials: `${firstIdentity}:${ORIGINAL_SECRET}\n${secondIdentity}:fixture-sibling-secret-3wH7`,
megaDebridApiCredentials: `${firstIdentity}:${ORIGINAL_SECRET}\n${secondIdentity}:fixture-sibling-secret-3wH7`,
megaDebridApiEnabled: true
};
const updated = applyAccountCommand(settings, validateAccountCommand({
action: "update-secret",
kind: "megadebrid-api",
accountId: firstId,
secret: REPLACEMENT_SECRET
}));
const deleted = applyAccountCommand(updated.settings, validateAccountCommand({
action: "delete",
kind: "megadebrid-api",
accountId: firstId
}));
expect(updated.settings.megaDebridApiCredentials).toContain(`${firstIdentity}:${REPLACEMENT_SECRET}`);
expect(deleted.settings.megaDebridApiCredentials).toBe(`${secondIdentity}:fixture-sibling-secret-3wH7`);
expect(deleted.response.accountId).toBe(secondId);
expect(JSON.stringify([updated.response, deleted.response])).not.toContain(REPLACEMENT_SECRET);
});
it("creates and deletes a Debrid-Link API key by stable key identity", () => {
const secret = "fixture-dl-create-delete-1pQ4";
const created = applyAccountCommand(defaultSettings(), validateAccountCommand({
action: "create",
kind: "debridlink-api",
secret,
dailyLimitBytes: 3 * GIB
}));
expect(created.response.accountId).toBe(getDebridLinkApiKeyId(secret));
expect(created.settings.debridLinkApiKeys).toBe(secret);
expect(created.settings.debridLinkApiKeyDailyLimitBytes).toEqual({ [getDebridLinkApiKeyId(secret)]: 3 * GIB });
expect(JSON.stringify(created.response)).not.toContain(secret);
const deleted = applyAccountCommand(created.settings, validateAccountCommand({
action: "delete",
kind: "debridlink-api",
accountId: created.response.accountId
}));
expect(deleted.settings.debridLinkApiKeys).toBe("");
expect(deleted.settings.debridLinkApiKeyDailyLimitBytes).toEqual({});
expect(deleted.response.accountId).toBeNull();
});
it("rejects malformed payloads without echoing submitted secrets", () => {
let errorText = "";
try {
validateAccountCommand({
action: "replace",
kind: "megadebrid-api",
accountId: 42,
secret: REPLACEMENT_SECRET
});
} catch (error) {
errorText = String(error);
}
expect(errorText).toMatch(/ungültig/i);
expect(errorText).not.toContain(REPLACEMENT_SECRET);
});
it.each(ACCOUNT_KINDS)("rejects malformed %s payloads without echoing their submitted secret", (kind) => {
const secret = `fixture-malformed-${kind}-3qR5`;
let errorText = "";
try {
validateAccountCommand({ action: "replace", kind, accountId: 42, secret });
} catch (error) {
errorText = String(error);
}
expect(errorText).toMatch(/ungültig/i);
expect(errorText).not.toContain(secret);
});
});
+22 -73
View File
@@ -1,81 +1,30 @@
import { describe, expect, it } from "vitest";
import { applyAccountDialogToSettings, createAccountDialogState, AccountDialogState } from "../src/renderer/App";
import { buildAccountCreateCommand, createAccountDialogState } from "../src/renderer/App";
import { createRendererSettings } from "../src/main/renderer-state";
import { defaultSettings } from "../src/main/constants";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
import { isMegaDebridAccountDisabled } from "../src/shared/provider-daily-limits";
function megaDialog(kind: "megadebrid-api" | "megadebrid-web"): AccountDialogState {
return {
mode: "edit",
kind,
service: kind,
token: "",
login: "",
password: "",
dailyLimitGb: "",
keyDailyLimitGbById: {},
megaAccounts: [{ login: "user@x", password: "pw" }],
megaNewLogin: "",
megaNewPassword: "",
megaDisabledIds: []
};
}
describe("applyAccountDialogToSettings — keeps the user's Mega preferApi choice", () => {
it("does not flip megaDebridPreferApi to true when editing the API account", () => {
const settings = { ...defaultSettings(), megaDebridApiEnabled: true, megaDebridWebEnabled: true, megaDebridPreferApi: false };
const next = applyAccountDialogToSettings(settings, megaDialog("megadebrid-api"));
expect(next.megaDebridApiEnabled).toBe(true);
expect(next.megaDebridPreferApi).toBe(false);
});
it("does not flip megaDebridPreferApi to false when editing the Web account", () => {
const settings = { ...defaultSettings(), megaDebridApiEnabled: true, megaDebridWebEnabled: true, megaDebridPreferApi: true };
const next = applyAccountDialogToSettings(settings, megaDialog("megadebrid-web"));
expect(next.megaDebridWebEnabled).toBe(true);
expect(next.megaDebridPreferApi).toBe(true);
});
it("adds a Web account without copying it into the API account pool", () => {
const settings = {
...defaultSettings(),
megaCredentials: "api@example.test:api-pass",
megaDebridApiCredentials: "api@example.test:api-pass",
megaDebridWebCredentials: "",
megaDebridApiEnabled: true,
megaDebridWebEnabled: false
describe("account creation dialog", () => {
it("creates a mode-specific Mega-Debrid command without existing credentials", () => {
const settings = createRendererSettings(defaultSettings());
const dialog = {
...createAccountDialogState("create", "megadebrid-web", settings),
megaNewLogin: "web-safe@example.test",
megaNewPassword: "fixture-dialog-secret-7pL2"
};
const dialog = createAccountDialogState("create", "megadebrid-web", settings);
expect(buildAccountCreateCommand(dialog)).toEqual({
action: "create",
kind: "megadebrid-web",
identity: "web-safe@example.test",
secret: "fixture-dialog-secret-7pL2",
dailyLimitBytes: 0
});
});
it("keeps all account fields blank before user input", () => {
const dialog = createAccountDialogState("create", "debridlink-api", createRendererSettings(defaultSettings()));
expect(dialog.token).toBe("");
expect(dialog.password).toBe("");
expect(dialog.megaAccounts).toEqual([]);
const next = applyAccountDialogToSettings(settings, {
...dialog,
megaAccounts: [{ login: "web@example.test", password: "web-pass" }]
});
expect(next.megaDebridApiCredentials).toBe("api@example.test:api-pass");
expect(next.megaDebridWebCredentials).toBe("web@example.test:web-pass");
expect(next.megaDebridApiEnabled).toBe(true);
expect(next.megaDebridWebEnabled).toBe(true);
});
it("disables an API account without disabling the matching Web account", () => {
const accountId = getMegaDebridAccountId("shared@example.test");
const settings = {
...defaultSettings(),
megaCredentials: "shared@example.test:api-pass",
megaDebridApiCredentials: "shared@example.test:api-pass",
megaDebridWebCredentials: "shared@example.test:web-pass",
megaDebridApiEnabled: true,
megaDebridWebEnabled: true
};
const next = applyAccountDialogToSettings(settings, {
...createAccountDialogState("edit", "megadebrid-api", settings),
megaDisabledIds: [accountId]
});
expect(isMegaDebridAccountDisabled(next, accountId, "api")).toBe(true);
expect(isMegaDebridAccountDisabled(next, accountId, "web")).toBe(false);
});
});
+52 -275
View File
@@ -1,305 +1,82 @@
import { describe, expect, it } from "vitest";
import { defaultSettings } from "../src/main/constants";
import { createRendererState } from "../src/main/renderer-state";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
import {
applyAccountEdit,
buildAccountEditCheckSettings,
buildAccountDeleteCommand,
buildAccountReplaceCommand,
createAccountEditState,
removeAccountTarget,
validateAccountEdit,
validateAccountEditStatuses,
type AccountEditTarget
} from "../src/renderer/account-edit";
import { getDebridLinkApiKeyId } from "../src/shared/debrid-link-keys";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
const GIB = 1024 * 1024 * 1024;
function megaTarget(login: string): AccountEditTarget {
function megaTarget(identity: string): AccountEditTarget {
const accountId = getMegaDebridAccountId(identity);
return {
type: "mega",
rowKey: `mega-${getMegaDebridAccountId(login)}`,
rowKey: `mega-megadebrid-api-${accountId}`,
kind: "megadebrid-api",
service: "megadebrid-api",
accountId: getMegaDebridAccountId(login)
accountId
};
}
function debridLinkTarget(token: string): AccountEditTarget {
return {
type: "debridlink",
rowKey: `dl-${getDebridLinkApiKeyId(token)}`,
kind: "debridlink-api",
service: "debridlink",
keyId: getDebridLinkApiKeyId(token)
};
}
describe("account-specific editing", () => {
it("changes only the selected Mega-Debrid account and preserves sibling order and mode settings", () => {
const oldId = getMegaDebridAccountId("second@example.com");
const newId = getMegaDebridAccountId("renamed@example.com");
const firstId = getMegaDebridAccountId("first@example.com");
const webId = getMegaDebridAccountId("web@example.com");
const settings = {
describe("renderer-safe account editing", () => {
it("opens an existing account without reading its stored secret", () => {
const identity = "safe-edit@example.test";
const state = createRendererState({
...defaultSettings(),
megaCredentials: "first@example.com:first-pass\nsecond@example.com:second-pass\nthird@example.com:third-pass\nweb@example.com:web-pass",
megaDebridApiCredentials: "first@example.com:first-pass\nsecond@example.com:second-pass\nthird@example.com:third-pass",
megaDebridWebCredentials: "web@example.com:web-pass",
megaLogin: "first@example.com",
megaPassword: "first-pass",
megaDebridApiEnabled: true,
megaDebridWebEnabled: true,
megaDebridPreferApi: false,
megaDebridDisabledAccountIds: [oldId, firstId, webId],
megaDebridApiDisabledAccountIds: [oldId, firstId],
megaDebridWebDisabledAccountIds: [webId],
megaDebridAccountDailyLimitBytes: { [oldId]: 15 * GIB, [firstId]: 9 * GIB },
megaDebridAccountDailyUsageBytes: { [oldId]: 4 * GIB, [firstId]: 2 * GIB },
megaDebridAccountTotalUsageBytes: { [oldId]: 40 * GIB, [firstId]: 20 * GIB },
debridAccountStatuses: {
[oldId]: { accountId: oldId, provider: "megadebrid" as const, label: "Account 2", maskedLogin: "se***om", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 },
[firstId]: { accountId: firstId, provider: "megadebrid" as const, label: "Account 1", maskedLogin: "fi***om", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
}
};
const state = {
...createAccountEditState(megaTarget("second@example.com"), settings),
login: "renamed@example.com",
password: "new-pass",
dailyLimitGb: "25,5"
};
expect(validateAccountEdit(state, settings)).toBeNull();
const next = applyAccountEdit(settings, state);
expect(next.megaCredentials).toBe("first@example.com:first-pass\nrenamed@example.com:new-pass\nthird@example.com:third-pass\nweb@example.com:web-pass");
expect(next.megaDebridApiCredentials).toBe("first@example.com:first-pass\nrenamed@example.com:new-pass\nthird@example.com:third-pass");
expect(next.megaDebridWebCredentials).toBe("web@example.com:web-pass");
expect(next.megaLogin).toBe("first@example.com");
expect(next.megaPassword).toBe("first-pass");
expect(next.megaDebridApiEnabled).toBe(true);
expect(next.megaDebridWebEnabled).toBe(true);
expect(next.megaDebridPreferApi).toBe(false);
expect(next.megaDebridDisabledAccountIds).toEqual([firstId, newId, webId]);
expect(next.megaDebridAccountDailyLimitBytes).toEqual({ [firstId]: 9 * GIB, [newId]: Math.floor(25.5 * GIB) });
expect(next.megaDebridAccountDailyUsageBytes).toEqual({ [firstId]: 2 * GIB });
expect(next.megaDebridAccountTotalUsageBytes).toEqual({ [firstId]: 20 * GIB });
expect(next.debridAccountStatuses).toEqual({
[firstId]: { accountId: firstId, provider: "megadebrid", label: "Account 1", maskedLogin: "fi***om", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
megaCredentials: `${identity}:fixture-stored-secret-4dH8`,
megaDebridApiCredentials: `${identity}:fixture-stored-secret-4dH8`,
megaDebridApiEnabled: true
});
const edit = createAccountEditState(megaTarget(identity), state.accounts);
expect(edit.login).toBe(identity);
expect(edit.password).toBe("");
expect(JSON.stringify(edit)).not.toContain("fixture-stored-secret-4dH8");
});
it("keeps Mega-Debrid usage when only the password changes", () => {
const id = getMegaDebridAccountId("user@example.com");
const settings = {
it("builds a replace command whose blank secret retains the main-process value", () => {
const identity = "safe-edit@example.test";
const renderer = createRendererState({
...defaultSettings(),
megaCredentials: "user@example.com:old-pass",
megaLogin: "user@example.com",
megaPassword: "old-pass",
megaDebridAccountDailyLimitBytes: { [id]: 8 * GIB },
megaDebridAccountDailyUsageBytes: { [id]: 3 * GIB },
megaDebridAccountTotalUsageBytes: { [id]: 33 * GIB }
};
const state = { ...createAccountEditState(megaTarget("user@example.com"), settings), password: "new-pass" };
const next = applyAccountEdit(settings, state);
megaCredentials: `${identity}:fixture-stored-secret-4dH8`,
megaDebridApiCredentials: `${identity}:fixture-stored-secret-4dH8`,
megaDebridApiEnabled: true
});
const edit = createAccountEditState(megaTarget(identity), renderer.accounts);
expect(next.megaCredentials).toBe("user@example.com:new-pass");
expect(next.megaDebridAccountDailyUsageBytes).toEqual({ [id]: 3 * GIB });
expect(next.megaDebridAccountTotalUsageBytes).toEqual({ [id]: 33 * GIB });
expect(validateAccountEdit(edit, renderer.accounts)).toBeNull();
expect(buildAccountReplaceCommand(edit)).toEqual(expect.objectContaining({
action: "replace",
accountId: getMegaDebridAccountId(identity),
identity,
secret: ""
}));
});
it("preserves exact account limits when the rounded display value is left unchanged", () => {
const megaLogin = "user@example.com";
const megaId = getMegaDebridAccountId(megaLogin);
const key = "debrid-link-token";
const keyId = getDebridLinkApiKeyId(key);
const exactLimit = Math.floor(10.05 * GIB);
const settings = {
it("rejects duplicate identities using safe account metadata", () => {
const first = "first-safe@example.test";
const second = "second-safe@example.test";
const renderer = createRendererState({
...defaultSettings(),
megaCredentials: `${megaLogin}:pass`,
megaLogin,
megaPassword: "pass",
megaDebridAccountDailyLimitBytes: { [megaId]: exactLimit },
debridLinkApiKeys: key,
debridLinkApiKeyDailyLimitBytes: { [keyId]: exactLimit }
};
megaCredentials: `${first}:fixture-first-secret-1aB2\n${second}:fixture-second-secret-3cD4`,
megaDebridApiCredentials: `${first}:fixture-first-secret-1aB2\n${second}:fixture-second-secret-3cD4`,
megaDebridApiEnabled: true
});
const edit = { ...createAccountEditState(megaTarget(second), renderer.accounts), login: first };
const megaNext = applyAccountEdit(settings, createAccountEditState(megaTarget(megaLogin), settings));
const debridLinkNext = applyAccountEdit(settings, createAccountEditState(debridLinkTarget(key), settings));
expect(megaNext.megaDebridAccountDailyLimitBytes[megaId]).toBe(exactLimit);
expect(debridLinkNext.debridLinkApiKeyDailyLimitBytes[keyId]).toBe(exactLimit);
expect(validateAccountEdit(edit, renderer.accounts)).toMatch(/bereits vorhanden/i);
});
it("rejects whitespace-only Mega-Debrid passwords and empty or mismatched check results", () => {
const login = "user@example.com";
const settings = {
...defaultSettings(),
megaCredentials: `${login}:pass`,
megaLogin: login,
megaPassword: "pass"
};
const state = { ...createAccountEditState(megaTarget(login), settings), password: " " };
expect(validateAccountEdit(state, settings)).toMatch(/Passwort/i);
expect(validateAccountEditStatuses(state, [])).toMatch(/keinen Account/i);
expect(validateAccountEditStatuses(state, [{
accountId: "mda_other",
provider: "megadebrid",
label: "Account 1",
maskedLogin: "ot***er",
valid: true,
isPremium: true,
premiumUntilMs: null,
message: "OK",
checkedAt: 1
}])).toMatch(/falschen Account/i);
});
it("rejects duplicate Mega-Debrid logins and missing row targets", () => {
const settings = {
...defaultSettings(),
megaCredentials: "first@example.com:first-pass\nsecond@example.com:second-pass"
};
const duplicate = {
...createAccountEditState(megaTarget("second@example.com"), settings),
login: "first@example.com"
};
expect(validateAccountEdit(duplicate, settings)).toMatch(/bereits vorhanden/i);
expect(() => createAccountEditState(megaTarget("missing@example.com"), settings)).toThrow(/nicht gefunden/i);
});
it("replaces only the selected Debrid-Link key and migrates its own metadata", () => {
const keyA = "token-a";
const keyB = "token-b";
const keyC = "token-c";
const newKey = "token-b-new";
const idA = getDebridLinkApiKeyId(keyA);
const idB = getDebridLinkApiKeyId(keyB);
const idNew = getDebridLinkApiKeyId(newKey);
const settings = {
...defaultSettings(),
debridLinkApiKeys: `${keyA}\n${keyB}\n${keyC}`,
debridLinkDisabledKeyIds: [idB, idA],
debridLinkApiKeyDailyLimitBytes: { [idA]: 5 * GIB, [idB]: 10 * GIB },
debridLinkApiKeyDailyUsageBytes: { [idA]: 2 * GIB, [idB]: 4 * GIB },
debridLinkApiKeyTotalUsageBytes: { [idA]: 12 * GIB, [idB]: 24 * GIB }
};
const state = {
...createAccountEditState(debridLinkTarget(keyB), settings),
token: newKey,
dailyLimitGb: "12"
};
const next = applyAccountEdit(settings, state);
expect(next.debridLinkApiKeys).toBe(`${keyA}\n${newKey}\n${keyC}`);
expect(next.debridLinkDisabledKeyIds).toEqual([idA, idNew]);
expect(next.debridLinkApiKeyDailyLimitBytes).toEqual({ [idA]: 5 * GIB, [idNew]: 12 * GIB });
expect(next.debridLinkApiKeyDailyUsageBytes).toEqual({ [idA]: 2 * GIB });
expect(next.debridLinkApiKeyTotalUsageBytes).toEqual({ [idA]: 12 * GIB });
});
it("edits a single login without changing unrelated credentials", () => {
const settings = {
...defaultSettings(),
ddownloadLogin: "old@example.com",
ddownloadPassword: "old-pass",
linkSnappyLogin: "keep@example.com",
linkSnappyPassword: "keep-pass"
};
const target: AccountEditTarget = {
type: "single",
rowKey: "svc-ddownload",
kind: "ddownload-login",
service: "ddownload",
provider: "ddownload"
};
const state = {
...createAccountEditState(target, settings),
login: "new@example.com",
password: "new-pass",
dailyLimitGb: "7"
};
const next = applyAccountEdit(settings, state);
expect(next.ddownloadLogin).toBe("new@example.com");
expect(next.ddownloadPassword).toBe("new-pass");
expect(next.linkSnappyLogin).toBe("keep@example.com");
expect(next.linkSnappyPassword).toBe("keep-pass");
expect(next.providerDailyLimitBytes.ddownload).toBe(7 * GIB);
});
it("rejects whitespace-only passwords for direct login accounts", () => {
const settings = {
...defaultSettings(),
ddownloadLogin: "user@example.com",
ddownloadPassword: "password",
linkSnappyLogin: "member@example.com",
linkSnappyPassword: "secret"
};
const ddownloadTarget: AccountEditTarget = {
type: "single",
rowKey: "svc-ddownload",
kind: "ddownload-login",
service: "ddownload",
provider: "ddownload"
};
const linkSnappyTarget: AccountEditTarget = {
type: "single",
rowKey: "svc-linksnappy",
kind: "linksnappy-login",
service: "linksnappy",
provider: "linksnappy"
};
expect(validateAccountEdit({ ...createAccountEditState(ddownloadTarget, settings), password: " " }, settings)).toMatch(/Passwort/i);
expect(validateAccountEdit({ ...createAccountEditState(linkSnappyTarget, settings), password: "\t" }, settings)).toMatch(/Passwort/i);
});
it("builds a targeted check snapshot without invalid sibling accounts", () => {
const settings = {
...defaultSettings(),
megaCredentials: "first@example.com:first-pass\nsecond@example.com:second-pass",
megaLogin: "first@example.com",
megaPassword: "first-pass",
debridLinkApiKeys: "one\ntwo"
};
const target = megaTarget("second@example.com");
const state = createAccountEditState(target, settings);
const checkSettings = buildAccountEditCheckSettings(settings, state);
expect(checkSettings.megaCredentials).toBe("second@example.com:second-pass");
expect(checkSettings.megaLogin).toBe("second@example.com");
expect(checkSettings.megaPassword).toBe("second-pass");
expect(checkSettings.debridLinkApiKeys).toBe("");
});
it("removes only the selected Mega-Debrid account and all metadata belonging to it", () => {
const removeId = getMegaDebridAccountId("second@example.com");
const keepId = getMegaDebridAccountId("first@example.com");
const settings = {
...defaultSettings(),
megaCredentials: "first@example.com:first-pass\nsecond@example.com:second-pass",
megaLogin: "first@example.com",
megaPassword: "first-pass",
megaDebridDisabledAccountIds: [removeId, keepId],
megaDebridAccountDailyLimitBytes: { [removeId]: 2, [keepId]: 1 },
megaDebridAccountDailyUsageBytes: { [removeId]: 4, [keepId]: 3 },
megaDebridAccountTotalUsageBytes: { [removeId]: 6, [keepId]: 5 },
debridAccountStatuses: {
[removeId]: { accountId: removeId, provider: "megadebrid" as const, label: "Account 2", maskedLogin: "se***om", valid: true, isPremium: false, premiumUntilMs: null, message: "Free", checkedAt: 1 },
[keepId]: { accountId: keepId, provider: "megadebrid" as const, label: "Account 1", maskedLogin: "fi***om", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
}
};
const next = removeAccountTarget(settings, megaTarget("second@example.com"));
expect(next.megaCredentials).toBe("first@example.com:first-pass");
expect(next.megaDebridDisabledAccountIds).toEqual([keepId]);
expect(next.megaDebridAccountDailyLimitBytes).toEqual({ [keepId]: 1 });
expect(next.megaDebridAccountDailyUsageBytes).toEqual({ [keepId]: 3 });
expect(next.megaDebridAccountTotalUsageBytes).toEqual({ [keepId]: 5 });
expect(next.debridAccountStatuses).toEqual({
[keepId]: { accountId: keepId, provider: "megadebrid", label: "Account 1", maskedLogin: "fi***om", valid: true, isPremium: true, premiumUntilMs: null, message: "OK", checkedAt: 1 }
it("builds an identity-only delete command", () => {
const target = megaTarget("delete-safe@example.test");
expect(buildAccountDeleteCommand(target)).toEqual({
action: "delete",
kind: "megadebrid-api",
accountId: target.type === "mega" ? target.accountId : ""
});
});
});
+64
View File
@@ -0,0 +1,64 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { IPC_CHANNELS } from "../src/shared/ipc";
import type { ElectronApi } from "../src/shared/preload-api";
const electron = vi.hoisted(() => ({
api: undefined as ElectronApi | undefined,
invoke: vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => undefined)
}));
vi.mock("electron", () => ({
contextBridge: {
exposeInMainWorld: (_name: string, api: ElectronApi) => {
electron.api = api;
}
},
ipcRenderer: {
invoke: electron.invoke,
on: vi.fn(),
removeListener: vi.fn(),
send: vi.fn()
}
}));
describe("account preload contract", () => {
beforeAll(async () => {
await import("../src/preload/preload");
});
beforeEach(() => {
electron.invoke.mockClear();
});
it("forwards submitted secrets only in write-only account commands", async () => {
const secret = "fixture-preload-secret-5zK1";
electron.invoke.mockResolvedValueOnce({ accountId: "mda_fixture", settings: { language: "de" }, accounts: [] });
const result = await electron.api?.createAccount({
action: "create",
kind: "megadebrid-api",
identity: "preload-account@example.test",
secret,
dailyLimitBytes: 0
});
expect(electron.invoke).toHaveBeenCalledWith(
IPC_CHANNELS.CREATE_ACCOUNT,
expect.objectContaining({ secret })
);
expect(JSON.stringify(result)).not.toContain(secret);
});
it("exposes separate replace, update-secret and delete channels", async () => {
electron.invoke.mockResolvedValue({ accountId: "mda_fixture", settings: { language: "de" }, accounts: [] });
await electron.api?.replaceAccount({ action: "replace", kind: "megadebrid-api", accountId: "mda_fixture", identity: "account@example.test", secret: "", dailyLimitBytes: 0 });
await electron.api?.updateAccountSecret({ action: "update-secret", kind: "megadebrid-api", accountId: "mda_fixture", secret: "fixture-new-secret-8sP4" });
await electron.api?.deleteAccount({ action: "delete", kind: "megadebrid-api", accountId: "mda_fixture" });
expect(electron.invoke.mock.calls.map((call) => call[0])).toEqual([
IPC_CHANNELS.REPLACE_ACCOUNT,
IPC_CHANNELS.UPDATE_ACCOUNT_SECRET,
IPC_CHANNELS.DELETE_ACCOUNT
]);
});
});
+16 -3
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import { once } from "node:events";
import AdmZip from "adm-zip";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../src/main/windows-host-diagnostics", () => ({
getWindowsHostDiagnostics: () => ({
@@ -41,6 +41,8 @@ vi.mock("../src/main/windows-host-diagnostics", () => ({
}));
import { defaultSettings } from "../src/main/constants";
import { configureCredentialProtector } from "../src/main/credential-protection";
import { createRendererState } from "../src/main/renderer-state";
import { getAuditLogPath, initAuditLog, logAuditEvent, shutdownAuditLog } from "../src/main/audit-log";
import { startDebugServer, stopDebugServer } from "../src/main/debug-server";
import { ensureItemLog, initItemLogs, shutdownItemLogs } from "../src/main/item-log";
@@ -71,6 +73,14 @@ const forbiddenSupportMarkers = [
["K", "I"].join("")
];
beforeEach(() => {
configureCredentialProtector({
isEncryptionAvailable: () => true,
encryptString: (value) => Buffer.from(value, "utf8").reverse(),
decryptString: (value) => Buffer.from(value).reverse().toString("utf8")
});
});
async function getFreePort(): Promise<number> {
const probe = http.createServer();
probe.listen(0, "127.0.0.1");
@@ -106,8 +116,9 @@ function buildSnapshot(baseDir: string): UiSnapshot {
extractDir: path.join(baseDir, "extract")
};
const renderer = createRendererState(settings);
return {
settings,
...renderer,
session: {
version: 1,
packageOrder: ["pkg-1"],
@@ -221,7 +232,9 @@ async function createFixture() {
const debridLinkKeyIds = getDebridLinkApiKeyIds(debridLinkApiKeys);
saveSettings(storagePaths, {
...snapshot.settings,
...defaultSettings(),
outputDir: snapshot.settings.outputDir,
extractDir: snapshot.settings.extractDir,
token: "rd-secret-token",
realDebridUseWebLogin: true,
debridLinkApiKeys,
+1
View File
@@ -6,6 +6,7 @@ import type { UiSnapshot } from "../src/shared/types";
function buildSnapshot(): UiSnapshot {
return {
settings: {} as UiSnapshot["settings"],
accounts: [],
session: {
version: 1,
packageOrder: ["pkg-1", "pkg-2"],
+131
View File
@@ -0,0 +1,131 @@
import { describe, expect, it } from "vitest";
import { defaultSettings } from "../src/main/constants";
import { createRendererState } from "../src/main/renderer-state";
import { getDebridLinkApiKeyId } from "../src/shared/debrid-link-keys";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
import type { AppSettings, RendererAccountKind } from "../src/shared/types";
const SECRETS = {
token: "fixture-rd-token-7vQ2",
megaPassword: "fixture-mega-password-8kM3",
bestToken: "fixture-best-token-5xL9",
allDebridToken: "fixture-ad-token-4pR6",
ddownloadPassword: "fixture-dd-password-2tN8",
oneFichierApiKey: "fixture-onefichier-key-6cW1",
debridLinkApiKey: "fixture-debridlink-key-9hS4",
linkSnappyPassword: "fixture-linksnappy-password-3mB7",
archivePassword: "fixture-archive-password-1jD5",
notifyUrl: "https://notify.example.test/hooks/fixture-notify-secret-0fA2"
} as const;
const ACCOUNT_FIXTURES: Array<{
kind: RendererAccountKind;
secret: string;
settings: Partial<AppSettings>;
}> = [
{ kind: "realdebrid-api", secret: "fixture-rd-api-secret-1aK4", settings: { token: "fixture-rd-api-secret-1aK4" } },
{ kind: "realdebrid-web", secret: "fixture-rd-web-session-2bL5", settings: { token: "fixture-rd-web-session-2bL5", realDebridUseWebLogin: true } },
{ kind: "megadebrid-api", secret: "fixture-mega-api-secret-3cM6", settings: { megaCredentials: "mega-api@example.test:fixture-mega-api-secret-3cM6", megaDebridApiCredentials: "mega-api@example.test:fixture-mega-api-secret-3cM6", megaDebridApiEnabled: true } },
{ kind: "megadebrid-web", secret: "fixture-mega-web-secret-4dN7", settings: { megaCredentials: "mega-web@example.test:fixture-mega-web-secret-4dN7", megaDebridWebCredentials: "mega-web@example.test:fixture-mega-web-secret-4dN7", megaDebridWebEnabled: true } },
{ kind: "bestdebrid-api", secret: "fixture-best-api-secret-5eP8", settings: { bestToken: "fixture-best-api-secret-5eP8" } },
{ kind: "bestdebrid-web", secret: "fixture-best-web-session-6fQ9", settings: { bestToken: "fixture-best-web-session-6fQ9", bestDebridUseWebLogin: true } },
{ kind: "alldebrid-api", secret: "fixture-all-api-secret-7gR1", settings: { allDebridToken: "fixture-all-api-secret-7gR1" } },
{ kind: "alldebrid-web", secret: "fixture-all-web-session-8hS2", settings: { allDebridToken: "fixture-all-web-session-8hS2", allDebridUseWebLogin: true } },
{ kind: "ddownload-login", secret: "fixture-dd-secret-9jT3", settings: { ddownloadLogin: "dd@example.test", ddownloadPassword: "fixture-dd-secret-9jT3" } },
{ kind: "onefichier-api", secret: "fixture-one-secret-0kU4", settings: { oneFichierApiKey: "fixture-one-secret-0kU4" } },
{ kind: "debridlink-api", secret: "fixture-dl-secret-1mV5", settings: { debridLinkApiKeys: "fixture-dl-secret-1mV5" } },
{ kind: "linksnappy-login", secret: "fixture-ls-secret-2nW6", settings: { linkSnappyLogin: "ls@example.test", linkSnappyPassword: "fixture-ls-secret-2nW6" } }
];
describe("renderer state serialization", () => {
it.each(ACCOUNT_FIXTURES)("serializes $kind without its representative secret", ({ kind, secret, settings }) => {
const state = createRendererState({ ...defaultSettings(), ...settings });
expect(state.accounts).toEqual(expect.arrayContaining([expect.objectContaining({ kind, hasSecret: true })]));
expect(JSON.stringify(state)).not.toContain(secret);
expect(JSON.stringify(state.settings)).not.toContain(secret);
});
it("excludes every provider and settings secret while preserving safe account metadata", () => {
const megaLogin = "renderer-fixture@example.test";
const settings = {
...defaultSettings(),
token: SECRETS.token,
megaLogin,
megaPassword: SECRETS.megaPassword,
megaCredentials: `${megaLogin}:${SECRETS.megaPassword}`,
megaDebridApiCredentials: `${megaLogin}:${SECRETS.megaPassword}`,
megaDebridApiEnabled: true,
bestToken: SECRETS.bestToken,
allDebridToken: SECRETS.allDebridToken,
ddownloadLogin: "renderer-dd@example.test",
ddownloadPassword: SECRETS.ddownloadPassword,
oneFichierApiKey: SECRETS.oneFichierApiKey,
debridLinkApiKeys: SECRETS.debridLinkApiKey,
linkSnappyLogin: "renderer-linksnappy@example.test",
linkSnappyPassword: SECRETS.linkSnappyPassword,
archivePasswordList: SECRETS.archivePassword,
notifyUrl: SECRETS.notifyUrl
};
const state = createRendererState(settings);
const serialized = JSON.stringify(state);
for (const secret of Object.values(SECRETS)) {
expect(serialized).not.toContain(secret);
}
expect(state.settings.archivePasswordListConfigured).toBe(true);
expect(state.settings.notifyUrlConfigured).toBe(true);
expect(state.accounts).toEqual(expect.arrayContaining([
expect.objectContaining({ kind: "realdebrid-api", hasSecret: true }),
expect.objectContaining({ kind: "megadebrid-api", identity: megaLogin, hasSecret: true }),
expect.objectContaining({ kind: "debridlink-api", hasSecret: true })
]));
});
it("redacts individual secrets embedded in status metadata for multi-account pools", () => {
const firstMegaSecret = "fixture-first-mega-pool-secret-3pX7";
const secondMegaSecret = "fixture-second-mega-pool-secret-4qY8";
const firstKey = "fixture-first-debridlink-pool-secret-5rZ9";
const secondKey = "fixture-second-debridlink-pool-secret-6sA1";
const secondMegaId = getMegaDebridAccountId("second-pool@example.test");
const secondKeyId = getDebridLinkApiKeyId(secondKey);
const settings = {
...defaultSettings(),
megaCredentials: `first-pool@example.test:${firstMegaSecret}\nsecond-pool@example.test:${secondMegaSecret}`,
megaDebridApiCredentials: `first-pool@example.test:${firstMegaSecret}\nsecond-pool@example.test:${secondMegaSecret}`,
megaDebridApiEnabled: true,
debridLinkApiKeys: `${firstKey}\n${secondKey}`,
debridAccountStatuses: {
[secondMegaId]: {
accountId: secondMegaId,
provider: "megadebrid" as const,
label: "Account 2",
maskedLogin: "se***st",
valid: false,
isPremium: false,
premiumUntilMs: null,
message: `Rejected ${secondMegaSecret}`,
checkedAt: 1
},
[secondKeyId]: {
accountId: secondKeyId,
provider: "debridlink" as const,
label: "Key 2",
maskedLogin: "fi***A1",
valid: false,
isPremium: false,
premiumUntilMs: null,
message: `Rejected ${secondKey}`,
checkedAt: 1
}
}
};
const serialized = JSON.stringify(createRendererState(settings));
for (const secret of [firstMegaSecret, secondMegaSecret, firstKey, secondKey]) {
expect(serialized).not.toContain(secret);
}
});
});
+14 -17
View File
@@ -3,12 +3,9 @@ import { isValidElement, type ReactElement, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { defaultSettings } from "../src/main/constants";
import { createRendererSettings, createRendererState } from "../src/main/renderer-state";
import { buildAccountAddFields, createAccountDialogState } from "../src/renderer/App";
import {
applyAccountEdit,
createAccountEditState,
type AccountEditTarget
} from "../src/renderer/account-edit";
import { buildAccountReplaceCommand, createAccountEditState, type AccountEditTarget } from "../src/renderer/account-edit";
import {
buildBulkAccountEnabledState,
buildConfiguredProviderOrder
@@ -416,7 +413,6 @@ describe("settings model", () => {
const login = "member@example.test";
const oldId = getMegaDebridAccountId(login);
const newLogin = "renamed@example.test";
const newId = getMegaDebridAccountId(newLogin);
const exactLimit = Math.floor(10.05 * GIB);
const settings = {
...defaultSettings(),
@@ -435,17 +431,17 @@ describe("settings model", () => {
service: "megadebrid-api",
accountId: oldId
};
const unchanged = applyAccountEdit(settings, createAccountEditState(target, settings));
const renamed = applyAccountEdit(settings, {
...createAccountEditState(target, settings),
const renderer = createRendererState(settings);
const unchanged = buildAccountReplaceCommand(createAccountEditState(target, renderer.accounts));
const renamed = buildAccountReplaceCommand({
...createAccountEditState(target, renderer.accounts),
login: newLogin
});
expect(unchanged.megaDebridAccountDailyLimitBytes[oldId]).toBe(exactLimit);
expect(renamed.megaDebridDisabledAccountIds).toEqual([newId]);
expect(renamed.megaDebridAccountDailyLimitBytes[newId]).toBe(exactLimit);
expect(renamed.megaDebridAccountDailyUsageBytes[newId]).toBeUndefined();
expect(renamed.megaDebridAccountTotalUsageBytes[newId]).toBeUndefined();
expect(unchanged.dailyLimitBytes).toBe(exactLimit);
expect(unchanged.secret).toBe("");
expect(renamed.identity).toBe(newLogin);
expect(renamed.secret).toBe("");
});
});
@@ -468,7 +464,7 @@ describe("settings views", () => {
it("offers animated language and bounded history retention choices", () => {
const form = buildSettingsFormViewModel({
settings: defaultSettings(),
settings: { ...createRendererSettings(defaultSettings()), archivePasswordList: "", notifyUrl: "" },
section: "allgemein",
speedLimitInput: "0",
scheduleSpeedInputs: {}
@@ -912,9 +908,10 @@ describe("settings App integration", () => {
megaCredentials: "first@example.test:first-secret\nsecond@example.test:second-secret",
debridLinkApiKeys: "existing-debrid-link-key"
};
const megaDialog = createAccountDialogState("create", "megadebrid-api", settings);
const rendererSettings = createRendererSettings(settings);
const megaDialog = createAccountDialogState("create", "megadebrid-api", rendererSettings);
const megaFields = buildAccountAddFields(megaDialog);
const debridLinkFields = buildAccountAddFields(createAccountDialogState("create", "debridlink-api", settings));
const debridLinkFields = buildAccountAddFields(createAccountDialogState("create", "debridlink-api", rendererSettings));
expect(megaDialog.megaNewLogin).toBe("");
expect(megaDialog.megaNewPassword).toBe("");
+13 -14
View File
@@ -1,8 +1,6 @@
import React, { type ReactElement } from "react";
import { describe, expect, it } from "vitest";
import { App } from "../src/renderer/App";
import { parseDebridLinkApiKeys } from "../src/shared/debrid-link-keys";
import { getMegaDebridAccountId } from "../src/shared/mega-debrid-accounts";
import type { ElectronApi } from "../src/shared/preload-api";
import * as visualFixtures from "./visual/fixtures";
import * as visualMain from "./visual/main";
@@ -136,11 +134,12 @@ describe("visual fixtures", () => {
it("aligns dense account table values with credential-derived account IDs", async () => {
const dense = createVisualFixture("dense");
const settings = dense.snapshot.settings;
const megaAccountId = getMegaDebridAccountId(settings.megaLogin);
const debridLinkKeys = parseDebridLinkApiKeys(settings.debridLinkApiKeys);
const megaAccount = dense.snapshot.accounts.find((account) => account.kind === "megadebrid-api");
const debridLinkKeys = dense.snapshot.accounts.filter((account) => account.kind === "debridlink-api");
const megaAccountId = megaAccount?.accountId || "";
expect(megaAccountId).toBe("mda_2f92guyzhdf6j");
expect(debridLinkKeys.map((entry) => entry.id)).toEqual([
expect(debridLinkKeys.map((entry) => entry.accountId)).toEqual([
"dlk_1ix5qlyx6mtm1",
"dlk_1ix5pfvlg4nkg"
]);
@@ -152,23 +151,23 @@ describe("visual fixtures", () => {
);
for (const entry of debridLinkKeys) {
expect(settings.debridAccountStatuses[entry.id]?.valid).toBe(true);
expect(settings.debridLinkApiKeyDailyLimitBytes[entry.id]).toBeGreaterThan(0);
expect(settings.debridLinkApiKeyDailyUsageBytes[entry.id]).toBeGreaterThan(0);
expect(settings.debridLinkApiKeyDailyUsageBytes[entry.id]).toBeLessThan(
settings.debridLinkApiKeyDailyLimitBytes[entry.id]
expect(settings.debridAccountStatuses[entry.accountId]?.valid).toBe(true);
expect(settings.debridLinkApiKeyDailyLimitBytes[entry.accountId]).toBeGreaterThan(0);
expect(settings.debridLinkApiKeyDailyUsageBytes[entry.accountId]).toBeGreaterThan(0);
expect(settings.debridLinkApiKeyDailyUsageBytes[entry.accountId]).toBeLessThan(
settings.debridLinkApiKeyDailyLimitBytes[entry.accountId]
);
expect(settings.debridLinkApiKeyTotalUsageBytes[entry.id]).toBeGreaterThan(
settings.debridLinkApiKeyDailyUsageBytes[entry.id]
expect(settings.debridLinkApiKeyTotalUsageBytes[entry.accountId]).toBeGreaterThan(
settings.debridLinkApiKeyDailyUsageBytes[entry.accountId]
);
}
const debridLinkItem = Object.values(dense.snapshot.session.items).find(
(item) => item.provider === "debridlink"
);
expect(debridLinkItem?.providerAccountId).toBe(debridLinkKeys[0].id);
expect(debridLinkItem?.providerAccountId).toBe(debridLinkKeys[0].accountId);
const hostLimits = await createVisualElectronApi(dense).getDebridLinkHostLimits();
expect(hostLimits[0]?.keyId).toBe(debridLinkKeys[0].id);
expect(hostLimits[0]?.keyId).toBe(debridLinkKeys[0].accountId);
});
it("stores every mutable bridge state inside the visual fixture", async () => {
+5 -3
View File
@@ -8,6 +8,7 @@ import type {
} from "../../src/shared/types";
import { parseDebridLinkApiKeys } from "../../src/shared/debrid-link-keys";
import { getMegaDebridAccountId } from "../../src/shared/mega-debrid-accounts";
import { createRendererState } from "../../src/main/renderer-state";
export const VISUAL_SCENARIOS = ["empty", "dense", "update"] as const;
@@ -229,8 +230,9 @@ function createSettings(): AppSettings {
}
function createEmptySnapshot(): UiSnapshot {
const renderer = createRendererState(createSettings());
return {
settings: createSettings(),
...renderer,
session: {
version: 1,
packageOrder: [],
@@ -276,7 +278,7 @@ function createEmptySnapshot(): UiSnapshot {
function createDenseSnapshot(): UiSnapshot {
const snapshot = createEmptySnapshot();
const debridLinkKeys = parseDebridLinkApiKeys(snapshot.settings.debridLinkApiKeys);
const debridLinkKeys = snapshot.accounts.filter((account) => account.kind === "debridlink-api");
snapshot.session = {
version: 1,
packageOrder: ["visual-package-active", "visual-package-complete", "visual-package-failed"],
@@ -359,7 +361,7 @@ function createDenseSnapshot(): UiSnapshot {
url: "https://ddownload.com/visual-active-2",
provider: "debridlink",
providerLabel: "Debrid-Link",
providerAccountId: debridLinkKeys[0].id,
providerAccountId: debridLinkKeys[0].accountId,
providerAccountLabel: "Debrid-Link Key 1",
status: "queued",
retries: 0,
+23 -13
View File
@@ -1,6 +1,5 @@
import type { ElectronApi } from "../../src/shared/preload-api";
import type { AppSettings, HistoryEntry } from "../../src/shared/types";
import { parseDebridLinkApiKeys } from "../../src/shared/debrid-link-keys";
import type { HistoryEntry, RendererSettings, RendererSettingsUpdate } from "../../src/shared/types";
import type { VisualFixture } from "./fixtures";
const stableNoopUnsubscribe = (): void => {};
@@ -15,8 +14,9 @@ export function createVisualElectronApi(
): ElectronApi {
const historyState = new URLSearchParams(search).get("history-state");
let historyRequestCount = 0;
const updateSettings = (settings: Partial<AppSettings>): AppSettings => {
Object.assign(fixture.snapshot.settings, settings);
const updateSettings = (settings: RendererSettingsUpdate): RendererSettings => {
const { archivePasswordList: _archivePasswordList, notifyUrl: _notifyUrl, ...safe } = settings;
Object.assign(fixture.snapshot.settings, safe);
return clone(fixture.snapshot.settings);
};
@@ -35,6 +35,10 @@ export function createVisualElectronApi(
fixture.snapshot.settings.debridLinkApiKeyDailyUsageBytes[keyId] = 0;
return clone(fixture.snapshot.settings);
},
createAccount: async () => ({ accountId: null, settings: clone(fixture.snapshot.settings), accounts: clone(fixture.snapshot.accounts) }),
replaceAccount: async () => ({ accountId: null, settings: clone(fixture.snapshot.settings), accounts: clone(fixture.snapshot.accounts) }),
updateAccountSecret: async () => ({ accountId: null, settings: clone(fixture.snapshot.settings), accounts: clone(fixture.snapshot.accounts) }),
deleteAccount: async () => ({ accountId: null, settings: clone(fixture.snapshot.settings), accounts: clone(fixture.snapshot.accounts) }),
addLinks: async () => ({ addedPackages: 0, addedLinks: 0, invalidCount: 0 }),
addContainers: async () => ({ addedPackages: 0, addedLinks: 0 }),
getStartConflicts: async () => [],
@@ -291,10 +295,11 @@ export function createVisualElectronApi(
note: "Visual host status"
}),
getDebridLinkHostLimits: async () => {
const primaryKey = parseDebridLinkApiKeys(fixture.snapshot.settings.debridLinkApiKeys)[0];
const primaryKey = fixture.snapshot.accounts.find((account) => account.kind === "debridlink-api");
if (!primaryKey) return [];
return [{
keyId: primaryKey.id,
keyLabel: primaryKey.label,
keyId: primaryKey.accountId,
keyLabel: "Key 1",
host: "ddownload.com",
fetchedAt: 1786312800000,
trafficCurrentBytes: 53687091200,
@@ -314,12 +319,17 @@ export function createVisualElectronApi(
}];
},
checkDebridAccounts: async () => clone(Object.values(fixture.snapshot.settings.debridAccountStatuses)),
checkMegaDebridAccount: async () => {
const status = Object.values(fixture.snapshot.settings.debridAccountStatuses).find(
(entry) => entry.provider === "megadebrid"
);
return status ? clone(status) : null;
},
checkAccountCredentials: async (input) => clone(fixture.snapshot.accounts.find((account) => account.accountId === input.accountId)?.status || {
accountId: input.accountId || "visual-account",
provider: input.kind === "debridlink-api" ? "debridlink" : "megadebrid",
label: "Visual Account",
maskedLogin: "vi***al",
valid: true,
isPremium: true,
premiumUntilMs: null,
message: "Premium aktiv",
checkedAt: 1786312800000
}),
retryExtraction: async (packageId) => {
const entry = fixture.snapshot.session.packages[packageId];
if (entry) {