/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) ================= Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here runs. Players share a session by a six-character code: each builds their own network in the same world (one seed, one rules preset), each network's save is also kept on the server (so it can move to another device), and a small public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq, sim?}; the secret token is never in S (saves get exported and shared): it lives in this browser's storage, sot-mp::. */ const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i; // Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive // request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request, // with room to spare), else the card alone. const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat']; /* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */ const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false}; const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn()); const mpShow=c=>c.slice(0,3)+'-'+c.slice(3); // "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32). function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;} const mpPath=(m,p)=>'/sessions/'+m.code+(p||''); const mpTokK=(c,p)=>'sot-mp:'+c+':'+p; function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;} function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}} // The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses. const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64); // sim:1, a network the session server runs (its days happen there, this page shows them). Only a page built with the // server's client (src/game/98-server-play/, MP builds) says yes here; everywhere else this one stays. function srvOn(){return false;} function mpSanitize(s){const m=s.mp; if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;} s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall', color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0),...(m.sim===1?{sim:1}:{})};} // What the server said when a session started or someone joined: checked before it becomes S.mp. function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null; return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};} /* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with {status, j} on an HTTP error, so callers can tell "no such session" from "server away". */ function mpReq(method,p,body,o={}){ if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0})); const h={};if(body!==undefined)h['content-type']='application/json'; // o.tok: a token not stored yet (a #mp= link's, until the server takes it). if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;} const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0; let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});} catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));} return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}), e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});} /* The public card: what the leaderboard shows (and what peering between players will need later). */ function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){} const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map(); for(const l of S.links){if(l.ready>S.day)continue;const k=l.ab[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];}); const served=R.served||0; return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64), ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0), cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};} /* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own catalogs. Names and chat stay text: everything that shows them escapes them. */ function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null; const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[]; return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500), links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]), ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9), cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};} function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null; const txt=(v,max)=>typeof v==='string'?v.slice(0,max):''; const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0), color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)})); const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''})); return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};} // Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last. const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0; function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);} /* ---------- staying in step with the server ---------- */ function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();} /* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once (429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away": wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say the server is away, but never stretches the wait. */ function mpFail(e,poll){const st=e&&e.status; if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;} if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;} if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);} if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}} const mpHid=()=>MP.leaving||document.visibilityState==='hidden'; // What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only // when something changed since the last push. function mpSig(t){let h=0x811c9dc5;for(let i=0;i>>0).toString(36)+'.'+t.length;} // The request's size in bytes (UTF-8), which is what the keepalive limit counts. function mpBytes(t){let n=t.length;for(let i=0;i127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;} /* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in a puzzle: save() returns before then. */ function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0; const hid=mpHid(),now=performance.now(); // One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush). if(MP.busy&&!hid)return 0; const ask=MP.now;MP.now=false; if(MP.force&&(hid||now>=MP.wait))return 1; if(S.day===MP.day)return hid||ask?2:0; return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;} /* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is picked before the text is made, so the save here and the one on the server carry the same: reopening this device then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */ function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st)); if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}} if(d)mpPush(txt);return txt;} /* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */ function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return; const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;} // A push still on its way while the page goes away with a newer save: that one is cut short, this one goes. if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}} MP.cur=me;MP.busy=true;MP.last=performance.now(); const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})}); // Only a save that went counts as this day's push; a card alone does not. const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));}; const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);}; const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}}; const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController(); mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);}; if(hid){const b=txt.lengthsend('/save',body(data),false); if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);} // The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request). if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});} function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);} // Pushes this network's save now if it changed since the last push (before a link to another device is handed out). function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);} // The server's save text as a game state: unzipped, parsed, and only if it is this very network. function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save')); return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));} function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false; if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);} /* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead. Nothing is pushed until the answer is in. */ function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud(); // A push of the page going away meanwhile is its own: only an answer to this question frees the next one. const free=()=>{if(!MP.cur)MP.busy=false;}; mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();}, e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});} // A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten). function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);} function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return; // A day still routing in the worker finishes first. if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;} mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0); S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()}); renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();}) .catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});} function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));} /* ---------- a link to the same network on another device ---------- /#mp=..: the fragment never reaches a server. At boot (before the slots are picked) the save is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the server took it: a wrong or old link never replaces nor deletes the one this browser already has. */ const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';}; // "Send to another device" (#263) for a network of a session (e: its slot entry): the link it sends is this one, so the // network carries on in the session as the same player; a save file stays a copy that plays on alone elsewhere (no // token goes with it). Without the token here, no link at all. null for any other network, and in every other build. function mpXfer(e){if(!MP_API||!e||typeof e.mp!=='string')return null;const m={code:e.mp.slice(0,6),pid:e.mp.slice(7)}; return MP_CODE.test(m.code)&&MP_PID.test(m.pid)?{code:m.code,link:mpLink(m)||null}:null;} function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null; if(!h){go();return;} try{history.replaceState(null,'',location.pathname+location.search);}catch(e){} const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();}; if(!code){fin({bad:1});return;} const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);}; // The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again. const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500; if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});}; const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken); if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});}; // Opening it fetches the server's save when that one is newer. A link with another token is asked about first. if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;} mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network'); delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{ const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep(); slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});})) .then(()=>fin({code}),no);} // Said once the game is on screen (or the title is). function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null; if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad'); else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');}