feat: harden operated production release

This commit is contained in:
jwinterm
2026-07-22 12:56:00 -04:00
parent dfe4d1ad97
commit 91f139eeaa
44 changed files with 4500 additions and 653 deletions
+5 -5
View File
@@ -161,11 +161,11 @@ describe('disposable clone migration execution', () => {
logSpy.mockRestore();
});
test('discovers the contiguous repository manifest through migration 41 dynamically', () => {
test('discovers the contiguous repository manifest through migration 42 dynamically', () => {
const manifest = discoverMigrationManifest();
expect(manifest.latestOrdinal).toBeGreaterThanOrEqual(MINIMUM_RELEASE_MIGRATION);
expect(manifest.latestFilename).toBe('041_financial_event_outbox.sql');
expect(manifest.files).toHaveLength(41);
expect(manifest.latestFilename).toBe('042_immutable_financial_event_snapshots.sql');
expect(manifest.files).toHaveLength(42);
});
test('runs the normal ordered migration implementation and proves the exact ledger', async () => {
@@ -185,9 +185,9 @@ describe('disposable clone migration execution', () => {
});
expect(pool.transactions).toEqual(result.files);
expect(result.latestFilename).toBe('041_financial_event_outbox.sql');
expect(result.latestFilename).toBe('042_immutable_financial_event_snapshots.sql');
expect(output).toContain('clone_migration_status=ok');
expect(output).toContain('latest_migration=041_financial_event_outbox.sql');
expect(output).toContain('latest_migration=042_immutable_financial_event_snapshots.sql');
expect(output.join('\n')).not.toContain(secret);
expect(pool.config).toEqual(expect.objectContaining({
database: env.DB_NAME,
+58
View File
@@ -53,6 +53,64 @@ describe('commerce disclosure and paid-action policy', () => {
}));
});
test('publishes the immutable play.wowne.ro scope and Such Software identity', () => {
const disclosure = buildCommerceDisclosure(manager({
cryptoType: 'WOW',
currencyLabel: 'WOW',
network: 'mainnet',
isTestNetwork: false,
directModeEnabled: false,
creditsModeEnabled: true,
payoutsEnabled: false,
isPayoutEnabledForMode: () => false
}), env({
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige',
OPERATOR_NAME: 'untrusted override',
OPERATOR_CONTACT_URL: 'mailto:untrusted@example.invalid'
}));
expect(disclosure.operator).toEqual({
name: 'Such Software',
contactUrl: 'mailto:apps@such.software',
contactLabel: 'apps@such.software'
});
expect(disclosure.operatedProduct).toEqual(expect.objectContaining({
id: 'such-play-wow-prestige',
hostname: 'play.wowne.ro',
noRealValueNotice: null
}));
expect(disclosure.operatedProduct.scopeNotice).toContain('pay-for-credits leaderboard/prestige');
expect(disclosure.operatedProduct.scopeNotice).toContain('offers no prizes, winnings, cash-out, or payouts');
expect(disclosure.operatedProduct.scopeNotice).toContain('not offered or marketed as gambling');
expect(disclosure.operatedProduct.scopeNotice).toContain('legal classification depends on applicable law');
});
test('publishes conspicuous no-real-value monerogue.app scope and MIT operator boundary', () => {
const disclosure = buildCommerceDisclosure(manager(), env({
OPERATED_PRODUCT_PROFILE: 'such-monerogue-stagenet'
}));
expect(disclosure.operatedProduct.scopeNotice).toContain('single-player 2×/3× outcomes are test gambling mechanics');
expect(disclosure.operatedProduct.noRealValueNotice).toContain('NO REAL VALUE');
expect(disclosure.operatedProduct.commerceSummary).toContain('never send mainnet XMR');
expect(disclosure.software).toEqual(expect.objectContaining({
license: 'MIT',
publisherName: 'Such Software'
}));
expect(disclosure.software.rightsNotice).toContain('copyright and permission notice');
expect(disclosure.software.warrantyNotice).toContain('AS IS');
expect(disclosure.software.legalAdviceNotice).toContain('not legal advice');
expect(disclosure.software.thirdPartyNotice).toContain('solely responsible');
expect(disclosure.software.thirdPartyNotice).toContain('does not operate, supervise, endorse, or accept responsibility');
});
test('an unprofiled deployment remains generic and is not represented as Such-operated', () => {
const disclosure = buildCommerceDisclosure(manager(), env());
expect(disclosure.operatedProduct).toBeNull();
expect(disclosure.operator.name).toBe('Test Operator');
expect(disclosure.software.operatedBoundaryNotice).toContain('operates only play.wowne.ro and monerogue.app');
});
test('describes paid prestige separately when every payout path is off', () => {
const disclosure = buildCommerceDisclosure(manager({
cryptoType: 'WOW', currencyLabel: 'WOW', network: 'mainnet', isTestNetwork: false,
+285
View File
@@ -107,6 +107,291 @@ describe('EnvironmentValidator production launch gate', () => {
}));
});
test('accepts a complete HTTPS mainnet financial-event sink without exposing its token', () => {
const token = 'A1b2C3d4E5f6G7h8J9k0L1m2N3p4Q5r6';
const result = new EnvironmentValidator({
env: productionEnv({
MONERO_NETWORK: 'mainnet',
FINANCIAL_EVENT_SINK_URL: 'https://ledger.operator.invalid/v1/events',
FINANCIAL_EVENT_SINK_TOKEN: token,
FINANCIAL_EVENT_ACCOUNT_REF: 'wowngeon:receipts'
}),
logger: silentLogger
}).validate(config());
expect(result.errors).toEqual([]);
expect(JSON.stringify(result)).not.toContain(token);
});
test('rejects partial, insecure, weak, credential-bearing, or testnet accounting export', () => {
const token = 'A1b2C3d4E5f6G7h8J9k0L1m2N3p4Q5r6';
const cases = [
[
{ FINANCIAL_EVENT_SINK_URL: 'https://ledger.operator.invalid/events' },
'must be configured together'
],
[
{
FINANCIAL_EVENT_SINK_URL: 'http://ledger.operator.invalid/events',
FINANCIAL_EVENT_SINK_TOKEN: token,
MONERO_NETWORK: 'mainnet'
},
'must use https:// in production'
],
[
{
FINANCIAL_EVENT_SINK_URL: 'https://user:pass@ledger.operator.invalid/events',
FINANCIAL_EVENT_SINK_TOKEN: token,
MONERO_NETWORK: 'mainnet'
},
'must not embed credentials'
],
[
{
FINANCIAL_EVENT_SINK_URL: 'https://ledger.operator.invalid/events',
FINANCIAL_EVENT_SINK_TOKEN: 'change-me'
},
'strong non-placeholder secret'
],
[
{
FINANCIAL_EVENT_SINK_URL: 'https://ledger.operator.invalid/events',
FINANCIAL_EVENT_SINK_TOKEN: token
},
'must be unset on non-mainnet networks'
],
[
{
FINANCIAL_EVENT_SINK_URL: 'https://ledger.operator.invalid/events',
FINANCIAL_EVENT_SINK_TOKEN: token,
FINANCIAL_EVENT_ACCOUNT_REF: 'customer@example.invalid',
MONERO_NETWORK: 'mainnet'
},
'must be a non-PII identifier'
]
];
for (const [overrides, expected] of cases) {
const result = new EnvironmentValidator({
env: productionEnv(overrides), logger: silentLogger
}).validate(config());
expect(result.errors).toEqual(expect.arrayContaining([expect.stringContaining(expected)]));
expect(JSON.stringify(result)).not.toContain(token);
}
});
test('accepts the exact Such Software play.wowne.ro operated-product contract', () => {
const env = productionEnv({
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige',
HOSTED_BY: 'https://play.wowne.ro',
OPERATOR_NAME: 'Such Software',
OPERATOR_CONTACT_URL: 'mailto:apps@such.software',
OPERATOR_CONTACT_LABEL: 'apps@such.software',
CRYPTO_TYPE: 'WOW',
MONERO_NETWORK: 'mainnet',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'credits',
DIRECT_PAYMENT_ENABLED: 'false',
CREDITS_ENABLED: 'true',
PAYOUTS_ENABLED: 'false',
DIRECT_PAYOUTS_ENABLED: 'false',
CREDITS_PAYOUTS_ENABLED: 'false',
ALLOW_MAINNET_PAYOUTS: 'false',
MATCH_CRYPTO_RACE_ENABLED: 'false',
MATCH_PAYOUTS_ENABLED: 'false'
});
const operatedConfig = config({
currency: { symbol: 'WOW' },
modes: {
direct: { enabled: false, price: 10000n },
credits: {
enabled: true,
packages: [{ id: 'small', credits: 10, price: 90000000000n }]
}
}
});
expect(new EnvironmentValidator({ env, logger: silentLogger })
.assertValid(operatedConfig).errors).toEqual([]);
expect(new EnvironmentValidator({ env, logger: silentLogger }).validate({
...operatedConfig,
products: { cosmetic: [{ id: 'unrelated-pack', price: 1n }] }
}).errors).toContain(
'OPERATED_PRODUCT_PROFILE=such-play-wow-prestige requires no standalone products or bundled entitlement grants; credit packages may grant only their top-level credits and bonus.'
);
});
test('accepts the exact Such Software monerogue.app stagenet 2x/3x contract', () => {
const env = productionEnv({
OPERATED_PRODUCT_PROFILE: 'such-monerogue-stagenet',
HOSTED_BY: 'https://monerogue.app',
OPERATOR_NAME: 'Such Software',
OPERATOR_CONTACT_URL: 'mailto:apps@such.software',
OPERATOR_CONTACT_LABEL: 'apps@such.software',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'direct,credits',
DIRECT_PAYMENT_ENABLED: 'true',
CREDITS_ENABLED: 'true',
PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUTS_ENABLED: 'true',
CREDITS_PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUT_ESCAPE: '2.0',
DIRECT_PAYOUT_TREASURE: '3.0',
CREDITS_PAYOUT_ESCAPE: '2.0',
CREDITS_PAYOUT_TREASURE: '3.0',
ALLOW_MAINNET_PAYOUTS: 'false',
MATCH_CRYPTO_RACE_ENABLED: 'false',
MATCH_PAYOUTS_ENABLED: 'false'
});
const operatedConfig = config({
payouts: {
enabled: true,
rules: {
direct: { enabled: true },
credits: { enabled: true }
}
}
});
expect(new EnvironmentValidator({ env, logger: silentLogger })
.assertValid(operatedConfig).errors).toEqual([]);
const outOfScopeCatalogs = [
{
...operatedConfig,
products: { cosmetic: [{ id: 'pack', price: 20000n }] }
},
...[
{ packs: ['kenney-3d-characters'] },
{ premiumLevel: 'supporter' },
{ race_entries: 2, race_entry_value_atomic: '10000' },
{ future_entitlement: true },
{ credits: 10 }
].map(grants => ({
...operatedConfig,
modes: {
...operatedConfig.modes,
credits: {
...operatedConfig.modes.credits,
packages: [{ id: 'small', credits: 10, price: 90000000000n, grants }]
}
}
}))
];
for (const widenedCatalog of outOfScopeCatalogs) {
expect(new EnvironmentValidator({ env, logger: silentLogger })
.validate(widenedCatalog).errors).toContain(
'OPERATED_PRODUCT_PROFILE=such-monerogue-stagenet requires no standalone products or bundled entitlement grants; credit packages may grant only their top-level credits and bonus.'
);
}
});
test('play.wowne.ro profile rejects direct entry or any payout activation', () => {
const env = productionEnv({
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige',
HOSTED_BY: 'https://play.wowne.ro',
OPERATOR_NAME: 'Such Software',
OPERATOR_CONTACT_URL: 'mailto:apps@such.software',
OPERATOR_CONTACT_LABEL: 'apps@such.software',
CRYPTO_TYPE: 'WOW',
MONERO_NETWORK: 'mainnet',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'direct,credits',
DIRECT_PAYMENT_ENABLED: 'true',
CREDITS_ENABLED: 'true',
PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUTS_ENABLED: 'true',
CREDITS_PAYOUTS_ENABLED: 'false',
ALLOW_MAINNET_PAYOUTS: 'false',
MATCH_CRYPTO_RACE_ENABLED: 'false',
MATCH_PAYOUTS_ENABLED: 'false'
});
const result = new EnvironmentValidator({ env, logger: silentLogger }).validate(config({
currency: { symbol: 'WOW' },
payouts: { enabled: true, rules: { direct: { enabled: true } } }
}));
expect(result.errors).toEqual(expect.arrayContaining([
expect.stringContaining('requires PAYMENT_MODES=credits'),
expect.stringContaining('requires DIRECT_PAYMENT_ENABLED=false'),
expect.stringContaining('requires PAYOUTS_ENABLED=false'),
expect.stringContaining('requires DIRECT_PAYOUTS_ENABLED=false')
]));
});
test('operated profiles fail closed on identity, network, mode, multiplier, or payout drift', () => {
const env = productionEnv({
OPERATED_PRODUCT_PROFILE: 'such-monerogue-stagenet',
HOSTED_BY: 'https://play.wowne.ro',
OPERATOR_NAME: 'Someone Else',
OPERATOR_CONTACT_URL: 'mailto:other@example.invalid',
OPERATOR_CONTACT_LABEL: 'Other',
CRYPTO_TYPE: 'XMR',
MONERO_NETWORK: 'mainnet',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'direct,credits',
DIRECT_PAYMENT_ENABLED: 'true',
CREDITS_ENABLED: 'true',
PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUTS_ENABLED: 'true',
CREDITS_PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUT_ESCAPE: '4',
DIRECT_PAYOUT_TREASURE: '3',
CREDITS_PAYOUT_ESCAPE: '2',
CREDITS_PAYOUT_TREASURE: '3',
ALLOW_MAINNET_PAYOUTS: 'true',
MATCH_CRYPTO_RACE_ENABLED: 'true',
MATCH_PAYOUTS_ENABLED: 'true'
});
const result = new EnvironmentValidator({ env, logger: silentLogger }).validate(config({
payouts: {
enabled: true,
rules: { direct: { enabled: true }, credits: { enabled: true } }
}
}));
expect(result.errors).toEqual(expect.arrayContaining([
expect.stringContaining('requires HOSTED_BY=https://monerogue.app'),
expect.stringContaining('requires OPERATOR_NAME=Such Software'),
expect.stringContaining('requires OPERATOR_CONTACT_URL=mailto:apps@such.software'),
expect.stringContaining('requires MONERO_NETWORK=stagenet'),
expect.stringContaining('requires DIRECT_PAYOUT_ESCAPE=2'),
expect.stringContaining('requires MATCH_CRYPTO_RACE_ENABLED=false'),
expect.stringContaining('requires MATCH_PAYOUTS_ENABLED=false'),
expect.stringContaining('requires ALLOW_MAINNET_PAYOUTS=false')
]));
});
test('unknown operated profile is rejected while an omitted profile preserves generic MIT hosting', () => {
expect(new EnvironmentValidator({ env: productionEnv(), logger: silentLogger })
.validate(config()).errors).toEqual([]);
const result = new EnvironmentValidator({
env: productionEnv({ OPERATED_PRODUCT_PROFILE: 'third-party-claim' }),
logger: silentLogger
}).validate(config());
expect(result.errors).toContain(
'OPERATED_PRODUCT_PROFILE=third-party-claim is unknown. Remove it for an independent MIT deployment or use a reviewed Such Software profile.'
);
});
test('operated identity cannot bypass its exact contract outside production', () => {
const env = productionEnv({
NODE_ENV: 'development',
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige',
HOSTED_BY: 'http://localhost:3000',
OPERATOR_NAME: 'Such Software'
});
const result = new EnvironmentValidator({ env, logger: silentLogger }).validate(config());
expect(result.errors).toEqual(expect.arrayContaining([
expect.stringContaining('requires HOSTED_BY=https://play.wowne.ro'),
expect.stringContaining('requires CRYPTO_TYPE=WOW'),
expect.stringContaining('requires PAYMENT_MODES=credits')
]));
});
test('accepts explicitly capped stagenet crypto match payouts', () => {
const env = productionEnv({
PAYOUTS_ENABLED: 'true',
+2 -2
View File
@@ -16,7 +16,7 @@ describe('deployment financial-audit contract', () => {
test('nullable or unknown money/game states and a stale schema ledger fail closed', () => {
expect(audit).toContain("payouts WHERE status IS DISTINCT FROM 'completed'");
expect(audit).toContain("games WHERE status IS NULL OR status NOT IN ('won', 'lost', 'expired')");
expect(audit).toContain("MAX(filename) = '040_paid_match_entropy_precommit.sql'");
expect(audit).toContain('COUNT(*) = 40');
expect(audit).toContain("MAX(filename) = '042_immutable_financial_event_snapshots.sql'");
expect(audit).toContain('COUNT(*) = 42');
});
});
+340 -28
View File
@@ -1,5 +1,13 @@
'use strict';
const fs = require('fs');
const path = require('path');
const FinancialEventExporter = require('../src/services/financialEventExporter');
const { buildFinancialEvent } = FinancialEventExporter;
const {
buildFinancialEvent,
sourceSnapshotFromPayment,
DELIVERY_CONTRACT
} = FinancialEventExporter;
const ENV = {
NODE_ENV: 'production',
@@ -7,7 +15,8 @@ const ENV = {
MONERO_NETWORK: 'mainnet',
FINANCIAL_EVENT_SINK_URL: 'https://accounting.example.test/api/events/wowngeon',
FINANCIAL_EVENT_SINK_TOKEN: 'a'.repeat(64),
FINANCIAL_EVENT_ACCOUNT_REF: 'wowngeon:receipts'
FINANCIAL_EVENT_ACCOUNT_REF: 'wowngeon:receipts',
FINANCIAL_EVENT_BATCH_SIZE: '2'
};
const PAYMENT = {
@@ -18,16 +27,64 @@ const PAYMENT = {
confirmed_at: '2026-07-22T14:30:00Z',
provider_id: 'native-monero',
product_id: 'small',
receipts: [{ evidence_type: 'chain_output', evidence_id: `${'a'.repeat(64)}:${'b'.repeat(64)}` }]
receipts: [{
evidence_type: 'chain_output',
evidence_id: `${'a'.repeat(64)}:${'b'.repeat(64)}`,
payout_address: 'wallet-address-must-not-escape'
}]
};
describe('financial event exporter', () => {
test('builds a backend-neutral, unpriced WOW receipt without customer data', () => {
const event = buildFinancialEvent(PAYMENT, ENV);
function paymentClaim(overrides = {}) {
return {
id: 5,
event_id: 'payment-confirmed-22',
event_kind: 'payment.confirmed',
source_type: 'payment',
source_id: 22,
aggregate_id: 22,
payload_snapshot: sourceSnapshotFromPayment(PAYMENT),
delivery_payload: null,
attempts: 1,
...overrides
};
}
function healthRows(overrides = {}) {
return { rows: [{ backlog: '0', dead_letters: '0', ignored_rows: '0', ...overrides }] };
}
function standardDb({ claims = [paymentClaim()], onQuery } = {}) {
const queue = [...claims];
const db = {
query: jest.fn(async (sql, params = []) => {
if (onQuery) {
const custom = await onQuery(sql, params);
if (custom) return custom;
}
if (/attempts >= \$1/i.test(sql)) return { rows: [], rowCount: 0 };
if (/RETURNING id, event_id, event_kind/i.test(sql)) {
const next = queue.shift();
return { rows: next ? [next] : [], rowCount: next ? 1 : 0 };
}
if (/SET delivery_payload = \$2::jsonb/i.test(sql)) {
return { rows: [{ delivery_payload: JSON.parse(params[1]) }], rowCount: 1 };
}
if (/SET status = 'delivered'/i.test(sql)) return { rows: [{ id: params[0] }], rowCount: 1 };
if (/COUNT\(\*\) FILTER/i.test(sql)) return healthRows();
return { rows: [], rowCount: 0 };
})
};
return db;
}
describe('financial event payload snapshots', () => {
test('builds a backend-neutral, unpriced WOW receipt without customer or wallet data', () => {
const source = sourceSnapshotFromPayment(PAYMENT);
const event = buildFinancialEvent(source, ENV);
expect(event).toEqual(expect.objectContaining({
schema: 'financial-event/v1',
id: 'payment-22',
id: 'payment-confirmed-22',
producer: 'wowngeon',
product: 'wowngeon',
activity: 'customer-payment',
@@ -36,41 +93,296 @@ describe('financial event exporter', () => {
attributes: expect.objectContaining({
valuation_required: true,
atomic_amount: '900000000000',
atomic_decimals: 11
atomic_decimals: 11,
receipt_count: 1
})
}));
expect(event.legs[0]).toEqual(expect.objectContaining({
asset: 'WOW', quantity: '9', direction: 'in', usd_value: '0'
}));
expect(JSON.stringify(event)).not.toMatch(/user|email|address_index/i);
expect(JSON.stringify(source)).not.toContain(PAYMENT.receipts[0].evidence_id);
expect(JSON.stringify({ source, event })).not.toMatch(
/user_id|socket_id|ip_address|subaddress|payout_address|provider_invoice_id|wallet-address-must-not-escape/i
);
});
test('claims and delivers one durable outbox row', async () => {
const db = {
query: jest.fn(async (sql) => {
if (/RETURNING id, aggregate_id, attempts/i.test(sql)) {
return db.claimed ? { rows: [] } : (db.claimed = true, { rows: [{ id: 5, aggregate_id: 22, attempts: 1 }] });
}
if (/FROM payments p/i.test(sql)) return { rows: [PAYMENT] };
return { rows: [] };
})
};
test('exports only the immutable snapshot after the payment becomes mutable/refunded', async () => {
const snapshot = sourceSnapshotFromPayment(PAYMENT);
const mutatedPayment = { ...PAYMENT, status: 'refunded', received_amount: '1' };
const db = standardDb({ claims: [paymentClaim({ payload_snapshot: snapshot })] });
const fetchFn = jest.fn(async () => ({ ok: true, status: 201 }));
const exporter = new FinancialEventExporter({ db, env: ENV, fetchFn, logger: { warn: jest.fn() } });
await expect(exporter.runOnce()).resolves.toEqual({ skipped: false, delivered: 1, deferred: 0 });
expect(fetchFn).toHaveBeenCalledWith(ENV.FINANCIAL_EVENT_SINK_URL, expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({ authorization: `Bearer ${ENV.FINANCIAL_EVENT_SINK_TOKEN}` })
}));
expect(db.query.mock.calls.some(([sql]) => /SET status = 'delivered'/i.test(sql))).toBe(true);
await expect(exporter.runOnce()).resolves.toEqual({
skipped: false, delivered: 1, deferred: 0, deadLettered: 0, ignored: 0
});
const delivered = JSON.parse(fetchFn.mock.calls[0][1].body);
expect(delivered.attributes.atomic_amount).toBe('900000000000');
expect(mutatedPayment.received_amount).toBe('1');
expect(db.query.mock.calls.some(([sql]) => /FROM payments\b/i.test(sql))).toBe(false);
});
test('refuses to export stagenet value into production accounting', () => {
test.each([
['recorded', 'customer-payment-reversal'],
['completed', 'customer-refund']
])('exports final %s refund as an outgoing leg', (refundStatus, activity) => {
const event = buildFinancialEvent({
schema: 'financial-event-source/v1',
event_id: 'payment-refund-91',
event_kind: 'payment.refund',
source_type: 'payment_refund',
source_id: 91,
aggregate_id: 22,
occurred_at: '2026-07-22T15:00:00Z',
atomic_amount: '450000000000',
refund_status: refundStatus
}, ENV);
expect(event).toEqual(expect.objectContaining({
id: 'payment-refund-91',
activity,
attributes: expect.objectContaining({ refund_status: refundStatus })
}));
expect(event.legs).toEqual([expect.objectContaining({
quantity: '4.5', direction: 'out', asset: 'WOW'
})]);
});
test.each(['requested', 'processing', 'needs_review'])('refuses non-final %s refund snapshots', status => {
expect(() => buildFinancialEvent({
schema: 'financial-event-source/v1',
event_id: 'payment-refund-91',
event_kind: 'payment.refund',
source_type: 'payment_refund',
source_id: 91,
aggregate_id: 22,
occurred_at: '2026-07-22T15:00:00Z',
atomic_amount: '1',
refund_status: status
}, ENV)).toThrow(/final exportable state/);
});
test('rejects PII-shaped account references and credential-bearing sink URLs', () => {
expect(() => buildFinancialEvent(sourceSnapshotFromPayment(PAYMENT), {
...ENV,
FINANCIAL_EVENT_ACCOUNT_REF: 'customer@example.invalid'
})).toThrow(/non-PII/);
expect(() => new FinancialEventExporter({
db: { query: jest.fn() },
env: { ...ENV, CRYPTO_TYPE: 'XMR', MONERO_NETWORK: 'stagenet' },
env: { ...ENV, FINANCIAL_EVENT_SINK_URL: 'https://user:pass@accounting.example.test/events' },
fetchFn: jest.fn()
})).toThrow(/must not be exported/);
})).toThrow(/must not embed credentials/);
});
});
describe('at-least-once financial event delivery', () => {
test('uses one stable idempotency key and stored body when the durable acknowledgement is retried', async () => {
const claim1 = paymentClaim({ attempts: 1 });
let storedPayload = null;
let claimNumber = 0;
let acknowledgementNumber = 0;
const db = standardDb({
claims: [],
onQuery: async (sql, params) => {
if (/RETURNING id, event_id, event_kind/i.test(sql)) {
claimNumber += 1;
if (claimNumber === 1) return { rows: [claim1], rowCount: 1 };
if (claimNumber === 2) return { rows: [], rowCount: 0 };
if (claimNumber === 3) {
return { rows: [{ ...claim1, attempts: 2, delivery_payload: storedPayload }], rowCount: 1 };
}
return { rows: [], rowCount: 0 };
}
if (/SET delivery_payload = \$2::jsonb/i.test(sql)) {
storedPayload = JSON.parse(params[1]);
return { rows: [{ delivery_payload: storedPayload }], rowCount: 1 };
}
if (/SET status = 'delivered'/i.test(sql)) {
acknowledgementNumber += 1;
if (acknowledgementNumber === 1) throw new Error('database acknowledgement unavailable');
return { rows: [{ id: params[0] }], rowCount: 1 };
}
return null;
}
});
const fetchFn = jest.fn(async () => ({ ok: true, status: 202 }));
const exporter = new FinancialEventExporter({ db, env: ENV, fetchFn, logger: { warn: jest.fn() } });
await expect(exporter.runOnce()).resolves.toEqual(expect.objectContaining({ deferred: 1 }));
await expect(exporter.runOnce()).resolves.toEqual(expect.objectContaining({ delivered: 1 }));
expect(fetchFn).toHaveBeenCalledTimes(2);
const first = fetchFn.mock.calls[0][1];
const second = fetchFn.mock.calls[1][1];
expect(first.headers['idempotency-key']).toBe('payment-confirmed-22');
expect(second.headers['idempotency-key']).toBe(first.headers['idempotency-key']);
expect(second.body).toBe(first.body);
expect(DELIVERY_CONTRACT).toEqual(expect.objectContaining({ guarantee: 'at-least-once' }));
expect(exporter.getDeliveryContract().deduplication).toMatch(/Idempotency-Key/);
});
test('bounds repeated failures and moves the last attempt to dead letter', async () => {
const db = standardDb({
claims: [paymentClaim({ attempts: 2 })],
onQuery: async (sql, params) => {
if (/SET status = 'dead_letter'/i.test(sql) && /WHERE id = \$1/i.test(sql)) {
return { rows: [{ id: params[0] }], rowCount: 1 };
}
if (/COUNT\(\*\) FILTER/i.test(sql)) return healthRows({ backlog: '0', dead_letters: '1' });
return null;
}
});
const fetchFn = jest.fn(async () => ({ ok: false, status: 503 }));
const exporter = new FinancialEventExporter({
db,
env: { ...ENV, FINANCIAL_EVENT_MAX_ATTEMPTS: '2' },
fetchFn,
logger: { warn: jest.fn() }
});
await expect(exporter.runOnce()).resolves.toEqual({
skipped: false, delivered: 0, deferred: 0, deadLettered: 1, ignored: 0
});
expect(exporter.getHealth()).toEqual(expect.objectContaining({
attempted: 1, deadLettered: 1, deadLetters: 1, backlog: 0
}));
expect(exporter.getPublicHealth()).toEqual(expect.objectContaining({
contract: 'at-least-once', deadLettered: 1, deadLetters: 1, backlog: 0
}));
expect(JSON.stringify(exporter.getPublicHealth())).not.toMatch(
/accounting\.example|authorization|token|lastError|event_id|payment-confirmed/i
);
});
test('malformed stored snapshots fail closed and dead-letter without an HTTP attempt', async () => {
const malformed = paymentClaim({
attempts: 1,
payload_snapshot: { ...paymentClaim().payload_snapshot, occurred_at: null }
});
const db = standardDb({
claims: [malformed],
onQuery: async (sql, params) => {
if (/SET status = 'dead_letter'/i.test(sql) && /WHERE id = \$1/i.test(sql)) {
return { rows: [{ id: params[0] }], rowCount: 1 };
}
return null;
}
});
const fetchFn = jest.fn();
const exporter = new FinancialEventExporter({
db,
env: { ...ENV, FINANCIAL_EVENT_MAX_ATTEMPTS: '1' },
fetchFn,
logger: { warn: jest.fn() }
});
await expect(exporter.runOnce()).resolves.toEqual(expect.objectContaining({ deadLettered: 1 }));
expect(fetchFn).not.toHaveBeenCalled();
});
});
describe('non-mainnet suppression and migration safety', () => {
test('keeps backlog counters current when the optional mainnet sink is disabled', async () => {
const db = {
query: jest.fn(async sql => {
if (/COUNT\(\*\) FILTER/i.test(sql)) {
return healthRows({ backlog: '7', dead_letters: '2', ignored_rows: '1' });
}
throw new Error(`unexpected SQL: ${sql}`);
})
};
const exporter = new FinancialEventExporter({
db,
env: { NODE_ENV: 'production', CRYPTO_TYPE: 'WOW', MONERO_NETWORK: 'mainnet' },
fetchFn: jest.fn(),
logger: { warn: jest.fn() }
});
await expect(exporter.runOnce()).resolves.toEqual({
skipped: true, delivered: 0, deferred: 0, deadLettered: 0, ignored: 0
});
expect(exporter.getPublicHealth()).toEqual(expect.objectContaining({
enabled: false, backlog: 7, deadLetters: 2, ignoredRows: 1
}));
expect(exporter.start()).toBe(true);
exporter.stop();
});
test.each(['stagenet', 'testnet'])('continuously suppresses XMR %s rows without a configured sink', async network => {
const db = {
query: jest.fn(async sql => {
if (/ignored_reason = 'non_mainnet_network'/i.test(sql)) {
return { rows: [{ id: 1 }, { id: 2 }], rowCount: 2 };
}
if (/COUNT\(\*\) FILTER/i.test(sql)) return healthRows({ ignored_rows: '2' });
throw new Error(`unexpected SQL: ${sql}`);
})
};
const fetchFn = jest.fn();
const exporter = new FinancialEventExporter({
db,
env: { NODE_ENV: 'production', CRYPTO_TYPE: 'XMR', MONERO_NETWORK: network },
fetchFn,
logger: { warn: jest.fn() }
});
await expect(exporter.runOnce()).resolves.toEqual({
skipped: false, delivered: 0, deferred: 0, deadLettered: 0, ignored: 2
});
expect(fetchFn).not.toHaveBeenCalled();
expect(exporter.getHealth()).toEqual(expect.objectContaining({
exportAllowed: false, ignored: 2, ignoredRows: 2
}));
const suppressionSql = db.query.mock.calls.find(([sql]) =>
/ignored_reason = 'non_mainnet_network'/i.test(sql)
)[0];
expect(suppressionSql).toMatch(/lease_until = NULL/i);
expect(suppressionSql).toMatch(/dead_lettered_at = NULL/i);
expect(suppressionSql).toMatch(/status IN \('pending', 'in_flight', 'dead_letter'\)/i);
});
test('does not dead-letter an actively leased attempt from another worker', () => {
const source = fs.readFileSync(path.join(
__dirname, '../src/services/financialEventExporter.js'
), 'utf8');
expect(source).toMatch(
/status = 'in_flight' AND lease_until < NOW\(\)[\s\S]*RETURNING id/
);
});
test('wires sanitized exporter counters into public health without a readiness dependency', () => {
const indexSource = fs.readFileSync(path.join(__dirname, '../src/index.js'), 'utf8');
expect(indexSource).toMatch(
/health\.financialEvents = financialEventExporter\.getPublicHealth\(\)/
);
expect(indexSource).not.toMatch(
/ready\s*=\s*[^;\n]*financialEventExporter|getPublicHealth\(\)[^;\n]*ready/i
);
});
test('042 corrects 041 without rereading at delivery or exporting unsettled refunds', () => {
const migration = fs.readFileSync(path.join(
__dirname, '../src/migrations/042_immutable_financial_event_snapshots.sql'
), 'utf8');
expect(migration).toMatch(/payload_snapshot JSONB/i);
expect(migration).toMatch(/delivery_payload JSONB/i);
expect(migration).toMatch(/COALESCE\(p\.confirmed_at, p\.created_at, o\.created_at, NOW\(\)\)/i);
expect(migration).toMatch(/malformed_legacy_snapshot/i);
expect(migration).toMatch(/NEW\.status IN \('recorded', 'completed'\)/i);
expect(migration).toMatch(/WHERE r\.status IN \('recorded', 'completed'\)/i);
expect(migration).not.toMatch(/WHERE r\.status IN \([^)]*needs_review/i);
expect(migration).toMatch(/reject_financial_event_identity_mutation/i);
expect(migration).toMatch(
/payload_snapshot->>'event_id'\) IS NOT DISTINCT FROM event_id/i
);
expect(migration).toMatch(
/delivery_payload->>'id'\) IS NOT DISTINCT FROM event_id/i
);
expect(migration).toMatch(/OLD\.delivery_payload IS NOT NULL[\s\S]*NEW\.delivery_payload IS DISTINCT/i);
expect(migration).toMatch(
/OLD\.delivery_payload IS NULL AND NEW\.delivery_payload IS NOT NULL[\s\S]*OLD\.status IS DISTINCT FROM 'in_flight'/i
);
expect(migration).not.toMatch(/payout_address|subaddress|provider_invoice_id|evidence_id|tx_hash/i);
});
});
+8
View File
@@ -0,0 +1,8 @@
'use strict';
const path = require('path');
const { createRequire } = require('module');
// The application is the package boundary; top-level tests must resolve its dependencies from
// src/package.json instead of accidentally using an unrelated repository-root node_modules tree.
module.exports = createRequire(path.join(__dirname, '..', '..', 'src', 'package.json'));
+49 -2
View File
@@ -1,12 +1,13 @@
const { buildCommerceDisclosure } = require('../src/config/commerceDisclosurePolicy');
const { renderPrivacy, renderResponsiblePlay, renderTerms } = require('../src/views/legalPages');
function disclosure(overrides = {}) {
function disclosure(overrides = {}, managerOverrides = {}) {
const manager = {
cryptoType: 'WOW', currencyLabel: 'WOW', network: 'mainnet', isTestNetwork: false,
gameName: '<script>bad</script>', paymentsEnabled: true, freePlayEnabled: true,
directModeEnabled: true, creditsModeEnabled: true, payoutsEnabled: false,
isPayoutEnabledForMode: () => false
isPayoutEnabledForMode: () => false,
...managerOverrides
};
return buildCommerceDisclosure(manager, {
NODE_ENV: 'production', LEGAL_POLICY_VERSION: 'v1', TERMS_EFFECTIVE_DATE: '2026-07-21',
@@ -39,4 +40,50 @@ describe('production disclosure pages', () => {
expect(html).toContain('credits_prestige matches use the Prestige board');
expect(html).toContain('crypto_race matches use the Hall of Champions');
});
test('generic self-hosted pages carry the MIT conditions and third-party operator disclaimer', () => {
const html = renderTerms(disclosure());
expect(html).toContain('Independent deployment');
expect(html).toContain('solely responsible for its deployment');
expect(html).toContain('does not operate, supervise, endorse, or accept responsibility');
expect(html).toContain('copyright and permission notice');
expect(html).toContain('AS IS');
expect(html).toContain('not legal advice');
expect(html).toContain('operates only play.wowne.ro and monerogue.app');
});
test('play.wowne.ro pages state credits-only prestige and the no-payout product positioning', () => {
const html = renderTerms(disclosure({
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige'
}, {
directModeEnabled: false,
creditsModeEnabled: true
}));
expect(html).toContain('Such Software');
expect(html).toContain('apps@such.software');
expect(html).toContain('pay-for-credits leaderboard/prestige play');
expect(html).toContain('offers no prizes, winnings, cash-out, or payouts');
expect(html).toContain('not offered or marketed as gambling');
expect(html).toContain('legal classification depends on applicable law');
expect(html).not.toContain('NO REAL VALUE');
});
test('monerogue.app pages conspicuously state stagenet 2x/3x test gambling has no real value', () => {
const html = renderResponsiblePlay(disclosure({
OPERATED_PRODUCT_PROFILE: 'such-monerogue-stagenet'
}, {
cryptoType: 'XMR',
currencyLabel: 'sXMR',
network: 'stagenet',
isTestNetwork: true,
payoutsEnabled: true,
isPayoutEnabledForMode: () => true
}));
expect(html).toContain('single-player 2×/3× outcomes are test gambling mechanics');
expect(html).toContain('NO REAL VALUE');
expect(html).toContain('Never send mainnet XMR');
expect(html).toContain('no real-money or mainnet gambling is offered');
});
});
+113
View File
@@ -0,0 +1,113 @@
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const appRequire = require('./helpers/appRequire');
const dotenv = appRequire('dotenv');
const ROOT = path.join(__dirname, '..');
function parseExample(name) {
const contents = fs.readFileSync(path.join(ROOT, 'src', name), 'utf8');
return Object.fromEntries(contents.split(/\r?\n/).flatMap(line => {
const match = line.match(/^([A-Z][A-Z0-9_]*)=(.*)$/);
return match ? [[match[1], match[2]]] : [];
}));
}
function preflightExample(name) {
const contents = fs.readFileSync(path.join(ROOT, 'src', name), 'utf8');
const env = {
...dotenv.parse(contents),
DB_PASSWORD: '6f4d9b8270e1c35aa96d2408b75f13ce59a0472d7e86c914',
ADMIN_API_KEY: 'b12f078ce49d6a3510ef7b29d8435ca6982e04f17bd6593c',
WALLET_RPC_PASSWORD: '8ce2b970a64d1f35e0897c42db6513fa724eb960d18c53a7'
};
return spawnSync(process.execPath, [path.join(ROOT, 'src', 'scripts', 'preflight.js')], {
cwd: ROOT,
env,
encoding: 'utf8',
timeout: 10000
});
}
describe('operated product environment templates', () => {
test('play.wowne.ro is exactly credits-only Wownero prestige with every payout path off', () => {
const env = parseExample('.env.mainnet.example');
expect(env).toEqual(expect.objectContaining({
OPERATED_PRODUCT_PROFILE: 'such-play-wow-prestige',
HOSTED_BY: 'https://play.wowne.ro',
OPERATOR_NAME: 'Such Software',
OPERATOR_CONTACT_URL: 'mailto:apps@such.software',
OPERATOR_CONTACT_LABEL: 'apps@such.software',
LEGAL_POLICY_VERSION: '2026-07-22-v1',
TERMS_EFFECTIVE_DATE: '2026-07-22',
MINIMUM_AGE: '18',
PAID_ACKNOWLEDGEMENT_REQUIRED: 'true',
CRYPTO_TYPE: 'WOW',
MONERO_NETWORK: 'mainnet',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'credits',
DIRECT_PAYMENT_ENABLED: 'false',
CREDITS_ENABLED: 'true',
PAYOUTS_ENABLED: 'false',
DIRECT_PAYOUTS_ENABLED: 'false',
CREDITS_PAYOUTS_ENABLED: 'false',
ALLOW_MAINNET_PAYOUTS: 'false',
MATCH_CRYPTO_RACE_ENABLED: 'false',
MATCH_PAYOUTS_ENABLED: 'false'
}));
});
test('monerogue.app is exactly stagenet 2x/3x solo testing with crypto-match payouts off', () => {
const env = parseExample('.env.stagenet.example');
expect(env).toEqual(expect.objectContaining({
OPERATED_PRODUCT_PROFILE: 'such-monerogue-stagenet',
HOSTED_BY: 'https://monerogue.app',
OPERATOR_NAME: 'Such Software',
OPERATOR_CONTACT_URL: 'mailto:apps@such.software',
OPERATOR_CONTACT_LABEL: 'apps@such.software',
LEGAL_POLICY_VERSION: '2026-07-22-v1',
TERMS_EFFECTIVE_DATE: '2026-07-22',
MINIMUM_AGE: '18',
PAID_ACKNOWLEDGEMENT_REQUIRED: 'true',
CRYPTO_TYPE: 'XMR',
MONERO_NETWORK: 'stagenet',
FREE_PLAY_ENABLED: 'true',
PAYMENT_MODES: 'direct,credits',
PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUTS_ENABLED: 'true',
CREDITS_PAYOUTS_ENABLED: 'true',
DIRECT_PAYOUT_ESCAPE: '2.0',
DIRECT_PAYOUT_TREASURE: '3.0',
CREDITS_PAYOUT_ESCAPE: '2.0',
CREDITS_PAYOUT_TREASURE: '3.0',
ALLOW_MAINNET_PAYOUTS: 'false',
MATCH_CRYPTO_RACE_ENABLED: 'false',
MATCH_PAYOUTS_ENABLED: 'false'
}));
expect(BigInt(env.PAYOUT_MAX_PER_GAME)).toBeGreaterThanOrEqual(
3n * BigInt(env.DIRECT_GAME_PRICE)
);
expect(BigInt(env.PAYOUT_MAX_PER_GAME)).toBeGreaterThanOrEqual(
3n * BigInt(env.CREDITS_PAYOUT_BASE)
);
expect(env.COSMETIC_PRODUCTS).toBeUndefined();
});
test('the generic MIT self-hosting template does not opt into a Such Software profile', () => {
const env = parseExample('.env.example');
expect(env.OPERATED_PRODUCT_PROFILE).toBeUndefined();
});
test.each([
['.env.mainnet.example', 'paid modes: credits'],
['.env.stagenet.example', 'paid modes: direct, credits']
])('%s passes the real production preflight after only secret substitution', (name, summary) => {
const result = preflightExample(name);
expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' });
expect(result.stdout).toContain('Production configuration preflight passed');
expect(result.stdout).toContain(summary);
});
});
+3 -2
View File
@@ -1,6 +1,7 @@
const express = require('express');
const appRequire = require('./helpers/appRequire');
const express = appRequire('express');
const http = require('http');
const nacl = require('../src/node_modules/tweetnacl');
const nacl = appRequire('tweetnacl');
const createAuthRoutes = require('../src/routes/auth');
function normalized(sql) {
+2 -1
View File
@@ -14,6 +14,7 @@
// nostr-tools' self-contained pre-bundled build (an esbuild IIFE with deps inlined).
const fs = require('fs');
const path = require('path');
const appRequire = require('./helpers/appRequire');
function loadNostrTools() {
const cjsIndex = require.resolve('nostr-tools', { paths: [path.join(__dirname, '..', 'src')] });
try {
@@ -225,7 +226,7 @@ describe('verifyNip98Event — adversarial round-trip', () => {
});
describe('(ix) route layer — single-use challenge consume rejects replay', () => {
const express = require('express');
const express = appRequire('express');
const http = require('http');
const createAuthRoutes = require('../src/routes/auth');
+2 -1
View File
@@ -6,6 +6,7 @@ const path = require('path');
const {
LIVE_CONFIRM,
REQUIRED_MIGRATIONS,
SAFE_PROFILE_CONFIRM,
SCENARIOS,
addVisible,
@@ -172,7 +173,7 @@ describe('XMR stagenet financial canary safety contract', () => {
const row = {
users: 1,
seed_admins: 1,
required_migrations: 5,
required_migrations: REQUIRED_MIGRATIONS.length,
payments: 0,
games: 0,
payouts: 0,
@@ -0,0 +1,150 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const rootPath = (...parts) => path.join(__dirname, '..', ...parts);
const helperPath = rootPath('scripts', 'deploy', 'wallet-keyfile-recovery-proof.py');
const fixturePath = rootPath('scripts', 'deploy', 'wallet-keyfile-recovery-fixture-test.py');
const runbookPath = rootPath('docs', 'WALLET_KEYFILE_RECOVERY_PROOF.md');
describe('fixed wallet keyfile/password recovery proof boundary', () => {
const helper = fs.readFileSync(helperPath, 'utf8');
const runbook = fs.readFileSync(runbookPath, 'utf8');
test('accepts only the two audited legacy profiles and fixed recovery artifacts', () => {
for (const expected of [
'monero-wallet-rpc.service',
'/usr/bin/monero-wallet-rpc',
'/home/jw/Programs/monero-x86_64-linux-gnu-v0.18.4.4/test',
'monero-stagenet-preprod-20260721T1140Z.wallet',
'monero-stagenet-preprod-20260721T1140Z.keys',
'/run/wowngeon-wallet-keyfile-proof-monero-stagenet',
'wownero-wallet-rpc.service',
'/usr/bin/wownero-wallet-rpc',
'/home/jw/Programs/wow-11.3.0/game',
'wownero-mainnet-preprod-20260721T1140Z.wallet',
'wownero-mainnet-preprod-20260721T1140Z.keys',
'/run/wowngeon-wallet-keyfile-proof-wownero-mainnet',
]) {
expect(helper).toContain(expected);
}
expect(helper).toContain('live_rpc_port=38083');
expect(helper).toContain('proof_port=39084');
expect(helper).toContain('live_rpc_port=34570');
expect(helper).toContain('proof_port=39570');
expect(helper).toContain('if len(arguments) != 1 or arguments[0] not in PROFILES:');
expect(helper).not.toContain('argparse');
});
test('validates live identity before extracting and wiping the exact inline password', () => {
expect(helper).toContain('systemctl("is-active", "--quiet", profile.unit)');
expect(helper).toContain('process_executable(pid) != profile.binary');
expect(helper).toContain('process_executable_identity(pid) != expected_binary');
expect(helper).toContain('process_has_unit_cgroup(pid, profile.unit)');
expect(helper).toContain('require_exact_listener(');
expect(helper).toContain('b"--wallet-file"');
expect(helper).toContain('b"--password"');
expect(helper).toContain('f"/proc/{pid}/cmdline"');
expect(helper).toContain('os.readv(descriptor, [buffer])');
expect(helper).toContain('wipe_buffer(buffer, buffer_is_protected)');
expect(helper).toContain('PR_SET_DUMPABLE');
expect(helper).toContain('PR_SET_NO_NEW_PRIVS');
expect(helper).toContain('MADV_DONTDUMP');
expect(helper).not.toMatch(/systemctl\([^\n]*(?:stop|start|restart|reload|enable|disable)/);
});
test('drops candidate privilege and uses only fixed read/proof RPC methods', () => {
expect(helper).toContain('os.setgroups([])');
expect(helper).toContain('os.setgid(expected_gid)');
expect(helper).toContain('os.setuid(expected_uid)');
expect(helper).toContain('os.getresuid() != (expected_uid, expected_uid, expected_uid)');
expect(helper).toContain('os.getresgid() != (expected_gid, expected_gid, expected_gid)');
expect(helper).toContain('if process_groups(process.pid):');
expect(helper).toContain('process_status_integer(process.pid, "NoNewPrivs") != 1');
expect(helper).toContain('("CapInh", "CapPrm", "CapEff", "CapAmb")');
expect(helper).toContain('LIBC.prctl(PR_SET_KEEPCAPS, 0, 0, 0, 0)');
expect(helper).toContain('publish_candidate_tree(profile, expected_uid, expected_gid)');
expect(helper).toContain('"method": "get_address"');
expect(helper).toContain('rpc_request("sign", {"data": SIGN_MESSAGE})');
expect(helper).toContain('"verify",');
expect(helper).toContain('signature_type not in (None, "spend")');
expect(helper).toContain('"--offline"');
expect(helper).toContain('"--log-file"');
expect(helper).toContain('"/dev/null"');
expect(helper).toContain('password-file=');
expect(helper).toContain('rpc-bind-ip=127.0.0.1');
expect(helper).toContain('rpc-login=');
expect(helper).toContain('if status != 401:');
expect(helper).toContain('if status != 200:');
expect(helper).toContain('hmac.compare_digest(live_address, restored_address)');
for (const forbiddenMethod of [
'query_key',
'get_seed',
'get_spend_key',
'get_view_key',
'transfer_split',
'sweep_all',
]) {
expect(helper).not.toContain(`"method": "${forbiddenMethod}"`);
}
});
test('fails closed around source links, races, port collisions, and exact cleanup', () => {
expect(helper).toContain('details.st_nlink != 1');
expect(helper).toContain('O_NOFOLLOW');
expect(helper).toContain('file_identity(os.fstat(source_fd)) != expected_source');
expect(helper).toContain('refuse("proof-port-collision")');
expect(helper).toContain('secure_remove_proof_directory(');
expect(helper).toContain('(details.st_dev, details.st_ino) != expected_identity');
expect(helper).toContain('result=passed');
expect(helper).toContain('result=refused');
expect(helper).not.toMatch(/(?:import traceback|traceback\.)/);
expect(helper).not.toMatch(/\bprint\(/);
});
test('runbook keeps seed custody and off-host restore explicitly unproven', () => {
expect(runbook).toContain('has not been installed on or run against');
expect(runbook).toContain('This is **not seed custody**');
expect(runbook).toContain('it is **not an off-host disaster-recovery test**');
expect(runbook).toMatch(/record seed custody and off-host recovery as\s+\*\*unproven\*\*/);
expect(runbook).toContain('The proof candidate is offline');
expect(runbook).toMatch(/Wallet-RPC never runs\s+as root/);
expect(runbook).toContain('not from an independent custody source');
expect(runbook).toContain('**not** an RPC-hardening or');
expect(runbook).toContain('not evidence they have been run');
expect(runbook).toContain('do not blindly remove it');
});
test('synthetic fixture passes without opening a real wallet', () => {
const result = spawnSync('/usr/bin/python3', [fixturePath], {
encoding: 'utf8',
timeout: 15000,
});
expect({ status: result.status, signal: result.signal, stdout: result.stdout }).toEqual({
status: 0,
signal: null,
stdout: '',
});
expect(result.stderr).toContain('OK');
});
test('invalid invocation renders only the refusal status', () => {
const result = spawnSync('/usr/bin/python3', [helperPath, 'not-a-profile'], {
encoding: 'utf8',
timeout: 5000,
});
expect({
status: result.status,
signal: result.signal,
stdout: result.stdout,
stderr: result.stderr,
}).toEqual({
status: 1,
signal: null,
stdout: 'result=refused\n',
stderr: '',
});
});
});