seriesoftubes/scripts/lib/mp-sim-acts.js
jvanvik 08eb349d87
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
Merge upstream: POP standards, latency contracts, device transfer, typed links and NOC downgrades (3.4.0, 3.5.0)
Conflicts, file by file:
- CHANGELOG.md: the fork's Unreleased bullets on top; 3.5.0 and 3.4.0 exactly as upstream has them.
- src/i18n/en.js, site/i18n/{de,es,fr,it,pt}.js: merged label by label, sorted; the labels each side dropped stay dropped.
- src/agent/10-domains.js, 30-docs.js, 40-read.js: both sides' enums, state docs and tables (popStd as the build standard, popTiers, ip4, mp).
- src/agent/20-commands.js: the fork's wording on accept and upRouter, upstream's acceptFix, utilityKitAll/New and pt*; theme, session and transfer acts in the local table.
- src/game/60-features/80-new-game.js: ip4, rgen and mp next to popTiers.
- src/game/80-simulation/29-route-core.js, 30-compute.js: the route core takes both SATN and the spill tiers (TT).
- src/game/80-simulation/40-billing.js: upstream's gulfPair and borderShut; linkCut() is built on borderShut, linkDown() keeps express and satellite.
- src/game/80-simulation/50-sanitize.js: PNI bundles up to PNI_LAG_MAX next to the fork's link kinds; popStdSanitize then ptSanitize; mpSanitize then lcSanitize.
- src/game/80-simulation/75-customer-lifecycle.js: clGrow() stops at a type's most (#137) and at an IPv4 block that is not free (#150).
- src/game/90-actions/60-links.js: rmLink keeps the express guard and moves on to the next parallel link (#119).
- src/game/90-actions/85-routing-and-routers.js: rmRouter checks the PNIs on its routers (#323), upRouter keeps own().
- src/game/90-actions/89-game-and-settings.js: the menu keeps the build standard and session tiles and gains Send to another device.
- src/game/93-ui/40-hud-and-panels.js, 70-link-panels.js: offers show both the IPv4 note and Buy and sign; link headers name their cities, the closed-border section reads in dark mode; the express count stays.
- src/game/93-ui/50-city-panel.js: the teleport section and Link to a city.
- src/game/94-dashboard/40-connections.js: upstream's per-table next port size replaces the fork's own 400G guard.
- src/game/94-dashboard/90-noc-window.js, 96-map/95-clicks.js, 99-loop.js: both sides' acts and boot steps.
- src/styles/40-modal.css: the dark-mode tag tokens and the transfer textarea.
- tests/mcp-commands.test.js: both sides' sample args.

Interaction fixes:
- POP standards and the build standard: a POP marked as a kind keeps its kind's routers (ptKind). The build
  standard's router jobs and the intern's model swaps leave it alone; every other target still applies. Both sheets say so.
- Spill tiers: pathMs() fills a path's ground latency and satellite edges too, so a tier's detour costs users its
  latency (it went uncharged before).
- Send to another device: a session network goes by the session's own #mp= link; its save file is called a copy.
- Buy and sign (#241) does not buy for an offer whose IPv4 block does not fit.
- Dark mode: the closed-border title and the renewal ticks use the dark-aware red (upstream's #292 test follows).
- Server-run tables: the new acts classified (pt*, acceptFix and utilityKitAll quote their cost); mp-sim fixtures
  written again with tests/lib/mp-sim-fixtures.js.

Review fixes:
- POP standards: ptSave, ptApply, ptPlan, ptAll and popStdSet find a POP with own(), so 'toString' is no POP (also
  decomToggle, decomGo, dkStay).
- Server-run envelope: an arg value that names anything on Object.prototype is refused, in args, drafts and
  ctx.win.ui.
- Decommissioning a POP drops its POP-standard mark, so live state stays what a reload makes of it (the T2 gate
  refused later pt* acts).
- acceptFix, ptApply, ptAll and utilityKitAll take a quote within 1% (quoteNear), like utilityKit and bstdApply:
  router prices drift daily.
- The transfer paste box reads in dark mode (--text, as input.t).
- A session's #mp= link pasted under From another device opens it (saved, then loaded again with it), in MP builds.
- The express and satellite circuit panels name their cities as links (#196); a circuit shows the closed-border
  section (#329).
- CHANGELOG: the fork's 400G connections bullet goes (3.5.0 ships it); bullets for POP kinds, the session link and Buy
  and sign's IPv4 check.
2026-11-12 00:52:42 +01:00

639 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',
'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',
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 };