From b3d1e18933e72f3e308dfb7d822828d7352f8354 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:00:57 +0000 Subject: [PATCH 01/14] Wallet server: generated catalogue and captains list for functions/, with a --check Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/shop/tools/server-data.js | 115 +++++++++++++++++++++ functions/_captains.js | 3 + functions/_catalog.js | 3 + 3 files changed, 121 insertions(+) create mode 100644 e63334287a3deaa3/shop/tools/server-data.js create mode 100644 functions/_captains.js create mode 100644 functions/_catalog.js diff --git a/e63334287a3deaa3/shop/tools/server-data.js b/e63334287a3deaa3/shop/tools/server-data.js new file mode 100644 index 00000000..664bde90 --- /dev/null +++ b/e63334287a3deaa3/shop/tools/server-data.js @@ -0,0 +1,115 @@ +/* + * The server wallet's copy of the shop's numbers, made from the browser files so the two can't drift apart. + * + * node e63334287a3deaa3/shop/tools/server-data.js writes functions/_catalog.js and functions/_captains.js + * node e63334287a3deaa3/shop/tools/server-data.js --check writes nothing; fails (exit 1) if either file is out of date + * + * Run it (without --check) after changing anything the server must agree on, then commit the two files it writes: + * cosmetics.js prices (PRICE), chest price and duplicate refund, rarity weights, every skin / accessory / game item + * id and rarity (and which are `give` items, never sold), every pack and what it holds + * wallet.js MANGOS_PER_EMERALD, EMERALD_PACKS (count and dollar price of each pack; its Stripe lookup key is the + * pack id with _ for -, e.g. emeralds_7), and PAYMENTS.enabled (the one switch: while it is false the + * server only serves captains) + * miles.js OWNERS (captains: never charged, own everything, never paid rewards). Vice Captains are not included, + * the same as captains.js. + * The browser files are run in a sandbox the way a page runs them (no libraries); nothing else is read. + */ +'use strict'; +const fs = require('fs'), path = require('path'), vm = require('vm'); +const ROOT = path.join(__dirname, '..', '..', '..'); +const BR = path.join(ROOT, 'e63334287a3deaa3'); +const OUT_CAT = path.join(ROOT, 'functions', '_catalog.js'); +const OUT_CAP = path.join(ROOT, 'functions', '_captains.js'); + +function sandbox() { + const noop = () => {}; + const el = () => ({ style: {}, setAttribute: noop, appendChild: noop, addEventListener: noop, querySelector: () => null }); + const document = { currentScript: null, readyState: 'complete', addEventListener: noop, removeEventListener: noop, dispatchEvent: noop, + querySelector: () => null, querySelectorAll: () => [], getElementById: () => null, getElementsByTagName: () => [], createElement: el, + head: { appendChild: noop }, body: { appendChild: noop }, documentElement: { appendChild: noop } }; + const store = { getItem: () => null, setItem: noop, removeItem: noop }; + const win = { document, localStorage: store, sessionStorage: store, navigator: {}, location: { search: '', hostname: 'build', pathname: '/', href: 'http://build/' }, + addEventListener: noop, setTimeout: () => 0, clearTimeout: noop, console, CustomEvent: function () {}, MutationObserver: function () { this.observe = noop; } }; + win.window = win; win.parent = win; win.top = win; win.self = win; + return vm.createContext(win); +} +function run(ctx, file) { vm.runInContext(fs.readFileSync(path.join(BR, file), 'utf8'), ctx, { filename: file }); } + +function build() { + const ctx = sandbox(); + run(ctx, 'cosmetics.js'); + run(ctx, 'wallet.js'); + const C = ctx.BackRoomCosmetics, W = ctx.BackRoomWallet; + if (!C || !W) throw new Error('cosmetics.js or wallet.js did not load'); + const items = {}; + const add = (id, rarity, kind, give) => { + if (items[id]) throw new Error('two items share the id ' + id + ' (the server keeps one owned list for all of them)'); + if (!C.PRICE[rarity]) throw new Error(id + ': unknown rarity ' + rarity); + items[id] = give ? [rarity, kind, give] : [rarity, kind]; + }; + C.SKINS.forEach(s => add(s.id, s.rarity, 's')); + C.ACCESSORIES.forEach(a => add(a.id, a.rarity, 'a')); + C.GAME_ITEMS.forEach(g => add(g.id, g.rarity, 'g', g.give || '')); + const packs = {}; + C.PACKS.forEach(p => { + const c = {}; + if (p.contents.draws) c.draws = p.contents.draws; + const list = [].concat(p.contents.skins || [], p.contents.acc || [], p.contents.items || []); + if (list.length) c.items = list; + list.forEach(id => { if (!items[id]) throw new Error('pack ' + p.id + ' holds unknown item ' + id); }); + packs[p.id] = { kind: p.kind, name: p.name, price: p.price, contents: c }; + }); + const emeralds = {}; + W.EMERALD_PACKS.forEach(e => { + const sku = e.id.replace(/-/g, '_'); + if (!/^[a-z][a-z0-9_]{0,39}$/.test(sku)) throw new Error('bad emerald pack id ' + e.id); + emeralds[sku] = { name: e.name, emeralds: e.emeralds, cents: Math.round(e.usd * 100), currency: 'usd' }; + }); + const cat = { + PUBLIC: !!(W.PAYMENTS && W.PAYMENTS.enabled), + MANGOS_PER_EMERALD: W.MANGOS_PER_EMERALD, + PRICE: Object.assign({}, C.PRICE), + CHEST_PRICE: C.CHEST_PRICE, + DUP_REFUND: C.DUP_REFUND, + RARITY: C.RARITY.map(r => ({ id: r.id, name: r.name, w: r.w })), + RARITY_TOTAL: C.RARITY_TOTAL, + NOTE_MAX: W.NOTE_MAX, + ITEMS: items, + PACKS: packs, + EMERALDS: emeralds + }; + C.RARITY.forEach(r => { if (!C.SKINS.some(s => s.rarity === r.id)) throw new Error('no skin is ' + r.id + ': a chest roll could not be paid out'); }); + + const mctx = sandbox(); + run(mctx, 'miles.js'); + const owners = (mctx.BackRoomMiles && mctx.BackRoomMiles.OWNERS) || []; + if (!owners.length) throw new Error('miles.js has no OWNERS'); + + const head = '// GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing '; + const catJs = head + 'cosmetics.js\n// or wallet.js, and commit this file; its --check fails while the two disagree. Read by functions/_wallet.js.\n' + + 'export const CATALOG = ' + JSON.stringify(cat, null, 1).replace(/\n\s*/g, ' ').replace(/\{ "/g, '{"') + ';\n'; + const capJs = head + "miles.js's\n// OWNERS (the captains: never charged, own everything, never paid rewards), and commit this file.\n" + + 'export const OWNERS = ' + JSON.stringify(owners.slice()) + ';\n'; + return { catJs, capJs, cat, owners }; +} + +if (require.main === module) { + const check = process.argv.includes('--check'); + let out; + try { out = build(); } catch (e) { console.error('server-data: ' + e.message); process.exit(1); } + const files = [[OUT_CAT, out.catJs], [OUT_CAP, out.capJs]]; + if (check) { + let bad = 0; + for (const [f, want] of files) { + const have = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : ''; + if (have !== want) { bad++; console.error('OUT OF DATE: ' + path.relative(ROOT, f) + ' (run: node e63334287a3deaa3/shop/tools/server-data.js)'); } + } + if (bad) process.exit(1); + console.log('server-data: functions/_catalog.js and functions/_captains.js match the browser files (' + Object.keys(out.cat.ITEMS).length + ' items, ' + + Object.keys(out.cat.PACKS).length + ' packs, ' + Object.keys(out.cat.EMERALDS).length + ' emerald packs, ' + out.owners.length + ' captains; PAYMENTS.enabled ' + out.cat.PUBLIC + ').'); + } else { + for (const [f, want] of files) fs.writeFileSync(f, want); + console.log('server-data: wrote functions/_catalog.js and functions/_captains.js'); + } +} +module.exports = { build }; diff --git a/functions/_captains.js b/functions/_captains.js new file mode 100644 index 00000000..6204cb78 --- /dev/null +++ b/functions/_captains.js @@ -0,0 +1,3 @@ +// GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing miles.js's +// OWNERS (the captains: never charged, own everything, never paid rewards), and commit this file. +export const OWNERS = ["6QQvFAzdtMeJdAUSPwHd6v2zaDk1","QaJlsT7SVnf85IK1PRHFpR9Zbln2","lxvfrYnKqAQ7qcTCnh1hPX1nYxs2","dUdkRLW9dKfhchtQuNepDRrQ95n1","z3ATmlobzgfIp5suh8ITz5Im2dH2"]; diff --git a/functions/_catalog.js b/functions/_catalog.js new file mode 100644 index 00000000..e69d4d9d --- /dev/null +++ b/functions/_catalog.js @@ -0,0 +1,3 @@ +// GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing cosmetics.js +// or wallet.js, and commit this file; its --check fails while the two disagree. Read by functions/_wallet.js. +export const CATALOG = {"PUBLIC": false, "MANGOS_PER_EMERALD": 17, "PRICE": {"common": 60, "uncommon": 119, "rare": 420, "epic": 600, "legendary": 1200 }, "CHEST_PRICE": 119, "DUP_REFUND": 48, "RARITY": [ {"id": "legendary", "name": "Legendary", "w": 250 }, {"id": "epic", "name": "Epic", "w": 500 }, {"id": "rare", "name": "Rare", "w": 1250 }, {"id": "uncommon", "name": "Uncommon", "w": 2000 }, {"id": "common", "name": "Common", "w": 6000 } ], "RARITY_TOTAL": 10000, "NOTE_MAX": 60, "ITEMS": {"moon-walker": [ "common", "s" ], "tide-pool": [ "common", "s" ], "neon-jogger": [ "common", "s" ], "bubblegum": [ "common", "s" ], "sprinkle-pop": [ "common", "s" ], "tin-tinker": [ "common", "s" ], "tabby": [ "common", "s" ], "cub": [ "common", "s" ], "hopper": [ "common", "s" ], "spring-sprout": [ "common", "s" ], "summer-sun": [ "common", "s" ], "dune-rover": [ "common", "s" ], "comet-courier": [ "uncommon", "s" ], "coral-diver": [ "uncommon", "s" ], "grid-runner": [ "uncommon", "s" ], "gumdrop-knight": [ "uncommon", "s" ], "circuit-scout": [ "rare", "s" ], "red-fox": [ "rare", "s" ], "autumn-ember": [ "rare", "s" ], "winter-frost": [ "rare", "s" ], "magma-walker": [ "rare", "s" ], "nebula-drifter": [ "epic", "s" ], "abyss-lantern": [ "epic", "s" ], "synthwave": [ "epic", "s" ], "rock-candy": [ "epic", "s" ], "chrome-unit": [ "epic", "s" ], "storm-drake": [ "epic", "s" ], "star-sovereign": [ "legendary", "s" ], "golden-automaton": [ "legendary", "s" ], "four-seasons": [ "legendary", "s" ], "pom-beanie": [ "common", "a" ], "wizard-cone": [ "uncommon", "a" ], "propeller-cap": [ "common", "a" ], "tall-topper": [ "rare", "a" ], "daisy-crown": [ "common", "a" ], "star-shades": [ "uncommon", "a" ], "heart-specs": [ "common", "a" ], "monocle": [ "rare", "a" ], "glow-visor": [ "epic", "a" ], "hero-cape": [ "common", "a" ], "galaxy-cape": [ "epic", "a" ], "leaf-cloak": [ "uncommon", "a" ], "sparkle-trail": [ "uncommon", "a" ], "bubble-trail": [ "common", "a" ], "rainbow-streak": [ "epic", "a" ], "halo-glow": [ "uncommon", "a" ], "ember-aura": [ "epic", "a" ], "frost-ring": [ "rare", "a" ], "pocket-slime": [ "common", "a" ], "mini-bot": [ "uncommon", "a" ], "star-buddy": [ "common", "a" ], "ghost-pup": [ "epic", "a" ], "baby-drake": [ "legendary", "a" ], "bb-decal-flames": [ "common", "g" ], "bb-decal-racing-stripes": [ "common", "g" ], "bb-decal-lightning-bolts": [ "common", "g" ], "bb-decal-checkered-flag": [ "common", "g" ], "bb-decal-shark-mouth": [ "uncommon", "g" ], "bb-decal-tiger-stripes": [ "uncommon", "g" ], "bb-decal-dragon-scales": [ "uncommon", "g" ], "bb-decal-carbon-fiber": [ "common", "g" ], "bb-decal-pixel-camo": [ "common", "g" ], "bb-decal-galaxy": [ "epic", "g" ], "bb-decal-constellations": [ "uncommon", "g" ], "bb-decal-circuit-board": [ "uncommon", "g" ], "bb-decal-graffiti-drips": [ "uncommon", "g" ], "bb-decal-honeycomb": [ "common", "g" ], "bb-decal-lava-cracks": [ "epic", "g" ], "bb-decal-frost": [ "uncommon", "g" ], "bb-decal-comic-book-dots": [ "common", "g" ], "bb-decal-topographic-lines": [ "common", "g" ], "bb-decal-stained-glass": [ "epic", "g" ], "bb-decal-wireframe": [ "rare", "g" ], "bb-decal-skeleton-ribs": [ "rare", "g" ], "bb-decal-duct-tape-patches": [ "common", "g" ], "bb-decal-rust-bucket": [ "common", "g" ], "bb-decal-wood-paneling": [ "rare", "g" ], "bb-decal-cow-print": [ "common", "g" ], "bb-decal-donut-sprinkles": [ "rare", "g" ], "bb-decal-bubble-wrap": [ "common", "g" ], "bb-decal-taxi": [ "rare", "g" ], "bb-decal-police-cruiser": [ "rare", "g" ], "bb-decal-ice-cream-truck": [ "epic", "g" ], "bb-decal-autumn-leaves": [ "common", "g" ], "bb-trail-classic-flame": [ "common", "g" ], "bb-trail-blue-plasma": [ "common", "g" ], "bb-trail-rainbow": [ "epic", "g" ], "bb-trail-lightning": [ "uncommon", "g" ], "bb-trail-bubbles": [ "common", "g" ], "bb-trail-confetti": [ "common", "g" ], "bb-trail-snowflakes": [ "common", "g" ], "bb-trail-autumn-leaves": [ "common", "g" ], "bb-trail-sparkles": [ "uncommon", "g" ], "bb-trail-hearts": [ "uncommon", "g" ], "bb-trail-music-notes": [ "uncommon", "g" ], "bb-trail-pixel-blocks": [ "common", "g" ], "bb-trail-smoke-rings": [ "uncommon", "g" ], "bb-trail-slime": [ "common", "g" ], "bb-trail-lava": [ "rare", "g" ], "bb-trail-stardust": [ "epic", "g" ], "bb-trail-popcorn": [ "rare", "g" ], "bb-trail-rubber-ducks": [ "epic", "g" ], "bb-trail-feathers": [ "common", "g" ], "bb-trail-soap-suds": [ "common", "g" ], "bb-trail-ink": [ "rare", "g" ], "bb-trail-ones-and-zeros": [ "rare", "g" ], "bb-trail-bats": [ "rare", "g" ], "bb-trail-toast-slices": [ "epic", "g" ], "bb-trail-dollar-bills": [ "epic", "g" ], "bb-trail-water-jet": [ "common", "g" ], "bb-trail-laser-beam": [ "legendary", "g" ], "bb-goal-fireworks": [ "uncommon", "g" ], "bb-goal-confetti-cannon": [ "uncommon", "g" ], "bb-goal-black-hole": [ "epic", "g" ], "bb-goal-supernova": [ "epic", "g" ], "bb-goal-lightning-strike": [ "uncommon", "g" ], "bb-goal-tornado": [ "epic", "g" ], "bb-goal-volcano": [ "epic", "g" ], "bb-goal-meteor": [ "epic", "g" ], "bb-goal-freeze-and-shatter": [ "uncommon", "g" ], "bb-goal-pixel-shatter": [ "rare", "g" ], "bb-goal-disco-ball-drop": [ "epic", "g" ], "bb-goal-giant-foot-stomp": [ "legendary", "g" ], "bb-goal-pinata-burst": [ "epic", "g" ], "bb-goal-popcorn-pop": [ "rare", "g" ], "bb-goal-ufo-abduction": [ "legendary", "g" ], "bb-goal-shark-attack": [ "legendary", "g" ], "bb-goal-giant-airhorn": [ "epic", "g" ], "bb-goal-money-rain": [ "epic", "g" ], "bb-goal-pumpkin-splat": [ "rare", "g" ], "bb-goal-goal-letters": [ "legendary", "g" ], "bb-goal-flock-of-birds": [ "epic", "g" ], "bb-topper-tennis-ball": [ "common", "g" ], "bb-topper-gold-star": [ "uncommon", "g" ], "bb-topper-bath-duck": [ "rare", "g" ], "bb-topper-mini-pumpkin": [ "common", "g" ], "bb-topper-pennant": [ "common", "g" ], "bb-topper-eyeball": [ "epic", "g" ], "bb-hat-traffic-cone": [ "common", "g" ], "bb-hat-top-hat": [ "uncommon", "g" ], "bb-hat-crown": [ "epic", "g" ], "bb-hat-propeller-beanie": [ "uncommon", "g" ], "bb-hat-cowboy-hat": [ "rare", "g" ], "bb-hat-chef-hat": [ "common", "g" ], "bb-wheels-five-spoke": [ "common", "g" ], "bb-wheels-discs": [ "common", "g" ], "bb-wheels-cross": [ "uncommon", "g" ], "bb-wheels-gold-rims": [ "epic", "g" ], "bb-engine-purr": [ "common", "g" ], "bb-engine-buzz": [ "uncommon", "g" ], "bb-engine-rumble": [ "rare", "g" ], "bb-engine-whirr": [ "epic", "g" ], "ss-sponsor-zoomi-cola": [ "common", "g", "free" ], "ss-sponsor-burnout-coffee": [ "common", "g", "free" ], "ss-sponsor-apex-tires": [ "common", "g", "free" ], "ss-sponsor-turbo-taco": [ "common", "g", "free" ], "ss-sponsor-grandma-s-motor-oil": [ "common", "g", "free" ], "ss-sponsor-pit-stop-pizza": [ "common", "g", "free" ], "ss-sponsor-slick-s-hair-gel": [ "common", "g", "free" ], "ss-sponsor-late-brake-insurance": [ "common", "g", "free" ], "ss-sponsor-draft-punk-records": [ "common", "g", "free" ], "ss-sponsor-gravel-trap-granola": [ "common", "g", "free" ], "ss-sponsor-blue-flag-bottled-water": [ "common", "g", "free" ], "ss-sponsor-honk-energy": [ "common", "g", "free" ], "ss-sponsor-chicane-chicken": [ "common", "g", "free" ], "ss-sponsor-podium-pickles": [ "common", "g", "free" ], "ss-sponsor-lap-nap-mattresses": [ "common", "g", "free" ], "ss-livery-two-tone-classic": [ "common", "g" ], "ss-livery-retro-stripes": [ "common", "g" ], "ss-livery-matte-black-with-neon": [ "uncommon", "g" ], "ss-livery-chrome": [ "epic", "g" ], "ss-livery-carbon": [ "uncommon", "g" ], "ss-livery-pastel": [ "common", "g" ], "ss-livery-flames": [ "rare", "g" ], "ss-livery-checkered": [ "common", "g" ], "ss-livery-zoomi-cola-livery": [ "epic", "g", "earned" ], "ss-livery-burnout-coffee-livery": [ "epic", "g", "earned" ], "ss-livery-apex-tires-livery": [ "epic", "g", "earned" ], "ss-livery-turbo-taco-livery": [ "epic", "g", "earned" ], "ss-livery-grandma-s-motor-oil-livery": [ "epic", "g", "earned" ], "ss-livery-pit-stop-pizza-livery": [ "epic", "g", "earned" ], "ss-livery-slick-s-hair-gel-livery": [ "epic", "g", "earned" ], "ss-livery-late-brake-insurance-livery": [ "epic", "g", "earned" ], "ss-livery-draft-punk-records-livery": [ "epic", "g", "earned" ], "ss-livery-gravel-trap-granola-livery": [ "epic", "g", "earned" ], "ss-livery-blue-flag-bottled-water-livery": [ "epic", "g", "earned" ], "ss-livery-honk-energy-livery": [ "epic", "g", "earned" ], "ss-livery-chicane-chicken-livery": [ "epic", "g", "earned" ], "ss-livery-podium-pickles-livery": [ "epic", "g", "earned" ], "ss-livery-lap-nap-mattresses-livery": [ "epic", "g", "earned" ], "ss-helmet-red-helmet": [ "common", "g", "free" ], "ss-helmet-blue-helmet": [ "common", "g", "free" ], "ss-helmet-yellow-helmet": [ "common", "g", "free" ], "ss-helmet-green-helmet": [ "common", "g", "free" ], "ss-helmet-orange-helmet": [ "common", "g", "free" ], "ss-helmet-pink-helmet": [ "common", "g", "free" ], "ss-helmet-black-helmet": [ "common", "g", "free" ], "ss-helmet-white-helmet": [ "common", "g", "free" ], "ss-helmet-flames-helmet": [ "common", "g" ], "ss-helmet-checkered-helmet": [ "common", "g" ], "ss-helmet-lightning-helmet": [ "common", "g" ], "ss-helmet-chrome-visor": [ "uncommon", "g" ], "ss-helmet-shark-helmet": [ "uncommon", "g" ], "ss-helmet-skull-helmet": [ "uncommon", "g" ], "ss-helmet-tiger-helmet": [ "uncommon", "g" ], "ss-helmet-galaxy-helmet": [ "epic", "g" ], "ss-helmet-disco-ball": [ "legendary", "g" ], "ss-helmet-watermelon-helmet": [ "rare", "g" ], "ss-helmet-eight-ball": [ "rare", "g" ], "ss-helmet-eyeball": [ "epic", "g" ], "ss-helmet-pumpkin-helmet": [ "rare", "g" ], "ss-helmet-cat-ears": [ "epic", "g" ], "ss-helmet-pizza-helmet": [ "epic", "g" ], "ss-effect-white-air-streaks": [ "common", "g" ], "ss-effect-flames": [ "common", "g" ], "ss-effect-sparks": [ "uncommon", "g" ], "ss-effect-electric-arcs": [ "uncommon", "g" ], "ss-effect-rainbow": [ "epic", "g" ], "ss-effect-vapor-trail": [ "common", "g" ], "ss-effect-confetti": [ "rare", "g" ], "ss-effect-purple-plasma": [ "epic", "g" ], "ss-smoke-pink-tyre-smoke": [ "common", "g" ], "ss-smoke-blue-tyre-smoke": [ "common", "g" ], "ss-smoke-green-tyre-smoke": [ "common", "g" ], "ss-smoke-purple-tyre-smoke": [ "common", "g" ], "ss-smoke-gold-tyre-smoke": [ "common", "g" ], "ss-podium-confetti-podium": [ "common", "g" ], "ss-podium-fireworks-podium": [ "uncommon", "g" ], "cl-color-cherry": [ "common", "g" ], "cl-color-tangerine": [ "common", "g" ], "cl-color-lemon": [ "common", "g" ], "cl-color-grass": [ "common", "g" ], "cl-color-aqua": [ "common", "g" ], "cl-color-ocean": [ "common", "g" ], "cl-color-violet": [ "common", "g" ], "cl-color-bubblegum": [ "common", "g" ], "cl-color-snow": [ "common", "g" ], "cl-color-cocoa": [ "common", "g" ], "cl-color-gold": [ "uncommon", "g" ], "cl-color-slate": [ "common", "g" ], "cl-color-neon-green": [ "uncommon", "g" ], "cl-color-neon-pink": [ "uncommon", "g" ], "cl-color-neon-blue": [ "uncommon", "g" ], "cl-color-neon-orange": [ "uncommon", "g" ], "cl-color-neon-yellow": [ "uncommon", "g" ], "cl-color-sunrise": [ "rare", "g" ], "cl-color-deep-sea": [ "rare", "g" ], "cl-color-mint-grape": [ "rare", "g" ], "cl-color-fireball": [ "rare", "g" ], "cl-color-cotton-candy": [ "rare", "g" ], "cl-color-forest": [ "rare", "g" ], "cl-color-rainbow": [ "epic", "g" ], "cl-color-rainbow-flow": [ "epic", "g" ], "cl-animal-python": [ "uncommon", "g" ], "cl-animal-rattlesnake": [ "uncommon", "g" ], "cl-animal-coral-snake": [ "uncommon", "g" ], "cl-animal-tiger": [ "uncommon", "g" ], "cl-animal-zebra": [ "rare", "g" ], "cl-animal-leopard": [ "rare", "g" ], "cl-animal-cow": [ "common", "g" ], "cl-animal-bee": [ "rare", "g" ], "cl-animal-caterpillar": [ "epic", "g" ], "cl-animal-centipede": [ "epic", "g" ], "cl-animal-dragon": [ "legendary", "g" ], "cl-design-stripes": [ "common", "g" ], "cl-design-candy-cane": [ "uncommon", "g" ], "cl-design-barber-pole": [ "uncommon", "g" ], "cl-design-checker": [ "common", "g" ], "cl-design-polka-dots": [ "common", "g" ], "cl-design-zigzag": [ "common", "g" ], "cl-design-galaxy": [ "epic", "g" ], "cl-design-lava": [ "epic", "g" ], "cl-design-ice": [ "rare", "g" ], "cl-design-circuit-board": [ "epic", "g" ], "cl-design-pixel": [ "rare", "g" ], "cl-design-camo": [ "common", "g" ], "cl-object-train-cars": [ "epic", "g" ], "cl-object-sausage-links": [ "uncommon", "g" ], "cl-object-spaghetti-noodle": [ "uncommon", "g" ], "cl-object-gummy-worm": [ "epic", "g" ], "cl-object-licorice": [ "uncommon", "g" ], "cl-object-garden-hose": [ "uncommon", "g" ], "cl-object-rope": [ "common", "g" ], "cl-object-chain": [ "rare", "g" ], "cl-object-measuring-tape": [ "rare", "g" ], "cl-object-pencil": [ "epic", "g" ], "cl-object-twinkling-lights": [ "legendary", "g" ], "cl-object-bead-necklace": [ "rare", "g" ], "cl-object-piano-keys": [ "epic", "g" ], "cl-object-film-strip": [ "epic", "g" ], "cl-object-dominoes": [ "epic", "g" ], "cl-object-scarf": [ "rare", "g" ], "cl-object-skeleton-spine": [ "legendary", "g" ], "cl-head-sunglasses": [ "uncommon", "g" ], "cl-head-crown": [ "epic", "g" ], "cl-head-party-hat": [ "uncommon", "g" ], "cl-head-googly-eyes": [ "rare", "g" ], "cl-head-tongue-out": [ "common", "g" ], "cl-head-tiny-cowboy-hat": [ "rare", "g" ], "cl-trail-sparkle-trail": [ "epic", "g" ], "cl-burst-candy-burst": [ "epic", "g" ], "cl-burst-coin-burst": [ "legendary", "g" ], "up-skin-jungle-explorer": [ "common", "g" ], "up-skin-mountaineer": [ "common", "g" ], "up-skin-arctic-explorer": [ "common", "g" ], "up-skin-safari-guide": [ "common", "g" ], "up-skin-deep-sea-diver": [ "uncommon", "g" ], "up-skin-aviator": [ "uncommon", "g" ], "up-skin-cave-explorer": [ "common", "g" ], "up-skin-treasure-hunter": [ "uncommon", "g" ], "up-skin-dusty-archaeologist": [ "common", "g" ], "up-skin-storm-chaser": [ "uncommon", "g" ], "up-skin-balloonist": [ "uncommon", "g" ], "up-skin-old-timey-explorer": [ "epic", "g" ], "up-skin-pirate": [ "epic", "g" ], "up-skin-park-ranger": [ "common", "g" ], "up-skin-astronaut": [ "epic", "g" ], "up-skin-tourist": [ "rare", "g" ], "up-skin-pizza-delivery": [ "rare", "g" ], "up-skin-window-washer": [ "rare", "g" ], "up-skin-grandma": [ "epic", "g" ], "up-skin-knight": [ "epic", "g" ], "up-skin-ninja": [ "rare", "g" ], "up-skin-chicken-suit": [ "legendary", "g" ], "up-pack-parachute-pack": [ "common", "g" ], "up-pack-teddy-bear": [ "uncommon", "g" ], "up-pack-picnic-basket": [ "common", "g" ], "up-pack-giant-sandwich": [ "rare", "g" ], "up-pack-fake-jetpack": [ "epic", "g" ], "up-pack-rolled-up-tent": [ "common", "g" ], "up-reward-1-000-m-badge": [ "uncommon", "g", "earned" ], "up-reward-space-helmet": [ "epic", "g", "earned" ], "up-reward-golden-crown": [ "legendary", "g", "earned" ], "up-scream-aaaah": [ "common", "g" ], "up-scream-yodel": [ "uncommon", "g" ], "up-scream-slide-whistle": [ "common", "g" ], "up-scream-opera-note": [ "epic", "g" ], "up-scream-wheee": [ "common", "g" ], "up-trail-rainbow-streamer": [ "uncommon", "g" ], "up-trail-comet-tail": [ "rare", "g" ], "up-trail-smoke-trail": [ "common", "g" ], "up-trail-gold-sparkles": [ "epic", "g" ], "rk-driver-sir-honksalot": [ "epic", "g" ], "rk-driver-captain-crumb": [ "uncommon", "g" ], "rk-driver-granny-vroom": [ "uncommon", "g" ], "rk-driver-bolt": [ "common", "g" ], "rk-driver-wasabi": [ "uncommon", "g" ], "rk-driver-professor-pickle": [ "common", "g" ], "rk-driver-dj-raccoon": [ "epic", "g" ], "rk-driver-chef-meatball": [ "common", "g" ], "rk-driver-yeti-betty": [ "uncommon", "g" ], "rk-driver-count-dracoola": [ "epic", "g" ], "rk-driver-tiny-rex": [ "legendary", "g" ], "rk-driver-sergeant-sprinkles": [ "rare", "g" ], "rk-driver-moolissa": [ "common", "g" ], "rk-driver-astro-hamster": [ "epic", "g" ], "rk-driver-cactus-jack": [ "rare", "g" ], "rk-driver-waddles": [ "rare", "g" ], "rk-driver-turkey-tom": [ "common", "g" ], "rk-kart-bathtub": [ "uncommon", "g" ], "rk-kart-shopping-cart": [ "common", "g" ], "rk-kart-lawnmower": [ "common", "g" ], "rk-kart-hot-dog-cart": [ "uncommon", "g" ], "rk-kart-bumper-car": [ "common", "g" ], "rk-kart-giant-shoe": [ "uncommon", "g" ], "rk-kart-banana": [ "epic", "g" ], "rk-kart-rubber-duck": [ "epic", "g" ], "rk-kart-couch": [ "rare", "g" ], "rk-kart-bed": [ "rare", "g" ], "rk-kart-toilet": [ "rare", "g" ], "rk-kart-pumpkin-carriage": [ "legendary", "g" ], "rk-kart-ice-cream-truck": [ "epic", "g" ], "rk-kart-rocket-sled": [ "legendary", "g" ], "rk-kart-cardboard-box": [ "common", "g" ], "rk-wheels-chrome-spokes": [ "common", "g" ], "rk-wheels-monster-treads": [ "uncommon", "g" ], "rk-wheels-wagon-wheels": [ "common", "g" ], "rk-wheels-donut-wheels": [ "epic", "g" ], "rk-wheels-whitewalls": [ "common", "g" ], "rk-wheels-golden-stars": [ "uncommon", "g" ], "rk-wheels-peppermint-swirls": [ "rare", "g" ], "rk-wheels-button-wheels": [ "common", "g" ], "rk-horn-goose-honk": [ "uncommon", "g" ], "rk-horn-clown-horn": [ "common", "g" ], "rk-horn-air-horn": [ "epic", "g" ], "rk-horn-kazoo": [ "rare", "g" ], "rk-horn-bike-bell": [ "common", "g" ], "rk-wreck-confetti-pop": [ "uncommon", "g" ], "rk-wreck-feather-poof": [ "uncommon", "g" ], "rk-wreck-bubble-burst": [ "common", "g" ], "rk-wreck-jelly-splat": [ "rare", "g" ], "rk-wreck-nuts-and-bolts": [ "common", "g" ], "rk-wreck-fireworks": [ "epic", "g" ], "rk-wreck-popcorn": [ "rare", "g" ], "rk-wreck-snow-globe": [ "epic", "g" ], "tt-colour-red": [ "common", "g" ], "tt-colour-orange": [ "common", "g" ], "tt-colour-yellow": [ "common", "g" ], "tt-colour-lime": [ "common", "g" ], "tt-colour-teal": [ "common", "g" ], "tt-colour-sky-blue": [ "common", "g" ], "tt-colour-purple": [ "common", "g" ], "tt-colour-pink": [ "common", "g" ], "tt-colour-white": [ "common", "g" ], "tt-colour-black": [ "common", "g" ], "tt-premium-gold": [ "epic", "g" ], "tt-premium-chrome": [ "epic", "g" ], "tt-premium-glow-in-the-dark": [ "uncommon", "g" ], "tt-premium-see-through-jelly": [ "uncommon", "g" ], "tt-premium-rainbow-shift": [ "legendary", "g" ], "tt-premium-bubblegum-sprinkles": [ "rare", "g" ], "tt-pattern-polka-dots": [ "common", "g" ], "tt-pattern-stripes": [ "common", "g" ], "tt-pattern-cow-print": [ "uncommon", "g" ], "tt-pattern-tie-dye": [ "uncommon", "g" ], "tt-pattern-checkerboard": [ "common", "g" ], "tt-pattern-leopard": [ "rare", "g" ], "tt-pattern-camo": [ "common", "g" ], "tt-pattern-plaid": [ "common", "g" ], "tt-pattern-watermelon": [ "rare", "g" ], "tt-pants-heart-boxers": [ "common", "g" ], "tt-pants-tighty-whities": [ "common", "g" ], "tt-pants-polka-dot-briefs": [ "common", "g" ], "tt-pants-banana-boxers": [ "uncommon", "g" ], "tt-pants-leopard-print": [ "uncommon", "g" ], "tt-pants-long-johns": [ "rare", "g" ], "tt-pants-diaper": [ "rare", "g" ], "tt-pants-super-undies": [ "epic", "g" ], "tt-pants-undies-on-head": [ "epic", "g" ], "tt-hat-traffic-cone": [ "common", "g" ], "tt-hat-propeller-beanie": [ "uncommon", "g" ], "tt-hat-chef-hat": [ "common", "g" ], "tt-hat-crown": [ "epic", "g" ], "tt-hat-pirate-hat": [ "uncommon", "g" ], "tt-hat-viking-helmet": [ "uncommon", "g" ], "tt-hat-cowboy-hat": [ "common", "g" ], "tt-hat-plunger": [ "rare", "g" ], "tt-hat-fishbowl": [ "epic", "g" ], "tt-hat-cooking-pot": [ "common", "g" ], "tt-hat-birthday-cone": [ "common", "g" ], "tt-hat-rubber-duck": [ "rare", "g" ], "tt-hat-toilet-paper-roll": [ "rare", "g" ], "tt-hat-tiny-top-hat": [ "common", "g" ], "tt-face-mustache": [ "common", "g" ], "tt-face-monocle": [ "uncommon", "g" ], "tt-face-googly-eyes": [ "common", "g" ], "tt-face-unibrow": [ "common", "g" ], "tt-face-braces": [ "common", "g" ], "tt-face-sunglasses": [ "rare", "g" ], "tt-costume-hot-dog": [ "epic", "g" ], "tt-costume-banana": [ "epic", "g" ], "tt-costume-pickle": [ "epic", "g" ], "tt-costume-chicken": [ "epic", "g" ], "tt-costume-dinosaur-onesie": [ "epic", "g" ], "tt-costume-shark": [ "epic", "g" ], "tt-costume-cactus": [ "epic", "g" ], "tt-costume-sushi-roll": [ "epic", "g" ], "tt-costume-astronaut": [ "epic", "g" ], "tt-costume-knight": [ "epic", "g" ], "tt-costume-toilet-paper-mummy": [ "epic", "g" ], "tt-costume-turkey": [ "epic", "g" ], "tt-dance-wiggle-wobble": [ "uncommon", "g" ], "tt-dance-robot": [ "uncommon", "g" ], "tt-dance-spin-cycle": [ "uncommon", "g" ], "tt-dance-chicken-flap": [ "rare", "g" ], "tt-dance-jelly-jump": [ "epic", "g" ], "tt-dance-disco-point": [ "rare", "g" ], "tt-scream-wheee": [ "common", "g" ], "tt-scream-aaaah": [ "common", "g" ], "tt-scream-yodel-drop": [ "common", "g" ], "tt-scream-slide-whistle": [ "common", "g" ], "tt-scream-kazoo-wail": [ "common", "g" ], "tt-scream-squeaky-toy": [ "common", "g" ], "tt-splash-confetti-pop": [ "uncommon", "g" ], "tt-splash-bubble-burst": [ "uncommon", "g" ], "tt-splash-rainbow-splat": [ "rare", "g" ], "tt-splash-star-shower": [ "rare", "g" ], "tt-splash-glitter-geyser": [ "epic", "g" ], "sc-egg-white-egg": [ "common", "g" ], "sc-egg-brown-egg": [ "common", "g" ], "sc-egg-speckled-quail": [ "common", "g" ], "sc-egg-robin-blue": [ "common", "g" ], "sc-egg-ostrich-egg": [ "uncommon", "g" ], "sc-egg-emu-egg": [ "uncommon", "g" ], "sc-egg-rotten-egg": [ "uncommon", "g" ], "sc-egg-golden-egg": [ "epic", "g" ], "sc-egg-painted-easter-egg": [ "rare", "g" ], "sc-egg-chocolate-egg": [ "epic", "g" ], "sc-egg-hard-boiled": [ "rare", "g" ], "sc-egg-century-egg": [ "epic", "g" ], "sc-egg-dinosaur-egg": [ "epic", "g" ], "sc-egg-dragon-egg": [ "legendary", "g" ], "sc-egg-alien-egg": [ "legendary", "g" ], "sc-egg-jeweled-egg": [ "legendary", "g" ], "sc-egg-disco-ball": [ "legendary", "g" ], "sc-egg-pixel-egg": [ "epic", "g" ], "sc-egg-bandaged-egg": [ "rare", "g" ], "sc-hat-eggcup-crown": [ "epic", "g" ], "sc-hat-frying-pan": [ "common", "g" ], "sc-hat-nest": [ "uncommon", "g" ], "sc-hat-chef-hat": [ "common", "g" ], "sc-hat-bacon-headband": [ "uncommon", "g" ], "sc-hat-baby-chick": [ "epic", "g" ], "sc-hat-sunny-side-up-beret": [ "rare", "g" ], "sc-gun-cast-iron": [ "common", "g" ], "sc-gun-gold-plated": [ "epic", "g" ], "sc-gun-egg-carton": [ "common", "g" ], "sc-gun-yolk-drip": [ "uncommon", "g" ], "sc-gun-bacon-wrap": [ "uncommon", "g" ], "sc-gun-ketchup-and-mustard": [ "common", "g" ], "sc-gun-hot-sauce": [ "uncommon", "g" ], "sc-gun-toaster-chrome": [ "epic", "g" ], "sc-gun-candy-stripe": [ "common", "g" ], "sc-gun-whisk-barrel": [ "rare", "g" ], "sc-gun-wooden-spoon-stock": [ "rare", "g" ], "sc-gun-rubber-chicken": [ "legendary", "g" ], "sc-crack-fried-egg": [ "common", "g" ], "sc-crack-scrambled": [ "uncommon", "g" ], "sc-crack-chick-hatches": [ "epic", "g" ], "sc-crack-shell-confetti": [ "rare", "g" ], "sc-crack-stink-puff": [ "common", "g" ], "ar-alien-little-green": [ "common", "g" ], "ar-alien-one-eyed-blob": [ "common", "g" ], "ar-alien-three-eyed-guy": [ "common", "g" ], "ar-alien-tentacle-squid": [ "uncommon", "g" ], "ar-alien-slime-cube": [ "uncommon", "g" ], "ar-alien-fuzzy-furball": [ "common", "g" ], "ar-alien-crystal-alien": [ "epic", "g" ], "ar-alien-mushroom-alien": [ "uncommon", "g" ], "ar-alien-jellyfish": [ "rare", "g" ], "ar-alien-cat-alien": [ "epic", "g" ], "ar-alien-potato-alien": [ "common", "g" ], "ar-alien-star-alien": [ "rare", "g" ], "ar-alien-eyeball-with-legs": [ "epic", "g" ], "ar-alien-brain-in-a-jar": [ "epic", "g" ], "ar-alien-robot-suit-pilot": [ "legendary", "g" ], "ar-alien-mustache-disguise": [ "legendary", "g" ], "ar-alien-escaped-cow": [ "legendary", "g" ], "ar-alien-astronaut-hamster": [ "epic", "g" ], "ar-alien-retro-robot": [ "rare", "g" ], "ar-trail-stardust": [ "common", "g" ], "ar-trail-slime-drips": [ "common", "g" ], "ar-trail-bubbles": [ "common", "g" ], "ar-trail-hearts": [ "uncommon", "g" ], "ar-trail-confetti": [ "uncommon", "g" ], "ar-trail-pixels": [ "rare", "g" ], "ar-trail-snowflakes": [ "common", "g" ], "ar-trail-petals": [ "rare", "g" ], "ar-trail-zaps": [ "epic", "g" ], "ar-trail-tractor-rings": [ "epic", "g" ], "ar-tunnel-deep-blue": [ "common", "g" ], "ar-tunnel-silver": [ "common", "g" ], "ar-tunnel-bubblegum": [ "uncommon", "g" ], "ar-tunnel-ultraviolet": [ "uncommon", "g" ], "ar-tunnel-ocean": [ "common", "g" ], "ar-tunnel-moon-dust": [ "rare", "g" ], "ar-tunnel-treasure": [ "epic", "g" ], "ar-tunnel-checkerboard": [ "epic", "g" ], "ar-tunnel-candy-checker": [ "epic", "g" ], "ar-tunnel-prism": [ "legendary", "g" ], "rl-car-muscle-car": [ "common", "g" ], "rl-car-rally-hatch": [ "common", "g" ], "rl-car-hot-rod": [ "uncommon", "g" ], "rl-car-pickup": [ "common", "g" ], "rl-car-dune-buggy": [ "common", "g" ], "rl-car-monster-truck": [ "epic", "g" ], "rl-car-retro-wedge": [ "uncommon", "g" ], "rl-car-go-kart": [ "common", "g" ], "rl-car-limo": [ "uncommon", "g" ], "rl-car-school-bus": [ "uncommon", "g" ], "rl-car-taxi": [ "common", "g" ], "rl-car-police-cruiser": [ "uncommon", "g" ], "rl-car-fire-truck": [ "epic", "g" ], "rl-car-ice-cream-truck": [ "epic", "g" ], "rl-car-garbage-truck": [ "rare", "g" ], "rl-car-tractor": [ "rare", "g" ], "rl-car-golf-cart": [ "common", "g" ], "rl-car-lunar-rover": [ "epic", "g" ], "rl-car-wooden-toy": [ "rare", "g" ], "rl-car-wind-up-car": [ "epic", "g" ], "rl-car-rc-car": [ "rare", "g" ], "rl-car-soapbox-crate": [ "rare", "g" ], "rl-car-cardboard-box": [ "common", "g" ], "rl-car-shopping-cart": [ "epic", "g" ], "rl-car-bathtub": [ "epic", "g" ], "rl-car-couch": [ "epic", "g" ], "rl-car-hot-dog": [ "epic", "g" ], "rl-car-banana": [ "epic", "g" ], "rl-car-rubber-duck": [ "legendary", "g" ], "rl-car-giant-shoe": [ "legendary", "g" ], "rl-car-rocket-car": [ "legendary", "g" ], "rl-paint-candy-apple-paint": [ "common", "g" ], "rl-paint-tangerine-paint": [ "common", "g" ], "rl-paint-lemon-drop-paint": [ "common", "g" ], "rl-paint-lime-fizz-paint": [ "common", "g" ], "rl-paint-mint-paint": [ "common", "g" ], "rl-paint-teal-paint": [ "common", "g" ], "rl-paint-sky-paint": [ "common", "g" ], "rl-paint-midnight-paint": [ "common", "g" ], "rl-paint-lavender-paint": [ "common", "g" ], "rl-paint-grape-paint": [ "common", "g" ], "rl-paint-bubblegum-paint": [ "common", "g" ], "rl-paint-magenta-paint": [ "common", "g" ], "rl-paint-copper-paint": [ "uncommon", "g" ], "rl-paint-sand-paint": [ "common", "g" ], "rl-paint-gold-paint": [ "uncommon", "g" ], "rl-paint-silver-paint": [ "rare", "g" ], "rl-wheels-whitewalls": [ "common", "g" ], "rl-wheels-wire-spokes": [ "uncommon", "g" ], "rl-wheels-gold-star": [ "uncommon", "g" ], "rl-wheels-off-road": [ "common", "g" ], "rl-wheels-neon-rings": [ "epic", "g" ], "rl-wheels-wooden": [ "uncommon", "g" ], "rl-wheels-red-steelies": [ "common", "g" ], "rl-wheels-turbine": [ "rare", "g" ], "rl-wheels-candy-swirl": [ "rare", "g" ], "rl-wheels-flower-caps": [ "rare", "g" ], "rl-wheels-race-slicks": [ "common", "g" ], "rl-wheels-rainbow-rings": [ "epic", "g" ], "rl-smoke-pink-tyre-smoke": [ "common", "g" ], "rl-smoke-sky-blue-tyre-smoke": [ "common", "g" ], "rl-smoke-lime-tyre-smoke": [ "common", "g" ], "rl-smoke-purple-tyre-smoke": [ "common", "g" ], "rl-smoke-gold-tyre-smoke": [ "common", "g" ], "rl-smoke-orange-tyre-smoke": [ "common", "g" ], "rl-smoke-red-tyre-smoke": [ "common", "g" ], "rl-smoke-mint-tyre-smoke": [ "common", "g" ], "rl-smoke-rainbow-tyre-smoke": [ "epic", "g" ], "rl-smoke-confetti-tyre-smoke": [ "epic", "g" ], "rl-horn-beep-beep": [ "common", "g" ], "rl-horn-clown-honk": [ "uncommon", "g" ], "rl-horn-air-horn": [ "uncommon", "g" ], "rl-horn-little-tune": [ "uncommon", "g" ], "rl-horn-duck-quack": [ "epic", "g" ], "rl-horn-bike-bell": [ "common", "g" ], "rl-horn-squeaky-toy": [ "rare", "g" ], "rl-horn-space-zap": [ "epic", "g" ], "rl-horn-foghorn": [ "rare", "g" ], "rl-horn-ice-cream-jingle": [ "epic", "g" ], "rl-horn-train-whistle": [ "rare", "g" ], "cf-hat-detective-deerstalker": [ "uncommon", "g" ], "cf-hat-safari-hat": [ "common", "g" ], "cf-hat-painter-s-beret": [ "common", "g" ], "cf-hat-museum-guard-cap": [ "common", "g" ], "cf-hat-hard-hat": [ "common", "g" ], "cf-hat-exterminator-cap": [ "rare", "g" ], "cf-hat-goggles": [ "common", "g" ], "cf-tool-magnifying-glass": [ "uncommon", "g" ], "cf-tool-paint-scraper": [ "common", "g" ], "cf-tool-spray-bottle": [ "common", "g" ], "cf-tool-feather-duster": [ "rare", "g" ], "cf-splash-paint-splash": [ "epic", "g" ], "cf-caught-surprise-spin": [ "epic", "g" ], "oo-outfit-police-officer": [ "common", "g" ], "oo-outfit-sheriff": [ "uncommon", "g" ], "oo-outfit-mall-cop": [ "common", "g" ], "oo-outfit-security-guard": [ "common", "g" ], "oo-outfit-detective": [ "uncommon", "g" ], "oo-outfit-store-manager": [ "common", "g" ], "oo-outfit-janitor": [ "common", "g" ], "oo-outfit-park-ranger": [ "uncommon", "g" ], "oo-outfit-exterminator": [ "rare", "g" ], "oo-outfit-construction-worker": [ "common", "g" ], "oo-outfit-cowboy": [ "rare", "g" ], "oo-outfit-pirate": [ "epic", "g" ], "oo-outfit-top-hat": [ "epic", "g" ], "oo-outfit-traffic-cone": [ "legendary", "g" ], "oo-tool-flashlight": [ "common", "g" ], "oo-tool-price-scanner": [ "uncommon", "g" ], "oo-tool-flyswatter": [ "common", "g" ], "oo-tool-butterfly-net": [ "rare", "g" ], "oo-tool-broom": [ "common", "g" ], "oo-tool-rubber-chicken": [ "epic", "g" ], "oo-taunt-bike-horn": [ "common", "g" ], "oo-taunt-squeaky-duck": [ "common", "g" ], "oo-taunt-slide-whistle": [ "common", "g" ], "oo-taunt-boing": [ "common", "g" ], "oo-taunt-cuckoo": [ "uncommon", "g" ], "oo-taunt-kazoo": [ "uncommon", "g" ], "oo-taunt-doorbell": [ "rare", "g" ], "oo-taunt-party-blower": [ "epic", "g" ], "oo-poof-cloud-poof": [ "common", "g" ], "oo-poof-feather-poof": [ "uncommon", "g" ], "oo-poof-bubble-poof": [ "rare", "g" ], "oo-poof-star-poof": [ "epic", "g" ], "oo-poof-price-tag-poof": [ "epic", "g" ], "dz-outfit-jet-pilot": [ "uncommon", "g" ], "dz-outfit-lumberjack": [ "common", "g" ], "dz-outfit-park-ranger": [ "common", "g" ], "dz-outfit-scuba-diver": [ "uncommon", "g" ], "dz-outfit-head-chef": [ "uncommon", "g" ], "dz-outfit-hazmat-suit": [ "uncommon", "g" ], "dz-outfit-castle-knight": [ "epic", "g" ], "dz-outfit-astronaut": [ "epic", "g" ], "dz-outfit-farmer": [ "common", "g" ], "dz-outfit-mail-carrier": [ "common", "g" ], "dz-outfit-lifeguard": [ "common", "g" ], "dz-outfit-ninja": [ "rare", "g" ], "dz-outfit-scarecrow": [ "rare", "g" ], "dz-outfit-skeleton": [ "rare", "g" ], "dz-outfit-banana-suit": [ "epic", "g" ], "dz-outfit-cardboard-box-robot": [ "epic", "g" ], "dz-pack-rucksack": [ "common", "g" ], "dz-pack-jetpack": [ "epic", "g" ], "dz-pack-teddy-bear": [ "uncommon", "g" ], "dz-pack-tortoise-shell": [ "uncommon", "g" ], "dz-pack-treasure-chest": [ "epic", "g" ], "dz-pack-lunchbox": [ "common", "g" ], "dz-pack-guitar-case": [ "rare", "g" ], "dz-pack-fishbowl": [ "epic", "g" ], "dz-glider-umbrella": [ "common", "g" ], "dz-glider-paper-airplane": [ "common", "g" ], "dz-glider-hang-glider": [ "uncommon", "g" ], "dz-glider-kite": [ "common", "g" ], "dz-glider-bedsheet-parachute": [ "common", "g" ], "dz-glider-trash-bag-parachute": [ "common", "g" ], "dz-glider-cardboard-wings": [ "common", "g" ], "dz-glider-dragon-wings": [ "epic", "g" ], "dz-glider-bat-wings": [ "uncommon", "g" ], "dz-glider-bunch-of-balloons": [ "uncommon", "g" ], "dz-glider-lawn-chair-with-balloons": [ "epic", "g" ], "dz-glider-magic-carpet": [ "epic", "g" ], "dz-glider-picnic-blanket": [ "uncommon", "g" ], "dz-glider-surfboard": [ "rare", "g" ], "dz-glider-pizza-slice": [ "rare", "g" ], "dz-glider-broomstick": [ "epic", "g" ], "dz-glider-giant-leaf": [ "common", "g" ], "dz-glider-spinning-maple-seed": [ "rare", "g" ], "dz-glider-rubber-duck-float": [ "rare", "g" ], "dz-glider-giant-pigeon": [ "legendary", "g" ], "dz-glider-pterodactyl": [ "legendary", "g" ], "dz-glider-flying-squirrel-suit": [ "epic", "g" ], "dz-glider-ufo-disc": [ "legendary", "g" ], "dz-glider-small-cloud": [ "epic", "g" ], "dz-trail-smoke": [ "common", "g" ], "dz-trail-sparkles": [ "uncommon", "g" ], "dz-trail-rainbow": [ "epic", "g" ], "dz-trail-feathers": [ "common", "g" ], "dz-trail-leaves": [ "common", "g" ], "dz-trail-bubbles": [ "rare", "g" ], "dz-wrap-gold": [ "legendary", "g" ], "dz-wrap-chrome": [ "epic", "g" ], "dz-wrap-wood-grain": [ "common", "g" ], "dz-wrap-forest-camo": [ "common", "g" ], "dz-wrap-desert-camo": [ "common", "g" ], "dz-wrap-arctic-camo": [ "common", "g" ], "dz-wrap-pixel-camo": [ "uncommon", "g" ], "dz-wrap-neon-outline": [ "epic", "g" ], "dz-wrap-toy-blaster": [ "uncommon", "g" ], "dz-wrap-cardboard": [ "common", "g" ], "dz-wrap-candy-cane": [ "uncommon", "g" ], "dz-wrap-lava": [ "epic", "g" ], "dz-wrap-ice": [ "rare", "g" ], "dz-wrap-galaxy": [ "epic", "g" ], "dz-wrap-rust": [ "common", "g" ], "dz-wrap-graffiti": [ "rare", "g" ], "dz-wrap-bubblegum-pink": [ "common", "g" ], "dz-wrap-hazard-stripes": [ "rare", "g" ], "dz-wrap-plastic-brick": [ "epic", "g" ], "dz-build-cardboard": [ "common", "g" ], "dz-build-frosted-glass": [ "uncommon", "g" ], "dz-build-ice": [ "uncommon", "g" ], "dz-build-candy": [ "epic", "g" ], "dz-build-stone": [ "common", "g" ], "dz-build-scrap-metal": [ "rare", "g" ], "dz-emote-wave": [ "common", "g" ], "dz-emote-dance": [ "uncommon", "g" ], "dz-emote-clap": [ "common", "g" ], "dz-emote-jumping-jacks": [ "common", "g" ], "dz-emote-robot": [ "uncommon", "g" ], "dz-emote-twirl": [ "rare", "g" ], "dz-victory-champion": [ "epic", "g" ], "dz-victory-flex": [ "uncommon", "g" ], "dz-victory-take-a-bow": [ "rare", "g" ], "dz-victory-jump-for-joy": [ "epic", "g" ] }, "PACKS": {"draw-1": {"kind": "draws", "name": "One chest", "price": 119, "contents": {"draws": 1 } }, "draw-5": {"kind": "draws", "name": "Five chests", "price": 595, "contents": {"draws": 5 } }, "draw-10": {"kind": "draws", "name": "Ten chests", "price": 1190, "contents": {"draws": 10 } }, "skins-space": {"kind": "skins", "name": "Launch Bay", "price": 179, "contents": {"items": [ "moon-walker", "comet-courier" ] } }, "skins-ocean": {"kind": "skins", "name": "Deep End", "price": 179, "contents": {"items": [ "tide-pool", "coral-diver" ] } }, "skins-neon": {"kind": "skins", "name": "After Dark", "price": 179, "contents": {"items": [ "neon-jogger", "grid-runner" ] } }, "skins-candy": {"kind": "skins", "name": "Sweet Tooth", "price": 239, "contents": {"items": [ "bubblegum", "sprinkle-pop", "gumdrop-knight" ] } }, "skins-robot": {"kind": "skins", "name": "Workshop", "price": 480, "contents": {"items": [ "tin-tinker", "circuit-scout" ] } }, "skins-animals": {"kind": "skins", "name": "Wild Things", "price": 600, "contents": {"items": [ "tabby", "cub", "hopper", "red-fox" ] } }, "skins-seasons": {"kind": "skins", "name": "All Year Round", "price": 960, "contents": {"items": [ "spring-sprout", "summer-sun", "autumn-ember", "winter-frost" ] } }, "skins-wild": {"kind": "skins", "name": "Far Lands", "price": 480, "contents": {"items": [ "dune-rover", "magma-walker" ] } }, "acc-hats": {"kind": "accessories", "name": "Hat Box", "price": 719, "contents": {"items": [ "pom-beanie", "wizard-cone", "propeller-cap", "tall-topper", "daisy-crown" ] } }, "acc-glasses": {"kind": "accessories", "name": "Eyewear Case", "price": 1199, "contents": {"items": [ "star-shades", "heart-specs", "monocle", "glow-visor" ] } }, "acc-capes": {"kind": "accessories", "name": "Cape Rack", "price": 779, "contents": {"items": [ "hero-cape", "galaxy-cape", "leaf-cloak" ] } }, "acc-trails": {"kind": "accessories", "name": "Trail Kit", "price": 779, "contents": {"items": [ "sparkle-trail", "bubble-trail", "rainbow-streak" ] } }, "acc-auras": {"kind": "accessories", "name": "Glow Jar", "price": 1139, "contents": {"items": [ "halo-glow", "ember-aura", "frost-ring" ] } }, "acc-pets": {"kind": "accessories", "name": "Pet Carrier", "price": 839, "contents": {"items": [ "pocket-slime", "mini-bot", "star-buddy", "ghost-pup" ] } }, "acc-drake": {"kind": "accessories", "name": "Dragon Egg", "price": 1200, "contents": {"items": [ "baby-drake" ] } }, "bb-decals-speed": {"kind": "items", "name": "Speed Shop", "price": 300, "contents": {"items": [ "bb-decal-flames", "bb-decal-racing-stripes", "bb-decal-lightning-bolts", "bb-decal-checkered-flag", "bb-decal-carbon-fiber" ] } }, "bb-decals-wild": {"kind": "items", "name": "Wild Side", "price": 837, "contents": {"items": [ "bb-decal-shark-mouth", "bb-decal-tiger-stripes", "bb-decal-dragon-scales", "bb-decal-cow-print", "bb-decal-skeleton-ribs" ] } }, "bb-decals-tech": {"kind": "items", "name": "Late Night", "price": 1318, "contents": {"items": [ "bb-decal-galaxy", "bb-decal-constellations", "bb-decal-circuit-board", "bb-decal-wireframe", "bb-decal-pixel-camo" ] } }, "bb-decals-art": {"kind": "items", "name": "Art Class", "price": 899, "contents": {"items": [ "bb-decal-graffiti-drips", "bb-decal-comic-book-dots", "bb-decal-topographic-lines", "bb-decal-stained-glass", "bb-decal-honeycomb" ] } }, "bb-decals-weather": {"kind": "items", "name": "Hot and Cold", "price": 1259, "contents": {"items": [ "bb-decal-lava-cracks", "bb-decal-frost", "bb-decal-autumn-leaves", "bb-decal-rust-bucket", "bb-decal-wood-paneling" ] } }, "bb-decals-jobs": {"kind": "items", "name": "Odd Jobs", "price": 1980, "contents": {"items": [ "bb-decal-duct-tape-patches", "bb-decal-donut-sprinkles", "bb-decal-bubble-wrap", "bb-decal-taxi", "bb-decal-police-cruiser", "bb-decal-ice-cream-truck" ] } }, "bb-trails-burn": {"kind": "items", "name": "Afterburners", "price": 1919, "contents": {"items": [ "bb-trail-classic-flame", "bb-trail-blue-plasma", "bb-trail-lightning", "bb-trail-lava", "bb-trail-water-jet", "bb-trail-laser-beam" ] } }, "bb-trails-party": {"kind": "items", "name": "Party Bag", "price": 1017, "contents": {"items": [ "bb-trail-rainbow", "bb-trail-confetti", "bb-trail-hearts", "bb-trail-music-notes", "bb-trail-sparkles" ] } }, "bb-trails-weather": {"kind": "items", "name": "Light and Fluffy", "price": 419, "contents": {"items": [ "bb-trail-bubbles", "bb-trail-snowflakes", "bb-trail-autumn-leaves", "bb-trail-feathers", "bb-trail-soap-suds", "bb-trail-smoke-rings" ] } }, "bb-trails-odd": {"kind": "items", "name": "Odds and Ends", "price": 2280, "contents": {"items": [ "bb-trail-popcorn", "bb-trail-rubber-ducks", "bb-trail-toast-slices", "bb-trail-dollar-bills", "bb-trail-slime" ] } }, "bb-trails-night": {"kind": "items", "name": "Night Shift", "price": 1920, "contents": {"items": [ "bb-trail-stardust", "bb-trail-pixel-blocks", "bb-trail-ink", "bb-trail-ones-and-zeros", "bb-trail-bats" ] } }, "bb-goals-bang": {"kind": "items", "name": "Big Bangs", "price": 2038, "contents": {"items": [ "bb-goal-fireworks", "bb-goal-supernova", "bb-goal-lightning-strike", "bb-goal-meteor", "bb-goal-volcano" ] } }, "bb-goals-party": {"kind": "items", "name": "Party Time", "price": 2339, "contents": {"items": [ "bb-goal-confetti-cannon", "bb-goal-disco-ball-drop", "bb-goal-pinata-burst", "bb-goal-popcorn-pop", "bb-goal-money-rain" ] } }, "bb-goals-science": {"kind": "items", "name": "Strange Science", "price": 2339, "contents": {"items": [ "bb-goal-black-hole", "bb-goal-tornado", "bb-goal-freeze-and-shatter", "bb-goal-pixel-shatter", "bb-goal-flock-of-birds" ] } }, "bb-goals-giant": {"kind": "items", "name": "Giant Trouble", "price": 5820, "contents": {"items": [ "bb-goal-giant-foot-stomp", "bb-goal-ufo-abduction", "bb-goal-shark-attack", "bb-goal-giant-airhorn", "bb-goal-pumpkin-splat", "bb-goal-goal-letters" ] } }, "bb-toppers": {"kind": "items", "name": "Aerial Shop", "price": 1319, "contents": {"items": [ "bb-topper-tennis-ball", "bb-topper-gold-star", "bb-topper-bath-duck", "bb-topper-mini-pumpkin", "bb-topper-pennant", "bb-topper-eyeball" ] } }, "bb-hats": {"kind": "items", "name": "Roof Rack", "price": 1378, "contents": {"items": [ "bb-hat-traffic-cone", "bb-hat-top-hat", "bb-hat-crown", "bb-hat-propeller-beanie", "bb-hat-cowboy-hat", "bb-hat-chef-hat" ] } }, "bb-wheels": {"kind": "items", "name": "Tyre Fitter", "price": 839, "contents": {"items": [ "bb-wheels-five-spoke", "bb-wheels-discs", "bb-wheels-cross", "bb-wheels-gold-rims" ] } }, "bb-engines": {"kind": "items", "name": "Under the Bonnet", "price": 1199, "contents": {"items": [ "bb-engine-purr", "bb-engine-buzz", "bb-engine-rumble", "bb-engine-whirr" ] } }, "ss-liveries-classic": {"kind": "items", "name": "Paint Shop", "price": 240, "contents": {"items": [ "ss-livery-two-tone-classic", "ss-livery-retro-stripes", "ss-livery-pastel", "ss-livery-checkered" ] } }, "ss-liveries-loud": {"kind": "items", "name": "Show Car", "price": 1258, "contents": {"items": [ "ss-livery-matte-black-with-neon", "ss-livery-chrome", "ss-livery-carbon", "ss-livery-flames" ] } }, "ss-helmets-fast": {"kind": "items", "name": "Helmet Rack", "price": 299, "contents": {"items": [ "ss-helmet-flames-helmet", "ss-helmet-checkered-helmet", "ss-helmet-lightning-helmet", "ss-helmet-chrome-visor" ] } }, "ss-helmets-wild": {"kind": "items", "name": "Wild Lids", "price": 1557, "contents": {"items": [ "ss-helmet-shark-helmet", "ss-helmet-skull-helmet", "ss-helmet-tiger-helmet", "ss-helmet-eyeball", "ss-helmet-cat-ears" ] } }, "ss-helmets-odd": {"kind": "items", "name": "Odd Lids", "price": 3660, "contents": {"items": [ "ss-helmet-galaxy-helmet", "ss-helmet-disco-ball", "ss-helmet-watermelon-helmet", "ss-helmet-eight-ball", "ss-helmet-pumpkin-helmet", "ss-helmet-pizza-helmet" ] } }, "ss-effects-air": {"kind": "items", "name": "Clean Air", "price": 299, "contents": {"items": [ "ss-effect-white-air-streaks", "ss-effect-vapor-trail", "ss-effect-flames", "ss-effect-sparks" ] } }, "ss-effects-show": {"kind": "items", "name": "Light Show", "price": 1739, "contents": {"items": [ "ss-effect-electric-arcs", "ss-effect-rainbow", "ss-effect-confetti", "ss-effect-purple-plasma" ] } }, "ss-extras": {"kind": "items", "name": "Pit Wall Party", "price": 479, "contents": {"items": [ "ss-smoke-pink-tyre-smoke", "ss-smoke-blue-tyre-smoke", "ss-smoke-green-tyre-smoke", "ss-smoke-purple-tyre-smoke", "ss-smoke-gold-tyre-smoke", "ss-podium-confetti-podium", "ss-podium-fireworks-podium" ] } } }, "EMERALDS": {"emeralds_7": {"name": "Emerald Handful", "emeralds": 7, "cents": 99, "currency": "usd" }, "emeralds_39": {"name": "Emerald Pouch", "emeralds": 39, "cents": 499, "currency": "usd" }, "emeralds_80": {"name": "Emerald Sack", "emeralds": 80, "cents": 999, "currency": "usd" }, "emeralds_180": {"name": "Emerald Chest", "emeralds": 180, "cents": 1999, "currency": "usd" }, "emeralds_1000": {"name": "Emerald Buttload", "emeralds": 1000, "cents": 4999, "currency": "usd" }, "emeralds_4000": {"name": "Emerald Vault", "emeralds": 4000, "cents": 9999, "currency": "usd" } } }; From fda9cf03f50ca18dbaf65d7cb67e070fd7aca048 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:05:41 +0000 Subject: [PATCH 02/14] Wallet server: /api/wallet (balance, buy, chest, gift, seen), emerald checkout and webhook credit, node tests with faked Stripe and Firestore Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/shop/tests/fakes.mjs | 143 +++++++++ e63334287a3deaa3/shop/tests/server.test.mjs | 300 +++++++++++++++++++ e63334287a3deaa3/shop/tools/server-data.js | 11 +- functions/_catalog.js | 2 +- functions/_wallet.js | 316 ++++++++++++++++++++ functions/api/checkout.js | 31 ++ functions/api/stripe-webhook.js | 9 + functions/api/wallet/buy.js | 7 + functions/api/wallet/chest.js | 7 + functions/api/wallet/gift.js | 7 + functions/api/wallet/index.js | 8 + functions/api/wallet/seen.js | 5 + 12 files changed, 840 insertions(+), 6 deletions(-) create mode 100644 e63334287a3deaa3/shop/tests/fakes.mjs create mode 100644 e63334287a3deaa3/shop/tests/server.test.mjs create mode 100644 functions/_wallet.js create mode 100644 functions/api/wallet/buy.js create mode 100644 functions/api/wallet/chest.js create mode 100644 functions/api/wallet/gift.js create mode 100644 functions/api/wallet/index.js create mode 100644 functions/api/wallet/seen.js diff --git a/e63334287a3deaa3/shop/tests/fakes.mjs b/e63334287a3deaa3/shop/tests/fakes.mjs new file mode 100644 index 00000000..fea10e06 --- /dev/null +++ b/e63334287a3deaa3/shop/tests/fakes.mjs @@ -0,0 +1,143 @@ +// Test doubles for the shop's server tests: a fake fetch that answers for Google's keys and token endpoint, Firestore +// (with real transaction conflicts) and Stripe, and refuses every other address, so a test can never reach a real +// service. Nothing here is a real key: every key is made fresh in memory for each run. +import { webcrypto as wc } from 'node:crypto'; + +const enc = new TextEncoder(); +const b64u = (b) => Buffer.from(b).toString('base64url'); +export const PROJECT = 'rumblekarts'; +const DOCS = 'projects/' + PROJECT + '/databases/(default)/documents'; +const FS = 'https://firestore.googleapis.com/v1/' + DOCS; +const tick = () => new Promise(r => setImmediate(r)); + +export async function makeKeys() { + const id = await wc.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify']); + const jwk = Object.assign(await wc.subtle.exportKey('jwk', id.publicKey), { kid: 'test-kid', alg: 'RS256', use: 'sig' }); + const sa = await wc.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign']); + const pk = Buffer.from(await wc.subtle.exportKey('pkcs8', sa.privateKey)).toString('base64'); + const pem = '-----BEGIN PRIVATE KEY-----\n' + pk.match(/.{1,64}/g).join('\n') + '\n-----END PRIVATE KEY-----\n'; + return { + jwk, + serviceAccount: JSON.stringify({ client_email: 'tests@example.invalid', private_key: pem }), + // A Firebase ID token for uid, signed with the in-memory key. provider: 'google.com' or 'anonymous'. + async token(uid, provider) { + const now = Math.floor(Date.now() / 1000); + const h = b64u(JSON.stringify({ alg: 'RS256', kid: 'test-kid', typ: 'JWT' })); + const p = b64u(JSON.stringify({ aud: PROJECT, iss: 'https://securetoken.google.com/' + PROJECT, sub: uid, iat: now - 5, exp: now + 3600, + email: uid + '@example.invalid', firebase: { sign_in_provider: provider || 'google.com' } })); + const s = await wc.subtle.sign('RSASSA-PKCS1-v1_5', id.privateKey, enc.encode(h + '.' + p)); + return h + '.' + p + '.' + b64u(s); + } + }; +} + +// Firestore REST with optimistic transactions: a commit fails with 409 ABORTED when a document the transaction read +// changed after it was read (real Firestore locks instead; either way the caller must retry). +export function fakeFirestore() { + const docs = new Map(); // path -> { fields, v } + const txs = new Map(); let txn = 0; + const pathOf = (name) => decodeURIComponent(name.slice(DOCS.length + 1)); + const res = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + function setPath(fields, dotted, value) { + const parts = dotted.split('.'); let f = fields; + for (let i = 0; i < parts.length - 1; i++) { + if (!f[parts[i]] || !f[parts[i]].mapValue) f[parts[i]] = { mapValue: { fields: {} } }; + f = f[parts[i]].mapValue.fields = f[parts[i]].mapValue.fields || {}; + } + f[parts[parts.length - 1]] = value; + } + function getPath(fields, dotted) { let f = { mapValue: { fields } }; for (const p of dotted.split('.')) { f = f && f.mapValue && f.mapValue.fields && f.mapValue.fields[p]; } return f; } + const api = { + docs, writes: 0, commits: 0, aborts: 0, + async handle(url, opts) { + await tick(); + const u = new URL(url), method = (opts && opts.method) || 'GET'; + const body = opts && opts.body ? JSON.parse(opts.body) : null; + if (u.pathname.endsWith(':beginTransaction')) { const id = 'tx' + (++txn); txs.set(id, new Map()); return res(200, { transaction: id }); } + if (u.pathname.endsWith(':rollback')) { txs.delete(body.transaction); return res(200, {}); } + if (u.pathname.endsWith(':commit')) { + api.commits++; + await tick(); + if (body.transaction) { + const reads = txs.get(body.transaction); + if (!reads) return res(400, { error: { status: 'INVALID_ARGUMENT', message: 'no such transaction' } }); + txs.delete(body.transaction); + for (const [p, v] of reads) { const d = docs.get(p); if ((d ? d.v : 0) !== v) { api.aborts++; return res(409, { error: { status: 'ABORTED', message: 'contention' } }); } } + } + for (const w of body.writes) { + const p = pathOf(w.update.name); + if (w.currentDocument && w.currentDocument.exists === false && docs.has(p)) return res(400, { error: { status: 'FAILED_PRECONDITION', message: 'exists' } }); + } + for (const w of body.writes) { + const p = pathOf(w.update.name), old = docs.get(p); + let fields; + if (w.updateMask) { fields = JSON.parse(JSON.stringify(old ? old.fields : {})); for (const fp of w.updateMask.fieldPaths) setPath(fields, fp, getPath(w.update.fields, fp)); } + else fields = JSON.parse(JSON.stringify(w.update.fields)); + docs.set(p, { fields, v: (old ? old.v : 0) + 1 }); api.writes++; + } + return res(200, { commitTime: new Date().toISOString() }); + } + if (method === 'GET' && u.pathname.startsWith('/v1/' + DOCS + '/')) { + const p = decodeURIComponent(u.pathname.slice(('/v1/' + DOCS + '/').length)), tx = u.searchParams.get('transaction'); + const d = docs.get(p); + if (tx) { const reads = txs.get(tx); if (!reads) return res(400, { error: { status: 'INVALID_ARGUMENT' } }); reads.set(p, d ? d.v : 0); } + if (!d) return res(404, { error: { code: 404, status: 'NOT_FOUND' } }); + return res(200, { name: DOCS + '/' + p, fields: JSON.parse(JSON.stringify(d.fields)) }); + } + return res(400, { error: { status: 'UNIMPLEMENTED', message: method + ' ' + url } }); + } + }; + return api; +} + +// Stripe: prices by lookup key, and Checkout sessions (remembered, so tests can look at what was asked for). +export function fakeStripe(prices) { + const api = { prices, sessions: [], calls: 0, + async handle(url, opts) { + api.calls++; + const u = new URL(url), method = (opts && opts.method) || 'GET'; + const res = (s, b) => new Response(JSON.stringify(b), { status: s, headers: { 'Content-Type': 'application/json' } }); + if (method === 'GET' && u.pathname === '/v1/prices') { + const key = u.searchParams.get('lookup_keys[0]'); + return res(200, { data: api.prices[key] ? [api.prices[key]] : [] }); + } + if (method === 'POST' && u.pathname === '/v1/checkout/sessions') { + const p = new URLSearchParams(opts.body), o = {}; for (const [k, v] of p) o[k] = v; + const s = { id: 'cs_test_' + (api.sessions.length + 1), url: 'https://checkout.stripe.com/c/pay/cs_test_' + (api.sessions.length + 1), params: o }; + api.sessions.push(s); return res(200, s); + } + return res(404, { error: { message: 'not faked: ' + method + ' ' + url } }); + } }; + return api; +} + +// The fetch every test uses. Anything not faked throws, so no test can reach a real service. +export function fakeFetch(keys, fs, st) { + const log = []; + const f = async (url, opts) => { + url = String(url); log.push(url); + if (url.startsWith('https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com')) + return new Response(JSON.stringify({ keys: [keys.jwk] }), { status: 200, headers: { 'Cache-Control': 'public, max-age=3600' } }); + if (url === 'https://oauth2.googleapis.com/token') return new Response(JSON.stringify({ access_token: 'fake-access', expires_in: 3600 }), { status: 200 }); + if (url.startsWith(FS)) return fs.handle(url, opts); + if (url.startsWith('https://api.stripe.com/')) return st.handle(url, opts); + throw new Error('test tried to reach a real address: ' + url); + }; + f.log = log; + return f; +} + +// A Stripe-Signature header for raw, signed with secret (the webhook's own check, in reverse). +export async function stripeSig(raw, secret, t) { + t = t || Math.floor(Date.now() / 1000); + const key = await wc.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); + const sig = Buffer.from(await wc.subtle.sign('HMAC', key, enc.encode(t + '.' + raw))).toString('hex'); + return 't=' + t + ',v1=' + sig; +} + +// Firestore fields -> plain values (the same as functions/_wallet.js's decFields, kept separate so a bug there shows). +export function plain(fields) { + const d = (v) => 'integerValue' in v ? Number(v.integerValue) : 'stringValue' in v ? v.stringValue : 'booleanValue' in v ? v.booleanValue + : 'nullValue' in v ? null : 'arrayValue' in v ? (v.arrayValue.values || []).map(d) : 'mapValue' in v ? plain(v.mapValue.fields || {}) : v; + const o = {}; for (const k of Object.keys(fields || {})) o[k] = d(fields[k]); return o; +} diff --git a/e63334287a3deaa3/shop/tests/server.test.mjs b/e63334287a3deaa3/shop/tests/server.test.mjs new file mode 100644 index 00000000..204264ca --- /dev/null +++ b/e63334287a3deaa3/shop/tests/server.test.mjs @@ -0,0 +1,300 @@ +// The shop's server side (functions/), run in node with fetch faked (tests/fakes.mjs): no real Stripe, Firestore or +// Google is ever called. Run from the repo root: node e63334287a3deaa3/shop/tests/server.test.mjs +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { makeKeys, fakeFirestore, fakeStripe, fakeFetch, stripeSig, plain } from './fakes.mjs'; +import { CATALOG, roll, cryptoNext, encFields } from '../../../functions/_wallet.js'; +import { OWNERS } from '../../../functions/_captains.js'; +import * as checkout from '../../../functions/api/checkout.js'; +import * as webhook from '../../../functions/api/stripe-webhook.js'; +import * as owned from '../../../functions/api/owned.js'; +import * as wallet from '../../../functions/api/wallet/index.js'; +import * as buy from '../../../functions/api/wallet/buy.js'; +import * as chest from '../../../functions/api/wallet/chest.js'; +import * as gift from '../../../functions/api/wallet/gift.js'; +import * as seen from '../../../functions/api/wallet/seen.js'; + +const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..'); +const keys = await makeKeys(); +const FAKE_SK = 'sk_' + 'test_' + 'not-a-real-key', FAKE_WH = 'wh' + 'sec_' + 'not-a-real-secret'; +const env = { STRIPE_SECRET_KEY: FAKE_SK, STRIPE_WEBHOOK_SECRET: FAKE_WH, FIREBASE_SERVICE_ACCOUNT: keys.serviceAccount }; +const PRICES = {}; +Object.entries(CATALOG.EMERALDS).forEach(([k, e]) => { PRICES[k] = { id: 'price_' + k, unit_amount: e.cents, currency: 'usd', type: 'one_time', lookup_key: k }; }); +PRICES.boostball_flame = { id: 'price_bf', unit_amount: 299, currency: 'usd', type: 'one_time' }; +let W; // this test's world: { fs, st } +function world() { W = { fs: fakeFirestore(), st: fakeStripe(JSON.parse(JSON.stringify(PRICES))) }; return W; } +const realFetch = globalThis.fetch; +globalThis.fetch = (u, o) => fakeFetch(keys, W.fs, W.st)(u, o); + +const ALICE = 'aliceAAAAAAAAAAAAAAAAAAAAAA1', BOB = 'bobBBBBBBBBBBBBBBBBBBBBBBBB2', CAP = OWNERS[0]; +async function call(mod, method, p, opts) { + opts = opts || {}; + const h = { Origin: 'https://ascoding11.github.io' }; + if (opts.as) h.Authorization = 'Bearer ' + await keys.token(opts.as, opts.provider); + if (opts.body !== undefined) h['Content-Type'] = 'application/json'; + const request = new Request('https://ascoding11.com/api/' + p, { method, headers: h, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined }); + const fn = method === 'GET' ? mod.onRequestGet : mod.onRequestPost; + const r = await fn({ request, env: opts.env || env }); + return { status: r.status, data: await r.json() }; +} +function seed(uid, w) { W.fs.docs.set('wallets/' + uid, { fields: encFields(Object.assign({ balance: 0, owned: {}, recent: [], notices: [], reqs: {}, created: 1, updated: 1 }, w)), v: 1 }); } +const doc = (p) => { const d = W.fs.docs.get(p); return d ? plain(d.fields) : null; }; +const bal = (uid) => doc('wallets/' + uid).balance; +const ledger = (uid) => [...W.fs.docs.entries()].filter(([k, d]) => k.startsWith('ledger/') && plain(d.fields).uid === uid).map(([, d]) => plain(d.fields)); +async function event(s, type, secret) { + const raw = JSON.stringify({ id: 'evt_' + Math.random().toString(36).slice(2), type: type || 'checkout.session.completed', created: Math.floor(Date.now() / 1000), data: { object: s } }); + const request = new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': await stripeSig(raw, secret || FAKE_WH) }, body: raw }); + const r = await webhook.onRequestPost({ request, env }); + return { status: r.status, data: await r.json() }; +} +const session = (o) => Object.assign({ id: 'cs_test_a1', mode: 'payment', payment_status: 'paid', amount_total: 99, currency: 'usd', client_reference_id: ALICE, + metadata: { uid: ALICE, sku: 'emeralds_7', kind: 'emeralds' }, customer_details: { email: 'a@example.invalid' } }, o || {}); + +let passed = 0; +const tests = []; +const test = (name, fn) => tests.push([name, fn]); +const ITEM_RARE = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][0] === 'rare' && CATALOG.ITEMS[id][1] === 's'); +const ITEM_RARE2 = Object.keys(CATALOG.ITEMS).filter(id => CATALOG.ITEMS[id][0] === 'rare' && CATALOG.ITEMS[id][1] === 's')[1]; +const ITEM_COMMON = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][0] === 'common' && CATALOG.ITEMS[id][1] === 'a'); +const SKINS = Object.keys(CATALOG.ITEMS).filter(id => CATALOG.ITEMS[id][1] === 's'); + +// ---------- Emeralds: checkout and webhook ---------- +test('webhook credits 7 emeralds once for a repeated and a concurrent event', async () => { + world(); CATALOG.PUBLIC = false; + const a = await event(session()); + assert.equal(a.status, 200); assert.equal(a.data.credited, 7 * 17); + const b = await event(session()); + assert.equal(b.status, 200); assert.equal(b.data.already, true); + const [c, d] = await Promise.all([event(session({ id: 'cs_test_a2' })), event(session({ id: 'cs_test_a2' }))]); + assert.equal([c, d].filter(x => x.data.credited).length, 1, 'exactly one of two concurrent deliveries credits'); + assert.equal(bal(ALICE), 2 * 7 * 17); + assert.equal(ledger(ALICE).filter(l => l.kind === 'emeralds').length, 2); + assert.equal(doc('orders/cs_test_a1').status, 'credited'); assert.equal(doc('orders/cs_test_a1').mangos, 119); +}); +test('every pack credits its own count from the server table, ignoring a forged count in metadata', async () => { + world(); + let n = 0, total = 0; + for (const [sku, e] of Object.entries(CATALOG.EMERALDS)) { + const r = await event(session({ id: 'cs_test_p' + (++n), amount_total: e.cents, metadata: { uid: ALICE, sku, kind: 'emeralds', emeralds: '999999' } })); + assert.equal(r.data.credited, e.emeralds * 17, sku); total += e.emeralds * 17; + } + assert.deepEqual(Object.values(CATALOG.EMERALDS).map(e => [e.emeralds, e.cents]), [[7, 99], [39, 499], [80, 999], [180, 1999], [1000, 4999], [4000, 9999]]); + assert.equal(bal(ALICE), total); +}); +test('webhook refuses a bad signature and writes nothing', async () => { + world(); + const r = await event(session(), null, 'wh' + 'sec_' + 'wrong'); + assert.equal(r.status, 400); assert.equal(W.fs.writes, 0); +}); +test('webhook refuses a mismatched amount or currency: nothing credited, order marked', async () => { + world(); + const r = await event(session({ amount_total: 1 })); + assert.equal(r.status, 200); assert.equal(r.data.refused, 'amount'); + assert.equal(doc('wallets/' + ALICE), null); assert.equal(doc('orders/cs_test_a1').status, 'mismatch'); + const r2 = await event(session({ id: 'cs_test_eur', currency: 'eur' })); + assert.equal(r2.data.refused, 'amount'); assert.equal(doc('wallets/' + ALICE), null); + const r3 = await event(session({ payment_status: 'unpaid', id: 'cs_test_unpaid' })); + assert.equal(r3.status, 200); assert.equal(doc('orders/cs_test_unpaid'), null); +}); +test('emerald checkout: consumable, captains only while closed, price checked, session id in the return address', async () => { + world(); CATALOG.PUBLIC = false; + const back = 'https://ascoding11.github.io/e63334287a3deaa3/shop/'; + const shut = await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'emeralds_7', back } }); + assert.equal(shut.status, 403); + const a = await call(checkout, 'POST', 'checkout', { as: CAP, body: { sku: 'emeralds_7', back } }); + assert.equal(a.status, 200); assert.match(a.data.url, /^https:\/\/checkout\.stripe\.com\//); + const b = await call(checkout, 'POST', 'checkout', { as: CAP, body: { sku: 'emeralds_7', back } }); + assert.equal(b.status, 200, 'a second pack is not "already owned"'); + const p = W.st.sessions[0].params; + assert.equal(p['metadata[sku]'], 'emeralds_7'); assert.equal(p['metadata[uid]'], CAP); assert.equal(p['metadata[kind]'], 'emeralds'); + assert.ok(p.success_url.endsWith('&session={CHECKOUT_SESSION_ID}')); assert.ok(p.success_url.includes('purchase=success')); + W.st.prices.emeralds_80.unit_amount = 899; + const c = await call(checkout, 'POST', 'checkout', { as: CAP, body: { sku: 'emeralds_80', back } }); + assert.equal(c.status, 409); assert.equal(W.st.sessions.length, 2); + W.st.prices.emeralds_80.unit_amount = 999; W.st.prices.emeralds_80.currency = 'gbp'; + assert.equal((await call(checkout, 'POST', 'checkout', { as: CAP, body: { sku: 'emeralds_80', back } })).status, 409); + CATALOG.PUBLIC = true; + assert.equal((await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'emeralds_39', back } })).status, 200); + assert.equal((await call(checkout, 'POST', 'checkout', { body: { sku: 'emeralds_39', back } })).status, 401); + assert.equal((await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'emeralds_39', back: 'https://evil.example/' } })).status, 400); + CATALOG.PUBLIC = false; +}); + +// ---------- The existing item shop, unchanged ---------- +test('item shop: checkout, webhook grant, owned, already-owned refusal', async () => { + world(); + const back = 'https://ascoding11.com/boostball/'; + const a = await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'boostball_flame', back } }); + assert.equal(a.status, 200); + const p = W.st.sessions[0].params; + assert.equal(p['metadata[sku]'], 'boostball_flame'); assert.equal(p['metadata[kind]'], undefined); + assert.equal(p.success_url, 'https://ascoding11.com/boostball/?purchase=success&sku=boostball_flame'); + assert.equal((await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'nope_missing', back } })).status, 404); + const r = await event(session({ id: 'cs_test_item', amount_total: 299, metadata: { uid: ALICE, sku: 'boostball_flame' } })); + assert.equal(r.status, 200); + assert.ok(doc('entitlements/' + ALICE).items.boostball_flame > 0); assert.equal(doc('orders/cs_test_item').sku, 'boostball_flame'); + const o = await call(owned, 'GET', 'owned', { as: ALICE }); + assert.deepEqual(Object.keys(o.data.items), ['boostball_flame']); + const again = await call(checkout, 'POST', 'checkout', { as: ALICE, body: { sku: 'boostball_flame', back } }); + assert.equal(again.status, 409); assert.equal(again.data.owned, true); + assert.equal(doc('wallets/' + ALICE), null, 'an item purchase never touches the wallet'); +}); + +// ---------- The wallet endpoints ---------- +test('sign-in: none, anonymous, and a non-captain while closed are refused', async () => { + world(); CATALOG.PUBLIC = false; + assert.equal((await call(wallet, 'GET', 'wallet')).status, 401); + assert.equal((await call(wallet, 'GET', 'wallet', { as: ALICE, provider: 'anonymous' })).status, 401); + const c = await call(wallet, 'GET', 'wallet', { as: ALICE }); + assert.equal(c.status, 403); assert.equal(c.data.reason, 'closed'); + assert.equal((await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE } })).status, 403); + const g = await call(wallet, 'GET', 'wallet', { as: CAP }); + assert.equal(g.status, 200); assert.equal(g.data.captain, true); assert.equal(g.data.test, true); + assert.ok(!JSON.stringify(g.data).includes(FAKE_SK.slice(8)), 'the key is never sent'); + const live = await call(wallet, 'GET', 'wallet', { as: CAP, env: Object.assign({}, env, { STRIPE_SECRET_KEY: 'sk_' + 'live_' + 'not-real' }) }); + assert.equal(live.data.test, false); +}); +test('buy: exact debit, ownership, already owned, insufficient balance', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 500 }); + const a = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE, req: 'req00000001' } }); + assert.equal(a.status, 200); assert.equal(a.data.spent, 420); assert.equal(a.data.balance, 80); + assert.equal(bal(ALICE), 80); assert.ok(doc('wallets/' + ALICE).owned[ITEM_RARE]); + assert.ok(a.data.state.owned.includes(ITEM_RARE)); + const dup = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_COMMON, req: 'req00000001' } }); + assert.equal(dup.status, 409); assert.equal(dup.data.reason, 'duplicate'); assert.equal(bal(ALICE), 80); + const own = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE } }); + assert.equal(own.status, 409); assert.equal(own.data.reason, 'owned'); + const poor = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE2 } }); + assert.equal(poor.status, 402); assert.equal(poor.data.need, 340); assert.equal(bal(ALICE), 80); + const c = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_COMMON } }); + assert.equal(c.data.spent, 60); assert.equal(bal(ALICE), 20); + assert.equal((await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'emeralds-7' } })).data.reason, 'money'); + assert.equal((await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:nope' } })).status, 400); + const free = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][3]); + assert.equal((await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + free } })).status, 400, 'a give item is not sold'); + const l = ledger(ALICE).sort((x, y) => x.b - y.b); + assert.deepEqual(l.map(x => x.d).sort((x, y) => x - y), [-420, -60]); +}); +test('pack: costs the sum of its items, duplicates refunded 48 each', async () => { + world(); CATALOG.PUBLIC = true; + const p = CATALOG.PACKS['skins-animals']; + const sum = p.contents.items.reduce((t, id) => t + CATALOG.PRICE[CATALOG.ITEMS[id][0]], 0); + assert.equal(p.price, sum); + const ownedOne = {}; ownedOne[p.contents.items[0]] = 1; + seed(ALICE, { balance: 5000, owned: ownedOne }); + const r = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'skins-animals' } }); + assert.equal(r.status, 200); assert.equal(r.data.spent, sum); assert.equal(r.data.refund, 48); + assert.equal(bal(ALICE), 5000 - sum + 48); + assert.equal(r.data.got.skins.length, p.contents.items.length - 1); +}); +test('two concurrent buys cannot overspend', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 500 }); + const rs = await Promise.all([ITEM_RARE, ITEM_RARE2].map(id => call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + id } }))); + assert.deepEqual(rs.map(r => r.status).sort(), [200, 402]); + assert.equal(bal(ALICE), 80); assert.ok(W.fs.aborts >= 1, 'the race really happened (a transaction was retried)'); + // ten chests bought at once with money for five + seed(BOB, { balance: 5 * 119 }); + const many = await Promise.all(Array.from({ length: 10 }, () => call(chest, 'POST', 'wallet/chest', { as: BOB, body: { n: 1 } }))); + const ok = many.filter(r => r.status === 200); + const refunds = ok.reduce((t, r) => t + r.data.refund, 0); + assert.ok(ok.length >= 5, 'at least the five paid for'); + assert.equal(bal(BOB), 5 * 119 - ok.length * 119 + refunds); + assert.ok(bal(BOB) >= 0); +}); +test('chest: exact debit, server roll, duplicate refund; bad counts refused', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 10000 }); + const r = await call(chest, 'POST', 'wallet/chest', { as: ALICE, body: { n: 5 } }); + assert.equal(r.status, 200); assert.equal(r.data.spent, 595); assert.equal(r.data.got.draws.length, 5); + const dups = r.data.got.draws.filter(d => d.dup).length; + assert.equal(r.data.refund, dups * 48); assert.equal(bal(ALICE), 10000 - 595 + dups * 48); + r.data.got.draws.forEach(d => { assert.ok(SKINS.includes(d.skin)); assert.equal(CATALOG.ITEMS[d.skin][0], d.rarity); assert.ok(doc('wallets/' + ALICE).owned[d.skin]); }); + const all = {}; SKINS.forEach(id => { all[id] = 1; }); + seed(BOB, { balance: 1190, owned: all }); + const b = await call(chest, 'POST', 'wallet/chest', { as: BOB, body: { n: 10 } }); + assert.equal(b.data.spent, 1190); assert.equal(b.data.refund, 480); assert.equal(bal(BOB), 480); + assert.equal((await call(chest, 'POST', 'wallet/chest', { as: BOB, body: { n: 3 } })).status, 400); + assert.equal((await call(chest, 'POST', 'wallet/chest', { as: BOB, body: { n: 10 } })).status, 402); +}); +test('captain: never charged, never refunded, owns everything, gifts free', async () => { + world(); CATALOG.PUBLIC = false; + seed(CAP, { balance: 7 }); + const c = await call(chest, 'POST', 'wallet/chest', { as: CAP, body: { n: 10 } }); + assert.equal(c.status, 200); assert.equal(c.data.spent, 0); assert.equal(c.data.refund, 0); assert.equal(bal(CAP), 7); + const i = await call(buy, 'POST', 'wallet/buy', { as: CAP, body: { what: 'item:' + ITEM_RARE } }); + assert.equal(i.status, 409); assert.equal(i.data.reason, 'owned'); assert.equal(bal(CAP), 7); + seed(BOB, { balance: 0 }); + const g = await call(gift, 'POST', 'wallet/gift', { as: CAP, body: { what: 'item:' + ITEM_RARE, to: BOB, toName: 'Bob', fromName: 'Cap' } }); + assert.equal(g.status, 200); assert.equal(g.data.spent, 0); assert.equal(bal(CAP), 7); assert.ok(doc('wallets/' + BOB).owned[ITEM_RARE]); + CATALOG.PUBLIC = true; + seed(ALICE, { balance: 5000 }); + const toCap = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE2, to: CAP } }); + assert.equal(toCap.status, 409); assert.equal(toCap.data.reason, 'captain'); assert.equal(bal(ALICE), 5000); +}); +test('gift: sender pays, recipient owns it and gets a notice; refusals; seen clears notices', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 1000 }); + const nobody = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE, to: BOB } }); + assert.equal(nobody.status, 404); assert.equal(nobody.data.reason, 'recipient'); assert.equal(bal(ALICE), 1000); + await call(wallet, 'GET', 'wallet', { as: BOB }); // Bob opens the shop once: his wallet now exists + assert.equal(bal(BOB), 0); + const note = 'Happy birthday! '.repeat(6); + const g = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE, to: BOB, toName: 'Bob', fromName: 'Alice ', note, req: 'giftreq0001' } }); + assert.equal(g.status, 200); assert.equal(g.data.spent, 420); assert.equal(bal(ALICE), 580); + const bw = doc('wallets/' + BOB); + assert.ok(bw.owned[ITEM_RARE]); assert.equal(bw.balance, 0); + assert.equal(bw.notices.length, 1); assert.equal(bw.notices[0].from, 'Alice b'); assert.equal(bw.notices[0].note.length, 60); + const again = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE, to: BOB } }); + assert.equal(again.status, 409); assert.equal(again.data.reason, 'owned'); assert.equal(bal(ALICE), 580); + assert.equal((await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE2, to: ALICE } })).data.reason, 'self'); + assert.equal((await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'emeralds-80', to: BOB } })).data.reason, 'money'); + const LEG = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][0] === 'legendary'); + const poor = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + LEG, to: BOB } }); + assert.equal(poor.status, 402); assert.equal(bal(ALICE), 580); assert.ok(!doc('wallets/' + BOB).owned[LEG]); + // a chest as a gift: opened for Bob, his duplicates refunded to him + const all = {}; SKINS.forEach(id => { all[id] = 1; }); seed(BOB, { balance: 0, owned: all }); + const ch = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'draw-1', to: BOB, fromName: 'Alice' } }); + assert.equal(ch.status, 200); assert.equal(ch.data.spent, 119); assert.equal(bal(ALICE), 461); assert.equal(bal(BOB), 48); + const st = await call(wallet, 'GET', 'wallet', { as: BOB }); + assert.equal(st.data.notices.length, 1); assert.equal(st.data.notices[0].got.draws.length, 1); + const s = await call(seen, 'POST', 'wallet/seen', { as: BOB, body: { ids: [st.data.notices[0].id] } }); + assert.equal(s.data.notices.length, 0); + assert.ok(st.data.recent.some(l => l[1] === 48 && /Gift from Alice/.test(l[3]))); +}); +test('chest odds over 1,000,000 server rolls are within 0.2 points', async () => { + const next = cryptoNext(), n = 1000000, c = {}; + for (let i = 0; i < n; i++) { const r = roll(next); c[r.rarity] = (c[r.rarity] || 0) + 1; } + const want = { common: 60, uncommon: 20, rare: 12.5, epic: 5, legendary: 2.5 }; + for (const k of Object.keys(want)) assert.ok(Math.abs(c[k] * 100 / n - want[k]) < 0.2, k + ' ' + (c[k] * 100 / n).toFixed(3) + '%'); + console.log(' odds: ' + Object.keys(want).map(k => k + ' ' + (c[k] * 100 / n).toFixed(2) + '%').join(', ')); +}); +test('catalogue check: passes in sync, fails when cosmetics.js, wallet.js, miles.js or the generated file changes', async () => { + execFileSync('node', [path.join(ROOT, 'e63334287a3deaa3/shop/tools/server-data.js'), '--check'], { stdio: 'pipe' }); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wallet-check-')); + const copy = (f) => { fs.mkdirSync(path.dirname(path.join(tmp, f)), { recursive: true }); fs.copyFileSync(path.join(ROOT, f), path.join(tmp, f)); }; + ['e63334287a3deaa3/cosmetics.js', 'e63334287a3deaa3/wallet.js', 'e63334287a3deaa3/miles.js', 'e63334287a3deaa3/shop/tools/server-data.js', 'functions/_catalog.js', 'functions/_captains.js'].forEach(copy); + const run = () => { try { execFileSync('node', [path.join(tmp, 'e63334287a3deaa3/shop/tools/server-data.js'), '--check'], { stdio: 'pipe' }); return true; } catch (e) { return false; } }; + assert.equal(run(), true); + const edits = [['e63334287a3deaa3/cosmetics.js', 'common: 60,', 'common: 61,'], ['e63334287a3deaa3/wallet.js', 'emeralds: 39, usd: 4.99', 'emeralds: 40, usd: 4.99'], + ['e63334287a3deaa3/wallet.js', 'enabled: false,', 'enabled: true,'], ['e63334287a3deaa3/miles.js', "'6QQvFAzdtMeJdAUSPwHd6v2zaDk1',", "'6QQvFAzdtMeJdAUSPwHd6v2zaDk1', 'someoneElse12345',"], + ['functions/_catalog.js', '"CHEST_PRICE": 119', '"CHEST_PRICE": 1']]; + for (const [f, a, b] of edits) { + const p = path.join(tmp, f), was = fs.readFileSync(p, 'utf8'); + assert.ok(was.includes(a), f + ' has ' + a); + fs.writeFileSync(p, was.replace(a, b)); + assert.equal(run(), false, 'check fails after editing ' + f); + fs.writeFileSync(p, was); + assert.equal(run(), true); + } + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +for (const [name, fn] of tests) { + try { await fn(); passed++; console.log('ok ' + name); } + catch (e) { console.log('FAIL ' + name + '\n ' + (e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); process.exitCode = 1; } +} +globalThis.fetch = realFetch; +console.log(passed + '/' + tests.length + ' passed'); diff --git a/e63334287a3deaa3/shop/tools/server-data.js b/e63334287a3deaa3/shop/tools/server-data.js index 664bde90..e4bd681b 100644 --- a/e63334287a3deaa3/shop/tools/server-data.js +++ b/e63334287a3deaa3/shop/tools/server-data.js @@ -42,14 +42,15 @@ function build() { const C = ctx.BackRoomCosmetics, W = ctx.BackRoomWallet; if (!C || !W) throw new Error('cosmetics.js or wallet.js did not load'); const items = {}; - const add = (id, rarity, kind, give) => { + // ITEMS: { id: [rarity, kind ('s' skin, 'a' accessory, 'g' game item), name, give ('free' / 'earned': never sold)] } + const add = (id, rarity, kind, name, give) => { if (items[id]) throw new Error('two items share the id ' + id + ' (the server keeps one owned list for all of them)'); if (!C.PRICE[rarity]) throw new Error(id + ': unknown rarity ' + rarity); - items[id] = give ? [rarity, kind, give] : [rarity, kind]; + items[id] = give ? [rarity, kind, name, give] : [rarity, kind, name]; }; - C.SKINS.forEach(s => add(s.id, s.rarity, 's')); - C.ACCESSORIES.forEach(a => add(a.id, a.rarity, 'a')); - C.GAME_ITEMS.forEach(g => add(g.id, g.rarity, 'g', g.give || '')); + C.SKINS.forEach(s => add(s.id, s.rarity, 's', s.name)); + C.ACCESSORIES.forEach(a => add(a.id, a.rarity, 'a', a.name)); + C.GAME_ITEMS.forEach(g => add(g.id, g.rarity, 'g', g.name, g.give || '')); const packs = {}; C.PACKS.forEach(p => { const c = {}; diff --git a/functions/_catalog.js b/functions/_catalog.js index e69d4d9d..e1f20361 100644 --- a/functions/_catalog.js +++ b/functions/_catalog.js @@ -1,3 +1,3 @@ // GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing cosmetics.js // or wallet.js, and commit this file; its --check fails while the two disagree. Read by functions/_wallet.js. -export const CATALOG = {"PUBLIC": false, "MANGOS_PER_EMERALD": 17, "PRICE": {"common": 60, "uncommon": 119, "rare": 420, "epic": 600, "legendary": 1200 }, "CHEST_PRICE": 119, "DUP_REFUND": 48, "RARITY": [ {"id": "legendary", "name": "Legendary", "w": 250 }, {"id": "epic", "name": "Epic", "w": 500 }, {"id": "rare", "name": "Rare", "w": 1250 }, {"id": "uncommon", "name": "Uncommon", "w": 2000 }, {"id": "common", "name": "Common", "w": 6000 } ], "RARITY_TOTAL": 10000, "NOTE_MAX": 60, "ITEMS": {"moon-walker": [ "common", "s" ], "tide-pool": [ "common", "s" ], "neon-jogger": [ "common", "s" ], "bubblegum": [ "common", "s" ], "sprinkle-pop": [ "common", "s" ], "tin-tinker": [ "common", "s" ], "tabby": [ "common", "s" ], "cub": [ "common", "s" ], "hopper": [ "common", "s" ], "spring-sprout": [ "common", "s" ], "summer-sun": [ "common", "s" ], "dune-rover": [ "common", "s" ], "comet-courier": [ "uncommon", "s" ], "coral-diver": [ "uncommon", "s" ], "grid-runner": [ "uncommon", "s" ], "gumdrop-knight": [ "uncommon", "s" ], "circuit-scout": [ "rare", "s" ], "red-fox": [ "rare", "s" ], "autumn-ember": [ "rare", "s" ], "winter-frost": [ "rare", "s" ], "magma-walker": [ "rare", "s" ], "nebula-drifter": [ "epic", "s" ], "abyss-lantern": [ "epic", "s" ], "synthwave": [ "epic", "s" ], "rock-candy": [ "epic", "s" ], "chrome-unit": [ "epic", "s" ], "storm-drake": [ "epic", "s" ], "star-sovereign": [ "legendary", "s" ], "golden-automaton": [ "legendary", "s" ], "four-seasons": [ "legendary", "s" ], "pom-beanie": [ "common", "a" ], "wizard-cone": [ "uncommon", "a" ], "propeller-cap": [ "common", "a" ], "tall-topper": [ "rare", "a" ], "daisy-crown": [ "common", "a" ], "star-shades": [ "uncommon", "a" ], "heart-specs": [ "common", "a" ], "monocle": [ "rare", "a" ], "glow-visor": [ "epic", "a" ], "hero-cape": [ "common", "a" ], "galaxy-cape": [ "epic", "a" ], "leaf-cloak": [ "uncommon", "a" ], "sparkle-trail": [ "uncommon", "a" ], "bubble-trail": [ "common", "a" ], "rainbow-streak": [ "epic", "a" ], "halo-glow": [ "uncommon", "a" ], "ember-aura": [ "epic", "a" ], "frost-ring": [ "rare", "a" ], "pocket-slime": [ "common", "a" ], "mini-bot": [ "uncommon", "a" ], "star-buddy": [ "common", "a" ], "ghost-pup": [ "epic", "a" ], "baby-drake": [ "legendary", "a" ], "bb-decal-flames": [ "common", "g" ], "bb-decal-racing-stripes": [ "common", "g" ], "bb-decal-lightning-bolts": [ "common", "g" ], "bb-decal-checkered-flag": [ "common", "g" ], "bb-decal-shark-mouth": [ "uncommon", "g" ], "bb-decal-tiger-stripes": [ "uncommon", "g" ], "bb-decal-dragon-scales": [ "uncommon", "g" ], "bb-decal-carbon-fiber": [ "common", "g" ], "bb-decal-pixel-camo": [ "common", "g" ], "bb-decal-galaxy": [ "epic", "g" ], "bb-decal-constellations": [ "uncommon", "g" ], "bb-decal-circuit-board": [ "uncommon", "g" ], "bb-decal-graffiti-drips": [ "uncommon", "g" ], "bb-decal-honeycomb": [ "common", "g" ], "bb-decal-lava-cracks": [ "epic", "g" ], "bb-decal-frost": [ "uncommon", "g" ], "bb-decal-comic-book-dots": [ "common", "g" ], "bb-decal-topographic-lines": [ "common", "g" ], "bb-decal-stained-glass": [ "epic", "g" ], "bb-decal-wireframe": [ "rare", "g" ], "bb-decal-skeleton-ribs": [ "rare", "g" ], "bb-decal-duct-tape-patches": [ "common", "g" ], "bb-decal-rust-bucket": [ "common", "g" ], "bb-decal-wood-paneling": [ "rare", "g" ], "bb-decal-cow-print": [ "common", "g" ], "bb-decal-donut-sprinkles": [ "rare", "g" ], "bb-decal-bubble-wrap": [ "common", "g" ], "bb-decal-taxi": [ "rare", "g" ], "bb-decal-police-cruiser": [ "rare", "g" ], "bb-decal-ice-cream-truck": [ "epic", "g" ], "bb-decal-autumn-leaves": [ "common", "g" ], "bb-trail-classic-flame": [ "common", "g" ], "bb-trail-blue-plasma": [ "common", "g" ], "bb-trail-rainbow": [ "epic", "g" ], "bb-trail-lightning": [ "uncommon", "g" ], "bb-trail-bubbles": [ "common", "g" ], "bb-trail-confetti": [ "common", "g" ], "bb-trail-snowflakes": [ "common", "g" ], "bb-trail-autumn-leaves": [ "common", "g" ], "bb-trail-sparkles": [ "uncommon", "g" ], "bb-trail-hearts": [ "uncommon", "g" ], "bb-trail-music-notes": [ "uncommon", "g" ], "bb-trail-pixel-blocks": [ "common", "g" ], "bb-trail-smoke-rings": [ "uncommon", "g" ], "bb-trail-slime": [ "common", "g" ], "bb-trail-lava": [ "rare", "g" ], "bb-trail-stardust": [ "epic", "g" ], "bb-trail-popcorn": [ "rare", "g" ], "bb-trail-rubber-ducks": [ "epic", "g" ], "bb-trail-feathers": [ "common", "g" ], "bb-trail-soap-suds": [ "common", "g" ], "bb-trail-ink": [ "rare", "g" ], "bb-trail-ones-and-zeros": [ "rare", "g" ], "bb-trail-bats": [ "rare", "g" ], "bb-trail-toast-slices": [ "epic", "g" ], "bb-trail-dollar-bills": [ "epic", "g" ], "bb-trail-water-jet": [ "common", "g" ], "bb-trail-laser-beam": [ "legendary", "g" ], "bb-goal-fireworks": [ "uncommon", "g" ], "bb-goal-confetti-cannon": [ "uncommon", "g" ], "bb-goal-black-hole": [ "epic", "g" ], "bb-goal-supernova": [ "epic", "g" ], "bb-goal-lightning-strike": [ "uncommon", "g" ], "bb-goal-tornado": [ "epic", "g" ], "bb-goal-volcano": [ "epic", "g" ], "bb-goal-meteor": [ "epic", "g" ], "bb-goal-freeze-and-shatter": [ "uncommon", "g" ], "bb-goal-pixel-shatter": [ "rare", "g" ], "bb-goal-disco-ball-drop": [ "epic", "g" ], "bb-goal-giant-foot-stomp": [ "legendary", "g" ], "bb-goal-pinata-burst": [ "epic", "g" ], "bb-goal-popcorn-pop": [ "rare", "g" ], "bb-goal-ufo-abduction": [ "legendary", "g" ], "bb-goal-shark-attack": [ "legendary", "g" ], "bb-goal-giant-airhorn": [ "epic", "g" ], "bb-goal-money-rain": [ "epic", "g" ], "bb-goal-pumpkin-splat": [ "rare", "g" ], "bb-goal-goal-letters": [ "legendary", "g" ], "bb-goal-flock-of-birds": [ "epic", "g" ], "bb-topper-tennis-ball": [ "common", "g" ], "bb-topper-gold-star": [ "uncommon", "g" ], "bb-topper-bath-duck": [ "rare", "g" ], "bb-topper-mini-pumpkin": [ "common", "g" ], "bb-topper-pennant": [ "common", "g" ], "bb-topper-eyeball": [ "epic", "g" ], "bb-hat-traffic-cone": [ "common", "g" ], "bb-hat-top-hat": [ "uncommon", "g" ], "bb-hat-crown": [ "epic", "g" ], "bb-hat-propeller-beanie": [ "uncommon", "g" ], "bb-hat-cowboy-hat": [ "rare", "g" ], "bb-hat-chef-hat": [ "common", "g" ], "bb-wheels-five-spoke": [ "common", "g" ], "bb-wheels-discs": [ "common", "g" ], "bb-wheels-cross": [ "uncommon", "g" ], "bb-wheels-gold-rims": [ "epic", "g" ], "bb-engine-purr": [ "common", "g" ], "bb-engine-buzz": [ "uncommon", "g" ], "bb-engine-rumble": [ "rare", "g" ], "bb-engine-whirr": [ "epic", "g" ], "ss-sponsor-zoomi-cola": [ "common", "g", "free" ], "ss-sponsor-burnout-coffee": [ "common", "g", "free" ], "ss-sponsor-apex-tires": [ "common", "g", "free" ], "ss-sponsor-turbo-taco": [ "common", "g", "free" ], "ss-sponsor-grandma-s-motor-oil": [ "common", "g", "free" ], "ss-sponsor-pit-stop-pizza": [ "common", "g", "free" ], "ss-sponsor-slick-s-hair-gel": [ "common", "g", "free" ], "ss-sponsor-late-brake-insurance": [ "common", "g", "free" ], "ss-sponsor-draft-punk-records": [ "common", "g", "free" ], "ss-sponsor-gravel-trap-granola": [ "common", "g", "free" ], "ss-sponsor-blue-flag-bottled-water": [ "common", "g", "free" ], "ss-sponsor-honk-energy": [ "common", "g", "free" ], "ss-sponsor-chicane-chicken": [ "common", "g", "free" ], "ss-sponsor-podium-pickles": [ "common", "g", "free" ], "ss-sponsor-lap-nap-mattresses": [ "common", "g", "free" ], "ss-livery-two-tone-classic": [ "common", "g" ], "ss-livery-retro-stripes": [ "common", "g" ], "ss-livery-matte-black-with-neon": [ "uncommon", "g" ], "ss-livery-chrome": [ "epic", "g" ], "ss-livery-carbon": [ "uncommon", "g" ], "ss-livery-pastel": [ "common", "g" ], "ss-livery-flames": [ "rare", "g" ], "ss-livery-checkered": [ "common", "g" ], "ss-livery-zoomi-cola-livery": [ "epic", "g", "earned" ], "ss-livery-burnout-coffee-livery": [ "epic", "g", "earned" ], "ss-livery-apex-tires-livery": [ "epic", "g", "earned" ], "ss-livery-turbo-taco-livery": [ "epic", "g", "earned" ], "ss-livery-grandma-s-motor-oil-livery": [ "epic", "g", "earned" ], "ss-livery-pit-stop-pizza-livery": [ "epic", "g", "earned" ], "ss-livery-slick-s-hair-gel-livery": [ "epic", "g", "earned" ], "ss-livery-late-brake-insurance-livery": [ "epic", "g", "earned" ], "ss-livery-draft-punk-records-livery": [ "epic", "g", "earned" ], "ss-livery-gravel-trap-granola-livery": [ "epic", "g", "earned" ], "ss-livery-blue-flag-bottled-water-livery": [ "epic", "g", "earned" ], "ss-livery-honk-energy-livery": [ "epic", "g", "earned" ], "ss-livery-chicane-chicken-livery": [ "epic", "g", "earned" ], "ss-livery-podium-pickles-livery": [ "epic", "g", "earned" ], "ss-livery-lap-nap-mattresses-livery": [ "epic", "g", "earned" ], "ss-helmet-red-helmet": [ "common", "g", "free" ], "ss-helmet-blue-helmet": [ "common", "g", "free" ], "ss-helmet-yellow-helmet": [ "common", "g", "free" ], "ss-helmet-green-helmet": [ "common", "g", "free" ], "ss-helmet-orange-helmet": [ "common", "g", "free" ], "ss-helmet-pink-helmet": [ "common", "g", "free" ], "ss-helmet-black-helmet": [ "common", "g", "free" ], "ss-helmet-white-helmet": [ "common", "g", "free" ], "ss-helmet-flames-helmet": [ "common", "g" ], "ss-helmet-checkered-helmet": [ "common", "g" ], "ss-helmet-lightning-helmet": [ "common", "g" ], "ss-helmet-chrome-visor": [ "uncommon", "g" ], "ss-helmet-shark-helmet": [ "uncommon", "g" ], "ss-helmet-skull-helmet": [ "uncommon", "g" ], "ss-helmet-tiger-helmet": [ "uncommon", "g" ], "ss-helmet-galaxy-helmet": [ "epic", "g" ], "ss-helmet-disco-ball": [ "legendary", "g" ], "ss-helmet-watermelon-helmet": [ "rare", "g" ], "ss-helmet-eight-ball": [ "rare", "g" ], "ss-helmet-eyeball": [ "epic", "g" ], "ss-helmet-pumpkin-helmet": [ "rare", "g" ], "ss-helmet-cat-ears": [ "epic", "g" ], "ss-helmet-pizza-helmet": [ "epic", "g" ], "ss-effect-white-air-streaks": [ "common", "g" ], "ss-effect-flames": [ "common", "g" ], "ss-effect-sparks": [ "uncommon", "g" ], "ss-effect-electric-arcs": [ "uncommon", "g" ], "ss-effect-rainbow": [ "epic", "g" ], "ss-effect-vapor-trail": [ "common", "g" ], "ss-effect-confetti": [ "rare", "g" ], "ss-effect-purple-plasma": [ "epic", "g" ], "ss-smoke-pink-tyre-smoke": [ "common", "g" ], "ss-smoke-blue-tyre-smoke": [ "common", "g" ], "ss-smoke-green-tyre-smoke": [ "common", "g" ], "ss-smoke-purple-tyre-smoke": [ "common", "g" ], "ss-smoke-gold-tyre-smoke": [ "common", "g" ], "ss-podium-confetti-podium": [ "common", "g" ], "ss-podium-fireworks-podium": [ "uncommon", "g" ], "cl-color-cherry": [ "common", "g" ], "cl-color-tangerine": [ "common", "g" ], "cl-color-lemon": [ "common", "g" ], "cl-color-grass": [ "common", "g" ], "cl-color-aqua": [ "common", "g" ], "cl-color-ocean": [ "common", "g" ], "cl-color-violet": [ "common", "g" ], "cl-color-bubblegum": [ "common", "g" ], "cl-color-snow": [ "common", "g" ], "cl-color-cocoa": [ "common", "g" ], "cl-color-gold": [ "uncommon", "g" ], "cl-color-slate": [ "common", "g" ], "cl-color-neon-green": [ "uncommon", "g" ], "cl-color-neon-pink": [ "uncommon", "g" ], "cl-color-neon-blue": [ "uncommon", "g" ], "cl-color-neon-orange": [ "uncommon", "g" ], "cl-color-neon-yellow": [ "uncommon", "g" ], "cl-color-sunrise": [ "rare", "g" ], "cl-color-deep-sea": [ "rare", "g" ], "cl-color-mint-grape": [ "rare", "g" ], "cl-color-fireball": [ "rare", "g" ], "cl-color-cotton-candy": [ "rare", "g" ], "cl-color-forest": [ "rare", "g" ], "cl-color-rainbow": [ "epic", "g" ], "cl-color-rainbow-flow": [ "epic", "g" ], "cl-animal-python": [ "uncommon", "g" ], "cl-animal-rattlesnake": [ "uncommon", "g" ], "cl-animal-coral-snake": [ "uncommon", "g" ], "cl-animal-tiger": [ "uncommon", "g" ], "cl-animal-zebra": [ "rare", "g" ], "cl-animal-leopard": [ "rare", "g" ], "cl-animal-cow": [ "common", "g" ], "cl-animal-bee": [ "rare", "g" ], "cl-animal-caterpillar": [ "epic", "g" ], "cl-animal-centipede": [ "epic", "g" ], "cl-animal-dragon": [ "legendary", "g" ], "cl-design-stripes": [ "common", "g" ], "cl-design-candy-cane": [ "uncommon", "g" ], "cl-design-barber-pole": [ "uncommon", "g" ], "cl-design-checker": [ "common", "g" ], "cl-design-polka-dots": [ "common", "g" ], "cl-design-zigzag": [ "common", "g" ], "cl-design-galaxy": [ "epic", "g" ], "cl-design-lava": [ "epic", "g" ], "cl-design-ice": [ "rare", "g" ], "cl-design-circuit-board": [ "epic", "g" ], "cl-design-pixel": [ "rare", "g" ], "cl-design-camo": [ "common", "g" ], "cl-object-train-cars": [ "epic", "g" ], "cl-object-sausage-links": [ "uncommon", "g" ], "cl-object-spaghetti-noodle": [ "uncommon", "g" ], "cl-object-gummy-worm": [ "epic", "g" ], "cl-object-licorice": [ "uncommon", "g" ], "cl-object-garden-hose": [ "uncommon", "g" ], "cl-object-rope": [ "common", "g" ], "cl-object-chain": [ "rare", "g" ], "cl-object-measuring-tape": [ "rare", "g" ], "cl-object-pencil": [ "epic", "g" ], "cl-object-twinkling-lights": [ "legendary", "g" ], "cl-object-bead-necklace": [ "rare", "g" ], "cl-object-piano-keys": [ "epic", "g" ], "cl-object-film-strip": [ "epic", "g" ], "cl-object-dominoes": [ "epic", "g" ], "cl-object-scarf": [ "rare", "g" ], "cl-object-skeleton-spine": [ "legendary", "g" ], "cl-head-sunglasses": [ "uncommon", "g" ], "cl-head-crown": [ "epic", "g" ], "cl-head-party-hat": [ "uncommon", "g" ], "cl-head-googly-eyes": [ "rare", "g" ], "cl-head-tongue-out": [ "common", "g" ], "cl-head-tiny-cowboy-hat": [ "rare", "g" ], "cl-trail-sparkle-trail": [ "epic", "g" ], "cl-burst-candy-burst": [ "epic", "g" ], "cl-burst-coin-burst": [ "legendary", "g" ], "up-skin-jungle-explorer": [ "common", "g" ], "up-skin-mountaineer": [ "common", "g" ], "up-skin-arctic-explorer": [ "common", "g" ], "up-skin-safari-guide": [ "common", "g" ], "up-skin-deep-sea-diver": [ "uncommon", "g" ], "up-skin-aviator": [ "uncommon", "g" ], "up-skin-cave-explorer": [ "common", "g" ], "up-skin-treasure-hunter": [ "uncommon", "g" ], "up-skin-dusty-archaeologist": [ "common", "g" ], "up-skin-storm-chaser": [ "uncommon", "g" ], "up-skin-balloonist": [ "uncommon", "g" ], "up-skin-old-timey-explorer": [ "epic", "g" ], "up-skin-pirate": [ "epic", "g" ], "up-skin-park-ranger": [ "common", "g" ], "up-skin-astronaut": [ "epic", "g" ], "up-skin-tourist": [ "rare", "g" ], "up-skin-pizza-delivery": [ "rare", "g" ], "up-skin-window-washer": [ "rare", "g" ], "up-skin-grandma": [ "epic", "g" ], "up-skin-knight": [ "epic", "g" ], "up-skin-ninja": [ "rare", "g" ], "up-skin-chicken-suit": [ "legendary", "g" ], "up-pack-parachute-pack": [ "common", "g" ], "up-pack-teddy-bear": [ "uncommon", "g" ], "up-pack-picnic-basket": [ "common", "g" ], "up-pack-giant-sandwich": [ "rare", "g" ], "up-pack-fake-jetpack": [ "epic", "g" ], "up-pack-rolled-up-tent": [ "common", "g" ], "up-reward-1-000-m-badge": [ "uncommon", "g", "earned" ], "up-reward-space-helmet": [ "epic", "g", "earned" ], "up-reward-golden-crown": [ "legendary", "g", "earned" ], "up-scream-aaaah": [ "common", "g" ], "up-scream-yodel": [ "uncommon", "g" ], "up-scream-slide-whistle": [ "common", "g" ], "up-scream-opera-note": [ "epic", "g" ], "up-scream-wheee": [ "common", "g" ], "up-trail-rainbow-streamer": [ "uncommon", "g" ], "up-trail-comet-tail": [ "rare", "g" ], "up-trail-smoke-trail": [ "common", "g" ], "up-trail-gold-sparkles": [ "epic", "g" ], "rk-driver-sir-honksalot": [ "epic", "g" ], "rk-driver-captain-crumb": [ "uncommon", "g" ], "rk-driver-granny-vroom": [ "uncommon", "g" ], "rk-driver-bolt": [ "common", "g" ], "rk-driver-wasabi": [ "uncommon", "g" ], "rk-driver-professor-pickle": [ "common", "g" ], "rk-driver-dj-raccoon": [ "epic", "g" ], "rk-driver-chef-meatball": [ "common", "g" ], "rk-driver-yeti-betty": [ "uncommon", "g" ], "rk-driver-count-dracoola": [ "epic", "g" ], "rk-driver-tiny-rex": [ "legendary", "g" ], "rk-driver-sergeant-sprinkles": [ "rare", "g" ], "rk-driver-moolissa": [ "common", "g" ], "rk-driver-astro-hamster": [ "epic", "g" ], "rk-driver-cactus-jack": [ "rare", "g" ], "rk-driver-waddles": [ "rare", "g" ], "rk-driver-turkey-tom": [ "common", "g" ], "rk-kart-bathtub": [ "uncommon", "g" ], "rk-kart-shopping-cart": [ "common", "g" ], "rk-kart-lawnmower": [ "common", "g" ], "rk-kart-hot-dog-cart": [ "uncommon", "g" ], "rk-kart-bumper-car": [ "common", "g" ], "rk-kart-giant-shoe": [ "uncommon", "g" ], "rk-kart-banana": [ "epic", "g" ], "rk-kart-rubber-duck": [ "epic", "g" ], "rk-kart-couch": [ "rare", "g" ], "rk-kart-bed": [ "rare", "g" ], "rk-kart-toilet": [ "rare", "g" ], "rk-kart-pumpkin-carriage": [ "legendary", "g" ], "rk-kart-ice-cream-truck": [ "epic", "g" ], "rk-kart-rocket-sled": [ "legendary", "g" ], "rk-kart-cardboard-box": [ "common", "g" ], "rk-wheels-chrome-spokes": [ "common", "g" ], "rk-wheels-monster-treads": [ "uncommon", "g" ], "rk-wheels-wagon-wheels": [ "common", "g" ], "rk-wheels-donut-wheels": [ "epic", "g" ], "rk-wheels-whitewalls": [ "common", "g" ], "rk-wheels-golden-stars": [ "uncommon", "g" ], "rk-wheels-peppermint-swirls": [ "rare", "g" ], "rk-wheels-button-wheels": [ "common", "g" ], "rk-horn-goose-honk": [ "uncommon", "g" ], "rk-horn-clown-horn": [ "common", "g" ], "rk-horn-air-horn": [ "epic", "g" ], "rk-horn-kazoo": [ "rare", "g" ], "rk-horn-bike-bell": [ "common", "g" ], "rk-wreck-confetti-pop": [ "uncommon", "g" ], "rk-wreck-feather-poof": [ "uncommon", "g" ], "rk-wreck-bubble-burst": [ "common", "g" ], "rk-wreck-jelly-splat": [ "rare", "g" ], "rk-wreck-nuts-and-bolts": [ "common", "g" ], "rk-wreck-fireworks": [ "epic", "g" ], "rk-wreck-popcorn": [ "rare", "g" ], "rk-wreck-snow-globe": [ "epic", "g" ], "tt-colour-red": [ "common", "g" ], "tt-colour-orange": [ "common", "g" ], "tt-colour-yellow": [ "common", "g" ], "tt-colour-lime": [ "common", "g" ], "tt-colour-teal": [ "common", "g" ], "tt-colour-sky-blue": [ "common", "g" ], "tt-colour-purple": [ "common", "g" ], "tt-colour-pink": [ "common", "g" ], "tt-colour-white": [ "common", "g" ], "tt-colour-black": [ "common", "g" ], "tt-premium-gold": [ "epic", "g" ], "tt-premium-chrome": [ "epic", "g" ], "tt-premium-glow-in-the-dark": [ "uncommon", "g" ], "tt-premium-see-through-jelly": [ "uncommon", "g" ], "tt-premium-rainbow-shift": [ "legendary", "g" ], "tt-premium-bubblegum-sprinkles": [ "rare", "g" ], "tt-pattern-polka-dots": [ "common", "g" ], "tt-pattern-stripes": [ "common", "g" ], "tt-pattern-cow-print": [ "uncommon", "g" ], "tt-pattern-tie-dye": [ "uncommon", "g" ], "tt-pattern-checkerboard": [ "common", "g" ], "tt-pattern-leopard": [ "rare", "g" ], "tt-pattern-camo": [ "common", "g" ], "tt-pattern-plaid": [ "common", "g" ], "tt-pattern-watermelon": [ "rare", "g" ], "tt-pants-heart-boxers": [ "common", "g" ], "tt-pants-tighty-whities": [ "common", "g" ], "tt-pants-polka-dot-briefs": [ "common", "g" ], "tt-pants-banana-boxers": [ "uncommon", "g" ], "tt-pants-leopard-print": [ "uncommon", "g" ], "tt-pants-long-johns": [ "rare", "g" ], "tt-pants-diaper": [ "rare", "g" ], "tt-pants-super-undies": [ "epic", "g" ], "tt-pants-undies-on-head": [ "epic", "g" ], "tt-hat-traffic-cone": [ "common", "g" ], "tt-hat-propeller-beanie": [ "uncommon", "g" ], "tt-hat-chef-hat": [ "common", "g" ], "tt-hat-crown": [ "epic", "g" ], "tt-hat-pirate-hat": [ "uncommon", "g" ], "tt-hat-viking-helmet": [ "uncommon", "g" ], "tt-hat-cowboy-hat": [ "common", "g" ], "tt-hat-plunger": [ "rare", "g" ], "tt-hat-fishbowl": [ "epic", "g" ], "tt-hat-cooking-pot": [ "common", "g" ], "tt-hat-birthday-cone": [ "common", "g" ], "tt-hat-rubber-duck": [ "rare", "g" ], "tt-hat-toilet-paper-roll": [ "rare", "g" ], "tt-hat-tiny-top-hat": [ "common", "g" ], "tt-face-mustache": [ "common", "g" ], "tt-face-monocle": [ "uncommon", "g" ], "tt-face-googly-eyes": [ "common", "g" ], "tt-face-unibrow": [ "common", "g" ], "tt-face-braces": [ "common", "g" ], "tt-face-sunglasses": [ "rare", "g" ], "tt-costume-hot-dog": [ "epic", "g" ], "tt-costume-banana": [ "epic", "g" ], "tt-costume-pickle": [ "epic", "g" ], "tt-costume-chicken": [ "epic", "g" ], "tt-costume-dinosaur-onesie": [ "epic", "g" ], "tt-costume-shark": [ "epic", "g" ], "tt-costume-cactus": [ "epic", "g" ], "tt-costume-sushi-roll": [ "epic", "g" ], "tt-costume-astronaut": [ "epic", "g" ], "tt-costume-knight": [ "epic", "g" ], "tt-costume-toilet-paper-mummy": [ "epic", "g" ], "tt-costume-turkey": [ "epic", "g" ], "tt-dance-wiggle-wobble": [ "uncommon", "g" ], "tt-dance-robot": [ "uncommon", "g" ], "tt-dance-spin-cycle": [ "uncommon", "g" ], "tt-dance-chicken-flap": [ "rare", "g" ], "tt-dance-jelly-jump": [ "epic", "g" ], "tt-dance-disco-point": [ "rare", "g" ], "tt-scream-wheee": [ "common", "g" ], "tt-scream-aaaah": [ "common", "g" ], "tt-scream-yodel-drop": [ "common", "g" ], "tt-scream-slide-whistle": [ "common", "g" ], "tt-scream-kazoo-wail": [ "common", "g" ], "tt-scream-squeaky-toy": [ "common", "g" ], "tt-splash-confetti-pop": [ "uncommon", "g" ], "tt-splash-bubble-burst": [ "uncommon", "g" ], "tt-splash-rainbow-splat": [ "rare", "g" ], "tt-splash-star-shower": [ "rare", "g" ], "tt-splash-glitter-geyser": [ "epic", "g" ], "sc-egg-white-egg": [ "common", "g" ], "sc-egg-brown-egg": [ "common", "g" ], "sc-egg-speckled-quail": [ "common", "g" ], "sc-egg-robin-blue": [ "common", "g" ], "sc-egg-ostrich-egg": [ "uncommon", "g" ], "sc-egg-emu-egg": [ "uncommon", "g" ], "sc-egg-rotten-egg": [ "uncommon", "g" ], "sc-egg-golden-egg": [ "epic", "g" ], "sc-egg-painted-easter-egg": [ "rare", "g" ], "sc-egg-chocolate-egg": [ "epic", "g" ], "sc-egg-hard-boiled": [ "rare", "g" ], "sc-egg-century-egg": [ "epic", "g" ], "sc-egg-dinosaur-egg": [ "epic", "g" ], "sc-egg-dragon-egg": [ "legendary", "g" ], "sc-egg-alien-egg": [ "legendary", "g" ], "sc-egg-jeweled-egg": [ "legendary", "g" ], "sc-egg-disco-ball": [ "legendary", "g" ], "sc-egg-pixel-egg": [ "epic", "g" ], "sc-egg-bandaged-egg": [ "rare", "g" ], "sc-hat-eggcup-crown": [ "epic", "g" ], "sc-hat-frying-pan": [ "common", "g" ], "sc-hat-nest": [ "uncommon", "g" ], "sc-hat-chef-hat": [ "common", "g" ], "sc-hat-bacon-headband": [ "uncommon", "g" ], "sc-hat-baby-chick": [ "epic", "g" ], "sc-hat-sunny-side-up-beret": [ "rare", "g" ], "sc-gun-cast-iron": [ "common", "g" ], "sc-gun-gold-plated": [ "epic", "g" ], "sc-gun-egg-carton": [ "common", "g" ], "sc-gun-yolk-drip": [ "uncommon", "g" ], "sc-gun-bacon-wrap": [ "uncommon", "g" ], "sc-gun-ketchup-and-mustard": [ "common", "g" ], "sc-gun-hot-sauce": [ "uncommon", "g" ], "sc-gun-toaster-chrome": [ "epic", "g" ], "sc-gun-candy-stripe": [ "common", "g" ], "sc-gun-whisk-barrel": [ "rare", "g" ], "sc-gun-wooden-spoon-stock": [ "rare", "g" ], "sc-gun-rubber-chicken": [ "legendary", "g" ], "sc-crack-fried-egg": [ "common", "g" ], "sc-crack-scrambled": [ "uncommon", "g" ], "sc-crack-chick-hatches": [ "epic", "g" ], "sc-crack-shell-confetti": [ "rare", "g" ], "sc-crack-stink-puff": [ "common", "g" ], "ar-alien-little-green": [ "common", "g" ], "ar-alien-one-eyed-blob": [ "common", "g" ], "ar-alien-three-eyed-guy": [ "common", "g" ], "ar-alien-tentacle-squid": [ "uncommon", "g" ], "ar-alien-slime-cube": [ "uncommon", "g" ], "ar-alien-fuzzy-furball": [ "common", "g" ], "ar-alien-crystal-alien": [ "epic", "g" ], "ar-alien-mushroom-alien": [ "uncommon", "g" ], "ar-alien-jellyfish": [ "rare", "g" ], "ar-alien-cat-alien": [ "epic", "g" ], "ar-alien-potato-alien": [ "common", "g" ], "ar-alien-star-alien": [ "rare", "g" ], "ar-alien-eyeball-with-legs": [ "epic", "g" ], "ar-alien-brain-in-a-jar": [ "epic", "g" ], "ar-alien-robot-suit-pilot": [ "legendary", "g" ], "ar-alien-mustache-disguise": [ "legendary", "g" ], "ar-alien-escaped-cow": [ "legendary", "g" ], "ar-alien-astronaut-hamster": [ "epic", "g" ], "ar-alien-retro-robot": [ "rare", "g" ], "ar-trail-stardust": [ "common", "g" ], "ar-trail-slime-drips": [ "common", "g" ], "ar-trail-bubbles": [ "common", "g" ], "ar-trail-hearts": [ "uncommon", "g" ], "ar-trail-confetti": [ "uncommon", "g" ], "ar-trail-pixels": [ "rare", "g" ], "ar-trail-snowflakes": [ "common", "g" ], "ar-trail-petals": [ "rare", "g" ], "ar-trail-zaps": [ "epic", "g" ], "ar-trail-tractor-rings": [ "epic", "g" ], "ar-tunnel-deep-blue": [ "common", "g" ], "ar-tunnel-silver": [ "common", "g" ], "ar-tunnel-bubblegum": [ "uncommon", "g" ], "ar-tunnel-ultraviolet": [ "uncommon", "g" ], "ar-tunnel-ocean": [ "common", "g" ], "ar-tunnel-moon-dust": [ "rare", "g" ], "ar-tunnel-treasure": [ "epic", "g" ], "ar-tunnel-checkerboard": [ "epic", "g" ], "ar-tunnel-candy-checker": [ "epic", "g" ], "ar-tunnel-prism": [ "legendary", "g" ], "rl-car-muscle-car": [ "common", "g" ], "rl-car-rally-hatch": [ "common", "g" ], "rl-car-hot-rod": [ "uncommon", "g" ], "rl-car-pickup": [ "common", "g" ], "rl-car-dune-buggy": [ "common", "g" ], "rl-car-monster-truck": [ "epic", "g" ], "rl-car-retro-wedge": [ "uncommon", "g" ], "rl-car-go-kart": [ "common", "g" ], "rl-car-limo": [ "uncommon", "g" ], "rl-car-school-bus": [ "uncommon", "g" ], "rl-car-taxi": [ "common", "g" ], "rl-car-police-cruiser": [ "uncommon", "g" ], "rl-car-fire-truck": [ "epic", "g" ], "rl-car-ice-cream-truck": [ "epic", "g" ], "rl-car-garbage-truck": [ "rare", "g" ], "rl-car-tractor": [ "rare", "g" ], "rl-car-golf-cart": [ "common", "g" ], "rl-car-lunar-rover": [ "epic", "g" ], "rl-car-wooden-toy": [ "rare", "g" ], "rl-car-wind-up-car": [ "epic", "g" ], "rl-car-rc-car": [ "rare", "g" ], "rl-car-soapbox-crate": [ "rare", "g" ], "rl-car-cardboard-box": [ "common", "g" ], "rl-car-shopping-cart": [ "epic", "g" ], "rl-car-bathtub": [ "epic", "g" ], "rl-car-couch": [ "epic", "g" ], "rl-car-hot-dog": [ "epic", "g" ], "rl-car-banana": [ "epic", "g" ], "rl-car-rubber-duck": [ "legendary", "g" ], "rl-car-giant-shoe": [ "legendary", "g" ], "rl-car-rocket-car": [ "legendary", "g" ], "rl-paint-candy-apple-paint": [ "common", "g" ], "rl-paint-tangerine-paint": [ "common", "g" ], "rl-paint-lemon-drop-paint": [ "common", "g" ], "rl-paint-lime-fizz-paint": [ "common", "g" ], "rl-paint-mint-paint": [ "common", "g" ], "rl-paint-teal-paint": [ "common", "g" ], "rl-paint-sky-paint": [ "common", "g" ], "rl-paint-midnight-paint": [ "common", "g" ], "rl-paint-lavender-paint": [ "common", "g" ], "rl-paint-grape-paint": [ "common", "g" ], "rl-paint-bubblegum-paint": [ "common", "g" ], "rl-paint-magenta-paint": [ "common", "g" ], "rl-paint-copper-paint": [ "uncommon", "g" ], "rl-paint-sand-paint": [ "common", "g" ], "rl-paint-gold-paint": [ "uncommon", "g" ], "rl-paint-silver-paint": [ "rare", "g" ], "rl-wheels-whitewalls": [ "common", "g" ], "rl-wheels-wire-spokes": [ "uncommon", "g" ], "rl-wheels-gold-star": [ "uncommon", "g" ], "rl-wheels-off-road": [ "common", "g" ], "rl-wheels-neon-rings": [ "epic", "g" ], "rl-wheels-wooden": [ "uncommon", "g" ], "rl-wheels-red-steelies": [ "common", "g" ], "rl-wheels-turbine": [ "rare", "g" ], "rl-wheels-candy-swirl": [ "rare", "g" ], "rl-wheels-flower-caps": [ "rare", "g" ], "rl-wheels-race-slicks": [ "common", "g" ], "rl-wheels-rainbow-rings": [ "epic", "g" ], "rl-smoke-pink-tyre-smoke": [ "common", "g" ], "rl-smoke-sky-blue-tyre-smoke": [ "common", "g" ], "rl-smoke-lime-tyre-smoke": [ "common", "g" ], "rl-smoke-purple-tyre-smoke": [ "common", "g" ], "rl-smoke-gold-tyre-smoke": [ "common", "g" ], "rl-smoke-orange-tyre-smoke": [ "common", "g" ], "rl-smoke-red-tyre-smoke": [ "common", "g" ], "rl-smoke-mint-tyre-smoke": [ "common", "g" ], "rl-smoke-rainbow-tyre-smoke": [ "epic", "g" ], "rl-smoke-confetti-tyre-smoke": [ "epic", "g" ], "rl-horn-beep-beep": [ "common", "g" ], "rl-horn-clown-honk": [ "uncommon", "g" ], "rl-horn-air-horn": [ "uncommon", "g" ], "rl-horn-little-tune": [ "uncommon", "g" ], "rl-horn-duck-quack": [ "epic", "g" ], "rl-horn-bike-bell": [ "common", "g" ], "rl-horn-squeaky-toy": [ "rare", "g" ], "rl-horn-space-zap": [ "epic", "g" ], "rl-horn-foghorn": [ "rare", "g" ], "rl-horn-ice-cream-jingle": [ "epic", "g" ], "rl-horn-train-whistle": [ "rare", "g" ], "cf-hat-detective-deerstalker": [ "uncommon", "g" ], "cf-hat-safari-hat": [ "common", "g" ], "cf-hat-painter-s-beret": [ "common", "g" ], "cf-hat-museum-guard-cap": [ "common", "g" ], "cf-hat-hard-hat": [ "common", "g" ], "cf-hat-exterminator-cap": [ "rare", "g" ], "cf-hat-goggles": [ "common", "g" ], "cf-tool-magnifying-glass": [ "uncommon", "g" ], "cf-tool-paint-scraper": [ "common", "g" ], "cf-tool-spray-bottle": [ "common", "g" ], "cf-tool-feather-duster": [ "rare", "g" ], "cf-splash-paint-splash": [ "epic", "g" ], "cf-caught-surprise-spin": [ "epic", "g" ], "oo-outfit-police-officer": [ "common", "g" ], "oo-outfit-sheriff": [ "uncommon", "g" ], "oo-outfit-mall-cop": [ "common", "g" ], "oo-outfit-security-guard": [ "common", "g" ], "oo-outfit-detective": [ "uncommon", "g" ], "oo-outfit-store-manager": [ "common", "g" ], "oo-outfit-janitor": [ "common", "g" ], "oo-outfit-park-ranger": [ "uncommon", "g" ], "oo-outfit-exterminator": [ "rare", "g" ], "oo-outfit-construction-worker": [ "common", "g" ], "oo-outfit-cowboy": [ "rare", "g" ], "oo-outfit-pirate": [ "epic", "g" ], "oo-outfit-top-hat": [ "epic", "g" ], "oo-outfit-traffic-cone": [ "legendary", "g" ], "oo-tool-flashlight": [ "common", "g" ], "oo-tool-price-scanner": [ "uncommon", "g" ], "oo-tool-flyswatter": [ "common", "g" ], "oo-tool-butterfly-net": [ "rare", "g" ], "oo-tool-broom": [ "common", "g" ], "oo-tool-rubber-chicken": [ "epic", "g" ], "oo-taunt-bike-horn": [ "common", "g" ], "oo-taunt-squeaky-duck": [ "common", "g" ], "oo-taunt-slide-whistle": [ "common", "g" ], "oo-taunt-boing": [ "common", "g" ], "oo-taunt-cuckoo": [ "uncommon", "g" ], "oo-taunt-kazoo": [ "uncommon", "g" ], "oo-taunt-doorbell": [ "rare", "g" ], "oo-taunt-party-blower": [ "epic", "g" ], "oo-poof-cloud-poof": [ "common", "g" ], "oo-poof-feather-poof": [ "uncommon", "g" ], "oo-poof-bubble-poof": [ "rare", "g" ], "oo-poof-star-poof": [ "epic", "g" ], "oo-poof-price-tag-poof": [ "epic", "g" ], "dz-outfit-jet-pilot": [ "uncommon", "g" ], "dz-outfit-lumberjack": [ "common", "g" ], "dz-outfit-park-ranger": [ "common", "g" ], "dz-outfit-scuba-diver": [ "uncommon", "g" ], "dz-outfit-head-chef": [ "uncommon", "g" ], "dz-outfit-hazmat-suit": [ "uncommon", "g" ], "dz-outfit-castle-knight": [ "epic", "g" ], "dz-outfit-astronaut": [ "epic", "g" ], "dz-outfit-farmer": [ "common", "g" ], "dz-outfit-mail-carrier": [ "common", "g" ], "dz-outfit-lifeguard": [ "common", "g" ], "dz-outfit-ninja": [ "rare", "g" ], "dz-outfit-scarecrow": [ "rare", "g" ], "dz-outfit-skeleton": [ "rare", "g" ], "dz-outfit-banana-suit": [ "epic", "g" ], "dz-outfit-cardboard-box-robot": [ "epic", "g" ], "dz-pack-rucksack": [ "common", "g" ], "dz-pack-jetpack": [ "epic", "g" ], "dz-pack-teddy-bear": [ "uncommon", "g" ], "dz-pack-tortoise-shell": [ "uncommon", "g" ], "dz-pack-treasure-chest": [ "epic", "g" ], "dz-pack-lunchbox": [ "common", "g" ], "dz-pack-guitar-case": [ "rare", "g" ], "dz-pack-fishbowl": [ "epic", "g" ], "dz-glider-umbrella": [ "common", "g" ], "dz-glider-paper-airplane": [ "common", "g" ], "dz-glider-hang-glider": [ "uncommon", "g" ], "dz-glider-kite": [ "common", "g" ], "dz-glider-bedsheet-parachute": [ "common", "g" ], "dz-glider-trash-bag-parachute": [ "common", "g" ], "dz-glider-cardboard-wings": [ "common", "g" ], "dz-glider-dragon-wings": [ "epic", "g" ], "dz-glider-bat-wings": [ "uncommon", "g" ], "dz-glider-bunch-of-balloons": [ "uncommon", "g" ], "dz-glider-lawn-chair-with-balloons": [ "epic", "g" ], "dz-glider-magic-carpet": [ "epic", "g" ], "dz-glider-picnic-blanket": [ "uncommon", "g" ], "dz-glider-surfboard": [ "rare", "g" ], "dz-glider-pizza-slice": [ "rare", "g" ], "dz-glider-broomstick": [ "epic", "g" ], "dz-glider-giant-leaf": [ "common", "g" ], "dz-glider-spinning-maple-seed": [ "rare", "g" ], "dz-glider-rubber-duck-float": [ "rare", "g" ], "dz-glider-giant-pigeon": [ "legendary", "g" ], "dz-glider-pterodactyl": [ "legendary", "g" ], "dz-glider-flying-squirrel-suit": [ "epic", "g" ], "dz-glider-ufo-disc": [ "legendary", "g" ], "dz-glider-small-cloud": [ "epic", "g" ], "dz-trail-smoke": [ "common", "g" ], "dz-trail-sparkles": [ "uncommon", "g" ], "dz-trail-rainbow": [ "epic", "g" ], "dz-trail-feathers": [ "common", "g" ], "dz-trail-leaves": [ "common", "g" ], "dz-trail-bubbles": [ "rare", "g" ], "dz-wrap-gold": [ "legendary", "g" ], "dz-wrap-chrome": [ "epic", "g" ], "dz-wrap-wood-grain": [ "common", "g" ], "dz-wrap-forest-camo": [ "common", "g" ], "dz-wrap-desert-camo": [ "common", "g" ], "dz-wrap-arctic-camo": [ "common", "g" ], "dz-wrap-pixel-camo": [ "uncommon", "g" ], "dz-wrap-neon-outline": [ "epic", "g" ], "dz-wrap-toy-blaster": [ "uncommon", "g" ], "dz-wrap-cardboard": [ "common", "g" ], "dz-wrap-candy-cane": [ "uncommon", "g" ], "dz-wrap-lava": [ "epic", "g" ], "dz-wrap-ice": [ "rare", "g" ], "dz-wrap-galaxy": [ "epic", "g" ], "dz-wrap-rust": [ "common", "g" ], "dz-wrap-graffiti": [ "rare", "g" ], "dz-wrap-bubblegum-pink": [ "common", "g" ], "dz-wrap-hazard-stripes": [ "rare", "g" ], "dz-wrap-plastic-brick": [ "epic", "g" ], "dz-build-cardboard": [ "common", "g" ], "dz-build-frosted-glass": [ "uncommon", "g" ], "dz-build-ice": [ "uncommon", "g" ], "dz-build-candy": [ "epic", "g" ], "dz-build-stone": [ "common", "g" ], "dz-build-scrap-metal": [ "rare", "g" ], "dz-emote-wave": [ "common", "g" ], "dz-emote-dance": [ "uncommon", "g" ], "dz-emote-clap": [ "common", "g" ], "dz-emote-jumping-jacks": [ "common", "g" ], "dz-emote-robot": [ "uncommon", "g" ], "dz-emote-twirl": [ "rare", "g" ], "dz-victory-champion": [ "epic", "g" ], "dz-victory-flex": [ "uncommon", "g" ], "dz-victory-take-a-bow": [ "rare", "g" ], "dz-victory-jump-for-joy": [ "epic", "g" ] }, "PACKS": {"draw-1": {"kind": "draws", "name": "One chest", "price": 119, "contents": {"draws": 1 } }, "draw-5": {"kind": "draws", "name": "Five chests", "price": 595, "contents": {"draws": 5 } }, "draw-10": {"kind": "draws", "name": "Ten chests", "price": 1190, "contents": {"draws": 10 } }, "skins-space": {"kind": "skins", "name": "Launch Bay", "price": 179, "contents": {"items": [ "moon-walker", "comet-courier" ] } }, "skins-ocean": {"kind": "skins", "name": "Deep End", "price": 179, "contents": {"items": [ "tide-pool", "coral-diver" ] } }, "skins-neon": {"kind": "skins", "name": "After Dark", "price": 179, "contents": {"items": [ "neon-jogger", "grid-runner" ] } }, "skins-candy": {"kind": "skins", "name": "Sweet Tooth", "price": 239, "contents": {"items": [ "bubblegum", "sprinkle-pop", "gumdrop-knight" ] } }, "skins-robot": {"kind": "skins", "name": "Workshop", "price": 480, "contents": {"items": [ "tin-tinker", "circuit-scout" ] } }, "skins-animals": {"kind": "skins", "name": "Wild Things", "price": 600, "contents": {"items": [ "tabby", "cub", "hopper", "red-fox" ] } }, "skins-seasons": {"kind": "skins", "name": "All Year Round", "price": 960, "contents": {"items": [ "spring-sprout", "summer-sun", "autumn-ember", "winter-frost" ] } }, "skins-wild": {"kind": "skins", "name": "Far Lands", "price": 480, "contents": {"items": [ "dune-rover", "magma-walker" ] } }, "acc-hats": {"kind": "accessories", "name": "Hat Box", "price": 719, "contents": {"items": [ "pom-beanie", "wizard-cone", "propeller-cap", "tall-topper", "daisy-crown" ] } }, "acc-glasses": {"kind": "accessories", "name": "Eyewear Case", "price": 1199, "contents": {"items": [ "star-shades", "heart-specs", "monocle", "glow-visor" ] } }, "acc-capes": {"kind": "accessories", "name": "Cape Rack", "price": 779, "contents": {"items": [ "hero-cape", "galaxy-cape", "leaf-cloak" ] } }, "acc-trails": {"kind": "accessories", "name": "Trail Kit", "price": 779, "contents": {"items": [ "sparkle-trail", "bubble-trail", "rainbow-streak" ] } }, "acc-auras": {"kind": "accessories", "name": "Glow Jar", "price": 1139, "contents": {"items": [ "halo-glow", "ember-aura", "frost-ring" ] } }, "acc-pets": {"kind": "accessories", "name": "Pet Carrier", "price": 839, "contents": {"items": [ "pocket-slime", "mini-bot", "star-buddy", "ghost-pup" ] } }, "acc-drake": {"kind": "accessories", "name": "Dragon Egg", "price": 1200, "contents": {"items": [ "baby-drake" ] } }, "bb-decals-speed": {"kind": "items", "name": "Speed Shop", "price": 300, "contents": {"items": [ "bb-decal-flames", "bb-decal-racing-stripes", "bb-decal-lightning-bolts", "bb-decal-checkered-flag", "bb-decal-carbon-fiber" ] } }, "bb-decals-wild": {"kind": "items", "name": "Wild Side", "price": 837, "contents": {"items": [ "bb-decal-shark-mouth", "bb-decal-tiger-stripes", "bb-decal-dragon-scales", "bb-decal-cow-print", "bb-decal-skeleton-ribs" ] } }, "bb-decals-tech": {"kind": "items", "name": "Late Night", "price": 1318, "contents": {"items": [ "bb-decal-galaxy", "bb-decal-constellations", "bb-decal-circuit-board", "bb-decal-wireframe", "bb-decal-pixel-camo" ] } }, "bb-decals-art": {"kind": "items", "name": "Art Class", "price": 899, "contents": {"items": [ "bb-decal-graffiti-drips", "bb-decal-comic-book-dots", "bb-decal-topographic-lines", "bb-decal-stained-glass", "bb-decal-honeycomb" ] } }, "bb-decals-weather": {"kind": "items", "name": "Hot and Cold", "price": 1259, "contents": {"items": [ "bb-decal-lava-cracks", "bb-decal-frost", "bb-decal-autumn-leaves", "bb-decal-rust-bucket", "bb-decal-wood-paneling" ] } }, "bb-decals-jobs": {"kind": "items", "name": "Odd Jobs", "price": 1980, "contents": {"items": [ "bb-decal-duct-tape-patches", "bb-decal-donut-sprinkles", "bb-decal-bubble-wrap", "bb-decal-taxi", "bb-decal-police-cruiser", "bb-decal-ice-cream-truck" ] } }, "bb-trails-burn": {"kind": "items", "name": "Afterburners", "price": 1919, "contents": {"items": [ "bb-trail-classic-flame", "bb-trail-blue-plasma", "bb-trail-lightning", "bb-trail-lava", "bb-trail-water-jet", "bb-trail-laser-beam" ] } }, "bb-trails-party": {"kind": "items", "name": "Party Bag", "price": 1017, "contents": {"items": [ "bb-trail-rainbow", "bb-trail-confetti", "bb-trail-hearts", "bb-trail-music-notes", "bb-trail-sparkles" ] } }, "bb-trails-weather": {"kind": "items", "name": "Light and Fluffy", "price": 419, "contents": {"items": [ "bb-trail-bubbles", "bb-trail-snowflakes", "bb-trail-autumn-leaves", "bb-trail-feathers", "bb-trail-soap-suds", "bb-trail-smoke-rings" ] } }, "bb-trails-odd": {"kind": "items", "name": "Odds and Ends", "price": 2280, "contents": {"items": [ "bb-trail-popcorn", "bb-trail-rubber-ducks", "bb-trail-toast-slices", "bb-trail-dollar-bills", "bb-trail-slime" ] } }, "bb-trails-night": {"kind": "items", "name": "Night Shift", "price": 1920, "contents": {"items": [ "bb-trail-stardust", "bb-trail-pixel-blocks", "bb-trail-ink", "bb-trail-ones-and-zeros", "bb-trail-bats" ] } }, "bb-goals-bang": {"kind": "items", "name": "Big Bangs", "price": 2038, "contents": {"items": [ "bb-goal-fireworks", "bb-goal-supernova", "bb-goal-lightning-strike", "bb-goal-meteor", "bb-goal-volcano" ] } }, "bb-goals-party": {"kind": "items", "name": "Party Time", "price": 2339, "contents": {"items": [ "bb-goal-confetti-cannon", "bb-goal-disco-ball-drop", "bb-goal-pinata-burst", "bb-goal-popcorn-pop", "bb-goal-money-rain" ] } }, "bb-goals-science": {"kind": "items", "name": "Strange Science", "price": 2339, "contents": {"items": [ "bb-goal-black-hole", "bb-goal-tornado", "bb-goal-freeze-and-shatter", "bb-goal-pixel-shatter", "bb-goal-flock-of-birds" ] } }, "bb-goals-giant": {"kind": "items", "name": "Giant Trouble", "price": 5820, "contents": {"items": [ "bb-goal-giant-foot-stomp", "bb-goal-ufo-abduction", "bb-goal-shark-attack", "bb-goal-giant-airhorn", "bb-goal-pumpkin-splat", "bb-goal-goal-letters" ] } }, "bb-toppers": {"kind": "items", "name": "Aerial Shop", "price": 1319, "contents": {"items": [ "bb-topper-tennis-ball", "bb-topper-gold-star", "bb-topper-bath-duck", "bb-topper-mini-pumpkin", "bb-topper-pennant", "bb-topper-eyeball" ] } }, "bb-hats": {"kind": "items", "name": "Roof Rack", "price": 1378, "contents": {"items": [ "bb-hat-traffic-cone", "bb-hat-top-hat", "bb-hat-crown", "bb-hat-propeller-beanie", "bb-hat-cowboy-hat", "bb-hat-chef-hat" ] } }, "bb-wheels": {"kind": "items", "name": "Tyre Fitter", "price": 839, "contents": {"items": [ "bb-wheels-five-spoke", "bb-wheels-discs", "bb-wheels-cross", "bb-wheels-gold-rims" ] } }, "bb-engines": {"kind": "items", "name": "Under the Bonnet", "price": 1199, "contents": {"items": [ "bb-engine-purr", "bb-engine-buzz", "bb-engine-rumble", "bb-engine-whirr" ] } }, "ss-liveries-classic": {"kind": "items", "name": "Paint Shop", "price": 240, "contents": {"items": [ "ss-livery-two-tone-classic", "ss-livery-retro-stripes", "ss-livery-pastel", "ss-livery-checkered" ] } }, "ss-liveries-loud": {"kind": "items", "name": "Show Car", "price": 1258, "contents": {"items": [ "ss-livery-matte-black-with-neon", "ss-livery-chrome", "ss-livery-carbon", "ss-livery-flames" ] } }, "ss-helmets-fast": {"kind": "items", "name": "Helmet Rack", "price": 299, "contents": {"items": [ "ss-helmet-flames-helmet", "ss-helmet-checkered-helmet", "ss-helmet-lightning-helmet", "ss-helmet-chrome-visor" ] } }, "ss-helmets-wild": {"kind": "items", "name": "Wild Lids", "price": 1557, "contents": {"items": [ "ss-helmet-shark-helmet", "ss-helmet-skull-helmet", "ss-helmet-tiger-helmet", "ss-helmet-eyeball", "ss-helmet-cat-ears" ] } }, "ss-helmets-odd": {"kind": "items", "name": "Odd Lids", "price": 3660, "contents": {"items": [ "ss-helmet-galaxy-helmet", "ss-helmet-disco-ball", "ss-helmet-watermelon-helmet", "ss-helmet-eight-ball", "ss-helmet-pumpkin-helmet", "ss-helmet-pizza-helmet" ] } }, "ss-effects-air": {"kind": "items", "name": "Clean Air", "price": 299, "contents": {"items": [ "ss-effect-white-air-streaks", "ss-effect-vapor-trail", "ss-effect-flames", "ss-effect-sparks" ] } }, "ss-effects-show": {"kind": "items", "name": "Light Show", "price": 1739, "contents": {"items": [ "ss-effect-electric-arcs", "ss-effect-rainbow", "ss-effect-confetti", "ss-effect-purple-plasma" ] } }, "ss-extras": {"kind": "items", "name": "Pit Wall Party", "price": 479, "contents": {"items": [ "ss-smoke-pink-tyre-smoke", "ss-smoke-blue-tyre-smoke", "ss-smoke-green-tyre-smoke", "ss-smoke-purple-tyre-smoke", "ss-smoke-gold-tyre-smoke", "ss-podium-confetti-podium", "ss-podium-fireworks-podium" ] } } }, "EMERALDS": {"emeralds_7": {"name": "Emerald Handful", "emeralds": 7, "cents": 99, "currency": "usd" }, "emeralds_39": {"name": "Emerald Pouch", "emeralds": 39, "cents": 499, "currency": "usd" }, "emeralds_80": {"name": "Emerald Sack", "emeralds": 80, "cents": 999, "currency": "usd" }, "emeralds_180": {"name": "Emerald Chest", "emeralds": 180, "cents": 1999, "currency": "usd" }, "emeralds_1000": {"name": "Emerald Buttload", "emeralds": 1000, "cents": 4999, "currency": "usd" }, "emeralds_4000": {"name": "Emerald Vault", "emeralds": 4000, "cents": 9999, "currency": "usd" } } }; +export const CATALOG = {"PUBLIC": false, "MANGOS_PER_EMERALD": 17, "PRICE": {"common": 60, "uncommon": 119, "rare": 420, "epic": 600, "legendary": 1200 }, "CHEST_PRICE": 119, "DUP_REFUND": 48, "RARITY": [ {"id": "legendary", "name": "Legendary", "w": 250 }, {"id": "epic", "name": "Epic", "w": 500 }, {"id": "rare", "name": "Rare", "w": 1250 }, {"id": "uncommon", "name": "Uncommon", "w": 2000 }, {"id": "common", "name": "Common", "w": 6000 } ], "RARITY_TOTAL": 10000, "NOTE_MAX": 60, "ITEMS": {"moon-walker": [ "common", "s", "Moon Walker" ], "tide-pool": [ "common", "s", "Tide Pool" ], "neon-jogger": [ "common", "s", "Neon Jogger" ], "bubblegum": [ "common", "s", "Bubblegum" ], "sprinkle-pop": [ "common", "s", "Sprinkle Pop" ], "tin-tinker": [ "common", "s", "Tin Tinker" ], "tabby": [ "common", "s", "Tabby" ], "cub": [ "common", "s", "Cub" ], "hopper": [ "common", "s", "Hopper" ], "spring-sprout": [ "common", "s", "Spring Sprout" ], "summer-sun": [ "common", "s", "Summer Sun" ], "dune-rover": [ "common", "s", "Dune Rover" ], "comet-courier": [ "uncommon", "s", "Comet Courier" ], "coral-diver": [ "uncommon", "s", "Coral Diver" ], "grid-runner": [ "uncommon", "s", "Grid Runner" ], "gumdrop-knight": [ "uncommon", "s", "Gumdrop Knight" ], "circuit-scout": [ "rare", "s", "Circuit Scout" ], "red-fox": [ "rare", "s", "Red Fox" ], "autumn-ember": [ "rare", "s", "Autumn Ember" ], "winter-frost": [ "rare", "s", "Winter Frost" ], "magma-walker": [ "rare", "s", "Magma Walker" ], "nebula-drifter": [ "epic", "s", "Nebula Drifter" ], "abyss-lantern": [ "epic", "s", "Abyss Lantern" ], "synthwave": [ "epic", "s", "Synthwave" ], "rock-candy": [ "epic", "s", "Rock Candy" ], "chrome-unit": [ "epic", "s", "Chrome Unit" ], "storm-drake": [ "epic", "s", "Storm Drake" ], "star-sovereign": [ "legendary", "s", "Star Sovereign" ], "golden-automaton": [ "legendary", "s", "Golden Automaton" ], "four-seasons": [ "legendary", "s", "Four Seasons" ], "pom-beanie": [ "common", "a", "Pom Beanie" ], "wizard-cone": [ "uncommon", "a", "Wizard Cone" ], "propeller-cap": [ "common", "a", "Propeller Cap" ], "tall-topper": [ "rare", "a", "Tall Topper" ], "daisy-crown": [ "common", "a", "Daisy Crown" ], "star-shades": [ "uncommon", "a", "Star Shades" ], "heart-specs": [ "common", "a", "Heart Specs" ], "monocle": [ "rare", "a", "Monocle" ], "glow-visor": [ "epic", "a", "Glow Visor" ], "hero-cape": [ "common", "a", "Hero Cape" ], "galaxy-cape": [ "epic", "a", "Galaxy Cape" ], "leaf-cloak": [ "uncommon", "a", "Leaf Cloak" ], "sparkle-trail": [ "uncommon", "a", "Sparkle Trail" ], "bubble-trail": [ "common", "a", "Bubble Trail" ], "rainbow-streak": [ "epic", "a", "Rainbow Streak" ], "halo-glow": [ "uncommon", "a", "Halo Glow" ], "ember-aura": [ "epic", "a", "Ember Aura" ], "frost-ring": [ "rare", "a", "Frost Ring" ], "pocket-slime": [ "common", "a", "Pocket Slime" ], "mini-bot": [ "uncommon", "a", "Mini Bot" ], "star-buddy": [ "common", "a", "Star Buddy" ], "ghost-pup": [ "epic", "a", "Ghost Pup" ], "baby-drake": [ "legendary", "a", "Baby Drake" ], "bb-decal-flames": [ "common", "g", "Flames" ], "bb-decal-racing-stripes": [ "common", "g", "Racing Stripes" ], "bb-decal-lightning-bolts": [ "common", "g", "Lightning Bolts" ], "bb-decal-checkered-flag": [ "common", "g", "Checkered Flag" ], "bb-decal-shark-mouth": [ "uncommon", "g", "Shark Mouth" ], "bb-decal-tiger-stripes": [ "uncommon", "g", "Tiger Stripes" ], "bb-decal-dragon-scales": [ "uncommon", "g", "Dragon Scales" ], "bb-decal-carbon-fiber": [ "common", "g", "Carbon Fiber" ], "bb-decal-pixel-camo": [ "common", "g", "Pixel Camo" ], "bb-decal-galaxy": [ "epic", "g", "Galaxy" ], "bb-decal-constellations": [ "uncommon", "g", "Constellations" ], "bb-decal-circuit-board": [ "uncommon", "g", "Circuit Board" ], "bb-decal-graffiti-drips": [ "uncommon", "g", "Graffiti Drips" ], "bb-decal-honeycomb": [ "common", "g", "Honeycomb" ], "bb-decal-lava-cracks": [ "epic", "g", "Lava Cracks" ], "bb-decal-frost": [ "uncommon", "g", "Frost" ], "bb-decal-comic-book-dots": [ "common", "g", "Comic Book Dots" ], "bb-decal-topographic-lines": [ "common", "g", "Topographic Lines" ], "bb-decal-stained-glass": [ "epic", "g", "Stained Glass" ], "bb-decal-wireframe": [ "rare", "g", "Wireframe" ], "bb-decal-skeleton-ribs": [ "rare", "g", "Skeleton Ribs" ], "bb-decal-duct-tape-patches": [ "common", "g", "Duct Tape Patches" ], "bb-decal-rust-bucket": [ "common", "g", "Rust Bucket" ], "bb-decal-wood-paneling": [ "rare", "g", "Wood Paneling" ], "bb-decal-cow-print": [ "common", "g", "Cow Print" ], "bb-decal-donut-sprinkles": [ "rare", "g", "Donut Sprinkles" ], "bb-decal-bubble-wrap": [ "common", "g", "Bubble Wrap" ], "bb-decal-taxi": [ "rare", "g", "Taxi" ], "bb-decal-police-cruiser": [ "rare", "g", "Police Cruiser" ], "bb-decal-ice-cream-truck": [ "epic", "g", "Ice Cream Truck" ], "bb-decal-autumn-leaves": [ "common", "g", "Autumn Leaves" ], "bb-trail-classic-flame": [ "common", "g", "Classic Flame" ], "bb-trail-blue-plasma": [ "common", "g", "Blue Plasma" ], "bb-trail-rainbow": [ "epic", "g", "Rainbow" ], "bb-trail-lightning": [ "uncommon", "g", "Lightning" ], "bb-trail-bubbles": [ "common", "g", "Bubbles" ], "bb-trail-confetti": [ "common", "g", "Confetti" ], "bb-trail-snowflakes": [ "common", "g", "Snowflakes" ], "bb-trail-autumn-leaves": [ "common", "g", "Autumn Leaves" ], "bb-trail-sparkles": [ "uncommon", "g", "Sparkles" ], "bb-trail-hearts": [ "uncommon", "g", "Hearts" ], "bb-trail-music-notes": [ "uncommon", "g", "Music Notes" ], "bb-trail-pixel-blocks": [ "common", "g", "Pixel Blocks" ], "bb-trail-smoke-rings": [ "uncommon", "g", "Smoke Rings" ], "bb-trail-slime": [ "common", "g", "Slime" ], "bb-trail-lava": [ "rare", "g", "Lava" ], "bb-trail-stardust": [ "epic", "g", "Stardust" ], "bb-trail-popcorn": [ "rare", "g", "Popcorn" ], "bb-trail-rubber-ducks": [ "epic", "g", "Rubber Ducks" ], "bb-trail-feathers": [ "common", "g", "Feathers" ], "bb-trail-soap-suds": [ "common", "g", "Soap Suds" ], "bb-trail-ink": [ "rare", "g", "Ink" ], "bb-trail-ones-and-zeros": [ "rare", "g", "Ones and Zeros" ], "bb-trail-bats": [ "rare", "g", "Bats" ], "bb-trail-toast-slices": [ "epic", "g", "Toast Slices" ], "bb-trail-dollar-bills": [ "epic", "g", "Dollar Bills" ], "bb-trail-water-jet": [ "common", "g", "Water Jet" ], "bb-trail-laser-beam": [ "legendary", "g", "Laser Beam" ], "bb-goal-fireworks": [ "uncommon", "g", "Fireworks" ], "bb-goal-confetti-cannon": [ "uncommon", "g", "Confetti Cannon" ], "bb-goal-black-hole": [ "epic", "g", "Black Hole" ], "bb-goal-supernova": [ "epic", "g", "Supernova" ], "bb-goal-lightning-strike": [ "uncommon", "g", "Lightning Strike" ], "bb-goal-tornado": [ "epic", "g", "Tornado" ], "bb-goal-volcano": [ "epic", "g", "Volcano" ], "bb-goal-meteor": [ "epic", "g", "Meteor" ], "bb-goal-freeze-and-shatter": [ "uncommon", "g", "Freeze and Shatter" ], "bb-goal-pixel-shatter": [ "rare", "g", "Pixel Shatter" ], "bb-goal-disco-ball-drop": [ "epic", "g", "Disco Ball Drop" ], "bb-goal-giant-foot-stomp": [ "legendary", "g", "Giant Foot Stomp" ], "bb-goal-pinata-burst": [ "epic", "g", "Pinata Burst" ], "bb-goal-popcorn-pop": [ "rare", "g", "Popcorn Pop" ], "bb-goal-ufo-abduction": [ "legendary", "g", "UFO Abduction" ], "bb-goal-shark-attack": [ "legendary", "g", "Shark Attack" ], "bb-goal-giant-airhorn": [ "epic", "g", "Giant Airhorn" ], "bb-goal-money-rain": [ "epic", "g", "Money Rain" ], "bb-goal-pumpkin-splat": [ "rare", "g", "Pumpkin Splat" ], "bb-goal-goal-letters": [ "legendary", "g", "Goal Letters" ], "bb-goal-flock-of-birds": [ "epic", "g", "Flock of Birds" ], "bb-topper-tennis-ball": [ "common", "g", "Tennis Ball" ], "bb-topper-gold-star": [ "uncommon", "g", "Gold Star" ], "bb-topper-bath-duck": [ "rare", "g", "Bath Duck" ], "bb-topper-mini-pumpkin": [ "common", "g", "Mini Pumpkin" ], "bb-topper-pennant": [ "common", "g", "Pennant" ], "bb-topper-eyeball": [ "epic", "g", "Eyeball" ], "bb-hat-traffic-cone": [ "common", "g", "Traffic Cone" ], "bb-hat-top-hat": [ "uncommon", "g", "Top Hat" ], "bb-hat-crown": [ "epic", "g", "Crown" ], "bb-hat-propeller-beanie": [ "uncommon", "g", "Propeller Beanie" ], "bb-hat-cowboy-hat": [ "rare", "g", "Cowboy Hat" ], "bb-hat-chef-hat": [ "common", "g", "Chef Hat" ], "bb-wheels-five-spoke": [ "common", "g", "Five Spoke" ], "bb-wheels-discs": [ "common", "g", "Discs" ], "bb-wheels-cross": [ "uncommon", "g", "Cross" ], "bb-wheels-gold-rims": [ "epic", "g", "Gold Rims" ], "bb-engine-purr": [ "common", "g", "Purr" ], "bb-engine-buzz": [ "uncommon", "g", "Buzz" ], "bb-engine-rumble": [ "rare", "g", "Rumble" ], "bb-engine-whirr": [ "epic", "g", "Whirr" ], "ss-sponsor-zoomi-cola": [ "common", "g", "Zoomi Cola", "free" ], "ss-sponsor-burnout-coffee": [ "common", "g", "Burnout Coffee", "free" ], "ss-sponsor-apex-tires": [ "common", "g", "Apex Tires", "free" ], "ss-sponsor-turbo-taco": [ "common", "g", "Turbo Taco", "free" ], "ss-sponsor-grandma-s-motor-oil": [ "common", "g", "Grandma's Motor Oil", "free" ], "ss-sponsor-pit-stop-pizza": [ "common", "g", "Pit Stop Pizza", "free" ], "ss-sponsor-slick-s-hair-gel": [ "common", "g", "Slick's Hair Gel", "free" ], "ss-sponsor-late-brake-insurance": [ "common", "g", "Late Brake Insurance", "free" ], "ss-sponsor-draft-punk-records": [ "common", "g", "Draft Punk Records", "free" ], "ss-sponsor-gravel-trap-granola": [ "common", "g", "Gravel Trap Granola", "free" ], "ss-sponsor-blue-flag-bottled-water": [ "common", "g", "Blue Flag Bottled Water", "free" ], "ss-sponsor-honk-energy": [ "common", "g", "Honk Energy", "free" ], "ss-sponsor-chicane-chicken": [ "common", "g", "Chicane Chicken", "free" ], "ss-sponsor-podium-pickles": [ "common", "g", "Podium Pickles", "free" ], "ss-sponsor-lap-nap-mattresses": [ "common", "g", "Lap Nap Mattresses", "free" ], "ss-livery-two-tone-classic": [ "common", "g", "Two-Tone Classic" ], "ss-livery-retro-stripes": [ "common", "g", "Retro Stripes" ], "ss-livery-matte-black-with-neon": [ "uncommon", "g", "Matte Black with Neon" ], "ss-livery-chrome": [ "epic", "g", "Chrome" ], "ss-livery-carbon": [ "uncommon", "g", "Carbon" ], "ss-livery-pastel": [ "common", "g", "Pastel" ], "ss-livery-flames": [ "rare", "g", "Flames" ], "ss-livery-checkered": [ "common", "g", "Checkered" ], "ss-livery-zoomi-cola-livery": [ "epic", "g", "Zoomi Cola livery", "earned" ], "ss-livery-burnout-coffee-livery": [ "epic", "g", "Burnout Coffee livery", "earned" ], "ss-livery-apex-tires-livery": [ "epic", "g", "Apex Tires livery", "earned" ], "ss-livery-turbo-taco-livery": [ "epic", "g", "Turbo Taco livery", "earned" ], "ss-livery-grandma-s-motor-oil-livery": [ "epic", "g", "Grandma's Motor Oil livery", "earned" ], "ss-livery-pit-stop-pizza-livery": [ "epic", "g", "Pit Stop Pizza livery", "earned" ], "ss-livery-slick-s-hair-gel-livery": [ "epic", "g", "Slick's Hair Gel livery", "earned" ], "ss-livery-late-brake-insurance-livery": [ "epic", "g", "Late Brake Insurance livery", "earned" ], "ss-livery-draft-punk-records-livery": [ "epic", "g", "Draft Punk Records livery", "earned" ], "ss-livery-gravel-trap-granola-livery": [ "epic", "g", "Gravel Trap Granola livery", "earned" ], "ss-livery-blue-flag-bottled-water-livery": [ "epic", "g", "Blue Flag Bottled Water livery", "earned" ], "ss-livery-honk-energy-livery": [ "epic", "g", "Honk Energy livery", "earned" ], "ss-livery-chicane-chicken-livery": [ "epic", "g", "Chicane Chicken livery", "earned" ], "ss-livery-podium-pickles-livery": [ "epic", "g", "Podium Pickles livery", "earned" ], "ss-livery-lap-nap-mattresses-livery": [ "epic", "g", "Lap Nap Mattresses livery", "earned" ], "ss-helmet-red-helmet": [ "common", "g", "Red helmet", "free" ], "ss-helmet-blue-helmet": [ "common", "g", "Blue helmet", "free" ], "ss-helmet-yellow-helmet": [ "common", "g", "Yellow helmet", "free" ], "ss-helmet-green-helmet": [ "common", "g", "Green helmet", "free" ], "ss-helmet-orange-helmet": [ "common", "g", "Orange helmet", "free" ], "ss-helmet-pink-helmet": [ "common", "g", "Pink helmet", "free" ], "ss-helmet-black-helmet": [ "common", "g", "Black helmet", "free" ], "ss-helmet-white-helmet": [ "common", "g", "White helmet", "free" ], "ss-helmet-flames-helmet": [ "common", "g", "Flames helmet" ], "ss-helmet-checkered-helmet": [ "common", "g", "Checkered helmet" ], "ss-helmet-lightning-helmet": [ "common", "g", "Lightning helmet" ], "ss-helmet-chrome-visor": [ "uncommon", "g", "Chrome Visor" ], "ss-helmet-shark-helmet": [ "uncommon", "g", "Shark helmet" ], "ss-helmet-skull-helmet": [ "uncommon", "g", "Skull helmet" ], "ss-helmet-tiger-helmet": [ "uncommon", "g", "Tiger helmet" ], "ss-helmet-galaxy-helmet": [ "epic", "g", "Galaxy helmet" ], "ss-helmet-disco-ball": [ "legendary", "g", "Disco Ball" ], "ss-helmet-watermelon-helmet": [ "rare", "g", "Watermelon helmet" ], "ss-helmet-eight-ball": [ "rare", "g", "Eight Ball" ], "ss-helmet-eyeball": [ "epic", "g", "Eyeball" ], "ss-helmet-pumpkin-helmet": [ "rare", "g", "Pumpkin helmet" ], "ss-helmet-cat-ears": [ "epic", "g", "Cat Ears" ], "ss-helmet-pizza-helmet": [ "epic", "g", "Pizza helmet" ], "ss-effect-white-air-streaks": [ "common", "g", "White Air Streaks" ], "ss-effect-flames": [ "common", "g", "Flames" ], "ss-effect-sparks": [ "uncommon", "g", "Sparks" ], "ss-effect-electric-arcs": [ "uncommon", "g", "Electric Arcs" ], "ss-effect-rainbow": [ "epic", "g", "Rainbow" ], "ss-effect-vapor-trail": [ "common", "g", "Vapor Trail" ], "ss-effect-confetti": [ "rare", "g", "Confetti" ], "ss-effect-purple-plasma": [ "epic", "g", "Purple Plasma" ], "ss-smoke-pink-tyre-smoke": [ "common", "g", "Pink tyre smoke" ], "ss-smoke-blue-tyre-smoke": [ "common", "g", "Blue tyre smoke" ], "ss-smoke-green-tyre-smoke": [ "common", "g", "Green tyre smoke" ], "ss-smoke-purple-tyre-smoke": [ "common", "g", "Purple tyre smoke" ], "ss-smoke-gold-tyre-smoke": [ "common", "g", "Gold tyre smoke" ], "ss-podium-confetti-podium": [ "common", "g", "Confetti Podium" ], "ss-podium-fireworks-podium": [ "uncommon", "g", "Fireworks Podium" ], "cl-color-cherry": [ "common", "g", "Cherry" ], "cl-color-tangerine": [ "common", "g", "Tangerine" ], "cl-color-lemon": [ "common", "g", "Lemon" ], "cl-color-grass": [ "common", "g", "Grass" ], "cl-color-aqua": [ "common", "g", "Aqua" ], "cl-color-ocean": [ "common", "g", "Ocean" ], "cl-color-violet": [ "common", "g", "Violet" ], "cl-color-bubblegum": [ "common", "g", "Bubblegum" ], "cl-color-snow": [ "common", "g", "Snow" ], "cl-color-cocoa": [ "common", "g", "Cocoa" ], "cl-color-gold": [ "uncommon", "g", "Gold" ], "cl-color-slate": [ "common", "g", "Slate" ], "cl-color-neon-green": [ "uncommon", "g", "Neon Green" ], "cl-color-neon-pink": [ "uncommon", "g", "Neon Pink" ], "cl-color-neon-blue": [ "uncommon", "g", "Neon Blue" ], "cl-color-neon-orange": [ "uncommon", "g", "Neon Orange" ], "cl-color-neon-yellow": [ "uncommon", "g", "Neon Yellow" ], "cl-color-sunrise": [ "rare", "g", "Sunrise" ], "cl-color-deep-sea": [ "rare", "g", "Deep Sea" ], "cl-color-mint-grape": [ "rare", "g", "Mint Grape" ], "cl-color-fireball": [ "rare", "g", "Fireball" ], "cl-color-cotton-candy": [ "rare", "g", "Cotton Candy" ], "cl-color-forest": [ "rare", "g", "Forest" ], "cl-color-rainbow": [ "epic", "g", "Rainbow" ], "cl-color-rainbow-flow": [ "epic", "g", "Rainbow Flow" ], "cl-animal-python": [ "uncommon", "g", "Python" ], "cl-animal-rattlesnake": [ "uncommon", "g", "Rattlesnake" ], "cl-animal-coral-snake": [ "uncommon", "g", "Coral Snake" ], "cl-animal-tiger": [ "uncommon", "g", "Tiger" ], "cl-animal-zebra": [ "rare", "g", "Zebra" ], "cl-animal-leopard": [ "rare", "g", "Leopard" ], "cl-animal-cow": [ "common", "g", "Cow" ], "cl-animal-bee": [ "rare", "g", "Bee" ], "cl-animal-caterpillar": [ "epic", "g", "Caterpillar" ], "cl-animal-centipede": [ "epic", "g", "Centipede" ], "cl-animal-dragon": [ "legendary", "g", "Dragon" ], "cl-design-stripes": [ "common", "g", "Stripes" ], "cl-design-candy-cane": [ "uncommon", "g", "Candy Cane" ], "cl-design-barber-pole": [ "uncommon", "g", "Barber Pole" ], "cl-design-checker": [ "common", "g", "Checker" ], "cl-design-polka-dots": [ "common", "g", "Polka Dots" ], "cl-design-zigzag": [ "common", "g", "Zigzag" ], "cl-design-galaxy": [ "epic", "g", "Galaxy" ], "cl-design-lava": [ "epic", "g", "Lava" ], "cl-design-ice": [ "rare", "g", "Ice" ], "cl-design-circuit-board": [ "epic", "g", "Circuit Board" ], "cl-design-pixel": [ "rare", "g", "Pixel" ], "cl-design-camo": [ "common", "g", "Camo" ], "cl-object-train-cars": [ "epic", "g", "Train Cars" ], "cl-object-sausage-links": [ "uncommon", "g", "Sausage Links" ], "cl-object-spaghetti-noodle": [ "uncommon", "g", "Spaghetti Noodle" ], "cl-object-gummy-worm": [ "epic", "g", "Gummy Worm" ], "cl-object-licorice": [ "uncommon", "g", "Licorice" ], "cl-object-garden-hose": [ "uncommon", "g", "Garden Hose" ], "cl-object-rope": [ "common", "g", "Rope" ], "cl-object-chain": [ "rare", "g", "Chain" ], "cl-object-measuring-tape": [ "rare", "g", "Measuring Tape" ], "cl-object-pencil": [ "epic", "g", "Pencil" ], "cl-object-twinkling-lights": [ "legendary", "g", "Twinkling Lights" ], "cl-object-bead-necklace": [ "rare", "g", "Bead Necklace" ], "cl-object-piano-keys": [ "epic", "g", "Piano Keys" ], "cl-object-film-strip": [ "epic", "g", "Film Strip" ], "cl-object-dominoes": [ "epic", "g", "Dominoes" ], "cl-object-scarf": [ "rare", "g", "Scarf" ], "cl-object-skeleton-spine": [ "legendary", "g", "Skeleton Spine" ], "cl-head-sunglasses": [ "uncommon", "g", "Sunglasses" ], "cl-head-crown": [ "epic", "g", "Crown" ], "cl-head-party-hat": [ "uncommon", "g", "Party Hat" ], "cl-head-googly-eyes": [ "rare", "g", "Googly Eyes" ], "cl-head-tongue-out": [ "common", "g", "Tongue Out" ], "cl-head-tiny-cowboy-hat": [ "rare", "g", "Tiny Cowboy Hat" ], "cl-trail-sparkle-trail": [ "epic", "g", "Sparkle Trail" ], "cl-burst-candy-burst": [ "epic", "g", "Candy Burst" ], "cl-burst-coin-burst": [ "legendary", "g", "Coin Burst" ], "up-skin-jungle-explorer": [ "common", "g", "Jungle Explorer" ], "up-skin-mountaineer": [ "common", "g", "Mountaineer" ], "up-skin-arctic-explorer": [ "common", "g", "Arctic Explorer" ], "up-skin-safari-guide": [ "common", "g", "Safari Guide" ], "up-skin-deep-sea-diver": [ "uncommon", "g", "Deep-Sea Diver" ], "up-skin-aviator": [ "uncommon", "g", "Aviator" ], "up-skin-cave-explorer": [ "common", "g", "Cave Explorer" ], "up-skin-treasure-hunter": [ "uncommon", "g", "Treasure Hunter" ], "up-skin-dusty-archaeologist": [ "common", "g", "Dusty Archaeologist" ], "up-skin-storm-chaser": [ "uncommon", "g", "Storm Chaser" ], "up-skin-balloonist": [ "uncommon", "g", "Balloonist" ], "up-skin-old-timey-explorer": [ "epic", "g", "Old-Timey Explorer" ], "up-skin-pirate": [ "epic", "g", "Pirate" ], "up-skin-park-ranger": [ "common", "g", "Park Ranger" ], "up-skin-astronaut": [ "epic", "g", "Astronaut" ], "up-skin-tourist": [ "rare", "g", "Tourist" ], "up-skin-pizza-delivery": [ "rare", "g", "Pizza Delivery" ], "up-skin-window-washer": [ "rare", "g", "Window Washer" ], "up-skin-grandma": [ "epic", "g", "Grandma" ], "up-skin-knight": [ "epic", "g", "Knight" ], "up-skin-ninja": [ "rare", "g", "Ninja" ], "up-skin-chicken-suit": [ "legendary", "g", "Chicken Suit" ], "up-pack-parachute-pack": [ "common", "g", "Parachute Pack" ], "up-pack-teddy-bear": [ "uncommon", "g", "Teddy Bear" ], "up-pack-picnic-basket": [ "common", "g", "Picnic Basket" ], "up-pack-giant-sandwich": [ "rare", "g", "Giant Sandwich" ], "up-pack-fake-jetpack": [ "epic", "g", "Fake Jetpack" ], "up-pack-rolled-up-tent": [ "common", "g", "Rolled-Up Tent" ], "up-reward-1-000-m-badge": [ "uncommon", "g", "1,000 m Badge", "earned" ], "up-reward-space-helmet": [ "epic", "g", "Space Helmet", "earned" ], "up-reward-golden-crown": [ "legendary", "g", "Golden Crown", "earned" ], "up-scream-aaaah": [ "common", "g", "Aaaah!" ], "up-scream-yodel": [ "uncommon", "g", "Yodel" ], "up-scream-slide-whistle": [ "common", "g", "Slide Whistle" ], "up-scream-opera-note": [ "epic", "g", "Opera Note" ], "up-scream-wheee": [ "common", "g", "Wheee!" ], "up-trail-rainbow-streamer": [ "uncommon", "g", "Rainbow Streamer" ], "up-trail-comet-tail": [ "rare", "g", "Comet Tail" ], "up-trail-smoke-trail": [ "common", "g", "Smoke Trail" ], "up-trail-gold-sparkles": [ "epic", "g", "Gold Sparkles" ], "rk-driver-sir-honksalot": [ "epic", "g", "Sir Honksalot" ], "rk-driver-captain-crumb": [ "uncommon", "g", "Captain Crumb" ], "rk-driver-granny-vroom": [ "uncommon", "g", "Granny Vroom" ], "rk-driver-bolt": [ "common", "g", "Bolt" ], "rk-driver-wasabi": [ "uncommon", "g", "Wasabi" ], "rk-driver-professor-pickle": [ "common", "g", "Professor Pickle" ], "rk-driver-dj-raccoon": [ "epic", "g", "DJ Raccoon" ], "rk-driver-chef-meatball": [ "common", "g", "Chef Meatball" ], "rk-driver-yeti-betty": [ "uncommon", "g", "Yeti Betty" ], "rk-driver-count-dracoola": [ "epic", "g", "Count Dracoola" ], "rk-driver-tiny-rex": [ "legendary", "g", "Tiny Rex" ], "rk-driver-sergeant-sprinkles": [ "rare", "g", "Sergeant Sprinkles" ], "rk-driver-moolissa": [ "common", "g", "Moolissa" ], "rk-driver-astro-hamster": [ "epic", "g", "Astro Hamster" ], "rk-driver-cactus-jack": [ "rare", "g", "Cactus Jack" ], "rk-driver-waddles": [ "rare", "g", "Waddles" ], "rk-driver-turkey-tom": [ "common", "g", "Turkey Tom" ], "rk-kart-bathtub": [ "uncommon", "g", "Bathtub" ], "rk-kart-shopping-cart": [ "common", "g", "Shopping Cart" ], "rk-kart-lawnmower": [ "common", "g", "Lawnmower" ], "rk-kart-hot-dog-cart": [ "uncommon", "g", "Hot Dog Cart" ], "rk-kart-bumper-car": [ "common", "g", "Bumper Car" ], "rk-kart-giant-shoe": [ "uncommon", "g", "Giant Shoe" ], "rk-kart-banana": [ "epic", "g", "Banana" ], "rk-kart-rubber-duck": [ "epic", "g", "Rubber Duck" ], "rk-kart-couch": [ "rare", "g", "Couch" ], "rk-kart-bed": [ "rare", "g", "Bed" ], "rk-kart-toilet": [ "rare", "g", "Toilet" ], "rk-kart-pumpkin-carriage": [ "legendary", "g", "Pumpkin Carriage" ], "rk-kart-ice-cream-truck": [ "epic", "g", "Ice Cream Truck" ], "rk-kart-rocket-sled": [ "legendary", "g", "Rocket Sled" ], "rk-kart-cardboard-box": [ "common", "g", "Cardboard Box" ], "rk-wheels-chrome-spokes": [ "common", "g", "Chrome Spokes" ], "rk-wheels-monster-treads": [ "uncommon", "g", "Monster Treads" ], "rk-wheels-wagon-wheels": [ "common", "g", "Wagon Wheels" ], "rk-wheels-donut-wheels": [ "epic", "g", "Donut Wheels" ], "rk-wheels-whitewalls": [ "common", "g", "Whitewalls" ], "rk-wheels-golden-stars": [ "uncommon", "g", "Golden Stars" ], "rk-wheels-peppermint-swirls": [ "rare", "g", "Peppermint Swirls" ], "rk-wheels-button-wheels": [ "common", "g", "Button Wheels" ], "rk-horn-goose-honk": [ "uncommon", "g", "Goose Honk" ], "rk-horn-clown-horn": [ "common", "g", "Clown Horn" ], "rk-horn-air-horn": [ "epic", "g", "Air Horn" ], "rk-horn-kazoo": [ "rare", "g", "Kazoo" ], "rk-horn-bike-bell": [ "common", "g", "Bike Bell" ], "rk-wreck-confetti-pop": [ "uncommon", "g", "Confetti Pop" ], "rk-wreck-feather-poof": [ "uncommon", "g", "Feather Poof" ], "rk-wreck-bubble-burst": [ "common", "g", "Bubble Burst" ], "rk-wreck-jelly-splat": [ "rare", "g", "Jelly Splat" ], "rk-wreck-nuts-and-bolts": [ "common", "g", "Nuts and Bolts" ], "rk-wreck-fireworks": [ "epic", "g", "Fireworks" ], "rk-wreck-popcorn": [ "rare", "g", "Popcorn" ], "rk-wreck-snow-globe": [ "epic", "g", "Snow Globe" ], "tt-colour-red": [ "common", "g", "Red" ], "tt-colour-orange": [ "common", "g", "Orange" ], "tt-colour-yellow": [ "common", "g", "Yellow" ], "tt-colour-lime": [ "common", "g", "Lime" ], "tt-colour-teal": [ "common", "g", "Teal" ], "tt-colour-sky-blue": [ "common", "g", "Sky Blue" ], "tt-colour-purple": [ "common", "g", "Purple" ], "tt-colour-pink": [ "common", "g", "Pink" ], "tt-colour-white": [ "common", "g", "White" ], "tt-colour-black": [ "common", "g", "Black" ], "tt-premium-gold": [ "epic", "g", "Gold" ], "tt-premium-chrome": [ "epic", "g", "Chrome" ], "tt-premium-glow-in-the-dark": [ "uncommon", "g", "Glow in the Dark" ], "tt-premium-see-through-jelly": [ "uncommon", "g", "See-through Jelly" ], "tt-premium-rainbow-shift": [ "legendary", "g", "Rainbow Shift" ], "tt-premium-bubblegum-sprinkles": [ "rare", "g", "Bubblegum Sprinkles" ], "tt-pattern-polka-dots": [ "common", "g", "Polka Dots" ], "tt-pattern-stripes": [ "common", "g", "Stripes" ], "tt-pattern-cow-print": [ "uncommon", "g", "Cow Print" ], "tt-pattern-tie-dye": [ "uncommon", "g", "Tie-Dye" ], "tt-pattern-checkerboard": [ "common", "g", "Checkerboard" ], "tt-pattern-leopard": [ "rare", "g", "Leopard" ], "tt-pattern-camo": [ "common", "g", "Camo" ], "tt-pattern-plaid": [ "common", "g", "Plaid" ], "tt-pattern-watermelon": [ "rare", "g", "Watermelon" ], "tt-pants-heart-boxers": [ "common", "g", "Heart Boxers" ], "tt-pants-tighty-whities": [ "common", "g", "Tighty Whities" ], "tt-pants-polka-dot-briefs": [ "common", "g", "Polka Dot Briefs" ], "tt-pants-banana-boxers": [ "uncommon", "g", "Banana Boxers" ], "tt-pants-leopard-print": [ "uncommon", "g", "Leopard Print" ], "tt-pants-long-johns": [ "rare", "g", "Long Johns" ], "tt-pants-diaper": [ "rare", "g", "Diaper" ], "tt-pants-super-undies": [ "epic", "g", "Super Undies" ], "tt-pants-undies-on-head": [ "epic", "g", "Undies on Head" ], "tt-hat-traffic-cone": [ "common", "g", "Traffic Cone" ], "tt-hat-propeller-beanie": [ "uncommon", "g", "Propeller Beanie" ], "tt-hat-chef-hat": [ "common", "g", "Chef Hat" ], "tt-hat-crown": [ "epic", "g", "Crown" ], "tt-hat-pirate-hat": [ "uncommon", "g", "Pirate Hat" ], "tt-hat-viking-helmet": [ "uncommon", "g", "Viking Helmet" ], "tt-hat-cowboy-hat": [ "common", "g", "Cowboy Hat" ], "tt-hat-plunger": [ "rare", "g", "Plunger" ], "tt-hat-fishbowl": [ "epic", "g", "Fishbowl" ], "tt-hat-cooking-pot": [ "common", "g", "Cooking Pot" ], "tt-hat-birthday-cone": [ "common", "g", "Birthday Cone" ], "tt-hat-rubber-duck": [ "rare", "g", "Rubber Duck" ], "tt-hat-toilet-paper-roll": [ "rare", "g", "Toilet Paper Roll" ], "tt-hat-tiny-top-hat": [ "common", "g", "Tiny Top Hat" ], "tt-face-mustache": [ "common", "g", "Mustache" ], "tt-face-monocle": [ "uncommon", "g", "Monocle" ], "tt-face-googly-eyes": [ "common", "g", "Googly Eyes" ], "tt-face-unibrow": [ "common", "g", "Unibrow" ], "tt-face-braces": [ "common", "g", "Braces" ], "tt-face-sunglasses": [ "rare", "g", "Sunglasses" ], "tt-costume-hot-dog": [ "epic", "g", "Hot Dog" ], "tt-costume-banana": [ "epic", "g", "Banana" ], "tt-costume-pickle": [ "epic", "g", "Pickle" ], "tt-costume-chicken": [ "epic", "g", "Chicken" ], "tt-costume-dinosaur-onesie": [ "epic", "g", "Dinosaur Onesie" ], "tt-costume-shark": [ "epic", "g", "Shark" ], "tt-costume-cactus": [ "epic", "g", "Cactus" ], "tt-costume-sushi-roll": [ "epic", "g", "Sushi Roll" ], "tt-costume-astronaut": [ "epic", "g", "Astronaut" ], "tt-costume-knight": [ "epic", "g", "Knight" ], "tt-costume-toilet-paper-mummy": [ "epic", "g", "Toilet Paper Mummy" ], "tt-costume-turkey": [ "epic", "g", "Turkey" ], "tt-dance-wiggle-wobble": [ "uncommon", "g", "Wiggle Wobble" ], "tt-dance-robot": [ "uncommon", "g", "Robot" ], "tt-dance-spin-cycle": [ "uncommon", "g", "Spin Cycle" ], "tt-dance-chicken-flap": [ "rare", "g", "Chicken Flap" ], "tt-dance-jelly-jump": [ "epic", "g", "Jelly Jump" ], "tt-dance-disco-point": [ "rare", "g", "Disco Point" ], "tt-scream-wheee": [ "common", "g", "Wheee!" ], "tt-scream-aaaah": [ "common", "g", "Aaaah!" ], "tt-scream-yodel-drop": [ "common", "g", "Yodel Drop" ], "tt-scream-slide-whistle": [ "common", "g", "Slide Whistle" ], "tt-scream-kazoo-wail": [ "common", "g", "Kazoo Wail" ], "tt-scream-squeaky-toy": [ "common", "g", "Squeaky Toy" ], "tt-splash-confetti-pop": [ "uncommon", "g", "Confetti Pop" ], "tt-splash-bubble-burst": [ "uncommon", "g", "Bubble Burst" ], "tt-splash-rainbow-splat": [ "rare", "g", "Rainbow Splat" ], "tt-splash-star-shower": [ "rare", "g", "Star Shower" ], "tt-splash-glitter-geyser": [ "epic", "g", "Glitter Geyser" ], "sc-egg-white-egg": [ "common", "g", "White Egg" ], "sc-egg-brown-egg": [ "common", "g", "Brown Egg" ], "sc-egg-speckled-quail": [ "common", "g", "Speckled Quail" ], "sc-egg-robin-blue": [ "common", "g", "Robin Blue" ], "sc-egg-ostrich-egg": [ "uncommon", "g", "Ostrich Egg" ], "sc-egg-emu-egg": [ "uncommon", "g", "Emu Egg" ], "sc-egg-rotten-egg": [ "uncommon", "g", "Rotten Egg" ], "sc-egg-golden-egg": [ "epic", "g", "Golden Egg" ], "sc-egg-painted-easter-egg": [ "rare", "g", "Painted Easter Egg" ], "sc-egg-chocolate-egg": [ "epic", "g", "Chocolate Egg" ], "sc-egg-hard-boiled": [ "rare", "g", "Hard-Boiled" ], "sc-egg-century-egg": [ "epic", "g", "Century Egg" ], "sc-egg-dinosaur-egg": [ "epic", "g", "Dinosaur Egg" ], "sc-egg-dragon-egg": [ "legendary", "g", "Dragon Egg" ], "sc-egg-alien-egg": [ "legendary", "g", "Alien Egg" ], "sc-egg-jeweled-egg": [ "legendary", "g", "Jeweled Egg" ], "sc-egg-disco-ball": [ "legendary", "g", "Disco Ball" ], "sc-egg-pixel-egg": [ "epic", "g", "Pixel Egg" ], "sc-egg-bandaged-egg": [ "rare", "g", "Bandaged Egg" ], "sc-hat-eggcup-crown": [ "epic", "g", "Eggcup Crown" ], "sc-hat-frying-pan": [ "common", "g", "Frying Pan" ], "sc-hat-nest": [ "uncommon", "g", "Nest" ], "sc-hat-chef-hat": [ "common", "g", "Chef Hat" ], "sc-hat-bacon-headband": [ "uncommon", "g", "Bacon Headband" ], "sc-hat-baby-chick": [ "epic", "g", "Baby Chick" ], "sc-hat-sunny-side-up-beret": [ "rare", "g", "Sunny-Side-Up Beret" ], "sc-gun-cast-iron": [ "common", "g", "Cast Iron" ], "sc-gun-gold-plated": [ "epic", "g", "Gold Plated" ], "sc-gun-egg-carton": [ "common", "g", "Egg Carton" ], "sc-gun-yolk-drip": [ "uncommon", "g", "Yolk Drip" ], "sc-gun-bacon-wrap": [ "uncommon", "g", "Bacon Wrap" ], "sc-gun-ketchup-and-mustard": [ "common", "g", "Ketchup and Mustard" ], "sc-gun-hot-sauce": [ "uncommon", "g", "Hot Sauce" ], "sc-gun-toaster-chrome": [ "epic", "g", "Toaster Chrome" ], "sc-gun-candy-stripe": [ "common", "g", "Candy Stripe" ], "sc-gun-whisk-barrel": [ "rare", "g", "Whisk Barrel" ], "sc-gun-wooden-spoon-stock": [ "rare", "g", "Wooden Spoon Stock" ], "sc-gun-rubber-chicken": [ "legendary", "g", "Rubber Chicken" ], "sc-crack-fried-egg": [ "common", "g", "Fried Egg" ], "sc-crack-scrambled": [ "uncommon", "g", "Scrambled" ], "sc-crack-chick-hatches": [ "epic", "g", "Chick Hatches" ], "sc-crack-shell-confetti": [ "rare", "g", "Shell Confetti" ], "sc-crack-stink-puff": [ "common", "g", "Stink Puff" ], "ar-alien-little-green": [ "common", "g", "Little Green" ], "ar-alien-one-eyed-blob": [ "common", "g", "One-Eyed Blob" ], "ar-alien-three-eyed-guy": [ "common", "g", "Three-Eyed Guy" ], "ar-alien-tentacle-squid": [ "uncommon", "g", "Tentacle Squid" ], "ar-alien-slime-cube": [ "uncommon", "g", "Slime Cube" ], "ar-alien-fuzzy-furball": [ "common", "g", "Fuzzy Furball" ], "ar-alien-crystal-alien": [ "epic", "g", "Crystal Alien" ], "ar-alien-mushroom-alien": [ "uncommon", "g", "Mushroom Alien" ], "ar-alien-jellyfish": [ "rare", "g", "Jellyfish" ], "ar-alien-cat-alien": [ "epic", "g", "Cat Alien" ], "ar-alien-potato-alien": [ "common", "g", "Potato Alien" ], "ar-alien-star-alien": [ "rare", "g", "Star Alien" ], "ar-alien-eyeball-with-legs": [ "epic", "g", "Eyeball with Legs" ], "ar-alien-brain-in-a-jar": [ "epic", "g", "Brain in a Jar" ], "ar-alien-robot-suit-pilot": [ "legendary", "g", "Robot Suit Pilot" ], "ar-alien-mustache-disguise": [ "legendary", "g", "Mustache Disguise" ], "ar-alien-escaped-cow": [ "legendary", "g", "Escaped Cow" ], "ar-alien-astronaut-hamster": [ "epic", "g", "Astronaut Hamster" ], "ar-alien-retro-robot": [ "rare", "g", "Retro Robot" ], "ar-trail-stardust": [ "common", "g", "Stardust" ], "ar-trail-slime-drips": [ "common", "g", "Slime Drips" ], "ar-trail-bubbles": [ "common", "g", "Bubbles" ], "ar-trail-hearts": [ "uncommon", "g", "Hearts" ], "ar-trail-confetti": [ "uncommon", "g", "Confetti" ], "ar-trail-pixels": [ "rare", "g", "Pixels" ], "ar-trail-snowflakes": [ "common", "g", "Snowflakes" ], "ar-trail-petals": [ "rare", "g", "Petals" ], "ar-trail-zaps": [ "epic", "g", "Zaps" ], "ar-trail-tractor-rings": [ "epic", "g", "Tractor Rings" ], "ar-tunnel-deep-blue": [ "common", "g", "Deep Blue" ], "ar-tunnel-silver": [ "common", "g", "Silver" ], "ar-tunnel-bubblegum": [ "uncommon", "g", "Bubblegum" ], "ar-tunnel-ultraviolet": [ "uncommon", "g", "Ultraviolet" ], "ar-tunnel-ocean": [ "common", "g", "Ocean" ], "ar-tunnel-moon-dust": [ "rare", "g", "Moon Dust" ], "ar-tunnel-treasure": [ "epic", "g", "Treasure" ], "ar-tunnel-checkerboard": [ "epic", "g", "Checkerboard" ], "ar-tunnel-candy-checker": [ "epic", "g", "Candy Checker" ], "ar-tunnel-prism": [ "legendary", "g", "Prism" ], "rl-car-muscle-car": [ "common", "g", "Muscle Car" ], "rl-car-rally-hatch": [ "common", "g", "Rally Hatch" ], "rl-car-hot-rod": [ "uncommon", "g", "Hot Rod" ], "rl-car-pickup": [ "common", "g", "Pickup" ], "rl-car-dune-buggy": [ "common", "g", "Dune Buggy" ], "rl-car-monster-truck": [ "epic", "g", "Monster Truck" ], "rl-car-retro-wedge": [ "uncommon", "g", "Retro Wedge" ], "rl-car-go-kart": [ "common", "g", "Go-Kart" ], "rl-car-limo": [ "uncommon", "g", "Limo" ], "rl-car-school-bus": [ "uncommon", "g", "School Bus" ], "rl-car-taxi": [ "common", "g", "Taxi" ], "rl-car-police-cruiser": [ "uncommon", "g", "Police Cruiser" ], "rl-car-fire-truck": [ "epic", "g", "Fire Truck" ], "rl-car-ice-cream-truck": [ "epic", "g", "Ice Cream Truck" ], "rl-car-garbage-truck": [ "rare", "g", "Garbage Truck" ], "rl-car-tractor": [ "rare", "g", "Tractor" ], "rl-car-golf-cart": [ "common", "g", "Golf Cart" ], "rl-car-lunar-rover": [ "epic", "g", "Lunar Rover" ], "rl-car-wooden-toy": [ "rare", "g", "Wooden Toy" ], "rl-car-wind-up-car": [ "epic", "g", "Wind-Up Car" ], "rl-car-rc-car": [ "rare", "g", "RC Car" ], "rl-car-soapbox-crate": [ "rare", "g", "Soapbox Crate" ], "rl-car-cardboard-box": [ "common", "g", "Cardboard Box" ], "rl-car-shopping-cart": [ "epic", "g", "Shopping Cart" ], "rl-car-bathtub": [ "epic", "g", "Bathtub" ], "rl-car-couch": [ "epic", "g", "Couch" ], "rl-car-hot-dog": [ "epic", "g", "Hot Dog" ], "rl-car-banana": [ "epic", "g", "Banana" ], "rl-car-rubber-duck": [ "legendary", "g", "Rubber Duck" ], "rl-car-giant-shoe": [ "legendary", "g", "Giant Shoe" ], "rl-car-rocket-car": [ "legendary", "g", "Rocket Car" ], "rl-paint-candy-apple-paint": [ "common", "g", "Candy Apple Paint" ], "rl-paint-tangerine-paint": [ "common", "g", "Tangerine Paint" ], "rl-paint-lemon-drop-paint": [ "common", "g", "Lemon Drop Paint" ], "rl-paint-lime-fizz-paint": [ "common", "g", "Lime Fizz Paint" ], "rl-paint-mint-paint": [ "common", "g", "Mint Paint" ], "rl-paint-teal-paint": [ "common", "g", "Teal Paint" ], "rl-paint-sky-paint": [ "common", "g", "Sky Paint" ], "rl-paint-midnight-paint": [ "common", "g", "Midnight Paint" ], "rl-paint-lavender-paint": [ "common", "g", "Lavender Paint" ], "rl-paint-grape-paint": [ "common", "g", "Grape Paint" ], "rl-paint-bubblegum-paint": [ "common", "g", "Bubblegum Paint" ], "rl-paint-magenta-paint": [ "common", "g", "Magenta Paint" ], "rl-paint-copper-paint": [ "uncommon", "g", "Copper Paint" ], "rl-paint-sand-paint": [ "common", "g", "Sand Paint" ], "rl-paint-gold-paint": [ "uncommon", "g", "Gold Paint" ], "rl-paint-silver-paint": [ "rare", "g", "Silver Paint" ], "rl-wheels-whitewalls": [ "common", "g", "Whitewalls" ], "rl-wheels-wire-spokes": [ "uncommon", "g", "Wire Spokes" ], "rl-wheels-gold-star": [ "uncommon", "g", "Gold Star" ], "rl-wheels-off-road": [ "common", "g", "Off-Road" ], "rl-wheels-neon-rings": [ "epic", "g", "Neon Rings" ], "rl-wheels-wooden": [ "uncommon", "g", "Wooden" ], "rl-wheels-red-steelies": [ "common", "g", "Red Steelies" ], "rl-wheels-turbine": [ "rare", "g", "Turbine" ], "rl-wheels-candy-swirl": [ "rare", "g", "Candy Swirl" ], "rl-wheels-flower-caps": [ "rare", "g", "Flower Caps" ], "rl-wheels-race-slicks": [ "common", "g", "Race Slicks" ], "rl-wheels-rainbow-rings": [ "epic", "g", "Rainbow Rings" ], "rl-smoke-pink-tyre-smoke": [ "common", "g", "Pink Tyre Smoke" ], "rl-smoke-sky-blue-tyre-smoke": [ "common", "g", "Sky Blue Tyre Smoke" ], "rl-smoke-lime-tyre-smoke": [ "common", "g", "Lime Tyre Smoke" ], "rl-smoke-purple-tyre-smoke": [ "common", "g", "Purple Tyre Smoke" ], "rl-smoke-gold-tyre-smoke": [ "common", "g", "Gold Tyre Smoke" ], "rl-smoke-orange-tyre-smoke": [ "common", "g", "Orange Tyre Smoke" ], "rl-smoke-red-tyre-smoke": [ "common", "g", "Red Tyre Smoke" ], "rl-smoke-mint-tyre-smoke": [ "common", "g", "Mint Tyre Smoke" ], "rl-smoke-rainbow-tyre-smoke": [ "epic", "g", "Rainbow Tyre Smoke" ], "rl-smoke-confetti-tyre-smoke": [ "epic", "g", "Confetti Tyre Smoke" ], "rl-horn-beep-beep": [ "common", "g", "Beep Beep" ], "rl-horn-clown-honk": [ "uncommon", "g", "Clown Honk" ], "rl-horn-air-horn": [ "uncommon", "g", "Air Horn" ], "rl-horn-little-tune": [ "uncommon", "g", "Little Tune" ], "rl-horn-duck-quack": [ "epic", "g", "Duck Quack" ], "rl-horn-bike-bell": [ "common", "g", "Bike Bell" ], "rl-horn-squeaky-toy": [ "rare", "g", "Squeaky Toy" ], "rl-horn-space-zap": [ "epic", "g", "Space Zap" ], "rl-horn-foghorn": [ "rare", "g", "Foghorn" ], "rl-horn-ice-cream-jingle": [ "epic", "g", "Ice Cream Jingle" ], "rl-horn-train-whistle": [ "rare", "g", "Train Whistle" ], "cf-hat-detective-deerstalker": [ "uncommon", "g", "Detective Deerstalker" ], "cf-hat-safari-hat": [ "common", "g", "Safari Hat" ], "cf-hat-painter-s-beret": [ "common", "g", "Painter's Beret" ], "cf-hat-museum-guard-cap": [ "common", "g", "Museum Guard Cap" ], "cf-hat-hard-hat": [ "common", "g", "Hard Hat" ], "cf-hat-exterminator-cap": [ "rare", "g", "Exterminator Cap" ], "cf-hat-goggles": [ "common", "g", "Goggles" ], "cf-tool-magnifying-glass": [ "uncommon", "g", "Magnifying Glass" ], "cf-tool-paint-scraper": [ "common", "g", "Paint Scraper" ], "cf-tool-spray-bottle": [ "common", "g", "Spray Bottle" ], "cf-tool-feather-duster": [ "rare", "g", "Feather Duster" ], "cf-splash-paint-splash": [ "epic", "g", "Paint Splash" ], "cf-caught-surprise-spin": [ "epic", "g", "Surprise Spin" ], "oo-outfit-police-officer": [ "common", "g", "Police Officer" ], "oo-outfit-sheriff": [ "uncommon", "g", "Sheriff" ], "oo-outfit-mall-cop": [ "common", "g", "Mall Cop" ], "oo-outfit-security-guard": [ "common", "g", "Security Guard" ], "oo-outfit-detective": [ "uncommon", "g", "Detective" ], "oo-outfit-store-manager": [ "common", "g", "Store Manager" ], "oo-outfit-janitor": [ "common", "g", "Janitor" ], "oo-outfit-park-ranger": [ "uncommon", "g", "Park Ranger" ], "oo-outfit-exterminator": [ "rare", "g", "Exterminator" ], "oo-outfit-construction-worker": [ "common", "g", "Construction Worker" ], "oo-outfit-cowboy": [ "rare", "g", "Cowboy" ], "oo-outfit-pirate": [ "epic", "g", "Pirate" ], "oo-outfit-top-hat": [ "epic", "g", "Top Hat" ], "oo-outfit-traffic-cone": [ "legendary", "g", "Traffic Cone" ], "oo-tool-flashlight": [ "common", "g", "Flashlight" ], "oo-tool-price-scanner": [ "uncommon", "g", "Price Scanner" ], "oo-tool-flyswatter": [ "common", "g", "Flyswatter" ], "oo-tool-butterfly-net": [ "rare", "g", "Butterfly Net" ], "oo-tool-broom": [ "common", "g", "Broom" ], "oo-tool-rubber-chicken": [ "epic", "g", "Rubber Chicken" ], "oo-taunt-bike-horn": [ "common", "g", "Bike Horn" ], "oo-taunt-squeaky-duck": [ "common", "g", "Squeaky Duck" ], "oo-taunt-slide-whistle": [ "common", "g", "Slide Whistle" ], "oo-taunt-boing": [ "common", "g", "Boing" ], "oo-taunt-cuckoo": [ "uncommon", "g", "Cuckoo" ], "oo-taunt-kazoo": [ "uncommon", "g", "Kazoo" ], "oo-taunt-doorbell": [ "rare", "g", "Doorbell" ], "oo-taunt-party-blower": [ "epic", "g", "Party Blower" ], "oo-poof-cloud-poof": [ "common", "g", "Cloud Poof" ], "oo-poof-feather-poof": [ "uncommon", "g", "Feather Poof" ], "oo-poof-bubble-poof": [ "rare", "g", "Bubble Poof" ], "oo-poof-star-poof": [ "epic", "g", "Star Poof" ], "oo-poof-price-tag-poof": [ "epic", "g", "Price Tag Poof" ], "dz-outfit-jet-pilot": [ "uncommon", "g", "Jet Pilot" ], "dz-outfit-lumberjack": [ "common", "g", "Lumberjack" ], "dz-outfit-park-ranger": [ "common", "g", "Park Ranger" ], "dz-outfit-scuba-diver": [ "uncommon", "g", "Scuba Diver" ], "dz-outfit-head-chef": [ "uncommon", "g", "Head Chef" ], "dz-outfit-hazmat-suit": [ "uncommon", "g", "Hazmat Suit" ], "dz-outfit-castle-knight": [ "epic", "g", "Castle Knight" ], "dz-outfit-astronaut": [ "epic", "g", "Astronaut" ], "dz-outfit-farmer": [ "common", "g", "Farmer" ], "dz-outfit-mail-carrier": [ "common", "g", "Mail Carrier" ], "dz-outfit-lifeguard": [ "common", "g", "Lifeguard" ], "dz-outfit-ninja": [ "rare", "g", "Ninja" ], "dz-outfit-scarecrow": [ "rare", "g", "Scarecrow" ], "dz-outfit-skeleton": [ "rare", "g", "Skeleton" ], "dz-outfit-banana-suit": [ "epic", "g", "Banana Suit" ], "dz-outfit-cardboard-box-robot": [ "epic", "g", "Cardboard Box Robot" ], "dz-pack-rucksack": [ "common", "g", "Rucksack" ], "dz-pack-jetpack": [ "epic", "g", "Jetpack" ], "dz-pack-teddy-bear": [ "uncommon", "g", "Teddy Bear" ], "dz-pack-tortoise-shell": [ "uncommon", "g", "Tortoise Shell" ], "dz-pack-treasure-chest": [ "epic", "g", "Treasure Chest" ], "dz-pack-lunchbox": [ "common", "g", "Lunchbox" ], "dz-pack-guitar-case": [ "rare", "g", "Guitar Case" ], "dz-pack-fishbowl": [ "epic", "g", "Fishbowl" ], "dz-glider-umbrella": [ "common", "g", "Umbrella" ], "dz-glider-paper-airplane": [ "common", "g", "Paper Airplane" ], "dz-glider-hang-glider": [ "uncommon", "g", "Hang Glider" ], "dz-glider-kite": [ "common", "g", "Kite" ], "dz-glider-bedsheet-parachute": [ "common", "g", "Bedsheet Parachute" ], "dz-glider-trash-bag-parachute": [ "common", "g", "Trash Bag Parachute" ], "dz-glider-cardboard-wings": [ "common", "g", "Cardboard Wings" ], "dz-glider-dragon-wings": [ "epic", "g", "Dragon Wings" ], "dz-glider-bat-wings": [ "uncommon", "g", "Bat Wings" ], "dz-glider-bunch-of-balloons": [ "uncommon", "g", "Bunch of Balloons" ], "dz-glider-lawn-chair-with-balloons": [ "epic", "g", "Lawn Chair with Balloons" ], "dz-glider-magic-carpet": [ "epic", "g", "Magic Carpet" ], "dz-glider-picnic-blanket": [ "uncommon", "g", "Picnic Blanket" ], "dz-glider-surfboard": [ "rare", "g", "Surfboard" ], "dz-glider-pizza-slice": [ "rare", "g", "Pizza Slice" ], "dz-glider-broomstick": [ "epic", "g", "Broomstick" ], "dz-glider-giant-leaf": [ "common", "g", "Giant Leaf" ], "dz-glider-spinning-maple-seed": [ "rare", "g", "Spinning Maple Seed" ], "dz-glider-rubber-duck-float": [ "rare", "g", "Rubber Duck Float" ], "dz-glider-giant-pigeon": [ "legendary", "g", "Giant Pigeon" ], "dz-glider-pterodactyl": [ "legendary", "g", "Pterodactyl" ], "dz-glider-flying-squirrel-suit": [ "epic", "g", "Flying Squirrel Suit" ], "dz-glider-ufo-disc": [ "legendary", "g", "UFO Disc" ], "dz-glider-small-cloud": [ "epic", "g", "Small Cloud" ], "dz-trail-smoke": [ "common", "g", "Smoke" ], "dz-trail-sparkles": [ "uncommon", "g", "Sparkles" ], "dz-trail-rainbow": [ "epic", "g", "Rainbow" ], "dz-trail-feathers": [ "common", "g", "Feathers" ], "dz-trail-leaves": [ "common", "g", "Leaves" ], "dz-trail-bubbles": [ "rare", "g", "Bubbles" ], "dz-wrap-gold": [ "legendary", "g", "Gold" ], "dz-wrap-chrome": [ "epic", "g", "Chrome" ], "dz-wrap-wood-grain": [ "common", "g", "Wood Grain" ], "dz-wrap-forest-camo": [ "common", "g", "Forest Camo" ], "dz-wrap-desert-camo": [ "common", "g", "Desert Camo" ], "dz-wrap-arctic-camo": [ "common", "g", "Arctic Camo" ], "dz-wrap-pixel-camo": [ "uncommon", "g", "Pixel Camo" ], "dz-wrap-neon-outline": [ "epic", "g", "Neon Outline" ], "dz-wrap-toy-blaster": [ "uncommon", "g", "Toy Blaster" ], "dz-wrap-cardboard": [ "common", "g", "Cardboard" ], "dz-wrap-candy-cane": [ "uncommon", "g", "Candy Cane" ], "dz-wrap-lava": [ "epic", "g", "Lava" ], "dz-wrap-ice": [ "rare", "g", "Ice" ], "dz-wrap-galaxy": [ "epic", "g", "Galaxy" ], "dz-wrap-rust": [ "common", "g", "Rust" ], "dz-wrap-graffiti": [ "rare", "g", "Graffiti" ], "dz-wrap-bubblegum-pink": [ "common", "g", "Bubblegum Pink" ], "dz-wrap-hazard-stripes": [ "rare", "g", "Hazard Stripes" ], "dz-wrap-plastic-brick": [ "epic", "g", "Plastic Brick" ], "dz-build-cardboard": [ "common", "g", "Cardboard" ], "dz-build-frosted-glass": [ "uncommon", "g", "Frosted Glass" ], "dz-build-ice": [ "uncommon", "g", "Ice" ], "dz-build-candy": [ "epic", "g", "Candy" ], "dz-build-stone": [ "common", "g", "Stone" ], "dz-build-scrap-metal": [ "rare", "g", "Scrap Metal" ], "dz-emote-wave": [ "common", "g", "Wave" ], "dz-emote-dance": [ "uncommon", "g", "Dance" ], "dz-emote-clap": [ "common", "g", "Clap" ], "dz-emote-jumping-jacks": [ "common", "g", "Jumping Jacks" ], "dz-emote-robot": [ "uncommon", "g", "Robot" ], "dz-emote-twirl": [ "rare", "g", "Twirl" ], "dz-victory-champion": [ "epic", "g", "Champion" ], "dz-victory-flex": [ "uncommon", "g", "Flex" ], "dz-victory-take-a-bow": [ "rare", "g", "Take a Bow" ], "dz-victory-jump-for-joy": [ "epic", "g", "Jump for Joy" ] }, "PACKS": {"draw-1": {"kind": "draws", "name": "One chest", "price": 119, "contents": {"draws": 1 } }, "draw-5": {"kind": "draws", "name": "Five chests", "price": 595, "contents": {"draws": 5 } }, "draw-10": {"kind": "draws", "name": "Ten chests", "price": 1190, "contents": {"draws": 10 } }, "skins-space": {"kind": "skins", "name": "Launch Bay", "price": 179, "contents": {"items": [ "moon-walker", "comet-courier" ] } }, "skins-ocean": {"kind": "skins", "name": "Deep End", "price": 179, "contents": {"items": [ "tide-pool", "coral-diver" ] } }, "skins-neon": {"kind": "skins", "name": "After Dark", "price": 179, "contents": {"items": [ "neon-jogger", "grid-runner" ] } }, "skins-candy": {"kind": "skins", "name": "Sweet Tooth", "price": 239, "contents": {"items": [ "bubblegum", "sprinkle-pop", "gumdrop-knight" ] } }, "skins-robot": {"kind": "skins", "name": "Workshop", "price": 480, "contents": {"items": [ "tin-tinker", "circuit-scout" ] } }, "skins-animals": {"kind": "skins", "name": "Wild Things", "price": 600, "contents": {"items": [ "tabby", "cub", "hopper", "red-fox" ] } }, "skins-seasons": {"kind": "skins", "name": "All Year Round", "price": 960, "contents": {"items": [ "spring-sprout", "summer-sun", "autumn-ember", "winter-frost" ] } }, "skins-wild": {"kind": "skins", "name": "Far Lands", "price": 480, "contents": {"items": [ "dune-rover", "magma-walker" ] } }, "acc-hats": {"kind": "accessories", "name": "Hat Box", "price": 719, "contents": {"items": [ "pom-beanie", "wizard-cone", "propeller-cap", "tall-topper", "daisy-crown" ] } }, "acc-glasses": {"kind": "accessories", "name": "Eyewear Case", "price": 1199, "contents": {"items": [ "star-shades", "heart-specs", "monocle", "glow-visor" ] } }, "acc-capes": {"kind": "accessories", "name": "Cape Rack", "price": 779, "contents": {"items": [ "hero-cape", "galaxy-cape", "leaf-cloak" ] } }, "acc-trails": {"kind": "accessories", "name": "Trail Kit", "price": 779, "contents": {"items": [ "sparkle-trail", "bubble-trail", "rainbow-streak" ] } }, "acc-auras": {"kind": "accessories", "name": "Glow Jar", "price": 1139, "contents": {"items": [ "halo-glow", "ember-aura", "frost-ring" ] } }, "acc-pets": {"kind": "accessories", "name": "Pet Carrier", "price": 839, "contents": {"items": [ "pocket-slime", "mini-bot", "star-buddy", "ghost-pup" ] } }, "acc-drake": {"kind": "accessories", "name": "Dragon Egg", "price": 1200, "contents": {"items": [ "baby-drake" ] } }, "bb-decals-speed": {"kind": "items", "name": "Speed Shop", "price": 300, "contents": {"items": [ "bb-decal-flames", "bb-decal-racing-stripes", "bb-decal-lightning-bolts", "bb-decal-checkered-flag", "bb-decal-carbon-fiber" ] } }, "bb-decals-wild": {"kind": "items", "name": "Wild Side", "price": 837, "contents": {"items": [ "bb-decal-shark-mouth", "bb-decal-tiger-stripes", "bb-decal-dragon-scales", "bb-decal-cow-print", "bb-decal-skeleton-ribs" ] } }, "bb-decals-tech": {"kind": "items", "name": "Late Night", "price": 1318, "contents": {"items": [ "bb-decal-galaxy", "bb-decal-constellations", "bb-decal-circuit-board", "bb-decal-wireframe", "bb-decal-pixel-camo" ] } }, "bb-decals-art": {"kind": "items", "name": "Art Class", "price": 899, "contents": {"items": [ "bb-decal-graffiti-drips", "bb-decal-comic-book-dots", "bb-decal-topographic-lines", "bb-decal-stained-glass", "bb-decal-honeycomb" ] } }, "bb-decals-weather": {"kind": "items", "name": "Hot and Cold", "price": 1259, "contents": {"items": [ "bb-decal-lava-cracks", "bb-decal-frost", "bb-decal-autumn-leaves", "bb-decal-rust-bucket", "bb-decal-wood-paneling" ] } }, "bb-decals-jobs": {"kind": "items", "name": "Odd Jobs", "price": 1980, "contents": {"items": [ "bb-decal-duct-tape-patches", "bb-decal-donut-sprinkles", "bb-decal-bubble-wrap", "bb-decal-taxi", "bb-decal-police-cruiser", "bb-decal-ice-cream-truck" ] } }, "bb-trails-burn": {"kind": "items", "name": "Afterburners", "price": 1919, "contents": {"items": [ "bb-trail-classic-flame", "bb-trail-blue-plasma", "bb-trail-lightning", "bb-trail-lava", "bb-trail-water-jet", "bb-trail-laser-beam" ] } }, "bb-trails-party": {"kind": "items", "name": "Party Bag", "price": 1017, "contents": {"items": [ "bb-trail-rainbow", "bb-trail-confetti", "bb-trail-hearts", "bb-trail-music-notes", "bb-trail-sparkles" ] } }, "bb-trails-weather": {"kind": "items", "name": "Light and Fluffy", "price": 419, "contents": {"items": [ "bb-trail-bubbles", "bb-trail-snowflakes", "bb-trail-autumn-leaves", "bb-trail-feathers", "bb-trail-soap-suds", "bb-trail-smoke-rings" ] } }, "bb-trails-odd": {"kind": "items", "name": "Odds and Ends", "price": 2280, "contents": {"items": [ "bb-trail-popcorn", "bb-trail-rubber-ducks", "bb-trail-toast-slices", "bb-trail-dollar-bills", "bb-trail-slime" ] } }, "bb-trails-night": {"kind": "items", "name": "Night Shift", "price": 1920, "contents": {"items": [ "bb-trail-stardust", "bb-trail-pixel-blocks", "bb-trail-ink", "bb-trail-ones-and-zeros", "bb-trail-bats" ] } }, "bb-goals-bang": {"kind": "items", "name": "Big Bangs", "price": 2038, "contents": {"items": [ "bb-goal-fireworks", "bb-goal-supernova", "bb-goal-lightning-strike", "bb-goal-meteor", "bb-goal-volcano" ] } }, "bb-goals-party": {"kind": "items", "name": "Party Time", "price": 2339, "contents": {"items": [ "bb-goal-confetti-cannon", "bb-goal-disco-ball-drop", "bb-goal-pinata-burst", "bb-goal-popcorn-pop", "bb-goal-money-rain" ] } }, "bb-goals-science": {"kind": "items", "name": "Strange Science", "price": 2339, "contents": {"items": [ "bb-goal-black-hole", "bb-goal-tornado", "bb-goal-freeze-and-shatter", "bb-goal-pixel-shatter", "bb-goal-flock-of-birds" ] } }, "bb-goals-giant": {"kind": "items", "name": "Giant Trouble", "price": 5820, "contents": {"items": [ "bb-goal-giant-foot-stomp", "bb-goal-ufo-abduction", "bb-goal-shark-attack", "bb-goal-giant-airhorn", "bb-goal-pumpkin-splat", "bb-goal-goal-letters" ] } }, "bb-toppers": {"kind": "items", "name": "Aerial Shop", "price": 1319, "contents": {"items": [ "bb-topper-tennis-ball", "bb-topper-gold-star", "bb-topper-bath-duck", "bb-topper-mini-pumpkin", "bb-topper-pennant", "bb-topper-eyeball" ] } }, "bb-hats": {"kind": "items", "name": "Roof Rack", "price": 1378, "contents": {"items": [ "bb-hat-traffic-cone", "bb-hat-top-hat", "bb-hat-crown", "bb-hat-propeller-beanie", "bb-hat-cowboy-hat", "bb-hat-chef-hat" ] } }, "bb-wheels": {"kind": "items", "name": "Tyre Fitter", "price": 839, "contents": {"items": [ "bb-wheels-five-spoke", "bb-wheels-discs", "bb-wheels-cross", "bb-wheels-gold-rims" ] } }, "bb-engines": {"kind": "items", "name": "Under the Bonnet", "price": 1199, "contents": {"items": [ "bb-engine-purr", "bb-engine-buzz", "bb-engine-rumble", "bb-engine-whirr" ] } }, "ss-liveries-classic": {"kind": "items", "name": "Paint Shop", "price": 240, "contents": {"items": [ "ss-livery-two-tone-classic", "ss-livery-retro-stripes", "ss-livery-pastel", "ss-livery-checkered" ] } }, "ss-liveries-loud": {"kind": "items", "name": "Show Car", "price": 1258, "contents": {"items": [ "ss-livery-matte-black-with-neon", "ss-livery-chrome", "ss-livery-carbon", "ss-livery-flames" ] } }, "ss-helmets-fast": {"kind": "items", "name": "Helmet Rack", "price": 299, "contents": {"items": [ "ss-helmet-flames-helmet", "ss-helmet-checkered-helmet", "ss-helmet-lightning-helmet", "ss-helmet-chrome-visor" ] } }, "ss-helmets-wild": {"kind": "items", "name": "Wild Lids", "price": 1557, "contents": {"items": [ "ss-helmet-shark-helmet", "ss-helmet-skull-helmet", "ss-helmet-tiger-helmet", "ss-helmet-eyeball", "ss-helmet-cat-ears" ] } }, "ss-helmets-odd": {"kind": "items", "name": "Odd Lids", "price": 3660, "contents": {"items": [ "ss-helmet-galaxy-helmet", "ss-helmet-disco-ball", "ss-helmet-watermelon-helmet", "ss-helmet-eight-ball", "ss-helmet-pumpkin-helmet", "ss-helmet-pizza-helmet" ] } }, "ss-effects-air": {"kind": "items", "name": "Clean Air", "price": 299, "contents": {"items": [ "ss-effect-white-air-streaks", "ss-effect-vapor-trail", "ss-effect-flames", "ss-effect-sparks" ] } }, "ss-effects-show": {"kind": "items", "name": "Light Show", "price": 1739, "contents": {"items": [ "ss-effect-electric-arcs", "ss-effect-rainbow", "ss-effect-confetti", "ss-effect-purple-plasma" ] } }, "ss-extras": {"kind": "items", "name": "Pit Wall Party", "price": 479, "contents": {"items": [ "ss-smoke-pink-tyre-smoke", "ss-smoke-blue-tyre-smoke", "ss-smoke-green-tyre-smoke", "ss-smoke-purple-tyre-smoke", "ss-smoke-gold-tyre-smoke", "ss-podium-confetti-podium", "ss-podium-fireworks-podium" ] } } }, "EMERALDS": {"emeralds_7": {"name": "Emerald Handful", "emeralds": 7, "cents": 99, "currency": "usd" }, "emeralds_39": {"name": "Emerald Pouch", "emeralds": 39, "cents": 499, "currency": "usd" }, "emeralds_80": {"name": "Emerald Sack", "emeralds": 80, "cents": 999, "currency": "usd" }, "emeralds_180": {"name": "Emerald Chest", "emeralds": 180, "cents": 1999, "currency": "usd" }, "emeralds_1000": {"name": "Emerald Buttload", "emeralds": 1000, "cents": 4999, "currency": "usd" }, "emeralds_4000": {"name": "Emerald Vault", "emeralds": 4000, "cents": 9999, "currency": "usd" } } }; diff --git a/functions/_wallet.js b/functions/_wallet.js new file mode 100644 index 00000000..54321505 --- /dev/null +++ b/functions/_wallet.js @@ -0,0 +1,316 @@ +/* + * The emerald wallet's server side: the balance, what each player owns and every change to them live here, in + * Firestore, written only by these functions with the service account (functions/_lib.js has the secrets). The page + * (e63334287a3deaa3/wallet.js and cosmetics.js, when the server wallet is in use) only asks for them. + * + * wallets/{uid} balance (whole mangos), owned { item id: time got, ms }, recent [last 40 ledger lines, newest last: + * { t, d (change in mangos), b (balance after), w (why), r (ref) }], notices [gifts not yet seen: + * { id, t, from, what, note, got, refund }], reqs { request id: time } (the last 30, so a request + * sent twice is done once), created, updated + * ledger/{id} one row per change, never edited: uid, t, d, b, w, r, kind (emeralds | buy | chest | gift-out | + * gift-in | refund) + * orders/{session id} the shop's existing record of a paid Checkout; for emeralds it also says kind 'emeralds', + * mangos credited, and status 'mismatch' when the amount paid didn't match the pack (nothing credited) + * + * Every change is one Firestore transaction (read the wallet, check, debit, grant, write the ledger), retried when + * Firestore says another request changed the same wallet first, so double clicks and concurrent requests can't + * overspend or pay twice. Emeralds come only from the Stripe webhook (creditEmeralds), once per Checkout session. + * + * The numbers (prices, packs, chest odds, emerald packs) are in _catalog.js, generated from the browser files by + * e63334287a3deaa3/shop/tools/server-data.js; the captains are in _captains.js, generated from miles.js the same way. + * Captains are never charged, own everything and are never paid refunds or rewards. While wallet.js's + * PAYMENTS.enabled is false (CATALOG.PUBLIC), only captains may use any of this: the live captains' preview. + */ +import { DOCS, FS, googleToken, googleUser, json, cors } from './_lib.js'; +import { CATALOG } from './_catalog.js'; +import { OWNERS } from './_captains.js'; + +export { CATALOG }; +export const MPE = CATALOG.MANGOS_PER_EMERALD; +const RECENT_MAX = 40, NOTICE_MAX = 20, REQ_MAX = 30, MAX_BAL = 1e12; +export const UID_RE = /^[A-Za-z0-9_-]{6,128}$/; +const REQ_RE = /^[a-z0-9]{8,40}$/; +const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k); + +export class WErr extends Error { constructor(status, reason, message, extra) { super(message); this.status = status; this.reason = reason; this.extra = extra; } } + +export function isCaptain(uid) { return OWNERS.indexOf(uid) >= 0; } +// While PAYMENTS.enabled is false (the generated CATALOG.PUBLIC), only captains get in: the preview. +export function allowed(uid) { return !!CATALOG.PUBLIC || isCaptain(uid); } +// True while Cloudflare holds a Stripe test key (sandbox: no real money). The key itself never leaves the server. +export function testMode(env) { return /^(sk|rk)_test_/.test(String((env && env.STRIPE_SECRET_KEY) || '')); } + +// ---------- Firestore values ---------- +export function enc(v) { + if (v === null || v === undefined) return { nullValue: null }; + if (typeof v === 'boolean') return { booleanValue: v }; + if (typeof v === 'number') return Number.isInteger(v) ? { integerValue: String(v) } : { doubleValue: v }; + if (typeof v === 'string') return { stringValue: v }; + if (Array.isArray(v)) return { arrayValue: v.length ? { values: v.map(enc) } : {} }; + return { mapValue: { fields: encFields(v) } }; +} +export function encFields(o) { const f = {}; for (const k of Object.keys(o)) if (o[k] !== undefined) f[k] = enc(o[k]); return f; } +export function dec(v) { + if (!v || typeof v !== 'object') return null; + if ('integerValue' in v) return Number(v.integerValue); + if ('doubleValue' in v) return Number(v.doubleValue); + if ('stringValue' in v) return v.stringValue; + if ('booleanValue' in v) return !!v.booleanValue; + if ('timestampValue' in v) return v.timestampValue; + if ('arrayValue' in v) return ((v.arrayValue && v.arrayValue.values) || []).map(dec); + if ('mapValue' in v) return decFields((v.mapValue && v.mapValue.fields) || {}); + return null; +} +export function decFields(f) { const o = {}; for (const k of Object.keys(f || {})) o[k] = dec(f[k]); return o; } + +// ---------- The catalogue ---------- +const ITEMS = CATALOG.ITEMS, PRICE = CATALOG.PRICE; +export function itemName(id) { return has(ITEMS, id) ? ITEMS[id][2] : id; } +// A pack by id, or one item on its own as 'item:' at its rarity's price (items a game gives itself aren't sold). +export function pack(id) { + id = String(id || ''); + if (has(CATALOG.PACKS, id)) return Object.assign({ id }, CATALOG.PACKS[id]); + const m = /^item:(.{1,80})$/.exec(id), it = m && has(ITEMS, m[1]) ? ITEMS[m[1]] : null; + if (!it || it[3]) return null; + return { id, kind: 'one', name: it[2], price: PRICE[it[0]], contents: { items: [m[1]] } }; +} + +// ---------- Chest rolls: crypto randomness, the same unbiased roll as cosmetics.js ---------- +export function cryptoNext() { + const buf = new Uint32Array(256); let i = 256; + return () => { if (i >= 256) { crypto.getRandomValues(buf); i = 0; } return buf[i++]; }; +} +export function below(next, n) { + const lim = Math.floor(4294967296 / n) * n; let x; + do { x = next(); } while (x >= lim); + return x % n; +} +const BY_RARITY = {}; +CATALOG.RARITY.forEach(r => { BY_RARITY[r.id] = Object.keys(ITEMS).filter(id => ITEMS[id][1] === 's' && ITEMS[id][0] === r.id); }); +export function roll(next) { + const r = below(next, CATALOG.RARITY_TOTAL); let acc = 0, rar = CATALOG.RARITY[CATALOG.RARITY.length - 1]; + for (const x of CATALOG.RARITY) { acc += x.w; if (r < acc) { rar = x; break; } } + const list = BY_RARITY[rar.id]; + return { rarity: rar.id, skin: list[below(next, list.length)] }; +} +// Put what a pack holds into `owned` (opening chests here). -> { got: { skins, acc, items, draws }, dups, refund } +export function fill(owned, p, next, now) { + const got = { skins: [], acc: [], items: [], draws: [] }; let dups = 0; + for (const id of p.contents.items || []) { + if (owned[id]) { dups++; continue; } + owned[id] = now; (ITEMS[id][1] === 's' ? got.skins : ITEMS[id][1] === 'a' ? got.acc : got.items).push(id); + } + for (let i = 0; i < (p.contents.draws || 0); i++) { + const r = roll(next), dup = !!owned[r.skin]; + if (dup) dups++; else owned[r.skin] = now; + got.draws.push({ rarity: r.rarity, skin: r.skin, dup }); + } + return { got, dups, refund: dups * CATALOG.DUP_REFUND }; +} + +// ---------- The wallet document ---------- +function blank(now) { return { balance: 0, owned: {}, recent: [], notices: [], reqs: {}, created: now, updated: now }; } +function int(v) { return typeof v === 'number' && Number.isSafeInteger(v); } +function clean(d, now) { + if (!d) return null; + const w = blank(now); + if (int(d.balance) && d.balance >= 0) w.balance = d.balance; + if (d.owned && typeof d.owned === 'object') for (const k of Object.keys(d.owned)) if (has(ITEMS, k)) w.owned[k] = int(d.owned[k]) ? d.owned[k] : now; + if (Array.isArray(d.recent)) w.recent = d.recent.filter(x => x && int(x.t)).slice(-RECENT_MAX); + if (Array.isArray(d.notices)) w.notices = d.notices.filter(x => x && typeof x.id === 'string').slice(-NOTICE_MAX); + if (d.reqs && typeof d.reqs === 'object') for (const k of Object.keys(d.reqs)) if (REQ_RE.test(k) && int(d.reqs[k])) w.reqs[k] = d.reqs[k]; + if (int(d.created)) w.created = d.created; + return w; +} +export function cleanText(t, max) { + return String(t == null ? '' : t).replace(/[|<>\u0000-\u001f\u007f​-‏‪-‮⁦-⁩]/g, '').replace(/\s+/g, ' ').trim().slice(0, max); +} +function newId() { return crypto.randomUUID().replace(/-/g, ''); } +// A ledger line: added to the wallet's recent list and written as its own ledger row (never edited). +function line(w, uid, now, d, why, ref, kind, writes, id) { + const l = { t: now, d, b: w.balance, w: cleanText(why, 80) || kind, r: ref || '' }; + w.recent.push(l); w.recent = w.recent.slice(-RECENT_MAX); + writes.push(put('ledger/' + (id || newId()), Object.assign({ uid, kind }, l), true)); +} +function seenReq(w, req, now) { + if (!req) return; + if (!REQ_RE.test(req)) throw new WErr(400, 'bad', 'Bad request.'); + if (has(w.reqs, req)) throw new WErr(409, 'duplicate', 'That was already done.'); + w.reqs[req] = now; + const ks = Object.keys(w.reqs).sort((a, b) => w.reqs[b] - w.reqs[a]); + for (const k of ks.slice(REQ_MAX)) delete w.reqs[k]; +} +// What the page is told: never reqs, never anything about another player. +export function view(w, uid, env) { + w = w || blank(Date.now()); + return { balance: w.balance, captain: isCaptain(uid), owned: Object.keys(w.owned), notices: w.notices, + recent: w.recent.map(l => [l.t, l.d, l.b, l.w, l.r]), mangosPerEmerald: MPE, test: testMode(env), public: !!CATALOG.PUBLIC }; +} + +// ---------- Firestore REST, with transactions ---------- +const put = (p, obj, mustBeNew) => { const w = { update: { name: DOCS + '/' + p, fields: encFields(obj) } }; if (mustBeNew) w.currentDocument = { exists: false }; return w; }; +const docPath = (col, id) => col + '/' + encodeURIComponent(id); +async function headers(env) { return { Authorization: 'Bearer ' + await googleToken(env, fetch), 'Content-Type': 'application/json' }; } +async function getDoc(env, p, txid) { + const r = await fetch(FS + '/' + p + (txid ? '?transaction=' + encodeURIComponent(txid) : ''), { headers: await headers(env) }); + if (r.status === 404) return null; + if (!r.ok) throw new Error('Firestore error ' + r.status); + return decFields((await r.json()).fields || {}); +} +const sleep = ms => new Promise(r => setTimeout(r, ms)); +// Runs body(get) in a read-write transaction: body reads with get(path) and returns { writes, result }. Retried when +// Firestore reports a conflict (another request touched the same documents first), up to 8 times. +export async function transact(env, body) { + for (let i = 0; i < 8; i++) { + const H = await headers(env); + const b = await fetch(FS + ':beginTransaction', { method: 'POST', headers: H, body: JSON.stringify({ options: { readWrite: {} } }) }); + if (!b.ok) throw new Error('Firestore error ' + b.status); + const txid = (await b.json()).transaction; + let out; + try { out = await body(p => getDoc(env, p, txid)); } + catch (e) { await fetch(FS + ':rollback', { method: 'POST', headers: H, body: JSON.stringify({ transaction: txid }) }).catch(() => {}); throw e; } + if (!out.writes.length) { await fetch(FS + ':rollback', { method: 'POST', headers: H, body: JSON.stringify({ transaction: txid }) }).catch(() => {}); return out.result; } + const c = await fetch(FS + ':commit', { method: 'POST', headers: H, body: JSON.stringify({ writes: out.writes, transaction: txid }) }); + if (c.ok) return out.result; + const text = await c.text(); + if (c.status === 409 || c.status === 503 || (c.status === 400 && /FAILED_PRECONDITION|ALREADY_EXISTS/.test(text))) { await sleep(20 + Math.random() * 60 * (i + 1)); continue; } + throw new Error('Firestore error ' + c.status + ' ' + text.slice(0, 200)); + } + throw new WErr(503, 'busy', 'The shop is busy. Try again in a moment.'); +} + +// ---------- What the endpoints do ---------- +export async function walletGet(env, user) { + const now = Date.now(), p = docPath('wallets', user.uid); + let w = clean(await getDoc(env, p), now); + if (!w) { + // First visit: make the wallet, so others can send this player gifts. A race with another first visit is harmless. + w = blank(now); + await fetch(FS + ':commit', { method: 'POST', headers: await headers(env), body: JSON.stringify({ writes: [put(p, w, true)] }) }).catch(() => {}); + } + return view(w, user.uid, env); +} + +// Buy a pack, one item ('item:') or chests ('draw-1', 'draw-5', 'draw-10'), for yourself. +export async function walletBuy(env, user, body, next) { + const p = pack(body.what); + if (!p) throw new WErr(400, /^emeralds[-_]/.test(String(body.what || '')) ? 'money' : 'unknown', /^emeralds[-_]/.test(String(body.what || '')) ? 'Emeralds are bought with Buy emeralds.' : 'Unknown item.'); + const cap = isCaptain(user.uid), req = body.req ? String(body.req) : ''; + next = next || cryptoNext(); + return transact(env, async get => { + const now = Date.now(), writes = []; + const w = clean(await get(docPath('wallets', user.uid)), now) || blank(now); + seenReq(w, req, now); + const items = p.contents.items || []; + if (!p.contents.draws && (cap || items.every(id => w.owned[id]))) throw new WErr(409, 'owned', p.kind === 'one' ? 'You already own this.' : 'You already own everything in this pack.'); + const price = cap ? 0 : p.price; + if (w.balance < price) throw new WErr(402, 'funds', 'Not enough emeralds yet.', { need: price - w.balance, balance: w.balance }); + w.balance -= price; + const f = fill(w.owned, p, next, now), refund = cap ? 0 : f.refund; + const kind = p.contents.draws ? 'chest' : 'buy'; + line(w, user.uid, now, -price, (cap ? 'Free (captain): ' : 'Bought ') + p.name, p.id, kind, writes); + if (refund) { w.balance += refund; line(w, user.uid, now, refund, f.dups === 1 ? 'Back for a duplicate' : 'Back for ' + f.dups + ' duplicates', p.id, 'refund', writes); } + w.updated = now; + writes.unshift(put(docPath('wallets', user.uid), w)); + return { writes, result: { ok: true, pack: p.id, spent: price, got: f.got, refund, balance: w.balance, state: view(w, user.uid, env) } }; + }); +} +export function walletChest(env, user, body, next) { + const n = Number(body.n); + if (n !== 1 && n !== 5 && n !== 10) return Promise.reject(new WErr(400, 'bad', 'Chests come in 1, 5 or 10.')); + return walletBuy(env, user, { what: 'draw-' + n, req: body.req }, next); +} + +// Send an item, pack or chests to another player: the sender pays the same price, the recipient gets it (a chest is +// opened for them here) and a notice. The recipient must have a wallet (opened the shop signed in with Google once). +export async function walletGift(env, user, body, next) { + const to = String(body.to || ''), what = String(body.what || ''); + if (!UID_RE.test(to)) throw new WErr(400, 'recipient', 'Pick who to send it to.'); + if (to === user.uid) throw new WErr(400, 'self', 'You can’t send a gift to yourself.'); + const p = pack(what); + if (!p) throw new WErr(400, /^emeralds[-_]/.test(what) ? 'money' : 'unknown', /^emeralds[-_]/.test(what) ? 'Emeralds and mangos can’t be gifted.' : 'Unknown item.'); + if (isCaptain(to)) throw new WErr(409, 'captain', 'Captains already own everything.'); + const note = cleanText(body.note, CATALOG.NOTE_MAX), from = cleanText(body.fromName, 14) || 'A player', toName = cleanText(body.toName, 14) || 'a player'; + const cap = isCaptain(user.uid), req = body.req ? String(body.req) : ''; + next = next || cryptoNext(); + return transact(env, async get => { + const now = Date.now(), writes = []; + const w = clean(await get(docPath('wallets', user.uid)), now) || blank(now); + const r = clean(await get(docPath('wallets', to)), now); + if (!r) throw new WErr(404, 'recipient', toName + ' needs to open the shop once, signed in with Google, before they can get gifts.'); + seenReq(w, req, now); + if (p.kind === 'one' && r.owned[p.contents.items[0]]) throw new WErr(409, 'owned', toName + ' already has this.'); + const price = cap ? 0 : p.price; + if (w.balance < price) throw new WErr(402, 'funds', 'Not enough emeralds yet.', { need: price - w.balance, balance: w.balance }); + w.balance -= price; + const id = newId(); + line(w, user.uid, now, -price, (cap ? 'Free gift (captain) to ' : 'Gift to ') + toName + ': ' + p.name, 'gift:' + id, 'gift-out', writes, id + 'o'); + const f = fill(r.owned, p, next, now); + r.balance = Math.min(MAX_BAL, r.balance + f.refund); + line(r, to, now, f.refund, 'Gift from ' + from + ': ' + p.name + (f.refund ? ' (' + (f.dups === 1 ? 'already had one' : 'already had ' + f.dups) + ')' : ''), 'gift:' + id, 'gift-in', writes, id + 'i'); + r.notices.push({ id, t: now, from, what: p.name, pack: p.id, note, got: f.got, refund: f.refund }); + r.notices = r.notices.slice(-NOTICE_MAX); + w.updated = r.updated = now; + writes.unshift(put(docPath('wallets', user.uid), w), put(docPath('wallets', to), r)); + return { writes, result: { ok: true, id, spent: price, balance: w.balance, state: view(w, user.uid, env) } }; + }); +} + +// The page has shown these gift notices: drop them. +export async function walletSeen(env, user, body) { + const ids = Array.isArray(body.ids) ? body.ids.map(String).slice(0, 50) : []; + return transact(env, async get => { + const now = Date.now(), w = clean(await get(docPath('wallets', user.uid)), now); + if (!w) return { writes: [], result: view(null, user.uid, env) }; + const before = w.notices.length; + w.notices = w.notices.filter(n => ids.indexOf(n.id) < 0); + if (w.notices.length === before) return { writes: [], result: view(w, user.uid, env) }; + return { writes: [put(docPath('wallets', user.uid), w)], result: view(w, user.uid, env) }; + }); +} + +// The Stripe webhook's part (functions/api/stripe-webhook.js): a paid Checkout for an emerald pack. The count comes +// from CATALOG.EMERALDS by the sku our own checkout put in the metadata, never from Stripe's metadata or the page, and +// the amount and currency paid must match the pack exactly. Credits once per Checkout session: orders/{session id} +// is read and written in the same transaction, so a repeated or concurrent webhook finds it and does nothing. +export async function creditEmeralds(env, s, at) { + const md = s.metadata || {}, sku = String(md.sku || ''), E = has(CATALOG.EMERALDS, sku) ? CATALOG.EMERALDS[sku] : null; + const uid = String(md.uid || s.client_reference_id || ''); + if (!E || !UID_RE.test(uid) || !/^[A-Za-z0-9_]{1,200}$/.test(String(s.id || ''))) return { skipped: 'not an emerald pack' }; + const paidOk = s.amount_total === E.cents && String(s.currency || '').toLowerCase() === E.currency; + return transact(env, async get => { + const op = docPath('orders', s.id); + if (await get(op)) return { writes: [], result: { already: true } }; + const order = { uid, sku, amount: int(s.amount_total) ? s.amount_total : 0, currency: String(s.currency || ''), + email: (s.customer_details && s.customer_details.email) || s.customer_email || '', created: at, kind: 'emeralds' }; + if (!paidOk) return { writes: [put(op, Object.assign(order, { status: 'mismatch', mangos: 0 }), true)], result: { refused: 'amount' } }; + const w = clean(await get(docPath('wallets', uid)), at) || blank(at), m = E.emeralds * MPE, writes = []; + w.balance = Math.min(MAX_BAL, w.balance + m); w.updated = at; + line(w, uid, at, m, 'Bought ' + E.name + ' (' + E.emeralds.toLocaleString('en-US') + ' emeralds)', s.id, 'emeralds', writes, 'stripe_' + s.id); + writes.unshift(put(docPath('wallets', uid), w), put(op, Object.assign(order, { status: 'credited', mangos: m }), true)); + return { writes, result: { credited: m } }; + }); +} + +// ---------- HTTP ---------- +// Every wallet endpoint: the same verified Google sign-in the shop uses, then the preview / public check. +export function endpoint(fn) { + return async ({ request, env }) => { + const h = cors(request, env); + let user = null; + try { user = await googleUser(request); } catch (e) { return json({ error: 'Couldn’t check your sign-in. Try again in a minute.', reason: 'server' }, 502, h); } + if (!user) return json({ error: 'Buying needs a Google sign-in.', reason: 'signin' }, 401, h); + if (!allowed(user.uid)) return json({ error: 'The shop isn’t open yet.', reason: 'closed' }, 403, h); + let body = {}; + if (request.method === 'POST') { + try { body = await request.json(); } catch (e) { return json({ error: 'Bad request.', reason: 'bad' }, 400, h); } + if (!body || typeof body !== 'object' || Array.isArray(body)) return json({ error: 'Bad request.', reason: 'bad' }, 400, h); + } + try { return json(await fn(env, user, body), 200, h); } + catch (e) { + if (e instanceof WErr) return json(Object.assign({ error: e.message, reason: e.reason }, e.extra || {}), e.status, h); + return json({ error: 'Something went wrong. Try again in a minute.', reason: 'server' }, 502, h); + } + }; +} +export const options = ({ request, env }) => new Response(null, { status: 204, headers: cors(request, env) }); diff --git a/functions/api/checkout.js b/functions/api/checkout.js index 9d36eeab..ee45fbbc 100644 --- a/functions/api/checkout.js +++ b/functions/api/checkout.js @@ -1,7 +1,12 @@ // POST /api/checkout { sku, back } with "Authorization: Bearer " from a Google sign-in. // Starts a Stripe-hosted Checkout for one item and returns { url } to send the player to. The item is the active // Stripe price whose lookup key is the sku; back is the page to return to (on one of the site's own addresses). +// The six emerald packs (emeralds_7 … emeralds_4000, functions/_catalog.js) are consumables: bought as often as +// wanted, only while the wallet is open to this player (functions/_wallet.js allowed()), and only when the Stripe +// price's amount and currency match the pack exactly. The webhook credits them; the return address also carries +// the Checkout session id (session=cs_…) so the shop can tell when the emeralds have arrived. import { cors, json, allowedOrigin, googleUser, stripe, ownedItems, SKU_RE } from '../_lib.js'; +import { CATALOG, allowed } from '../_wallet.js'; export const onRequestOptions = ({ request, env }) => new Response(null, { status: 204, headers: cors(request, env) }); @@ -18,6 +23,32 @@ export async function onRequestPost({ request, env }) { if (!allowedOrigin(back.origin, env)) return json({ error: 'Bad return page.' }, 400, h); back.hash = ''; + const E = Object.prototype.hasOwnProperty.call(CATALOG.EMERALDS, sku) ? CATALOG.EMERALDS[sku] : null; + if (E) { + if (!allowed(user.uid)) return json({ error: 'The shop isn’t open yet.', reason: 'closed' }, 403, h); + try { + const prices = await stripe(env, 'GET', 'prices', { lookup_keys: [sku], active: 'true' }); + const price = prices.data && prices.data[0]; + if (!price) return json({ error: 'Unknown item.' }, 404, h); + if (price.unit_amount !== E.cents || String(price.currency || '').toLowerCase() !== E.currency || (price.type && price.type !== 'one_time')) + return json({ error: 'This pack isn’t set up right yet.', reason: 'price' }, 409, h); + const ret = (k) => { const u = new URL(back); u.searchParams.set('purchase', k); u.searchParams.set('sku', sku); return u.toString() + (k === 'success' ? '&session={CHECKOUT_SESSION_ID}' : ''); }; + const session = await stripe(env, 'POST', 'checkout/sessions', { + mode: 'payment', + line_items: [{ price: price.id, quantity: 1 }], + client_reference_id: user.uid, + customer_email: user.email || undefined, + metadata: { uid: user.uid, sku, kind: 'emeralds' }, + payment_intent_data: { metadata: { uid: user.uid, sku, kind: 'emeralds' } }, + success_url: ret('success'), + cancel_url: ret('cancel') + }); + return json({ url: session.url }, 200, h); + } catch (e) { + return json({ error: 'Couldn’t start checkout. Try again in a minute.' }, 502, h); + } + } + try { if ((await ownedItems(env, user.uid))[sku]) return json({ error: 'You already own this.', owned: true }, 409, h); const prices = await stripe(env, 'GET', 'prices', { lookup_keys: [sku], active: 'true' }); diff --git a/functions/api/stripe-webhook.js b/functions/api/stripe-webhook.js index 39841452..e1346f21 100644 --- a/functions/api/stripe-webhook.js +++ b/functions/api/stripe-webhook.js @@ -4,6 +4,7 @@ // checkout.session.async_payment_succeeded; its signing secret is STRIPE_WEBHOOK_SECRET. import { json, stripeEvent, grant, SKU_RE } from '../_lib.js'; import { marketPaid } from '../_market.js'; +import { CATALOG, creditEmeralds } from '../_wallet.js'; export async function onRequestPost({ request, env }) { const raw = await request.text(); @@ -18,6 +19,14 @@ export async function onRequestPost({ request, env }) { catch (e) { return json({ error: 'could not record the sale' }, 500); } // Stripe retries return json({ ok: true }); } + // An emerald pack (functions/_wallet.js): credits wallets/{uid} once per Checkout session, only when the amount and + // currency paid match the pack. A mismatch is recorded in orders/{session id} with nothing credited, and not retried. + if (s.metadata && Object.prototype.hasOwnProperty.call(CATALOG.EMERALDS, String(s.metadata.sku || ''))) { + let r; + try { r = await creditEmeralds(env, s, (ev.created || Math.floor(Date.now() / 1000)) * 1000); } + catch (e) { return json({ error: 'could not record the purchase' }, 500); } // Stripe retries + return json(Object.assign({ ok: true }, r)); + } const uid = String((s.metadata && s.metadata.uid) || s.client_reference_id || ''), sku = String((s.metadata && s.metadata.sku) || ''); if (!uid || uid.length > 128 || /[/]/.test(uid) || !SKU_RE.test(sku)) return json({ ok: true, skipped: 'no player or item' }); try { diff --git a/functions/api/wallet/buy.js b/functions/api/wallet/buy.js new file mode 100644 index 00000000..4c32a718 --- /dev/null +++ b/functions/api/wallet/buy.js @@ -0,0 +1,7 @@ +// POST /api/wallet/buy { what: a pack id or 'item:', req: a random id for this click } (Google sign-in required) +// Buys it with the wallet's mangos in one Firestore transaction: { ok, pack, spent, got, refund, balance, state }. +// Refusals: 402 funds, 409 owned / duplicate, 400 unknown / money. See functions/_wallet.js. +import { endpoint, options, walletBuy } from '../../_wallet.js'; + +export const onRequestOptions = options; +export const onRequestPost = endpoint((env, user, body) => walletBuy(env, user, body)); diff --git a/functions/api/wallet/chest.js b/functions/api/wallet/chest.js new file mode 100644 index 00000000..c306f89f --- /dev/null +++ b/functions/api/wallet/chest.js @@ -0,0 +1,7 @@ +// POST /api/wallet/chest { n: 1 | 5 | 10, req } (Google sign-in required) +// Opens chests: the roll is made here with crypto randomness. { ok, spent, got: { draws: [{ rarity, skin, dup }] }, +// refund (48 mangos for each skin already owned), balance, state }. See functions/_wallet.js. +import { endpoint, options, walletChest } from '../../_wallet.js'; + +export const onRequestOptions = options; +export const onRequestPost = endpoint((env, user, body) => walletChest(env, user, body)); diff --git a/functions/api/wallet/gift.js b/functions/api/wallet/gift.js new file mode 100644 index 00000000..4a6e5a34 --- /dev/null +++ b/functions/api/wallet/gift.js @@ -0,0 +1,7 @@ +// POST /api/wallet/gift { what: a pack id, 'item:' or 'draw-1/5/10', to: uid, toName, fromName, note (≤ 60), req } +// (Google sign-in required). Charges the sender the same price, gives the recipient the item (or the opened chest's +// skins) and a notice. Refusals: recipient (no wallet yet), self, captain, owned, funds, money. See functions/_wallet.js. +import { endpoint, options, walletGift } from '../../_wallet.js'; + +export const onRequestOptions = options; +export const onRequestPost = endpoint((env, user, body) => walletGift(env, user, body)); diff --git a/functions/api/wallet/index.js b/functions/api/wallet/index.js new file mode 100644 index 00000000..1ec197ad --- /dev/null +++ b/functions/api/wallet/index.js @@ -0,0 +1,8 @@ +// GET /api/wallet with "Authorization: Bearer " from a Google sign-in (the same check as the shop). +// The player's emerald wallet: { balance (whole mangos), captain, owned: [item ids], notices: [gifts not yet seen], +// recent: [[time ms, change, balance after, why, ref], ...] newest last, mangosPerEmerald, test (true while Cloudflare +// holds a Stripe test key; the key itself is never sent), public (PAYMENTS.enabled) }. See functions/_wallet.js. +import { endpoint, options, walletGet } from '../../_wallet.js'; + +export const onRequestOptions = options; +export const onRequestGet = endpoint(walletGet); diff --git a/functions/api/wallet/seen.js b/functions/api/wallet/seen.js new file mode 100644 index 00000000..487d1541 --- /dev/null +++ b/functions/api/wallet/seen.js @@ -0,0 +1,5 @@ +// POST /api/wallet/seen { ids: [notice id, ...] } (Google sign-in required): the page has shown these gift notices. +import { endpoint, options, walletSeen } from '../../_wallet.js'; + +export const onRequestOptions = options; +export const onRequestPost = endpoint(walletSeen); From 65e1869807f9e9f23b530678092b6d5a95cfada0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:24:12 +0000 Subject: [PATCH 03/14] Wallet client: wallet.js and cosmetics.js use /api/wallet when the server wallet is in use; shop: captains' preview, Stripe emerald packs, Test mode tag; README and setup checklist Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- README.md | 14 +- e63334287a3deaa3/cosmetics.js | 75 ++++++- e63334287a3deaa3/shop/index.html | 108 +++++++++- e63334287a3deaa3/shop/tests/shop.test.mjs | 238 ++++++++++++++++++++++ e63334287a3deaa3/slipstream/garage.js | 5 +- e63334287a3deaa3/wallet.js | 156 +++++++++++--- 6 files changed, 549 insertions(+), 47 deletions(-) create mode 100644 e63334287a3deaa3/shop/tests/shop.test.mjs diff --git a/README.md b/README.md index 5ca67867..f773c6b7 100644 --- a/README.md +++ b/README.md @@ -95,8 +95,8 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - `e63334287a3deaa3/aisles.js`: Aisles (Back Room page, home page Back Room and phone page), the site's clans. Any player (signed in the way the Party panel signs everyone in) can start one from the **Aisle** button in the Online panel: a name (3–24 characters, checked with `namefilter.js`), a tag of 2–4 letters or digits (also checked, spaced out too) and one of 12 colours (only an index is stored). One Aisle per player, up to 6 seats (`MAX`, open invites included). The leader invites from a person's card in the Online panel (**Invite to Aisle**) or with an invite link `/#xj-` or the same 16-character code typed into the Aisle window; the invitee sees a toast and **Accept** / **Decline** in the window. The leader can remove (kick) members, make someone else leader (hand over), make a new invite code (the old one stops working) and disband; members can leave (a leader must hand over first, unless alone). The tag is drawn as text in front of members' names wherever a name is marked with `data-aisle-u=""`: the Party panel (`party.js`), the Online list, a person's card and the cabin and party chat (`social.js`) and the Leaderboards rows (`leaderboard.js`); a MutationObserver tags names as they are drawn. Playing now's sentences are not tagged. The Aisle window shows the members with their tier badge, miles and Elo, and the Aisle's two totals and ranks. **Boards:** the Leaderboards' Board menu gets an "Aisles" group with **Aisle Miles** and **Aisle Elo** (not in a game's own panel). They are drawn by `aisles.js` from `leaderboard.js`'s own checked and merged rows (`BackRoomBoards.data()`, which `leaderboard.js` now exposes, and the `backroom:boards` event after each read), never from raw nodes; each member counts once, through the merged account their row was folded into. Aisle Miles = the sum of the members' `BackRoomMiles.of(row).miles` (the number behind their tier), with Total ÷ members as the average. **Weekly contest:** the Aisle Miles board has This week / All time (This week unless the browser picked All time, localStorage `ais:span`). This week ranks Aisles by their members' miles from play time since Monday (the viewer's clock, the same week as the Miles board, `BackRoomMiles.HOUR` an hour), from leaderboard.js's checked per-day history `dy` (every day from last week's Monday on, merged like the week), and only from the day each member joined the Aisle (the later of the leader's `m` time and the member's `aj`; the founder from `t0`), so a big week can't be carried into another Aisle. The top Aisle is marked Leading this week, and the board's note names last week's winner (worked out the same way from last week's days, with the Aisles as they are now). Nothing is stored for it: every browser works it out from the boards. Aisle Elo = for each member, the average of their checked Elo over every game whose board has an Elo stat and in which they have a rating; those member averages are added up for the total, and the average is Total ÷ members with a rating; a toggle (saved in `ais:elosort`) sorts by Total or Average. A note under each board says this. **Storage:** Realtime Database, same project and rules as the games, prefix `xj` (the invite links use it; the room itself is not a game room). The rules only let a browser write its own node and need `n, c, x, z, h, ts`, so everything is in each player's own node `rooms/xj-all/players/` (`v` 1, `x/z/h` 0, `c` the Aisle colour): `a` the Aisle they say they're in and `aj` when; `ap` a proof of an invite code, `SHA-256(id:code:uid)`, only while waiting; `ad` invites they declined; and `L`, the records of Aisles they founded or led (`{f, ld, q, nm, tg, cl, m, iv, kx, ch, t0, dis}`: `m` members, `iv` invites with their time, 7 days, `kx` people removed, `ch` a hash of the current invite code, whose plain code stays in the leader's browser as `aisle:code:`). An Aisle's id is a hash of the founder's uid and a small number, so only the founder's node can start the trail; its current record is found by following `ld` from the founder's record to each next leader's own record with a higher `q`. **Both sides must agree:** a player is in an Aisle only while their own node names it (`a`, written only by their browser when they accept or use a code) AND the leader's record lists them (`m`, or a live invite in `iv`), so nobody is added without accepting and nobody gets in without the leader's invite or code. A code join is let in by the leader's browser (which checks the proof against its code) the next time the leader has the Back Room open. **Captains** remove an Aisle with a bad name on the admin page's new **Aisles** tab (the button works only for Captains, `captains.js`); the removal is a list signed with the admin key (ECDSA, like the hours resets) at `rooms/xj-ban/players/` (`r` JSON `{: {t, x, nm}}`, `sig`), and only correctly signed nodes count. A removed Aisle is hidden everywhere (tag, boards, joining) but nobody is let go, so **Put back** restores it; its members can leave it for good from the Aisle window. Like the rest of the Back Room this is checked in every browser, not enforced by the server: someone using developer tools could write odd data into their own node (it is size-capped and cleaned when read), but they can't change anyone else's membership, and the boards only use the checked leaderboard rows. Hooks in shared files are small: `leaderboard.js` (the two board options, `BackRoomBoards.data()`, the event, `data-aisle-u`), `party.js` and `social.js` (`data-aisle-u`, and the Invite to Aisle button through `BackRoomAisles.inviteBtn`), `index.html` (home page: loads it and holds a `#xj-` link in sessionStorage `aisle:inv` until the Back Room opens), `m/index.html` (same for the phone page), `e63334287a3deaa3/index.html` (a ``, lists its actions in `Keybinds.create({game, actions: [{id, label, keys: ['KeyW', 'ArrowUp']}]})` (keys are `e.code` names, so they're physical keys on any layout; mouse buttons are `Mouse0`/`Mouse1`/`Mouse2` in games that pass `mouse: true`), checks input with `KB.is(action, e.code)` and `KB.held(action, keys)` instead of comparing key codes, and opens the panel from a Controls button with `KB.open()`. Changed keys are saved only in the player's browser, under localStorage `keybinds:` as `{v: 1, b: {action: [codes]}}` (only the actions that differ from the defaults; Reset to defaults removes the entry), and never go to Firebase. Esc is never rebindable. Elements with `data-kb="action"` show the current keys and update themselves. The panel takes each game's look from `--kb-*` CSS variables and the game's own button classes; the comment at the top of the file lists the options. To add it to a game, do the same, and keep text inputs (names, room codes, chat) returning before any key lookup. Touch controls don't go through key codes: each game's touch buttons feed its input directly (in Shell Crackers, Quarry and Backrooms they hold actions by id in `tAct`, which the game checks alongside `KB.held`), so they keep working whatever keys are bound, and the Change keys / Controls buttons are hidden in the touch layout (`body.touch`). **Spanish** (lang.js, when the page loads it): keybinds.js adds the panel's own words and common key and action names once (guarded by `if (window.BackRoomLang)`), and builds its messages and aria-labels with the action and key names in the page's language (a game's own dictionary supplies its action names); in English, or without lang.js, every string is as before. @@ -227,7 +231,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the Touch: every game plays on a phone. Each game draws its own touch controls (a move stick, buttons, and drag-to-look for the first-person games) and shows them only on touch screens (`pointer: coarse`, or after the first touch), so the keyboard-and-mouse version is unchanged. The first-person games (Shell Crackers, Backrooms 1v1–4v4, Quarry) skip pointer lock on touch screens; in Quarry, taps in the inventory and crafting screens go to the same code as mouse clicks. - `functions/api/traffic.js`: `GET https://ascoding11.com/api/traffic`, the showcase page's live traffic numbers (last 30 UTC days including today, in the analytics dashboard's "Copy showcase numbers" shape: anonymous totals, no names, emails or visitor IDs; the homepage is left out of the top pages, and sessions made only of 0-second homepage views with no referrer are treated as bots). It reads the analytics `pv` pageviews with the shop's `FIREBASE_SERVICE_ACCOUNT` secret, so no Firestore rules change. To keep reads low it saves each finished day's summary in `traffic_days/{YYYY-MM-DD}` once and reuses its last answer (`traffic_days/_latest`) for 30 minutes; only this function touches `traffic_days`. `showcase/index.html` loads it (from ascoding11.com when opened on github.io) and shows its saved `trafficData` snapshot only if it can't be reached. -- `store.js` and `functions/` (site root): the shop, for selling skins and other items with Stripe. Buying needs a Google sign-in, and an item belongs to that Google account on every device and on both addresses. A page loads `` and calls `Store.buy(sku)` from a click (signs the player in with Google if needed, then sends them to Stripe's own payment page), `Store.owned()` / `Store.has(sku)` to see what they own, and `Store.returned()` / `Store.waitFor(sku)` when Stripe sends them back (`?purchase=success&sku=…`). The server side is three Cloudflare Pages Functions, which run only on ascoding11.com (GitHub Pages can't run code), so the shop on ascoding11.github.io calls them there: `functions/api/checkout.js` (checks the Google sign-in, refuses items already owned, starts a Stripe Checkout), `functions/api/stripe-webhook.js` (Stripe's signed "payment finished" message: the only thing that gives an item) and `functions/api/owned.js`; shared code in `functions/_lib.js`. Items are Stripe prices: an item exists when an active price has its sku as the lookup key (lowercase letters, digits and `_`, starting with a letter, e.g. `boostball_flame`), and its price comes from Stripe. Purchases are written only by the webhook, with a Firebase service account, to Firestore `entitlements/{uid}` (`items: { sku: time bought }`) and `orders/{Checkout session id}`; the site's pages never read or write those collections directly. Secrets live only in Cloudflare (the site's Settings → Variables and secrets): `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `FIREBASE_SERVICE_ACCOUNT` (the whole JSON key). The Stripe webhook endpoint is `https://ascoding11.com/api/stripe-webhook` with `checkout.session.completed` and `checkout.session.async_payment_succeeded`. Refunds don't take items back automatically. +- `store.js` and `functions/` (site root): the shop, for selling skins and other items with Stripe. Buying needs a Google sign-in, and an item belongs to that Google account on every device and on both addresses. A page loads `` and calls `Store.buy(sku)` from a click (signs the player in with Google if needed, then sends them to Stripe's own payment page), `Store.owned()` / `Store.has(sku)` to see what they own, and `Store.returned()` / `Store.waitFor(sku)` when Stripe sends them back (`?purchase=success&sku=…`). The server side is three Cloudflare Pages Functions, which run only on ascoding11.com (GitHub Pages can't run code), so the shop on ascoding11.github.io calls them there: `functions/api/checkout.js` (checks the Google sign-in, refuses items already owned, starts a Stripe Checkout), `functions/api/stripe-webhook.js` (Stripe's signed "payment finished" message: the only thing that gives an item) and `functions/api/owned.js`; shared code in `functions/_lib.js`. The same checkout and webhook also sell the Back Room's emerald packs (lookup keys `emeralds_7` … `emeralds_4000`, credited to the server wallet; see "Server wallet" under `cosmetics.js` above); item purchases work exactly as before. Items are Stripe prices: an item exists when an active price has its sku as the lookup key (lowercase letters, digits and `_`, starting with a letter, e.g. `boostball_flame`), and its price comes from Stripe. Purchases are written only by the webhook, with a Firebase service account, to Firestore `entitlements/{uid}` (`items: { sku: time bought }`) and `orders/{Checkout session id}`; the site's pages never read or write those collections directly. Secrets live only in Cloudflare (the site's Settings → Variables and secrets): `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `FIREBASE_SERVICE_ACCOUNT` (the whole JSON key). The Stripe webhook endpoint is `https://ascoding11.com/api/stripe-webhook` with `checkout.session.completed` and `checkout.session.async_payment_succeeded`. Refunds don't take items back automatically. - `marketplace/` and `functions/_market.js` (with `functions/api/market/[action].js`): the Marketplace, a public page in the site's top bar where people sell second-hand things. Sellers post an item (title, asking price, category, condition, a rough area, up to three photos and private contact details); each buyer gets their own haggling thread with the seller (offer, counter, accept, decline, withdraw; offering the asking price is an instant deal), and the listing's card shows how many offers are open and the best one. When a price is agreed the listing is reserved ("Sale pending") and the buyer pays it on Stripe's page. **Nobody sees who they are dealing with until the payment has gone through**: buyers show as "Buyer 1", "Buyer 2" to the seller, the seller has no name at all, and listings and offer notes with phone numbers, emails, links or usernames are refused. Stripe's signed webhook (`functions/api/stripe-webhook.js`, the branch for `metadata.kind == "market"`) is the only thing that marks a deal paid; from then on the buyer gets the seller's name and contact details and the seller the buyer's name and email. Like the shop, the page never touches the database: everything goes through `https://ascoding11.com/api/market/` (Cloudflare Pages Functions, same three secrets as the shop) with the Google sign-in from `account.js`, and the server reads and writes Firestore with the service account, so **no security rules are needed** and the rules should not open these collections: `marketListings/{id}`, `marketPhotos/{id}_{n}` (JPEG bytes, shrunk in the browser to under 400 KB, which also drops location data), `marketOffers/{listing}_{hash of buyer}` (one thread per buyer per listing), `marketSellers/{uid}` (the seller's Stripe account) and `marketReports/{listing}_{uid}`. Queries filter on a single field, so no Firestore indexes need creating. **Money:** sellers are paid through Stripe Connect (Express accounts, set up from the page's "Set up payouts" button; a seller must finish it before they can accept or counter). The payment is a destination charge, so Stripe passes it straight to the seller and the site never holds it. Out of the seller's payout come the site's cut and Stripe's card fee (2.9% + 30¢, which Stripe otherwise bills to the site). **The site's cut is `FEE_PERCENT` at the top of `functions/_market.js`, 0 for now; change it to 10 for 10%** (or set `MARKET_FEE_PERCENT` in Cloudflare, which wins). A listing keeps the cut it was posted with, and the page's fee wording follows the server. To go live: turn on Connect in the Stripe dashboard (the same account as `STRIPE_SECRET_KEY`); nothing else is new. Optional Cloudflare variable `MARKET_ADMINS` (comma-separated Google emails) lets those people remove any listing; three reports from different people hide a listing. There is no email or push notice: people see new offers on the page (it refreshes every 20 s, and "My deals" shows a count). Refunds and disputes are done by hand in Stripe and don't change a deal's status here. Counted in analytics as `marketplace`. - `adrefresh.js` (site root, so the public games can load it without linking to the Back Room): loads a fresh ad in the ads that are showing (menu banners, side rails) when someone clicks or taps a button on the screen. Keyboard presses don't count (their clicks have `detail` 0), nor do the in-game touch controls (anything in `#touch`, `.tb`/`.tbtn`, Coil's `#boostBtn`, Hail Mary's `#tA`/`#tB`, or anything marked `data-no-ad-refresh`), and it refreshes at most once every 30 seconds, only on screen and only ads that were filled. AdSense doesn't allow timed refresh, only refresh on what the person does, and these limits keep it that way. Every game page with ads loads it with `` in its ``; with no ad slots set up it does nothing. Ads: Google AdSense runs only on the game pages. The home page carries just the `google-adsense-account` meta tag, which verifies the site with AdSense without loading any ads. `ads.txt` (site root) and `privacy.html` are required by AdSense. Hype Cycle Exchange uses automatic ads. Boxed has no ads: its menu banner and side rails were removed while the site is under AdSense review, because its problems come from other sites (the AoPS Wiki); to bring them back, copy the `AD_SLOT` block and side rails from another game. The other games show banners only on their menu and results screens, switched on by pasting a display ad unit ID into `AD_SLOT` near the top of each game's script. diff --git a/e63334287a3deaa3/cosmetics.js b/e63334287a3deaa3/cosmetics.js index dbdea3e5..2b6b2e1f 100644 --- a/e63334287a3deaa3/cosmetics.js +++ b/e63334287a3deaa3/cosmetics.js @@ -10,7 +10,16 @@ * Set it to true to open everything. For testing only, ?cosmetics=1 in the page address turns it on, and only when the * page is on localhost or driven by an automated browser (navigator.webdriver): that check is captains.js's, the one * file every hidden cosmetic asks (without it on the page the address does nothing). - * The site's captains are NOT let in here early. captains.js lets them see the games' own screens (Driftfall's Locker, + * THE REAL SWITCH is wallet.js's PAYMENTS.enabled: true opens the shop for everyone with the server wallet (server() + * below; functions/_wallet.js): balance, locker and every purchase, chest and gift come from and go to the server. The + * browser-only locker and wallet (the old local mode) are kept only for the ?cosmetics=1 test switch. ENABLED, if set, + * also opens the shop with the server wallet. + * CAPTAINS' PREVIEW (CAPTAIN_PREVIEW, below): while PAYMENTS.enabled is false, a captain who opens the shop page gets the + * real shop with the server wallet in that browser tab (sessionStorage 'cosmetics:preview', set by shop/ once + * captains.js confirms the captain), so the owners can try the whole flow on the live site; everyone else still sees + * "not open yet", and the server refuses everyone but captains until PAYMENTS.enabled is true. Turn the preview off + * by setting CAPTAIN_PREVIEW to false (?preview=0 on the shop page also ends it for that tab). + * 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, * Boostball's garage and Kit, Slipstream's Garage), where every item is free to wear while this file is off; the * shop, the wallet, earning and buying stay shut for them like everyone else, so on() asks captains.js's open(), which * leaves captains out, not may(). @@ -67,7 +76,9 @@ 'use strict'; if (window.BackRoomCosmetics) return; - var ENABLED = false; // THE SWITCH: false keeps every part of the cosmetics hidden; true opens the shop for everyone. + var ENABLED = false; // false keeps every part of the cosmetics hidden (see THE REAL SWITCH above: wallet.js PAYMENTS.enabled) + var CAPTAIN_PREVIEW = true; // the captains' preview of the real shop (see above); false turns it off for everyone + var PREVIEW_KEY = 'cosmetics:preview'; var me0 = document.currentScript; var HUB = !!(me0 && me0.hasAttribute('data-hub')); @@ -97,7 +108,22 @@ var SHARED = window.BackRoomCaptains || null; // captains.js: the test switch lives there, with the others var FLAG = !!(SHARED && SHARED.open(false, 'cosmetics')); - function on() { return !!(api.ENABLED || FLAG); } + function on() { return server() || FLAG; } + // The server wallet is in use: PAYMENTS.enabled (wallet.js), ENABLED, or the captains' preview on the shop page. + // Otherwise, with the test switch alone, the old browser-only mode. + function payments() { try { var w = window.BackRoomWallet; return !!(w && w.PAYMENTS && w.PAYMENTS.enabled); } catch (e) { return false; } } + function shopPage() { try { return /^\/e63334287a3deaa3\/shop(\/(index\.html)?)?$/.test(location.pathname); } catch (e) { return false; } } + function previewOn() { if (!CAPTAIN_PREVIEW || !shopPage()) return false; try { return sessionStorage.getItem(PREVIEW_KEY) === '1'; } catch (e) { return false; } } + function server() { return !!(api.ENABLED || payments() || previewOn()); } + // shop/ calls these: start the preview once captains.js has confirmed a captain; stop it when that changes. + function previewAllowed() { return CAPTAIN_PREVIEW && shopPage() && !payments() && !api.ENABLED; } + function startPreview() { + if (!previewAllowed() || !(SHARED && SHARED.captain && SHARED.captain())) return false; + try { sessionStorage.setItem(PREVIEW_KEY, '1'); } catch (e) { return false; } + return previewOn(); + } + function stopPreview() { try { sessionStorage.removeItem(PREVIEW_KEY); } catch (e) {} } + try { if (/[?&]preview=0(&|$)/.test(location.search)) stopPreview(); } catch (e) {} // ---------------- Skins ---------------- // look: bg / bg2 background colours, bgp background pattern, outfit, head (piece on the head), tone (skin colour, optional), @@ -1133,14 +1159,25 @@ // lists every skin, accessory and game item as owned, and save() writes back only what they really own (L.raw), so // nothing they didn't buy is ever saved, mirrored into their account or kept after they sign out. load(true) is the // real locker alone (the account mirror and buying use it). - function cap() { try { return !!(on() && SHARED && SHARED.captain && SHARED.captain()); } catch (e) { return false; } } + function cap() { + try { if (on() && server() && window.BackRoomWallet && window.BackRoomWallet.unlimited && window.BackRoomWallet.unlimited()) return true; } catch (e) {} + try { return !!(on() && SHARED && SHARED.captain && SHARED.captain()); } catch (e) { return false; } + } function load(raw) { var o = json(ls(KEY)), L = { v: 1, s: [], a: [], g: [], e: { skin: '' }, ge: {} }; SLOTS.forEach(function (k) { L.e[k] = ''; }); if (!obj(o) || o.v !== 1) o = {}; + if (server()) { + // The server wallet: what's owned is the server's answer (wallet.js), plus the game items a game hands over + // itself (give: free to everyone, so kept in this browser). Only what is worn (e, ge) is read from here. + var w = window.BackRoomWallet, mine = w && w._owned ? w._owned() : []; + 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); }); + 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); }); + } else { if (Array.isArray(o.s)) o.s.forEach(function (id) { if (SKINS_BY_ID[id] && L.s.indexOf(id) < 0) L.s.push(id); }); if (Array.isArray(o.a)) o.a.forEach(function (id) { if (ACC_BY_ID[id] && L.a.indexOf(id) < 0) L.a.push(id); }); if (Array.isArray(o.g)) o.g.forEach(function (id) { if (ITEM_BY_ID[id] && L.g.indexOf(id) < 0) L.g.push(id); }); + } if (!raw && cap()) { Object.defineProperty(L, 'raw', { value: { s: L.s, a: L.a, g: L.g }, enumerable: false }); 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; }); @@ -1154,6 +1191,14 @@ } function save(L) { 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 + if (server()) { + // The server wallet: ownership is never saved here (the server holds it). What was saved before is left as it + // was; only what is worn and the game-given items change. + var o = json(ls(KEY)); o = obj(o) && o.v === 1 ? o : {}; + var keep = Array.isArray(o.g) ? o.g.filter(function (id) { return ITEM_BY_ID[id]; }) : []; + L.g.forEach(function (id) { if (ITEM_BY_ID[id] && ITEM_BY_ID[id].give && keep.indexOf(id) < 0) keep.push(id); }); + 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 }; + } 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 ls(KEY, JSON.stringify(L)); try { document.dispatchEvent(new CustomEvent('backroom:cosmetics', { detail: { equipped: equipped() } })); } catch (e) {} } function equip(id) { @@ -1264,9 +1309,12 @@ // unknown, money (emerald packs: wallet.js EMERALD_PACKS and PAYMENTS), owned (you already own everything in it), // wallet (no wallet.js), funds (not enough mangos). function emeraldPack(id) { var w = W(); return w && w.EMERALD_PACKS ? w.EMERALD_PACKS.filter(function (e) { return e.id === id; })[0] : null; } + // With the server wallet buy() returns a PROMISE of the same answer (the server buys, rolls and fills the locker; + // extra reasons: signin, closed, server, duplicate, with a message). Callers: Promise.resolve(buy(id)).then(...). function buy(packId, opts) { var p = pack(packId); if (!on()) return { ok: false, reason: 'off' }; + if (server()) return serverBuy(p, packId); if (!p && emeraldPack(packId)) return { ok: false, reason: 'money', checkout: W().PAYMENTS.checkout(packId) }; if (!p) return { ok: false, reason: 'unknown' }; var pv = preview(packId); @@ -1279,6 +1327,20 @@ if (f.refund) w.earn(f.refund, f.dups === 1 ? 'Back for a duplicate' : 'Back for ' + f.dups + ' duplicates'); return { ok: true, pack: p.id, spent: free ? 0 : p.price, got: f.got, refund: f.refund, balance: w.balance() }; } + function serverBuy(p, packId) { + if (!p && emeraldPack(packId)) return Promise.resolve({ ok: false, reason: 'money' }); + if (!p) return Promise.resolve({ ok: false, reason: 'unknown' }); + if (preview(packId).all) return Promise.resolve({ ok: false, reason: 'owned' }); + var w = W(); if (!w || !w._buy) return Promise.resolve({ ok: false, reason: 'wallet' }); + var dm = /^draw-(\d+)$/.exec(p.id); + return (dm ? w._chest(+dm[1]) : w._buy(p.id)).then(function (r) { + if (!r || !r.ok) return r || { ok: false, reason: 'server' }; + 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) || [] }; + var L = load(), first = got.skins[0] || (got.draws[0] && got.draws[0].skin); + if (!L.e.skin && first && L.s.indexOf(first) >= 0) { L.e.skin = first; save(L); } + return { ok: true, pack: p.id, spent: r.spent, got: got, refund: r.refund || 0, balance: r.balance }; + }); + } // Put what a pack (or one item, or chests) holds into the real locker, opening chests here. Pays nothing: the caller // pays the refund for duplicates (buy() above, or wallet.js's grant() for a gift). -> { got, dups, refund } function fill(p, opts) { @@ -1296,7 +1358,7 @@ return { got: got, dups: dups, refund: dups * DUP_REFUND }; } // A gift arriving (wallet.js's grant('gift'), the only caller): fill the locker with what packId holds, free. - function receive(packId, opts) { var p = pack(packId); if (!on() || !p) return null; var f = fill(p, opts); f.pack = p; return f; } + function receive(packId, opts) { var p = pack(packId); if (!on() || server() || !p) return null; var f = fill(p, opts); f.pack = p; return f; } // ---------------- Drawing (64 × 64 units, avatar.js's grid) ---------------- var INK = '#1B1513', WH = '#FFFFFF'; @@ -1526,7 +1588,8 @@ // ---------------- API ---------------- var api = { ENABLED: ENABLED, - on: on, + on: on, server: server, previewAllowed: previewAllowed, startPreview: startPreview, stopPreview: stopPreview, + previewing: function () { return previewOn() && !payments() && !api.ENABLED; }, SKINS: SKINS, ACCESSORIES: ACCESSORIES, SKINS_BY_ID: SKINS_BY_ID, ACCESSORIES_BY_ID: ACC_BY_ID, SLOTS: SLOTS, SLOT_NAMES: SLOT_NAMES, RARITY: RARITY, RARITY_BY_ID: RARITY_BY_ID, RARITY_TOTAL: RARITY_TOTAL, PACKS: PACKS, PACKS_BY_ID: PACKS_BY_ID, PRICE: PRICE, CHEST_PRICE: CHEST_PRICE, DUP_REFUND: DUP_REFUND, pack: pack, diff --git a/e63334287a3deaa3/shop/index.html b/e63334287a3deaa3/shop/index.html index 686fc621..20eedf2e 100644 --- a/e63334287a3deaa3/shop/index.html +++ b/e63334287a3deaa3/shop/index.html @@ -167,6 +167,11 @@ #giftdlg .who small{color:var(--ink-3);font-weight:700} #giftdlg .err{color:var(--bad);font-size:13.5px;min-height:1em;margin:0} #giftdlg .row{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap} +/* The server wallet: the captains' preview and Stripe test mode bar, and the signed-out note */ +.modebar{display:flex;flex-wrap:wrap;gap:4px 10px;justify-content:center;align-items:center;padding:6px max(16px,env(safe-area-inset-right)) 6px max(16px,env(safe-area-inset-left));font-size:12.5px;font-weight:800;color:var(--ink-2);background:rgba(255,178,56,.08);border-bottom:1px solid var(--line);text-align:center} +.modebar .tag{display:inline-block;background:var(--mango);color:#2a1700;border-radius:999px;padding:2px 9px;font-size:12px;letter-spacing:.02em;margin-right:4px} +.signin{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:12px 0 0;padding:10px 14px;border:1px solid rgba(255,178,56,.45);border-radius:12px;background:rgba(255,178,56,.08);font-size:14px;font-weight:700} +.signin .btn{min-height:36px;padding:6px 12px} #toast{position:fixed;left:50%;bottom:max(18px,env(safe-area-inset-bottom));transform:translateX(-50%);z-index:60;background:var(--panel-2);border:1px solid var(--line);border-radius:12px;padding:10px 14px;font-weight:700;font-size:14px;max-width:calc(100vw - 32px);box-shadow:0 8px 30px rgba(0,0,0,.4)} @media (max-width:760px){ @@ -228,11 +233,24 @@

The shop isn’t open yet

'use strict'; // Everything here waits for cosmetics.js and wallet.js (deferred), then builds the shop only when cosmetics are switched on. function ready(fn) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); else fn(); } + var built = false; ready(function () { var C = window.BackRoomCosmetics, W = window.BackRoomWallet; - if (!C || !W || !C.on()) return; // switched off: the page stays "not open yet" - build(C, W); + if (!C || !W) return; + if (C.on()) { build(C, W); if (C.previewing && C.previewing()) watchPreview(C); return; } + // The captains' preview (cosmetics.js CAPTAIN_PREVIEW): once captains.js confirms a captain, the real shop opens in + // this tab with the server wallet. Anyone else keeps "not open yet" (and the server refuses them anyway). + var K = window.BackRoomCaptains; + if (!C.previewAllowed || !C.previewAllowed() || !K || !K.onChange) return; // switched off: the page stays "not open yet" + var go = function () { if (!built && K.captain() && C.startPreview()) { build(C, W); watchPreview(C); } }; + K.ready.then(go); K.onChange(go); }); + // A preview tab whose account stops being a captain (signed out, another account) goes back to "not open yet". + function watchPreview(C) { + var K = window.BackRoomCaptains; if (!K || !K.onChange) return; + var end = function () { if (!K.captain()) { C.stopPreview(); location.reload(); } }; + K.ready.then(end); K.onChange(end); + } function ls(k) { try { return localStorage.getItem(k); } catch (e) { return null; } } function esc(s) { return String(s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } @@ -249,7 +267,9 @@

The shop isn’t open yet

function price(n) { var e = Math.floor(n / MPE), m = n % MPE; return '' + (e || !m ? EMS + e : '') + (m ? (e ? ' ' : '') + MANGO + m : '') + ''; } function build(C, W) { + built = true; document.getElementById('closed').hidden = true; + var S = !!(C.server && C.server()); // the server wallet (functions/_wallet.js) is in use var uid = ls('lbs:uid') || 'you'; MPE = W.MANGOS_PER_EMERALD || MPE; var RC = {}; C.RARITY.forEach(function (r) { RC[r.id] = r; }); @@ -259,6 +279,7 @@

The shop isn’t open yet

bar.innerHTML = '← Back Room

Shop

' + '
'; document.body.appendChild(bar); + var modeBar = el('div', 'modebar'); modeBar.id = 'modebar'; modeBar.hidden = true; document.body.appendChild(modeBar); var acc = document.createElement('script'); acc.src = '/account/account.js'; acc.defer = true; document.body.appendChild(acc); var main = el('main'); @@ -267,6 +288,7 @@

The shop isn’t open yet

'

Chest

Each chest costs ' + W.format(C.CHEST_PRICE) + ' and gives one random skin. A skin you already have gives back ' + W.format(C.DUP_REFUND) + '.

' + '
    ' + C.RARITY.slice().reverse().map(function (r) { return '
  • ' + r.name + ' ' + (r.w * 100 / C.RARITY_TOTAL) + '%
  • '; }).join('') + '
' + '
' + + '' + '' + '
'; document.body.appendChild(main); @@ -295,27 +317,47 @@

The shop isn’t open yet

var id = b.getAttribute('data-pack'), p = C.pack(id), pv = C.preview(id), have = W.balance(), cost = p.price; var lab = b.getAttribute('data-label') || 'Buy'; b.classList.remove('confirm'); + if (S && W.signedIn() !== true) { b.disabled = W.signedIn() === null; b.textContent = W.signedIn() === null ? 'Loading…' : 'Sign in to buy'; return; } if (pv.all) { b.disabled = true; b.textContent = 'Owned'; return; } if (!W.unlimited() && have < cost) { b.disabled = true; b.innerHTML = 'Need ' + price(cost - have) + ' more'; return; } b.disabled = false; if (armed === id) { b.classList.add('confirm'); b.innerHTML = 'Tap again: ' + price(p.price); } else b.innerHTML = lab + ' ' + price(p.price); } + // With the server wallet buying needs a Google sign-in (account.js's button in the top bar). + function signIn() { try { if (window.SiteAccount && SiteAccount.signIn) SiteAccount.signIn().then(function () { W.refresh(); }, function () {}); } catch (e) {} } + var busy = false; // one purchase at a time (the server also does each request once) document.addEventListener('click', function (e) { var b = e.target.closest('button[data-pack]'); if (!b || b.disabled) return; var id = b.getAttribute('data-pack'); + if (S && W.signedIn() === false) { toast('Buying needs a Google sign-in.'); signIn(); return; } + if (busy) return; if (armed !== id) { armed = id; clearTimeout(armT); armT = setTimeout(function () { armed = null; draw(); }, 3000); draw(); return; } armed = null; clearTimeout(armT); - var r = C.buy(id); - if (!r.ok) { toast(r.reason === 'funds' ? 'Not enough emeralds yet.' : r.reason === 'owned' ? 'You already own ' + (/^item:/.test(id) ? 'this.' : 'everything in this pack.') : 'That didn’t work. Try again.'); draw(); return; } - if (r.got.draws.length) reveal(r); - else { var n = r.got.skins.length + r.got.acc.length + (r.got.items || []).length; toast('Added ' + n + (n === 1 ? ' item' : ' items') + ' to your locker' + (r.refund ? ', and ' + W.format(r.refund) + ' back for ones you had' : '') + '. You have ' + W.format(r.balance) + ' left.'); } - draw(); + busy = true; b.disabled = true; if (S) b.textContent = 'Buying…'; + Promise.resolve(C.buy(id)).then(function (r) { + busy = false; + if (!r.ok) { toast(r.reason === 'funds' ? 'Not enough emeralds yet.' : r.reason === 'owned' ? 'You already own ' + (/^item:/.test(id) ? 'this.' : 'everything in this pack.') : r.reason === 'signin' ? 'Buying needs a Google sign-in.' : r.message || 'That didn’t work. Try again.'); draw(); return; } + if (r.got.draws.length) reveal(r); + else { var n = r.got.skins.length + r.got.acc.length + (r.got.items || []).length; toast('Added ' + n + (n === 1 ? ' item' : ' items') + ' to your locker' + (r.refund ? ', and ' + W.format(r.refund) + ' back for ones you had' : '') + '. You have ' + W.format(r.balance) + ' left.'); } + draw(); + }, function () { busy = false; toast('That didn’t work. Try again.'); draw(); }); + }); + // Emerald packs (real money): Stripe Checkout through store.js; Stripe sends the tab back here afterwards. + document.addEventListener('click', function (e) { + var b = e.target.closest('button[data-emerald]'); if (!b || b.disabled) return; + if (W.signedIn() === false) { toast('Buying needs a Google sign-in.'); signIn(); return; } + b.disabled = true; b.textContent = 'Opening checkout…'; + W.buyEmeralds(b.getAttribute('data-emerald')).then(function (r) { + if (r.ok) return; + toast(r.reason === 'signin' ? 'Buying needs a Google sign-in.' : r.reason === 'closed' ? 'The shop isn’t open yet.' : r.message || 'Couldn’t start checkout. Try again in a minute.'); + draw(); + }); }); // ---------- Packs ---------- function packCard(p) { - var c = el('div', 'pack' + (p.kind === 'emeralds' ? ' money' : '')); + var c = el('div', 'pack' + (p.kind === 'emeralds' && !S ? ' money' : '')); if (p.kind === 'emeralds') p = { kind: 'emeralds', name: p.name, desc: p.emeralds.toLocaleString('en-US') + ' emeralds, to spend in the shop.', usd: p.usd, emeralds: p.emeralds, link: p.link, contents: {} }; var faces = ''; if (p.contents.skins) faces = p.contents.skins.map(function (id) { return C.avatarSvg(uid, 48, { look: { skin: id, accessories: {} } }); }).join(''); @@ -326,6 +368,11 @@

The shop isn’t open yet

c.innerHTML = '
' + faces + '
' + esc(p.name) + '
' + esc(p.desc) + '
'; if (p.kind === 'emeralds') { c.innerHTML += '
$' + p.usd.toFixed(2) + '
'; + if (S) { // the server wallet: Stripe Checkout (store.js), credited by the webhook + var sb = el('button', 'btn go', 'Buy for $' + p.usd.toFixed(2)); sb.type = 'button'; sb.setAttribute('data-emerald', p.id); + c.appendChild(sb); + return c; + } // Only a pack with a Payment Link pasted in wallet.js AND PAYMENTS switched on links anywhere; today none does. var live = !!(p.link && W.PAYMENTS && W.PAYMENTS.enabled && /^https:\/\/buy\.stripe\.com\//.test(p.link)); var mb = live ? el('a', 'btn go', 'Buy for $' + p.usd.toFixed(2)) : el('button', 'btn', 'Not available yet'); @@ -341,7 +388,7 @@

The shop isn’t open yet

} function drawPacks() { var t = document.getElementById('t-packs'); t.innerHTML = ''; - [['skins', 'Skin packs', 'A pack costs the same as its skins bought one by one. Every skin, accessory and game item can also be bought on its own in the Locker.'], ['accessories', 'Accessory packs', 'Wear one of each kind with any skin.']].concat(Object.keys(C.GAMES || {}).map(function (gm) { return ['items', C.GAMES[gm].name + ' packs', 'Things to wear in ' + C.GAMES[gm].name + '. Put them on here in your locker or in the game’s own garage.', gm]; }), [['draws', 'Chests', 'Bought with emeralds only. Odds for every chest: ' + C.RARITY.slice().reverse().map(function (r) { return r.name.toLowerCase() + ' ' + (r.w * 100 / C.RARITY_TOTAL) + '%'; }).join(', ') + '.'], ['emeralds', 'Buy emeralds', 'Packs of emeralds for real money (not loot chests). Buying them isn’t available yet.']]).forEach(function (g) { + [['skins', 'Skin packs', 'A pack costs the same as its skins bought one by one. Every skin, accessory and game item can also be bought on its own in the Locker.'], ['accessories', 'Accessory packs', 'Wear one of each kind with any skin.']].concat(Object.keys(C.GAMES || {}).map(function (gm) { return ['items', C.GAMES[gm].name + ' packs', 'Things to wear in ' + C.GAMES[gm].name + '. Put them on here in your locker or in the game’s own garage.', gm]; }), [['draws', 'Chests', 'Bought with emeralds only. Odds for every chest: ' + C.RARITY.slice().reverse().map(function (r) { return r.name.toLowerCase() + ' ' + (r.w * 100 / C.RARITY_TOTAL) + '%'; }).join(', ') + '.'], ['emeralds', 'Buy emeralds', S ? 'Packs of emeralds for real money (not loot chests). You pay on Stripe’s own page and come back here; the emeralds arrive a few seconds later. Buying needs a Google sign-in.' : 'Packs of emeralds for real money (not loot chests). Buying them isn’t available yet.']]).forEach(function (g) { var h = el('h3', null, esc(g[1])); t.appendChild(h); if (g[2]) t.appendChild(el('p', 'note', esc(g[2]))); var grid = el('div', 'grid'); grid.style.marginTop = '10px'; @@ -439,6 +486,21 @@

The shop isn’t open yet

function drawWallet() { var e = W.inEmeralds(), inf = W.unlimited(); + if (S) { + var bits = []; + if (C.previewing && C.previewing()) bits.push('Captains’ preview: only captains can open this shop until it launches.'); + if (W.testMode()) bits.push('Test modeStripe sandbox: no real money is taken.'); + modeBar.innerHTML = bits.join(''); modeBar.hidden = !bits.length; + var sn = document.getElementById('signinNote'), st = W.state(); + sn.hidden = !(st.signedIn === false || st.closed); + if (!sn.hidden) sn.innerHTML = st.closed ? 'The shop isn’t open to this account yet.' : 'Buying needs a Google sign-in. Your emeralds and items stay with your Google account.'; + if (W.signedIn() !== true && !inf) { + document.getElementById('wEm').innerHTML = EM + ' —'; + document.getElementById('wMa').textContent = W.signedIn() === false ? 'Sign in' : '…'; + document.getElementById('wallet').title = W.signedIn() === false ? 'Sign in with Google to see your emeralds.' : ''; + return; + } + } document.getElementById('wEm').innerHTML = EM + ' ' + (inf ? '∞' : e.emeralds.toLocaleString('en-US')); document.getElementById('wMa').innerHTML = inf ? 'Captain' : MANGO + ' ' + e.mangos + '/' + MPE; document.getElementById('wallet').title = inf ? 'Captains have no limit: everything is free and owned.' : W.format(); @@ -479,7 +541,8 @@

The shop isn’t open yet

if (!gdlg) return; if (!r.ok) { yes.disabled = false; - gdlg.querySelector('#gerr').textContent = { signin: 'Sign in with Google to send gifts.', owned: pick.n + ' already has this.', busy: 'You have ' + W.GIFT_MAX + ' gifts still waiting to be opened. Try again once they are.', funds: 'Not enough emeralds yet.', recipient: pick.n + ' needs to sign in with Google first.', money: 'Emeralds and mangos can’t be gifted.' }[r.reason] || 'That didn’t work. Try again.'; + var gm = { signin: 'Sign in with Google to send gifts.', owned: pick.n + ' already has this.', busy: 'You have ' + W.GIFT_MAX + ' gifts still waiting to be opened. Try again once they are.', funds: 'Not enough emeralds yet.', recipient: pick.n + ' needs to sign in with Google first.', money: 'Emeralds and mangos can’t be gifted.' }; + gdlg.querySelector('#gerr').textContent = (S && r.reason !== 'signin' && r.reason !== 'funds' && r.message) || gm[r.reason] || r.message || 'That didn’t work. Try again.'; return; } close(); toast('Gift sent to ' + pick.n + '.' + (r.spent ? ' You have ' + W.format(r.balance) + ' left.' : '')); draw(); @@ -535,6 +598,31 @@

The shop isn’t open yet

} if (navigator.webdriver) window.__shop = { reveal: reveal, draw: draw, toast: toast, giftDialog: giftDialog }; + // ---------- The server wallet: sign-in changes and coming back from Stripe ---------- + if (S) { + document.addEventListener('click', function (e) { if (e.target.closest('#signinBtn')) signIn(); }); + var tries = 0; + (function hookAcct() { var A = window.SiteAccount; if (A && A.onChange) { A.onChange(function () { W.refresh(); }); return; } if (++tries < 60) setTimeout(hookAcct, 250); })(); + W.refresh().then(function () { draw(); returned(); }); + } + // Stripe sends the tab back with ?purchase=success&sku=emeralds_7&session=cs_… (or purchase=cancel). The webhook, + // not this page, adds the emeralds: wait for the wallet's ledger to show that Checkout session. + function returned() { + var q = new URLSearchParams(location.search), st = q.get('purchase'), sku = q.get('sku') || '', ses = q.get('session') || ''; + if ((st !== 'success' && st !== 'cancel') || !/^emeralds_\d+$/.test(sku)) return; + ['purchase', 'sku', 'session'].forEach(function (k) { q.delete(k); }); + try { history.replaceState(history.state, '', location.pathname + (q.toString() ? '?' + q : '') + location.hash); } catch (e) {} + if (st === 'cancel') { toast('Checkout cancelled: nothing was charged.'); return; } + var pk = (W.EMERALD_PACKS || []).filter(function (x) { return x.id === sku.replace(/_/g, '-'); })[0], end = Date.now() + 45000; + toast('Payment received. Adding your emeralds…'); + (function poll() { + var hit = W.state().recent.some(function (l) { return l[4] === ses; }); + if (hit) { toast('Added ' + (pk ? pk.emeralds.toLocaleString('en-US') + ' emeralds' : 'your emeralds') + '. You have ' + W.format() + '.'); draw(); return; } + if (Date.now() > end) { toast('Your emeralds are on their way: it can take a minute. Reload the page to check.'); return; } + setTimeout(function () { W.refresh().then(poll); }, 2000); + })(); + } + document.addEventListener('backroom:wallet', function () { draw(); }); document.addEventListener('backroom:captain', function () { draw(); }); document.addEventListener('backroom:gift', function (e) { var d = e.detail || {}; if (d.got && d.got.draws && d.got.draws.length) reveal({ got: d.got }); draw(); }); diff --git a/e63334287a3deaa3/shop/tests/shop.test.mjs b/e63334287a3deaa3/shop/tests/shop.test.mjs new file mode 100644 index 00000000..043f11aa --- /dev/null +++ b/e63334287a3deaa3/shop/tests/shop.test.mjs @@ -0,0 +1,238 @@ +// The shop page in a real browser (Playwright), with the server wallet. The page's requests to https://ascoding11.com/api +// are answered by the real Pages Functions (functions/api/*) running here in node over the fake Firestore and Stripe of +// tests/fakes.mjs: no real Stripe, Firestore, Realtime Database or Google is reached (firebaseio, gstatic, account.js, +// analytics and fonts are blocked; account.js is replaced by a stand-in Google sign-in). +// python3 -m http.server 8962 (from the repo root, in another terminal) +// node e63334287a3deaa3/shop/tests/shop.test.mjs +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { execFileSync } from 'node:child_process'; +import { makeKeys, fakeFirestore, fakeStripe, fakeFetch, stripeSig } from './fakes.mjs'; +import { CATALOG, encFields } from '../../../functions/_wallet.js'; +import { OWNERS } from '../../../functions/_captains.js'; +import * as checkout from '../../../functions/api/checkout.js'; +import * as webhook from '../../../functions/api/stripe-webhook.js'; +import * as wallet from '../../../functions/api/wallet/index.js'; +import * as buy from '../../../functions/api/wallet/buy.js'; +import * as chest from '../../../functions/api/wallet/chest.js'; +import * as gift from '../../../functions/api/wallet/gift.js'; +import * as seen from '../../../functions/api/wallet/seen.js'; +const require = createRequire(import.meta.url); +const { chromium } = require('playwright'); + +const BASE = 'http://localhost:8962', SHOP = BASE + '/e63334287a3deaa3/shop/', HUB = BASE + '/e63334287a3deaa3/'; +const OUT = process.env.SHOTS || '/tmp/claude-0/-home-user-ASCoding11-github-io/b2f6a318-3df9-5dc9-95b8-6c60ee130ed1/scratchpad/overnight/wallet-server/shots'; +execFileSync('mkdir', ['-p', OUT]); +const keys = await makeKeys(); +const FAKE_SK = 'sk_' + 'test_' + 'not-a-real-key', FAKE_WH = 'wh' + 'sec_' + 'not-a-real-secret'; +let env = { STRIPE_SECRET_KEY: FAKE_SK, STRIPE_WEBHOOK_SECRET: FAKE_WH, FIREBASE_SERVICE_ACCOUNT: keys.serviceAccount, ALLOWED_ORIGINS: BASE }; +const PRICES = {}; Object.entries(CATALOG.EMERALDS).forEach(([k, e]) => { PRICES[k] = { id: 'price_' + k, unit_amount: e.cents, currency: 'usd', type: 'one_time' }; }); +let fs, st; +function world() { fs = fakeFirestore(); st = fakeStripe(JSON.parse(JSON.stringify(PRICES))); } +world(); +globalThis.fetch = (u, o) => fakeFetch(keys, fs, st)(u, o); +const ROUTES = { 'checkout': checkout, 'wallet': wallet, 'wallet/buy': buy, 'wallet/chest': chest, 'wallet/gift': gift, 'wallet/seen': seen }; +const apiCalls = []; +const ALICE = 'aliceAAAAAAAAAAAAAAAAAAAAAA1', BOB = 'bobBBBBBBBBBBBBBBBBBBBBBBBB2', CAP = OWNERS[0]; +const seed = (uid, w) => fs.docs.set('wallets/' + uid, { fields: encFields(Object.assign({ balance: 0, owned: {}, recent: [], notices: [], reqs: {}, created: 1, updated: 1 }, w)), v: 1 }); +const bal = (uid) => Number(fs.docs.get('wallets/' + uid).fields.balance.integerValue); +const errors = []; + +async function open(viewport, o) { + const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] }); + const ctx = await browser.newContext({ viewport, deviceScaleFactor: 1, hasTouch: viewport.width < 600, isMobile: viewport.width < 600 }); + // Nothing real: no database, no Google, no analytics, no fonts. + await ctx.route(/firebaseio\.com|gstatic\.com|googleapis\.com|googlesyndication|analytics\/tracker|fonts\.g/, r => r.abort()); + await ctx.route('**/account/account.js', r => r.fulfill({ contentType: 'text/javascript', body: '/* the test stand-in for account.js is in the init script */' })); + await ctx.route('https://checkout.stripe.com/**', r => r.fulfill({ contentType: 'text/html', body: 'Stripe Checkout (test stand-in)

Stripe Checkout (test stand-in)

' })); + if (o.paymentsOn) await ctx.route('**/e63334287a3deaa3/wallet.js', async r => { const res = await r.fetch(); r.fulfill({ response: res, body: (await res.text()).replace('enabled: false,', 'enabled: true,') }); }); + // The API: the real Pages Functions over the fake Firestore and Stripe. + await ctx.route('https://ascoding11.com/api/**', async r => { + const req = r.request(), url = new URL(req.url()), p = url.pathname.replace(/^\/api\//, ''); + const cors = { 'Access-Control-Allow-Origin': BASE, 'Access-Control-Allow-Headers': 'Authorization, Content-Type', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS' }; + if (req.method() === 'OPTIONS') return r.fulfill({ status: 204, headers: cors }); + const mod = ROUTES[p]; if (!mod) return r.fulfill({ status: 404, headers: cors, body: '{}' }); + apiCalls.push(req.method() + ' ' + p); + const h = Object.assign({}, await req.allHeaders(), { origin: BASE }); + const request = new Request(url.toString(), { method: req.method(), headers: h, body: req.method() === 'POST' ? req.postData() : undefined }); + const res = await (req.method() === 'GET' ? mod.onRequestGet : mod.onRequestPost)({ request, env }); + r.fulfill({ status: res.status, headers: Object.assign({ 'Content-Type': 'application/json' }, cors), body: await res.text() }); + }); + const token = o.uid ? await keys.token(o.uid) : ''; + await ctx.addInitScript(([uid, token]) => { + const u = uid ? { uid, isAnonymous: false, providerData: [{ providerId: 'google.com' }], getIdToken: () => Promise.resolve(token) } : null; + window.SiteAccount = { boot: () => Promise.resolve(u), user: () => u, signIn: () => Promise.resolve(u), onChange: () => {} }; + }, [o.uid || '', token]); + const page = await ctx.newPage(); + page.setDefaultTimeout(15000); + page.on('pageerror', e => errors.push(String(e))); + return { browser, page }; +} +const shot = (page, name) => page.screenshot({ path: OUT + '/' + name + '.png' }); +async function openShop(page, o) { + await page.goto(SHOP + (o.query || '')); + if (o.captainAs) await page.evaluate(id => window.__captains.as(id), o.captainAs); + await page.waitForSelector('.topbar', { timeout: 8000 }); + await page.waitForFunction(() => window.BackRoomWallet.state().ready, null, { timeout: 8000 }); + await page.evaluate(() => window.__shop && window.__shop.draw()); +} +async function noOverlap(page) { + return page.evaluate(() => { + const vw = innerWidth, bad = []; + if (document.documentElement.scrollWidth > vw + 1) bad.push('page scrolls sideways ' + document.documentElement.scrollWidth); + const tb = document.querySelector('.topbar').getBoundingClientRect(); + document.querySelectorAll('.topbar > *').forEach(e => { const r = e.getBoundingClientRect(); if (r.right > vw + 1 || r.width && r.bottom > tb.bottom + 1) bad.push('topbar child out ' + (e.id || e.className)); }); + const kids = [...document.querySelectorAll('.topbar > *')].filter(e => e.getBoundingClientRect().width > 2); + for (let i = 0; i < kids.length; i++) for (let j = i + 1; j < kids.length; j++) { const a = kids[i].getBoundingClientRect(), b = kids[j].getBoundingClientRect(); if (a.left < b.right - 1 && b.left < a.right - 1 && a.top < b.bottom - 1 && b.top < a.bottom - 1) bad.push('overlap ' + (kids[i].className || kids[i].id) + ' / ' + (kids[j].className || kids[j].id)); } + return bad; + }); +} +async function twoTap(page, sel) { await page.click(sel); await page.click(sel); } + +let passed = 0; const tests = []; +const test = (name, fn) => tests.push([name, fn]); +const SIZES = [['laptop', { width: 1366, height: 768 }], ['phone', { width: 390, height: 844 }]]; +const RARE = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][0] === 'rare' && CATALOG.ITEMS[id][1] === 's'); + +for (const [sz, vp] of SIZES) { + test(sz + ': captains’ preview (PAYMENTS off): opens for a captain only, server wallet, Test mode tag, chest, gift, emeralds to Checkout', async () => { + world(); CATALOG.PUBLIC = false; seed(BOB, {}); + // a non-captain: still "not open yet", and no API call is made + let { browser, page } = await open(vp, { uid: ALICE }); + apiCalls.length = 0; + await page.goto(SHOP); await page.evaluate(id => window.__captains.as(id), ALICE); await page.waitForTimeout(400); + assert.equal(await page.isVisible('#closed'), true); assert.equal(await page.$('.topbar'), null); assert.equal(apiCalls.length, 0); + await browser.close(); + ({ browser, page } = await open(vp, { uid: CAP })); + await openShop(page, { captainAs: CAP }); + assert.equal(await page.isVisible('#closed'), false); + assert.equal(await page.evaluate(() => sessionStorage.getItem('cosmetics:preview')), '1'); + assert.match(await page.textContent('#modebar'), /Captains’ preview/); + assert.equal(await page.isVisible('#testTag'), true, 'Test mode tag shown for a test key'); + assert.match(await page.textContent('#wEm'), /∞/); + assert.deepEqual(await noOverlap(page), []); + await shot(page, sz + '-preview'); + // a chest: free for a captain, rolled by the server + await twoTap(page, '#drawbtns button[data-pack="draw-1"]'); + await page.waitForSelector('#reveal .card', { timeout: 8000 }); + assert.equal(fs.docs.get('wallets/' + CAP).fields.balance.integerValue, '0'); + await shot(page, sz + '-preview-chest'); + await page.click('#reveal .done'); + // a gift to Bob (who has a wallet), free for a captain + await page.evaluate(() => { window.BackRoomWallet.giftPeople = () => Promise.resolve([{ uid: 'bobBBBBBBBBBBBBBBBBBBBBBBBB2', n: 'Bob', from: 'online' }]); }); + await page.evaluate(id => window.__shop.giftDialog(id), 'item:' + RARE); + await page.click('#giftdlg button[data-to]'); await page.fill('#gnote', 'From the captain'); + await page.click('#gyes'); + await page.waitForSelector('#giftdlg', { state: 'detached', timeout: 8000 }); + assert.ok(fs.docs.get('wallets/' + BOB).fields.owned.mapValue.fields[RARE], 'Bob owns the gift'); + // emeralds: Buy goes to Stripe Checkout (the test stand-in page) + await page.click('button[data-emerald="emeralds-7"]'); + await page.waitForURL(/checkout\.stripe\.com/, { timeout: 8000 }); + assert.equal(st.sessions[st.sessions.length - 1].params['metadata[sku]'], 'emeralds_7'); + // a captain who signs out: back to "not open yet" + await page.goto(SHOP); await page.evaluate(id => window.__captains.as(id), CAP); await page.waitForSelector('.topbar'); + await Promise.all([page.waitForNavigation(), page.evaluate(() => window.__captains.as(null))]); + await page.waitForTimeout(300); + assert.equal(await page.isVisible('#closed'), true); + await browser.close(); + }); + + test(sz + ': PAYMENTS on: balance, buy an item, open a chest, send a gift, buy emeralds and come back to the new balance', async () => { + world(); CATALOG.PUBLIC = true; seed(ALICE, { balance: 2000 }); seed(BOB, {}); + const { browser, page } = await open(vp, { uid: ALICE, paymentsOn: true }); + await openShop(page, {}); + assert.equal(await page.textContent('#wEm').then(t => t.trim()), '117'); // 2000 mangos = 117 emeralds 11 mangos + assert.match(await page.textContent('#wMa'), /11\/17/); + assert.equal(await page.isVisible('#modebar'), true); assert.equal(await page.isVisible('#testTag'), true); + assert.deepEqual(await noOverlap(page), []); + await shot(page, sz + '-open'); + // buy one item from the Locker + await page.click('.tabs button[data-tab="locker"]'); + await twoTap(page, `button.ibuy[data-pack="item:${RARE}"]`); + await page.waitForFunction(() => window.BackRoomWallet.balance() === 1580, null, { timeout: 8000 }); + assert.equal(bal(ALICE), 1580); + assert.equal(await page.$eval(`.item[data-item="${RARE}"]`, e => e.classList.contains('locked')), false, 'now owned in the locker'); + await shot(page, sz + '-locker'); + // a chest + await page.click('.tabs button[data-tab="packs"]'); + await twoTap(page, '#drawbtns button[data-pack="draw-1"]'); + await page.waitForSelector('#reveal .card', { timeout: 8000 }); + const after = bal(ALICE); assert.ok(after === 1580 - 119 || after === 1580 - 119 + 48); + await page.click('#reveal .done'); + // a gift + await page.evaluate(() => { window.BackRoomWallet.giftPeople = () => Promise.resolve([{ uid: 'bobBBBBBBBBBBBBBBBBBBBBBBBB2', n: 'Bob', from: 'online' }]); }); + await page.evaluate(() => window.__shop.giftDialog('item:pom-beanie')); + await page.click('#giftdlg button[data-to]'); await page.click('#gyes'); + await page.waitForSelector('#giftdlg', { state: 'detached', timeout: 8000 }); + assert.equal(bal(ALICE), after - 60); + // emeralds: Checkout, then Stripe's webhook, then back to the shop + await page.click('button[data-emerald="emeralds-39"]'); + await page.waitForURL(/checkout\.stripe\.com/, { timeout: 8000 }); + const s = st.sessions[st.sessions.length - 1]; + assert.equal(s.params['metadata[uid]'], ALICE); + const raw = JSON.stringify({ id: 'evt_1', type: 'checkout.session.completed', created: Math.floor(Date.now() / 1000), data: { object: { + id: s.id, mode: 'payment', payment_status: 'paid', amount_total: 499, currency: 'usd', client_reference_id: ALICE, metadata: { uid: ALICE, sku: 'emeralds_39', kind: 'emeralds' } } } }); + const wr = await webhook.onRequestPost({ request: new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': await stripeSig(raw, FAKE_WH) }, body: raw }), env }); + assert.equal(wr.status, 200); + await page.goto(s.params.success_url.replace('{CHECKOUT_SESSION_ID}', s.id)); + await page.waitForFunction(n => window.BackRoomWallet.balance() === n, after - 60 + 39 * 17, { timeout: 8000 }); + await page.waitForFunction(() => /Added 39 emeralds/.test(document.getElementById('toast').textContent), null, { timeout: 8000 }); + assert.equal(new URL(page.url()).search, '', 'the return address is tidied'); + await shot(page, sz + '-back-from-stripe'); + // the history tab shows the server's ledger + await page.click('.tabs button[data-tab="history"]'); + assert.match(await page.textContent('#t-history'), /Bought Emerald Pouch/); + await browser.close(); + }); + + test(sz + ': PAYMENTS on, signed out: "Buying needs a Google sign-in", nothing is bought', async () => { + world(); CATALOG.PUBLIC = true; + const { browser, page } = await open(vp, { uid: '', paymentsOn: true }); + await openShop(page, {}); + assert.equal(await page.isVisible('#signinNote'), true); + assert.match(await page.textContent('#signinNote'), /Buying needs a Google sign-in/); + assert.match(await page.textContent('#drawbtns'), /Sign in to buy/); + await page.click('#drawbtns button[data-pack="draw-1"]'); + await page.waitForFunction(() => /Google sign-in/.test(document.getElementById('toast').textContent)); + assert.deepEqual(await noOverlap(page), []); + await shot(page, sz + '-signed-out'); + assert.equal(fs.writes, 0); + await browser.close(); + }); +} + +test('everything off: the shop and the Back Room page are the same as before this change', async () => { + const base = execFileSync('git', ['merge-base', 'HEAD', 'origin/coin-economy']).toString().trim(); + const old = {}; + for (const f of ['e63334287a3deaa3/cosmetics.js', 'e63334287a3deaa3/wallet.js', 'e63334287a3deaa3/shop/index.html', 'e63334287a3deaa3/slipstream/garage.js']) + old['/' + f] = execFileSync('git', ['show', base + ':' + f], { maxBuffer: 1 << 26 }).toString(); + const look = async (useOld, url, uid) => { + const { browser, page } = await open({ width: 1366, height: 768 }, { uid }); + const reqs = []; + page.on('request', r => reqs.push(r.url())); + if (useOld) await page.route(u => old[new URL(u).pathname.replace(/\/$/, '/index.html')] !== undefined || old[new URL(u).pathname + 'index.html'] !== undefined, r => { + const pth = new URL(r.request().url()).pathname, body = old[pth] || old[pth + 'index.html']; + r.fulfill({ contentType: /\.html$|\/$/.test(pth) ? 'text/html' : 'text/javascript', body }); + }); + await page.goto(url); await page.waitForTimeout(2500); + const out = await page.evaluate(() => ({ text: document.body.innerText.replace(/\d+/g, '#'), chip: !!document.getElementById('brc-chip'), topbar: !!document.querySelector('.topbar .wallet'), wallet: localStorage.getItem('wallet:v1'), cos: localStorage.getItem('cosmetics:v1'), preview: sessionStorage.getItem('cosmetics:preview') })); + out.api = reqs.filter(u => /ascoding11\.com\/api|\/store\.js/.test(u)); + out.png = await page.screenshot(); + await browser.close(); + return out; + }; + for (const [url, uid] of [[SHOP, ALICE], [SHOP, CAP], [HUB, ALICE]]) { + const a = await look(true, url, uid), b = await look(false, url, uid); + assert.equal(b.text, a.text, url); assert.equal(b.chip, false); assert.equal(b.topbar, a.topbar); assert.equal(b.wallet, null); assert.equal(b.cos, null); assert.equal(b.preview, null); + assert.deepEqual(b.api, []); + if (url === SHOP) assert.ok(a.png.equals(b.png), 'shop screenshot is pixel-identical: ' + url + ' ' + uid); + } +}); + +for (const [name, fn] of tests) { + try { await Promise.race([fn(), new Promise((_, no) => setTimeout(() => no(new Error('test took over 120 s')), 120000))]); passed++; console.log('ok ' + name); } + catch (e) { console.log('FAIL ' + name + '\n ' + (e.stack || e).toString().split('\n').slice(0, 5).join('\n ')); process.exitCode = 1; } +} +const errs = errors.filter(e => !/firebase|gstatic|Failed to fetch|NetworkError|net::/i.test(e)); +if (errs.length) { console.log('page errors:\n ' + errs.join('\n ')); process.exitCode = 1; } +console.log(passed + '/' + tests.length + ' passed' + (errs.length ? ', with page errors' : '')); diff --git a/e63334287a3deaa3/slipstream/garage.js b/e63334287a3deaa3/slipstream/garage.js index cc7c3ce0..bd2f0a24 100644 --- a/e63334287a3deaa3/slipstream/garage.js +++ b/e63334287a3deaa3/slipstream/garage.js @@ -903,7 +903,10 @@ function onActClick(e){ } if(act==='st-remove'){setSticker(null);G.draft.t='';$('gsText').value='';m.className='msg';m.textContent='Sticker removed.';renderAct();refreshPv();return} const it=BY_ID[G.sel];if(!it)return; - if(act==='buy'){const pk=packOf(it),r=pk?C.buy(pk.id):{ok:false};if(!r.ok){renderAct();return}wear(it)} + if(act==='buy'){const pk=packOf(it),r=pk?C.buy(pk.id):{ok:false}; + // the server wallet (wallet.js PAYMENTS.enabled): buy() answers with a promise + if(r&&typeof r.then==='function'){r.then(x=>{if(x&&x.ok)wear(it);mine=null;G.tryOn={};showBalance();keepScroll(render);refreshPv()});return} + if(!r.ok){renderAct();return}wear(it)} else if(act==='wear')wear(it); else if(act==='off')takeOff(it.id); mine=null;G.tryOn={};showBalance();keepScroll(render);refreshPv(); diff --git a/e63334287a3deaa3/wallet.js b/e63334287a3deaa3/wallet.js index 63ec4c4a..78efdc27 100644 --- a/e63334287a3deaa3/wallet.js +++ b/e63334287a3deaa3/wallet.js @@ -18,8 +18,14 @@ * (cosmetics.js PRICE). Play pays nothing and there is no welcome gift (PLAY_PAYS below is false, on purpose; the EARN * table is kept in case that ever changes). * - * Money. There is no way to put real money in yet and there is no payment code here: PAYMENTS is a switched-off hook - * that says what a real setup needs. Read it before turning it on. + * Money. Emeralds are sold for real money by the server (functions/: Stripe Checkout, the webhook and Firestore + * wallets/{uid}; see functions/_wallet.js and README). Whenever cosmetics.js says the server wallet is in use + * (BackRoomCosmetics.server(): PAYMENTS.enabled below, or the captains' preview on the shop page), this file keeps NO + * balance of its own: it reads the balance, what's owned, gift notices and the last ledger lines from GET /api/wallet, + * and sends every purchase, chest and gift to the server ("The server wallet" below). Earning, syncing into the stats + * node, weekly titles, the Aisle reward and the old node gifts are all off then. Everything else in this file (the + * browser-only balance, the node mirror, rewards) is the old local mode, kept only for the localhost test switch + * (?cosmetics=1 on localhost or in an automated browser). * * Earning. Games already report wins, kills, escapes, laps and bests through stats.js (BackRoomStats.add / max / min). * This file wraps those three functions (in the page itself, and in any same-origin game frame a hub page opens) and @@ -156,25 +162,20 @@ ]; /* - * PAYMENTS: the hook for buying emeralds with real money. SWITCHED OFF, and there is deliberately no payment code here. - * - * A static site can't take money safely: anything the browser does, the player can change, so the browser must never be - * the one that says "paid, add 7 emeralds". A real setup needs: - * 1. Stripe prices (or Payment Links) for the EMERALD_PACKS above (e.g. lookup key emeralds_7). - * 2. A server (a Cloud Function, or the Cloudflare Pages Functions this repo already has for the item shop: store.js - * and functions/api/checkout.js, see README) that checks the player's Google sign-in and creates a Stripe Checkout - * Session for the pack. checkout() below would call it and send the player to Stripe's page (store.js shows how). - * 3. A Stripe webhook (like functions/api/stripe-webhook.js) that, only when Stripe says the payment finished, adds - * the pack's mangos to a server-held ledger (e.g. Firestore wallets/{uid}, written only with a service account). - * 4. Security rules so players can read but never write that ledger, and this file reading the balance from it. - * While the balance lives in the player's own stats node (today), bought emeralds could be faked, so turning this - * on without steps 3 and 4 would be selling nothing. - * Until then checkout() only answers that buying isn't available. + * PAYMENTS: THE ONE SWITCH for the real shop. enabled: true opens the shop to every signed-in player, with the server + * wallet (functions/_wallet.js): emeralds bought through Stripe Checkout (store.js's Store.buy with the pack's lookup + * key, emeralds_7 … emeralds_4000), credited only by the Stripe webhook, and every purchase, chest and gift made on the + * server. Whether the money is real is decided only by the Stripe key in Cloudflare (sk_test_… is the sandbox; the shop + * then shows a "Test mode" tag). After changing enabled, run node e63334287a3deaa3/shop/tools/server-data.js and commit + * functions/_catalog.js: the server reads the switch from there (while it says false, only captains get in). + * While enabled is false the public site is exactly as before: the shop says it isn't open, except the captains' + * preview (cosmetics.js CAPTAIN_PREVIEW). The `link` fields of EMERALD_PACKS above are not used. */ var PAYMENTS = { provider: 'stripe', enabled: false, checkout: function (packId) { + if (server()) return buyEmeralds(packId); return Promise.resolve({ ok: false, reason: 'not-available', pack: String(packId || ''), message: 'Buying emeralds isn’t available yet.' }); } }; @@ -244,7 +245,7 @@ } // One change to the balance, read fresh from storage (another tab may have changed it a moment ago). function change(delta, reason, game) { - if (!on() || !int(delta) || delta === 0) return false; + if (!on() || server() || !int(delta) || delta === 0) return false; var w = load(), b = bal(w); if (delta < 0 && b + delta < 0) return false; if (delta > 0 && game) { @@ -263,7 +264,7 @@ return after; } - function balance() { return on() ? bal(load()) : 0; } + function balance() { return on() ? (server() ? SV.balance : bal(load())) : 0; } function inEmeralds(m) { m = m == null ? balance() : m; if (!int(m) || m < 0) m = 0; return { emeralds: Math.floor(m / MANGOS_PER_EMERALD), mangos: m % MANGOS_PER_EMERALD }; } function format(m, short) { if (m == null && unlimited()) return '∞'; // a captain: no balance to show @@ -272,9 +273,9 @@ var s = e.emeralds.toLocaleString('en-US') + (e.emeralds === 1 ? ' emerald' : ' emeralds'); return e.mangos ? s + ' ' + e.mangos + (e.mangos === 1 ? ' mango' : ' mangos') : s; } - function earn(mangos, reason) { if (!int(mangos) || mangos < 1 || mangos > MAX_GRANT) return false; return change(mangos, reason || 'earned'); } + function earn(mangos, reason) { if (server() || !int(mangos) || mangos < 1 || mangos > MAX_GRANT) return false; return change(mangos, reason || 'earned'); } function spend(mangos, reason) { - if (!int(mangos) || mangos < 1) return false; + if (server() || !int(mangos) || mangos < 1) return false; // the server wallet: purchases go to the server if (unlimited()) { var b = bal(load()); addLog(0, b, why('Free (captain): ' + (reason || 'spent'))); fire(b, 0, why(reason)); return b; } // captains are never charged return change(-mangos, reason || 'spent'); } @@ -282,7 +283,7 @@ // ---------------- Earning from play (stats.js's hooks) ---------------- function baseStat(k) { return String(k).split(':')[0].replace(/-(w\d+|easy|medium|hard)$/, ''); } function onStat(game, how, k, v) { - if (!PLAY_PAYS || !on() || !okGame(game) || typeof k !== 'string') return; + if (!PLAY_PAYS || !on() || server() || !okGame(game) || typeof k !== 'string') return; var rule = EARN[game] || EARN['*'], name = baseStat(k), pay = 0; if (how === 'add') { var n = Number(v == null ? 1 : v); @@ -329,6 +330,11 @@ } function start() { if (!on()) return; + if (server()) { // the server wallet: just read it, now and on coming back + refresh(); + document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') refresh(); }); + return; + } var tries = 0; (function look() { if (!hookStats(window.BackRoomStats) && ++tries < 20) setTimeout(look, 500); })(); watchFrames(); @@ -380,6 +386,7 @@ // One sync: add this browser's pend to the node's balance, join the lockers, all in one transaction on w. function sync() { if (!on()) return Promise.resolve(false); + if (server()) return refresh().then(function () { return true; }); if (syncing) { again = true; return syncing; } syncing = getConn().then(function (c) { var u = c.user(); @@ -444,7 +451,7 @@ // Captains (captains.js, which asks miles.js's OWNERS; Vice Captains are not captains here) have no limit: their // balance shows ∞, spending never charges them, they own everything (cosmetics.js) and gift for free. function captain() { try { return !!(window.BackRoomCaptains && window.BackRoomCaptains.captain && window.BackRoomCaptains.captain()); } catch (e) { return false; } } - function unlimited() { return on() && captain(); } + function unlimited() { return on() && (captain() || (server() && SV.captain)); } function isCaptainUid(u) { try { var M = window.BackRoomMiles; return !!(M && M.isOwner && M.isOwner(u)); } catch (e) { return false; } } function cleanText(t, max) { t = String(t == null ? '' : t).replace(/[|<>\u0000-\u001f\u007f​-‏‪-‮⁦-⁩]/g, '').replace(/\s+/g, ' ').trim().slice(0, max); @@ -515,7 +522,7 @@ * Returns { mangos, ... } or false. */ function grant(kind, d) { - if (!on() || !obj(d)) return false; + if (!on() || server() || !obj(d)) return false; // the server wallet: no claims from the browser (README) var w = load(); if (kind === 'title' || kind === 'aisle') { var key = kind === 'title' ? 'tw' : 'aw'; @@ -615,6 +622,7 @@ function gift(what, to, toName, note) { var C = window.BackRoomCosmetics; if (!on() || !C || !C.pack) return Promise.resolve({ ok: false, reason: 'off' }); + if (server()) return svGift(what, to, toName, note); return getConn().then(function (c) { return c.user(); }, function () { return null; }).then(function (u) { if (!googleOk(u) || !okUid(u.uid)) return { ok: false, reason: 'signin' }; if (!okUid(to) || to === u.uid) return { ok: false, reason: 'self' }; @@ -650,6 +658,7 @@ var scanning = null; function scan(force) { if (!on()) return Promise.resolve(false); + if (server()) return refresh().then(function () { return true; }); // gift notices come with the wallet if (scanning) return scanning; var at = +(ls('wallet:scan') || 0); if (!force && Date.now() - at < SCAN_MS && lastVal) return Promise.resolve(false); @@ -706,13 +715,110 @@ }).catch(function () { return []; }); } + // ---------------- The server wallet (functions/_wallet.js, on ascoding11.com) ---------------- + // In use whenever BackRoomCosmetics.server() says so. SV is the last answer from GET /api/wallet (or from a purchase, + // which returns the same state); nothing of it is saved in this browser. Requests carry the Google sign-in's ID token + // (store.js's Store.user(): the page's account.js sign-in), the same as the item shop. + var API = /(^|\.)ascoding11\.com$/.test(location.hostname) ? '/api/' : 'https://ascoding11.com/api/'; + var SV = { ready: false, signedIn: null, closed: false, error: '', balance: 0, owned: [], recent: [], notices: [], captain: false, test: false }; + function server() { try { var C = window.BackRoomCosmetics; return !!(C && C.server && C.server()); } catch (e) { return false; } } + var storeP = null; + function store() { + if (window.Store) return Promise.resolve(window.Store); + if (!storeP) { storeP = load1('/store.js').then(function () { return window.Store || null; }); storeP.catch(function () { storeP = null; }); } + return storeP; + } + function rid() { var s = ''; try { var a = new Uint8Array(16); crypto.getRandomValues(a); for (var i = 0; i < 16; i++) s += 'abcdefghijklmnopqrstuvwxyz0123456789'.charAt(a[i] % 36); } catch (e) { s = (Math.random().toString(36) + Math.random().toString(36)).replace(/[^a-z0-9]/g, '').slice(0, 16); } return s; } + function apiCall(path, body) { + return store().then(function (St) { return St ? St.user() : null; }).then(function (u) { + if (!u) { var e = new Error('Buying needs a Google sign-in.'); e.reason = 'signin'; throw e; } + return u.getIdToken().then(function (t) { + var h = { Authorization: 'Bearer ' + t }; if (body) h['Content-Type'] = 'application/json'; + return fetch(API + path, { method: body ? 'POST' : 'GET', headers: h, body: body ? JSON.stringify(body) : undefined }); + }); + }).then(function (r) { + return r.json().catch(function () { return {}; }).then(function (d) { + if (!r.ok) { var e = new Error(d.error || 'Something went wrong. Try again in a minute.'); e.reason = d.reason || (r.status === 401 ? 'signin' : 'server'); e.status = r.status; e.data = d; throw e; } + return d; + }); + }); + } + function adoptState(st) { + if (!obj(st) || !int(st.balance)) return; + var before = SV.balance; + SV.ready = true; SV.signedIn = true; SV.closed = false; SV.error = ''; + SV.balance = st.balance; SV.captain = !!st.captain; SV.test = !!st.test; + SV.owned = Array.isArray(st.owned) ? st.owned.filter(function (x) { return typeof x === 'string'; }) : []; + SV.recent = Array.isArray(st.recent) ? st.recent.filter(function (e) { return Array.isArray(e) && int(e[0]) && int(e[1]) && int(e[2]); }) : []; + SV.notices = Array.isArray(st.notices) ? st.notices.filter(obj) : []; + fire(SV.balance, SV.balance - before, 'server'); + showNotices(); + } + var refreshing = null; + // Read the wallet again. Resolves with SV whatever happens (signed out: SV.signedIn false; not open to this account: + // SV.closed; anything else: SV.error). + function refresh() { + if (!server()) return Promise.resolve(null); + if (refreshing) return refreshing; + refreshing = apiCall('wallet').then(function (d) { adoptState(d); return SV; }, function (e) { + if (e.reason === 'signin') { SV.signedIn = false; SV.balance = 0; SV.owned = []; SV.recent = []; SV.notices = []; SV.captain = false; } + else if (e.reason === 'closed') { SV.signedIn = true; SV.closed = true; } + else SV.error = e.message; + SV.ready = true; fire(SV.balance, 0, 'server'); + return SV; + }).then(function (r) { refreshing = null; return r; }); + return refreshing; + } + // One purchase, chest or gift. -> { ok: true, ... } or { ok: false, reason, message, need } + function svPost(path, body) { + if (!server()) return Promise.resolve({ ok: false, reason: 'off' }); + body.req = rid(); // the server does each request id once + return apiCall(path, body).then(function (d) { if (d.state) adoptState(d.state); return d; }, function (e) { + if (e.reason === 'signin') SV.signedIn = false; + return { ok: false, reason: e.reason || 'server', message: e.message, need: e.data && e.data.need }; + }); + } + function svBuy(what) { return svPost('wallet/buy', { what: String(what) }); } + function svChest(n) { return svPost('wallet/chest', { n: n }); } + function svGift(what, to, toName, note) { + if (!okUid(to)) return Promise.resolve({ ok: false, reason: 'self' }); + return svPost('wallet/gift', { what: String(what), to: to, toName: cleanText(toName, 14), fromName: myName(), note: cleanText(note, NOTE_MAX) }); + } + // Gift notices from the server: shown once, then marked seen. + var shownN = {}; + function showNotices() { + var fresh = SV.notices.filter(function (n) { return typeof n.id === 'string' && !shownN[n.id]; }); + if (!fresh.length) return; + fresh.forEach(function (n) { + shownN[n.id] = 1; + notice(cleanText(n.from, 14) + ' sent you a gift: ' + cleanText(n.what, 60) + (n.note ? ' “' + cleanText(n.note, NOTE_MAX) + '”' : '')); + try { document.dispatchEvent(new CustomEvent('backroom:gift', { detail: { from: n.from, name: n.what, note: n.note, got: n.got, refund: n.refund } })); } catch (e) {} + }); + apiCall('wallet/seen', { ids: fresh.map(function (n) { return n.id; }) }).catch(function () {}); + } + // Buy an emerald pack (wallet's EMERALD_PACKS id): Stripe Checkout through store.js, which signs the player in with + // Google first if needed and then sends the tab to Stripe; Stripe brings it back with ?purchase=success&sku=…&session=…. + function buyEmeralds(packId) { + var p = EMERALD_PACKS.filter(function (e) { return e.id === packId; })[0]; + if (!p) return Promise.resolve({ ok: false, reason: 'unknown' }); + return store().then(function (St) { + if (!St) throw new Error('Couldn’t reach the shop. Try again in a minute.'); + return St.buy(p.id.replace(/-/g, '_')); + }).then(function (d) { return { ok: true, url: d.url }; }, function (e) { + return { ok: false, reason: e.status === 401 || /sign in/i.test(e.message || '') ? 'signin' : e.status === 403 ? 'closed' : 'server', message: e.message }; + }); + } + // ---------------- API ---------------- window.BackRoomWallet = { balance: balance, inEmeralds: inEmeralds, format: format, earn: earn, spend: spend, - log: function () { return readLog(); }, on: on, sync: sync, + log: function () { return server() ? SV.recent.map(function (e) { return [e[0], e[1], e[2], String(e[3] || '')]; }) : readLog(); }, on: on, sync: sync, + // The server wallet (see above): whether it is in use, read it again, its state, and buying through it. + server: server, refresh: refresh, signedIn: function () { return SV.signedIn; }, testMode: function () { return server() && SV.test; }, + state: function () { return SV; }, buyEmeralds: buyEmeralds, _owned: function () { return SV.owned.slice(); }, _buy: svBuy, _chest: svChest, unlimited: unlimited, gift: gift, giftPeople: giftPeople, scan: scan, NOTE_MAX: NOTE_MAX, GIFT_MAX: GS_MAX, // The welcome gift (once per browser), given by the shop page the first time it opens. - welcome: function () { if (!on() || !(WELCOME > 0)) return false; var w = load(); if (w.gift) return false; w.gift = 1; save(w); return change(WELCOME, 'Welcome gift'); }, + welcome: function () { if (!on() || server() || !(WELCOME > 0)) return false; var w = load(); if (w.gift) return false; w.gift = 1; save(w); return change(WELCOME, 'Welcome gift'); }, MANGOS_PER_EMERALD: MANGOS_PER_EMERALD, EMERALD_PACKS: EMERALD_PACKS, EARN: EARN, PLAY_PAYS: PLAY_PAYS, PAYMENTS: PAYMENTS }; if (navigator.webdriver) window.__wallet = { From 8373c9852eac8850a32c619d1ecc732a07502b12 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:27:12 +0000 Subject: [PATCH 04/14] Shop: emerald Buy buttons carry their pack id; Playwright tests for the shop with the server wallet (preview, payments on, signed out, everything off) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/shop/index.html | 2 +- e63334287a3deaa3/shop/tests/shop.test.mjs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/e63334287a3deaa3/shop/index.html b/e63334287a3deaa3/shop/index.html index 20eedf2e..42784df7 100644 --- a/e63334287a3deaa3/shop/index.html +++ b/e63334287a3deaa3/shop/index.html @@ -358,7 +358,7 @@

The shop isn’t open yet

// ---------- Packs ---------- function packCard(p) { var c = el('div', 'pack' + (p.kind === 'emeralds' && !S ? ' money' : '')); - if (p.kind === 'emeralds') p = { kind: 'emeralds', name: p.name, desc: p.emeralds.toLocaleString('en-US') + ' emeralds, to spend in the shop.', usd: p.usd, emeralds: p.emeralds, link: p.link, contents: {} }; + if (p.kind === 'emeralds') p = { kind: 'emeralds', id: p.id, name: p.name, desc: p.emeralds.toLocaleString('en-US') + ' emeralds, to spend in the shop.', usd: p.usd, emeralds: p.emeralds, link: p.link, contents: {} }; var faces = ''; if (p.contents.skins) faces = p.contents.skins.map(function (id) { return C.avatarSvg(uid, 48, { look: { skin: id, accessories: {} } }); }).join(''); else if (p.contents.acc) faces = p.contents.acc.map(function (id) { var a = C.ACCESSORIES_BY_ID[id], o = {}; o[a.slot] = id; return C.avatarSvg(uid, 48, { look: { skin: null, accessories: o } }); }).join(''); diff --git a/e63334287a3deaa3/shop/tests/shop.test.mjs b/e63334287a3deaa3/shop/tests/shop.test.mjs index 043f11aa..127c53c8 100644 --- a/e63334287a3deaa3/shop/tests/shop.test.mjs +++ b/e63334287a3deaa3/shop/tests/shop.test.mjs @@ -130,7 +130,8 @@ for (const [sz, vp] of SIZES) { await page.waitForURL(/checkout\.stripe\.com/, { timeout: 8000 }); assert.equal(st.sessions[st.sessions.length - 1].params['metadata[sku]'], 'emeralds_7'); // a captain who signs out: back to "not open yet" - await page.goto(SHOP); await page.evaluate(id => window.__captains.as(id), CAP); await page.waitForSelector('.topbar'); + // (?preview=0 first: a tab that still has the preview flag reloads itself once captains.js's own check says "no captain") + await page.goto(SHOP + '?preview=0'); await page.evaluate(id => window.__captains.as(id), CAP); await page.waitForSelector('.topbar'); await Promise.all([page.waitForNavigation(), page.evaluate(() => window.__captains.as(null))]); await page.waitForTimeout(300); assert.equal(await page.isVisible('#closed'), true); From a38d9f9abadebbc91269399af2505213992ef3fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:29:08 +0000 Subject: [PATCH 05/14] Wallet server: filter gift notes and names with a server copy of namefilter.js (word lists generated, --check), refuse notes over 60 characters Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- README.md | 2 +- e63334287a3deaa3/shop/tests/server.test.mjs | 40 ++++++++++++++++++--- e63334287a3deaa3/shop/tools/server-data.js | 30 +++++++++++++--- functions/_namefilter.js | 3 ++ functions/_wallet.js | 40 ++++++++++++++++++++- functions/api/wallet/gift.js | 4 ++- 6 files changed, 106 insertions(+), 13 deletions(-) create mode 100644 functions/_namefilter.js diff --git a/README.md b/README.md index f773c6b7..36210177 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - **For games.** `BackRoomCosmetics.equipped()` returns `{skin, accessories: {slot: id}, colors}`, and `avatarSvg(uid, size)` returns the avatar wearing them. - **Storage.** Everything is in this browser: `wallet:v1` (`base` balance at last sync, `pend` change since, `su` synced uid, `dc` today's earnings per game, `dv` browser id), `wallet:dev`, `wallet:log` and `cosmetics:v1` (`s`, `a` owned ids, `e` worn per slot; `g` owned game items and `ge` worn per `game:slot`, written only once a game item is owned). Signed in with Google, the wallet is mirrored into the player's own stats node `rooms/lb-all/players/` as `w {v, b (mangos), s, a (owned bitmasks by item number), e ('s12,h3'), lh (log hash), t, tw, aw (claimed weeks), gc (claimed gifts: sender uid to time), gs (unopened gifts sent)}`, kept under 950 characters so the node stays under the boards' 8,000. This is a transaction on `w` that adds this browser's `pend` to the node's balance, so devices add up. The mirror waits until the node exists, and it rewrites `w` when a stats.js publish drops it. - **Local mode is not cheat-proof.** In the old browser-only mode (now only the `?cosmetics=1` test switch) the balance is self-reported: a player can edit their own storage and node. The server wallet below is what real money uses. - - **Server wallet (emeralds for real money).** Emeralds are sold for real money, so the balance and everything bought with it are held and changed only by the server: Cloudflare Pages Functions in `functions/` (`_wallet.js` and `api/wallet/`), writing Firestore with the service account, like the item shop (see `store.js` and `functions/` below). The server wallet is in use whenever `BackRoomCosmetics.server()` is true: `wallet.js`'s `PAYMENTS.enabled` (the one switch, false today), `ENABLED`, or the captains' preview. Then `wallet.js` keeps no balance of its own: it reads the balance, what's owned, gift notices and the last 40 ledger lines from `GET /api/wallet`, and sends every purchase (`POST /api/wallet/buy`, a pack or `item:`), chest (`POST /api/wallet/chest`, 1, 5 or 10, rolled on the server with crypto randomness) and gift (`POST /api/wallet/gift`, to a uid, note at most 60 characters) to the server; `POST /api/wallet/seen` drops gift notices the page has shown. `cosmetics.js` takes what's owned from the server (only what is worn, and the free items a game hands over itself, stay in `cosmetics:v1`) and its `buy()` then returns a promise (`slipstream/garage.js` handles that). Every endpoint needs the same verified Google sign-in as the item shop; signed out, the shop says "Buying needs a Google sign-in". Each change is one Firestore transaction (read, check balance, debit, grant, ledger) retried on conflicts, and each click carries a request id the server does only once, so double clicks and concurrent requests can't overspend. The server enforces the same numbers as the page: 17 mangos an emerald; items by rarity 60, 119, 420, 600, 1,200 mangos; a pack costs the sum of its items; a chest 119 mangos at 60 / 20 / 12.5 / 5 / 2.5 %, equal chance within a rarity; 48 mangos back for each skin or pack item already owned; captains (miles.js's `OWNERS`) are never charged, own everything, are never paid refunds, and can't be sent gifts; a gift costs the sender the same price, can only go to someone whose wallet exists (they have opened the shop once, signed in with Google), and a single item they already own is refused. Firestore: `wallets/{uid}` (`balance` in whole mangos, `owned {item id: time}`, `recent` last 40 ledger lines, `notices` unseen gifts, `reqs` the last 30 request ids), `ledger/{id}` (one row per change, never edited: `uid, t, d, b, w, r, kind`) and the existing `orders/{Checkout session id}` (for emeralds also `kind: 'emeralds'`, `mangos`, and `status` `credited` or `mismatch`). The pages never read or write these directly: the Firestore rules must keep them closed to browsers (they are today; this change doesn't touch the rules). The server's numbers come from the browser files: `node e63334287a3deaa3/shop/tools/server-data.js` writes `functions/_catalog.js` (from `cosmetics.js` and `wallet.js`, including `PAYMENTS.enabled`) and `functions/_captains.js` (from miles.js's `OWNERS`); run it after changing any price, item, pack, emerald pack or captain and commit both files; `--check` fails while they are out of date. Tests: `node e63334287a3deaa3/shop/tests/server.test.mjs` (the functions with Stripe and Firestore faked) and, with `python3 -m http.server 8962` running from the repo root, `node e63334287a3deaa3/shop/tests/shop.test.mjs` (the shop in Playwright, its API answered by the real functions over the fakes). + - **Server wallet (emeralds for real money).** Emeralds are sold for real money, so the balance and everything bought with it are held and changed only by the server: Cloudflare Pages Functions in `functions/` (`_wallet.js` and `api/wallet/`), writing Firestore with the service account, like the item shop (see `store.js` and `functions/` below). The server wallet is in use whenever `BackRoomCosmetics.server()` is true: `wallet.js`'s `PAYMENTS.enabled` (the one switch, false today), `ENABLED`, or the captains' preview. Then `wallet.js` keeps no balance of its own: it reads the balance, what's owned, gift notices and the last 40 ledger lines from `GET /api/wallet`, and sends every purchase (`POST /api/wallet/buy`, a pack or `item:`), chest (`POST /api/wallet/chest`, 1, 5 or 10, rolled on the server with crypto randomness) and gift (`POST /api/wallet/gift`, to a uid, note at most 60 characters) to the server; `POST /api/wallet/seen` drops gift notices the page has shown. `cosmetics.js` takes what's owned from the server (only what is worn, and the free items a game hands over itself, stay in `cosmetics:v1`) and its `buy()` then returns a promise (`slipstream/garage.js` handles that). Every endpoint needs the same verified Google sign-in as the item shop; signed out, the shop says "Buying needs a Google sign-in". Each change is one Firestore transaction (read, check balance, debit, grant, ledger) retried on conflicts, and each click carries a request id the server does only once, so double clicks and concurrent requests can't overspend. The server enforces the same numbers as the page: 17 mangos an emerald; items by rarity 60, 119, 420, 600, 1,200 mangos; a pack costs the sum of its items; a chest 119 mangos at 60 / 20 / 12.5 / 5 / 2.5 %, equal chance within a rarity; 48 mangos back for each skin or pack item already owned; captains (miles.js's `OWNERS`) are never charged, own everything, are never paid refunds, and can't be sent gifts; a gift costs the sender the same price, can only go to someone whose wallet exists (they have opened the shop once, signed in with Google), and a single item they already own is refused; the note (at most 60 characters, longer is refused) and the names shown with it go through the server's copy of `/namefilter.js` (`nameClean` in `functions/_wallet.js`, its word lists generated into `functions/_namefilter.js`), which masks a rude word and refuses a note hiding one of the worst ones. Firestore: `wallets/{uid}` (`balance` in whole mangos, `owned {item id: time}`, `recent` last 40 ledger lines, `notices` unseen gifts, `reqs` the last 30 request ids), `ledger/{id}` (one row per change, never edited: `uid, t, d, b, w, r, kind`) and the existing `orders/{Checkout session id}` (for emeralds also `kind: 'emeralds'`, `mangos`, and `status` `credited` or `mismatch`). The pages never read or write these directly: the Firestore rules must keep them closed to browsers (they are today; this change doesn't touch the rules). The server's numbers come from the browser files: `node e63334287a3deaa3/shop/tools/server-data.js` writes `functions/_catalog.js` (from `cosmetics.js` and `wallet.js`, including `PAYMENTS.enabled`) `functions/_captains.js` (from miles.js's `OWNERS`) and `functions/_namefilter.js` (`/namefilter.js`'s word lists, ROT13 as there); run it after changing any price, item, pack, emerald pack, captain or filtered word and commit all three; `--check` fails while they are out of date. Tests: `node e63334287a3deaa3/shop/tests/server.test.mjs` (the functions with Stripe and Firestore faked) and, with `python3 -m http.server 8962` running from the repo root, `node e63334287a3deaa3/shop/tests/shop.test.mjs` (the shop in Playwright, its API answered by the real functions over the fakes). - **Buying emeralds.** The shop's emerald packs have a Buy button that calls `BackRoomWallet.buyEmeralds(id)`, which uses `store.js`'s `Store.buy('emeralds_7')` (and so on): Google sign-in, then `/api/checkout`, which for the six emerald lookup keys skips the "already owned" check (they are consumables), refuses anyone but captains while `PAYMENTS.enabled` is false, and refuses a Stripe price whose amount or currency doesn't match the pack. Stripe sends the tab back to the shop with `?purchase=success&sku=emeralds_7&session=cs_…`; the webhook, and only the webhook, credits `wallets/{uid}` with emeralds × 17 mangos and a ledger line, exactly once per Checkout session (it reads and writes `orders/{session id}` in the same transaction), and only when the amount and currency paid match the pack (otherwise it records the order as `mismatch` and credits nothing). The shop waits for that ledger line and then shows the new balance. Whether money is real is decided only by the Stripe key in Cloudflare: with a test key (`sk_test_…`) the shop shows a "Test mode" tag (`GET /api/wallet` says `test: true`; the key itself is never sent). - **Captains' preview.** While `PAYMENTS.enabled` is false, a captain who opens `shop/` on the live site gets the real shop with the server wallet in that browser tab: once `captains.js` confirms the signed-in account is a captain, the page sets `sessionStorage['cosmetics:preview']` and opens, with a bar saying it is the captains' preview. Everyone else still sees "not open yet", and the server refuses everyone but captains (`functions/_catalog.js` `PUBLIC: false`), so the preview can't be opened by anyone else by editing their browser. If the account stops being a captain the tab goes back to "not open yet". **To turn the preview off**: set `var CAPTAIN_PREVIEW = false;` near the top of `cosmetics.js` (nothing else; the server needs no change). `?preview=0` on the shop page ends it for one tab. - **Setup checklist for the owners (nothing here works until this is done).** 1. Cloudflare (Workers & Pages → the site → Settings → Variables and secrets), names only, values never in the repo: `STRIPE_SECRET_KEY` (start with the test key `sk_test_…`), `STRIPE_WEBHOOK_SECRET` (`whsec_…` from step 3), `FIREBASE_SERVICE_ACCOUNT` (the whole JSON key of a service account of project rumblekarts that can write Firestore). The item shop already uses these three; nothing new is needed if they are set. 2. Stripe, in test mode first: on each of the six emerald prices set the lookup key `emeralds_7`, `emeralds_39`, `emeralds_80`, `emeralds_180`, `emeralds_1000`, `emeralds_4000` (one-time prices in USD of exactly $0.99, $4.99, $9.99, $19.99, $49.99, $99.99; any other amount is refused). 3. Stripe → Developers → Webhooks: an endpoint `https://ascoding11.com/api/stripe-webhook` with the events `checkout.session.completed` and `checkout.session.async_payment_succeeded` (the item shop's endpoint, if it exists, already is this); its signing secret is `STRIPE_WEBHOOK_SECRET`. 4. Check it worked: signed in with Google as a captain, open `https://ascoding11.com/e63334287a3deaa3/shop/`; the preview bar and the "Test mode" tag show, and the balance shows "∞". Buy the Emerald Handful with Stripe's test card 4242 4242 4242 4242; you come back to the shop, which says "Added 7 emeralds"; in Firebase's Firestore console `wallets/` has `balance` 119 and a `ledger` row, and `orders/` says `credited`; in Stripe the webhook delivery shows 200. Open a chest and send a gift to the other owner (who must have opened the shop once): their `wallets` document shows the item and a notice. 5. To go live: swap both Stripe values in Cloudflare for the live key and the live webhook's secret (with the same lookup keys on the live prices), set `PAYMENTS.enabled: true` in `wallet.js`, run `node e63334287a3deaa3/shop/tools/server-data.js`, and commit `wallet.js` and `functions/_catalog.js` together. diff --git a/e63334287a3deaa3/shop/tests/server.test.mjs b/e63334287a3deaa3/shop/tests/server.test.mjs index 204264ca..0d18962d 100644 --- a/e63334287a3deaa3/shop/tests/server.test.mjs +++ b/e63334287a3deaa3/shop/tests/server.test.mjs @@ -4,7 +4,8 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { makeKeys, fakeFirestore, fakeStripe, fakeFetch, stripeSig, plain } from './fakes.mjs'; -import { CATALOG, roll, cryptoNext, encFields } from '../../../functions/_wallet.js'; +import { CATALOG, roll, cryptoNext, encFields, nameClean } from '../../../functions/_wallet.js'; +import vm from 'node:vm'; import { OWNERS } from '../../../functions/_captains.js'; import * as checkout from '../../../functions/api/checkout.js'; import * as webhook from '../../../functions/api/stripe-webhook.js'; @@ -241,12 +242,12 @@ test('gift: sender pays, recipient owns it and gets a notice; refusals; seen cle assert.equal(nobody.status, 404); assert.equal(nobody.data.reason, 'recipient'); assert.equal(bal(ALICE), 1000); await call(wallet, 'GET', 'wallet', { as: BOB }); // Bob opens the shop once: his wallet now exists assert.equal(bal(BOB), 0); - const note = 'Happy birthday! '.repeat(6); + const note = 'Happy birthday! '.repeat(4).trim().slice(0, 60); const g = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE, to: BOB, toName: 'Bob', fromName: 'Alice ', note, req: 'giftreq0001' } }); assert.equal(g.status, 200); assert.equal(g.data.spent, 420); assert.equal(bal(ALICE), 580); const bw = doc('wallets/' + BOB); assert.ok(bw.owned[ITEM_RARE]); assert.equal(bw.balance, 0); - assert.equal(bw.notices.length, 1); assert.equal(bw.notices[0].from, 'Alice b'); assert.equal(bw.notices[0].note.length, 60); + assert.equal(bw.notices.length, 1); assert.equal(bw.notices[0].from, 'Alice b'); assert.equal(bw.notices[0].note, note); const again = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE, to: BOB } }); assert.equal(again.status, 409); assert.equal(again.data.reason, 'owned'); assert.equal(bal(ALICE), 580); assert.equal((await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_RARE2, to: ALICE } })).data.reason, 'self'); @@ -264,6 +265,34 @@ test('gift: sender pays, recipient owns it and gets a notice; refusals; seen cle assert.equal(s.data.notices.length, 0); assert.ok(st.data.recent.some(l => l[1] === 48 && /Gift from Alice/.test(l[3]))); }); +test('gift notes are filtered on the server: clean passes, rude masked, hidden-worst and 61 characters refused', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 5000 }); seed(BOB, {}); + const rot = w => w.replace(/[a-z]/g, c => String.fromCharCode((c.charCodeAt(0) - 84) % 26 + 97)); + const bad = rot('shpx'), bad2 = rot('fuvg'); // two words from namefilter.js's list (kept in ROT13 here too) + const send = (n, what) => call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: what, to: BOB, toName: 'Bob', fromName: 'Alice', note: n } }); + const items = Object.keys(CATALOG.ITEMS).filter(id => CATALOG.ITEMS[id][0] === 'common' && !CATALOG.ITEMS[id][3]); + const ok = await send('Have fun with this one!', 'item:' + items[0]); + assert.equal(ok.status, 200); + const masked = await send('you ' + bad + 'ing legend', 'item:' + items[1]); + assert.equal(masked.status, 200); + const ns = doc('wallets/' + BOB).notices; + assert.equal(ns[0].note, 'Have fun with this one!'); + assert.equal(ns[1].note, 'you ' + bad[0] + '******' + ' legend', 'masked like namefilter.js masks names'); + assert.ok(!ns[1].note.includes(bad)); + const hidden = await send(bad2.split('').join('.') + ' x', 'item:' + items[2]); + assert.equal(hidden.status, 400); assert.equal(hidden.data.reason, 'note'); + const long = await send('a'.repeat(61), 'item:' + items[3]); + assert.equal(long.status, 400); assert.equal(long.data.reason, 'note'); + assert.equal((await send('a'.repeat(60), 'item:' + items[3])).status, 200); + assert.equal(bal(ALICE), 5000 - 3 * 60, 'refused notes cost nothing'); + // the server's copy behaves exactly like /namefilter.js's NameFilter.clean + const ctx = { window: {}, document: { readyState: 'complete', addEventListener() {}, querySelectorAll: () => [] }, setTimeout() {} }; + vm.createContext(ctx); vm.runInContext(fs.readFileSync(path.join(ROOT, 'namefilter.js'), 'utf8'), ctx); + const samples = ['Morgan', 'Shiitake fan', 'grapes', 'therapist', bad, 'big_' + rot('fuvg'), bad.toUpperCase() + 'face', bad2.split('').join(' '), rot('ovgpu') + 'y day', + '5h' + rot('vg') + 'e', 'p0rn', 'nice ' + rot('cbea'), 'f' + 'uuuu' + bad.slice(1), 'hello there', 'x' + bad + 'x', 'a|b']; + for (const t of samples) assert.equal(nameClean(t), ctx.window.NameFilter.clean(t), 'same answer for ' + rot(t)); +}); test('chest odds over 1,000,000 server rolls are within 0.2 points', async () => { const next = cryptoNext(), n = 1000000, c = {}; for (let i = 0; i < n; i++) { const r = roll(next); c[r.rarity] = (c[r.rarity] || 0) + 1; } @@ -275,12 +304,13 @@ test('catalogue check: passes in sync, fails when cosmetics.js, wallet.js, miles execFileSync('node', [path.join(ROOT, 'e63334287a3deaa3/shop/tools/server-data.js'), '--check'], { stdio: 'pipe' }); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wallet-check-')); const copy = (f) => { fs.mkdirSync(path.dirname(path.join(tmp, f)), { recursive: true }); fs.copyFileSync(path.join(ROOT, f), path.join(tmp, f)); }; - ['e63334287a3deaa3/cosmetics.js', 'e63334287a3deaa3/wallet.js', 'e63334287a3deaa3/miles.js', 'e63334287a3deaa3/shop/tools/server-data.js', 'functions/_catalog.js', 'functions/_captains.js'].forEach(copy); + ['e63334287a3deaa3/cosmetics.js', 'e63334287a3deaa3/wallet.js', 'e63334287a3deaa3/miles.js', 'namefilter.js', 'e63334287a3deaa3/shop/tools/server-data.js', 'functions/_catalog.js', 'functions/_captains.js', 'functions/_namefilter.js'].forEach(copy); const run = () => { try { execFileSync('node', [path.join(tmp, 'e63334287a3deaa3/shop/tools/server-data.js'), '--check'], { stdio: 'pipe' }); return true; } catch (e) { return false; } }; assert.equal(run(), true); const edits = [['e63334287a3deaa3/cosmetics.js', 'common: 60,', 'common: 61,'], ['e63334287a3deaa3/wallet.js', 'emeralds: 39, usd: 4.99', 'emeralds: 40, usd: 4.99'], ['e63334287a3deaa3/wallet.js', 'enabled: false,', 'enabled: true,'], ['e63334287a3deaa3/miles.js', "'6QQvFAzdtMeJdAUSPwHd6v2zaDk1',", "'6QQvFAzdtMeJdAUSPwHd6v2zaDk1', 'someoneElse12345',"], - ['functions/_catalog.js', '"CHEST_PRICE": 119', '"CHEST_PRICE": 1']]; + ['functions/_catalog.js', '"CHEST_PRICE": 119', '"CHEST_PRICE": 1'], ['namefilter.js', "'shx'].map(rot)", "'shx', 'tbbsl'].map(rot)"], + ['functions/_namefilter.js', '"shpx",', '']]; for (const [f, a, b] of edits) { const p = path.join(tmp, f), was = fs.readFileSync(p, 'utf8'); assert.ok(was.includes(a), f + ' has ' + a); diff --git a/e63334287a3deaa3/shop/tools/server-data.js b/e63334287a3deaa3/shop/tools/server-data.js index e4bd681b..348d1d70 100644 --- a/e63334287a3deaa3/shop/tools/server-data.js +++ b/e63334287a3deaa3/shop/tools/server-data.js @@ -1,7 +1,7 @@ /* * The server wallet's copy of the shop's numbers, made from the browser files so the two can't drift apart. * - * node e63334287a3deaa3/shop/tools/server-data.js writes functions/_catalog.js and functions/_captains.js + * node e63334287a3deaa3/shop/tools/server-data.js writes functions/_catalog.js, _captains.js and _namefilter.js * node e63334287a3deaa3/shop/tools/server-data.js --check writes nothing; fails (exit 1) if either file is out of date * * Run it (without --check) after changing anything the server must agree on, then commit the two files it writes: @@ -10,6 +10,8 @@ * wallet.js MANGOS_PER_EMERALD, EMERALD_PACKS (count and dollar price of each pack; its Stripe lookup key is the * pack id with _ for -, e.g. emeralds_7), and PAYMENTS.enabled (the one switch: while it is false the * server only serves captains) + * /namefilter.js the rude-word lists (WORDS, WORST, SAFE, LEET), kept in ROT13 as there, for the server's check of + * gift notes (functions/_wallet.js cleanNote, a copy of NameFilter.clean) * miles.js OWNERS (captains: never charged, own everything, never paid rewards). Vice Captains are not included, * the same as captains.js. * The browser files are run in a sandbox the way a page runs them (no libraries); nothing else is read. @@ -20,6 +22,21 @@ const ROOT = path.join(__dirname, '..', '..', '..'); const BR = path.join(ROOT, 'e63334287a3deaa3'); const OUT_CAT = path.join(ROOT, 'functions', '_catalog.js'); const OUT_CAP = path.join(ROOT, 'functions', '_captains.js'); +const OUT_NF = path.join(ROOT, 'functions', '_namefilter.js'); + +// The word lists from /namefilter.js, as written there (ROT13): each `var NAME = ` is evaluated on its own. +function nameFilterData() { + const src = fs.readFileSync(path.join(ROOT, 'namefilter.js'), 'utf8'); + const out = {}; + for (const [k, re] of [['words', /var WORDS = (\[[\s\S]*?\])\.map\(rot\);/], ['worst', /var WORST = (\[[\s\S]*?\])\.map\(rot\);/], + ['safe', /var SAFE = (\[[\s\S]*?\]);/], ['leet', /var LEET = (\{[\s\S]*?\});/]]) { + const m = re.exec(src); + if (!m) throw new Error('namefilter.js: could not find ' + k.toUpperCase() + ' (keep it as one `var` the way it is written now)'); + out[k] = vm.runInNewContext('(' + m[1] + ')'); + } + if (!out.words.length || !out.worst.length) throw new Error('namefilter.js: empty word list'); + return out; +} function sandbox() { const noop = () => {}; @@ -89,16 +106,19 @@ function build() { const head = '// GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing '; const catJs = head + 'cosmetics.js\n// or wallet.js, and commit this file; its --check fails while the two disagree. Read by functions/_wallet.js.\n' + 'export const CATALOG = ' + JSON.stringify(cat, null, 1).replace(/\n\s*/g, ' ').replace(/\{ "/g, '{"') + ';\n'; + const nf = nameFilterData(); + const nfJs = head + "/namefilter.js's\n// word lists, and commit this file. ROT13 like namefilter.js. Read by functions/_wallet.js (cleanNote).\n" + + 'export const NAMEFILTER = ' + JSON.stringify(nf) + ';\n'; const capJs = head + "miles.js's\n// OWNERS (the captains: never charged, own everything, never paid rewards), and commit this file.\n" + 'export const OWNERS = ' + JSON.stringify(owners.slice()) + ';\n'; - return { catJs, capJs, cat, owners }; + return { catJs, capJs, nfJs, cat, owners }; } if (require.main === module) { const check = process.argv.includes('--check'); let out; try { out = build(); } catch (e) { console.error('server-data: ' + e.message); process.exit(1); } - const files = [[OUT_CAT, out.catJs], [OUT_CAP, out.capJs]]; + const files = [[OUT_CAT, out.catJs], [OUT_CAP, out.capJs], [OUT_NF, out.nfJs]]; if (check) { let bad = 0; for (const [f, want] of files) { @@ -106,11 +126,11 @@ if (require.main === module) { if (have !== want) { bad++; console.error('OUT OF DATE: ' + path.relative(ROOT, f) + ' (run: node e63334287a3deaa3/shop/tools/server-data.js)'); } } if (bad) process.exit(1); - console.log('server-data: functions/_catalog.js and functions/_captains.js match the browser files (' + Object.keys(out.cat.ITEMS).length + ' items, ' + + console.log('server-data: functions/_catalog.js, _captains.js and _namefilter.js match the browser files (' + Object.keys(out.cat.ITEMS).length + ' items, ' + Object.keys(out.cat.PACKS).length + ' packs, ' + Object.keys(out.cat.EMERALDS).length + ' emerald packs, ' + out.owners.length + ' captains; PAYMENTS.enabled ' + out.cat.PUBLIC + ').'); } else { for (const [f, want] of files) fs.writeFileSync(f, want); - console.log('server-data: wrote functions/_catalog.js and functions/_captains.js'); + console.log('server-data: wrote functions/_catalog.js, _captains.js and _namefilter.js'); } } module.exports = { build }; diff --git a/functions/_namefilter.js b/functions/_namefilter.js new file mode 100644 index 00000000..f8c5b5bc --- /dev/null +++ b/functions/_namefilter.js @@ -0,0 +1,3 @@ +// GENERATED by e63334287a3deaa3/shop/tools/server-data.js: do not edit by hand. Run that script after changing /namefilter.js's +// word lists, and commit this file. ROT13 like namefilter.js. Read by functions/_wallet.js (cleanNote). +export const NAMEFILTER = {"words":["shpx","fuvg","ovgpu","phag","fyhg","juber","avtt","snttbg","ergneq","nffubyr","onfgneq","gjng","jnax","zbgureshpx","cravf","intvan","cbea","encr","encvfg","uvgyre","xxx","qvyqb","fcrez","betnfz","pyvg","qvpxurnq","pbpxfhpx","wvmm","unaqwbo","oybjwbo","uragnv","shx"],"worst":["shpx","fuvg","avtt","snttbg","juber","ovgpu","zbgureshpx","cbea","encr","encvfg","uvgyre","pbpxfhpx","oybjwbo"],"safe":["grape","drape","trapez","scrape","therap","parapet"],"leet":{"0":"o","1":"i","3":"e","4":"a","5":"s","7":"t","@":"a","$":"s","!":"i","|":"l"}}; diff --git a/functions/_wallet.js b/functions/_wallet.js index 54321505..eb464865 100644 --- a/functions/_wallet.js +++ b/functions/_wallet.js @@ -24,6 +24,7 @@ import { DOCS, FS, googleToken, googleUser, json, cors } from './_lib.js'; import { CATALOG } from './_catalog.js'; import { OWNERS } from './_captains.js'; +import { NAMEFILTER } from './_namefilter.js'; export { CATALOG }; export const MPE = CATALOG.MANGOS_PER_EMERALD; @@ -125,6 +126,43 @@ function clean(d, now) { export function cleanText(t, max) { return String(t == null ? '' : t).replace(/[|<>\u0000-\u001f\u007f​-‏‪-‮⁦-⁩]/g, '').replace(/\s+/g, ' ').trim().slice(0, max); } +// ---------- Rude words in gift notes and names: a copy of /namefilter.js's NameFilter.clean ---------- +// The word lists are generated from namefilter.js (_namefilter.js, ROT13 there too). Keep these functions in step with +// namefilter.js's clean(), norm(), squash(), unsafe() and mask(); the server tests compare the two on sample text. +const rot = w => w.replace(/[a-z]/g, c => String.fromCharCode((c.charCodeAt(0) - 84) % 26 + 97)); +const NF_WORDS = NAMEFILTER.words.map(rot), NF_WORST = NAMEFILTER.worst.map(rot), NF_SAFE = NAMEFILTER.safe, NF_LEET = NAMEFILTER.leet; +const NF_RE = new RegExp('(^|[^a-z])(' + NF_WORDS.join('|') + ')[a-z]*', 'g'); +function nfNorm(s) { const low = s.toLowerCase(); let out = ''; for (let i = 0; i < low.length; i++) { const c = low.charAt(i); out += (c.length === s.charAt(i).length && NF_LEET[c]) || c; } return out; } +const nfSquash = n => n.replace(/[^a-z]/g, '').replace(/(.)\1{2,}/g, '$1'); +const NF_WORST_SQ = NF_WORST.map(nfSquash); +function nfUnsafe(sq) { for (const w of NF_SAFE) sq = sq.split(w).join('_'); return sq; } +function nfMask(s, n) { + if (n.length !== s.length) return s; + let out = s, m; NF_RE.lastIndex = 0; + while ((m = NF_RE.exec(n))) { const st = m.index + m[1].length, len = m[0].length - m[1].length; out = out.slice(0, st + 1) + new Array(len).join('*') + out.slice(st + len); } + return out; +} +export function nameClean(name) { + if (name == null) return name; + const s = String(name); if (!s) return s; + const n = nfNorm(s), sq = nfUnsafe(nfSquash(n)); + for (const w of NF_WORST_SQ) if (sq.indexOf(w) !== -1) { + const masked = nfMask(s, n); + if (nfUnsafe(nfSquash(nfNorm(masked))).indexOf(w) !== -1 || masked === s) return 'Player'; + } + return n.length === s.length ? nfMask(s, n) : s; +} +// A gift note: at most NOTE_MAX characters (longer is refused, not cut), a rude word masked the way namefilter.js masks +// names ("F***"); a note that hides one of the worst words some other way (which namefilter.js turns into "Player") is +// refused. -> the note to keep +export function cleanNote(raw) { + const t = cleanText(raw, 1000); + if (t.length > CATALOG.NOTE_MAX) throw new WErr(400, 'note', 'A note can be at most ' + CATALOG.NOTE_MAX + ' characters.'); + if (!t) return ''; + const c = nameClean(t); + if (c === 'Player' && t !== 'Player') throw new WErr(400, 'note', 'Please change the note: it has a word that isn’t allowed.'); + return c; +} function newId() { return crypto.randomUUID().replace(/-/g, ''); } // A ledger line: added to the wallet's recent list and written as its own ledger row (never edited). function line(w, uid, now, d, why, ref, kind, writes, id) { @@ -230,7 +268,7 @@ export async function walletGift(env, user, body, next) { const p = pack(what); if (!p) throw new WErr(400, /^emeralds[-_]/.test(what) ? 'money' : 'unknown', /^emeralds[-_]/.test(what) ? 'Emeralds and mangos can’t be gifted.' : 'Unknown item.'); if (isCaptain(to)) throw new WErr(409, 'captain', 'Captains already own everything.'); - const note = cleanText(body.note, CATALOG.NOTE_MAX), from = cleanText(body.fromName, 14) || 'A player', toName = cleanText(body.toName, 14) || 'a player'; + const note = cleanNote(body.note), from = nameClean(cleanText(body.fromName, 14)) || 'A player', toName = nameClean(cleanText(body.toName, 14)) || 'a player'; const cap = isCaptain(user.uid), req = body.req ? String(body.req) : ''; next = next || cryptoNext(); return transact(env, async get => { diff --git a/functions/api/wallet/gift.js b/functions/api/wallet/gift.js index 4a6e5a34..8a821bc1 100644 --- a/functions/api/wallet/gift.js +++ b/functions/api/wallet/gift.js @@ -1,6 +1,8 @@ // POST /api/wallet/gift { what: a pack id, 'item:' or 'draw-1/5/10', to: uid, toName, fromName, note (≤ 60), req } // (Google sign-in required). Charges the sender the same price, gives the recipient the item (or the opened chest's -// skins) and a notice. Refusals: recipient (no wallet yet), self, captain, owned, funds, money. See functions/_wallet.js. +// skins) and a notice. Refusals: recipient (no wallet yet), self, captain, owned, funds, money, note (over 60 characters, +// or hiding one of the worst words). The note, and the names shown with it, go through the server's copy of +// /namefilter.js (cleanNote / nameClean in functions/_wallet.js), so a rude word is masked even when the page is bypassed. import { endpoint, options, walletGift } from '../../_wallet.js'; export const onRequestOptions = options; From 1c0c85092db3832f67d17fcab81c1de437533826 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:04:21 +0000 Subject: [PATCH 06/14] Wallet server tests: the two-buys race test now forces both buys to read before either commits, so it no longer fails on a quiet run Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/shop/tests/fakes.mjs | 7 +++++++ e63334287a3deaa3/shop/tests/server.test.mjs | 1 + 2 files changed, 8 insertions(+) diff --git a/e63334287a3deaa3/shop/tests/fakes.mjs b/e63334287a3deaa3/shop/tests/fakes.mjs index fea10e06..cfa5d5d8 100644 --- a/e63334287a3deaa3/shop/tests/fakes.mjs +++ b/e63334287a3deaa3/shop/tests/fakes.mjs @@ -49,6 +49,10 @@ export function fakeFirestore() { function getPath(fields, dotted) { let f = { mapValue: { fields } }; for (const p of dotted.split('.')) { f = f && f.mapValue && f.mapValue.fields && f.mapValue.fields[p]; } return f; } const api = { docs, writes: 0, commits: 0, aborts: 0, + // gate: n > 0 holds transaction commits until n of them have arrived (or 2 s pass), so a test of a race is a real + // race every run and not only when the requests happen to overlap. It resets itself to 0 when it opens. + gate: 0, held: [], + open() { api.gate = 0; const h = api.held; api.held = []; h.forEach(f => f()); }, async handle(url, opts) { await tick(); const u = new URL(url), method = (opts && opts.method) || 'GET'; @@ -58,6 +62,9 @@ export function fakeFirestore() { if (u.pathname.endsWith(':commit')) { api.commits++; await tick(); + if (api.gate > 0 && body.transaction) { + await new Promise(ok => { api.held.push(ok); if (api.held.length >= api.gate) api.open(); else setTimeout(() => { if (api.held.includes(ok)) api.open(); }, 2000); }); + } if (body.transaction) { const reads = txs.get(body.transaction); if (!reads) return res(400, { error: { status: 'INVALID_ARGUMENT', message: 'no such transaction' } }); diff --git a/e63334287a3deaa3/shop/tests/server.test.mjs b/e63334287a3deaa3/shop/tests/server.test.mjs index 0d18962d..8e9c0169 100644 --- a/e63334287a3deaa3/shop/tests/server.test.mjs +++ b/e63334287a3deaa3/shop/tests/server.test.mjs @@ -193,6 +193,7 @@ test('pack: costs the sum of its items, duplicates refunded 48 each', async () = test('two concurrent buys cannot overspend', async () => { world(); CATALOG.PUBLIC = true; seed(ALICE, { balance: 500 }); + W.fs.gate = 2; // both buys have read the balance before either commits const rs = await Promise.all([ITEM_RARE, ITEM_RARE2].map(id => call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + id } }))); assert.deepEqual(rs.map(r => r.status).sort(), [200, 402]); assert.equal(bal(ALICE), 80); assert.ok(W.fs.aborts >= 1, 'the race really happened (a transaction was retried)'); From 18ae96a250aea0437d9ffe3fbfef0aab042355e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:13:20 +0000 Subject: [PATCH 07/14] Wallet hardening: webhook mode/Payment Link checks, refunds and chargebacks take emeralds back, captain gifts mint nothing, rate limits - Webhook: a non-numeric signature timestamp no longer skips the 5-minute replay check; bodies over 512 KB refused; events from a connected account ignored; livemode must match the Stripe key; Payment Link sessions and sessions not made by our checkout credit nobody and are written to orders/{session} as 'unclaimed'; the player comes only from metadata.uid (never client_reference_id, which a Payment Link takes from its address). - charge.refunded, charge.dispute.created and charge.dispute.closed take back the pack's mangos (target-based, so idempotent and safe out of order); the balance may go below zero, and a negative wallet can't buy, open chests or gift. - Captains' free gifts pay no duplicate refunds; a pack the recipient fully owns is refused as a gift. - Rate limits inside the wallet transaction (changes a minute, gifts sent and received a day) and a per-instance call limit; wallet request bodies capped at 4 KB. - Google keys: refetched on an unknown kid (at most once a minute), empty answers never cached; exp/iat must be numbers. - Items the catalogue no longer lists stay in a wallet; the generator refuses a catalogue where a refund could pay back as much as a purchase costs. - Tests for each. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/shop/tests/fakes.mjs | 24 +- e63334287a3deaa3/shop/tests/server.test.mjs | 268 +++++++++++++++++++- e63334287a3deaa3/shop/tests/shop.test.mjs | 2 +- e63334287a3deaa3/shop/tools/server-data.js | 7 + functions/_lib.js | 48 +++- functions/_wallet.js | 121 ++++++++- functions/api/stripe-webhook.js | 60 ++++- 7 files changed, 485 insertions(+), 45 deletions(-) diff --git a/e63334287a3deaa3/shop/tests/fakes.mjs b/e63334287a3deaa3/shop/tests/fakes.mjs index cfa5d5d8..b915f2f1 100644 --- a/e63334287a3deaa3/shop/tests/fakes.mjs +++ b/e63334287a3deaa3/shop/tests/fakes.mjs @@ -10,9 +10,10 @@ const DOCS = 'projects/' + PROJECT + '/databases/(default)/documents'; const FS = 'https://firestore.googleapis.com/v1/' + DOCS; const tick = () => new Promise(r => setImmediate(r)); -export async function makeKeys() { +export async function makeKeys(kid) { + kid = kid || 'test-kid'; const id = await wc.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify']); - const jwk = Object.assign(await wc.subtle.exportKey('jwk', id.publicKey), { kid: 'test-kid', alg: 'RS256', use: 'sig' }); + const jwk = Object.assign(await wc.subtle.exportKey('jwk', id.publicKey), { kid, alg: 'RS256', use: 'sig' }); const sa = await wc.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign']); const pk = Buffer.from(await wc.subtle.exportKey('pkcs8', sa.privateKey)).toString('base64'); const pem = '-----BEGIN PRIVATE KEY-----\n' + pk.match(/.{1,64}/g).join('\n') + '\n-----END PRIVATE KEY-----\n'; @@ -22,11 +23,16 @@ export async function makeKeys() { // A Firebase ID token for uid, signed with the in-memory key. provider: 'google.com' or 'anonymous'. async token(uid, provider) { const now = Math.floor(Date.now() / 1000); - const h = b64u(JSON.stringify({ alg: 'RS256', kid: 'test-kid', typ: 'JWT' })); + const h = b64u(JSON.stringify({ alg: 'RS256', kid, typ: 'JWT' })); const p = b64u(JSON.stringify({ aud: PROJECT, iss: 'https://securetoken.google.com/' + PROJECT, sub: uid, iat: now - 5, exp: now + 3600, email: uid + '@example.invalid', firebase: { sign_in_provider: provider || 'google.com' } })); const s = await wc.subtle.sign('RSASSA-PKCS1-v1_5', id.privateKey, enc.encode(h + '.' + p)); return h + '.' + p + '.' + b64u(s); + }, + // Any header and payload, signed with the in-memory key (for tests of tokens that must be refused). + async tokenWith(head, pay) { + const h = b64u(JSON.stringify(head)), p = b64u(JSON.stringify(pay)); + return h + '.' + p + '.' + b64u(await wc.subtle.sign('RSASSA-PKCS1-v1_5', id.privateKey, enc.encode(h + '.' + p))); } }; } @@ -84,6 +90,10 @@ export function fakeFirestore() { } return res(200, { commitTime: new Date().toISOString() }); } + if (u.pathname.endsWith(':batchGet')) { + api.batchGets = (api.batchGets || 0) + 1; + return res(200, body.documents.map(n => { const d = docs.get(pathOf(n)); return d ? { found: { name: n, fields: JSON.parse(JSON.stringify(d.fields)) } } : { missing: n }; })); + } if (method === 'GET' && u.pathname.startsWith('/v1/' + DOCS + '/')) { const p = decodeURIComponent(u.pathname.slice(('/v1/' + DOCS + '/').length)), tx = u.searchParams.get('transaction'); const d = docs.get(p); @@ -99,7 +109,7 @@ export function fakeFirestore() { // Stripe: prices by lookup key, and Checkout sessions (remembered, so tests can look at what was asked for). export function fakeStripe(prices) { - const api = { prices, sessions: [], calls: 0, + const api = { prices, sessions: [], paid: [], calls: 0, async handle(url, opts) { api.calls++; const u = new URL(url), method = (opts && opts.method) || 'GET'; @@ -108,6 +118,12 @@ export function fakeStripe(prices) { const key = u.searchParams.get('lookup_keys[0]'); return res(200, { data: api.prices[key] ? [api.prices[key]] : [] }); } + // Finished Checkout sessions, found by payment intent (what a refund or dispute event points at): tests put the + // session objects Stripe would hold into api.paid. + if (method === 'GET' && u.pathname === '/v1/checkout/sessions') { + const pi = u.searchParams.get('payment_intent'); + return res(200, { data: (api.paid || []).filter(s => s.payment_intent === pi).slice(0, 1) }); + } if (method === 'POST' && u.pathname === '/v1/checkout/sessions') { const p = new URLSearchParams(opts.body), o = {}; for (const [k, v] of p) o[k] = v; const s = { id: 'cs_test_' + (api.sessions.length + 1), url: 'https://checkout.stripe.com/c/pay/cs_test_' + (api.sessions.length + 1), params: o }; diff --git a/e63334287a3deaa3/shop/tests/server.test.mjs b/e63334287a3deaa3/shop/tests/server.test.mjs index 8e9c0169..e7950ca5 100644 --- a/e63334287a3deaa3/shop/tests/server.test.mjs +++ b/e63334287a3deaa3/shop/tests/server.test.mjs @@ -4,7 +4,8 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { makeKeys, fakeFirestore, fakeStripe, fakeFetch, stripeSig, plain } from './fakes.mjs'; -import { CATALOG, roll, cryptoNext, encFields, nameClean } from '../../../functions/_wallet.js'; +import { CATALOG, LIMITS, roll, cryptoNext, encFields, nameClean } from '../../../functions/_wallet.js'; +import { googleUser, resetKeyCache, resetLimits } from '../../../functions/_lib.js'; import vm from 'node:vm'; import { OWNERS } from '../../../functions/_captains.js'; import * as checkout from '../../../functions/api/checkout.js'; @@ -24,7 +25,7 @@ const PRICES = {}; Object.entries(CATALOG.EMERALDS).forEach(([k, e]) => { PRICES[k] = { id: 'price_' + k, unit_amount: e.cents, currency: 'usd', type: 'one_time', lookup_key: k }; }); PRICES.boostball_flame = { id: 'price_bf', unit_amount: 299, currency: 'usd', type: 'one_time' }; let W; // this test's world: { fs, st } -function world() { W = { fs: fakeFirestore(), st: fakeStripe(JSON.parse(JSON.stringify(PRICES))) }; return W; } +function world() { resetLimits(); W = { fs: fakeFirestore(), st: fakeStripe(JSON.parse(JSON.stringify(PRICES))) }; return W; } const realFetch = globalThis.fetch; globalThis.fetch = (u, o) => fakeFetch(keys, W.fs, W.st)(u, o); @@ -43,9 +44,10 @@ function seed(uid, w) { W.fs.docs.set('wallets/' + uid, { fields: encFields(Obje const doc = (p) => { const d = W.fs.docs.get(p); return d ? plain(d.fields) : null; }; const bal = (uid) => doc('wallets/' + uid).balance; const ledger = (uid) => [...W.fs.docs.entries()].filter(([k, d]) => k.startsWith('ledger/') && plain(d.fields).uid === uid).map(([, d]) => plain(d.fields)); -async function event(s, type, secret) { - const raw = JSON.stringify({ id: 'evt_' + Math.random().toString(36).slice(2), type: type || 'checkout.session.completed', created: Math.floor(Date.now() / 1000), data: { object: s } }); - const request = new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': await stripeSig(raw, secret || FAKE_WH) }, body: raw }); +// A signed webhook delivery. extra: more event fields (livemode, account, created); sig: a Stripe-Signature to send instead. +async function event(s, type, secret, extra, sig) { + const raw = JSON.stringify(Object.assign({ id: 'evt_' + Math.random().toString(36).slice(2), type: type || 'checkout.session.completed', livemode: false, created: Math.floor(Date.now() / 1000), data: { object: s } }, extra || {})); + const request = new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': sig ? await sig(raw) : await stripeSig(raw, secret || FAKE_WH) }, body: raw }); const r = await webhook.onRequestPost({ request, env }); return { status: r.status, data: await r.json() }; } @@ -323,6 +325,262 @@ test('catalogue check: passes in sync, fails when cosmetics.js, wallet.js, miles fs.rmSync(tmp, { recursive: true, force: true }); }); +// ---------- Hardening (attacks a cheater would try) ---------- +test('attack: webhook replay older than 5 minutes, a non-numeric timestamp and a huge body are refused', async () => { + world(); + const old = await event(session(), null, null, null, raw => stripeSig(raw, FAKE_WH, Math.floor(Date.now() / 1000) - 301)); + assert.equal(old.status, 400); + const nan = await event(session(), null, null, null, raw => stripeSig(raw, FAKE_WH, 'abc')); + assert.equal(nan.status, 400, 'Number("abc") is NaN, and NaN > 300 is false: the age check must not be skipped'); + const big = await event(session({ pad: 'x'.repeat(600 * 1024) })); + assert.equal(big.status, 413); + assert.equal(W.fs.writes, 0); +}); +test('attack: test-mode event while a live key is set (and the other way round) credits nobody, recorded unclaimed', async () => { + world(); + const live = Object.assign({}, env, { STRIPE_SECRET_KEY: 'sk_' + 'live_' + 'not-real' }); + const req = async (s, extra, e) => { + const raw = JSON.stringify(Object.assign({ id: 'evt_x', type: 'checkout.session.completed', created: Math.floor(Date.now() / 1000), data: { object: s } }, extra)); + const r = await webhook.onRequestPost({ request: new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': await stripeSig(raw, FAKE_WH) }, body: raw }), env: e }); + return { status: r.status, data: await r.json() }; + }; + const a = await req(session({ id: 'cs_test_m1' }), { livemode: false }, live); + assert.equal(a.status, 200); assert.equal(a.data.unclaimed, 'mode'); + const b = await req(session({ id: 'cs_live_m2' }), { livemode: true }, env); + assert.equal(b.data.unclaimed, 'mode'); + const c = await req(session({ id: 'cs_test_m3' }), {}, env); // no livemode at all + assert.equal(c.data.unclaimed, 'mode'); + assert.equal(doc('wallets/' + ALICE), null); + assert.equal(doc('orders/cs_test_m1').status, 'unclaimed'); assert.equal(doc('orders/cs_test_m1').reason, 'mode'); + const d = await event(session({ id: 'cs_test_m4' }), null, null, { account: 'acct_seller1' }); + assert.equal(d.data.ignored, 'connected account'); assert.equal(doc('orders/cs_test_m4'), null); + assert.equal(doc('wallets/' + ALICE), null); +}); +test('attack: a Payment Link (?client_reference_id=anyone) or a session not made by our checkout credits nobody, recorded', async () => { + world(); + // one of the owners' Payment Links, opened with someone's uid in the address + const a = await event(session({ id: 'cs_test_pl1', payment_link: 'plink_test_1', client_reference_id: BOB, metadata: {} })); + assert.equal(a.data.unclaimed, 'payment link'); + // the same, if the link had been given the pack's sku as metadata + const b = await event(session({ id: 'cs_test_pl2', payment_link: 'plink_test_2', client_reference_id: BOB, metadata: { sku: 'emeralds_7' } })); + assert.equal(b.data.unclaimed, 'payment link'); + // a session with the sku but without our checkout's uid and kind (made in the dashboard or by another tool) + const c = await event(session({ id: 'cs_test_pl3', client_reference_id: BOB, metadata: { sku: 'emeralds_7' } })); + assert.equal(c.data.unclaimed, 'not from our checkout'); + // an item session with only client_reference_id + const d = await event(session({ id: 'cs_test_pl4', amount_total: 299, client_reference_id: BOB, metadata: { sku: 'boostball_flame' } })); + assert.equal(d.data.unclaimed, 'no player or item'); + assert.equal(doc('wallets/' + BOB), null); assert.equal(doc('entitlements/' + BOB), null); + for (const id of ['cs_test_pl1', 'cs_test_pl2', 'cs_test_pl3', 'cs_test_pl4']) assert.equal(doc('orders/' + id).status, 'unclaimed', id); + assert.equal(doc('orders/cs_test_pl1').clientRef, BOB); assert.equal(doc('orders/cs_test_pl1').paymentLink, 'plink_test_1'); + // a repeat delivery doesn't fail or change it + assert.equal((await event(session({ id: 'cs_test_pl1', payment_link: 'plink_test_1', metadata: {} }))).status, 200); + // async payments: unpaid on completion, then failed: nothing; then succeeded: credited once + const s2 = session({ id: 'cs_test_async', payment_status: 'unpaid' }); + await event(s2); await event(Object.assign({}, s2), 'checkout.session.async_payment_failed'); + assert.equal(doc('orders/cs_test_async'), null); + await event(Object.assign({}, s2, { payment_status: 'paid' }), 'checkout.session.async_payment_succeeded'); + assert.equal(doc('orders/cs_test_async').status, 'credited'); assert.equal(bal(ALICE), 119); +}); +// A paid emerald session that Stripe holds (found by payment intent for refunds and disputes). +function paidSession(id, pi, sku, uid) { + const e = CATALOG.EMERALDS[sku]; + const s = session({ id, payment_intent: pi, amount_total: e.cents, client_reference_id: uid, metadata: { uid, sku, kind: 'emeralds' } }); + W.st.paid.push(s); return s; +} +const charge = (pi, refunded, amount) => ({ id: 'ch_' + pi, object: 'charge', payment_intent: pi, amount, amount_refunded: refunded, refunded: refunded >= amount }); +const dispute = (pi, status, amount) => ({ id: 'dp_' + pi, object: 'dispute', payment_intent: pi, status, amount }); +test('refund: pay, spend, refund: the mangos are taken back, the wallet goes below zero and is frozen; idempotent', async () => { + world(); CATALOG.PUBLIC = true; + const s = paidSession('cs_test_r1', 'pi_r1', 'emeralds_39', ALICE); + await event(s); + assert.equal(bal(ALICE), 39 * 17); + const b = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE } }); + assert.equal(b.status, 200); assert.equal(bal(ALICE), 663 - 420); + const r = await event(charge('pi_r1', 499, 499), 'charge.refunded'); + assert.equal(r.status, 200); assert.equal(r.data.clawed, 663); + assert.equal(bal(ALICE), 243 - 663); + assert.equal(doc('orders/cs_test_r1').status, 'refunded'); assert.equal(doc('orders/cs_test_r1').clawed, 663); + assert.equal(ledger(ALICE).filter(l => l.kind === 'reversal').length, 1); + const again = await event(charge('pi_r1', 499, 499), 'charge.refunded'); + assert.equal(again.status, 200); assert.equal(bal(ALICE), -420, 'a repeated event takes nothing twice'); + assert.equal(ledger(ALICE).filter(l => l.kind === 'reversal').length, 1); + // frozen: no buy, chest or gift while below zero + seed(BOB, {}); + const nb = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_COMMON } }); + assert.equal(nb.status, 402); assert.equal(nb.data.reason, 'negative'); + assert.equal((await call(chest, 'POST', 'wallet/chest', { as: ALICE, body: { n: 1 } })).data.reason, 'negative'); + assert.equal((await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_COMMON, to: BOB } })).data.reason, 'negative'); + const w = await call(wallet, 'GET', 'wallet', { as: ALICE }); + assert.equal(w.status, 200); assert.equal(w.data.balance, -420, 'the page sees the debt'); + // topping up pays off the debt first + await event(paidSession('cs_test_r2', 'pi_r2', 'emeralds_80', ALICE)); + assert.equal(bal(ALICE), -420 + 80 * 17); + assert.equal((await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_COMMON } })).status, 200); + CATALOG.PUBLIC = false; +}); +test('refund: partial refunds take back their share (rounded up); a refund before the credit means no credit later', async () => { + world(); + const s = paidSession('cs_test_p1', 'pi_p1', 'emeralds_80', ALICE); // 999 cents, 1360 mangos + await event(s); + await event(charge('pi_p1', 500, 999), 'charge.refunded'); + assert.equal(bal(ALICE), 1360 - Math.ceil(1360 * 500 / 999)); assert.equal(doc('orders/cs_test_p1').status, 'partly-refunded'); + await event(charge('pi_p1', 400, 999), 'charge.refunded'); // an older event arriving late: never gives back + assert.equal(bal(ALICE), 1360 - Math.ceil(1360 * 500 / 999)); + await event(charge('pi_p1', 999, 999), 'charge.refunded'); + assert.equal(bal(ALICE), 0); assert.equal(doc('orders/cs_test_p1').status, 'refunded'); + // refunded before the payment webhook arrived + const s2 = paidSession('cs_test_p2', 'pi_p2', 'emeralds_7', BOB); + await event(charge('pi_p2', 99, 99), 'charge.refunded'); + assert.equal(doc('orders/cs_test_p2').status, 'reversed'); + const late = await event(s2); + assert.equal(late.data.already, true); assert.equal(doc('wallets/' + BOB), null, 'never credited'); + // not one of ours: an item session, or an unknown payment intent + W.st.paid.push(session({ id: 'cs_test_item9', payment_intent: 'pi_item9', amount_total: 299, metadata: { uid: BOB, sku: 'boostball_flame' } })); + assert.equal((await event(charge('pi_item9', 299, 299), 'charge.refunded')).data.skipped, 'not an emerald pack'); + assert.equal((await event(charge('pi_nobody', 99, 99), 'charge.refunded')).data.skipped, 'not an emerald pack'); + // the mode check applies to refunds too + assert.equal((await event(charge('pi_p1', 999, 999), 'charge.refunded', null, { livemode: true })).data.ignored, 'mode'); +}); +test('chargeback: dispute takes everything back, won gives it back, lost keeps it taken; out of order is safe', async () => { + world(); + await event(paidSession('cs_test_d1', 'pi_d1', 'emeralds_180', ALICE)); + const full = 180 * 17, t = Math.floor(Date.now() / 1000); + await event(charge('pi_d1', 999, 1999), 'charge.refunded'); // half refunded first + const half = Math.ceil(full * 999 / 1999); + assert.equal(bal(ALICE), full - half); + await event(dispute('pi_d1', 'needs_response', 1999), 'charge.dispute.created', null, { created: t }); + assert.equal(bal(ALICE), 0); assert.equal(doc('orders/cs_test_d1').status, 'disputed'); + await event(dispute('pi_d1', 'needs_response', 1999), 'charge.dispute.created', null, { created: t }); + assert.equal(bal(ALICE), 0, 'idempotent'); + await event(dispute('pi_d1', 'won', 1999), 'charge.dispute.closed', null, { created: t + 10 }); + assert.equal(bal(ALICE), full - half, 'a won dispute gives back what the dispute took, not the refund'); + await event(dispute('pi_d1', 'needs_response', 1999), 'charge.dispute.created', null, { created: t }); // stale, late + assert.equal(bal(ALICE), full - half, 'an older dispute event arriving late changes nothing'); + await event(paidSession('cs_test_d2', 'pi_d2', 'emeralds_7', BOB)); + await event(dispute('pi_d2', 'lost', 99), 'charge.dispute.closed', null, { created: t + 20 }); + assert.equal(bal(BOB), 0); assert.equal(doc('orders/cs_test_d2').clawed, 119); + const rev = ledger(ALICE).filter(l => l.kind === 'reversal').map(l => l.d); + assert.deepEqual(rev, [-half, -(full - half), full - half]); +}); +test('attack: captain free gifts pay no duplicate refunds; a pack the recipient fully owns is refused', async () => { + world(); CATALOG.PUBLIC = true; + const all = {}; SKINS.forEach(id => { all[id] = 1; }); + seed(BOB, { balance: 0, owned: all }); + const g = await call(gift, 'POST', 'wallet/gift', { as: CAP, body: { what: 'draw-10', to: BOB, fromName: 'Cap' } }); + assert.equal(g.status, 200); assert.equal(bal(BOB), 0, 'before the fix: 480 mangos from nothing per free gift'); + seed(ALICE, { balance: 5000 }); + const p = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'skins-animals', to: BOB } }); + assert.equal(p.status, 409); assert.equal(p.data.reason, 'owned'); assert.equal(bal(ALICE), 5000); + // a paid gift of chests still refunds the recipient's duplicates (the sender paid more than that) + const c = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'draw-1', to: BOB } }); + assert.equal(c.status, 200); assert.equal(bal(BOB), 48); assert.equal(bal(ALICE), 5000 - 119); +}); +test('money: no sequence of buys, packs, chests and gifts makes mangos (every refund is below its price)', async () => { + // The rule behind it, checked over the whole catalogue: a duplicate pays back 48, every item costs at least 60, + // a chest 119, and every pack costs more than 48 per thing in it. So each purchase or gift takes more from the + // payer than it can ever pay back to anyone, and the total of all wallets only grows when emeralds are bought. + const minPrice = Math.min(...Object.values(CATALOG.PRICE)); + assert.ok(CATALOG.DUP_REFUND < minPrice && CATALOG.DUP_REFUND < CATALOG.CHEST_PRICE); + for (const [id, p] of Object.entries(CATALOG.PACKS)) { + const slots = (p.contents.items || []).length + (p.contents.draws || 0); + assert.ok(p.price > slots * CATALOG.DUP_REFUND, id + ' costs ' + p.price + ' but could pay back ' + slots * CATALOG.DUP_REFUND); + } + world(); CATALOG.PUBLIC = true; + const saved = Object.assign({}, LIMITS); LIMITS.perMinute = 1e6; LIMITS.giftsPerDay = 1e6; LIMITS.receivedPerDay = 1e6; LIMITS.callsPerMinute = 1e6; + const C = 'carolCCCCCCCCCCCCCCCCCCCCCC3', people = [ALICE, BOB, C]; + people.forEach(u => seed(u, { balance: 20000 })); + const whats = Object.keys(CATALOG.PACKS).concat(Object.keys(CATALOG.ITEMS).filter(id => !CATALOG.ITEMS[id][3]).slice(0, 40).map(id => 'item:' + id)); + let total = 60000, seedn = 12345; const rnd = n => { seedn = (seedn * 1103515245 + 12345) % 2147483648; return seedn % n; }; + for (let i = 0; i < 250; i++) { + const u = people[rnd(3)], what = whats[rnd(whats.length)], kind = rnd(3); + if (kind === 0) await call(buy, 'POST', 'wallet/buy', { as: u, body: { what } }); + else if (kind === 1) await call(chest, 'POST', 'wallet/chest', { as: u, body: { n: [1, 5, 10][rnd(3)] } }); + else await call(gift, 'POST', 'wallet/gift', { as: u, body: { what, to: people[(people.indexOf(u) + 1 + rnd(2)) % 3] } }); + const now = people.reduce((t, p) => t + bal(p), 0); + assert.ok(now <= total, 'step ' + i + ': mangos went up from ' + total + ' to ' + now); + total = now; + } + assert.ok(total < 60000); + Object.assign(LIMITS, saved); +}); +test('attack: rate limits: changes a minute, gifts a day (sent and received), calls a minute, body size', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 100000 }); seed(BOB, {}); + const rs = []; + for (let i = 0; i < LIMITS.perMinute + 2; i++) rs.push(await call(chest, 'POST', 'wallet/chest', { as: ALICE, body: { n: 1 } })); + assert.equal(rs.filter(r => r.status === 200).length, LIMITS.perMinute); + assert.equal(rs[rs.length - 1].status, 429); assert.equal(rs[rs.length - 1].data.reason, 'slow'); + // gifts a day: the minute limit lifted to see the daily one + world(); seed(ALICE, { balance: 100000 }); seed(BOB, {}); + const saved = LIMITS.perMinute; LIMITS.perMinute = 1000; + let last; + for (let i = 0; i < LIMITS.giftsPerDay + 1; i++) last = await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'draw-1', to: BOB } }); + assert.equal(last.status, 429); assert.equal(last.data.reason, 'gifts'); + assert.equal(bal(ALICE), 100000 - LIMITS.giftsPerDay * 119); + // received a day: many senders, one inbox + world(); seed(BOB, {}); + const senders = Array.from({ length: LIMITS.receivedPerDay + 1 }, (_, i) => 'sender' + String(i).padStart(22, 'S')); + senders.forEach(u => seed(u, { balance: 1000 })); + for (const u of senders) last = await call(gift, 'POST', 'wallet/gift', { as: u, body: { what: 'draw-1', to: BOB } }); + assert.equal(last.status, 429); assert.equal(last.data.reason, 'inbox'); + assert.equal(doc('wallets/' + BOB).notices.length, 20); + LIMITS.perMinute = saved; + // plain calls a minute (per Cloudflare instance), before any Firestore read + world(); const savedC = LIMITS.callsPerMinute; LIMITS.callsPerMinute = 5; + const gets = []; for (let i = 0; i < 7; i++) gets.push((await call(wallet, 'GET', 'wallet', { as: ALICE })).status); + assert.deepEqual(gets, [200, 200, 200, 200, 200, 429, 429]); + LIMITS.callsPerMinute = savedC; resetLimits(); + const huge = await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_RARE, pad: 'x'.repeat(5000) } }); + assert.equal(huge.status, 413); + CATALOG.PUBLIC = false; +}); +test('attack: sign-in tokens: alg none, wrong kid, other project, wrong issuer, expired, future, no exp, anonymous', async () => { + const b64 = o => Buffer.from(JSON.stringify(o)).toString('base64url'); + const now = Math.floor(Date.now() / 1000); + const good = { aud: 'rumblekarts', iss: 'https://securetoken.google.com/rumblekarts', sub: ALICE, iat: now - 5, exp: now + 3600, firebase: { sign_in_provider: 'google.com' } }; + const ask = async tok => googleUser(new Request('https://x/', { headers: { Authorization: 'Bearer ' + tok } }), (u, o) => fakeFetch(keys, fakeFirestore(), fakeStripe({}))(u, o)); + resetKeyCache(); + assert.ok(await ask(await keys.token(ALICE)), 'a good token passes'); + assert.equal(await ask(b64({ alg: 'none', kid: 'test-kid' }) + '.' + b64(good) + '.x'), null); + assert.equal(await ask(b64({ alg: 'HS256', kid: 'test-kid' }) + '.' + b64(good) + '.x'), null); + const bad = [Object.assign({}, good, { aud: 'other-project' }), Object.assign({}, good, { iss: 'https://securetoken.google.com/other-project' }), + Object.assign({}, good, { exp: now - 1 }), Object.assign({}, good, { iat: now + 3600 }), Object.assign({}, good, { exp: undefined }), + Object.assign({}, good, { firebase: { sign_in_provider: 'anonymous' } }), Object.assign({}, good, { sub: '' })]; + for (const p of bad) assert.equal(await ask(await keys.tokenWith({ alg: 'RS256', kid: 'test-kid', typ: 'JWT' }, p)), null, JSON.stringify(p)); + assert.ok(await ask(await keys.tokenWith({ alg: 'RS256', kid: 'test-kid', typ: 'JWT' }, good))); + // a token signed by some other key that claims our kid: the signature fails + const other = await makeKeys(); + assert.equal(await ask(await other.token(ALICE)), null); +}); +test('attack: Google rotates its keys: a new kid is fetched again (at most once a minute), junk kids do not refetch', async () => { + resetKeyCache(); + const k1 = keys, k2 = await makeKeys('rotated-kid'); + let served = [k1.jwk], fetches = 0; + const f = async (u) => { fetches++; return new Response(JSON.stringify({ keys: served }), { status: 200, headers: { 'Cache-Control': 'public, max-age=20000' } }); }; + const ask = async tok => googleUser(new Request('https://x/', { headers: { Authorization: 'Bearer ' + tok } }), f); + assert.ok(await ask(await k1.token(ALICE))); assert.equal(fetches, 1); + served = [k1.jwk, k2.jwk]; + // within a minute of the last fetch an unknown kid is not refetched (junk kids can't make us fetch every time) + assert.equal(await ask(await k2.token(ALICE)), null); assert.equal(fetches, 1); + const realNow = Date.now; Date.now = () => realNow() + 61000; + try { assert.ok(await ask(await k2.token(ALICE)), 'the rotated key is picked up'); assert.equal(fetches, 2); } + finally { Date.now = realNow; } + // an empty answer is never cached over good keys + resetKeyCache(); served = []; let threw = false; + try { await ask(await k1.token(ALICE)); } catch (e) { threw = true; } + assert.ok(threw); served = [k1.jwk]; + assert.ok(await ask(await k1.token(ALICE))); + resetKeyCache(); +}); +test('a renamed or removed item stays in the wallet (not silently dropped by the next purchase)', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 500, owned: { 'retired-item': 5 } }); + await call(buy, 'POST', 'wallet/buy', { as: ALICE, body: { what: 'item:' + ITEM_COMMON } }); + assert.equal(doc('wallets/' + ALICE).owned['retired-item'], 5); + CATALOG.PUBLIC = false; +}); + for (const [name, fn] of tests) { try { await fn(); passed++; console.log('ok ' + name); } catch (e) { console.log('FAIL ' + name + '\n ' + (e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); process.exitCode = 1; } diff --git a/e63334287a3deaa3/shop/tests/shop.test.mjs b/e63334287a3deaa3/shop/tests/shop.test.mjs index 127c53c8..5f7c3eff 100644 --- a/e63334287a3deaa3/shop/tests/shop.test.mjs +++ b/e63334287a3deaa3/shop/tests/shop.test.mjs @@ -171,7 +171,7 @@ for (const [sz, vp] of SIZES) { await page.waitForURL(/checkout\.stripe\.com/, { timeout: 8000 }); const s = st.sessions[st.sessions.length - 1]; assert.equal(s.params['metadata[uid]'], ALICE); - const raw = JSON.stringify({ id: 'evt_1', type: 'checkout.session.completed', created: Math.floor(Date.now() / 1000), data: { object: { + const raw = JSON.stringify({ id: 'evt_1', type: 'checkout.session.completed', livemode: false, created: Math.floor(Date.now() / 1000), data: { object: { id: s.id, mode: 'payment', payment_status: 'paid', amount_total: 499, currency: 'usd', client_reference_id: ALICE, metadata: { uid: ALICE, sku: 'emeralds_39', kind: 'emeralds' } } } }); const wr = await webhook.onRequestPost({ request: new Request('https://ascoding11.com/api/stripe-webhook', { method: 'POST', headers: { 'Stripe-Signature': await stripeSig(raw, FAKE_WH) }, body: raw }), env }); assert.equal(wr.status, 200); diff --git a/e63334287a3deaa3/shop/tools/server-data.js b/e63334287a3deaa3/shop/tools/server-data.js index 348d1d70..1377b7c8 100644 --- a/e63334287a3deaa3/shop/tools/server-data.js +++ b/e63334287a3deaa3/shop/tools/server-data.js @@ -97,6 +97,13 @@ function build() { EMERALDS: emeralds }; C.RARITY.forEach(r => { if (!C.SKINS.some(s => s.rarity === r.id)) throw new Error('no skin is ' + r.id + ': a chest roll could not be paid out'); }); + // No purchase may pay back as much as it costs, or a loop of buys and gifts would make mangos from nothing: a + // duplicate refund must be below every price and below a chest, and every pack must cost more than its refunds. + const minPrice = Math.min.apply(null, Object.values(cat.PRICE)); + if (!(cat.DUP_REFUND < minPrice && cat.DUP_REFUND < cat.CHEST_PRICE)) throw new Error('DUP_REFUND ' + cat.DUP_REFUND + ' must be below every price and the chest price'); + Object.keys(packs).forEach(id => { const c = packs[id].contents, slots = (c.items || []).length + (c.draws || 0); + if (!(packs[id].price > slots * cat.DUP_REFUND)) throw new Error('pack ' + id + ' costs ' + packs[id].price + ' but its duplicates could pay back ' + slots * cat.DUP_REFUND); + (c.items || []).forEach(i => { if (items[i][3]) throw new Error('pack ' + id + ' holds ' + i + ', which is a give item (never sold)'); }); }); const mctx = sandbox(); run(mctx, 'miles.js'); diff --git a/functions/_lib.js b/functions/_lib.js index 41605951..a6167abf 100644 --- a/functions/_lib.js +++ b/functions/_lib.js @@ -31,6 +31,24 @@ export function json(data, status, headers) { return new Response(JSON.stringify(data), { status: status || 200, headers: Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, headers || {}) }); } +// The request body as text, refused (null) when it is bigger than max bytes, so a huge body can't cost parse time. +export async function readBody(request, max) { + const len = Number(request.headers.get('Content-Length') || 0); + if (len > max) return null; + const t = await request.text(); + return new TextEncoder().encode(t).length > max ? null : t; +} +// A small per-instance counter (each Cloudflare instance keeps its own; no storage needed): true while key has made +// fewer than max calls this minute. Best effort only: the durable limits are in the wallet document (_wallet.js). +const hits = new Map(); +export function underLimit(key, max) { + const slot = Math.floor(Date.now() / 60000), c = hits.get(key); + if (hits.size > 20000) hits.clear(); + if (!c || c[0] !== slot) { hits.set(key, [slot, 1]); return true; } + return ++c[1] <= max; +} +export function resetLimits() { hits.clear(); } + // ---------- base64url / crypto helpers ---------- const enc = new TextEncoder(); function b64urlToBytes(s) { @@ -46,15 +64,24 @@ function sameString(a, b) { if (a.length !== b.length) return false; let d = 0; // ---------- Firebase ID tokens: only Google sign-ins may buy ---------- const JWKS_URL = 'https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com'; -let jwks = null, jwksUntil = 0; -async function firebaseKeys(fetchFn) { - if (jwks && Date.now() < jwksUntil) return jwks; +let jwks = null, jwksUntil = 0, jwksAt = 0; +// Google's public keys for Firebase ID tokens, cached as long as Google says. A kid we don't know (Google rotated its +// keys before our cache ran out) fetches them again, at most once a minute, so new tokens aren't refused for hours and +// junk kids can't make us fetch on every request. An empty or broken answer is never cached. +async function firebaseKeys(fetchFn, wantKid) { + const now = Date.now(); + const fresh = jwks && now < jwksUntil, known = fresh && (!wantKid || jwks.some(k => k.kid === wantKid)); + if (known || (fresh && now - jwksAt < 60000)) return jwks; const r = await fetchFn(JWKS_URL); - if (!r.ok) throw new Error('could not load Google keys'); + if (!r.ok) { if (fresh) return jwks; throw new Error('could not load Google keys'); } const m = /max-age=(\d+)/.exec(r.headers.get('Cache-Control') || ''); - jwks = (await r.json()).keys || []; jwksUntil = Date.now() + (m ? +m[1] : 3600) * 1000; + const keys = ((await r.json()) || {}).keys; + if (!Array.isArray(keys) || !keys.length) { if (fresh) return jwks; throw new Error('could not load Google keys'); } + jwks = keys.filter(k => k && k.kty === 'RSA' && typeof k.kid === 'string'); jwksAt = now; + jwksUntil = now + Math.min(m ? +m[1] : 3600, 6 * 3600) * 1000; return jwks; } +export function resetKeyCache() { jwks = null; jwksUntil = 0; jwksAt = 0; } // The signed-in player from "Authorization: Bearer ", or null. Anonymous game sign-ins don't count. export async function googleUser(request, fetchFn) { fetchFn = fetchFn || fetch; @@ -63,14 +90,14 @@ export async function googleUser(request, fetchFn) { const [h, p, s] = m[1].split('.'); let head, pay; try { head = JSON.parse(new TextDecoder().decode(b64urlToBytes(h))); pay = JSON.parse(new TextDecoder().decode(b64urlToBytes(p))); } catch (e) { return null; } - if (head.alg !== 'RS256' || !head.kid) return null; - const jwk = (await firebaseKeys(fetchFn)).find(k => k.kid === head.kid); + if (!head || head.alg !== 'RS256' || typeof head.kid !== 'string' || !head.kid || !pay || typeof pay !== 'object') return null; + const jwk = (await firebaseKeys(fetchFn, head.kid)).find(k => k.kid === head.kid); if (!jwk) return null; const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']); if (!(await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, b64urlToBytes(s), enc.encode(h + '.' + p)))) return null; const now = Date.now() / 1000; if (pay.aud !== PROJECT || pay.iss !== 'https://securetoken.google.com/' + PROJECT) return null; - if (!(pay.exp > now) || !(pay.iat <= now + 300) || typeof pay.sub !== 'string' || !pay.sub || pay.sub.length > 128) return null; + if (typeof pay.exp !== 'number' || typeof pay.iat !== 'number' || !(pay.exp > now) || !(pay.iat <= now + 300) || (pay.auth_time !== undefined && !(pay.auth_time <= now + 300)) || typeof pay.sub !== 'string' || !pay.sub || pay.sub.length > 128) return null; if (!pay.firebase || pay.firebase.sign_in_provider !== 'google.com') return null; return { uid: pay.sub, email: pay.email || '', name: pay.name || '' }; } @@ -99,8 +126,9 @@ export async function stripeEvent(request, raw, secret, nowSec) { const sig = request.headers.get('Stripe-Signature') || ''; const parts = Object.create(null); let t = null; const v1 = []; for (const kv of sig.split(',')) { const i = kv.indexOf('='); const k = kv.slice(0, i).trim(), v = kv.slice(i + 1).trim(); if (k === 't') t = v; else if (k === 'v1') v1.push(v); parts[k] = v; } - if (!t || !v1.length || !secret) return null; - if (Math.abs((nowSec || Date.now() / 1000) - Number(t)) > 300) return null; + // t must be a plain number: Number('abc') is NaN, and NaN > 300 is false, which would skip the age check. + if (!t || !/^\d{1,12}$/.test(t) || !v1.length || !secret) return null; + if (!(Math.abs((nowSec || Date.now() / 1000) - Number(t)) <= 300)) return null; // older than 5 minutes: a replay const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); const want = hex(await crypto.subtle.sign('HMAC', key, enc.encode(t + '.' + raw))); if (!v1.some(s => sameString(s, want))) return null; diff --git a/functions/_wallet.js b/functions/_wallet.js index eb464865..f069596d 100644 --- a/functions/_wallet.js +++ b/functions/_wallet.js @@ -8,9 +8,14 @@ * { id, t, from, what, note, got, refund }], reqs { request id: time } (the last 30, so a request * sent twice is done once), created, updated * ledger/{id} one row per change, never edited: uid, t, d, b, w, r, kind (emeralds | buy | chest | gift-out | - * gift-in | refund) + * gift-in | refund | reversal (mangos taken back for a Stripe refund or chargeback, or returned when + * the chargeback is won)) + * wallets/{uid}.lim { m: [minute, changes], gd: [day, gifts sent], gr: [day, gifts received] }: the rate limits * orders/{session id} the shop's existing record of a paid Checkout; for emeralds it also says kind 'emeralds', - * mangos credited, and status 'mismatch' when the amount paid didn't match the pack (nothing credited) + * mangos credited, and status 'mismatch' when the amount paid didn't match the pack (nothing credited), + * 'unclaimed' (paid, but not through our own checkout, e.g. a Payment Link, or in the other Stripe + * mode: nothing credited, the owners decide by hand), 'refunded' / 'partly-refunded' / 'disputed' + * (refunded = cents refunded, dispute = Stripe's dispute status, clawed = mangos taken back) * * Every change is one Firestore transaction (read the wallet, check, debit, grant, write the ledger), retried when * Firestore says another request changed the same wallet first, so double clicks and concurrent requests can't @@ -21,7 +26,7 @@ * Captains are never charged, own everything and are never paid refunds or rewards. While wallet.js's * PAYMENTS.enabled is false (CATALOG.PUBLIC), only captains may use any of this: the live captains' preview. */ -import { DOCS, FS, googleToken, googleUser, json, cors } from './_lib.js'; +import { DOCS, FS, googleToken, googleUser, json, cors, readBody, underLimit, stripe } from './_lib.js'; import { CATALOG } from './_catalog.js'; import { OWNERS } from './_captains.js'; import { NAMEFILTER } from './_namefilter.js'; @@ -29,6 +34,11 @@ import { NAMEFILTER } from './_namefilter.js'; export { CATALOG }; export const MPE = CATALOG.MANGOS_PER_EMERALD; const RECENT_MAX = 40, NOTICE_MAX = 20, REQ_MAX = 30, MAX_BAL = 1e12; +// Rate limits, kept in the wallet document and checked inside the same transaction (no extra reads or writes): +// changes a minute per player (buy, chest, gift, seen), gifts sent a day (captains have their own cap), gifts one +// player can receive a day, and plain calls a minute per player per Cloudflare instance (reads included). +export const LIMITS = { perMinute: 20, giftsPerDay: 30, captainGiftsPerDay: 200, receivedPerDay: 40, callsPerMinute: 120 }; +const MINUTE = 60000, DAY = 86400000, BODY_MAX = 4096; export const UID_RE = /^[A-Za-z0-9_-]{6,128}$/; const REQ_RE = /^[a-z0-9]{8,40}$/; const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k); @@ -110,13 +120,27 @@ export function fill(owned, p, next, now) { } // ---------- The wallet document ---------- -function blank(now) { return { balance: 0, owned: {}, recent: [], notices: [], reqs: {}, created: now, updated: now }; } +function blank(now) { return { balance: 0, owned: {}, recent: [], notices: [], reqs: {}, lim: {}, created: now, updated: now }; } +// Counts one more against a limit kept in w.lim[key] (per span of time); refuses with 429 once max is reached. +function limit(w, key, now, span, max, reason, message) { + const slot = Math.floor(now / span), c = w.lim[key], n = c && c[0] === slot ? c[1] : 0; + if (n >= max) throw new WErr(429, reason, message); + w.lim[key] = [slot, n + 1]; +} +const busy = (w, now) => limit(w, 'm', now, MINUTE, LIMITS.perMinute, 'slow', 'That’s a lot of clicks. Wait a minute and try again.'); +// A wallet below zero (a refund or chargeback took back mangos already spent) can't buy, open chests or send gifts. +function notNegative(w) { + if (w.balance < 0) throw new WErr(402, 'negative', 'Your wallet is below zero after a refund or chargeback. Buy emeralds to top it up first.', { balance: w.balance }); +} function int(v) { return typeof v === 'number' && Number.isSafeInteger(v); } function clean(d, now) { if (!d) return null; const w = blank(now); - if (int(d.balance) && d.balance >= 0) w.balance = d.balance; - if (d.owned && typeof d.owned === 'object') for (const k of Object.keys(d.owned)) if (has(ITEMS, k)) w.owned[k] = int(d.owned[k]) ? d.owned[k] : now; + // The balance can be below zero after a refund or chargeback took mangos back (see reverseEmeralds). + if (int(d.balance) && d.balance >= -MAX_BAL) w.balance = d.balance; + // Items the catalogue no longer lists are kept (a renamed or removed item must not silently vanish from a wallet). + if (d.owned && typeof d.owned === 'object') for (const k of Object.keys(d.owned)) if (k.length <= 80) w.owned[k] = int(d.owned[k]) ? d.owned[k] : now; + if (d.lim && typeof d.lim === 'object') for (const k of ['m', 'gd', 'gr']) { const c = d.lim[k]; if (Array.isArray(c) && c.length === 2 && int(c[0]) && int(c[1])) w.lim[k] = c; } if (Array.isArray(d.recent)) w.recent = d.recent.filter(x => x && int(x.t)).slice(-RECENT_MAX); if (Array.isArray(d.notices)) w.notices = d.notices.filter(x => x && typeof x.id === 'string').slice(-NOTICE_MAX); if (d.reqs && typeof d.reqs === 'object') for (const k of Object.keys(d.reqs)) if (REQ_RE.test(k) && int(d.reqs[k])) w.reqs[k] = d.reqs[k]; @@ -239,6 +263,7 @@ export async function walletBuy(env, user, body, next) { const now = Date.now(), writes = []; const w = clean(await get(docPath('wallets', user.uid)), now) || blank(now); seenReq(w, req, now); + busy(w, now); notNegative(w); const items = p.contents.items || []; if (!p.contents.draws && (cap || items.every(id => w.owned[id]))) throw new WErr(409, 'owned', p.kind === 'one' ? 'You already own this.' : 'You already own everything in this pack.'); const price = cap ? 0 : p.price; @@ -277,13 +302,20 @@ export async function walletGift(env, user, body, next) { const r = clean(await get(docPath('wallets', to)), now); if (!r) throw new WErr(404, 'recipient', toName + ' needs to open the shop once, signed in with Google, before they can get gifts.'); seenReq(w, req, now); - if (p.kind === 'one' && r.owned[p.contents.items[0]]) throw new WErr(409, 'owned', toName + ' already has this.'); + busy(w, now); notNegative(w); + limit(w, 'gd', now, DAY, cap ? LIMITS.captainGiftsPerDay : LIMITS.giftsPerDay, 'gifts', 'That’s the most gifts you can send today. Try again tomorrow.'); + limit(r, 'gr', now, DAY, LIMITS.receivedPerDay, 'inbox', toName + ' has had a lot of gifts today. Try again tomorrow.'); + const its = p.contents.items || []; + if (!p.contents.draws && its.length && its.every(id => r.owned[id])) throw new WErr(409, 'owned', toName + (p.kind === 'one' ? ' already has this.' : ' already has everything in this pack.')); const price = cap ? 0 : p.price; if (w.balance < price) throw new WErr(402, 'funds', 'Not enough emeralds yet.', { need: price - w.balance, balance: w.balance }); w.balance -= price; const id = newId(); line(w, user.uid, now, -price, (cap ? 'Free gift (captain) to ' : 'Gift to ') + toName + ': ' + p.name, 'gift:' + id, 'gift-out', writes, id + 'o'); const f = fill(r.owned, p, next, now); + // A free (captain's) gift pays no duplicate refunds: otherwise a captain could print mangos for anyone by sending + // chests to a player who already owns every skin. + if (cap) f.refund = 0; r.balance = Math.min(MAX_BAL, r.balance + f.refund); line(r, to, now, f.refund, 'Gift from ' + from + ': ' + p.name + (f.refund ? ' (' + (f.dups === 1 ? 'already had one' : 'already had ' + f.dups) + ')' : ''), 'gift:' + id, 'gift-in', writes, id + 'i'); r.notices.push({ id, t: now, from, what: p.name, pack: p.id, note, got: f.got, refund: f.refund }); @@ -303,6 +335,7 @@ export async function walletSeen(env, user, body) { const before = w.notices.length; w.notices = w.notices.filter(n => ids.indexOf(n.id) < 0); if (w.notices.length === before) return { writes: [], result: view(w, user.uid, env) }; + busy(w, now); return { writes: [put(docPath('wallets', user.uid), w)], result: view(w, user.uid, env) }; }); } @@ -311,16 +344,21 @@ export async function walletSeen(env, user, body) { // from CATALOG.EMERALDS by the sku our own checkout put in the metadata, never from Stripe's metadata or the page, and // the amount and currency paid must match the pack exactly. Credits once per Checkout session: orders/{session id} // is read and written in the same transaction, so a repeated or concurrent webhook finds it and does nothing. +// The player is metadata.uid, which only our /api/checkout sets (with kind 'emeralds'); never client_reference_id, +// which a Payment Link takes from its own address (?client_reference_id=anyone). A session without them is +// recorded as 'unclaimed' and credits nobody. export async function creditEmeralds(env, s, at) { const md = s.metadata || {}, sku = String(md.sku || ''), E = has(CATALOG.EMERALDS, sku) ? CATALOG.EMERALDS[sku] : null; - const uid = String(md.uid || s.client_reference_id || ''); - if (!E || !UID_RE.test(uid) || !/^[A-Za-z0-9_]{1,200}$/.test(String(s.id || ''))) return { skipped: 'not an emerald pack' }; + const uid = String(md.uid || ''); + if (!E || !/^[A-Za-z0-9_]{1,200}$/.test(String(s.id || ''))) return { skipped: 'not an emerald pack' }; + if (md.kind !== 'emeralds' || !UID_RE.test(uid)) return recordUnclaimed(env, s, at, 'not from our checkout'); const paidOk = s.amount_total === E.cents && String(s.currency || '').toLowerCase() === E.currency; return transact(env, async get => { const op = docPath('orders', s.id); if (await get(op)) return { writes: [], result: { already: true } }; const order = { uid, sku, amount: int(s.amount_total) ? s.amount_total : 0, currency: String(s.currency || ''), - email: (s.customer_details && s.customer_details.email) || s.customer_email || '', created: at, kind: 'emeralds' }; + email: (s.customer_details && s.customer_details.email) || s.customer_email || '', created: at, kind: 'emeralds', + pi: typeof s.payment_intent === 'string' ? s.payment_intent : '' }; if (!paidOk) return { writes: [put(op, Object.assign(order, { status: 'mismatch', mangos: 0 }), true)], result: { refused: 'amount' } }; const w = clean(await get(docPath('wallets', uid)), at) || blank(at), m = E.emeralds * MPE, writes = []; w.balance = Math.min(MAX_BAL, w.balance + m); w.updated = at; @@ -330,6 +368,64 @@ export async function creditEmeralds(env, s, at) { }); } +// A paid Checkout we won't credit (a Payment Link, a session not made by our checkout, or one from the other Stripe +// mode): written once to orders/{session id} with status 'unclaimed' and the reason, so the owners can see it in +// Firestore (and the webhook's 200 reply in Stripe) and refund it or credit the right player by hand. +export async function recordUnclaimed(env, s, at, reason) { + if (!/^[A-Za-z0-9_]{1,200}$/.test(String(s.id || ''))) return { unclaimed: reason }; + const md = s.metadata || {}; + const order = { status: 'unclaimed', reason, uid: '', sku: String(md.sku || '').slice(0, 40), mangos: 0, + amount: int(s.amount_total) ? s.amount_total : 0, currency: String(s.currency || '').slice(0, 8), + email: String((s.customer_details && s.customer_details.email) || s.customer_email || '').slice(0, 200), + paymentLink: String(s.payment_link || '').slice(0, 80), clientRef: String(s.client_reference_id || '').slice(0, 200), + livemode: !!s.livemode, created: at }; + const r = await fetch(FS + ':commit', { method: 'POST', headers: await headers(env), body: JSON.stringify({ writes: [put(docPath('orders', s.id), order, true)] }) }); + if (!r.ok && r.status !== 409 && !(r.status === 400 && /FAILED_PRECONDITION|ALREADY_EXISTS/.test(await r.text()))) throw new Error('Firestore error ' + r.status); + return { unclaimed: reason }; +} + +// Refunds and chargebacks (charge.refunded, charge.dispute.created, charge.dispute.closed): take back the mangos of +// the emerald pack that was refunded or disputed. The Checkout session is found from the charge's payment intent +// (Stripe: GET checkout/sessions?payment_intent=…), so only a session our checkout made for an emerald pack counts. +// Worked out as a target, not a step: clawed = all the pack's mangos while a dispute is open or lost, else the share +// refunded (rounded up); the wallet changes by the difference from what was already taken back. So a repeated, +// late or out-of-order event changes nothing twice, a won dispute gives the mangos back, and the balance may go +// below zero (the wallet then can't buy, open chests or send gifts until topped up). A refund that arrives before +// the purchase was credited writes the order first, so the purchase is never credited afterwards. +const DISPUTE_FREE = ['won', 'warning_closed']; +export async function reverseEmeralds(env, ev, at, fetchFn) { + const o = (ev.data && ev.data.object) || {}, isDispute = /^charge\.dispute\./.test(ev.type); + const pi = typeof o.payment_intent === 'string' ? o.payment_intent : (o.payment_intent && o.payment_intent.id) || ''; + if (!/^pi_[A-Za-z0-9_]{1,200}$/.test(pi)) return { skipped: 'no payment intent' }; + const list = await stripe(env, 'GET', 'checkout/sessions', { payment_intent: pi, limit: 1 }, fetchFn); + const s = list && list.data && list.data[0], md = (s && s.metadata) || {}; + const sku = String(md.sku || ''), E = has(CATALOG.EMERALDS, sku) ? CATALOG.EMERALDS[sku] : null, uid = String(md.uid || ''); + if (!s || !E || md.kind !== 'emeralds' || !UID_RE.test(uid) || !/^[A-Za-z0-9_]{1,200}$/.test(String(s.id || ''))) return { skipped: 'not an emerald pack' }; + const evAt = int(ev.created) ? ev.created * 1000 : at; + return transact(env, async get => { + const op = docPath('orders', s.id), writes = []; + const order = (await get(op)) || { uid, sku, kind: 'emeralds', status: 'reversed', mangos: 0, created: at, pi, + amount: int(s.amount_total) ? s.amount_total : 0, currency: String(s.currency || '') }; + order.clawed = int(order.clawed) ? order.clawed : 0; + if (!isDispute) order.refunded = Math.max(int(order.refunded) ? order.refunded : 0, int(o.amount_refunded) ? o.amount_refunded : 0); + else if (!int(order.disputeAt) || evAt >= order.disputeAt) { order.dispute = String(o.status || 'needs_response').slice(0, 30); order.disputeAt = evAt; } + const m = int(order.mangos) && order.mangos > 0 ? order.mangos : 0, amt = int(order.amount) && order.amount > 0 ? order.amount : 0; + const disputed = !!order.dispute && DISPUTE_FREE.indexOf(order.dispute) < 0; + const share = disputed ? m : amt ? Math.min(m, Math.ceil(m * Math.min(order.refunded || 0, amt) / amt)) : 0; + const delta = share - order.clawed; + if (delta && order.uid) { + const w = clean(await get(docPath('wallets', order.uid)), at) || blank(at); + w.balance = Math.max(-MAX_BAL, w.balance - delta); w.updated = at; + line(w, order.uid, at, -delta, (delta > 0 ? (disputed ? 'Taken back (chargeback): ' : 'Taken back (refund): ') : 'Given back (chargeback won): ') + E.name, s.id, 'reversal', writes); + writes.unshift(put(docPath('wallets', order.uid), w)); + } + order.clawed = share; + if (m) order.status = disputed ? 'disputed' : share >= m ? 'refunded' : share > 0 ? 'partly-refunded' : 'credited'; + writes.unshift(put(op, order)); + return { writes, result: { clawed: share, change: -delta } }; + }); +} + // ---------- HTTP ---------- // Every wallet endpoint: the same verified Google sign-in the shop uses, then the preview / public check. export function endpoint(fn) { @@ -339,9 +435,12 @@ export function endpoint(fn) { try { user = await googleUser(request); } catch (e) { return json({ error: 'Couldn’t check your sign-in. Try again in a minute.', reason: 'server' }, 502, h); } if (!user) return json({ error: 'Buying needs a Google sign-in.', reason: 'signin' }, 401, h); if (!allowed(user.uid)) return json({ error: 'The shop isn’t open yet.', reason: 'closed' }, 403, h); + if (!underLimit('w:' + user.uid, LIMITS.callsPerMinute)) return json({ error: 'That’s a lot of clicks. Wait a minute and try again.', reason: 'slow' }, 429, h); let body = {}; if (request.method === 'POST') { - try { body = await request.json(); } catch (e) { return json({ error: 'Bad request.', reason: 'bad' }, 400, h); } + const raw = await readBody(request, BODY_MAX); + if (raw === null) return json({ error: 'Bad request.', reason: 'bad' }, 413, h); + try { body = JSON.parse(raw); } catch (e) { return json({ error: 'Bad request.', reason: 'bad' }, 400, h); } if (!body || typeof body !== 'object' || Array.isArray(body)) return json({ error: 'Bad request.', reason: 'bad' }, 400, h); } try { return json(await fn(env, user, body), 200, h); } diff --git a/functions/api/stripe-webhook.js b/functions/api/stripe-webhook.js index e1346f21..947458c3 100644 --- a/functions/api/stripe-webhook.js +++ b/functions/api/stripe-webhook.js @@ -1,21 +1,48 @@ -// POST /api/stripe-webhook: Stripe tells us a Checkout finished. This, not the page the player lands on afterwards, -// is what gives them the item: the signature proves the message came from Stripe. Set up in Stripe (Developers → -// Webhooks) for https://ascoding11.com/api/stripe-webhook with the events checkout.session.completed and -// checkout.session.async_payment_succeeded; its signing secret is STRIPE_WEBHOOK_SECRET. -import { json, stripeEvent, grant, SKU_RE } from '../_lib.js'; +// POST /api/stripe-webhook: Stripe tells us a Checkout finished, or a payment was refunded or disputed. This, not the +// page the player lands on afterwards, is what gives them the item or the emeralds: the signature proves the message +// came from Stripe. Set up in Stripe (Developers → Webhooks) for https://ascoding11.com/api/stripe-webhook with the +// events checkout.session.completed, checkout.session.async_payment_succeeded, charge.refunded, +// charge.dispute.created and charge.dispute.closed; its signing secret is STRIPE_WEBHOOK_SECRET. +// +// Refused before anything is written: a bad or missing signature, a signature older than 5 minutes (a replay), a body +// over 512 KB. Ignored (200, so Stripe doesn't retry): events from a connected account (event.account), and events +// whose livemode doesn't match the key in Cloudflare (a test-mode event while a live key is set, or the other way +// round). A paid Checkout that our own /api/checkout didn't make (a Payment Link, or one made in the dashboard) or +// one from the other mode is written to orders/{session id} as 'unclaimed' and credits nobody. +import { json, stripeEvent, grant, readBody, SKU_RE } from '../_lib.js'; import { marketPaid } from '../_market.js'; -import { CATALOG, creditEmeralds } from '../_wallet.js'; +import { CATALOG, UID_RE, creditEmeralds, recordUnclaimed, reverseEmeralds, testMode } from '../_wallet.js'; + +const BODY_MAX = 512 * 1024; +const PAID = ['checkout.session.completed', 'checkout.session.async_payment_succeeded']; +const REVERSE = ['charge.refunded', 'charge.dispute.created', 'charge.dispute.closed']; export async function onRequestPost({ request, env }) { - const raw = await request.text(); + const raw = await readBody(request, BODY_MAX); + if (raw === null) return json({ error: 'too large' }, 413); const ev = await stripeEvent(request, raw, env.STRIPE_WEBHOOK_SECRET); - if (!ev) return json({ error: 'bad signature' }, 400); - if (ev.type !== 'checkout.session.completed' && ev.type !== 'checkout.session.async_payment_succeeded') return json({ ok: true }); + if (!ev || typeof ev !== 'object') return json({ error: 'bad signature' }, 400); + const at = (Number.isSafeInteger(ev.created) ? ev.created : Math.floor(Date.now() / 1000)) * 1000; + const paid = PAID.includes(ev.type), reverse = REVERSE.includes(ev.type); + if (!paid && !reverse) return json({ ok: true }); + if (ev.account) return json({ ok: true, ignored: 'connected account' }); + const modeOk = ev.livemode === !testMode(env); + + if (reverse) { + if (!modeOk) return json({ ok: true, ignored: 'mode' }); + try { return json(Object.assign({ ok: true }, await reverseEmeralds(env, ev, at))); } + catch (e) { return json({ error: 'could not record the refund' }, 500); } // Stripe retries + } + const s = ev.data && ev.data.object; if (!s || s.mode !== 'payment' || s.payment_status !== 'paid') return json({ ok: true }); // e.g. a bank payment still on its way + try { + if (!modeOk) return json(Object.assign({ ok: true }, await recordUnclaimed(env, s, at, 'mode'))); + if (s.payment_link) return json(Object.assign({ ok: true }, await recordUnclaimed(env, s, at, 'payment link'))); + } catch (e) { return json({ error: 'could not record the payment' }, 500); } // A Marketplace sale (functions/_market.js): marks the deal paid, which shows the buyer and seller each other's details. if (s.metadata && s.metadata.kind === 'market') { - try { await marketPaid(env, s, (ev.created || Math.floor(Date.now() / 1000)) * 1000); } + try { await marketPaid(env, s, at); } catch (e) { return json({ error: 'could not record the sale' }, 500); } // Stripe retries return json({ ok: true }); } @@ -23,15 +50,20 @@ export async function onRequestPost({ request, env }) { // currency paid match the pack. A mismatch is recorded in orders/{session id} with nothing credited, and not retried. if (s.metadata && Object.prototype.hasOwnProperty.call(CATALOG.EMERALDS, String(s.metadata.sku || ''))) { let r; - try { r = await creditEmeralds(env, s, (ev.created || Math.floor(Date.now() / 1000)) * 1000); } + try { r = await creditEmeralds(env, s, at); } catch (e) { return json({ error: 'could not record the purchase' }, 500); } // Stripe retries return json(Object.assign({ ok: true }, r)); } - const uid = String((s.metadata && s.metadata.uid) || s.client_reference_id || ''), sku = String((s.metadata && s.metadata.sku) || ''); - if (!uid || uid.length > 128 || /[/]/.test(uid) || !SKU_RE.test(sku)) return json({ ok: true, skipped: 'no player or item' }); + // An item: the player is metadata.uid, set only by our checkout (never client_reference_id, which a Payment Link + // takes from its own address). + const uid = String((s.metadata && s.metadata.uid) || ''), sku = String((s.metadata && s.metadata.sku) || ''); + if (!UID_RE.test(uid) || !SKU_RE.test(sku)) { + try { return json(Object.assign({ ok: true }, await recordUnclaimed(env, s, at, 'no player or item'))); } + catch (e) { return json({ error: 'could not record the payment' }, 500); } + } try { await grant(env, { uid, sku, session: s.id, amount: s.amount_total, currency: s.currency, - email: (s.customer_details && s.customer_details.email) || s.customer_email || '', at: (ev.created || Math.floor(Date.now() / 1000)) * 1000 }); + email: (s.customer_details && s.customer_details.email) || s.customer_email || '', at }); } catch (e) { return json({ error: 'could not record the purchase' }, 500); // Stripe retries } From 4a25ee4c0a838d809aeb6720a4355e6eb6d6f699 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:14:43 +0000 Subject: [PATCH 08/14] Owned check: public GET /api/owned?uids= (edge-cached, limited) and e63334287a3deaa3/owned.js for games /api/owned?uids=a,b,c (at most 24) answers, for each player, the item ids they own on the server (wallet items and gifts, plus item-shop skus), '*' for captains, and the give items anyone may wear; a wallet below zero owns nothing. No balance, history, notes or email. Cached 60 s at the edge by the sorted list; cache misses limited per address. The signed-in /api/owned is unchanged. BackRoomOwned.check(uid, id) batches and caches these and answers true / false / undefined (draw the default look), never throwing. No game uses it yet. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01DfCR7RPoK1UNAvb7iRuPWn --- e63334287a3deaa3/owned.js | 82 +++++++++++++++++++++ e63334287a3deaa3/shop/tests/server.test.mjs | 72 ++++++++++++++++++ functions/api/owned.js | 67 +++++++++++++++-- 3 files changed, 216 insertions(+), 5 deletions(-) create mode 100644 e63334287a3deaa3/owned.js diff --git a/e63334287a3deaa3/owned.js b/e63334287a3deaa3/owned.js new file mode 100644 index 00000000..5a938b14 --- /dev/null +++ b/e63334287a3deaa3/owned.js @@ -0,0 +1,82 @@ +/* + * BackRoomOwned: may ANOTHER player be drawn wearing this item? Asks the server (GET /api/owned?uids=…, public and + * edge-cached), because each player's own page can be edited to wear anything, and other players' pages would then + * draw it. Games call this before drawing someone else's skin, accessory or game item once the shop is public. + * + * BackRoomOwned.check(uid, itemId) → true (owns it, or a captain, or a give item anyone may wear), + * false (doesn't own it: draw the default look), + * undefined (not known yet, or the server can't be reached: draw the default + * look for now; onChange fires when the answer arrives) + * BackRoomOwned.want(uids) ask ahead for a list of uids (e.g. everyone in the room as they join) + * BackRoomOwned.onChange(fn) fn(uids) after answers arrive, so the game can redraw those players + * BackRoomOwned.active() true once the shop is public (wallet.js PAYMENTS.enabled): until then games + * needn't check at all + * + * Calls are batched (up to 24 uids a request, sent 50 ms after the first ask) and answers kept for 60 seconds. It + * never throws and never blocks a frame: a failure only means "not known yet" (retried after 30 seconds). + * It can't stop a player seeing an item on their OWN screen: that page is theirs to edit. + */ +(function () { + 'use strict'; + if (window.BackRoomOwned) return; + var API = /(^|\.)ascoding11\.com$/.test(location.hostname) ? '/api/' : 'https://ascoding11.com/api/'; + var MAX = 24, KEEP = 60000, RETRY = 30000, UID = /^[A-Za-z0-9_-]{6,128}$/; + var known = {}; // uid -> { t: time, all: bool, set: { id: 1 } } or { t, failed: true } + var give = {}; // item ids anyone may wear (free or earned in a game), from the server + var queue = [], timer = 0, inflight = {}, listeners = []; + + function now() { return Date.now(); } + function fresh(k) { return k && now() - k.t < (k.failed ? RETRY : KEEP); } + function want(uids) { + (uids || []).forEach(function (u) { + u = String(u || ''); + if (!UID.test(u) || fresh(known[u]) || inflight[u] || queue.indexOf(u) >= 0) return; + queue.push(u); + }); + if (queue.length && !timer) timer = setTimeout(flush, 50); + } + function flush() { + timer = 0; + while (queue.length) send(queue.splice(0, MAX)); + } + function send(batch) { + batch.forEach(function (u) { inflight[u] = 1; }); + var done = function (players) { + var t = now(); + batch.forEach(function (u) { + delete inflight[u]; + var p = players && players[u]; + if (p === '*') known[u] = { t: t, all: true, set: {} }; + else if (Array.isArray(p)) { var s = {}; p.forEach(function (id) { s[id] = 1; }); known[u] = { t: t, all: false, set: s }; } + else known[u] = { t: t, failed: true }; + }); + listeners.forEach(function (fn) { try { fn(batch.slice()); } catch (e) {} }); + }; + try { + fetch(API + 'owned?uids=' + batch.map(encodeURIComponent).join(','), { credentials: 'omit' }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (d) { + if (d && d.give && Array.isArray(d.give)) d.give.forEach(function (id) { give[id] = 1; }); + done(d && d.v === 1 && d.players); + }, function () { done(null); }); + } catch (e) { done(null); } + } + function check(uid, itemId) { + uid = String(uid || ''); itemId = String(itemId || ''); + if (!itemId) return true; + if (give[itemId]) return true; + var k = known[uid]; + if (!fresh(k)) want([uid]); + if (!k || k.failed) return undefined; + return k.all || !!k.set[itemId]; + } + function active() { + try { var W = window.BackRoomWallet || (window.parent && window.parent.BackRoomWallet); return !!(W && W.PAYMENTS && W.PAYMENTS.enabled); } + catch (e) { return false; } + } + window.BackRoomOwned = { + check: check, want: want, active: active, + onChange: function (fn) { if (typeof fn === 'function') listeners.push(fn); }, + _reset: function () { known = {}; give = {}; queue = []; inflight = {}; if (timer) clearTimeout(timer); timer = 0; } + }; +})(); diff --git a/e63334287a3deaa3/shop/tests/server.test.mjs b/e63334287a3deaa3/shop/tests/server.test.mjs index e7950ca5..44156a93 100644 --- a/e63334287a3deaa3/shop/tests/server.test.mjs +++ b/e63334287a3deaa3/shop/tests/server.test.mjs @@ -581,6 +581,78 @@ test('a renamed or removed item stays in the wallet (not silently dropped by the CATALOG.PUBLIC = false; }); +// ---------- Wearing what you don't own: the public owned list ---------- +async function ownedOf(uids, extra) { + const r = await owned.onRequestGet(Object.assign({ request: new Request('https://ascoding11.com/api/owned?uids=' + uids, { headers: { Origin: 'https://ascoding11.github.io' } }), env }, extra || {})); + return { status: r.status, data: await r.json(), headers: r.headers }; +} +test('public owned list: wallet items, gifts and item-shop skus; captains own everything; nothing private; negative = nothing', async () => { + world(); CATALOG.PUBLIC = true; + seed(ALICE, { balance: 1000, owned: { [ITEM_RARE]: 1 } }); seed(BOB, {}); + await call(gift, 'POST', 'wallet/gift', { as: ALICE, body: { what: 'item:' + ITEM_COMMON, to: BOB, note: 'secret note' } }); + W.fs.docs.set('entitlements/' + BOB, { fields: encFields({ items: { boostball_flame: 5 } }), v: 1 }); + const C = 'carolCCCCCCCCCCCCCCCCCCCCCC3'; + const r = await ownedOf([BOB, ALICE, CAP, C].join(',')); + assert.equal(r.status, 200); + assert.deepEqual(r.data.players[ALICE], [ITEM_RARE]); + assert.deepEqual(r.data.players[BOB], ['boostball_flame', ITEM_COMMON].sort(), 'a gift counts, and so does an item-shop purchase'); + assert.equal(r.data.players[CAP], '*'); assert.deepEqual(r.data.players[C], []); + assert.ok(r.data.give.length > 0 && r.data.give.every(id => CATALOG.ITEMS[id][3])); + const text = JSON.stringify(r.data); + assert.ok(!/secret note|balance|recent|notices|reqs|example\.invalid/.test(text), 'no balance, notes, history or email'); + assert.equal(r.headers.get('Access-Control-Allow-Origin'), '*'); assert.match(r.headers.get('Cache-Control'), /max-age=60/); + assert.equal(W.fs.batchGets, 1, 'one Firestore call for the whole list (captains need none)'); + // a wallet below zero shows nothing until topped up + seed(ALICE, { balance: -5, owned: { [ITEM_RARE]: 1 } }); + assert.deepEqual((await ownedOf(ALICE)).data.players[ALICE], []); + // bad lists + assert.equal((await ownedOf(Array.from({ length: 25 }, (_, i) => 'user' + String(i).padStart(24, 'x')).join(','))).status, 400); + assert.equal((await ownedOf('../wallets/x')).status, 400); + assert.equal((await ownedOf('')).status, 400); + // the signed-in form is unchanged + assert.equal((await call(owned, 'GET', 'owned')).status, 401); + CATALOG.PUBLIC = false; +}); +test('public owned list: edge-cached by the sorted list; a flood from one address is limited', async () => { + world(); seed(ALICE, { owned: { [ITEM_RARE]: 1 } }); + const store = new Map(); let puts = 0; + globalThis.caches = { default: { match: async k => { const v = store.get(k.url); return v ? v.clone() : undefined; }, put: async (k, v) => { puts++; store.set(k.url, v); } } }; + try { + const a = await ownedOf(ALICE + ',' + BOB), b = await ownedOf(BOB + ',' + ALICE); + assert.deepEqual(a.data, b.data); assert.equal(W.fs.batchGets, 1, 'the second order was answered from the cache'); assert.equal(puts, 1); + store.clear(); + const st = []; + for (let i = 0; i < 62; i++) st.push((await ownedOf('', { request: new Request('https://ascoding11.com/api/owned?uids=flood' + String(i).padStart(10, '0'), { headers: { 'CF-Connecting-IP': '203.0.113.9' } }) })).status); + assert.equal(st.filter(s => s === 429).length, 2, 'cache misses (a new list each time) are limited per address'); + } finally { delete globalThis.caches; resetLimits(); } +}); +test('owned.js: check() is batched, cached, true/false/undefined, and fails to "default look" without throwing', async () => { + world(); seed(ALICE, { owned: { [ITEM_RARE]: 1 } }); + const calls = []; let down = false; + const ctx = { location: { hostname: 'ascoding11.github.io' }, setTimeout, clearTimeout, Date, console, + fetch: async (u) => { calls.push(u); if (down) throw new Error('offline'); const q = new URL(u).searchParams.get('uids'); + const r = await owned.onRequestGet({ request: new Request(u), env }); return r; } }; + ctx.window = ctx; vm.createContext(ctx); + vm.runInContext(fs.readFileSync(path.join(ROOT, 'e63334287a3deaa3/owned.js'), 'utf8'), ctx); + const O = ctx.BackRoomOwned; const changed = []; O.onChange(u => changed.push(u)); + assert.equal(O.check(ALICE, ITEM_RARE), undefined, 'not known yet: draw the default look'); + assert.equal(O.check(BOB, ITEM_RARE), undefined); assert.equal(O.check(CAP, ITEM_RARE), undefined); + await new Promise(r => setTimeout(r, 150)); + assert.equal(calls.length, 1, 'three asks, one request'); assert.match(calls[0], /^https:\/\/ascoding11\.com\/api\/owned\?uids=/); + assert.equal(changed.length, 1); + assert.equal(O.check(ALICE, ITEM_RARE), true); assert.equal(O.check(ALICE, ITEM_RARE2), false); + assert.equal(O.check(BOB, ITEM_RARE), false); assert.equal(O.check(CAP, ITEM_RARE2), true); + const free = Object.keys(CATALOG.ITEMS).find(id => CATALOG.ITEMS[id][3]); + assert.equal(O.check(BOB, free), true, 'a give item anyone may wear'); + assert.equal(calls.length, 1, 'answers are kept'); + O._reset(); down = true; resetLimits(); + assert.equal(O.check(ALICE, ITEM_RARE), undefined); + await new Promise(r => setTimeout(r, 150)); + assert.equal(O.check(ALICE, ITEM_RARE), undefined, 'offline: still the default look, no throw'); + assert.equal(O.active(), false); + ctx.BackRoomWallet = { PAYMENTS: { enabled: true } }; assert.equal(O.active(), true); +}); + for (const [name, fn] of tests) { try { await fn(); passed++; console.log('ok ' + name); } catch (e) { console.log('FAIL ' + name + '\n ' + (e.stack || e).toString().split('\n').slice(0, 4).join('\n ')); process.exitCode = 1; } diff --git a/functions/api/owned.js b/functions/api/owned.js index 570a75d9..c687d1f2 100644 --- a/functions/api/owned.js +++ b/functions/api/owned.js @@ -1,13 +1,70 @@ -// GET /api/owned with "Authorization: Bearer " from a Google sign-in. -// Returns { items: { :