settings.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. import json
  2. import re
  3. from pydantic import BaseModel, Field, ValidationInfo, field_validator
  4. from backend.app.schemas.print_queue import TriState
  5. from backend.app.utils.printer_models import MAX_CHAMBER_TEMP_C
  6. # Outbound service URLs validated on save, so a bad value is rejected at
  7. # configuration time with a clear message rather than failing opaquely at
  8. # request time. Every one of these services is commonly self-hosted on the same
  9. # host or LAN as Bambuddy, so the LAN-service policy applies: loopback and
  10. # RFC-1918 stay permitted, while cloud-metadata endpoints, numeric-encoded IPs,
  11. # IPv4-mapped IPv6 and non-HTTP schemes are rejected. See
  12. # ``_url_safety.assert_safe_lan_service_url``.
  13. #
  14. # Module-level rather than a class attribute so the CI backstop in
  15. # tests/unit/test_outbound_url_ssrf_guards.py can import the real list and
  16. # cannot drift from it. Any new outbound-URL setting belongs here (or, if it
  17. # must be reachable on the public internet, on the stricter OIDC guard).
  18. LAN_SERVICE_URL_SETTINGS = ("ha_url", "obico_ml_url", "orcaslicer_api_url", "bambu_studio_api_url")
  19. # ``docker_compose_dir`` is unusual among the string settings: it is not
  20. # consumed by Bambuddy at all, it is interpolated into a shell command that
  21. # the Settings page invites the user to copy and paste into a root-capable
  22. # terminal (#2664). A value like ``/opt/bambuddy; rm -rf /`` would render as a
  23. # perfectly plausible-looking update command, so anyone with settings:update
  24. # could hand every admin a destructive one-liner to run. Restricting the field
  25. # to characters that occur in real paths removes that entirely; the frontend
  26. # double-quotes the value when it contains a space, which is safe precisely
  27. # because quotes, ``$`` and backticks cannot survive this pattern.
  28. _COMPOSE_DIR_ALLOWED = re.compile(r"^[\w \-./\\:~]+$", re.UNICODE)
  29. _COMPOSE_DIR_MAX_LEN = 512
  30. class AppSettings(BaseModel):
  31. """Application settings schema."""
  32. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  33. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  34. capture_finish_photo: bool = Field(
  35. default=True,
  36. description=(
  37. "Capture photo from printer camera when print completes. Bambuddy records a "
  38. "brief timelapse during the print so the photo can be sourced from the moment "
  39. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  40. "this print, otherwise it is deleted automatically after the photo is captured."
  41. ),
  42. )
  43. finish_photo_restore_plate: bool = Field(
  44. default=True,
  45. description=(
  46. "Raise the build plate back into camera framing before taking the finish photo. "
  47. "Bambu's end G-code drops the plate ~100mm as the last thing it does, leaving the "
  48. "finished print far below the camera's natural framing. Bambuddy moves it back to "
  49. "just above the last printed layer, takes the photo, then lowers it again. Skipped "
  50. "when the print height is unknown or another job is queued for the printer."
  51. ),
  52. )
  53. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  54. currency: str = Field(default="USD", description="Currency for cost tracking")
  55. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  56. energy_tracking_mode: str = Field(
  57. default="total",
  58. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  59. )
  60. # Spoolman integration
  61. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  62. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  63. spoolman_sync_mode: str = Field(
  64. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  65. )
  66. spoolman_disable_weight_sync: bool = Field(
  67. default=False,
  68. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  69. )
  70. spoolman_report_partial_usage: bool = Field(
  71. default=True,
  72. description="Report Partial Usage for Failed Prints. When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress.",
  73. )
  74. auto_add_unknown_rfid: bool = Field(
  75. default=True,
  76. description="Automatically add spools with unknown RFID tags to inventory. Disable if you pre-create inventory entries manually to avoid duplicates.",
  77. )
  78. disable_filament_warnings: bool = Field(
  79. default=False,
  80. description="Disable insufficient filament warnings when printing or queueing prints",
  81. )
  82. prefer_lowest_filament: bool = Field(
  83. default=False,
  84. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  85. )
  86. # Updates
  87. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  88. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  89. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  90. # Language
  91. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  92. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  93. # Bed cooled notification threshold
  94. bed_cooled_threshold: float = Field(
  95. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  96. )
  97. # AMS threshold settings for humidity and temperature coloring
  98. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  99. ams_humidity_fair: int = Field(
  100. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  101. )
  102. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  103. ams_temp_fair: float = Field(
  104. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  105. )
  106. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  107. printer_sensor_history_retention_days: int = Field(
  108. default=30, description="Number of days to keep printer heater history data (nozzle / bed / chamber)"
  109. )
  110. # Queue auto-drying settings
  111. queue_drying_enabled: bool = Field(
  112. default=False, description="Automatically dry AMS filament between queued prints"
  113. )
  114. queue_drying_block: bool = Field(
  115. default=False,
  116. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  117. )
  118. ambient_drying_enabled: bool = Field(
  119. default=False,
  120. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  121. )
  122. print_drying_enabled: bool = Field(
  123. default=False,
  124. description=(
  125. "Allow auto-drying to also fire on a printer that is currently printing, "
  126. "when its model+firmware supports concurrent drying (H2D 01.03.00.00+, "
  127. "H2C/H2S/P2S/H2D Pro 01.02.00.00+, X2D/A2L 01.01.00.00+, X1C 01.11.02.00+). "
  128. "Drying temperature is automatically capped 5 degC below the idle preset "
  129. "(floor 40 degC) to protect spools during print."
  130. ),
  131. )
  132. drying_presets: str = Field(
  133. default="",
  134. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  135. )
  136. ams_humidity_thresholds: str = Field(
  137. default="",
  138. description=(
  139. "JSON blob of per-filament-type humidity trigger thresholds for auto-drying and alarms. "
  140. 'Shape: {"default": int, "PLA": int, "ASA": int, ...}. '
  141. "Empty = fall back to ams_humidity_fair for all types."
  142. ),
  143. )
  144. # Auto-print G-code injection (#422)
  145. gcode_snippets: str = Field(
  146. default="",
  147. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  148. )
  149. # Scheduled local backup (#884)
  150. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  151. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  152. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  153. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  154. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  155. # Print modal settings
  156. per_printer_mapping_expanded: bool = Field(
  157. default=False, description="Expand custom filament mapping by default in print modal"
  158. )
  159. # Date/time display format
  160. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  161. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  162. # Default printer for operations
  163. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  164. # Slicer Pipelines (#1425 PR C). Cap on the ``copies`` field in the
  165. # Run-with-pipeline modal — keeps a misclick from queueing 5000 prints.
  166. pipeline_max_copies: int = Field(
  167. default=50,
  168. ge=1,
  169. le=1000,
  170. description="Upper bound on the copies an operator can request when running a Slicer Pipeline. Larger fleets / production rigs can raise this; the hard ceiling at 1000 is a sanity guard against fat-fingered input.",
  171. )
  172. # Virtual Printer
  173. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  174. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  175. virtual_printer_mode: str = Field(
  176. default="archive",
  177. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  178. )
  179. virtual_printer_archive_name_source: str = Field(
  180. default="metadata",
  181. description="Source for the archive's display name on virtual-printer uploads: 'metadata' uses the 3MF's embedded print_name (default, matches Bambu's behavior), 'filename' uses the filename Bambu Studio sent over FTP (lets users rename via the slicer's 'send to printer' dialog).",
  182. )
  183. # Dark mode theme settings
  184. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  185. dark_background: str = Field(
  186. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  187. )
  188. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  189. # Light mode theme settings
  190. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  191. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  192. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  193. # FTP retry settings for unreliable WiFi connections
  194. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  195. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  196. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  197. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  198. # MQTT Relay settings for publishing events to external broker
  199. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  200. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  201. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  202. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  203. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  204. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  205. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  206. # External URL for notifications
  207. external_url: str = Field(
  208. default="", description="External URL where Bambuddy is accessible (for notification images)"
  209. )
  210. # Directory holding the user's docker-compose.yml, shown in the update
  211. # instructions so the printed command can be pasted from anywhere (#2664).
  212. # Empty means "omit the cd" — which is also the correct rendering when
  213. # nothing could be detected, rather than guessing a path that fails.
  214. docker_compose_dir: str = Field(
  215. default="", description="Host directory containing docker-compose.yml, used in the update instructions"
  216. )
  217. # Home Assistant integration for smart plug control
  218. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  219. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  220. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  221. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  222. ha_token_from_env: bool = Field(
  223. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  224. )
  225. ha_env_managed: bool = Field(
  226. default=False, description="Whether HA integration is fully managed by environment variables"
  227. )
  228. # File Manager / Library settings
  229. library_archive_mode: str = Field(
  230. default="ask",
  231. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  232. )
  233. library_disk_warning_gb: float = Field(
  234. default=5.0,
  235. description="Show warning when free disk space falls below this threshold (GB)",
  236. )
  237. # Camera view settings
  238. camera_view_mode: str = Field(
  239. default="window",
  240. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  241. )
  242. # Preferred slicer application (server-side / API sidecar slicer)
  243. preferred_slicer: str = Field(
  244. default="bambu_studio",
  245. description="Slicer used for the server-side API / sidecar: 'bambu_studio' or 'orcaslicer'",
  246. )
  247. # "Open in Slicer" desktop URI handler — independent of the API slicer so
  248. # a user can slice via the Bambu Studio sidecar but open files locally in
  249. # OrcaSlicer, or vice versa (#1329). None falls back to ``preferred_slicer``
  250. # so existing installs behave identically until someone changes it.
  251. open_in_slicer: str | None = Field(
  252. default=None,
  253. description=(
  254. "Desktop slicer for the 'Open in Slicer' button: 'bambu_studio' or "
  255. "'orcaslicer'. None inherits from preferred_slicer."
  256. ),
  257. )
  258. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  259. # SliceModal and call the slicer-API sidecar. When False (default), they
  260. # hand off to the user's local desktop slicer via URI scheme — preserving
  261. # the original Bambuddy behavior for users who don't run a sidecar.
  262. use_slicer_api: bool = Field(
  263. default=False,
  264. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  265. )
  266. # Slicer-API sidecar base URLs. Per-installation, configured via the
  267. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  268. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  269. # default to the docker-compose ports in core/config.py.
  270. orcaslicer_api_url: str = Field(
  271. default="",
  272. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  273. )
  274. bambu_studio_api_url: str = Field(
  275. default="",
  276. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  277. )
  278. # How long to keep waiting on a slice that isn't finishing. Measured against
  279. # the sidecar's progress channel, not total elapsed time — a heavy model can
  280. # legitimately slice for half an hour, and a wall-clock ceiling cannot tell
  281. # that apart from a stalled one (#2730). Sidecars too old to report progress
  282. # fall back to using this as a total-elapsed ceiling, which is the pre-#2730
  283. # behaviour with a configurable number.
  284. slicer_stall_timeout_minutes: int = Field(
  285. default=15,
  286. ge=1,
  287. le=240,
  288. description=(
  289. "Give up on a slice after this many minutes with no progress from the sidecar. "
  290. "On sidecars that do not report progress, applies to total slicing time instead."
  291. ),
  292. )
  293. # Prometheus metrics endpoint
  294. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  295. prometheus_token: str = Field(
  296. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  297. )
  298. # Inventory low stock threshold
  299. low_stock_threshold: float = Field(
  300. default=20.0,
  301. ge=0.1,
  302. le=99.9,
  303. description="Low stock threshold percentage (%) for inventory filtering and display",
  304. )
  305. # Session policy (#1706) — admin-set ceiling for user session lifetime.
  306. # Default 24h preserves the M-2 audit reduction from 7 days. Max 720h
  307. # (30 days) bounds blast radius if an admin chooses a long session.
  308. session_max_hours: int = Field(
  309. default=24,
  310. ge=1,
  311. le=720,
  312. description=(
  313. "Maximum session lifetime in hours for user logins (default 24, max 720). "
  314. "Applies to new logins only; already-issued tokens keep their original expiry. "
  315. "Longer sessions reduce automatic logout protection."
  316. ),
  317. )
  318. # User email notifications (requires Advanced Authentication)
  319. user_notifications_enabled: bool = Field(
  320. default=True,
  321. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  322. )
  323. # Default print options. bed_levelling / flow_cali / nozzle_offset_cali are
  324. # tri-state (off/on/auto), defaulting to "auto" per BambuStudio.
  325. default_bed_levelling: TriState = Field(default="auto", description="Default bed levelling option for new prints")
  326. default_flow_cali: TriState = Field(default="auto", description="Default flow calibration option for new prints")
  327. default_vibration_cali: bool = Field(
  328. default=True, description="Default vibration calibration option for new prints"
  329. )
  330. default_layer_inspect: bool = Field(
  331. default=False, description="Default first layer inspection option for new prints"
  332. )
  333. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  334. default_nozzle_offset_cali: TriState = Field(
  335. default="auto",
  336. description="Default nozzle offset calibration option for new prints (dual-nozzle printers only)",
  337. )
  338. # Staggered batch start for multi-printer jobs
  339. stagger_group_size: int = Field(
  340. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  341. )
  342. stagger_interval_minutes: int = Field(
  343. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  344. )
  345. # Finance budget window settings
  346. billing_enabled: bool = Field(
  347. default=False,
  348. description="Enable cost-center billing enforcement for print and queue operations",
  349. )
  350. printer_kill_switch_enabled: bool = Field(
  351. default=False,
  352. description="Immediately stop printer jobs that start without Bambuddy authorization",
  353. )
  354. finance_budget_reset_day: int = Field(
  355. default=1,
  356. ge=1,
  357. le=31,
  358. description="Day of month when monthly finance budget window resets (1-31, clamped for short months)",
  359. )
  360. finance_budget_reset_timezone: str = Field(
  361. default="UTC",
  362. description="IANA timezone for finance monthly budget reset calculation (e.g., Europe/Berlin)",
  363. )
  364. # Plate-clear confirmation for queue scheduling
  365. require_plate_clear: bool = Field(
  366. default=False,
  367. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  368. )
  369. queue_shortest_first: bool = Field(
  370. default=False,
  371. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  372. )
  373. queue_max_concurrent_uploads: int = Field(
  374. default=4,
  375. ge=1,
  376. le=16,
  377. description=(
  378. "How many printers the queue may upload to at the same time. Printers are independent "
  379. "machines, so raising this starts a multi-printer batch proportionally sooner; each "
  380. "concurrent upload costs one connection and one thread on the Bambuddy host."
  381. ),
  382. )
  383. # Preheat / heat-soak before queued prints (#1468). The scheduler stage runs
  384. # BEFORE FTP upload. Three hardware tiers behave differently:
  385. # - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E): M141 → wait for chamber
  386. # sensor to reach target → soak
  387. # - Chamber sensor only (X1C/P2S): M140 only → wait for radiant chamber
  388. # warm-up to reach target OR max-wait timeout → soak
  389. # - No chamber sensor (P1S/P1P/A1/A1 Mini): M140 only → fixed soak timer
  390. # (no way to verify chamber temp; relies entirely on max_wait + soak)
  391. # Chamber target derives per-print from the loaded AMS filament types via
  392. # preheat_filament_targets (max across loaded slots). A target of 0 skips
  393. # the chamber phase but keeps the bed phase + soak. Per-queue-item
  394. # `preheat_chamber_target_override` (nullable) bypasses the derivation.
  395. preheat_enabled: bool = Field(
  396. default=False,
  397. description="Master toggle / default for new queue items. Per-item preheat_override can flip the decision per print.",
  398. )
  399. preheat_filament_targets: str = Field(
  400. default="",
  401. description=(
  402. "JSON map of normalized filament type → chamber target °C. Empty = bundled defaults "
  403. "(PLA/PETG/TPU/PVA: 0, PETG-CF: 40, ABS/ASA: 45, PA/PC/PC-FR: 50, PA-CF: 55, default: 0). "
  404. "Scheduler picks max across loaded AMS slots; 0 disables chamber phase for that print."
  405. ),
  406. )
  407. preheat_max_wait_seconds: int = Field(
  408. default=900,
  409. ge=60,
  410. le=3600,
  411. description="Maximum time to wait for the chamber to reach the target before falling through to the soak phase (radiant heating on X1C/P2S can take 15-30 min).",
  412. )
  413. preheat_soak_seconds: int = Field(
  414. default=300,
  415. ge=0,
  416. le=1800,
  417. description="Additional hold time at temperature after the chamber reaches the target (or after max_wait_seconds elapses). 0 = no soak.",
  418. )
  419. # User-configurable presets for the printer-card temperature / fan-speed
  420. # popovers. Each is a JSON array of exactly 3 ints (the "Off" button is
  421. # rendered separately and is not configurable). Empty string = use built-in
  422. # defaults. Validators on AppSettingsUpdate enforce the shape on writes.
  423. nozzle_temp_presets: str = Field(
  424. default="",
  425. description="JSON array of 3 nozzle-temperature preset values in C (0-320). Empty = use defaults [120, 220, 260]",
  426. )
  427. bed_temp_presets: str = Field(
  428. default="",
  429. description="JSON array of 3 bed-temperature preset values in C (0-140). Empty = use defaults [55, 75, 90]",
  430. )
  431. chamber_temp_presets: str = Field(
  432. default="",
  433. description="JSON array of 3 chamber-temperature preset values in C (0-65). Empty = use defaults [35, 45, 60]",
  434. )
  435. fan_speed_presets: str = Field(
  436. default="",
  437. description="JSON array of 3 fan-speed preset values in % (0-100). Empty = use defaults [50, 75, 100]",
  438. )
  439. # Local login (#1589) — when False, /auth/login rejects username+password
  440. # credentials with HTTP 403 and the login page hides the credentials form,
  441. # leaving only the OIDC SSO provider buttons. LDAP is governed by its own
  442. # `ldap_enabled` toggle and is not affected. The env-var
  443. # ``BAMBUDDY_LOCAL_LOGIN=true`` bypasses this gate at the route level so a
  444. # server admin can recover an install whose SSO provider is unreachable
  445. # without editing the DB.
  446. local_login_enabled: bool = Field(
  447. default=True,
  448. description=(
  449. "Allow username + password login on /auth/login. Disable when only SSO should be usable. "
  450. "BAMBUDDY_LOCAL_LOGIN=true on the server overrides this to keep a recovery path open."
  451. ),
  452. )
  453. # LDAP authentication (#794)
  454. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  455. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  456. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  457. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  458. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  459. ldap_user_filter: str = Field(
  460. default="(sAMAccountName={username})",
  461. description="LDAP user search filter. {username} is replaced with the login username",
  462. )
  463. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  464. ldap_group_mapping: str = Field(
  465. default="",
  466. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  467. )
  468. ldap_auto_provision: bool = Field(
  469. default=False,
  470. description="Auto-create BamBuddy user on first successful LDAP login",
  471. )
  472. ldap_default_group: str = Field(
  473. default="",
  474. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  475. )
  476. # Obico AI failure detection (#172)
  477. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  478. obico_ml_url: str = Field(
  479. default="",
  480. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  481. )
  482. obico_ml_token: str = Field(
  483. default="",
  484. description=(
  485. "Bearer token for the Obico ML API, matching the server's ML_API_TOKEN "
  486. "environment variable. Empty when the server runs without one."
  487. ),
  488. )
  489. obico_sensitivity: str = Field(
  490. default="medium",
  491. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  492. )
  493. obico_action: str = Field(
  494. default="notify",
  495. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  496. )
  497. obico_poll_interval: int = Field(
  498. default=10,
  499. ge=5,
  500. le=120,
  501. description="Seconds between detection checks while a print is running",
  502. )
  503. obico_enabled_printers: str = Field(
  504. default="",
  505. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  506. )
  507. # Inventory forecasting
  508. forecast_global_lead_time_days: int = Field(
  509. default=0,
  510. ge=0,
  511. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  512. )
  513. # Default sidebar order (admin-set for all users)
  514. default_sidebar_order: str = Field(
  515. default="",
  516. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  517. )
  518. class AppSettingsUpdate(BaseModel):
  519. """Schema for updating settings (all fields optional)."""
  520. auto_archive: bool | None = None
  521. save_thumbnails: bool | None = None
  522. capture_finish_photo: bool | None = None
  523. finish_photo_restore_plate: bool | None = None
  524. default_filament_cost: float | None = None
  525. currency: str | None = None
  526. energy_cost_per_kwh: float | None = None
  527. energy_tracking_mode: str | None = None
  528. spoolman_enabled: bool | None = None
  529. spoolman_url: str | None = None
  530. spoolman_sync_mode: str | None = None
  531. spoolman_disable_weight_sync: bool | None = None
  532. spoolman_report_partial_usage: bool | None = None
  533. auto_add_unknown_rfid: bool | None = None
  534. disable_filament_warnings: bool | None = None
  535. prefer_lowest_filament: bool | None = None
  536. check_updates: bool | None = None
  537. check_printer_firmware: bool | None = None
  538. include_beta_updates: bool | None = None
  539. local_login_enabled: bool | None = None
  540. language: str | None = None
  541. notification_language: str | None = None
  542. bed_cooled_threshold: float | None = None
  543. ams_humidity_good: int | None = None
  544. ams_humidity_fair: int | None = None
  545. ams_temp_good: float | None = None
  546. ams_temp_fair: float | None = None
  547. ams_history_retention_days: int | None = None
  548. printer_sensor_history_retention_days: int | None = None
  549. queue_drying_enabled: bool | None = None
  550. queue_drying_block: bool | None = None
  551. ambient_drying_enabled: bool | None = None
  552. print_drying_enabled: bool | None = None
  553. drying_presets: str | None = None
  554. ams_humidity_thresholds: str | None = None
  555. per_printer_mapping_expanded: bool | None = None
  556. date_format: str | None = None
  557. time_format: str | None = None
  558. default_printer_id: int | None = None
  559. pipeline_max_copies: int | None = None
  560. virtual_printer_enabled: bool | None = None
  561. virtual_printer_access_code: str | None = None
  562. virtual_printer_mode: str | None = None
  563. virtual_printer_archive_name_source: str | None = None
  564. dark_style: str | None = None
  565. dark_background: str | None = None
  566. dark_accent: str | None = None
  567. light_style: str | None = None
  568. light_background: str | None = None
  569. light_accent: str | None = None
  570. ftp_retry_enabled: bool | None = None
  571. ftp_retry_count: int | None = None
  572. ftp_retry_delay: int | None = None
  573. ftp_timeout: int | None = None
  574. mqtt_enabled: bool | None = None
  575. mqtt_broker: str | None = None
  576. mqtt_port: int | None = None
  577. mqtt_username: str | None = None
  578. mqtt_password: str | None = None
  579. mqtt_topic_prefix: str | None = None
  580. mqtt_use_tls: bool | None = None
  581. external_url: str | None = None
  582. docker_compose_dir: str | None = None
  583. ha_enabled: bool | None = None
  584. ha_url: str | None = None
  585. ha_token: str | None = None
  586. library_archive_mode: str | None = None
  587. library_disk_warning_gb: float | None = None
  588. camera_view_mode: str | None = None
  589. preferred_slicer: str | None = None
  590. open_in_slicer: str | None = None
  591. use_slicer_api: bool | None = None
  592. orcaslicer_api_url: str | None = None
  593. bambu_studio_api_url: str | None = None
  594. slicer_stall_timeout_minutes: int | None = Field(default=None, ge=1, le=240)
  595. prometheus_enabled: bool | None = None
  596. prometheus_token: str | None = None
  597. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  598. session_max_hours: int | None = Field(default=None, ge=1, le=720)
  599. user_notifications_enabled: bool | None = None
  600. default_bed_levelling: TriState | None = None
  601. default_flow_cali: TriState | None = None
  602. default_vibration_cali: bool | None = None
  603. default_layer_inspect: bool | None = None
  604. default_timelapse: bool | None = None
  605. default_nozzle_offset_cali: TriState | None = None
  606. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  607. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  608. billing_enabled: bool | None = None
  609. printer_kill_switch_enabled: bool | None = None
  610. finance_budget_reset_day: int | None = Field(default=None, ge=1, le=31)
  611. finance_budget_reset_timezone: str | None = None
  612. require_plate_clear: bool | None = None
  613. queue_shortest_first: bool | None = None
  614. queue_max_concurrent_uploads: int | None = Field(default=None, ge=1, le=16)
  615. preheat_enabled: bool | None = None
  616. preheat_filament_targets: str | None = None
  617. preheat_max_wait_seconds: int | None = Field(default=None, ge=60, le=3600)
  618. preheat_soak_seconds: int | None = Field(default=None, ge=0, le=1800)
  619. nozzle_temp_presets: str | None = None
  620. bed_temp_presets: str | None = None
  621. chamber_temp_presets: str | None = None
  622. fan_speed_presets: str | None = None
  623. gcode_snippets: str | None = None
  624. local_backup_enabled: bool | None = None
  625. local_backup_schedule: str | None = None
  626. local_backup_time: str | None = None
  627. local_backup_retention: int | None = None
  628. local_backup_path: str | None = None
  629. ldap_enabled: bool | None = None
  630. ldap_server_url: str | None = None
  631. ldap_bind_dn: str | None = None
  632. ldap_bind_password: str | None = None
  633. ldap_search_base: str | None = None
  634. ldap_user_filter: str | None = None
  635. ldap_security: str | None = None
  636. ldap_group_mapping: str | None = None
  637. ldap_auto_provision: bool | None = None
  638. ldap_default_group: str | None = None
  639. obico_enabled: bool | None = None
  640. obico_ml_url: str | None = None
  641. obico_ml_token: str | None = None
  642. obico_sensitivity: str | None = None
  643. obico_action: str | None = None
  644. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  645. obico_enabled_printers: str | None = None
  646. default_sidebar_order: str | None = None
  647. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  648. @field_validator(*LAN_SERVICE_URL_SETTINGS)
  649. @classmethod
  650. def validate_lan_service_url(cls, v: str | None, info: ValidationInfo) -> str | None:
  651. """Reject SSRF-unsafe outbound service URLs on save.
  652. Empty (and whitespace-only) is the documented "not configured / fall
  653. back to the env var" value for all four fields and must keep passing.
  654. Values that are not absolute URLs at all ("192.168.1.10:3333",
  655. "localhost:3333") are left alone rather than rejected. Two reasons:
  656. - They are inert. Every consumer of these four settings goes through
  657. httpx, which raises UnsupportedProtocol for a URL with no scheme, so
  658. no request is ever issued and there is nothing to guard against.
  659. - They were storable before this validator existed, and the settings
  660. UI is a plain text input with no scheme enforcement. Newly rejecting
  661. them would break saves that have nothing to do with the URL: the
  662. Obico panel, for one, sends obico_ml_url with every change and
  663. auto-saves, so one legacy value would block toggling detection on or
  664. off. A pre-existing misconfiguration should keep failing where it
  665. already failed (at request time), not spread to unrelated fields.
  666. ``urlparse`` is no help in telling the two apart — it reads
  667. "localhost:3333" as scheme "localhost" — so the test is the literal
  668. "://" that makes a string an absolute URL.
  669. """
  670. if v is None or not v.strip():
  671. return v
  672. candidate = v.strip()
  673. if "://" not in candidate:
  674. return v
  675. # Lazy-imported: schemas avoid top-level imports from api/routes,
  676. # matching the existing pattern in auth.py's _validate_icon_url.
  677. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  678. try:
  679. assert_safe_lan_service_url(candidate, label=info.field_name or "URL")
  680. except ValueError as exc:
  681. raise ValueError(str(exc)) from exc
  682. return v
  683. @field_validator("docker_compose_dir")
  684. @classmethod
  685. def validate_docker_compose_dir(cls, v: str | None) -> str | None:
  686. """Keep the copy-and-paste update command free of shell injection (#2664).
  687. Validated on the write path only. Doing it on ``AppSettings`` as well
  688. would mean a single bad row — however it got there — 500s the entire
  689. settings GET and takes the app down with it, which is a worse outcome
  690. than rendering a string that has to be pasted into a shell by hand to
  691. do anything at all.
  692. """
  693. if v is None or not v.strip():
  694. return v
  695. candidate = v.strip()
  696. if len(candidate) > _COMPOSE_DIR_MAX_LEN:
  697. raise ValueError(f"Compose directory must be at most {_COMPOSE_DIR_MAX_LEN} characters")
  698. if not _COMPOSE_DIR_ALLOWED.match(candidate):
  699. raise ValueError(
  700. "Compose directory may only contain path characters (letters, digits, space, and - _ . / \\ : ~)"
  701. )
  702. # A trailing backslash is the one survivor that would still break the
  703. # frontend's double-quoting: `cd "/opt/bam buddy\"` escapes the closing
  704. # quote and swallows the rest of the line. Harmless (the shell just
  705. # waits for a terminator rather than running anything) but the user
  706. # would be left staring at a continuation prompt, so refuse it here
  707. # instead of shipping a command that cannot work.
  708. if candidate.endswith("\\"):
  709. raise ValueError("Compose directory must not end with a backslash")
  710. return candidate
  711. @field_validator("gcode_snippets")
  712. @classmethod
  713. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  714. if v is None or v == "":
  715. return v
  716. try:
  717. parsed = json.loads(v)
  718. except json.JSONDecodeError:
  719. raise ValueError("gcode_snippets must be valid JSON or empty")
  720. if not isinstance(parsed, dict):
  721. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  722. return v
  723. @field_validator("ldap_group_mapping")
  724. @classmethod
  725. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  726. if v is None or v == "":
  727. return v
  728. try:
  729. parsed = json.loads(v)
  730. except json.JSONDecodeError:
  731. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  732. if not isinstance(parsed, dict):
  733. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  734. return v
  735. @field_validator("obico_enabled_printers")
  736. @classmethod
  737. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  738. if v is None or v == "":
  739. return v
  740. try:
  741. parsed = json.loads(v)
  742. except json.JSONDecodeError:
  743. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  744. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  745. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  746. return v
  747. @staticmethod
  748. def _validate_preset_triple(v: str | None, field_name: str, lo: int, hi: int) -> str | None:
  749. """Validate a JSON array of exactly 3 ints in [lo, hi]. Empty = defaults."""
  750. if v is None or v == "":
  751. return v
  752. try:
  753. parsed = json.loads(v)
  754. except json.JSONDecodeError:
  755. raise ValueError(f"{field_name} must be valid JSON or empty")
  756. if not isinstance(parsed, list) or len(parsed) != 3:
  757. raise ValueError(f"{field_name} must be a JSON array of exactly 3 integers")
  758. if not all(isinstance(item, int) and not isinstance(item, bool) for item in parsed):
  759. raise ValueError(f"{field_name} entries must all be integers")
  760. if not all(lo <= item <= hi for item in parsed):
  761. raise ValueError(f"{field_name} entries must each be in [{lo}, {hi}]")
  762. return v
  763. @field_validator("nozzle_temp_presets")
  764. @classmethod
  765. def validate_nozzle_temp_presets(cls, v: str | None) -> str | None:
  766. return cls._validate_preset_triple(v, "nozzle_temp_presets", 0, 320)
  767. @field_validator("bed_temp_presets")
  768. @classmethod
  769. def validate_bed_temp_presets(cls, v: str | None) -> str | None:
  770. return cls._validate_preset_triple(v, "bed_temp_presets", 0, 140)
  771. @field_validator("chamber_temp_presets")
  772. @classmethod
  773. def validate_chamber_temp_presets(cls, v: str | None) -> str | None:
  774. return cls._validate_preset_triple(v, "chamber_temp_presets", 0, MAX_CHAMBER_TEMP_C)
  775. @field_validator("fan_speed_presets")
  776. @classmethod
  777. def validate_fan_speed_presets(cls, v: str | None) -> str | None:
  778. return cls._validate_preset_triple(v, "fan_speed_presets", 0, 100)
  779. @field_validator("obico_sensitivity")
  780. @classmethod
  781. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  782. if v is None:
  783. return v
  784. if v not in ("low", "medium", "high"):
  785. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  786. return v
  787. @field_validator("obico_action")
  788. @classmethod
  789. def validate_obico_action(cls, v: str | None) -> str | None:
  790. if v is None:
  791. return v
  792. if v not in ("notify", "pause", "pause_and_off"):
  793. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  794. return v
  795. @field_validator("default_sidebar_order")
  796. @classmethod
  797. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  798. if v is None or v == "":
  799. return v
  800. try:
  801. parsed = json.loads(v)
  802. except json.JSONDecodeError:
  803. raise ValueError("default_sidebar_order must be valid JSON or empty")
  804. if isinstance(parsed, dict):
  805. order = parsed.get("order")
  806. hidden_system_item_ids = parsed.get("hiddenSystemItemIds", [])
  807. if not isinstance(hidden_system_item_ids, list) or not all(
  808. isinstance(item, str) for item in hidden_system_item_ids
  809. ):
  810. raise ValueError("sidebar hidden system item IDs must be an array of strings")
  811. elif isinstance(parsed, list):
  812. order = parsed
  813. else:
  814. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  815. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  816. raise ValueError("sidebar order must be an array of strings")
  817. return v