Share Cash and Investment register account access #77

Merged
eleith merged 1 commits from refactor/shared-register-account-access into main 2026-11-23 15:31:55 +00:00
8 changed files with 71 additions and 78 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
'@hledger-reports/web': patch
---
Share account access checks between Cash and Investment registers while preserving page and row-request behavior.
+3 -2
View File
@@ -40,8 +40,9 @@ details query parseTransactionDetailsRequest → getTransactionDetails → readT
```
Remote entry points live in `register.remote.ts`; server operations live in
`server/registers/cash/register.ts`. Named checks in `prerequisites.ts` establish
account access and readiness; `projection.ts` whitelists public financial fields.
`server/registers/cash/register.ts`. Shared checks in
`server/registers/account-access.ts` establish account access and readiness;
`projection.ts` whitelists public financial fields.
Storage-integrity checks remain in snapshots/DB.
- `transactionIndex`: native transaction identity, exposed by our public projection;
@@ -2,12 +2,14 @@ import type { AccountConfig } from '@hledger-reports/config';
import { error } from '@sveltejs/kit';
import { requireApplication } from '#lib/server/auth/gate.js';
import { requireSavedReport } from '#lib/server/reports.js';
import { registerMembers } from '../accounts.js';
import { registerMembers } from './accounts.js';
import {
selectPreparedAccount,
type ReadableAccount,
type SelectedAccount
} from '../prepared-account.js';
} from './prepared-account.js';
type RegisterKind = NonNullable<AccountConfig['register']>;
export type RegisterLocals = Pick<App.Locals, 'application' | 'auth' | 'savedReports'>;
export interface RegisterPageContext {
@@ -15,30 +17,35 @@ export interface RegisterPageContext {
parent: () => Promise<unknown>;
}
export async function resolveInvestmentPageAccount(
export async function selectRegisterPageAccount(
{ locals, parent }: RegisterPageContext,
kind: RegisterKind,
accountId: string
): Promise<SelectedAccount> {
const { config } = requireApplication(locals);
const members = requireInvestmentMembers(config.accounts);
const members = requireRegisterMembers(config.accounts, kind);
await parent(); // Track protected layout invalidation.
return selectPreparedAccount(await requireSavedReport(locals), members, accountId);
const publication = await requireSavedReport(locals);
return selectPreparedAccount(publication, members, accountId);
}
export async function requireAuthenticatedInvestmentAccount(
export async function requireAuthenticatedReadableAccount(
locals: RegisterLocals,
kind: RegisterKind,
accountId: string
): Promise<ReadableAccount> {
const { config } = requireApplication(locals);
if (!(await locals.auth())) error(401, 'Sign in to continue.');
const members = requireInvestmentMembers(config.accounts);
const account = selectPreparedAccount(await requireSavedReport(locals), members, accountId);
const session = await locals.auth();
if (!session) error(401, 'Sign in to continue.');
const members = requireRegisterMembers(config.accounts, kind);
const publication = await requireSavedReport(locals);
const account = selectPreparedAccount(publication, members, accountId);
if (account.access === 'ambiguous') error(404, 'Account not found in the prepared reports.');
return account;
}
function requireInvestmentMembers(accounts: readonly AccountConfig[]): string[] {
const members = registerMembers(accounts, 'investment');
function requireRegisterMembers(accounts: readonly AccountConfig[], kind: RegisterKind): string[] {
const members = registerMembers(accounts, kind);
if (members.length === 0) error(404, 'Register not configured.');
return members;
}
@@ -1,44 +0,0 @@
import type { AccountConfig } from '@hledger-reports/config';
import { error } from '@sveltejs/kit';
import { requireApplication } from '#lib/server/auth/gate.js';
import { requireSavedReport } from '#lib/server/reports.js';
import { registerMembers } from '../accounts.js';
import {
selectPreparedAccount,
type ReadableAccount,
type SelectedAccount
} from '../prepared-account.js';
export type RegisterLocals = Pick<App.Locals, 'application' | 'auth' | 'savedReports'>;
export interface RegisterPageContext {
locals: Pick<App.Locals, 'application' | 'savedReports'>;
parent: () => Promise<unknown>;
}
export async function resolveCashPageAccount(
{ locals, parent }: RegisterPageContext,
accountId: string
): Promise<SelectedAccount> {
const { config } = requireApplication(locals);
const members = requireCashMembers(config.accounts);
await parent(); // Track protected layout invalidation.
return selectPreparedAccount(await requireSavedReport(locals), members, accountId);
}
export async function requireReadableAccount(
locals: RegisterLocals,
accountId: string
): Promise<ReadableAccount> {
const { config } = requireApplication(locals);
if (!(await locals.auth())) error(401, 'Sign in to continue.');
const members = requireCashMembers(config.accounts);
const account = selectPreparedAccount(await requireSavedReport(locals), members, accountId);
if (account.access === 'ambiguous') error(404, 'Account not found in the prepared reports.');
return account;
}
function requireCashMembers(accounts: readonly AccountConfig[]): string[] {
const members = registerMembers(accounts, 'cash');
if (members.length === 0) error(404, 'Register not configured.');
return members;
}
@@ -17,11 +17,11 @@ import {
import type { ReadableAccount } from '../prepared-account.js';
import { projectActivityPage, projectTransactionDetails } from './projection.js';
import {
requireReadableAccount,
resolveCashPageAccount,
requireAuthenticatedReadableAccount,
selectRegisterPageAccount,
type RegisterLocals,
type RegisterPageContext
} from './prerequisites.js';
} from '../account-access.js';
type RegisterActivity = Pick<
RegisterPageData,
@@ -32,7 +32,7 @@ export async function loadRegisterPage(
context: RegisterPageContext,
request: RegisterPageRequest
): Promise<RegisterPageData> {
const account = await resolveCashPageAccount(context, request.accountId);
const account = await selectRegisterPageAccount(context, 'cash', request.accountId);
const metadata = {
accountId: account.id,
accountName: account.name,
@@ -59,7 +59,7 @@ export async function readRowBatch(
locals: RegisterLocals,
request: RowBatchRequest
): Promise<RowBatch> {
const account = await requireReadableAccount(locals, request.accountId);
const account = await requireAuthenticatedReadableAccount(locals, 'cash', request.accountId);
requireBatchPosition(request.batchStart, account.rowCount);
try {
const page = await readSavedActivityPage(account, request.order, request.batchStart);
@@ -73,7 +73,7 @@ export async function readTransactionDetails(
locals: RegisterLocals,
request: TransactionDetailsRequest
): Promise<TransactionDetails> {
const account = await requireReadableAccount(locals, request.accountId);
const account = await requireAuthenticatedReadableAccount(locals, 'cash', request.accountId);
const transaction = await readSavedTransaction(account, request.transactionIndex);
return projectTransactionDetails(transaction);
}
@@ -12,7 +12,7 @@ import {
} from '../../../../../../../packages/db/src/reports/data.fixture.js';
import { testConfig } from '#lib/server/application.fixture.js';
import { savedReportFixture } from '#lib/server/reports.fixture.js';
import type { RegisterLocals } from './account-access.js';
import type { RegisterLocals } from '../account-access.js';
import { loadRegisterPage, readActivityBatch } from './register.js';
vi.mock('@hledger-reports/snapshots', () => ({
@@ -124,10 +124,14 @@ it('requires configuration and authentication before saved reads', async () => {
unconfigured.application = null;
await expect(readActivityBatch(unconfigured, request)).rejects.toMatchObject({ status: 503 });
expect(unconfigured.auth).not.toHaveBeenCalled();
const anonymous = locals();
anonymous.savedReports = Promise.resolve({ status: 'ready', publication });
vi.mocked(readReportPublication).mockResolvedValue(null);
const anonymous = locals([]);
vi.mocked(anonymous.auth).mockResolvedValue(null);
await expect(readActivityBatch(anonymous, request)).rejects.toMatchObject({ status: 401 });
await expect(readActivityBatch(locals([]), request)).rejects.toMatchObject({
status: 404,
body: { message: 'Register not configured.' }
});
expect(readReportPublication).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
@@ -14,18 +14,18 @@ import {
import type { RegisterPageRequest } from '#lib/registers/investment/register-page-request.js';
import type { ReadableAccount } from '../prepared-account.js';
import {
resolveInvestmentPageAccount,
requireAuthenticatedInvestmentAccount,
selectRegisterPageAccount,
requireAuthenticatedReadableAccount,
type RegisterLocals,
type RegisterPageContext
} from './account-access.js';
} from '../account-access.js';
import { projectInvestmentActivityPage } from './projection.js';
export async function loadRegisterPage(
context: RegisterPageContext,
request: RegisterPageRequest
): Promise<InvestmentAccountPageData> {
const account = await resolveInvestmentPageAccount(context, request.accountId);
const account = await selectRegisterPageAccount(context, 'investment', request.accountId);
const metadata = {
accountName: account.name,
access: account.access,
@@ -39,7 +39,11 @@ export async function readActivityBatch(
locals: RegisterLocals,
request: ActivityBatchRequest
): Promise<ActivityBatch> {
const account = await requireAuthenticatedInvestmentAccount(locals, request.accountId);
const account = await requireAuthenticatedReadableAccount(
locals,
'investment',
request.accountId
);
if (account.rowCount === 0) {
if (request.batchStart !== 0) error(404, 'History position not found.');
return { batchStart: 0, activities: [] };
@@ -52,7 +52,8 @@ const projection: ReturnType<typeof projectInvestmentActivityPage> = {
};
function event(
query = '',
accounts: AccountConfig[] = [{ account: name, register: 'investment' }]
accounts: AccountConfig[] = [{ account: name, register: 'investment' }],
parent: () => Promise<unknown> = vi.fn().mockResolvedValue({})
) {
const application: ApplicationContext = {
config: { ...testConfig, accounts },
@@ -70,7 +71,7 @@ function event(
params: { accountId: id },
request: new Request(url, { headers: { host: url.host } }),
getClientAddress: () => '127.0.0.1',
parent: vi.fn().mockResolvedValue({}),
parent,
setHeaders: vi.fn(),
locals: {
application,
@@ -215,12 +216,27 @@ it('rejects pages outside the activity count before reading canonical activity b
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('uses the gate-pinned publication and still depends on the parent layout', async () => {
const request = event();
request.locals.savedReports = Promise.resolve({ status: 'ready', publication });
it('waits for the parent layout before using the request-pinned publication', async () => {
const releaseParent = Promise.withResolvers<void>();
const parent = vi.fn(async () => {
await releaseParent.promise;
request.locals.savedReports = Promise.resolve({ status: 'ready', publication });
return {};
});
const request = event('', undefined, parent);
vi.mocked(readReportPublication).mockResolvedValue(null);
await load(request);
expect(request.parent).toHaveBeenCalledOnce();
const loading = load(request);
try {
const pending = Symbol('parent still pending');
const nextTurn = new Promise((resolve) => setImmediate(() => resolve(pending)));
expect(await Promise.race([loading, nextTurn])).toBe(pending);
expect(parent).toHaveBeenCalledOnce();
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).not.toHaveBeenCalled();
} finally {
releaseParent.resolve();
await loading;
}
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, {