Builds on the recent uvicorn-access-log-into-bambuddy.log change.
Until now the access line told us who called an endpoint, but there
was no way to tie that line to the application records emitted on the
server side while handling that request. The rogue stop_print mystery
on 2026-04-26 left exactly that gap: even with access logs piped in,
correlating "this POST landed" with "this MQTT publish went out 6 ms
later" required eyeball-matching timestamps across different loggers.
A new ContextVar + middleware + logging filter wire a trace ID through
every record:
* trace_id_middleware mints an 8-char hex ID per request (or honours
a sane inbound X-Trace-Id for cross-system correlation), stores it
in trace_id_var (ContextVar), echoes it on the response as
X-Trace-Id, and resets the var in finally.
* TraceIDFilter, attached to root + uvicorn.access, copies the
current trace_id_var value onto every LogRecord so the format
string [%(trace_id)s] resolves to the right ID per record.
* Records emitted outside any request scope (startup, MQTT
callbacks, scheduler) get a stable "-" placeholder so the column
stays visually aligned and grep stays simple.
ContextVars are the right plumbing because asyncio copies the current
context into every asyncio.create_task, so background work spawned
from inside a request inherits the same ID without explicit threading.
request.state can't make that hop. The logging filter also has no
access to the FastAPI request object — it runs synchronously inside
the stdlib logging machinery — and the ContextVar is the only
mechanism that bridges async request scope to sync log emission.
Inbound X-Trace-Id is hard-validated against [A-Za-z0-9_-]+ (max 64
chars) before being honoured — a hostile/buggy caller cannot smuggle
log-injection payloads (newlines, control chars, megabyte blobs) into
bambuddy.log via the trace ID column; values that fail the gate
silently trigger a freshly minted server-side ID rather than failing
the request.
Middleware is decorated AFTER auth_middleware on purpose: Starlette
stacks @app.middleware decorators LIFO so the last-decorated runs
first inbound, making trace stamp the OUTERMOST layer — auth log
lines and every record emitted on the way down to and back from the
route handler all carry the same ID.
Output now correlates as:
2026-04-26 09:51:39,152 INFO [uvicorn.access] [a4f3b1e7] - "POST
/api/v1/printers/1/print/stop HTTP/1.1" 200
2026-04-26 09:51:39,158 INFO [bambu_mqtt] [a4f3b1e7] [SERIAL] Sent
stop print command
One grep a4f3b1e7 returns the full causality chain.
30 new tests: 22 unit (ContextVar placeholder, filter copies value,
asyncio task propagation, concurrent-request isolation, hex generator
uniqueness, hostile-payload validator, max-length boundary, all four
write verbs survive, GET/HEAD/OPTIONS dropped, URL-substring false-
match guards, edge cases) and 8 integration (X-Trace-Id round-trips,
body matches header, hostile inbound replaced, overlong inbound
replaced, ContextVar resets after request, generator format stable,
each request gets unique ID).
Bambu MQTT can deliver two ams_data push frames for the same printer
~30 ms apart (observed on H2D + dual AMS at K-profile-load / RFID-read
boundaries). Each frame triggers on_ams_change in main.py, whose
auto-assign block reads (printer_id, ams_id, tray_id), decides "no
existing assignment", and INSERTs via auto_assign_spool — and the two
callbacks raced in their respective sessions, both deciding to insert,
with the second commit losing on:
asyncpg.exceptions.UniqueViolationError: duplicate key value
violates unique constraint
"spool_assignment_printer_id_ams_id_tray_id_key"
DETAIL: Key (printer_id, ams_id, tray_id)=(1, 0, 0) already exists.
SQLite's WAL serial-write semantics had been silently swallowing the
race for ~7 weeks since the spool-assignment feature shipped (latent in
ec82092b "Sync", 2026-02-12). When optional Postgres support landed in
610431d6 (2026-04-03) and asyncpg started allowing true concurrent
transactions, it surfaced. Net impact: log noise + one assignment cycle
skipped, retried on the next on_ams_change.
Adds a per-printer asyncio.Lock (_ams_assignment_locks keyed by
printer_id) wrapping the auto-assign critical section. By the time the
second callback's session runs the SELECT, the first's commit is
visible and the early-return "existing assignment" branch fires instead
of a duplicate INSERT.
The Spoolman sync block further down in on_ams_change intentionally
stays OUTSIDE the lock — it's network-bound and idempotent, so
serialising it would block subsequent AMS callbacks for the duration of
a remote roundtrip. Per-printer scope keeps unrelated printers fully
parallel. The auto-unlink block above isn't wrapped because its
DELETE/UPDATE operations don't have the same constraint surface.
5 new regression tests in test_ams_assignment_lock.py: same-printer-
same-lock identity, different-printers-different-lock isolation, second
acquirer waits for first (proves serialisation), different printers run
truly in parallel under a held lock (proves per-printer scope), and an
autouse fixture that resets the module-level dict between tests so
cross-test loop affinity bugs can't surface.
The bidirectional forwarders inside create_tls_proxy._handle catch
(ConnectionError, OSError, asyncio.CancelledError) on writes, but
uvloop's UVStream.write raises a plain RuntimeError from
UVHandle._ensure_alive when the underlying handle is already closed.
asyncio's default selector loop reports the same situation as
ConnectionResetError, so the bug only surfaced on uvloop — and only at
the moment ffmpeg (or a snapshot-capture subprocess) dropped its socket
while the proxy was mid-flush.
The RuntimeError slipped past the except tuple, escaped the forwarder
coroutine, and asyncio's client_connected_cb task-exception handler
logged a noisy multi-line traceback ending in:
RuntimeError: unable to perform operation on
<TCPTransport closed=True ...>; the handler is closed
Adds RuntimeError to the except tuple in both _fwd_to_server and
_fwd_to_client (the latter is the actual frame from the bug report —
server→client is where buffered TLS chunks land after the client has
gone). The forwarders are intentionally fire-and-forget on tear-down;
the existing dst.close() in the finally block already handles cleanup.
No functional regression possible — the connection is already dead by
the time the exception fires; this only changes whether asyncio logs an
"Unhandled exception" trace for it.
2 new regression contract tests in test_camera_tls_proxy.py use
inspect.getsource to assert both forwarder closures' except clauses
include RuntimeError. Source-level rather than a runtime test because
the forwarders are nested closures inside _handle and extracting them
just for testability would require a pure-cosmetic refactor.
Latent since 0feed83c (Fix P2S camera TLS compatibility via OpenSSL
proxy, #661, 2026-03-15) — only commit that ever touched these
forwarders.
Follow-up to #1042. The post-dispatch watchdog _verify_print_response was
fire-and-forget — it correctly detected when the printer never transitioned
(HMS error pending, half-broken MQTT session, plate-clear gate, SD card
fault) and force-reconnected the MQTT session, but the dispatch job had
already been marked successful on the optimistic MQTT-publish-acknowledged
path. The UI carried on showing "Print started successfully" while the
printer sat idle.
The watchdog now returns bool and is awaited inline by both call sites in
_run_reprint_archive and _run_print_library_file. On False the call sites
raise a RuntimeError carrying a user-actionable message ("Printer did not
acknowledge print command — state still {pre_state}. Check the printer for
a pending error...") which routes through the existing _run_active_job →
_mark_job_finished(failed=True) → background_dispatch WS broadcast path.
Library-file flow rolls back the freshly-created archive on timeout so no
phantom row is left behind for a print that never started.
The watchdog now also accepts subtask_id advancing past pre_subtask_id as a
definitive "command landed" signal — same as the queue-side watchdog at
print_scheduler.py:1992 — so slow H2D FINISH→PREPARE transitions (~50 s
observed) don't false-fail when the printer has clearly accepted the
project_file but is still in FINISH. Default timeout raised from 15 s to
90 s to match the queue-side watchdog and give the same headroom on both
dispatch paths. Brief mid-window MQTT disconnects keep polling instead of
immediately failing — matches what the queue watchdog already does and
avoids false-failing on transient telemetry gaps.
11 new tests in test_background_dispatch_watchdog.py: state-change pickup,
subtask_id-change pickup with state still FINISH, neither-changed timeout
plus force_reconnect_stale_session call, pre_subtask_id=None backwards-
compat, post-dispatch subtask_id=None not counting as a change, brief
disconnect not short-circuiting the window, persistent disconnect for the
full window returning False, default-timeout=90s contract, _run_reprint_archive
raises RuntimeError with the captured pre-state args on watchdog False,
_run_reprint_archive happy path doesn't rollback, _run_active_job marks
the job failed with the message when _process_job raises RuntimeError.
feat(oidc): add Azure Entra ID support with configurable email claim resolution
Adds two new OIDC provider fields: email_claim and require_email_verified.
Two new optional fields on Spool: free-text `category` (max 50) and
`low_stock_threshold_pct` (1-99). Powers the "differentiate critical
spools from prototype spools and alert at different thresholds" use
case from #729 without taking on the full multi-tag taxonomy + auto-
apply rules + per-tag alert system the ticket originally proposed.
Form gains:
- Category input with datalist autocomplete sourced from categories
already in use, so casing/spelling stays consistent.
- Per-spool low-stock threshold input. Empty = global default; the
global value renders as the placeholder.
Inventory page:
- New category filter chip (hidden until at least one spool carries
a category — keeps the chip row uncluttered).
- Stat-card "Low Stock" count and the "Low Stock" filter both honour
the per-spool override.
Plus: rename "Delete Tag" button to "Clear RFID Tag" (the original
ticket reporter mistook it for a taxonomy-tag delete; the button
actually clears the RFID UID/UUID off the spool record). Toast key
renamed from `tagDeleted` to `rfidCleared`.
i18n: full translations across all 8 locales.
Tests: 9 new backend schema tests (defaults, partial-update, range
rejection, max-length); 2 new frontend tests (per-spool threshold
pulls extra spools into low-stock count, filter chip hidden when no
categories exist).
`find_matching_untagged_spool` is supposed to attach an incoming Bambu
RFID UUID to a pre-existing manually-logged spool of the same
material/color so users who log inventory before scanning don't end up
with duplicate rows. Two bugs meant it almost never worked for the
actual reporting workflow:
1. Subtype filter was strict. AMS reports `tray_sub_brands="PLA Basic"`
→ matcher required `Spool.subtype = 'Basic'` exactly. The form's
Quick-Add mode only requires `material`, so bulk-logged rows have
`subtype=NULL` and were always excluded → duplicate on first AMS
read.
2. Brand wasn't filtered. The docstring claimed brand was matched but
the WHERE clause didn't include it, so a same-color Polymaker (or
any non-Bambu) untagged row could acquire a Bambu UUID — silent
data corruption.
Fix in the same query: subtype prefers exact match but accepts NULL as
fallback (CASE in ORDER BY ensures exact wins when both exist); brand
restricted to NULL or LOWER(brand) LIKE '%bambu%' (covers 'Bambu',
'Bambu Lab', 'BambuLab', 'bambu lab' — the spellings users actually
type).
6 regression tests added in test_spool_tag_matcher.py.
ntfy supports a Priority header (1=min, 2=low, 3=default, 4=high, 5=urgent)
that controls escalation on the receiving device, but every event was being
sent at the server default — so a "50% complete" ping looked identical to
"print failed" or "printer offline". Add a per-event priority dropdown
section in the Add/Edit Notification modal (visible only for ntfy, listing
only enabled events); the backend reads config.event_priorities and emits
the matching Priority header on POST and PUT (image-attachment) paths.
Unmapped events fall through to the ntfy server default. Out-of-range
and non-numeric values are dropped, not clamped, so a misconfigured value
never silently sends at the wrong urgency. Test sends omit the header by
design so the test path can't accidentally page someone at urgent priority.
Backward compatible: existing providers without event_priorities behave
exactly as before. NtfyConfig.event_priorities is optional; the route
stores config as a JSON blob so no migration is needed.
i18n: full translations across all 8 locales (en/de/fr/it/ja/pt-BR/zh-CN/
zh-TW). README, CHANGELOG, and the wiki notifications page updated.
Tests: 6 backend (Priority set on mapped, omitted on unmapped/missing/
no-priorities, ignored for bad values, propagated through attachment
path), 6 frontend (section visible only for ntfy, lists only enabled
events, save round-trip, edit pre-fill, toggle drops row, non-ntfy
never writes the key).
The global CSP set script-src 'self', so FastAPI's /docs page rendered
blank: the inline boot <script> and the cdn.jsdelivr.net swagger-ui
bundle/CSS were both blocked. /redoc and /docs/oauth2-redirect had the
same problem.
Branch the security_headers_middleware to emit a docs-scoped CSP for
those three paths that allows cdn.jsdelivr.net (scripts + styles), the
FastAPI/Redoc favicon hosts (images), and 'unsafe-inline' for the
inline boot script. Every other route keeps the stricter SPA policy
unchanged.
#1108 — Long-lived camera-stream tokens for HA / Frigate / kiosks. Camera-only
V1, hard 365-day cap (no infinite tokens), pbkdf2 hashed at rest, plaintext
shown to user exactly once on creation. New "Camera API Tokens" panel under
Settings → API Keys with self-service create/revoke, styled confirm modal,
admin "All users" view for leak triage. Auth path: /camera/stream tries the
existing 60-min ephemeral table first, falls through to the long-lived path.
Indexed lookup_prefix keeps verify O(1) per token.
Permission audit: gated the existing API-keys-CRUD + Webhook docs + API
Browser content behind api_keys:read so non-admins with camera:view land on
the API Keys tab and see only the Camera Tokens panel they actually have
permission to use. Grid layout collapses to single column for non-admins.
Tests: 29 new backend (15 service + 14 integration covering create/list/
revoke ownership rules, the auth fall-through, scope enforcement, prefix
collisions) + 6 new frontend tests for the section UI including the new
modal flow. All 77 backend tests + 21 frontend camera tests pass. Ruff
clean (lint + format).
Docs: README updated with fan-out + long-lived-token bullets. Wiki gets a
new "Long-Lived Camera Tokens" section under features/camera.md (HA YAML
example, security model, permission requirements, revoke flow). Website
features.html gets the bullet under Camera Streaming.
Also includes #1089 follow-up tweaks already merged in this branch:
_stream_start_times.setdefault for accurate stream_uptime, subscribe()
RuntimeError retry to close the grace-vs-subscribe race, atomic
unsubscribe count via the iter_subscriber on_unsubscribe callback.
Most Bambu Lab printers only allow one concurrent camera connection, but
GET /printers/{id}/camera/stream opened a fresh upstream per viewer.
Two browser tabs → second viewer fails or kicks the first off.
New MjpegBroadcaster (services/camera_fanout.py) owns one upstream per
printer and fans MJPEG chunks out to N subscribers. 5 s grace window
absorbs tab refreshes without reconnecting. Bounded subscriber queues
drop frames for slow viewers rather than blocking the broadcaster.
Audit-pass fixes:
- _stream_start_times set with setdefault() so stream_uptime reflects
the shared upstream's age, not the most-recent viewer's
- subscribe() retried once on RuntimeError to close a tiny grace race
- unsubscribe() returns post-removal count atomically so the detach log
no longer races with concurrent leavers
Permission gates unchanged; broadcaster has no FastAPI surface.
Tests: 13 broadcaster unit tests + 2 integration tests on /camera/stop.
External-camera path untouched.
The dual-nozzle active-extruder card was the only tile in the printer
status row without a theme icon, making the row look uneven on H2D /
H2S / H2C. Adds a schematic nozzle icon (filament body + heater block
+ tip) matching the SVG @m4rtini2 contributed, sized and coloured to
match the adjacent Nozzle/Bed/Chamber temperature cards.
POST /library/files only rejected the read-only external branch and
then unconditionally wrote to get_library_files_dir() with a UUID
filename. The resulting LibraryFile row pointed at the external folder
via folder_id, so the file showed up in Bambuddy's UI, but the bytes
physically lived in archive/library/files/ and never touched the mount
-- invisible from any other machine accessing the NAS/SMB share.
Writable external uploads now write through to <external_path>/<filename>
with the original filename preserved, and the DB row matches what scan
produces (is_external=True, file_path=<absolute mount path>). Collisions
return 409 instead of silently overwriting; inaccessible or non-writable
mount returns 400; path-traversal filenames are rejected via resolve +
relative_to.
Extract-zip is now rejected against any external folder (not just
read-only) with a clear "extract on the mount and run Scan" message --
the nested-subfolder creation path would need mkdir on the mount plus
matching is_external LibraryFolder rows, which is a separate design.
Scan already handles that shape.
When a file sliced for the wrong nozzle size is dispatched, the printer
goes IDLE -> PREPARE -> FAILED without ever entering RUNNING. Completion
detection required prev=RUNNING or _was_running=True, so on_print_complete
never fired and the queue item stayed at "printing" forever -- blocking
every subsequent pending item for that printer (check_queue seeds
busy_printers from any row in 'printing').
Fire completion on FAILED from PREPARE or SLICING too. Restricted to
those two pre-print states so a stale FAILED on first connection
(prev=None) still can't accidentally advance an unrelated queue item.
Also populate PrintQueueItem.error_message from the current HMS error
list via the existing hms_errors.py lookup, so users see e.g.
"[0500_4038] The nozzle diameter in sliced file is not consistent
with the current nozzle setting" instead of a blank failure reason.
The SSRF guard added in this PR rejected all RFC-1918 private and loopback
addresses, which breaks Bambuddy's primary deployment topology — Spoolman
running on the same LAN as Bambuddy (192.168.x.x, 10.x.x.x, 127.0.0.1).
Users hit "Spoolman URL must not point to a private, loopback, link-local,
multicast, or unspecified address" on legitimate setups.
Rescope the guard to block what's actually dangerous in this context:
cloud metadata endpoints (AWS/Alibaba IMDS), multicast, unspecified,
non-http(s) schemes, and numeric-encoded IP bypasses. Loopback and
RFC-1918 ranges are now explicitly permitted.
Tests:
- test_ssrf_blocked_schemes_and_addresses updated with refined block list
- test_ssrf_allows_lan_spoolman_topologies (new) asserts loopback +
RFC-1918 are accepted so this regression cannot recur silently
- TestSpoolmanInventorySSRFSpoolBuddyPath parametrize lists trimmed
feat(inventory): replace Spoolman iframe with internal inventory UI
When Spoolman is enabled, the Inventory page now uses the same internal
UI (spool list, create/edit modal, archive, delete, weight sync) backed
by a new proxy layer instead of opening an iframe.
1. `_cancel_restart_task` self-await guard (manager.py:389-413).
stop_server() / stop_proxy() are called from inside
_restart_for_cert_renewal, which runs AS _cert_restart_task.
Cancelling+awaiting self flagged a CancelledError on the next
`await` in stop_server, tearing down old listeners but never
letting start_server run — the VP sat on the expired cert
until the process was manually restarted, silently defeating
auto-renewal. Skip when `task is asyncio.current_task()` and
just clear the reference.
2. Clipboard fallback textarea leak (VirtualPrinterCard.tsx:66-81).
The HTTP fallback created a hidden textarea, called
select() + execCommand('copy'), then removed the textarea.
If select() or execCommand threw, removal never ran and the
textarea leaked into the DOM. Move the removal into `finally`
so it happens regardless of the inner block's outcome.
Regression tests in test_tailscale.py::TestCancelRestartTaskSelfAwait
cover both the self-cancel path (must NOT cancel self) and the
outside-cancel path (must still cancel and await).
Add the Tailscale CLI to the production image and document how to
enable Let's Encrypt cert provisioning for virtual printers from a
Docker-deployed Bambuddy.
- Dockerfile installs `tailscale` from the official Debian repo. Only
the CLI is used at runtime; tailscaled itself stays on the host.
The binary is harmless if the socket isn't mounted — the code logs
an actionable hint and falls back to self-signed certs.
- docker-compose.yml adds a commented-out volume mount for
/var/run/tailscale/tailscaled.sock with inline setup instructions.
- tailscale.py's docker-socket hint now also fires when the binary is
present but the daemon socket is unreachable (i.e. the new Docker
pattern), not just when the binary is missing, so users get the
actionable "mount the socket" message instead of opaque CLI stderr.
Enabling the integration on a Docker host:
1. `curl -fsSL https://tailscale.com/install.sh | sh` on host
2. `sudo tailscale up`
3. `sudo tailscale set --operator=<user>` for the container PUID
4. Uncomment the tailscaled.sock mount in docker-compose.yml
5. `docker compose up -d --force-recreate`
6. Flip the Tailscale toggle on the VP card
The Tailscale FQDN copy button used only `navigator.clipboard.writeText`,
which browsers block when `window.isSecureContext === false` — i.e. when
Bambuddy is reached over HTTP on a LAN / tailnet IP, which is the
common case. My catch block swallowed the error and the generic
"Failed to update settings" toast fired instead of actually copying.
Add a legacy `document.execCommand('copy')` fallback via a hidden
textarea for non-secure contexts. New i18n key
`virtualPrinter.toast.copyFailed` added to all 8 locales for the
(rare) both-paths-fail case.
Legacy SQLite installs created the `settings` table without a UNIQUE
constraint on `key`. The seed loop's `INSERT OR IGNORE` silently
degraded to a plain INSERT, so every `systemctl restart` added another
row of `advanced_auth_enabled` / `smtp_auth_enabled`. After a handful
of restarts, `scalar_one_or_none()` in is_advanced_auth_enabled() and
similar sites blew up with `MultipleResultsFound`, 500'ing the login
flow.
Run-migrations now deletes dup rows (keeping MIN(id) per key) and
creates the missing `ix_settings_key` unique index before the seed
loop. Both ops are idempotent — fresh installs and Postgres already
have the index, so they no-op.
Bambu started shipping H2C units with a new serial prefix (`31B8B…`
observed on a January 2026 unit) instead of the legacy `094…` shared by
the H2D/H2C/H2S family. Two serial-prefix-driven paths — the K-profile
edit branch in `kprofiles.py` and the delete-K-profile MQTT command in
`bambu_mqtt.py::delete_kprofile` — were silently routing the new units
through the single-nozzle format.
Match on 5 chars (`31B8B`): covers the 3-char model code plus the two
revision bytes, leaving the revision-letter slot free to iterate. This
mirrors the X2D precedent of using a longer-than-3-char prefix when a
single data point can't confirm family reuse.
Runtime dual-nozzle detection via `device.extruder.info` count and
model-string branches (`self.model in ("H2C", "H2D", …)`) are already
prefix-agnostic — no change needed there.
- backend/app/api/routes/kprofiles.py: add "31B8B" to is_h2d tuple
- backend/app/services/bambu_mqtt.py: same in delete_kprofile
- backend/tests/unit/services/test_bambu_mqtt.py: regression test
`test_h2c_new_prefix_uses_dual_nozzle_format`
Fix a silent correctness bug: archive purge used `created_at` which is
pinned to the first print, so reprinting a two-year-old archive yesterday
would still make it eligible for a 365-day purge. The preview and purge
queries now age each archive by `COALESCE(completed_at, started_at,
created_at)` — reprints refresh the clock.
Also flesh out both purge modals (File Manager + Archives) with an
explicit "What happens when you click Purge" effects list so users see
upfront that library files go to Trash (reversible) while archives are
hard-deleted (irreversible), plus what disk artefacts get removed.
Backend:
- services/archive_purge.py: `_last_activity_expr()` helper used by
preview, purge, and sample query
- tests/integration/test_archive_purge_api.py: new test covering the
reprinted-archive case
Frontend:
- PurgeOldFilesModal / PurgeArchivesModal: new effects bullet list
- i18n: reprint-aware ageLabel/description/warning and effects bullets
across all 8 locales (en/de fully translated, rest English fallback)
Docs:
- wiki/features/archiving.md: "How old is measured" note + effects list
- wiki/features/file-manager.md: "What happens when you click Purge"
section + explicit age-rule breakdown
- CHANGELOG: archive auto-purge entry rewritten to mention reprint
semantics, `archives:purge` permission backfill, and updated test count
Adds an archive counterpart to the library trash sweeper shipped in the
previous commit. Unlike the library flow, archives are hard-deleted —
print history is a decaying timeline, so there is no trash intermediate;
download or favourite anything you want to keep first.
Backend
- New ArchivePurgeService (backend/app/services/archive_purge.py) with
its own 15-minute scheduler loop and a 24h throttle on actual purge
runs. Delegates every delete to the existing safety-checked
ArchiveService.delete_archive so the 3MF, thumbnail, timelapse, source
3MF, F3D, and photo folder all get cleaned up together with the DB
row. Per-row session via async_session() avoids commit-per-row churn
on any caller-passed session.
- New /archives/purge/{preview,settings} + POST /archives/purge routes
gated on a dedicated archives:purge permission (not archives:delete_all)
so admins can delegate bulk-delete to a role without granting
per-archive delete on other users' rows.
- seed_default_groups() now backfills both library:purge and
archives:purge on the Administrators group for upgraded installs —
the original library:purge was added after Administrators was first
seeded so the "create if not exists" path skipped existing DBs and
left admins without the permission.
- 8 new integration tests (defaults, settings roundtrip, bound
validation, preview, manual purge, auto-purge enabled path, 24h
throttle, disabled skip).
Frontend
- Settings → Archives card gains an auto-purge toggle + age input (7d
floor, 10y ceiling, 365d default), with a save-toast on every change.
The bulk "Purge old" button lives on the Archives page header
(rightmost, after Upload 3MF) to match the File Manager pattern —
configuration in Settings, one-shot action on the page.
- New PurgeArchivesModal mirrors PurgeOldFilesModal: live preview (count
+ total size freed + sample filenames) debounced at 300ms, amber
"hard-delete, no undo" warning.
- Admin-only UI gates on archives:purge via the standard hasPermission
hook; Permission TS union updated.
- i18n blocks across all 8 locales (en/de full, other 6 English
fallback per project convention).
Docs
- CHANGELOG entry under 0.2.4b1 following the existing library-trash
entry.
- bambuddy-wiki archiving.md gains a new "Auto-Purge" section.
- bambuddy-website features.html gets a matching bullet.
Verification: python -m ruff check backend/app/ clean; 25 integration
tests pass (8 archive_purge + 17 library_trash regression); npm run
build clean.
Library files now move to a configurable-retention trash bin on delete
instead of being hard-deleted from disk (default 30 days). Admins get a
"Purge old" bulk action on the File Manager with a live preview, plus an
optional auto-purge setting in Settings → File Manager that runs the same
operation once per 24h when enabled (default off). Regular users see and
manage their own trashed files; admins see everyone's. External (linked)
files bypass trash since their bytes aren't under Bambuddy's control.
- New `library:purge` permission (admin-only by default)
- Nullable indexed `deleted_at` column on library_files; dialect-aware
ALTER TABLE so the column actually gets added on PostgreSQL (raw
DATETIME is SQLite-only syntax)
- New `LibraryFile.active()` classmethod; every query site routed through
it so trashed rows don't leak into listings, print dispatch, MakerWorld
dedupe, or stats
- Trash page: select-all + bulk restore/delete, per-row checkboxes, wider
layout so datetime columns don't clip
- Auto-purge: 24h throttle via `library_auto_purge_last_run` setting so
the 15-minute sweeper cadence still runs the purge at most once per day
- Save toast wired into every trash/auto-purge setting change
- 17 new backend integration tests (service + routes + auto-purge throttle),
8 new frontend tests, localised across all 8 UI languages
- Wiki + website feature entries updated
Users behind an HTTPS reverse proxy pointing the Spoolman URL at plain
HTTP saw the Filament tab render as a blank page with only a console-
side Mixed Content warning. Browsers block HTTP iframes inside HTTPS
parents by design (independent of CSP; #1054's frame-src http: fix
only helps when the parent is also HTTP). The fix for the user's
setup is to put Spoolman behind the same reverse proxy with HTTPS.
Bambuddy can't override the browser's mixed-content block, but it can
stop rendering an iframe that will silently fail. When
window.location.protocol is https: and the Spoolman URL starts with
http://, render a warning card explaining the root cause and offering
an "Open in new tab" fallback (standalone tabs aren't subject to
mixed-content rules).
Localised across all 8 UI languages.
Reprint from Archive kept showing `created_by_id = NULL` even after the
Direct Print / File Manager / Library attribution fixes in 0.2.4b1.
Root cause: reprint reuses the source archive row (via
register_expected_print → _expected_prints lookup) to avoid duplicate
archives. When the source was auto-created from a printer-initiated
print, its created_by_id was NULL — and reprint never touched it.
Print Log correctly attributed the reprinter (set_current_print_user
→ _print_user_info at print-complete), but the Statistics per-user
filter reads archive.created_by_id and stayed unassigned forever.
Fix in main.py's print-complete handler: when the archive's
created_by_id is NULL and a print-session user is known, back-fill
from _print_user_info. Never overwrites existing attribution — the
original uploader keeps ownership; only NULLs are filled.
Already-completed archives stay NULL (no retroactive rewrite). Next
print after deploy credits the current user on any NULL archive.
* feat(makerworld): URL-paste import and print for MakerWorld models
Add a dedicated /makerworld sidebar page where users paste a MakerWorld
model URL and get the full plate list + one-click "Import to Library" or
"Print Now". Closes the workflow gap that kept LAN-only users on the
Bambu Handy app solely for MakerWorld download-and-send.
The authenticated tier reuses the existing Bambu Cloud token that
Bambuddy already stores for firmware checks and slicer settings --
MakerWorld shares the same auth backend, so the same JWT works there.
No separate OAuth flow, no companion browser extension, no credential
hijack. Anonymous users can still paste a URL and see model metadata;
the 3MF download itself requires the Cloud login.
Print Now hands off to the existing PrintModal (plate picker + AMS
mapping + dispatch) so multi-filament models work via the same code
path as library-file prints. Imported 3MFs are stored through a new
shared save_3mf_bytes_to_library() helper so the multipart upload
route and the MakerWorld import route don't duplicate 3MF parsing +
thumbnail extraction logic.
LibraryFile gains indexed source_type + source_url columns. Re-pasting
a URL for a model already in the library returns the existing row
instead of re-downloading -- dedupe is by canonicalised URL, not SHA256,
because MakerWorld's download URLs are signed and change per request.
Thumbnail proxy (/makerworld/thumbnail) hot-links through the backend
instead of directly to makerworld.bblmw.com -- the SPA's img-src CSP
stays strict and users' IPs don't hit MakerWorld's CDN logs. The
endpoint is intentionally unauthenticated since <img> tags can't carry
a Bearer token; SSRF-guarded by a CDN host allowlist so it can't be
used as a generic proxy.
Search and browse-catalogue are explicitly out of scope. The public
design/search endpoint returns empty results from server-originated
requests (likely needs csrf/session state reproducible only from a
real browser), and the __NEXT_DATA__ HTML fallback is blocked by
Cloudflare. URL-paste covers the realistic discovery pattern (Reddit /
YouTube / shared links).
Headers match kloshi-io/makerworld-api-reverse's production-tested set
(User-Agent: 3d-printing-service/1.0, x-bbl-* client identifiers,
Referer). The /instance/{id}/f3mf call includes ?type=download which
community userscripts use to signal legitimate download intent. 418
responses (MakerWorld's CAPTCHA gate) retry once with backoff and then
surface a clear actionable error with an "Open on MakerWorld" fallback
link; we never try to evade bot detection.
Permissions: new makerworld:view (browse metadata, view thumbnails) and
makerworld:import (save 3MFs to library). Administrators and Operators
get both; Viewers get view-only. Migration grants these to existing
groups based on whether they already have library:upload / library:read.
Disclaimer in the UI and wiki page mirrors kloshi's framing: not
affiliated with or endorsed by MakerWorld or Bambu Lab, interoperability
only, not intended to circumvent access controls.
Tests: 30 backend (service + routes) + 4 frontend. Full backend suite
(1931 tests) clean. Frontend build clean.
* feat(makerworld): ship working URL-paste import via api.bambulab.com iot-service
The MakerWorld integration shipped in 0.2.4b1 dev was broken for most
public models: the makerworld.com/design-service path returns "Please
log in to download models" even with a valid Bambu Cloud bearer,
because it's cookie-gated behind Cloudflare. Published reverse-
engineering projects work around this by pasting browser cookies; we
route around it entirely by using the api.bambulab.com/iot-service
endpoint (documented by Pr0zak/YASTL#51), which accepts the same
bearer Bambuddy already has and returns a presigned S3 URL.
Working flow:
GET api.bambulab.com/v1/design-service/design/{id} → metadata
GET api.bambulab.com/v1/iot-service/api/user/profile/{pid}?model_id=<str>
Authorization: Bearer {cloud_token} → signed S3 URL
urllib.request (no redirects, no query re-encoding) → bytes
Notes on each step:
- The model_id query param is the alphanumeric string from the
design response (e.g. US2bb73b106683e5), NOT the integer designId
from the /models/{N} URL. The import route fetches design metadata
first to get it.
- S3 presigned URLs MUST be fetched with urllib (not httpx/curl_cffi)
because the signature is computed over exact query-string bytes;
any normalising encoder breaks it with SignatureDoesNotMatch 400s
(YASTL#52 hit the same issue). Wrapped in a no-redirect opener so
the .amazonaws.com host allowlist guarantee isn't bypassed by a
302 elsewhere.
- The canonical source_url now includes profile_id so different
plates of the same model get distinct library entries. Older rows
from dev builds keep the model-level URL; the resolve endpoint's
"already imported" check LIKEs both shapes.
UI rebuild:
- Per-plate Save + Save & Slice in Bambu Studio / OrcaSlicer (the
plate is unsliced source, so "Print Now" was misleading and is
replaced by an explicit slicer hand-off).
- Import all plates with sequential progress.
- Folder picker (default: auto-created top-level "MakerWorld"
folder, created on first import, folder tree invalidated so
File Manager shows it immediately).
- Image gallery per plate with keyboard-navigable lightbox.
- Recent imports sidebar (sticky on lg+, vertical list with
jump-to-library / slicer / open-on-makerworld icons).
- Inline follow-up actions on imported plate rows so the user
doesn't scroll back to a top-of-page card.
- Per-plate delete via the standard ConfirmModal (no window.confirm).
- Elapsed-time + phase label during import so the 10-30s synchronous
POST doesn't feel frozen.
- URL-change detection drops the preview when the pasted URL
diverges from the resolved one.
Security hardening (found in review):
- DOMPurify.sanitize on the MakerWorld HTML summary before
dangerouslySetInnerHTML (user-authored content).
- <img> tags in that HTML routed through the thumbnail proxy so
the SPA's img-src 'self' data: blob: CSP isn't widened.
- /makerworld/thumbnail uses follow_redirects=False (the host
allowlist only covers the initial URL).
- 3MF CDN fetch strips the bearer (signed URL is the credential).
- S3 fetch uses a no-op HTTPRedirectHandler for the same reason.
- Upstream filename is os.path.basename'd before persisting.
Tests: 46 backend service unit tests, 19 route tests, 12 frontend
tests — all passing. All user-facing strings localised across the
8 UI languages.
* - frontend/src/App.tsx — removed the 3 stale <AdminRoute> lines (kept the 3 <PermissionRoute> equivalents). TSC + Vite both clean.
- backend/tests/integration/test_auth_api.py — added # pragma: allowlist secret + # noqa: S106 on the test fixture line that GitGuardian flagged.
"Open in Slicer" emitted `orcaslicer://open?file=<URL>` and
`bambustudio://open?file=<URL>` by plain string concatenation, relying
on a stale comment that claimed the browser preserves URLs in the query
string. That ignores the slicer's own `url_decode()` on the received
query (BS post_init → url_decode + split_str; OrcaSlicer Downloader
regex + url_decode), so any already-percent-encoded character — most
commonly `%20` from filenames with spaces — decoded to a literal space
and the slicer's subsequent HTTP GET returned 0 bytes or 404.
All three URL forms now use `encodeURIComponent()` (matching what the
macOS `bambustudioopen://` branch was already doing, which is why the
bug didn't surface on macOS). Corrected the file-level comment to
document the actual invariant.
Regression test in slicer.test.ts feeds the exact issue reproduction
URL and asserts `%2520` appears in the generated href.