Skip to content

Commit 66ef341

Browse files
authored
Merge pull request #266 from ngcoding10/wallet-hardening
2 parents a5c6063 + 0ce28c1 commit 66ef341

23 files changed

Lines changed: 2519 additions & 76 deletions

‎README.md‎

Lines changed: 11 additions & 5 deletions
Large diffs are not rendered by default.

‎e63334287a3deaa3/cosmetics.js‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,16 @@
1010
* Set it to true to open everything. For testing only, ?cosmetics=1 in the page address turns it on, and only when the
1111
* page is on localhost or driven by an automated browser (navigator.webdriver): that check is captains.js's, the one
1212
* file every hidden cosmetic asks (without it on the page the address does nothing).
13-
* The site's captains are NOT let in here early. captains.js lets them see the games' own screens (Driftfall's Locker,
13+
* THE REAL SWITCH is wallet.js's PAYMENTS.enabled: true opens the shop for everyone with the server wallet (server()
14+
* below; functions/_wallet.js): balance, locker and every purchase, chest and gift come from and go to the server. The
15+
* browser-only locker and wallet (the old local mode) are kept only for the ?cosmetics=1 test switch. ENABLED, if set,
16+
* also opens the shop with the server wallet.
17+
* CAPTAINS' PREVIEW (CAPTAIN_PREVIEW, below): while PAYMENTS.enabled is false, a captain who opens the shop page gets the
18+
* real shop with the server wallet in that browser tab (sessionStorage 'cosmetics:preview', set by shop/ once
19+
* captains.js confirms the captain), so the owners can try the whole flow on the live site; everyone else still sees
20+
* "not open yet", and the server refuses everyone but captains until PAYMENTS.enabled is true. Turn the preview off
21+
* by setting CAPTAIN_PREVIEW to false (?preview=0 on the shop page also ends it for that tab).
22+
* Apart from that preview, the site's captains are NOT let in here early. captains.js lets them see the games' own screens (Driftfall's Locker,
1423
* Boostball's garage and Kit, Slipstream's Garage), where every item is free to wear while this file is off; the
1524
* shop, the wallet, earning and buying stay shut for them like everyone else, so on() asks captains.js's open(), which
1625
* leaves captains out, not may().
@@ -67,7 +76,9 @@
6776
'use strict';
6877
if (window.BackRoomCosmetics) return;
6978

70-
var ENABLED = false; // THE SWITCH: false keeps every part of the cosmetics hidden; true opens the shop for everyone.
79+
var ENABLED = false; // false keeps every part of the cosmetics hidden (see THE REAL SWITCH above: wallet.js PAYMENTS.enabled)
80+
var CAPTAIN_PREVIEW = true; // the captains' preview of the real shop (see above); false turns it off for everyone
81+
var PREVIEW_KEY = 'cosmetics:preview';
7182

7283
var me0 = document.currentScript;
7384
var HUB = !!(me0 && me0.hasAttribute('data-hub'));
@@ -97,7 +108,22 @@
97108

98109
var SHARED = window.BackRoomCaptains || null; // captains.js: the test switch lives there, with the others
99110
var FLAG = !!(SHARED && SHARED.open(false, 'cosmetics'));
100-
function on() { return !!(api.ENABLED || FLAG); }
111+
function on() { return server() || FLAG; }
112+
// The server wallet is in use: PAYMENTS.enabled (wallet.js), ENABLED, or the captains' preview on the shop page.
113+
// Otherwise, with the test switch alone, the old browser-only mode.
114+
function payments() { try { var w = window.BackRoomWallet; return !!(w && w.PAYMENTS && w.PAYMENTS.enabled); } catch (e) { return false; } }
115+
function shopPage() { try { return /^\/e63334287a3deaa3\/shop(\/(index\.html)?)?$/.test(location.pathname); } catch (e) { return false; } }
116+
function previewOn() { if (!CAPTAIN_PREVIEW || !shopPage()) return false; try { return sessionStorage.getItem(PREVIEW_KEY) === '1'; } catch (e) { return false; } }
117+
function server() { return !!(api.ENABLED || payments() || previewOn()); }
118+
// shop/ calls these: start the preview once captains.js has confirmed a captain; stop it when that changes.
119+
function previewAllowed() { return CAPTAIN_PREVIEW && shopPage() && !payments() && !api.ENABLED; }
120+
function startPreview() {
121+
if (!previewAllowed() || !(SHARED && SHARED.captain && SHARED.captain())) return false;
122+
try { sessionStorage.setItem(PREVIEW_KEY, '1'); } catch (e) { return false; }
123+
return previewOn();
124+
}
125+
function stopPreview() { try { sessionStorage.removeItem(PREVIEW_KEY); } catch (e) {} }
126+
try { if (/[?&]preview=0(&|$)/.test(location.search)) stopPreview(); } catch (e) {}
101127

