seriesoftubes/scripts/lib/mp-sim-acts.js
jvanvik 7967a29083 Rent low-orbit satellite capacity from Starblink (#83)
A Starblink gateway on a teleport at a POP on your fiber (level 5, within
56 degrees of the equator) rents LEO circuits of 5 to 50 Gbps to small
islands and remote towns within 1,200 km: a bent pipe 550 km up, about
30 ms round trip, 3% of the service counted as bad, and no selective
network refuses it. LEO puts GEO and MEO circuits on the same pair on
standby and waits beside a cable. The gateway's Infra section shows its
POP's forwarding load and the fiber out of the city, the islands'
bottleneck. A rare solar storm (and Pie's own) puts LEO in safe mode for
a day or two. Once your own crust carries traffic Starblink sells nothing
new. Rule O8. Hooks for island Wi-Fi: leoReachLL, leoKmLL, leoMsLL.
2026-11-12 01:34:46 +01:00

642 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// What a page of a server-run network may ask the session server to do, as plain data, and the envelope check every
// request body passes before anything reaches a game (docs: the server-sim design, sections 5.8-5.9 and 10).
// Shared by the realm (scripts/lib/mp-sim-realm.js), the host (scripts/lib/mp-sim.js) and the page's own copies
// (src/game/98-server-play/40-acts.js), which tests hold equal to these tables. Plain data only: no game code here,
// and nothing here is ever evaluated.
//
// Every ACT is in exactly one of SEND, ASK, VOTE, LOCAL or PUZZLE (tests/mp-sim-contract.test.js names the act and this
// file when one is not). SEND is the agent's API_CMD minus the pz* acts and teCheck, traceRun, closeModal, plus
// connCancel, pieRename and tutSkip: a test derives it again, so nobody counts it by hand.
'use strict';
// Acts that change the game: the page sends them, the server runs them as a click (ACT[act](args)).
const SEND = [
'accept',
'acceptFix',
'ad',
'addCh',
'addGen',
'addPair',
'addRouter',
'addSite',
'applyCn',
'bstdApply',
'bstdSet',
'buildLink',
'buildPop',
'buildScrub',
'buyIx',
'buyNni',
'buySat',
'buySpare',
'buyTE',
'buyTransit',
'buyVxc',
'cache',
'cacheSite',
'callBank',
'cancelIx',
'cancelPni',
'cancelTransit',
'cancelVxc',
'charter',
'cleanPipe',
'confGo',
'confSponsor',
'connCancel',
'coreLab',
'coreSet',
'coreUp',
'crews',
'ddosAuto',
'ddosEngage',
'ddosTest',
'decline',
'declineLoan',
'decomGo',
'demoAsk',
'dkAccept',
'dkHaggle',
'dkOptOut',
'dkStay',
'dkWalk',
'downIx',
'downP',
'downT',
'dropBiz',
'fixInc',
'foundIx',
'hackback',
'hwLock',
'ip4Back',
'ip4Buy',
'ip4Lease',
'ip4Nat',
'ip4Nat64',
'ip4Out',
'ip4Return',
'ip4Sell',
'ip6Go',
'ip6Stop',
'lagIx',
'lagNni',
'lagP',
'lagT',
'launchBB',
'layShip',
'listFiber',
'metricMode',
'metricSet',
'mkBanana',
'mktCfg',
'mktHold',
'mktRoute',
'myIxUp',
'opsCap',
'opsFire',
'opsFloor',
'opsHire',
'opsNewPop',
'opsParam',
'opsPop',
'opsToggle',
'opsTpl',
'orderCable',
'orderDf',
'pathAuto',
'pathMove',
'pathPin',
'peer',
'peerAll',
'peerPol',
'pieAnt',
'pieBid',
'pieDish',
'pieExim',
'pieFactory',
'pieFound',
'pieLaunch',
'pieLic',
'pieName',
'piePad',
'pieRd',
'pieRename',
'pieSafe',
'pieSpatPick',
'pni',
'pniAll',
'pniChase',
'popStdClear',
'popStdSet',
'ptAll',
'ptApply',
'ptSave',
'regen',
'renameGo',
'renewLet',
'renewMatch',
'renewMeet',
'repayLoan',
'rmCache',
'rmCh',
'rmLink',
'rmNni',
'rmRouter',
'rmScrub',
'rmSite',
'rs',
'rtbh',
'sacrif',
'salesAuto',
'salesFire',
'salesHire',
'salesMin',
'salesRen',
'salesVp',
'satSize',
'scrubMode',
'scrubUp',
'seaRush',
'seatBuy',
'seatNo',
'sellSpare',
'setCarry',
'setChCount',
'setMetric',
'setPref',
'setRoute',
'setStandby',
'siteSet',
'spares',
'subUpgrade',
'takeLoan',
'teClear',
'teDeploy',
'teToggle',
'teleBuild',
'teleLeo',
'teleLeoRm',
'teleRm',
'teleTrk',
'togglePrem',
'tutSkip',
'unlistFiber',
'unpeer',
'unrtbh',
'upLink',
'upRouter',
'upSys',
'upVxc',
'utilityCaches',
'utilityKit',
'utilityKitAll',
'utilityKitNew',
'utilityPeers',
'utilityRouteServers',
'xpBuild',
'xpCh',
];
// What-ifs the server answers with the window they open, putting the game back as it was (5.9).
const ASK = ['linkCheck', 'teCheck', 'teSlop'];
// The clock's buttons: on a server network they are a vote for the session's speed (4.5).
const VOTE = ['phonePlay', 'phoneSpeed', 'speed'];
// The page runs these itself: views, drafts, settings, slots, session acts, teOpt.
const LOCAL = [
'addParallel',
'animSet',
'bank',
'bankClose',
'bstdOpen',
'chaosSet',
'chartToggle',
'closeModal',
'closePanel',
'cnPrem',
'connCity',
'connF',
'connFor',
'connNet',
'connOpen',
'connSort',
'cont',
'custCity',
'custF',
'custGo',
'custOpen',
'custSort',
'dash',
'dashClose',
'dashLink',
'dashSort',
'dashTab',
'decomOpen',
'decomToggle',
'dfMode',
'dfSrc',
'dfSys',
'exportSave',
'findGo',
'findLink',
'findOpen',
'focusCity',
'goConn',
'goEgress',
'help',
'helpClose',
'importGo',
'importPick',
'install',
'ip4Open',
'ip4Pick',
'keepPlaying',
'keys',
'langSet',
'leaseSwap',
'leftTab',
'linkTo',
'listMore',
'logAll',
'logOpen',
'mapSet',
'marketOpen',
'meetGo',
'menu',
'modeSet',
'models',
'mpBack',
'mpChat',
'mpCopyLink',
'mpDoor',
'mpJoin',
'mpKeep',
'mpLeave',
'mpLeaveAsk',
'mpNewer',
'mpOpen',
'mpShare',
'mpStart',
'mute',
'netClear',
'netFilter',
'netFind',
'netFocus',
'netOnly',
'newgame',
'nocWindow',
'offerStep',
'openVxc',
'opsCity',
'opsOpen',
'ownCab',
'pathOpen',
'phoneTab',
'pickHome',
'pickStart',
'pieCity',
'pieGlobeNight',
'pieGovOpen',
'pieHi',
'pieIns',
'pieLas',
'pieOpen',
'pieSpatOpen',
'pieTab',
'pitchSkip',
'pniAllOpen',
'pniAllSize',
'pniFilter',
'pniGrp',
'pniSort',
'popGo',
'popStep',
'popsReg',
'popsSort',
'prefSet',
'presetSet',
'puzzleDoor',
'puzzleMenu',
'randomName',
'rename',
'resetAsk',
'route',
'routingOpen',
'salesOpen',
'satOpen',
'scenarios',
'seaDesign',
'seaPackage',
'selLink',
'settings',
'settingsClose',
'share',
'shareDl',
'shareGo',
'slotBack',
'slotDel',
'slotDelGo',
'slotExport',
'slotMenu',
'slotRetry',
'slotSpace',
'slotSwitch',
'slotTake',
'soundSet',
'start',
'startScn',
'startWeekly',
'tab',
'tailTog',
'teBack',
'teClose',
'teEdit',
'teExample',
'teHelp',
'teOpt',
'teRecipe',
'themeSet',
'toTitle',
'toggleLeft',
'trace',
'traceCopy',
'traceMode',
'traceRun',
'updateLater',
'updateNow',
'utilities',
'utilityPick',
'via',
'vpSet',
'whatsNewShow',
'wsShare',
'xfer',
'xferFile',
'xferLink',
'xferPaste',
'xferRecv',
'xferShare',
'xpOpen',
'zoomStep',
];
// Puzzles never run on the server: they stay on the device, like everything that starts with pz.
const PUZZLE = [
'pzAddPar',
'pzArAll',
'pzArGo',
'pzArNext',
'pzArSkip',
'pzArStart',
'pzCity',
'pzDiv',
'pzFinish',
'pzLeave',
'pzLink',
'pzLinkTo',
'pzLook',
'pzMkSkip',
'pzMonkey',
'pzPop',
'pzReset',
'pzRetry',
'pzRmLink',
'pzRmPop',
'pzRoute',
'pzRtAdd',
'pzRtModel',
'pzRtRm',
'pzShare',
'pzStart',
'pzTab',
'pzTier',
'pzUndo',
'pzVia',
'pzWeekly',
];
/* Two-click buttons: the first click arms the button on the page (a view change), only the second is sent, with
confirmed:true. 'arg': the act takes ok:1 and runs at once. Anything else: the key the first click writes to
UI.confirm, as a template over the act's args ({id} is String(args.id)); the server sets UI.confirm to it and runs the
act once. */
const CONFIRM = {
cancelIx: 'arg',
cancelPni: 'arg',
cancelTransit: 'arg',
cancelVxc: '{id}',
connCancel: 'cc:{k}:{id}',
dkOptOut: 'dk{city}{n}',
dropBiz: '{id}',
ip4Sell: '{id}',
opsFire: 'opsFire',
repayLoan: '{id}',
rmLink: '{id}',
rmScrub: 'scrub:{city}',
rmSite: 'site{city}',
salesFire: 'salesFire',
teleLeoRm: 'leo:{city}',
teleRm: 'tele:{city}',
};
// The UI.confirm key a preset act's first click writes (null for 'arg' acts and acts that do not confirm).
const SRV_ARM = Object.fromEntries(Object.entries(CONFIRM).filter(([, v]) => v !== 'arg'));
function armKey(act, args) {
const t = Object.prototype.hasOwnProperty.call(SRV_ARM, act) ? SRV_ARM[act] : null;
return t === null ? null : t.replace(/\{(\w+)\}/g, (m, k) => String(args && args[k] !== undefined ? args[k] : ''));
}
/* The UI drafts an act reads, and the only UI keys a request may set (its ui object). Types are checked here; the realm
checks the values against the game's catalogs (cities, CABLES, DF_SYS, SEA_DESIGNS, the route picker's values). */
const DRAFTS = {
buildLink: ['pending', 'route', 'via', 'cnPrem'],
decomGo: ['decom'],
orderCable: ['pending', 'seaDesign', 'seaterminal', 'seaengineering'],
orderDf: ['pending', 'dfSrc', 'dfSys'],
pieLaunch: ['pieIns', 'pieLas'],
teDeploy: ['slop'],
};
// pair: {a, b}, two different city-like ids; id: a short id string; ids: an array of at most 200 of them (a Set in the game).
const DRAFT_TYPES = {
cnPrem: 'boolean',
decom: 'ids',
dfSrc: ['lease', 'build', 'cable'],
dfSys: 'id',
pending: 'pair',
pieIns: 'boolean',
pieLas: 'boolean',
route: 'string',
seaDesign: 'id',
seaengineering: 'boolean',
seaterminal: 'boolean',
slop: 'boolean',
via: 'string',
};
// Args longer than the envelope's 64 characters: their own cap (the game cuts the texts shorter itself).
const TEXT = {
metricSet: { v: 16 },
// A pinned path's cities, comma-separated: a long path is longer than 64 characters.
pathPin: { via: 1024 },
pieRename: { name: 64 },
renameGo: { name: 64 },
teCheck: { script: 4000 },
teDeploy: { script: 4000 },
utilityCaches: { quote: 1024 },
// An express's spans, as link ids joined by ',' (up to XP_HOPS = 6 ids of about 10 characters).
xpBuild: { via: 256 },
};
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
showed. The game refuses a different one ("The quote changed"); the server also refuses a request without it.
'quote' is the plan's key (a string), any other name the total (a number). pniAll: the exact total (fixed prices, so
the total names the plan). bstdApply: the plan's key, plus its total q, which may drift 1% (hardware prices move
daily under the market rule). utilityKit, utilityKitAll, acceptFix, ptApply, ptAll: the total, within 1% (each prices
routers, so a day's drift moves it; ptApply's "Mark it" sends 0). utilityCaches: the list of boxes. */
const QUOTE = {
acceptFix: 'cost',
bstdApply: 'quote',
pniAll: 'q',
ptAll: 'cost',
ptApply: 'cost',
utilityCaches: 'quote',
utilityKit: 'cost',
utilityKitAll: 'cost',
};
/* The windows a request's ctx.win may name: the one the page has open when the click came from inside it. The game asks
which window is open by its class and by a marker inside it (pieRe: class 'pie'; bstdShown: [data-sheet="bstd"];
routingRefresh: [data-routing]; charter), so the realm's stand-in has to be that window, or a redraw on the server
opens another one. c: its class (#modal's className); sel: the marker inside #modalCard, if it has one; ui: the view
state it draws from that only the page holds (set by LOCAL acts: the intern window's POP, the pie window's tab and
POP), each checked against the game in the realm. The page names the first entry, in this order, whose c is the open
window's class and whose sel (when it has one) matches inside it; a window none names is sent as ctx.modal alone. */
const WINDOWS = {
bstd: { c: 'ops', sel: '[data-sheet="bstd"]' },
routing: { c: '', sel: '[data-routing]' },
charter: { c: 'charter' },
ops: { c: 'ops', ui: ['opsCity'] },
pie: { c: 'pie', ui: ['pieCity', 'pieTab'] },
};
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
const VIEW_MIN = 200, VIEW_MAX = 4000;
const PREFS = ['pauseFurious', 'pauseIncident', 'warnUnhappy'];
const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.keys(CONFIRM)) };
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
// Keys a request object may never carry, whatever the regex says; nor values, where a value names something: written
// through as a key (S.pops[city]), they reach a prototype, and any name Object.prototype has ('toString', 'valueOf')
// reads as something there. Free text (TEXT) may say them.
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
const badVal = (v) => (typeof v === 'string' ? BAD_KEY.has(v) || v in Object.prototype : Array.isArray(v) ? v.some(badVal) : !!v && typeof v === 'object' && Object.keys(v).some((k) => BAD_KEY.has(k) || badVal(v[k])));
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
function checkArgs(act, args) {
if (!plain(args)) return 'args must be an object';
const keys = Object.keys(args);
if (keys.length > 12) return 'too many args';
const caps = own(TEXT, act) ? TEXT[act] : {};
for (const k of keys) {
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
if (!own(caps, k) && badVal(v)) return `bad arg ${k}`;
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
if (!prim(v, cap)) return `bad arg ${k}`;
}
if (own(QUOTE, act)) { const q = args[QUOTE[act]]; if (QUOTE[act] === 'quote' ? typeof q !== 'string' : !(typeof q === 'number' && Number.isFinite(q))) return `${act} needs the quoted ${QUOTE[act]}`; }
return null;
}
function checkDraft(k, v) {
const t = DRAFT_TYPES[k];
if (badVal(v)) return false;
if (Array.isArray(t)) return t.includes(v);
if (t === 'boolean') return typeof v === 'boolean';
if (t === 'string') return typeof v === 'string' && v.length <= 64;
if (t === 'id') return typeof v === 'string' && SHORT_RE.test(v);
// Two different places: the game's own drag never opens a link from a city to itself.
if (t === 'pair') return plain(v) && Object.keys(v).length === 2 && typeof v.a === 'string' && typeof v.b === 'string' && SHORT_RE.test(v.a) && SHORT_RE.test(v.b) && v.a !== v.b;
if (t === 'ids') return Array.isArray(v) && v.length <= 200 && v.every((x) => typeof x === 'string' && SHORT_RE.test(x));
return false;
}
function checkCtx(c) {
if (!plain(c)) return 'ctx must be an object';
for (const k of Object.keys(c)) {
const v = c[k];
if (k === 'sel') { if (v !== null && !(plain(v) && Object.keys(v).length === 2 && (v.type === 'city' || v.type === 'link') && typeof v.id === 'string' && SHORT_RE.test(v.id))) return 'bad ctx.sel'; }
else if (k === 'tab' || k === 'left') { if (v !== null && !(typeof v === 'string' && VIEW_RE.test(v))) return `bad ctx.${k}`; }
else if (k === 'modal' || k === 'coarse') { if (typeof v !== 'boolean') return `bad ctx.${k}`; }
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
// The open window, by name, with its view state (WINDOWS): {k, ui?}.
else if (k === 'win') {
const W = plain(v) && typeof v.k === 'string' && own(WINDOWS, v.k) ? WINDOWS[v.k] : null;
if (!W || !Object.keys(v).every((x) => x === 'k' || x === 'ui')) return 'bad ctx.win';
if (v.ui !== undefined && !(plain(v.ui) && Object.keys(v.ui).every((u) => (W.ui || []).includes(u) && (v.ui[u] === null || (typeof v.ui[u] === 'string' && SHORT_RE.test(v.ui[u]) && !badVal(v.ui[u])))))) return 'bad ctx.win.ui';
}
else return `unknown ctx.${String(k).slice(0, 20)}`;
}
return null;
}
const bool = (v) => v === undefined || typeof v === 'boolean';
/* The envelope of one request body, before anything reaches a game. kind: 'act' | 'ask' | 'vote' | 'here' | 'prefs'.
opts.sim: the server's build id; a request built by another one answers 409 {old:true}. Returns {ok:true} or
{ok:false, code (400 or 409), error, old?}. Only shapes are checked here; what the ids name is the realm's to check.
One repair, in place: ctx.w and ctx.h (any finite width up to 100000) are clamped into VIEW_MIN–VIEW_MAX, so the
realm only ever sees a viewport in that range. */
function checkEnvelope(kind, body, opts = {}) {
if (!plain(body)) return bad('the body must be a JSON object');
const keys = Object.keys(body);
const only = (allowed) => { for (const k of keys) if (!allowed.includes(k)) return `unknown field ${JSON.stringify(k).slice(0, 40)}`; return null; };
const simOk = () => {
if (typeof body.sim !== 'string' || !SIM_RE.test(body.sim)) return bad('sim must be the page\'s build id');
if (opts.sim && body.sim !== opts.sim) return bad('this page is from another build', 409, { old: true });
return null;
};
if (kind === 'act' || kind === 'ask') {
const e = only(kind === 'act' ? ['rid', 'dev', 'sim', 'act', 'args', 'ui', 'confirmed', 'ctx'] : ['rid', 'dev', 'sim', 'act', 'args', 'ctx']);
if (e) return bad(e);
if (typeof body.rid !== 'string' || !ID_RE.test(body.rid)) return bad('bad rid');
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
const s = simOk(); if (s) return s;
if (typeof body.act !== 'string' || !(kind === 'act' ? SETS.SEND : SETS.ASK).has(body.act)) return bad(`${kind} ${JSON.stringify(String(body.act).slice(0, 40))} is not one the server runs`);
const a = checkArgs(body.act, body.args === undefined ? {} : body.args); if (a) return bad(a);
if (body.ui !== undefined) {
if (kind !== 'act' || !plain(body.ui)) return bad('bad ui');
const allowed = own(DRAFTS, body.act) ? DRAFTS[body.act] : [];
for (const k of Object.keys(body.ui)) if (!allowed.includes(k) || !checkDraft(k, body.ui[k])) return bad(`bad ui.${String(k).slice(0, 20)}`);
}
if (body.confirmed !== undefined && (body.confirmed !== true || !SETS.CONFIRM.has(body.act))) return bad('confirmed only goes with a two-click act');
if (body.ctx !== undefined) { const c = checkCtx(body.ctx); if (c) return bad(c); }
return { ok: true };
}
if (kind === 'vote') {
const e = only(['speed', 'sim']); if (e) return bad(e);
const s = simOk(); if (s) return s;
if (body.speed !== null && !SPEEDS.includes(body.speed)) return bad('bad speed');
return { ok: true };
}
if (kind === 'here') {
const e = only(['dev', 'hidden', 'hold', 'idle', 'away', 'view']); if (e) return bad(e);
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
if (!['hidden', 'hold', 'idle', 'away'].every((k) => bool(body[k]))) return bad('bad flag');
if (body.view !== undefined) {
const v = body.view;
if (v !== null && !(plain(v) && Object.keys(v).every((k) => (k === 'link' || k === 'peer') && (v[k] === null || (typeof v[k] === 'string' && SHORT_RE.test(v[k])))))) return bad('bad view');
}
return { ok: true };
}
if (kind === 'prefs') {
const e = only(['prefs', 'lang']); if (e) return bad(e);
if (body.prefs !== undefined && !(plain(body.prefs) && Object.keys(body.prefs).every((k) => PREFS.includes(k) && typeof body.prefs[k] === 'boolean'))) return bad('bad prefs');
if (body.lang !== undefined && !(typeof body.lang === 'string' && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(body.lang))) return bad('bad lang');
return { ok: true };
}
return bad(`unknown kind ${String(kind).slice(0, 20)}`);
}
// Body size caps per kind, in bytes (section 10), for the host's readJson.
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, WINDOWS, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };