Files
RedditBot/tests/reddit-accounts-service.test.ts
T
Jamie BruntonandClaude Opus 5 a9cea7ed18 Retire removed accounts instead of deleting them
Removing an account had no path at all, so a dead session could only be
left running or hand-edited out of the database. The first cut deleted the
account and everything it owned, which threw away conversations and media
that are worth keeping.

Retire instead: keep the row and every row it produced, destroy the stored
cookies and Matrix token. Wiping the credentials is what makes sending and
syncing impossible rather than merely disabled — isEnabledAccount requires
a verified status, so no runtime ever starts, and no session survives for
anything to use. setActive, markLoginRequired and the background credential
refresh now skip retired accounts so none of them quietly revives one;
re-importing a session deliberately does.

Keeping the content visible needed more than keeping the rows. Conversations
and media are only served from running runtimes, so a retired account's
history would have disappeared from the dashboard regardless. Media already
reads the account content table for every listed account. Conversations now
have an archive path that reads the stored ActiveChat payloads directly.

Every write path refuses a retired conversation with a 409: send-reply,
both suggest endpoints, share-media, shareable-media and all read-state
writes. Lazy-loading detail is skipped too — the fallback chat service
belongs to a different account, so it would sync the wrong session and
write the wrong cache. Archived detail derives conversation state from the
transcript alone for the same reason.

Migration 32 rebuilds reddit_accounts to admit the new status, with foreign
keys off and a foreign_key_check before they are restored, as migration 11
does. Two migration tests rewound user_version by counting back from the
head, which silently breaks whenever a migration is appended; they now
target absolute versions.

Conversations never opened before removal keep only their summary. Message
history is lazy-loaded on first open and there is no session left to fetch
the rest with.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 08:58:22 +01:00

120 lines
4.2 KiB
TypeScript

import Database from 'better-sqlite3';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { RedditAccountsRepository } from '../src/database/account-repositories.js';
import { runMigrations } from '../src/database/client.js';
import { AccountAuthContext } from '../src/services/account-auth-context.js';
import { RedditAccountsService } from '../src/services/reddit-accounts.js';
const silentLogger = {
info: () => undefined,
warn: () => undefined,
error: () => undefined,
debug: () => undefined,
} as never;
describe('removing a Reddit account', () => {
let db: Database.Database;
let accounts: RedditAccountsRepository;
let auth: AccountAuthContext;
let stopped: string[];
let service: RedditAccountsService;
beforeEach(() => {
db = new Database(':memory:');
db.pragma('foreign_keys = ON');
runMigrations(db);
accounts = new RedditAccountsRepository(db);
auth = new AccountAuthContext(silentLogger);
stopped = [];
const runtimes = {
get: () => null,
stop: async (accountId: string) => { stopped.push(accountId); },
};
service = new RedditAccountsService(
accounts,
{ import: async () => { throw new Error('not used'); } } as never,
auth,
runtimes as never,
);
accounts.upsertVerified({
accountId: 't2_alice',
redditUsername: 'alice-bot',
matrixUserId: '@t2_alice:reddit.com',
cookiesJson: JSON.stringify([{ name: 'reddit_session', value: 'secret' }]),
matrixCredentialsJson: JSON.stringify({ accessToken: 'matrix-secret' }),
now: 100,
});
});
afterEach(() => db.close());
it('stops the runtime and destroys the session while keeping the account', async () => {
const removed = await service.remove('t2_alice');
expect(stopped).toEqual(['t2_alice']);
expect(removed).toMatchObject({
accountId: 't2_alice',
redditUsername: 'alice-bot',
isRunning: false,
status: 'removed',
});
// Retired, not deleted: the row survives so its content keeps an owner.
expect(accounts.get('t2_alice')).toMatchObject({
status: 'removed', cookiesJson: '[]', matrixCredentialsJson: '{}',
});
expect(service.list().map((account) => account.accountId)).toEqual(['t2_alice']);
expect(service.listRemoved().map((account) => account.accountId)).toEqual(['t2_alice']);
});
it('refuses to remove an account twice', async () => {
await service.remove('t2_alice');
stopped = [];
await expect(service.remove('t2_alice')).rejects.toThrow('Reddit account was already removed');
expect(stopped).toEqual([]);
});
it('drops the authenticated session when the removed account held it', async () => {
auth.markAuthenticated({
accountId: 't2_alice',
redditUsername: 'alice-bot',
matrixUserId: '@t2_alice:reddit.com',
});
expect(auth.getSnapshot().accountId).toBe('t2_alice');
await service.remove('t2_alice');
expect(auth.getSnapshot()).toMatchObject({ status: 'login-required', accountId: null });
});
it('leaves another account\'s session alone', async () => {
accounts.upsertVerified({
accountId: 't2_bob',
redditUsername: 'bob-bot',
matrixUserId: '@t2_bob:reddit.com',
cookiesJson: JSON.stringify([{ name: 'reddit_session', value: 'bob-secret' }]),
matrixCredentialsJson: JSON.stringify({ accessToken: 'bob-matrix-secret' }),
now: 110,
});
auth.markAuthenticated({
accountId: 't2_bob',
redditUsername: 'bob-bot',
matrixUserId: '@t2_bob:reddit.com',
});
await service.remove('t2_alice');
expect(auth.getSnapshot()).toMatchObject({ status: 'authenticated', accountId: 't2_bob' });
expect(service.listRemoved().map((account) => account.accountId)).toEqual(['t2_alice']);
// Bob is untouched by Alice's removal — still listed, still not retired.
expect(service.list().find((account) => account.accountId === 't2_bob')?.status)
.not.toBe('removed');
});
it('refuses to remove an account it does not know, without stopping anything', async () => {
await expect(service.remove('t2_missing')).rejects.toThrow('Reddit account not found');
expect(stopped).toEqual([]);
expect(accounts.get('t2_alice')).toMatchObject({ status: 'verified' });
});
});