102128
// ---------------- Skins ----------------
103129
// look: bg / bg2 background colours, bgp background pattern, outfit, head (piece on the head), tone (skin colour, optional),
@@ -1134,14 +1160,25 @@
11341160
// lists every skin, accessory and game item as owned, and save() writes back only what they really own (L.raw), so
11351161
// nothing they didn't buy is ever saved, mirrored into their account or kept after they sign out. load(true) is the
11361162
// real locker alone (the account mirror and buying use it).
1137-
function cap() { try { return !!(on() && SHARED && SHARED.captain && SHARED.captain()); } catch (e) { return false; } }
1163+
function cap() {
1164+
try { if (on() && server() && window.BackRoomWallet && window.BackRoomWallet.unlimited && window.BackRoomWallet.unlimited()) return true; } catch (e) {}
1165+
try { return !!(on() && SHARED && SHARED.captain && SHARED.captain()); } catch (e) { return false; }
1166+
}
11381167
function load(raw) {
11391168
var o = json(ls(KEY)), L = { v: 1, s: [], a: [], g: [], e: { skin: '' }, ge: {} };
11401169
SLOTS.forEach(function (k) { L.e[k] = ''; });
11411170
if (!obj(o) || o.v !== 1) o = {};
1171+
if (server()) {
1172+
// The server wallet: what's owned is the server's answer (wallet.js), plus the game items a game hands over
1173+
// itself (give: free to everyone, so kept in this browser). Only what is worn (e, ge) is read from here.
1174+
var w = window.BackRoomWallet, mine = w && w._owned ? w._owned() : [];
1175+
mine.forEach(function (id) { if (SKINS_BY_ID[id]) L.s.push(id); else if (ACC_BY_ID[id]) L.a.push(id); else if (ITEM_BY_ID[id]) L.g.push(id); });
1176+
if (Array.isArray(o.g)) o.g.forEach(function (id) { var it = ITEM_BY_ID[id]; if (it && it.give && L.g.indexOf(id) < 0) L.g.push(id); });
1177+
} else {
11421178
if (Array.isArray(o.s)) o.s.forEach(function (id) { if (SKINS_BY_ID[id] && L.s.indexOf(id) < 0) L.s.push(id); });
11431179
if (Array.isArray(o.a)) o.a.forEach(function (id) { if (ACC_BY_ID[id] && L.a.indexOf(id) < 0) L.a.push(id); });
11441180
if (Array.isArray(o.g)) o.g.forEach(function (id) { if (ITEM_BY_ID[id] && L.g.indexOf(id) < 0) L.g.push(id); });
1181+
}
11451182
if (!raw && cap()) {
11461183
Object.defineProperty(L, 'raw', { value: { s: L.s, a: L.a, g: L.g }, enumerable: false });
11471184
L.s = SKINS.map(function (x) { return x.id; }); L.a = ACCESSORIES.map(function (x) { return x.id; }); L.g = GAME_ITEMS.map(function (x) { return x.id; });
@@ -1155,6 +1192,14 @@
11551192
}
11561193
function save(L) {
11571194
if (L.raw) { var r = L.raw; L = { v: 1, s: r.s, a: r.a, g: r.g, e: L.e, ge: L.ge }; } // a captain: only what they really own
1195+
if (server()) {
1196+
// The server wallet: ownership is never saved here (the server holds it). What was saved before is left as it
1197+
// was; only what is worn and the game-given items change.
1198+
var o = json(ls(KEY)); o = obj(o) && o.v === 1 ? o : {};
1199+
var keep = Array.isArray(o.g) ? o.g.filter(function (id) { return ITEM_BY_ID[id]; }) : [];
1200+
L.g.forEach(function (id) { if (ITEM_BY_ID[id] && ITEM_BY_ID[id].give && keep.indexOf(id) < 0) keep.push(id); });
1201+
L = { v: 1, s: Array.isArray(o.s) ? o.s : [], a: Array.isArray(o.a) ? o.a : [], g: keep, e: L.e, ge: L.ge };
1202+
}
11581203
if (!L.g.length && !Object.keys(L.ge || {}).length) { delete L.g; delete L.ge; } // no game items: the saved locker is exactly what it was before they existed
11591204
ls(KEY, JSON.stringify(L)); try { document.dispatchEvent(new CustomEvent('backroom:cosmetics', { detail: { equipped: equipped() } })); } catch (e) {} }
11601205
function equip(id) {
@@ -1265,9 +1310,12 @@
12651310
// unknown, money (emerald packs: wallet.js EMERALD_PACKS and PAYMENTS), owned (you already own everything in it),
12661311
// wallet (no wallet.js), funds (not enough mangos).
12671312
function emeraldPack(id) { var w = W(); return w && w.EMERALD_PACKS ? w.EMERALD_PACKS.filter(function (e) { return e.id === id; })[0] : null; }
1313+
// With the server wallet buy() returns a PROMISE of the same answer (the server buys, rolls and fills the locker;
1314+
// extra reasons: signin, closed, server, duplicate, with a message). Callers: Promise.resolve(buy(id)).then(...).
12681315
function buy(packId, opts) {
12691316
var p = pack(packId);
12701317
if (!on()) return { ok: false, reason: 'off' };
1318+
if (server()) return serverBuy(p, packId);
12711319
if (!p && emeraldPack(packId)) return { ok: false, reason: 'money', checkout: W().PAYMENTS.checkout(packId) };
12721320
if (!p) return { ok: false, reason: 'unknown' };
12731321
var pv = preview(packId);
@@ -1280,6 +1328,20 @@
12801328
if (f.refund) w.earn(f.refund, f.dups === 1 ? 'Back for a duplicate' : 'Back for ' + f.dups + ' duplicates');
12811329
return { ok: true, pack: p.id, spent: free ? 0 : p.price, got: f.got, refund: f.refund, balance: w.balance() };
12821330
}
1331+
function serverBuy(p, packId) {
1332+
if (!p && emeraldPack(packId)) return Promise.resolve({ ok: false, reason: 'money' });
1333+
if (!p) return Promise.resolve({ ok: false, reason: 'unknown' });
1334+
if (preview(packId).all) return Promise.resolve({ ok: false, reason: 'owned' });
1335+
var w = W(); if (!w || !w._buy) return Promise.resolve({ ok: false, reason: 'wallet' });
1336+
var dm = /^draw-(\d+)$/.exec(p.id);
1337+
return (dm ? w._chest(+dm[1]) : w._buy(p.id)).then(function (r) {
1338+
if (!r || !r.ok) return r || { ok: false, reason: 'server' };
1339+
var got = { skins: (r.got && r.got.skins) || [], acc: (r.got && r.got.acc) || [], items: (r.got && r.got.items) || [], draws: (r.got && r.got.draws) || [] };
1340+
var L = load(), first = got.skins[0] || (got.draws[0] && got.draws[0].skin);
1341+
if (!L.e.skin && first && L.s.indexOf(first) >= 0) { L.e.skin = first; save(L); }
1342+
return { ok: true, pack: p.id, spent: r.spent, got: got, refund: r.refund || 0, balance: r.balance };
1343+
});
1344+
}
12831345
// Put what a pack (or one item, or chests) holds into the real locker, opening chests here. Pays nothing: the caller
12841346
// pays the refund for duplicates (buy() above, or wallet.js's grant() for a gift). -> { got, dups, refund }
12851347
function fill(p, opts) {
@@ -1297,7 +1359,7 @@
12971359
return { got: got, dups: dups, refund: dups * DUP_REFUND };
12981360
}
12991361
// A gift arriving (wallet.js's grant('gift'), the only caller): fill the locker with what packId holds, free.
1300-
function receive(packId, opts) { var p = pack(packId); if (!on() || !p) return null; var f = fill(p, opts); f.pack = p; return f; }
1362+
function receive(packId, opts) { var p = pack(packId); if (!on() || server() || !p) return null; var f = fill(p, opts); f.pack = p; return f; }
13011363

13021364
// ---------------- Drawing (64 × 64 units, avatar.js's grid) ----------------
13031365
var INK = '#1B1513', WH = '#FFFFFF';
@@ -1527,7 +1589,8 @@
15271589
// ---------------- API ----------------
15281590
var api = {
15291591
ENABLED: ENABLED,
1530-
on: on,
1592+
on: on, server: server, previewAllowed: previewAllowed, startPreview: startPreview, stopPreview: stopPreview,
1593+
previewing: function () { return previewOn() && !payments() && !api.ENABLED; },
15311594
SKINS: SKINS, ACCESSORIES: ACCESSORIES, SKINS_BY_ID: SKINS_BY_ID, ACCESSORIES_BY_ID: ACC_BY_ID, SLOTS: SLOTS, SLOT_NAMES: SLOT_NAMES,
15321595
RARITY: RARITY, RARITY_BY_ID: RARITY_BY_ID, RARITY_TOTAL: RARITY_TOTAL, PACKS: PACKS, PACKS_BY_ID: PACKS_BY_ID,
15331596
PRICE: PRICE, CHEST_PRICE: CHEST_PRICE, DUP_REFUND: DUP_REFUND, pack: pack,

‎e63334287a3deaa3/owned.js‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
* BackRoomOwned: may ANOTHER player be drawn wearing this item? Asks the server (GET /api/owned?uids=…, public and
3+
* edge-cached), because each player's own page can be edited to wear anything, and other players' pages would then
4+
* draw it. Games call this before drawing someone else's skin, accessory or game item once the shop is public.
5+
*
6+
* BackRoomOwned.check(uid, itemId) → true (owns it, or a captain, or a give item anyone may wear),
7+
* false (doesn't own it: draw the default look),
8+
* undefined (not known yet, or the server can't be reached: draw the default
9+
* look for now; onChange fires when the answer arrives)
10+
* BackRoomOwned.want(uids) ask ahead for a list of uids (e.g. everyone in the room as they join)
11+
* BackRoomOwned.onChange(fn) fn(uids) after answers arrive, so the game can redraw those players
12+
* BackRoomOwned.active() true once the shop is public (wallet.js PAYMENTS.enabled): until then games
13+
* needn't check at all
14+
*
15+
* Calls are batched (up to 24 uids a request, sent 50 ms after the first ask) and answers kept for 60 seconds. It
16+
* never throws and never blocks a frame: a failure only means "not known yet" (retried after 30 seconds).
17+
* It can't stop a player seeing an item on their OWN screen: that page is theirs to edit.
18+
*/
19+
(function () {
20+
'use strict';
21+
if (window.BackRoomOwned) return;
22+
var API = /(^|\.)ascoding11\.com$/.test(location.hostname) ? '/api/' : 'https://ascoding11.com/api/';
23+
var MAX = 24, KEEP = 60000, RETRY = 30000, UID = /^[A-Za-z0-9_-]{6,128}$/;
24+
var known = {}; // uid -> { t: time, all: bool, set: { id: 1 } } or { t, failed: true }
25+
var give = {}; // item ids anyone may wear (free or earned in a game), from the server
26+
var queue = [], timer = 0, inflight = {}, listeners = [];
27+
28+
function now() { return Date.now(); }
29+
function fresh(k) { return k && now() - k.t < (k.failed ? RETRY : KEEP); }
30+
function want(uids) {
31+
(uids || []).forEach(function (u) {
32+
u = String(u || '');
33+
if (!UID.test(u) || fresh(known[u]) || inflight[u] || queue.indexOf(u) >= 0) return;
34+
queue.push(u);
35+
});
36+
if (queue.length && !timer) timer = setTimeout(flush, 50);
37+
}
38+
function flush() {
39+
timer = 0;
40+
while (queue.length) send(queue.splice(0, MAX));
41+
}
42+
function send(batch) {
43+
batch.forEach(function (u) { inflight[u] = 1; });
44+
var done = function (players) {
45+
var t = now();
46+
batch.forEach(function (u) {
47+
delete inflight[u];
48+
var p = players && players[u];
49+
if (p === '*') known[u] = { t: t, all: true, set: {} };
50+
else if (Array.isArray(p)) { var s = {}; p.forEach(function (id) { s[id] = 1; }); known[u] = { t: t, all: false, set: s }; }
51+
else known[u] = { t: t, failed: true };
52+
});
53+
listeners.forEach(function (fn) { try { fn(batch.slice()); } catch (e) {} });
54+
};
55+
try {
56+
fetch(API + 'owned?uids=' + batch.map(encodeURIComponent).join(','), { credentials: 'omit' })
57+
.then(function (r) { return r.ok ? r.json() : null; })
58+
.then(function (d) {
59+
if (d && d.give && Array.isArray(d.give)) d.give.forEach(function (id) { give[id] = 1; });
60+
done(d && d.v === 1 && d.players);
61+
}, function () { done(null); });
62+
} catch (e) { done(null); }
63+
}
64+
function check(uid, itemId) {
65+
uid = String(uid || ''); itemId = String(itemId || '');
66+
if (!itemId) return true;
67+
if (give[itemId]) return true;
68+
var k = known[uid];
69+
if (!fresh(k)) want([uid]);
70+
if (!k || k.failed) return undefined;
71+
return k.all || !!k.set[itemId];
72+
}
73+
function active() {
74+
try { var W = window.BackRoomWallet || (window.parent && window.parent.BackRoomWallet); return !!(W && W.PAYMENTS && W.PAYMENTS.enabled); }
75+
catch (e) { return false; }
76+
}
77+
window.BackRoomOwned = {
78+
check: check, want: want, active: active,
79+
onChange: function (fn) { if (typeof fn === 'function') listeners.push(fn); },
80+
_reset: function () { known = {}; give = {}; queue = []; inflight = {}; if (timer) clearTimeout(timer); timer = 0; }
81+
};
82+
})();

0 commit comments

Comments
 (0)