fix(sessions): carry the signed-in sessions across a demo reset and a restore

Both swap the whole database file. The demo reset copies a baseline
saved at first seed, before anyone logged in, so it brings back an empty
user_sessions table; a backup restore brings the backup's own rows, or
none for a backup from before sessions were tracked. A session token
whose row is missing is refused, so the hourly reset signed every demo
visitor and the demo admin out, and the admin who ran a restore got a
401 on the next request. Before session tracking only the password
version applied, and those tokens survived.

Both paths now read the active rows with their owner's email before the
swap and put them back after the reopen, in a fresh fork, for every
account the new file still holds under the same id and email. A row the
new file already has is left as it is, so a session that ended there
stays ended, and a session whose id now names somebody else (a backup
from another install) is dropped instead of handed to them. The password
version check still refuses a token the restored account no longer
matches. Reading or writing them is best effort and never fails the
reset or the restore.
This commit is contained in:
Maurice
2026-10-08 17:24:26 +02:00
parent 9aab9e7513
commit 474beb0dfb
9 changed files with 379 additions and 0 deletions
@@ -146,4 +146,61 @@ describe('UserSessionsRepository', () => {
testDb.prepare('DELETE FROM users WHERE id = ?').run(user.id);
expect(row('s1')).toBeUndefined();
});
it('SESSREPO-010: listActiveToCarry reads every active session with the email of its owner', async () => {
const { user } = createUser(testDb, { email: 'carry-a@example.test' });
const { user: other } = createUser(testDb, { email: 'carry-b@example.test' });
await add('a1', user.id, { user_agent: 'A' });
await add('b1', other.id);
await add('expired', user.id, { expires_at: NOW });
await add('revoked', other.id);
testDb.prepare("UPDATE user_sessions SET revoked_at = ? WHERE id = 'revoked'").run(EARLIER);
expect(await sessions.listActiveToCarry(NOW)).toEqual([
{ id: 'a1', user_id: user.id, email: 'carry-a@example.test', created_at: EARLIER, last_seen_at: EARLIER, expires_at: LATER, user_agent: 'A' },
{ id: 'b1', user_id: other.id, email: 'carry-b@example.test', created_at: EARLIER, last_seen_at: EARLIER, expires_at: LATER, user_agent: null },
]);
expect(await sessions.listActiveToCarry(LATER)).toEqual([]);
});
it('SESSREPO-011: restoreCarried puts the rows back for the same account only, and keeps a row already there', async () => {
const { user } = createUser(testDb, { email: 'kept@example.test' });
const { user: renamed } = createUser(testDb, { email: 'renamed@example.test' });
await add('kept', user.id, { user_agent: 'Kept' });
await add('present', user.id);
await add('elsewhere', renamed.id);
const carried = await sessions.listActiveToCarry(NOW);
// What a swap does: the rows are gone (or ended), and one id now names somebody else.
testDb.prepare("DELETE FROM user_sessions WHERE id IN ('kept', 'elsewhere')").run();
testDb.prepare("UPDATE user_sessions SET revoked_at = ? WHERE id = 'present'").run(EARLIER);
testDb.prepare("UPDATE users SET email = 'someone-else@example.test' WHERE id = ?").run(renamed.id);
t.clear();
expect(await sessions.restoreCarried(carried)).toBe(2);
expect(row('kept')).toStrictEqual({
id: 'kept',
user_id: user.id,
created_at: EARLIER,
last_seen_at: EARLIER,
expires_at: LATER,
revoked_at: null,
user_agent: 'Kept',
});
// The swapped-in file's own row wins, ended or not.
expect(row('present')).toEqual(expect.objectContaining({ revoked_at: EARLIER }));
expect(row('elsewhere')).toBeUndefined();
});
it('SESSREPO-012: restoreCarried drops a session whose user is gone, and does nothing for none', async () => {
const { user } = createUser(testDb, { email: 'gone@example.test' });
await add('orphan', user.id);
const carried = await sessions.listActiveToCarry(NOW);
testDb.prepare('DELETE FROM users WHERE id = ?').run(user.id);
t.clear();
expect(await sessions.restoreCarried(carried)).toBe(0);
expect(row('orphan')).toBeUndefined();
expect(await sessions.restoreCarried([])).toBe(0);
});
});
@@ -0,0 +1,120 @@
/**
* The hourly demo reset keeps everybody signed in.
*
* The reset copies the baseline over the live database file. That baseline
* was saved at first seed, before anybody logged in, so it holds no
* `user_sessions` rows, and a session token whose row is gone is refused.
* Without carrying the active rows across the swap, every demo visitor and
* the demo admin would get a 401 on the hour.
*
* The connection lifecycle is stubbed the way demo-reset-path.test.ts stubs
* it, and the stubbed `reinitialize()` stands in for the file swap by
* emptying `user_sessions`, which is exactly what the baseline brings back.
* The reads and writes around it run for real against the snapshot schema.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import type Database from 'better-sqlite3';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { createUser } from '../../helpers/factories';
import { withRequestContext } from '../../../src/nest/database/request-context';
const LIVE_DB = path.join(path.sep, 'srv', 'trek', 'travel.db');
const { handleStub, swap, databaseModule } = vi.hoisted(() => {
const handleStub = { name: '' };
const swap: { run: () => void } = { run: () => undefined };
return {
handleStub,
swap,
databaseModule: {
getRawConnection: () => handleStub,
closeDb: vi.fn(),
reinitialize: vi.fn(async () => {
swap.run();
}),
},
};
});
vi.mock('../../../src/db/database', () => databaseModule);
const BASELINE = path.resolve(__dirname, '..', '..', '..', 'data', 'travel-baseline.db');
import { resetDemoUser } from '../../../src/demo/demo-reset';
import { SessionsService } from '../../../src/nest/sessions/sessions.service';
import { verifyJwtAndLoadUser } from '../../../src/nest/auth/jwt-verify';
import { Users } from '../../../src/db/entities/Users.entity';
import { UserSessions } from '../../../src/db/entities/UserSessions.entity';
describe('demo reset and the signed-in sessions', () => {
let ormDb: Database.Database;
let t: TestOrm;
beforeEach(async () => {
handleStub.name = LIVE_DB;
vi.spyOn(console, 'log').mockImplementation(() => undefined);
ormDb = createSnapshotTestDb();
t = await createTestOrm(ormDb);
swap.run = () => {
ormDb.exec('DELETE FROM user_sessions');
};
vi.spyOn(fs, 'copyFileSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'unlinkSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE) as typeof fs.existsSync);
});
afterEach(async () => {
vi.restoreAllMocks();
await t.close();
ormDb.close();
});
const verify = (token: string) => verifyJwtAndLoadUser(token, t.repo(Users), t.repo(UserSessions));
it('DEMORESET-SESS-001: a session signed in before the reset still authenticates after it', async () => {
const { user } = createUser(ormDb, { email: 'demo-visitor@example.test' });
const sessions = new SessionsService(t.repo(UserSessions));
const token = await sessions.issue({ id: user.id, pv: 0 }, undefined, { userAgent: 'Visitor' });
expect((await verify(token))?.id).toBe(user.id);
await withRequestContext(t.orm, () => resetDemoUser());
t.clear();
expect(databaseModule.reinitialize).toHaveBeenCalled();
expect((await verify(token))?.id).toBe(user.id);
expect(ormDb.prepare('SELECT user_id, user_agent, revoked_at FROM user_sessions').all()).toEqual([
{ user_id: user.id, user_agent: 'Visitor', revoked_at: null },
]);
});
it('DEMORESET-SESS-002: a session that had already ended stays ended', async () => {
const { user } = createUser(ormDb, { email: 'demo-ended@example.test' });
const sessions = new SessionsService(t.repo(UserSessions));
const token = await sessions.issue({ id: user.id, pv: 0 });
await sessions.revokeAll(user.id);
await withRequestContext(t.orm, () => resetDemoUser());
t.clear();
expect(await verify(token)).toBeNull();
expect(ormDb.prepare('SELECT COUNT(*) AS n FROM user_sessions').get()).toEqual({ n: 0 });
});
it('DEMORESET-SESS-003: a session whose account the baseline does not hold is not brought back', async () => {
const { user } = createUser(ormDb, { email: 'registered-after-seed@example.test' });
const sessions = new SessionsService(t.repo(UserSessions));
const token = await sessions.issue({ id: user.id, pv: 0 });
swap.run = () => {
ormDb.exec('DELETE FROM user_sessions');
ormDb.prepare('DELETE FROM users WHERE id = ?').run(user.id);
};
await withRequestContext(t.orm, () => resetDemoUser());
t.clear();
expect(await verify(token)).toBeNull();
expect(ormDb.prepare('SELECT COUNT(*) AS n FROM user_sessions').get()).toEqual({ n: 0 });
});
});
@@ -1385,6 +1385,63 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
expect(dbMock.closeDb).toHaveBeenCalled();
});
it('BACKUP-045i: the sessions signed in before the restore are put back after the reopen', async () => {
setupSuccessfulExtraction();
setupAllTablesPresent();
const callOrder: string[] = [];
const carried = [{ id: 'sess-1', user_id: 1, email: 'admin@example.test', created_at: 'a', last_seen_at: 'b', expires_at: 'c', user_agent: null }];
const sessionsRepo = {
listActiveToCarry: vi.fn(async () => { callOrder.push('read'); return carried; }),
restoreCarried: vi.fn(async () => { callOrder.push('restore'); return 1; }),
};
const { RequestContext } = await import('@mikro-orm/core');
const em = vi.spyOn(RequestContext, 'getEntityManager').mockReturnValue({ getRepository: () => sessionsRepo } as never);
const fork = vi.spyOn(RequestContext, 'create').mockImplementation(((_em: unknown, next: () => unknown) => next()) as never);
onTestFinished(() => { em.mockRestore(); fork.mockRestore(); });
dbMock.closeDb.mockImplementation(() => { callOrder.push('closeDb'); });
dbMock.reinitialize.mockImplementation(() => { callOrder.push('reinitialize'); });
fsMock.unlinkSync.mockReturnValue(undefined);
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads') && !String(p).endsWith('.encryption_key'));
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
expect(callOrder).toEqual(['read', 'closeDb', 'reinitialize', 'restore']);
expect(sessionsRepo.restoreCarried).toHaveBeenCalledWith(carried);
// Put back in a fresh fork, not through the one that read the replaced file.
expect(fork).toHaveBeenCalledTimes(1);
});
it('BACKUP-045j: sessions that cannot be read or put back do not fail the restore', async () => {
setupSuccessfulExtraction();
setupAllTablesPresent();
const sessionsRepo = {
listActiveToCarry: vi.fn().mockRejectedValueOnce(new Error('no such table: user_sessions')).mockResolvedValueOnce([{ id: 's' }]),
restoreCarried: vi.fn().mockRejectedValue(new Error('database is locked')),
};
const { RequestContext } = await import('@mikro-orm/core');
const em = vi.spyOn(RequestContext, 'getEntityManager').mockReturnValue({ getRepository: () => sessionsRepo } as never);
const fork = vi.spyOn(RequestContext, 'create').mockImplementation(((_em: unknown, next: () => unknown) => next()) as never);
onTestFinished(() => { em.mockRestore(); fork.mockRestore(); });
fsMock.unlinkSync.mockReturnValue(undefined);
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads') && !String(p).endsWith('.encryption_key'));
const unreadable = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
expect(unreadable).toEqual({ success: true });
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('could not read the active sessions (no such table: user_sessions)'));
expect(sessionsRepo.restoreCarried).not.toHaveBeenCalled();
setupSuccessfulExtraction();
setupAllTablesPresent();
const unwritable = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
expect(unwritable).toEqual({ success: true });
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('could not keep the active sessions (database is locked)'));
});
it('BACKUP-045c — reinitialize is called even when copyFileSync throws', async () => {
setupSuccessfulExtraction();
setupAllTablesPresent();