Fix bank GUID serialization on T5 and T6 (Refs #15)
This commit is contained in:
+130
-11
@@ -2,9 +2,29 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { loadEcBank } from './tests/ec_bank_contract.mjs';
|
||||
const root = new URL('../', import.meta.url);
|
||||
const publicEndpoint = 'https://ec.thewrightserver.net/api/bank';
|
||||
const privateToken = 'ec_bank_' + 'a'.repeat(43);
|
||||
const ecIndex = process.argv.indexOf('--ec-root');
|
||||
const realEc = ecIndex < 0 ? undefined : loadEcBank(process.argv[ecIndex + 1]);
|
||||
|
||||
// EC src/lib/server/fleet/bank.ts token/transfer contract, also checked against
|
||||
// that actual implementation with --ec-root (no HTTP or production database).
|
||||
function assertContract(action, data) {
|
||||
const token = value => typeof value === 'string' && value.length > 0 && value.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value);
|
||||
const integer = (value, min = 0) => Number.isSafeInteger(value) && value >= min && value <= 1000000;
|
||||
assert.equal(data.server, 'server');
|
||||
assert(token(data.guid), 'EC requires a nonempty string GUID token');
|
||||
if (action === 'balance') return;
|
||||
assert(token(data.request_id)); assert(token(data.match));
|
||||
assert(['deposit','withdraw'].includes(data.operation));
|
||||
assert(integer(data.amount, 1) || (data.operation === 'withdraw' && data.amount === 'all'));
|
||||
assert(integer(data.capacity));
|
||||
assert(['commit','cancel'].includes(data.decision));
|
||||
if (action === 'deposit' || action === 'withdraw') assert.equal(action, data.operation);
|
||||
else assert.equal(action, data.decision);
|
||||
}
|
||||
function functions(source) {
|
||||
const literals = [];
|
||||
const protectedSource = source.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, token => {
|
||||
@@ -26,6 +46,7 @@ function functions(source) {
|
||||
const locals = new Set([...body.matchAll(/(?<![\w.])(\w+)\s*(?:[+*/%-]?=(?!=)|\+\+|--)/g)].map(x => x[1]));
|
||||
body = body.replace(/\.size\b/g, '.length').replace(/http::request/g, 'httpPost');
|
||||
body = body.replace(/player getGuid\(\)/g, 'getGuid(player)');
|
||||
body = body.replace(/typeof\(/g, 'gscType(');
|
||||
body = body.replace(/#(?=__literal_)/g, '');
|
||||
body = body.replace(/scripts\\(?:sp|zm)\\tws_t[56]_common::register_help_command/g, 'registerHelpCommand');
|
||||
body = body.replace(/level thread \w+\(\);/g, '').replace(/level notify\(/g, 'notify(');
|
||||
@@ -45,10 +66,14 @@ function engine(game, options = {}) {
|
||||
const source = readFileSync(new URL(`${game}/scripts/tws_${game}_bank.gsc`, root), 'utf8');
|
||||
const excluded = new Set(['bank_chat_listener','bank_end_watcher','bank_guard','bank_say','bank_request']);
|
||||
const functionsByName = functions(source);
|
||||
const player = { guid: '18446744073709551615', sessionstate: 'playing', score: 3000, score_total: 4000, pers: {}, alive: true };
|
||||
if (game === 't6') assert(!/\bgetGuid\s*\(/i.test(source), 'T6 bank must use the persistent field, as telemetry does');
|
||||
const identity = Object.hasOwn(options, 'guid') ? options.guid : '18446744073709551615';
|
||||
const player = { sessionstate: 'playing', score: 3000, score_total: 4000, pers: {}, alive: true };
|
||||
if (game === 't6') player.guid = identity;
|
||||
const entry = { player, active: true };
|
||||
const recovered = options.recovered ?? [];
|
||||
const saved = recovered.map(report => JSON.parse(report.body)), sent = [], messages = [], order = [], loaded = [], dvarsRead = [];
|
||||
const recovered = (options.recovered ?? []).map(report => ({...report}));
|
||||
const saved = recovered.map(report => JSON.parse(report.body)), writes = [], sent = [], messages = [], order = [], loaded = [], dvarsRead = [];
|
||||
let serial = 0;
|
||||
const dvars = { zombiemode: '1', tws_server_id: 'server', tws_bank_token: privateToken, ...options.dvars };
|
||||
function assertScope(server, url) {
|
||||
assert.equal(server, dvars.tws_server_id);
|
||||
@@ -59,36 +84,85 @@ function engine(game, options = {}) {
|
||||
GetDvar: name => { dvarsRead.push(name); return dvars[name] ?? ''; },
|
||||
getSubStr: (value, start, end) => value.substring(start, end), registerHelpCommand: () => {},
|
||||
isDefined: v => v !== undefined && v !== null, is_true: v => !!v, isAlive: p => p.alive,
|
||||
int: Math.trunc, getGuid: p => p.guid,
|
||||
int: Math.trunc,
|
||||
...(game === 't5' ? {getGuid: p => { assert.equal(p, player); return identity; }} : {}),
|
||||
gscType: value => typeof value === 'number' ? Number.isInteger(value) ? 'int' : 'float' : typeof value,
|
||||
jsonSerialize: a => JSON.stringify(Object.fromEntries(Object.entries(a))),
|
||||
bank_say: (_entry, message) => messages.push(message),
|
||||
telemetryNewMatch: () => 'request-1',
|
||||
telemetryNewMatch: () => `${options.idPrefix ?? 'request'}-${++serial}`,
|
||||
bankLoad: (server, url) => { assertScope(server, url); loaded.push({ server, url }); return recovered; },
|
||||
bankStore: (server, url, body) => {
|
||||
assertScope(server, url);
|
||||
const data = JSON.parse(body); order.push(data.decision);
|
||||
const data = JSON.parse(body); assertContract(data.decision, data);
|
||||
writes.push(data); order.push(data.decision);
|
||||
if (options.storageFailure === data.decision) return false;
|
||||
saved.splice(0, saved.length, data); return true;
|
||||
},
|
||||
bankRemove: (server, url) => { assertScope(server, url); if (options.removeFailure) return false; saved.length = 0; return true; },
|
||||
httpPost: (url, data) => { order.push('http'); sent.push({ url, ...data }); return options.noHandle ? undefined : {}; },
|
||||
httpPost: (url, data) => {
|
||||
assertContract(url.split('/').at(-1), JSON.parse(data.body));
|
||||
order.push('http'); sent.push({ url, ...data }); return options.noHandle ? undefined : {};
|
||||
},
|
||||
httpComplete: () => {
|
||||
options.during?.(c, entry);
|
||||
const action = sent.at(-1).url.split('/').at(-1);
|
||||
if (options.receiver) {
|
||||
const response = options.receiver(action, JSON.parse(sent.at(-1).body));
|
||||
return [JSON.stringify(response.body), !options.timeout, '', {http_status: response.status}];
|
||||
}
|
||||
const state = action === 'commit' ? 'committed' : action === 'cancel' ? 'cancelled' : action === 'balance' ? 'balance' : options.state ?? 'prepared';
|
||||
const reply = { valid: true, state, request_id: action === 'balance' ? '' : options.wrongId ? 'wrong' : JSON.parse(sent.at(-1).body).request_id, amount: options.amount ?? 2000, balance: options.balance ?? 5000, code: options.code ?? 'ok' };
|
||||
return [JSON.stringify(reply), !options.timeout, '', options.missingDiagnostics ? undefined : { http_status: options.status ?? 200 }];
|
||||
},
|
||||
bankResponse: data => options.malformed ? { valid: false } : JSON.parse(data),
|
||||
bankResponse: data => options.malformed ? { valid: false } : {valid:true, ...JSON.parse(data)},
|
||||
print: () => {}, println: () => {}
|
||||
});
|
||||
vm.runInContext([...functionsByName].filter(([name]) => !excluded.has(name)).map(([, code]) => code).join('\n'), c);
|
||||
c.init();
|
||||
return { c, player, entry, saved, sent, messages, order, loaded, dvarsRead, run: args => c.bank_transfer(entry,args) };
|
||||
return { c, player, entry, saved, writes, sent, messages, order, loaded, dvarsRead, run: args => c.bank_transfer(entry,args) };
|
||||
}
|
||||
let checks = 0;
|
||||
function journalEntries(engine) {
|
||||
// GSC associative arrays do not serialize as JS arrays. Copy the native
|
||||
// bankLoad shape while retaining the exact serialized decision body.
|
||||
return Array.from(engine.c.level.bank_queue, entry => ({id:entry.id, body:entry.body, decision:entry.decision}));
|
||||
}
|
||||
for (const game of ['t5','t6']) {
|
||||
function test(name, fn) { try { fn(); checks++; } catch (cause) { throw new Error(`${game}: ${name}`, {cause}); } }
|
||||
test('engine identities remain exact strings in balance, prepare, both decisions and restart replay', () => {
|
||||
for (const guid of [2741626, 0, '2741626', '0002741626', '18446744073709551615']) {
|
||||
for (const command of [['.b'], ['.d','2000'], ['.w','all']]) {
|
||||
for (const timeout of [false, true]) {
|
||||
const e = engine(game, {guid, timeout}); e.run(command);
|
||||
assert.equal(e.sent.length, 1);
|
||||
for (const data of [...e.writes, ...e.sent.map(request => JSON.parse(request.body))]) assert.equal(data.guid, String(guid));
|
||||
if (command[0] === '.b') { assert.equal(e.writes.length, 0); continue; }
|
||||
assert.equal(e.writes[0].decision, 'cancel');
|
||||
assert.equal(e.saved[0].decision, timeout ? 'cancel' : 'commit');
|
||||
const recovered = journalEntries(e);
|
||||
const restarted = engine(game, {guid:undefined, recovered});
|
||||
restarted.c.bank_sender().next();
|
||||
assert.equal(restarted.sent[0].body, recovered[0].body);
|
||||
assert.equal(JSON.parse(restarted.sent[0].body).guid, String(guid));
|
||||
assert.equal(restarted.saved.length, 0);
|
||||
assert.equal(restarted.player.score, 3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
test('missing or invalid identities reject before HTTP, journal writes or point changes', () => {
|
||||
for (const guid of [undefined, null, '', ' ', 'bad guid', 'x'.repeat(65), 'x\n', true, {}, [], 1.5]) {
|
||||
for (const command of [['.b'], ['.d','2000'], ['.w','all']]) {
|
||||
const e = engine(game, {guid}); e.run(command);
|
||||
assert.match(e.messages[0], /player identity unavailable/);
|
||||
assert.equal(e.sent.length, 0); assert.equal(e.writes.length, 0);
|
||||
assert.equal(e.c.level.bank_write, 0); assert.equal(e.player.score, 3000);
|
||||
assert.equal(e.player.score_total, 4000);
|
||||
}
|
||||
}
|
||||
const e = engine(game); e.entry.player = undefined; e.run(['.b']);
|
||||
assert.match(e.messages[0], /player identity unavailable/); assert.equal(e.sent.length, 0);
|
||||
});
|
||||
test('startup and every request ignore obsolete endpoint overrides and retain instance authentication', () => {
|
||||
for (const url of ['', 'https://controller.internal/api/bank', 'http://old-controller/api/bank', 'https://untrusted.example/api/bank']) {
|
||||
for (const command of [['.b'], ['.d','2000'], ['.w','all']]) {
|
||||
@@ -120,7 +194,7 @@ for (const game of ['t5','t6']) {
|
||||
const e=engine(game); e.run(['.d','2000']);
|
||||
assert.equal(e.player.score,1000); assert.equal(e.player.score_total,4000); assert.equal(e.player.pers.score,1000);
|
||||
assert.deepEqual(e.order,['cancel','http','commit']); assert.equal(e.saved[0].decision,'commit');
|
||||
assert.equal(e.saved[0].guid,e.player.guid);
|
||||
assert.equal(e.saved[0].guid,'18446744073709551615');
|
||||
assert.equal(e.sent[0].headers.Authorization,'Bearer ' + privateToken);
|
||||
assert.equal(e.sent[0].timeout_ms,15000);
|
||||
});
|
||||
@@ -169,7 +243,7 @@ for (const game of ['t5','t6']) {
|
||||
});
|
||||
test('recovered commit and cancel decisions retry at the public endpoint without applying points', () => {
|
||||
for (const decision of ['commit','cancel']) {
|
||||
const body = JSON.stringify({server:'server', request_id:'recovered', decision});
|
||||
const body = JSON.stringify({server:'server', guid:'18446744073709551615', request_id:'recovered', match:'old-match', operation:'withdraw', amount:'all', capacity:999370, decision});
|
||||
const options = {timeout:true, dvars:{tws_bank_url:'https://controller.internal/api/bank'}, recovered:[{id:'recovered', body, decision}]};
|
||||
const e = engine(game, options), sender = e.c.bank_sender();
|
||||
sender.next();
|
||||
@@ -194,5 +268,50 @@ for (const game of ['t5','t6']) {
|
||||
assert(!c.bank_resolved('commit','cancelled')); assert(!c.bank_resolved('cancel','committed'));
|
||||
assert(c.bank_resolved('cancel','rejected')); assert(c.bank_resolved('commit','committed'));
|
||||
});
|
||||
if (realEc) test('actual EC rejects numeric GUIDs and settles normalized script payloads exactly once', () => {
|
||||
for (const guid of [2741626, '2741626', '0002741626', '18446744073709551615']) {
|
||||
const ec = realEc(String(guid));
|
||||
try {
|
||||
// Reproduce the live rejection before any EC transaction exists.
|
||||
const numeric = {server:'server', guid:2741626, match:'match', request_id:'old-cancel', operation:'withdraw', amount:'all', capacity:999370, decision:'cancel'};
|
||||
for (const action of ['balance','withdraw','cancel','commit']) {
|
||||
const rejected = ec.request(action, numeric);
|
||||
assert.equal(rejected.status, 400); assert.equal(rejected.body.code, 'invalid_request');
|
||||
assert.equal(rejected.body.request_id, '');
|
||||
}
|
||||
assert.equal(ec.requests().length, 0);
|
||||
const e = engine(game, {guid, receiver:ec.request});
|
||||
e.run(['.b']); assert.equal(e.messages[0], '^3Bank: ^70 ^3points; available: ^70');
|
||||
e.run(['.w','all']); assert.match(e.messages.at(-1), /Not enough bank balance/);
|
||||
assert.equal(e.player.score, 3000); assert.equal(e.saved[0].decision, 'cancel');
|
||||
e.c.bank_sender().next(); assert.equal(e.saved.length, 0);
|
||||
|
||||
e.run(['.d','2000']); assert.equal(e.player.score, 1000);
|
||||
assert.equal(e.saved[0].decision, 'commit');
|
||||
const recovered = journalEntries(e);
|
||||
const options = {guid:undefined, receiver:ec.request, recovered, removeFailure:true};
|
||||
const replay = engine(game, options), sender = replay.c.bank_sender();
|
||||
sender.next(); sender.next(); // EC commits once even when cleanup fails.
|
||||
assert.equal(replay.saved.length, 1); assert.equal(replay.player.score, 3000);
|
||||
assert.deepEqual(ec.ledger(), [{guid:String(guid), amount:2000}]);
|
||||
options.removeFailure = false; sender.next(); assert.equal(replay.saved.length, 0);
|
||||
for (const request of replay.sent) assert.equal(request.body, recovered[0].body);
|
||||
|
||||
const withdrawal = engine(game, {guid, receiver:ec.request, idPrefix:'withdraw'});
|
||||
withdrawal.run(['.w','all']); assert.equal(withdrawal.player.score, 5000);
|
||||
withdrawal.c.bank_sender().next(); assert.equal(withdrawal.saved.length, 0);
|
||||
assert.deepEqual(ec.ledger(), [{guid:String(guid), amount:2000}, {guid:String(guid), amount:-2000}]);
|
||||
|
||||
const cancel = engine(game, {guid, receiver:ec.request, idPrefix:'cancel', during:(_c, entry) => {entry.player.alive = false;}});
|
||||
cancel.run(['.d','2000']); assert.equal(cancel.saved[0].decision, 'cancel');
|
||||
const restart = engine(game, {guid:undefined, receiver:ec.request, recovered:journalEntries(cancel)});
|
||||
restart.c.bank_sender().next(); assert.equal(restart.saved.length, 0);
|
||||
assert.equal(cancel.player.score, 3000); assert.equal(ec.ledger().length, 2);
|
||||
assert.equal(ec.requests().find(row => row.request_id === 'cancel-1').state, 'cancelled');
|
||||
assert(ec.requests().every(row => row.guid === String(guid)));
|
||||
} finally { ec.close(); }
|
||||
}
|
||||
});
|
||||
}
|
||||
console.log(`PASS ${checks} bank script fixtures (T5 and T6); live VM checks still required.`);
|
||||
console.log(realEc ? 'PASS actual EC bank service and SQLite integration.' : 'Actual EC integration skipped; pass --ec-root /path/to/electric-cherry to include it.');
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// Optional integration with a local EC checkout. Execute its real bank service
|
||||
// and bank migrations against disposable SQLite, with minimal fleet fixtures.
|
||||
// No EC configuration, credentials, HTTP routes or production DB are loaded.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
|
||||
export function loadEcBank(directory) {
|
||||
assert(directory, '--ec-root requires an EC checkout with installed dependencies');
|
||||
const requireEc = createRequire(resolve(directory, 'package.json'));
|
||||
const ts = requireEc('typescript');
|
||||
const Database = requireEc('better-sqlite3');
|
||||
function compile(file) {
|
||||
const source = readFileSync(resolve(directory, 'src/lib/server', file), 'utf8');
|
||||
return new vm.Script(ts.transpileModule(source, {
|
||||
compilerOptions: {module:ts.ModuleKind.CommonJS, target:ts.ScriptTarget.ES2022}
|
||||
}).outputText, {filename:file});
|
||||
}
|
||||
const service = compile('fleet/bank.ts');
|
||||
const bankMigration = compile('db/bank.ts');
|
||||
const credentialMigration = compile('db/bank-credentials.ts');
|
||||
return guid => {
|
||||
const database = new Database(':memory:');
|
||||
function execute(script) {
|
||||
const context = vm.createContext({
|
||||
exports: {}, process: {env:{}},
|
||||
require: name => {
|
||||
assert.equal(name, '../db/index.js', 'unexpected EC runtime dependency');
|
||||
return {db:() => database};
|
||||
}
|
||||
});
|
||||
script.runInContext(context);
|
||||
return context.exports;
|
||||
}
|
||||
database.exec(`
|
||||
CREATE TABLE native_instances (id TEXT PRIMARY KEY, server TEXT, retired_at TEXT);
|
||||
INSERT INTO native_instances VALUES ('instance', 'server', NULL);
|
||||
CREATE TABLE servers (name TEXT PRIMARY KEY, destroyed_at TEXT);
|
||||
INSERT INTO servers VALUES ('server', NULL);
|
||||
CREATE TABLE leaderboard_matches (id INTEGER PRIMARY KEY, server TEXT, reporter_match_key TEXT, status TEXT);
|
||||
INSERT INTO leaderboard_matches VALUES (1, 'server', 'match', 'active');
|
||||
CREATE TABLE leaderboard_match_players (match_id INTEGER, guid TEXT, present INTEGER);
|
||||
`);
|
||||
database.prepare('INSERT INTO leaderboard_match_players VALUES (1, ?, 1)').run(guid);
|
||||
execute(bankMigration).migrateBank(database);
|
||||
execute(credentialMigration).migrateBankCredentials(database);
|
||||
const {bankRequest} = execute(service);
|
||||
return {
|
||||
request: (action, body) => bankRequest(action, body, 'server', 'instance'),
|
||||
ledger: () => database.prepare('SELECT guid, amount FROM bank_ledger ORDER BY id').all(),
|
||||
requests: () => database.prepare('SELECT request_id, guid, state FROM bank_requests ORDER BY request_id').all(),
|
||||
close: () => database.close()
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user