import fs from 'node:fs/promises'; import postgres from 'postgres'; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { PostgresCreditLedger } from '../../src/document-workbench/credit-ledger'; import { PostgresCreditPurchaseStore } from '../../src/document-workbench/credit-purchase-store'; import { Pay0CreditVerifier } from '../../src/document-workbench/pay0-credit-verification'; import { reconcileCreditPurchase } from '../../src/document-workbench/reconcile-credit-purchase'; const url = process.env.CREDIT_LEDGER_TEST_DATABASE_URL; const schema = `credit_test_${process.pid}_${Date.now()}`; const role = `credit_role_${process.pid}_${Date.now()}`; let admin: ReturnType; let scopedUrl: string; let sql: ReturnType; let ledger: PostgresCreditLedger; describe.skipIf(!url)('credit ledger against isolated PostgreSQL schema', () => { afterEach(() => vi.unstubAllGlobals()); beforeAll(async () => { if (process.env.CREDIT_LEDGER_TEST_ALLOW_LOCAL !== '1' || new URL(url!).hostname !== '127.0.0.1') { throw new Error('Only an explicitly enabled isolated loopback database may be used'); } admin = postgres(url!, { max: 1, prepare: false, connection: { search_path: schema } }); await admin.unsafe(`CREATE SCHEMA ${schema}`); await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOBYPASSRLS`); await admin.unsafe(await fs.readFile('sql/017_document_credits.sql', 'utf8')); await admin.unsafe(await fs.readFile('sql/019_document_credit_rls.sql', 'utf8')); await admin.unsafe(`GRANT USAGE ON SCHEMA ${schema} TO ${role}`); await admin.unsafe(`GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA ${schema} TO ${role}`); await admin.unsafe(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${schema} TO ${role}`); const appUrl = new URL(url!); appUrl.username = role; scopedUrl = appUrl.toString(); sql = postgres(scopedUrl, { max: 8, prepare: false, connection: { search_path: schema } }); ledger = new PostgresCreditLedger(sql); }); afterAll(async () => { if (sql) await sql.end(); if (admin) { try { await admin.unsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); await admin.unsafe(`DROP ROLE IF EXISTS ${role}`); } finally { await admin.end({ timeout: 2 }); } } }); it('rejects superusers and does not expose rows without a tenant scope', async () => { await expect(new PostgresCreditLedger(admin).apply({ tenantId: 'a', idempotencyKey: 'bad-role', kind: 'verified_payment', reference: 'bad-role', amount: 1 })).rejects.toThrow(/RLS-enforced/); expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]); expect(await sql`SELECT * FROM opt_credit_purchases`).toEqual([]); }); it('fails before writing when the isolation migration is not fully active', async () => { await admin.unsafe('ALTER TABLE opt_credit_accounts DISABLE ROW LEVEL SECURITY'); try { await expect(ledger.apply({ tenantId: 'unscoped', idempotencyKey: 'disabled-rls', kind: 'verified_payment', reference: 'disabled-rls', amount: 1 })).rejects.toThrow(/isolation migration/); } finally { await admin.unsafe('ALTER TABLE opt_credit_accounts ENABLE ROW LEVEL SECURITY'); } const rows = await admin`SELECT * FROM opt_credit_accounts WHERE tenant_id = 'unscoped'`; expect(rows).toEqual([]); }); it('grants verified payments only once and rejects a payment reused across tenants', async () => { const payment = { tenantId: 'a', idempotencyKey: 'p1', kind: 'verified_payment' as const, reference: 'stripe:account:payment-1', amount: 100, }; expect((await ledger.apply(payment)).balance).toEqual({ available: 100, reserved: 0 }); expect((await ledger.apply(payment)).replay).toBe(true); await expect(ledger.apply({ ...payment, amount: 101 })).rejects.toThrow(/Idempotency/); await expect(ledger.apply({ ...payment, tenantId: 'b' })).rejects.toThrow(); }); it('serializes concurrent reservations and prevents overspending', async () => { const command = { tenantId: 'a', kind: 'reserve' as const, amount: 80 }; const outcomes = await Promise.allSettled([ ledger.apply({ ...command, idempotencyKey: 'r1', reference: 'job1' }), ledger.apply({ ...command, idempotencyKey: 'r2', reference: 'job2' }), ]); expect(outcomes.filter((item) => item.status === 'fulfilled')).toHaveLength(1); expect(outcomes.filter((item) => item.status === 'rejected')).toHaveLength(1); const won = outcomes.find((item) => item.status === 'fulfilled') as PromiseFulfilledResult<{ replay: boolean; balance: { available: number; reserved: number }; }>; expect(won.value.balance).toEqual({ available: 20, reserved: 80 }); const rows = await sql.begin(async (tx) => { await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`; return tx<{ reservation_id: string }[]>`SELECT reservation_id FROM opt_credit_reservations`; }); const reservationId = rows[0]!.reservation_id; await expect( ledger.apply({ tenantId: 'a', idempotencyKey: 'over', kind: 'settle', reference: reservationId, amount: 81, }), ).rejects.toThrow(/exceeds/); const settled = await ledger.apply({ tenantId: 'a', idempotencyKey: 's1', kind: 'settle', reference: reservationId, amount: 30, }); expect(settled.balance).toEqual({ available: 70, reserved: 0 }); await expect( ledger.apply({ tenantId: 'a', idempotencyKey: 's2', kind: 'settle', reference: reservationId, amount: 30, }), ).rejects.toThrow(/not found/); }); it("cannot release another tenant's reservation and returns unused credits on release", async () => { await ledger.apply({ tenantId: 'a', idempotencyKey: 'r3', kind: 'reserve', reference: 'job3', amount: 40, }); await expect( ledger.apply({ tenantId: 'b', idempotencyKey: 'release-foreign', kind: 'release', reference: 'job3', amount: 0, }), ).rejects.toThrow(/not found/); expect( ( await ledger.apply({ tenantId: 'a', idempotencyKey: 'release-own', kind: 'release', reference: 'job3', amount: 0, }) ).balance, ).toEqual({ available: 70, reserved: 0 }); }); it('deduplicates concurrent payment callbacks and preserves the account across connections', async () => { const payment = { tenantId: 'c', idempotencyKey: 'concurrent-payment', kind: 'verified_payment' as const, reference: 'stripe:account:payment-2', amount: 25, }; const results = await Promise.all([ledger.apply(payment), ledger.apply(payment)]); expect(results.map((item) => item.replay).sort()).toEqual([false, true]); const secondSql = postgres(scopedUrl, { max: 1, prepare: false, connection: { search_path: schema } }); try { const replay = await new PostgresCreditLedger(secondSql).apply(payment); expect(replay).toEqual({ replay: true, balance: { available: 25, reserved: 0 } }); } finally { await secondSql.end(); } }); it('stores a tenant-scoped price snapshot and rejects changed or reused checkout data', async () => { const store = new PostgresCreditPurchaseStore(sql); const purchase = { tenantId: 'a', purchaseId: 'purchase-1', checkoutSessionId: 'cs-1', amountMinor: 1000, currency: 'SEK', credits: 25, }; expect(await store.create(purchase)).toEqual(purchase); expect(await store.create(purchase)).toEqual(purchase); expect(await store.get('b', 'purchase-1')).toBeUndefined(); await expect(store.create({ ...purchase, credits: 500 })).rejects.toThrow(/different price snapshot/); await expect(store.create({ ...purchase, tenantId: 'b', purchaseId: 'purchase-2' })).rejects.toThrow(); }); it('reconciles a stored purchase through PAY0 and grants exactly once', async () => { const purchases = new PostgresCreditPurchaseStore(sql); await purchases.create({ tenantId: 'd', purchaseId: 'purchase-d', checkoutSessionId: 'cs-d', amountMinor: 1000, currency: 'SEK', credits: 25, }); const common = { tenant_id: 'd', payable_type: '0pt_credit_purchase', payable_ref: 'purchase-d', currency: 'SEK', }; vi.stubGlobal( 'fetch', vi.fn( async (url: string) => new Response( JSON.stringify({ data: url.includes('checkout-sessions') ? { ...common, id: 'cs-d', payment_intent_id: 'pi-d', amount_snapshot: 1000, status: 'completed', provider: 'stripe', provider_reference: 'psp-d', } : { ...common, id: 'pi-d', amount: 1000, canonical_status: 'captured', captured_amount: 1000, refunded_amount: 0, }, }), { status: 200 }, ), ), ); const context = { tenantId: 'd', actorId: 'svc-0pt', capability: '0pt.credit.purchase', correlationId: 'req-d', }; const deps = { purchases, ledger, pay0: new Pay0CreditVerifier('https://pay0.test', 'service-token') }; expect(await reconcileCreditPurchase(deps, 'd', 'purchase-d', context)).toEqual({ replay: false, balance: { available: 25, reserved: 0 }, }); expect(await reconcileCreditPurchase(deps, 'd', 'purchase-d', context)).toEqual({ replay: true, balance: { available: 25, reserved: 0 }, }); await expect( reconcileCreditPurchase(deps, 'd', 'purchase-d', { ...context, tenantId: 'other' }), ).rejects.toThrow(/scope/); }); it('enforces tenant filters even when a query omits its predicate', async () => { const visible = await sql.begin(async (tx) => { await tx`SELECT set_config('app.opt_credit_tenant_id', 'a', true)`; const accounts = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_accounts`; const purchases = await tx<{ tenant_id: string }[]>`SELECT tenant_id FROM opt_credit_purchases`; return { accounts, purchases }; }); expect(visible.accounts).toEqual([{ tenant_id: 'a' }]); expect(visible.purchases).toEqual([{ tenant_id: 'a' }]); expect(await sql`SELECT * FROM opt_credit_accounts`).toEqual([]); await expect(sql.begin(async (tx) => { await tx`SELECT set_config('app.opt_credit_tenant_id', 'b', true)`; await tx`INSERT INTO opt_credit_accounts (tenant_id) VALUES ('wrong-tenant')`; })).rejects.toThrow(); }); });