[glm-grade=B] fix: dead dashboard WS, corrupted error.log, auth-polling storm, re-auth freeze + CVE bumps
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s

Adversarial audit 2026-08-16 (GLM-5.3 delegate, 2 rounds, 141 tool calls):

P0-1: Dashboard WebSocket (/api/v1/ws) dead on EVERY boot since DC-076.
server.js passed module exports (DependencyManager class, {AutoRestartManager}
namespace, SSLMonitor class) instead of createApp()'s live instances — first
.on() threw ERR_INVALID_ARG_TYPE, catch swallowed it. Fix: app.locals.ctx
exposed in src/app.js; server.js passes all 8 real EventEmitter instances.

P0-2: error.log corrupted since 2026-07-14. errorMiddleware called
logError(FILE, SIZE, path, err, meta) — 5 args into a 3-arg wrapper —
logging 'Error: 5242880' garbage every ~60s and DISCARDING the real error
object. Fix: correct 3-arg call + legacy-shape guard in logErrorWrapper +
~74 log.error sites swept to pass real error objects (AST-verified scope-
safe 71/71, 29/29 modules load clean).

P0-3: auth-polling storm (stranded grade=B commit never landed in prod):
401/403 behind TOTP gate hammered /api/v1/services/status + SSE reconnect
every 2-8s, with misleading direct-probe fallback marking services 'up'.
Fix landed + B-round MEDIUM follow-up: TOTP re-auth success now clears
_dcAuthLost, resumes SSE (new _sseResume clears the latch), and refreshes.

Also: eslintignore static-sites/ (33→0 errors); nodemailer 8→9.0.5 and
sharp 0.33→0.35.3 (3 high CVEs killed; jest green on new majors);
dockerode@5/uuid deferred (semver-major, Docker API surface).

Verification: 80/80 suites, 1837/1837 tests; ESLint 0 errors/743 warnings;
node --check all changed files; bundles rebuilt + SW cache bumped.

