home-hosted 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -709,7 +709,22 @@ function parseBind(value) {
709
709
  const parsed = bindSchema(value);
710
710
  return parsed instanceof type.errors ? null : parsed;
711
711
  }
712
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, telegramSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, telegramPatchSchema, notificationsPatchSchema, hostPatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, telegramStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, workspaceViewSchema, appStateSchema, logQuerySchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
712
+ /**
713
+ * The ids that appear more than once, so a write can refuse them.
714
+ *
715
+ * A schema-level check is not available here (see above), and this is the one shape that has to
716
+ * be told apart from a plain validation error: the list is valid, but its identity is not.
717
+ */
718
+ function duplicateWebhookIds(targets) {
719
+ const seen = /* @__PURE__ */ new Set();
720
+ const duplicates = /* @__PURE__ */ new Set();
721
+ for (const target of targets) {
722
+ if (seen.has(target.id)) duplicates.add(target.id);
723
+ seen.add(target.id);
724
+ }
725
+ return [...duplicates];
726
+ }
727
+ var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, backupFileSchema, backupEntrySchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, workspaceViewSchema, appStateSchema, logQuerySchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
713
728
  var init_contracts = __esmMin((() => {
714
729
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
715
730
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
@@ -735,6 +750,10 @@ var init_contracts = __esmMin((() => {
735
750
  resetAfterMs: "number >= 0 = 60000"
736
751
  }).onUndeclaredKey("reject");
737
752
  httpCheckSchema = type({
753
+ /** `https` is for a backend that serves TLS itself; pair it with `allowInvalidCert` when it is self-signed. */
754
+ scheme: "\"http\" | \"https\" = \"http\"",
755
+ /** Accept any certificate. A self-signed pair is the normal case here, and the probe is local. */
756
+ allowInvalidCert: "boolean = false",
738
757
  /** Path on the server's own port, e.g. `/healthz`. */
739
758
  path: "string = \"/\"",
740
759
  method: "\"GET\" | \"HEAD\" = \"GET\"",
@@ -831,9 +850,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
831
850
  maxLoginAttempts: "number.integer >= 1 = 5",
832
851
  lockoutMs: "number >= 1000 = 60000"
833
852
  }).onUndeclaredKey("reject");
834
- telegramSchema = type({
835
- enabled: "boolean = false",
836
- chatId: "string = \"\"",
853
+ notificationPolicyShape = {
837
854
  onCrash: "boolean = true",
838
855
  onUnhealthy: "boolean = true",
839
856
  onForcedRestart: "boolean = true",
@@ -844,8 +861,45 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
844
861
  onDdns: "boolean = true",
845
862
  /** Per server *and* reason, so a flapping server cannot spam the chat. */
846
863
  cooldownMs: "number >= 0 = 120000"
864
+ };
865
+ notificationDefaultsSchema = type({ ...notificationPolicyShape }).onUndeclaredKey("reject");
866
+ notificationDefaultsViewSchema = type({ ...notificationPolicyShape });
867
+ useOwnSettingsSchema = "boolean = true";
868
+ telegramDestinationSchema = type({
869
+ kind: "\"telegram\"",
870
+ id: "/^[a-z0-9][a-z0-9_-]*$/",
871
+ /** Off until configured: a bare `enabled: true` with no chat would fail every send. */
872
+ enabled: "boolean = false",
873
+ chatId: "string = \"\"",
874
+ useOwnSettings: useOwnSettingsSchema,
875
+ ...notificationPolicyShape
876
+ }).onUndeclaredKey("reject");
877
+ webhookTargetSchema = type({
878
+ kind: "\"webhook\"",
879
+ id: "/^[a-z0-9][a-z0-9_-]*$/",
880
+ /** Empty only while the target is a draft; the page will not save one without it. */
881
+ url: "string = \"\"",
882
+ enabled: "boolean = true",
883
+ method: "\"POST\" | \"PUT\" = \"POST\"",
884
+ /** Payload format: `json` sends the event as JSON, `text` sends the plain message. */
885
+ format: "\"json\" | \"text\" = \"json\"",
886
+ /**
887
+ * Extra headers, `Name: value` per line. The one field that lets this transport talk to
888
+ * ntfy (`Title`, `Priority`), a bearer-token endpoint (`Authorization`) or anything else
889
+ * with a header-shaped contract.
890
+ */
891
+ headers: "string = \"\"",
892
+ useOwnSettings: useOwnSettingsSchema,
893
+ ...notificationPolicyShape
894
+ }).onUndeclaredKey("reject");
895
+ notificationTargetSchema = telegramDestinationSchema.or(webhookTargetSchema);
896
+ destinationListSchema = notificationTargetSchema.array();
897
+ notificationsSchema = type({
898
+ /** What every destination inherits unless it carries its own settings. */
899
+ defaults: notificationDefaultsSchema.default(() => ({})),
900
+ /** Replaced by a patch, the same way `ddns.accounts` is: a merge cannot express removing one. */
901
+ destinations: destinationListSchema.default(() => [])
847
902
  }).onUndeclaredKey("reject");
848
- notificationsSchema = type({ telegram: telegramSchema.default(() => ({})) }).onUndeclaredKey("reject");
849
903
  logsSchema = type({
850
904
  persist: "boolean = true",
851
905
  /** Per server, before rotating to `.1`, `.2`, ... */
@@ -970,12 +1024,20 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
970
1024
  accounts: ddnsAccountSchema.array().optional(),
971
1025
  domains: ddnsDomainSchema.array().optional()
972
1026
  }).onUndeclaredKey("reject");
1027
+ backupScheduleSchema = type({
1028
+ /** 0 turns the schedule off; otherwise the gap between automatic archives. */
1029
+ intervalMs: "number.integer >= 0 = 0",
1030
+ /** How many automatic archives to keep. Manual ones are never pruned by it. */
1031
+ keep: "number.integer >= 1 = 7"
1032
+ }).onUndeclaredKey("reject");
973
1033
  backupsSchema = type({
974
1034
  enabled: "boolean = true",
975
1035
  dir: "string = \".backups\"",
1036
+ /** How many archives to keep in total, newest first. */
976
1037
  keep: "number.integer >= 1 = 5",
977
1038
  /** Extra paths in every backup, in addition to each server's `backupPaths`. */
978
- includePaths: type("string[]").default(() => [])
1039
+ includePaths: type("string[]").default(() => []),
1040
+ schedule: backupScheduleSchema.default(() => ({}))
979
1041
  }).onUndeclaredKey("reject");
980
1042
  controlSchema = type({
981
1043
  /** What the panel calls itself; the stock UI shows it in the sidebar. */
@@ -1006,6 +1068,8 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1006
1068
  resetAfterMs: "number >= 0?"
1007
1069
  }).onUndeclaredKey("reject");
1008
1070
  httpCheckPatchSchema = type({
1071
+ scheme: "\"http\" | \"https\"?",
1072
+ allowInvalidCert: "boolean?",
1009
1073
  path: "string?",
1010
1074
  method: "\"GET\" | \"HEAD\"?",
1011
1075
  expectStatus: "number.integer | null?",
@@ -1037,9 +1101,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1037
1101
  maxLoginAttempts: "number.integer >= 1?",
1038
1102
  lockoutMs: "number >= 1000?"
1039
1103
  }).onUndeclaredKey("reject");
1040
- telegramPatchSchema = type({
1041
- enabled: "boolean?",
1042
- chatId: "string?",
1104
+ notificationPolicyPatchShape = {
1043
1105
  onCrash: "boolean?",
1044
1106
  onUnhealthy: "boolean?",
1045
1107
  onForcedRestart: "boolean?",
@@ -1047,8 +1109,36 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1047
1109
  onHost: "boolean?",
1048
1110
  onDdns: "boolean?",
1049
1111
  cooldownMs: "number >= 0?"
1112
+ };
1113
+ destinationPatchSchema = type({
1114
+ kind: "\"telegram\" | \"webhook\"",
1115
+ id: "/^[a-z0-9][a-z0-9_-]*$/",
1116
+ enabled: "boolean?",
1117
+ useOwnSettings: "boolean?",
1118
+ /** Telegram only. */
1119
+ chatId: "string?",
1120
+ /** Webhook only. */
1121
+ url: "string?",
1122
+ method: "\"POST\" | \"PUT\"?",
1123
+ format: "\"json\" | \"text\"?",
1124
+ headers: "string?",
1125
+ ...notificationPolicyPatchShape
1126
+ }).onUndeclaredKey("reject");
1127
+ notificationsPatchSchema = type({
1128
+ /** Merged key by key, like the other nested groups. */
1129
+ /**
1130
+ * A merge key-by-key, and **every field optional** — `notificationPolicyPatchShape`, not a
1131
+ * `.partial()` of the defaults schema.
1132
+ *
1133
+ * ArkType's `.partial()` leaves a field's `= false` / `= 120000` default in place, so a body of
1134
+ * `{ onHost: false }` validated into all seven keys and one toggle overwrote the rest. A patch
1135
+ * schema here carries no defaults (the rule for every patch), and the store merges it over the
1136
+ * stored block.
1137
+ */
1138
+ defaults: type({ ...notificationPolicyPatchShape }).onUndeclaredKey("reject").optional(),
1139
+ /** Replaced whole, so a removed destination stays removed. */
1140
+ destinations: destinationPatchSchema.array().optional()
1050
1141
  }).onUndeclaredKey("reject");
1051
- notificationsPatchSchema = type({ telegram: telegramPatchSchema.optional() }).onUndeclaredKey("reject");
1052
1142
  hostPatchSchema = type({
1053
1143
  enabled: "boolean?",
1054
1144
  intervalMs: "number >= 5000?",
@@ -1059,11 +1149,16 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1059
1149
  loadPerCpu: "number >= 0?",
1060
1150
  tempCelsius: "number >= 0?"
1061
1151
  }).onUndeclaredKey("reject");
1152
+ backupSchedulePatchSchema = type({
1153
+ intervalMs: "number.integer >= 0?",
1154
+ keep: "number.integer >= 1?"
1155
+ }).onUndeclaredKey("reject");
1062
1156
  backupsPatchSchema = type({
1063
1157
  enabled: "boolean?",
1064
1158
  dir: "string?",
1065
1159
  keep: "number.integer >= 1?",
1066
- includePaths: type("string[]").optional()
1160
+ includePaths: type("string[]").optional(),
1161
+ schedule: backupSchedulePatchSchema.optional()
1067
1162
  }).onUndeclaredKey("reject");
1068
1163
  logsPatchSchema = type({
1069
1164
  persist: "boolean?",
@@ -1384,10 +1479,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1384
1479
  privateKey: "string >= 1"
1385
1480
  }).onUndeclaredKey("reject");
1386
1481
  proxyEngineInstallSchema = type({ version: "string = \"\"" }).onUndeclaredKey("reject");
1387
- telegramStatusSchema = type({
1388
- enabled: "boolean",
1389
- tokenSet: "boolean",
1390
- chatId: "string",
1482
+ notificationPolicyStatusShape = {
1391
1483
  onCrash: "boolean",
1392
1484
  onUnhealthy: "boolean",
1393
1485
  onForcedRestart: "boolean",
@@ -1396,16 +1488,37 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1396
1488
  onHost: "boolean",
1397
1489
  /** Dynamic DNS, when this panel knows about it (optional for an older panel). */
1398
1490
  onDdns: "boolean?",
1399
- cooldownMs: "number",
1400
- /** Last delivery outcome, for the settings page. */
1401
- lastResult: "string | null",
1402
- lastResultAt: "number | null"
1491
+ cooldownMs: "number"
1492
+ };
1493
+ destinationStatusSchema = type({
1494
+ "id": "string",
1495
+ "kind": "\"telegram\" | \"webhook\"",
1496
+ "enabled": "boolean",
1497
+ "useOwnSettings": "boolean",
1498
+ ...notificationPolicyStatusShape,
1499
+ /** Telegram only, null on a webhook. */
1500
+ "chatId": "string | null",
1501
+ /** Telegram only: whether a bot token is stored for this destination. */
1502
+ "tokenSet": "boolean",
1503
+ /** Webhook only, null on a Telegram destination. */
1504
+ "url": "string | null",
1505
+ "method": "\"POST\" | \"PUT\" | null",
1506
+ "format": "\"json\" | \"text\" | null",
1507
+ "headers": "string | null",
1508
+ /** Last delivery outcome, for the page. Optional: a newer panel may not have sent one yet. */
1509
+ "lastResult?": "string | null",
1510
+ "lastResultAt?": "number | null"
1403
1511
  });
1404
1512
  telegramChatsSchema = type({ chats: type({
1405
1513
  id: "string | number",
1406
1514
  title: "string"
1407
1515
  }).array() });
1408
- notificationViewSchema = type({ telegram: telegramStatusSchema });
1516
+ notificationViewSchema = type({
1517
+ /** The general block: what a destination inherits unless it overrides it. Optional for an older panel. */
1518
+ "defaults?": notificationDefaultsViewSchema,
1519
+ /** Every destination, in config order. Optional for an older panel. */
1520
+ "destinations?": destinationStatusSchema.array()
1521
+ });
1409
1522
  sessionViewSchema = type({
1410
1523
  authenticated: "boolean",
1411
1524
  authRequired: "boolean",
@@ -1526,14 +1639,24 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1526
1639
  }).array()
1527
1640
  });
1528
1641
  backupsViewSchema = type({
1529
- enabled: "boolean",
1530
- dir: "string",
1531
- keep: "number",
1642
+ "enabled": "boolean",
1643
+ "dir": "string",
1644
+ "keep": "number",
1645
+ /**
1646
+ * The scheduled half, so the page can show and edit it.
1647
+ *
1648
+ * Optional because the panel and the UI upgrade separately: an older panel does not send it,
1649
+ * and a required field would blank the settings page for that panel. The page reads it as
1650
+ * "off, keep 7" when absent — the schema defaults — so nothing changes for it.
1651
+ */
1652
+ "schedule?": backupScheduleSchema,
1653
+ /** When the last automatic archive was written; null until one has run. Optional for the same reason. */
1654
+ "lastAutomaticAt?": "number | null",
1532
1655
  /** Extra paths from the global config, in addition to each server's own. */
1533
- includePaths: type("string[]"),
1656
+ "includePaths": type("string[]"),
1534
1657
  /** Every selectable entry, global first, then each workspace. */
1535
- entries: backupEntrySchema.array(),
1536
- files: backupFileSchema.array()
1658
+ "entries": backupEntrySchema.array(),
1659
+ "files": backupFileSchema.array()
1537
1660
  });
1538
1661
  restoreItemSchema = type({
1539
1662
  /** A backup entry or leaf id (`workspace:<id>:servers`, `data:<path>`, ...). */
@@ -1662,11 +1785,11 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1662
1785
  "files?": "number.integer >= 1",
1663
1786
  /** `owner/name` of the UI's own repository, for `ui-update`. */
1664
1787
  "repo?": "string",
1665
- /** The release tag this build came from, e.g. `v0.6.0`. */
1788
+ /** The release tag this build came from, e.g. `v0.6.0`. Stamped by the build, never committed. */
1666
1789
  "tag?": "string",
1667
1790
  /** The release asset name, e.g. `home-hosted-ui-noc-console`. */
1668
1791
  "asset?": "string",
1669
- /** When the UI was built, in unix epoch seconds. */
1792
+ /** When the UI was built, in unix epoch seconds. Stamped by the build, never committed. */
1670
1793
  "unix?": "number.integer >= 0"
1671
1794
  });
1672
1795
  uiStatusSchema = type({
@@ -1766,10 +1889,19 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1766
1889
  lines: logLineSchema.array()
1767
1890
  });
1768
1891
  notificationActionSchema = type({
1769
- /** Optional override, so the token can be tested before it is saved. */
1892
+ /** Optional override, so the token can be tried before it is saved. */
1770
1893
  botToken: "string?",
1771
1894
  chatId: "string?"
1772
1895
  }).onUndeclaredKey("reject");
1896
+ destinationIdParamSchema = type({ id: "/^[a-z0-9][a-z0-9_-]*$/" });
1897
+ destinationTestSchema = type({
1898
+ target: webhookTargetSchema.omit("kind", "id").and(type({
1899
+ id: "string?",
1900
+ kind: "\"webhook\"?"
1901
+ })),
1902
+ /** Echoed so the result is recorded against the right row; absent for a draft. */
1903
+ id: "string?"
1904
+ }).onUndeclaredKey("reject");
1773
1905
  telegramTokenSchema = type({ botToken: "string >= 1" }).onUndeclaredKey("reject");
1774
1906
  apiErrorSchema = type({
1775
1907
  "message": "string",
@@ -1967,6 +2099,20 @@ function isPlainDdns(value) {
1967
2099
  return "plain" in value;
1968
2100
  }
1969
2101
  /**
2102
+ * The bot tokens by destination id.
2103
+ *
2104
+ * Two shapes read: the map this release writes, and the single `{ botToken }` written before a
2105
+ * workspace could have more than one Telegram destination. The old one arrives under the id the
2106
+ * config migration gave the destination it came from, so an upgrade keeps a working Telegram.
2107
+ */
2108
+ function readTelegramTokens(value) {
2109
+ if (!isRecord(value)) return {};
2110
+ if (typeof value.botToken === "string") return value.botToken.trim().length > 0 ? { [LEGACY_TELEGRAM_ID]: value.botToken.trim() } : {};
2111
+ const tokens = {};
2112
+ for (const [id, token] of Object.entries(value)) if (typeof token === "string" && token.trim().length > 0) tokens[id] = token.trim();
2113
+ return tokens;
2114
+ }
2115
+ /**
1970
2116
  * Sealed on disk, or `{ provider, values }` waiting for the sealing write. A bare
1971
2117
  * field map — written before the provider was recorded — no longer reads, because
1972
2118
  * there is nothing to say which provider those fields belong to.
@@ -2048,7 +2194,7 @@ function openDdns(accountId, sealed, key) {
2048
2194
  return null;
2049
2195
  }
2050
2196
  }
2051
- var COST, KEYLEN, SALT_BYTES, DDNS_KEYLEN, DDNS_IV_BYTES, DDNS_AAD_PREFIX, DDNS_SEALED_ALGO, API_TOKEN_BYTES, API_TOKEN_HINT_CHARS, SecretsStore;
2197
+ var COST, KEYLEN, SALT_BYTES, LEGACY_TELEGRAM_ID, DDNS_KEYLEN, DDNS_IV_BYTES, DDNS_AAD_PREFIX, DDNS_SEALED_ALGO, API_TOKEN_BYTES, API_TOKEN_HINT_CHARS, SecretsStore;
2052
2198
  var init_secrets = __esmMin((() => {
2053
2199
  init_atomic();
2054
2200
  init_logger();
@@ -2061,6 +2207,7 @@ var init_secrets = __esmMin((() => {
2061
2207
  };
2062
2208
  KEYLEN = 64;
2063
2209
  SALT_BYTES = 16;
2210
+ LEGACY_TELEGRAM_ID = "telegram";
2064
2211
  DDNS_KEYLEN = 32;
2065
2212
  DDNS_IV_BYTES = 12;
2066
2213
  DDNS_AAD_PREFIX = "hh-ddns-v1:";
@@ -2138,11 +2285,17 @@ var init_secrets = __esmMin((() => {
2138
2285
  get apiTokenHint() {
2139
2286
  return this.apiToken?.hint ?? null;
2140
2287
  }
2141
- get telegramToken() {
2142
- return this.load().telegram?.botToken ?? null;
2288
+ /** The bot token for one destination, or null when it has none. */
2289
+ telegramToken(id) {
2290
+ const token = this.load().telegram[id] ?? "";
2291
+ return token.length > 0 ? token : null;
2292
+ }
2293
+ telegramTokenSet(id) {
2294
+ return this.telegramToken(id) !== null;
2143
2295
  }
2144
- get telegramTokenSet() {
2145
- return (this.telegramToken ?? "").length > 0;
2296
+ /** Every destination id a token is stored for — including one the config no longer declares. */
2297
+ get telegramTokenIds() {
2298
+ return Object.keys(this.load().telegram).sort();
2146
2299
  }
2147
2300
  setPassword(password, options = {}) {
2148
2301
  const record = hashPassword(password, options);
@@ -2177,11 +2330,24 @@ var init_secrets = __esmMin((() => {
2177
2330
  apiToken: null
2178
2331
  });
2179
2332
  }
2180
- setTelegramToken(token) {
2333
+ setTelegramToken(id, token) {
2181
2334
  const trimmed = token?.trim() ?? "";
2335
+ const current = { ...this.load().telegram };
2336
+ if (trimmed.length > 0) current[id] = trimmed;
2337
+ else delete current[id];
2182
2338
  this.save({
2183
2339
  ...this.load(),
2184
- telegram: trimmed.length > 0 ? { botToken: trimmed } : null
2340
+ telegram: current
2341
+ });
2342
+ }
2343
+ /** Drops every token whose destination is gone, so a deleted target leaves nothing behind. */
2344
+ forgetTelegramTokens(keep) {
2345
+ const allowed = new Set(keep);
2346
+ const current = this.load().telegram;
2347
+ const next = Object.fromEntries(Object.entries(current).filter(([id]) => allowed.has(id)));
2348
+ if (Object.keys(next).length !== Object.keys(current).length) this.save({
2349
+ ...this.load(),
2350
+ telegram: next
2185
2351
  });
2186
2352
  }
2187
2353
  /** Ids that have something stored, whether or not a config still declares them. */
@@ -2286,7 +2452,7 @@ var init_secrets = __esmMin((() => {
2286
2452
  const empty = {
2287
2453
  password: null,
2288
2454
  apiToken: null,
2289
- telegram: null,
2455
+ telegram: {},
2290
2456
  ddns: {},
2291
2457
  ddnsKdf: null
2292
2458
  };
@@ -2303,7 +2469,7 @@ var init_secrets = __esmMin((() => {
2303
2469
  return this.inScope({
2304
2470
  password: parsed?.password ?? null,
2305
2471
  apiToken: parsed?.apiToken?.hash ? parsed.apiToken : null,
2306
- telegram: parsed?.telegram?.botToken ? { botToken: parsed.telegram.botToken } : null,
2472
+ telegram: readTelegramTokens(parsed?.telegram),
2307
2473
  ddns: readStoredDdns(parsed?.ddns),
2308
2474
  ddnsKdf: readDdnsKdf(parsed?.ddnsKdf)
2309
2475
  });
@@ -2316,7 +2482,7 @@ var init_secrets = __esmMin((() => {
2316
2482
  inScope(contents) {
2317
2483
  if (this.scope === "global") return {
2318
2484
  ...contents,
2319
- telegram: null,
2485
+ telegram: {},
2320
2486
  ddns: {},
2321
2487
  ddnsKdf: null
2322
2488
  };
@@ -3121,7 +3287,10 @@ function buildWorkspaceView(source) {
3121
3287
  logsDir: source.logsDir,
3122
3288
  defaults: source.store.defaults,
3123
3289
  logs: source.store.logs,
3124
- notifications: { telegram: source.notifications.status() },
3290
+ notifications: {
3291
+ defaults: source.notifications.defaults(),
3292
+ destinations: source.notifications.destinations()
3293
+ },
3125
3294
  ddns: source.ddns.view,
3126
3295
  serverCount: servers.length,
3127
3296
  runningCount: servers.filter((server) => server.status === "running").length,
@@ -3717,9 +3886,62 @@ var init_control = __esmMin((() => {
3717
3886
  }));
3718
3887
  //#endregion
3719
3888
  //#region src/config/migrations.ts
3889
+ /**
3890
+ * The id the pre-list Telegram destination takes.
3891
+ *
3892
+ * **The one definition**, imported from the secrets reader, because that is where the bot token for
3893
+ * it already sits: the two have to agree on the id or the upgrade loses a working Telegram. They
3894
+ * were two literals with a comment claiming they were shared, and drifting one was undetected.
3895
+ */
3896
+ /**
3897
+ * Schema 1 → 2: `notifications.{telegram, webhooks}` → `notifications.{defaults, destinations}`.
3898
+ *
3899
+ * The old singleton becomes one `telegram` destination, and each webhook keeps its id, so a
3900
+ * destination's cooldown, last-result record and Telegram token all still point at the same thing.
3901
+ * `useOwnSettings` is set **true** on every migrated destination: before this schema each one
3902
+ * carried its own toggles, and reading one as "inherit" would silently change what it delivers.
3903
+ * The old webhook `enabled` default (true) and the Telegram one (false) are preserved as they were.
3904
+ */
3905
+ function notificationsToDestinations(config) {
3906
+ const notifications = config.notifications;
3907
+ if (notifications === null || typeof notifications !== "object" || Array.isArray(notifications)) return config;
3908
+ const group = notifications;
3909
+ if (group.destinations !== void 0 || group.telegram === void 0 && group.webhooks === void 0) return config;
3910
+ const destinations = [];
3911
+ const telegram = group.telegram;
3912
+ if (telegram !== null && typeof telegram === "object") {
3913
+ const { enabled, chatId, ...policy } = telegram;
3914
+ destinations.push({
3915
+ kind: "telegram",
3916
+ id: LEGACY_TELEGRAM_ID,
3917
+ enabled: enabled ?? false,
3918
+ chatId: chatId ?? "",
3919
+ useOwnSettings: true,
3920
+ ...policy
3921
+ });
3922
+ }
3923
+ if (Array.isArray(group.webhooks)) for (const entry of group.webhooks) {
3924
+ if (entry === null || typeof entry !== "object") continue;
3925
+ destinations.push({
3926
+ kind: "webhook",
3927
+ useOwnSettings: true,
3928
+ ...entry
3929
+ });
3930
+ }
3931
+ const next = {
3932
+ ...group,
3933
+ destinations
3934
+ };
3935
+ delete next.telegram;
3936
+ delete next.webhooks;
3937
+ return {
3938
+ ...config,
3939
+ notifications: next
3940
+ };
3941
+ }
3720
3942
  /** What would have to run to bring `from` up to `to`. */
3721
3943
  function planConfigMigrations(from, options = {}) {
3722
- const to = options.to ?? 1;
3944
+ const to = options.to ?? 2;
3723
3945
  const steps = (options.migrations ?? configMigrations).filter((migration) => migration.to > from && migration.to <= to).sort((a, b) => a.to - b.to);
3724
3946
  return {
3725
3947
  from,
@@ -3729,19 +3951,42 @@ function planConfigMigrations(from, options = {}) {
3729
3951
  reached: steps.at(-1)?.to ?? from
3730
3952
  };
3731
3953
  }
3732
- /** Applies the plan in order; the caller owns writing the result. */
3954
+ /**
3955
+ * Applies the plan in order; the caller owns writing the result.
3956
+ *
3957
+ * The result carries `meta.schema` set to the schema the steps reached, so it is readable by this
3958
+ * release's own parser — which refuses a file whose stamp still says an older schema. Without that,
3959
+ * `migrate` validated its own output as "needs 1 migration" and refused every config it exists to
3960
+ * lift.
3961
+ */
3733
3962
  function applyConfigMigrations(config, from, options = {}) {
3734
- const { steps } = planConfigMigrations(from, options);
3963
+ const plan = planConfigMigrations(from, options);
3735
3964
  let current = config;
3736
- for (const step of steps) current = step.apply(current);
3737
- return {
3965
+ for (const step of plan.steps) current = step.apply(current);
3966
+ if (plan.steps.length === 0) return {
3738
3967
  config: current,
3739
- applied: steps
3968
+ applied: plan.steps
3969
+ };
3970
+ const meta = current.meta !== null && typeof current.meta === "object" && !Array.isArray(current.meta) ? current.meta : {};
3971
+ return {
3972
+ config: {
3973
+ ...current,
3974
+ meta: {
3975
+ ...meta,
3976
+ schema: plan.reached
3977
+ }
3978
+ },
3979
+ applied: plan.steps
3740
3980
  };
3741
3981
  }
3742
3982
  var configMigrations;
3743
3983
  var init_migrations = __esmMin((() => {
3744
- configMigrations = [];
3984
+ init_secrets();
3985
+ configMigrations = [{
3986
+ to: 2,
3987
+ describe: "notifications: fold the Telegram singleton and the webhook list into one `destinations` list, with a shared `defaults` block",
3988
+ apply: notificationsToDestinations
3989
+ }];
3745
3990
  }));
3746
3991
  //#endregion
3747
3992
  //#region src/config/parse.ts
@@ -3805,10 +4050,10 @@ function readStamp(raw, options) {
3805
4050
  const meta = isRecord(raw.meta) ? raw.meta : null;
3806
4051
  const schemaVersion = typeof meta?.schema === "number" ? meta.schema : 1;
3807
4052
  const writtenBy = typeof meta?.writtenBy === "string" && meta.writtenBy.length > 0 ? meta.writtenBy : null;
3808
- if (schemaVersion > 1) return {
4053
+ if (schemaVersion > 2) return {
3809
4054
  schemaVersion,
3810
4055
  writtenBy,
3811
- error: `written by home-hosted ${writtenBy ?? "a newer release"} (config schema ${schemaVersion}); this release understands schema 1`
4056
+ error: `written by home-hosted ${writtenBy ?? "a newer release"} (config schema ${schemaVersion}); this release understands schema 2`
3812
4057
  };
3813
4058
  const { steps } = planConfigMigrations(schemaVersion, options);
3814
4059
  if (steps.length > 0) return {
@@ -3965,6 +4210,7 @@ function validateCrossField(servers) {
3965
4210
  for (const server of servers) {
3966
4211
  const { health } = server;
3967
4212
  if (health.mode === "http" && health.http.method === "HEAD" && health.http.expectBody.length > 0) errors.push(`"${server.id}" requires a response body with method HEAD, which has none — the body check is ignored`);
4213
+ if (health.mode === "http" && health.http.scheme === "http" && health.http.allowInvalidCert) errors.push(`"${server.id}" sets allowInvalidCert on an http probe, where there is no certificate to check`);
3968
4214
  for (const dependency of server.dependsOn) if (dependency === server.id) errors.push(`"${server.id}" depends on itself`);
3969
4215
  else if (!ids.has(dependency)) errors.push(`"${server.id}" depends on unknown server "${dependency}"`);
3970
4216
  }
@@ -3992,7 +4238,7 @@ function stampConfig(draft) {
3992
4238
  ...$schema === void 0 ? {} : { $schema },
3993
4239
  meta: {
3994
4240
  writtenBy: appVersion(),
3995
- schema: 1
4241
+ schema: 2
3996
4242
  },
3997
4243
  ...rest
3998
4244
  };
@@ -4043,7 +4289,7 @@ function mergeGroup(target, patch) {
4043
4289
  }
4044
4290
  return merged;
4045
4291
  }
4046
- var SERVER_MERGE_KEYS, CONTROL_MERGE_KEYS, NOTIFICATION_MERGE_KEYS, DDNS_MERGE_KEYS, PROXY_MERGE_KEYS, EMPTY_MERGE_KEYS;
4292
+ var SERVER_MERGE_KEYS, CONTROL_MERGE_KEYS, NOTIFICATION_MERGE_KEYS, DDNS_MERGE_KEYS, PROXY_MERGE_KEYS, BACKUP_MERGE_KEYS, EMPTY_MERGE_KEYS;
4047
4293
  var init_patch = __esmMin((() => {
4048
4294
  init_shape();
4049
4295
  SERVER_MERGE_KEYS = /* @__PURE__ */ new Set([
@@ -4052,9 +4298,10 @@ var init_patch = __esmMin((() => {
4052
4298
  "stop"
4053
4299
  ]);
4054
4300
  CONTROL_MERGE_KEYS = /* @__PURE__ */ new Set(["auth", "tls"]);
4055
- NOTIFICATION_MERGE_KEYS = /* @__PURE__ */ new Set(["telegram"]);
4301
+ NOTIFICATION_MERGE_KEYS = /* @__PURE__ */ new Set(["defaults"]);
4056
4302
  DDNS_MERGE_KEYS = /* @__PURE__ */ new Set(["ipv4", "ipv6"]);
4057
4303
  PROXY_MERGE_KEYS = /* @__PURE__ */ new Set(["dns01"]);
4304
+ BACKUP_MERGE_KEYS = /* @__PURE__ */ new Set(["schedule"]);
4058
4305
  EMPTY_MERGE_KEYS = /* @__PURE__ */ new Set();
4059
4306
  }));
4060
4307
  //#endregion
@@ -4244,7 +4491,7 @@ var init_settings$1 = __esmMin((() => {
4244
4491
  updateBackups(patch) {
4245
4492
  const draft = structuredClone(this.raw);
4246
4493
  draft.backups = { ...draft.backups ?? {} };
4247
- applyPatch(draft.backups, patch, EMPTY_MERGE_KEYS);
4494
+ applyPatch(draft.backups, patch, BACKUP_MERGE_KEYS);
4248
4495
  const backups = this.parseGroup(backupsSchema, draft.backups, "backups");
4249
4496
  this.commit(draft);
4250
4497
  return backups;
@@ -5806,6 +6053,171 @@ var init_ddns$2 = __esmMin((() => {
5806
6053
  BY_ID$1 = new Map(DDNS_PROVIDERS.map((provider) => [provider.id, provider]));
5807
6054
  }));
5808
6055
  //#endregion
6056
+ //#region src/helpers/env-file.ts
6057
+ /** `KEY=value` files, with optional `export `, `#` comments and quoted values. */
6058
+ function parseEnvFile(text) {
6059
+ const env = {};
6060
+ for (const raw of text.split("\n")) {
6061
+ const line = raw.trim();
6062
+ if (line.length === 0 || line.startsWith("#")) continue;
6063
+ const assignment = line.startsWith("export ") ? line.slice(7) : line;
6064
+ const separator = assignment.indexOf("=");
6065
+ if (separator <= 0) continue;
6066
+ const key = assignment.slice(0, separator).trim();
6067
+ let value = assignment.slice(separator + 1).trim();
6068
+ if (value.length > 1 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
6069
+ env[key] = value;
6070
+ }
6071
+ return env;
6072
+ }
6073
+ /** Missing files are not an error: an env file is an optional override layer. */
6074
+ function loadEnvFile(file) {
6075
+ try {
6076
+ return {
6077
+ env: parseEnvFile(fs.readFileSync(file, "utf8")),
6078
+ path: file,
6079
+ error: null
6080
+ };
6081
+ } catch (error) {
6082
+ if (error.code === "ENOENT") return {
6083
+ env: {},
6084
+ path: file,
6085
+ error: null
6086
+ };
6087
+ return {
6088
+ env: {},
6089
+ path: file,
6090
+ error: errorMessage(error)
6091
+ };
6092
+ }
6093
+ }
6094
+ /** Expands `${VAR}` from the given vars; unknown references are left visible. */
6095
+ function expandEnv(value, vars) {
6096
+ return value.replace(VARIABLE, (match, name) => vars[name] ?? match);
6097
+ }
6098
+ function expandEnvRecord(record, vars) {
6099
+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, expandEnv(value, vars)]));
6100
+ }
6101
+ function expandEnvList(values, vars) {
6102
+ return values.map((value) => expandEnv(value, vars));
6103
+ }
6104
+ function resolveEnvFilePath(file, cwd) {
6105
+ if (path.isAbsolute(file)) return file;
6106
+ return path.resolve(cwd, file);
6107
+ }
6108
+ var VARIABLE;
6109
+ var init_env_file = __esmMin((() => {
6110
+ init_error_message();
6111
+ VARIABLE = /\$\{([A-Z_]\w*)\}/gi;
6112
+ }));
6113
+ //#endregion
6114
+ //#region src/providers/webhook.ts
6115
+ /** The JSON body for one event. Exported so a test can pin the shape without a round trip. */
6116
+ function webhookPayload(event, now = Date.now()) {
6117
+ const text = `${event.title}\n${event.message}`;
6118
+ return {
6119
+ text,
6120
+ content: text,
6121
+ title: event.title,
6122
+ message: event.message,
6123
+ reason: event.reason,
6124
+ server: event.serverId.length > 0 ? event.serverId : null,
6125
+ label: event.label.length > 0 ? event.label : null,
6126
+ at: now
6127
+ };
6128
+ }
6129
+ /**
6130
+ * `Name: value` lines into a header map.
6131
+ *
6132
+ * The format is line-based rather than a JSON object because it is edited in a textarea, and
6133
+ * a value with a colon in it (`Authorization: Bearer a:b`) must survive: only the **first**
6134
+ * colon separates the two.
6135
+ *
6136
+ * `vars` expands `${ENV}` in the values, so a credential does not have to be written into the
6137
+ * config file. A name the panel's environment does not define is left as written, the same rule
6138
+ * `expandEnv` follows everywhere else.
6139
+ */
6140
+ function parseHeaders(text, vars = process.env) {
6141
+ const headers = {};
6142
+ const errors = [];
6143
+ for (const line of text.split("\n")) {
6144
+ const trimmed = line.trim();
6145
+ if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
6146
+ const at = trimmed.indexOf(":");
6147
+ if (at <= 0) {
6148
+ errors.push(`"${trimmed}" is not a "Name: value" header`);
6149
+ continue;
6150
+ }
6151
+ headers[trimmed.slice(0, at).trim()] = expandEnv(trimmed.slice(at + 1).trim(), vars);
6152
+ }
6153
+ return {
6154
+ headers,
6155
+ errors
6156
+ };
6157
+ }
6158
+ /** Why a target cannot be sent to, or null when it can. Also used to validate a save. */
6159
+ function targetProblem(target, options = {}) {
6160
+ const url = target.url.trim();
6161
+ if (url.length === 0) return options.requireUrl === false ? null : "no URL configured";
6162
+ let parsed;
6163
+ try {
6164
+ parsed = new URL(url);
6165
+ } catch {
6166
+ return "the URL is not valid";
6167
+ }
6168
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return `the URL must be http or https, not ${parsed.protocol}`;
6169
+ const { errors } = parseHeaders(target.headers);
6170
+ return errors.length > 0 ? errors.join("; ") : null;
6171
+ }
6172
+ async function sendWebhook(target, event, fetchImpl) {
6173
+ const problem = targetProblem(target);
6174
+ if (problem !== null) return {
6175
+ ok: false,
6176
+ error: problem
6177
+ };
6178
+ const { headers, errors } = parseHeaders(target.headers);
6179
+ if (errors.length > 0) return {
6180
+ ok: false,
6181
+ error: errors.join("; ")
6182
+ };
6183
+ const payload = webhookPayload(event);
6184
+ const asText = target.format === "text";
6185
+ const body = asText ? payload.message : JSON.stringify(payload);
6186
+ const url = expandEnv(target.url.trim(), process.env);
6187
+ if (url.includes("${")) return {
6188
+ ok: false,
6189
+ error: `the URL still holds an unexpanded placeholder: ${url}`
6190
+ };
6191
+ try {
6192
+ const response = await (fetchImpl ?? fetch)(url, {
6193
+ method: target.method,
6194
+ headers: {
6195
+ "content-type": asText ? "text/plain; charset=utf-8" : "application/json",
6196
+ ...headers
6197
+ },
6198
+ body,
6199
+ signal: AbortSignal.timeout(1e4)
6200
+ });
6201
+ if (!response.ok) {
6202
+ const trimmed = (await response.text().catch(() => "")).trim().slice(0, 200);
6203
+ return {
6204
+ ok: false,
6205
+ error: `answered ${response.status}${trimmed.length > 0 ? `: ${trimmed}` : ""}`
6206
+ };
6207
+ }
6208
+ return { ok: true };
6209
+ } catch (error) {
6210
+ return {
6211
+ ok: false,
6212
+ error: errorMessage(error)
6213
+ };
6214
+ }
6215
+ }
6216
+ var init_webhook = __esmMin((() => {
6217
+ init_env_file();
6218
+ init_error_message();
6219
+ }));
6220
+ //#endregion
5809
6221
  //#region src/config/store.ts
5810
6222
  function readFile(file) {
5811
6223
  let text;
@@ -5851,6 +6263,8 @@ var init_store = __esmMin((() => {
5851
6263
  init_settings$1();
5852
6264
  init_atomic();
5853
6265
  init_ddns$2();
6266
+ init_webhook();
6267
+ init_contracts();
5854
6268
  WorkspaceStore = class {
5855
6269
  workspaceId;
5856
6270
  settingsFile;
@@ -6070,6 +6484,13 @@ var init_store = __esmMin((() => {
6070
6484
  draft.notifications = { ...draft.notifications ?? {} };
6071
6485
  applyPatch(draft.notifications, patch, NOTIFICATION_MERGE_KEYS);
6072
6486
  const notifications = this.parseGroup(notificationsSchema, draft.notifications, "notifications");
6487
+ const duplicates = duplicateWebhookIds(notifications.destinations);
6488
+ if (duplicates.length > 0) throw new ConfigError(`notifications: duplicate webhook id ${duplicates.map((id) => `"${id}"`).join(", ")}`);
6489
+ for (const target of notifications.destinations) {
6490
+ if (target.kind !== "webhook") continue;
6491
+ const problem = targetProblem(target, { requireUrl: true });
6492
+ if (problem !== null) throw new ConfigError(`notifications: webhook "${target.id}" ${problem}`);
6493
+ }
6073
6494
  this.commitSettings(draft);
6074
6495
  return notifications;
6075
6496
  }
@@ -6769,58 +7190,77 @@ var init_telegram = __esmMin((() => {
6769
7190
  //#endregion
6770
7191
  //#region src/api/notifications.ts
6771
7192
  /**
6772
- * The bot token is written straight to a workspace's secrets file and never into a
7193
+ * A destination's credential is written straight to a workspace's secrets file and never into a
6773
7194
  * servers config, so notification *policy* and the *credential* stay separate.
6774
7195
  *
6775
- * Notifications belong to a workspace: each one keeps its own token and chat.
7196
+ * Notifications belong to a workspace, and every route is scoped to one. The token is keyed by the
7197
+ * **destination id**, which is what lets a workspace point at more than one Telegram chat.
6776
7198
  */
6777
7199
  function createNotificationsRoute(deps) {
6778
- return appFactory.createApp().put("/notifications/token", describeRoute({
7200
+ const runtimeFor = (workspace) => requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), workspace);
7201
+ return appFactory.createApp().put("/notifications/destinations/:id/token", describeRoute({
6779
7202
  tags: ["notifications"],
6780
- summary: "Store the Telegram bot token (verified first)",
7203
+ summary: "Store a Telegram destination's bot token (verified first)",
6781
7204
  responses: {
6782
7205
  200: { description: "Stored" },
6783
7206
  400: ERROR_RESPONSES[400]
6784
7207
  }
6785
- }), validate("query", workspaceQuerySchema), validate("json", telegramTokenSchema), async (c) => {
6786
- const runtime = requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace);
7208
+ }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), validate("json", telegramTokenSchema), async (c) => {
7209
+ const runtime = runtimeFor(c.req.valid("query").workspace);
7210
+ const id = c.req.valid("param").id;
6787
7211
  const { botToken } = c.req.valid("json");
6788
7212
  const verified = await runtime.notifications.verifyToken(botToken);
6789
7213
  if (!verified.ok) throw new DetailedError(`telegram rejected the token: ${verified.error ?? "unknown error"}`, {
6790
7214
  statusCode: 400,
6791
7215
  code: "TELEGRAM_TOKEN_REJECTED"
6792
7216
  });
6793
- runtime.secrets.setTelegramToken(botToken);
7217
+ runtime.secrets.setTelegramToken(id, botToken);
6794
7218
  forgetBots();
6795
7219
  return c.json({
6796
7220
  ok: true,
6797
7221
  username: verified.username ?? null
6798
7222
  });
6799
- }).delete("/notifications/token", describeRoute({
7223
+ }).delete("/notifications/destinations/:id/token", describeRoute({
6800
7224
  tags: ["notifications"],
6801
- summary: "Forget the Telegram bot token",
7225
+ summary: "Forget a Telegram destination's bot token",
6802
7226
  responses: { 200: { description: "Removed" } }
6803
- }), validate("query", workspaceQuerySchema), (c) => {
6804
- requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace).secrets.setTelegramToken(null);
7227
+ }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), (c) => {
7228
+ runtimeFor(c.req.valid("query").workspace).secrets.setTelegramToken(c.req.valid("param").id, null);
6805
7229
  forgetBots();
6806
7230
  return c.json({ ok: true });
6807
- }).post("/notifications/test", describeRoute({
7231
+ }).post("/notifications/destinations/:id/test", describeRoute({
6808
7232
  tags: ["notifications"],
6809
- summary: "Send a test message",
7233
+ summary: "Send a test message to one destination",
6810
7234
  responses: {
6811
7235
  200: { description: "Sent or refused" },
6812
7236
  400: ERROR_RESPONSES[400]
6813
7237
  }
6814
- }), validate("query", workspaceQuerySchema), validate("json", notificationActionSchema), async (c) => {
6815
- const result = await requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace).notifications.sendTest(c.req.valid("json"));
7238
+ }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), validate("json", notificationActionSchema), async (c) => {
7239
+ const result = await runtimeFor(c.req.valid("query").workspace).notifications.sendTest(c.req.valid("param").id, c.req.valid("json"));
6816
7240
  if (!result.ok) throw new DetailedError(result.error ?? "the test message failed", {
6817
7241
  statusCode: 400,
6818
7242
  code: "TELEGRAM_SEND_FAILED"
6819
7243
  });
6820
7244
  return c.json(result);
6821
- }).post("/notifications/detect-chats", describeRoute({
7245
+ }).post("/notifications/test-webhook", describeRoute({
6822
7246
  tags: ["notifications"],
6823
- summary: "List the chats the bot can see",
7247
+ summary: "Send a test to one webhook destination",
7248
+ responses: {
7249
+ 200: { description: "Sent or refused" },
7250
+ 400: ERROR_RESPONSES[400]
7251
+ }
7252
+ }), validate("query", workspaceQuerySchema), validate("json", destinationTestSchema), async (c) => {
7253
+ const runtime = runtimeFor(c.req.valid("query").workspace);
7254
+ const { target, id } = c.req.valid("json");
7255
+ const result = await runtime.notifications.testWebhook(target, id);
7256
+ if (!result.ok) throw new DetailedError(result.error ?? "the test message failed", {
7257
+ statusCode: 400,
7258
+ code: "WEBHOOK_SEND_FAILED"
7259
+ });
7260
+ return c.json(result);
7261
+ }).post("/notifications/destinations/:id/detect-chats", describeRoute({
7262
+ tags: ["notifications"],
7263
+ summary: "List the chats a Telegram destination's bot can see",
6824
7264
  responses: {
6825
7265
  200: {
6826
7266
  description: "Chats",
@@ -6828,8 +7268,8 @@ function createNotificationsRoute(deps) {
6828
7268
  },
6829
7269
  400: ERROR_RESPONSES[400]
6830
7270
  }
6831
- }), validate("query", workspaceQuerySchema), validate("json", notificationActionSchema), async (c) => {
6832
- const result = await requireWorkspace(deps.panel.requireWorkspace.bind(deps.panel), c.req.valid("query").workspace).notifications.detectChats(c.req.valid("json"));
7271
+ }), validate("query", workspaceQuerySchema), validate("param", destinationIdParamSchema), validate("json", notificationActionSchema), async (c) => {
7272
+ const result = await runtimeFor(c.req.valid("query").workspace).notifications.detectChats(c.req.valid("param").id, c.req.valid("json"));
6833
7273
  if (!result.ok) throw new DetailedError(result.error ?? "could not list chats", {
6834
7274
  statusCode: 400,
6835
7275
  code: "TELEGRAM_LIST_FAILED"
@@ -10531,7 +10971,10 @@ function buildWorkspaceSettings(runtime) {
10531
10971
  configError: runtime.store.configError,
10532
10972
  defaults: runtime.store.defaults,
10533
10973
  logs: runtime.store.logs,
10534
- notifications: { telegram: runtime.notifications.status() }
10974
+ notifications: {
10975
+ defaults: runtime.notifications.defaults(),
10976
+ destinations: runtime.notifications.destinations()
10977
+ }
10535
10978
  };
10536
10979
  }
10537
10980
  function createSettingsRoute(deps) {
@@ -10723,7 +11166,10 @@ function createSettingsRoute(deps) {
10723
11166
  try {
10724
11167
  if (patch.defaults !== void 0) runtime.store.updateDefaults(patch.defaults);
10725
11168
  if (patch.logs !== void 0) runtime.store.updateLogs(patch.logs);
10726
- if (patch.notifications !== void 0) runtime.store.updateNotifications(patch.notifications);
11169
+ if (patch.notifications !== void 0) {
11170
+ const saved = runtime.store.updateNotifications(patch.notifications);
11171
+ runtime.secrets.forgetTelegramTokens(saved.destinations.map((destination) => destination.id));
11172
+ }
10727
11173
  } catch (error) {
10728
11174
  if (error instanceof ConfigError) throw new DetailedError(error.message, {
10729
11175
  statusCode: 400,
@@ -11546,64 +11992,6 @@ var init_secret_parts = __esmMin((() => {
11546
11992
  EXTRA_FIELDS = { ddns: ["ddns", "ddnsKdf"] };
11547
11993
  }));
11548
11994
  //#endregion
11549
- //#region src/helpers/env-file.ts
11550
- /** `KEY=value` files, with optional `export `, `#` comments and quoted values. */
11551
- function parseEnvFile(text) {
11552
- const env = {};
11553
- for (const raw of text.split("\n")) {
11554
- const line = raw.trim();
11555
- if (line.length === 0 || line.startsWith("#")) continue;
11556
- const assignment = line.startsWith("export ") ? line.slice(7) : line;
11557
- const separator = assignment.indexOf("=");
11558
- if (separator <= 0) continue;
11559
- const key = assignment.slice(0, separator).trim();
11560
- let value = assignment.slice(separator + 1).trim();
11561
- if (value.length > 1 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
11562
- env[key] = value;
11563
- }
11564
- return env;
11565
- }
11566
- /** Missing files are not an error: an env file is an optional override layer. */
11567
- function loadEnvFile(file) {
11568
- try {
11569
- return {
11570
- env: parseEnvFile(fs.readFileSync(file, "utf8")),
11571
- path: file,
11572
- error: null
11573
- };
11574
- } catch (error) {
11575
- if (error.code === "ENOENT") return {
11576
- env: {},
11577
- path: file,
11578
- error: null
11579
- };
11580
- return {
11581
- env: {},
11582
- path: file,
11583
- error: errorMessage(error)
11584
- };
11585
- }
11586
- }
11587
- /** Expands `${VAR}` from the given vars; unknown references are left visible. */
11588
- function expandEnv(value, vars) {
11589
- return value.replace(VARIABLE, (match, name) => vars[name] ?? match);
11590
- }
11591
- function expandEnvRecord(record, vars) {
11592
- return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, expandEnv(value, vars)]));
11593
- }
11594
- function expandEnvList(values, vars) {
11595
- return values.map((value) => expandEnv(value, vars));
11596
- }
11597
- function resolveEnvFilePath(file, cwd) {
11598
- if (path.isAbsolute(file)) return file;
11599
- return path.resolve(cwd, file);
11600
- }
11601
- var VARIABLE;
11602
- var init_env_file = __esmMin((() => {
11603
- init_error_message();
11604
- VARIABLE = /\$\{([A-Z_]\w*)\}/gi;
11605
- }));
11606
- //#endregion
11607
11995
  //#region src/providers/archive.ts
11608
11996
  /** Recognised by content, never by the file's name. */
11609
11997
  function isZipArchive(file) {
@@ -11850,18 +12238,99 @@ async function probeTcp(host, port, timeoutMs) {
11850
12238
  };
11851
12239
  }
11852
12240
  /**
12241
+ * One request/response, capped at `timeoutMs` and `MAX_BODY_BYTES`.
12242
+ *
12243
+ * Node's `fetch` cannot be told to accept a certificate it does not trust, which is the normal
12244
+ * case for a backend on a home network: its own self-signed pair, or one from the engine's local
12245
+ * CA. So this speaks http/https directly, the same way `helpers/daemon.ts` reaches a panel with an
12246
+ * uploaded pair. A `HEAD` gets no body, which the caller already accounts for.
12247
+ */
12248
+ function request(url, method, allowInvalidCert, timeoutMs) {
12249
+ return new Promise((resolve, reject) => {
12250
+ const secure = url.protocol === "https:";
12251
+ let req;
12252
+ let settled = false;
12253
+ let deadline;
12254
+ const finish = (value) => {
12255
+ if (settled) return;
12256
+ settled = true;
12257
+ clearTimeout(deadline);
12258
+ resolve(value);
12259
+ };
12260
+ const fail = (error) => {
12261
+ if (settled) return;
12262
+ settled = true;
12263
+ clearTimeout(deadline);
12264
+ reject(error instanceof Error ? error : new Error(String(error)));
12265
+ };
12266
+ /**
12267
+ * The whole exchange, not just the socket.
12268
+ *
12269
+ * `timeout` on the request is an **idle** timeout, so a server dripping one byte every half
12270
+ * second keeps resetting it and the probe never returns — which hangs the supervisor's tick,
12271
+ * since the probe is awaited. The old `fetch` path had `AbortSignal.timeout`, an absolute
12272
+ * cap; this restores that guarantee.
12273
+ */
12274
+ deadline = setTimeout(() => {
12275
+ fail(/* @__PURE__ */ new Error(`no complete response within ${timeoutMs}ms`));
12276
+ req.destroy();
12277
+ }, timeoutMs);
12278
+ deadline.unref();
12279
+ req = (secure ? https : http).request({
12280
+ hostname: url.hostname,
12281
+ port: url.port,
12282
+ path: `${url.pathname}${url.search}`,
12283
+ method,
12284
+ ...secure && allowInvalidCert ? { rejectUnauthorized: false } : {},
12285
+ timeout: timeoutMs
12286
+ }, (response) => {
12287
+ let body = "";
12288
+ let bytes = 0;
12289
+ let truncated = false;
12290
+ response.setEncoding("utf8");
12291
+ response.on("data", (chunk) => {
12292
+ if (truncated) return;
12293
+ bytes += Buffer$1.byteLength(chunk);
12294
+ if (bytes > MAX_BODY_BYTES) {
12295
+ truncated = true;
12296
+ body += chunk.slice(0, Math.max(0, MAX_BODY_BYTES - (bytes - Buffer$1.byteLength(chunk))));
12297
+ response.destroy();
12298
+ finish({
12299
+ status: response.statusCode ?? 0,
12300
+ body,
12301
+ truncated
12302
+ });
12303
+ return;
12304
+ }
12305
+ body += chunk;
12306
+ });
12307
+ response.once("end", () => {
12308
+ if (!truncated) finish({
12309
+ status: response.statusCode ?? 0,
12310
+ body,
12311
+ truncated
12312
+ });
12313
+ });
12314
+ response.once("error", (error) => {
12315
+ if (!truncated) fail(error);
12316
+ });
12317
+ });
12318
+ req.once("error", (error) => fail(error));
12319
+ req.once("timeout", () => {
12320
+ fail(/* @__PURE__ */ new Error(`no response within ${timeoutMs}ms`));
12321
+ req.destroy();
12322
+ });
12323
+ req.end();
12324
+ });
12325
+ }
12326
+ /**
11853
12327
  * Fetches the configured path and asserts the response, so "listening" is not
11854
12328
  * mistaken for "working".
11855
12329
  */
11856
12330
  async function probeHttp(host, port, options) {
11857
- const url = `http://${host}:${port}${options.path.startsWith("/") ? options.path : `/${options.path}`}`;
11858
12331
  const started = Date.now();
11859
12332
  try {
11860
- const response = await fetch(url, {
11861
- method: options.method,
11862
- redirect: "manual",
11863
- signal: AbortSignal.timeout(options.timeoutMs)
11864
- });
12333
+ const response = await request(new URL(`${options.scheme}://${host}:${port}${options.path.startsWith("/") ? options.path : `/${options.path}`}`), options.method, options.allowInvalidCert, options.timeoutMs);
11865
12334
  const ms = Date.now() - started;
11866
12335
  const expected = options.expectStatus ?? null;
11867
12336
  if (expected !== null && response.status !== expected) return {
@@ -11876,11 +12345,14 @@ async function probeHttp(host, port, options) {
11876
12345
  };
11877
12346
  const bodySkipped = options.expectBody.length > 0 && options.method === "HEAD";
11878
12347
  if (options.expectBody.length > 0 && !bodySkipped) {
11879
- if (!(await response.text()).includes(options.expectBody)) return {
11880
- healthy: false,
11881
- ms,
11882
- detail: `body does not contain ${JSON.stringify(options.expectBody)}`
11883
- };
12348
+ if (!response.body.includes(options.expectBody)) {
12349
+ const scope = response.truncated ? ` (only the first ${MAX_BODY_BYTES} bytes were read)` : "";
12350
+ return {
12351
+ healthy: false,
12352
+ ms,
12353
+ detail: `body does not contain ${JSON.stringify(options.expectBody)}${scope}`
12354
+ };
12355
+ }
11884
12356
  }
11885
12357
  if (bodySkipped) return {
11886
12358
  healthy: true,
@@ -11916,9 +12388,11 @@ async function probeHealth(options) {
11916
12388
  }
11917
12389
  return last;
11918
12390
  }
12391
+ var MAX_BODY_BYTES;
11919
12392
  var init_health_check = __esmMin((() => {
11920
12393
  init_port();
11921
12394
  init_error_message();
12395
+ MAX_BODY_BYTES = 1e6;
11922
12396
  }));
11923
12397
  //#endregion
11924
12398
  //#region src/providers/process.ts
@@ -13716,6 +14190,7 @@ var init_supervisor = __esmMin((() => {
13716
14190
  }
13717
14191
  /** The decisions that have to survive this panel, and nothing else. */
13718
14192
  persistEntryState(entry) {
14193
+ if (entry.removed) return;
13719
14194
  writeEntryState(entryStatePath(this.options.nannyDir, entry.config.id), {
13720
14195
  restarts: entry.restarts,
13721
14196
  bootstrapDone: entry.bootstrapDone,
@@ -14001,6 +14476,10 @@ function readText(file) {
14001
14476
  return null;
14002
14477
  }
14003
14478
  }
14479
+ /** Whether an archive came from the schedule rather than from a person. */
14480
+ function isAutomatic(file) {
14481
+ return file.name.startsWith(`${AUTO_PREFIX}-`);
14482
+ }
14004
14483
  /** The label of one item, for `applied`; items are built before actions run. */
14005
14484
  function labelOf(plan, id) {
14006
14485
  return plan.items.find((item) => item.id === id)?.label ?? id;
@@ -14048,13 +14527,14 @@ function readableWorkspaceSettings(text) {
14048
14527
  return false;
14049
14528
  }
14050
14529
  }
14051
- var MANIFEST, ALLOWED_ROOTS, SUFFIX, RELOADABLE, SECRET_LABELS, BackupService;
14530
+ var MANIFEST, ALLOWED_ROOTS, SUFFIX, AUTO_PREFIX, RELOADABLE, SECRET_LABELS, BackupService;
14052
14531
  var init_backups = __esmMin((() => {
14053
14532
  init_migrations();
14054
14533
  init_parse();
14055
14534
  init_secret_parts();
14056
14535
  init_atomic();
14057
14536
  init_env_file();
14537
+ init_logger();
14058
14538
  init_paths();
14059
14539
  init_template();
14060
14540
  init_version();
@@ -14070,6 +14550,7 @@ var init_backups = __esmMin((() => {
14070
14550
  "data"
14071
14551
  ]);
14072
14552
  SUFFIX = ".zip";
14553
+ AUTO_PREFIX = "auto";
14073
14554
  RELOADABLE = /^global:settings$|^workspace:[^:]+:(?:settings|servers)$/;
14074
14555
  SECRET_LABELS = {
14075
14556
  password: {
@@ -14098,6 +14579,17 @@ var init_backups = __esmMin((() => {
14098
14579
  */
14099
14580
  flags = /* @__PURE__ */ new Map();
14100
14581
  refreshing = null;
14582
+ /** One scheduled pass at a time: a slow archive must not stack up behind itself. */
14583
+ running = false;
14584
+ disposed = false;
14585
+ /**
14586
+ * When this instance last attempted an automatic pass, whatever it wrote.
14587
+ *
14588
+ * The archive's own mtime is the durable record across a restart, but it cannot bound a
14589
+ * failed pass: nothing is written, so every panel tick would retry — once a second, for as
14590
+ * long as the failure lasts. This is the in-memory backstop for that case.
14591
+ */
14592
+ lastAttemptAt = null;
14101
14593
  constructor(options) {
14102
14594
  this.options = options;
14103
14595
  }
@@ -14105,6 +14597,9 @@ var init_backups = __esmMin((() => {
14105
14597
  async warm() {
14106
14598
  await this.refresh();
14107
14599
  }
14600
+ dispose() {
14601
+ this.disposed = true;
14602
+ }
14108
14603
  get directory() {
14109
14604
  return this.resolveDir();
14110
14605
  }
@@ -14116,6 +14611,8 @@ var init_backups = __esmMin((() => {
14116
14611
  enabled: config.enabled,
14117
14612
  dir: this.directory,
14118
14613
  keep: config.keep,
14614
+ schedule: { ...config.schedule },
14615
+ lastAutomaticAt: this.lastAutomatic(),
14119
14616
  includePaths: [...sources.includePaths],
14120
14617
  entries: this.entries(sources),
14121
14618
  files: this.list()
@@ -14141,7 +14638,13 @@ var init_backups = __esmMin((() => {
14141
14638
  const file = path.join(this.resolveDir(), name);
14142
14639
  return fs.existsSync(file) ? file : null;
14143
14640
  }
14144
- /** `password` encrypts the archive; it is never stored anywhere. */
14641
+ /**
14642
+ * `password` encrypts the archive; it is never stored anywhere.
14643
+ *
14644
+ * `automatic` marks an archive the schedule wrote, which is what keeps the two retention
14645
+ * counts apart: an automatic pass must never prune the backup a person took by hand, and a
14646
+ * manual one must not silently eat the history the schedule is keeping.
14647
+ */
14145
14648
  async create(options = {}) {
14146
14649
  if (!this.options.getConfig().enabled) return {
14147
14650
  ok: false,
@@ -14165,7 +14668,7 @@ var init_backups = __esmMin((() => {
14165
14668
  const sources = this.options.getSources();
14166
14669
  const staging = path.join(dir, `.staging-${Date.now()}`);
14167
14670
  const createdAt = Date.now();
14168
- const name = `backup-${new Date(createdAt).toISOString().replace(/[:T]/g, "-").replace(/\.\d+Z$/, "")}-${createdAt % 1e3}${SUFFIX}`;
14671
+ const name = `${options.automatic === true ? AUTO_PREFIX : "backup"}-${new Date(createdAt).toISOString().replace(/[:T]/g, "-").replace(/\.\d+Z$/, "")}-${createdAt % 1e3}${SUFFIX}`;
14169
14672
  const destination = path.join(dir, name);
14170
14673
  try {
14171
14674
  fs.mkdirSync(staging, { recursive: true });
@@ -14239,7 +14742,7 @@ var init_backups = __esmMin((() => {
14239
14742
  createdAt,
14240
14743
  hostname: os.hostname(),
14241
14744
  writtenBy: appVersion(),
14242
- schema: 1,
14745
+ schema: 2,
14243
14746
  data
14244
14747
  };
14245
14748
  fs.writeFileSync(path.join(staging, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
@@ -14355,9 +14858,9 @@ var init_backups = __esmMin((() => {
14355
14858
  };
14356
14859
  const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
14357
14860
  plan.archive = manifestInfo(manifest);
14358
- if (manifest.schema !== void 0 && manifest.schema > 1) return {
14861
+ if (manifest.schema !== void 0 && manifest.schema > 2) return {
14359
14862
  ...plan,
14360
- error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 1`
14863
+ error: `written by home-hosted ${manifest.writtenBy ?? "a newer release"} (config schema ${manifest.schema}); this release understands schema 2`
14361
14864
  };
14362
14865
  const sources = this.options.getSources();
14363
14866
  const selectedIds = options.include === void 0 ? null : new Set(options.include);
@@ -14943,9 +15446,46 @@ var init_backups = __esmMin((() => {
14943
15446
  });
14944
15447
  return true;
14945
15448
  }
15449
+ /**
15450
+ * Drops the oldest archives past their own limit.
15451
+ *
15452
+ * Two budgets, because the two sources are not the same thing: `keep` is what a person
15453
+ * agreed to store, and pruning a hand-taken archive to make room for a scheduled one would
15454
+ * lose the copy they deliberately made. The scheduled pair keeps `schedule.keep` automatic
15455
+ * archives; the rest keeps `keep`.
15456
+ */
14946
15457
  prune() {
14947
- const { keep } = this.options.getConfig();
14948
- for (const file of this.list().slice(keep)) this.remove(file.name);
15458
+ const config = this.options.getConfig();
15459
+ const files = this.list();
15460
+ const automatic = files.filter(isAutomatic);
15461
+ const manual = files.filter((file) => !isAutomatic(file));
15462
+ for (const file of automatic.slice(config.schedule.keep)) this.remove(file.name);
15463
+ for (const file of manual.slice(config.keep)) this.remove(file.name);
15464
+ }
15465
+ /** When the newest automatic archive was written, or null when there is none. */
15466
+ lastAutomatic() {
15467
+ return this.list().find(isAutomatic)?.createdAt ?? null;
15468
+ }
15469
+ /**
15470
+ * Runs one scheduled pass when it is due. Modelled on the DDNS pass: cheap to call on every
15471
+ * panel tick, never blocking, and never two at once.
15472
+ */
15473
+ tick(now = Date.now()) {
15474
+ if (this.disposed || this.running) return;
15475
+ const config = this.options.getConfig();
15476
+ if (!config.enabled || config.schedule.intervalMs <= 0) return;
15477
+ const last = this.lastAutomatic();
15478
+ const latest = last === null ? this.lastAttemptAt : Math.max(last, this.lastAttemptAt ?? 0);
15479
+ if (latest !== null && now - latest < config.schedule.intervalMs) return;
15480
+ this.running = true;
15481
+ this.lastAttemptAt = now;
15482
+ this.create({ automatic: true }).then((result) => {
15483
+ if (!result.ok) logger.warn("the scheduled backup failed", result.error);
15484
+ }).catch((error) => {
15485
+ logger.error("the scheduled backup failed", error);
15486
+ }).finally(() => {
15487
+ this.running = false;
15488
+ });
14949
15489
  }
14950
15490
  resolveDir() {
14951
15491
  const configured = this.options.getConfig().dir;
@@ -16193,10 +16733,11 @@ var init_log_files = __esmMin((() => {
16193
16733
  }));
16194
16734
  //#endregion
16195
16735
  //#region src/services/notifications.ts
16196
- var REASON_LABEL, TITLE, NotificationService;
16736
+ var REASON_LABEL, TITLE, COVERS, NotificationService;
16197
16737
  var init_notifications = __esmMin((() => {
16198
16738
  init_logger();
16199
16739
  init_telegram();
16740
+ init_webhook();
16200
16741
  init_error_message();
16201
16742
  REASON_LABEL = {
16202
16743
  "crash": "gave up restarting",
@@ -16220,122 +16761,230 @@ var init_notifications = __esmMin((() => {
16220
16761
  "ddns": "🌐 DNS updated",
16221
16762
  "ddns-error": "🌐 DNS update failed"
16222
16763
  };
16764
+ COVERS = {
16765
+ "crash": (policy) => policy.onCrash,
16766
+ "rss": (policy) => policy.onCrash,
16767
+ "unhealthy": (policy) => policy.onUnhealthy,
16768
+ "forced-restart": (policy) => policy.onForcedRestart,
16769
+ "recovered": (policy) => policy.onRecovered,
16770
+ "host": (policy) => policy.onHost,
16771
+ "host-recovered": (policy) => policy.onHost,
16772
+ "ddns": (policy) => policy.onDdns,
16773
+ "ddns-error": (policy) => policy.onDdns
16774
+ };
16223
16775
  NotificationService = class {
16224
16776
  secrets;
16225
16777
  getConfig;
16226
16778
  cooldowns = /* @__PURE__ */ new Map();
16227
- lastResult = null;
16228
- lastResultAt = null;
16779
+ results = /* @__PURE__ */ new Map();
16229
16780
  constructor(secrets, getConfig) {
16230
16781
  this.secrets = secrets;
16231
16782
  this.getConfig = getConfig;
16232
16783
  }
16233
- get telegramTokenSet() {
16234
- return this.secrets.telegramTokenSet;
16784
+ /** The general block, as the page edits it. */
16785
+ defaults() {
16786
+ return { ...this.getConfig().defaults };
16235
16787
  }
16236
- status() {
16237
- const telegram = this.getConfig().telegram;
16238
- return {
16239
- enabled: telegram.enabled,
16240
- tokenSet: this.secrets.telegramTokenSet,
16241
- chatId: telegram.chatId,
16242
- onCrash: telegram.onCrash,
16243
- onUnhealthy: telegram.onUnhealthy,
16244
- onForcedRestart: telegram.onForcedRestart,
16245
- onRecovered: telegram.onRecovered,
16246
- onHost: telegram.onHost,
16247
- onDdns: telegram.onDdns,
16248
- cooldownMs: telegram.cooldownMs,
16249
- lastResult: this.lastResult,
16250
- lastResultAt: this.lastResultAt
16788
+ /**
16789
+ * Every destination as a row: its own fields, the policy it will actually use, and its last result.
16790
+ *
16791
+ * The page shows this rather than the raw config, so an inheriting destination displays the
16792
+ * inherited toggles — the values a send will use, not the stale ones on disk.
16793
+ */
16794
+ destinations() {
16795
+ return this.getConfig().destinations.map((target) => {
16796
+ const result = this.results.get(target.id) ?? {
16797
+ lastResult: null,
16798
+ lastResultAt: null
16799
+ };
16800
+ const common = {
16801
+ id: target.id,
16802
+ kind: target.kind,
16803
+ enabled: target.enabled,
16804
+ useOwnSettings: target.useOwnSettings,
16805
+ ...this.effectivePolicy(target),
16806
+ lastResult: result.lastResult,
16807
+ lastResultAt: result.lastResultAt
16808
+ };
16809
+ if (target.kind === "telegram") return {
16810
+ ...common,
16811
+ chatId: target.chatId,
16812
+ tokenSet: this.secrets.telegramTokenSet(target.id),
16813
+ url: null,
16814
+ method: null,
16815
+ format: null,
16816
+ headers: null
16817
+ };
16818
+ return {
16819
+ ...common,
16820
+ chatId: null,
16821
+ tokenSet: false,
16822
+ url: target.url,
16823
+ method: target.method,
16824
+ format: target.format,
16825
+ headers: target.headers
16826
+ };
16827
+ });
16828
+ }
16829
+ /** The policy a destination actually uses: its own, or the general block's. */
16830
+ effectivePolicy(target) {
16831
+ if (target.useOwnSettings) return {
16832
+ onCrash: target.onCrash,
16833
+ onUnhealthy: target.onUnhealthy,
16834
+ onForcedRestart: target.onForcedRestart,
16835
+ onRecovered: target.onRecovered,
16836
+ onHost: target.onHost,
16837
+ onDdns: target.onDdns,
16838
+ cooldownMs: target.cooldownMs
16251
16839
  };
16840
+ return { ...this.getConfig().defaults };
16841
+ }
16842
+ /**
16843
+ * The destinations that would deliver this event right now.
16844
+ *
16845
+ * Per destination rather than one boolean for the service: a single answer would either send a
16846
+ * host warning somewhere switched off for it, or silence a crash because another destination's
16847
+ * cooldown was still running.
16848
+ */
16849
+ targetsFor(event, now = Date.now()) {
16850
+ return this.getConfig().destinations.filter((target) => {
16851
+ if (!target.enabled) return false;
16852
+ const policy = this.effectivePolicy(target);
16853
+ if (!COVERS[event.reason](policy)) return false;
16854
+ const until = this.cooldowns.get(this.cooldownKey(target, event)) ?? 0;
16855
+ return !(policy.cooldownMs > 0 && until > now);
16856
+ });
16252
16857
  }
16253
- /** Enabled for this reason *and* outside its cooldown window. */
16858
+ /** Whether *any* destination would deliver this event. */
16254
16859
  shouldNotify(event, now = Date.now()) {
16255
- const telegram = this.getConfig().telegram;
16256
- if (!telegram.enabled) return false;
16257
- if (!{
16258
- "crash": telegram.onCrash,
16259
- "unhealthy": telegram.onUnhealthy,
16260
- "forced-restart": telegram.onForcedRestart,
16261
- "recovered": telegram.onRecovered,
16262
- "rss": telegram.onCrash,
16263
- "host": telegram.onHost,
16264
- "host-recovered": telegram.onHost,
16265
- "ddns": telegram.onDdns,
16266
- "ddns-error": telegram.onDdns
16267
- }[event.reason]) return false;
16268
- const until = this.cooldowns.get(`${event.serverId}:${event.reason}`) ?? 0;
16269
- return !(telegram.cooldownMs > 0 && until > now);
16270
- }
16271
- /** Starts the cooldown window for this event, so a flapping server stays quiet. */
16860
+ return this.targetsFor(event, now).length > 0;
16861
+ }
16862
+ /** Starts the cooldown window for every destination about to be asked to send. */
16272
16863
  markSent(event, now = Date.now()) {
16273
- this.cooldowns.set(`${event.serverId}:${event.reason}`, now + this.getConfig().telegram.cooldownMs);
16864
+ for (const target of this.targetsFor(event, now)) this.cooldowns.set(this.cooldownKey(target, event), now + this.effectivePolicy(target).cooldownMs);
16274
16865
  }
16275
- /** Fire-and-forget by design: supervision must never wait on a chat API. */
16866
+ /** Fire-and-forget by design: supervision must never wait on a chat or webhook API. */
16276
16867
  notify(event) {
16277
16868
  this.dispatch(event).catch((error) => {
16278
16869
  logger.warn(`notification failed: ${errorMessage(error)}`);
16279
16870
  });
16280
16871
  }
16281
16872
  async dispatch(event) {
16282
- if (!this.shouldNotify(event)) return false;
16873
+ const targets = this.targetsFor(event);
16874
+ if (targets.length === 0) return false;
16283
16875
  this.markSent(event);
16284
- return this.sendTelegram(formatTelegramMessage(TITLE[event.reason], [`${event.label} (${event.serverId}) ${REASON_LABEL[event.reason]}`, event.detail]));
16876
+ const title = TITLE[event.reason];
16877
+ const message = `${event.label} (${event.serverId}) ${REASON_LABEL[event.reason]}\n${event.detail}`;
16878
+ return (await Promise.all(targets.map((target) => this.deliver(target, title, message, event)))).includes(true);
16879
+ }
16880
+ /** One destination, one event. A throw is recorded against it and nothing else. */
16881
+ async deliver(target, title, message, event) {
16882
+ try {
16883
+ const result = target.kind === "telegram" ? await this.sendTelegram(target, title, message) : await sendWebhook(target, {
16884
+ title,
16885
+ message,
16886
+ reason: event.reason,
16887
+ serverId: event.serverId,
16888
+ label: event.label
16889
+ });
16890
+ this.remember(target.id, result.ok ? "sent" : result.error ?? "send failed");
16891
+ return result.ok;
16892
+ } catch (error) {
16893
+ this.remember(target.id, errorMessage(error));
16894
+ return false;
16895
+ }
16896
+ }
16897
+ /** A probe for one destination. */
16898
+ async sendTest(id, overrides = {}) {
16899
+ const target = this.getConfig().destinations.find((entry) => entry.id === id);
16900
+ if (target === void 0) return {
16901
+ ok: false,
16902
+ error: "no such destination"
16903
+ };
16904
+ const result = target.kind === "telegram" ? await this.testTelegram(id, target.chatId, overrides.chatId, overrides.botToken) : await this.testWebhook(target, id);
16905
+ this.remember(id, result.ok ? "test message sent" : result.error ?? "test failed");
16906
+ return result;
16285
16907
  }
16286
- /** Used by the "send test" button in settings. */
16287
- async sendTest(overrides = {}) {
16288
- const chatId = overrides.chatId ?? this.getConfig().telegram.chatId;
16289
- if (chatId.length === 0) return {
16908
+ /**
16909
+ * A Telegram destination's own token, with the chat id and the token both overridable.
16910
+ *
16911
+ * The override is what lets a token be tried before it is saved — the route advertises it and
16912
+ * `detect-chats` honours it, so ignoring it here made "send a test" fail on a token the page was
16913
+ * still holding.
16914
+ */
16915
+ async testTelegram(id, chatId, overrideChatId, overrideToken) {
16916
+ const chat = (overrideChatId ?? chatId).trim();
16917
+ if (chat.length === 0) return {
16290
16918
  ok: false,
16291
16919
  error: "no chat id configured"
16292
16920
  };
16293
- const token = this.resolveToken(overrides.botToken);
16921
+ const token = overrideToken !== void 0 && overrideToken.length > 0 ? overrideToken : this.secrets.telegramToken(id);
16294
16922
  if (token === null) return {
16295
16923
  ok: false,
16296
- error: "no bot token configured"
16924
+ error: "no bot token configured for this destination"
16925
+ };
16926
+ return sendTelegramMessage(token, chat, formatTelegramMessage("✅ home-hosted test", ["notifications are wired up correctly"]));
16927
+ }
16928
+ /**
16929
+ * A webhook probe, for a saved destination or for a draft the page has not saved.
16930
+ *
16931
+ * A draft is passed whole, so a URL and its headers can be tried before they are stored — and so
16932
+ * a destination's own "test" tests *that* destination, not whichever one comes first.
16933
+ */
16934
+ async testWebhook(target, id) {
16935
+ const problem = targetProblem(target, { requireUrl: true });
16936
+ if (problem !== null) return {
16937
+ ok: false,
16938
+ error: problem
16297
16939
  };
16298
- const result = await sendTelegramMessage(token, chatId, formatTelegramMessage("✅ home-hosted test", ["notifications are wired up correctly"]));
16299
- this.remember(result.ok ? "test message sent" : result.error ?? "test failed");
16940
+ const result = await sendWebhook(target, {
16941
+ title: "home-hosted test",
16942
+ message: "notifications are wired up correctly",
16943
+ reason: "test",
16944
+ serverId: "",
16945
+ label: ""
16946
+ });
16947
+ if (id !== void 0) this.remember(id, result.ok ? "test message sent" : result.error ?? "test failed");
16300
16948
  return result;
16301
16949
  }
16302
- async detectChats(overrides = {}) {
16303
- const token = this.resolveToken(overrides.botToken);
16304
- if (token === null) return {
16950
+ /** Lists the chats a destination's bot can see, so its chat id can be picked. */
16951
+ async detectChats(id, overrides = {}) {
16952
+ const token = (overrides.botToken ?? this.secrets.telegramToken(id) ?? "").trim();
16953
+ if (token.length === 0) return {
16305
16954
  ok: false,
16306
16955
  chats: [],
16307
- error: "no bot token configured"
16956
+ error: "no bot token configured for this destination"
16308
16957
  };
16309
16958
  const result = await listTelegramChats(token);
16310
- this.remember(result.ok ? `${result.chats.length} chat(s) found` : result.error ?? "detect failed");
16959
+ this.remember(id, result.ok ? `${result.chats.length} chat(s) found` : result.error ?? "detect failed");
16311
16960
  return result;
16312
16961
  }
16313
- /** Verifies a token without sending anything. */
16962
+ /** Verifies a token without storing or sending anything. */
16314
16963
  async verifyToken(token) {
16315
16964
  return verifyTelegramToken(token);
16316
16965
  }
16317
- resolveToken(tokenOverride) {
16318
- const token = tokenOverride?.trim() ?? this.secrets.telegramToken ?? "";
16319
- return token.length > 0 ? token : null;
16320
- }
16321
- async sendTelegram(html) {
16322
- const telegram = this.getConfig().telegram;
16323
- if (telegram.chatId.length === 0) {
16324
- this.remember("no chat id configured");
16325
- return false;
16326
- }
16327
- const token = this.resolveToken();
16328
- if (token === null) {
16329
- this.remember("no bot token configured");
16330
- return false;
16331
- }
16332
- const result = await sendTelegramMessage(token, telegram.chatId, html);
16333
- this.remember(result.ok ? "sent" : result.error ?? "send failed");
16334
- return result.ok;
16966
+ cooldownKey(target, event) {
16967
+ return `${target.id}:${event.serverId}:${event.reason}`;
16335
16968
  }
16336
- remember(message) {
16337
- this.lastResult = message;
16338
- this.lastResultAt = Date.now();
16969
+ async sendTelegram(target, title, message) {
16970
+ if (target.chatId.length === 0) return {
16971
+ ok: false,
16972
+ error: "no chat id configured"
16973
+ };
16974
+ const token = this.secrets.telegramToken(target.id);
16975
+ if (token === null) return {
16976
+ ok: false,
16977
+ error: "no bot token configured for this destination"
16978
+ };
16979
+ const body = message.split("\n").filter((line) => line.length > 0);
16980
+ return sendTelegramMessage(token, target.chatId, formatTelegramMessage(title, body));
16981
+ }
16982
+ /** Records one destination's outcome, keyed by its id. */
16983
+ remember(id, message) {
16984
+ this.results.set(id, {
16985
+ lastResult: message,
16986
+ lastResultAt: Date.now()
16987
+ });
16339
16988
  }
16340
16989
  };
16341
16990
  }));
@@ -16374,8 +17023,27 @@ function stateSignature(state) {
16374
17023
  workspace.ddns.ipv6,
16375
17024
  ...workspace.ddns.records.map((record) => `${record.host}:${record.type}:${record.state}:${record.ip}`)
16376
17025
  ].join(":"),
16377
- workspace.notifications.telegram.enabled,
16378
- workspace.notifications.telegram.tokenSet,
17026
+ ...(workspace.notifications.destinations ?? []).map((destination) => [
17027
+ destination.id,
17028
+ destination.kind,
17029
+ destination.enabled,
17030
+ destination.useOwnSettings,
17031
+ destination.chatId ?? "",
17032
+ destination.tokenSet,
17033
+ destination.url ?? "",
17034
+ destination.method ?? "",
17035
+ destination.format ?? "",
17036
+ destination.headers ?? "",
17037
+ destination.onCrash,
17038
+ destination.onUnhealthy,
17039
+ destination.onForcedRestart,
17040
+ destination.onRecovered,
17041
+ destination.onHost,
17042
+ destination.onDdns ?? "",
17043
+ destination.cooldownMs,
17044
+ destination.lastResult ?? "",
17045
+ destination.lastResultAt ?? ""
17046
+ ].join(":")),
16379
17047
  ...workspace.servers.map((server) => [
16380
17048
  server.id,
16381
17049
  server.status,
@@ -16606,6 +17274,7 @@ var init_panel = __esmMin((() => {
16606
17274
  async dispose() {
16607
17275
  this.disposed = true;
16608
17276
  clearInterval(this.timer);
17277
+ this.options.backups.dispose();
16609
17278
  await Promise.all(this.workspaces().map((runtime) => runtime.supervisor.dispose()));
16610
17279
  for (const runtime of this.workspaces()) this.disposeRuntime(runtime);
16611
17280
  }
@@ -16719,6 +17388,7 @@ var init_panel = __esmMin((() => {
16719
17388
  if (this.disposed) return;
16720
17389
  const now = Date.now();
16721
17390
  await this.options.hostMonitor.tick(now);
17391
+ this.options.backups.tick(now);
16722
17392
  for (const runtime of this.workspaces()) runtime.ddns.tick(now);
16723
17393
  const proxy = this.options.proxy();
16724
17394
  if (proxy !== null) await proxy.sync().catch((error) => {
@@ -18561,7 +19231,10 @@ function targets(configOverride) {
18561
19231
  validate: (raw) => {
18562
19232
  let defaults = {};
18563
19233
  try {
18564
- defaults = parseWorkspaceSettings(JSON.parse(fs.readFileSync(workspaceSettingsPath(workspace.id), "utf8"))).config?.defaults ?? {};
19234
+ const settingsRaw = JSON.parse(fs.readFileSync(workspaceSettingsPath(workspace.id), "utf8"));
19235
+ const meta = typeof settingsRaw.meta === "object" && settingsRaw.meta !== null ? settingsRaw.meta : {};
19236
+ const from = typeof meta.schema === "number" ? meta.schema : 1;
19237
+ defaults = (planConfigMigrations(from).steps.length > 0 ? applyConfigMigrations(settingsRaw, from).config : settingsRaw)?.defaults ?? {};
18565
19238
  } catch {}
18566
19239
  return parseServersFile(raw, defaults).errors[0] ?? null;
18567
19240
  }
@@ -18585,7 +19258,18 @@ async function runMigrate(config, dryRun, yes) {
18585
19258
  const from = typeof meta.schema === "number" ? meta.schema : 1;
18586
19259
  const plan = planConfigMigrations(from);
18587
19260
  if (plan.tooNew) fail(`${target.file} was written by home-hosted ${meta.writtenBy ?? "a newer release"} (config schema ${from});\n this release understands schema ${plan.to}. Install that version, or edit the file yourself.`);
18588
- const problem = target.validate(raw);
19261
+ /**
19262
+ * Validate what this release will actually read: the file as-is when it needs no migration,
19263
+ * otherwise the result the steps produce.
19264
+ *
19265
+ * The parsed check cannot be run on the raw file when a migration is pending — the reader
19266
+ * refuses an older schema by design (`readStamp`), which would make `migrate` refuse every
19267
+ * config it exists to lift. `checkShape` below catches a file that is not even JSON-shaped
19268
+ * before the steps touch it.
19269
+ */
19270
+ const migrated = plan.steps.length === 0 ? raw : applyConfigMigrations(raw, from).config;
19271
+ if (plan.steps.length > 0 && !isRecord(migrated)) fail(`${target.file} did not produce an object when migrated — refusing to write it`);
19272
+ const problem = target.validate(migrated);
18589
19273
  if (problem !== null) fail(`${target.file} is not a config this release can read: ${problem}`);
18590
19274
  if (plan.reached !== plan.to) fail(`${target.file} is schema ${from} and this release can only lift it to schema ${plan.reached} — the migration chain in configMigrations has a gap to schema ${plan.to}.
18591
19275
  That is a bug in this release: report it rather than editing the file.`);
@@ -18606,7 +19290,6 @@ async function runMigrate(config, dryRun, yes) {
18606
19290
  return;
18607
19291
  }
18608
19292
  }
18609
- const { config: migrated } = applyConfigMigrations(raw, from);
18610
19293
  const migratedProblem = target.validate(migrated);
18611
19294
  if (migratedProblem !== null) fail(`the migration produced a config this release cannot read:\n ${migratedProblem}`);
18612
19295
  fs.copyFileSync(target.file, `${target.file}.bak`);
@@ -18631,6 +19314,7 @@ var init_migrate = __esmMin((() => {
18631
19314
  init_paths();
18632
19315
  init_version();
18633
19316
  init_error_message();
19317
+ init_shape();
18634
19318
  migrateArgs = {
18635
19319
  config: {
18636
19320
  type: "string",