Debian Codegraph @

docs/static/js/config-generator.js

raw
1 // Config Generator for ntfy
2 //
3 // Warning, AI code
4 // ----------------
5 // This code is entirely AI generated, but this very comment is not. Phil wrote this. Hi!
6 // I felt like the Config Generator was a great feature to have, but it would have taken me forever
7 // to write this code without AI. I reviewed the code manually, and it doesn't do anything dangerous.
8 // It's not the greatest code, but it works well enough to deliver value, and that's what it's all about.
9 //
10 // End of human comment. ;)
11 //
12 // How it works
13 // ------------
14 // The generator is a modal with a left panel (form inputs) and a right panel (live output).
15 // On every input change, the update cycle runs: updateVisibility() syncs the UI state, then
16 // updateOutput() collects values from the form and renders them as server.yml, docker-compose.yml,
17 // or env vars.
18 //
19 // The CONFIG array is the source of truth for which config keys exist, their env var names,
20 // which section they belong to, and optional defaults. collectValues() walks CONFIG, reads each
21 // matching DOM element, skips anything in a hidden panel or section, and returns a plain
22 // {key: value} object. The three generators (generateServerYml, generateDockerCompose,
23 // generateEnvVars) each iterate CONFIG in order and format the collected values. Provisioned
24 // users, ACLs, and tokens are collected separately from repeatable rows and stored as arrays
25 // under "_auth-users", "_auth-acls", "_auth-tokens". The formatAuthUsers/Acls/Tokens() helpers
26 // turn those arrays into "user:pass:role" strings shared by all three generators.
27 //
28 // Visibility is managed by updateVisibility(), which delegates to five helpers:
29 // syncRadiosToHiddenInputs() copies user-facing radios and selects to hidden inputs that CONFIG
30 // knows about (e.g. login mode radio → enable-login + require-login checkboxes).
31 // updateFeatureVisibility() shows/hides nav tabs, configure buttons, and email sections based
32 // on which feature checkboxes are checked. updatePostgresFields() swaps file-path inputs for
33 // "Using PostgreSQL" labels when PostgreSQL is selected. prefillDefaults() sets sensible values
34 // (file paths, addresses) when a feature is first enabled, tracked via a data-cleared attribute
35 // so user edits are respected. autoDetectServerType() flips the server-type radio to "custom"
36 // if the user's access/login settings no longer match "open" or "private".
37 //
38 // Event listeners are grouped into setup functions (setupModalEvents, setupAuthEvents,
39 // setupServerTypeEvents, setupUnifiedPushEvents, setupFormListeners, setupWebPushEvents)
40 // called from initGenerator().
41 // A general listener on all inputs calls the update cycle. Specific listeners handle cleanup
42 // logic, e.g. unchecking auth resets all auth-related fields and provisioned rows.
43 //
44 // Frequently-used DOM elements are queried once in cacheElements() and passed around as an
45 // `els` object, avoiding repeated querySelector calls.
46 //
47 // Field inter-dependencies
48 // ------------------------
49 // Several UI fields don't map 1:1 to config keys. Instead, user-friendly controls drive
50 // hidden inputs that CONFIG knows about. The sync happens in syncRadiosToHiddenInputs(),
51 // called on every change via updateVisibility().
52 //
53 // Server type (Open / Private / Custom)
54 // "Open" → unchecks auth, sets default-access to read-write, login to disabled
55 // "Private" → checks auth, sets default-access to deny-all, login to required
56 // "Custom" → no automatic changes; also auto-selected when the user manually
57 // changes access/login to values that don't match Open or Private
58 //
59 // Auth checkbox (#cg-feat-auth)
60 // When unchecked → resets: default-access to read-write, login to disabled,
61 // signup to no, UnifiedPush to no, removes all provisioned users/ACLs/tokens,
62 // clears auth-file, switches server type back to Open.
63 // Also explicitly unchecks hidden enable-login, require-login, enable-signup.
64 // When checked by PostgreSQL auto-enable → no reset, just enables the tab.
65 //
66 // Login mode (Disabled / Enabled / Required) — three-way radio
67 // Maps to two hidden checkboxes:
68 // enable-login = checked when Enabled OR Required
69 // require-login = checked when Required only
70 //
71 // Signup (Yes / No) — radio pair
72 // Maps to hidden enable-signup checkbox.
73 //
74 // Proxy (Yes / No) — radio pair
75 // Maps to hidden behind-proxy checkbox.
76 //
77 // iOS support (Yes / No) — radio pair
78 // Sets upstream-base-url to "https://ntfy.sh" when Yes, clears when No.
79 //
80 // UnifiedPush (Yes / No) — radio pair
81 // When Yes, enables auth (if not already on) and adds a disabled "*:up*:write-only"
82 // ACL row to the Users tab. The row's fields are grayed out and non-editable. It is
83 // collected like any other ACL row. Clicking its [x] removes the row and toggles
84 // UnifiedPush back to No.
85 //
86 // Database type (SQLite / PostgreSQL)
87 // When PostgreSQL is selected:
88 // - Auto-enables auth if not already on
89 // - Hides file-path fields (auth-file, cache-file, web-push-file) and shows
90 // "Using PostgreSQL" labels instead
91 // - Shows the Database nav tab for the database-url field
92 // - Prefills database-url with a postgres:// template
93 // The database question itself only appears when a DB-dependent feature
94 // (auth, cache, or web push) is enabled.
95 //
96 // Feature checkboxes (auth, cache, attachments, web push, email out, email in)
97 // Each shows/hides its nav tab and "Configure" button.
98 // When first enabled, prefillDefaults() fills in sensible paths/values.
99 // The prefill is skipped if the user has already typed (or cleared) the field
100 // (tracked via data-cleared attribute).
101 //
102 (function() {
103 "use strict";
104
105 const CONFIG = [
106 { key: "base-url", env: "NTFY_BASE_URL", section: "basic" },
107 { key: "behind-proxy", env: "NTFY_BEHIND_PROXY", section: "basic", type: "bool" },
108 { key: "database-url", env: "NTFY_DATABASE_URL", section: "database" },
109 { key: "auth-file", env: "NTFY_AUTH_FILE", section: "auth" },
110 { key: "auth-default-access", env: "NTFY_AUTH_DEFAULT_ACCESS", section: "auth", def: "read-write" },
111 { key: "enable-login", env: "NTFY_ENABLE_LOGIN", section: "auth", type: "bool" },
112 { key: "require-login", env: "NTFY_REQUIRE_LOGIN", section: "auth", type: "bool" },
113 { key: "enable-signup", env: "NTFY_ENABLE_SIGNUP", section: "auth", type: "bool" },
114 { key: "attachment-cache-dir", env: "NTFY_ATTACHMENT_CACHE_DIR", section: "attach" },
115 { key: "attachment-file-size-limit", env: "NTFY_ATTACHMENT_FILE_SIZE_LIMIT", section: "attach", def: "15M" },
116 { key: "attachment-total-size-limit", env: "NTFY_ATTACHMENT_TOTAL_SIZE_LIMIT", section: "attach", def: "5G" },
117 { key: "attachment-expiry-duration", env: "NTFY_ATTACHMENT_EXPIRY_DURATION", section: "attach", def: "3h" },
118 { key: "cache-file", env: "NTFY_CACHE_FILE", section: "cache" },
119 { key: "cache-duration", env: "NTFY_CACHE_DURATION", section: "cache", def: "12h" },
120 { key: "web-push-public-key", env: "NTFY_WEB_PUSH_PUBLIC_KEY", section: "webpush" },
121 { key: "web-push-private-key", env: "NTFY_WEB_PUSH_PRIVATE_KEY", section: "webpush" },
122 { key: "web-push-file", env: "NTFY_WEB_PUSH_FILE", section: "webpush" },
123 { key: "web-push-email-address", env: "NTFY_WEB_PUSH_EMAIL_ADDRESS", section: "webpush" },
124 { key: "smtp-sender-addr", env: "NTFY_SMTP_SENDER_ADDR", section: "smtp-out" },
125 { key: "smtp-sender-from", env: "NTFY_SMTP_SENDER_FROM", section: "smtp-out" },
126 { key: "smtp-sender-user", env: "NTFY_SMTP_SENDER_USER", section: "smtp-out" },
127 { key: "smtp-sender-pass", env: "NTFY_SMTP_SENDER_PASS", section: "smtp-out" },
128 { key: "smtp-sender-verify", env: "NTFY_SMTP_SENDER_VERIFY", section: "smtp-out", type: "bool" },
129 { key: "smtp-server-listen", env: "NTFY_SMTP_SERVER_LISTEN", section: "smtp-in" },
130 { key: "smtp-server-domain", env: "NTFY_SMTP_SERVER_DOMAIN", section: "smtp-in" },
131 { key: "smtp-server-addr-prefix", env: "NTFY_SMTP_SERVER_ADDR_PREFIX", section: "smtp-in" },
132 { key: "upstream-base-url", env: "NTFY_UPSTREAM_BASE_URL", section: "upstream" }
133 ];
134
135 // Feature checkbox → nav tab ID
136 const NAV_MAP = {
137 "cg-feat-auth": "cg-nav-auth",
138 "cg-feat-cache": "cg-nav-cache",
139 "cg-feat-attach": "cg-nav-attach",
140 "cg-feat-webpush": "cg-nav-webpush"
141 };
142
143 const SECTION_COMMENTS = {
144 basic: "# Server",
145 database: "# Database",
146 auth: "# Access control",
147 attach: "# Attachments",
148 cache: "# Message cache",
149 webpush: "# Web push",
150 "smtp-out": "# Email notifications (outgoing)",
151 "smtp-in": "# Email publishing (incoming)",
152 upstream: "# Upstream"
153 };
154
155 const durationRegex = /^(\d+)\s*(d|days?|h|hours?|m|mins?|minutes?|s|secs?|seconds?)$/i;
156 const sizeRegex = /^(\d+)([tgmkb])?$/i;
157
158 // --- DOM cache ---
159
160 function cacheElements(modal) {
161 return {
162 modal,
163 authCheckbox: modal.querySelector("#cg-feat-auth"),
164 cacheCheckbox: modal.querySelector("#cg-feat-cache"),
165 attachCheckbox: modal.querySelector("#cg-feat-attach"),
166 webpushCheckbox: modal.querySelector("#cg-feat-webpush"),
167 smtpOutCheckbox: modal.querySelector("#cg-feat-smtp-out"),
168 smtpInCheckbox: modal.querySelector("#cg-feat-smtp-in"),
169 accessSelect: modal.querySelector("#cg-default-access-select"),
170 accessHidden: modal.querySelector("input[type=\"hidden\"][data-key=\"auth-default-access\"]"),
171 loginHidden: modal.querySelector("#cg-enable-login-hidden"),
172 requireLoginHidden: modal.querySelector("#cg-require-login-hidden"),
173 signupHidden: modal.querySelector("#cg-enable-signup-hidden"),
174 proxyCheckbox: modal.querySelector("#cg-behind-proxy"),
175 smtpSenderVerifyHidden: modal.querySelector("#cg-smtp-sender-verify-hidden"),
176 dbStep: modal.querySelector("#cg-wizard-db"),
177 navDb: modal.querySelector("#cg-nav-database"),
178 navEmail: modal.querySelector("#cg-nav-email"),
179 emailOutSection: modal.querySelector("#cg-email-out-section"),
180 emailInSection: modal.querySelector("#cg-email-in-section"),
181 codeEl: modal.querySelector("#cg-code"),
182 warningsEl: modal.querySelector("#cg-warnings")
183 };
184 }
185
186 // --- Collect values ---
187
188 function collectValues(els) {
189 const { modal } = els;
190 const values = {};
191
192 CONFIG.forEach((c) => {
193 const el = modal.querySelector(`[data-key="${c.key}"]`);
194 if (!el) return;
195
196 // Skip fields in hidden panels (feature not enabled)
197 const panel = el.closest(".cg-panel");
198 if (panel) {
199 // Panel hidden directly
200 if (panel.style.display === "none" || panel.classList.contains("cg-hidden")) return;
201 // Panel with a nav tab that is hidden (feature not enabled)
202 if (!panel.classList.contains("active")) {
203 const panelId = panel.id;
204 const navTab = modal.querySelector(`[data-panel="${panelId}"]`);
205 if (!navTab || navTab.classList.contains("cg-hidden")) return;
206 }
207 }
208
209 // Skip file inputs replaced by PostgreSQL
210 if (el.dataset.pgDisabled) return;
211
212 // Skip hidden individual fields or sections
213 let ancestor = el.parentElement;
214 while (ancestor && ancestor !== modal) {
215 if (ancestor.style.display === "none" || ancestor.classList.contains("cg-hidden")) return;
216 ancestor = ancestor.parentElement;
217 }
218
219 let val;
220 if (c.type === "bool") {
221 if (el.checked) val = "true";
222 } else {
223 val = el.value.trim();
224 if (!val) return;
225 }
226 if (val && c.def && val === c.def) return;
227 if (val) values[c.key] = val;
228 });
229
230 // Provisioned users
231 const users = collectRepeatableRows(modal, ".cg-auth-user-row", (row) => {
232 const u = row.querySelector("[data-field=\"username\"]");
233 const p = row.querySelector("[data-field=\"password\"]");
234 const r = row.querySelector("[data-field=\"role\"]");
235 if (u && p && u.value.trim() && p.value.trim()) {
236 return { username: u.value.trim(), password: p.value.trim(), role: r ? r.value : "user" };
237 }
238 return null;
239 });
240 if (users.length) values["_auth-users"] = users;
241
242 // Provisioned ACLs
243 const acls = collectRepeatableRows(modal, ".cg-auth-acl-row", (row) => {
244 const u = row.querySelector("[data-field=\"username\"]");
245 const t = row.querySelector("[data-field=\"topic\"]");
246 const p = row.querySelector("[data-field=\"permission\"]");
247 if (u && t && t.value.trim()) {
248 return { user: u.value.trim(), topic: t.value.trim(), permission: p ? p.value : "read-write" };
249 }
250 return null;
251 });
252 if (acls.length) values["_auth-acls"] = acls;
253
254 // Provisioned tokens
255 const tokens = collectRepeatableRows(modal, ".cg-auth-token-row", (row) => {
256 const u = row.querySelector("[data-field=\"username\"]");
257 const t = row.querySelector("[data-field=\"token\"]");
258 const l = row.querySelector("[data-field=\"label\"]");
259 if (u && t && u.value.trim() && t.value.trim()) {
260 return { user: u.value.trim(), token: t.value.trim(), label: l ? l.value.trim() : "" };
261 }
262 return null;
263 });
264 if (tokens.length) values["_auth-tokens"] = tokens;
265
266 return values;
267 }
268
269 function collectRepeatableRows(modal, selector, extractor) {
270 const results = [];
271 modal.querySelectorAll(selector).forEach((row) => {
272 const item = extractor(row);
273 if (item) results.push(item);
274 });
275 return results;
276 }
277
278 // --- Shared auth formatting ---
279
280 const bcryptCache = {};
281
282 function hashPassword(username, password) {
283 if (password.startsWith("$2")) return password; // already a bcrypt hash
284 const cacheKey = username + "\0" + password;
285 if (bcryptCache[cacheKey]) return bcryptCache[cacheKey];
286 const hash = (typeof bcrypt !== "undefined") ? bcrypt.hashSync(password, 10) : password;
287 bcryptCache[cacheKey] = hash;
288 return hash;
289 }
290
291 function formatAuthUsers(values) {
292 if (!values["_auth-users"]) return null;
293 return values["_auth-users"].map((u) => `${u.username}:${hashPassword(u.username, u.password)}:${u.role}`);
294 }
295
296 function formatAuthAcls(values) {
297 if (!values["_auth-acls"]) return null;
298 return values["_auth-acls"].map((a) => `${a.user || "*"}:${a.topic}:${a.permission}`);
299 }
300
301 function formatAuthTokens(values) {
302 if (!values["_auth-tokens"]) return null;
303 return values["_auth-tokens"].map((t) => t.label ? `${t.user}:${t.token}:${t.label}` : `${t.user}:${t.token}`);
304 }
305
306 // --- Output generators ---
307
308 function generateServerYml(values) {
309 const lines = [];
310 let lastSection = "";
311 let hadAuth = false;
312
313 CONFIG.forEach((c) => {
314 if (!(c.key in values)) return;
315 if (c.section !== lastSection) {
316 if (lines.length) lines.push("");
317 if (SECTION_COMMENTS[c.section]) lines.push(SECTION_COMMENTS[c.section]);
318 lastSection = c.section;
319 }
320 if (c.section === "auth") hadAuth = true;
321 const val = values[c.key];
322 lines.push(c.type === "bool" ? `${c.key}: true` : `${c.key}: "${escapeYamlValue(val)}"`);
323 });
324
325 // Find insertion point for auth-users/auth-access/auth-tokens:
326 // right after the last "auth-" prefixed line, before enable-*/require-* lines
327 let authInsertIdx = lines.length;
328 if (hadAuth) {
329 for (let i = 0; i < lines.length; i++) {
330 if (lines[i] === "# Access control") {
331 // Find the last auth-* prefixed key in this section
332 let lastAuthKey = i;
333 for (let j = i + 1; j < lines.length; j++) {
334 if (lines[j].startsWith("# ")) break;
335 if (lines[j].startsWith("auth-")) lastAuthKey = j;
336 }
337 authInsertIdx = lastAuthKey + 1;
338 break;
339 }
340 }
341 }
342
343 const authExtra = [];
344 const users = formatAuthUsers(values);
345 if (users) {
346 if (!hadAuth) {
347 authExtra.push("");
348 authExtra.push("# Access control");
349 hadAuth = true;
350 }
351 authExtra.push("auth-users:");
352 users.forEach((entry) => authExtra.push(` - "${escapeYamlValue(entry)}"`));
353 }
354
355 const acls = formatAuthAcls(values);
356 if (acls) {
357 if (!hadAuth) {
358 authExtra.push("");
359 authExtra.push("# Access control");
360 hadAuth = true;
361 }
362 authExtra.push("auth-access:");
363 acls.forEach((entry) => authExtra.push(` - "${escapeYamlValue(entry)}"`));
364 }
365
366 const tokens = formatAuthTokens(values);
367 if (tokens) {
368 if (!hadAuth) {
369 authExtra.push("");
370 authExtra.push("# Access control");
371 hadAuth = true;
372 }
373 authExtra.push("auth-tokens:");
374 tokens.forEach((entry) => authExtra.push(` - "${escapeYamlValue(entry)}"`));
375 }
376
377 // Splice auth extras into the right position
378 if (authExtra.length) {
379 lines.splice(authInsertIdx, 0, ...authExtra);
380 }
381
382 return lines.join("\n");
383 }
384
385 function generateDockerCompose(values) {
386 const lines = [
387 "services:",
388 " ntfy:",
389 " image: binwiederhier/ntfy",
390 " command: serve",
391 " environment:"
392 ];
393
394 let hasDollarNote = false;
395 CONFIG.forEach((c) => {
396 if (!(c.key in values)) return;
397 let val = c.type === "bool" ? "true" : values[c.key];
398 if (val.includes("$")) {
399 val = val.replace(/\$/g, "$$$$");
400 hasDollarNote = true;
401 }
402 lines.push(` ${c.env}: "${escapeYamlValue(val)}"`);
403 });
404
405 const users = formatAuthUsers(values);
406 if (users) {
407 let usersVal = users.join(",");
408 usersVal = usersVal.replace(/\$/g, "$$$$");
409 hasDollarNote = true;
410 lines.push(` NTFY_AUTH_USERS: "${escapeYamlValue(usersVal)}"`);
411 }
412
413 const acls = formatAuthAcls(values);
414 if (acls) {
415 lines.push(` NTFY_AUTH_ACCESS: "${escapeYamlValue(acls.join(","))}"`);
416 }
417
418 const tokens = formatAuthTokens(values);
419 if (tokens) {
420 lines.push(` NTFY_AUTH_TOKENS: "${escapeYamlValue(tokens.join(","))}"`);
421 }
422
423 if (hasDollarNote) {
424 // Insert note after "environment:" line
425 const envIdx = lines.indexOf(" environment:");
426 if (envIdx !== -1) {
427 lines.splice(envIdx + 1, 0, " # Note: $ is doubled to $$ for docker-compose");
428 }
429 }
430
431 // Derive volumes from configured file/directory paths
432 const dirs = new Set();
433 ["auth-file", "cache-file", "web-push-file"].forEach((key) => {
434 if (values[key]) {
435 const dir = values[key].substring(0, values[key].lastIndexOf("/"));
436 if (dir) dirs.add(dir);
437 }
438 });
439 if (values["attachment-cache-dir"]) {
440 dirs.add(values["attachment-cache-dir"]);
441 }
442
443 if (dirs.size) {
444 lines.push(" volumes:");
445 [...dirs].sort().forEach((dir) => {
446 lines.push(` - ${dir}:${dir}`);
447 });
448 }
449
450 lines.push(
451 " ports:",
452 " - \"80:80\"",
453 " restart: unless-stopped"
454 );
455
456 return lines.join("\n");
457 }
458
459 function generateEnvVars(values) {
460 const lines = [];
461
462 CONFIG.forEach((c) => {
463 if (!(c.key in values)) return;
464 const val = c.type === "bool" ? "true" : values[c.key];
465 lines.push(`${c.env}=${escapeShellValue(val)}`);
466 });
467
468 const users = formatAuthUsers(values);
469 if (users) {
470 lines.push(`NTFY_AUTH_USERS=${escapeShellValue(users.join(","))}`);
471 }
472
473 const acls = formatAuthAcls(values);
474 if (acls) {
475 lines.push(`NTFY_AUTH_ACCESS=${escapeShellValue(acls.join(","))}`);
476 }
477
478 const tokens = formatAuthTokens(values);
479 if (tokens) {
480 lines.push(`NTFY_AUTH_TOKENS=${escapeShellValue(tokens.join(","))}`);
481 }
482
483 return lines.join("\n");
484 }
485
486 // --- Web Push VAPID key generation (P-256 ECDH) ---
487
488 function generateVAPIDKeys() {
489 return crypto.subtle.generateKey(
490 { name: "ECDH", namedCurve: "P-256" },
491 true,
492 ["deriveBits"]
493 ).then((keyPair) => {
494 return Promise.all([
495 crypto.subtle.exportKey("raw", keyPair.publicKey),
496 crypto.subtle.exportKey("pkcs8", keyPair.privateKey)
497 ]);
498 }).then((keys) => {
499 const pubBytes = new Uint8Array(keys[0]);
500 const privPkcs8 = new Uint8Array(keys[1]);
501 // Extract raw 32-byte private key from PKCS#8 (last 32 bytes of the DER)
502 const privBytes = privPkcs8.slice(privPkcs8.length - 32);
503 return {
504 publicKey: arrayToBase64Url(pubBytes),
505 privateKey: arrayToBase64Url(privBytes)
506 };
507 });
508 }
509
510 function arrayToBase64Url(arr) {
511 let str = "";
512 for (let i = 0; i < arr.length; i++) {
513 str += String.fromCharCode(arr[i]);
514 }
515 return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
516 }
517
518 // --- Output + validation ---
519
520 function updateOutput(els) {
521 const { modal, codeEl, warningsEl } = els;
522 if (!codeEl) return;
523
524 const values = collectValues(els);
525 const activeTab = modal.querySelector(".cg-output-tab.active");
526 const format = activeTab ? activeTab.getAttribute("data-format") : "server-yml";
527
528 const hasValues = Object.keys(values).length > 0;
529 if (!hasValues) {
530 codeEl.innerHTML = "<span class=\"cg-empty-msg\">Configure options on the left to generate your config...</span>";
531 setHidden(warningsEl, true);
532 return;
533 }
534
535 let output;
536 if (format === "docker-compose") {
537 output = generateDockerCompose(values);
538 } else if (format === "env-vars") {
539 output = generateEnvVars(values);
540 } else {
541 output = generateServerYml(values);
542 }
543
544 codeEl.textContent = output;
545
546 // Validation warnings
547 const warnings = validate(values);
548 if (warningsEl) {
549 if (warnings.length) {
550 warningsEl.innerHTML = warnings.map((w) => `<div class="cg-warning">${w}</div>`).join("");
551 }
552 setHidden(warningsEl, !warnings.length);
553 }
554 }
555
556 function validate(values) {
557 const warnings = [];
558 const baseUrl = values["base-url"] || "";
559
560 // base-url format
561 if (baseUrl) {
562 if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
563 warnings.push("base-url must start with http:// or https://");
564 } else {
565 try {
566 const u = new URL(baseUrl);
567 if (u.pathname !== "/" && u.pathname !== "") {
568 warnings.push("base-url must not have a path, ntfy does not support sub-paths");
569 }
570 } catch (e) {
571 warnings.push("base-url is not a valid URL");
572 }
573 }
574 }
575
576 // database-url must start with postgres://
577 if (values["database-url"] && !values["database-url"].startsWith("postgres://")) {
578 warnings.push("database-url must start with postgres://");
579 }
580
581 // Web push requires all fields + base-url
582 const wpPublic = values["web-push-public-key"];
583 const wpPrivate = values["web-push-private-key"];
584 const wpEmail = values["web-push-email-address"];
585 const wpFile = values["web-push-file"];
586 const dbUrl = values["database-url"];
587 if (wpPublic || wpPrivate || wpEmail) {
588 const missing = [];
589 if (!wpPublic) missing.push("web-push-public-key");
590 if (!wpPrivate) missing.push("web-push-private-key");
591 if (!wpFile && !dbUrl) missing.push("web-push-file or database-url");
592 if (!wpEmail) missing.push("web-push-email-address");
593 if (!baseUrl) missing.push("base-url");
594 if (missing.length) {
595 warnings.push(`Web push requires: ${missing.join(", ")}`);
596 }
597 }
598
599 // SMTP sender requires base-url and smtp-sender-from
600 if (values["smtp-sender-addr"]) {
601 const smtpMissing = [];
602 if (!baseUrl) smtpMissing.push("base-url");
603 if (!values["smtp-sender-from"]) smtpMissing.push("smtp-sender-from");
604 if (smtpMissing.length) {
605 warnings.push(`Email sending requires: ${smtpMissing.join(", ")}`);
606 }
607 }
608
609 // SMTP server requires domain
610 if (values["smtp-server-listen"] && !values["smtp-server-domain"]) {
611 warnings.push("Email publishing requires smtp-server-domain");
612 }
613
614 // Attachments require base-url
615 if (values["attachment-cache-dir"] && !baseUrl) {
616 warnings.push("Attachments require base-url to be set");
617 }
618
619 // Upstream requires base-url and can't equal it
620 if (values["upstream-base-url"]) {
621 if (!baseUrl) {
622 warnings.push("Upstream server requires base-url to be set");
623 } else if (baseUrl === values["upstream-base-url"]) {
624 warnings.push("base-url and upstream-base-url cannot be the same");
625 }
626 }
627
628 // enable-signup requires enable-login
629 if (values["enable-signup"] && !values["enable-login"]) {
630 warnings.push("Enable signup requires enable-login to also be set");
631 }
632
633 // Duration field validation
634 [
635 { key: "cache-duration", label: "Cache duration" },
636 { key: "attachment-expiry-duration", label: "Attachment expiry duration" }
637 ].forEach((f) => {
638 if (values[f.key] && !durationRegex.test(values[f.key])) {
639 warnings.push(`${f.label} must be a valid duration (e.g. 12h, 3d, 30m, 60s)`);
640 }
641 });
642
643 // Size field validation
644 [
645 { key: "attachment-file-size-limit", label: "Attachment file size limit" },
646 { key: "attachment-total-size-limit", label: "Attachment total size limit" }
647 ].forEach((f) => {
648 if (values[f.key] && !sizeRegex.test(values[f.key])) {
649 warnings.push(`${f.label} must be a valid size (e.g. 15M, 5G, 100K)`);
650 }
651 });
652
653 return warnings;
654 }
655
656 // --- Helpers ---
657
658 function secureRandomInt(max) {
659 const arr = new Uint32Array(1);
660 crypto.getRandomValues(arr);
661 return arr[0] % max;
662 }
663
664 function generateToken() {
665 const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
666 let token = "tk_";
667 for (let i = 0; i < 29; i++) {
668 token += chars.charAt(secureRandomInt(chars.length));
669 }
670 return token;
671 }
672
673 function generatePassword() {
674 const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
675 let password = "";
676 for (let i = 0; i < 16; i++) {
677 password += chars.charAt(secureRandomInt(chars.length));
678 }
679 return password;
680 }
681
682 function escapeHtml(str) {
683 return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
684 }
685
686 function escapeYamlValue(str) {
687 return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
688 }
689
690 function escapeShellValue(val) {
691 // Use single quotes for values with $, double quotes otherwise
692 // Escape the chosen quote character within the value
693 if (val.includes("$")) {
694 return "'" + val.replace(/'/g, "'\\''") + "'";
695 }
696 return '"' + val.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
697 }
698
699 function prefill(modal, key, value) {
700 const el = modal.querySelector(`[data-key="${key}"]`);
701 if (el && !el.value.trim() && !el.dataset.cleared) el.value = value;
702 }
703
704 function switchPanel(modal, panelId) {
705 modal.querySelectorAll(".cg-nav-tab").forEach((t) => t.classList.remove("active"));
706 modal.querySelectorAll(".cg-panel").forEach((p) => p.classList.remove("active"));
707
708 const navTab = modal.querySelector(`[data-panel="${panelId}"]`);
709 const panel = modal.querySelector(`#${panelId}`);
710 if (navTab) navTab.classList.add("active");
711 if (panel) panel.classList.add("active");
712 }
713
714 function setHidden(el, hidden) {
715 if (!el) return;
716 if (hidden) {
717 el.classList.add("cg-hidden");
718 } else {
719 el.classList.remove("cg-hidden");
720 }
721 }
722
723 // --- Visibility: broken into focused helpers ---
724
725 function syncRadiosToHiddenInputs(els) {
726 const { modal, accessSelect, accessHidden, loginHidden, requireLoginHidden, signupHidden, proxyCheckbox } = els;
727
728 // Proxy radio → hidden checkbox
729 const proxyYes = modal.querySelector("input[name=\"cg-proxy\"][value=\"yes\"]");
730 if (proxyYes && proxyCheckbox) {
731 proxyCheckbox.checked = proxyYes.checked;
732 }
733
734 // Default access select → hidden input
735 if (accessSelect && accessHidden) {
736 accessHidden.value = accessSelect.value;
737 }
738
739 // Login mode three-way toggle → hidden checkboxes
740 const loginMode = modal.querySelector("input[name=\"cg-login-mode\"]:checked");
741 const loginModeVal = loginMode ? loginMode.value : "disabled";
742 if (loginHidden) loginHidden.checked = (loginModeVal === "enabled" || loginModeVal === "required");
743 if (requireLoginHidden) requireLoginHidden.checked = (loginModeVal === "required");
744
745 const signupYes = modal.querySelector("input[name=\"cg-enable-signup\"][value=\"yes\"]");
746 if (signupYes && signupHidden) signupHidden.checked = signupYes.checked;
747
748 // SMTP sender verify radio → hidden checkbox
749 const smtpVerifyYes = modal.querySelector("input[name=\"cg-smtp-sender-verify\"][value=\"yes\"]");
750 if (smtpVerifyYes && els.smtpSenderVerifyHidden) els.smtpSenderVerifyHidden.checked = smtpVerifyYes.checked;
751
752 return loginModeVal;
753 }
754
755 function updateFeatureVisibility(els, flags) {
756 const { modal, dbStep, navDb, navEmail, emailOutSection, emailInSection } = els;
757 const { authEnabled, cacheEnabled, webpushEnabled, smtpOutEnabled, smtpInEnabled, needsDb, isPostgres } = flags;
758
759 // Show database question only if a DB-dependent feature is selected
760 setHidden(dbStep, !needsDb);
761
762 // Nav tabs for features
763 for (const featId in NAV_MAP) {
764 const checkbox = modal.querySelector(`#${featId}`);
765 const navTab = modal.querySelector(`#${NAV_MAP[featId]}`);
766 if (checkbox && navTab) {
767 setHidden(navTab, !checkbox.checked);
768 }
769 }
770
771 // Email tab — show if either outgoing or incoming is enabled
772 setHidden(navEmail, !smtpOutEnabled && !smtpInEnabled);
773 setHidden(emailOutSection, !smtpOutEnabled);
774 setHidden(emailInSection, !smtpInEnabled);
775
776 // Show/hide configure buttons next to feature checkboxes
777 modal.querySelectorAll(".cg-btn-configure").forEach((btn) => {
778 const row = btn.closest(".cg-feature-row");
779 if (!row) return;
780 const cb = row.querySelector("input[type=\"checkbox\"]");
781 setHidden(btn, !(cb && cb.checked));
782 });
783
784 // If active nav tab got hidden, switch to General
785 const activeNav = modal.querySelector(".cg-nav-tab.active");
786 if (activeNav && activeNav.classList.contains("cg-hidden")) {
787 switchPanel(modal, "cg-panel-general");
788 }
789
790 // Database tab — show only when PostgreSQL is selected and a DB-dependent feature is on
791 setHidden(navDb, !(needsDb && isPostgres));
792 }
793
794 function updatePostgresFields(modal, isPostgres) {
795 // Show "Using PostgreSQL" instead of file inputs when PostgreSQL is selected
796 ["auth-file", "web-push-file", "cache-file"].forEach((key) => {
797 const input = modal.querySelector(`[data-key="${key}"]`);
798 if (!input) return;
799 const field = input.closest(".cg-field");
800 if (!field) return;
801 input.style.display = isPostgres ? "none" : "";
802 if (isPostgres) {
803 input.dataset.pgDisabled = "1";
804 } else {
805 delete input.dataset.pgDisabled;
806 }
807 let pgLabel = field.querySelector(".cg-pg-label");
808 if (isPostgres) {
809 if (!pgLabel) {
810 pgLabel = document.createElement("span");
811 pgLabel.className = "cg-pg-label";
812 pgLabel.textContent = "Using PostgreSQL";
813 input.parentNode.insertBefore(pgLabel, input.nextSibling);
814 }
815 pgLabel.style.display = "";
816 } else if (pgLabel) {
817 pgLabel.style.display = "none";
818 }
819 });
820
821 // iOS question → upstream-base-url
822 const iosYes = modal.querySelector("input[name=\"cg-ios\"][value=\"yes\"]");
823 const upstreamInput = modal.querySelector("[data-key=\"upstream-base-url\"]");
824 if (iosYes && upstreamInput) {
825 upstreamInput.value = iosYes.checked ? "https://ntfy.sh" : "";
826 }
827 }
828
829 function prefillDefaults(modal, flags) {
830 const {
831 isPostgres,
832 authEnabled,
833 cacheEnabled,
834 attachEnabled,
835 webpushEnabled,
836 smtpOutEnabled,
837 smtpInEnabled
838 } = flags;
839
840 if (isPostgres) {
841 prefill(modal, "database-url", "postgres://user:pass@host:5432/ntfy");
842 }
843
844 if (authEnabled) {
845 if (!isPostgres) prefill(modal, "auth-file", "/var/lib/ntfy/auth.db");
846 }
847
848 if (cacheEnabled) {
849 if (!isPostgres) prefill(modal, "cache-file", "/var/cache/ntfy/cache.db");
850 }
851
852 if (attachEnabled) {
853 prefill(modal, "attachment-cache-dir", "/var/cache/ntfy/attachments");
854 }
855
856 if (webpushEnabled) {
857 if (!isPostgres) prefill(modal, "web-push-file", "/var/lib/ntfy/webpush.db");
858 prefill(modal, "web-push-email-address", "[email protected]");
859 }
860
861 if (smtpOutEnabled) {
862 prefill(modal, "smtp-sender-addr", "smtp.example.com:587");
863 prefill(modal, "smtp-sender-from", "[email protected]");
864 prefill(modal, "smtp-sender-user", "yoursmtpuser");
865 prefill(modal, "smtp-sender-pass", "yoursmtppass");
866 }
867
868 if (smtpInEnabled) {
869 prefill(modal, "smtp-server-listen", ":25");
870 prefill(modal, "smtp-server-domain", "ntfy.example.com");
871 }
872 }
873
874 function autoDetectServerType(els, loginModeVal) {
875 const { modal, accessSelect } = els;
876 const serverTypeRadio = modal.querySelector("input[name=\"cg-server-type\"]:checked");
877 const serverType = serverTypeRadio ? serverTypeRadio.value : "open";
878
879 if (serverType !== "custom") {
880 const currentAccess = accessSelect ? accessSelect.value : "read-write";
881 const currentLoginEnabled = loginModeVal !== "disabled";
882 const matchesOpen = currentAccess === "read-write" && !currentLoginEnabled;
883 const matchesPrivate = currentAccess === "deny-all" && currentLoginEnabled;
884 if (!matchesOpen && !matchesPrivate) {
885 const customRadio = modal.querySelector("input[name=\"cg-server-type\"][value=\"custom\"]");
886 if (customRadio) customRadio.checked = true;
887 }
888 }
889 }
890
891 function updateVisibility(els) {
892 const {
893 modal,
894 authCheckbox,
895 cacheCheckbox,
896 attachCheckbox,
897 webpushCheckbox,
898 smtpOutCheckbox,
899 smtpInCheckbox
900 } = els;
901
902 const isPostgresRadio = modal.querySelector("input[name=\"cg-db-type\"][value=\"postgres\"]");
903 const isPostgres = isPostgresRadio && isPostgresRadio.checked;
904
905 // Auto-enable auth when PostgreSQL is selected
906 if (isPostgres && authCheckbox && !authCheckbox.checked) {
907 authCheckbox.checked = true;
908 }
909
910 const authEnabled = authCheckbox && authCheckbox.checked;
911 const cacheEnabled = cacheCheckbox && cacheCheckbox.checked;
912 const attachEnabled = attachCheckbox && attachCheckbox.checked;
913 const webpushEnabled = webpushCheckbox && webpushCheckbox.checked;
914 const smtpOutEnabled = smtpOutCheckbox && smtpOutCheckbox.checked;
915 const smtpInEnabled = smtpInCheckbox && smtpInCheckbox.checked;
916 const needsDb = authEnabled || cacheEnabled || webpushEnabled;
917
918 const flags = {
919 isPostgres,
920 authEnabled,
921 cacheEnabled,
922 attachEnabled,
923 webpushEnabled,
924 smtpOutEnabled,
925 smtpInEnabled,
926 needsDb
927 };
928
929 const loginModeVal = syncRadiosToHiddenInputs(els);
930 updateFeatureVisibility(els, flags);
931 updatePostgresFields(modal, isPostgres);
932 prefillDefaults(modal, flags);
933 autoDetectServerType(els, loginModeVal);
934 }
935
936 // --- Repeatable rows ---
937
938 function addRepeatableRow(container, type, onUpdate) {
939 const row = document.createElement("div");
940 row.className = `cg-repeatable-row cg-auth-${type}-row`;
941
942 if (type === "user") {
943 const username = `newuser${secureRandomInt(100) + 1}`;
944 row.innerHTML =
945 `<input type="text" data-field="username" placeholder="Username" value="${escapeHtml(username)}">` +
946 `<input type="text" data-field="password" placeholder="Password" value="${escapeHtml(generatePassword())}">` +
947 "<select data-field=\"role\"><option value=\"user\">User</option><option value=\"admin\">Admin</option></select>" +
948 "<button type=\"button\" class=\"cg-btn-remove\" title=\"Remove\">&times;</button>";
949 } else if (type === "acl") {
950 let aclUser = `someuser${secureRandomInt(100) + 1}`;
951 const modal = container.closest(".cg-modal");
952 if (modal) {
953 const userRows = modal.querySelectorAll(".cg-auth-user-row");
954 for (const ur of userRows) {
955 const role = ur.querySelector("[data-field=\"role\"]");
956 const name = ur.querySelector("[data-field=\"username\"]");
957 if (role && role.value !== "admin" && name && name.value.trim()) {
958 aclUser = name.value.trim();
959 break;
960 }
961 }
962 }
963 row.innerHTML =
964 `<input type="text" data-field="username" placeholder="Username (* for everyone)" value="${escapeHtml(aclUser)}">` +
965 "<input type=\"text\" data-field=\"topic\" placeholder=\"Topic pattern\" value=\"sometopic*\">" +
966 "<select data-field=\"permission\"><option value=\"read-write\">Read &amp; Write</option><option value=\"read-only\">Read Only</option><option value=\"write-only\">Write Only</option><option value=\"deny\">Deny</option></select>" +
967 "<button type=\"button\" class=\"cg-btn-remove\" title=\"Remove\">&times;</button>";
968 } else if (type === "token") {
969 let tokenUser = "";
970 const modal = container.closest(".cg-modal");
971 if (modal) {
972 const firstRow = modal.querySelector(".cg-auth-user-row");
973 const name = firstRow ? firstRow.querySelector("[data-field=\"username\"]") : null;
974 if (name && name.value.trim()) tokenUser = name.value.trim();
975 }
976 row.innerHTML =
977 `<input type="text" data-field="username" placeholder="Username" value="${escapeHtml(tokenUser)}">` +
978 `<input type="text" data-field="token" placeholder="Token" value="${escapeHtml(generateToken())}">` +
979 "<input type=\"text\" data-field=\"label\" placeholder=\"Label (optional)\">" +
980 "<button type=\"button\" class=\"cg-btn-remove\" title=\"Remove\">&times;</button>";
981 }
982
983 row.querySelector(".cg-btn-remove").addEventListener("click", () => {
984 row.remove();
985 onUpdate();
986 });
987 row.querySelectorAll("input, select").forEach((el) => {
988 el.addEventListener("input", onUpdate);
989 });
990
991 container.appendChild(row);
992 }
993
994 // --- Modal functions (module-level) ---
995
996 function openModal(els) {
997 els.modal.style.display = "";
998 document.body.style.overflow = "hidden";
999 updateVisibility(els);
1000 updateOutput(els);
1001 }
1002
1003 function closeModal(els) {
1004 els.modal.style.display = "none";
1005 document.body.style.overflow = "";
1006 }
1007
1008 function resetAll(els) {
1009 const { modal } = els;
1010
1011 // Reset all text/password inputs and clear flags
1012 modal.querySelectorAll("input[type=\"text\"], input[type=\"password\"]").forEach((el) => {
1013 el.value = "";
1014 delete el.dataset.cleared;
1015 });
1016 // Uncheck all checkboxes
1017 modal.querySelectorAll("input[type=\"checkbox\"]").forEach((el) => {
1018 el.checked = false;
1019 el.disabled = false;
1020 });
1021 // Reset radio buttons to first option
1022 const radioGroups = {};
1023 modal.querySelectorAll("input[type=\"radio\"]").forEach((el) => {
1024 if (!radioGroups[el.name]) {
1025 radioGroups[el.name] = true;
1026 const first = modal.querySelector(`input[type="radio"][name="${el.name}"]`);
1027 if (first) first.checked = true;
1028 } else {
1029 el.checked = false;
1030 }
1031 });
1032 // Reset selects to first option
1033 modal.querySelectorAll("select").forEach((el) => {
1034 el.selectedIndex = 0;
1035 });
1036 // Remove all repeatable rows
1037 modal.querySelectorAll(".cg-auth-user-row, .cg-auth-acl-row, .cg-auth-token-row").forEach((row) => {
1038 row.remove();
1039 });
1040 // Re-prefill base-url
1041 const baseUrlInput = modal.querySelector("[data-key=\"base-url\"]");
1042 if (baseUrlInput) {
1043 baseUrlInput.value = "https://ntfy.example.com";
1044 }
1045 // Reset to General tab
1046 switchPanel(modal, "cg-panel-general");
1047 updateVisibility(els);
1048 updateOutput(els);
1049 }
1050
1051 function fillVAPIDKeys(els) {
1052 const { modal } = els;
1053 generateVAPIDKeys().then((keys) => {
1054 const pubInput = modal.querySelector("[data-key=\"web-push-public-key\"]");
1055 const privInput = modal.querySelector("[data-key=\"web-push-private-key\"]");
1056 if (pubInput) pubInput.value = keys.publicKey;
1057 if (privInput) privInput.value = keys.privateKey;
1058 updateOutput(els);
1059 });
1060 }
1061
1062 // --- Event setup (grouped) ---
1063
1064 function setupModalEvents(els) {
1065 const { modal } = els;
1066 const openBtn = document.getElementById("cg-open-btn");
1067 const closeBtn = document.getElementById("cg-close-btn");
1068 const backdrop = modal.querySelector(".cg-modal-backdrop");
1069 const resetBtn = document.getElementById("cg-reset-btn");
1070
1071 if (openBtn) openBtn.addEventListener("click", () => openModal(els));
1072 if (closeBtn) closeBtn.addEventListener("click", () => closeModal(els));
1073 if (resetBtn) resetBtn.addEventListener("click", () => resetAll(els));
1074 if (backdrop) backdrop.addEventListener("click", () => closeModal(els));
1075
1076 document.addEventListener("keydown", (e) => {
1077 if (e.key === "Escape" && modal.style.display !== "none") {
1078 closeModal(els);
1079 }
1080 });
1081
1082 // Mobile toggle between Edit and Preview panels
1083 const toggleBtns = modal.querySelectorAll(".cg-mobile-toggle-btn");
1084 const leftPanel = document.getElementById("cg-left");
1085 const rightPanel = document.getElementById("cg-right");
1086 toggleBtns.forEach((btn) => {
1087 btn.addEventListener("click", () => {
1088 toggleBtns.forEach((b) => b.classList.remove("active"));
1089 btn.classList.add("active");
1090 if (btn.dataset.show === "right") {
1091 leftPanel.classList.add("cg-mobile-hidden");
1092 rightPanel.classList.add("cg-mobile-active");
1093 } else {
1094 leftPanel.classList.remove("cg-mobile-hidden");
1095 rightPanel.classList.remove("cg-mobile-active");
1096 }
1097 });
1098 });
1099 }
1100
1101 function setupAuthEvents(els) {
1102 const { modal, authCheckbox, accessSelect } = els;
1103 if (!authCheckbox) return;
1104
1105 // Auth checkbox: clean up when unchecked
1106 authCheckbox.addEventListener("change", () => {
1107 if (!authCheckbox.checked) {
1108 // Clear auth-file
1109 const authFile = modal.querySelector("[data-key=\"auth-file\"]");
1110 if (authFile) {
1111 authFile.value = "";
1112 delete authFile.dataset.cleared;
1113 }
1114 // Reset default access
1115 if (accessSelect) accessSelect.value = "read-write";
1116 // Reset login mode to Disabled and unset hidden checkboxes
1117 const loginDisabled = modal.querySelector("input[name=\"cg-login-mode\"][value=\"disabled\"]");
1118 if (loginDisabled) loginDisabled.checked = true;
1119 if (els.loginHidden) els.loginHidden.checked = false;
1120 if (els.requireLoginHidden) els.requireLoginHidden.checked = false;
1121 const signupNo = modal.querySelector("input[name=\"cg-enable-signup\"][value=\"no\"]");
1122 if (signupNo) signupNo.checked = true;
1123 if (els.signupHidden) els.signupHidden.checked = false;
1124 // Reset UnifiedPush to No
1125 const upNo = modal.querySelector("input[name=\"cg-unifiedpush\"][value=\"no\"]");
1126 if (upNo) upNo.checked = true;
1127 // Remove provisioned users/ACLs/tokens
1128 modal.querySelectorAll(".cg-auth-user-row, .cg-auth-acl-row, .cg-auth-token-row").forEach((row) => {
1129 row.remove();
1130 });
1131 // Switch server type to Open
1132 const openRadio = modal.querySelector("input[name=\"cg-server-type\"][value=\"open\"]");
1133 if (openRadio) openRadio.checked = true;
1134 }
1135 });
1136 }
1137
1138 function setupServerTypeEvents(els) {
1139 const { modal, authCheckbox, accessSelect } = els;
1140
1141 modal.querySelectorAll("input[name=\"cg-server-type\"]").forEach((radio) => {
1142 radio.addEventListener("change", () => {
1143 const loginDisabledRadio = modal.querySelector("input[name=\"cg-login-mode\"][value=\"disabled\"]");
1144 const loginRequiredRadio = modal.querySelector("input[name=\"cg-login-mode\"][value=\"required\"]");
1145 if (radio.value === "open") {
1146 if (accessSelect) accessSelect.value = "read-write";
1147 if (loginDisabledRadio) loginDisabledRadio.checked = true;
1148 if (authCheckbox) authCheckbox.checked = false;
1149 // Trigger the auth cleanup
1150 authCheckbox.dispatchEvent(new Event("change"));
1151 } else if (radio.value === "private") {
1152 // Enable auth with required login
1153 if (authCheckbox) authCheckbox.checked = true;
1154 if (accessSelect) accessSelect.value = "deny-all";
1155 if (loginRequiredRadio) loginRequiredRadio.checked = true;
1156 if (els.loginHidden) els.loginHidden.checked = true;
1157 if (els.requireLoginHidden) els.requireLoginHidden.checked = true;
1158 // Add default admin user if no users exist
1159 const usersContainer = modal.querySelector("#cg-auth-users-container");
1160 if (usersContainer && !usersContainer.querySelector(".cg-auth-user-row")) {
1161 const onUpdate = () => {
1162 updateVisibility(els);
1163 updateOutput(els);
1164 };
1165 addRepeatableRow(usersContainer, "user", onUpdate);
1166 const adminRow = usersContainer.querySelector(".cg-auth-user-row:last-child");
1167 if (adminRow) {
1168 const u = adminRow.querySelector("[data-field=\"username\"]");
1169 const p = adminRow.querySelector("[data-field=\"password\"]");
1170 const r = adminRow.querySelector("[data-field=\"role\"]");
1171 if (u) u.value = "ntfyadmin";
1172 if (p) p.value = generatePassword();
1173 if (r) r.value = "admin";
1174 }
1175 addRepeatableRow(usersContainer, "user", onUpdate);
1176 const userRow = usersContainer.querySelector(".cg-auth-user-row:last-child");
1177 if (userRow) {
1178 const u = userRow.querySelector("[data-field=\"username\"]");
1179 const p = userRow.querySelector("[data-field=\"password\"]");
1180 if (u) u.value = "ntfyuser";
1181 if (p) p.value = generatePassword();
1182 }
1183 }
1184 }
1185 // "custom" doesn't change anything
1186 });
1187 });
1188 }
1189
1190 function setupUnifiedPushEvents(els) {
1191 const { modal } = els;
1192 const onUpdate = () => {
1193 updateVisibility(els);
1194 updateOutput(els);
1195 };
1196
1197 modal.querySelectorAll("input[name=\"cg-unifiedpush\"]").forEach((radio) => {
1198 radio.addEventListener("change", () => {
1199 const aclsContainer = modal.querySelector("#cg-auth-acls-container");
1200 if (!aclsContainer) return;
1201 const existing = aclsContainer.querySelector(".cg-auth-acl-row-up");
1202 if (radio.value === "yes" && radio.checked && !existing) {
1203 // Enable auth if not already enabled
1204 if (els.authCheckbox && !els.authCheckbox.checked) {
1205 els.authCheckbox.checked = true;
1206 }
1207 // Add a disabled UnifiedPush ACL row
1208 const row = document.createElement("div");
1209 row.className = "cg-repeatable-row cg-auth-acl-row cg-auth-acl-row-up";
1210 row.innerHTML =
1211 "<input type=\"text\" data-field=\"username\" value=\"*\" disabled>" +
1212 "<input type=\"text\" data-field=\"topic\" value=\"up*\" disabled>" +
1213 "<select data-field=\"permission\" disabled><option value=\"write-only\">Write Only</option></select>" +
1214 "<button type=\"button\" class=\"cg-btn-remove\" title=\"Removing this ACL entry will disable UnifiedPush support\">&times;</button>";
1215 row.querySelector(".cg-btn-remove").addEventListener("click", () => {
1216 row.remove();
1217 const upNo = modal.querySelector("input[name=\"cg-unifiedpush\"][value=\"no\"]");
1218 if (upNo) upNo.checked = true;
1219 onUpdate();
1220 });
1221 // Insert at the beginning
1222 aclsContainer.insertBefore(row, aclsContainer.firstChild);
1223 onUpdate();
1224 } else if (radio.value === "no" && radio.checked && existing) {
1225 existing.remove();
1226 onUpdate();
1227 }
1228 });
1229 });
1230 }
1231
1232 function setupFormListeners(els) {
1233 const { modal } = els;
1234 const onUpdate = () => {
1235 updateVisibility(els);
1236 updateOutput(els);
1237 };
1238
1239 // Left nav tab switching
1240 modal.querySelectorAll(".cg-nav-tab").forEach((tab) => {
1241 tab.addEventListener("click", () => {
1242 const panelId = tab.getAttribute("data-panel");
1243 switchPanel(modal, panelId);
1244 });
1245 });
1246
1247 // Configure buttons in feature grid
1248 modal.querySelectorAll(".cg-btn-configure").forEach((btn) => {
1249 btn.addEventListener("click", () => {
1250 const panelId = btn.getAttribute("data-panel");
1251 if (panelId) switchPanel(modal, panelId);
1252 });
1253 });
1254
1255 // Output format tab switching
1256 modal.querySelectorAll(".cg-output-tab").forEach((tab) => {
1257 tab.addEventListener("click", () => {
1258 modal.querySelectorAll(".cg-output-tab").forEach((t) => t.classList.remove("active"));
1259 tab.classList.add("active");
1260 updateOutput(els);
1261 });
1262 });
1263
1264 // All form inputs trigger update
1265 modal.querySelectorAll("input, select").forEach((el) => {
1266 const evt = (el.type === "checkbox" || el.type === "radio") ? "change" : "input";
1267 el.addEventListener(evt, () => {
1268 // Mark text fields as cleared when user empties them
1269 if ((el.type === "text" || el.type === "password") && el.dataset.key && !el.value.trim()) {
1270 el.dataset.cleared = "1";
1271 } else if ((el.type === "text" || el.type === "password") && el.dataset.key && el.value.trim()) {
1272 delete el.dataset.cleared;
1273 }
1274 onUpdate();
1275 });
1276 });
1277
1278 // Add buttons for repeatable rows
1279 modal.querySelectorAll(".cg-btn-add[data-add-type]").forEach((btn) => {
1280 btn.addEventListener("click", () => {
1281 const type = btn.getAttribute("data-add-type");
1282 let container = btn.previousElementSibling;
1283 if (!container) container = btn.parentElement.querySelector(".cg-repeatable-container");
1284 addRepeatableRow(container, type, onUpdate);
1285 onUpdate();
1286 });
1287 });
1288
1289 // Copy button
1290 const copyBtn = modal.querySelector("#cg-copy-btn");
1291 if (copyBtn) {
1292 const copyIcon = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg>";
1293 const checkIcon = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"20 6 9 17 4 12\"></polyline></svg>";
1294 copyBtn.addEventListener("click", () => {
1295 const code = modal.querySelector("#cg-code");
1296 if (code && code.textContent) {
1297 navigator.clipboard.writeText(code.textContent).then(() => {
1298 copyBtn.innerHTML = checkIcon;
1299 copyBtn.style.color = "var(--md-primary-fg-color)";
1300 setTimeout(() => {
1301 copyBtn.innerHTML = copyIcon;
1302 copyBtn.style.color = "";
1303 }, 2000);
1304 });
1305 }
1306 });
1307 }
1308 }
1309
1310 function setupWebPushEvents(els) {
1311 const { modal } = els;
1312 let vapidKeysGenerated = false;
1313 const regenBtn = modal.querySelector("#cg-regen-keys");
1314
1315 if (regenBtn) {
1316 regenBtn.addEventListener("click", () => fillVAPIDKeys(els));
1317 }
1318
1319 // Auto-generate keys when web push is first enabled
1320 const webpushFeat = modal.querySelector("#cg-feat-webpush");
1321 if (webpushFeat) {
1322 webpushFeat.addEventListener("change", () => {
1323 if (webpushFeat.checked && !vapidKeysGenerated) {
1324 vapidKeysGenerated = true;
1325 fillVAPIDKeys(els);
1326 }
1327 });
1328 }
1329 }
1330
1331 // --- Init ---
1332
1333 function initGenerator() {
1334 const modal = document.getElementById("cg-modal");
1335 if (!modal) return;
1336
1337 const els = cacheElements(modal);
1338
1339 setupModalEvents(els);
1340 setupAuthEvents(els);
1341 setupServerTypeEvents(els);
1342 setupUnifiedPushEvents(els);
1343 setupFormListeners(els);
1344 setupWebPushEvents(els);
1345
1346 // Pre-fill base-url
1347 const baseUrlInput = modal.querySelector("[data-key=\"base-url\"]");
1348 if (baseUrlInput && !baseUrlInput.value.trim()) {
1349 baseUrlInput.value = "https://ntfy.example.com";
1350 }
1351
1352 // Auto-open if URL hash points to config generator
1353 if (window.location.hash === "#config-generator") {
1354 openModal(els);
1355 }
1356 }
1357
1358 if (document.readyState === "loading") {
1359 document.addEventListener("DOMContentLoaded", initGenerator);
1360 } else {
1361 initGenerator();
1362 }
1363 })();