Judges: Codex quota-dead until Aug 19 (verified live) — GLM adversarial
delegate per operator directive 2026-08-07. Round 1: 98-call mechanical
verification (timed out pre-verdict). Round 2 (this grade): B, one MEDIUM
(re-auth freeze) — fixed in this commit as prescribed.
This commit is contained in:
Krystie committed 2026-08-16 04:18:07 -07:00
1 parent 295c63ce94
commit e99413150e
39 files changed
+533 -355

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ coverage/
dist/
build/
*.min.js
static-sites/
+270 -159
View File
@@ -19,13 +19,13 @@
"js-yaml": "^4.1.1",
"jsonwebtoken": "^9.0.2",
"lru-cache": "^10.4.3",
"nodemailer": "^8.0.4",
"nodemailer": "^9.0.5",
"otplib": "^12.0.1",
"pdfkit": "^0.15.2",
"png-to-ico": "^2.1.8",
"proper-lockfile": "^4.1.2",
"qrcode": "^1.5.3",
"sharp": "^0.33.5",
"sharp": "^0.35.3",
"ssh2-sftp-client": "^11.0.0",
"validator": "^13.11.0",
"webdav": "^5.7.1",
@@ -564,9 +564,9 @@
}
},
"node_modules/@emnapi/runtime": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.8.1.tgz",
"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==",
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"license": "MIT",
"optional": true,
"dependencies": {
@@ -771,10 +771,19 @@
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@img/colour": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
"integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.3.tgz",
"integrity": "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==",
"cpu": [
"arm64"
],
@@ -784,19 +793,19 @@
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.0.4"
"@img/sharp-libvips-darwin-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-darwin-x64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz",
"integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.3.tgz",
"integrity": "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==",
"cpu": [
"x64"
],
@@ -806,19 +815,38 @@
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.0.4"
"@img/sharp-libvips-darwin-x64": "1.3.2"
}
},
"node_modules/@img/sharp-freebsd-wasm32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.3.tgz",
"integrity": "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==",
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"dependencies": {
"@img/sharp-wasm32": "0.35.3"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz",
"integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.2.tgz",
"integrity": "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==",
"cpu": [
"arm64"
],
@@ -832,9 +860,9 @@
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz",
"integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.2.tgz",
"integrity": "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==",
"cpu": [
"x64"
],
@@ -848,9 +876,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz",
"integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.2.tgz",
"integrity": "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==",
"cpu": [
"arm"
],
@@ -864,9 +892,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-arm64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz",
"integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.2.tgz",
"integrity": "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==",
"cpu": [
"arm64"
],
@@ -879,10 +907,42 @@
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.2.tgz",
"integrity": "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==",
"cpu": [
"ppc64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-riscv64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.2.tgz",
"integrity": "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==",
"cpu": [
"riscv64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz",
"integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.2.tgz",
"integrity": "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==",
"cpu": [
"s390x"
],
@@ -896,9 +956,9 @@
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
"integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz",
"integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==",
"cpu": [
"x64"
],
@@ -912,9 +972,9 @@
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz",
"integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.2.tgz",
"integrity": "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==",
"cpu": [
"arm64"
],
@@ -928,9 +988,9 @@
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz",
"integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==",
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz",
"integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==",
"cpu": [
"x64"
],
@@ -944,9 +1004,9 @@
}
},
"node_modules/@img/sharp-linux-arm": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz",
"integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.3.tgz",
"integrity": "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==",
"cpu": [
"arm"
],
@@ -956,19 +1016,19 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm": "1.0.5"
"@img/sharp-libvips-linux-arm": "1.3.2"
}
},
"node_modules/@img/sharp-linux-arm64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz",
"integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.3.tgz",
"integrity": "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==",
"cpu": [
"arm64"
],
@@ -978,19 +1038,63 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.0.4"
"@img/sharp-libvips-linux-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-ppc64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.3.tgz",
"integrity": "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==",
"cpu": [
"ppc64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-ppc64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-riscv64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.3.tgz",
"integrity": "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==",
"cpu": [
"riscv64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-riscv64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-s390x": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz",
"integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.3.tgz",
"integrity": "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==",
"cpu": [
"s390x"
],
@@ -1000,19 +1104,19 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.0.4"
"@img/sharp-libvips-linux-s390x": "1.3.2"
}
},
"node_modules/@img/sharp-linux-x64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz",
"integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz",
"integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==",
"cpu": [
"x64"
],
@@ -1022,19 +1126,19 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.0.4"
"@img/sharp-libvips-linux-x64": "1.3.2"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz",
"integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.3.tgz",
"integrity": "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==",
"cpu": [
"arm64"
],
@@ -1044,19 +1148,19 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.0.4"
"@img/sharp-libvips-linuxmusl-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz",
"integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz",
"integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==",
"cpu": [
"x64"
],
@@ -1066,38 +1170,73 @@
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-x64": "1.0.4"
"@img/sharp-libvips-linuxmusl-x64": "1.3.2"
}
},
"node_modules/@img/sharp-wasm32": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz",
"integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==",
"cpu": [
"wasm32"
],
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz",
"integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==",
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
"@emnapi/runtime": "^1.2.0"
"@emnapi/runtime": "^1.11.1"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-webcontainers-wasm32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.3.tgz",
"integrity": "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==",
"cpu": [
"wasm32"
],
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/sharp-wasm32": "0.35.3"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-arm64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.3.tgz",
"integrity": "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==",
"cpu": [
"arm64"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-ia32": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz",
"integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.3.tgz",
"integrity": "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==",
"cpu": [
"ia32"
],
@@ -1107,16 +1246,16 @@
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": "^20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-x64": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz",
"integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==",
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.3.tgz",
"integrity": "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==",
"cpu": [
"x64"
],
@@ -1126,7 +1265,7 @@
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
@@ -2623,19 +2762,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
"integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1",
"color-string": "^1.9.0"
},
"engines": {
"node": ">=12.5.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -2654,16 +2780,6 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"license": "MIT",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -6002,9 +6118,9 @@
}
},
"node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -6127,9 +6243,9 @@
}
},
"node_modules/nodemailer": {
"version": "8.0.11",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.11.tgz",
"integrity": "sha512-nrO/pDAUKl+wXX+lx16tDLbnm0fW6sK/x8mgohaCpg+CdCEl482bD4tCuAZk2DyliruiNTIZxRCoWkDqJEnAiA==",
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.5.tgz",
"integrity": "sha512-wvjiKvjczmsN7U/8006JOdXubgBk2XFAbioDMbT+sM7cPs0QrhJTa6KBRX7P5REGGkDcLUz/EarWidb8G8C1jQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
@@ -7242,48 +7358,58 @@
"license": "ISC"
},
"node_modules/sharp": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",
"integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==",
"hasInstallScript": true,
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz",
"integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==",
"license": "Apache-2.0",
"dependencies": {
"color": "^4.2.3",
"detect-libc": "^2.0.3",
"semver": "^7.6.3"
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
"semver": "^7.8.5"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-darwin-arm64": "0.33.5",
"@img/sharp-darwin-x64": "0.33.5",
"@img/sharp-libvips-darwin-arm64": "1.0.4",
"@img/sharp-libvips-darwin-x64": "1.0.4",
"@img/sharp-libvips-linux-arm": "1.0.5",
"@img/sharp-libvips-linux-arm64": "1.0.4",
"@img/sharp-libvips-linux-s390x": "1.0.4",
"@img/sharp-libvips-linux-x64": "1.0.4",
"@img/sharp-libvips-linuxmusl-arm64": "1.0.4",
"@img/sharp-libvips-linuxmusl-x64": "1.0.4",
"@img/sharp-linux-arm": "0.33.5",
"@img/sharp-linux-arm64": "0.33.5",
"@img/sharp-linux-s390x": "0.33.5",
"@img/sharp-linux-x64": "0.33.5",
"@img/sharp-linuxmusl-arm64": "0.33.5",
"@img/sharp-linuxmusl-x64": "0.33.5",
"@img/sharp-wasm32": "0.33.5",
"@img/sharp-win32-ia32": "0.33.5",
"@img/sharp-win32-x64": "0.33.5"
"@img/sharp-darwin-arm64": "0.35.3",
"@img/sharp-darwin-x64": "0.35.3",
"@img/sharp-freebsd-wasm32": "0.35.3",
"@img/sharp-libvips-darwin-arm64": "1.3.2",
"@img/sharp-libvips-darwin-x64": "1.3.2",
"@img/sharp-libvips-linux-arm": "1.3.2",
"@img/sharp-libvips-linux-arm64": "1.3.2",
"@img/sharp-libvips-linux-ppc64": "1.3.2",
"@img/sharp-libvips-linux-riscv64": "1.3.2",
"@img/sharp-libvips-linux-s390x": "1.3.2",
"@img/sharp-libvips-linux-x64": "1.3.2",
"@img/sharp-libvips-linuxmusl-arm64": "1.3.2",
"@img/sharp-libvips-linuxmusl-x64": "1.3.2",
"@img/sharp-linux-arm": "0.35.3",
"@img/sharp-linux-arm64": "0.35.3",
"@img/sharp-linux-ppc64": "0.35.3",
"@img/sharp-linux-riscv64": "0.35.3",
"@img/sharp-linux-s390x": "0.35.3",
"@img/sharp-linux-x64": "0.35.3",
"@img/sharp-linuxmusl-arm64": "0.35.3",
"@img/sharp-linuxmusl-x64": "0.35.3",
"@img/sharp-webcontainers-wasm32": "0.35.3",
"@img/sharp-win32-arm64": "0.35.3",
"@img/sharp-win32-ia32": "0.35.3",
"@img/sharp-win32-x64": "0.35.3"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/sharp/node_modules/semver": {
"version": "7.7.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
"integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -7393,21 +7519,6 @@
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"license": "ISC"
},
"node_modules/simple-swizzle": {
"version": "0.2.4",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz",
"integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==",
"license": "MIT",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/simple-swizzle/node_modules/is-arrayish": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz",
"integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==",
"license": "MIT"
},
"node_modules/sisteransi": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
+2 -2
View File
@@ -33,13 +33,13 @@
"js-yaml": "^4.1.1",
"jsonwebtoken": "^9.0.2",
"lru-cache": "^10.4.3",
"nodemailer": "^8.0.4",
"nodemailer": "^9.0.5",
"otplib": "^12.0.1",
"pdfkit": "^0.15.2",
"png-to-ico": "^2.1.8",
"proper-lockfile": "^4.1.2",
"qrcode": "^1.5.3",
"sharp": "^0.33.5",
"sharp": "^0.35.3",
"ssh2-sftp-client": "^11.0.0",
"validator": "^13.11.0",
"webdav": "^5.7.1",
+3 -3
View File
@@ -95,7 +95,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
log.info('deploy', 'DashCA: For full features, copy certificate files to ' + destPath);
log.info('deploy', 'DashCA: Static site deployment completed successfully');
} catch (error) {
log.error('deploy', 'DashCA deployment error', { error: error.message });
log.error('deploy', error, null, { note: 'DashCA deployment error' });
throw new Error(`DashCA deployment failed: ${error.message}`);
}
}
@@ -231,7 +231,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
await portLockManager.releasePorts(lockId);
log.info('deploy', 'Port locks released after error', { lockId });
} catch (releaseError) {
log.error('deploy', 'Failed to release port locks', { lockId, error: releaseError.message });
log.error('deploy', releaseError, null, { note: 'Failed to release port locks', lockId });
}
}
throw deployError;
@@ -425,7 +425,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
} catch (error) {
try { await logError('app-deploy', error, { appId, config }); } catch (_) { /* logError failure should not mask original error */ }
const msg = error?.message || String(error || 'Unknown error');
log.error('deploy', 'Deployment failed', { appId, error: msg });
log.error('deploy', error, null, { note: 'Deployment failed', appId });
const template = ctx.APP_TEMPLATES[appId];
try { ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${msg}`, 'error'); } catch (_) {}
errorResponse(res, 500, ctx.safeErrorMessage(error));
+1 -1
View File
@@ -297,7 +297,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
// P0-5 fix: was `errorResponse(res, 500, err.message)` which leaks internal
// error details (paths, stack traces, library error codes) to the client.
// Log the actual error server-side and return a generic message.
log.error('apps-revert', 'Revert failed', { error: err.message, stack: err.stack });
log.error('apps-revert', err, null, { note: 'Revert failed', stack: err.stack });
errorResponse(res, 500, 'Revert failed');
}
}, 'apps-revert'));
+1 -1
View File
@@ -148,7 +148,7 @@ module.exports = function({
}
} catch (error) {
results.caddy = `failed: ${error.message}`;
log.error('caddy', 'Caddy update error', { error: error.message });
log.error('caddy', error, null, { note: 'Caddy update error' });
}
try {
+3 -3
View File
@@ -37,7 +37,7 @@ module.exports = function({ docker, credentialManager, fetchT, log }) {
stream.on('error', () => resolve(null));
});
} catch (error) {
log.error('docker', 'Failed to get API key', { containerName, error: error.message });
log.error('docker', error, null, { note: 'Failed to get API key', containerName });
return null;
}
}
@@ -71,7 +71,7 @@ module.exports = function({ docker, credentialManager, fetchT, log }) {
stream.on('error', () => resolve(null));
});
} catch (error) {
log.error('docker', 'Failed to get Plex token', { error: error.message });
log.error('docker', error, null, { note: 'Failed to get Plex token' });
return null;
}
}
@@ -123,7 +123,7 @@ module.exports = function({ docker, credentialManager, fetchT, log }) {
const sessionCookie = setCookie.split(';')[0];
return { cookie: sessionCookie, plexToken };
} catch (e) {
log.error('arr', 'Could not get Seerr session', { error: e.message });
log.error('arr', e, null, { note: 'Could not get Seerr session' });
return null;
}
}
+1 -1
View File
@@ -162,7 +162,7 @@ module.exports = function({ docker, log, asyncHandler, workflowEngine }) {
await newContainer.start();
} catch (startError) {
// Clean up the failed container so it doesn't block future attempts
log.error('docker', 'Failed to start new container', { containerName, error: startError.message });
log.error('docker', startError, null, { note: 'Failed to start new container', containerName });
if (newContainer) {
try { await newContainer.remove({ force: true }); } catch (e) { /* already gone */ }
}
+8 -8
View File
@@ -110,7 +110,7 @@ module.exports = function({
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
});
} catch (error) {
log.error('dns', 'Universal DNS record creation error', { error: error.message });
log.error('dns', error, null, { note: 'Universal DNS record creation error' });
errorResponse(res, safeErrorMessage(error), 500);
}
}, 'dns-universal-create'));
@@ -136,7 +136,7 @@ module.exports = function({
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
});
} catch (error) {
log.error('dns', 'Universal DNS record deletion error', { error: error.message });
log.error('dns', error, null, { note: 'Universal DNS record deletion error' });
errorResponse(res, safeErrorMessage(error), 500);
}
}, 'dns-universal-delete'));
@@ -167,7 +167,7 @@ module.exports = function({
throw new NotFoundError('No records found for domain');
}
} catch (error) {
log.error('dns', 'Universal DNS resolve error', { error: error.message });
log.error('dns', error, null, { note: 'Universal DNS resolve error' });
errorResponse(res, safeErrorMessage(error), error.statusCode || 500);
}
}, 'dns-universal-resolve'));
@@ -283,7 +283,7 @@ module.exports = function({
// Error handled by middleware
}
} catch (error) {
log.error('dns', 'DNS record creation error', { error: error.message });
log.error('dns', error, null, { note: 'DNS record creation error' });
errorResponse(res, safeErrorMessage(error), 500, { details: error.cause?.code || 'fetch failed' });
}
}, 'dns-create-record'));
@@ -328,7 +328,7 @@ module.exports = function({
// Error handled by middleware
}
} catch (error) {
log.error('dns', 'DNS resolve error', { error: error.message });
log.error('dns', error, null, { note: 'DNS resolve error' });
// Error handled by middleware
}
}, 'dns-resolve'));
@@ -465,7 +465,7 @@ module.exports = function({
});
} catch (error) {
log.error('dns', 'DNS logs proxy error', { error: error.message });
log.error('dns', error, null, { note: 'DNS logs proxy error' });
// Error handled by middleware
}
}, 'dns-logs'));
@@ -723,7 +723,7 @@ module.exports = function({
// Error handled by middleware
}
} catch (error) {
log.error('dns', 'DNS update check error', { error: error.message });
log.error('dns', error, null, { note: 'DNS update check error' });
// Error handled by middleware
}
}, 'dns-check-update'));
@@ -791,7 +791,7 @@ module.exports = function({
manualUpdateRequired: true
});
} catch (error) {
log.error('dns', 'DNS update error', { error: error.message });
log.error('dns', error, null, { note: 'DNS update error' });
// Error handled by middleware
}
}, 'dns-update'));
+1 -1
View File
@@ -165,7 +165,7 @@ async function handleExec(ws, containerId, log, auth) {
});
} catch (err) {
log.error('exec', 'Failed to start exec session', { containerId, error: err.message });
log.error('exec', err, null, { note: 'Failed to start exec session', containerId });
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify({ type: 'error', message: err.message }));
ws.close();
+1 -1
View File
@@ -149,7 +149,7 @@ module.exports = function({ docker, credentialManager: _credentialManager, servi
ok(res, response);
} catch (error) {
log.error('recipe', 'Recipe deployment failed', { recipeId, error: error.message });
log.error('recipe', error, null, { note: 'Recipe deployment failed', recipeId });
// Cleanup: remove partially deployed containers
for (const deployed of deployedComponents) {
+1 -1
View File
@@ -421,7 +421,7 @@ module.exports = function({
resyncHealthChecker?.().catch(() => {});
success(res, { message: `Service "${name}" added to dashboard` });
} catch (error) {
log.error('deploy', 'Error adding service', { error: error.message });
log.error('deploy', error, null, { note: 'Error adding service' });
if (error.message.includes('already exists')) {
errorResponse(res, safeErrorMessage(error), 409);
} else {
+1 -1
View File
@@ -46,7 +46,7 @@ module.exports = function({ asyncHandler, ok, caddy, dns, fetchT, buildDomain, a
if (!response.ok) {
const errorText = await response.text();
log.error('caddy', 'Caddy reload failed', { error: errorText });
log.error('caddy', new Error(`Caddy reload failed: ${errorText.slice(0, 500)}`));
throw new Error('Caddy reload failed. Check server logs for details.');
}
+1 -1
View File
@@ -31,7 +31,7 @@ module.exports = function({ asyncHandler, log }) {
themes[slug] = data;
}
} catch (e) {
log.error('themes', 'Failed to read themes', { error: e.message });
log.error('themes', e, null, { note: 'Failed to read themes' });
}
return themes;
}
+25 -26
View File
@@ -68,30 +68,29 @@ process.on('uncaughtException', (error) => {
attachExecWS(server, log, authManager);
log.info('server', 'WebSocket exec handler attached (auth enforced)');
// DC-076: Attach dashboard WebSocket for real-time updates
// DC-076: Attach dashboard WebSocket for real-time updates.
// createApp() returns the live manager instances — use those instead
// of re-requiring the modules (which yields singletons for some
// managers and raw classes / namespace objects for others; calling
// .on() on a class threw on every boot and silently killed the WS).
try {
const { ctx } = app.locals;
const createDashboardWS = require('./src/websocket/dashboard-ws');
const resourceMonitor = require('./src/managers/resource-monitor');
const healthChecker = require('./src/monitoring/health-checker');
const updateManager = require('./src/managers/update-manager');
const dependencyManager = require('./src/managers/dependency-manager');
const autoRestartManager = require('./src/managers/auto-restart-manager');
const configDriftDetector = require('./src/managers/config-drift-detector');
const sslMonitor = require('./src/monitoring/ssl-monitor');
createDashboardWS(server, {
resourceMonitor,
healthChecker,
updateManager,
dependencyManager,
autoRestartManager,
driftDetector: configDriftDetector,
sslMonitor,
resourceMonitor: ctx.resourceMonitor,
healthChecker: ctx.healthChecker,
updateManager: ctx.updateManager,
dependencyManager: ctx.dependencyManager,
autoRestartManager: ctx.autoRestartManager,
driftDetector: ctx.driftDetector,
sslMonitor: ctx.sslMonitor,
dnsPropagationChecker: ctx.dnsPropagationChecker,
log,
});
log.info('server', 'Dashboard WebSocket attached at /api/v1/ws');
} catch (err) {
log.error('server', 'Dashboard WebSocket failed to attach', { error: err.message });
log.error('server', err, null, { feature: 'dashboard-ws' });
}
// Start feature modules
@@ -136,7 +135,7 @@ process.on('uncaughtException', (error) => {
workflowEngine = new WorkflowEngine(workflowCtx);
log.info('server', 'Workflow engine initialized');
} catch (err) {
log.error('server', 'Workflow engine failed to initialize', { error: err.message });
log.error('server', err, null, { note: 'Workflow engine failed to initialize' });
}
}
@@ -145,7 +144,7 @@ process.on('uncaughtException', (error) => {
// Clean up stale port locks
portLockManager.cleanupStaleLocks()
.then(() => log.info('server', 'Port lock cleanup completed'))
.catch(err => log.error('server', 'Port lock cleanup failed', { error: err.message }));
.catch(err => log.error('server', err, null, { note: 'Port lock cleanup failed' }));
// Resource monitoring
try {
@@ -156,7 +155,7 @@ process.on('uncaughtException', (error) => {
}
log.info('server', 'Resource monitoring started');
} catch (err) {
log.error('server', 'Resource monitoring failed to start', { error: err.message });
log.error('server', err, null, { note: 'Resource monitoring failed to start' });
}
// Backup manager
@@ -164,7 +163,7 @@ process.on('uncaughtException', (error) => {
backupManager.start();
log.info('server', 'Backup manager started');
} catch (err) {
log.error('server', 'Backup manager failed to start', { error: err.message });
log.error('server', err, null, { note: 'Backup manager failed to start' });
}
// Security event workers (Caddy access log, fail2ban, shared_bans)
@@ -175,7 +174,7 @@ process.on('uncaughtException', (error) => {
startSecurityWorkers({ log });
log.info('server', 'Security event workers started');
} catch (err) {
log.error('server', 'Security event workers failed to start', { error: err.message });
log.error('server', err, null, { note: 'Security event workers failed to start' });
}
// Connect workflow engine to update manager for pre-update events
@@ -206,7 +205,7 @@ process.on('uncaughtException', (error) => {
healthChecker.start();
log.info('server', 'Health checker started');
} catch (err) {
log.error('server', 'Health checker failed to start', { error: err.message });
log.error('server', err, null, { note: 'Health checker failed to start' });
}
})();
@@ -215,7 +214,7 @@ process.on('uncaughtException', (error) => {
updateManager.start();
log.info('server', 'Update manager started');
} catch (err) {
log.error('server', 'Update manager failed to start', { error: err.message });
log.error('server', err, null, { note: 'Update manager failed to start' });
}
// Self-updater
@@ -234,7 +233,7 @@ process.on('uncaughtException', (error) => {
})
.catch(() => {});
} catch (err) {
log.error('server', 'Self-updater failed to start', { error: err.message });
log.error('server', err, null, { note: 'Self-updater failed to start' });
}
// Docker maintenance (optional)
@@ -257,7 +256,7 @@ process.on('uncaughtException', (error) => {
}
});
} catch (err) {
log.error('server', 'Docker maintenance failed to start', { error: err.message });
log.error('server', err, null, { note: 'Docker maintenance failed to start' });
}
}
@@ -271,7 +270,7 @@ process.on('uncaughtException', (error) => {
log.info('digest', `Daily digest generated for ${date}`);
});
} catch (err) {
log.error('server', 'Log digest failed to start', { error: err.message });
log.error('server', err, null, { note: 'Log digest failed to start' });
}
}
+10 -6
View File
@@ -318,7 +318,7 @@ async function createApp() {
const { writeJsonFile } = require('./utilities/fs-helpers');
await writeJsonFile(config.TOTP_CONFIG_FILE, totpConfig);
} catch (e) {
log.error('config', 'Could not save TOTP config', { error: e.message });
log.error('config', e, null, { note: 'Could not save TOTP config' });
}
}
@@ -437,7 +437,7 @@ async function createApp() {
ctx.workflowEngine = workflowEngine;
log.info('app', 'Workflow engine initialized');
} catch (err) {
log.error('app', 'Failed to initialize workflow engine', { error: err.message });
log.error('app', err, null, { note: 'Failed to initialize workflow engine' });
}
}
@@ -501,12 +501,12 @@ async function createApp() {
if (ctx.notification && ctx.resourceMonitor) {
ctx.resourceMonitor.on('alert', (alertData) => {
ctx.notification.sendAlert(alertData).catch(err => {
log.error('notification', 'Failed to send alert', { error: err.message });
log.error('notification', err, null, { note: 'Failed to send alert' });
});
});
ctx.resourceMonitor.on('auto-restart', (data) => {
ctx.notification.sendServiceEvent('auto-restart', data).catch(err => {
log.error('notification', 'Failed to send auto-restart notification', { error: err.message });
log.error('notification', err, null, { note: 'Failed to send auto-restart notification' });
});
});
}
@@ -514,12 +514,12 @@ async function createApp() {
if (ctx.notification && ctx.backupManager) {
ctx.backupManager.on('backup-complete', (data) => {
ctx.notification.send('backup-complete', data).catch(err => {
log.error('notification', 'Failed to send backup-complete', { error: err.message });
log.error('notification', err, null, { note: 'Failed to send backup-complete' });
});
});
ctx.backupManager.on('backup-failed', (data) => {
ctx.notification.send('backup-failed', data).catch(err => {
log.error('notification', 'Failed to send backup-failed', { error: err.message });
log.error('notification', err, null, { note: 'Failed to send backup-failed' });
});
});
}
@@ -1097,6 +1097,10 @@ async function createApp() {
app.use('/api', notFoundHandler);
app.use(errorMiddleware);
// Expose ctx on the app for entry points (server.js dashboard-WS wiring)
// without changing the returned shape for existing callers/tests.
app.locals.ctx = ctx;
return { app, log, config: config.siteConfig, licenseManager };
}
+1 -1
View File
@@ -97,7 +97,7 @@ function loadAndMigrate(configFile, log) {
raw = JSON.parse(fs.readFileSync(configFile, 'utf8'));
} catch (e) {
if (log && log.error) {
log.error('config-migration', 'Failed to parse config.json, using defaults', { error: e.message });
log.error('config-migration', e, null, { note: 'Failed to parse config.json, using defaults' });
}
raw = null;
}
+1 -1
View File
@@ -62,7 +62,7 @@ function loadSiteConfig(CONFIG_FILE, log) {
}
} catch (e) {
if (log && log.error) {
log.error('config', 'Failed to load site config', { error: e.message });
log.error('config', e, null, { note: 'Failed to load site config' });
}
}
}
+3 -3
View File
@@ -74,7 +74,7 @@ async function refreshDnsToken(username, password, server, fetchT, log) {
return { success: false, error: result.errorMessage || 'Login failed' };
} catch (error) {
log.error('dns', 'DNS token refresh error', { error: error.message });
log.error('dns', error, null, { note: 'DNS token refresh error' });
return { success: false, error: error.message };
}
}
@@ -141,7 +141,7 @@ async function ensureValidDnsToken(siteConfig, credentialManager, fetchT, log) {
return await refreshDnsToken(username, password, server || primaryIp, fetchT, log);
}
} catch (err) {
log.error('dns', 'Credential manager error', { error: err.message });
log.error('dns', err, null, { note: 'Credential manager error' });
}
return {
@@ -237,7 +237,7 @@ async function getTokenForServer(targetServer, siteConfig, credentialManager, fe
return await authenticateToServer(username, password);
}
} catch (err) {
log.error('dns', 'Credential manager error', { server: targetServer, error: err.message });
log.error('dns', err, null, { note: 'Credential manager error', server: targetServer });
}
return { success: false, error: 'No DNS credentials configured' };
+1 -1
View File
@@ -121,7 +121,7 @@ function assembleContext({
try {
fs.writeFileSync(TAILSCALE_CONFIG_FILE, JSON.stringify(meta, null, 2), 'utf8');
} catch (e) {
log.error('tailscale-coord', 'Failed to write tailscale-config.json', { error: e.message });
log.error('tailscale-coord', e, null, { note: 'Failed to write tailscale-config.json' });
}
}
async function getCoordClient() {
+1 -1
View File
@@ -103,7 +103,7 @@ function createProviderDnsContext(siteConfig, buildDomain, credentialManager, fe
}
return { success: false, error: result.errorMessage || 'Login failed' };
} catch (error) {
log.error('dns', 'DNS token refresh error', { error: error.message });
log.error('dns', error, null, { note: 'DNS token refresh error' });
return { success: false, error: error.message };
}
}
+2 -6
View File
@@ -172,9 +172,7 @@ class DNSPropagationChecker extends EventEmitter {
expectedIp,
totalTime: result.totalTime
}, 'success').catch(err => {
this.log.error('dns-propagation', 'Failed to send propagation notification', {
error: err.message
});
this.log.error('dns-propagation', err, null, { note: 'Failed to send propagation notification' });
});
}
} else {
@@ -187,9 +185,7 @@ class DNSPropagationChecker extends EventEmitter {
expectedIp,
totalTime: result.totalTime
}, 'warning').catch(err => {
this.log.error('dns-propagation', 'Failed to send timeout notification', {
error: err.message
});
this.log.error('dns-propagation', err, null, { note: 'Failed to send timeout notification' });
});
}
}
@@ -118,7 +118,7 @@ class TechnitiumDNSProvider extends BaseDNSProvider {
return await this._doLogin(username, password);
}
} catch (err) {
log.error('technitium', 'Global credential error', { error: err.message });
log.error('technitium', err, null, { note: 'Global credential error' });
}
return {
@@ -164,7 +164,7 @@ class TechnitiumDNSProvider extends BaseDNSProvider {
return { success: false, error: result.errorMessage || 'Login failed' };
} catch (error) {
log.error('technitium', 'Login error', { error: error.message });
log.error('technitium', error, null, { note: 'Login error' });
return { success: false, error: error.message };
}
}
@@ -363,7 +363,7 @@ class TechnitiumDNSProvider extends BaseDNSProvider {
const parsed = this._parseLogText(logText, limit);
return { success: true, logs: parsed };
} catch (error) {
log.error('technitium', 'Failed to fetch DNS logs', { error: error.message });
log.error('technitium', error, null, { note: 'Failed to fetch DNS logs' });
throw new Error(`Failed to get DNS logs: ${error.message}`);
}
}
@@ -449,7 +449,7 @@ class TechnitiumDNSProvider extends BaseDNSProvider {
throw new Error(result.errorMessage || 'Restart failed');
} catch (error) {
log.error('technitium', 'DNS restart error', { error: error.message });
log.error('technitium', error, null, { note: 'DNS restart error' });
throw new Error(`Failed to restart DNS server: ${error.message}`);
}
}
@@ -483,7 +483,7 @@ class TechnitiumDNSProvider extends BaseDNSProvider {
throw new Error(result.errorMessage || 'Update check failed');
} catch (error) {
log.error('technitium', 'Update check error', { error: error.message });
log.error('technitium', error, null, { note: 'Update check error' });
throw new Error(`Failed to check for updates: ${error.message}`);
}
}
@@ -86,7 +86,7 @@ class AutoRestartManager extends EventEmitter {
}
this.log.info('auto-restart', 'Policies loaded', { count: this.policies.size });
} catch (err) {
this.log.error('auto-restart', 'Failed to load policies', { error: err.message });
this.log.error('auto-restart', err, null, { note: 'Failed to load policies' });
}
// Listen to health checker status transitions
@@ -246,7 +246,7 @@ class AutoRestartManager extends EventEmitter {
...eventData,
});
} catch (notifErr) {
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
this.log.error('auto-restart', notifErr, null, { note: 'Notification failed' });
}
return { action: 'max-reached', ...eventData };
@@ -312,7 +312,7 @@ class AutoRestartManager extends EventEmitter {
...successData,
});
} catch (notifErr) {
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
this.log.error('auto-restart', notifErr, null, { note: 'Notification failed' });
}
this.log.info('auto-restart', 'Container restarted', {
@@ -349,7 +349,7 @@ class AutoRestartManager extends EventEmitter {
...failData,
});
} catch (notifErr) {
this.log.error('auto-restart', 'Notification failed', { error: notifErr.message });
this.log.error('auto-restart', notifErr, null, { note: 'Notification failed' });
}
this.log.error('auto-restart', 'Restart failed', {
@@ -478,7 +478,7 @@ class AutoRestartManager extends EventEmitter {
}
await writeJsonFile(this.policiesFile, obj);
} catch (err) {
this.log.error('auto-restart', 'Failed to save policies', { error: err.message });
this.log.error('auto-restart', err, null, { note: 'Failed to save policies' });
}
}
@@ -75,7 +75,7 @@ class ConfigDriftDetector extends EventEmitter {
const data = await this.servicesStateManager.read();
services = Array.isArray(data) ? data : (data.services || []);
} catch (err) {
this.log.error('drift', 'Failed to read services', { error: err.message });
this.log.error('drift', err, null, { note: 'Failed to read services' });
}
// Gather live Docker containers
@@ -83,7 +83,7 @@ class ConfigDriftDetector extends EventEmitter {
try {
containers = await this.docker.client.listContainers({ all: true });
} catch (err) {
this.log.error('drift', 'Failed to list containers', { error: err.message });
this.log.error('drift', err, null, { note: 'Failed to list containers' });
}
// Build lookup maps
@@ -51,7 +51,7 @@ class NotificationManager extends EventEmitter {
this.config = this._mergeConfig(DEFAULT_CONFIG, data);
}
} catch (error) {
this.log.error('notification', 'Failed to load config', { error: error.message });
this.log.error('notification', error, null, { note: 'Failed to load config' });
}
}
@@ -89,7 +89,7 @@ class NotificationManager extends EventEmitter {
fs.writeFileSync(this.NOTIFICATIONS_FILE, JSON.stringify(this.config, null, 2));
return true;
} catch (error) {
this.log.error('notification', 'Failed to save config', { error: error.message });
this.log.error('notification', error, null, { note: 'Failed to save config' });
throw error;
}
}
@@ -429,7 +429,7 @@ class NotificationManager extends EventEmitter {
const interval = (this.config.healthCheck?.intervalMinutes || 5) * 60 * 1000;
this.healthDaemonInterval = setInterval(() => {
this.checkHealth().catch(err => {
this.log.error('notification', 'Health check failed', { error: err.message });
this.log.error('notification', err, null, { note: 'Health check failed' });
});
}, interval);
@@ -488,7 +488,7 @@ class NotificationManager extends EventEmitter {
lastCheck: this.config.healthCheck.lastCheck
};
} catch (error) {
this.log.error('notification', 'Health check error', { error: error.message });
this.log.error('notification', error, null, { note: 'Health check error' });
throw error;
}
}
@@ -331,7 +331,7 @@ class DiskSpaceMonitor extends EventEmitter {
result.error = err.message;
result.completedAt = new Date().toISOString();
if (this.log) {
this.log.error('disk', 'Disk cleanup failed', { error: err.message, level });
this.log.error('disk', err, null, { note: 'Disk cleanup failed', level });
}
return result;
}
+5 -5
View File
@@ -143,7 +143,7 @@ class SSLMonitor extends EventEmitter {
try {
servicesData = await this.ctx.servicesStateManager.read();
} catch (err) {
this.log.error('ssl-monitor', 'Failed to read services', { error: err.message });
this.log.error('ssl-monitor', err, null, { note: 'Failed to read services' });
return this.getStatus();
}
@@ -212,13 +212,13 @@ class SSLMonitor extends EventEmitter {
// Initial check (non-blocking)
this.checkAll().catch(err => {
this.log.error('ssl-monitor', 'Initial SSL check failed', { error: err.message });
this.log.error('ssl-monitor', err, null, { note: 'Initial SSL check failed' });
});
// Schedule periodic checks
this.intervalHandle = setInterval(() => {
this.checkAll().catch(err => {
this.log.error('ssl-monitor', 'Periodic SSL check failed', { error: err.message });
this.log.error('ssl-monitor', err, null, { note: 'Periodic SSL check failed' });
});
}, this.config.intervalMs);
@@ -299,7 +299,7 @@ class SSLMonitor extends EventEmitter {
clearInterval(this.intervalHandle);
this.intervalHandle = setInterval(() => {
this.checkAll().catch(err => {
this.log.error('ssl-monitor', 'Periodic SSL check failed', { error: err.message });
this.log.error('ssl-monitor', err, null, { note: 'Periodic SSL check failed' });
});
}, this.config.intervalMs);
}
@@ -355,7 +355,7 @@ class SSLMonitor extends EventEmitter {
validTo: certResult.validTo
}, level <= THRESHOLDS.CRITICAL ? 'error' : 'warning');
} catch (err) {
this.log.error('ssl-monitor', 'Failed to send SSL notification', { error: err.message });
this.log.error('ssl-monitor', err, null, { note: 'Failed to send SSL notification' });
}
}
} else if (level === null) {
+1 -1
View File
@@ -81,7 +81,7 @@ class PluginManager extends EventEmitter {
workflowActions: [...this.workflowActions.keys()],
});
} catch (err) {
this.log.error('plugins', 'Failed to scan plugin directory', { error: err.message });
this.log.error('plugins', err, null, { note: 'Failed to scan plugin directory' });
this.loaded = true; // Don't crash — just run without plugins
}
}
+1 -8
View File
@@ -7,15 +7,9 @@
* ./error-logger.js and its ./error.log file have been retired.
*/
const path = require('path');
const { AppError } = require('./errors');
const { LIMITS } = require('./constants');
const { logError: unifiedLogError, safeErrorMessage } = require('../utils/logging');
const { errorResponse } = require('../utils/responses');
const platformPaths = require('../../platform-paths');
const ERROR_LOG_FILE = process.env.ERROR_LOG_FILE || path.join(platformPaths.dataDir, 'error.log');
const MAX_ERROR_LOG_SIZE = LIMITS.ERROR_LOG_SIZE;
/**
* Global error handling middleware
@@ -24,11 +18,10 @@ const MAX_ERROR_LOG_SIZE = LIMITS.ERROR_LOG_SIZE;
function errorMiddleware(err, req, res, next) {
// Log all errors with request context (unified, same file the rest of the app uses)
unifiedLogError(
ERROR_LOG_FILE,
MAX_ERROR_LOG_SIZE,
req.path,
err,
{
req,
method: req.method,
ip: req.ip,
userId: req.user?.id,
@@ -228,7 +228,7 @@ async function syncHealthCheckerServices({ log, SERVICES_FILE, servicesStateMana
log.info('health', 'Health checker synced', { added, updated, removed });
}
} catch (error) {
log.error('health', 'Error syncing health checker', { error: error.message });
log.error('health', error, null, { note: 'Error syncing health checker' });
}
}
+8
View File
@@ -417,6 +417,14 @@ function safeErrorMessage(error) {
// Supports: logError(context, error, extra) → existing route call pattern
async function logErrorWrapper(ctx, err, extra) {
// Guard against legacy call shapes that used to corrupt error.log:
// the old 5-arg form logError(file, maxSize, path, err, meta) made ctx
// a file path and turned maxSize (a number) into the "error". Detect and
// normalize so the real error always reaches error.log.
if (typeof ctx === 'string' && /^\/.*\.(log|json)$/.test(ctx) && typeof err === 'number') {
// Legacy shape: (file, size, reqPath, error, meta) → shift args.
[ctx, err, extra] = [arguments[2], arguments[3], { ...arguments[4], req: undefined }];
}
const req = extra?.req;
const payload = extra ? { ...extra } : {};
if (payload.req) delete payload.req;
+89 -89
View File
@@ -1,4 +1,4 @@
(function(l){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(b,h,u={}){const y={timestamp:new Date().toISOString(),context:b,message:h instanceof Error?h.message:h,stack:h instanceof Error?h.stack:null,metadata:u};this.errors.push(y),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${b}:`,h,u)}recoverFromError(b,h){switch(this.classifyError(b)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",b,{currentStep:h}),{action:"SKIP_STEP",nextStep:h+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",b),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",b),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",b,{currentStep:h}),{action:"SKIP_STEP",nextStep:h+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",b),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",b,{currentStep:h}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(b){const h=b.message||b.toString();return h.includes("element")&&h.includes("not found")?"ELEMENT_NOT_FOUND":h.includes("storage")||h.includes("quota")?"STORAGE_UNAVAILABLE":h.includes("driver")||h.includes("undefined")?"DRIVER_NOT_LOADED":h.includes("invalid")||h.includes("validation")?"INVALID_TOOLTIP":h.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const b={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(h=>{b.byContext[h.context]=(b.byContext[h.context]||0)+1;const u=this.classifyError({message:h.message});b.byType[u]=(b.byType[u]||0)+1}),b}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const b=document.createElement("div");return b.id="onboarding-fallback",b.style.cssText=`
(function(c){"use strict";class s{constructor(){this.errors=[],this.maxErrors=50}logError(h,b,y={}){const v={timestamp:new Date().toISOString(),context:h,message:b instanceof Error?b.message:b,stack:b instanceof Error?b.stack:null,metadata:y};this.errors.push(v),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,b,y)}recoverFromError(h,b){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:b}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const b=h.message||h.toString();return b.includes("element")&&b.includes("not found")?"ELEMENT_NOT_FOUND":b.includes("storage")||b.includes("quota")?"STORAGE_UNAVAILABLE":b.includes("driver")||b.includes("undefined")?"DRIVER_NOT_LOADED":b.includes("invalid")||b.includes("validation")?"INVALID_TOOLTIP":b.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(b=>{h.byContext[b.context]=(h.byContext[b.context]||0)+1;const y=this.classifyError({message:b.message});h.byType[y]=(h.byType[y]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=`
position: fixed;
bottom: 20px;
right: 20px;
@@ -10,32 +10,32 @@
z-index: 9999;
max-width: 300px;
font-size: 14px;
`,b.innerHTML=`
`,h.innerHTML=`
<strong>Welcome to DashCaddy!</strong><br>
<p style="margin: 10px 0 0 0; font-size: 12px;">
The interactive tour is unavailable, but you can explore the dashboard freely.
Check the documentation for help getting started.
</p>
`,document.body.appendChild(b),setTimeout(()=>{b.parentNode&&b.parentNode.removeChild(b)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const b={data:{},getItem(h){return this.data[h]||null},setItem(h,u){this.data[h]=u},removeItem(h){delete this.data[h]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),b}sendToErrorTracking(b){}}l.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window),(function(){try{var a=typeof localStorage<"u"&&localStorage.getItem("dashcaddy-health-settings")||null;if(a){var f=JSON.parse(a);f.statsPollingInterval&&f.statsPollingInterval>=5&&f.statsPollingInterval<=3600&&(window.__DC_STATS_OVERRIDE=f.statsPollingInterval*1e3)}}catch{}})();const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:typeof window<"u"&&window.__DC_STATS_OVERRIDE||5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const b=await fetch("/api/v1/config");if(b.ok){const h=await b.json();if(h.tld&&(SITE.tld=h.tld.startsWith(".")?h.tld:"."+h.tld),h.dns&&(SITE.dnsIp=h.dns.ip||"",SITE.dnsPort=h.dns.port||DC.DEFAULTS.DNS_PORT),h.dnsServers&&typeof h.dnsServers=="object")for(const[y,c]of Object.entries(h.dnsServers))y!=="__proto__"&&y!=="constructor"&&y!=="prototype"&&(SITE.dnsServers[y]=c);h.configurationType&&(SITE.configurationType=h.configurationType),h.domain&&(SITE.domain=h.domain),h.defaults&&(SITE.defaults=h.defaults),h.routingMode&&(SITE.routingMode=h.routingMode),SITE.onboardingCompleted=h.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const u=document.getElementById("manage-tokens");u&&(u.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(b=>b.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const f=document.getElementById("external-proxy-ip");f&&SITE.dnsIp&&(f.value=SITE.dnsIp,f.placeholder=SITE.dnsIp)})();function buildDomain(l){return l+SITE.tld}function buildServiceUrl(l){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+l:SITE.configurationType==="public"&&SITE.domain?"https://"+l+"."+SITE.domain:"https://"+buildDomain(l)}function getDnsServerAddr(l){const a=SITE.dnsServers[l];return a?`${a.ip}:${a.port}`:buildDomain(l)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[l,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return l;return null}function renderDnsCards(){const l=document.querySelector(".top");if(!l)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const f='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',b=l.firstElementChild;a.forEach(h=>{const u=escapeHtml(h),y=escapeHtml((SITE.dnsServers[h].name||h).toUpperCase()),c=document.createElement("div");c.className="card",c.setAttribute("data-app",h),c.setAttribute("data-status","off"),c.innerHTML=`<span id="${u}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${f}</div><span class="name">${y}</span><span class="spacer"></span><span id="${u}-pill" class="badge off" data-i18n-live-status="binary">OFF</span></div><div class="response-row"><span id="${u}-time" class="response-time">--</span></div><div class="health-row" id="health-${u}"><span id="uptime-${u}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${u}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${u}-restart" class="restart-btn" data-i18n="action.restart">Restart</button><button id="${u}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${u}-open" data-i18n="action.open">OpLine truncated
`,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(b){return this.data[b]||null},setItem(b,y){this.data[b]=y},removeItem(b){delete this.data[b]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=s,console.log("[ErrorHandler] Module loaded")})(window),(function(){try{var s=typeof localStorage<"u"&&localStorage.getItem("dashcaddy-health-settings")||null;if(s){var m=JSON.parse(s);m.statsPollingInterval&&m.statsPollingInterval>=5&&m.statsPollingInterval<=3600&&(window.__DC_STATS_OVERRIDE=m.statsPollingInterval*1e3)}}catch{}})();const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:typeof window<"u"&&window.__DC_STATS_OVERRIDE||5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const b=await h.json();if(b.tld&&(SITE.tld=b.tld.startsWith(".")?b.tld:"."+b.tld),b.dns&&(SITE.dnsIp=b.dns.ip||"",SITE.dnsPort=b.dns.port||DC.DEFAULTS.DNS_PORT),b.dnsServers&&typeof b.dnsServers=="object")for(const[v,u]of Object.entries(b.dnsServers))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(SITE.dnsServers[v]=u);b.configurationType&&(SITE.configurationType=b.configurationType),b.domain&&(SITE.domain=b.domain),b.defaults&&(SITE.defaults=b.defaults),b.routingMode&&(SITE.routingMode=b.routingMode),SITE.onboardingCompleted=b.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const y=document.getElementById("manage-tokens");y&&(y.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const s=document.getElementById("edit-tld-suffix");s&&(s.textContent=SITE.tld);const m=document.getElementById("external-proxy-ip");m&&SITE.dnsIp&&(m.value=SITE.dnsIp,m.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const s=SITE.dnsServers[c];return s?`${s.ip}:${s.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,s]of Object.entries(SITE.dnsServers))if(s.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const s=Object.keys(SITE.dnsServers);if(!s.length)return;const m='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',h=c.firstElementChild;s.forEach(b=>{const y=escapeHtml(b),v=escapeHtml((SITE.dnsServers[b].name||b).toUpperCase()),u=document.createElement("div");u.className="card",u.setAttribute("data-app",b),u.setAttribute("data-status","off"),u.innerHTML=`<span id="${y}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${m}</div><span class="name">${v}</span><span class="spacer"></span><span id="${y}-pill" class="badge off" data-i18n-live-status="binary">OFF</span></div><div class="response-row"><span id="${y}-time" class="response-time">--</span></div><div class="health-row" id="health-${y}"><span id="uptime-${y}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${y}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${y}-restart" class="restart-btn" data-i18n="action.restart">Restart</button><button id="${y}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${y}-open" data-i18n="action.open">OpLine truncated
position: fixed; top: 20px; right: 20px;
background: ${u.bg}; color: ${u.fg};
background: ${y.bg}; color: ${y.fg};
padding: 16px 24px; border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,.3);
z-index: 10000; animation: slideIn 0.3s ease-out;
max-width: 400px; white-space: pre-line; font-size: 14px;
`,document.body.appendChild(y),f>0&&setTimeout(()=>y.remove(),f)}function timeAgo(l){const a=Date.now()-new Date(l).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(l,a=null){try{const f=localStorage.getItem(l);return f!==null?f:a}catch{return a}}function safeSet(l,a){try{localStorage.setItem(l,a)}catch{}}function safeRemove(l){try{localStorage.removeItem(l)}catch{}}function safeSessionGet(l,a=null){try{const f=sessionStorage.getItem(l);return f!==null?f:a}catch{return a}}function safeSessionSet(l,a){try{sessionStorage.setItem(l,a)}catch{}}function safeGetJSON(l,a=null){try{const f=localStorage.getItem(l);return f?JSON.parse(f):a}catch{return a}}function escapeHtml(l){return String(l??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(l,a){document.getElementById(l)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(l,a){var f;((f=this._handlers)[l]||(f[l]=[])).push(a)},off(l,a){this._handlers[l]=this._handlers[l]?.filter(f=>f!==a)},emit(l,a){this._handlers[l]?.forEach(f=>f(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(l){this._apps=l,window.APPS=l,DC_BUS.emit("apps:changed",l)},findApp(l){return this._apps.find(a=>a.id===l)},addApp(l){this._apps.push(l),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(l){const a=this._apps.findIndex(f=>f.id===l);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(l,a){const f=this._apps.find(b=>b.id===l);if(f){for(const[b,h]of Object.entries(a))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(f[b]=h);DC_BUS.emit("apps:changed",this._apps)}return f}};(function(){function l(){const b=document.createElement("div");return b.className="skeleton-card",b.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',b}function a(b){const h=document.getElementById("cards");if(!(!h||h.querySelector(".card"))){b=b||6;for(let u=0;u<b;u++){const y=l();h.appendChild(y),setTimeout(function(){y.classList.add("loaded")},u*60)}}}function f(){const b=document.getElementById("cards");if(b){var h=b.querySelectorAll(".skeleton-card");h.length&&(h.forEach(function(u,y){setTimeout(function(){u.style.opacity="0",u.style.transform="translateY(-10px)"},y*25)}),setTimeout(function(){h.forEach(function(u){u.parentNode&&u.remove()})},h.length*25+300))}}window.SkeletonLoader={show:a,hide:f}})(),(function(){var l="theme",a="user-themes",f="custom-theme",b=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],h=b.slice(),u=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],y=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],c=["fg-muted","hover","card-hover","base","success","error","warning"],p={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0", Line truncated
`,document.body.appendChild(v),m>0&&setTimeout(()=>v.remove(),m)}function timeAgo(c){const s=Date.now()-new Date(c).getTime();return s<6e4?"just now":s<36e5?Math.floor(s/6e4)+"m ago":s<864e5?Math.floor(s/36e5)+"h ago":Math.floor(s/864e5)+"d ago"}function safeGet(c,s=null){try{const m=localStorage.getItem(c);return m!==null?m:s}catch{return s}}function safeSet(c,s){try{localStorage.setItem(c,s)}catch{}}function safeRemove(c){try{localStorage.removeItem(c)}catch{}}function safeSessionGet(c,s=null){try{const m=sessionStorage.getItem(c);return m!==null?m:s}catch{return s}}function safeSessionSet(c,s){try{sessionStorage.setItem(c,s)}catch{}}function safeGetJSON(c,s=null){try{const m=localStorage.getItem(c);return m?JSON.parse(m):s}catch{return s}}function escapeHtml(c){return String(c??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(c,s){document.getElementById(c)||document.body.insertAdjacentHTML("beforeend",s)}const DC_BUS={_handlers:{},on(c,s){var m;((m=this._handlers)[c]||(m[c]=[])).push(s)},off(c,s){this._handlers[c]=this._handlers[c]?.filter(m=>m!==s)},emit(c,s){this._handlers[c]?.forEach(m=>m(s))}},AppState={_apps:[],getApps(){return this._apps},setApps(c){this._apps=c,window.APPS=c,DC_BUS.emit("apps:changed",c)},findApp(c){return this._apps.find(s=>s.id===c)},addApp(c){this._apps.push(c),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(c){const s=this._apps.findIndex(m=>m.id===c);return s>-1&&(this._apps.splice(s,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),s>-1},updateApp(c,s){const m=this._apps.find(h=>h.id===c);if(m){for(const[h,b]of Object.entries(s))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(m[h]=b);DC_BUS.emit("apps:changed",this._apps)}return m}};(function(){function c(){const h=document.createElement("div");return h.className="skeleton-card",h.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',h}function s(h){const b=document.getElementById("cards");if(!(!b||b.querySelector(".card"))){h=h||6;for(let y=0;y<h;y++){const v=c();b.appendChild(v),setTimeout(function(){v.classList.add("loaded")},y*60)}}}function m(){const h=document.getElementById("cards");if(h){var b=h.querySelectorAll(".skeleton-card");b.length&&(b.forEach(function(y,v){setTimeout(function(){y.style.opacity="0",y.style.transform="translateY(-10px)"},v*25)}),setTimeout(function(){b.forEach(function(y){y.parentNode&&y.remove()})},b.length*25+300))}}window.SkeletonLoader={show:s,hide:m}})(),(function(){var c="theme",s="user-themes",m="custom-theme",h=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],b=h.slice(),y=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],v=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],u=["fg-muted","hover","card-hover","base","success","error","warning"],l={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0", Line truncated
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+w.r+","+w.g+","+w.b+`, .05), transparent 55%),
radial-gradient(1200px 800px at 10% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+x.r+","+x.g+","+x.b+`, .05), transparent 55%),
var(--bg);
}
`:":root."+C+` body {
background:
radial-gradient(1200px 900px at 8% -12%, rgba(`+w.r+","+w.g+","+w.b+`, .10), transparent 60%),
radial-gradient(1000px 700px at 110% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .07), transparent 55%),
radial-gradient(1200px 900px at 8% -12%, rgba(`+x.r+","+x.g+","+x.b+`, .10), transparent 60%),
radial-gradient(1000px 700px at 110% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .07), transparent 55%),
var(--bg);
}
`}function s(C,B){var $=B.lightBg||B.bg&&i(B.bg)>.4;return $?":root."+C+` button:hover {
`}function i(C,B){var $=B.lightBg||B.bg&&d(B.bg)>.4;return $?":root."+C+` button:hover {
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
border-color: rgba(0, 0, 0, .15);
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
@@ -44,20 +44,20 @@
background: color-mix(in srgb, var(--accent) 18%, transparent);
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function n(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function r(){u.forEach(function(C){document.documentElement.style.removeProperty("--"+C)})}function g(C,B){var $=C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),b.indexOf($)!==-1&&($=$+"-custom");for(var E=safeGetJSON(a,{}),w=$,S=2;E[$]&&$!==B;)$=w+"-"+S++;return $}function m(C){var B=document.getElementById("user-theme-styles");B&&B.remove(),h.length=b.length,Object.keys(p).forEach(function(T){b.indexOf(T)===-1&&delete p[T]});var $=C||safeGetJSON(a,{}),E=Object.keys($);if(E=E.filter(function(T){return b.indexOf(T)===-1}),!!E.length){var w="";E.forEach(function(T){var k=$[T];h.indexOf(T)===-1&&h.push(T);var A={};u.forEach(function(O){k[O]&&(A[O]=k[O])}),A["card-bg"]=k["card-base"]||k.bg,k.lightBg&&(A.lightBg=!0);var D=t(A);c.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),p[T]=A,w+=":root."+T+` {
`,u.forEach(function(O){A[O]&&(w+=" --"+O+": "+A[O]+`;
`)}),w+=`}
`,w+=e(T,A),w+=s(T,A)});var S=document.createElement("style");S.id="user-theme-styles",S.textContent=w,document.head.appendChild(S)}}function x(){secureFetch("/api/v1/themes").then(function(C){return C.json()}).then(function(C){if(!(!C.success||!C.themes)){var B=C.themes,$=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(a,JSON.stringify(B)),m(B);var E=safeGet(l);E&&h.indexOf(E)!==-1&&L(E)}}}).catch(function(){})}function I(){var C=safeGetJSON(f);if(C){var B=C.name||"Custom",$=g(B),E={name:B};u.forEach(function(T){C[T]&&(E[T]=C[T])});var w=safeGetJSON(a,{});w[$]=E,safeSet(a,JSON.stringify(w)),safeGet(l)==="custom"&&safeSet(l,$),safeRemove(f);var S={};u.forEach(function(T){E[T]&&(S[T]=E[T])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:S})}).catch(function(){})}}function L(C){document.documentElement.classList.add("theme-transitioning"),h.forEach(function(w){w!=="dark"&&document.documentElement.classList.remove(w)}),r(),C!=="dark"&&document.documentElement.classList.add(C),safeSet(l,C);var B=p[C],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var E=B&&B.lightBg;!E&&B&&B.bg&&(E=i(B.bg)>.4),E?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}I(),m();var P=safeGet(l);P==="red"&&(P="black",safeSet(l,"black")),P&&P!=="dark"&&h.indexOf(P)===-1&&(P=null),L(P||n()),x(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(C){safeGet(l)||L(C.matches?"dark":"light")}),window.THEMES=h,window.BUILTIN_THEMES=b,window.THEME_COLORS=p,window.THEME_PROPS=u,window.BASE_PROPS=y,window.DERIVED_PROPS=c,window.USER_THEMES_KEY=a,window.applyTheme=L,window.clearCustomProperties=r,window.injectUserThemeStyles=m,window.syncThemesFromServer=x,window.slugifyThemeName=g,window.getActiveTheme=function(){return safeGet(l)||n()},window.deriveExtendedColors=t,window.hexToRgb=d,window.rgbToHex=o,window.blendColors=v})(),(function(){let l=null;async function a(){if(l)return l;try{const d=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!d.ok)throw new Error(`methods HTTP ${d.status}`);const o=await d.json();return l=Array.isArray(o.providers)?o.providers:[],l}catch(d){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",d),[]}}function f(d){const o=document.getElementById("totp-overlay");if(!o)return;const v=o.querySelector(".totp-card");if(!v)return;const i=v.innerHTML;v.dataset.originalBody||(v.dataset.originalBody=i);const t=d.map(e=>{const s=e.config&&(e.config.label||e.name)||e.name;return`<button class="provider-btn" data-provider="${e.name}"
`}function n(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function r(){y.forEach(function(C){document.documentElement.style.removeProperty("--"+C)})}function f(C,B){var $=C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),h.indexOf($)!==-1&&($=$+"-custom");for(var E=safeGetJSON(s,{}),x=$,S=2;E[$]&&$!==B;)$=x+"-"+S++;return $}function p(C){var B=document.getElementById("user-theme-styles");B&&B.remove(),b.length=h.length,Object.keys(l).forEach(function(T){h.indexOf(T)===-1&&delete l[T]});var $=C||safeGetJSON(s,{}),E=Object.keys($);if(E=E.filter(function(T){return h.indexOf(T)===-1}),!!E.length){var x="";E.forEach(function(T){var k=$[T];b.indexOf(T)===-1&&b.push(T);var A={};y.forEach(function(O){k[O]&&(A[O]=k[O])}),A["card-bg"]=k["card-base"]||k.bg,k.lightBg&&(A.lightBg=!0);var D=t(A);u.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),l[T]=A,x+=":root."+T+` {
`,y.forEach(function(O){A[O]&&(x+=" --"+O+": "+A[O]+`;
`)}),x+=`}
`,x+=e(T,A),x+=i(T,A)});var S=document.createElement("style");S.id="user-theme-styles",S.textContent=x,document.head.appendChild(S)}}function w(){secureFetch("/api/v1/themes").then(function(C){return C.json()}).then(function(C){if(!(!C.success||!C.themes)){var B=C.themes,$=safeGetJSON(s,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(s,JSON.stringify(B)),p(B);var E=safeGet(c);E&&b.indexOf(E)!==-1&&L(E)}}}).catch(function(){})}function I(){var C=safeGetJSON(m);if(C){var B=C.name||"Custom",$=f(B),E={name:B};y.forEach(function(T){C[T]&&(E[T]=C[T])});var x=safeGetJSON(s,{});x[$]=E,safeSet(s,JSON.stringify(x)),safeGet(c)==="custom"&&safeSet(c,$),safeRemove(m);var S={};y.forEach(function(T){E[T]&&(S[T]=E[T])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:S})}).catch(function(){})}}function L(C){document.documentElement.classList.add("theme-transitioning"),b.forEach(function(x){x!=="dark"&&document.documentElement.classList.remove(x)}),r(),C!=="dark"&&document.documentElement.classList.add(C),safeSet(c,C);var B=l[C],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var E=B&&B.lightBg;!E&&B&&B.bg&&(E=d(B.bg)>.4),E?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}I(),p();var P=safeGet(c);P==="red"&&(P="black",safeSet(c,"black")),P&&P!=="dark"&&b.indexOf(P)===-1&&(P=null),L(P||n()),w(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(C){safeGet(c)||L(C.matches?"dark":"light")}),window.THEMES=b,window.BUILTIN_THEMES=h,window.THEME_COLORS=l,window.THEME_PROPS=y,window.BASE_PROPS=v,window.DERIVED_PROPS=u,window.USER_THEMES_KEY=s,window.applyTheme=L,window.clearCustomProperties=r,window.injectUserThemeStyles=p,window.syncThemesFromServer=w,window.slugifyThemeName=f,window.getActiveTheme=function(){return safeGet(c)||n()},window.deriveExtendedColors=t,window.hexToRgb=a,window.rgbToHex=o,window.blendColors=g})(),(function(){let c=null;async function s(){if(c)return c;try{const a=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!a.ok)throw new Error(`methods HTTP ${a.status}`);const o=await a.json();return c=Array.isArray(o.providers)?o.providers:[],c}catch(a){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",a),[]}}function m(a){const o=document.getElementById("totp-overlay");if(!o)return;const g=o.querySelector(".totp-card");if(!g)return;const d=g.innerHTML;g.dataset.originalBody||(g.dataset.originalBody=d);const t=a.map(e=>{const i=e.config&&(e.config.label||e.name)||e.name;return`<button class="provider-btn" data-provider="${e.name}"
style="margin: 6px 4px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem;">
Sign in with ${s}
Sign in with ${i}
</button>`}).join(`
`);v.innerHTML=`
`);g.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<p class="subtitle">Choose how to sign in</p>
<div id="auth-gate-providers" style="margin: 14px 0 10px;">${t}</div>
<div id="auth-gate-message" style="margin-top: 8px; color: var(--muted); font-size: 0.8rem;"></div>
`,o.classList.add("show"),v.querySelectorAll(".provider-btn").forEach(e=>{e.addEventListener("click",()=>{const s=e.dataset.provider,n=d.find(r=>r.name===s);h(n)})})}function b(){const d=document.getElementById("totp-overlay");if(!d)return;const o=d.querySelector(".totp-card");!o||!o.dataset.originalBody||(o.innerHTML=o.dataset.originalBody,window.location.reload())}function h(d){const o=document.getElementById("totp-overlay");if(!o)return;const v=o.querySelector(".totp-card");if(v){if(d.name==="totp"){window.location.reload();return}if(d.name==="email"){v.innerHTML=`
`,o.classList.add("show"),g.querySelectorAll(".provider-btn").forEach(e=>{e.addEventListener("click",()=>{const i=e.dataset.provider,n=a.find(r=>r.name===i);b(n)})})}function h(){const a=document.getElementById("totp-overlay");if(!a)return;const o=a.querySelector(".totp-card");!o||!o.dataset.originalBody||(o.innerHTML=o.dataset.originalBody,window.location.reload())}function b(a){const o=document.getElementById("totp-overlay");if(!o)return;const g=o.querySelector(".totp-card");if(g){if(a.name==="totp"){window.location.reload();return}if(a.name==="email"){g.innerHTML=`
<img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
<img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
<p class="subtitle">Sign in with email</p>
@@ -75,13 +75,13 @@
<div style="margin-top: 16px;">
<a href="#" id="auth-gate-back" style="color: var(--muted); font-size: 0.8rem;">\u2190 Back</a>
</div>
`,o.classList.add("show");const i=v.querySelector("#auth-gate-email-input"),t=v.querySelector("#auth-gate-email-submit"),e=v.querySelector("#auth-gate-email-status"),s=v.querySelector("#auth-gate-back");t.addEventListener("click",async()=>{const n=(i.value||"").trim();if(!n||!n.includes("@")){e.textContent="Enter a valid email address.",e.style.color="var(--error, #d33)";return}t.disabled=!0,e.textContent="Sending\u2026",e.style.color="";try{const g=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:n})})).json();if(g.success){const m=g.deliveredVia||"email",x=g.maskedEmail||n;m==="dev-console"?e.innerHTML=`
`,o.classList.add("show");const d=g.querySelector("#auth-gate-email-input"),t=g.querySelector("#auth-gate-email-submit"),e=g.querySelector("#auth-gate-email-status"),i=g.querySelector("#auth-gate-back");t.addEventListener("click",async()=>{const n=(d.value||"").trim();if(!n||!n.includes("@")){e.textContent="Enter a valid email address.",e.style.color="var(--error, #d33)";return}t.disabled=!0,e.textContent="Sending\u2026",e.style.color="";try{const f=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:n})})).json();if(f.success){const p=f.deliveredVia||"email",w=f.maskedEmail||n;p==="dev-console"?e.innerHTML=`
Check the server logs for your one-time link.
(Dev mode: no SMTP configured. In production this would email <strong>${x}</strong>.)`:e.innerHTML=`Sign-in link sent to <strong>${x}</strong>.
Check your inbox (and spam folder).`,e.style.color="var(--success, #2a7)"}else e.textContent=g.error||"Could not send link.",e.style.color="var(--error, #d33)",t.disabled=!1}catch{e.textContent="Connection error. Try again.",e.style.color="var(--error, #d33)",t.disabled=!1}}),i.addEventListener("keydown",n=>{n.key==="Enter"&&t.click()}),s.addEventListener("click",n=>{n.preventDefault(),f(providers)});return}console.warn("[auth-gate] unknown provider",d.name),window.location.reload()}}async function u(){if(!document.getElementById("totp-overlay"))return;const o=await a();if(o.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(o.length===1&&o[0].name==="totp"){y(o[0]);return}f(o)}function y(d){const o=l&&l.find(e=>e.name==="email");if(!o){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const v=document.getElementById("totp-overlay"),i=v.querySelector(".totp-card");if(!i)return;if(i.dataset.originalBody||(i.dataset.originalBody=i.innerHTML),!i.querySelector("#auth-gate-email-alt")){const e=document.createElement("div");e.id="auth-gate-email-alt",e.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",e.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
(Dev mode: no SMTP configured. In production this would email <strong>${w}</strong>.)`:e.innerHTML=`Sign-in link sent to <strong>${w}</strong>.
Check your inbox (and spam folder).`,e.style.color="var(--success, #2a7)"}else e.textContent=f.error||"Could not send link.",e.style.color="var(--error, #d33)",t.disabled=!1}catch{e.textContent="Connection error. Try again.",e.style.color="var(--error, #d33)",t.disabled=!1}}),d.addEventListener("keydown",n=>{n.key==="Enter"&&t.click()}),i.addEventListener("click",n=>{n.preventDefault(),m(providers)});return}console.warn("[auth-gate] unknown provider",a.name),window.location.reload()}}async function y(){if(!document.getElementById("totp-overlay"))return;const o=await s();if(o.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(o.length===1&&o[0].name==="totp"){v(o[0]);return}m(o)}function v(a){const o=c&&c.find(e=>e.name==="email");if(!o){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const g=document.getElementById("totp-overlay"),d=g.querySelector(".totp-card");if(!d)return;if(d.dataset.originalBody||(d.dataset.originalBody=d.innerHTML),!d.querySelector("#auth-gate-email-alt")){const e=document.createElement("div");e.id="auth-gate-email-alt",e.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",e.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
style="color: var(--accent); text-decoration: none;">
Or sign in with email instead \u2192
</a>`,i.appendChild(e),e.querySelector("#auth-gate-email-alt-link").addEventListener("click",s=>{s.preventDefault(),h(o)})}v.classList.add("show")}window.__dc_049_handled=!0;function c(d){try{const o=new URL(d,window.location.origin);if(!["http:","https:"].includes(o.protocol))return!1;if(o.origin===window.location.origin)return!0;if(o.protocol!=="https:")return!1;const v=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return o.hostname===v.slice(1)||o.hostname.endsWith(v)}catch{return!1}}const p=new URLSearchParams(window.location.search);if(p.get("auth")==="required"){const d=p.get("return");if(d&&c(d))try{sessionStorage.setItem("totp_redirect",d)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(u,0)}window._showAuthGate=u,window._authGateMethods=a})(),(function(){function l(){const c=document.querySelector(".totp-card");if(!c)return;const d=getComputedStyle(c).backgroundColor.match(/\d+/g);if(!d)return;const o=(.299*+d[0]+.587*+d[1]+.114*+d[2])/255,v=c.querySelector(".totp-logo-dark"),i=c.querySelector(".totp-logo-light");v&&(v.style.display=o>.5?"none":""),i&&(i.style.display=o>.5?"":"none")}function a(){const c=document.getElementById("totp-overlay");if(c){c.classList.add("show"),setTimeout(l,50);const p=c.querySelector(".totp-digits input");p&&setTimeout(()=>p.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function f(){const c=document.getElementById("totp-overlay");c&&c.classList.remove("show")}function b(c,p){const d=new URL(c,window.location.origin);if(d.origin===window.location.origin)return d.toString();const o=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,v=d.hostname===o.slice(1)||d.hostname.endsWith(o);if(d.protocol!=="https:"||!v)return null;if(!p)return d.toString();const i=`${d.pathname}${d.search}${d.hash}`;return d.pathname="/dashcaddy-sso",d.search="",d.hash="",d.searchParams.set("token",p),d.searchParams.set("return",i),d.toString()}const h=document.getElementById("totp-digits");if(h){const c=h.querySelectorAll("input");c.forEach((p,d)=>{p.addEventListener("input",o=>{const v=o.target.value.replace(/\D/g,"");o.target.value=v.slice(0,1),v&&d<c.length-1&&c[d+1].focus();const i=Array.from(c).map(t=>t.value).join("");i.length===6&&u(i)}),p.addEventListener("keydown",o=>{o.key==="Backspace"&&!o.target.value&&d>0&&(c[d-1].focus(),c[d-1].value="")}),p.addEventListener("paste",o=>{o.preventDefault();const v=(o.clipboardData.getData("text")||"").replace(/\D/g,"");v.length>=6&&(c.forEach((i,t)=>{i.value=v[t]||""}),c[5].focus(),u(v.slice(0,6)))})})}async function u(c){const p=document.getElementById("totp-error");p.textContent="Verifying...",p.className="totp-error verifying";try{const o=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:c})})).json();if(o.success){p.textContent="",o.csrfToken&&(csrfToken=o.csrfToken),f();const v=safeSessionGet("totp_redirect");if(v){try{sessionStorage.removeItem("totp_redirect")}catch{}const i=b(v,o.ssoToken);if(!i)return;window.location.href=i;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{p.textContent=o.error||"Invalid code",p.className="totp-error";const v=document.querySelectorAll("#totp-digits input");v.forEach(i=>{i.value=""}),v[0]?.focus()}}catch{p.textContent="Connection error",p.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const c=urlParams.get("return");if(c)try{const p=new URL(c,window.location.origin),d=p.hostname,o=p.origin===window.location.origin,v=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,i=d.endsWith(v)||d===v.substring(1);(o||i)&&safeSessionSet("totp_redirect",c)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=a})(),(function(){"use strict";async function l(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function a(y){const c=document.getElementById("totp-recovery-link");c&&(c.style.display=y?"":"none")}function f(){const y=document.getElementById("totp-recovery-panel");y&&(y.style.display="");const c=document.getElementById("totp-recovery-status"),p=document.getElementById("totp-recovery-import"),d=document.getElementById("totp-recovery-verify");p&&(p.style.display=""),d&&(d.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",l().then(o=>{c.textContent=o.hint||"",o.status==="healthy"?c.style.borderColor="var(--ok-fg, #7ef2ff)":o.status==="unreadable"?(c.style.borderColor="var(--bad-fg, #ff9aa3)",c.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):o.status==="not_configured"?c.style.borderColor="var(--muted)"Line truncated
</a>`,d.appendChild(e),e.querySelector("#auth-gate-email-alt-link").addEventListener("click",i=>{i.preventDefault(),b(o)})}g.classList.add("show")}window.__dc_049_handled=!0;function u(a){try{const o=new URL(a,window.location.origin);if(!["http:","https:"].includes(o.protocol))return!1;if(o.origin===window.location.origin)return!0;if(o.protocol!=="https:")return!1;const g=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return o.hostname===g.slice(1)||o.hostname.endsWith(g)}catch{return!1}}const l=new URLSearchParams(window.location.search);if(l.get("auth")==="required"){const a=l.get("return");if(a&&u(a))try{sessionStorage.setItem("totp_redirect",a)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(y,0)}window._showAuthGate=y,window._authGateMethods=s})(),(function(){function c(){const u=document.querySelector(".totp-card");if(!u)return;const a=getComputedStyle(u).backgroundColor.match(/\d+/g);if(!a)return;const o=(.299*+a[0]+.587*+a[1]+.114*+a[2])/255,g=u.querySelector(".totp-logo-dark"),d=u.querySelector(".totp-logo-light");g&&(g.style.display=o>.5?"none":""),d&&(d.style.display=o>.5?"":"none")}function s(){const u=document.getElementById("totp-overlay");if(u){u.classList.add("show"),setTimeout(c,50);const l=u.querySelector(".totp-digits input");l&&setTimeout(()=>l.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function m(){const u=document.getElementById("totp-overlay");u&&u.classList.remove("show")}function h(u,l){const a=new URL(u,window.location.origin);if(a.origin===window.location.origin)return a.toString();const o=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,g=a.hostname===o.slice(1)||a.hostname.endsWith(o);if(a.protocol!=="https:"||!g)return null;if(!l)return a.toString();const d=`${a.pathname}${a.search}${a.hash}`;return a.pathname="/dashcaddy-sso",a.search="",a.hash="",a.searchParams.set("token",l),a.searchParams.set("return",d),a.toString()}const b=document.getElementById("totp-digits");if(b){const u=b.querySelectorAll("input");u.forEach((l,a)=>{l.addEventListener("input",o=>{const g=o.target.value.replace(/\D/g,"");o.target.value=g.slice(0,1),g&&a<u.length-1&&u[a+1].focus();const d=Array.from(u).map(t=>t.value).join("");d.length===6&&y(d)}),l.addEventListener("keydown",o=>{o.key==="Backspace"&&!o.target.value&&a>0&&(u[a-1].focus(),u[a-1].value="")}),l.addEventListener("paste",o=>{o.preventDefault();const g=(o.clipboardData.getData("text")||"").replace(/\D/g,"");g.length>=6&&(u.forEach((d,t)=>{d.value=g[t]||""}),u[5].focus(),y(g.slice(0,6)))})})}async function y(u){const l=document.getElementById("totp-error");l.textContent="Verifying...",l.className="totp-error verifying";try{const o=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:u})})).json();if(o.success){l.textContent="",o.csrfToken&&(csrfToken=o.csrfToken),m();const g=safeSessionGet("totp_redirect");if(g){try{sessionStorage.removeItem("totp_redirect")}catch{}const d=h(g,o.ssoToken);if(!d)return;window.location.href=d;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard(),window._dcAuthLost=!1,typeof window._sseResume=="function"?window._sseResume():typeof window._sseReconnect=="function"&&window._sseReconnect(),typeof window.refreshAll=="function"&&window.refreshAll()}else{l.textContent=o.error||"Invalid code",l.className="totp-error";const g=document.querySelectorAll("#totp-digits input");g.forEach(d=>{d.value=""}),g[0]?.focus()}}catch{l.textContent="Connection error",l.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const u=urlParams.get("return");if(u)try{const l=new URL(u,window.location.origin),a=l.hostname,o=l.origin===window.location.origin,g=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,d=a.endsWith(g)||a===g.substring(1);(o||d)&&safeSessionSet("totp_redirect",u)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=s})(),(function(){"use strict";async function c(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function s(v){const u=document.getElementById("totp-recovery-link");u&&(u.style.display=v?"":"none")}function m(){const v=document.getElementById("totp-recovery-panel");v&&(v.style.display="");const u=document.getElementById("totp-recovery-status"),l=document.getElementById("totp-recovery-import"),a=document.getElementById("totp-recovery-verify");l&&(l.style.display=""),a&&(a.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",c().then(o=>{u.textContent=o.hint||"",o.status==="healthy"?u.style.borderColor="var(--ok-fg, #7ef2ff)":o.sLine truncated
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
<h3>\u{1F4C2} Browse for Media Folders</h3>
@@ -179,7 +179,7 @@
</button>
</div>
</div>
</div>`);const a=document.getElementById("service-creds-modal");let f=null;const b=["sonarr","radarr","prowlarr","overseerr"],h=["sonarr","radarr"];function u(o){return o.externalUrl||o.url||""}function y(o){const v=document.getElementById("svc-creds-error");v.textContent=o,v.style.display=""}function c(){const o=document.getElementById("svc-creds-error");o.textContent="",o.style.display="none"}window.openServiceCredsModal=async function(o){f=o,c();const v=document.getElementById("svc-creds-title"),i=document.getElementById("svc-creds-desc"),t=document.getElementById("svc-creds-seedhost"),e=document.getElementById("svc-creds-apikey"),s=document.getElementById("svc-creds-basic"),n=document.getElementById("svc-creds-quality");v.textContent=o.name+" Credentials";const r=!!o.isExternal,g=b.includes(o.id)||b.includes(o.appTemplate),m=h.includes(o.id)||h.includes(o.appTemplate);t.style.display=r?"":"none",e.style.display=g?"":"none",n.style.display=m?"":"none",s.style.display=r?"none":"";const x=document.getElementById("svc-quality-select");x.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",r?(i.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${o.name}`):g?i.textContent="API key bypasses the app login screen automatically.":i.textContent="Credentials are injected automatically when accessing this service.",await p(o),a.classList.add("show")};async function p(o){const v=document.getElementById("svc-creds-dot"),i=document.getElementById("svc-creds-status"),t=document.getElementById("svc-creds-clear");let e=!1;if(o.isExternal){try{const r=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();r.success?(document.getElementById("svc-seedhost-user").value=r.username||"",r.hasCredentials&&(e=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const r=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();r.success&&(r.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",e=!0):document.getElementById("svc-apikey-input").value="",r.hasBasicAuth&&!o.isExternal?(document.getElementById("svc-basic-user").value=r.username||"",e=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const s=o.id||o.appTemplate;if(h.includes(s)&&await d(o),e){v.style.background="var(--ok-fg, #74dfc4)",i.style.color="var(--ok-fg, #74dfc4)",i.textContent="Credentials stored",t.style.display="";const n=document.getElementById(`creds-btn-${o.id}`);n&&n.classList.add("has-creds")}else v.style.background="var(--muted)",i.style.color="var(--muted)",i.textContent="No credentials stored",t.style.display="none"}async function d(o){const v=document.getElementById("svc-quality-select"),i=document.getElementById("svc-quality-status"),t=o.id||o.appTemplate,e=u(o);if(!e){v.innerHTML='<option value="">-- No service URL --</option>';return}v.innerHTML='<option value="">Loading...</option>',i.textContent="";try{const s=new URLSearchParams({service:t,url:e}),r=await(await fetch(`/api/v1/arr/quality-profiles?${s}`)).json();if(!r.success||!r.profiles?.length){v.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}v.innerHTML="";for(const g of r.profiles){const m=document.createElement("option");m.value=g.id,m.textContent=g.name,v.appendChild(m)}if(r.storedProfileId&&(v.value=String(r.storedProfileId)),!v.value){const g=r.profiles.find(m=>/720/i.test(m.name));g&&(v.value=String(g.id))}!v.value&&r.profiles.length&&(v.value=String(r.profiles[0].id)),i.innerHTML=`<span style="color: var(--ok-fg);">${r.profiles.length} profiles loaded</span>`}catch(s){v.innerHTML='<option value="">-- Failed to load --</option>',i.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${s.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!f)return;const o=f.id||f.appTemplate,v=u(f),t=document.getElementById("svc-apikey-input")?.value.trim(),e=document.getElementById("svc-quality-select"),s=document.getElementById("svc-quality-status");if(!v){s.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!t||t==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){s.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}e.innerHTML='<option value="">Fetching...</option>',s.textContent="";try{const n=new URLSearchParams({service:o,url:v,apiKey:t}),g=await(await fetch(`/api/v1/arr/quality-profiles?${n}`)).json();if(!g.success){e.innerHTML='<option value="">-- Error --</option>',s.innerHTML=`<span style="color: var(--error, #c62828);">${g.error||"Failed to feLine truncated
</div>`);const s=document.getElementById("service-creds-modal");let m=null;const h=["sonarr","radarr","prowlarr","overseerr"],b=["sonarr","radarr"];function y(o){return o.externalUrl||o.url||""}function v(o){const g=document.getElementById("svc-creds-error");g.textContent=o,g.style.display=""}function u(){const o=document.getElementById("svc-creds-error");o.textContent="",o.style.display="none"}window.openServiceCredsModal=async function(o){m=o,u();const g=document.getElementById("svc-creds-title"),d=document.getElementById("svc-creds-desc"),t=document.getElementById("svc-creds-seedhost"),e=document.getElementById("svc-creds-apikey"),i=document.getElementById("svc-creds-basic"),n=document.getElementById("svc-creds-quality");g.textContent=o.name+" Credentials";const r=!!o.isExternal,f=h.includes(o.id)||h.includes(o.appTemplate),p=b.includes(o.id)||b.includes(o.appTemplate);t.style.display=r?"":"none",e.style.display=f?"":"none",n.style.display=p?"":"none",i.style.display=r?"none":"";const w=document.getElementById("svc-quality-select");w.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",r?(d.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${o.name}`):f?d.textContent="API key bypasses the app login screen automatically.":d.textContent="Credentials are injected automatically when accessing this service.",await l(o),s.classList.add("show")};async function l(o){const g=document.getElementById("svc-creds-dot"),d=document.getElementById("svc-creds-status"),t=document.getElementById("svc-creds-clear");let e=!1;if(o.isExternal){try{const r=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();r.success?(document.getElementById("svc-seedhost-user").value=r.username||"",r.hasCredentials&&(e=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const r=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();r.success&&(r.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",e=!0):document.getElementById("svc-apikey-input").value="",r.hasBasicAuth&&!o.isExternal?(document.getElementById("svc-basic-user").value=r.username||"",e=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const i=o.id||o.appTemplate;if(b.includes(i)&&await a(o),e){g.style.background="var(--ok-fg, #74dfc4)",d.style.color="var(--ok-fg, #74dfc4)",d.textContent="Credentials stored",t.style.display="";const n=document.getElementById(`creds-btn-${o.id}`);n&&n.classList.add("has-creds")}else g.style.background="var(--muted)",d.style.color="var(--muted)",d.textContent="No credentials stored",t.style.display="none"}async function a(o){const g=document.getElementById("svc-quality-select"),d=document.getElementById("svc-quality-status"),t=o.id||o.appTemplate,e=y(o);if(!e){g.innerHTML='<option value="">-- No service URL --</option>';return}g.innerHTML='<option value="">Loading...</option>',d.textContent="";try{const i=new URLSearchParams({service:t,url:e}),r=await(await fetch(`/api/v1/arr/quality-profiles?${i}`)).json();if(!r.success||!r.profiles?.length){g.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}g.innerHTML="";for(const f of r.profiles){const p=document.createElement("option");p.value=f.id,p.textContent=f.name,g.appendChild(p)}if(r.storedProfileId&&(g.value=String(r.storedProfileId)),!g.value){const f=r.profiles.find(p=>/720/i.test(p.name));f&&(g.value=String(f.id))}!g.value&&r.profiles.length&&(g.value=String(r.profiles[0].id)),d.innerHTML=`<span style="color: var(--ok-fg);">${r.profiles.length} profiles loaded</span>`}catch(i){g.innerHTML='<option value="">-- Failed to load --</option>',d.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${i.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!m)return;const o=m.id||m.appTemplate,g=y(m),t=document.getElementById("svc-apikey-input")?.value.trim(),e=document.getElementById("svc-quality-select"),i=document.getElementById("svc-quality-status");if(!g){i.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!t||t==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){i.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}e.innerHTML='<option value="">Fetching...</option>',i.textContent="";try{const n=new URLSearchParams({service:o,url:g,apiKey:t}),f=await(await fetch(`/api/v1/arr/quality-profiles?${n}`)).json();if(!f.success){e.innerHTML='<option value="">-- Error --</option>',i.innerHTML=`<span style="color: var(--error, #c62828);">${f.error||"Failed to feLine truncated
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3 style="margin: 0 0 16px; font-size: 1.1rem;">Authentication Settings</h3>
@@ -288,7 +288,7 @@
</button>
</div>
</div>
</div>`);async function a(){try{const y=await(await fetch("/api/v1/totp/config")).json();if(!y.success)return;const{enabled:c,sessionDuration:p,isSetUp:d}=y.config,o=document.getElementById("totp-status-dot"),v=document.getElementById("totp-status-text"),i=document.getElementById("totp-status-banner"),t=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),s=document.getElementById("totp-duration-section"),n=document.getElementById("totp-disable-section");if(c&&d){o.style.background="var(--ok-fg, #7ef2ff)",i.style.borderColor="var(--ok-fg, #7ef2ff)",i.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",v.textContent="TOTP is active",v.style.color="var(--ok-fg, #7ef2ff)",t.style.display="block";const r=document.getElementById("totp-setup-btn");r&&(r.textContent="Generate New Secret"),e.style.display="none",s.style.display="block",n.style.display="block",document.getElementById("totp-duration-select").value=p}else o.style.background="var(--muted)",i.style.borderColor="var(--border)",i.style.background="transparent",v.textContent="TOTP is not configured",v.style.color="var(--muted)",t.style.display="block",e.style.display="none",s.style.display="none",n.style.display="none";h(c&&d,p)}catch(u){console.warn("Failed to load TOTP settings:",u)}}const f={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function b(u,y){const c=window.DCI18n;return c&&c.isLoaded()?c.t(u):y}function h(u,y){const c=document.getElementById("auth-card"),p=document.getElementById("auth-pill"),d=document.getElementById("auth-dot"),o=document.getElementById("auth-status-text");c&&(u?(c.setAttribute("data-status","on"),p.className="badge on",p.textContent=b("card.status.yes","YES"),d.className="dot ok at-bl",o.textContent="Session: "+(f[y]||y)):(c.setAttribute("data-status","off"),p.className="badge off",p.textContent=b("card.status.no","NO"),d.className="dot bad at-bl",o.textContent=b("card.auth.not_configured","Not configured")))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const y=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();y.success&&(document.getElementById("totp-qr-image").src=y.qrCode,document.getElementById("totp-manual-key").textContent=y.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(u){l.logError("[TOTP] Setup Failed",u,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const u=document.getElementById("totp-import-key").value.trim(),y=document.getElementById("totp-import-error");if(y.textContent="",!u){y.textContent="Paste a Base32 secret key first";return}try{const p=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:u})})).json();p.success?(y.textContent="",document.getElementById("totp-qr-image").src=p.qrCode,document.getElementById("totp-manual-key").textContent=p.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):y.textContent=p.error||p.message||"Import failed"}catch{y.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const u=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(u).then(()=>{const y=document.getElementById("totp-copy-key");y.textContent="\u2705",setTimeout(()=>{y.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const u=document.getElementById("totp-manual-key").textContent.trim();if(!u)return;const y={service:"DashCaddy",type:"totp-secret",secret:u,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},c=new Blob([JSON.stringify(y,null,2)],{type:"application/json"}),p=URL.createObjectURL(c),d=document.createElement("a");d.href=p,d.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(p);const o=document.getElementById("totp-download-backup");o.textContent="\u2705 Saved",setTimeLine truncated
</div>`);async function s(){try{const v=await(await fetch("/api/v1/totp/config")).json();if(!v.success)return;const{enabled:u,sessionDuration:l,isSetUp:a}=v.config,o=document.getElementById("totp-status-dot"),g=document.getElementById("totp-status-text"),d=document.getElementById("totp-status-banner"),t=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),i=document.getElementById("totp-duration-section"),n=document.getElementById("totp-disable-section");if(u&&a){o.style.background="var(--ok-fg, #7ef2ff)",d.style.borderColor="var(--ok-fg, #7ef2ff)",d.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",g.textContent="TOTP is active",g.style.color="var(--ok-fg, #7ef2ff)",t.style.display="block";const r=document.getElementById("totp-setup-btn");r&&(r.textContent="Generate New Secret"),e.style.display="none",i.style.display="block",n.style.display="block",document.getElementById("totp-duration-select").value=l}else o.style.background="var(--muted)",d.style.borderColor="var(--border)",d.style.background="transparent",g.textContent="TOTP is not configured",g.style.color="var(--muted)",t.style.display="block",e.style.display="none",i.style.display="none",n.style.display="none";b(u&&a,l)}catch(y){console.warn("Failed to load TOTP settings:",y)}}const m={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(y,v){const u=window.DCI18n;return u&&u.isLoaded()?u.t(y):v}function b(y,v){const u=document.getElementById("auth-card"),l=document.getElementById("auth-pill"),a=document.getElementById("auth-dot"),o=document.getElementById("auth-status-text");u&&(y?(u.setAttribute("data-status","on"),l.className="badge on",l.textContent=h("card.status.yes","YES"),a.className="dot ok at-bl",o.textContent="Session: "+(m[v]||v)):(u.setAttribute("data-status","off"),l.className="badge off",l.textContent=h("card.status.no","NO"),a.className="dot bad at-bl",o.textContent=h("card.auth.not_configured","Not configured")))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const v=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();v.success&&(document.getElementById("totp-qr-image").src=v.qrCode,document.getElementById("totp-manual-key").textContent=v.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(y){c.logError("[TOTP] Setup Failed",y,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const y=document.getElementById("totp-import-key").value.trim(),v=document.getElementById("totp-import-error");if(v.textContent="",!y){v.textContent="Paste a Base32 secret key first";return}try{const l=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:y})})).json();l.success?(v.textContent="",document.getElementById("totp-qr-image").src=l.qrCode,document.getElementById("totp-manual-key").textContent=l.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):v.textContent=l.error||l.message||"Import failed"}catch{v.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const y=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(y).then(()=>{const v=document.getElementById("totp-copy-key");v.textContent="\u2705",setTimeout(()=>{v.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const y=document.getElementById("totp-manual-key").textContent.trim();if(!y)return;const v={service:"DashCaddy",type:"totp-secret",secret:y,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},u=new Blob([JSON.stringify(v,null,2)],{type:"application/json"}),l=URL.createObjectURL(u),a=document.createElement("a");a.href=l,a.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(l);const o=document.getElementById("totp-download-backup");o.textContent="\u2705 Saved",setTimeLine truncated
<div id="token-management-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
<h3>\u{1F511} DNS Credentials</h3>
@@ -306,40 +306,40 @@
</div>
</div>
</div>
`);function l(){return Object.keys(SITE.dnsServers||{})}function a(n){return(SITE.dnsServers||{})[n]?.name||n.toUpperCase()}function f(){const n=document.getElementById("dns-cred-sections");if(!n)return;n.innerHTML="";const r=l();if(r.length===0){n.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const g of r)n.insertAdjacentHTML("beforeend",`
`);function c(){return Object.keys(SITE.dnsServers||{})}function s(n){return(SITE.dnsServers||{})[n]?.name||n.toUpperCase()}function m(){const n=document.getElementById("dns-cred-sections");if(!n)return;n.innerHTML="";const r=c();if(r.length===0){n.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const f of r)n.insertAdjacentHTML("beforeend",`
<div class="token-section">
<h4 class="token-section-title">${a(g)}</h4>
<h4 class="token-section-title">${s(f)}</h4>
<div class="token-grid">
<div class="token-field">
<label for="${g}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${g}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${f}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${f}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${g}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${g}-readonly-token">\u{1F441}</button>
<input type="password" id="${f}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${f}-readonly-token">\u{1F441}</button>
</div>
</div>
<div class="token-field">
<label for="${g}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${g}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<label for="${f}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${f}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${g}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${g}-admin-token">\u{1F441}</button>
<input type="password" id="${f}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${f}-admin-token">\u{1F441}</button>
</div>
</div>
</div>
<div class="token-status" id="${g}-token-status"></div>
<div class="token-status" id="${f}-token-status"></div>
</div>
`)}function b(){let n=safeSessionGet("dashcaddy-encryption-key");if(n)return n;const r=safeGet("dashcaddy-encryption-key");if(r)return safeSessionSet("dashcaddy-encryption-key",r),safeRemove("dashcaddy-encryption-key"),r;const g=new Uint8Array(32);return crypto.getRandomValues(g),n=Array.from(g,m=>m.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",n),n}const h=b();function u(n,r){if(!n)return"";const g=crypto.getRandomValues(new Uint8Array(8)),m=Array.from(g,L=>L.toString(16).padStart(2,"0")).join(""),x=new TextEncoder().encode(r+m);let I="";for(let L=0;L<n.length;L++){const P=n.charCodeAt(L)^x[L%x.length]^g[L%g.length]^L*31+17&255;I+=String.fromCharCode(P)}return m+":"+btoa(I)}function y(n,r){if(!n)return"";try{if(n.indexOf(":")===16){const I=n.substring(0,16),L=new Uint8Array(I.match(/.{2}/g).map($=>parseInt($,16))),P=atob(n.substring(17)),C=new TextEncoder().encode(r+I);let B="";for(let $=0;$<P.length;$++){const E=P.charCodeAt($)^C[$%C.length]^L[$%L.length]^$*31+17&255;B+=String.fromCharCode(E)}return B}const m=atob(n);let x="";for(let I=0;I<m.length;I++){const L=m.charCodeAt(I)^r.charCodeAt(I%r.length);x+=String.fromCharCode(L)}return x}catch{return""}}function c(n,r,g){const m=safeGet(`${n}-${r}-${g}-enc`);return y(m,h)}function p(n,r,g,m){const x=`${n}-${r}-${g}-enc`;m?safeSet(x,u(m,h)):safeRemove(x)}function d(n,r){return c(n,r,"token")}function o(n,r){return c(n,r,"username")}function v(n,r,g){p(n,r,"token",g)}function i(n,r,g){p(n,r,"username",g)}function t(){const n={};for(const r of l())n[r]={readonly:{username:o(r,"readonly"),token:d(r,"readonly")},admin:{username:o(r,"admin"),token:d(r,"admin")}};return n}function e(){l().forEach(n=>{["readonly","admin"].forEach(r=>{["token","username"].forEach(g=>{safeRemove(`${n}-${r}-${g}-enc`)})}),safeRemove(`${n}-token-enc`),safeRemove(`${n}-username-enc`)})}function s(n){const r=d(n,"readonly"),g=o(n,"readonly"),m=d(n,"admin"),x=o(n,"admin"),I=y(safeGet(`${n}-token-enc`),h),L=y(safeGet(`${n}-username-enc`),h);return{username:x||g||L,token:m||r||I,readonlyToken:r||I,readonlyUsername:g||L,adminToken:m||I,adminUsername:x||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{f();const n=document.getElementById("token-management-modal"),r=t();l().forEach(g=>{const m=r[g];document.getElementById(`${g}-readonly-username`).value=m.readonly.username,document.getElementById(`${g}-readonly-token`).value=m.readonly.token,document.getElementById(`${g}-admin-username`).value=m.admin.username,document.getElementById(`${g}-admin-token`).value=m.admin.token,document.getElementById(`${g}-token-status`).textContent=""}),n.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",n=>{const r=n.target.closest(".token-toggle");if(r){const g=r.dataset.target,m=document.getElementById(g);m.type==="password"?(m.type="text",r.textContent="\u{1F648}"):(m.type="password",r.textContent="\u{1F441}");return}n.target.id==="token-management-modal"&&n.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const n=l();n.forEach(m=>{i(m,"readonly",document.getElementById(`${m}-readonly-username`).value.trim()),v(m,"readonly",document.getElementById(`${m}-readonly-token`).value.trim()),i(m,"admin",document.getElementById(`${m}-admin-username`).value.trim()),v(m,"admin",document.getElementById(`${m}-admin-token`).value.trim())});const r={};let g=!1;if(n.forEach(m=>{const x={},I=document.getElementById(`${m}-readonly-username`).value.trim(),L=document.getElementById(`${m}-readonly-token`).value.trim(),P=document.getElementById(`${m}-admin-username`).value.trim(),C=document.getElementById(`${m}-admin-token`).value.trim();I&&L&&(x.readonly={username:I,password:L},g=!0),P&&C&&(x.admin={username:P,password:C},g=!0),Object.keys(x).length>0&&(r[m]=x)}),g){n.forEach(m=>{r[m]&&(document.getElementById(`${m}-token-status`).textContent="Verifying...",document.getElementById(`${m}-token-status`).className="token-status")});try{const x=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:r})})).json();x.results?n.forEach(I=>{const L=document.getElementById(`${I}-token-status`);if(!r[I]){L.textContent="";return}const P=x.results[I];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):x.success?n.forEach(I=>{r[I]&&(document.getElementById(`${I}-token-status`).textContent="\u2713 Saved",document.getElementById(`${I}-token-status`).className="token-status success")}):n.forEach(I=>{r[I]&&(document.getElementById(`${I}-token-status`).textContent="\u2717 "+(x.error||"Failed"),document.getElementById(`${I}-token-status`).className="token-status error")})}catch(m){console.erro Line truncated
`)}function h(){let n=safeSessionGet("dashcaddy-encryption-key");if(n)return n;const r=safeGet("dashcaddy-encryption-key");if(r)return safeSessionSet("dashcaddy-encryption-key",r),safeRemove("dashcaddy-encryption-key"),r;const f=new Uint8Array(32);return crypto.getRandomValues(f),n=Array.from(f,p=>p.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",n),n}const b=h();function y(n,r){if(!n)return"";const f=crypto.getRandomValues(new Uint8Array(8)),p=Array.from(f,L=>L.toString(16).padStart(2,"0")).join(""),w=new TextEncoder().encode(r+p);let I="";for(let L=0;L<n.length;L++){const P=n.charCodeAt(L)^w[L%w.length]^f[L%f.length]^L*31+17&255;I+=String.fromCharCode(P)}return p+":"+btoa(I)}function v(n,r){if(!n)return"";try{if(n.indexOf(":")===16){const I=n.substring(0,16),L=new Uint8Array(I.match(/.{2}/g).map($=>parseInt($,16))),P=atob(n.substring(17)),C=new TextEncoder().encode(r+I);let B="";for(let $=0;$<P.length;$++){const E=P.charCodeAt($)^C[$%C.length]^L[$%L.length]^$*31+17&255;B+=String.fromCharCode(E)}return B}const p=atob(n);let w="";for(let I=0;I<p.length;I++){const L=p.charCodeAt(I)^r.charCodeAt(I%r.length);w+=String.fromCharCode(L)}return w}catch{return""}}function u(n,r,f){const p=safeGet(`${n}-${r}-${f}-enc`);return v(p,b)}function l(n,r,f,p){const w=`${n}-${r}-${f}-enc`;p?safeSet(w,y(p,b)):safeRemove(w)}function a(n,r){return u(n,r,"token")}function o(n,r){return u(n,r,"username")}function g(n,r,f){l(n,r,"token",f)}function d(n,r,f){l(n,r,"username",f)}function t(){const n={};for(const r of c())n[r]={readonly:{username:o(r,"readonly"),token:a(r,"readonly")},admin:{username:o(r,"admin"),token:a(r,"admin")}};return n}function e(){c().forEach(n=>{["readonly","admin"].forEach(r=>{["token","username"].forEach(f=>{safeRemove(`${n}-${r}-${f}-enc`)})}),safeRemove(`${n}-token-enc`),safeRemove(`${n}-username-enc`)})}function i(n){const r=a(n,"readonly"),f=o(n,"readonly"),p=a(n,"admin"),w=o(n,"admin"),I=v(safeGet(`${n}-token-enc`),b),L=v(safeGet(`${n}-username-enc`),b);return{username:w||f||L,token:p||r||I,readonlyToken:r||I,readonlyUsername:f||L,adminToken:p||I,adminUsername:w||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{m();const n=document.getElementById("token-management-modal"),r=t();c().forEach(f=>{const p=r[f];document.getElementById(`${f}-readonly-username`).value=p.readonly.username,document.getElementById(`${f}-readonly-token`).value=p.readonly.token,document.getElementById(`${f}-admin-username`).value=p.admin.username,document.getElementById(`${f}-admin-token`).value=p.admin.token,document.getElementById(`${f}-token-status`).textContent=""}),n.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",n=>{const r=n.target.closest(".token-toggle");if(r){const f=r.dataset.target,p=document.getElementById(f);p.type==="password"?(p.type="text",r.textContent="\u{1F648}"):(p.type="password",r.textContent="\u{1F441}");return}n.target.id==="token-management-modal"&&n.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const n=c();n.forEach(p=>{d(p,"readonly",document.getElementById(`${p}-readonly-username`).value.trim()),g(p,"readonly",document.getElementById(`${p}-readonly-token`).value.trim()),d(p,"admin",document.getElementById(`${p}-admin-username`).value.trim()),g(p,"admin",document.getElementById(`${p}-admin-token`).value.trim())});const r={};let f=!1;if(n.forEach(p=>{const w={},I=document.getElementById(`${p}-readonly-username`).value.trim(),L=document.getElementById(`${p}-readonly-token`).value.trim(),P=document.getElementById(`${p}-admin-username`).value.trim(),C=document.getElementById(`${p}-admin-token`).value.trim();I&&L&&(w.readonly={username:I,password:L},f=!0),P&&C&&(w.admin={username:P,password:C},f=!0),Object.keys(w).length>0&&(r[p]=w)}),f){n.forEach(p=>{r[p]&&(document.getElementById(`${p}-token-status`).textContent="Verifying...",document.getElementById(`${p}-token-status`).className="token-status")});try{const w=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:r})})).json();w.results?n.forEach(I=>{const L=document.getElementById(`${I}-token-status`);if(!r[I]){L.textContent="";return}const P=w.results[I];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):w.success?n.forEach(I=>{r[I]&&(document.getElementById(`${I}-token-status`).textContent="\u2713 Saved",document.getElementById(`${I}-token-status`).className="token-status success")}):n.forEach(I=>{r[I]&&(document.getElementById(`${I}-token-status`).textContent="\u2717 "+(w.error||"Failed"),document.getElementById(`${I}-token-status`).className="token-status error")})}catch(p){console.erro Line truncated
Current: ${i.currentVersion}
New: ${i.updateVersion}
Current: ${d.currentVersion}
New: ${d.updateVersion}
`+(i.updateTitle?`${i.updateTitle}
`+(d.updateTitle?`${d.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){d.textContent=o,d.disabled=!1,d.title="Update DNS server";return}d.textContent="\u{1F504}",d.title="Updating...";const s=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(p)}`,{method:"POST"})).json();if(!s.success)throw new Error(s.error||"Update failed");if(s.manualUpdateRequired){d.textContent="\u2B06\uFE0F",d.title=`Update available: ${s.newVersion}`;const n=s.downloadLink?`
Download: ${s.downloadLink}`:"",r=s.instructionsLink?`
Instructions: ${s.instructionsLink}`:"";showNotification(`${c.toUpperCase()} update requires manual installation. Current: ${s.previousVersion} \u2192 ${s.newVersion}. Please update manually on the host machine.`,"warning",8e3),d.disabled=!1;return}d.textContent="\u2705",d.title="Updated successfully!",showNotification(`${c.toUpperCase()} updated successfully! ${s.previousVersion} \u2192 ${s.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server",window.refreshAll()},1e4)}catch(v){console.error("DNS update error:",v),d.textContent="\u274C",d.title="Update failed",showNotification(`Failed to update ${c.toUpperCase()}: ${v.message}`,"error"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",c=>{const p=c.target.closest('[id$="-update"]');if(!p)return;const d=p.id.replace("-update","");SITE.dnsServers[d]&&a(d,SITE.dnsServers[d]?.ip)}),injectModal("dns-settings-modal",`
Proceed?`)){a.textContent=o,a.disabled=!1,a.title="Update DNS server";return}a.textContent="\u{1F504}",a.title="Updating...";const i=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(l)}`,{method:"POST"})).json();if(!i.success)throw new Error(i.error||"Update failed");if(i.manualUpdateRequired){a.textContent="\u2B06\uFE0F",a.title=`Update available: ${i.newVersion}`;const n=i.downloadLink?`
Download: ${i.downloadLink}`:"",r=i.instructionsLink?`
Instructions: ${i.instructionsLink}`:"";showNotification(`${u.toUpperCase()} update requires manual installation. Current: ${i.previousVersion} \u2192 ${i.newVersion}. Please update manually on the host machine.`,"warning",8e3),a.disabled=!1;return}a.textContent="\u2705",a.title="Updated successfully!",showNotification(`${u.toUpperCase()} updated successfully! ${i.previousVersion} \u2192 ${i.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{a.textContent=o,a.disabled=!1,a.title="Update DNS server",window.refreshAll()},1e4)}catch(g){console.error("DNS update error:",g),a.textContent="\u274C",a.title="Update failed",showNotification(`Failed to update ${u.toUpperCase()}: ${g.message}`,"error"),setTimeout(()=>{a.textContent=o,a.disabled=!1,a.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",u=>{const l=u.target.closest('[id$="-update"]');if(!l)return;const a=l.id.replace("-update","");SITE.dnsServers[a]&&s(a,SITE.dnsServers[a]?.ip)}),injectModal("dns-settings-modal",`
<div id="dns-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3 id="dns-settings-title">DNS Settings</h3>
@@ -366,7 +366,7 @@ Instructions: ${s.instructionsLink}`:"";showNotification(`${c.toUpperCase()} upd
<button id="dns-settings-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);let f=null;function b(c){f=c;const p=SITE.dnsServers[c]||{},d=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(p.name||c).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=p.ip||"",document.getElementById("dns-edit-port").value=p.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=p.name||"",d.classList.add("show")}async function h(){if(!f)return;const c=document.getElementById("dns-edit-ip").value.trim(),p=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,d=document.getElementById("dns-edit-name").value.trim();if(!c){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[f]={ip:c,port:String(p)},d&&(o.dnsServers[f].name=d);try{const i=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();i.success?(SITE.dnsServers[f]=o.dnsServers[f],showNotification(`${f.toUpperCase()} settings saved`,"success"),y(),window.refreshAll()):showNotification(i.error||"Failed to save settings","error")}catch(v){showNotification("Failed to save: "+v.message,"error")}}async function u(){if(f&&confirm(`Remove ${f.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const p=await(await secureFetch("/api/v1/config")).json();p.dnsServers&&delete p.dnsServers[f];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:p.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[f];const v=document.querySelector(`.top [data-app="${f}"]`);v&&v.remove(),showNotification(`${f.toUpperCase()} removed from dashboard`,"success"),y()}else showNotification(o.error||"Failed to remove","error")}catch(c){showNotification("Failed to remove: "+c.message,"error")}}function y(){closeModal("dns-settings-modal"),f=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",y),document.getElementById("dns-settings-save")?.addEventListener("click",h),document.getElementById("dns-settings-delete")?.addEventListener("click",u),document.getElementById("dns-settings-modal")?.addEventListener("click",c=>{c.target.id==="dns-settings-modal"&&y()}),document.querySelector(".top")?.addEventListener("click",c=>{const p=c.target.closest('[id$="-settings"]');if(!p)return;const d=p.id.replace("-settings","");SITE.dnsServers[d]&&(c.stopPropagation(),b(d))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
</div>`);let m=null;function h(u){m=u;const l=SITE.dnsServers[u]||{},a=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(l.name||u).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=l.ip||"",document.getElementById("dns-edit-port").value=l.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=l.name||"",a.classList.add("show")}async function b(){if(!m)return;const u=document.getElementById("dns-edit-ip").value.trim(),l=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,a=document.getElementById("dns-edit-name").value.trim();if(!u){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[m]={ip:u,port:String(l)},a&&(o.dnsServers[m].name=a);try{const d=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();d.success?(SITE.dnsServers[m]=o.dnsServers[m],showNotification(`${m.toUpperCase()} settings saved`,"success"),v(),window.refreshAll()):showNotification(d.error||"Failed to save settings","error")}catch(g){showNotification("Failed to save: "+g.message,"error")}}async function y(){if(m&&confirm(`Remove ${m.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const l=await(await secureFetch("/api/v1/config")).json();l.dnsServers&&delete l.dnsServers[m];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:l.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[m];const g=document.querySelector(`.top [data-app="${m}"]`);g&&g.remove(),showNotification(`${m.toUpperCase()} removed from dashboard`,"success"),v()}else showNotification(o.error||"Failed to remove","error")}catch(u){showNotification("Failed to remove: "+u.message,"error")}}function v(){closeModal("dns-settings-modal"),m=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",v),document.getElementById("dns-settings-save")?.addEventListener("click",b),document.getElementById("dns-settings-delete")?.addEventListener("click",y),document.getElementById("dns-settings-modal")?.addEventListener("click",u=>{u.target.id==="dns-settings-modal"&&v()}),document.querySelector(".top")?.addEventListener("click",u=>{const l=u.target.closest('[id$="-settings"]');if(!l)return;const a=l.id.replace("-settings","");SITE.dnsServers[a]&&(u.stopPropagation(),h(a))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
<div id="logs-modal" class="logs-modal">
<div class="logs-modal-content" style="min-width: 800px; max-width: 1000px;">
<div class="logs-header">
@@ -390,66 +390,66 @@ Instructions: ${s.instructionsLink}`:"";showNotification(`${c.toUpperCase()} upd
</div>
</div>
</div>
</div>`);let l=null,a=null,f=!1,b=null,h=null,u=!1,y=null,c=null,p=!1,d=null,o=!1;async function v(E,w=25){try{const S=getDnsServerAddr(E),T=await fetch(`/api/v1/dns/logs?server=${S}&limit=${w}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,server:k.server}:{error:k.error||"Failed to fetch logs"}}else return T.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${T.status}`}}catch(S){return console.error("DNS logs fetch failed:",S),{error:S.message}}}function i(E){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[E]||"var(--fg)"}function t(E){const w=document.createElement("div");if(w.className="log-entry",w.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",E.parsed===!1)return w.style.gridTemplateColumns="1fr",w.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(E.raw)}</span>`,w;const S=i(E.rcode),T=E.rcode==="Refused"||E.rcode==="REFUSED";return w.innerHTML=`
</div>`);let c=null,s=null,m=!1,h=null,b=null,y=!1,v=null,u=null,l=!1,a=null,o=!1;async function g(E,x=25){try{const S=getDnsServerAddr(E),T=await fetch(`/api/v1/dns/logs?server=${S}&limit=${x}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,server:k.server}:{error:k.error||"Failed to fetch logs"}}else return T.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${T.status}`}}catch(S){return console.error("DNS logs fetch failed:",S),{error:S.message}}}function d(E){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[E]||"var(--fg)"}function t(E){const x=document.createElement("div");if(x.className="log-entry",x.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",E.parsed===!1)return x.style.gridTemplateColumns="1fr",x.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(E.raw)}</span>`,x;const S=d(E.rcode),T=E.rcode==="Refused"||E.rcode==="REFUSED";return x.innerHTML=`
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.timestamp)}</span>
<span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(E.client)}">${escapeHtml(E.client)}</span>
<span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${T?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(E.domain)}">${escapeHtml(E.domain)}</span>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.type)}</span>
<span style="color: ${S}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(E.rcode)}</span>
`,w}async function e(){if(p){await B();return}if(u){await I();return}if(f||!l)return;const E=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const S=await v(l,E);if(S.error){w.innerHTML=`
`,x}async function e(){if(l){await B();return}if(y){await I();return}if(m||!c)return;const E=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await g(c,E);if(S.error){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(S.error)}</div>
</div>`;return}w.innerHTML=`
</div>`;return}x.innerHTML=`
<div style="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
<span>Time</span>
<span>Client</span>
<span>Domain</span>
<span>Type</span>
<span>Status</span>
</div>`,S.logs&&S.logs.length>0?S.logs.forEach(T=>{const k=t(T);w.appendChild(k)}):w.innerHTML+=`
</div>`,S.logs&&S.logs.length>0?S.logs.forEach(T=>{const k=t(T);x.appendChild(k)}):x.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No DNS queries logged yet
</div>`}catch(S){w.innerHTML=`
</div>`}catch(S){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function s(E){l=E,f=!1,u=!1;const w=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),T=document.getElementById("logs-pause"),k=document.getElementById("logs-stream");S.textContent=`${E.toUpperCase()} DNS Logs`,T.textContent="\u23F8\uFE0F Pause",T.classList.remove("paused"),k&&(k.style.display="none"),w.classList.add("show"),e(),a=setInterval(e,DC.POLL.LOGS)}function n(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),g(),l=null,u=!1,b=null,h=null,p=!1,y=null,c=null,f=!1}function r(E){d&&g();const w=document.getElementById("logs-stream"),S=document.getElementById("logs-pause"),T=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{d=new EventSource(`/api/v1/logs/stream/${E}`),o=!0,w.classList.add("active"),w.textContent="\u{1F534} Live",w.title="Streaming - click to stop",S.style.display="none";const k=document.getElementById("logs-title");k.textContent.includes("\u{1F534}")||(k.innerHTML=k.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),d.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),g();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const U=(D.stream||"stdout")==="stderr",N=U?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${U?"var(--bad-bg)":"var(--ok-bg)"}; color: ${N}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${U?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
</div>`}}function i(E){c=E,m=!1,y=!1;const x=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),T=document.getElementById("logs-pause"),k=document.getElementById("logs-stream");S.textContent=`${E.toUpperCase()} DNS Logs`,T.textContent="\u23F8\uFE0F Pause",T.classList.remove("paused"),k&&(k.style.display="none"),x.classList.add("show"),e(),s=setInterval(e,DC.POLL.LOGS)}function n(){document.getElementById("logs-modal").classList.remove("show"),s&&(clearInterval(s),s=null),f(),c=null,y=!1,h=null,b=null,l=!1,v=null,u=null,m=!1}function r(E){a&&f();const x=document.getElementById("logs-stream"),S=document.getElementById("logs-pause"),T=document.getElementById("logs-content");s&&(clearInterval(s),s=null);try{a=new EventSource(`/api/v1/logs/stream/${E}`),o=!0,x.classList.add("active"),x.textContent="\u{1F534} Live",x.title="Streaming - click to stop",S.style.display="none";const k=document.getElementById("logs-title");k.textContent.includes("\u{1F534}")||(k.innerHTML=k.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),a.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),f();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const _=(D.stream||"stdout")==="stderr",N=_?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${_?"var(--bad-bg)":"var(--ok-bg)"}; color: ${N}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${_?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
<div style="flex-shrink: 0;">${M}</div>
<div style="flex: 1; color: ${N}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(D.text)}</div>
`,T.appendChild(O),T.scrollTop=T.scrollHeight;T.children.length>500;)T.removeChild(T.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},d.onerror=A=>{console.error("EventSource error:",A),g()}}catch(k){console.error("Failed to start streaming:",k),g()}}function g(){d&&(d.close(),d=null),o=!1;const E=document.getElementById("logs-stream"),w=document.getElementById("logs-pause"),S=document.getElementById("logs-title");E&&(E.classList.remove("active"),E.textContent="\u{1F4E1} Live",E.title="Enable real-time streaming"),w&&(w.style.display=""),S&&(S.textContent=S.textContent.replace(" \u{1F534}","")),u&&b&&!a&&(a=setInterval(I,DC.POLL.LOGS))}async function m(E,w=100){try{const S=`/api/v1/logs/container/${E}?tail=${w}&timestamps=true`,T=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,containerName:k.containerName,containerId:k.containerId}:{error:k.error||"Failed to fetch container logs"}}else return{error:`HTTP ${T.status}: ${T.statusText}`}}catch(S){return console.error("Container logs fetch failed:",S),{error:S.message}}}function x(E){const w=document.createElement("div");w.className="log-entry",w.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=E.stream==="stderr"?"var(--bad-fg)":"var(--fg)",T=E.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return w.innerHTML=`
`,T.appendChild(O),T.scrollTop=T.scrollHeight;T.children.length>500;)T.removeChild(T.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},a.onerror=A=>{console.error("EventSource error:",A),f()}}catch(k){console.error("Failed to start streaming:",k),f()}}function f(){a&&(a.close(),a=null),o=!1;const E=document.getElementById("logs-stream"),x=document.getElementById("logs-pause"),S=document.getElementById("logs-title");E&&(E.classList.remove("active"),E.textContent="\u{1F4E1} Live",E.title="Enable real-time streaming"),x&&(x.style.display=""),S&&(S.textContent=S.textContent.replace(" \u{1F534}","")),y&&h&&!s&&(s=setInterval(I,DC.POLL.LOGS))}async function p(E,x=100){try{const S=`/api/v1/logs/container/${E}?tail=${x}&timestamps=true`,T=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,containerName:k.containerName,containerId:k.containerId}:{error:k.error||"Failed to fetch container logs"}}else return{error:`HTTP ${T.status}: ${T.statusText}`}}catch(S){return console.error("Container logs fetch failed:",S),{error:S.message}}}function w(E){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=E.stream==="stderr"?"var(--bad-fg)":"var(--fg)",T=E.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return x.innerHTML=`
<div style="flex-shrink: 0;">${T}</div>
<div style="flex: 1; color: ${S}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(E.text)}</div>
`,w}async function I(){if(f||!b||!u)return;const E=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const S=await m(b,E);if(S.error){w.innerHTML=`
`,x}async function I(){if(m||!h||!y)return;const E=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await p(h,E);if(S.error){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(S.error)}</div>
</div>`;return}w.innerHTML=`
</div>`;return}x.innerHTML=`
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
<span style="flex-shrink: 0; width: 80px;">Stream</span>
<span style="flex: 1;">Log Output</span>
</div>`,S.logs&&S.logs.length>0?(S.logs.forEach(T=>{const k=x(T);w.appendChild(k)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
</div>`,S.logs&&S.logs.length>0?(S.logs.forEach(T=>{const k=w(T);x.appendChild(k)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No logs available for this container
</div>`}catch(S){w.innerHTML=`
</div>`}catch(S){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function L(E,w){b=E,h=w,u=!0,p=!1,f=!1,g();const S=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");T.textContent=`\u{1F4CB} ${w} - Container Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),A&&(A.style.display=""),S.classList.add("show"),I(),a=setInterval(I,DC.POLL.LOGS)}async function P(E,w=100){try{const S=`/api/v1/logs/file?path=${encodeURIComponent(E)}&tail=${w}`,T=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,logPath:k.logPath,totalLines:k.totalLines}:{error:k.error||"Failed to fetch file logs"}}else return{error:(await T.json().catch(()=>({}))).error||`HTTP ${T.status}`}}catch(S){return console.error("File logs fetch failed:",S),{error:S.message}}}function C(E){const w=document.createElement("div");w.className="log-entry",w.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=E.text;let T="INFO",k="var(--fg)";S.match(/ERROR|FATAL|CRITICAL/i)?(T="ERROR",k="var(--bad-fg)"):S.match(/WARN|WARNING/i)?(T="WARN",k="#f39c12"):S.match(/DEBUG/i)&&(T="DEBUG",k="var(--muted)");const D=`<span style="background: ${k==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${k}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${T}</span>`;return w.innerHTML=`
</div>`}}function L(E,x){h=E,b=x,y=!0,l=!1,m=!1,f();const S=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");T.textContent=`\u{1F4CB} ${x} - Container Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),A&&(A.style.display=""),S.classList.add("show"),I(),s=setInterval(I,DC.POLL.LOGS)}async function P(E,x=100){try{const S=`/api/v1/logs/file?path=${encodeURIComponent(E)}&tail=${x}`,T=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(T.ok){const k=await T.json();return k.success&&k.logs?{logs:k.logs,count:k.count,logPath:k.logPath,totalLines:k.totalLines}:{error:k.error||"Failed to fetch file logs"}}else return{error:(await T.json().catch(()=>({}))).error||`HTTP ${T.status}`}}catch(S){return console.error("File logs fetch failed:",S),{error:S.message}}}function C(E){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=E.text;let T="INFO",k="var(--fg)";S.match(/ERROR|FATAL|CRITICAL/i)?(T="ERROR",k="var(--bad-fg)"):S.match(/WARN|WARNING/i)?(T="WARN",k="#f39c12"):S.match(/DEBUG/i)&&(T="DEBUG",k="var(--muted)");const D=`<span style="background: ${k==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${k}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${T}</span>`;return x.innerHTML=`
<div style="flex-shrink: 0;">${D}</div>
<div style="flex: 1; color: ${k}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(S)}</div>
`,w}async function B(){if(f||!y||!p)return;const E=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const S=await P(y,E);if(S.error){w.innerHTML=`
`,x}async function B(){if(m||!v||!l)return;const E=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await P(v,E);if(S.error){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
<div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
<div>${escapeHtml(S.error)}</div>
</div>`;return}w.innerHTML=`
</div>`;return}x.innerHTML=`
<div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
<span style="flex: 1;">Log Output (${S.count} of ${S.totalLines} lines)</span>
</div>`,S.logs&&S.logs.length>0?(S.logs.forEach(T=>{const k=C(T);w.appendChild(k)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
</div>`,S.logs&&S.logs.length>0?(S.logs.forEach(T=>{const k=C(T);x.appendChild(k)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No logs available in this file
</div>`}catch(S){w.innerHTML=`
</div>`}catch(S){x.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function $(E,w){y=E,c=w,p=!0,u=!1,f=!1;const S=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");T.textContent=`\u{1F4CB} ${w} - Application Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),A&&(A.style.display="none"),S.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",E=>{const w=E.target.closest('[id$="-logs"]');if(!w)return;const S=w.id.replace("-logs","");SITE.dnsServers[S]&&s(S)}),document.getElementById("logs-close")?.addEventListener("click",n),document.getElementById("logs-pause")?.addEventListener("click",()=>{f=!f;const E=document.getElementById("logs-pause");f?(E.textContent="\u25B6\uFE0F Resume",E.classList.add("paused")):(E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),e())}),document.getElementById("log-lines")?.addEventListener("change",()=>{f||e()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!u||!b||(o?g():r(b))}),document.getElementById("logs-modal")?.addEventListener("click",E=>{E.target.id==="logs-modal"&&n()}),document.addEventListener("keydown",E=>{E.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&n()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=s})(),(function(){injectModal("service-edit-modal",`
</div>`}}function $(E,x){v=E,u=x,l=!0,y=!1,m=!1;const S=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");T.textContent=`\u{1F4CB} ${x} - Application Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),A&&(A.style.display="none"),S.classList.add("show"),B(),s=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",E=>{const x=E.target.closest('[id$="-logs"]');if(!x)return;const S=x.id.replace("-logs","");SITE.dnsServers[S]&&i(S)}),document.getElementById("logs-close")?.addEventListener("click",n),document.getElementById("logs-pause")?.addEventListener("click",()=>{m=!m;const E=document.getElementById("logs-pause");m?(E.textContent="\u25B6\uFE0F Resume",E.classList.add("paused")):(E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),e())}),document.getElementById("log-lines")?.addEventListener("change",()=>{m||e()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!y||!h||(o?f():r(h))}),document.getElementById("logs-modal")?.addEventListener("click",E=>{E.target.id==="logs-modal"&&n()}),document.addEventListener("keydown",E=>{E.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&n()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=i})(),(function(){injectModal("service-edit-modal",`
<div id="service-edit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
<h3 id="service-edit-title">Edit Service</h3>
@@ -805,45 +805,45 @@ Instructions: ${s.instructionsLink}`:"";showNotification(`${c.toUpperCase()} upd
<button id="add-service-create" class="btn-accent">Create Service</button>
</div>
</div>
</div>`)})(),(function(){async function l(u){try{const y=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(u)}`);if(!y.ok)throw new Error(`Failed to load CAs: ${y.status}`);const c=await y.json();if(c.success){const p=document.getElementById("existing-ca-select");return p.innerHTML="",c.cas.length===0?p.innerHTML='<option value="">No CAs found in Caddyfile</option>':(p.innerHTML='<option value="">Select existing CA...</option>',c.cas.forEach(d=>{const o=document.createElement("option");typeof d=="object"?(o.value=d.id,o.textContent=d.displayName||d.name):(o.value=d,o.textContent=d),p.appendChild(o)})),c.data.cas}else throw new Error(c.message)}catch(y){console.error("Error loading CAs:",y);const c=document.getElementById("existing-ca-select");return c.innerHTML='<option value="">Error loading CAs</option>',[]}}function a(u){const{subdomain:y,port:c,ip:p,sslType:d,caName:o,existingCa:v,enableAuth:i,enableCors:t,customHeaders:e,upstreamPath:s,healthCheck:n,timeout:r,tailscaleOnly:g}=u;let m=`${buildDomain(y)} {
`;switch(g&&(m+=` @blocked not remote_ip 100.64.0.0/10
`,m+=` respond @blocked "Access denied. Tailscale connection required." 403
`),d){case"letsencrypt":break;case"caddy-managed":m+=` tls internal
`;break;case"existing-ca":v&&(m+=` tls {
ca ${v}
</div>`)})(),(function(){async function c(y){try{const v=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(y)}`);if(!v.ok)throw new Error(`Failed to load CAs: ${v.status}`);const u=await v.json();if(u.success){const l=document.getElementById("existing-ca-select");return l.innerHTML="",u.cas.length===0?l.innerHTML='<option value="">No CAs found in Caddyfile</option>':(l.innerHTML='<option value="">Select existing CA...</option>',u.cas.forEach(a=>{const o=document.createElement("option");typeof a=="object"?(o.value=a.id,o.textContent=a.displayName||a.name):(o.value=a,o.textContent=a),l.appendChild(o)})),u.data.cas}else throw new Error(u.message)}catch(v){console.error("Error loading CAs:",v);const u=document.getElementById("existing-ca-select");return u.innerHTML='<option value="">Error loading CAs</option>',[]}}function s(y){const{subdomain:v,port:u,ip:l,sslType:a,caName:o,existingCa:g,enableAuth:d,enableCors:t,customHeaders:e,upstreamPath:i,healthCheck:n,timeout:r,tailscaleOnly:f}=y;let p=`${buildDomain(v)} {
`;switch(f&&(p+=` @blocked not remote_ip 100.64.0.0/10
`,p+=` respond @blocked "Access denied. Tailscale connection required." 403
`),a){case"letsencrypt":break;case"caddy-managed":p+=` tls internal
`;break;case"existing-ca":g&&(p+=` tls {
ca ${g}
}
`);break;case"custom-ca":o&&(m+=` tls {
`);break;case"custom-ca":o&&(p+=` tls {
ca ${o}
}
`);break}if(i&&(m+=` basicauth {
`);break}if(d&&(p+=` basicauth {
admin $2a$14$hashed_password_here
}
`),t&&(m+=` header {
`,m+=` Access-Control-Allow-Origin "*"
`,m+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,m+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,m+=` }
`),e)try{const x=JSON.parse(e);m+=` header {
`,Object.entries(x).forEach(([I,L])=>{m+=` ${I} "${L}"
`}),m+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return n&&(m+=` health_uri ${n}
`),m+=` reverse_proxy ${p}:${c} {
`,s&&s!=="/"&&(m+=` rewrite ${s}
`),r&&r!==30&&(m+=` transport http {
`,m+=` dial_timeout ${r}s
`,m+=` response_header_timeout ${r}s
`,m+=` }
`),m+=` }
`,m+=`}
`,m}async function f(u,y,c=DC.DEFAULTS.TTL){const p=window.getToken(getPrimaryDnsId(),"admin");if(!p)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const d=buildDomain(u),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:d,ip:y,ttl:c,token:p,server:SITE.dnsIp})});if(!o.ok){const i=await o.text();throw new Error(`DNS API Error: ${o.status} - ${i}`)}const v=await o.json();if(!v.success)throw new Error(`DNS Error: ${v.error||"Unknown error"}`);return v}async function b(u){const y={id:u.subdomain,name:u.name,logo:u.logo||`/assets/${u.subdomain}.png`};u.category&&(y.category=u.category),u.containerId&&(y.containerId=u.containerId);try{const c=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!c.ok){const p=await c.json();throw new Error(p.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),y}catch(c){throw console.error("Failed to add service to config:",c),c}}async function h(u){const y=document.getElementById("service-subdomain-input").value.trim(),c=document.getElementById("service-ip-input").value.trim()||"localhost",p=document.getElementById("service-port-input").value.trim()||"80",d=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(y),upstream:`${c}:${p}`,config:u})}),o=await d.json();if(!d.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${d.status}`);return o}window.loadExistingCAs=l,window.generateCaddyConfig=a,window.createDnsRecord=f,window.addServiceToConfig=b,window.addToCaddyfile=h})(),(function(){let l=null;function a(c){l=c;const p=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${c.name}`,document.getElementById("edit-service-name").value=c.name,document.getElementById("edit-service-url-display").textContent=c.url||buildServiceUrl(c.id),document.getElementById("edit-service-logo-preview").src=c.logo||`/assets/${c.id}.png`,document.getElementById("edit-subdomain").value=c.id,document.getElementById("edit-port").value=c.port||"",document.getElementById("edit-ip").value=c.ip||"localhost",document.getElementById("edit-tailscale-only").checked=c.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=c.logo||"";const d=document.getElementById("edit-service-category");d&&(d.dataset.current=c.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),p.classList.add("show")}function f(){closeModal("service-edit-modal"),l=null}async function b(){if(!l)return;const c=document.getElementById("edit-subdomain").value.trim().toLowerCase(),p=document.getElementById("edit-service-name").value.trim(),d=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",v=document.getElementById("edit-tailscale-only").checked,i=document.getElementById("edit-logo-url").value.trim(),t=document.getElementById("edit-service-category")?.value||"";if(!c){showNotification("Subdomain is required","warning");return}const e=l.id,s=[];if(c!==e&&s.push("subdomain"),p&&p!==l.name&&s.push("name"),d&&d!==String(l.port)&&s.push("port"),o!==l.ip&&s.push("ip"),v!==(l.tailscaleOnly||!1)&&s.push("tailscale"),i&&i!==l.logo&&s.push("logo"),t!==(l.category||"")&&s.push("category"),s.length===0){f();return}const n=document.getElementById("service-edit-save");n.textContent="Saving...",n.disabled=!0;try{const g=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:c,name:p||l.name,port:d||l.port,ip:o,tailscaleOnly:v,logo:i||void 0,category:t})})).json();if(!g.success)throw new Error(g.error||"Failed to update service");const m=window.APPS.findIndex(x=>x.id===e);m!==-1&&(window.APPS[m]={...window.APPS[m],id:c,name:p||window.APPS[m].name,port:d||window.APPS[m].port,ip:o,tailscaleOnly:v,logo:i||window.APPS[m].logo,category:t||void 0}),f(),window.buildGrid(),window.refreshAll()}catch(r){console.error("Error saving service changes:",r),showNotification(`Error saving changes: ${r.message}`,"error")}finally{n.textContent="Save Changes",n.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async c=>{const p=c.target.files[0];if(!p)return;if(!p.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const d=new FileReader;d.onload=async o=>{const v=o.target.result;if(document.getElementById("edit-service-logo-preview").src=v,document.getElementById("edit-logo-url").value=v,l)try{const t=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${l.id}.png`,data:v})})).json();t.success&&t.path&&(document.getElementById("edit-logo-url").val Line truncated
`),t&&(p+=` header {
`,p+=` Access-Control-Allow-Origin "*"
`,p+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,p+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,p+=` }
`),e)try{const w=JSON.parse(e);p+=` header {
`,Object.entries(w).forEach(([I,L])=>{p+=` ${I} "${L}"
`}),p+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return n&&(p+=` health_uri ${n}
`),p+=` reverse_proxy ${l}:${u} {
`,i&&i!=="/"&&(p+=` rewrite ${i}
`),r&&r!==30&&(p+=` transport http {
`,p+=` dial_timeout ${r}s
`,p+=` response_header_timeout ${r}s
`,p+=` }
`),p+=` }
`,p+=`}
`,p}async function m(y,v,u=DC.DEFAULTS.TTL){const l=window.getToken(getPrimaryDnsId(),"admin");if(!l)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const a=buildDomain(y),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:a,ip:v,ttl:u,token:l,server:SITE.dnsIp})});if(!o.ok){const d=await o.text();throw new Error(`DNS API Error: ${o.status} - ${d}`)}const g=await o.json();if(!g.success)throw new Error(`DNS Error: ${g.error||"Unknown error"}`);return g}async function h(y){const v={id:y.subdomain,name:y.name,logo:y.logo||`/assets/${y.subdomain}.png`};y.category&&(v.category=y.category),y.containerId&&(v.containerId=y.containerId);try{const u=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!u.ok){const l=await u.json();throw new Error(l.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),v}catch(u){throw console.error("Failed to add service to config:",u),u}}async function b(y){const v=document.getElementById("service-subdomain-input").value.trim(),u=document.getElementById("service-ip-input").value.trim()||"localhost",l=document.getElementById("service-port-input").value.trim()||"80",a=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(v),upstream:`${u}:${l}`,config:y})}),o=await a.json();if(!a.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${a.status}`);return o}window.loadExistingCAs=c,window.generateCaddyConfig=s,window.createDnsRecord=m,window.addServiceToConfig=h,window.addToCaddyfile=b})(),(function(){let c=null;function s(u){c=u;const l=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${u.name}`,document.getElementById("edit-service-name").value=u.name,document.getElementById("edit-service-url-display").textContent=u.url||buildServiceUrl(u.id),document.getElementById("edit-service-logo-preview").src=u.logo||`/assets/${u.id}.png`,document.getElementById("edit-subdomain").value=u.id,document.getElementById("edit-port").value=u.port||"",document.getElementById("edit-ip").value=u.ip||"localhost",document.getElementById("edit-tailscale-only").checked=u.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=u.logo||"";const a=document.getElementById("edit-service-category");a&&(a.dataset.current=u.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),l.classList.add("show")}function m(){closeModal("service-edit-modal"),c=null}async function h(){if(!c)return;const u=document.getElementById("edit-subdomain").value.trim().toLowerCase(),l=document.getElementById("edit-service-name").value.trim(),a=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",g=document.getElementById("edit-tailscale-only").checked,d=document.getElementById("edit-logo-url").value.trim(),t=document.getElementById("edit-service-category")?.value||"";if(!u){showNotification("Subdomain is required","warning");return}const e=c.id,i=[];if(u!==e&&i.push("subdomain"),l&&l!==c.name&&i.push("name"),a&&a!==String(c.port)&&i.push("port"),o!==c.ip&&i.push("ip"),g!==(c.tailscaleOnly||!1)&&i.push("tailscale"),d&&d!==c.logo&&i.push("logo"),t!==(c.category||"")&&i.push("category"),i.length===0){m();return}const n=document.getElementById("service-edit-save");n.textContent="Saving...",n.disabled=!0;try{const f=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:u,name:l||c.name,port:a||c.port,ip:o,tailscaleOnly:g,logo:d||void 0,category:t})})).json();if(!f.success)throw new Error(f.error||"Failed to update service");const p=window.APPS.findIndex(w=>w.id===e);p!==-1&&(window.APPS[p]={...window.APPS[p],id:u,name:l||window.APPS[p].name,port:a||window.APPS[p].port,ip:o,tailscaleOnly:g,logo:d||window.APPS[p].logo,category:t||void 0}),m(),window.buildGrid(),window.refreshAll()}catch(r){console.error("Error saving service changes:",r),showNotification(`Error saving changes: ${r.message}`,"error")}finally{n.textContent="Save Changes",n.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async u=>{const l=u.target.files[0];if(!l)return;if(!l.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=async o=>{const g=o.target.result;if(document.getElementById("edit-service-logo-preview").src=g,document.getElementById("edit-logo-url").value=g,c)try{const t=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${c.id}.png`,data:g})})).json();t.success&&t.path&&(document.getElementById("edit-logo-url").val Line truncated
This will:
1. Pull the latest image
2. Stop the container
3. Recreate with same settings
The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.disabled=!0,o.title="Updating...");const t=await(await secureFetch(`/api/v1/containers/${c}/update`,{method:"POST"})).json();if(t.success){const e=window.APPS.find(s=>s.id===d);e&&t.newContainerId&&(e.containerId=t.newContainerId),o&&(o.textContent="\u2705",o.title="Updated successfully!",setTimeout(()=>{o.textContent=v,o.disabled=!1,o.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${p} updated successfully!`,"success")}else throw new Error(t.error||"Update failed")}catch(i){console.error("Update error:",i),o&&(o.textContent="\u274C",o.title="Update failed",setTimeout(()=>{o.textContent=v,o.disabled=!1,o.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${p}: ${i.message}`,"error")}}async function y(c,p){const d=window.APPS.find(m=>m.id===c),o=d?buildDomain(d.id):null,v=d?.containerId,i=await h(p||c,v,d?.containerId);if(i===null)return;let t={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(i&&v)try{const m=new URLSearchParams({containerId:d.containerId,subdomain:d.id,ip:d.ip||"localhost",deleteContainer:"true"}),I=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(d.id)}?${m.toString()}`,{method:"DELETE"})).json();I.success?t={...t,...I.results,dashboard:!1}:console.error("App removal failed:",I.error)}catch(m){console.error("App removal error:",m)}else if(i&&o){try{const m=d?.ip||"localhost",I=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(o)}&type=A&ipAddress=${encodeURIComponent(m)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();t.dns=I.success?"deleted":I.error||"failed"}catch(m){t.dns=m.message}try{const x=await(await secureFetch(`/api/v1/site/${encodeURIComponent(o)}`,{method:"DELETE"})).json();t.caddy=x.success||x.error&&x.error.includes("not found")?"removed":x.error||"failed"}catch(m){t.caddy=m.message}}const e=window.APPS.findIndex(m=>m.id===c);e>-1&&(window.APPS.splice(e,1),t.dashboard=!0);try{const m=safeGetJSON("custom-apps",[]),x=m.findIndex(I=>I.id===c);x>-1&&(m.splice(x,1),safeSet("custom-apps",JSON.stringify(m)))}catch{}try{const x=await(await secureFetch(`/api/v1/services/${encodeURIComponent(c)}`,{method:"DELETE"})).json();t.service=x.success?"removed":x.error||"failed"}catch(m){t.service=m.message}window.buildGrid(),window.refreshAll();let s=!1,n=[];t.dashboard||(s=!0,n.push("\u2717 Failed to remove from dashboard"));const r=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],g=m=>!m||r.some(x=>m.toLowerCase().includes(x.toLowerCase()));t.container&&!g(t.container)&&(s=!0,n.push(`\u26A0 Container: ${t.container}`)),t.dns&&!g(t.dns)&&(s=!0,n.push(`\u26A0 DNS Record: ${t.dns}`)),t.caddy&&!g(t.caddy)&&(s=!0,n.push(`\u26A0 Caddy Config: ${t.caddy}`)),t.service&&!g(t.service)&&(s=!0,n.push(`\u26A0 Service File: ${t.service}`)),s&&showNotification(`Error deleting "${p||c}": ${n.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=h,window.updateContainer=u,window.deleteService=y})(),(function(){function l(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function f(){const t=document.getElementById("service-subdomain-input").value||"subdomain",e=document.getElementById("service-ip-input").value||b.lan||"localhost",s=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,n=document.getElementById("ssl-type-select").value,r=document.getElementById("ca-name-input").value||"sami-ca",g=document.getElementById("existing-ca-select").value,m=document.getElementById("enable-auth").checked,x=document.getElementById("enable-cors").checked,I=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,C=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(t)} \u2192 ${e}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(t));const E={subdomain:t,port:s,ip:e,sslType:n,caName:r,existingCa:g,enableAuth:m,enableCors:x,customHeaders:I,upstreamPath:L,healthCheck:P,timeout:C},w=window.generateCaddyConfig(E),S=document.getElementById("caddy-config-preview");S&&(S.value=w)}const b={localhost:"127.0.0.1",lan:"",tailscale:""};async function h(){try{const n=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(n.ok){const r=await n.json();r.lan&&(b.lan=r.lan),r.tailscale&&(b.tailscale=r.tailscale)}}catch{}const t=document.getElementById("quick-ip-lan"),e=document.getElementById("quick-ip-tailscale");t&&(b.lan?(t.dataset.ip=b.lan,t.textContent=`LAN (${b.lan})`,t.title=`LAN IP: ${b.lan}`):t Line truncated
The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.disabled=!0,o.title="Updating...");const t=await(await secureFetch(`/api/v1/containers/${u}/update`,{method:"POST"})).json();if(t.success){const e=window.APPS.find(i=>i.id===a);e&&t.newContainerId&&(e.containerId=t.newContainerId),o&&(o.textContent="\u2705",o.title="Updated successfully!",setTimeout(()=>{o.textContent=g,o.disabled=!1,o.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${l} updated successfully!`,"success")}else throw new Error(t.error||"Update failed")}catch(d){console.error("Update error:",d),o&&(o.textContent="\u274C",o.title="Update failed",setTimeout(()=>{o.textContent=g,o.disabled=!1,o.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${l}: ${d.message}`,"error")}}async function v(u,l){const a=window.APPS.find(p=>p.id===u),o=a?buildDomain(a.id):null,g=a?.containerId,d=await b(l||u,g,a?.containerId);if(d===null)return;let t={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(d&&g)try{const p=new URLSearchParams({containerId:a.containerId,subdomain:a.id,ip:a.ip||"localhost",deleteContainer:"true"}),I=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(a.id)}?${p.toString()}`,{method:"DELETE"})).json();I.success?t={...t,...I.results,dashboard:!1}:console.error("App removal failed:",I.error)}catch(p){console.error("App removal error:",p)}else if(d&&o){try{const p=a?.ip||"localhost",I=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(o)}&type=A&ipAddress=${encodeURIComponent(p)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();t.dns=I.success?"deleted":I.error||"failed"}catch(p){t.dns=p.message}try{const w=await(await secureFetch(`/api/v1/site/${encodeURIComponent(o)}`,{method:"DELETE"})).json();t.caddy=w.success||w.error&&w.error.includes("not found")?"removed":w.error||"failed"}catch(p){t.caddy=p.message}}const e=window.APPS.findIndex(p=>p.id===u);e>-1&&(window.APPS.splice(e,1),t.dashboard=!0);try{const p=safeGetJSON("custom-apps",[]),w=p.findIndex(I=>I.id===u);w>-1&&(p.splice(w,1),safeSet("custom-apps",JSON.stringify(p)))}catch{}try{const w=await(await secureFetch(`/api/v1/services/${encodeURIComponent(u)}`,{method:"DELETE"})).json();t.service=w.success?"removed":w.error||"failed"}catch(p){t.service=p.message}window.buildGrid(),window.refreshAll();let i=!1,n=[];t.dashboard||(i=!0,n.push("\u2717 Failed to remove from dashboard"));const r=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],f=p=>!p||r.some(w=>p.toLowerCase().includes(w.toLowerCase()));t.container&&!f(t.container)&&(i=!0,n.push(`\u26A0 Container: ${t.container}`)),t.dns&&!f(t.dns)&&(i=!0,n.push(`\u26A0 DNS Record: ${t.dns}`)),t.caddy&&!f(t.caddy)&&(i=!0,n.push(`\u26A0 Caddy Config: ${t.caddy}`)),t.service&&!f(t.service)&&(i=!0,n.push(`\u26A0 Service File: ${t.service}`)),i&&showNotification(`Error deleting "${l||u}": ${n.join(", ")}`,"error",6e3)}window.openServiceEditModal=s,window.showDeleteModal=b,window.updateContainer=y,window.deleteService=v})(),(function(){function c(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function s(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function m(){const t=document.getElementById("service-subdomain-input").value||"subdomain",e=document.getElementById("service-ip-input").value||h.lan||"localhost",i=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,n=document.getElementById("ssl-type-select").value,r=document.getElementById("ca-name-input").value||"sami-ca",f=document.getElementById("existing-ca-select").value,p=document.getElementById("enable-auth").checked,w=document.getElementById("enable-cors").checked,I=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,C=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(t)} \u2192 ${e}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(t));const E={subdomain:t,port:i,ip:e,sslType:n,caName:r,existingCa:f,enableAuth:p,enableCors:w,customHeaders:I,upstreamPath:L,healthCheck:P,timeout:C},x=window.generateCaddyConfig(E),S=document.getElementById("caddy-config-preview");S&&(S.value=x)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function b(){try{const n=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(n.ok){const r=await n.json();r.lan&&(h.lan=r.lan),r.tailscale&&(h.tailscale=r.tailscale)}}catch{}const t=document.getElementById("quick-ip-lan"),e=document.getElementById("quick-ip-tailscale");t&&(h.lan?(t.dataset.ip=h.lan,t.textContent=`LAN (${h.lan})`,t.title=`LAN IP: ${h.lan}`):t Line truncated
<span style="color: #4caf50;">\u2713 Connected</span>
<span style="color: var(--muted); margin-left: 6px;">${x.self?.hostname} (${x.self?.ip})</span>
`,g.disabled=!1):x.installed?(r.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',g.disabled=!0):(r.innerHTML='<span style="color: var(--muted);">Not available</span>',g.disabled=!0)}catch{r.innerHTML='<span style="color: var(--muted);">Could not check</span>',g.disabled=!0}g.checked=!1,f()}function c(){const t=document.getElementById("service-type-local"),e=document.getElementById("service-type-external"),s=document.getElementById("local-service-config"),n=document.getElementById("external-service-config"),r=document.getElementById("tab-local"),g=document.getElementById("tab-external");function m(){t.checked?(s.style.display="grid",n.style.display="none",r&&(r.style.background="var(--accent)",r.style.color="var(--bg)"),g&&(g.style.background="transparent",g.style.color="var(--muted)")):(s.style.display="none",n.style.display="block",g&&(g.style.background="var(--accent)",g.style.color="var(--bg)"),r&&(r.style.background="transparent",r.style.color="var(--muted)"))}t?.addEventListener("change",m),e?.addEventListener("change",m)}function p(){const t=document.getElementById("service-name-input"),e=document.getElementById("service-subdomain-input"),s=document.getElementById("subdomain-preview");let n=!1;t?.addEventListener("input",()=>{const L=l(t.value);!n&&e&&(e.value=L),s&&(s.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()}),e?.addEventListener("input",()=>{n=e.value!==l(t?.value||"");const L=e.value.trim()||l(t?.value||"");s&&(s.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()});const r=document.getElementById("external-service-name"),g=document.getElementById("external-service-subdomain"),m=document.getElementById("external-subdomain-preview"),x=document.getElementById("external-domain-preview");let I=!1;r?.addEventListener("input",()=>{const L=l(r.value);!I&&g&&(g.value=L);const P=g?.value||L;m&&(m.textContent=P?`\u2192 ${buildDomain(P)}`:""),x&&(x.textContent=P?buildDomain(P):"")}),g?.addEventListener("input",()=>{I=g.value!==l(r?.value||"");const L=g.value.trim()||l(r?.value||"");m&&(m.textContent=L?`\u2192 ${buildDomain(L)}`:""),x&&(x.textContent=L?buildDomain(L):"")})}async function d(){const t=document.getElementById("external-service-name").value.trim(),e=document.getElementById("external-service-url").value.trim(),s=(document.getElementById("external-service-subdomain").value.trim()||l(t)).toLowerCase(),n=document.getElementById("external-service-logo").value.trim(),r=document.getElementById("external-service-icon").value.trim(),g=document.getElementById("external-create-dns").checked,m=document.getElementById("external-create-caddy").checked,x=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",I=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!t||!e){showNotification("Please fill in Name and External URL","warning");return}if(!s){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!e.startsWith("http://")&&!e.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const C=buildDomain(s);try{const B={dns:null,caddy:null,dashboard:!1};if(g)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:C,ip:x,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(k){B.dns=k.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(m)try{const T={subdomain:s,externalUrl:e,preserveHost:I,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(T){B.caddy=T.message}const $={id:s,name:t,url:`https://${C}`,externalUrl:e,logo:n||r||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const E=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],w=window.APPS.filter(T=>!E.includes(T.id));safeSet("custom-services",JSON.stringify(w));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(T){console.warn("Failed to save to services.json:",T)}window.buildGrid(),window.refreshAll(),o();const S=[`External service "${t}" added!`];g&&S.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),m&&S.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),S.push(`Access at: https://${C}`),showNotification(S.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKiBFcnJvciBIYW5kbGVyXG4gKiBIYW5kbGVzIGVycm9ycyBncmFjZWZ1bGx5IHdpdGhvdXQgYnJlYWtpbmcgdGhlIG9uYm9hcmRpbmcgdG91clxuICovXG5cbihmdW5jdGlvbih3aW5kb3cpIHtcbiAgJ3VzZSBzdHJpY3QnO1xuXG4gIGNsYXNzIEVycm9ySGFuZGxlciB7XG4gICAgY29uc3RydWN0b3IoKSB7XG4gICAgICB0aGlzLmVycm9ycyA9IFtdO1xuICAgICAgdGhpcy5tYXhFcnJvcnMgPSA1MDsgLy8gS2VlcCBsYXN0IDUwIGVycm9yc1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIExvZyBhbiBlcnJvciB3aXRob3V0IGJyZWFraW5nIHRoZSB0b3VyXG4gICAgICogQHBhcmFtIHtzdHJpbmd9IGNvbnRleHQgLSBDb250ZXh0IHdoZXJlIGVycm9yIG9jY3VycmVkXG4gICAgICogQHBhcmFtIHtFcnJvcnxzdHJpbmd9IGVycm9yIC0gVGhlIGVycm9yIG9iamVjdCBvciBtZXNzYWdlXG4gICAgICogQHBhcmFtIHtPYmplY3R9IG1ldGFkYXRhIC0gQWRkaXRpb25hbCBtZXRhZGF0YVxuICAgICAqL1xuICAgIGxvZ0Vycm9yKGNvbnRleHQsIGVycm9yLCBtZXRhZGF0YSA9IHt9KSB7XG4gICAgICBjb25zdCBlc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LyoqXG4gICAgICogQ2xhc3NpZnkgZXJyb3IgdHlwZVxuICAgICAqIEBwcml2YXRlXG4gICAgICogQHBhcmFtIHtFcnJvcn0gZXJyb3IgLSBUaGUgZXJyb3Igb2JqZWN0XG4gICAgICogQHJldHVybnMge3N0cmluZ30gRXJyb3IgdHlwZVxuICAgICAqL1xuICAgIGNsYXNzaWZ5RXJyb3IoZXJyb3IpIHtcbiAgICAgIGNvbnN0IG1lc3NhZ2UgPSBlcnJvci5tZXNzYWdlIHx8IGVycm9yLnRvU3RyaW5nKCk7XG5cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated
<span style="color: var(--muted); margin-left: 6px;">${w.self?.hostname} (${w.self?.ip})</span>
`,f.disabled=!1):w.installed?(r.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',f.disabled=!0):(r.innerHTML='<span style="color: var(--muted);">Not available</span>',f.disabled=!0)}catch{r.innerHTML='<span style="color: var(--muted);">Could not check</span>',f.disabled=!0}f.checked=!1,m()}function u(){const t=document.getElementById("service-type-local"),e=document.getElementById("service-type-external"),i=document.getElementById("local-service-config"),n=document.getElementById("external-service-config"),r=document.getElementById("tab-local"),f=document.getElementById("tab-external");function p(){t.checked?(i.style.display="grid",n.style.display="none",r&&(r.style.background="var(--accent)",r.style.color="var(--bg)"),f&&(f.style.background="transparent",f.style.color="var(--muted)")):(i.style.display="none",n.style.display="block",f&&(f.style.background="var(--accent)",f.style.color="var(--bg)"),r&&(r.style.background="transparent",r.style.color="var(--muted)"))}t?.addEventListener("change",p),e?.addEventListener("change",p)}function l(){const t=document.getElementById("service-name-input"),e=document.getElementById("service-subdomain-input"),i=document.getElementById("subdomain-preview");let n=!1;t?.addEventListener("input",()=>{const L=c(t.value);!n&&e&&(e.value=L),i&&(i.textContent=L?`\u2192 ${buildDomain(L)}`:""),m()}),e?.addEventListener("input",()=>{n=e.value!==c(t?.value||"");const L=e.value.trim()||c(t?.value||"");i&&(i.textContent=L?`\u2192 ${buildDomain(L)}`:""),m()});const r=document.getElementById("external-service-name"),f=document.getElementById("external-service-subdomain"),p=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let I=!1;r?.addEventListener("input",()=>{const L=c(r.value);!I&&f&&(f.value=L);const P=f?.value||L;p&&(p.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),f?.addEventListener("input",()=>{I=f.value!==c(r?.value||"");const L=f.value.trim()||c(r?.value||"");p&&(p.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function a(){const t=document.getElementById("external-service-name").value.trim(),e=document.getElementById("external-service-url").value.trim(),i=(document.getElementById("external-service-subdomain").value.trim()||c(t)).toLowerCase(),n=document.getElementById("external-service-logo").value.trim(),r=document.getElementById("external-service-icon").value.trim(),f=document.getElementById("external-create-dns").checked,p=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",I=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!t||!e){showNotification("Please fill in Name and External URL","warning");return}if(!i){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!e.startsWith("http://")&&!e.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const C=buildDomain(i);try{const B={dns:null,caddy:null,dashboard:!1};if(f)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:C,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(k){B.dns=k.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(p)try{const T={subdomain:i,externalUrl:e,preserveHost:I,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(T){B.caddy=T.message}const $={id:i,name:t,url:`https://${C}`,externalUrl:e,logo:n||r||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const E=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(T=>!E.includes(T.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(T){console.warn("Failed to save to services.json:",T)}window.buildGrid(),window.refreshAll(),o();const S=[`External service "${t}" added!`];f&&S.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),p&&S.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),S.push(`Access at: https://${C}`),showNotification(S.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`F Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLyoqXG4gKi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ZGVzKCdlbGVtZW50JykgJiYgbWVzc2FnZS5pbmNsdWRlcygnbm90IGZvdW5kJykpIHtcbiAgICAgICAgcmV0dXJuICdFTEVNRU5UX05PVF9GT1VORCc7XG4gICAgICB9XG4gICAgICBpZiAobWVzc2FnZS5pbmNsdWRlcygnc3RvcmFnZScpIHx8IG1lc3NhZ2UuaW5jbHVkZXMoJ3F1b3RhJykpIHtcbiAgICAgICAgcmV0dXJuICdTVE9SQUdFX1VOQVZBSUxBQkxFJztcbiAgICAgIH1cbiAgICAgIGlmIChtZXNzYWdlLmluY2x1ZGVzKCdkcml2ZXInKSB8fCBtZXNzYWdlLmluY2x1ZGVzKCd1bmRlZmluZWQnKSkge1xuICAgI Line truncated
+2 -2
View File
@@ -1,4 +1,4 @@
(function(){function v(){const i=safeGet("custom-services");if(i)try{JSON.parse(i).forEach(e=>{window.APPS.find(a=>a.id===e.id)||window.APPS.push(e)})}catch(n){console.warn("Failed to load custom services:",n)}}v();function k(){const i=document.querySelectorAll(".top .card");i.forEach((n,e)=>{n.style.transitionDelay=`${Math.min(e*60,300)}ms`}),requestAnimationFrame(()=>{i.forEach(n=>n.classList.add("loaded"))})}function u(){if(!("serviceWorker"in navigator)||!window.isSecureContext&&location.hostname!=="localhost"&&location.hostname!=="127.0.0.1")return;const i=()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).catch(n=>{console.warn("[init] Service worker registration failed:",n)})};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}let h=!1;async function f(){if(h){console.warn("[init] initializeDashboard called again, skipping duplicate");return}if(h=!0,await window.loadServices(),await y(),window.buildGrid(),k(),window.refreshAll(),setInterval(window.refreshAll,DC.POLL.DASHBOARD),typeof window.refreshCredsButtons=="function"&&window.refreshCredsButtons(),typeof window.refreshMonitoringWidgets=="function"&&window.refreshMonitoringWidgets(),typeof window._updateAuthCard=="function")try{const n=await(await fetch("/api/v1/totp/config",{cache:"no-store"})).json();n.success&&window._updateAuthCard(n.config.enabled&&n.config.isSetUp,n.config.sessionDuration)}catch{}if(window.__dashcaddySiteConfigLoaded)try{await window.__dashcaddySiteConfigLoaded}catch{}if(S(),C()&&b(),window.AdminPanel&&typeof window.AdminPanel.attachTrigger=="function")try{await window.AdminPanel.attachTrigger(document.body)}catch(i){console.warn("[init] AdminPanel attachTrigger failed:",i)}}function b(){if(document.querySelector('script[src="/dist/onboarding.js"]'))return;const i=document.createElement("script");if(i.src="/dist/onboarding.js",i.defer=!0,document.head.appendChild(i),!document.querySelector('link[href="/css/driver.min.css"]')){const n=document.createElement("link");n.rel="stylesheet",n.href="/css/driver.min.css",document.head.appendChild(n)}if(!document.querySelector('link[href="/css/onboarding.css"]')){const n=document.createElement("link");n.rel="stylesheet",n.href="/css/onboarding.css",document.head.appendChild(n)}}function C(){if(typeof SITE<"u"&&SITE.onboardingCompleted)return!1;try{const i=JSON.parse(localStorage.getItem("dashcaddy_onboarding"));return!i||!i.tourCompleted&&i.currentStep===0}catch{return!0}}function E(){const i=document.querySelectorAll(".tools-section");if(!i.length)return;let n={};try{n=JSON.parse(localStorage.getItem("toolbar-sections")||"{}")}catch{}i.forEach(e=>{const a=e.dataset.section,c=e.querySelector(".tools-section-header");c&&(n[a]&&(e.classList.add("open"),c.setAttribute("aria-expanded","true")),c.addEventListener("click",s=>{s.preventDefault();const l=e.classList.toggle("open");c.setAttribute("aria-expanded",l?"true":"false");const m={};document.querySelectorAll(".tools-section").forEach(t=>{m[t.dataset.section]=t.classList.contains("open")}),localStorage.setItem("toolbar-sections",JSON.stringify(m))}))})}E();function S(){if(document.getElementById("restart-tour-btn"))return;let i=typeof SITE<"u"&&SITE.onboardingCompleted;try{const a=JSON.parse(localStorage.getItem("dashcaddy_onboarding"));i=i||!!(a&&a.tourCompleted)}catch{}const n=i?document.querySelector('.tools-section[data-section="admin"] .tools-section-items'):document.querySelector(".tools-primary");if(!n)return;const e=document.createElement("button");e.id="restart-tour-btn",e.textContent=i?"Help Tour":"\u{1F393} Help Tour",e.title="Restart the onboarding tour",e.onclick=()=>{if(window.DashCaddyOnboarding)window.DashCaddyOnboarding.restartTour();else{b();const a=setInterval(()=>{window.DashCaddyOnboarding&&(clearInterval(a),window.DashCaddyOnboarding.restartTour())},100);setTimeout(()=>clearInterval(a),5e3)}},n.appendChild(e)}window.initializeDashboard=f,window.loadCustomServices=v,u();async function y(){try{const i=await fetch("/api/v1/templates",{cache:"no-store"});if(!i.ok)return;const n=await i.json();n&&n.categories&&(window.DC_CATEGORIES=n.categories,typeof DC<"u"&&(DC.CATEGORIES=n.categories),q())}catch(i){console.warn("[init] Failed to load template categories:",i)}}function q(){const i=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES;i&&document.querySelectorAll('select[data-role="service-category"]').forEach(n=>{const e=n.dataset.current||"",a=n.querySelector('option[value=""]');if(n.innerHTML="",a)n.appendChild(a);else{const c=document.createElement("option");c.value="",c.textContent="\u2014 Select category \u2014",n.appendChild(c)}Object.entries(i).forEach(([c,s])=>{const l=document.createElement("option");l.value=c,l.textContent=`${s.icon||""} ${c}`.trim(),c===e&&(l.selected=!0),n.appendChild(l)})})}window.populateCategorySelects=q,window.loadTemplateCategories=y,(async()=>{try{const n=await(await fetch("/api/v1/totp/config",{cache:"no-store"})).json();if(n.success&&Line truncated
(function(){function v(){const i=safeGet("custom-services");if(i)try{JSON.parse(i).forEach(e=>{window.APPS.find(a=>a.id===e.id)||window.APPS.push(e)})}catch(n){console.warn("Failed to load custom services:",n)}}v();function k(){const i=document.querySelectorAll(".top .card");i.forEach((n,e)=>{n.style.transitionDelay=`${Math.min(e*60,300)}ms`}),requestAnimationFrame(()=>{i.forEach(n=>n.classList.add("loaded"))})}function u(){if(!("serviceWorker"in navigator)||!window.isSecureContext&&location.hostname!=="localhost"&&location.hostname!=="127.0.0.1")return;const i=()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).catch(n=>{console.warn("[init] Service worker registration failed:",n)})};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}let h=!1;async function f(){if(h){console.warn("[init] initializeDashboard called again, skipping duplicate");return}if(h=!0,await window.loadServices(),await y(),window.buildGrid(),k(),window.refreshAll(),setInterval(()=>{window._dcAuthLost||window.refreshAll()},DC.POLL.DASHBOARD),typeof window.refreshCredsButtons=="function"&&window.refreshCredsButtons(),typeof window.refreshMonitoringWidgets=="function"&&window.refreshMonitoringWidgets(),typeof window._updateAuthCard=="function")try{const n=await(await fetch("/api/v1/totp/config",{cache:"no-store"})).json();n.success&&window._updateAuthCard(n.config.enabled&&n.config.isSetUp,n.config.sessionDuration)}catch{}if(window.__dashcaddySiteConfigLoaded)try{await window.__dashcaddySiteConfigLoaded}catch{}if(S(),C()&&b(),window.AdminPanel&&typeof window.AdminPanel.attachTrigger=="function")try{await window.AdminPanel.attachTrigger(document.body)}catch(i){console.warn("[init] AdminPanel attachTrigger failed:",i)}}function b(){if(document.querySelector('script[src="/dist/onboarding.js"]'))return;const i=document.createElement("script");if(i.src="/dist/onboarding.js",i.defer=!0,document.head.appendChild(i),!document.querySelector('link[href="/css/driver.min.css"]')){const n=document.createElement("link");n.rel="stylesheet",n.href="/css/driver.min.css",document.head.appendChild(n)}if(!document.querySelector('link[href="/css/onboarding.css"]')){const n=document.createElement("link");n.rel="stylesheet",n.href="/css/onboarding.css",document.head.appendChild(n)}}function C(){if(typeof SITE<"u"&&SITE.onboardingCompleted)return!1;try{const i=JSON.parse(localStorage.getItem("dashcaddy_onboarding"));return!i||!i.tourCompleted&&i.currentStep===0}catch{return!0}}function E(){const i=document.querySelectorAll(".tools-section");if(!i.length)return;let n={};try{n=JSON.parse(localStorage.getItem("toolbar-sections")||"{}")}catch{}i.forEach(e=>{const a=e.dataset.section,c=e.querySelector(".tools-section-header");c&&(n[a]&&(e.classList.add("open"),c.setAttribute("aria-expanded","true")),c.addEventListener("click",s=>{s.preventDefault();const l=e.classList.toggle("open");c.setAttribute("aria-expanded",l?"true":"false");const m={};document.querySelectorAll(".tools-section").forEach(t=>{m[t.dataset.section]=t.classList.contains("open")}),localStorage.setItem("toolbar-sections",JSON.stringify(m))}))})}E();function S(){if(document.getElementById("restart-tour-btn"))return;let i=typeof SITE<"u"&&SITE.onboardingCompleted;try{const a=JSON.parse(localStorage.getItem("dashcaddy_onboarding"));i=i||!!(a&&a.tourCompleted)}catch{}const n=i?document.querySelector('.tools-section[data-section="admin"] .tools-section-items'):document.querySelector(".tools-primary");if(!n)return;const e=document.createElement("button");e.id="restart-tour-btn",e.textContent=i?"Help Tour":"\u{1F393} Help Tour",e.title="Restart the onboarding tour",e.onclick=()=>{if(window.DashCaddyOnboarding)window.DashCaddyOnboarding.restartTour();else{b();const a=setInterval(()=>{window.DashCaddyOnboarding&&(clearInterval(a),window.DashCaddyOnboarding.restartTour())},100);setTimeout(()=>clearInterval(a),5e3)}},n.appendChild(e)}window.initializeDashboard=f,window.loadCustomServices=v,u();async function y(){try{const i=await fetch("/api/v1/templates",{cache:"no-store"});if(!i.ok)return;const n=await i.json();n&&n.categories&&(window.DC_CATEGORIES=n.categories,typeof DC<"u"&&(DC.CATEGORIES=n.categories),q())}catch(i){console.warn("[init] Failed to load template categories:",i)}}function q(){const i=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES;i&&document.querySelectorAll('select[data-role="service-category"]').forEach(n=>{const e=n.dataset.current||"",a=n.querySelector('option[value=""]');if(n.innerHTML="",a)n.appendChild(a);else{const c=document.createElement("option");c.value="",c.textContent="\u2014 Select category \u2014",n.appendChild(c)}Object.entries(i).forEach(([c,s])=>{const l=document.createElement("option");l.value=c,l.textContent=`${s.icon||""} ${c}`.trim(),c===e&&(l.selected=!0),n.appendChild(l)})})}window.populateCategorySelects=q,window.loadTemplateCategories=y,(async()=>{try{const n=await(await fetch("/api/v1/totp/config",{cache:"no-stoLine truncated
.dc-monitor {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
@@ -329,4 +329,4 @@
<span class="quick-search-item-badge">${r.status.toUpperCase()}</span>
</div>
`})),o||(o='<div class="quick-search-empty">No results found</div>'),f.innerHTML=o,s()}function s(){f.querySelectorAll(".quick-search-item").forEach((o,r)=>{o.addEventListener("click",()=>m(o)),r===0&&o.classList.add("selected")})}function l(t){try{const o=f.querySelectorAll(".quick-search-item"),r=f.querySelector(".quick-search-item.selected"),p=Array.from(o).indexOf(r);if(t.key==="ArrowDown"){t.preventDefault(),r&&r.classList.remove("selected");const d=(p+1)%o.length;o[d]?.classList.add("selected"),o[d]?.scrollIntoView({block:"nearest"})}else if(t.key==="ArrowUp"){t.preventDefault(),r&&r.classList.remove("selected");const d=p<=0?o.length-1:p-1;o[d]?.classList.add("selected"),o[d]?.scrollIntoView({block:"nearest"})}else t.key==="Enter"&&(t.preventDefault(),r&&m(r))}catch(o){console.warn("[Keyboard Shortcuts] Error handling search navigation:",o.message)}}function m(t){try{const o=t.dataset.action,r=t.dataset.service;switch(y(),o){case"refresh":document.getElementById("refresh")?.click();break;case"reload-caddy":document.getElementById("reload-caddy-top")?.click();break;case"add-service":document.getElementById("add-service")?.click();break;case"app-selector":document.getElementById("add-service-btn")?.click();break;case"backup":document.getElementById("backup-restore-btn")?.click();break;case"stats":document.getElementById("container-stats-btn")?.click();break;case"logs":document.getElementById("view-error-logs")?.click();break;case"tokens":document.getElementById("manage-tokens")?.click();break;case"notifications":document.getElementById("manage-notifications")?.click();break;case"theme":document.getElementById("theme")?.click();break;case"tour":document.getElementById("restart-tour-btn")?.click();break;case"open-service":if(r){const p=document.querySelector(`[data-app="${r}"] [id$="-open"], [data-app="${r}"] button:not(.restart-btn):not(.logs-btn):not(.settings-btn)`);if(p)p.click();else{const d=document.querySelector(`[data-app="${r}"]`);d&&d.click()}}break;default:v("[Keyboard Shortcuts] Unknown action:",o)}}catch(o){console.warn("[Keyboard Shortcuts] Error executing action:",o.message)}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",b):b(),window.DashCaddyKeyboardShortcuts={openQuickSearch:S,closeQuickSearch:y}})();
//# sourceMappingURL=data:application/json;base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gIGlmIChzaG91bGRMb2FkT25ib2FyZGluZygpKSB7XG4gICAgICBsb2FkT25ib2FyZGluZygpO1xuICAgIH1cblxuICAgIC8vIERDLTA0ODogaW5qZWN0IHRoZSBcIkFkbWluXCIgdHJpZ2dlciBidXR0b24gaW50byB0aGUgdG9wIGJhci4gVGhlXG4gICAgLy8gYnV0dG9uIG9ubHkgcmVuZGVycyB3aGVuIC9tZSByZXR1cm5zIGlzQWRtaW49dHJ1ZTsgdGhlIG1vZHVsZVxuICAgIC8vIHJlLWNoZWNrcyBldmVyeSA2MHMgc28gYSBwZXJtaXNzaW9uIGRvd25ncmFkZSB0YWtlcyBlZmZlY3QuXG4gICAgaWYgKHdpbmRvdy5BZG1pblBhbmVsICYmIHR5cGVvZiB3aW5kb3cuQWRtaW5QYW5lbC5hdHRhY2hUcmlnZ2VyID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICB0cnkge1xuICAgICAgICBhd2FpdCB3aW5kb3cuQWRtaW5QYW5lbC5hdHRhY2hUcmlnZ2VyKGRvY3VtZW50LmJvZHkpO1xuICAgICAgfSBjYXRjaCAoZ Line truncated
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gPT09PT09PT09PSBEQVNIQk9BUkQgSU5JVElBTElaQVRJT04gPT09PT09PT09PVxuKGZ1bmN0aW9uICgpIHtcblxuICBmdW5jdGlvbiBsb2FkQ3VzdG9tU2VydmljZXMoKSB7XG4gICAgY29uc3QgY3VzdG9tU2VydmljZXMgPSBzYWZlR2V0KCdjdXN0b20tc2VydmljZXMnKTtcbiAgICBpZiAoY3VzdG9tU2VydmljZXMpIHtcbiAgICAgIHRyeSB7XG4gICAgICAgIGNvbnN0IHNlcnZpY2VzID0gSlNPTi5wYXJzZShjdXN0b21TZXJ2aWNlcyk7XG4gICAgICAgIC8vIE1lcmdlIHdpdGggZGVmYXVsdC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3AgYmFyLiBUaGVcbiAgICAvLyBidXR0b24gb25seSByZW5kZXJzIHdoZW4gL21lIHJldHVybnMgaXNBZG1pbj10cnVlOyB0aGUgbW9kdWxlXG4gICAgLy8gcmUtY2hlY2tzIGV2ZXJ5IDYwcyBzbyBhI Line truncated
+18 -1
View File
@@ -365,6 +365,9 @@
}
async function refreshAll() {
// Skip if auth has been lost (e.g. TOTP gate activated externally).
// The polling interval in init.js also checks this flag.
if (window._dcAuthLost) return;
if (refreshInFlight) {
refreshQueued = true;
return refreshInFlight;
@@ -417,9 +420,21 @@
refreshInFlight = (async () => {
try {
const response = await fetch('/api/v1/services/status', { cache: 'no-store' });
if (response.status === 401 || response.status === 403) {
// Auth lost — stop the polling loop and close SSE; do NOT fall
// through to direct probes (those would misleadingly mark
// services as healthy since /probe/ treats 401/403 as "up").
window._dcAuthLost = true;
if (window._sseReconnect && window._sseClose) {
window._sseClose(); // tell SSE to stop reconnecting
}
updateStamp('auth required');
return; // skip the fallback entirely
}
if (!response.ok) {
throw new Error(`Status refresh failed (${response.status})`);
}
window._dcAuthLost = false; // auth working again
const data = await response.json();
applyBatchResults(data.statuses || {});
updateStamp('last check', data.checkedAt || new Date());
@@ -434,9 +449,11 @@
}
} finally {
refreshInFlight = null;
if (refreshQueued) {
if (refreshQueued && !window._dcAuthLost) {
refreshQueued = false;
setTimeout(() => { window.refreshAll(); }, 0);
} else {
refreshQueued = false;
}
}
})();
+6 -1
View File
@@ -63,7 +63,12 @@
window.buildGrid();
animateTopCards();
window.refreshAll();
setInterval(window.refreshAll, DC.POLL.DASHBOARD);
setInterval(() => {
// Stop polling if the session has been invalidated (e.g. TOTP gate
// now active, or user logged out). Avoids relentless 401/403 noise.
if (window._dcAuthLost) return;
window.refreshAll();
}, DC.POLL.DASHBOARD);
if (typeof window.refreshCredsButtons === 'function') window.refreshCredsButtons();
if (typeof window.refreshMonitoringWidgets === 'function') window.refreshMonitoringWidgets();
// Update auth card (may have already been updated by the auto-load IIFE but ensure it's correct)
+36 -1
View File
@@ -3,14 +3,18 @@
let es = null;
let reconnectDelay = 1000;
const MAX_RECONNECT = 30000;
let _sseFailCount = 0;
let _sseManuallyClosed = false;
function connect() {
if (es) { try { es.close(); } catch (_) {} }
if (_sseManuallyClosed) return; // auth-lost: don't reconnect
es = new EventSource('/api/v1/events/stream');
es.addEventListener('connected', () => {
reconnectDelay = 1000; // reset backoff
_sseFailCount = 0; // reset failure counter
debug('[SSE] Connected to event stream');
});
@@ -101,15 +105,46 @@
// Reconnect on error
es.onerror = () => {
es.close();
// If auth was explicitly lost (401/403 from the polling loop),
// don't attempt reconnection at all.
if (window._dcAuthLost || _sseManuallyClosed) {
console.warn('[SSE] Auth lost — stopping reconnection');
return;
}
// Transient failures: retry with exponential backoff, stop after 5
_sseFailCount++;
if (_sseFailCount > 5) {
console.warn('[SSE] Max reconnect attempts reached — stopping (server unreachable)');
return;
}
console.warn(`[SSE] Disconnected, reconnecting in ${reconnectDelay / 1000}s...`);
setTimeout(connect, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT);
};
}
// Called by grid.js when the polling loop detects auth loss (401/403)
function closeAndStop() {
_sseManuallyClosed = true;
if (es) { try { es.close(); } catch (_) {} }
}
// Called by totp-auth.js after a successful mid-session re-auth:
// clears the latch so connect() can proceed again and resets the
// failure backoff. (Plain _sseReconnect/connect() would early-return
// on the latch forever — the user would need a manual F5.)
function resumeAfterReauth() {
_sseManuallyClosed = false;
_sseFailCount = 0;
reconnectDelay = 1000;
connect();
}
// Start on page load
connect();
// Expose for debugging
// Expose for debugging and cross-module coordination
window._sseReconnect = connect;
window._sseClose = closeAndStop;
window._sseResume = resumeAfterReauth;
})();
+9
View File
@@ -125,6 +125,15 @@
if (typeof window.initializeDashboard === 'function') {
window.initializeDashboard();
}
// Resume live updates after mid-session re-auth. The auth-loss
// handlers latched polling + SSE off when the session expired
// (grid.js sets _dcAuthLost, live-events.js latches the stream
// closed); a fresh login must clear both and reconnect, or the
// dashboard stays frozen on stale data until a manual F5.
window._dcAuthLost = false;
if (typeof window._sseResume === 'function') window._sseResume();
else if (typeof window._sseReconnect === 'function') window._sseReconnect();
if (typeof window.refreshAll === 'function') window.refreshAll();
} else {
errorEl.textContent = data.error || 'Invalid code';
errorEl.className = 'totp-error';
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-4a75cb88af';
const CACHE = 'dashcaddy-shell-78eab743c2';
const PRECACHE = [
'/',
'/index.html',