From 4e5cb298ef3876634264d96cd35c9bbbff7d0379 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 4 Dec 2026 10:48:00 -0500 Subject: [PATCH] web: every Copy button works over plain http; saved keys and passwords can be removed (#8508, #8511) copyText (family idea "copyText"): - web/src/lib/utils/clipboard.ts tries the Clipboard API first. - Where the API is missing (plain http on a home network) or refuses, it copies through the copy command on a hidden textarea instead. - If that fails too, it selects the shown value. - All six Copy buttons go through it: an invite token, the needs-a-file list, diagnostics, connection details, a playlist link, and report details. Before, five of them only showed an error over http. SecretField (family idea "SecretField"): - One component for a write-only credential: a password box for a new value, which the card's own Save sends, and a Remove button while one is saved. - Used for the provider API keys, the SMTP password, the backup secret key and the AcoustID key. Only AcoustID had Remove before. - The server gains clear_password (SMTP) and clear_secret_key (backup). An empty value still keeps the stored one. Provider keys already clear when sent empty. - Remove sends the saved settings back with only the credential cleared, so unsaved edits elsewhere on the card stay unsaved. Co-Authored-By: Claude Opus 5.5 --- internal/api/admin_backups.go | 2 +- internal/api/admin_smtp.go | 6 ++ internal/api/admin_smtp_test.go | 21 +++++ internal/backup/service.go | 7 +- internal/backup/service_test.go | 10 +++ web/src/lib/api/admin.ts | 7 +- web/src/lib/components/AcoustIDCard.svelte | 13 +-- web/src/lib/components/AcoustIDCard.test.ts | 2 +- .../lib/components/admin/BackupPanel.test.ts | 14 +++- .../components/admin/BackupSettings.svelte | 21 +++-- .../lib/components/admin/ProviderGroup.svelte | 24 ++++-- .../lib/components/admin/SmtpSettings.svelte | 24 +++++- .../components/settings/SecretField.svelte | 68 +++++++++++++++ web/src/lib/utils/clipboard.test.ts | 83 +++++++++++++++++++ web/src/lib/utils/clipboard.ts | 62 ++++++++++++++ web/src/routes/admin/diagnostics/+page.svelte | 8 +- web/src/routes/admin/users/+page.svelte | 9 +- .../routes/collection/missing/+page.svelte | 3 +- .../routes/collection/reports/+page.svelte | 9 +- web/src/routes/playlists/[id]/+page.svelte | 10 +-- .../routes/settings/connections/+page.svelte | 9 +- 21 files changed, 349 insertions(+), 63 deletions(-) create mode 100644 web/src/lib/components/settings/SecretField.svelte create mode 100644 web/src/lib/utils/clipboard.test.ts create mode 100644 web/src/lib/utils/clipboard.ts diff --git a/internal/api/admin_backups.go b/internal/api/admin_backups.go index 21cd906d..5e4a1df0 100644 --- a/internal/api/admin_backups.go +++ b/internal/api/admin_backups.go @@ -41,7 +41,7 @@ func fieldErr(w http.ResponseWriter, err error) bool { } // PUT /api/admin/backups — save the settings. An empty secret_key keeps the -// stored one. Returns the new status. +// stored one, and clear_secret_key removes it. Returns the new status. func (h *handlers) handleUpdateBackups(w http.ResponseWriter, r *http.Request) { u, ok := decodeBackupUpdate(w, r) if !ok { diff --git a/internal/api/admin_smtp.go b/internal/api/admin_smtp.go index 77a73094..b3680cbf 100644 --- a/internal/api/admin_smtp.go +++ b/internal/api/admin_smtp.go @@ -33,6 +33,9 @@ type updateSMTPConfigReq struct { FromAddress string `json:"from_address"` FromName string `json:"from_name"` UseTLS bool `json:"use_tls"` + // ClearPassword removes the stored password. An empty Password alone + // keeps it, so the admin doesn't retype it on every save. + ClearPassword bool `json:"clear_password"` } func (h *handlers) handleGetSMTPConfig(w http.ResponseWriter, r *http.Request) { @@ -80,6 +83,9 @@ func (h *handlers) handleUpdateSMTPConfig(w http.ResponseWriter, r *http.Request // Preserve the stored (sealed) password when the request sends "", so // the admin doesn't have to re-enter it on every save. password := current.Password + if req.ClearPassword { + password = "" + } if req.Password != "" { password, err = secret.Seal(secret.SMTPPassword.Purpose(), "", req.Password) if err != nil { diff --git a/internal/api/admin_smtp_test.go b/internal/api/admin_smtp_test.go index b7864bb7..f9878f13 100644 --- a/internal/api/admin_smtp_test.go +++ b/internal/api/admin_smtp_test.go @@ -11,6 +11,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/dbtest" ) func newAdminSMTPRouter(h *handlers) chi.Router { @@ -92,6 +93,26 @@ func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) { } } +// The password is removed only when the save asks for it. +func TestSMTPConfig_UpdateClearsPasswordWhenAsked(t *testing.T) { + h, pool := testHandlers(t) + admin := seedUser(t, pool, "smtpclear", "pw", true) + fx := dbtest.On(t, pool) + fx.Exec("UPDATE smtp_config SET password = 'original' WHERE id = true") + + body := `{"enabled": false, "host": "", "port": 587, "username": "", "password": "", + "from_address": "", "from_name": "T", "use_tls": true, "clear_password": true}` + req := withUser(httptest.NewRequest(http.MethodPut, "/api/admin/smtp-config", bytes.NewReader([]byte(body))), admin) + rec := httptest.NewRecorder() + newAdminSMTPRouter(h).ServeHTTP(rec, req) + if rec.Code != http.StatusNoContent { + t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String()) + } + if n := fx.Count("SELECT count(*) FROM smtp_config WHERE password <> ''"); n != 0 { + t.Error("the stored password survived a save with clear_password") + } +} + func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) { h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpvalid", "pw", true) diff --git a/internal/backup/service.go b/internal/backup/service.go index 9ddc4a26..387474fa 100644 --- a/internal/backup/service.go +++ b/internal/backup/service.go @@ -99,7 +99,8 @@ type Config struct { } // Update is a save from the admin card. An empty SecretKey keeps the stored -// one, so the key doesn't have to be typed again on every save. +// one, so the key doesn't have to be typed again on every save; +// ClearSecretKey removes it. type Update struct { Enabled bool `json:"enabled"` Destination string `json:"destination"` @@ -108,6 +109,7 @@ type Update struct { Bucket string `json:"bucket"` AccessKey string `json:"access_key"` SecretKey string `json:"secret_key"` + ClearSecretKey bool `json:"clear_secret_key"` RunHour int `json:"run_hour"` UploadLimitKiB int `json:"upload_limit_kib"` IncludeMusic bool `json:"include_music"` @@ -246,6 +248,9 @@ func merge(st dbq.BackupSetting, u Update) (dbq.BackupSetting, error) { st.RunHour = int16(u.RunHour) st.UploadLimitKib = int32(u.UploadLimitKiB) st.IncludeMusic = u.IncludeMusic + if u.ClearSecretKey { + st.SecretKey = "" + } if u.SecretKey != "" { sealed, err := secret.Seal(secret.BackupSecretKey.Purpose(), "", u.SecretKey) if err != nil { diff --git a/internal/backup/service_test.go b/internal/backup/service_test.go index 20572b08..38b4fd03 100644 --- a/internal/backup/service_test.go +++ b/internal/backup/service_test.go @@ -129,6 +129,16 @@ func TestMergeTidiesAndKeepsTheStoredSecret(t *testing.T) { } } +func TestMergeRemovesTheSecretWhenAsked(t *testing.T) { + st, err := merge(dbq.BackupSetting{SecretKey: "v1.stored"}, Update{Destination: DestinationS3, ClearSecretKey: true}) + if err != nil { + t.Fatal(err) + } + if st.SecretKey != "" { + t.Errorf("secret key = %q after a clear, want it removed", st.SecretKey) + } +} + func TestThrottleKeepsToItsRate(t *testing.T) { data := bytes.Repeat([]byte("x"), 20*1024) start := time.Now() diff --git a/web/src/lib/api/admin.ts b/web/src/lib/api/admin.ts index 8e0f64e0..3ed37bb4 100644 --- a/web/src/lib/api/admin.ts +++ b/web/src/lib/api/admin.ts @@ -658,7 +658,8 @@ export async function getSMTPConfig(): Promise { return api.get('/api/admin/smtp-config'); } -export async function updateSMTPConfig(input: SMTPConfig): Promise { +/** A save. An empty password keeps the stored one; clear_password removes it. */ +export async function updateSMTPConfig(input: SMTPConfig & { clear_password?: boolean }): Promise { await api.put('/api/admin/smtp-config', input); } @@ -1036,8 +1037,8 @@ export type BackupStatus = { music: BackupMusicProgress | null; }; -/** A save or test. An empty secret_key keeps the stored one. */ -export type BackupUpdate = Omit & { secret_key: string }; +/** A save or test. An empty secret_key keeps the stored one; clear_secret_key removes it. */ +export type BackupUpdate = Omit & { secret_key: string; clear_secret_key?: boolean }; export type BackupTestResult = { backups: number; latest: string | null }; diff --git a/web/src/lib/components/AcoustIDCard.svelte b/web/src/lib/components/AcoustIDCard.svelte index d5b245b1..51029616 100644 --- a/web/src/lib/components/AcoustIDCard.svelte +++ b/web/src/lib/components/AcoustIDCard.svelte @@ -1,4 +1,5 @@ + +
+ + {#if has} + + {/if} +
diff --git a/web/src/lib/utils/clipboard.test.ts b/web/src/lib/utils/clipboard.test.ts new file mode 100644 index 00000000..c0ae1be4 --- /dev/null +++ b/web/src/lib/utils/clipboard.test.ts @@ -0,0 +1,83 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { copyText } from './clipboard'; + +// The Clipboard API is there on a secure origin and missing over plain http. +function setClipboard(writeText: ((t: string) => Promise) | undefined) { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: writeText ? { writeText } : undefined + }); +} + +function setCopyCommand(result: boolean | undefined) { + Object.defineProperty(document, 'execCommand', { + configurable: true, + writable: true, + value: result === undefined ? undefined : vi.fn(() => result) + }); +} + +afterEach(() => { + vi.restoreAllMocks(); + window.getSelection()?.removeAllRanges(); + document.body.innerHTML = ''; +}); + +describe('copyText', () => { + it('uses the Clipboard API on a secure origin', async () => { + const writeText = vi.fn(async () => {}); + setClipboard(writeText); + setCopyCommand(false); + + expect(await copyText('token-1')).toBe(true); + expect(writeText).toHaveBeenCalledWith('token-1'); + expect(document.execCommand).not.toHaveBeenCalled(); + }); + + it('copies over plain http, where there is no Clipboard API', async () => { + setClipboard(undefined); + let copied = ''; + setCopyCommand(true); + vi.mocked(document.execCommand).mockImplementation(() => { + copied = document.querySelector('textarea')?.value ?? ''; + return true; + }); + + expect(await copyText('http://music.example.lan/playlists/1')).toBe(true); + expect(copied).toBe('http://music.example.lan/playlists/1'); + expect(document.querySelector('textarea')).toBeNull(); + }); + + it('falls back to the copy command when the Clipboard API refuses', async () => { + setClipboard(async () => Promise.reject(new Error('denied'))); + setCopyCommand(true); + + expect(await copyText('x')).toBe(true); + expect(document.execCommand).toHaveBeenCalledWith('copy'); + }); + + it('selects the shown value when nothing can copy', async () => { + setClipboard(undefined); + setCopyCommand(false); + const input = document.createElement('input'); + input.readOnly = true; + input.value = 'invite-code'; + document.body.appendChild(input); + + expect(await copyText('invite-code', input)).toBe(false); + expect(document.activeElement).toBe(input); + expect(input.selectionStart).toBe(0); + expect(input.selectionEnd).toBe('invite-code'.length); + }); + + it('selects the contents of a shown element that is not an input', async () => { + setClipboard(undefined); + setCopyCommand(undefined); + const code = document.createElement('code'); + code.textContent = '/music/library'; + document.body.appendChild(code); + + expect(await copyText('/music/library', code)).toBe(false); + expect(window.getSelection()?.getRangeAt(0).toString()).toBe('/music/library'); + }); +}); diff --git a/web/src/lib/utils/clipboard.ts b/web/src/lib/utils/clipboard.ts new file mode 100644 index 00000000..58b97a0a --- /dev/null +++ b/web/src/lib/utils/clipboard.ts @@ -0,0 +1,62 @@ +// copyText puts text on the clipboard and says whether it got there. +// +// navigator.clipboard exists only on a secure origin, and a self-hosted +// server is often reached over plain http on a home network, where it is +// undefined. So a failed or missing Clipboard API falls back to the copy +// command on a hidden textarea, which browsers still honour there. If that +// fails too and the value is on the page, `shown` is selected so a press of +// Ctrl+C or a long-press copies it. +// +// Every Copy button goes through here. Don't call navigator.clipboard directly. +export async function copyText(text: string, shown?: Element | null): Promise { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + // Denied or unfocused: try the copy command below. + } + } + if (copyByCommand(text)) return true; + if (shown) select(shown); + return false; +} + +function copyByCommand(text: string): boolean { + if (typeof document === 'undefined' || typeof document.execCommand !== 'function') return false; + const focused = document.activeElement as HTMLElement | null; + const box = document.createElement('textarea'); + box.value = text; + box.readOnly = true; + box.setAttribute('aria-hidden', 'true'); + box.style.position = 'fixed'; + box.style.top = '0'; + box.style.left = '-9999px'; + document.body.appendChild(box); + box.select(); + let ok = false; + try { + ok = document.execCommand('copy'); + } catch { + ok = false; + } + box.remove(); + focused?.focus?.(); + return ok; +} + +// select highlights a shown value: an input or textarea by its own selection, +// any other element by a range over its contents. A disabled input can't be +// selected, so a shown value sits in a readonly one. +function select(el: Element) { + if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) { + el.focus(); + el.select(); + return; + } + const range = document.createRange(); + range.selectNodeContents(el); + const sel = window.getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); +} diff --git a/web/src/routes/admin/diagnostics/+page.svelte b/web/src/routes/admin/diagnostics/+page.svelte index 783052cd..517bc31e 100644 --- a/web/src/routes/admin/diagnostics/+page.svelte +++ b/web/src/routes/admin/diagnostics/+page.svelte @@ -1,4 +1,5 @@