feat: a new Minstrel restores a backup, from the web app or the command line, then rescans (#6775)
release / govulncheck (push) Successful in 29s
release / web (push) Failing after 1m21s
release / go (push) Successful in 1m39s
release / integration (push) Successful in 5m26s
release / android (push) Successful in 5m27s
release / Build signed APK (push) Successful in 5m44s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped

A new server (no accounts, no library) offers "Restore a backup" beside
"Create account". The file goes up as the request body to
POST /api/auth/restore with the setup token from the log in X-Setup-Token,
since the backup's admins become this server's. It loads in one transaction,
then a library scan starts and finds each file at its path. The same load runs
offline as `minstrel restore FILE`, which migrates the schema first.

That path alone gets a 1 GiB, 15-minute body allowance instead of 4 MiB and
30s, and skips the JSON-only check for cookie writes: a stale cookie from the
old server would otherwise refuse the upload, and the custom header already
rules out a cross-site form.

The library sync answers 410 cursor_ahead to a cursor past the last one the
server has handed out, read from the change sequence, so an app synced with
the old server after the backup was made starts over instead of skipping the
ids the restored server reuses. Restore now leaves each sequence as having
issued the restored maximum, so that reading holds; a compacted log still
counts its handed-out cursors.

backup.Read keeps the underlying error in its chain, so an oversized upload
answers 413 rather than "not a backup". The hosting docs say how to put the
music back first and what is entered again afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 16:10:06 -05:00
co-authored by Claude Opus 5.5
parent 5090c89d20
commit 29042e4eb2
19 changed files with 607 additions and 13 deletions
+15 -1
View File
@@ -1,4 +1,4 @@
import { api, type User, type LoginResponse } from '#lib/api/client.js';
import { api, apiFetch, type User, type LoginResponse } from '#lib/api/client.js';
import { putMyTimezone } from '#lib/api/me.js';
import { queryClient } from '#lib/query/client.js';
import { signalSessionEnd } from './sessionEnd.svelte';
@@ -75,6 +75,20 @@ export async function register(opts: {
void sendTimezoneIfStale();
}
export type RestoreResult = { accounts: number; scan_started: boolean };
/**
* Loads a backup file into a new server, which has no accounts yet. The file
* is the request body; the setup token from the server log goes in a header.
*/
export async function restoreBackup(file: Blob, setupToken: string): Promise<RestoreResult> {
return (await apiFetch('/api/auth/restore', {
method: 'POST',
body: file,
headers: { 'Content-Type': 'application/x-tar', 'X-Setup-Token': setupToken }
})) as RestoreResult;
}
export async function forgotPassword(email: string): Promise<void> {
await api.post('/api/auth/forgot-password', { email });
}
@@ -0,0 +1,94 @@
<script lang="ts">
import { restoreBackup, type RestoreResult } from '#lib/auth/store.svelte.js';
import { errCode } from '#lib/api/errors.js';
import { plural } from '#lib/utils/plural.js';
// A new server can start from a backup instead of a new admin account. It
// asks for the same setup token as the first account, since the backup's
// admins become this server's.
let file = $state<File | null>(null);
let setupToken = $state('');
let restoring = $state(false);
let error = $state<string | null>(null);
let done = $state<RestoreResult | null>(null);
function messageFor(code: string): string {
switch (code) {
case 'setup_token_invalid':
return "That setup token doesn't match. Copy it from the server log; it changes each time the server restarts.";
case 'not_a_backup':
return "That file isn't a Minstrel backup. Choose a minstrel-….tar file from the backup's database folder.";
case 'newer_backup':
return 'That backup was made by a newer Minstrel. Update this server first, then restore it.';
case 'not_empty':
return 'This server already has accounts or a library, so it can’t take a backup.';
case 'too_large':
return 'That file is larger than a backup can be.';
default:
return 'The restore failed. Please try again.';
}
}
async function handleSubmit(e: SubmitEvent) {
e.preventDefault();
if (restoring || !file) return;
error = null;
restoring = true;
try {
done = await restoreBackup(file, setupToken.trim());
} catch (err: unknown) {
error = messageFor(errCode(err));
} finally {
restoring = false;
}
}
const field = 'w-full rounded border border-border bg-background px-3 py-2 outline-hidden focus:border-accent';
</script>
{#if done}
<div class="space-y-3" role="status" data-testid="restore-done">
<p class="text-sm text-text-primary">
Restored {plural(done.accounts, 'account', 'accounts')}. Sign in with the password you had.
</p>
<p class="text-sm text-text-secondary">
{done.scan_started
? 'The library scan has started: it finds each music file and fetches the artwork and tags again.'
: 'Start a library scan under Admin › Library once you’re signed in.'}
</p>
<a href="/login" class="block w-full rounded bg-accent px-3 py-2 text-center font-medium text-background">Sign in</a>
</div>
{:else}
<form class="space-y-4" onsubmit={handleSubmit}>
<label class="block">
<span class="mb-1 block text-sm text-text-secondary">Backup file</span>
<input
type="file"
accept=".tar,application/x-tar"
required
class="{field} text-sm"
onchange={(e) => (file = (e.currentTarget as HTMLInputElement).files?.[0] ?? null)}
/>
<span class="mt-1 block text-xs text-text-secondary">
A minstrel-….tar file from the backup's database folder. Copy the music back into the library folder first.
</span>
</label>
<label class="block">
<span class="mb-1 block text-sm text-text-secondary">Setup token</span>
<input type="text" autocomplete="off" spellcheck="false" required class="{field} font-mono" bind:value={setupToken} />
<span class="mt-1 block text-xs text-text-secondary">Printed in the server log (look for "setup_token").</span>
</label>
<button
type="submit"
class="w-full rounded bg-accent px-3 py-2 font-medium text-background disabled:opacity-60"
aria-busy={restoring ? 'true' : undefined}
disabled={restoring || !file}
>
{restoring ? 'Restoring…' : 'Restore'}
</button>
{#if error}
<p role="alert" class="text-sm text-danger">{error}</p>
{/if}
</form>
{/if}
+22 -1
View File
@@ -5,6 +5,7 @@
import { getSetupStatus, register } from '#lib/auth/store.svelte.js';
import { errCode } from '#lib/api/errors.js';
import { rateLimitMessage } from '#lib/api/client.js';
import RestoreForm from '#lib/components/auth/RestoreForm.svelte';
let username = $state('');
let password = $state('');
@@ -14,6 +15,8 @@
// True on a brand-new server: the first account becomes admin and must
// carry the setup token from the server log.
let setupRequired = $state(false);
// A new server can instead start from a backup of another Minstrel.
let restoring = $state(false);
onMount(async () => {
try {
@@ -76,7 +79,24 @@
<main class="flex min-h-screen items-center justify-center bg-background text-text-primary">
<div class="w-full max-w-sm rounded-lg border border-border bg-surface p-6 shadow-sm">
<h1 class="mb-6 text-center text-2xl font-semibold">Create account</h1>
<h1 class="mb-6 text-center text-2xl font-semibold">{restoring ? 'Restore a backup' : 'Create account'}</h1>
{#if setupRequired}
<p class="mb-4 text-center text-sm text-text-secondary">
{#if restoring}
<button type="button" class="text-accent-fg hover:underline" onclick={() => (restoring = false)}>
Create a new admin account instead
</button>
{:else}
Moving from another Minstrel?
<button type="button" class="text-accent-fg hover:underline" onclick={() => (restoring = true)}>
Restore a backup
</button>
{/if}
</p>
{/if}
{#if restoring}
<RestoreForm />
{:else}
<form class="space-y-4" onsubmit={handleSubmit}>
<label class="block">
<span class="mb-1 block text-sm text-text-secondary">Username</span>
@@ -167,6 +187,7 @@
<p role="alert" class="text-sm text-danger">{error}</p>
{/if}
</form>
{/if}
<p class="mt-4 text-center text-sm text-text-secondary">
Already have an account?
+41 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { render, screen, fireEvent, waitFor, within } from '@testing-library/svelte';
vi.mock('#lib/branding.js', () => ({
pageTitle: (s: string) => `${s} · Minstrel`
@@ -11,12 +11,13 @@ vi.mock('$app/navigation', () => ({
vi.mock('#lib/auth/store.svelte.js', () => ({
register: vi.fn(),
restoreBackup: vi.fn(),
getSetupStatus: vi.fn().mockResolvedValue({ setup_required: false }),
user: { value: null }
}));
import RegisterPage from './+page.svelte';
import { getSetupStatus, register } from '#lib/auth/store.svelte.js';
import { getSetupStatus, register, restoreBackup } from '#lib/auth/store.svelte.js';
import { goto } from '$app/navigation';
afterEach(() => {
@@ -156,4 +157,42 @@ describe('/register page', () => {
const link = screen.getByRole('link', { name: /sign in/i });
expect(link).toHaveAttribute('href', '/login');
});
test('only a new server offers to restore a backup', async () => {
render(RegisterPage);
await waitFor(() => expect(getSetupStatus).toHaveBeenCalled());
expect(screen.queryByRole('button', { name: /restore a backup/i })).toBeNull();
});
test('a new server restores a backup with the setup token, then sends you to sign in', async () => {
(getSetupStatus as ReturnType<typeof vi.fn>).mockResolvedValue({ setup_required: true });
(restoreBackup as ReturnType<typeof vi.fn>).mockResolvedValue({ accounts: 2, scan_started: true });
render(RegisterPage);
await fireEvent.click(await screen.findByRole('button', { name: /restore a backup/i }));
expect(screen.getByRole('heading', { name: /restore a backup/i })).toBeInTheDocument();
expect(screen.queryByLabelText(/username/i)).toBeNull();
const file = new File(['tar'], 'minstrel-20261102T030000Z.tar', { type: 'application/x-tar' });
await fireEvent.change(screen.getByLabelText(/backup file/i), { target: { files: [file] } });
await fireEvent.input(screen.getByLabelText(/setup token/i), { target: { value: ' 0123abcd ' } });
await fireEvent.click(screen.getByRole('button', { name: /^restore$/i }));
await waitFor(() => expect(restoreBackup).toHaveBeenCalledWith(file, '0123abcd'));
const done = await screen.findByTestId('restore-done');
expect(done.textContent).toMatch(/Restored 2 accounts\. Sign in with the password you had\./);
expect(done.textContent).toMatch(/library scan has started/);
expect(within(done).getByRole('link', { name: /^sign in$/i })).toHaveAttribute('href', '/login');
});
test('a file that is not a backup says so', async () => {
(getSetupStatus as ReturnType<typeof vi.fn>).mockResolvedValue({ setup_required: true });
(restoreBackup as ReturnType<typeof vi.fn>).mockRejectedValue({ code: 'not_a_backup', status: 400 });
render(RegisterPage);
await fireEvent.click(await screen.findByRole('button', { name: /restore a backup/i }));
const file = new File(['x'], 'notes.txt');
await fireEvent.change(screen.getByLabelText(/backup file/i), { target: { files: [file] } });
await fireEvent.input(screen.getByLabelText(/setup token/i), { target: { value: 'tok' } });
await fireEvent.click(screen.getByRole('button', { name: /^restore$/i }));
expect((await screen.findByRole('alert')).textContent).toMatch(/isn't a Minstrel backup/);
});
});