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 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
// 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) {
|
func (h *handlers) handleUpdateBackups(w http.ResponseWriter, r *http.Request) {
|
||||||
u, ok := decodeBackupUpdate(w, r)
|
u, ok := decodeBackupUpdate(w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ type updateSMTPConfigReq struct {
|
|||||||
FromAddress string `json:"from_address"`
|
FromAddress string `json:"from_address"`
|
||||||
FromName string `json:"from_name"`
|
FromName string `json:"from_name"`
|
||||||
UseTLS bool `json:"use_tls"`
|
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) {
|
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
|
// Preserve the stored (sealed) password when the request sends "", so
|
||||||
// the admin doesn't have to re-enter it on every save.
|
// the admin doesn't have to re-enter it on every save.
|
||||||
password := current.Password
|
password := current.Password
|
||||||
|
if req.ClearPassword {
|
||||||
|
password = ""
|
||||||
|
}
|
||||||
if req.Password != "" {
|
if req.Password != "" {
|
||||||
password, err = secret.Seal(secret.SMTPPassword.Purpose(), "", req.Password)
|
password, err = secret.Seal(secret.SMTPPassword.Purpose(), "", req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
"github.com/Fabled-Sword/minstrel/internal/auth"
|
"github.com/Fabled-Sword/minstrel/internal/auth"
|
||||||
|
"github.com/Fabled-Sword/minstrel/internal/dbtest"
|
||||||
)
|
)
|
||||||
|
|
||||||
func newAdminSMTPRouter(h *handlers) chi.Router {
|
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) {
|
func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) {
|
||||||
h, pool := testHandlers(t)
|
h, pool := testHandlers(t)
|
||||||
admin := seedUser(t, pool, "smtpvalid", "pw", true)
|
admin := seedUser(t, pool, "smtpvalid", "pw", true)
|
||||||
|
|||||||
@@ -99,7 +99,8 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update is a save from the admin card. An empty SecretKey keeps the stored
|
// 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 {
|
type Update struct {
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
Destination string `json:"destination"`
|
Destination string `json:"destination"`
|
||||||
@@ -108,6 +109,7 @@ type Update struct {
|
|||||||
Bucket string `json:"bucket"`
|
Bucket string `json:"bucket"`
|
||||||
AccessKey string `json:"access_key"`
|
AccessKey string `json:"access_key"`
|
||||||
SecretKey string `json:"secret_key"`
|
SecretKey string `json:"secret_key"`
|
||||||
|
ClearSecretKey bool `json:"clear_secret_key"`
|
||||||
RunHour int `json:"run_hour"`
|
RunHour int `json:"run_hour"`
|
||||||
UploadLimitKiB int `json:"upload_limit_kib"`
|
UploadLimitKiB int `json:"upload_limit_kib"`
|
||||||
IncludeMusic bool `json:"include_music"`
|
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.RunHour = int16(u.RunHour)
|
||||||
st.UploadLimitKib = int32(u.UploadLimitKiB)
|
st.UploadLimitKib = int32(u.UploadLimitKiB)
|
||||||
st.IncludeMusic = u.IncludeMusic
|
st.IncludeMusic = u.IncludeMusic
|
||||||
|
if u.ClearSecretKey {
|
||||||
|
st.SecretKey = ""
|
||||||
|
}
|
||||||
if u.SecretKey != "" {
|
if u.SecretKey != "" {
|
||||||
sealed, err := secret.Seal(secret.BackupSecretKey.Purpose(), "", u.SecretKey)
|
sealed, err := secret.Seal(secret.BackupSecretKey.Purpose(), "", u.SecretKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -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) {
|
func TestThrottleKeepsToItsRate(t *testing.T) {
|
||||||
data := bytes.Repeat([]byte("x"), 20*1024)
|
data := bytes.Repeat([]byte("x"), 20*1024)
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|||||||
@@ -658,7 +658,8 @@ export async function getSMTPConfig(): Promise<SMTPConfig> {
|
|||||||
return api.get<SMTPConfig>('/api/admin/smtp-config');
|
return api.get<SMTPConfig>('/api/admin/smtp-config');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateSMTPConfig(input: SMTPConfig): Promise<void> {
|
/** A save. An empty password keeps the stored one; clear_password removes it. */
|
||||||
|
export async function updateSMTPConfig(input: SMTPConfig & { clear_password?: boolean }): Promise<void> {
|
||||||
await api.put('/api/admin/smtp-config', input);
|
await api.put('/api/admin/smtp-config', input);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1036,8 +1037,8 @@ export type BackupStatus = {
|
|||||||
music: BackupMusicProgress | null;
|
music: BackupMusicProgress | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** A save or test. An empty secret_key keeps the stored one. */
|
/** A save or test. An empty secret_key keeps the stored one; clear_secret_key removes it. */
|
||||||
export type BackupUpdate = Omit<BackupConfig, 'has_secret_key'> & { secret_key: string };
|
export type BackupUpdate = Omit<BackupConfig, 'has_secret_key'> & { secret_key: string; clear_secret_key?: boolean };
|
||||||
|
|
||||||
export type BackupTestResult = { backups: number; latest: string | null };
|
export type BackupTestResult = { backups: number; latest: string | null };
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import SecretField from '#lib/components/settings/SecretField.svelte';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import {
|
import {
|
||||||
getAcoustID,
|
getAcoustID,
|
||||||
@@ -157,17 +158,7 @@
|
|||||||
>Register an application</a
|
>Register an application</a
|
||||||
>
|
>
|
||||||
{/snippet}
|
{/snippet}
|
||||||
<input
|
<SecretField id="acoustid-key" has={overview.settings.api_key_set} bind:value={keyInput} remove={forgetKey} disabled={saving} class="w-40" />
|
||||||
id="acoustid-key"
|
|
||||||
type="password"
|
|
||||||
autocomplete="off"
|
|
||||||
bind:value={keyInput}
|
|
||||||
placeholder={overview.settings.api_key_set ? 'Key saved' : 'Paste key'}
|
|
||||||
class="{field} w-40 font-mono"
|
|
||||||
/>
|
|
||||||
{#if overview.settings.api_key_set}
|
|
||||||
<button type="button" class={button} disabled={saving} onclick={forgetKey}>Remove</button>
|
|
||||||
{/if}
|
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="Minimum score" for="acoustid-score" hint="How sure AcoustID must be, 0.5 to 1.">
|
<SettingRow label="Minimum score" for="acoustid-score" hint="How sure AcoustID must be, 0.5 to 1.">
|
||||||
<input id="acoustid-score" type="number" min="0.5" max="1" step="0.01" bind:value={minScore} class="{field} w-24" />
|
<input id="acoustid-score" type="number" min="0.5" max="1" step="0.01" bind:value={minScore} class="{field} w-24" />
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ describe("AcoustIDCard", () => {
|
|||||||
await renderCard();
|
await renderCard();
|
||||||
const key = screen.getByLabelText(/api key/i) as HTMLInputElement;
|
const key = screen.getByLabelText(/api key/i) as HTMLInputElement;
|
||||||
expect(key.value).toBe("");
|
expect(key.value).toBe("");
|
||||||
expect(key.placeholder).toBe("Key saved");
|
expect(key.placeholder).toBe("Key saved · leave empty to keep it");
|
||||||
expect(saveButton()).toHaveProperty("disabled", true);
|
expect(saveButton()).toHaveProperty("disabled", true);
|
||||||
|
|
||||||
await fireEvent.input(
|
await fireEvent.input(
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ describe('BackupPanel', () => {
|
|||||||
await renderPanel();
|
await renderPanel();
|
||||||
const key = screen.getByLabelText(/secret key/i) as HTMLInputElement;
|
const key = screen.getByLabelText(/secret key/i) as HTMLInputElement;
|
||||||
expect(key.value).toBe('');
|
expect(key.value).toBe('');
|
||||||
expect(key.placeholder).toBe('Key saved');
|
expect(key.placeholder).toBe('Key saved · leave empty to keep it');
|
||||||
const save = screen.getByRole('button', { name: /^save$/i });
|
const save = screen.getByRole('button', { name: /^save$/i });
|
||||||
expect(save).toHaveProperty('disabled', true);
|
expect(save).toHaveProperty('disabled', true);
|
||||||
|
|
||||||
@@ -165,6 +165,18 @@ describe('BackupPanel', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Remove takes the saved secret key away, and leaves the rest as saved', async () => {
|
||||||
|
vi.mocked(saveBackups).mockResolvedValue(base);
|
||||||
|
await renderPanel();
|
||||||
|
await fireEvent.input(screen.getByLabelText(/^bucket$/i), { target: { value: 'not-saved-yet' } });
|
||||||
|
await fireEvent.click(screen.getByRole('button', { name: /^remove$/i }));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(saveBackups).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ bucket: base.config.bucket, secret_key: '', clear_secret_key: true })
|
||||||
|
)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test('Test destination checks the form as typed and says what it found', async () => {
|
test('Test destination checks the form as typed and says what it found', async () => {
|
||||||
vi.mocked(testBackups).mockResolvedValue({ backups: 3, latest: '2026-11-02T03:00:05Z' });
|
vi.mocked(testBackups).mockResolvedValue({ backups: 3, latest: '2026-11-02T03:00:05Z' });
|
||||||
await renderPanel();
|
await renderPanel();
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import SecretField from '#lib/components/settings/SecretField.svelte';
|
||||||
import {
|
import {
|
||||||
saveBackups,
|
saveBackups,
|
||||||
testBackups,
|
testBackups,
|
||||||
@@ -67,6 +68,17 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Removes only the secret key: the saved settings go back as they are, so
|
||||||
|
// unsaved edits elsewhere on the card stay unsaved.
|
||||||
|
async function removeKey() {
|
||||||
|
try {
|
||||||
|
onsaved(await saveBackups({ ...fromConfig(config), secret_key: '', clear_secret_key: true }));
|
||||||
|
pushToast('Secret key removed.');
|
||||||
|
} catch (e) {
|
||||||
|
pushToast(errMessage(e), 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function test() {
|
async function test() {
|
||||||
testing = true;
|
testing = true;
|
||||||
check = null;
|
check = null;
|
||||||
@@ -138,14 +150,7 @@
|
|||||||
<input id="backup-access-key" bind:value={draft.access_key} autocomplete="off" spellcheck="false" class="{field} w-56 font-mono" />
|
<input id="backup-access-key" bind:value={draft.access_key} autocomplete="off" spellcheck="false" class="{field} w-56 font-mono" />
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="Secret key" for="backup-secret-key" hint="Kept encrypted on the server.">
|
<SettingRow label="Secret key" for="backup-secret-key" hint="Kept encrypted on the server.">
|
||||||
<input
|
<SecretField id="backup-secret-key" has={config.has_secret_key} bind:value={secretKey} remove={removeKey} disabled={saving} />
|
||||||
id="backup-secret-key"
|
|
||||||
type="password"
|
|
||||||
autocomplete="new-password"
|
|
||||||
bind:value={secretKey}
|
|
||||||
placeholder={config.has_secret_key ? 'Key saved' : 'Paste key'}
|
|
||||||
class="{field} w-56 font-mono"
|
|
||||||
/>
|
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="Upload limit" for="backup-limit" hint="KiB a second, so an upload leaves room on the connection. 0 is no limit.">
|
<SettingRow label="Upload limit" for="backup-limit" hint="KiB a second, so an upload leaves room on the connection. 0 is no limit.">
|
||||||
<input id="backup-limit" type="number" min="0" step="256" bind:value={draft.upload_limit_kib} class="{field} w-28" />
|
<input id="backup-limit" type="number" min="0" step="256" bind:value={draft.upload_limit_kib} class="{field} w-28" />
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import type { Snippet } from 'svelte';
|
import type { Snippet } from 'svelte';
|
||||||
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
|
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
|
||||||
import SettingRow from '#lib/components/settings/SettingRow.svelte';
|
import SettingRow from '#lib/components/settings/SettingRow.svelte';
|
||||||
|
import SecretField from '#lib/components/settings/SecretField.svelte';
|
||||||
import { errMessage } from '#lib/api/errors.js';
|
import { errMessage } from '#lib/api/errors.js';
|
||||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||||
|
|
||||||
@@ -98,6 +99,17 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An empty key removes the saved one on the server.
|
||||||
|
async function onRemoveKey(p: P) {
|
||||||
|
try {
|
||||||
|
await save(p.id, { api_key: '' });
|
||||||
|
// A test result for the old key no longer says anything.
|
||||||
|
delete results[p.id];
|
||||||
|
} catch (e) {
|
||||||
|
pushToast(`Couldn't remove the key for ${p.display_name}: ${errMessage(e)}`, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function onTest(p: P) {
|
async function onTest(p: P) {
|
||||||
testing[p.id] = true;
|
testing[p.id] = true;
|
||||||
try {
|
try {
|
||||||
@@ -135,12 +147,14 @@
|
|||||||
{#if l}
|
{#if l}
|
||||||
<div class="flex flex-wrap items-center gap-2 px-4 pb-3">
|
<div class="flex flex-wrap items-center gap-2 px-4 pb-3">
|
||||||
{#if p.requires_api_key}
|
{#if p.requires_api_key}
|
||||||
<input
|
<SecretField
|
||||||
type="password"
|
label="{p.display_name} API key"
|
||||||
aria-label="{p.display_name} API key"
|
has={p.api_key_set}
|
||||||
placeholder={p.api_key_set ? 'Key saved · leave empty to keep it' : keyPlaceholder}
|
placeholder={p.api_key_set ? undefined : keyPlaceholder}
|
||||||
bind:value={l.apiKey}
|
bind:value={l.apiKey}
|
||||||
class="w-64 max-w-full rounded-md border border-border bg-background px-3 py-1.5 text-sm"
|
remove={() => onRemoveKey(p)}
|
||||||
|
disabled={saving[p.id]}
|
||||||
|
class="w-64"
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import SecretField from '#lib/components/settings/SecretField.svelte';
|
||||||
import { useQueryClient } from '@tanstack/svelte-query';
|
import { useQueryClient } from '@tanstack/svelte-query';
|
||||||
import { createSMTPConfigQuery, updateSMTPConfig, testSMTPConfig, type SMTPConfig } from '#lib/api/admin.js';
|
import { createSMTPConfigQuery, updateSMTPConfig, testSMTPConfig, type SMTPConfig } from '#lib/api/admin.js';
|
||||||
import { qk } from '#lib/api/queries.js';
|
import { qk } from '#lib/api/queries.js';
|
||||||
@@ -45,6 +46,19 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Removes only the password: the saved settings go back as they are, so
|
||||||
|
// unsaved edits elsewhere on the card stay unsaved.
|
||||||
|
async function onRemovePassword() {
|
||||||
|
if (!smtpQ.data) return;
|
||||||
|
try {
|
||||||
|
await updateSMTPConfig({ ...smtpQ.data, password: '', clear_password: true });
|
||||||
|
await client.invalidateQueries({ queryKey: qk.smtpConfig() });
|
||||||
|
pushToast('Email password removed.');
|
||||||
|
} catch (e: unknown) {
|
||||||
|
pushToast(`Not removed: ${errMessage(e)}`, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function onSave() {
|
async function onSave() {
|
||||||
saving = true;
|
saving = true;
|
||||||
try {
|
try {
|
||||||
@@ -116,12 +130,14 @@
|
|||||||
<input id="smtp-username" type="text" bind:value={form.username} class={field} />
|
<input id="smtp-username" type="text" bind:value={form.username} class={field} />
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="Password" for="smtp-password">
|
<SettingRow label="Password" for="smtp-password">
|
||||||
<input
|
<SecretField
|
||||||
id="smtp-password"
|
id="smtp-password"
|
||||||
type="password"
|
noun="password"
|
||||||
placeholder={form.password === '***' ? 'Saved · leave empty to keep it' : ''}
|
has={smtpQ.data?.password === '***'}
|
||||||
bind:value={passwordInput}
|
bind:value={passwordInput}
|
||||||
class={field}
|
remove={onRemovePassword}
|
||||||
|
disabled={!loaded || saving}
|
||||||
|
class="w-64"
|
||||||
/>
|
/>
|
||||||
</SettingRow>
|
</SettingRow>
|
||||||
<SettingRow label="From address" for="smtp-from">
|
<SettingRow label="From address" for="smtp-from">
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// A credential the server keeps and never sends back: an API key or a
|
||||||
|
// password. The box holds a new value for the card's own Save to send, and
|
||||||
|
// is empty while a saved one is kept. Remove takes the saved one away at
|
||||||
|
// once, so a key that was pasted by mistake, or belongs to an account
|
||||||
|
// that's gone, doesn't have to stay.
|
||||||
|
//
|
||||||
|
// `remove` does the request and reports its own failure; the button is busy
|
||||||
|
// until it settles.
|
||||||
|
|
||||||
|
let {
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
has,
|
||||||
|
value = $bindable(''),
|
||||||
|
remove,
|
||||||
|
noun = 'key',
|
||||||
|
placeholder,
|
||||||
|
disabled = false,
|
||||||
|
class: cls = 'w-56'
|
||||||
|
}: {
|
||||||
|
id?: string;
|
||||||
|
// The box's accessible name, when no visible label names it.
|
||||||
|
label?: string;
|
||||||
|
// Whether a value is saved now.
|
||||||
|
has: boolean;
|
||||||
|
value?: string;
|
||||||
|
remove: () => Promise<unknown>;
|
||||||
|
noun?: 'key' | 'password';
|
||||||
|
placeholder?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
class?: string;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let removing = $state(false);
|
||||||
|
|
||||||
|
async function onRemove() {
|
||||||
|
removing = true;
|
||||||
|
try {
|
||||||
|
await remove();
|
||||||
|
} finally {
|
||||||
|
removing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<input
|
||||||
|
{id}
|
||||||
|
type="password"
|
||||||
|
autocomplete="new-password"
|
||||||
|
spellcheck="false"
|
||||||
|
aria-label={label}
|
||||||
|
bind:value
|
||||||
|
{disabled}
|
||||||
|
placeholder={placeholder ?? (has ? `${noun === 'key' ? 'Key' : 'Password'} saved · leave empty to keep it` : `Paste the ${noun}`)}
|
||||||
|
class="{cls} max-w-full rounded-md border border-border bg-background px-3 py-1.5 font-mono text-sm"
|
||||||
|
/>
|
||||||
|
{#if has}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={disabled || removing}
|
||||||
|
onclick={onRemove}
|
||||||
|
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||||
|
>{removing ? 'Removing…' : 'Remove'}</button
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -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<void>) | 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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<boolean> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import { pageTitle } from '#lib/branding.js';
|
import { pageTitle } from '#lib/branding.js';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||||
@@ -162,11 +163,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onCopyJson() {
|
async function onCopyJson() {
|
||||||
try {
|
if (await copyText(JSON.stringify(exportObject(), null, 2))) {
|
||||||
await navigator.clipboard.writeText(JSON.stringify(exportObject(), null, 2));
|
|
||||||
pushToast(`Copied ${rows.length} events to clipboard`);
|
pushToast(`Copied ${rows.length} events to clipboard`);
|
||||||
} catch (e: unknown) {
|
} else {
|
||||||
pushToast(`Copy failed: ${errMessage(e)}`, 'error');
|
pushToast('Copy failed. Download the events instead.', 'error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import { PASSWORD_MIN_LENGTH, PASSWORDS_DIFFER } from '#lib/auth/password.js';
|
import { PASSWORD_MIN_LENGTH, PASSWORDS_DIFFER } from '#lib/auth/password.js';
|
||||||
import { knownCopy } from '#lib/api/error-copy.js';
|
import { knownCopy } from '#lib/api/error-copy.js';
|
||||||
import { plural } from '#lib/utils/plural.js';
|
import { plural } from '#lib/utils/plural.js';
|
||||||
@@ -185,12 +186,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function copyToken(token: string) {
|
async function copyToken(token: string) {
|
||||||
try {
|
if (await copyText(token)) pushToast('Token copied to clipboard.');
|
||||||
await navigator.clipboard.writeText(token);
|
else pushToast('Copy failed — select the token and copy manually.', 'error');
|
||||||
pushToast('Token copied to clipboard.');
|
|
||||||
} catch {
|
|
||||||
pushToast('Copy failed — select the token and copy manually.', 'error');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(iso: string): string {
|
function formatDate(iso: string): string {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import Cover from '#lib/components/Cover.svelte';
|
import Cover from '#lib/components/Cover.svelte';
|
||||||
import { plural } from '#lib/utils/plural.js';
|
import { plural } from '#lib/utils/plural.js';
|
||||||
import { pageTitle } from '#lib/branding.js';
|
import { pageTitle } from '#lib/branding.js';
|
||||||
@@ -73,7 +74,7 @@
|
|||||||
try {
|
try {
|
||||||
const res = await fetch(MISSING_FILES_CSV_URL, { credentials: 'same-origin', signal: AbortSignal.timeout(15_000) });
|
const res = await fetch(MISSING_FILES_CSV_URL, { credentials: 'same-origin', signal: AbortSignal.timeout(15_000) });
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||||
await navigator.clipboard.writeText(await res.text());
|
if (!(await copyText(await res.text()))) throw new Error('this browser refused to copy');
|
||||||
pushToast(`Copied ${plural(total, 'track', 'tracks')}`);
|
pushToast(`Copied ${plural(total, 'track', 'tracks')}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
pushToast(`Couldn't copy the list: ${errMessage(e)}`, 'error');
|
pushToast(`Couldn't copy the list: ${errMessage(e)}`, 'error');
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import Cover from '#lib/components/Cover.svelte';
|
import Cover from '#lib/components/Cover.svelte';
|
||||||
import { plural } from '#lib/utils/plural.js';
|
import { plural } from '#lib/utils/plural.js';
|
||||||
import { pageTitle } from '#lib/branding.js';
|
import { pageTitle } from '#lib/branding.js';
|
||||||
@@ -97,12 +98,8 @@
|
|||||||
at: x.occurred_at
|
at: x.occurred_at
|
||||||
}))
|
}))
|
||||||
};
|
};
|
||||||
try {
|
if (await copyText(JSON.stringify(payload, null, 2))) pushToast('Copied the details');
|
||||||
await navigator.clipboard.writeText(JSON.stringify(payload, null, 2));
|
else pushToast('Copy failed: this browser refused to copy', 'error');
|
||||||
pushToast('Copied the details');
|
|
||||||
} catch (e) {
|
|
||||||
pushToast(`Copy failed: ${errMessage(e)}`, 'error');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onPlay(r: ReportRow) {
|
async function onPlay(r: ReportRow) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import { plural } from '#lib/utils/plural.js';
|
import { plural } from '#lib/utils/plural.js';
|
||||||
import PageColumn from '#lib/components/PageColumn.svelte';
|
import PageColumn from '#lib/components/PageColumn.svelte';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
@@ -178,12 +179,11 @@
|
|||||||
|
|
||||||
async function onCopyLink() {
|
async function onCopyLink() {
|
||||||
const href = `${window.location.origin}/playlists/${id}`;
|
const href = `${window.location.origin}/playlists/${id}`;
|
||||||
try {
|
if (await copyText(href)) {
|
||||||
await navigator.clipboard.writeText(href);
|
|
||||||
pushToast('Link copied to clipboard.');
|
pushToast('Link copied to clipboard.');
|
||||||
} catch {
|
} else {
|
||||||
// navigator.clipboard fails in insecure contexts and older browsers.
|
// Nothing could copy, and the link isn't on the page: show it in a
|
||||||
// Fall back to selecting the link in a prompt so the user can copy.
|
// prompt, where it is selected ready to copy.
|
||||||
window.prompt('Copy the playlist link:', href);
|
window.prompt('Copy the playlist link:', href);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { copyText } from '#lib/utils/clipboard.js';
|
||||||
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
|
import SettingsLoadStatus from '#lib/components/settings/SettingsLoadStatus.svelte';
|
||||||
import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte';
|
import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
@@ -144,12 +145,8 @@
|
|||||||
|
|
||||||
async function copy(text: string | null) {
|
async function copy(text: string | null) {
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
try {
|
if (await copyText(text)) pushToast('Copied to clipboard.');
|
||||||
await navigator.clipboard.writeText(text);
|
else pushToast('Copy failed. Select it and copy it yourself.', 'error');
|
||||||
pushToast('Copied to clipboard.');
|
|
||||||
} catch {
|
|
||||||
pushToast('Copy failed.', 'error');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user