Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769import { afterEach, describe, expect, it, vi } from 'vitest';import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, utimesSync, writeFileSync} from 'node:fs';import { join } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { main, takeBackup, restoreBackup, verifyBackup, drillRestore, pruneUploads, dropOriginals, pruneHistory, deleteAccount, disableCaptcha, type BackupContents} from '../../../scripts/ops.mjs';import { readDrills } from '#lib/server/drills.ts';import { WORDS, createInstanceDatabase, makeRoom, readWords, writeSecret, writeWords, type InstanceRoom} from '#lib/server/backup-fixtures.ts';
/** * These tests run the whole promise: back up a live instance, check the copy, * wipe the instance, restore and read the words back. * * They run against a real SQLite file built from the real migration files, * because the failure that matters only appears against a real schema. */
const rooms: InstanceRoom[] = [];
function room(): InstanceRoom { const made = makeRoom(); rooms.push(made);
return made;}
/** A room holding a migrated database, a signing secret, and nothing else. */function populated(words = WORDS): InstanceRoom { const made = room(); createInstanceDatabase(made.databasePath, words); writeSecret(made.secretPath);
return made;}
type BackupManifest = { format: number; createdAt: string; database: { file: string; bytes: number | null; sha256: string | null }; secret: boolean; uploads: { files: number; bytes: number } | null; schema: { applied: number; newest: string | null } | null; integrity: string; contents: Record<string, number> | null;};
/** * Rewrites one backup's manifest, so a test can ask what `verify` makes of a * single field while the rest is exactly what the tool wrote. */function rewriteManifest(dir: string, change: (manifest: BackupManifest) => void) { const path = join(dir, 'manifest.json'); const manifest = JSON.parse(readFileSync(path, 'utf8')) as BackupManifest;
change(manifest); writeFileSync(path, `${JSON.stringify(manifest, null, '\t')}\n`);}
/** A populated instance whose uploads hold one file, and the backup of it. */function backupWithUploads() { const made = populated();
mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'image.webp'), 'webp-content');
const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
return { made, dir };}
afterEach(() => { vi.unstubAllEnvs();
for (const made of rooms.splice(0)) made.cleanup();});
describe('taking a backup', () => { it('restores feedback, invitations, and secret links during a drill', () => { const made = populated(); const connection = new DatabaseSync(made.databasePath); const project = connection.prepare('select id from project limit 1').get()!.id; const scene = connection.prepare('select id from scene limit 1').get()!.id; connection .prepare( 'insert into project_share (id, project_id, label, key_hash, permission, expires_at, created_at) values (?, ?, ?, ?, ?, ?, ?)' ) .run( 'share', project, 'Editor', 'a'.repeat(64), 'comment', Date.now() + 86400000, Date.now() ); connection .prepare( 'insert into project_invitation (id, project_id, user_id, role, expires_at, created_at) values (?, ?, ?, ?, ?, ?)' ) .run('invite', project, 'recipient', 'reader', Date.now() + 86400000, Date.now()); connection .prepare( 'insert into scene_feedback (id, project_id, scene_id, author, message, revision, created_at) values (?, ?, ?, ?, ?, ?, ?)' ) .run('feedback', project, scene, 'Editor', 'Keep this feedback.', 0, Date.now()); connection.close(); const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir }); expect(result.ok).toBe(true); const detail = result.checks.find((check) => check.id === 'contents')!.detail; expect(detail).toContain('1 feedback item'); expect(detail).toContain('1 secret link'); expect(detail).toContain('1 invitation'); }); it('writes the database, the secret and a manifest', () => { const made = populated(); const result = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const files = readdirSync(result.dir);
expect(files).toContain('fablewright.db'); expect(files).toContain('auth-secret'); expect(files).toContain('manifest.json'); expect(result.manifest.secret).toBe(true); expect(result.manifest.uploads).toBeNull(); expect(result.manifest.database.sha256).toMatch(/^[a-f0-9]{64}$/); });
it('writes the database alone when the deployment copies the rest itself', () => { const made = populated(); mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'image.webp'), 'webp-content');
const result = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir, databaseOnly: true }); const files = readdirSync(result.dir);
expect(files).toContain('fablewright.db'); expect(files).not.toContain('auth-secret'); expect(files).not.toContain('uploads'); expect(result.manifest.secret).toBe(false); expect(result.manifest.uploads).toBeNull(); expect(verifyBackup(result.dir).ok).toBe(true); });
it('names itself after the time and the version', () => { const made = populated(); const result = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir, now: new Date('2026-02-03T04:05:06.789Z') });
expect(result.dir).toContain('fablewright-2026-02-03T04-05-06Z-v'); expect(result.manifest.createdAt).toBe('2026-02-03T04:05:06.789Z'); });
it('records the migration level it copied', () => { const made = populated(); const result = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
expect(result.manifest.schema.applied).toBeGreaterThan(0); expect(result.manifest.schema.newest).toBe( readdirSync(join(process.cwd(), 'drizzle')) .sort() .filter((name) => name !== 'meta') .at(-1) ); expect(result.manifest.contents).toMatchObject({ projects: 1, scenes: 1, notes: 0 }); });
it('takes uploads with it when there are any', () => { const made = populated();
// The backup copies the uploads directory as it finds it, so any file there // is carried. mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'map.png'), '12345');
const result = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
expect(result.manifest.uploads).toEqual({ files: 1, bytes: 5 }); expect(existsSync(join(result.dir, 'uploads', 'map.png'))).toBe(true); });
it('keeps the number of backups it was told to keep', () => { const made = populated(); const times = ['2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z', '2026-01-03T00:00:00Z'];
for (const time of times) { takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir, now: new Date(time) }); }
const pruned = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir, now: new Date('2026-01-04T00:00:00Z'), keep: 2 });
const remaining = readdirSync(made.backupsDir).sort();
expect(remaining).toHaveLength(2); expect(remaining.at(-1)).toContain('2026-01-04'); expect(pruned.pruned).toHaveLength(2); expect(existsSync(join(made.backupsDir, pruned.pruned[0]))).toBe(false); });
it('stops when there is no database to copy', () => { const made = room();
expect(() => takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir })).toThrow( /no database/i ); expect(existsSync(made.backupsDir)).toBe(false); });});
describe('making sure a backup is sound', () => { it('passes a backup it just wrote', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const report = verifyBackup(dir);
expect(report.problems).toEqual([]); expect(report.ok).toBe(true); expect(report.integrity).toBe('ok'); expect(report.foreignKeyProblems).toBe(0); expect(report.secret).toBe(true); expect(report.contents).toMatchObject({ projects: 1, scenes: 1, notes: 0 }); });
it('passes a backup whose database a build without every table wrote', () => { // A table the writer's build did not have is recorded as null, so verify has // to accept that record. Otherwise the tool refuses a backup it just wrote. const made = populated(); const db = new DatabaseSync(made.databasePath);
db.exec('drop table import_report'); db.close();
const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const report = verifyBackup(dir);
expect(report.manifest?.contents?.importReports).toBeNull(); expect(report.problems).toEqual([]); });
it('fails a database that changed after the backup was written', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeFileSync(join(dir, 'fablewright.db'), 'not a database');
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/digest does not match/i); });
it('fails a directory that is not a backup', () => { expect(verifyBackup('/nonexistent/backup').ok).toBe(false); });
it('fails a backup that lost its uploads directory', () => { const made = populated(); mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'image.webp'), 'webp-content');
const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rmSync(join(dir, 'uploads'), { recursive: true, force: true });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.uploads).toBeNull(); expect(report.problems.join(' ')).toMatch(/no uploads directory/i); expect(() => restoreBackup({ dir, databasePath: made.databasePath, dataDir: made.dataDir }) ).toThrow(/failed its own check/i); });
it('fails a backup whose uploads no longer match the manifest', () => { const made = populated(); mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'image.webp'), 'webp-content');
const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeFileSync(join(dir, 'uploads', 'extra.webp'), 'hand-copied');
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/uploads directory holds/i); });});
describe('a crafted backup', () => { /* * A crafted backup is a well-formed directory with one field or one file that * lies. Every test here starts from a backup the tool really wrote, because that * is what an operator has when a directory reaches them from somewhere else. */
it('refuses a database outside the backup directory', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
// A real database one level up, so a joined path would find it. writeFileSync(join(dir, '..', 'outside.db'), readFileSync(made.databasePath)); rewriteManifest(dir, (manifest) => { manifest.database.file = '../outside.db'; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/not fablewright\.db/); expect(report.database).toBeNull(); });
it('refuses a manifest with no digest, rather than skipping the comparison', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeWords(join(dir, 'fablewright.db'), 'words nobody signed for'); rewriteManifest(dir, (manifest) => { manifest.database.sha256 = null; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/does not record a database digest/i); });
it('refuses a database whose size the manifest disagrees with', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rewriteManifest(dir, (manifest) => { manifest.database.bytes = 1; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/manifest says 1 B/); });
it('refuses a format this build does not read', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rewriteManifest(dir, (manifest) => { manifest.format = 2; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/format 2, not format 1/); });
it('refuses a manifest that names a secret the backup does not hold', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rmSync(join(dir, 'auth-secret'));
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.secret).toBe(false); expect(report.problems.join(' ')).toMatch(/no auth-secret file/i); });
it('refuses a secret the manifest does not name', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rewriteManifest(dir, (manifest) => { manifest.secret = false; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/does not name/i); });
it('refuses a database whose migrations cannot be read', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const db = new DatabaseSync(join(dir, 'fablewright.db'));
db.exec('drop table __drizzle_migrations'); db.close();
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/migrations could not be read/i); });
it('refuses a directory holding something a backup does not hold', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeFileSync(join(dir, 'README.md'), 'notes beside the copy');
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/README\.md is not part of a backup/); });
it('refuses uploads the manifest says are not there', () => { const { dir } = backupWithUploads();
rewriteManifest(dir, (manifest) => { manifest.uploads = null; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch( /holds no uploads, but there is an uploads directory/i ); });
it('refuses uploads the backup does not hold', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
rewriteManifest(dir, (manifest) => { manifest.uploads = { files: 2, bytes: 40 }; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/no uploads directory/i); });
// `symlinkSync` is how a crafted backup carries a link, and making one on // Windows needs a privilege a test run does not have. describe.skipIf(process.platform === 'win32')('links', () => { it('refuses a link in place of an upload', () => { const { made, dir } = backupWithUploads();
// The manifest still counts the file the tool wrote, so the only problem is // the link standing where that file should be. rmSync(join(dir, 'uploads', 'image.webp')); symlinkSync(made.secretPath, join(dir, 'uploads', 'image.webp'));
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/uploads\/image\.webp is a link/); });
it('refuses an uploads directory that is a link', () => { const made = populated(); const outside = join(made.root, 'outside-uploads');
mkdirSync(outside); writeFileSync(join(outside, 'image.webp'), 'webp-content');
const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
symlinkSync(outside, join(dir, 'uploads')); rewriteManifest(dir, (manifest) => { manifest.uploads = { files: 1, bytes: 12 }; });
const report = verifyBackup(dir);
expect(report.ok).toBe(false); expect(report.problems.join(' ')).toMatch(/uploads is a link/); });
it('leaves the instance alone when the backup holds a link', () => { const { made, dir } = backupWithUploads();
writeWords(made.databasePath, 'words that stay put'); rmSync(join(dir, 'uploads', 'image.webp')); symlinkSync(made.secretPath, join(dir, 'uploads', 'image.webp'));
expect(() => restoreBackup({ dir, databasePath: made.databasePath, dataDir: made.dataDir }) ).toThrow(/failed its own check/i); expect(readWords(made.databasePath)).toBe('words that stay put'); });
it('refuses to write uploads into a directory that is a link', () => { const { dir } = backupWithUploads(); const target = room(); const outside = join(target.root, 'outside-uploads');
mkdirSync(outside); symlinkSync(outside, join(target.dataDir, 'uploads'));
expect(() => restoreBackup({ dir, databasePath: target.databasePath, dataDir: target.dataDir }) ).toThrow(/is not a directory/i); expect(existsSync(target.databasePath)).toBe(false); });
it('refuses to back up an instance whose uploads hold a link', () => { const made = populated();
mkdirSync(made.uploadsDir); symlinkSync('/etc/hostname', join(made.uploadsDir, 'planted.webp'));
expect(() => takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir })).toThrow( /cannot be backed up/i ); expect(readdirSync(made.backupsDir)).toEqual([]); }); });});
describe('deleting an account at a shell', () => { it('notes that earlier copies can still contain deleted work', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); const now = Date.now(); db.prepare( "insert into user (id, name, email, email_verified, created_at, updated_at) values ('writer-3', 'Gone', 'gone@example.com', 0, ?, ?)" ).run(now, now); db.close(); const output = vi.spyOn(console, 'log').mockImplementation(() => {});
try { expect( main(['delete-account', '--database', made.databasePath, '--email', 'gone@example.com']) ).toBe(0); expect(output).toHaveBeenCalledWith( ' next earlier backups and project archives can still contain the deleted work.' ); } finally { output.mockRestore(); } });
it('removes the goal the account set, and keeps the project it shared', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); const now = Date.now();
// The fixture's project already belongs to `writer-1`, so this account is // the owner with a co-author: the project stays and the goal must not. db.prepare( "insert into user (id, name, email, email_verified, created_at, updated_at) values ('writer-1', 'Kat', 'kat@example.com', 0, ?, ?)" ).run(now, now); db.prepare( "insert into project_member (id, project_id, user_id, role, created_at) values ('member-1', 'project-1', 'writer-2', 'co_author', ?)" ).run(now); db.prepare( "insert into writing_goal (id, user_id, project_id, target, days_off, streak, created_at, updated_at) values ('goal-1', 'writer-1', 'project-1', 500, '0', 1, ?, ?)" ).run(now, now); db.close();
deleteAccount({ databasePath: made.databasePath, email: 'kat@example.com', deleteSharedProjects: true });
const after = new DatabaseSync(made.databasePath, { readOnly: true }); const goals = after.prepare('select count(*) as n from writing_goal').get() as { n: number }; after.close();
expect(goals.n).toBe(0); });
it('removes a passkey with the account', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); const now = Date.now();
db.prepare( "insert into user (id, name, email, email_verified, created_at, updated_at) values ('writer-4', 'Passkey owner', 'passkey@example.com', 0, ?, ?)" ).run(now, now); db.prepare( "insert into passkey (id, name, public_key, user_id, credential_id, counter, device_type, backed_up, created_at) values ('passkey-1', 'Laptop', 'not-a-real-key', 'writer-4', 'credential-1', 0, 'singleDevice', 0, ?)" ).run(now); db.close();
deleteAccount({ databasePath: made.databasePath, email: 'passkey@example.com' });
const after = new DatabaseSync(made.databasePath, { readOnly: true }); const left = after .prepare("select count(*) as n from passkey where user_id = 'writer-4'") .get() as { n: number }; after.close();
expect(left.n).toBe(0); });
it('removes a pending password-reset token with the account', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); const now = Date.now();
db.prepare( "insert into user (id, name, email, email_verified, created_at, updated_at) values ('writer-3', 'Gone', 'gone@example.com', 0, ?, ?)" ).run(now, now); db.prepare( "insert into verification (id, identifier, value, expires_at, created_at, updated_at) values ('reset-1', 'reset-password:abc', 'writer-3', ?, ?, ?)" ).run(now + 3_600_000, now, now); db.close();
deleteAccount({ databasePath: made.databasePath, email: 'gone@example.com' });
const after = new DatabaseSync(made.databasePath, { readOnly: true }); const left = after .prepare("select count(*) as n from verification where value = 'writer-3'") .get() as { n: number; }; after.close();
expect(left.n).toBe(0); });});
describe('the command line', () => { it('explains where a restore drill writes its result', () => { const output = vi.spyOn(console, 'log').mockImplementation(() => {});
try { expect(main(['--help'])).toBe(0); expect(output).toHaveBeenCalledWith( expect.stringContaining('It does not restore over the live database') ); expect(output).toHaveBeenCalledWith(expect.stringContaining('restore-drills.ndjson')); } finally { output.mockRestore(); } });
it('stops on a flag it cannot read', () => { // A wrong `--keep` must fail before it writes anything, not after. expect(main(['backup', '--keep', 'lots'])).toBe(1); expect(main(['backup', '--keep'])).toBe(1); });});
describe('restoring a backup', () => { it('puts the words back on a fresh instance', () => { const source = populated(WORDS); const { dir } = takeBackup({ databasePath: source.databasePath, dataDir: source.dataDir });
// A second instance with nothing in it: a database file that does not exist. const fresh = room(); restoreBackup({ dir, databasePath: fresh.databasePath, dataDir: fresh.dataDir });
expect(readWords(fresh.databasePath)).toBe(WORDS); expect(existsSync(fresh.secretPath)).toBe(true); });
it('keeps the database it replaced', () => { const made = populated('the words before the backup'); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeWords(made.databasePath, 'words written after the backup');
const result = restoreBackup({ dir, databasePath: made.databasePath, dataDir: made.dataDir });
expect(readWords(made.databasePath)).toBe('the words before the backup'); expect(result.previous).not.toBeNull(); expect(readWords(result.previous ?? '')).toBe('words written after the backup'); });
it('refuses a damaged backup and leaves the database alone', () => { const made = populated('words that stay put'); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeFileSync(join(dir, 'fablewright.db'), 'not a database');
expect(() => restoreBackup({ dir, databasePath: made.databasePath, dataDir: made.dataDir }) ).toThrow(/failed its own check/i); expect(readWords(made.databasePath)).toBe('words that stay put'); });
it('restores uploads when the backup holds them', () => { const source = populated(WORDS); mkdirSync(source.uploadsDir); writeFileSync(join(source.uploadsDir, 'image.webp'), 'webp-content'); writeFileSync(join(source.uploadsDir, 'image.orig'), 'orig-content');
const { dir } = takeBackup({ databasePath: source.databasePath, dataDir: source.dataDir });
const fresh = room(); const result = restoreBackup({ dir, databasePath: fresh.databasePath, dataDir: fresh.dataDir });
expect(result.uploads?.files).toBe(2); expect(existsSync(join(fresh.uploadsDir, 'image.webp'))).toBe(true); expect(existsSync(join(fresh.uploadsDir, 'image.orig'))).toBe(true); });
it('puts a database-only copy back and keeps the secret the instance already had', () => { const source = populated(WORDS); const { dir } = takeBackup({ databasePath: source.databasePath, dataDir: source.dataDir, databaseOnly: true });
const target = room(); createInstanceDatabase(target.databasePath, 'words written after the backup'); writeSecret(target.secretPath);
const result = restoreBackup({ dir, databasePath: target.databasePath, dataDir: target.dataDir });
expect(readWords(target.databasePath)).toBe(WORDS); expect(existsSync(target.secretPath)).toBe(true); expect(result.secret).toBe(false); expect(result.uploads).toBeNull(); });});
describe('drilling a restore', () => { it('restores a backup in a scratch directory and records what came back', () => { const made = populated(); const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root, now: new Date('2026-03-04T05:06:07Z') });
expect(result.checks.map((check) => check.id)).toEqual([ 'backup', 'database', 'schema', 'contents', 'words', 'secret', 'accounts', 'uploads' ]); expect(result.problems).toEqual([]); expect(result.ok).toBe(true); expect(result.checks.find((check) => check.id === 'words')?.detail).toBe( `${WORDS.split(' ').length} words in 1 scene` );
const trail = readDrills(made.dataDir);
expect(trail.count).toBe(1); expect(trail.latest?.ok).toBe(true); expect(trail.latest?.at).toBe('2026-03-04T05:06:07.000Z'); });
it('leaves the instance alone and clears the scratch directory', () => { const made = populated('words that stay where they are');
drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root });
expect(readWords(made.databasePath)).toBe('words that stay where they are'); expect(readdirSync(made.dataDir).filter((name) => name.includes('pre-restore'))).toEqual([]); expect(readdirSync(made.root).filter((name) => name.startsWith('fablewright-drill-'))).toEqual( [] ); });
it('drills a backup on a machine that has no instance yet', () => { const source = populated(); const { dir } = takeBackup({ databasePath: source.databasePath, dataDir: source.dataDir }); const clean = room();
const result = drillRestore({ dataDir: clean.dataDir, backupDir: dir, scratchDir: clean.root });
expect(result.ok).toBe(true); expect(result.source).toBeNull(); expect(result.checks[0].id).toBe('backup'); expect(readDrills(clean.dataDir).count).toBe(1); });
it('records a failure instead of throwing when the backup is damaged', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir });
writeFileSync(join(dir, 'fablewright.db'), 'not a database');
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, backupDir: dir, scratchDir: made.root });
expect(result.ok).toBe(false); expect(result.checks.map((check) => check.id)).toEqual(['backup']); expect(result.problems.join(' ')).toMatch(/digest does not match/i);
const trail = readDrills(made.dataDir);
expect(trail.latest?.ok).toBe(false); expect(trail.latest?.problems.join(' ')).toMatch(/digest does not match/i); });
it('refuses a drill that never found a backup', () => { // A mistyped path exercises no restore, so it must not leave a record saying // the instance's recovery was tried. const made = room();
expect(() => drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root }) ).toThrow(/no database/i); expect(readDrills(made.dataDir).count).toBe(0); });
it('fails a backup that holds no signing secret', () => { vi.stubEnv('BETTER_AUTH_SECRET', '');
const made = room(); createInstanceDatabase(made.databasePath);
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root });
expect(result.ok).toBe(false); expect(result.checks.find((check) => check.id === 'secret')).toMatchObject({ ok: false }); expect(result.checks.find((check) => check.id === 'secret')?.detail).toMatch( /no signing secret/i ); });
it('passes a secret the deployment keeps in the environment', () => { // A compose file or a unit file may supply the secret instead of the data // directory. The backup then holds none, and the drill says which variable // a restore depends on. vi.stubEnv('BETTER_AUTH_SECRET', 'x'.repeat(32));
const made = room(); createInstanceDatabase(made.databasePath);
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root });
expect(result.ok).toBe(true); expect(result.checks.find((check) => check.id === 'secret')?.detail).toMatch( /This host sets BETTER_AUTH_SECRET/ ); });
it('carries the images into the restored copy', () => { const made = populated(); const imageId = '44444444-4444-4444-8444-444444444444';
addImageNote(made, imageId, 5); mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, `${imageId}.webp`), 'display'); writeFileSync(join(made.uploadsDir, `${imageId}.orig`), 'orig!');
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root });
expect(result.ok).toBe(true); expect(result.checks.find((check) => check.id === 'uploads')?.detail).toMatch( /every file the database names is here/ ); expect(result.checks.find((check) => check.id === 'contents')?.detail).toContain('1 image'); });
it('fails when the database names a picture the backup does not hold', () => { const made = populated();
addImageNote(made, '55555555-5555-4555-8555-555555555555', 0);
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root });
expect(result.ok).toBe(false); expect(result.checks.find((check) => check.id === 'uploads')).toMatchObject({ ok: false }); expect(result.checks.find((check) => check.id === 'uploads')?.detail).toMatch( /holds no uploads, but the database names 1 file/ ); });
it('reports the plot grid, note types and writing rows a restore carries', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); const now = Date.now();
db.prepare( "insert into storyline (id, project_id, title, created_at, updated_at) values ('storyline-1', 'project-1', 'Main', ?, ?)" ).run(now, now); db.prepare( "insert into plot_card (id, storyline_id, scene_id, created_at, updated_at) values ('card-1', 'storyline-1', 'scene-1', ?, ?)" ).run(now, now); db.prepare( "insert into note_type (id, project_id, name, plural_name) values ('type-1', 'project-1', 'Clue', 'Clues')" ).run(); db.prepare( "insert into writing_day (id, user_id, project_id, day, words, updated_at) values ('day-1', 'writer-1', 'project-1', '2026-10-27', 120, ?)" ).run(now); db.prepare( "insert into writing_goal (id, user_id, project_id, target, days_off, created_at, updated_at) values ('goal-1', 'writer-1', 'project-1', 500, '', ?, ?)" ).run(now, now); db.close();
const result = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, scratchDir: made.root }); const detail = result.checks.find((check) => check.id === 'contents')!.detail;
expect(result.ok).toBe(true); expect(detail).toContain('1 storyline'); expect(detail).toContain('1 plot card'); expect(detail).toContain('1 note type'); expect(detail).toContain('1 writing day'); expect(detail).toContain('1 writing goal'); });
it('covers every inspected category in manifest checks and restore-drill comparisons', () => { const made = populated(); const { dir, manifest } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const baseline = { ...manifest.contents } as Record<string, number | null>; const expectedKeys: Record<keyof BackupContents, true> = { projects: true, scenes: true, notes: true, noteTypes: true, storylines: true, plotCards: true, accounts: true, passkeys: true, sceneVersions: true, itemVersions: true, checkpoints: true, images: true, feedback: true, shares: true, invitations: true, writingDays: true, writingGoals: true, importReports: true };
expect(Object.keys(baseline).sort()).toEqual(Object.keys(expectedKeys).sort());
for (const key of Object.keys(baseline) as (keyof BackupContents)[]) { rewriteManifest(dir, (copy) => { copy.contents = { ...(baseline as Record<string, number>), [key]: (baseline[key] ?? 0) + 1 }; }); const drilled = drillRestore({ databasePath: made.databasePath, dataDir: made.dataDir, backupDir: dir, scratchDir: made.root }); expect(drilled.ok, `drill mismatch for ${key}`).toBe(false); expect(drilled.checks.find((check) => check.id === 'contents')?.ok).toBe(false);
rewriteManifest(dir, (copy) => { const altered = { ...baseline } as Record<string, number>; delete altered[key]; copy.contents = altered; }); expect(verifyBackup(dir).ok, `manifest validation for ${key}`).toBe(false); } });
it('appends one line for every run through the command line', () => { const made = populated(); const argv = ['drill', '--database', made.databasePath, '--scratch', made.root];
expect(main(argv)).toBe(0); expect(main(argv)).toBe(0); expect(readDrills(made.dataDir).count).toBe(2); });
it('reports the limits of backup verification and a restore drill', () => { const made = populated(); const { dir } = takeBackup({ databasePath: made.databasePath, dataDir: made.dataDir }); const output = vi.spyOn(console, 'log').mockImplementation(() => {});
try { expect(main(['verify', '--file', dir])).toBe(0); expect(output).toHaveBeenCalledWith(`fablewright: ${dir} passed verification.`); expect(main(['drill', '--file', dir, '--database', made.databasePath])).toBe(0); expect(output).toHaveBeenCalledWith( ' next the drill did not restore over the live database. Copy the backup off this machine.' ); expect(readDrills(made.dataDir).count).toBe(1); } finally { output.mockRestore(); } });
it('does not assume a missing secret file means the environment has no secret', () => { const made = room(); createInstanceDatabase(made.databasePath, WORDS); vi.stubEnv('BETTER_AUTH_SECRET', 'a-secret-supplied-by-the-environment'); const output = vi.spyOn(console, 'log').mockImplementation(() => {});
try { expect(main(['backup', '--database', made.databasePath])).toBe(0); expect(output).toHaveBeenCalledWith( ' secret not included; keep an environment-supplied secret separately' ); } finally { output.mockRestore(); } });});
/** A note holding one image, so a drill has a file to look for. */function addImageNote(made: InstanceRoom, imageId: string, bytes: number) { const db = new DatabaseSync(made.databasePath); const now = Date.now();
db.prepare( 'insert into note (id, project_id, title, summary, body, body_text, ordinal, created_at, updated_at) values (?, ?, ?, ?, ?, ?, 0, ?, ?)' ).run('note-with-image', 'project-1', 'Map', '', '{}', '', now, now); db.prepare( 'insert into note_image (note_id, image_id, mime, bytes, width, height, alt, original_name, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?)' ).run('note-with-image', imageId, 'image/webp', bytes, 10, 10, 'alt', 'map.png', now);
db.close();}
/** * A sweep deletes a file only once it has sat on disk past the grace window, so a * spec that means "this is an orphan" has to age the file first. */function ageFile(path: string, seconds = 24 * 60 * 60) { const when = new Date(Date.now() - seconds * 1000); utimesSync(path, when, when);}
/** One note holding one image row, which is what makes an image file referenced. */function addNoteImage(made: InstanceRoom, imageId: string, bytes: number): string { const noteId = crypto.randomUUID(); const db = new DatabaseSync(made.databasePath); const now = Date.now();
db.prepare( 'insert into note (id, project_id, title, summary, body, body_text, ordinal, created_at, updated_at) values (?, ?, ?, ?, ?, ?, 0, ?, ?)' ).run(noteId, 'project-1', 'Note', '', '{}', '', now, now); db.prepare( 'insert into note_image (note_id, image_id, mime, bytes, width, height, alt, original_name, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?)' ).run(noteId, imageId, 'image/png', bytes, 10, 10, 'alt', 'pic.png', now);
db.close(); return noteId;}
function imageBytes(made: InstanceRoom, noteId: string): number { const db = new DatabaseSync(made.databasePath); const row = db.prepare('select bytes from note_image where note_id = ?').get(noteId) as { bytes: number; }; db.close();
return row.bytes;}
describe('pruning uploads', () => { it('identifies unreferenced files and does not delete in dry-run', () => { const made = populated(); mkdirSync(made.uploadsDir);
const imageId = '11111111-1111-4111-8111-111111111111'; addNoteImage(made, imageId, 100);
writeFileSync(join(made.uploadsDir, `${imageId}.webp`), 'referenced'); writeFileSync(join(made.uploadsDir, 'orphan.webp'), 'orphan'); writeFileSync(join(made.uploadsDir, 'temp.tmp'), 'tmp'); for (const name of [`${imageId}.webp`, 'orphan.webp', 'temp.tmp']) { ageFile(join(made.uploadsDir, name)); }
const dryRun = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: false }); expect(dryRun.totalFiles).toBe(3); expect(dryRun.referencedFiles).toBe(1); expect(dryRun.unreferencedFiles).toBe(2); expect(dryRun.recentFiles).toBe(0); expect(dryRun.removedFiles).toBe(0); expect(existsSync(join(made.uploadsDir, 'orphan.webp'))).toBe(true);
const applied = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.removedFiles).toBe(2); expect(existsSync(join(made.uploadsDir, 'orphan.webp'))).toBe(false); expect(existsSync(join(made.uploadsDir, 'temp.tmp'))).toBe(false); expect(existsSync(join(made.uploadsDir, `${imageId}.webp`))).toBe(true); });
/** * The app renames a file into place and commits the row that names it a moment * later, so a sweep that trusted the row set alone would delete a live upload. */ it('leaves a file alone until the grace window has passed', () => { const made = populated(); mkdirSync(made.uploadsDir); const orphan = join(made.uploadsDir, 'orphan.webp'); writeFileSync(orphan, 'just published');
const held = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(held.unreferencedFiles).toBe(1); expect(held.recentFiles).toBe(1); expect(held.removedFiles).toBe(0); expect(existsSync(orphan)).toBe(true);
// A window of zero is a sweep an operator asks for with the app stopped. const swept = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true, graceMs: 0 }); expect(swept.removedFiles).toBe(1); expect(existsSync(orphan)).toBe(false); });
it('leaves a staging copy that an upload is about to rename into place', () => { const made = populated(); mkdirSync(made.uploadsDir); const staging = join(made.uploadsDir, '.11111111-1111-4111-8111-111111111111.webp.tmp'); writeFileSync(staging, 'half-written');
const held = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(held.removedFiles).toBe(0); expect(existsSync(staging)).toBe(true);
// Nothing can read a staging copy, so one this old is a crashed upload. ageFile(staging); const swept = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(swept.removedFiles).toBe(1); expect(existsSync(staging)).toBe(false); });
it('keeps the file an import report names and reclaims the one it does not', () => { const made = populated(); const importsDir = join(made.uploadsDir, 'imports'); mkdirSync(importsDir, { recursive: true });
const kept = '22222222-2222-4222-8222-222222222222.md'; const orphan = '33333333-3333-4333-8333-333333333333.docx'; writeFileSync(join(importsDir, kept), 'kept'); writeFileSync(join(importsDir, orphan), 'orphan'); ageFile(join(importsDir, kept)); ageFile(join(importsDir, orphan));
const db = new DatabaseSync(made.databasePath); db.prepare( 'insert into import_report (id, project_id, format, source_name, source_bytes, source_sha256, source_id, source_mime, proposed, chapters, scenes, words, notes, notices, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, null, 0, 0, 0, 0, ?, ?)' ).run( crypto.randomUUID(), 'project-1', 'markdown', 'draft.md', 4, 'a'.repeat(64), kept, 'text/markdown; charset=utf-8', '[]', Date.now() ); db.close();
const dryRun = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir }); expect(dryRun.totalFiles).toBe(2); expect(dryRun.referencedFiles).toBe(1); expect(dryRun.unreferencedFiles).toBe(1); expect(existsSync(join(importsDir, orphan))).toBe(true);
const applied = pruneUploads({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.removedFiles).toBe(1); expect(existsSync(join(importsDir, kept))).toBe(true); expect(existsSync(join(importsDir, orphan))).toBe(false); });
it('drops originals and zeroes bytes in db when apply is true', () => { const made = populated(); mkdirSync(made.uploadsDir);
const imageId = '22222222-2222-4222-8222-222222222222'; const noteId = addNoteImage(made, imageId, 500);
writeFileSync(join(made.uploadsDir, `${imageId}.webp`), 'display-copy'); writeFileSync(join(made.uploadsDir, `${imageId}.orig`), 'original-copy'); ageFile(join(made.uploadsDir, `${imageId}.webp`)); ageFile(join(made.uploadsDir, `${imageId}.orig`));
const dryRun = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: false }); expect(dryRun.totalOriginals).toBe(1); expect(dryRun.droppableOriginals).toBe(1); expect(dryRun.droppedOriginals).toBe(0); expect(existsSync(join(made.uploadsDir, `${imageId}.orig`))).toBe(true);
const applied = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.droppedOriginals).toBe(1); expect(existsSync(join(made.uploadsDir, `${imageId}.orig`))).toBe(false); expect(existsSync(join(made.uploadsDir, `${imageId}.webp`))).toBe(true); // display copy untouched expect(imageBytes(made, noteId)).toBe(0); });
/** * The display copy is renamed into place first. Without it the original is the * only copy of the image, so dropping it would throw the picture away. */ it('keeps an original whose display copy is missing', () => { const made = populated(); mkdirSync(made.uploadsDir);
const imageId = '33333333-3333-4333-8333-333333333333'; const noteId = addNoteImage(made, imageId, 500); const original = join(made.uploadsDir, `${imageId}.orig`); writeFileSync(original, 'the only copy left'); ageFile(original);
const dryRun = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: false }); expect(dryRun.totalOriginals).toBe(1); expect(dryRun.droppableOriginals).toBe(0); expect(dryRun.keptOriginals).toBe(1);
const applied = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.droppedOriginals).toBe(0); expect(existsSync(original)).toBe(true); expect(imageBytes(made, noteId)).toBe(500); });
/** A deletion that fails must leave the row claiming the file it still has. */ it.skipIf(process.getuid?.() === 0)('reports an original it could not delete', () => { const made = populated(); mkdirSync(made.uploadsDir);
const imageId = '44444444-4444-4444-8444-444444444444'; const noteId = addNoteImage(made, imageId, 500); writeFileSync(join(made.uploadsDir, `${imageId}.webp`), 'display-copy'); writeFileSync(join(made.uploadsDir, `${imageId}.orig`), 'original-copy'); ageFile(join(made.uploadsDir, `${imageId}.webp`)); ageFile(join(made.uploadsDir, `${imageId}.orig`));
chmodSync(made.uploadsDir, 0o555); try { const applied = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.droppedOriginals).toBe(0); expect(applied.failedFiles).toHaveLength(1); } finally { chmodSync(made.uploadsDir, 0o755); }
expect(existsSync(join(made.uploadsDir, `${imageId}.orig`))).toBe(true); expect(imageBytes(made, noteId)).toBe(500); });
it('clears a claim whose original the disk has already lost', () => { const made = populated(); mkdirSync(made.uploadsDir);
const imageId = '55555555-5555-4555-8555-555555555555'; const noteId = addNoteImage(made, imageId, 500); writeFileSync(join(made.uploadsDir, `${imageId}.webp`), 'display-copy');
const applied = dropOriginals({ databasePath: made.databasePath, dataDir: made.dataDir, apply: true }); expect(applied.missingOriginals).toBe(1); expect(imageBytes(made, noteId)).toBe(0); });
it('handles CLI prune-uploads and --originals commands', () => { const made = populated(); mkdirSync(made.uploadsDir); writeFileSync(join(made.uploadsDir, 'trash.tmp'), 'junk'); ageFile(join(made.uploadsDir, 'trash.tmp'));
expect(main(['prune-uploads', '--database', made.databasePath])).toBe(0); expect(existsSync(join(made.uploadsDir, 'trash.tmp'))).toBe(true);
expect(main(['prune-uploads', '--database', made.databasePath, '--apply'])).toBe(0); expect(existsSync(join(made.uploadsDir, 'trash.tmp'))).toBe(false);
// Anything the app published a moment ago is still inside the window. writeFileSync(join(made.uploadsDir, 'fresh.webp'), 'just published'); expect(main(['prune-uploads', '--database', made.databasePath, '--apply'])).toBe(0); expect(existsSync(join(made.uploadsDir, 'fresh.webp'))).toBe(true); expect( main(['prune-uploads', '--database', made.databasePath, '--grace', '0', '--apply']) ).toBe(0); expect(existsSync(join(made.uploadsDir, 'fresh.webp'))).toBe(false);
expect(main(['prune-uploads', '--database', made.databasePath, '--grace', 'soon'])).toBe(1);
writeFileSync(join(made.uploadsDir, 'pic.webp'), 'display'); writeFileSync(join(made.uploadsDir, 'pic.orig'), 'raw-bytes'); // An original with no display copy beside it is the only copy of its image. writeFileSync(join(made.uploadsDir, 'lonely.orig'), 'raw-bytes'); for (const name of ['pic.webp', 'pic.orig', 'lonely.orig']) { ageFile(join(made.uploadsDir, name)); }
expect(main(['prune-uploads', '--originals', '--database', made.databasePath])).toBe(0); expect(existsSync(join(made.uploadsDir, 'pic.orig'))).toBe(true);
expect(main(['prune-uploads', '--originals', '--database', made.databasePath, '--apply'])).toBe( 0 ); expect(existsSync(join(made.uploadsDir, 'pic.orig'))).toBe(false); expect(existsSync(join(made.uploadsDir, 'lonely.orig'))).toBe(true); });});
// History grows without anybody asking, so the tool that trims it runs against the real schema.const HISTORY_NOW = new Date('2026-06-01T00:00:00.000Z');const HISTORY_OLD = new Date('2025-01-01T00:00:00.000Z');
type HistorySeed = { auto?: number; /** A version the writer saved by hand and named. */ named?: boolean; /** A version the writer saved by hand and left unnamed. */ manual?: boolean; /** A conflict version a guest save left behind, labelled with the link. */ guested?: boolean; /** A pre-split or pre-merge structural safeguard on a scene. */ structuredScene?: boolean; /** Old note versions, one entry per note id. */ notes?: number[]; /** Versions taken before a structural change. */ structural?: number; /** An old project version saved by hand. */ savedProject?: boolean; /** Characters of prose in each scene version, so a vacuum has work to do. */ bodySize?: number;};
/** Fills the database with history, oldest row first. */function seedHistory(path: string, seed: HistorySeed) { const db = new DatabaseSync(path); const body = '{}'.padEnd(seed.bodySize ?? 2, 'x'); const stamp = (index: number) => HISTORY_OLD.getTime() + index * 60_000; const scene = db.prepare( 'insert into scene_snapshot (id, scene_id, body, body_text, word_count, label, source, created_at) values (?, ?, ?, ?, 1, ?, ?, ?)' ); const project = db.prepare( 'insert into project_checkpoint (id, project_id, label, source, manuscript, created_at) values (?, ?, ?, ?, ?, ?)' ); let index = 0;
// The versions the writer asked for sit oldest, past the floor, so only the // rule that protects them can save them. A name only ever lands on a version // the writer saved by hand, which is what marks it. if (seed.guested) { scene.run( crypto.randomUUID(), 'scene-1', body, 'words', 'Before guest edit: Beta reader', 'conflict', stamp(index) ); index += 1; } if (seed.structuredScene) { scene.run( crypto.randomUUID(), 'scene-1', body, 'words', 'Before splitting the scene', 'structure', stamp(index) ); index += 1; } if (seed.named) { scene.run( crypto.randomUUID(), 'scene-1', body, 'words', 'The good draft', 'manual', stamp(index) ); index += 1; } if (seed.manual) { scene.run(crypto.randomUUID(), 'scene-1', body, 'words', null, 'manual', stamp(index)); index += 1; } for (let count = 0; count < (seed.auto ?? 0); count += 1) { scene.run(crypto.randomUUID(), 'scene-1', body, 'words', null, 'auto', stamp(index)); index += 1; }
if (seed.savedProject) { project.run(crypto.randomUUID(), 'project-1', 'Revision two', 'manual', '{}', stamp(index)); index += 1; } for (let count = 0; count < (seed.structural ?? 0); count += 1) { project.run( crypto.randomUUID(), 'project-1', 'Before a change', 'structure', '{}', stamp(index) ); index += 1; }
for (const [noteIndex, versions] of (seed.notes ?? []).entries()) { for (let count = 0; count < versions; count += 1) { db.prepare( 'insert into item_version (id, project_id, kind, item_id, title, summary, body, body_text, source, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ).run( crypto.randomUUID(), 'project-1', 'note', `note-${noteIndex}`, 'Note', '', '{}', 'words', 'edit', stamp(index) ); index += 1; } }
db.close();}
function rowsIn(path: string, table: string): number { const db = new DatabaseSync(path, { readOnly: true });
try { return Number((db.prepare(`select count(*) as n from ${table}`).get() as { n: number }).n ?? 0); } finally { db.close(); }}
function rowsWithSource(path: string, table: string, source: string): number { const db = new DatabaseSync(path, { readOnly: true });
try { const row = db.prepare(`select count(*) as n from ${table} where source = ?`).get(source) as { n: number; };
return Number(row.n ?? 0); } finally { db.close(); }}
/** Sets the retention window the way the admin page does. */function setWindow(path: string, days: number) { const db = new DatabaseSync(path); db.prepare('update instance_setting set history_retention_days = ? where id = 1').run(days); db.close();}
describe('pruning history', () => { it('reports what it would remove and deletes nothing without apply', () => { const made = populated(); seedHistory(made.databasePath, { auto: 21, named: true, manual: true });
const dry = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW });
// 23 rows: the newest 20 stay, one automatic version past them is due, and // the named and hand-saved versions are protected. expect(dry).toMatchObject({ days: 365, cutoff: '2025-06-01T00:00:00.000Z', sceneVersions: 1, itemVersions: 0, projectVersions: 0, removed: false, held: { sceneVersions: 23, itemVersions: 0, projectVersions: 0 } }); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(23);
const applied = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true });
expect(applied.sceneVersions).toBe(1); expect(applied.removed).toBe(true); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(22); });
it('removes the versions the writer asked for only with --all', () => { const made = populated(); seedHistory(made.databasePath, { auto: 21, named: true, manual: true });
pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true }); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(22);
const all = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true, includeKept: true });
expect(all.sceneVersions).toBe(2); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(20); });
it('removes conflict and structural scene safeguards while keeping explicit bookmarks', () => { const made = populated(); seedHistory(made.databasePath, { auto: 21, guested: true, structuredScene: true, named: true });
const result = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true });
// Structural safeguards and guest edits carry labels, yet only `manual` bookmarks stay protected. expect(result.sceneVersions).toBe(3); expect(rowsWithSource(made.databasePath, 'scene_snapshot', 'conflict')).toBe(0); expect(rowsWithSource(made.databasePath, 'scene_snapshot', 'structure')).toBe(0); expect(rowsWithSource(made.databasePath, 'scene_snapshot', 'manual')).toBe(1); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(21); });
it('prunes note versions and structural project versions, keeping the newest of each item', () => { const made = populated(); seedHistory(made.databasePath, { notes: [22, 3], structural: 7, savedProject: true });
const result = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true });
expect(result.itemVersions).toBe(2); expect(result.projectVersions).toBe(2); expect(rowsIn(made.databasePath, 'item_version')).toBe(23); expect(rowsIn(made.databasePath, 'project_checkpoint')).toBe(6); });
it('reads the window from the instance setting', () => { const made = populated(); seedHistory(made.databasePath, { auto: 21 }); setWindow(made.databasePath, 3650);
expect(pruneHistory({ databasePath: made.databasePath, now: HISTORY_NOW }).sceneVersions).toBe( 0 );
setWindow(made.databasePath, 30);
const result = pruneHistory({ databasePath: made.databasePath, now: HISTORY_NOW, apply: true });
expect(result.days).toBe(30); expect(result.sceneVersions).toBe(1); });
it('keeps everything when the window is zero', () => { const made = populated(); seedHistory(made.databasePath, { auto: 21 }); setWindow(made.databasePath, 0);
const result = pruneHistory({ databasePath: made.databasePath, now: HISTORY_NOW, apply: true });
expect(result).toMatchObject({ days: 0, cutoff: null, sceneVersions: 0 }); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(21); });
it('gives the space back when a vacuum is asked for', () => { const made = populated(); seedHistory(made.databasePath, { auto: 40, bodySize: 40_000 });
const result = pruneHistory({ databasePath: made.databasePath, days: 365, now: HISTORY_NOW, apply: true, vacuum: true });
expect(result.sceneVersions).toBe(20); expect(result.reclaimedBytes).toBeGreaterThan(0); expect(result.bytesAfter).toBeLessThan(result.bytesBefore); });
it('runs from the command line, and refuses a window that is not a day count', () => { const made = populated(); seedHistory(made.databasePath, { auto: 22 });
expect(main(['prune-history', '--database', made.databasePath, '--days', '365'])).toBe(0); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(22);
expect(main(['prune-history', '--database', made.databasePath, '--days', 'soon'])).toBe(1); expect(main(['prune-history', '--database', made.databasePath, '--days', '365'])).toBe(0); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(22);
expect( main(['prune-history', '--database', made.databasePath, '--days', '365', '--apply']) ).toBe(0); expect(rowsIn(made.databasePath, 'scene_snapshot')).toBe(20); });});
describe('disabling CAPTCHA offline', () => { it('resets an active provider to none and leaves an already-disabled instance untouched', () => { const made = populated(); const db = new DatabaseSync(made.databasePath); db.prepare( "update instance_setting set captcha_provider = 'hecapte', captcha_site_key = 'k', captcha_secret_key = 's' where id = 1" ).run(); db.close();
expect(disableCaptcha({ databasePath: made.databasePath })).toEqual({ previous: 'hecapte', changed: true });
const check = new DatabaseSync(made.databasePath, { readOnly: true }); const row = check .prepare('select captcha_provider, captcha_secret_key from instance_setting where id = 1') .get() as { captcha_provider: string; captcha_secret_key: string }; check.close(); expect(row.captcha_provider).toBe('none'); expect(row.captcha_secret_key).toBe('');
expect(disableCaptcha({ databasePath: made.databasePath })).toEqual({ previous: 'none', changed: false }); expect(main(['disable-captcha', '--database', made.databasePath])).toBe(0); });});